-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
91 lines (77 loc) · 1.54 KB
/
parser.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"fmt"
"strings"
"strconv"
"bufio"
)
type Parser struct {
scanner *bufio.Scanner
sub []string
doingTheThing bool
}
func (p Parser) Parse() (Op, error) {
p.scanner.Scan()
s := p.scanner.Text()
fmt.Printf("Parsing `%v`\n", s)
switch s {
case "(":
p.doingTheThing = true
p.sub = append(p.sub, s)
fmt.Printf("Gathering.. `%v`\n", s)
return p.Parse()
case ")":
panic("wtf")
p.doingTheThing = false
str := strings.Join(p.sub, " ")
sub := NewParser(str)
fmt.Printf("Sub parsing.. `%v`\n", str)
uh, what := sub.Parse()
fmt.Printf("sub parse returned %v and %v\n", uh, what)
return uh, what
case "+":
a, err := p.Parse()
if err != nil {
return nil, err
}
b, err := p.Parse()
if err != nil {
return nil, err
}
return AddOp{a: a, b: b}, nil
case "-":
a, err := p.Parse()
if err != nil {
return nil, err
}
b, err := p.Parse()
if err != nil {
return nil, err
}
return SubOp{a: a, b: b}, nil
case "*":
a, err := p.Parse()
if err != nil {
return nil, err
}
b, err := p.Parse()
if err != nil {
return nil, err
}
return MultiplyOp{a: a, b: b}, nil
default:
fmt.Printf("Atom? %v\n", s)
v, err := strconv.ParseInt(s, 10, 16)
if err != nil {
return nil, fmt.Errorf("Unbueno int %v: %v", s, err)
}
return Atom(v), nil
}
return nil, nil
}
func NewParser(input string) Parser {
fmt.Printf("New parser on `%v`\n", input);
scanner := bufio.NewScanner(strings.NewReader(input))
scanner.Split(bufio.ScanWords)
return Parser{scanner: scanner}
}