-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
77 lines (63 loc) · 1.5 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
read_prompt_and_parse(
func(exp string) {
sc := NewScanner([]rune(exp), -1)
parser := NewParser(sc)
for sc.HasNext() {
node := parser.Parse()
if node.kind == ERROR_NODE {
fmt.Println(node.val.(string))
break
}
visit(*node, 0)
}
},
)
}
func read_prompt_and_parse(parsefn func(exp string)) {
fmt.Println()
fmt.Println("Simple LL(1) grammer tokenizer & parser.")
fmt.Println("Author : Massiles Ghernaout (github.com/MassiGy)")
fmt.Println("Licence: MIT")
fmt.Println()
fmt.Println("Grammar:")
fmt.Println(" > Node -> Char | Pair")
fmt.Println(" > Char -> [a-z]")
fmt.Println(" > Pair -> ( . Node . Space . Node . )")
fmt.Println()
fmt.Println("Legend : ")
fmt.Println(" > '.' (dot) is the concatination operator.")
fmt.Println()
promptScanner := bufio.NewScanner(os.Stdin)
fmt.Print(">>> ")
for promptScanner.Scan() {
parsefn(promptScanner.Text())
fmt.Print(">>> ")
}
}
func visit(n Node, n_spaces int) {
indent(n_spaces)
switch n.kind {
case CHAR_NODE:
fmt.Printf("Char('%c')\n", n.val.(CharValue).char)
case PAIR_NODE:
fmt.Printf("Pair(\n")
visit(n.val.(PairValue).left, n_spaces+2)
visit(n.val.(PairValue).right, n_spaces+2)
indent(n_spaces)
fmt.Printf(")\n")
case ERROR_NODE:
fmt.Printf(n.val.(string) + "\n")
}
}
func indent(n_spaces int) {
for i := 0; i < n_spaces; i++ {
fmt.Printf(" ")
}
}