-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser_test.go
116 lines (100 loc) · 2.32 KB
/
parser_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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package prattle
import (
"errors"
"fmt"
"testing"
)
type testDriver struct {
infix func(*Parser, Token) error
prefix func(*Parser, Token) error
}
func (d testDriver) Infix(int) ParseFunc { return d.infix }
func (d testDriver) Prefix(int) ParseFunc { return d.prefix }
func (testDriver) Precedence(int) int { return 1 }
func (d testDriver) ParseError(t Token) error { return fmt.Errorf("kind: %d", t.Kind) }
type tokeniter []Token
func (it *tokeniter) Next() (tok Token, ok bool) {
if len(*it) != 0 {
tok, *it = (*it)[0], (*it)[1:]
return tok, true
}
return
}
func requireError(t testing.TB, err error) {
if err == nil {
t.Helper()
t.Error("expected error")
}
}
func requireNoError(t testing.TB, err error) {
if err != nil {
t.Helper()
t.Error("unexpected error", err)
}
}
func TestPrefixErrors(t *testing.T) {
tokens := []Token{{Kind: 1}}
t.Run("one", func(t *testing.T) {
p := Parser{Driver: &testDriver{}}
it := tokeniter(tokens)
p.Init(&it)
requireError(t, p.Parse(0))
})
t.Run("two", func(t *testing.T) {
p := Parser{
Driver: &testDriver{
prefix: func(p *Parser, t Token) error { return errors.New("") },
},
}
it := tokeniter(tokens)
p.Init(&it)
requireError(t, p.Parse(0))
})
}
func TestInfixErrors(t *testing.T) {
tokens := []Token{{Kind: 1}}
t.Run("one", func(t *testing.T) {
p := Parser{Driver: &testDriver{
prefix: func(p *Parser, t Token) error { return nil },
}}
it := tokeniter(tokens)
p.Init(&it)
requireError(t, p.Parse(0))
})
t.Run("two", func(t *testing.T) {
p := Parser{
Driver: &testDriver{
prefix: func(p *Parser, t Token) error { return nil },
infix: func(p *Parser, t Token) error { return errors.New("") },
},
}
it := tokeniter(tokens)
p.Init(&it)
requireError(t, p.Parse(0))
})
t.Run("nonassoc", func(t *testing.T) {
p := Parser{
Driver: &testDriver{
prefix: func(p *Parser, t Token) error { return nil },
infix: func(p *Parser, t Token) error { return NonAssoc },
},
}
it := tokeniter(tokens)
p.Init(&it)
requireNoError(t, p.Parse(0))
})
}
func TestParserExpect(t *testing.T) {
tokens := []Token{{Kind: 1}}
p := Parser{}
it := tokeniter(tokens)
p.Init(&it)
if p.Expect(3) {
t.Error("expected false")
}
}
func TestErrorString(t *testing.T) {
if NonAssoc.Error() == "" {
t.Fatal()
}
}