using System.Text; namespace Fantasy.SourceGenerator.Common { /// /// 辅助构建生成代码的工具类 /// internal sealed class SourceCodeBuilder { private readonly StringBuilder _builder; private int _indentLevel; private const string IndentString = " "; // 4 空格缩进 public SourceCodeBuilder(int indentLevel = 0) { _builder = new StringBuilder(); _indentLevel = indentLevel; } /// /// 增加缩进级别 /// public SourceCodeBuilder Indent(int indentLevel = 1) { _indentLevel += indentLevel; return this; } /// /// 减少缩进级别 /// public SourceCodeBuilder Unindent() { if (_indentLevel > 0) { _indentLevel--; } return this; } public void Append(string code = "") { _builder.Append(code); } /// /// 添加一行代码(自动处理缩进) /// public SourceCodeBuilder AppendLine(string code = "", bool indent = true) { if (string.IsNullOrEmpty(code)) { _builder.AppendLine(); } else { if (indent) { for (int i = 0; i < _indentLevel; i++) { _builder.Append(IndentString); } } _builder.AppendLine(code); } return this; } /// /// 添加代码块开始 { /// public SourceCodeBuilder OpenBrace() { AppendLine("{"); Indent(); return this; } /// /// 添加代码块结束 } /// public SourceCodeBuilder CloseBrace(bool semicolon = false) { Unindent(); AppendLine(semicolon ? "};" : "}"); return this; } /// /// 添加 using 语句 /// public SourceCodeBuilder AddUsing(string @namespace) { AppendLine($"using {@namespace};"); return this; } /// /// 添加多个 using 语句 /// public SourceCodeBuilder AddUsings(params string[] namespaces) { foreach (var ns in namespaces) { AddUsing(ns); } return this; } /// /// 开始命名空间 /// public SourceCodeBuilder BeginNamespace(string @namespace) { AppendLine($"namespace {@namespace}"); OpenBrace(); return this; } /// /// 结束命名空间 /// public SourceCodeBuilder EndNamespace() { CloseBrace(); return this; } /// /// 开始类定义 /// public SourceCodeBuilder BeginClass(string className, string? modifiers = "internal static", string? baseTypes = null) { var classDeclaration = $"{modifiers} class {className}"; if (!string.IsNullOrEmpty(baseTypes)) { classDeclaration += $" : {baseTypes}"; } AppendLine(classDeclaration); OpenBrace(); return this; } /// /// 结束类定义 /// public SourceCodeBuilder EndClass() { CloseBrace(); return this; } /// /// 开始方法定义 /// public SourceCodeBuilder BeginMethod(string signature) { AppendLine(signature); OpenBrace(); return this; } /// /// 结束方法定义 /// public SourceCodeBuilder EndMethod() { CloseBrace(); return this; } /// /// 添加注释 /// public SourceCodeBuilder AddComment(string comment) { AppendLine($"// {comment}"); return this; } /// /// 添加 XML 文档注释 /// public SourceCodeBuilder AddXmlComment(string summary) { AppendLine("/// "); AppendLine($"/// {summary}"); AppendLine("/// "); return this; } /// /// 构建最终代码 /// public override string ToString() { return _builder.ToString(); } /// /// 清空构建器 /// public void Clear() { _builder.Clear(); _indentLevel = 0; } } }