-
Notifications
You must be signed in to change notification settings - Fork 1
/
tokenizer.go
59 lines (48 loc) · 969 Bytes
/
tokenizer.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
package sqle
import (
"regexp"
"sync"
)
var (
tokenRegexp = regexp.MustCompile(`<\w+>|\{\w+\}`)
tokenizers = make(map[string]*Tokenizer)
tokenizersMutex sync.RWMutex
)
type Tokenizer struct {
Raw string
Tokens []Token
}
func Tokenize(text string) *Tokenizer {
tokenizersMutex.RLock()
tz, ok := tokenizers[text]
tokenizersMutex.RUnlock()
if ok {
return tz
}
indices := tokenRegexp.FindAllStringIndex(text, -1)
tz = &Tokenizer{
Raw: text,
}
start := 0
for _, p := range indices {
s := p[0]
if s > start {
tz.Tokens = append(tz.Tokens, Text(text[start:s]))
}
// input
if text[s] == '<' {
tz.Tokens = append(tz.Tokens, Input(text[s+1:p[1]-1]))
} else {
// params
tz.Tokens = append(tz.Tokens, Param(text[s+1:p[1]-1]))
}
start = p[1]
}
if start < len(text) {
tz.Tokens = append(tz.Tokens, Text(text[start:]))
}
tokenizersMutex.Lock()
tokenizers[text] = tz
tokenizersMutex.Unlock()
return tz
}