From 0d0fc14e61365cb3ecb1c8e8c7fd2faab3ceead8 Mon Sep 17 00:00:00 2001 From: nub31 Date: Thu, 3 Jul 2025 21:49:50 +0200 Subject: [PATCH] QBE writer --- .../Generation/QBE/QBEDebugEmitter.cs | 85 ------ src/compiler/Generation/QBE/QBEGenerator.cs | 241 ++++++++---------- src/compiler/Generation/QBE/QBEWriter.cs | 63 +++++ 3 files changed, 165 insertions(+), 224 deletions(-) delete mode 100644 src/compiler/Generation/QBE/QBEDebugEmitter.cs create mode 100644 src/compiler/Generation/QBE/QBEWriter.cs diff --git a/src/compiler/Generation/QBE/QBEDebugEmitter.cs b/src/compiler/Generation/QBE/QBEDebugEmitter.cs deleted file mode 100644 index e36387b..0000000 --- a/src/compiler/Generation/QBE/QBEDebugEmitter.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System.Text; -using Syntax; -using Syntax.Tokenization; -using Syntax.Typing.BoundNode; - -namespace Generation.QBE; - -public class QBEDebugEmitter -{ - private readonly StringBuilder _builder; - private int _currentLine = -1; - private readonly Dictionary _fileMap = new(); - private int _nextFileId = 0; - - public QBEDebugEmitter(StringBuilder builder) - { - _builder = builder; - } - - public int RegisterFile(string fileName) - { - if (_fileMap.TryGetValue(fileName, out var existingId)) - { - return existingId; - } - - var fileId = _nextFileId++; - _fileMap[fileName] = fileId; - - _builder.AppendLine($"# Debug file {fileId}: {fileName}"); - - return fileId; - } - - public void EmitDebugLocation(SourceSpan span) - { - if (span.IsEmpty) - return; - - var line = span.Start.Line; - - if (_currentLine != line) - { - _builder.AppendLine($" dbgloc {line}"); - _currentLine = line; - } - } - - public void EmitDebugLocation(Token token) - { - EmitDebugLocation(token.Span); - } - - public void EmitDebugLocation(BoundNode node) - { - var firstToken = node.Tokens.FirstOrDefault(); - if (firstToken != null) - { - EmitDebugLocation(firstToken); - } - } - - public void EmitDebugLocation(IEnumerable tokens) - { - var firstToken = tokens.FirstOrDefault(); - if (firstToken != null) - { - EmitDebugLocation(firstToken); - } - } - - public void ForceEmitDebugLocation(SourceSpan span) - { - if (!span.IsEmpty) - { - _builder.AppendLine($" dbgloc {span.Start.Line}"); - _currentLine = span.Start.Line; - } - } - - public void ResetLineTracker() - { - _currentLine = -1; - } -} \ No newline at end of file diff --git a/src/compiler/Generation/QBE/QBEGenerator.cs b/src/compiler/Generation/QBE/QBEGenerator.cs index f900c46..9cea4c9 100644 --- a/src/compiler/Generation/QBE/QBEGenerator.cs +++ b/src/compiler/Generation/QBE/QBEGenerator.cs @@ -15,9 +15,7 @@ public static class QBEGenerator private static BoundSyntaxTree _syntaxTree = null!; private static BoundDefinitionTable _definitionTable = null!; - private static QBEDebugEmitter _debugEmitter = null!; - - private static StringBuilder _builder = new(); + private static QBEWriter _writer = new(); private static List _cStringLiterals = []; private static List _stringLiterals = []; private static Stack _breakLabels = []; @@ -37,8 +35,7 @@ public static class QBEGenerator _syntaxTree = syntaxTree; _definitionTable = definitionTable; - _builder = new StringBuilder(); - _debugEmitter = new QBEDebugEmitter(_builder); + _writer = new QBEWriter(); _cStringLiterals = []; _stringLiterals = []; @@ -54,39 +51,39 @@ public static class QBEGenerator _stringLiteralIndex = 0; _codeIsReachable = true; - _builder.AppendLine($"dbgfile \"{file}\""); - _builder.AppendLine(); + _writer.WriteLine($"dbgfile \"{file}\""); + _writer.WriteLine(); foreach (var structDef in _definitionTable.GetStructs()) { EmitStructDefinition(structDef); - _builder.AppendLine(); + _writer.WriteLine(); } foreach (var funcDef in _syntaxTree.Definitions.OfType()) { EmitFuncDefinition(funcDef, FuncName(funcDef), funcDef.Parameters, funcDef.ReturnType, funcDef.Body, funcDef.Exported); - _builder.AppendLine(); + _writer.WriteLine(); } while (_anonymousFunctions.TryDequeue(out var anon)) { EmitFuncDefinition(anon.Func, anon.Name, anon.Func.Parameters, anon.Func.ReturnType, anon.Func.Body, false); - _builder.AppendLine(); + _writer.WriteLine(); } foreach (var cStringLiteral in _cStringLiterals) { - _builder.AppendLine($"data {cStringLiteral.Name} = {{ b \"{cStringLiteral.Value}\", b 0 }}"); + _writer.WriteLine($"data {cStringLiteral.Name} = {{ b \"{cStringLiteral.Value}\", b 0 }}"); } foreach (var stringLiteral in _stringLiterals) { var bytes = Encoding.UTF8.GetBytes(stringLiteral.Value).Select(b => $"b {b}"); - _builder.AppendLine($"data {stringLiteral.Name} = {{ l {stringLiteral.Value.Length}, {string.Join(", ", bytes)} }}"); + _writer.WriteLine($"data {stringLiteral.Name} = {{ l {stringLiteral.Value.Length}, {string.Join(", ", bytes)} }}"); } - return _builder.ToString(); + return _writer.ToString(); } private static string VarName() @@ -144,7 +141,7 @@ public static class QBEGenerator _ => throw new NotSupportedException($"'{type}' type cannot be used in store instructions") }; - _builder.AppendLine($" {store} {value}, {destination}"); + _writer.WriteLine($" {store} {value}, {destination}"); } private static Val EmitLoad(NubType type, string from) @@ -168,38 +165,38 @@ public static class QBEGenerator _ => throw new NotSupportedException($"'{type}' type cannot be used in load instructions") }; - _builder.AppendLine($" {into} {QBEAssign(type)} {load} {from}"); + _writer.WriteLine($" {into} {QBEAssign(type)} {load} {from}"); return new Val(into, type, ValKind.Direct); } private static void EmitMemcpy(string source, string destination, string length) { - _builder.AppendLine($" call $nub_memcpy(l {source}, l {destination}, l {length})"); + _writer.WriteLine($" call $nub_memcpy(l {source}, l {destination}, l {length})"); } private static string EmitArraySizeInBytes(NubArrayType type, string array) { var size = VarName(); - _builder.AppendLine($" {size} =l loadl {array}"); - _builder.AppendLine($" {size} =l mul {size}, {SizeOf(type.ElementType)}"); - _builder.AppendLine($" {size} =l add {size}, 8"); + _writer.WriteLine($" {size} =l loadl {array}"); + _writer.WriteLine($" {size} =l mul {size}, {SizeOf(type.ElementType)}"); + _writer.WriteLine($" {size} =l add {size}, 8"); return size; } private static string EmitCStringSizeInBytes(string cstring) { var size = VarName(); - _builder.AppendLine($" {size} =l call $nub_cstring_length(l {cstring})"); - _builder.AppendLine($" {size} =l add {size}, 1"); + _writer.WriteLine($" {size} =l call $nub_cstring_length(l {cstring})"); + _writer.WriteLine($" {size} =l add {size}, 1"); return size; } private static string EmitStringSizeInBytes(string nubstring) { var size = VarName(); - _builder.AppendLine($" {size} =l loadl {nubstring}"); - _builder.AppendLine($" {size} =l add {size}, 8"); + _writer.WriteLine($" {size} =l loadl {nubstring}"); + _writer.WriteLine($" {size} =l add {size}, 8"); return size; } @@ -257,7 +254,7 @@ public static class QBEGenerator case NubStringType: { var buffer = VarName(); - _builder.AppendLine($" {buffer} =l alloc8 {size}"); + _writer.WriteLine($" {buffer} =l alloc8 {size}"); EmitMemcpy(value, buffer, size); EmitStore(source.Type, buffer, destinationPointer); return; @@ -327,7 +324,7 @@ public static class QBEGenerator _ => throw new ArgumentOutOfRangeException(nameof(complexType)) }; - _builder.AppendLine($" {destination} =l alloc8 {size}"); + _writer.WriteLine($" {destination} =l alloc8 {size}"); EmitMemcpy(value, destination, size); return destination; } @@ -465,20 +462,22 @@ public static class QBEGenerator private static void EmitFuncDefinition(BoundNode debugNode, string name, List parameters, NubType returnType, BoundBlockNode body, bool exported) { - _debugEmitter.ResetLineTracker(); - + _writer.ResetLineTracker(); + _variables.Clear(); _variableScopes.Clear(); + var builder = new StringBuilder(); + if (exported) { - _builder.Append("export "); + builder.Append("export "); } - _builder.Append("function "); + builder.Append("function "); if (returnType is not NubVoidType) { - _builder.Append(returnType switch + builder.Append(returnType switch { NubPrimitiveType primitiveType => primitiveType.Kind switch { @@ -496,10 +495,10 @@ public static class QBEGenerator 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(' '); } - _builder.Append(name); + builder.Append(name); var parameterStrings = parameters.Select(parameter => { @@ -525,10 +524,10 @@ public static class QBEGenerator return $"{qbeType} %{parameter.Name}"; }); - _builder.AppendLine($"({string.Join(", ", parameterStrings)}) {{"); - _builder.AppendLine("@start"); - - _debugEmitter.EmitDebugLocation(debugNode); + builder.Append($"({string.Join(", ", parameterStrings)}) {{"); + + _writer.WriteLine(builder.ToString()); + _writer.WriteLine("@start"); List parameterVars = []; @@ -542,19 +541,19 @@ public static class QBEGenerator { case PrimitiveTypeKind.I16: parameterName = VarName(); - _builder.AppendLine($" {parameterName} =w extsh %{parameter.Name}"); + _writer.WriteLine($" {parameterName} =w extsh %{parameter.Name}"); break; case PrimitiveTypeKind.I8: parameterName = VarName(); - _builder.AppendLine($" {parameterName} =w extsb %{parameter.Name}"); + _writer.WriteLine($" {parameterName} =w extsb %{parameter.Name}"); break; case PrimitiveTypeKind.U16: parameterName = VarName(); - _builder.AppendLine($" {parameterName} =w extuh %{parameter.Name}"); + _writer.WriteLine($" {parameterName} =w extuh %{parameter.Name}"); break; case PrimitiveTypeKind.U8: parameterName = VarName(); - _builder.AppendLine($" {parameterName} =w extub %{parameter.Name}"); + _writer.WriteLine($" {parameterName} =w extub %{parameter.Name}"); break; } } @@ -568,16 +567,18 @@ public static class QBEGenerator { if (returnType is NubVoidType) { - _builder.AppendLine(" ret"); + _writer.WriteLine(" ret"); } } - _builder.AppendLine("}"); + _writer.WriteLine("}"); } private static void EmitStructDefinition(BoundStructDefinitionNode structDefinition) { - _builder.Append($"type {StructName(structDefinition)} = {{ "); + var builder = new StringBuilder(); + + builder.Append($"type {StructName(structDefinition)} = {{ "); foreach (var structDefinitionField in structDefinition.Fields) { var qbeType = structDefinitionField.Type switch @@ -596,10 +597,12 @@ public static class QBEGenerator NubArrayType or NubPointerType or NubFuncType or NubCStringType or NubStringType => "l", _ => throw new NotSupportedException($"'{structDefinitionField.Type}' type cannot be used in structs") }; - _builder.Append(qbeType + ", "); + builder.Append(qbeType + ", "); } - _builder.AppendLine("}"); + builder.Append("}"); + + _writer.WriteLine(builder.ToString()); } private static void EmitStatement(BoundStatementNode statement) @@ -637,8 +640,6 @@ public static class QBEGenerator private static void EmitAssignment(BoundAssignmentNode assignment) { - _debugEmitter.EmitDebugLocation(assignment); - var destination = EmitExpression(assignment.Expression); Debug.Assert(destination.Kind == ValKind.Pointer); EmitCopyIntoOrInitialize(assignment.Value, destination.Name); @@ -646,8 +647,6 @@ public static class QBEGenerator private static void EmitBlock(BoundBlockNode block, List? variables = null) { - _debugEmitter.EmitDebugLocation(block); - _variableScopes.Push(_variables.Count); if (variables != null) { @@ -673,34 +672,28 @@ public static class QBEGenerator private static void EmitBreak(BoundBreakNode @break) { - _debugEmitter.EmitDebugLocation(@break); - - _builder.AppendLine($" jmp {_breakLabels.Peek()}"); + _writer.WriteLine($" jmp {_breakLabels.Peek()}"); _codeIsReachable = false; } private static void EmitContinue(BoundContinueNode @continue) { - _debugEmitter.EmitDebugLocation(@continue); - - _builder.AppendLine($" jmp {_continueLabels.Peek()}"); + _writer.WriteLine($" jmp {_continueLabels.Peek()}"); _codeIsReachable = false; } private static void EmitIf(BoundIfNode ifStatement) { - _debugEmitter.EmitDebugLocation(ifStatement); - var trueLabel = LabelName(); var falseLabel = LabelName(); var endLabel = LabelName(); var result = EmitUnwrap(EmitExpression(ifStatement.Condition)); - _builder.AppendLine($" jnz {result}, {trueLabel}, {falseLabel}"); - _builder.AppendLine(trueLabel); + _writer.WriteLine($" jnz {result}, {trueLabel}, {falseLabel}"); + _writer.WriteLine(trueLabel); EmitBlock(ifStatement.Body); - _builder.AppendLine($" jmp {endLabel}"); - _builder.AppendLine(falseLabel); + _writer.WriteLine($" jmp {endLabel}"); + _writer.WriteLine(falseLabel); if (ifStatement.Else.HasValue) { ifStatement.Else.Value.Match @@ -710,30 +703,26 @@ public static class QBEGenerator ); } - _builder.AppendLine(endLabel); + _writer.WriteLine(endLabel); } private static void EmitReturn(BoundReturnNode @return) { - _debugEmitter.EmitDebugLocation(@return); - if (@return.Value.HasValue) { var result = EmitUnwrap(EmitExpression(@return.Value.Value)); - _builder.AppendLine($" ret {result}"); + _writer.WriteLine($" ret {result}"); } else { - _builder.AppendLine(" ret"); + _writer.WriteLine(" ret"); } } private static void EmitVariableDeclaration(BoundVariableDeclarationNode variableDeclaration) { - _debugEmitter.EmitDebugLocation(variableDeclaration); - var variable = VarName(); - _builder.AppendLine($" {variable} =l alloc8 {SizeOf(variableDeclaration.Type)}"); + _writer.WriteLine($" {variable} =l alloc8 {SizeOf(variableDeclaration.Type)}"); if (variableDeclaration.Assignment.HasValue) { @@ -745,8 +734,6 @@ public static class QBEGenerator private static void EmitWhile(BoundWhileNode whileStatement) { - _debugEmitter.EmitDebugLocation(whileStatement); - var conditionLabel = LabelName(); var iterationLabel = LabelName(); var endLabel = LabelName(); @@ -754,13 +741,13 @@ public static class QBEGenerator _breakLabels.Push(endLabel); _continueLabels.Push(conditionLabel); - _builder.AppendLine($" jmp {conditionLabel}"); - _builder.AppendLine(iterationLabel); + _writer.WriteLine($" jmp {conditionLabel}"); + _writer.WriteLine(iterationLabel); EmitBlock(whileStatement.Body); - _builder.AppendLine(conditionLabel); + _writer.WriteLine(conditionLabel); var result = EmitUnwrap(EmitExpression(whileStatement.Condition)); - _builder.AppendLine($" jnz {result}, {iterationLabel}, {endLabel}"); - _builder.AppendLine(endLabel); + _writer.WriteLine($" jnz {result}, {iterationLabel}, {endLabel}"); + _writer.WriteLine(endLabel); _continueLabels.Pop(); _breakLabels.Pop(); @@ -788,8 +775,6 @@ public static class QBEGenerator private static Val EmitAnonymousFunc(BoundAnonymousFuncNode anonymousFunc) { - _debugEmitter.EmitDebugLocation(anonymousFunc); - var name = $"$anon_func{++_anonymousFuncIndex}"; _anonymousFunctions.Enqueue((anonymousFunc, name)); return new Val(name, anonymousFunc.Type, ValKind.Direct); @@ -797,71 +782,65 @@ public static class QBEGenerator private static Val EmitArrayIndexAccess(BoundArrayIndexAccessNode arrayIndexAccess) { - _debugEmitter.EmitDebugLocation(arrayIndexAccess); - var array = EmitUnwrap(EmitExpression(arrayIndexAccess.Array)); var index = EmitUnwrap(EmitExpression(arrayIndexAccess.Index)); var elementType = ((NubArrayType)arrayIndexAccess.Array.Type).ElementType; var pointer = VarName(); - _builder.AppendLine($" {pointer} =l mul {index}, {SizeOf(elementType)}"); - _builder.AppendLine($" {pointer} =l add {pointer}, 8"); - _builder.AppendLine($" {pointer} =l add {array}, {pointer}"); + _writer.WriteLine($" {pointer} =l mul {index}, {SizeOf(elementType)}"); + _writer.WriteLine($" {pointer} =l add {pointer}, 8"); + _writer.WriteLine($" {pointer} =l add {array}, {pointer}"); return new Val(pointer, arrayIndexAccess.Type, ValKind.Pointer); } private static void EmitArrayBoundsCheck(string array, string index) { var count = VarName(); - _builder.AppendLine($" {count} =l loadl {array}"); + _writer.WriteLine($" {count} =l loadl {array}"); var isNegative = VarName(); - _builder.AppendLine($" {isNegative} =w csltl {index}, 0"); + _writer.WriteLine($" {isNegative} =w csltl {index}, 0"); var isOob = VarName(); - _builder.AppendLine($" {isOob} =w csgel {index}, {count}"); + _writer.WriteLine($" {isOob} =w csgel {index}, {count}"); var anyOob = VarName(); - _builder.AppendLine($" {anyOob} =w or {isNegative}, {isOob}"); + _writer.WriteLine($" {anyOob} =w or {isNegative}, {isOob}"); var oobLabel = LabelName(); var notOobLabel = LabelName(); - _builder.AppendLine($" jnz {anyOob}, {oobLabel}, {notOobLabel}"); + _writer.WriteLine($" jnz {anyOob}, {oobLabel}, {notOobLabel}"); - _builder.AppendLine(oobLabel); - _builder.AppendLine($" call $nub_panic_array_oob()"); + _writer.WriteLine(oobLabel); + _writer.WriteLine($" call $nub_panic_array_oob()"); - _builder.AppendLine(notOobLabel); + _writer.WriteLine(notOobLabel); } private static Val EmitArrayInitializer(BoundArrayInitializerNode arrayInitializer) { - _debugEmitter.EmitDebugLocation(arrayInitializer); - var capacity = EmitUnwrap(EmitExpression(arrayInitializer.Capacity)); var elementSize = SizeOf(arrayInitializer.ElementType); var capacityInBytes = VarName(); - _builder.AppendLine($" {capacityInBytes} =l mul {capacity}, {elementSize}"); + _writer.WriteLine($" {capacityInBytes} =l mul {capacity}, {elementSize}"); var totalSize = VarName(); - _builder.AppendLine($" {totalSize} =l add {capacityInBytes}, 8"); + _writer.WriteLine($" {totalSize} =l add {capacityInBytes}, 8"); var arrayPointer = VarName(); - _builder.AppendLine($" {arrayPointer} =l alloc8 {totalSize}"); - _builder.AppendLine($" storel {capacity}, {arrayPointer}"); + _writer.WriteLine($" {arrayPointer} =l alloc8 {totalSize}"); + _writer.WriteLine($" storel {capacity}, {arrayPointer}"); var dataPointer = VarName(); - _builder.AppendLine($" {dataPointer} =l add {arrayPointer}, 8"); - _builder.AppendLine($" call $nub_memset(l {dataPointer}, w 0, l {capacityInBytes})"); + _writer.WriteLine($" {dataPointer} =l add {arrayPointer}, 8"); + _writer.WriteLine($" call $nub_memset(l {dataPointer}, w 0, l {capacityInBytes})"); return new Val(arrayPointer, arrayInitializer.Type, ValKind.Direct); } private static Val EmitDereference(BoundDereferenceNode dereference) { - _debugEmitter.EmitDebugLocation(dereference); - var pointerType = (NubPointerType)dereference.Expression.Type; var pointer = EmitExpression(dereference.Expression); @@ -877,8 +856,6 @@ public static class QBEGenerator private static Val EmitAddressOf(BoundAddressOfNode addressOf) { - _debugEmitter.EmitDebugLocation(addressOf); - var value = EmitExpression(addressOf.Expression); Debug.Assert(value.Kind == ValKind.Pointer); return new Val(value.Name, addressOf.Type, ValKind.Direct); @@ -886,8 +863,6 @@ public static class QBEGenerator private static Val EmitBinaryExpression(BoundBinaryExpressionNode binaryExpression) { - _debugEmitter.EmitDebugLocation(binaryExpression); - var left = EmitUnwrap(EmitExpression(binaryExpression.Left)); var right = EmitUnwrap(EmitExpression(binaryExpression.Right)); @@ -895,7 +870,7 @@ public static class QBEGenerator var instruction = EmitBinaryInstructionFor(binaryExpression.Operator, binaryExpression.Left.Type, left, right); - _builder.AppendLine($" {outputName} {QBEAssign(binaryExpression.Left.Type)} {instruction} {left}, {right}"); + _writer.WriteLine($" {outputName} {QBEAssign(binaryExpression.Left.Type)} {instruction} {left}, {right}"); return new Val(outputName, binaryExpression.Type, ValKind.Direct); } @@ -915,13 +890,13 @@ public static class QBEGenerator { if (type.IsSignedInteger) { - _builder.AppendLine($" {left} =w extsb {left}"); - _builder.AppendLine($" {right} =w extsb {right}"); + _writer.WriteLine($" {left} =w extsb {left}"); + _writer.WriteLine($" {right} =w extsb {right}"); } else { - _builder.AppendLine($" {left} =w extub {left}"); - _builder.AppendLine($" {right} =w extub {right}"); + _writer.WriteLine($" {left} =w extub {left}"); + _writer.WriteLine($" {right} =w extub {right}"); } suffix = 'w'; @@ -930,13 +905,13 @@ public static class QBEGenerator { if (type.IsSignedInteger) { - _builder.AppendLine($" {left} =w extsh {left}"); - _builder.AppendLine($" {right} =w extsh {right}"); + _writer.WriteLine($" {left} =w extsh {left}"); + _writer.WriteLine($" {right} =w extsh {right}"); } else { - _builder.AppendLine($" {left} =w extuh {left}"); - _builder.AppendLine($" {right} =w extuh {right}"); + _writer.WriteLine($" {left} =w extuh {left}"); + _writer.WriteLine($" {right} =w extuh {right}"); } suffix = 'w'; @@ -1005,8 +980,6 @@ public static class QBEGenerator private static Val EmitIdentifier(BoundIdentifierNode identifier) { - _debugEmitter.EmitDebugLocation(identifier); - if (_definitionTable.LookupFunc(identifier.Namespace.Or(_syntaxTree.Namespace), identifier.Name).TryGetValue(out var func)) { return new Val(FuncName(func), identifier.Type, ValKind.Direct); @@ -1022,8 +995,6 @@ public static class QBEGenerator private static Val EmitLiteral(BoundLiteralNode literal) { - _debugEmitter.EmitDebugLocation(literal); - switch (literal.Kind) { case LiteralKind.Integer: @@ -1106,15 +1077,13 @@ public static class QBEGenerator private static Val EmitStructInitializer(BoundStructInitializerNode structInitializer, string? destination = null) { - _debugEmitter.EmitDebugLocation(structInitializer); - var structDefinition = _definitionTable.LookupStruct(structInitializer.StructType.Namespace, structInitializer.StructType.Name).GetValue(); if (destination == null) { destination = VarName(); var size = SizeOf(structInitializer.StructType); - _builder.AppendLine($" {destination} =l alloc8 {size}"); + _writer.WriteLine($" {destination} =l alloc8 {size}"); } foreach (var field in structDefinition.Fields) @@ -1127,7 +1096,7 @@ public static class QBEGenerator Debug.Assert(valueExpression != null); var offset = VarName(); - _builder.AppendLine($" {offset} =l add {destination}, {OffsetOf(structDefinition, field.Name)}"); + _writer.WriteLine($" {offset} =l add {destination}, {OffsetOf(structDefinition, field.Name)}"); EmitCopyIntoOrInitialize(valueExpression, offset); } @@ -1136,8 +1105,6 @@ public static class QBEGenerator private static Val EmitUnaryExpression(BoundUnaryExpressionNode unaryExpression) { - _debugEmitter.EmitDebugLocation(unaryExpression); - var operand = EmitUnwrap(EmitExpression(unaryExpression.Operand)); var outputName = VarName(); @@ -1148,16 +1115,16 @@ public static class QBEGenerator switch (unaryExpression.Operand.Type) { case NubPrimitiveType { Kind: PrimitiveTypeKind.I64 }: - _builder.AppendLine($" {outputName} =l neg {operand}"); + _writer.WriteLine($" {outputName} =l neg {operand}"); return new Val(outputName, unaryExpression.Type, ValKind.Direct); case NubPrimitiveType { Kind: PrimitiveTypeKind.I32 or PrimitiveTypeKind.I16 or PrimitiveTypeKind.I8 }: - _builder.AppendLine($" {outputName} =w neg {operand}"); + _writer.WriteLine($" {outputName} =w neg {operand}"); return new Val(outputName, unaryExpression.Type, ValKind.Direct); case NubPrimitiveType { Kind: PrimitiveTypeKind.F64 }: - _builder.AppendLine($" {outputName} =d neg {operand}"); + _writer.WriteLine($" {outputName} =d neg {operand}"); return new Val(outputName, unaryExpression.Type, ValKind.Direct); case NubPrimitiveType { Kind: PrimitiveTypeKind.F32 }: - _builder.AppendLine($" {outputName} =s neg {operand}"); + _writer.WriteLine($" {outputName} =s neg {operand}"); return new Val(outputName, unaryExpression.Type, ValKind.Direct); } @@ -1168,7 +1135,7 @@ public static class QBEGenerator switch (unaryExpression.Operand.Type) { case NubPrimitiveType { Kind: PrimitiveTypeKind.Bool }: - _builder.AppendLine($" {outputName} =w xor {operand}, 1"); + _writer.WriteLine($" {outputName} =w xor {operand}, 1"); return new Val(outputName, unaryExpression.Type, ValKind.Direct); } @@ -1185,8 +1152,6 @@ public static class QBEGenerator private static Val EmitMemberAccess(BoundMemberAccessNode memberAccess) { - _debugEmitter.EmitDebugLocation(memberAccess); - var item = EmitUnwrap(EmitExpression(memberAccess.Expression)); var output = VarName(); @@ -1196,7 +1161,7 @@ public static class QBEGenerator { if (memberAccess.Member == "count") { - _builder.AppendLine($" {output} =l loadl {item}"); + _writer.WriteLine($" {output} =l loadl {item}"); return new Val(output, memberAccess.Type, ValKind.Direct); } @@ -1206,7 +1171,7 @@ public static class QBEGenerator { if (memberAccess.Member == "count") { - _builder.AppendLine($" {output} =l call $nub_string_length(l {item})"); + _writer.WriteLine($" {output} =l call $nub_string_length(l {item})"); return new Val(output, memberAccess.Type, ValKind.Direct); } @@ -1216,7 +1181,7 @@ public static class QBEGenerator { if (memberAccess.Member == "count") { - _builder.AppendLine($" {output} =l call $nub_cstring_length(l {item})"); + _writer.WriteLine($" {output} =l call $nub_cstring_length(l {item})"); return new Val(output, memberAccess.Type, ValKind.Direct); } @@ -1227,7 +1192,7 @@ public static class QBEGenerator var structDefinition = _definitionTable.LookupStruct(structType.Namespace, structType.Name).GetValue(); var offset = OffsetOf(structDefinition, memberAccess.Member); - _builder.AppendLine($" {output} =l add {item}, {offset}"); + _writer.WriteLine($" {output} =l add {item}, {offset}"); return new Val(output, memberAccess.Type, ValKind.Pointer); } } @@ -1237,8 +1202,6 @@ public static class QBEGenerator private static Val EmitFuncCall(BoundFuncCallNode funcCall) { - _debugEmitter.EmitDebugLocation(funcCall); - var funcType = (NubFuncType)funcCall.Expression.Type; var parameterStrings = new List(); @@ -1274,12 +1237,12 @@ public static class QBEGenerator { var outputName = VarName(); - _builder.AppendLine($" {outputName} {QBEAssign(funcCall.Type)} call {funcPointer}({string.Join(", ", parameterStrings)})"); + _writer.WriteLine($" {outputName} {QBEAssign(funcCall.Type)} call {funcPointer}({string.Join(", ", parameterStrings)})"); return new Val(outputName, funcCall.Type, ValKind.Direct); } else { - _builder.AppendLine($" call {funcPointer}({string.Join(", ", parameterStrings)})"); + _writer.WriteLine($" call {funcPointer}({string.Join(", ", parameterStrings)})"); return new Val(string.Empty, funcCall.Type, ValKind.Direct); } } diff --git a/src/compiler/Generation/QBE/QBEWriter.cs b/src/compiler/Generation/QBE/QBEWriter.cs new file mode 100644 index 0000000..8103f14 --- /dev/null +++ b/src/compiler/Generation/QBE/QBEWriter.cs @@ -0,0 +1,63 @@ +using System.Text; +using Syntax; +using Syntax.Typing.BoundNode; + +namespace Generation.QBE; + +public class QBEWriter +{ + private int _currentLine = -1; + private readonly StringBuilder _builder = new(); + + public void ResetLineTracker() + { + _currentLine = -1; + } + + private void WriteDebugLocation(SourceSpan span) + { + if (span.IsEmpty) + return; + + var line = span.Start.Line; + + if (_currentLine != line) + { + _builder.AppendLine($" dbgloc {line}"); + _currentLine = line; + } + } + + private void WriteDebugLocation(BoundNode node) + { + var firstToken = node.Tokens.FirstOrDefault(); + if (firstToken != null) + { + WriteDebugLocation(firstToken.Span); + } + } + + public QBEWriter WriteLine(BoundNode node, string value) + { + WriteDebugLocation(node); + WriteLine(value); + return this; + } + + public QBEWriter WriteLine(string value) + { + _builder.AppendLine(value); + return this; + } + + public QBEWriter WriteLine() + { + _builder.AppendLine(); + return this; + } + + public override string ToString() + { + return _builder.ToString(); + } +} \ No newline at end of file