我正在写一个 AST(抽象语法树),不是以树的形式,而是为了正确格式化我的代码。类似于自定义语言的 Clang,我使用 StringBuilder 来实现效果......现在我必须执行以下操作:
public string Visit(IfStatement ifStatement, int indent = 0)
{
var sb = new StringBuilder()
.Append('\t', indent)
.Append(Token.IfKeyword.ToString())
.AppendBetween(ifStatement.Test.Accept(this), "(", ")").AppendLine()
.Append(ifStatement.Consequent.Accept(this, indent + 1));
if (ifStatement.Consequent != null)
{
sb.AppendLine()
.Append('\t', indent)
.AppendLine(Token.ElseKeyword.ToString())
.Append(ifStatement.Consequent.Accept(this, indent + 1));
}
return sb.ToString();
}
这有时会变得非常复杂,所以我希望我可以做类似的事情:
sb.Append("Hello").IfElse(a > 5, sb => sb.Append("world!"), sb => sb.AppendLine("ME!!")).Append(...)
这可以使用类扩展来完成吗?非常感谢您的宝贵时间!
(顺便说一句,有没有更好的方法来写下 AST?我目前正在使用访问者模式来实现效果,但如果您知道更好的方法,请告诉我......如果某些线宽是,我还想引入文本换行达到..虽然不知道该怎么做)。