This commit is contained in:
nub31
2025-07-04 21:43:26 +02:00
parent 2ad6529350
commit 0e0f29c6dd
13 changed files with 453 additions and 377 deletions

View File

@@ -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
}

View File

@@ -21,13 +21,15 @@ public static class QBEGenerator
private static Stack<string> _breakLabels = [];
private static Stack<string> _continueLabels = [];
private static Queue<(BoundAnonymousFuncNode Func, string Name)> _anonymousFunctions = [];
private static Dictionary<BoundImplementationFuncNode, string> _implFunctions = [];
private static Stack<Variable> _variables = [];
private static Stack<int> _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<BoundFuncParameter> 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<string, string>();
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<string>();
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
{

View File

@@ -44,7 +44,7 @@ internal class QBEWriter
var firstToken = node.Tokens.FirstOrDefault();
if (firstToken != null)
{
WriteDebugLocation(firstToken.Span);
// WriteDebugLocation(firstToken.Span);
}
}

View File

@@ -37,6 +37,43 @@ public class DefinitionTable
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()
{
return _syntaxTrees
@@ -65,18 +102,18 @@ public class DefinitionTable
.OfType<ExternFuncDefinitionNode>();
}
public IEnumerable<InterfaceDefinitionNode> GetInterfaces()
public IEnumerable<TraitDefinitionNode> GetTraits()
{
return _syntaxTrees
.SelectMany(c => c.Definitions)
.OfType<InterfaceDefinitionNode>();
.OfType<TraitDefinitionNode>();
}
public IEnumerable<ImplementationDefinitionNode> GetImplementations()
public IEnumerable<TraitImplementationDefinitionNode> GetTraitImplementations()
{
return _syntaxTrees
.SelectMany(c => c.Definitions)
.OfType<ImplementationDefinitionNode>();
.OfType<TraitImplementationDefinitionNode>();
}
}
@@ -111,6 +148,43 @@ public class BoundDefinitionTable
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()
{
return _syntaxTrees
@@ -139,17 +213,17 @@ public class BoundDefinitionTable
.OfType<BoundExternFuncDefinitionNode>();
}
public IEnumerable<BoundInterfaceDefinitionNode> GetInterfaces()
public IEnumerable<BoundTraitDefinitionNode> GetTraits()
{
return _syntaxTrees
.SelectMany(c => c.Definitions)
.OfType<BoundInterfaceDefinitionNode>();
.OfType<BoundTraitDefinitionNode>();
}
public IEnumerable<BoundImplementationDefinitionNode> GetImplementations()
public IEnumerable<BoundTraitImplementationDefinitionNode> GetTraitImplementations()
{
return _syntaxTrees
.SelectMany(c => c.Definitions)
.OfType<BoundImplementationDefinitionNode>();
.OfType<BoundTraitImplementationDefinitionNode>();
}
}

View File

@@ -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<Token> Tokens, Optional<strin
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 InterfaceFunc(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 TraitFunc(string Name, List<FuncParameter> Parameters, NubType ReturnType);
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 ImplementationDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, NubType Type, NubType Interface, List<ImplementationFunc> Functions) : DefinitionNode(Tokens, Documentation, Namespace);
public record ImplementationFuncNode(IEnumerable<Token> Tokens, string Name, List<FuncParameter> Parameters, NubType ReturnType, BlockNode Body) : BoundNode(Tokens);
public record TraitImplementationDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, NubType TraitType, NubType ForType, List<ImplementationFuncNode> Functions) : DefinitionNode(Tokens, Documentation, Namespace);

View File

@@ -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 LiteralNode(IEnumerable<Token> Tokens, string Literal, LiteralKind Kind) : 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);

View File

@@ -17,21 +17,13 @@ public static class Parser
public static SyntaxTree? ParseFile(IEnumerable<Token> tokens, out IEnumerable<Diagnostic> 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<ModifierToken> modifiers, Optional<string> documentation)
private static TraitDefinitionNode ParseTrait(int startIndex, List<ModifierToken> modifiers, Optional<string> documentation)
{
var name = ExpectIdentifier().Value;
ExpectSymbol(Symbol.OpenBrace);
List<InterfaceFunc> functions = [];
List<TraitFunc> 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<ModifierToken> modifiers, Optional<string> documentation)
private static TraitImplementationDefinitionNode ParseImplementation(int startIndex, List<ModifierToken> modifiers, Optional<string> documentation)
{
var type = ParseType();
ExpectSymbol(Symbol.Colon);
var @interface = ParseType();
var traitType = ParseType();
ExpectSymbol(Symbol.For);
var forType = ParseType();
List<ImplementationFunc> functions = [];
List<ImplementationFuncNode> functions = [];
ExpectSymbol(Symbol.OpenBrace);
while (!TryExpectSymbol(Symbol.CloseBrace))
{
var funcStartIndex = _index;
ExpectSymbol(Symbol.Func);
var functionName = ExpectIdentifier().Value;
var parameters = new List<FuncParameter>
{
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))

View File

@@ -44,6 +44,7 @@ public enum Symbol
Let,
Alloc,
Calls,
Interface,
Impl
Trait,
Impl,
For
}

View File

@@ -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<string, Modifier> Modifiers = new()

View File

@@ -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<BoundImplementationFunc>();
var functions = new List<BoundImplementationFuncNode>();
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<BoundInterfaceFunc>();
var functions = new List<BountTraitFunc>();
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)

View File

@@ -13,8 +13,8 @@ public record BoundExternFuncDefinitionNode(IEnumerable<Token> Tokens, Optional<
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 BoundInterfaceFunc(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 BountTraitFunc(string Name, List<BoundFuncParameter> Parameters, NubType ReturnType);
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 BoundImplementationDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, NubType Type, NubType Interface, List<BoundImplementationFunc> Functions) : BoundDefinitionNode(Tokens, Documentation, Namespace);
public record BoundImplementationFuncNode(IEnumerable<Token> Tokens, string Name, List<BoundFuncParameter> Parameters, NubType ReturnType, BoundBlockNode Body) : BoundNode(Tokens);
public record BoundTraitImplementationDefinitionNode(IEnumerable<Token> Tokens, Optional<string> Documentation, string Namespace, NubType TraitType, NubType ForType, List<BoundImplementationFuncNode> Functions) : BoundDefinitionNode(Tokens, Documentation, Namespace);

View File

@@ -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 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 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);

View File

@@ -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 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()