glox/ast_string.go

95 lines
1.8 KiB
Go
Raw Normal View History

2024-10-04 15:24:01 +03:00
package main
import (
"fmt"
"strings"
)
type AstStringer struct {
2024-10-05 23:27:00 +03:00
str strings.Builder
stmts []Stmt
2024-10-04 15:24:01 +03:00
}
2024-10-05 23:27:00 +03:00
func (as AstStringer) String() string {
2024-10-04 15:24:01 +03:00
2024-10-05 23:27:00 +03:00
for _, stmt := range as.stmts {
2024-10-05 18:58:49 +03:00
stmt.accept(&as)
2024-10-04 15:24:01 +03:00
}
return as.str.String()
}
func (as *AstStringer) visitBinary(b *Binary) any {
as.str.WriteString("(")
as.str.WriteString(b.op.lexeme)
as.str.WriteString(" ")
b.left.accept(as)
as.str.WriteString(" ")
b.right.accept(as)
as.str.WriteString(")")
return nil
}
func (as *AstStringer) visitLiteral(l *Literal) any {
as.str.WriteString(fmt.Sprintf("%v", l.value))
return nil
}
func (as *AstStringer) visitGrouping(g *Grouping) any {
as.str.WriteString("(group ")
g.expression.accept(as)
as.str.WriteString(")")
return nil
}
func (as *AstStringer) visitUnary(u *Unary) any {
as.str.WriteString(fmt.Sprintf("(%s ", u.op.lexeme))
u.right.accept(as)
as.str.WriteString(")")
return nil
}
2024-10-05 18:58:49 +03:00
func (as *AstStringer) visitVariable(va *Variable) any {
as.str.WriteString(va.name.lexeme)
return nil
}
func (as *AstStringer) visitAssignment(a *Assign) any {
as.str.WriteString(fmt.Sprintf("(= %s ", a.variable.lexeme))
a.value.accept(as)
as.str.WriteString(")")
return nil
}
func (as *AstStringer) visitPrintStmt(p *PrintStmt) {
as.str.WriteString("(print ")
p.val.accept(as)
as.str.WriteString(")")
}
func (as *AstStringer) visitExprStmt(se *ExprStmt) {
se.expr.accept(as)
}
func (as *AstStringer) visitVarStmt(vs *VarStmt) {
if vs.initializer != nil {
as.str.WriteString(fmt.Sprintf("(var %v ", vs.name.literal))
vs.initializer.accept(as)
as.str.WriteString(")")
} else {
as.str.WriteString(fmt.Sprintf("(var %v)", vs.name.literal))
}
}
2024-10-05 23:27:00 +03:00
func (as *AstStringer) visitBlockStmt(b *BlockStmt) {
as.str.WriteString("(block ")
for _, stmt := range b.stmts {
stmt.accept(as)
}
as.str.WriteString(")")
}