using System;
using System.Text;
namespace Vellum.Generator
{
///
/// Writes generated code a line at a time, tracking the indentation.
///
public sealed class CodeWriter
{
private const string IndentUnit = " ";
// Generated files use CRLF, matching what the rest of the tree checks in.
private const string LineEnding = "\r\n";
private readonly StringBuilder text = new StringBuilder();
private int depth;
public void Indent()
{
++depth;
}
public void Dedent()
{
if (depth == 0)
{
throw new InvalidOperationException("Dedent without a matching Indent.");
}
--depth;
}
public void NewLine()
{
text.Append(LineEnding);
}
///
/// Writes on its own line at the current indentation. Empty content writes a
/// blank line.
///
public void AddLine(string content)
{
if (content.Length == 0)
{
NewLine();
return;
}
for (int i = 0; i < depth; ++i)
{
text.Append(IndentUnit);
}
text.Append(content);
text.Append(LineEnding);
}
public void OpenNewBlock()
{
AddLine("{");
Indent();
}
public void OpenNewBlock(string header)
{
AddLine(header);
OpenNewBlock();
}
public void CloseBlock()
{
Dedent();
AddLine("}");
}
///
/// Returns everything written so far.
///
public override string ToString()
{
return text.ToString();
}
}
}