2023-06-26 20:47:31 +00:00
|
|
|
using System;
|
|
|
|
using System.IO;
|
|
|
|
using Finn.AST;
|
|
|
|
|
|
|
|
namespace Finn;
|
|
|
|
|
|
|
|
class ASTPrinter : IVisitor<string>
|
|
|
|
{
|
2023-06-28 18:12:14 +00:00
|
|
|
public string print(Expr expr)
|
2023-06-26 20:47:31 +00:00
|
|
|
{
|
|
|
|
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);
|
|
|
|
}
|
2023-06-28 22:26:08 +00:00
|
|
|
|
|
|
|
public string visitIfExpr(If expr)
|
|
|
|
{
|
|
|
|
return parenthesize("if", expr.Condition, expr.Then, expr.Else);
|
|
|
|
}
|
2023-06-28 23:18:31 +00:00
|
|
|
|
|
|
|
public string visitSequenceExpr(Sequence expr)
|
|
|
|
{
|
|
|
|
return parenthesize("seq", expr.Left, expr.Right);
|
|
|
|
}
|
2023-06-26 20:47:31 +00:00
|
|
|
}
|