c generator
This commit is contained in:
70
compiler/NubLang/Generation/CWriter.cs
Normal file
70
compiler/NubLang/Generation/CWriter.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
using System.Text;
|
||||
|
||||
namespace NubLang.Generation;
|
||||
|
||||
internal class CWriter
|
||||
{
|
||||
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 : IDisposable
|
||||
{
|
||||
private readonly CWriter _writer;
|
||||
private bool _disposed;
|
||||
|
||||
public IndentScope(CWriter writer)
|
||||
{
|
||||
_writer = writer;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_writer._indentLevel--;
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user