-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenizer.go
74 lines (62 loc) · 1.38 KB
/
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package nietzsche
import (
"errors"
"strings"
)
// Token type
type TokenType int
const (
TextToken TokenType = iota
ValueToken
OpenGroupToken
OpenInvertedGroupToken
CloseGroupToken
)
// Token
type Token struct {
Type TokenType
Value string
}
func Tokenize(template string) ([]Token, error) {
var tokens []Token
var buffer strings.Builder
var bracket int = 0
for _, char := range template {
if char == '{' {
bracket += 1
if bracket == 2 && buffer.Len() != 0 {
tokens = append(tokens, Token{Type: TextToken, Value: buffer.String()})
buffer.Reset()
}
} else if char == '}' {
bracket -= 1
if bracket == 0 && buffer.Len() != 0 {
tokens = append(tokens, createTagToken(buffer.String()))
buffer.Reset()
}
} else {
buffer.WriteRune(char)
}
}
if bracket != 0 {
return nil, errors.New("Unexpected bracket")
}
if buffer.Len() != 0 {
tokens = append(tokens, Token{Type: TextToken, Value: buffer.String()})
}
return tokens, nil
}
func createTagToken(val string) Token {
trimmed := strings.TrimSpace(val)
var head byte = trimmed[0]
var tail string = strings.TrimSpace(trimmed[1:])
switch head {
case '#':
return Token{Type: OpenGroupToken, Value: tail}
case '^':
return Token{Type: OpenInvertedGroupToken, Value: tail}
case '/':
return Token{Type: CloseGroupToken, Value: tail}
}
return Token{Type: ValueToken, Value: trimmed}
}