|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Text; |
| 4 | + |
| 5 | +namespace ChartTools.Generator; |
| 6 | + |
| 7 | +internal class CodeBuilder(StringBuilder? builder = default) |
| 8 | +{ |
| 9 | + public CodeBuilder(string value) |
| 10 | + : this(new StringBuilder(value)) { } |
| 11 | + |
| 12 | + public CodeBuilder(int indent, StringBuilder? builder = default) |
| 13 | + : this(builder) |
| 14 | + => m_indent = new('\t', indent); |
| 15 | + |
| 16 | + public StringBuilder StringBuilder { get; } = builder ?? new(); |
| 17 | + |
| 18 | + private readonly Stack<char> m_contextStack = []; |
| 19 | + private string m_indent = string.Empty; |
| 20 | + |
| 21 | + private static readonly Dictionary<char, char> m_contextClosers = new() |
| 22 | + { |
| 23 | + { '(', ')' }, |
| 24 | + { '{', '}' }, |
| 25 | + { '[', ']' }, |
| 26 | + { '"', '"' } |
| 27 | + }; |
| 28 | + |
| 29 | + public CodeBuilder StartContext(char openChar, bool newLine = true) |
| 30 | + { |
| 31 | + if (newLine) |
| 32 | + StringBuilder.AppendLine(m_indent + openChar); |
| 33 | + else |
| 34 | + StringBuilder.Append(m_indent + openChar); |
| 35 | + |
| 36 | + m_contextStack.Push(openChar); |
| 37 | + m_indent += '\t'; |
| 38 | + |
| 39 | + return this; |
| 40 | + } |
| 41 | + |
| 42 | + public CodeBuilder EndContext(bool newLine = true) |
| 43 | + { |
| 44 | + if (m_contextStack.Count == 0) |
| 45 | + throw new InvalidOperationException("No context to end."); |
| 46 | + |
| 47 | + char openChar = m_contextStack.Pop(); |
| 48 | + |
| 49 | + if (!m_contextClosers.TryGetValue(openChar, out char closeChar)) |
| 50 | + throw new InvalidOperationException($"No closing character defined for '{openChar}'."); |
| 51 | + |
| 52 | + m_indent = m_indent.Substring(0, m_indent.Length - 2); |
| 53 | + |
| 54 | + if (newLine) |
| 55 | + StringBuilder.AppendLine(m_indent + closeChar); |
| 56 | + else |
| 57 | + StringBuilder.Append(m_indent + closeChar); |
| 58 | + |
| 59 | + return this; |
| 60 | + } |
| 61 | + |
| 62 | + public CodeBuilder AppendLine(string line) |
| 63 | + { |
| 64 | + StringBuilder.AppendLine(m_indent + line); |
| 65 | + return this; |
| 66 | + } |
| 67 | + |
| 68 | + public CodeBuilder AppendLine() |
| 69 | + { |
| 70 | + StringBuilder.AppendLine(m_indent); |
| 71 | + return this; |
| 72 | + } |
| 73 | + |
| 74 | + public CodeBuilder Append(string text) |
| 75 | + { |
| 76 | + StringBuilder.Append(m_indent + text); |
| 77 | + return this; |
| 78 | + } |
| 79 | + |
| 80 | + public override string ToString() |
| 81 | + => StringBuilder.ToString(); |
| 82 | + |
| 83 | + public static implicit operator StringBuilder(CodeBuilder builder) |
| 84 | + => builder.StringBuilder; |
| 85 | +} |
0 commit comments