From cf7572a27becc49ba1d8f829f2166743799d21ff Mon Sep 17 00:00:00 2001 From: nub31 Date: Fri, 4 Jul 2025 21:43:26 +0200 Subject: [PATCH] Traits --- example/src/main.nub | 20 +- src/compiler/Generation/QBE/QBEGenerator.cs | 532 +++++++++--------- src/compiler/Generation/QBE/QBEWriter.cs | 2 +- src/compiler/Syntax/DefinitionTable.cs | 90 ++- .../Syntax/Parsing/Node/Definition.cs | 9 +- .../Syntax/Parsing/Node/Expression.cs | 2 +- src/compiler/Syntax/Parsing/Parser.cs | 75 +-- .../Syntax/Tokenization/SymbolToken.cs | 5 +- src/compiler/Syntax/Tokenization/Tokenizer.cs | 3 +- src/compiler/Syntax/Typing/Binder.cs | 78 +-- .../Syntax/Typing/BoundNode/Definition.cs | 8 +- .../Syntax/Typing/BoundNode/Expression.cs | 2 +- src/compiler/Syntax/Typing/NubType.cs | 4 +- 13 files changed, 453 insertions(+), 377 deletions(-) diff --git a/example/src/main.nub b/example/src/main.nub index ce803d7..8161698 100644 --- a/example/src/main.nub +++ b/example/src/main.nub @@ -1,41 +1,39 @@ -namespace main - -struct Name +struct name { first: cstring last: cstring } -struct Human +struct human { - name: Name + name: name age: i64 } -interface Printable +trait printable { func print() } -impl Human : Printable +impl printable for human { func print() { - c::puts(this.name) + c::puts(this.name.first) } } export func main(args: []cstring): i64 { - let x = alloc Human + let human = alloc human { - name = alloc Name { + name = alloc name { first = "john" last = "doe" } age = 23 } - x.print() + human.print() return 0 } diff --git a/src/compiler/Generation/QBE/QBEGenerator.cs b/src/compiler/Generation/QBE/QBEGenerator.cs index bb41a19..d2335c4 100644 --- a/src/compiler/Generation/QBE/QBEGenerator.cs +++ b/src/compiler/Generation/QBE/QBEGenerator.cs @@ -21,13 +21,15 @@ public static class QBEGenerator private static Stack _breakLabels = []; private static Stack _continueLabels = []; private static Queue<(BoundAnonymousFuncNode Func, string Name)> _anonymousFunctions = []; + private static Dictionary _implFunctions = []; private static Stack _variables = []; private static Stack _variableScopes = []; - private static int _variableIndex; + private static int _tmpIndex; private static int _labelIndex; private static int _anonymousFuncIndex; private static int _cStringLiteralIndex; private static int _stringLiteralIndex; + private static int _implFuncNameIndex; private static bool _codeIsReachable = true; public static string Emit(BoundSyntaxTree syntaxTree, BoundDefinitionTable definitionTable, string file) @@ -42,13 +44,15 @@ public static class QBEGenerator _breakLabels = []; _continueLabels = []; _anonymousFunctions = []; + _implFunctions = []; _variables = []; _variableScopes = []; - _variableIndex = 0; + _tmpIndex = 0; _labelIndex = 0; _anonymousFuncIndex = 0; _cStringLiteralIndex = 0; _stringLiteralIndex = 0; + _implFuncNameIndex = 0; _codeIsReachable = true; foreach (var structDef in _definitionTable.GetStructs()) @@ -57,9 +61,9 @@ public static class QBEGenerator _writer.NewLine(); } - foreach (var @interface in _definitionTable.GetInterfaces()) + foreach (var trait in _definitionTable.GetTraits()) { - EmitInterfaceVTableType(@interface); + EmitTraitVTable(trait); _writer.NewLine(); } @@ -75,6 +79,12 @@ public static class QBEGenerator _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) { _writer.WriteLine($"data {cStringLiteral.Name} = {{ b \"{cStringLiteral.Value}\", b 0 }}"); @@ -89,9 +99,9 @@ public static class QBEGenerator return _writer.ToString(); } - private static string VarName() + private static string TmpName() { - return $"%v{++_variableIndex}"; + return $"%t{++_tmpIndex}"; } 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) { var store = type switch { - NubPrimitiveType primitiveType => primitiveType.Kind switch + NubComplexType => "storel", + NubSimpleType simpleType => simpleType switch { - PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "storel", - PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "storew", - PrimitiveTypeKind.I16 or PrimitiveTypeKind.U16 => "storeh", - PrimitiveTypeKind.I8 or PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "storeb", - PrimitiveTypeKind.F64 => "stored", - PrimitiveTypeKind.F32 => "stores", - _ => throw new ArgumentOutOfRangeException() + NubFuncType or NubPointerType => "loadl", + NubPrimitiveType primitiveType => primitiveType.Kind switch + { + PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "storel", + PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "storew", + PrimitiveTypeKind.I16 or PrimitiveTypeKind.U16 => "storeh", + 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 NotSupportedException($"'{type}' type cannot be used in store instructions") + _ => throw new UnreachableException() }; _writer.Indented($"{store} {value}, {destination}"); @@ -154,23 +169,28 @@ public static class QBEGenerator private static Val EmitLoad(NubType type, string from) { - var into = VarName(); + var into = TmpName(); var load = type switch { - NubPrimitiveType primitiveType => primitiveType.Kind switch + NubComplexType => "loadl", + NubSimpleType simpleType => simpleType switch { - PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "loadl", - PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "loadw", - PrimitiveTypeKind.I16 => "loadsh", - PrimitiveTypeKind.I8 => "loadsb", - PrimitiveTypeKind.U16 => "loaduh", - PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "loadub", - PrimitiveTypeKind.F64 => "loadd", - PrimitiveTypeKind.F32 => "loads", - _ => throw new ArgumentOutOfRangeException() + NubFuncType or NubPointerType => "loadl", + NubPrimitiveType primitiveType => primitiveType.Kind switch + { + PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "loadl", + PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "loadw", + PrimitiveTypeKind.I16 => "loadsh", + PrimitiveTypeKind.I8 => "loadsb", + PrimitiveTypeKind.U16 => "loaduh", + 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 NotSupportedException($"'{type}' type cannot be used in load instructions") + _ => throw new UnreachableException() }; _writer.Indented($"{into} {QBEAssign(type)} {load} {from}"); @@ -185,7 +205,7 @@ public static class QBEGenerator private static string EmitArraySizeInBytes(NubArrayType type, string array) { - var size = VarName(); + var size = TmpName(); _writer.Indented($"{size} =l loadl {array}"); _writer.Indented($"{size} =l mul {size}, {SizeOf(type.ElementType)}"); _writer.Indented($"{size} =l add {size}, 8"); @@ -194,7 +214,7 @@ public static class QBEGenerator 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 add {size}, 1"); return size; @@ -202,7 +222,7 @@ public static class QBEGenerator private static string EmitStringSizeInBytes(string nubstring) { - var size = VarName(); + var size = TmpName(); _writer.Indented($"{size} =l loadl {nubstring}"); _writer.Indented($"{size} =l add {size}, 8"); return size; @@ -251,10 +271,10 @@ public static class QBEGenerator { var size = complexType switch { - NubArrayType nubArrayType => EmitArraySizeInBytes(nubArrayType, value), + NubArrayType arrayType => EmitArraySizeInBytes(arrayType, value), NubCStringType => EmitCStringSizeInBytes(value), NubStringType => EmitStringSizeInBytes(value), - NubStructType nubStructType => SizeOf(nubStructType).ToString(), + NubCustomType customType => SizeOf(customType).ToString(), _ => throw new ArgumentOutOfRangeException(nameof(complexType)) }; @@ -264,13 +284,13 @@ public static class QBEGenerator case NubCStringType: case NubStringType: { - var buffer = VarName(); + var buffer = TmpName(); _writer.Indented($"{buffer} =l alloc8 {size}"); EmitMemcpy(value, buffer, size); EmitStore(source.Type, buffer, destinationPointer); return; } - case NubStructType: + case NubCustomType: { EmitMemcpy(value, destinationPointer, size); return; @@ -310,7 +330,7 @@ public static class QBEGenerator 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 (EmitTryCreateWithoutCopy(source, out var uncopiedValue)) @@ -320,18 +340,18 @@ public static class QBEGenerator var value = EmitUnwrap(EmitExpression(source)); - switch (type) + switch (source.Type) { case NubComplexType complexType: { - var destination = VarName(); + var destination = TmpName(); var size = complexType switch { - NubArrayType nubArrayType => EmitArraySizeInBytes(nubArrayType, value), + NubArrayType arrayType => EmitArraySizeInBytes(arrayType, value), NubCStringType => EmitCStringSizeInBytes(value), NubStringType => EmitStringSizeInBytes(value), - NubStructType nubStructType => SizeOf(nubStructType).ToString(), + NubCustomType customType => SizeOf(customType).ToString(), _ => throw new ArgumentOutOfRangeException(nameof(complexType)) }; @@ -345,7 +365,7 @@ public static class QBEGenerator } default: { - throw new ArgumentOutOfRangeException(nameof(type)); + throw new ArgumentOutOfRangeException(nameof(source.Type)); } } } @@ -354,18 +374,23 @@ public static class QBEGenerator { return type switch { - NubPrimitiveType primitiveType => primitiveType.Kind switch + NubComplexType => "=l", + NubSimpleType simpleType => simpleType switch { - PrimitiveTypeKind.I64 or PrimitiveTypeKind.U64 => "=l", - PrimitiveTypeKind.I32 or PrimitiveTypeKind.U32 => "=w", - PrimitiveTypeKind.I16 or PrimitiveTypeKind.U16 => "=w", - PrimitiveTypeKind.I8 or PrimitiveTypeKind.U8 or PrimitiveTypeKind.Bool => "=w", - PrimitiveTypeKind.F64 => "=d", - PrimitiveTypeKind.F32 => "=s", - _ => throw new ArgumentOutOfRangeException() + NubFuncType 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 => "=w", + 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 NotSupportedException($"'{type}' type cannot be used in variables") + _ => throw new UnreachableException() }; } @@ -384,10 +409,21 @@ public static class QBEGenerator _ => throw new ArgumentOutOfRangeException() }; } - case NubStructType nubStructType: + case NubCustomType customType: { - var definition = _definitionTable.LookupStruct(nubStructType.Namespace, nubStructType.Name).GetValue(); - return definition.Fields.Max(f => AlignmentOf(f.Type)); + var structDef = _definitionTable.LookupStruct(customType.Namespace, customType.Name); + 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 NubArrayType: @@ -420,25 +456,35 @@ public static class QBEGenerator _ => throw new ArgumentOutOfRangeException() }; } - case NubStructType nubStructType: + case NubCustomType customType: { - var definition = _definitionTable.LookupStruct(nubStructType.Namespace, nubStructType.Name).GetValue(); - - var size = 0; - var maxAlignment = 1; - - foreach (var field in definition.Fields) + var structDef = _definitionTable.LookupStruct(customType.Namespace, customType.Name); + if (structDef.HasValue) { - var fieldAlignment = AlignmentOf(field.Type); - maxAlignment = Math.Max(maxAlignment, fieldAlignment); + var size = 0; + var maxAlignment = 1; - size = AlignTo(size, fieldAlignment); - size += SizeOf(field.Type); + foreach (var field in structDef.Value.Fields) + { + 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 NubArrayType: @@ -471,12 +517,39 @@ public static class QBEGenerator 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 parameters, NubType returnType, BoundBlockNode body, bool exported) { _variables.Clear(); _variableScopes.Clear(); - _variableIndex = 0; _labelIndex = 0; + _tmpIndex = 0; var builder = new StringBuilder(); @@ -488,52 +561,12 @@ public static class QBEGenerator builder.Append("function "); if (returnType is not NubVoidType) { - builder.Append(returnType 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($"'{returnType}' type cannot be used as a function return type") - }); - builder.Append(' '); + builder.Append(FuncQBETypeName(returnType) + ' '); } builder.Append(name); - var parameterStrings = parameters.Select(parameter => - { - 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}"; - }); + var parameterStrings = parameters.Select(x => FuncQBETypeName(x.Type) + $" %{x.Name}"); builder.Append($"({string.Join(", ", parameterStrings)})"); @@ -557,30 +590,14 @@ public static class QBEGenerator 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(); foreach (var field in structDef.Fields) { - var qbeType = field.Type switch - { - 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); + types.Add(field.Name, StructDefQBEType(field)); } var longest = types.Values.Max(x => x.Length); @@ -591,13 +608,39 @@ public static class QBEGenerator } _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}"); } @@ -723,15 +766,16 @@ public static class QBEGenerator private static void EmitVariableDeclaration(BoundVariableDeclarationNode variableDeclaration) { - var variable = VarName(); - _writer.Indented($"{variable} =l alloc8 {SizeOf(variableDeclaration.Type)}"); + var name = $"%{variableDeclaration.Name}"; + _writer.Indented($"{name} =l alloc8 8"); 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) @@ -790,7 +834,7 @@ public static class QBEGenerator 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 add {pointer}, 8"); _writer.Indented($"{pointer} =l add {array}, {pointer}"); @@ -799,16 +843,16 @@ public static class QBEGenerator private static void EmitArrayBoundsCheck(string array, string index) { - var count = VarName(); + var count = TmpName(); _writer.Indented($"{count} =l loadl {array}"); - var isNegative = VarName(); + var isNegative = TmpName(); _writer.Indented($"{isNegative} =w csltl {index}, 0"); - var isOob = VarName(); + var isOob = TmpName(); _writer.Indented($"{isOob} =w csgel {index}, {count}"); - var anyOob = VarName(); + var anyOob = TmpName(); _writer.Indented($"{anyOob} =w or {isNegative}, {isOob}"); var oobLabel = LabelName(); @@ -826,16 +870,16 @@ public static class QBEGenerator var capacity = EmitUnwrap(EmitExpression(arrayInitializer.Capacity)); var elementSize = SizeOf(arrayInitializer.ElementType); - var capacityInBytes = VarName(); + var capacityInBytes = TmpName(); _writer.Indented($"{capacityInBytes} =l mul {capacity}, {elementSize}"); - var totalSize = VarName(); + var totalSize = TmpName(); _writer.Indented($"{totalSize} =l add {capacityInBytes}, 8"); - var arrayPointer = VarName(); + var arrayPointer = TmpName(); _writer.Indented($"{arrayPointer} =l alloc8 {totalSize}"); _writer.Indented($"storel {capacity}, {arrayPointer}"); - var dataPointer = VarName(); + var dataPointer = TmpName(); _writer.Indented($"{dataPointer} =l add {arrayPointer}, 8"); _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) { - var pointerType = (NubPointerType)dereference.Expression.Type; - - 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)); + return EmitLoad(dereference.Type, EmitUnwrap(EmitExpression(dereference.Expression))); } private static Val EmitAddressOf(BoundAddressOfNode addressOf) @@ -869,7 +903,7 @@ public static class QBEGenerator var left = EmitUnwrap(EmitExpression(binaryExpression.Left)); var right = EmitUnwrap(EmitExpression(binaryExpression.Right)); - var outputName = VarName(); + var outputName = TmpName(); 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) { - 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) { - destination = VarName(); - var size = SizeOf(structInitializer.StructType); + destination = TmpName(); + var size = SizeOf(structType); _writer.Indented($"{destination} =l alloc8 {size}"); } @@ -1098,18 +1137,18 @@ public static class QBEGenerator Debug.Assert(valueExpression != null); - var offset = VarName(); + var offset = TmpName(); _writer.Indented($"{offset} =l add {destination}, {OffsetOf(structDefinition, field.Name)}"); EmitCopyIntoOrInitialize(valueExpression, offset); } - return new Val(destination, structInitializer.StructType, ValKind.Direct); + return new Val(destination, structType, ValKind.Direct); } private static Val EmitUnaryExpression(BoundUnaryExpressionNode unaryExpression) { var operand = EmitUnwrap(EmitExpression(unaryExpression.Operand)); - var outputName = VarName(); + var outputName = TmpName(); switch (unaryExpression.Operator) { @@ -1156,47 +1195,63 @@ public static class QBEGenerator private static Val EmitMemberAccess(BoundMemberAccessNode memberAccess) { 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}"); return new Val(output, memberAccess.Type, ValKind.Direct); } - - break; - } - case NubStringType: - { - if (memberAccess.Member == "count") + case NubStringType: { _writer.Indented($"{output} =l call $nub_string_length(l {item})"); return new Val(output, memberAccess.Type, ValKind.Direct); } - - break; - } - case NubCStringType: - { - if (memberAccess.Member == "count") + case NubCStringType: { _writer.Indented($"{output} =l call $nub_cstring_length(l {item})"); 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) { - var funcType = (NubFuncType)funcCall.Expression.Type; + var expression = EmitExpression(funcCall.Expression); + var funcPointer = EmitUnwrap(expression); var parameterStrings = new List(); + if (expression.FuncCallContext != null) + { + parameterStrings.Add($"{FuncQBETypeName(expression.FuncCallContext.ThisArgType)} {expression.FuncCallContext.ThisArgName}"); + } + foreach (var parameter in funcCall.Parameters) { - var qbeType = parameter.Type switch - { - 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 copy = EmitCreateCopyOrInitialize(parameter); + parameterStrings.Add($"{FuncQBETypeName(parameter.Type)} {copy}"); } - var funcPointer = EmitUnwrap(EmitExpression(funcCall.Expression)); - - 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 + if (funcCall.Type.IsVoid) { _writer.Indented($"call {funcPointer}({string.Join(", ", parameterStrings)})"); 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) { - if (val.Type.IsVoid) + return val.Kind switch { - throw new InvalidOperationException("Cannot unwrap temporary of void type"); - } - - 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(); - } - } + ValKind.Direct => val.Name, + ValKind.Pointer => EmitLoad(val.Type, val.Name).Name, + _ => throw new ArgumentOutOfRangeException() + }; } } @@ -1298,17 +1318,9 @@ internal class Variable(string name, Val val) public Val Val { get; } = val; } -internal class Val(string name, NubType type, ValKind kind) -{ - public string Name { get; } = name; - public NubType Type { get; } = type; - public ValKind Kind { get; } = kind; +internal record Val(string Name, NubType Type, ValKind Kind, MethodCallContext? FuncCallContext = null); - public override string ToString() - { - throw new InvalidOperationException(); - } -} +internal record MethodCallContext(string ThisArgName, NubType ThisArgType); internal enum ValKind { diff --git a/src/compiler/Generation/QBE/QBEWriter.cs b/src/compiler/Generation/QBE/QBEWriter.cs index c8e1447..8a0a4c6 100644 --- a/src/compiler/Generation/QBE/QBEWriter.cs +++ b/src/compiler/Generation/QBE/QBEWriter.cs @@ -44,7 +44,7 @@ internal class QBEWriter var firstToken = node.Tokens.FirstOrDefault(); if (firstToken != null) { - WriteDebugLocation(firstToken.Span); + // WriteDebugLocation(firstToken.Span); } } diff --git a/src/compiler/Syntax/DefinitionTable.cs b/src/compiler/Syntax/DefinitionTable.cs index 9392f91..313ecfe 100644 --- a/src/compiler/Syntax/DefinitionTable.cs +++ b/src/compiler/Syntax/DefinitionTable.cs @@ -37,6 +37,43 @@ public class DefinitionTable return Optional.OfNullable(definition); } + public Optional LookupTrait(string @namespace, string name) + { + var definition = _syntaxTrees + .Where(c => c.Namespace == @namespace) + .SelectMany(c => c.Definitions) + .OfType() + .SingleOrDefault(f => f.Name == name); + + return Optional.OfNullable(definition); + } + + public Optional> LookupTraitImplementationForType(NubType type, string funcName) + { + var implementations = _syntaxTrees + .SelectMany(c => c.Definitions) + .OfType() + .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(implementation, implementation.Functions.First(x => x.Name == funcName)); + + return Optional.OfNullable(value); + } + + public Optional 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.Empty(); + } + public IEnumerable GetStructs() { return _syntaxTrees @@ -65,18 +102,18 @@ public class DefinitionTable .OfType(); } - public IEnumerable GetInterfaces() + public IEnumerable GetTraits() { return _syntaxTrees .SelectMany(c => c.Definitions) - .OfType(); + .OfType(); } - public IEnumerable GetImplementations() + public IEnumerable GetTraitImplementations() { return _syntaxTrees .SelectMany(c => c.Definitions) - .OfType(); + .OfType(); } } @@ -111,6 +148,43 @@ public class BoundDefinitionTable return Optional.OfNullable(definition); } + public Optional LookupTrait(string @namespace, string name) + { + var definition = _syntaxTrees + .Where(c => c.Namespace == @namespace) + .SelectMany(c => c.Definitions) + .OfType() + .SingleOrDefault(f => f.Name == name); + + return Optional.OfNullable(definition); + } + + public Optional> LookupTraitImplementationForType(NubType type, string funcName) + { + var implementations = _syntaxTrees + .SelectMany(c => c.Definitions) + .OfType() + .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(implementation, implementation.Functions.First(x => x.Name == funcName)); + + return Optional.OfNullable(value); + } + + public Optional 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.Empty(); + } + public IEnumerable GetStructs() { return _syntaxTrees @@ -139,17 +213,17 @@ public class BoundDefinitionTable .OfType(); } - public IEnumerable GetInterfaces() + public IEnumerable GetTraits() { return _syntaxTrees .SelectMany(c => c.Definitions) - .OfType(); + .OfType(); } - public IEnumerable GetImplementations() + public IEnumerable GetTraitImplementations() { return _syntaxTrees .SelectMany(c => c.Definitions) - .OfType(); + .OfType(); } } \ No newline at end of file diff --git a/src/compiler/Syntax/Parsing/Node/Definition.cs b/src/compiler/Syntax/Parsing/Node/Definition.cs index 968a9f1..8455a38 100644 --- a/src/compiler/Syntax/Parsing/Node/Definition.cs +++ b/src/compiler/Syntax/Parsing/Node/Definition.cs @@ -1,6 +1,7 @@ using Common; using Syntax.Tokenization; using Syntax.Typing; +using Syntax.Typing.BoundNode; namespace Syntax.Parsing.Node; @@ -14,8 +15,8 @@ public record ExternFuncDefinitionNode(IEnumerable Tokens, Optional Value); public record StructDefinitionNode(IEnumerable Tokens, Optional Documentation, string Namespace, string Name, List Fields) : DefinitionNode(Tokens, Documentation, Namespace); -public record InterfaceFunc(string Name, List Parameters, NubType ReturnType); -public record InterfaceDefinitionNode(IEnumerable Tokens, Optional Documentation, string Namespace, string Name, List Functions) : DefinitionNode(Tokens, Documentation, Namespace); +public record TraitFunc(string Name, List Parameters, NubType ReturnType); +public record TraitDefinitionNode(IEnumerable Tokens, Optional Documentation, string Namespace, string Name, List Functions) : DefinitionNode(Tokens, Documentation, Namespace); -public record ImplementationFunc(string Name, List Parameters, NubType ReturnType, BlockNode Body); -public record ImplementationDefinitionNode(IEnumerable Tokens, Optional Documentation, string Namespace, NubType Type, NubType Interface, List Functions) : DefinitionNode(Tokens, Documentation, Namespace); \ No newline at end of file +public record ImplementationFuncNode(IEnumerable Tokens, string Name, List Parameters, NubType ReturnType, BlockNode Body) : BoundNode(Tokens); +public record TraitImplementationDefinitionNode(IEnumerable Tokens, Optional Documentation, string Namespace, NubType TraitType, NubType ForType, List Functions) : DefinitionNode(Tokens, Documentation, Namespace); \ No newline at end of file diff --git a/src/compiler/Syntax/Parsing/Node/Expression.cs b/src/compiler/Syntax/Parsing/Node/Expression.cs index 0f61aea..b56f835 100644 --- a/src/compiler/Syntax/Parsing/Node/Expression.cs +++ b/src/compiler/Syntax/Parsing/Node/Expression.cs @@ -38,5 +38,5 @@ public record AnonymousFuncNode(IEnumerable Tokens, List P public record AddressOfNode(IEnumerable Tokens, ExpressionNode Expression) : ExpressionNode(Tokens); public record LiteralNode(IEnumerable Tokens, string Literal, LiteralKind Kind) : ExpressionNode(Tokens); public record MemberAccessNode(IEnumerable Tokens, ExpressionNode Expression, string Member) : ExpressionNode(Tokens); -public record StructInitializerNode(IEnumerable Tokens, NubStructType StructType, Dictionary Initializers) : ExpressionNode(Tokens); +public record StructInitializerNode(IEnumerable Tokens, NubType StructType, Dictionary Initializers) : ExpressionNode(Tokens); public record DereferenceNode(IEnumerable Tokens, ExpressionNode Expression) : ExpressionNode(Tokens); diff --git a/src/compiler/Syntax/Parsing/Parser.cs b/src/compiler/Syntax/Parsing/Parser.cs index 9d60451..93f433c 100644 --- a/src/compiler/Syntax/Parsing/Parser.cs +++ b/src/compiler/Syntax/Parsing/Parser.cs @@ -17,21 +17,13 @@ public static class Parser public static SyntaxTree? ParseFile(IEnumerable tokens, out IEnumerable diagnostics) { _tokens = tokens; - _namespace = null!; + _namespace = "global"; _diagnostics = []; _index = 0; - try + if (TryExpectSymbol(Symbol.Namespace)) { - ExpectSymbol(Symbol.Namespace); - var @namespace = ExpectIdentifier(); - _namespace = @namespace.Value; - } - catch (ParseException ex) - { - _diagnostics.Add(ex.Diagnostic); - diagnostics = _diagnostics; - return null; + _namespace = ExpectIdentifier().Value; } try @@ -81,7 +73,7 @@ public static class Parser { Symbol.Func => ParseFuncDefinition(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)), _ => throw new ParseException(Diagnostic .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); } - private static InterfaceDefinitionNode ParseInterface(int startIndex, List modifiers, Optional documentation) + private static TraitDefinitionNode ParseTrait(int startIndex, List modifiers, Optional documentation) { var name = ExpectIdentifier().Value; ExpectSymbol(Symbol.OpenBrace); - List functions = []; + List functions = []; while (!TryExpectSymbol(Symbol.CloseBrace)) { @@ -222,34 +214,35 @@ public static class Parser if (modifiers.Count != 0) { throw new ParseException(Diagnostic - .Error($"Invalid modifiers for interface: {modifiers[0].Modifier}") - .WithHelp($"Interface cannot use the '{modifiers[0].Modifier}' modifier") + .Error($"Invalid modifiers for trait: {modifiers[0].Modifier}") + .WithHelp($"Traits cannot use the '{modifiers[0].Modifier}' modifier") .At(modifiers[0]) .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 modifiers, Optional documentation) + private static TraitImplementationDefinitionNode ParseImplementation(int startIndex, List modifiers, Optional documentation) { - var type = ParseType(); - ExpectSymbol(Symbol.Colon); - var @interface = ParseType(); + var traitType = ParseType(); + ExpectSymbol(Symbol.For); + var forType = ParseType(); - List functions = []; + List functions = []; ExpectSymbol(Symbol.OpenBrace); while (!TryExpectSymbol(Symbol.CloseBrace)) { + var funcStartIndex = _index; ExpectSymbol(Symbol.Func); var functionName = ExpectIdentifier().Value; var parameters = new List { - new("this", type) + new("this", forType) }; ExpectSymbol(Symbol.OpenParen); @@ -272,10 +265,19 @@ public static class Parser 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() @@ -580,15 +582,7 @@ public static class Parser initializers.Add(name, value); } - if (type is not NubStructType structType) - { - throw new ParseException(Diagnostic - .Error($"Cannot alloc type '{type}'") - .At(symbolToken) - .Build()); - } - - expr = new StructInitializerNode(GetTokensForNode(startIndex), structType, initializers); + expr = new StructInitializerNode(GetTokensForNode(startIndex), type, initializers); break; } default: @@ -729,16 +723,7 @@ public static class Parser @namespace = ExpectIdentifier().Value; } - if (@namespace == null) - { - 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); + return new NubCustomType(@namespace, name.Value); } if (TryExpectSymbol(Symbol.Caret)) diff --git a/src/compiler/Syntax/Tokenization/SymbolToken.cs b/src/compiler/Syntax/Tokenization/SymbolToken.cs index 4bc01ac..b1cf578 100644 --- a/src/compiler/Syntax/Tokenization/SymbolToken.cs +++ b/src/compiler/Syntax/Tokenization/SymbolToken.cs @@ -44,6 +44,7 @@ public enum Symbol Let, Alloc, Calls, - Interface, - Impl + Trait, + Impl, + For } \ No newline at end of file diff --git a/src/compiler/Syntax/Tokenization/Tokenizer.cs b/src/compiler/Syntax/Tokenization/Tokenizer.cs index c8d644d..68b3725 100644 --- a/src/compiler/Syntax/Tokenization/Tokenizer.cs +++ b/src/compiler/Syntax/Tokenization/Tokenizer.cs @@ -19,8 +19,9 @@ public static class Tokenizer ["struct"] = Symbol.Struct, ["let"] = Symbol.Let, ["calls"] = Symbol.Calls, - ["interface"] = Symbol.Interface, + ["trait"] = Symbol.Trait, ["impl"] = Symbol.Impl, + ["for"] = Symbol.For, }; private static readonly Dictionary Modifiers = new() diff --git a/src/compiler/Syntax/Typing/Binder.cs b/src/compiler/Syntax/Typing/Binder.cs index 153e1bd..565cbc3 100644 --- a/src/compiler/Syntax/Typing/Binder.cs +++ b/src/compiler/Syntax/Typing/Binder.cs @@ -41,18 +41,18 @@ public static class Binder return node switch { ExternFuncDefinitionNode definition => BindExternFuncDefinition(definition), - ImplementationDefinitionNode definition => BindImplementation(definition), - InterfaceDefinitionNode definition => BindInterfaceDefinition(definition), + TraitImplementationDefinitionNode definition => BindTraitImplementation(definition), + TraitDefinitionNode definition => BindTraitDefinition(definition), LocalFuncDefinitionNode definition => BindLocalFuncDefinition(definition), StructDefinitionNode definition => BindStruct(definition), _ => throw new ArgumentOutOfRangeException(nameof(node)) }; } - private static BoundImplementationDefinitionNode BindImplementation(ImplementationDefinitionNode node) + private static BoundTraitImplementationDefinitionNode BindTraitImplementation(TraitImplementationDefinitionNode node) { _variables.Clear(); - var functions = new List(); + var functions = new List(); foreach (var function in node.Functions) { @@ -63,15 +63,15 @@ public static class Binder _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(); + var functions = new List(); foreach (var func in node.Functions) { @@ -82,10 +82,10 @@ public static class Binder 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) @@ -393,51 +393,55 @@ public static class Binder { var boundExpression = BindExpression(expression.Expression); - NubType? type = null; - - switch (boundExpression.Type) + var implementation = _definitionTable.LookupTraitImplementationForType(boundExpression.Type, expression.Member); + if (implementation.HasValue) { - case NubArrayType: - case NubStringType: - case NubCStringType: - { - if (expression.Member == "count") - { - type = NubPrimitiveType.U64; - } + var type = new NubFuncType(implementation.Value.Item2.ReturnType, implementation.Value.Item2.Parameters.Select(p => p.Type).ToList()); + return new BoundMemberAccessNode(expression.Tokens, type, boundExpression, expression.Member); + } - break; - } - case NubStructType structType: + if (boundExpression.Type is NubCustomType customType) + { + var function = _definitionTable.LookupFunctionOnTrait(customType.Namespace, customType.Name, expression.Member); + if (function.HasValue) { - var defOpt = _definitionTable.LookupStruct(structType.Namespace, structType.Name); - if (!defOpt.TryGetValue(out var definition)) + var type = new NubFuncType(function.Value.ReturnType, function.Value.Parameters.Select(p => p.Type).ToList()); + 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"); } - var field = definition.Fields.FirstOrDefault(f => f.Name == expression.Member); - if (field == null) + if (matchingFields.Count == 1) { - 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) { - 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)) { throw new NotImplementedException("Diagnostics not implemented"); @@ -456,7 +460,7 @@ public static class Binder 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) diff --git a/src/compiler/Syntax/Typing/BoundNode/Definition.cs b/src/compiler/Syntax/Typing/BoundNode/Definition.cs index 638ec4f..c37131f 100644 --- a/src/compiler/Syntax/Typing/BoundNode/Definition.cs +++ b/src/compiler/Syntax/Typing/BoundNode/Definition.cs @@ -13,8 +13,8 @@ public record BoundExternFuncDefinitionNode(IEnumerable Tokens, Optional< public record BoundStructField(string Name, NubType Type, Optional Value); public record BoundStructDefinitionNode(IEnumerable Tokens, Optional Documentation, string Namespace, string Name, List Fields) : BoundDefinitionNode(Tokens, Documentation, Namespace); -public record BoundInterfaceFunc(string Name, List Parameters, NubType ReturnType); -public record BoundInterfaceDefinitionNode(IEnumerable Tokens, Optional Documentation, string Namespace, string Name, List Functions) : BoundDefinitionNode(Tokens, Documentation, Namespace); +public record BountTraitFunc(string Name, List Parameters, NubType ReturnType); +public record BoundTraitDefinitionNode(IEnumerable Tokens, Optional Documentation, string Namespace, string Name, List Functions) : BoundDefinitionNode(Tokens, Documentation, Namespace); -public record BoundImplementationFunc(string Name, List Parameters, NubType ReturnType, BoundBlockNode Body); -public record BoundImplementationDefinitionNode(IEnumerable Tokens, Optional Documentation, string Namespace, NubType Type, NubType Interface, List Functions) : BoundDefinitionNode(Tokens, Documentation, Namespace); \ No newline at end of file +public record BoundImplementationFuncNode(IEnumerable Tokens, string Name, List Parameters, NubType ReturnType, BoundBlockNode Body) : BoundNode(Tokens); +public record BoundTraitImplementationDefinitionNode(IEnumerable Tokens, Optional Documentation, string Namespace, NubType TraitType, NubType ForType, List Functions) : BoundDefinitionNode(Tokens, Documentation, Namespace); \ No newline at end of file diff --git a/src/compiler/Syntax/Typing/BoundNode/Expression.cs b/src/compiler/Syntax/Typing/BoundNode/Expression.cs index 61891fa..2dc8efe 100644 --- a/src/compiler/Syntax/Typing/BoundNode/Expression.cs +++ b/src/compiler/Syntax/Typing/BoundNode/Expression.cs @@ -15,5 +15,5 @@ public record BoundAnonymousFuncNode(IEnumerable Tokens, NubType Type, Li public record BoundAddressOfNode(IEnumerable Tokens, NubType Type, BoundExpressionNode Expression) : BoundExpressionNode(Tokens, Type); public record BoundLiteralNode(IEnumerable Tokens, NubType Type, string Literal, LiteralKind Kind) : BoundExpressionNode(Tokens, Type); public record BoundMemberAccessNode(IEnumerable Tokens, NubType Type, BoundExpressionNode Expression, string Member) : BoundExpressionNode(Tokens, Type); -public record BoundStructInitializerNode(IEnumerable Tokens, NubType Type, NubStructType StructType, Dictionary Initializers) : BoundExpressionNode(Tokens, Type); +public record BoundStructInitializerNode(IEnumerable Tokens, NubType Type, NubType StructType, Dictionary Initializers) : BoundExpressionNode(Tokens, Type); public record BoundDereferenceNode(IEnumerable Tokens, NubType Type, BoundExpressionNode Expression) : BoundExpressionNode(Tokens, Type); diff --git a/src/compiler/Syntax/Typing/NubType.cs b/src/compiler/Syntax/Typing/NubType.cs index fd92f65..108ed8b 100644 --- a/src/compiler/Syntax/Typing/NubType.cs +++ b/src/compiler/Syntax/Typing/NubType.cs @@ -89,14 +89,14 @@ public class NubFuncType(NubType returnType, List 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 Name { get; } = name; 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()