用 C# 开发一个解释器语言——基于《Crafting Interpreters》的实战系列(四)可视化 语法树

public class AstVisualizer : Expr.Visitor<string>
{
    public string Print(Expr expr)
    {
        return expr.Accept(this);
    }

    private string Indent(string text, string prefix)
    {
        var lines = text.Split('\n');
        for (int i = 0; i < lines.Length; i++)
        {
            lines[i] = prefix + lines[i];
        }
        return string.Join("\n", lines);
    }

    public string VisitBinaryExpr(Expr.Binary expr)
    {
        var left = Indent(expr.Left.Accept(this), "├── ");
        var right = Indent(expr.Right.Accept(this), "└── ");
        return $"Binary {expr.Operator.Lexeme}\n{left}\n{right}";
    }

    public string VisitGroupingExpr(Expr.Grouping expr)
    {
        var inner = Indent(expr.Expression.Accept(this), "└── ");
        return $"Grouping\n{inner}";
    }

    public string VisitLiteralExpr(Expr.Literal expr)
    {
        return $"Literal {expr.Value}";
    }

    public string VisitUnaryExpr(Expr.Unary expr)
    {
        var right = Indent(expr.Right.Accept(this), "└── ");
        return $"Unary {expr.Operator.Lexeme}\n{right}";
    }
}
 static void Main(string[] args)
 {
     PrintAst();
     Console.ReadKey();
 }
 static void PrintAst()
 {
     Expr expression = new Expr.Binary(
         new Expr.Literal(1.0),
         new Token(TokenType.PLUS, "+", null, 1),
         new Expr.Binary(new Expr.Literal(2.0),
         new Token(TokenType.STAR, "*", null, 1),
         new Expr.Literal(3.0)));
     var visualizer = new AstVisualizer();
     Console.WriteLine(visualizer.Print(expression));
 }

 

效果:

image

 

posted @ 2025-08-08 15:09  daviyoung  阅读(9)  评论(0)    收藏  举报