-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexamples_test.go
53 lines (47 loc) · 1.1 KB
/
examples_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package parse_test
import (
"fmt"
"github.com/orkes-io/go-parse"
"github.com/orkes-io/go-parse/bools"
"github.com/orkes-io/go-parse/comp"
"strings"
)
func Example() {
bParser, _ := bools.NewParser()
cParser, _ := comp.NewParser()
// parse boolean expression
ast, err := bParser.ParseStr("x >= 5 AND NOT(y < 7 OR z != 3)")
if err != nil {
fmt.Printf("error parsing boolean expression: %v\n", err)
}
// parse comparisons
err = ast.Parse(cParser)
if err != nil {
fmt.Printf("error parsing comparison: %v\n", err)
}
bfsPrint(ast)
// Output:
// x >= 5 AND NOT(y < 7 OR z != 3)
}
func bfsPrint(ast parse.AST) {
switch ast := (ast).(type) {
case *bools.BinExpr:
bfsPrint(ast.LHS)
fmt.Printf(" %s ", ast.Op.String())
bfsPrint(ast.RHS)
case *bools.UnaryExpr:
fmt.Print(" NOT(")
bfsPrint(ast.Expr)
fmt.Print(") ")
case *comp.EqualExpr:
bfsPrint(ast.LHS)
fmt.Printf(" %s ", ast.Op.String())
bfsPrint(ast.RHS)
case *comp.OrdinalExpr:
bfsPrint(ast.LHS)
fmt.Printf(" %s ", ast.Op.String())
bfsPrint(ast.RHS)
case parse.Unparsed:
fmt.Print(strings.Join(ast.Contents, " "))
}
}