-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
61 lines (51 loc) · 1.27 KB
/
main.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
54
55
56
57
58
59
60
61
package main
import (
"fmt"
"os"
"strings"
"flag"
"github.com/shivamMg/rd"
"github.com/shivamMg/rd/examples/arithmetic/backtrackingparser"
"github.com/shivamMg/rd/examples/arithmetic/parser"
)
var (
useBacktrackingParser = flag.Bool("backtrackingparser", false, "use backtracking parser")
expr = flag.String("expr", "", "arithmetic expression to be parsed")
)
func main() {
flag.Parse()
if *expr == "" {
printExit("empty expr flag. pass arithmetic expression as expr. ex. -expr='1+2'")
}
tokens, err := Lex(*expr)
if err != nil {
printExit("Lexing failed.", err)
}
printTokens(tokens)
fmt.Print("Grammar:")
fmt.Print(parser.Grammar)
var parseTree *rd.Tree
var debugTree *rd.DebugTree
if *useBacktrackingParser {
parseTree, debugTree, err = backtrackingparser.Parse(tokens)
} else {
parseTree, debugTree, err = parser.Parse(tokens)
}
if err != nil {
fmt.Print("Debug Tree:\n\n", debugTree)
printExit("Parsing failed.", err)
}
fmt.Print("Parse Tree:\n\n", parseTree)
}
func printTokens(tokens []rd.Token) {
fmt.Print("Tokens: ")
var b strings.Builder
for _, token := range tokens {
b.WriteString(fmt.Sprint(token, " "))
}
fmt.Println(b.String())
}
func printExit(a ...interface{}) {
fmt.Fprintln(os.Stderr, a...)
os.Exit(1)
}