You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

27 lines
736 B

module Lox
class AstPrinter
def print(expr) = expr.accept(self)
def visit_binary(expr) = parenthesize(expr.op.lexeme, expr.left, expr.right)
def visit_grouping(expr) = parenthesize("group", expr.expr)
def visit_literal(expr) = expr.value&.to_s || "nil"
def visit_unary(expr) = parenthesize(expr.op.lexeme, expr.right)
def visit_print(expr) = parenthesize("print", expr.expr)
def visit_var(expr)
if init = expr.initializer
"(assign #{expr.name.lexeme} #{expr.initializer.value})"
else
"(var #{expr.name.lexeme})"
end
end
private
def parenthesize(name, *exprs)
"(#{name} #{exprs.map {|expr| expr.accept(self) }.join(" ")})"
end
end
end