57 lines
1,023 B
Go
57 lines
1,023 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
func print(expr Expr) string {
|
|
switch e := expr.(type) {
|
|
case Binary:
|
|
return parenthesize(e.operator.Lexeme,
|
|
e.left,
|
|
e.right)
|
|
case Grouping:
|
|
return parenthesize("group", e.expression)
|
|
case Literal:
|
|
if e.value == nil {
|
|
return "nil"
|
|
}
|
|
return fmt.Sprintf("%v", e.value)
|
|
case Unary:
|
|
return parenthesize(e.operator.Lexeme, e.right)
|
|
}
|
|
return "ERROR: reached impossible branch in print function"
|
|
}
|
|
|
|
func parenthesize(name string, exprs ...Expr) string {
|
|
var sb strings.Builder
|
|
|
|
sb.WriteString("(" + name)
|
|
|
|
for _, expr := range exprs {
|
|
sb.WriteString(" ")
|
|
sb.WriteString(print(expr))
|
|
}
|
|
sb.WriteString(")")
|
|
|
|
return sb.String()
|
|
}
|
|
|
|
// This was briefly a testing function for the AST class at the end of ch. 5
|
|
/*
|
|
func main() {
|
|
var expression Expr = Binary{
|
|
Unary{
|
|
lexer.NewToken(lexer.MINUS, "-", nil, 1),
|
|
Literal{123},
|
|
},
|
|
lexer.NewToken(lexer.STAR, "*", nil, 1),
|
|
Grouping{
|
|
Literal{45.67},
|
|
},
|
|
}
|
|
fmt.Println(print(expression))
|
|
}
|
|
*/
|