You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1011 B
Go
51 lines
1011 B
Go
package ast
|
|
|
|
import (
|
|
"fmt"
|
|
"golox/parser"
|
|
)
|
|
|
|
type Printer struct {
|
|
}
|
|
|
|
func New() *Printer {
|
|
return &Printer{}
|
|
}
|
|
|
|
func (ap *Printer) Print(expr parser.Expr) string {
|
|
return expr.Accept(ap).(string)
|
|
}
|
|
|
|
func (ap *Printer) VisitBinaryExpr(expr *parser.BinaryExpr) any {
|
|
return ap.parenthesize(expr.Operator.Lexeme, expr.Left, expr.Right)
|
|
}
|
|
|
|
func (ap *Printer) VisitGroupingExpr(expr *parser.GroupingExpr) any {
|
|
return ap.parenthesize("group", expr.Expression)
|
|
}
|
|
|
|
func (ap *Printer) VisitLiteralExpr(expr *parser.LiteralExpr) any {
|
|
if expr.Value == nil {
|
|
return "nil"
|
|
}
|
|
return fmt.Sprint(expr.Value)
|
|
}
|
|
|
|
func (ap *Printer) VisitUnaryExpr(expr *parser.UnaryExpr) any {
|
|
return ap.parenthesize(expr.Operator.Lexeme, expr.Right)
|
|
}
|
|
|
|
func (ap *Printer) VisitErrorExpr(expr *parser.ErrorExpr) any {
|
|
return expr.Value
|
|
}
|
|
|
|
func (ap *Printer) parenthesize(name string, exprs ...parser.Expr) string {
|
|
str := "(" + name
|
|
|
|
for _, expr := range exprs {
|
|
str += " " + expr.Accept(ap).(string)
|
|
}
|
|
|
|
return str + ")"
|
|
}
|