From b9b8c8e24b19b5fe4ea1e646349f290a242f1753 Mon Sep 17 00:00:00 2001 From: Brandon Dyck Date: Mon, 26 Jun 2023 13:47:31 -0700 Subject: [PATCH] Added an AST printer --- ASTPrinter.cs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 ASTPrinter.cs diff --git a/ASTPrinter.cs b/ASTPrinter.cs new file mode 100644 index 0000000..a5ae86c --- /dev/null +++ b/ASTPrinter.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using Finn.AST; + +namespace Finn; + +class ASTPrinter : IVisitor +{ + string print(Expr expr) + { + return expr.accept(this); + } + + private string parenthesize(string name, params Expr[] exprs) + { + var w = new StringWriter(); + w.Write($"({name}"); + foreach (Expr expr in exprs) + { + w.Write(" "); + w.Write(expr.accept(this)); + } + w.Write(")"); + return w.ToString(); + } + + public string visitBinaryExpr(Binary expr) + { + return parenthesize(expr.Op.lexeme, expr.Left, expr.Right); + } + + public string visitGroupingExpr(Grouping expr) + { + return parenthesize("group", expr.Expression); + } + + public string visitLiteralExpr(Literal expr) + { + return expr.Value.ToString() ?? ""; + } + + public string visitUnaryExpr(Unary expr) + { + return parenthesize(expr.Op.lexeme, expr.Right); + } +}