惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The Cloudflare Blog
U
Unit 42
D
Docker
Hugging Face - Blog
Hugging Face - Blog
博客园 - 聂微东
Recent Announcements
Recent Announcements
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI
V
Visual Studio Blog
I
InfoQ
Google DeepMind News
Google DeepMind News
小众软件
小众软件
L
LangChain Blog
C
Check Point Blog
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 【当耐特】
J
Java Code Geeks
罗磊的独立博客

博客园 - daviyoung

Windows 11 22H2 安装 .NET Framework 3.5 完整教程 System.Threading.Timer 详细讲解 Agent 开发入门(一):从零构建你的第一个智能体 用 C# 开发一个解释器语言——基于《Crafting Interpreters》的实战系列(五)表达式求值 python使用plotly绘制图表 手把手搭建OPC UA服务器 图像处理库Pillow的使用:批量裁剪图片 python-docx库的使用:图片插入到word文档里 modbus(二)用NModbus4库实现Modbus tcp从站 Jenkins 容器化实践:Docker 部署与 CI/CD 流水线配置 Streamlit实战 用pycdc批量反编译pyc文件 以ENS 的 BaseRegistrarImplementation 合约为例,用web3.py调用合约 虚拟环境下安装包后,vs code仍然有下滑波浪线及显示找不到包(运行是正常的)的解决办法 Merkle Tree Solidity开发ERC20智能合约claim token的功能 Solidity开发ERC20智能合约demo及部署到测试网 用 C# 开发一个解释器语言——基于《Crafting Interpreters》的实战系列(三)表达式的抽象语法树设计(Expr) 用 C# 开发一个解释器语言——基于《Crafting Interpreters》的实战系列(二)词法分析器
用 C# 开发一个解释器语言——基于《Crafting Interpreters》的...
daviyoung · 2025-08-08 · via 博客园 - daviyoung
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