Files
nub-lang/compiler/Generator.cs
nub31 da2fa81c39 ...
2026-02-28 02:27:44 +01:00

851 lines
31 KiB
C#

using System.Diagnostics;
using System.Text;
namespace Compiler;
public class Generator
{
public static string Emit(List<TypedNodeDefinitionFunc> functions, ModuleGraph moduleGraph, string? entryPoint)
{
return new Generator(functions, moduleGraph, entryPoint).Emit();
}
private Generator(List<TypedNodeDefinitionFunc> functions, ModuleGraph moduleGraph, string? entryPoint)
{
this.functions = functions;
this.moduleGraph = moduleGraph;
this.entryPoint = entryPoint;
}
private readonly List<TypedNodeDefinitionFunc> functions;
private readonly ModuleGraph moduleGraph;
private readonly string? entryPoint;
private IndentedTextWriter writer = new();
private HashSet<NubType> referencedTypes = new();
private readonly HashSet<NubType> emittedTypes = new();
private readonly Stack<Scope> scopes = new();
private int tmpNameIndex = 0;
private string Emit()
{
if (entryPoint != null)
{
writer.WriteLine($$"""
int main(int argc, char *argv[])
{
return {{entryPoint}}();
}
""");
writer.WriteLine();
}
foreach (var function in functions)
{
if (!moduleGraph.TryResolveIdentifier(function.Module, function.Name.Ident, true, out var info))
throw new UnreachableException($"Module graph does not have info about the function {function.Module}::{function.Name.Ident}. This should have been caught earlier");
if (info.Source == Module.DefinitionSource.Imported || info.Extern)
writer.Write("extern ");
else if (info.Source == Module.DefinitionSource.Internal && !info.Extern && !info.Exported)
writer.Write("static ");
var parameters = function.Parameters.Select(x => CType(x.Type, x.Name.Ident));
writer.WriteLine($"{CType(function.ReturnType, info.MangledName)}({string.Join(", ", parameters)})");
writer.WriteLine("{");
using (writer.Indent())
{
PushScope();
EmitStatement(function.Body);
PopScope();
}
writer.WriteLine("}");
writer.WriteLine();
}
var implementations = writer.ToString();
writer = new IndentedTextWriter();
foreach (var module in moduleGraph.GetModules())
{
foreach (var (name, info) in module.GetIdentifiers())
{
if (info.Source == Module.DefinitionSource.Internal || info.Exported)
{
if (info.Source == Module.DefinitionSource.Imported || info.Extern)
writer.Write("extern ");
else if (info.Source == Module.DefinitionSource.Internal && !info.Extern && !info.Exported)
writer.Write("static ");
if (info.Type is NubTypeFunc fn)
writer.WriteLine($"{CType(fn.ReturnType, info.MangledName)}({string.Join(", ", fn.Parameters.Select(p => CType(p)))});");
else
writer.WriteLine($"{CType(info.Type, info.MangledName)};");
}
}
}
var declarations = writer.ToString();
writer = new IndentedTextWriter();
writer.WriteLine($$"""
#include <float.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
""");
while (referencedTypes.Count != 0)
{
var type = referencedTypes.ElementAt(0);
EmitTypeDefinitionIfNotEmitted(type);
referencedTypes.Remove(type);
}
var header = writer.ToString();
return $"{header}\n{declarations}\n{implementations}";
}
private void EmitTypeDefinitionIfNotEmitted(NubType type)
{
if (emittedTypes.Contains(type))
return;
emittedTypes.Add(type);
switch (type)
{
case NubTypeString stringType:
{
writer.WriteLine($"struct {NameMangler.Mangle("core", "string", stringType)}");
writer.WriteLine("{");
using (writer.Indent())
{
writer.WriteLine("char *data;");
writer.WriteLine("size_t length;");
writer.WriteLine("int32_t ref;");
writer.WriteLine("uint32_t flags;");
}
writer.WriteLine("};");
writer.WriteLine();
writer.WriteLine("#define FLAG_STRING_LITERAL 1");
writer.WriteLine();
writer.WriteLine($"static inline void rc_inc({CType(NubTypeString.Instance, "string")})");
writer.WriteLine("{");
using (writer.Indent())
{
writer.WriteLine($"string->ref += 1;");
}
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine($"static inline void rc_dec({CType(NubTypeString.Instance, "string")})");
writer.WriteLine("{");
using (writer.Indent())
{
writer.WriteLine($"string->ref -= 1;");
writer.WriteLine($"if (string->ref <= 0)");
writer.WriteLine("{");
using (writer.Indent())
{
writer.WriteLine($"if ((string->flags & FLAG_STRING_LITERAL) == 0)");
writer.WriteLine("{");
using (writer.Indent())
{
writer.WriteLine($"free(string->data);");
}
writer.WriteLine("}");
writer.WriteLine($"free(string);");
}
writer.WriteLine("}");
}
writer.WriteLine("}");
writer.WriteLine();
break;
}
case NubTypeStruct structType:
{
if (!moduleGraph.TryResolveType(structType.Module, structType.Name, true, out var info) || info is not Module.TypeInfoStruct structInfo)
throw new UnreachableException();
foreach (var field in structInfo.Fields)
EmitTypeDefinitionIfNotEmitted(field.Type);
writer.Write("struct ");
if (structInfo.Packed)
writer.Write("__attribute__((__packed__)) ");
writer.WriteLine(NameMangler.Mangle(structType.Module, structType.Name, structType));
writer.WriteLine("{");
using (writer.Indent())
{
foreach (var field in structInfo.Fields)
{
writer.WriteLine($"{CType(field.Type, field.Name)};");
}
}
writer.WriteLine("};");
writer.WriteLine();
break;
}
case NubTypeAnonymousStruct anonymousStructType:
{
foreach (var field in anonymousStructType.Fields)
EmitTypeDefinitionIfNotEmitted(field.Type);
writer.WriteLine($"struct {NameMangler.Mangle("anonymous", "struct", anonymousStructType)}");
writer.WriteLine("{");
using (writer.Indent())
{
foreach (var field in anonymousStructType.Fields)
{
writer.WriteLine($"{CType(field.Type, field.Name)};");
}
}
writer.WriteLine("};");
writer.WriteLine();
break;
}
case NubTypeEnum enumType:
{
if (!moduleGraph.TryResolveType(enumType.Module, enumType.Name, true, out var info) || info is not Module.TypeInfoEnum enumInfo)
throw new UnreachableException();
foreach (var variant in enumInfo.Variants)
EmitTypeDefinitionIfNotEmitted(variant.Type);
writer.WriteLine($"struct {NameMangler.Mangle(enumType.Module, enumType.Name, enumType)}");
writer.WriteLine("{");
using (writer.Indent())
{
writer.WriteLine("uint32_t tag;");
writer.WriteLine("union");
writer.WriteLine("{");
using (writer.Indent())
{
foreach (var variant in enumInfo.Variants)
{
writer.WriteLine($"{CType(variant.Type, variant.Name)};");
}
}
writer.WriteLine("};");
}
writer.WriteLine("};");
writer.WriteLine();
break;
}
case NubTypeEnumVariant variantType:
{
EmitTypeDefinitionIfNotEmitted(variantType.EnumType);
break;
}
}
}
private void EmitStatement(TypedNodeStatement node)
{
if (scopes.Peek().Unreachable)
return;
switch (node)
{
case TypedNodeStatementBlock statement:
EmitStatementBlock(statement);
break;
case TypedNodeStatementFuncCall statement:
EmitStatementFuncCall(statement);
break;
case TypedNodeStatementReturn statement:
EmitStatementReturn(statement);
break;
case TypedNodeStatementVariableDeclaration statement:
EmitStatementVariableDeclaration(statement);
break;
case TypedNodeStatementAssignment statement:
EmitStatementAssignment(statement);
break;
case TypedNodeStatementIf statement:
EmitStatementIf(statement);
break;
case TypedNodeStatementWhile statement:
EmitStatementWhile(statement);
break;
case TypedNodeStatementMatch statement:
EmitStatementMatch(statement);
break;
default:
throw new ArgumentOutOfRangeException(nameof(node), node, null);
}
}
private void EmitStatementBlock(TypedNodeStatementBlock node)
{
writer.WriteLine("{");
using (writer.Indent())
{
PushScope();
foreach (var statement in node.Statements)
EmitStatement(statement);
PopScope();
}
writer.WriteLine("}");
}
private void EmitStatementFuncCall(TypedNodeStatementFuncCall node)
{
var name = EmitExpression(node.Target);
var parameterValues = node.Parameters.Select(EmitExpression).ToList();
writer.WriteLine($"{name}({string.Join(", ", parameterValues)});");
}
private void EmitStatementReturn(TypedNodeStatementReturn statement)
{
if (statement.Value != null)
{
var value = EmitExpression(statement.Value);
var variableName = TmpName();
writer.WriteLine($"{CType(statement.Value.Type, variableName)} = {value};");
EmitCleanupAllScopes();
writer.WriteLine($"return {variableName};");
}
else
{
EmitCleanupAllScopes();
writer.WriteLine($"return;");
}
scopes.Peek().Unreachable = true;
}
private void EmitStatementVariableDeclaration(TypedNodeStatementVariableDeclaration statement)
{
var value = EmitExpression(statement.Value);
EmitCopyConstructor(value, statement.Value.Type);
writer.WriteLine($"{CType(statement.Type, statement.Name.Ident)} = {value};");
scopes.Peek().DeconstructableNames.Add((statement.Name.Ident, statement.Type));
}
private void EmitStatementAssignment(TypedNodeStatementAssignment statement)
{
var target = EmitExpression(statement.Target);
EmitCopyDestructor(target, statement.Target.Type);
var value = EmitExpression(statement.Value);
EmitCopyConstructor(value, statement.Value.Type);
writer.WriteLine($"{target} = {value};");
}
private void EmitStatementIf(TypedNodeStatementIf statement)
{
var condition = EmitExpression(statement.Condition);
writer.WriteLine($"if ({condition})");
writer.WriteLine("{");
using (writer.Indent())
{
PushScope();
EmitStatement(statement.ThenBlock);
PopScope();
}
writer.WriteLine("}");
if (statement.ElseBlock != null)
{
writer.Write("else");
if (statement.ElseBlock is TypedNodeStatementIf)
writer.Write(" ");
else
writer.WriteLine();
writer.WriteLine("{");
using (writer.Indent())
{
PushScope();
EmitStatement(statement.ElseBlock);
PopScope();
}
writer.WriteLine("}");
}
}
private void EmitStatementWhile(TypedNodeStatementWhile statement)
{
var condition = EmitExpression(statement.Condition);
writer.WriteLine($"while ({condition})");
writer.WriteLine("{");
using (writer.Indent())
{
PushScope();
EmitStatement(statement.Body);
PopScope();
}
writer.WriteLine("}");
}
private void EmitStatementMatch(TypedNodeStatementMatch statement)
{
var target = EmitExpression(statement.Target);
var enumType = (NubTypeEnum)statement.Target.Type;
if (!moduleGraph.TryResolveType(enumType.Module, enumType.Name, true, out var info))
throw new UnreachableException();
var enumInfo = (Module.TypeInfoEnum)info;
writer.WriteLine($"switch ({target}.tag)");
writer.WriteLine("{");
using (writer.Indent())
{
foreach (var @case in statement.Cases)
{
var variantInfo = enumInfo.Variants.First(x => x.Name == @case.Variant.Ident);
var tag = enumInfo.Variants.ToList().FindIndex(x => x.Name == @case.Variant.Ident);
writer.WriteLine($"case {tag}:");
writer.WriteLine("{");
using (writer.Indent())
{
PushScope();
writer.WriteLine($"{CType(variantInfo.Type, @case.VariableName.Ident)} = {target}.{@case.Variant.Ident};");
EmitStatement(@case.Body);
PopScope();
writer.WriteLine("break;");
}
writer.WriteLine("}");
}
}
writer.WriteLine("}");
}
private string EmitExpression(TypedNodeExpression node)
{
var value = node switch
{
TypedNodeExpressionBinary expression => EmitExpressionBinary(expression),
TypedNodeExpressionUnary expression => EmitExpressionUnary(expression),
TypedNodeExpressionBoolLiteral expression => expression.Value.Value ? "true" : "false",
TypedNodeExpressionIntLiteral expression => expression.Value.Value.ToString(),
TypedNodeExpressionStringLiteral expression => EmitExpressionStringLiteral(expression),
TypedNodeExpressionStructLiteral expression => EmitExpressionStructLiteral(expression),
TypedNodeExpressionEnumLiteral expression => EmitExpressionEnumLiteral(expression),
TypedNodeExpressionStructMemberAccess expression => EmitExpressionMemberAccess(expression),
TypedNodeExpressionStringLength expression => EmitExpressionStringLength(expression),
TypedNodeExpressionStringPointer expression => EmitExpressionStringPointer(expression),
TypedNodeExpressionLocalIdent expression => expression.Name,
TypedNodeExpressionGlobalIdent expression => EmitNodeExpressionGlobalIdent(expression),
TypedNodeExpressionFuncCall expression => EmitExpressionFuncCall(expression),
_ => throw new ArgumentOutOfRangeException(nameof(node), node, null)
};
var tmp = TmpName();
writer.WriteLine($"{CType(node.Type, tmp)} = {value};");
return tmp;
}
private string EmitExpressionBinary(TypedNodeExpressionBinary expression)
{
var left = EmitExpression(expression.Left);
var right = EmitExpression(expression.Right);
return expression.Operation switch
{
TypedNodeExpressionBinary.Op.Add => $"({left} + {right})",
TypedNodeExpressionBinary.Op.Subtract => $"({left} - {right})",
TypedNodeExpressionBinary.Op.Multiply => $"({left} * {right})",
TypedNodeExpressionBinary.Op.Divide => $"({left} / {right})",
TypedNodeExpressionBinary.Op.Modulo => $"({left} % {right})",
TypedNodeExpressionBinary.Op.Equal => $"({left} == {right})",
TypedNodeExpressionBinary.Op.NotEqual => $"({left} != {right})",
TypedNodeExpressionBinary.Op.LessThan => $"({left} < {right})",
TypedNodeExpressionBinary.Op.LessThanOrEqual => $"({left} <= {right})",
TypedNodeExpressionBinary.Op.GreaterThan => $"({left} > {right})",
TypedNodeExpressionBinary.Op.GreaterThanOrEqual => $"({left} >= {right})",
TypedNodeExpressionBinary.Op.LeftShift => $"({left} << {right})",
TypedNodeExpressionBinary.Op.RightShift => $"({left} >> {right})",
TypedNodeExpressionBinary.Op.LogicalAnd => $"({left} && {right})",
TypedNodeExpressionBinary.Op.LogicalOr => $"({left} || {right})",
_ => throw new ArgumentOutOfRangeException()
};
}
private string EmitExpressionUnary(TypedNodeExpressionUnary expression)
{
var target = EmitExpression(expression.Target);
return expression.Operation switch
{
TypedNodeExpressionUnary.Op.Negate => $"(-{target})",
TypedNodeExpressionUnary.Op.Invert => $"(!{target})",
_ => throw new ArgumentOutOfRangeException()
};
}
private string EmitExpressionStringLiteral(TypedNodeExpressionStringLiteral expression)
{
var name = TmpName();
scopes.Peek().DeconstructableNames.Add((name, expression.Type));
var variable = CType(expression.Type, name);
writer.WriteLine($"{variable} = malloc(sizeof(struct {NameMangler.Mangle("core", "string", expression.Type)}));");
writer.WriteLine($"{name}->data = \"{expression.Value.Value}\";");
writer.WriteLine($"{name}->length = {expression.Value.Value.Length};");
writer.WriteLine($"{name}->ref = 1;");
writer.WriteLine($"{name}->flags = FLAG_STRING_LITERAL;");
return name;
}
private string EmitExpressionStructLiteral(TypedNodeExpressionStructLiteral expression)
{
var name = TmpName();
scopes.Peek().DeconstructableNames.Add((name, expression.Type));
var initializerValues = new Dictionary<string, string>();
foreach (var initializer in expression.Initializers)
{
var value = EmitExpression(initializer.Value);
EmitCopyConstructor(value, initializer.Value.Type);
initializerValues[initializer.Name.Ident] = value;
}
var initializerStrings = initializerValues.Select(x => $".{x.Key} = {x.Value}");
writer.WriteLine($"{CType(expression.Type, name)} = ({CType(expression.Type)}){{ {string.Join(", ", initializerStrings)} }};");
return name;
}
private string EmitExpressionEnumLiteral(TypedNodeExpressionEnumLiteral expression)
{
var name = TmpName();
scopes.Peek().DeconstructableNames.Add((name, expression.Type));
var enumVariantType = (NubTypeEnumVariant)expression.Type;
if (!moduleGraph.TryResolveType(enumVariantType.EnumType.Module, enumVariantType.EnumType.Name, true, out var info))
throw new UnreachableException();
var enumInfo = (Module.TypeInfoEnum)info;
var tag = enumInfo.Variants.ToList().FindIndex(x => x.Name == enumVariantType.Variant);
var value = EmitExpression(expression.Value);
EmitCopyConstructor(value, expression.Value.Type);
writer.WriteLine($"{CType(expression.Type, name)} = ({CType(expression.Type)}){{ .tag = {tag}, .{enumVariantType.Variant} = {value} }};");
return name;
}
private string EmitExpressionMemberAccess(TypedNodeExpressionStructMemberAccess expression)
{
var target = EmitExpression(expression.Target);
return $"{target}.{expression.Name.Ident}";
}
private string EmitExpressionStringLength(TypedNodeExpressionStringLength expression)
{
var target = EmitExpression(expression.Target);
return $"{target}->length";
}
private string EmitExpressionStringPointer(TypedNodeExpressionStringPointer expression)
{
var target = EmitExpression(expression.Target);
return $"{target}->data";
}
private string EmitNodeExpressionGlobalIdent(TypedNodeExpressionGlobalIdent expression)
{
if (!moduleGraph.TryResolveIdentifier(expression.Module, expression.Name, true, out var info))
throw new UnreachableException($"Module graph does not have info about identifier {expression.Module}::{expression.Name}. This should have been caught earlier");
return info.MangledName;
}
private string EmitExpressionFuncCall(TypedNodeExpressionFuncCall expression)
{
var name = EmitExpression(expression.Target);
var parameterValues = expression.Parameters.Select(EmitExpression).ToList();
return $"{name}({string.Join(", ", parameterValues)})";
}
public string CType(NubType node, string? varName = null)
{
referencedTypes.Add(node);
return node switch
{
NubTypeVoid => "void" + (varName != null ? $" {varName}" : ""),
NubTypeBool => "bool" + (varName != null ? $" {varName}" : ""),
NubTypeStruct type => $"struct {NameMangler.Mangle(type.Module, type.Name, type)}" + (varName != null ? $" {varName}" : ""),
NubTypeAnonymousStruct type => CTypeAnonymousStruct(type, varName),
NubTypeEnum type => $"struct {NameMangler.Mangle(type.Module, type.Name, type)}" + (varName != null ? $" {varName}" : ""),
NubTypeEnumVariant type => CType(type.EnumType, varName),
NubTypeSInt type => $"int{type.Width}_t" + (varName != null ? $" {varName}" : ""),
NubTypeUInt type => $"uint{type.Width}_t" + (varName != null ? $" {varName}" : ""),
NubTypePointer type => CType(type.To) + (varName != null ? $" *{varName}" : "*"),
NubTypeString type => $"struct {NameMangler.Mangle("core", "string", type)}" + (varName != null ? $" *{varName}" : "*"),
NubTypeFunc type => $"{CType(type.ReturnType)} (*{varName})({string.Join(", ", type.Parameters.Select(p => CType(p)))})",
_ => throw new ArgumentOutOfRangeException(nameof(node), node, null)
};
}
private static string CTypeAnonymousStruct(NubTypeAnonymousStruct type, string? varName)
{
return $"struct {NameMangler.Mangle("anonymous", "struct", type)}{(varName != null ? $" {varName}" : "")}";
}
private string TmpName()
{
return $"_tmp{tmpNameIndex++}";
}
private void EmitCleanupAllScopes()
{
foreach (var scope in scopes.Reverse())
{
for (int i = scope.DeconstructableNames.Count - 1; i >= 0; i--)
{
var (name, type) = scope.DeconstructableNames[i];
EmitCopyDestructor(name, type);
}
}
}
private void EmitCleanupCurrentScope(Scope scope)
{
for (int i = scope.DeconstructableNames.Count - 1; i >= 0; i--)
{
var (name, type) = scope.DeconstructableNames[i];
EmitCopyDestructor(name, type);
}
}
private void EmitCopyConstructor(string value, NubType type)
{
switch (type)
{
case NubTypeString:
{
writer.WriteLine($"rc_inc({value});");
break;
}
case NubTypeStruct structType:
{
if (!moduleGraph.TryResolveType(structType.Module, structType.Name, true, out var info) || info is not Module.TypeInfoStruct structInfo)
throw new UnreachableException();
foreach (var field in structInfo.Fields)
{
EmitCopyConstructor($"{value}.{field.Name}", field.Type);
}
break;
}
case NubTypeAnonymousStruct anonymousStructType:
{
foreach (var field in anonymousStructType.Fields)
{
EmitCopyConstructor($"{value}.{field.Name}", field.Type);
}
break;
}
case NubTypeEnum enumType:
{
if (!moduleGraph.TryResolveType(enumType.Module, enumType.Name, true, out var info) || info is not Module.TypeInfoEnum enumInfo)
throw new UnreachableException();
writer.WriteLine($"switch ({value}.tag)");
writer.WriteLine("{");
using (writer.Indent())
{
for (int i = 0; i < enumInfo.Variants.Count; i++)
{
Module.TypeInfoEnum.Variant variant = enumInfo.Variants[i];
writer.WriteLine($"case {i}:");
writer.WriteLine("{");
using (writer.Indent())
{
EmitCopyConstructor($"{value}.{variant.Name}", variant.Type);
writer.WriteLine("break;");
}
writer.WriteLine("}");
}
}
writer.WriteLine("}");
break;
}
case NubTypeEnumVariant enumVariantType:
{
if (!moduleGraph.TryResolveType(enumVariantType.EnumType.Module, enumVariantType.EnumType.Name, true, out var info) || info is not Module.TypeInfoEnum enumInfo)
throw new UnreachableException();
var variant = enumInfo.Variants.First(x => x.Name == enumVariantType.Variant);
EmitCopyConstructor($"{value}.{variant.Name}", variant.Type);
break;
}
}
}
private void EmitCopyDestructor(string value, NubType type)
{
switch (type)
{
case NubTypeString:
{
writer.WriteLine($"rc_dec({value});");
break;
}
case NubTypeStruct structType:
{
if (!moduleGraph.TryResolveType(structType.Module, structType.Name, true, out var info) || info is not Module.TypeInfoStruct structInfo)
throw new UnreachableException();
foreach (var field in structInfo.Fields)
{
EmitCopyDestructor($"{value}.{field.Name}", field.Type);
}
break;
}
case NubTypeAnonymousStruct anonymousStructType:
{
foreach (var field in anonymousStructType.Fields)
{
EmitCopyDestructor($"{value}.{field.Name}", field.Type);
}
break;
}
case NubTypeEnum enumType:
{
if (!moduleGraph.TryResolveType(enumType.Module, enumType.Name, true, out var info) || info is not Module.TypeInfoEnum enumInfo)
throw new UnreachableException();
writer.WriteLine($"switch ({value}.tag)");
writer.WriteLine("{");
using (writer.Indent())
{
for (int i = 0; i < enumInfo.Variants.Count; i++)
{
var variant = enumInfo.Variants[i];
writer.WriteLine($"case {i}:");
writer.WriteLine("{");
using (writer.Indent())
{
EmitCopyDestructor($"{value}.{variant.Name}", variant.Type);
writer.WriteLine("break;");
}
writer.WriteLine("}");
}
}
writer.WriteLine("}");
break;
}
case NubTypeEnumVariant enumVariantType:
{
if (!moduleGraph.TryResolveType(enumVariantType.EnumType.Module, enumVariantType.EnumType.Name, true, out var info) || info is not Module.TypeInfoEnum enumInfo)
throw new UnreachableException();
var variant = enumInfo.Variants.First(x => x.Name == enumVariantType.Variant);
EmitCopyDestructor($"{value}.{variant.Name}", variant.Type);
break;
}
}
}
private void PushScope()
{
scopes.Push(new Scope());
}
private void PopScope()
{
var scope = scopes.Pop();
if (!scope.Unreachable)
EmitCleanupCurrentScope(scope);
}
private class Scope
{
public List<(string Name, NubType Type)> DeconstructableNames { get; } = [];
public bool Unreachable { get; set; }
}
}
internal class IndentedTextWriter
{
private readonly StringBuilder builder = new();
private int indentLevel;
public IDisposable Indent()
{
indentLevel++;
return new IndentScope(this);
}
public void WriteLine(string text)
{
WriteIndent();
builder.AppendLine(text);
}
public void Write(string text)
{
WriteIndent();
builder.Append(text);
}
public void WriteLine()
{
builder.AppendLine();
}
public override string ToString()
{
return builder.ToString();
}
private void WriteIndent()
{
if (builder.Length > 0)
{
var lastChar = builder[^1];
if (lastChar != '\n' && lastChar != '\r')
return;
}
for (var i = 0; i < indentLevel; i++)
{
builder.Append(" ");
}
}
private class IndentScope(IndentedTextWriter writer) : IDisposable
{
private bool disposed;
public void Dispose()
{
if (disposed) return;
writer.indentLevel--;
disposed = true;
}
}
}