-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexer_test.go
88 lines (73 loc) · 2.11 KB
/
lexer_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
package goply_test
import (
"fmt"
"testing"
"github.com/nayas360/goply"
)
// tests lexer in lenient mode
func TestNewLexer(t *testing.T) {
source := `func test() {
num := 123
var num2 = 123
}
`
lexer := goply.NewLexer(false)
lexer.AddRule("<lparen>", "\\(")
lexer.AddRule("<rparen>", "\\)")
lexer.AddRule("<lbrace>", "{")
lexer.AddRule("<rbrace>", "}")
// lexer is in lenient mode,
// the following should not raise an error
lexer.AddRule("<eq>", "=")
lexer.AddRule("<func_kw>", "func")
lexer.AddRule("<var_kw>", "var")
lexer.AddRule("<identifier>", "[A-Za-z_][A-Za-z0-9]+")
lexer.AddRule("<number>", "[0-9]+")
lexer.Ignore("\\s+")
tokens, err := lexer.GetTokenStream(source)
if err != nil {
t.Errorf("got error instead of tokens, %s", err)
}
if tokens.Len() != 13 {
t.Error("expected 13 tokens got,", tokens.Len())
}
}
// tests lexer in strict mode
func TestNewLexerStrict(t *testing.T) {
source := "num := 123"
lexer := goply.NewLexer(true)
// the lexer is in strict mode,
// and cannot match the ':' character to any rule
// this should raise an error
lexer.AddRule("<identifier>", "[A-Za-z_][A-Za-z0-9]+")
lexer.AddRule("<number>", "[0-9]+")
lexer.Ignore("\\s+")
_, err := lexer.GetTokenStream(source)
if err == nil {
t.Errorf("expected an error, got none")
}
}
// tests custom error handler in strict mode
func TestLexerStrict_SetLexerErrorFunc(t *testing.T) {
lexer := goply.NewLexer(true)
lexer.SetLexerErrorFunc(func(ls goply.LexerState) error {
return fmt.Errorf("there was an error")
})
_, err := lexer.GetTokenStream("123")
if fmt.Sprint(err) != "there was an error" {
t.Error("the custom error function was not set")
}
}
// tests custom error handler in lenient mode
// the error function is ignored since no error is raised
func TestLexer_SetLexerErrorFunc(t *testing.T) {
lexer := goply.NewLexer(false)
// the lexer error functions are ignored in lenient mode
lexer.SetLexerErrorFunc(func(ls goply.LexerState) error {
return fmt.Errorf("there was an error")
})
_, err := lexer.GetTokenStream("123")
if err != nil {
t.Error("the lexer returned an error in lenient mode")
}
}