-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
68 lines (50 loc) · 1.2 KB
/
example_test.go
File metadata and controls
68 lines (50 loc) · 1.2 KB
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
package parser_test
import (
"fmt"
"vimagination.zapto.org/parser"
)
func Example() {
const (
TokenWhitespace parser.TokenType = iota
TokenWord
)
var start, word, whitespace parser.TokenFunc
whitespace = func(t *parser.Tokeniser) (parser.Token, parser.TokenFunc) {
t.AcceptRun(" ")
if t.Len() == 0 {
return t.Done()
}
return t.Return(TokenWhitespace, word)
}
word = func(t *parser.Tokeniser) (parser.Token, parser.TokenFunc) {
t.ExceptRun(" ")
if t.Len() == 0 {
return t.Done()
}
return t.Return(TokenWord, whitespace)
}
start = func(t *parser.Tokeniser) (parser.Token, parser.TokenFunc) {
if t.Peek() == ' ' {
return whitespace(t)
}
return word(t)
}
p := parser.New(parser.NewStringTokeniser("Hello World Foo Bar"))
p.TokeniserState(start)
for p.Peek().Type != parser.TokenDone {
tk := p.Next()
typ := "word"
if tk.Type == TokenWhitespace {
typ = "whitespace"
}
fmt.Printf("got token (%s): %q\n", typ, tk.Data)
}
// Output:
// got token (word): "Hello"
// got token (whitespace): " "
// got token (word): "World"
// got token (whitespace): " "
// got token (word): "Foo"
// got token (whitespace): " "
// got token (word): "Bar"
}