This commit is contained in:
nub31
2025-10-17 23:39:13 +02:00
parent 267da1941d
commit 6671fced57
11 changed files with 32 additions and 186 deletions

View File

@@ -1,3 +1,4 @@
using System.Text;
using NubLang.Ast;
using NubLang.Syntax;
@@ -6,17 +7,16 @@ namespace NubLang.Generation;
public class Generator
{
private readonly List<DefinitionNode> _definitions;
private readonly HashSet<NubStructType> _structTypes;
private readonly IndentedTextWriter _writer;
private readonly Stack<List<DeferNode>> _deferStack = [];
private readonly Stack<(string Name, NubFuncType FuncType)> _funcDefs = [];
private readonly List<NubStructType> _structTypes = [];
private int _tmpIndex;
private int _funcDefIndex;
public Generator(List<DefinitionNode> definitions, HashSet<NubStructType> structTypes)
public Generator(List<DefinitionNode> definitions)
{
_definitions = definitions;
_structTypes = structTypes;
_writer = new IndentedTextWriter();
}
@@ -55,12 +55,18 @@ public class Generator
},
NubPointerType pointerType => MapType(pointerType.BaseType),
NubStringType => throw new NotImplementedException(),
NubStructType structType => StructName(structType.Module, structType.Name),
NubStructType structType => MapStructType(structType),
NubVoidType => "void",
_ => throw new ArgumentOutOfRangeException(nameof(nubType))
};
}
private string MapStructType(NubStructType structType)
{
_structTypes.Add(structType);
return StructName(structType.Module, structType.Name);
}
private string MapFuncType(NubFuncType funcType)
{
var name = $"_func_type_def{++_funcDefIndex}";
@@ -146,21 +152,7 @@ public class Generator
#define U64_C(x) x##ULL
""";
foreach (var structType in _structTypes)
{
_writer.WriteLine("typedef struct");
_writer.WriteLine("{");
using (_writer.Indent())
{
foreach (var field in structType.Fields)
{
_writer.WriteLine($"{MapNameWithType(field.Type, field.Name)};");
}
}
_writer.WriteLine($"}} {StructName(structType.Module, structType.Name)};");
_writer.WriteLine();
}
_writer.WriteLine();
var appendNewLine = false;
@@ -231,7 +223,21 @@ public class Generator
typedefs.Add($"typedef {returnType} (*{funcTypeDef.Name})({paramList});");
}
return header + "\n\n" + string.Join('\n', typedefs) + "\n\n" + _writer;
var structDefSb = new StringBuilder();
foreach (var structType in _structTypes)
{
structDefSb.AppendLine("typedef struct");
structDefSb.AppendLine("{");
foreach (var field in structType.Fields)
{
structDefSb.AppendLine($" {MapNameWithType(field.Type, field.Name)};");
}
structDefSb.AppendLine($"}} {StructName(structType.Module, structType.Name)};");
structDefSb.AppendLine();
}
return header + structDefSb + "\n\n" + string.Join('\n', typedefs) + "\n\n" + _writer;
}
private void EmitStatement(StatementNode statementNode)