47 lines
821 B
C#
47 lines
821 B
C#
|
using System;
|
||
|
using System.IO;
|
||
|
using Finn.AST;
|
||
|
|
||
|
namespace Finn;
|
||
|
|
||
|
class ASTPrinter : IVisitor<string>
|
||
|
{
|
||
|
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);
|
||
|
}
|
||
|
}
|