From 5e23da61f0f778681ae661f9578e7f85086de8e9 Mon Sep 17 00:00:00 2001 From: nub31 Date: Thu, 24 Jul 2025 18:46:32 +0200 Subject: [PATCH] Node postfix for nodes --- .../Generation/QBE/QBEGenerator.Expression.cs | 103 +++++---- .../Generation/QBE/QBEGenerator.Statement.cs | 28 +-- .../NubLang/Generation/QBE/QBEGenerator.cs | 82 +++---- .../Generation/TypedDefinitionTable.cs | 22 +- .../NubLang/TypeChecking/DefinitionTable.cs | 4 +- .../NubLang/TypeChecking/Node/Definition.cs | 23 -- .../TypeChecking/Node/DefinitionNode.cs | 19 ++ .../NubLang/TypeChecking/Node/Expression.cs | 55 ----- .../TypeChecking/Node/ExpressionNode.cs | 55 +++++ .../NubLang/TypeChecking/Node/Node.cs | 7 + .../NubLang/TypeChecking/Node/Statement.cs | 19 -- .../TypeChecking/Node/StatementNode.cs | 19 ++ .../NubLang/TypeChecking/Node/SyntaxTree.cs | 7 - .../Node/{NubType.cs => TypeNode.cs} | 88 +++---- .../NubLang/TypeChecking/TypeChecker.cs | 216 +++++++++--------- 15 files changed, 371 insertions(+), 376 deletions(-) delete mode 100644 src/compiler/NubLang/TypeChecking/Node/Definition.cs create mode 100644 src/compiler/NubLang/TypeChecking/Node/DefinitionNode.cs delete mode 100644 src/compiler/NubLang/TypeChecking/Node/Expression.cs create mode 100644 src/compiler/NubLang/TypeChecking/Node/ExpressionNode.cs create mode 100644 src/compiler/NubLang/TypeChecking/Node/Node.cs delete mode 100644 src/compiler/NubLang/TypeChecking/Node/Statement.cs create mode 100644 src/compiler/NubLang/TypeChecking/Node/StatementNode.cs delete mode 100644 src/compiler/NubLang/TypeChecking/Node/SyntaxTree.cs rename src/compiler/NubLang/TypeChecking/Node/{NubType.cs => TypeNode.cs} (70%) diff --git a/src/compiler/NubLang/Generation/QBE/QBEGenerator.Expression.cs b/src/compiler/NubLang/Generation/QBE/QBEGenerator.Expression.cs index 115c029..dacdcad 100644 --- a/src/compiler/NubLang/Generation/QBE/QBEGenerator.Expression.cs +++ b/src/compiler/NubLang/Generation/QBE/QBEGenerator.Expression.cs @@ -1,51 +1,50 @@ using System.Diagnostics; using System.Globalization; using NubLang.Tokenization; -using NubLang.TypeChecking; using NubLang.TypeChecking.Node; namespace NubLang.Generation.QBE; public partial class QBEGenerator { - private Val EmitExpression(Expression expression) + private Val EmitExpression(ExpressionNode expression) { return expression switch { - ArrayInitializer arrayInitializer => EmitArrayInitializer(arrayInitializer), - StructInitializer structInitializer => EmitStructInitializer(structInitializer), - AddressOf addressOf => EmitAddressOf(addressOf), - Dereference dereference => EmitDereference(dereference), - ArrowFunc arrowFunc => EmitArrowFunc(arrowFunc), - BinaryExpression binaryExpression => EmitBinaryExpression(binaryExpression), - FuncCall funcCallExpression => EmitFuncCall(funcCallExpression), - ExternFuncIdent externFuncIdent => EmitExternFuncIdent(externFuncIdent), - LocalFuncIdent localFuncIdent => EmitLocalFuncIdent(localFuncIdent), - VariableIdent variableIdent => EmitVariableIdent(variableIdent), - Literal literal => EmitLiteral(literal), - UnaryExpression unaryExpression => EmitUnaryExpression(unaryExpression), - StructFieldAccess structFieldAccess => EmitStructFieldAccess(structFieldAccess), - InterfaceFuncAccess traitFuncAccess => EmitTraitFuncAccess(traitFuncAccess), - ArrayIndexAccess arrayIndex => EmitArrayIndexAccess(arrayIndex), + ArrayInitializerNode arrayInitializer => EmitArrayInitializer(arrayInitializer), + StructInitializerNode structInitializer => EmitStructInitializer(structInitializer), + AddressOfNode addressOf => EmitAddressOf(addressOf), + DereferenceNode dereference => EmitDereference(dereference), + ArrowFuncNode arrowFunc => EmitArrowFunc(arrowFunc), + BinaryExpressionNode binaryExpression => EmitBinaryExpression(binaryExpression), + FuncCallNode funcCallExpression => EmitFuncCall(funcCallExpression), + ExternFuncIdentNode externFuncIdent => EmitExternFuncIdent(externFuncIdent), + LocalFuncIdentNode localFuncIdent => EmitLocalFuncIdent(localFuncIdent), + VariableIdentNode variableIdent => EmitVariableIdent(variableIdent), + LiteralNode literal => EmitLiteral(literal), + UnaryExpressionNode unaryExpression => EmitUnaryExpression(unaryExpression), + StructFieldAccessNode structFieldAccess => EmitStructFieldAccess(structFieldAccess), + InterfaceFuncAccessNode traitFuncAccess => EmitTraitFuncAccess(traitFuncAccess), + ArrayIndexAccessNode arrayIndex => EmitArrayIndexAccess(arrayIndex), _ => throw new ArgumentOutOfRangeException(nameof(expression)) }; } - private Val EmitArrowFunc(ArrowFunc arrowFunc) + private Val EmitArrowFunc(ArrowFuncNode arrowFunc) { var name = $"$arrow_func{++_arrowFuncIndex}"; _arrowFunctions.Enqueue((arrowFunc, name)); return new Val(name, arrowFunc.Type, ValKind.Direct); } - private Val EmitArrayIndexAccess(ArrayIndexAccess arrayIndexAccess) + private Val EmitArrayIndexAccess(ArrayIndexAccessNode arrayIndexAccess) { var array = EmitUnwrap(EmitExpression(arrayIndexAccess.Target)); var index = EmitUnwrap(EmitExpression(arrayIndexAccess.Index)); EmitArraysCheck(array, index); - var elementType = ((NubArrayType)arrayIndexAccess.Target.Type).ElementType; + var elementType = ((ArrayTypeNode)arrayIndexAccess.Target.Type).ElementType; var pointer = TmpName(); _writer.Indented($"{pointer} =l mul {index}, {elementType.Size(_definitionTable)}"); @@ -78,7 +77,7 @@ public partial class QBEGenerator _writer.Indented(notOobLabel); } - private Val EmitArrayInitializer(ArrayInitializer arrayInitializer) + private Val EmitArrayInitializer(ArrayInitializerNode arrayInitializer) { var capacity = EmitUnwrap(EmitExpression(arrayInitializer.Capacity)); var elementSize = arrayInitializer.ElementType.Size(_definitionTable); @@ -99,12 +98,12 @@ public partial class QBEGenerator return new Val(arrayPointer, arrayInitializer.Type, ValKind.Direct); } - private Val EmitDereference(Dereference dereference) + private Val EmitDereference(DereferenceNode dereference) { return EmitLoad(dereference.Type, EmitUnwrap(EmitExpression(dereference.Expression))); } - private Val EmitAddressOf(AddressOf addressOf) + private Val EmitAddressOf(AddressOfNode addressOf) { var value = EmitExpression(addressOf.Expression); if (value.Kind != ValKind.Pointer) @@ -115,7 +114,7 @@ public partial class QBEGenerator return new Val(value.Name, addressOf.Type, ValKind.Direct); } - private Val EmitBinaryExpression(BinaryExpression binaryExpression) + private Val EmitBinaryExpression(BinaryExpressionNode binaryExpression) { var left = EmitUnwrap(EmitExpression(binaryExpression.Left)); var right = EmitUnwrap(EmitExpression(binaryExpression.Right)); @@ -128,7 +127,7 @@ public partial class QBEGenerator return new Val(outputName, binaryExpression.Type, ValKind.Direct); } - private string EmitBinaryInstructionFor(BinaryOperator op, NubType type, string left, string right) + private string EmitBinaryInstructionFor(BinaryOperator op, TypeNode type, string left, string right) { if (op is BinaryOperator.Equal or @@ -189,11 +188,11 @@ public partial class QBEGenerator string sign; - if (simpleType is NubIntType { Signed: true }) + if (simpleType is IntTypeNode { Signed: true }) { sign = "s"; } - else if (simpleType is NubIntType { Signed: false }) + else if (simpleType is IntTypeNode { Signed: false }) { sign = "u"; } @@ -222,44 +221,44 @@ public partial class QBEGenerator }; } - private Val EmitExternFuncIdent(ExternFuncIdent externFuncIdent) + private Val EmitExternFuncIdent(ExternFuncIdentNode externFuncIdent) { var func = _definitionTable.LookupExternFunc(externFuncIdent.Name); return new Val(ExternFuncName(func), externFuncIdent.Type, ValKind.Direct); } - private Val EmitLocalFuncIdent(LocalFuncIdent localFuncIdent) + private Val EmitLocalFuncIdent(LocalFuncIdentNode localFuncIdent) { var func = _definitionTable.LookupLocalFunc(localFuncIdent.Name); return new Val(LocalFuncName(func), localFuncIdent.Type, ValKind.Direct); } - private Val EmitVariableIdent(VariableIdent variableIdent) + private Val EmitVariableIdent(VariableIdentNode variableIdent) { return Scope.Lookup(variableIdent.Name); } - private Val EmitLiteral(Literal literal) + private Val EmitLiteral(LiteralNode literal) { switch (literal.Kind) { case LiteralKind.Integer: { - if (literal.Type is NubFloatType { Width: 32 }) + if (literal.Type is FloatTypeNode { Width: 32 }) { var value = float.Parse(literal.Value, CultureInfo.InvariantCulture); var bits = BitConverter.SingleToInt32Bits(value); return new Val(bits.ToString(), literal.Type, ValKind.Direct); } - if (literal.Type is NubFloatType { Width: 64 }) + if (literal.Type is FloatTypeNode { Width: 64 }) { var value = double.Parse(literal.Value, CultureInfo.InvariantCulture); var bits = BitConverter.DoubleToInt64Bits(value); return new Val(bits.ToString(), literal.Type, ValKind.Direct); } - if (literal.Type is NubIntType) + if (literal.Type is IntTypeNode) { return new Val(literal.Value, literal.Type, ValKind.Direct); } @@ -268,19 +267,19 @@ public partial class QBEGenerator } case LiteralKind.Float: { - if (literal.Type is NubIntType) + if (literal.Type is IntTypeNode) { return new Val(literal.Value.Split(".").First(), literal.Type, ValKind.Direct); } - if (literal.Type is NubFloatType { Width: 32 }) + if (literal.Type is FloatTypeNode { Width: 32 }) { var value = float.Parse(literal.Value, CultureInfo.InvariantCulture); var bits = BitConverter.SingleToInt32Bits(value); return new Val(bits.ToString(), literal.Type, ValKind.Direct); } - if (literal.Type is NubFloatType { Width: 64 }) + if (literal.Type is FloatTypeNode { Width: 64 }) { var value = double.Parse(literal.Value, CultureInfo.InvariantCulture); var bits = BitConverter.DoubleToInt64Bits(value); @@ -291,14 +290,14 @@ public partial class QBEGenerator } case LiteralKind.String: { - if (literal.Type is NubStringType) + if (literal.Type is NubStringTypeNode) { var stringLiteral = new StringLiteral(literal.Value, StringName()); _stringLiterals.Add(stringLiteral); return new Val(stringLiteral.Name, literal.Type, ValKind.Direct); } - if (literal.Type is NubCStringType) + if (literal.Type is CStringTypeNode) { var cStringLiteral = new CStringLiteral(literal.Value, CStringName()); _cStringLiterals.Add(cStringLiteral); @@ -309,7 +308,7 @@ public partial class QBEGenerator } case LiteralKind.Bool: { - if (literal.Type is NubBoolType) + if (literal.Type is BoolTypeNode) { return new Val(bool.Parse(literal.Value) ? "1" : "0", literal.Type, ValKind.Direct); } @@ -321,7 +320,7 @@ public partial class QBEGenerator throw new NotSupportedException($"Cannot create literal of kind '{literal.Kind}' for type {literal.Type}"); } - private Val EmitStructInitializer(StructInitializer structInitializer, string? destination = null) + private Val EmitStructInitializer(StructInitializerNode structInitializer, string? destination = null) { var @struct = _definitionTable.LookupStruct(structInitializer.StructType.Name); @@ -349,7 +348,7 @@ public partial class QBEGenerator return new Val(destination, structInitializer.StructType, ValKind.Direct); } - private Val EmitUnaryExpression(UnaryExpression unaryExpression) + private Val EmitUnaryExpression(UnaryExpressionNode unaryExpression) { var operand = EmitUnwrap(EmitExpression(unaryExpression.Operand)); var outputName = TmpName(); @@ -360,16 +359,16 @@ public partial class QBEGenerator { switch (unaryExpression.Operand.Type) { - case NubIntType { Signed: true, Width: 64 }: + case IntTypeNode { Signed: true, Width: 64 }: _writer.Indented($"{outputName} =l neg {operand}"); return new Val(outputName, unaryExpression.Type, ValKind.Direct); - case NubIntType { Signed: true, Width: 8 or 16 or 32 }: + case IntTypeNode { Signed: true, Width: 8 or 16 or 32 }: _writer.Indented($"{outputName} =w neg {operand}"); return new Val(outputName, unaryExpression.Type, ValKind.Direct); - case NubFloatType { Width: 64 }: + case FloatTypeNode { Width: 64 }: _writer.Indented($"{outputName} =d neg {operand}"); return new Val(outputName, unaryExpression.Type, ValKind.Direct); - case NubFloatType { Width: 32 }: + case FloatTypeNode { Width: 32 }: _writer.Indented($"{outputName} =s neg {operand}"); return new Val(outputName, unaryExpression.Type, ValKind.Direct); } @@ -380,7 +379,7 @@ public partial class QBEGenerator { switch (unaryExpression.Operand.Type) { - case NubBoolType: + case BoolTypeNode: _writer.Indented($"{outputName} =w xor {operand}, 1"); return new Val(outputName, unaryExpression.Type, ValKind.Direct); } @@ -396,7 +395,7 @@ public partial class QBEGenerator throw new NotSupportedException($"Unary operator {unaryExpression.Operator} for type {unaryExpression.Operand.Type} not supported"); } - private Val EmitStructFieldAccess(StructFieldAccess structFieldAccess) + private Val EmitStructFieldAccess(StructFieldAccessNode structFieldAccess) { var target = EmitUnwrap(EmitExpression(structFieldAccess.Target)); @@ -407,7 +406,7 @@ public partial class QBEGenerator _writer.Indented($"{output} =l add {target}, {offset}"); // If the accessed member is an inline struct, it will not be a pointer - if (structFieldAccess.Type is NubCustomType customType && customType.Kind(_definitionTable) == CustomTypeKind.Struct) + if (structFieldAccess.Type is CustomTypeNode customType && customType.Kind(_definitionTable) == CustomTypeKind.Struct) { return new Val(output, structFieldAccess.Type, ValKind.Direct); } @@ -415,12 +414,12 @@ public partial class QBEGenerator return new Val(output, structFieldAccess.Type, ValKind.Pointer); } - private Val EmitTraitFuncAccess(InterfaceFuncAccess interfaceFuncAccess) + private Val EmitTraitFuncAccess(InterfaceFuncAccessNode interfaceFuncAccess) { throw new NotImplementedException(); } - private Val EmitFuncCall(FuncCall funcCall) + private Val EmitFuncCall(FuncCallNode funcCall) { var expression = EmitExpression(funcCall.Expression); var funcPointer = EmitUnwrap(expression); @@ -433,7 +432,7 @@ public partial class QBEGenerator parameterStrings.Add($"{FuncQBETypeName(parameter.Type)} {copy}"); } - if (funcCall.Type is NubVoidType) + if (funcCall.Type is VoidTypeNode) { _writer.Indented($"call {funcPointer}({string.Join(", ", parameterStrings)})"); return new Val(string.Empty, funcCall.Type, ValKind.Direct); diff --git a/src/compiler/NubLang/Generation/QBE/QBEGenerator.Statement.cs b/src/compiler/NubLang/Generation/QBE/QBEGenerator.Statement.cs index 2b0b6c8..7121b58 100644 --- a/src/compiler/NubLang/Generation/QBE/QBEGenerator.Statement.cs +++ b/src/compiler/NubLang/Generation/QBE/QBEGenerator.Statement.cs @@ -5,32 +5,32 @@ namespace NubLang.Generation.QBE; public partial class QBEGenerator { - private void EmitStatement(Statement statement) + private void EmitStatement(StatementNode statement) { switch (statement) { - case Assignment assignment: + case AssignmentNode assignment: EmitAssignment(assignment); break; - case Break: + case BreakNode: EmitBreak(); break; - case Continue: + case ContinueNode: EmitContinue(); break; - case If ifStatement: + case IfNode ifStatement: EmitIf(ifStatement); break; - case Return @return: + case ReturnNode @return: EmitReturn(@return); break; - case StatementExpression statementExpression: + case StatementExpressionNode statementExpression: EmitExpression(statementExpression.Expression); break; - case VariableDeclaration variableDeclaration: + case VariableDeclarationNode variableDeclaration: EmitVariableDeclaration(variableDeclaration); break; - case While whileStatement: + case WhileNode whileStatement: EmitWhile(whileStatement); break; default: @@ -38,7 +38,7 @@ public partial class QBEGenerator } } - private void EmitAssignment(Assignment assignment) + private void EmitAssignment(AssignmentNode assignment) { var destination = EmitExpression(assignment.Target); Debug.Assert(destination.Kind == ValKind.Pointer); @@ -57,7 +57,7 @@ public partial class QBEGenerator _codeIsReachable = false; } - private void EmitIf(If ifStatement) + private void EmitIf(IfNode ifStatement) { var trueLabel = LabelName(); var falseLabel = LabelName(); @@ -81,7 +81,7 @@ public partial class QBEGenerator _writer.WriteLine(endLabel); } - private void EmitReturn(Return @return) + private void EmitReturn(ReturnNode @return) { if (@return.Value.HasValue) { @@ -94,7 +94,7 @@ public partial class QBEGenerator } } - private void EmitVariableDeclaration(VariableDeclaration variableDeclaration) + private void EmitVariableDeclaration(VariableDeclarationNode variableDeclaration) { var name = $"%{variableDeclaration.Name}"; _writer.Indented($"{name} =l alloc8 8"); @@ -108,7 +108,7 @@ public partial class QBEGenerator Scope.Declare(variableDeclaration.Name, new Val(name, variableDeclaration.Type, ValKind.Pointer)); } - private void EmitWhile(While whileStatement) + private void EmitWhile(WhileNode whileStatement) { var conditionLabel = LabelName(); var iterationLabel = LabelName(); diff --git a/src/compiler/NubLang/Generation/QBE/QBEGenerator.cs b/src/compiler/NubLang/Generation/QBE/QBEGenerator.cs index 8f0f5ed..f45bafb 100644 --- a/src/compiler/NubLang/Generation/QBE/QBEGenerator.cs +++ b/src/compiler/NubLang/Generation/QBE/QBEGenerator.cs @@ -17,7 +17,7 @@ public partial class QBEGenerator private readonly List _stringLiterals = []; private readonly Stack _breakLabels = []; private readonly Stack _continueLabels = []; - private readonly Queue<(ArrowFunc Func, string Name)> _arrowFunctions = []; + private readonly Queue<(ArrowFuncNode Func, string Name)> _arrowFunctions = []; private readonly Stack _scopes = []; private int _tmpIndex; private int _labelIndex; @@ -62,7 +62,7 @@ public partial class QBEGenerator _writer.NewLine(); } - foreach (var funcDef in _syntaxTree.Definitions.OfType()) + foreach (var funcDef in _syntaxTree.Definitions.OfType()) { EmitFuncDefinition(LocalFuncName(funcDef), funcDef.Signature.Parameters, funcDef.Signature.ReturnType, funcDef.Body); _writer.NewLine(); @@ -88,7 +88,7 @@ public partial class QBEGenerator return _writer.ToString(); } - private static string QBEAssign(NubType type) + private static string QBEAssign(TypeNode type) { if (type.IsSimpleType(out var simpleType, out _)) { @@ -105,7 +105,7 @@ public partial class QBEGenerator return "=l"; } - private void EmitStore(NubType type, string value, string destination) + private void EmitStore(TypeNode type, string value, string destination) { string store; @@ -130,7 +130,7 @@ public partial class QBEGenerator _writer.Indented($"{store} {value}, {destination}"); } - private Val EmitLoad(NubType type, string from) + private Val EmitLoad(TypeNode type, string from) { string load; @@ -166,7 +166,7 @@ public partial class QBEGenerator _writer.Indented($"call $nub_memcpy(l {source}, l {destination}, l {length})"); } - private string EmitArraySizeInBytes(NubArrayType type, string array) + private string EmitArraySizeInBytes(ArrayTypeNode type, string array) { var size = TmpName(); _writer.Indented($"{size} =l loadl {array}"); @@ -191,21 +191,21 @@ public partial class QBEGenerator return size; } - private bool EmitTryMoveInto(Expression source, string destinationPointer) + private bool EmitTryMoveInto(ExpressionNode source, string destinationPointer) { switch (source) { - case ArrayInitializer arrayInitializer: + case ArrayInitializerNode arrayInitializer: { EmitStore(source.Type, EmitUnwrap(EmitArrayInitializer(arrayInitializer)), destinationPointer); return true; } - case StructInitializer structInitializer: + case StructInitializerNode structInitializer: { EmitStructInitializer(structInitializer, destinationPointer); return true; } - case Literal { Kind: LiteralKind.String } literal: + case LiteralNode { Kind: LiteralKind.String } literal: { EmitStore(source.Type, EmitUnwrap(EmitLiteral(literal)), destinationPointer); return true; @@ -215,7 +215,7 @@ public partial class QBEGenerator return false; } - private void EmitCopyIntoOrInitialize(Expression source, string destinationPointer) + private void EmitCopyIntoOrInitialize(ExpressionNode source, string destinationPointer) { // If the source is a value which is not used yet such as an array/struct initializer or literal, we can skip copying if (EmitTryMoveInto(source, destinationPointer)) @@ -231,7 +231,7 @@ public partial class QBEGenerator } else { - if (complexType is NubCustomType customType) + if (complexType is CustomTypeNode customType) { EmitMemcpy(value, destinationPointer, customType.Size(_definitionTable).ToString()); } @@ -239,9 +239,9 @@ public partial class QBEGenerator { var size = complexType switch { - NubArrayType arrayType => EmitArraySizeInBytes(arrayType, value), - NubCStringType => EmitCStringSizeInBytes(value), - NubStringType => EmitStringSizeInBytes(value), + ArrayTypeNode arrayType => EmitArraySizeInBytes(arrayType, value), + CStringTypeNode => EmitCStringSizeInBytes(value), + NubStringTypeNode => EmitStringSizeInBytes(value), _ => throw new ArgumentOutOfRangeException(nameof(source.Type)) }; @@ -253,13 +253,13 @@ public partial class QBEGenerator } } - private bool EmitTryCreateWithoutCopy(Expression source, [NotNullWhen(true)] out string? destination) + private bool EmitTryCreateWithoutCopy(ExpressionNode source, [NotNullWhen(true)] out string? destination) { switch (source) { - case ArrayInitializer: - case StructInitializer: - case Literal { Kind: LiteralKind.String }: + case ArrayInitializerNode: + case StructInitializerNode: + case LiteralNode { Kind: LiteralKind.String }: { destination = EmitUnwrap(EmitExpression(source)); return true; @@ -270,7 +270,7 @@ public partial class QBEGenerator return false; } - private string EmitCreateCopyOrInitialize(Expression source) + private string EmitCreateCopyOrInitialize(ExpressionNode 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)) @@ -288,10 +288,10 @@ public partial class QBEGenerator var size = complexType switch { - NubArrayType arrayType => EmitArraySizeInBytes(arrayType, value), - NubCStringType => EmitCStringSizeInBytes(value), - NubStringType => EmitStringSizeInBytes(value), - NubCustomType customType => customType.Size(_definitionTable).ToString(), + ArrayTypeNode arrayType => EmitArraySizeInBytes(arrayType, value), + CStringTypeNode => EmitCStringSizeInBytes(value), + NubStringTypeNode => EmitStringSizeInBytes(value), + CustomTypeNode customType => customType.Size(_definitionTable).ToString(), _ => throw new ArgumentOutOfRangeException(nameof(source.Type)) }; @@ -302,7 +302,7 @@ public partial class QBEGenerator } // Utility to create QBE type names for function parameters and return types - private string FuncQBETypeName(NubType type) + private string FuncQBETypeName(TypeNode type) { if (type.IsSimpleType(out var simpleType, out var complexType)) { @@ -320,7 +320,7 @@ public partial class QBEGenerator }; } - if (complexType is NubCustomType customType) + if (complexType is CustomTypeNode customType) { return CustomTypeName(customType); } @@ -328,7 +328,7 @@ public partial class QBEGenerator return "l"; } - private void EmitFuncDefinition(string name, IReadOnlyList parameters, NubType returnType, Block body) + private void EmitFuncDefinition(string name, IReadOnlyList parameters, TypeNode returnType, BlockNode body) { _labelIndex = 0; _tmpIndex = 0; @@ -337,7 +337,7 @@ public partial class QBEGenerator builder.Append("export function "); - if (returnType is not NubVoidType) + if (returnType is not VoidTypeNode) { builder.Append(FuncQBETypeName(returnType) + ' '); } @@ -360,9 +360,9 @@ public partial class QBEGenerator EmitBlock(body, scope); // Implicit return for void functions if no explicit return has been set - if (returnType is NubVoidType && body.Statements is [.., not Return]) + if (returnType is VoidTypeNode && body.Statements is [.., not ReturnNode]) { - if (returnType is NubVoidType) + if (returnType is VoidTypeNode) { _writer.Indented("ret"); } @@ -371,7 +371,7 @@ public partial class QBEGenerator _writer.EndFunction(); } - private void EmitStructDefinition(Struct structDef) + private void EmitStructDefinition(StructNode structDef) { _writer.WriteLine($"type {CustomTypeName(structDef.Name)} = {{ "); @@ -392,7 +392,7 @@ public partial class QBEGenerator _writer.WriteLine("}"); return; - string StructDefQBEType(StructField field) + string StructDefQBEType(StructFieldNode field) { if (field.Type.IsSimpleType(out var simpleType, out var complexType)) { @@ -408,7 +408,7 @@ public partial class QBEGenerator }; } - if (complexType is NubCustomType customType) + if (complexType is CustomTypeNode customType) { return CustomTypeName(customType); } @@ -417,7 +417,7 @@ public partial class QBEGenerator } } - private void EmitTraitVTable(Trait traitDef) + private void EmitTraitVTable(TraitNode traitDef) { _writer.WriteLine($"type {CustomTypeName(traitDef.Name)} = {{"); @@ -429,7 +429,7 @@ public partial class QBEGenerator _writer.WriteLine("}"); } - private void EmitBlock(Block block, Scope? scope = null) + private void EmitBlock(BlockNode block, Scope? scope = null) { _scopes.Push(scope ?? Scope.SubScope()); @@ -456,7 +456,7 @@ public partial class QBEGenerator }; } - private int OffsetOf(Struct structDefinition, string member) + private int OffsetOf(StructNode structDefinition, string member) { var offset = 0; @@ -469,7 +469,7 @@ public partial class QBEGenerator var fieldAlignment = field.Type.Alignment(_definitionTable); - offset = NubType.AlignTo(offset, fieldAlignment); + offset = TypeNode.AlignTo(offset, fieldAlignment); offset += field.Type.Size(_definitionTable); } @@ -498,17 +498,17 @@ public partial class QBEGenerator return $"$string{++_stringLiteralIndex}"; } - private string LocalFuncName(LocalFunc funcDef) + private string LocalFuncName(LocalFuncNode funcDef) { return $"${funcDef.Name}"; } - private string ExternFuncName(ExternFunc funcDef) + private string ExternFuncName(ExternFuncNode funcDef) { return $"${funcDef.CallName}"; } - private string CustomTypeName(NubCustomType customType) + private string CustomTypeName(CustomTypeNode customType) { return CustomTypeName(customType.Name); } @@ -533,7 +533,7 @@ public class CStringLiteral(string value, string name) public string Name { get; } = name; } -public record Val(string Name, NubType Type, ValKind Kind); +public record Val(string Name, TypeNode Type, ValKind Kind); public class Scope(Scope? parent = null) { diff --git a/src/compiler/NubLang/Generation/TypedDefinitionTable.cs b/src/compiler/NubLang/Generation/TypedDefinitionTable.cs index feb56ac..55151d2 100644 --- a/src/compiler/NubLang/Generation/TypedDefinitionTable.cs +++ b/src/compiler/NubLang/Generation/TypedDefinitionTable.cs @@ -4,41 +4,41 @@ namespace NubLang.Generation; public sealed class TypedDefinitionTable { - private readonly List _definitions; + private readonly List _definitions; public TypedDefinitionTable(IEnumerable syntaxTrees) { _definitions = syntaxTrees.SelectMany(x => x.Definitions).ToList(); } - public LocalFunc LookupLocalFunc(string name) + public LocalFuncNode LookupLocalFunc(string name) { return _definitions - .OfType() + .OfType() .First(x => x.Name == name); } - public ExternFunc LookupExternFunc(string name) + public ExternFuncNode LookupExternFunc(string name) { return _definitions - .OfType() + .OfType() .First(x => x.Name == name); } - public Struct LookupStruct(string name) + public StructNode LookupStruct(string name) { return _definitions - .OfType() + .OfType() .First(x => x.Name == name); } - public IEnumerable GetStructs() + public IEnumerable GetStructs() { - return _definitions.OfType(); + return _definitions.OfType(); } - public IEnumerable GetTraits() + public IEnumerable GetTraits() { - return _definitions.OfType(); + return _definitions.OfType(); } } \ No newline at end of file diff --git a/src/compiler/NubLang/TypeChecking/DefinitionTable.cs b/src/compiler/NubLang/TypeChecking/DefinitionTable.cs index f2e6335..e1bcc1d 100644 --- a/src/compiler/NubLang/TypeChecking/DefinitionTable.cs +++ b/src/compiler/NubLang/TypeChecking/DefinitionTable.cs @@ -26,7 +26,7 @@ public class DefinitionTable .Where(x => x.Name == name); } - public IEnumerable LookupStruct(NubCustomType type) + public IEnumerable LookupStruct(CustomTypeNode type) { return _definitions .OfType() @@ -38,7 +38,7 @@ public class DefinitionTable return structNode.Fields.Where(x => x.Name == field); } - public IEnumerable LookupTrait(NubCustomType type) + public IEnumerable LookupTrait(CustomTypeNode type) { return _definitions .OfType() diff --git a/src/compiler/NubLang/TypeChecking/Node/Definition.cs b/src/compiler/NubLang/TypeChecking/Node/Definition.cs deleted file mode 100644 index 98cd630..0000000 --- a/src/compiler/NubLang/TypeChecking/Node/Definition.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace NubLang.TypeChecking.Node; - -public abstract record Definition : Node; - -public record FuncParameter(string Name, NubType Type) : Node; - -public record FuncSignature(IReadOnlyList Parameters, NubType ReturnType) : Node; - -public record LocalFunc(string Name, FuncSignature Signature, Block Body) : Definition; - -public record ExternFunc(string Name, string CallName, FuncSignature Signature) : Definition; - -public record StructField(int Index, string Name, NubType Type, Optional Value) : Node; - -public record Struct(string Name, IReadOnlyList Fields) : Definition; - -public record TraitFunc(string Name, FuncSignature Signature) : Node; - -public record Trait(string Name, IReadOnlyList Functions) : Definition; - -public record TraitFuncImpl(string Name, FuncSignature Signature, Block Body) : Node; - -public record TraitImpl(NubType TraitType, NubType ForType, IReadOnlyList Functions) : Definition; \ No newline at end of file diff --git a/src/compiler/NubLang/TypeChecking/Node/DefinitionNode.cs b/src/compiler/NubLang/TypeChecking/Node/DefinitionNode.cs new file mode 100644 index 0000000..9ded243 --- /dev/null +++ b/src/compiler/NubLang/TypeChecking/Node/DefinitionNode.cs @@ -0,0 +1,19 @@ +namespace NubLang.TypeChecking.Node; + +public abstract record DefinitionNode : Node; + +public record FuncParameterNode(string Name, TypeNode Type) : Node; + +public record FuncSignatureNode(IReadOnlyList Parameters, TypeNode ReturnType) : Node; + +public record LocalFuncNode(string Name, FuncSignatureNode Signature, BlockNode Body) : DefinitionNode; + +public record ExternFuncNode(string Name, string CallName, FuncSignatureNode Signature) : DefinitionNode; + +public record StructFieldNode(int Index, string Name, TypeNode Type, Optional Value) : Node; + +public record StructNode(string Name, IReadOnlyList Fields) : DefinitionNode; + +public record TraitFuncNode(string Name, FuncSignatureNode Signature) : Node; + +public record TraitNode(string Name, IReadOnlyList Functions) : DefinitionNode; \ No newline at end of file diff --git a/src/compiler/NubLang/TypeChecking/Node/Expression.cs b/src/compiler/NubLang/TypeChecking/Node/Expression.cs deleted file mode 100644 index 1cf2a39..0000000 --- a/src/compiler/NubLang/TypeChecking/Node/Expression.cs +++ /dev/null @@ -1,55 +0,0 @@ -using NubLang.Tokenization; - -namespace NubLang.TypeChecking.Node; - -public enum UnaryOperator -{ - Negate, - Invert -} - -public enum BinaryOperator -{ - Equal, - NotEqual, - GreaterThan, - GreaterThanOrEqual, - LessThan, - LessThanOrEqual, - Plus, - Minus, - Multiply, - Divide -} - -public abstract record Expression(NubType Type) : Node; - -public record BinaryExpression(NubType Type, Expression Left, BinaryOperator Operator, Expression Right) : Expression(Type); - -public record UnaryExpression(NubType Type, UnaryOperator Operator, Expression Operand) : Expression(Type); - -public record FuncCall(NubType Type, Expression Expression, IReadOnlyList Parameters) : Expression(Type); - -public record VariableIdent(NubType Type, string Name) : Expression(Type); - -public record LocalFuncIdent(NubType Type, string Name) : Expression(Type); - -public record ExternFuncIdent(NubType Type, string Name) : Expression(Type); - -public record ArrayInitializer(NubType Type, Expression Capacity, NubType ElementType) : Expression(Type); - -public record ArrayIndexAccess(NubType Type, Expression Target, Expression Index) : Expression(Type); - -public record ArrowFunc(NubType Type, IReadOnlyList Parameters, NubType ReturnType, Block Body) : Expression(Type); - -public record AddressOf(NubType Type, Expression Expression) : Expression(Type); - -public record Literal(NubType Type, string Value, LiteralKind Kind) : Expression(Type); - -public record StructFieldAccess(NubType Type, NubCustomType StructType, Expression Target, string Field) : Expression(Type); - -public record InterfaceFuncAccess(NubType Type, NubCustomType InterfaceType, Expression Target, string FuncName) : Expression(Type); - -public record StructInitializer(NubCustomType StructType, Dictionary Initializers) : Expression(StructType); - -public record Dereference(NubType Type, Expression Expression) : Expression(Type); \ No newline at end of file diff --git a/src/compiler/NubLang/TypeChecking/Node/ExpressionNode.cs b/src/compiler/NubLang/TypeChecking/Node/ExpressionNode.cs new file mode 100644 index 0000000..b1ec4da --- /dev/null +++ b/src/compiler/NubLang/TypeChecking/Node/ExpressionNode.cs @@ -0,0 +1,55 @@ +using NubLang.Tokenization; + +namespace NubLang.TypeChecking.Node; + +public enum UnaryOperator +{ + Negate, + Invert +} + +public enum BinaryOperator +{ + Equal, + NotEqual, + GreaterThan, + GreaterThanOrEqual, + LessThan, + LessThanOrEqual, + Plus, + Minus, + Multiply, + Divide +} + +public abstract record ExpressionNode(TypeNode Type) : Node; + +public record BinaryExpressionNode(TypeNode Type, ExpressionNode Left, BinaryOperator Operator, ExpressionNode Right) : ExpressionNode(Type); + +public record UnaryExpressionNode(TypeNode Type, UnaryOperator Operator, ExpressionNode Operand) : ExpressionNode(Type); + +public record FuncCallNode(TypeNode Type, ExpressionNode Expression, IReadOnlyList Parameters) : ExpressionNode(Type); + +public record VariableIdentNode(TypeNode Type, string Name) : ExpressionNode(Type); + +public record LocalFuncIdentNode(TypeNode Type, string Name) : ExpressionNode(Type); + +public record ExternFuncIdentNode(TypeNode Type, string Name) : ExpressionNode(Type); + +public record ArrayInitializerNode(TypeNode Type, ExpressionNode Capacity, TypeNode ElementType) : ExpressionNode(Type); + +public record ArrayIndexAccessNode(TypeNode Type, ExpressionNode Target, ExpressionNode Index) : ExpressionNode(Type); + +public record ArrowFuncNode(TypeNode Type, IReadOnlyList Parameters, TypeNode ReturnType, BlockNode Body) : ExpressionNode(Type); + +public record AddressOfNode(TypeNode Type, ExpressionNode Expression) : ExpressionNode(Type); + +public record LiteralNode(TypeNode Type, string Value, LiteralKind Kind) : ExpressionNode(Type); + +public record StructFieldAccessNode(TypeNode Type, CustomTypeNode StructType, ExpressionNode Target, string Field) : ExpressionNode(Type); + +public record InterfaceFuncAccessNode(TypeNode Type, CustomTypeNode InterfaceType, ExpressionNode Target, string FuncName) : ExpressionNode(Type); + +public record StructInitializerNode(CustomTypeNode StructType, Dictionary Initializers) : ExpressionNode(StructType); + +public record DereferenceNode(TypeNode Type, ExpressionNode Expression) : ExpressionNode(Type); \ No newline at end of file diff --git a/src/compiler/NubLang/TypeChecking/Node/Node.cs b/src/compiler/NubLang/TypeChecking/Node/Node.cs new file mode 100644 index 0000000..1624372 --- /dev/null +++ b/src/compiler/NubLang/TypeChecking/Node/Node.cs @@ -0,0 +1,7 @@ +namespace NubLang.TypeChecking.Node; + +public abstract record Node; + +public record TypedSyntaxTree(IReadOnlyList Definitions) : Node; + +public record BlockNode(IReadOnlyList Statements) : Node; \ No newline at end of file diff --git a/src/compiler/NubLang/TypeChecking/Node/Statement.cs b/src/compiler/NubLang/TypeChecking/Node/Statement.cs deleted file mode 100644 index 5a1a42b..0000000 --- a/src/compiler/NubLang/TypeChecking/Node/Statement.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace NubLang.TypeChecking.Node; - -public record Statement : Node; - -public record StatementExpression(Expression Expression) : Statement; - -public record Return(Optional Value) : Statement; - -public record Assignment(Expression Target, Expression Value) : Statement; - -public record If(Expression Condition, Block Body, Optional> Else) : Statement; - -public record VariableDeclaration(string Name, Optional Assignment, NubType Type) : Statement; - -public record Continue : Statement; - -public record Break : Statement; - -public record While(Expression Condition, Block Body) : Statement; \ No newline at end of file diff --git a/src/compiler/NubLang/TypeChecking/Node/StatementNode.cs b/src/compiler/NubLang/TypeChecking/Node/StatementNode.cs new file mode 100644 index 0000000..6bf764a --- /dev/null +++ b/src/compiler/NubLang/TypeChecking/Node/StatementNode.cs @@ -0,0 +1,19 @@ +namespace NubLang.TypeChecking.Node; + +public record StatementNode : Node; + +public record StatementExpressionNode(ExpressionNode Expression) : StatementNode; + +public record ReturnNode(Optional Value) : StatementNode; + +public record AssignmentNode(ExpressionNode Target, ExpressionNode Value) : StatementNode; + +public record IfNode(ExpressionNode Condition, BlockNode Body, Optional> Else) : StatementNode; + +public record VariableDeclarationNode(string Name, Optional Assignment, TypeNode Type) : StatementNode; + +public record ContinueNode : StatementNode; + +public record BreakNode : StatementNode; + +public record WhileNode(ExpressionNode Condition, BlockNode Body) : StatementNode; \ No newline at end of file diff --git a/src/compiler/NubLang/TypeChecking/Node/SyntaxTree.cs b/src/compiler/NubLang/TypeChecking/Node/SyntaxTree.cs deleted file mode 100644 index 46d72e5..0000000 --- a/src/compiler/NubLang/TypeChecking/Node/SyntaxTree.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace NubLang.TypeChecking.Node; - -public record TypedSyntaxTree(IReadOnlyList Definitions); - -public abstract record Node; - -public record Block(IReadOnlyList Statements) : Node; \ No newline at end of file diff --git a/src/compiler/NubLang/TypeChecking/Node/NubType.cs b/src/compiler/NubLang/TypeChecking/Node/TypeNode.cs similarity index 70% rename from src/compiler/NubLang/TypeChecking/Node/NubType.cs rename to src/compiler/NubLang/TypeChecking/Node/TypeNode.cs index 127fd10..566f567 100644 --- a/src/compiler/NubLang/TypeChecking/Node/NubType.cs +++ b/src/compiler/NubLang/TypeChecking/Node/TypeNode.cs @@ -3,18 +3,18 @@ using NubLang.Generation; namespace NubLang.TypeChecking.Node; -public abstract class NubType : IEquatable +public abstract class TypeNode : IEquatable { - public bool IsSimpleType([NotNullWhen(true)] out NubSimpleType? simpleType, [NotNullWhen(false)] out NubComplexType? complexType) + public bool IsSimpleType([NotNullWhen(true)] out SimpleTypeNode? simpleType, [NotNullWhen(false)] out NubComplexTypeNode? complexType) { - if (this is NubSimpleType st) + if (this is SimpleTypeNode st) { complexType = null; simpleType = st; return true; } - if (this is NubComplexType ct) + if (this is NubComplexTypeNode ct) { complexType = ct; simpleType = null; @@ -32,14 +32,14 @@ public abstract class NubType : IEquatable return (offset + alignment - 1) & ~(alignment - 1); } - public override bool Equals(object? obj) => obj is NubType other && Equals(other); + public override bool Equals(object? obj) => obj is TypeNode other && Equals(other); - public abstract bool Equals(NubType? other); + public abstract bool Equals(TypeNode? other); public abstract override int GetHashCode(); public abstract override string ToString(); - public static bool operator ==(NubType? left, NubType? right) => Equals(left, right); - public static bool operator !=(NubType? left, NubType? right) => !Equals(left, right); + public static bool operator ==(TypeNode? left, TypeNode? right) => Equals(left, right); + public static bool operator !=(TypeNode? left, TypeNode? right) => !Equals(left, right); } public enum StorageSize @@ -57,7 +57,7 @@ public enum StorageSize F64 } -public abstract class NubSimpleType : NubType +public abstract class SimpleTypeNode : TypeNode { public abstract StorageSize StorageSize { get; } @@ -81,7 +81,7 @@ public abstract class NubSimpleType : NubType #region Simple types -public class NubIntType(bool signed, int width) : NubSimpleType +public class IntTypeNode(bool signed, int width) : SimpleTypeNode { public bool Signed { get; } = signed; public int Width { get; } = width; @@ -107,11 +107,11 @@ public class NubIntType(bool signed, int width) : NubSimpleType }; public override string ToString() => $"{(Signed ? "i" : "u")}{Width}"; - public override bool Equals(NubType? other) => other is NubIntType @int && @int.Width == Width && @int.Signed == Signed; - public override int GetHashCode() => HashCode.Combine(typeof(NubIntType), Signed, Width); + public override bool Equals(TypeNode? other) => other is IntTypeNode @int && @int.Width == Width && @int.Signed == Signed; + public override int GetHashCode() => HashCode.Combine(typeof(IntTypeNode), Signed, Width); } -public class NubFloatType(int width) : NubSimpleType +public class FloatTypeNode(int width) : SimpleTypeNode { public int Width { get; } = width; @@ -123,33 +123,33 @@ public class NubFloatType(int width) : NubSimpleType }; public override string ToString() => $"f{Width}"; - public override bool Equals(NubType? other) => other is NubFloatType @int && @int.Width == Width; - public override int GetHashCode() => HashCode.Combine(typeof(NubFloatType), Width); + public override bool Equals(TypeNode? other) => other is FloatTypeNode @int && @int.Width == Width; + public override int GetHashCode() => HashCode.Combine(typeof(FloatTypeNode), Width); } -public class NubBoolType : NubSimpleType +public class BoolTypeNode : SimpleTypeNode { public override StorageSize StorageSize => StorageSize.U8; public override string ToString() => "bool"; - public override bool Equals(NubType? other) => other is NubBoolType; - public override int GetHashCode() => HashCode.Combine(typeof(NubBoolType)); + public override bool Equals(TypeNode? other) => other is BoolTypeNode; + public override int GetHashCode() => HashCode.Combine(typeof(BoolTypeNode)); } -public class NubFuncType(List parameters, NubType returnType) : NubSimpleType +public class FuncTypeNode(List parameters, TypeNode returnType) : SimpleTypeNode { - public IReadOnlyList Parameters { get; } = parameters; - public NubType ReturnType { get; } = returnType; + public IReadOnlyList Parameters { get; } = parameters; + public TypeNode ReturnType { get; } = returnType; public override StorageSize StorageSize => StorageSize.U64; public override string ToString() => $"func({string.Join(", ", Parameters)}): {ReturnType}"; - public override bool Equals(NubType? other) => other is NubFuncType func && ReturnType.Equals(func.ReturnType) && Parameters.SequenceEqual(func.Parameters); + public override bool Equals(TypeNode? other) => other is FuncTypeNode func && ReturnType.Equals(func.ReturnType) && Parameters.SequenceEqual(func.Parameters); public override int GetHashCode() { var hash = new HashCode(); - hash.Add(typeof(NubFuncType)); + hash.Add(typeof(FuncTypeNode)); hash.Add(ReturnType); foreach (var param in Parameters) { @@ -160,53 +160,53 @@ public class NubFuncType(List parameters, NubType returnType) : NubSimp } } -public class NubPointerType(NubType baseType) : NubSimpleType +public class PointerTypeNode(TypeNode baseType) : SimpleTypeNode { - public NubType BaseType { get; } = baseType; + public TypeNode BaseType { get; } = baseType; public override StorageSize StorageSize => StorageSize.U64; public override string ToString() => "^" + BaseType; - public override bool Equals(NubType? other) => other is NubPointerType pointer && BaseType.Equals(pointer.BaseType); - public override int GetHashCode() => HashCode.Combine(typeof(NubPointerType), BaseType); + public override bool Equals(TypeNode? other) => other is PointerTypeNode pointer && BaseType.Equals(pointer.BaseType); + public override int GetHashCode() => HashCode.Combine(typeof(PointerTypeNode), BaseType); } -public class NubVoidType : NubSimpleType +public class VoidTypeNode : SimpleTypeNode { public override StorageSize StorageSize => StorageSize.Void; public override string ToString() => "void"; - public override bool Equals(NubType? other) => other is NubVoidType; - public override int GetHashCode() => HashCode.Combine(typeof(NubVoidType)); + public override bool Equals(TypeNode? other) => other is VoidTypeNode; + public override int GetHashCode() => HashCode.Combine(typeof(VoidTypeNode)); } #endregion -public abstract class NubComplexType : NubType; +public abstract class NubComplexTypeNode : TypeNode; #region Complex types -public class NubCStringType : NubComplexType +public class CStringTypeNode : NubComplexTypeNode { public override int Size(TypedDefinitionTable definitionTable) => 8; public override int Alignment(TypedDefinitionTable definitionTable) => Size(definitionTable); public override string ToString() => "cstring"; - public override bool Equals(NubType? other) => other is NubCStringType; - public override int GetHashCode() => HashCode.Combine(typeof(NubCStringType)); + public override bool Equals(TypeNode? other) => other is CStringTypeNode; + public override int GetHashCode() => HashCode.Combine(typeof(CStringTypeNode)); } -public class NubStringType : NubComplexType +public class NubStringTypeNode : NubComplexTypeNode { public override int Size(TypedDefinitionTable definitionTable) => 8; public override int Alignment(TypedDefinitionTable definitionTable) => Size(definitionTable); public override string ToString() => "string"; - public override bool Equals(NubType? other) => other is NubStringType; - public override int GetHashCode() => HashCode.Combine(typeof(NubStringType)); + public override bool Equals(TypeNode? other) => other is NubStringTypeNode; + public override int GetHashCode() => HashCode.Combine(typeof(NubStringTypeNode)); } -public class NubCustomType(string name) : NubComplexType +public class CustomTypeNode(string name) : NubComplexTypeNode { public string Name { get; } = name; @@ -269,8 +269,8 @@ public class NubCustomType(string name) : NubComplexType } public override string ToString() => Name; - public override bool Equals(NubType? other) => other is NubCustomType custom && Name == custom.Name; - public override int GetHashCode() => HashCode.Combine(typeof(NubCustomType), Name); + public override bool Equals(TypeNode? other) => other is CustomTypeNode custom && Name == custom.Name; + public override int GetHashCode() => HashCode.Combine(typeof(CustomTypeNode), Name); } public enum CustomTypeKind @@ -279,17 +279,17 @@ public enum CustomTypeKind Interface } -public class NubArrayType(NubType elementType) : NubComplexType +public class ArrayTypeNode(TypeNode elementType) : NubComplexTypeNode { - public NubType ElementType { get; } = elementType; + public TypeNode ElementType { get; } = elementType; public override int Size(TypedDefinitionTable definitionTable) => 8; public override int Alignment(TypedDefinitionTable definitionTable) => Size(definitionTable); public override string ToString() => "[]" + ElementType; - public override bool Equals(NubType? other) => other is NubArrayType array && ElementType.Equals(array.ElementType); - public override int GetHashCode() => HashCode.Combine(typeof(NubArrayType), ElementType); + public override bool Equals(TypeNode? other) => other is ArrayTypeNode array && ElementType.Equals(array.ElementType); + public override int GetHashCode() => HashCode.Combine(typeof(ArrayTypeNode), ElementType); } #endregion \ No newline at end of file diff --git a/src/compiler/NubLang/TypeChecking/TypeChecker.cs b/src/compiler/NubLang/TypeChecking/TypeChecker.cs index 8d870f3..3329ead 100644 --- a/src/compiler/NubLang/TypeChecking/TypeChecker.cs +++ b/src/compiler/NubLang/TypeChecking/TypeChecker.cs @@ -11,7 +11,7 @@ public sealed class TypeChecker private readonly DefinitionTable _definitionTable; private readonly Stack _scopes = []; - private readonly Stack _funcReturnTypes = []; + private readonly Stack _funcReturnTypes = []; private readonly List _diagnostics = []; private Scope Scope => _scopes.Peek(); @@ -30,7 +30,7 @@ public sealed class TypeChecker _funcReturnTypes.Clear(); _scopes.Clear(); - var definitions = new List(); + var definitions = new List(); foreach (var definition in _syntaxTree.Definitions) { @@ -47,7 +47,7 @@ public sealed class TypeChecker return new TypedSyntaxTree(definitions); } - private Definition CheckDefinition(DefinitionSyntax node) + private DefinitionNode CheckDefinition(DefinitionSyntax node) { return node switch { @@ -59,57 +59,57 @@ public sealed class TypeChecker }; } - private Trait CheckTraitDefinition(InterfaceSyntax node) + private TraitNode CheckTraitDefinition(InterfaceSyntax node) { - var functions = new List(); + var functions = new List(); foreach (var function in node.Functions) { - functions.Add(new TraitFunc(function.Name, CheckFuncSignature(function.Signature))); + functions.Add(new TraitFuncNode(function.Name, CheckFuncSignature(function.Signature))); } - return new Trait(node.Name, functions); + return new TraitNode(node.Name, functions); } - private Struct CheckStruct(StructSyntax node) + private StructNode CheckStruct(StructSyntax node) { - var structFields = new List(); + var structFields = new List(); foreach (var field in node.Fields) { - var value = Optional.Empty(); + var value = Optional.Empty(); if (field.Value.HasValue) { value = CheckExpression(field.Value.Value, CheckType(field.Type)); } - structFields.Add(new StructField(field.Index, field.Name, CheckType(field.Type), value)); + structFields.Add(new StructFieldNode(field.Index, field.Name, CheckType(field.Type), value)); } - return new Struct(node.Name, structFields); + return new StructNode(node.Name, structFields); } - private ExternFunc CheckExternFuncDefinition(ExternFuncSyntax node) + private ExternFuncNode CheckExternFuncDefinition(ExternFuncSyntax node) { - return new ExternFunc(node.Name, node.CallName, CheckFuncSignature(node.Signature)); + return new ExternFuncNode(node.Name, node.CallName, CheckFuncSignature(node.Signature)); } - private LocalFunc CheckLocalFuncDefinition(LocalFuncSyntax node) + private LocalFuncNode CheckLocalFuncDefinition(LocalFuncSyntax node) { var signature = CheckFuncSignature(node.Signature); var body = CheckFuncBody(node.Body, signature.ReturnType, signature.Parameters); - return new LocalFunc(node.Name, signature, body); + return new LocalFuncNode(node.Name, signature, body); } - private Statement CheckStatement(StatementSyntax node) + private StatementNode CheckStatement(StatementSyntax node) { return node switch { AssignmentSyntax statement => CheckAssignment(statement), - BreakSyntax => new Break(), - ContinueSyntax => new Continue(), + BreakSyntax => new BreakNode(), + ContinueSyntax => new ContinueNode(), IfSyntax statement => CheckIf(statement), ReturnSyntax statement => CheckReturn(statement), StatementExpressionSyntax statement => CheckStatementExpression(statement), @@ -119,56 +119,56 @@ public sealed class TypeChecker }; } - private Statement CheckAssignment(AssignmentSyntax statement) + private StatementNode CheckAssignment(AssignmentSyntax statement) { var expression = CheckExpression(statement.Target); var value = CheckExpression(statement.Value, expression.Type); - return new Assignment(expression, value); + return new AssignmentNode(expression, value); } - private If CheckIf(IfSyntax statement) + private IfNode CheckIf(IfSyntax statement) { - var elseStatement = Optional.Empty>(); + var elseStatement = Optional.Empty>(); if (statement.Else.HasValue) { - elseStatement = statement.Else.Value.Match> + elseStatement = statement.Else.Value.Match> ( elseIf => CheckIf(elseIf), @else => CheckBlock(@else) ); } - return new If(CheckExpression(statement.Condition, new NubBoolType()), CheckBlock(statement.Body), elseStatement); + return new IfNode(CheckExpression(statement.Condition, new BoolTypeNode()), CheckBlock(statement.Body), elseStatement); } - private Return CheckReturn(ReturnSyntax statement) + private ReturnNode CheckReturn(ReturnSyntax statement) { - var value = Optional.Empty(); + var value = Optional.Empty(); if (statement.Value.HasValue) { value = CheckExpression(statement.Value.Value, _funcReturnTypes.Peek()); } - return new Return(value); + return new ReturnNode(value); } - private StatementExpression CheckStatementExpression(StatementExpressionSyntax statement) + private StatementExpressionNode CheckStatementExpression(StatementExpressionSyntax statement) { - return new StatementExpression(CheckExpression(statement.Expression)); + return new StatementExpressionNode(CheckExpression(statement.Expression)); } - private VariableDeclaration CheckVariableDeclaration(VariableDeclarationSyntax statement) + private VariableDeclarationNode CheckVariableDeclaration(VariableDeclarationSyntax statement) { - NubType? type = null; + TypeNode? type = null; if (statement.ExplicitType.HasValue) { type = CheckType(statement.ExplicitType.Value); } - var assignment = Optional.Empty(); + var assignment = Optional.Empty(); if (statement.Assignment.HasValue) { var boundValue = CheckExpression(statement.Assignment.Value, type); @@ -183,15 +183,15 @@ public sealed class TypeChecker Scope.Declare(new Variable(statement.Name, type)); - return new VariableDeclaration(statement.Name, assignment, type); + return new VariableDeclarationNode(statement.Name, assignment, type); } - private While CheckWhile(WhileSyntax statement) + private WhileNode CheckWhile(WhileSyntax statement) { - return new While(CheckExpression(statement.Condition, new NubBoolType()), CheckBlock(statement.Body)); + return new WhileNode(CheckExpression(statement.Condition, new BoolTypeNode()), CheckBlock(statement.Body)); } - private Expression CheckExpression(ExpressionSyntax node, NubType? expectedType = null) + private ExpressionNode CheckExpression(ExpressionSyntax node, TypeNode? expectedType = null) { return node switch { @@ -211,25 +211,25 @@ public sealed class TypeChecker }; } - private AddressOf CheckAddressOf(AddressOfSyntax expression) + private AddressOfNode CheckAddressOf(AddressOfSyntax expression) { var inner = CheckExpression(expression.Expression); - return new AddressOf(new NubPointerType(inner.Type), inner); + return new AddressOfNode(new PointerTypeNode(inner.Type), inner); } - private ArrowFunc CheckArrowFunc(ArrowFuncSyntax expression, NubType? expectedType = null) + private ArrowFuncNode CheckArrowFunc(ArrowFuncSyntax expression, TypeNode? expectedType = null) { if (expectedType == null) { throw new CheckException(Diagnostic.Error("Cannot infer argument types for arrow function").Build()); } - if (expectedType is not NubFuncType funcType) + if (expectedType is not FuncTypeNode funcType) { throw new CheckException(Diagnostic.Error($"Expected {expectedType}, but got arrow function").Build()); } - var parameters = new List(); + var parameters = new List(); for (var i = 0; i < expression.Parameters.Count; i++) { @@ -240,49 +240,49 @@ public sealed class TypeChecker var expectedParameterType = funcType.Parameters[i]; var parameter = expression.Parameters[i]; - parameters.Add(new FuncParameter(parameter.Name, expectedParameterType)); + parameters.Add(new FuncParameterNode(parameter.Name, expectedParameterType)); } var body = CheckFuncBody(expression.Body, funcType.ReturnType, parameters); - return new ArrowFunc(new NubFuncType(parameters.Select(x => x.Type).ToList(), funcType.ReturnType), parameters, funcType.ReturnType, body); + return new ArrowFuncNode(new FuncTypeNode(parameters.Select(x => x.Type).ToList(), funcType.ReturnType), parameters, funcType.ReturnType, body); } - private ArrayIndexAccess CheckArrayIndexAccess(ArrayIndexAccessSyntax expression) + private ArrayIndexAccessNode CheckArrayIndexAccess(ArrayIndexAccessSyntax expression) { var boundArray = CheckExpression(expression.Target); - var elementType = ((NubArrayType)boundArray.Type).ElementType; - return new ArrayIndexAccess(elementType, boundArray, CheckExpression(expression.Index, new NubIntType(false, 64))); + var elementType = ((ArrayTypeNode)boundArray.Type).ElementType; + return new ArrayIndexAccessNode(elementType, boundArray, CheckExpression(expression.Index, new IntTypeNode(false, 64))); } - private ArrayInitializer CheckArrayInitializer(ArrayInitializerSyntax expression) + private ArrayInitializerNode CheckArrayInitializer(ArrayInitializerSyntax expression) { - var capacity = CheckExpression(expression.Capacity, new NubIntType(false, 64)); - var type = new NubArrayType(CheckType(expression.ElementType)); - return new ArrayInitializer(type, capacity, CheckType(expression.ElementType)); + var capacity = CheckExpression(expression.Capacity, new IntTypeNode(false, 64)); + var type = new ArrayTypeNode(CheckType(expression.ElementType)); + return new ArrayInitializerNode(type, capacity, CheckType(expression.ElementType)); } - private BinaryExpression CheckBinaryExpression(BinaryExpressionSyntax expression) + private BinaryExpressionNode CheckBinaryExpression(BinaryExpressionSyntax expression) { var boundLeft = CheckExpression(expression.Left); var boundRight = CheckExpression(expression.Right, boundLeft.Type); - return new BinaryExpression(boundLeft.Type, boundLeft, CheckBinaryOperator(expression.OperatorSyntax), boundRight); + return new BinaryExpressionNode(boundLeft.Type, boundLeft, CheckBinaryOperator(expression.OperatorSyntax), boundRight); } - private Dereference CheckDereference(DereferenceSyntax expression) + private DereferenceNode CheckDereference(DereferenceSyntax expression) { var boundExpression = CheckExpression(expression.Expression); - var dereferencedType = ((NubPointerType)boundExpression.Type).BaseType; - return new Dereference(dereferencedType, boundExpression); + var dereferencedType = ((PointerTypeNode)boundExpression.Type).BaseType; + return new DereferenceNode(dereferencedType, boundExpression); } - private FuncCall CheckFuncCall(FuncCallSyntax expression) + private FuncCallNode CheckFuncCall(FuncCallSyntax expression) { var boundExpression = CheckExpression(expression.Expression); - var funcType = (NubFuncType)boundExpression.Type; + var funcType = (FuncTypeNode)boundExpression.Type; - var parameters = new List(); + var parameters = new List(); foreach (var (i, parameter) in expression.Parameters.Index()) { @@ -296,15 +296,15 @@ public sealed class TypeChecker parameters.Add(CheckExpression(parameter, expectedType)); } - return new FuncCall(funcType.ReturnType, boundExpression, parameters); + return new FuncCallNode(funcType.ReturnType, boundExpression, parameters); } - private Expression CheckIdentifier(IdentifierSyntax expression) + private ExpressionNode CheckIdentifier(IdentifierSyntax expression) { var variable = Scope.Lookup(expression.Name); if (variable != null) { - return new VariableIdent(variable.Type, variable.Name); + return new VariableIdentNode(variable.Type, variable.Name); } var localFuncs = _definitionTable.LookupLocalFunc(expression.Name).ToArray(); @@ -319,8 +319,8 @@ public sealed class TypeChecker var returnType = CheckType(localFunc.Signature.ReturnType); var parameterTypes = localFunc.Signature.Parameters.Select(p => CheckType(p.Type)).ToList(); - var type = new NubFuncType(parameterTypes, returnType); - return new LocalFuncIdent(type, expression.Name); + var type = new FuncTypeNode(parameterTypes, returnType); + return new LocalFuncIdentNode(type, expression.Name); } var externFuncs = _definitionTable.LookupExternFunc(expression.Name).ToArray(); @@ -335,32 +335,32 @@ public sealed class TypeChecker var returnType = CheckType(externFunc.Signature.ReturnType); var parameterTypes = externFunc.Signature.Parameters.Select(p => CheckType(p.Type)).ToList(); - var type = new NubFuncType(parameterTypes, returnType); - return new ExternFuncIdent(type, expression.Name); + var type = new FuncTypeNode(parameterTypes, returnType); + return new ExternFuncIdentNode(type, expression.Name); } throw new CheckException(Diagnostic.Error($"No identifier with the name {expression.Name} exists").Build()); } - private Literal CheckLiteral(LiteralSyntax expression, NubType? expectedType = null) + private LiteralNode CheckLiteral(LiteralSyntax expression, TypeNode? expectedType = null) { var type = expectedType ?? expression.Kind switch { - LiteralKind.Integer => new NubIntType(true, 64), - LiteralKind.Float => new NubFloatType(64), - LiteralKind.String => new NubStringType(), - LiteralKind.Bool => new NubBoolType(), + LiteralKind.Integer => new IntTypeNode(true, 64), + LiteralKind.Float => new FloatTypeNode(64), + LiteralKind.String => new NubStringTypeNode(), + LiteralKind.Bool => new BoolTypeNode(), _ => throw new ArgumentOutOfRangeException() }; - return new Literal(type, expression.Value, expression.Kind); + return new LiteralNode(type, expression.Value, expression.Kind); } - private Expression CheckMemberAccess(MemberAccessSyntax expression) + private ExpressionNode CheckMemberAccess(MemberAccessSyntax expression) { var boundExpression = CheckExpression(expression.Target); - if (boundExpression.Type is NubCustomType customType) + if (boundExpression.Type is CustomTypeNode customType) { var traits = _definitionTable.LookupTrait(customType).ToArray(); if (traits.Length > 0) @@ -384,8 +384,8 @@ public sealed class TypeChecker var returnType = CheckType(traitFunc.Signature.ReturnType); var parameterTypes = traitFunc.Signature.Parameters.Select(p => CheckType(p.Type)).ToList(); - var type = new NubFuncType(parameterTypes, returnType); - return new InterfaceFuncAccess(type, customType, boundExpression, expression.Member); + var type = new FuncTypeNode(parameterTypes, returnType); + return new InterfaceFuncAccessNode(type, customType, boundExpression, expression.Member); } } @@ -409,7 +409,7 @@ public sealed class TypeChecker var field = fields[0]; - return new StructFieldAccess(CheckType(field.Type), customType, boundExpression, expression.Member); + return new StructFieldAccessNode(CheckType(field.Type), customType, boundExpression, expression.Member); } } } @@ -417,11 +417,11 @@ public sealed class TypeChecker throw new CheckException(Diagnostic.Error($"{boundExpression.Type} does not have a member with the name {expression.Member}").Build()); } - private StructInitializer CheckStructInitializer(StructInitializerSyntax expression) + private StructInitializerNode CheckStructInitializer(StructInitializerSyntax expression) { var boundType = CheckType(expression.StructType); - if (boundType is not NubCustomType structType) + if (boundType is not CustomTypeNode structType) { throw new CheckException(Diagnostic.Error($"Cannot initialize non-struct type {expression.StructType}").Build()); } @@ -440,7 +440,7 @@ public sealed class TypeChecker var @struct = structs[0]; - var initializers = new Dictionary(); + var initializers = new Dictionary(); foreach (var (field, initializer) in expression.Initializers) { @@ -459,22 +459,22 @@ public sealed class TypeChecker initializers[field] = CheckExpression(initializer, CheckType(fields[0].Type)); } - return new StructInitializer(structType, initializers); + return new StructInitializerNode(structType, initializers); } - private UnaryExpression CheckUnaryExpression(UnaryExpressionSyntax expression) + private UnaryExpressionNode CheckUnaryExpression(UnaryExpressionSyntax expression) { var boundOperand = CheckExpression(expression.Operand); - NubType? type = null; + TypeNode? type = null; switch (expression.OperatorSyntax) { case UnaryOperatorSyntax.Negate: { - boundOperand = CheckExpression(expression.Operand, new NubIntType(true, 64)); + boundOperand = CheckExpression(expression.Operand, new IntTypeNode(true, 64)); - if (boundOperand.Type is NubIntType or NubFloatType) + if (boundOperand.Type is IntTypeNode or FloatTypeNode) { type = boundOperand.Type; } @@ -483,9 +483,9 @@ public sealed class TypeChecker } case UnaryOperatorSyntax.Invert: { - boundOperand = CheckExpression(expression.Operand, new NubBoolType()); + boundOperand = CheckExpression(expression.Operand, new BoolTypeNode()); - type = new NubBoolType(); + type = new BoolTypeNode(); break; } } @@ -495,19 +495,19 @@ public sealed class TypeChecker throw new NotImplementedException("Diagnostics not implemented"); } - return new UnaryExpression(type, CheckUnaryOperator(expression.OperatorSyntax), boundOperand); + return new UnaryExpressionNode(type, CheckUnaryOperator(expression.OperatorSyntax), boundOperand); } - private FuncSignature CheckFuncSignature(FuncSignatureSyntax node) + private FuncSignatureNode CheckFuncSignature(FuncSignatureSyntax node) { - var parameters = new List(); + var parameters = new List(); foreach (var parameter in node.Parameters) { - parameters.Add(new FuncParameter(parameter.Name, CheckType(parameter.Type))); + parameters.Add(new FuncParameterNode(parameter.Name, CheckType(parameter.Type))); } - return new FuncSignature(parameters, CheckType(node.ReturnType)); + return new FuncSignatureNode(parameters, CheckType(node.ReturnType)); } private BinaryOperator CheckBinaryOperator(BinaryOperatorSyntax op) @@ -538,9 +538,9 @@ public sealed class TypeChecker }; } - private Block CheckBlock(BlockSyntax node, Scope? scope = null) + private BlockNode CheckBlock(BlockSyntax node, Scope? scope = null) { - var statements = new List(); + var statements = new List(); _scopes.Push(scope ?? Scope.SubScope()); @@ -551,10 +551,10 @@ public sealed class TypeChecker _scopes.Pop(); - return new Block(statements); + return new BlockNode(statements); } - private Block CheckFuncBody(BlockSyntax block, NubType returnType, IReadOnlyList parameters) + private BlockNode CheckFuncBody(BlockSyntax block, TypeNode returnType, IReadOnlyList parameters) { _funcReturnTypes.Push(returnType); @@ -569,26 +569,26 @@ public sealed class TypeChecker return body; } - private NubType CheckType(TypeSyntax node) + private TypeNode CheckType(TypeSyntax node) { return node switch { - ArrayTypeSyntax type => new NubArrayType(CheckType(type.BaseType)), - BoolTypeSyntax => new NubBoolType(), - CStringTypeSyntax => new NubCStringType(), - CustomTypeSyntax type => new NubCustomType(type.MangledName()), - FloatTypeSyntax @float => new NubFloatType(@float.Width), - FuncTypeSyntax type => new NubFuncType(type.Parameters.Select(CheckType).ToList(), CheckType(type.ReturnType)), - IntTypeSyntax @int => new NubIntType(@int.Signed, @int.Width), - PointerTypeSyntax type => new NubPointerType(CheckType(type.BaseType)), - StringTypeSyntax => new NubStringType(), - VoidTypeSyntax => new NubVoidType(), + ArrayTypeSyntax type => new ArrayTypeNode(CheckType(type.BaseType)), + BoolTypeSyntax => new BoolTypeNode(), + CStringTypeSyntax => new CStringTypeNode(), + CustomTypeSyntax type => new CustomTypeNode(type.MangledName()), + FloatTypeSyntax @float => new FloatTypeNode(@float.Width), + FuncTypeSyntax type => new FuncTypeNode(type.Parameters.Select(CheckType).ToList(), CheckType(type.ReturnType)), + IntTypeSyntax @int => new IntTypeNode(@int.Signed, @int.Width), + PointerTypeSyntax type => new PointerTypeNode(CheckType(type.BaseType)), + StringTypeSyntax => new NubStringTypeNode(), + VoidTypeSyntax => new VoidTypeNode(), _ => throw new ArgumentOutOfRangeException(nameof(node)) }; } } -public record Variable(string Name, NubType Type); +public record Variable(string Name, TypeNode Type); public class Scope(Scope? parent = null) {