Traits
This commit is contained in:
@@ -1,41 +1,39 @@
|
|||||||
namespace main
|
struct name
|
||||||
|
|
||||||
struct Name
|
|
||||||
{
|
{
|
||||||
first: cstring
|
first: cstring
|
||||||
last: cstring
|
last: cstring
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Human
|
struct human
|
||||||
{
|
{
|
||||||
name: Name
|
name: name
|
||||||
age: i64
|
age: i64
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Printable
|
trait printable
|
||||||
{
|
{
|
||||||
func print()
|
func print()
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Human : Printable
|
impl printable for human
|
||||||
{
|
{
|
||||||
func print() {
|
func print() {
|
||||||
c::puts(this.name)
|
c::puts(this.name.first)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export func main(args: []cstring): i64
|
export func main(args: []cstring): i64
|
||||||
{
|
{
|
||||||
let x = alloc Human
|
let human = alloc human
|
||||||
{
|
{
|
||||||
name = alloc Name {
|
name = alloc name {
|
||||||
first = "john"
|
first = "john"
|
||||||
last = "doe"
|
last = "doe"
|
||||||
}
|
}
|
||||||
age = 23
|
age = 23
|
||||||
}
|
}
|
||||||
|
|
||||||
x.print()
|
human.print()
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,13 +21,15 @@ public static class QBEGenerator
|
|||||||
private static Stack<string> _breakLabels = [];
|
private static Stack<string> _breakLabels = [];
|
||||||
private static Stack<string> _continueLabels = [];
|
private static Stack<string> _continueLabels = [];
|
||||||
private static Queue<(BoundAnonymousFuncNode Func, string Name)> _anonymousFunctions = [];
|
private static Queue<(BoundAnonymousFuncNode Func, string Name)> _anonymousFunctions = [];
|
||||||
|
private static Dictionary<BoundImplementationFuncNode, string> _implFunctions = [];
|
||||||
private static Stack<Variable> _variables = [];
|
private static Stack<Variable> _variables = [];
|
||||||
private static Stack<int> _variableScopes = [];
|
private static Stack<int> _variableScopes = [];
|
||||||
private static int _variableIndex;
|
private static int _tmpIndex;
|
||||||
private static int _labelIndex;
|
private static int _labelIndex;
|
||||||
private static int _anonymousFuncIndex;
|
private static int _anonymousFuncIndex;
|
||||||
private static int _cStringLiteralIndex;
|
private static int _cStringLiteralIndex;
|
||||||
private static int _stringLiteralIndex;
|
private static int _stringLiteralIndex;
|
||||||
|
private static int _implFuncNameIndex;
|
||||||
private static bool _codeIsReachable = true;
|
private static bool _codeIsReachable = true;
|
||||||
|
|
||||||
public static string Emit(BoundSyntaxTree syntaxTree, BoundDefinitionTable definitionTable, string file)
|
public static string Emit(BoundSyntaxTree syntaxTree, BoundDefinitionTable definitionTable, string file)
|
||||||
@@ -42,13 +44,15 @@ public static class QBEGenerator
|
|||||||
_breakLabels = [];
|
_breakLabels = [];
|
||||||
_continueLabels = [];
|
_continueLabels = [];
|
||||||
_anonymousFunctions = [];
|
_anonymousFunctions = [];
|
||||||
|
_implFunctions = [];
|
||||||
_variables = [];
|
_variables = [];
|
||||||
_variableScopes = [];
|
_variableScopes = [];
|
||||||
_variableIndex = 0;
|
_tmpIndex = 0;
|
||||||
_labelIndex = 0;
|
_labelIndex = 0;
|
||||||
_anonymousFuncIndex = 0;
|
_anonymousFuncIndex = 0;
|
||||||
_cStringLiteralIndex = 0;
|
_cStringLiteralIndex = 0;
|
||||||
_stringLiteralIndex = 0;
|
_stringLiteralIndex = 0;
|
||||||
|
_implFuncNameIndex = 0;
|
||||||
_codeIsReachable = true;
|
_codeIsReachable = true;
|
||||||
|
|
||||||
foreach (var structDef in _definitionTable.GetStructs())
|
foreach (var structDef in _definitionTable.GetStructs())
|
||||||
@@ -57,9 +61,9 @@ public static class QBEGenerator
|
|||||||
_writer.NewLine();
|
_writer.NewLine();
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var @interface in _definitionTable.GetInterfaces())
|
foreach (var trait in _definitionTable.GetTraits())
|
||||||
{
|
{
|
||||||
EmitInterfaceVTableType(@interface);
|
EmitTraitVTable(trait);
|
||||||
_writer.NewLine();
|
_writer.NewLine();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,6 +79,12 @@ public static class QBEGenerator
|
|||||||
_writer.NewLine();
|
_writer.NewLine();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
foreach (var (impl, name) in _implFunctions)
|
||||||
|
{
|
||||||
|
EmitFuncDefinition(impl, name, impl.Parameters, impl.ReturnType, impl.Body, false);
|
||||||
|
_writer.NewLine();
|
||||||
|
}
|
||||||
|
|
||||||
foreach (var cStringLiteral in _cStringLiterals)
|
foreach (var cStringLiteral in _cStringLiterals)
|
||||||
{
|
{
|
||||||
_writer.WriteLine($"data {cStringLiteral.Name} = {{ b \"{cStringLiteral.Value}\", b 0 }}");
|
_writer.WriteLine($"data {cStringLiteral.Name} = {{ b \"{cStringLiteral.Value}\", b 0 }}");
|
||||||
@@ -89,9 +99,9 @@ public static class QBEGenerator
|
|||||||
return _writer.ToString();
|
return _writer.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string VarName()
|
private static string TmpName()
|
||||||
{
|
{
|
||||||
return $"%v{++_variableIndex}";
|
return $"%t{++_tmpIndex}";
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string LabelName()
|
private static string LabelName()
|
||||||
@@ -121,32 +131,37 @@ public static class QBEGenerator
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string StructName(BoundStructDefinitionNode structDef)
|
private static string ImplFuncName(BoundTraitImplementationDefinitionNode implDef, string funcName)
|
||||||
{
|
{
|
||||||
return $":{structDef.Namespace}_{structDef.Name}";
|
return $"$impl{++_implFuncNameIndex}";
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string InterfaceVTableTypeName(BoundInterfaceDefinitionNode interfaceDef)
|
private static string CustomTypeName(NubCustomType customType)
|
||||||
{
|
{
|
||||||
return $":{interfaceDef.Namespace}_{interfaceDef.Name}";
|
return $":{customType.Namespace}_{customType.Name}";
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void EmitStore(NubType type, string value, string destination)
|
private static void EmitStore(NubType type, string value, string destination)
|
||||||
{
|
{
|
||||||
var store = type switch
|
var store = type switch
|
||||||
{
|
{
|
||||||
NubPrimitiveType primitiveType => primitiveType.Kind switch
|
NubComplexType => "storel",
|
||||||
|
NubSimpleType simpleType => simpleType switch
|
||||||
{
|
{
|
||||||
PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "storel",
|
NubFuncType or NubPointerType => "loadl",
|
||||||
PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "storew",
|
NubPrimitiveType primitiveType => primitiveType.Kind switch
|
||||||
PrimitiveTypeKind.I16 or PrimitiveTypeKind.U16 => "storeh",
|
{
|
||||||
PrimitiveTypeKind.I8 or PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "storeb",
|
PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "storel",
|
||||||
PrimitiveTypeKind.F64 => "stored",
|
PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "storew",
|
||||||
PrimitiveTypeKind.F32 => "stores",
|
PrimitiveTypeKind.I16 or PrimitiveTypeKind.U16 => "storeh",
|
||||||
_ => throw new ArgumentOutOfRangeException()
|
PrimitiveTypeKind.I8 or PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "storeb",
|
||||||
|
PrimitiveTypeKind.F64 => "stored",
|
||||||
|
PrimitiveTypeKind.F32 => "stores",
|
||||||
|
_ => throw new ArgumentOutOfRangeException()
|
||||||
|
},
|
||||||
|
_ => throw new ArgumentOutOfRangeException($"'{type}' type cannot be used in store instructions")
|
||||||
},
|
},
|
||||||
NubArrayType or NubPointerType or NubStructType or NubFuncType or NubCStringType or NubStringType => "storel",
|
_ => throw new UnreachableException()
|
||||||
_ => throw new NotSupportedException($"'{type}' type cannot be used in store instructions")
|
|
||||||
};
|
};
|
||||||
|
|
||||||
_writer.Indented($"{store} {value}, {destination}");
|
_writer.Indented($"{store} {value}, {destination}");
|
||||||
@@ -154,23 +169,28 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
private static Val EmitLoad(NubType type, string from)
|
private static Val EmitLoad(NubType type, string from)
|
||||||
{
|
{
|
||||||
var into = VarName();
|
var into = TmpName();
|
||||||
var load = type switch
|
var load = type switch
|
||||||
{
|
{
|
||||||
NubPrimitiveType primitiveType => primitiveType.Kind switch
|
NubComplexType => "loadl",
|
||||||
|
NubSimpleType simpleType => simpleType switch
|
||||||
{
|
{
|
||||||
PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "loadl",
|
NubFuncType or NubPointerType => "loadl",
|
||||||
PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "loadw",
|
NubPrimitiveType primitiveType => primitiveType.Kind switch
|
||||||
PrimitiveTypeKind.I16 => "loadsh",
|
{
|
||||||
PrimitiveTypeKind.I8 => "loadsb",
|
PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "loadl",
|
||||||
PrimitiveTypeKind.U16 => "loaduh",
|
PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "loadw",
|
||||||
PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "loadub",
|
PrimitiveTypeKind.I16 => "loadsh",
|
||||||
PrimitiveTypeKind.F64 => "loadd",
|
PrimitiveTypeKind.I8 => "loadsb",
|
||||||
PrimitiveTypeKind.F32 => "loads",
|
PrimitiveTypeKind.U16 => "loaduh",
|
||||||
_ => throw new ArgumentOutOfRangeException()
|
PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "loadub",
|
||||||
|
PrimitiveTypeKind.F64 => "loadd",
|
||||||
|
PrimitiveTypeKind.F32 => "loads",
|
||||||
|
_ => throw new ArgumentOutOfRangeException()
|
||||||
|
},
|
||||||
|
_ => throw new ArgumentOutOfRangeException($"'{type}' type cannot be used in load instructions")
|
||||||
},
|
},
|
||||||
NubArrayType or NubPointerType or NubStructType or NubFuncType or NubCStringType or NubStringType => "loadl",
|
_ => throw new UnreachableException()
|
||||||
_ => throw new NotSupportedException($"'{type}' type cannot be used in load instructions")
|
|
||||||
};
|
};
|
||||||
|
|
||||||
_writer.Indented($"{into} {QBEAssign(type)} {load} {from}");
|
_writer.Indented($"{into} {QBEAssign(type)} {load} {from}");
|
||||||
@@ -185,7 +205,7 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
private static string EmitArraySizeInBytes(NubArrayType type, string array)
|
private static string EmitArraySizeInBytes(NubArrayType type, string array)
|
||||||
{
|
{
|
||||||
var size = VarName();
|
var size = TmpName();
|
||||||
_writer.Indented($"{size} =l loadl {array}");
|
_writer.Indented($"{size} =l loadl {array}");
|
||||||
_writer.Indented($"{size} =l mul {size}, {SizeOf(type.ElementType)}");
|
_writer.Indented($"{size} =l mul {size}, {SizeOf(type.ElementType)}");
|
||||||
_writer.Indented($"{size} =l add {size}, 8");
|
_writer.Indented($"{size} =l add {size}, 8");
|
||||||
@@ -194,7 +214,7 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
private static string EmitCStringSizeInBytes(string cstring)
|
private static string EmitCStringSizeInBytes(string cstring)
|
||||||
{
|
{
|
||||||
var size = VarName();
|
var size = TmpName();
|
||||||
_writer.Indented($"{size} =l call $nub_cstring_length(l {cstring})");
|
_writer.Indented($"{size} =l call $nub_cstring_length(l {cstring})");
|
||||||
_writer.Indented($"{size} =l add {size}, 1");
|
_writer.Indented($"{size} =l add {size}, 1");
|
||||||
return size;
|
return size;
|
||||||
@@ -202,7 +222,7 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
private static string EmitStringSizeInBytes(string nubstring)
|
private static string EmitStringSizeInBytes(string nubstring)
|
||||||
{
|
{
|
||||||
var size = VarName();
|
var size = TmpName();
|
||||||
_writer.Indented($"{size} =l loadl {nubstring}");
|
_writer.Indented($"{size} =l loadl {nubstring}");
|
||||||
_writer.Indented($"{size} =l add {size}, 8");
|
_writer.Indented($"{size} =l add {size}, 8");
|
||||||
return size;
|
return size;
|
||||||
@@ -251,10 +271,10 @@ public static class QBEGenerator
|
|||||||
{
|
{
|
||||||
var size = complexType switch
|
var size = complexType switch
|
||||||
{
|
{
|
||||||
NubArrayType nubArrayType => EmitArraySizeInBytes(nubArrayType, value),
|
NubArrayType arrayType => EmitArraySizeInBytes(arrayType, value),
|
||||||
NubCStringType => EmitCStringSizeInBytes(value),
|
NubCStringType => EmitCStringSizeInBytes(value),
|
||||||
NubStringType => EmitStringSizeInBytes(value),
|
NubStringType => EmitStringSizeInBytes(value),
|
||||||
NubStructType nubStructType => SizeOf(nubStructType).ToString(),
|
NubCustomType customType => SizeOf(customType).ToString(),
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(complexType))
|
_ => throw new ArgumentOutOfRangeException(nameof(complexType))
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -264,13 +284,13 @@ public static class QBEGenerator
|
|||||||
case NubCStringType:
|
case NubCStringType:
|
||||||
case NubStringType:
|
case NubStringType:
|
||||||
{
|
{
|
||||||
var buffer = VarName();
|
var buffer = TmpName();
|
||||||
_writer.Indented($"{buffer} =l alloc8 {size}");
|
_writer.Indented($"{buffer} =l alloc8 {size}");
|
||||||
EmitMemcpy(value, buffer, size);
|
EmitMemcpy(value, buffer, size);
|
||||||
EmitStore(source.Type, buffer, destinationPointer);
|
EmitStore(source.Type, buffer, destinationPointer);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
case NubStructType:
|
case NubCustomType:
|
||||||
{
|
{
|
||||||
EmitMemcpy(value, destinationPointer, size);
|
EmitMemcpy(value, destinationPointer, size);
|
||||||
return;
|
return;
|
||||||
@@ -310,7 +330,7 @@ public static class QBEGenerator
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string EmitCreateCopyOrInitialize(NubType type, BoundExpressionNode source)
|
private static string EmitCreateCopyOrInitialize(BoundExpressionNode source)
|
||||||
{
|
{
|
||||||
// If the source is a value which is not used yet such as an array/struct initializer or literal, we can skip copying
|
// If the source is a value which is not used yet such as an array/struct initializer or literal, we can skip copying
|
||||||
if (EmitTryCreateWithoutCopy(source, out var uncopiedValue))
|
if (EmitTryCreateWithoutCopy(source, out var uncopiedValue))
|
||||||
@@ -320,18 +340,18 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
var value = EmitUnwrap(EmitExpression(source));
|
var value = EmitUnwrap(EmitExpression(source));
|
||||||
|
|
||||||
switch (type)
|
switch (source.Type)
|
||||||
{
|
{
|
||||||
case NubComplexType complexType:
|
case NubComplexType complexType:
|
||||||
{
|
{
|
||||||
var destination = VarName();
|
var destination = TmpName();
|
||||||
|
|
||||||
var size = complexType switch
|
var size = complexType switch
|
||||||
{
|
{
|
||||||
NubArrayType nubArrayType => EmitArraySizeInBytes(nubArrayType, value),
|
NubArrayType arrayType => EmitArraySizeInBytes(arrayType, value),
|
||||||
NubCStringType => EmitCStringSizeInBytes(value),
|
NubCStringType => EmitCStringSizeInBytes(value),
|
||||||
NubStringType => EmitStringSizeInBytes(value),
|
NubStringType => EmitStringSizeInBytes(value),
|
||||||
NubStructType nubStructType => SizeOf(nubStructType).ToString(),
|
NubCustomType customType => SizeOf(customType).ToString(),
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(complexType))
|
_ => throw new ArgumentOutOfRangeException(nameof(complexType))
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -345,7 +365,7 @@ public static class QBEGenerator
|
|||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
{
|
{
|
||||||
throw new ArgumentOutOfRangeException(nameof(type));
|
throw new ArgumentOutOfRangeException(nameof(source.Type));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -354,18 +374,23 @@ public static class QBEGenerator
|
|||||||
{
|
{
|
||||||
return type switch
|
return type switch
|
||||||
{
|
{
|
||||||
NubPrimitiveType primitiveType => primitiveType.Kind switch
|
NubComplexType => "=l",
|
||||||
|
NubSimpleType simpleType => simpleType switch
|
||||||
{
|
{
|
||||||
PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "=l",
|
NubFuncType or NubFuncType => "=l",
|
||||||
PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "=w",
|
NubPrimitiveType primitiveType => primitiveType.Kind switch
|
||||||
PrimitiveTypeKind.I16 or PrimitiveTypeKind.U16 => "=w",
|
{
|
||||||
PrimitiveTypeKind.I8 or PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "=w",
|
PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "=l",
|
||||||
PrimitiveTypeKind.F64 => "=d",
|
PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "=w",
|
||||||
PrimitiveTypeKind.F32 => "=s",
|
PrimitiveTypeKind.I16 or PrimitiveTypeKind.U16 => "=w",
|
||||||
_ => throw new ArgumentOutOfRangeException()
|
PrimitiveTypeKind.I8 or PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "=w",
|
||||||
|
PrimitiveTypeKind.F64 => "=d",
|
||||||
|
PrimitiveTypeKind.F32 => "=s",
|
||||||
|
_ => throw new ArgumentOutOfRangeException()
|
||||||
|
},
|
||||||
|
_ => throw new NotSupportedException($"'{type}' type cannot be used in variables")
|
||||||
},
|
},
|
||||||
NubArrayType or NubPointerType or NubStructType or NubFuncType or NubCStringType or NubStringType => "=l",
|
_ => throw new UnreachableException()
|
||||||
_ => throw new NotSupportedException($"'{type}' type cannot be used in variables")
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -384,10 +409,21 @@ public static class QBEGenerator
|
|||||||
_ => throw new ArgumentOutOfRangeException()
|
_ => throw new ArgumentOutOfRangeException()
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
case NubStructType nubStructType:
|
case NubCustomType customType:
|
||||||
{
|
{
|
||||||
var definition = _definitionTable.LookupStruct(nubStructType.Namespace, nubStructType.Name).GetValue();
|
var structDef = _definitionTable.LookupStruct(customType.Namespace, customType.Name);
|
||||||
return definition.Fields.Max(f => AlignmentOf(f.Type));
|
if (structDef.HasValue)
|
||||||
|
{
|
||||||
|
return structDef.Value.Fields.Max(f => AlignmentOf(f.Type));
|
||||||
|
}
|
||||||
|
|
||||||
|
var traitDef = _definitionTable.LookupTrait(customType.Namespace, customType.Name);
|
||||||
|
if (traitDef.HasValue)
|
||||||
|
{
|
||||||
|
return 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new UnreachableException();
|
||||||
}
|
}
|
||||||
case NubPointerType:
|
case NubPointerType:
|
||||||
case NubArrayType:
|
case NubArrayType:
|
||||||
@@ -420,25 +456,35 @@ public static class QBEGenerator
|
|||||||
_ => throw new ArgumentOutOfRangeException()
|
_ => throw new ArgumentOutOfRangeException()
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
case NubStructType nubStructType:
|
case NubCustomType customType:
|
||||||
{
|
{
|
||||||
var definition = _definitionTable.LookupStruct(nubStructType.Namespace, nubStructType.Name).GetValue();
|
var structDef = _definitionTable.LookupStruct(customType.Namespace, customType.Name);
|
||||||
|
if (structDef.HasValue)
|
||||||
var size = 0;
|
|
||||||
var maxAlignment = 1;
|
|
||||||
|
|
||||||
foreach (var field in definition.Fields)
|
|
||||||
{
|
{
|
||||||
var fieldAlignment = AlignmentOf(field.Type);
|
var size = 0;
|
||||||
maxAlignment = Math.Max(maxAlignment, fieldAlignment);
|
var maxAlignment = 1;
|
||||||
|
|
||||||
size = AlignTo(size, fieldAlignment);
|
foreach (var field in structDef.Value.Fields)
|
||||||
size += SizeOf(field.Type);
|
{
|
||||||
|
var fieldAlignment = AlignmentOf(field.Type);
|
||||||
|
maxAlignment = Math.Max(maxAlignment, fieldAlignment);
|
||||||
|
|
||||||
|
size = AlignTo(size, fieldAlignment);
|
||||||
|
size += SizeOf(field.Type);
|
||||||
|
}
|
||||||
|
|
||||||
|
size = AlignTo(size, maxAlignment);
|
||||||
|
|
||||||
|
return size;
|
||||||
}
|
}
|
||||||
|
|
||||||
size = AlignTo(size, maxAlignment);
|
var traitDef = _definitionTable.LookupTrait(customType.Namespace, customType.Name);
|
||||||
|
if (traitDef.HasValue)
|
||||||
|
{
|
||||||
|
return 16;
|
||||||
|
}
|
||||||
|
|
||||||
return size;
|
throw new UnreachableException();
|
||||||
}
|
}
|
||||||
case NubPointerType:
|
case NubPointerType:
|
||||||
case NubArrayType:
|
case NubArrayType:
|
||||||
@@ -471,12 +517,39 @@ public static class QBEGenerator
|
|||||||
throw new UnreachableException($"Member '{member}' not found in struct");
|
throw new UnreachableException($"Member '{member}' not found in struct");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string FuncQBETypeName(NubType type)
|
||||||
|
{
|
||||||
|
return type switch
|
||||||
|
{
|
||||||
|
NubCustomType customType => CustomTypeName(customType),
|
||||||
|
NubComplexType => "l",
|
||||||
|
NubSimpleType simpleType => simpleType switch
|
||||||
|
{
|
||||||
|
NubPointerType or NubFuncType => "l",
|
||||||
|
NubPrimitiveType primitiveType => primitiveType.Kind switch
|
||||||
|
{
|
||||||
|
PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "l",
|
||||||
|
PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "w",
|
||||||
|
PrimitiveTypeKind.I16 => "sh",
|
||||||
|
PrimitiveTypeKind.I8 => "sb",
|
||||||
|
PrimitiveTypeKind.U16 => "uh",
|
||||||
|
PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "ub",
|
||||||
|
PrimitiveTypeKind.F64 => "d",
|
||||||
|
PrimitiveTypeKind.F32 => "s",
|
||||||
|
_ => throw new ArgumentOutOfRangeException()
|
||||||
|
},
|
||||||
|
_ => throw new NotSupportedException($"'{type}' type cannot be used as a function definition type")
|
||||||
|
},
|
||||||
|
_ => throw new UnreachableException()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
private static void EmitFuncDefinition(BoundNode debugNode, string name, List<BoundFuncParameter> parameters, NubType returnType, BoundBlockNode body, bool exported)
|
private static void EmitFuncDefinition(BoundNode debugNode, string name, List<BoundFuncParameter> parameters, NubType returnType, BoundBlockNode body, bool exported)
|
||||||
{
|
{
|
||||||
_variables.Clear();
|
_variables.Clear();
|
||||||
_variableScopes.Clear();
|
_variableScopes.Clear();
|
||||||
_variableIndex = 0;
|
|
||||||
_labelIndex = 0;
|
_labelIndex = 0;
|
||||||
|
_tmpIndex = 0;
|
||||||
|
|
||||||
var builder = new StringBuilder();
|
var builder = new StringBuilder();
|
||||||
|
|
||||||
@@ -488,52 +561,12 @@ public static class QBEGenerator
|
|||||||
builder.Append("function ");
|
builder.Append("function ");
|
||||||
if (returnType is not NubVoidType)
|
if (returnType is not NubVoidType)
|
||||||
{
|
{
|
||||||
builder.Append(returnType switch
|
builder.Append(FuncQBETypeName(returnType) + ' ');
|
||||||
{
|
|
||||||
NubPrimitiveType primitiveType => primitiveType.Kind switch
|
|
||||||
{
|
|
||||||
PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "l",
|
|
||||||
PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "w",
|
|
||||||
PrimitiveTypeKind.I16 => "sh",
|
|
||||||
PrimitiveTypeKind.I8 => "sb",
|
|
||||||
PrimitiveTypeKind.U16 => "uh",
|
|
||||||
PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "ub",
|
|
||||||
PrimitiveTypeKind.F64 => "d",
|
|
||||||
PrimitiveTypeKind.F32 => "s",
|
|
||||||
_ => throw new ArgumentOutOfRangeException()
|
|
||||||
},
|
|
||||||
NubStructType structType => StructName(_definitionTable.LookupStruct(structType.Namespace, structType.Name).GetValue()),
|
|
||||||
NubArrayType or NubPointerType or NubFuncType or NubCStringType or NubStringType => "l",
|
|
||||||
_ => throw new NotSupportedException($"'{returnType}' type cannot be used as a function return type")
|
|
||||||
});
|
|
||||||
builder.Append(' ');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
builder.Append(name);
|
builder.Append(name);
|
||||||
|
|
||||||
var parameterStrings = parameters.Select(parameter =>
|
var parameterStrings = parameters.Select(x => FuncQBETypeName(x.Type) + $" %{x.Name}");
|
||||||
{
|
|
||||||
var qbeType = parameter.Type switch
|
|
||||||
{
|
|
||||||
NubPrimitiveType primitiveType => primitiveType.Kind switch
|
|
||||||
{
|
|
||||||
PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "l",
|
|
||||||
PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "w",
|
|
||||||
PrimitiveTypeKind.I16 => "sh",
|
|
||||||
PrimitiveTypeKind.I8 => "sb",
|
|
||||||
PrimitiveTypeKind.U16 => "uh",
|
|
||||||
PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "ub",
|
|
||||||
PrimitiveTypeKind.F64 => "d",
|
|
||||||
PrimitiveTypeKind.F32 => "s",
|
|
||||||
_ => throw new ArgumentOutOfRangeException()
|
|
||||||
},
|
|
||||||
NubStructType structType => StructName(_definitionTable.LookupStruct(structType.Namespace, structType.Name).GetValue()),
|
|
||||||
NubArrayType or NubPointerType or NubFuncType or NubCStringType or NubStringType => "l",
|
|
||||||
_ => throw new NotSupportedException($"'{parameter.Type}' type cannot be used as a function parameter type")
|
|
||||||
};
|
|
||||||
|
|
||||||
return $"{qbeType} %{parameter.Name}";
|
|
||||||
});
|
|
||||||
|
|
||||||
builder.Append($"({string.Join(", ", parameterStrings)})");
|
builder.Append($"({string.Join(", ", parameterStrings)})");
|
||||||
|
|
||||||
@@ -557,30 +590,14 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
private static void EmitStructDefinition(BoundStructDefinitionNode structDef)
|
private static void EmitStructDefinition(BoundStructDefinitionNode structDef)
|
||||||
{
|
{
|
||||||
_writer.WriteLine($"type {StructName(structDef)} = {{ ");
|
var structType = new NubCustomType(structDef.Namespace, structDef.Name);
|
||||||
|
_writer.WriteLine($"type {CustomTypeName(structType)} = {{ ");
|
||||||
|
|
||||||
var types = new Dictionary<string, string>();
|
var types = new Dictionary<string, string>();
|
||||||
|
|
||||||
foreach (var field in structDef.Fields)
|
foreach (var field in structDef.Fields)
|
||||||
{
|
{
|
||||||
var qbeType = field.Type switch
|
types.Add(field.Name, StructDefQBEType(field));
|
||||||
{
|
|
||||||
NubPrimitiveType primitiveType => primitiveType.Kind switch
|
|
||||||
{
|
|
||||||
PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "l",
|
|
||||||
PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "w",
|
|
||||||
PrimitiveTypeKind.I16 or PrimitiveTypeKind.U16 => "h",
|
|
||||||
PrimitiveTypeKind.I8 or PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "b",
|
|
||||||
PrimitiveTypeKind.F64 => "d",
|
|
||||||
PrimitiveTypeKind.F32 => "s",
|
|
||||||
_ => throw new ArgumentOutOfRangeException()
|
|
||||||
},
|
|
||||||
NubStructType structType => StructName(_definitionTable.LookupStruct(structType.Namespace, structType.Name).GetValue()),
|
|
||||||
NubArrayType or NubPointerType or NubFuncType or NubCStringType or NubStringType => "l",
|
|
||||||
_ => throw new NotSupportedException($"'{field.Type}' type cannot be used in structs")
|
|
||||||
};
|
|
||||||
|
|
||||||
types.Add(field.Name, qbeType);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var longest = types.Values.Max(x => x.Length);
|
var longest = types.Values.Max(x => x.Length);
|
||||||
@@ -591,13 +608,39 @@ public static class QBEGenerator
|
|||||||
}
|
}
|
||||||
|
|
||||||
_writer.WriteLine("}");
|
_writer.WriteLine("}");
|
||||||
|
return;
|
||||||
|
|
||||||
|
string StructDefQBEType(BoundStructField field)
|
||||||
|
{
|
||||||
|
return field.Type switch
|
||||||
|
{
|
||||||
|
NubCustomType customType => CustomTypeName(customType),
|
||||||
|
NubComplexType => "l",
|
||||||
|
NubSimpleType simpleType => simpleType switch
|
||||||
|
{
|
||||||
|
NubPointerType or NubFuncType => "l",
|
||||||
|
NubPrimitiveType primitiveType => primitiveType.Kind switch
|
||||||
|
{
|
||||||
|
PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "l",
|
||||||
|
PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "w",
|
||||||
|
PrimitiveTypeKind.I16 or PrimitiveTypeKind.U16 => "h",
|
||||||
|
PrimitiveTypeKind.I8 or PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "b",
|
||||||
|
PrimitiveTypeKind.F64 => "d",
|
||||||
|
PrimitiveTypeKind.F32 => "s",
|
||||||
|
_ => throw new ArgumentOutOfRangeException()
|
||||||
|
},
|
||||||
|
_ => throw new NotSupportedException($"'{field.Type}' type cannot be used in structs")
|
||||||
|
},
|
||||||
|
_ => throw new UnreachableException()
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void EmitInterfaceVTableType(BoundInterfaceDefinitionNode interfaceDef)
|
private static void EmitTraitVTable(BoundTraitDefinitionNode traitDef)
|
||||||
{
|
{
|
||||||
_writer.WriteLine($"type {InterfaceVTableTypeName(interfaceDef)} = {{");
|
_writer.WriteLine($"type {CustomTypeName(new NubCustomType(traitDef.Namespace, traitDef.Name))} = {{");
|
||||||
|
|
||||||
foreach (var func in interfaceDef.Functions)
|
foreach (var func in traitDef.Functions)
|
||||||
{
|
{
|
||||||
_writer.Indented($"l, # func {func.Name}({string.Join(", ", func.Parameters.Select(x => $"{x.Name}: {x.Type}"))}): {func.ReturnType}");
|
_writer.Indented($"l, # func {func.Name}({string.Join(", ", func.Parameters.Select(x => $"{x.Name}: {x.Type}"))}): {func.ReturnType}");
|
||||||
}
|
}
|
||||||
@@ -723,15 +766,16 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
private static void EmitVariableDeclaration(BoundVariableDeclarationNode variableDeclaration)
|
private static void EmitVariableDeclaration(BoundVariableDeclarationNode variableDeclaration)
|
||||||
{
|
{
|
||||||
var variable = VarName();
|
var name = $"%{variableDeclaration.Name}";
|
||||||
_writer.Indented($"{variable} =l alloc8 {SizeOf(variableDeclaration.Type)}");
|
_writer.Indented($"{name} =l alloc8 8");
|
||||||
|
|
||||||
if (variableDeclaration.Assignment.HasValue)
|
if (variableDeclaration.Assignment.HasValue)
|
||||||
{
|
{
|
||||||
EmitCopyIntoOrInitialize(variableDeclaration.Assignment.Value, variable);
|
var value = EmitCreateCopyOrInitialize(variableDeclaration.Assignment.Value);
|
||||||
|
EmitStore(variableDeclaration.Assignment.Value.Type, value, name);
|
||||||
}
|
}
|
||||||
|
|
||||||
_variables.Push(new Variable(variableDeclaration.Name, new Val(variable, variableDeclaration.Type, ValKind.Pointer)));
|
_variables.Push(new Variable(variableDeclaration.Name, new Val(name, variableDeclaration.Type, ValKind.Pointer)));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void EmitWhile(BoundWhileNode whileStatement)
|
private static void EmitWhile(BoundWhileNode whileStatement)
|
||||||
@@ -790,7 +834,7 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
var elementType = ((NubArrayType)arrayIndexAccess.Array.Type).ElementType;
|
var elementType = ((NubArrayType)arrayIndexAccess.Array.Type).ElementType;
|
||||||
|
|
||||||
var pointer = VarName();
|
var pointer = TmpName();
|
||||||
_writer.Indented($"{pointer} =l mul {index}, {SizeOf(elementType)}");
|
_writer.Indented($"{pointer} =l mul {index}, {SizeOf(elementType)}");
|
||||||
_writer.Indented($"{pointer} =l add {pointer}, 8");
|
_writer.Indented($"{pointer} =l add {pointer}, 8");
|
||||||
_writer.Indented($"{pointer} =l add {array}, {pointer}");
|
_writer.Indented($"{pointer} =l add {array}, {pointer}");
|
||||||
@@ -799,16 +843,16 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
private static void EmitArrayBoundsCheck(string array, string index)
|
private static void EmitArrayBoundsCheck(string array, string index)
|
||||||
{
|
{
|
||||||
var count = VarName();
|
var count = TmpName();
|
||||||
_writer.Indented($"{count} =l loadl {array}");
|
_writer.Indented($"{count} =l loadl {array}");
|
||||||
|
|
||||||
var isNegative = VarName();
|
var isNegative = TmpName();
|
||||||
_writer.Indented($"{isNegative} =w csltl {index}, 0");
|
_writer.Indented($"{isNegative} =w csltl {index}, 0");
|
||||||
|
|
||||||
var isOob = VarName();
|
var isOob = TmpName();
|
||||||
_writer.Indented($"{isOob} =w csgel {index}, {count}");
|
_writer.Indented($"{isOob} =w csgel {index}, {count}");
|
||||||
|
|
||||||
var anyOob = VarName();
|
var anyOob = TmpName();
|
||||||
_writer.Indented($"{anyOob} =w or {isNegative}, {isOob}");
|
_writer.Indented($"{anyOob} =w or {isNegative}, {isOob}");
|
||||||
|
|
||||||
var oobLabel = LabelName();
|
var oobLabel = LabelName();
|
||||||
@@ -826,16 +870,16 @@ public static class QBEGenerator
|
|||||||
var capacity = EmitUnwrap(EmitExpression(arrayInitializer.Capacity));
|
var capacity = EmitUnwrap(EmitExpression(arrayInitializer.Capacity));
|
||||||
var elementSize = SizeOf(arrayInitializer.ElementType);
|
var elementSize = SizeOf(arrayInitializer.ElementType);
|
||||||
|
|
||||||
var capacityInBytes = VarName();
|
var capacityInBytes = TmpName();
|
||||||
_writer.Indented($"{capacityInBytes} =l mul {capacity}, {elementSize}");
|
_writer.Indented($"{capacityInBytes} =l mul {capacity}, {elementSize}");
|
||||||
var totalSize = VarName();
|
var totalSize = TmpName();
|
||||||
_writer.Indented($"{totalSize} =l add {capacityInBytes}, 8");
|
_writer.Indented($"{totalSize} =l add {capacityInBytes}, 8");
|
||||||
|
|
||||||
var arrayPointer = VarName();
|
var arrayPointer = TmpName();
|
||||||
_writer.Indented($"{arrayPointer} =l alloc8 {totalSize}");
|
_writer.Indented($"{arrayPointer} =l alloc8 {totalSize}");
|
||||||
_writer.Indented($"storel {capacity}, {arrayPointer}");
|
_writer.Indented($"storel {capacity}, {arrayPointer}");
|
||||||
|
|
||||||
var dataPointer = VarName();
|
var dataPointer = TmpName();
|
||||||
_writer.Indented($"{dataPointer} =l add {arrayPointer}, 8");
|
_writer.Indented($"{dataPointer} =l add {arrayPointer}, 8");
|
||||||
_writer.Indented($"call $nub_memset(l {dataPointer}, w 0, l {capacityInBytes})");
|
_writer.Indented($"call $nub_memset(l {dataPointer}, w 0, l {capacityInBytes})");
|
||||||
|
|
||||||
@@ -844,17 +888,7 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
private static Val EmitDereference(BoundDereferenceNode dereference)
|
private static Val EmitDereference(BoundDereferenceNode dereference)
|
||||||
{
|
{
|
||||||
var pointerType = (NubPointerType)dereference.Expression.Type;
|
return EmitLoad(dereference.Type, EmitUnwrap(EmitExpression(dereference.Expression)));
|
||||||
|
|
||||||
var pointer = EmitExpression(dereference.Expression);
|
|
||||||
|
|
||||||
// Complex types are already pointers, so no need to load them
|
|
||||||
if (pointerType.BaseType is NubComplexType)
|
|
||||||
{
|
|
||||||
return pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
return EmitLoad(dereference.Type, EmitUnwrap(pointer));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Val EmitAddressOf(BoundAddressOfNode addressOf)
|
private static Val EmitAddressOf(BoundAddressOfNode addressOf)
|
||||||
@@ -869,7 +903,7 @@ public static class QBEGenerator
|
|||||||
var left = EmitUnwrap(EmitExpression(binaryExpression.Left));
|
var left = EmitUnwrap(EmitExpression(binaryExpression.Left));
|
||||||
var right = EmitUnwrap(EmitExpression(binaryExpression.Right));
|
var right = EmitUnwrap(EmitExpression(binaryExpression.Right));
|
||||||
|
|
||||||
var outputName = VarName();
|
var outputName = TmpName();
|
||||||
|
|
||||||
var instruction = EmitBinaryInstructionFor(binaryExpression.Operator, binaryExpression.Left.Type, left, right);
|
var instruction = EmitBinaryInstructionFor(binaryExpression.Operator, binaryExpression.Left.Type, left, right);
|
||||||
|
|
||||||
@@ -1080,12 +1114,17 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
private static Val EmitStructInitializer(BoundStructInitializerNode structInitializer, string? destination = null)
|
private static Val EmitStructInitializer(BoundStructInitializerNode structInitializer, string? destination = null)
|
||||||
{
|
{
|
||||||
var structDefinition = _definitionTable.LookupStruct(structInitializer.StructType.Namespace, structInitializer.StructType.Name).GetValue();
|
if (structInitializer.StructType is not NubCustomType structType)
|
||||||
|
{
|
||||||
|
throw new UnreachableException();
|
||||||
|
}
|
||||||
|
|
||||||
|
var structDefinition = _definitionTable.LookupStruct(structType.Namespace, structType.Name).GetValue();
|
||||||
|
|
||||||
if (destination == null)
|
if (destination == null)
|
||||||
{
|
{
|
||||||
destination = VarName();
|
destination = TmpName();
|
||||||
var size = SizeOf(structInitializer.StructType);
|
var size = SizeOf(structType);
|
||||||
_writer.Indented($"{destination} =l alloc8 {size}");
|
_writer.Indented($"{destination} =l alloc8 {size}");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1098,18 +1137,18 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
Debug.Assert(valueExpression != null);
|
Debug.Assert(valueExpression != null);
|
||||||
|
|
||||||
var offset = VarName();
|
var offset = TmpName();
|
||||||
_writer.Indented($"{offset} =l add {destination}, {OffsetOf(structDefinition, field.Name)}");
|
_writer.Indented($"{offset} =l add {destination}, {OffsetOf(structDefinition, field.Name)}");
|
||||||
EmitCopyIntoOrInitialize(valueExpression, offset);
|
EmitCopyIntoOrInitialize(valueExpression, offset);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new Val(destination, structInitializer.StructType, ValKind.Direct);
|
return new Val(destination, structType, ValKind.Direct);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Val EmitUnaryExpression(BoundUnaryExpressionNode unaryExpression)
|
private static Val EmitUnaryExpression(BoundUnaryExpressionNode unaryExpression)
|
||||||
{
|
{
|
||||||
var operand = EmitUnwrap(EmitExpression(unaryExpression.Operand));
|
var operand = EmitUnwrap(EmitExpression(unaryExpression.Operand));
|
||||||
var outputName = VarName();
|
var outputName = TmpName();
|
||||||
|
|
||||||
switch (unaryExpression.Operator)
|
switch (unaryExpression.Operator)
|
||||||
{
|
{
|
||||||
@@ -1156,47 +1195,63 @@ public static class QBEGenerator
|
|||||||
private static Val EmitMemberAccess(BoundMemberAccessNode memberAccess)
|
private static Val EmitMemberAccess(BoundMemberAccessNode memberAccess)
|
||||||
{
|
{
|
||||||
var item = EmitUnwrap(EmitExpression(memberAccess.Expression));
|
var item = EmitUnwrap(EmitExpression(memberAccess.Expression));
|
||||||
var output = VarName();
|
|
||||||
|
|
||||||
switch (memberAccess.Expression.Type)
|
var implementation = _definitionTable.LookupTraitImplementationForType(memberAccess.Expression.Type, memberAccess.Member);
|
||||||
|
if (implementation.HasValue)
|
||||||
{
|
{
|
||||||
case NubArrayType:
|
var name = ImplFuncName(implementation.Value.Item1, memberAccess.Member);
|
||||||
|
_implFunctions.TryAdd(implementation.Value.Item2, name);
|
||||||
|
return new Val(name, memberAccess.Type, ValKind.Direct, new MethodCallContext(item, memberAccess.Expression.Type));
|
||||||
|
}
|
||||||
|
|
||||||
|
var output = TmpName();
|
||||||
|
|
||||||
|
if (memberAccess.Expression.Type is NubCustomType customType)
|
||||||
|
{
|
||||||
|
var function = _definitionTable.LookupFunctionOnTrait(customType.Namespace, customType.Name, memberAccess.Member);
|
||||||
|
if (function.HasValue)
|
||||||
{
|
{
|
||||||
if (memberAccess.Member == "count")
|
throw new NotImplementedException("VTable lookup is not implemented");
|
||||||
|
}
|
||||||
|
|
||||||
|
var structDef = _definitionTable.LookupStruct(customType.Namespace, customType.Name);
|
||||||
|
if (structDef.HasValue)
|
||||||
|
{
|
||||||
|
var offset = OffsetOf(structDef.Value, memberAccess.Member);
|
||||||
|
_writer.Indented($"{output} =l add {item}, {offset}");
|
||||||
|
|
||||||
|
if (memberAccess.Type is NubCustomType inner)
|
||||||
|
{
|
||||||
|
// If the accessed member is an inline struct, it will not be a pointer
|
||||||
|
if (_definitionTable.LookupStruct(inner.Namespace, inner.Name).HasValue)
|
||||||
|
{
|
||||||
|
return new Val(output, memberAccess.Type, ValKind.Direct);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Val(output, memberAccess.Type, ValKind.Pointer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (memberAccess.Member == "count")
|
||||||
|
{
|
||||||
|
switch (memberAccess.Expression.Type)
|
||||||
|
{
|
||||||
|
case NubArrayType:
|
||||||
{
|
{
|
||||||
_writer.Indented($"{output} =l loadl {item}");
|
_writer.Indented($"{output} =l loadl {item}");
|
||||||
return new Val(output, memberAccess.Type, ValKind.Direct);
|
return new Val(output, memberAccess.Type, ValKind.Direct);
|
||||||
}
|
}
|
||||||
|
case NubStringType:
|
||||||
break;
|
|
||||||
}
|
|
||||||
case NubStringType:
|
|
||||||
{
|
|
||||||
if (memberAccess.Member == "count")
|
|
||||||
{
|
{
|
||||||
_writer.Indented($"{output} =l call $nub_string_length(l {item})");
|
_writer.Indented($"{output} =l call $nub_string_length(l {item})");
|
||||||
return new Val(output, memberAccess.Type, ValKind.Direct);
|
return new Val(output, memberAccess.Type, ValKind.Direct);
|
||||||
}
|
}
|
||||||
|
case NubCStringType:
|
||||||
break;
|
|
||||||
}
|
|
||||||
case NubCStringType:
|
|
||||||
{
|
|
||||||
if (memberAccess.Member == "count")
|
|
||||||
{
|
{
|
||||||
_writer.Indented($"{output} =l call $nub_cstring_length(l {item})");
|
_writer.Indented($"{output} =l call $nub_cstring_length(l {item})");
|
||||||
return new Val(output, memberAccess.Type, ValKind.Direct);
|
return new Val(output, memberAccess.Type, ValKind.Direct);
|
||||||
}
|
}
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case NubStructType structType:
|
|
||||||
{
|
|
||||||
var structDefinition = _definitionTable.LookupStruct(structType.Namespace, structType.Name).GetValue();
|
|
||||||
var offset = OffsetOf(structDefinition, memberAccess.Member);
|
|
||||||
|
|
||||||
_writer.Indented($"{output} =l add {item}, {offset}");
|
|
||||||
return new Val(output, memberAccess.Type, ValKind.Pointer);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1205,78 +1260,43 @@ public static class QBEGenerator
|
|||||||
|
|
||||||
private static Val EmitFuncCall(BoundFuncCallNode funcCall)
|
private static Val EmitFuncCall(BoundFuncCallNode funcCall)
|
||||||
{
|
{
|
||||||
var funcType = (NubFuncType)funcCall.Expression.Type;
|
var expression = EmitExpression(funcCall.Expression);
|
||||||
|
var funcPointer = EmitUnwrap(expression);
|
||||||
|
|
||||||
var parameterStrings = new List<string>();
|
var parameterStrings = new List<string>();
|
||||||
|
|
||||||
|
if (expression.FuncCallContext != null)
|
||||||
|
{
|
||||||
|
parameterStrings.Add($"{FuncQBETypeName(expression.FuncCallContext.ThisArgType)} {expression.FuncCallContext.ThisArgName}");
|
||||||
|
}
|
||||||
|
|
||||||
foreach (var parameter in funcCall.Parameters)
|
foreach (var parameter in funcCall.Parameters)
|
||||||
{
|
{
|
||||||
var qbeType = parameter.Type switch
|
var copy = EmitCreateCopyOrInitialize(parameter);
|
||||||
{
|
parameterStrings.Add($"{FuncQBETypeName(parameter.Type)} {copy}");
|
||||||
NubPrimitiveType pointerType => pointerType.Kind switch
|
|
||||||
{
|
|
||||||
PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "l",
|
|
||||||
PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "w",
|
|
||||||
PrimitiveTypeKind.I16 => "sh",
|
|
||||||
PrimitiveTypeKind.I8 => "sb",
|
|
||||||
PrimitiveTypeKind.U16 => "uh",
|
|
||||||
PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "ub",
|
|
||||||
PrimitiveTypeKind.F64 => "d",
|
|
||||||
PrimitiveTypeKind.F32 => "s",
|
|
||||||
_ => throw new ArgumentOutOfRangeException()
|
|
||||||
},
|
|
||||||
NubStructType structType => StructName(_definitionTable.LookupStruct(structType.Namespace, structType.Name).GetValue()),
|
|
||||||
NubArrayType or NubPointerType or NubFuncType or NubCStringType or NubStringType => "l",
|
|
||||||
_ => throw new NotSupportedException($"'{parameter.Type}' type cannot be used in function calls")
|
|
||||||
};
|
|
||||||
|
|
||||||
var copy = EmitCreateCopyOrInitialize(parameter.Type, parameter);
|
|
||||||
parameterStrings.Add($"{qbeType} {copy}");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var funcPointer = EmitUnwrap(EmitExpression(funcCall.Expression));
|
if (funcCall.Type.IsVoid)
|
||||||
|
|
||||||
if (funcType.ReturnType is not NubVoidType)
|
|
||||||
{
|
|
||||||
var outputName = VarName();
|
|
||||||
|
|
||||||
_writer.Indented($"{outputName} {QBEAssign(funcCall.Type)} call {funcPointer}({string.Join(", ", parameterStrings)})");
|
|
||||||
return new Val(outputName, funcCall.Type, ValKind.Direct);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
{
|
||||||
_writer.Indented($"call {funcPointer}({string.Join(", ", parameterStrings)})");
|
_writer.Indented($"call {funcPointer}({string.Join(", ", parameterStrings)})");
|
||||||
return new Val(string.Empty, funcCall.Type, ValKind.Direct);
|
return new Val(string.Empty, funcCall.Type, ValKind.Direct);
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var outputName = TmpName();
|
||||||
|
_writer.Indented($"{outputName} {QBEAssign(funcCall.Type)} call {funcPointer}({string.Join(", ", parameterStrings)})");
|
||||||
|
return new Val(outputName, funcCall.Type, ValKind.Direct);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string EmitUnwrap(Val val)
|
private static string EmitUnwrap(Val val)
|
||||||
{
|
{
|
||||||
if (val.Type.IsVoid)
|
return val.Kind switch
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Cannot unwrap temporary of void type");
|
ValKind.Direct => val.Name,
|
||||||
}
|
ValKind.Pointer => EmitLoad(val.Type, val.Name).Name,
|
||||||
|
_ => throw new ArgumentOutOfRangeException()
|
||||||
switch (val.Kind)
|
};
|
||||||
{
|
|
||||||
case ValKind.Direct:
|
|
||||||
{
|
|
||||||
return val.Name;
|
|
||||||
}
|
|
||||||
case ValKind.Pointer:
|
|
||||||
{
|
|
||||||
if (val.Type is NubStructType)
|
|
||||||
{
|
|
||||||
return val.Name;
|
|
||||||
}
|
|
||||||
|
|
||||||
return EmitLoad(val.Type, val.Name).Name;
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
{
|
|
||||||
throw new ArgumentOutOfRangeException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1298,17 +1318,9 @@ internal class Variable(string name, Val val)
|
|||||||
public Val Val { get; } = val;
|
public Val Val { get; } = val;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class Val(string name, NubType type, ValKind kind)
|
internal record Val(string Name, NubType Type, ValKind Kind, MethodCallContext? FuncCallContext = null);
|
||||||
{
|
|
||||||
public string Name { get; } = name;
|
|
||||||
public NubType Type { get; } = type;
|
|
||||||
public ValKind Kind { get; } = kind;
|
|
||||||
|
|
||||||
public override string ToString()
|
internal record MethodCallContext(string ThisArgName, NubType ThisArgType);
|
||||||
{
|
|
||||||
throw new InvalidOperationException();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal enum ValKind
|
internal enum ValKind
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ internal class QBEWriter
|
|||||||
var firstToken = node.Tokens.FirstOrDefault();
|
var firstToken = node.Tokens.FirstOrDefault();
|
||||||
if (firstToken != null)
|
if (firstToken != null)
|
||||||
{
|
{
|
||||||
WriteDebugLocation(firstToken.Span);
|
// WriteDebugLocation(firstToken.Span);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -37,6 +37,43 @@ public class DefinitionTable
|
|||||||
return Optional.OfNullable(definition);
|
return Optional.OfNullable(definition);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Optional<TraitDefinitionNode> LookupTrait(string @namespace, string name)
|
||||||
|
{
|
||||||
|
var definition = _syntaxTrees
|
||||||
|
.Where(c => c.Namespace == @namespace)
|
||||||
|
.SelectMany(c => c.Definitions)
|
||||||
|
.OfType<TraitDefinitionNode>()
|
||||||
|
.SingleOrDefault(f => f.Name == name);
|
||||||
|
|
||||||
|
return Optional.OfNullable(definition);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<Tuple<TraitImplementationDefinitionNode, ImplementationFuncNode>> LookupTraitImplementationForType(NubType type, string funcName)
|
||||||
|
{
|
||||||
|
var implementations = _syntaxTrees
|
||||||
|
.SelectMany(c => c.Definitions)
|
||||||
|
.OfType<TraitImplementationDefinitionNode>()
|
||||||
|
.Where(c => c.ForType.Equals(type));
|
||||||
|
|
||||||
|
var implementation = implementations.SingleOrDefault(c => c.Functions.Any(x => x.Name == funcName));
|
||||||
|
|
||||||
|
var value = implementation == null ? null : new Tuple<TraitImplementationDefinitionNode, ImplementationFuncNode>(implementation, implementation.Functions.First(x => x.Name == funcName));
|
||||||
|
|
||||||
|
return Optional.OfNullable(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<TraitFunc> LookupFunctionOnTrait(string @namespace, string name, string funcName)
|
||||||
|
{
|
||||||
|
var traitDef = LookupTrait(@namespace, name);
|
||||||
|
if (traitDef.HasValue)
|
||||||
|
{
|
||||||
|
var function = traitDef.Value.Functions.SingleOrDefault(x => x.Name == funcName);
|
||||||
|
return Optional.OfNullable(function);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Optional<TraitFunc>.Empty();
|
||||||
|
}
|
||||||
|
|
||||||
public IEnumerable<StructDefinitionNode> GetStructs()
|
public IEnumerable<StructDefinitionNode> GetStructs()
|
||||||
{
|
{
|
||||||
return _syntaxTrees
|
return _syntaxTrees
|
||||||
@@ -65,18 +102,18 @@ public class DefinitionTable
|
|||||||
.OfType<ExternFuncDefinitionNode>();
|
.OfType<ExternFuncDefinitionNode>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public IEnumerable<InterfaceDefinitionNode> GetInterfaces()
|
public IEnumerable<TraitDefinitionNode> GetTraits()
|
||||||
{
|
{
|
||||||
return _syntaxTrees
|
return _syntaxTrees
|
||||||
.SelectMany(c => c.Definitions)
|
.SelectMany(c => c.Definitions)
|
||||||
.OfType<InterfaceDefinitionNode>();
|
.OfType<TraitDefinitionNode>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public IEnumerable<ImplementationDefinitionNode> GetImplementations()
|
public IEnumerable<TraitImplementationDefinitionNode> GetTraitImplementations()
|
||||||
{
|
{
|
||||||
return _syntaxTrees
|
return _syntaxTrees
|
||||||
.SelectMany(c => c.Definitions)
|
.SelectMany(c => c.Definitions)
|
||||||
.OfType<ImplementationDefinitionNode>();
|
.OfType<TraitImplementationDefinitionNode>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,6 +148,43 @@ public class BoundDefinitionTable
|
|||||||
return Optional.OfNullable(definition);
|
return Optional.OfNullable(definition);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Optional<BoundTraitDefinitionNode> LookupTrait(string @namespace, string name)
|
||||||
|
{
|
||||||
|
var definition = _syntaxTrees
|
||||||
|
.Where(c => c.Namespace == @namespace)
|
||||||
|
.SelectMany(c => c.Definitions)
|
||||||
|
.OfType<BoundTraitDefinitionNode>()
|
||||||
|
.SingleOrDefault(f => f.Name == name);
|
||||||
|
|
||||||
|
return Optional.OfNullable(definition);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<Tuple<BoundTraitImplementationDefinitionNode, BoundImplementationFuncNode>> LookupTraitImplementationForType(NubType type, string funcName)
|
||||||
|
{
|
||||||
|
var implementations = _syntaxTrees
|
||||||
|
.SelectMany(c => c.Definitions)
|
||||||
|
.OfType<BoundTraitImplementationDefinitionNode>()
|
||||||
|
.Where(c => c.ForType.Equals(type));
|
||||||
|
|
||||||
|
var implementation = implementations.SingleOrDefault(c => c.Functions.Any(x => x.Name == funcName));
|
||||||
|
|
||||||
|
var value = implementation == null ? null : new Tuple<BoundTraitImplementationDefinitionNode, BoundImplementationFuncNode>(implementation, implementation.Functions.First(x => x.Name == funcName));
|
||||||
|
|
||||||
|
return Optional.OfNullable(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<BountTraitFunc> LookupFunctionOnTrait(string @namespace, string name, string funcName)
|
||||||
|
{
|
||||||
|
var traitDef = LookupTrait(@namespace, name);
|
||||||
|
if (traitDef.HasValue)
|
||||||
|
{
|
||||||
|
var function = traitDef.Value.Functions.SingleOrDefault(x => x.Name == funcName);
|
||||||
|
return Optional.OfNullable(function);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Optional<BountTraitFunc>.Empty();
|
||||||
|
}
|
||||||
|
|
||||||
public IEnumerable<BoundStructDefinitionNode> GetStructs()
|
public IEnumerable<BoundStructDefinitionNode> GetStructs()
|
||||||
{
|
{
|
||||||
return _syntaxTrees
|
return _syntaxTrees
|
||||||
@@ -139,17 +213,17 @@ public class BoundDefinitionTable
|
|||||||
.OfType<BoundExternFuncDefinitionNode>();
|
.OfType<BoundExternFuncDefinitionNode>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public IEnumerable<BoundInterfaceDefinitionNode> GetInterfaces()
|
public IEnumerable<BoundTraitDefinitionNode> GetTraits()
|
||||||
{
|
{
|
||||||
return _syntaxTrees
|
return _syntaxTrees
|
||||||
.SelectMany(c => c.Definitions)
|
.SelectMany(c => c.Definitions)
|
||||||
.OfType<BoundInterfaceDefinitionNode>();
|
.OfType<BoundTraitDefinitionNode>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public IEnumerable<BoundImplementationDefinitionNode> GetImplementations()
|
public IEnumerable<BoundTraitImplementationDefinitionNode> GetTraitImplementations()
|
||||||
{
|
{
|
||||||
return _syntaxTrees
|
return _syntaxTrees
|
||||||
.SelectMany(c => c.Definitions)
|
.SelectMany(c => c.Definitions)
|
||||||
.OfType<BoundImplementationDefinitionNode>();
|
.OfType<BoundTraitImplementationDefinitionNode>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using Common;
|
using Common;
|
||||||
using Syntax.Tokenization;
|
using Syntax.Tokenization;
|
||||||
using Syntax.Typing;
|
using Syntax.Typing;
|
||||||
|
using Syntax.Typing.BoundNode;
|
||||||
|
|
||||||
namespace Syntax.Parsing.Node;
|
namespace Syntax.Parsing.Node;
|
||||||
|
|
||||||
@@ -14,8 +15,8 @@ public record ExternFuncDefinitionNode(IEnumerable<Token> Tokens, Optional<strin
|
|||||||
public record StructField(string Name, NubType Type, Optional<ExpressionNode> Value);
|
public record StructField(string Name, NubType Type, Optional<ExpressionNode> Value);
|
||||||
public record StructDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, string Name, List<StructField> Fields) : DefinitionNode(Tokens, Documentation, Namespace);
|
public record StructDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, string Name, List<StructField> Fields) : DefinitionNode(Tokens, Documentation, Namespace);
|
||||||
|
|
||||||
public record InterfaceFunc(string Name, List<FuncParameter> Parameters, NubType ReturnType);
|
public record TraitFunc(string Name, List<FuncParameter> Parameters, NubType ReturnType);
|
||||||
public record InterfaceDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, string Name, List<InterfaceFunc> Functions) : DefinitionNode(Tokens, Documentation, Namespace);
|
public record TraitDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, string Name, List<TraitFunc> Functions) : DefinitionNode(Tokens, Documentation, Namespace);
|
||||||
|
|
||||||
public record ImplementationFunc(string Name, List<FuncParameter> Parameters, NubType ReturnType, BlockNode Body);
|
public record ImplementationFuncNode(IEnumerable<Token> Tokens, string Name, List<FuncParameter> Parameters, NubType ReturnType, BlockNode Body) : BoundNode(Tokens);
|
||||||
public record ImplementationDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, NubType Type, NubType Interface, List<ImplementationFunc> Functions) : DefinitionNode(Tokens, Documentation, Namespace);
|
public record TraitImplementationDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, NubType TraitType, NubType ForType, List<ImplementationFuncNode> Functions) : DefinitionNode(Tokens, Documentation, Namespace);
|
||||||
@@ -38,5 +38,5 @@ public record AnonymousFuncNode(IEnumerable<Token> Tokens, List<FuncParameter> P
|
|||||||
public record AddressOfNode(IEnumerable<Token> Tokens, ExpressionNode Expression) : ExpressionNode(Tokens);
|
public record AddressOfNode(IEnumerable<Token> Tokens, ExpressionNode Expression) : ExpressionNode(Tokens);
|
||||||
public record LiteralNode(IEnumerable<Token> Tokens, string Literal, LiteralKind Kind) : ExpressionNode(Tokens);
|
public record LiteralNode(IEnumerable<Token> Tokens, string Literal, LiteralKind Kind) : ExpressionNode(Tokens);
|
||||||
public record MemberAccessNode(IEnumerable<Token> Tokens, ExpressionNode Expression, string Member) : ExpressionNode(Tokens);
|
public record MemberAccessNode(IEnumerable<Token> Tokens, ExpressionNode Expression, string Member) : ExpressionNode(Tokens);
|
||||||
public record StructInitializerNode(IEnumerable<Token> Tokens, NubStructType StructType, Dictionary<string, ExpressionNode> Initializers) : ExpressionNode(Tokens);
|
public record StructInitializerNode(IEnumerable<Token> Tokens, NubType StructType, Dictionary<string, ExpressionNode> Initializers) : ExpressionNode(Tokens);
|
||||||
public record DereferenceNode(IEnumerable<Token> Tokens, ExpressionNode Expression) : ExpressionNode(Tokens);
|
public record DereferenceNode(IEnumerable<Token> Tokens, ExpressionNode Expression) : ExpressionNode(Tokens);
|
||||||
|
|||||||
@@ -17,21 +17,13 @@ public static class Parser
|
|||||||
public static SyntaxTree? ParseFile(IEnumerable<Token> tokens, out IEnumerable<Diagnostic> diagnostics)
|
public static SyntaxTree? ParseFile(IEnumerable<Token> tokens, out IEnumerable<Diagnostic> diagnostics)
|
||||||
{
|
{
|
||||||
_tokens = tokens;
|
_tokens = tokens;
|
||||||
_namespace = null!;
|
_namespace = "global";
|
||||||
_diagnostics = [];
|
_diagnostics = [];
|
||||||
_index = 0;
|
_index = 0;
|
||||||
|
|
||||||
try
|
if (TryExpectSymbol(Symbol.Namespace))
|
||||||
{
|
{
|
||||||
ExpectSymbol(Symbol.Namespace);
|
_namespace = ExpectIdentifier().Value;
|
||||||
var @namespace = ExpectIdentifier();
|
|
||||||
_namespace = @namespace.Value;
|
|
||||||
}
|
|
||||||
catch (ParseException ex)
|
|
||||||
{
|
|
||||||
_diagnostics.Add(ex.Diagnostic);
|
|
||||||
diagnostics = _diagnostics;
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
@@ -81,7 +73,7 @@ public static class Parser
|
|||||||
{
|
{
|
||||||
Symbol.Func => ParseFuncDefinition(startIndex, modifiers, Optional.OfNullable(documentation)),
|
Symbol.Func => ParseFuncDefinition(startIndex, modifiers, Optional.OfNullable(documentation)),
|
||||||
Symbol.Struct => ParseStruct(startIndex, modifiers, Optional.OfNullable(documentation)),
|
Symbol.Struct => ParseStruct(startIndex, modifiers, Optional.OfNullable(documentation)),
|
||||||
Symbol.Interface => ParseInterface(startIndex, modifiers, Optional.OfNullable(documentation)),
|
Symbol.Trait => ParseTrait(startIndex, modifiers, Optional.OfNullable(documentation)),
|
||||||
Symbol.Impl => ParseImplementation(startIndex, modifiers, Optional.OfNullable(documentation)),
|
Symbol.Impl => ParseImplementation(startIndex, modifiers, Optional.OfNullable(documentation)),
|
||||||
_ => throw new ParseException(Diagnostic
|
_ => throw new ParseException(Diagnostic
|
||||||
.Error($"Expected 'func' or 'struct', but found '{keyword.Symbol}'")
|
.Error($"Expected 'func' or 'struct', but found '{keyword.Symbol}'")
|
||||||
@@ -187,13 +179,13 @@ public static class Parser
|
|||||||
return new StructDefinitionNode(GetTokensForNode(startIndex), documentation, _namespace, name, variables);
|
return new StructDefinitionNode(GetTokensForNode(startIndex), documentation, _namespace, name, variables);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static InterfaceDefinitionNode ParseInterface(int startIndex, List<ModifierToken> modifiers, Optional<string> documentation)
|
private static TraitDefinitionNode ParseTrait(int startIndex, List<ModifierToken> modifiers, Optional<string> documentation)
|
||||||
{
|
{
|
||||||
var name = ExpectIdentifier().Value;
|
var name = ExpectIdentifier().Value;
|
||||||
|
|
||||||
ExpectSymbol(Symbol.OpenBrace);
|
ExpectSymbol(Symbol.OpenBrace);
|
||||||
|
|
||||||
List<InterfaceFunc> functions = [];
|
List<TraitFunc> functions = [];
|
||||||
|
|
||||||
while (!TryExpectSymbol(Symbol.CloseBrace))
|
while (!TryExpectSymbol(Symbol.CloseBrace))
|
||||||
{
|
{
|
||||||
@@ -222,34 +214,35 @@ public static class Parser
|
|||||||
if (modifiers.Count != 0)
|
if (modifiers.Count != 0)
|
||||||
{
|
{
|
||||||
throw new ParseException(Diagnostic
|
throw new ParseException(Diagnostic
|
||||||
.Error($"Invalid modifiers for interface: {modifiers[0].Modifier}")
|
.Error($"Invalid modifiers for trait: {modifiers[0].Modifier}")
|
||||||
.WithHelp($"Interface cannot use the '{modifiers[0].Modifier}' modifier")
|
.WithHelp($"Traits cannot use the '{modifiers[0].Modifier}' modifier")
|
||||||
.At(modifiers[0])
|
.At(modifiers[0])
|
||||||
.Build());
|
.Build());
|
||||||
}
|
}
|
||||||
|
|
||||||
functions.Add(new InterfaceFunc(funcName, parameters, returnType));
|
functions.Add(new TraitFunc(funcName, parameters, returnType));
|
||||||
}
|
}
|
||||||
|
|
||||||
return new InterfaceDefinitionNode(GetTokensForNode(startIndex), documentation, _namespace, name, functions);
|
return new TraitDefinitionNode(GetTokensForNode(startIndex), documentation, _namespace, name, functions);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ImplementationDefinitionNode ParseImplementation(int startIndex, List<ModifierToken> modifiers, Optional<string> documentation)
|
private static TraitImplementationDefinitionNode ParseImplementation(int startIndex, List<ModifierToken> modifiers, Optional<string> documentation)
|
||||||
{
|
{
|
||||||
var type = ParseType();
|
var traitType = ParseType();
|
||||||
ExpectSymbol(Symbol.Colon);
|
ExpectSymbol(Symbol.For);
|
||||||
var @interface = ParseType();
|
var forType = ParseType();
|
||||||
|
|
||||||
List<ImplementationFunc> functions = [];
|
List<ImplementationFuncNode> functions = [];
|
||||||
|
|
||||||
ExpectSymbol(Symbol.OpenBrace);
|
ExpectSymbol(Symbol.OpenBrace);
|
||||||
while (!TryExpectSymbol(Symbol.CloseBrace))
|
while (!TryExpectSymbol(Symbol.CloseBrace))
|
||||||
{
|
{
|
||||||
|
var funcStartIndex = _index;
|
||||||
ExpectSymbol(Symbol.Func);
|
ExpectSymbol(Symbol.Func);
|
||||||
var functionName = ExpectIdentifier().Value;
|
var functionName = ExpectIdentifier().Value;
|
||||||
var parameters = new List<FuncParameter>
|
var parameters = new List<FuncParameter>
|
||||||
{
|
{
|
||||||
new("this", type)
|
new("this", forType)
|
||||||
};
|
};
|
||||||
|
|
||||||
ExpectSymbol(Symbol.OpenParen);
|
ExpectSymbol(Symbol.OpenParen);
|
||||||
@@ -272,10 +265,19 @@ public static class Parser
|
|||||||
|
|
||||||
var body = ParseBlock();
|
var body = ParseBlock();
|
||||||
|
|
||||||
functions.AddRange(new ImplementationFunc(functionName, parameters, returnType, body));
|
functions.AddRange(new ImplementationFuncNode(GetTokensForNode(funcStartIndex), functionName, parameters, returnType, body));
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ImplementationDefinitionNode(GetTokensForNode(startIndex), documentation, _namespace, type, @interface, functions);
|
if (modifiers.Count != 0)
|
||||||
|
{
|
||||||
|
throw new ParseException(Diagnostic
|
||||||
|
.Error($"Invalid modifiers for implementation: {modifiers[0].Modifier}")
|
||||||
|
.WithHelp($"Implementations cannot use the '{modifiers[0].Modifier}' modifier")
|
||||||
|
.At(modifiers[0])
|
||||||
|
.Build());
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TraitImplementationDefinitionNode(GetTokensForNode(startIndex), documentation, _namespace, traitType, forType, functions);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static FuncParameter ParseFuncParameter()
|
private static FuncParameter ParseFuncParameter()
|
||||||
@@ -580,15 +582,7 @@ public static class Parser
|
|||||||
initializers.Add(name, value);
|
initializers.Add(name, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type is not NubStructType structType)
|
expr = new StructInitializerNode(GetTokensForNode(startIndex), type, initializers);
|
||||||
{
|
|
||||||
throw new ParseException(Diagnostic
|
|
||||||
.Error($"Cannot alloc type '{type}'")
|
|
||||||
.At(symbolToken)
|
|
||||||
.Build());
|
|
||||||
}
|
|
||||||
|
|
||||||
expr = new StructInitializerNode(GetTokensForNode(startIndex), structType, initializers);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -729,16 +723,7 @@ public static class Parser
|
|||||||
@namespace = ExpectIdentifier().Value;
|
@namespace = ExpectIdentifier().Value;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (@namespace == null)
|
return new NubCustomType(@namespace, name.Value);
|
||||||
{
|
|
||||||
throw new ParseException(Diagnostic
|
|
||||||
.Error($"Struct '{name.Value}' does not belong to a namespace")
|
|
||||||
.WithHelp("Make sure you have specified a namespace at the top of the file")
|
|
||||||
.At(name)
|
|
||||||
.Build());
|
|
||||||
}
|
|
||||||
|
|
||||||
return new NubStructType(@namespace, name.Value);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (TryExpectSymbol(Symbol.Caret))
|
if (TryExpectSymbol(Symbol.Caret))
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ public enum Symbol
|
|||||||
Let,
|
Let,
|
||||||
Alloc,
|
Alloc,
|
||||||
Calls,
|
Calls,
|
||||||
Interface,
|
Trait,
|
||||||
Impl
|
Impl,
|
||||||
|
For
|
||||||
}
|
}
|
||||||
@@ -19,8 +19,9 @@ public static class Tokenizer
|
|||||||
["struct"] = Symbol.Struct,
|
["struct"] = Symbol.Struct,
|
||||||
["let"] = Symbol.Let,
|
["let"] = Symbol.Let,
|
||||||
["calls"] = Symbol.Calls,
|
["calls"] = Symbol.Calls,
|
||||||
["interface"] = Symbol.Interface,
|
["trait"] = Symbol.Trait,
|
||||||
["impl"] = Symbol.Impl,
|
["impl"] = Symbol.Impl,
|
||||||
|
["for"] = Symbol.For,
|
||||||
};
|
};
|
||||||
|
|
||||||
private static readonly Dictionary<string, Modifier> Modifiers = new()
|
private static readonly Dictionary<string, Modifier> Modifiers = new()
|
||||||
|
|||||||
@@ -41,18 +41,18 @@ public static class Binder
|
|||||||
return node switch
|
return node switch
|
||||||
{
|
{
|
||||||
ExternFuncDefinitionNode definition => BindExternFuncDefinition(definition),
|
ExternFuncDefinitionNode definition => BindExternFuncDefinition(definition),
|
||||||
ImplementationDefinitionNode definition => BindImplementation(definition),
|
TraitImplementationDefinitionNode definition => BindTraitImplementation(definition),
|
||||||
InterfaceDefinitionNode definition => BindInterfaceDefinition(definition),
|
TraitDefinitionNode definition => BindTraitDefinition(definition),
|
||||||
LocalFuncDefinitionNode definition => BindLocalFuncDefinition(definition),
|
LocalFuncDefinitionNode definition => BindLocalFuncDefinition(definition),
|
||||||
StructDefinitionNode definition => BindStruct(definition),
|
StructDefinitionNode definition => BindStruct(definition),
|
||||||
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
_ => throw new ArgumentOutOfRangeException(nameof(node))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static BoundImplementationDefinitionNode BindImplementation(ImplementationDefinitionNode node)
|
private static BoundTraitImplementationDefinitionNode BindTraitImplementation(TraitImplementationDefinitionNode node)
|
||||||
{
|
{
|
||||||
_variables.Clear();
|
_variables.Clear();
|
||||||
var functions = new List<BoundImplementationFunc>();
|
var functions = new List<BoundImplementationFuncNode>();
|
||||||
|
|
||||||
foreach (var function in node.Functions)
|
foreach (var function in node.Functions)
|
||||||
{
|
{
|
||||||
@@ -63,15 +63,15 @@ public static class Binder
|
|||||||
_variables[parameter.Name] = parameter.Type;
|
_variables[parameter.Name] = parameter.Type;
|
||||||
}
|
}
|
||||||
|
|
||||||
functions.Add(new BoundImplementationFunc(function.Name, parameters, function.ReturnType, BindBlock(function.Body)));
|
functions.Add(new BoundImplementationFuncNode(function.Tokens, function.Name, parameters, function.ReturnType, BindBlock(function.Body)));
|
||||||
}
|
}
|
||||||
|
|
||||||
return new BoundImplementationDefinitionNode(node.Tokens, node.Documentation, node.Namespace, node.Type, node.Interface, functions);
|
return new BoundTraitImplementationDefinitionNode(node.Tokens, node.Documentation, node.Namespace, node.TraitType, node.ForType, functions);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static BoundInterfaceDefinitionNode BindInterfaceDefinition(InterfaceDefinitionNode node)
|
private static BoundTraitDefinitionNode BindTraitDefinition(TraitDefinitionNode node)
|
||||||
{
|
{
|
||||||
var functions = new List<BoundInterfaceFunc>();
|
var functions = new List<BountTraitFunc>();
|
||||||
|
|
||||||
foreach (var func in node.Functions)
|
foreach (var func in node.Functions)
|
||||||
{
|
{
|
||||||
@@ -82,10 +82,10 @@ public static class Binder
|
|||||||
parameters.Add(new BoundFuncParameter(parameter.Name, parameter.Type));
|
parameters.Add(new BoundFuncParameter(parameter.Name, parameter.Type));
|
||||||
}
|
}
|
||||||
|
|
||||||
functions.Add(new BoundInterfaceFunc(func.Name, parameters, func.ReturnType));
|
functions.Add(new BountTraitFunc(func.Name, parameters, func.ReturnType));
|
||||||
}
|
}
|
||||||
|
|
||||||
return new BoundInterfaceDefinitionNode(node.Tokens, node.Documentation, node.Namespace, node.Name, functions);
|
return new BoundTraitDefinitionNode(node.Tokens, node.Documentation, node.Namespace, node.Name, functions);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static BoundStructDefinitionNode BindStruct(StructDefinitionNode node)
|
private static BoundStructDefinitionNode BindStruct(StructDefinitionNode node)
|
||||||
@@ -393,51 +393,55 @@ public static class Binder
|
|||||||
{
|
{
|
||||||
var boundExpression = BindExpression(expression.Expression);
|
var boundExpression = BindExpression(expression.Expression);
|
||||||
|
|
||||||
NubType? type = null;
|
var implementation = _definitionTable.LookupTraitImplementationForType(boundExpression.Type, expression.Member);
|
||||||
|
if (implementation.HasValue)
|
||||||
switch (boundExpression.Type)
|
|
||||||
{
|
{
|
||||||
case NubArrayType:
|
var type = new NubFuncType(implementation.Value.Item2.ReturnType, implementation.Value.Item2.Parameters.Select(p => p.Type).ToList());
|
||||||
case NubStringType:
|
return new BoundMemberAccessNode(expression.Tokens, type, boundExpression, expression.Member);
|
||||||
case NubCStringType:
|
}
|
||||||
{
|
|
||||||
if (expression.Member == "count")
|
|
||||||
{
|
|
||||||
type = NubPrimitiveType.U64;
|
|
||||||
}
|
|
||||||
|
|
||||||
break;
|
if (boundExpression.Type is NubCustomType customType)
|
||||||
}
|
{
|
||||||
case NubStructType structType:
|
var function = _definitionTable.LookupFunctionOnTrait(customType.Namespace, customType.Name, expression.Member);
|
||||||
|
if (function.HasValue)
|
||||||
{
|
{
|
||||||
var defOpt = _definitionTable.LookupStruct(structType.Namespace, structType.Name);
|
var type = new NubFuncType(function.Value.ReturnType, function.Value.Parameters.Select(p => p.Type).ToList());
|
||||||
if (!defOpt.TryGetValue(out var definition))
|
return new BoundMemberAccessNode(expression.Tokens, type, boundExpression, expression.Member);
|
||||||
|
}
|
||||||
|
|
||||||
|
var structDef = _definitionTable.LookupStruct(customType.Namespace, customType.Name);
|
||||||
|
if (structDef.HasValue)
|
||||||
|
{
|
||||||
|
var matchingFields = structDef.Value.Fields.Where(f => f.Name == expression.Member).ToList();
|
||||||
|
|
||||||
|
if (matchingFields.Count > 1)
|
||||||
{
|
{
|
||||||
throw new NotImplementedException("Diagnostics not implemented");
|
throw new NotImplementedException("Diagnostics not implemented");
|
||||||
}
|
}
|
||||||
|
|
||||||
var field = definition.Fields.FirstOrDefault(f => f.Name == expression.Member);
|
if (matchingFields.Count == 1)
|
||||||
if (field == null)
|
|
||||||
{
|
{
|
||||||
throw new NotImplementedException("Diagnostics not implemented");
|
return new BoundMemberAccessNode(expression.Tokens, matchingFields[0].Type, boundExpression, expression.Member);
|
||||||
}
|
}
|
||||||
|
|
||||||
type = field.Type;
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type == null)
|
if (boundExpression.Type is NubStringType or NubCStringType or NubArrayType && expression.Member == "count")
|
||||||
{
|
{
|
||||||
throw new NotImplementedException("Diagnostics not implemented");
|
return new BoundMemberAccessNode(expression.Tokens, NubPrimitiveType.I64, boundExpression, expression.Member);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new BoundMemberAccessNode(expression.Tokens, type, boundExpression, expression.Member);
|
throw new NotImplementedException("Diagnostics not implemented");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static BoundStructInitializerNode BindStructInitializer(StructInitializerNode expression)
|
private static BoundStructInitializerNode BindStructInitializer(StructInitializerNode expression)
|
||||||
{
|
{
|
||||||
var defOpt = _definitionTable.LookupStruct(expression.StructType.Namespace, expression.StructType.Name);
|
if (expression.StructType is not NubCustomType structType)
|
||||||
|
{
|
||||||
|
throw new NotImplementedException("Diagnostics not implemented");
|
||||||
|
}
|
||||||
|
|
||||||
|
var defOpt = _definitionTable.LookupStruct(structType.Namespace, structType.Name);
|
||||||
if (!defOpt.TryGetValue(out var definition))
|
if (!defOpt.TryGetValue(out var definition))
|
||||||
{
|
{
|
||||||
throw new NotImplementedException("Diagnostics not implemented");
|
throw new NotImplementedException("Diagnostics not implemented");
|
||||||
@@ -456,7 +460,7 @@ public static class Binder
|
|||||||
initializers[member] = BindExpression(initializer, definitionField.Type);
|
initializers[member] = BindExpression(initializer, definitionField.Type);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new BoundStructInitializerNode(expression.Tokens, expression.StructType, expression.StructType, initializers);
|
return new BoundStructInitializerNode(expression.Tokens, structType, structType, initializers);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static BoundUnaryExpressionNode BindUnaryExpression(UnaryExpressionNode expression)
|
private static BoundUnaryExpressionNode BindUnaryExpression(UnaryExpressionNode expression)
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ public record BoundExternFuncDefinitionNode(IEnumerable<Token> Tokens, Optional<
|
|||||||
public record BoundStructField(string Name, NubType Type, Optional<BoundExpressionNode> Value);
|
public record BoundStructField(string Name, NubType Type, Optional<BoundExpressionNode> Value);
|
||||||
public record BoundStructDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, string Name, List<BoundStructField> Fields) : BoundDefinitionNode(Tokens, Documentation, Namespace);
|
public record BoundStructDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, string Name, List<BoundStructField> Fields) : BoundDefinitionNode(Tokens, Documentation, Namespace);
|
||||||
|
|
||||||
public record BoundInterfaceFunc(string Name, List<BoundFuncParameter> Parameters, NubType ReturnType);
|
public record BountTraitFunc(string Name, List<BoundFuncParameter> Parameters, NubType ReturnType);
|
||||||
public record BoundInterfaceDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, string Name, List<BoundInterfaceFunc> Functions) : BoundDefinitionNode(Tokens, Documentation, Namespace);
|
public record BoundTraitDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, string Name, List<BountTraitFunc> Functions) : BoundDefinitionNode(Tokens, Documentation, Namespace);
|
||||||
|
|
||||||
public record BoundImplementationFunc(string Name, List<BoundFuncParameter> Parameters, NubType ReturnType, BoundBlockNode Body);
|
public record BoundImplementationFuncNode(IEnumerable<Token> Tokens, string Name, List<BoundFuncParameter> Parameters, NubType ReturnType, BoundBlockNode Body) : BoundNode(Tokens);
|
||||||
public record BoundImplementationDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, NubType Type, NubType Interface, List<BoundImplementationFunc> Functions) : BoundDefinitionNode(Tokens, Documentation, Namespace);
|
public record BoundTraitImplementationDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, NubType TraitType, NubType ForType, List<BoundImplementationFuncNode> Functions) : BoundDefinitionNode(Tokens, Documentation, Namespace);
|
||||||
@@ -15,5 +15,5 @@ public record BoundAnonymousFuncNode(IEnumerable<Token> Tokens, NubType Type, Li
|
|||||||
public record BoundAddressOfNode(IEnumerable<Token> Tokens, NubType Type, BoundExpressionNode Expression) : BoundExpressionNode(Tokens, Type);
|
public record BoundAddressOfNode(IEnumerable<Token> Tokens, NubType Type, BoundExpressionNode Expression) : BoundExpressionNode(Tokens, Type);
|
||||||
public record BoundLiteralNode(IEnumerable<Token> Tokens, NubType Type, string Literal, LiteralKind Kind) : BoundExpressionNode(Tokens, Type);
|
public record BoundLiteralNode(IEnumerable<Token> Tokens, NubType Type, string Literal, LiteralKind Kind) : BoundExpressionNode(Tokens, Type);
|
||||||
public record BoundMemberAccessNode(IEnumerable<Token> Tokens, NubType Type, BoundExpressionNode Expression, string Member) : BoundExpressionNode(Tokens, Type);
|
public record BoundMemberAccessNode(IEnumerable<Token> Tokens, NubType Type, BoundExpressionNode Expression, string Member) : BoundExpressionNode(Tokens, Type);
|
||||||
public record BoundStructInitializerNode(IEnumerable<Token> Tokens, NubType Type, NubStructType StructType, Dictionary<string, BoundExpressionNode> Initializers) : BoundExpressionNode(Tokens, Type);
|
public record BoundStructInitializerNode(IEnumerable<Token> Tokens, NubType Type, NubType StructType, Dictionary<string, BoundExpressionNode> Initializers) : BoundExpressionNode(Tokens, Type);
|
||||||
public record BoundDereferenceNode(IEnumerable<Token> Tokens, NubType Type, BoundExpressionNode Expression) : BoundExpressionNode(Tokens, Type);
|
public record BoundDereferenceNode(IEnumerable<Token> Tokens, NubType Type, BoundExpressionNode Expression) : BoundExpressionNode(Tokens, Type);
|
||||||
|
|||||||
@@ -89,14 +89,14 @@ public class NubFuncType(NubType returnType, List<NubType> parameters) : NubSimp
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class NubStructType(string @namespace, string name) : NubComplexType
|
public class NubCustomType(string @namespace, string name) : NubComplexType
|
||||||
{
|
{
|
||||||
public string Namespace { get; } = @namespace;
|
public string Namespace { get; } = @namespace;
|
||||||
public string Name { get; } = name;
|
public string Name { get; } = name;
|
||||||
|
|
||||||
public override bool Equals(object? obj)
|
public override bool Equals(object? obj)
|
||||||
{
|
{
|
||||||
return obj is NubStructType other && other.Namespace == Namespace && other.Name == Name;
|
return obj is NubCustomType other && other.Namespace == Namespace && other.Name == Name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override int GetHashCode()
|
public override int GetHashCode()
|
||||||
|
|||||||
Reference in New Issue
Block a user