Traits
This commit is contained in:
@@ -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
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user