-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate.go
120 lines (105 loc) · 2.11 KB
/
translate.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
117
118
119
120
package translate
import (
"github.com/pkg/errors"
)
const (
TextTokenType = iota
VarTokenType
)
var EOFError = errors.New("EOF")
type Token interface {
toString() string
}
type JinjaTranslation struct {
original string
runes []rune
hasVars bool
tokens []Token
i int
currState uint
buff string
}
func NewJinjaTranslation(s string) *JinjaTranslation {
t := JinjaTranslation{}
t.tokenize(s)
return &t
}
func (tr *JinjaTranslation) toString() string {
s := ""
for _, t := range tr.tokens {
s += t.toString()
}
return s
}
func (tr *JinjaTranslation) peak() (rune, error) {
return tr.getAt(tr.i)
}
func (tr *JinjaTranslation) get() (rune, error) {
r, err := tr.getAt(tr.i)
tr.i += 1
return r, err
}
func (tr *JinjaTranslation) getAt(i int) (rune, error) {
if i >= len(tr.runes) {
return ' ', EOFError
}
return tr.runes[i], nil
}
func (tr *JinjaTranslation) thisAndNextAre(curr rune, expected rune) bool {
if curr != expected {
return false
}
n, _ := tr.peak()
if n != expected {
return false
}
return true
}
func (tr *JinjaTranslation) initTokenizer(s string) {
tr.i = 0
tr.original = s
tr.runes = []rune(s)
tr.currState = TextTokenType
tr.buff = ""
}
func (tr *JinjaTranslation) flush() string {
bufferContent := tr.buff
tr.buff = ""
return bufferContent
}
func (tr *JinjaTranslation) tokenize(s string) error {
tr.initTokenizer(s)
var err error
var r rune
for ; err == nil; r, err = tr.get() {
if string(r) == "\x00" {
continue
}
if err == EOFError {
break
}
if tr.currState == TextTokenType {
if tr.thisAndNextAre(r, '{') {
tr.tokens = append(tr.tokens, StringToken{s: tr.flush()})
tr.get()
tr.currState = VarTokenType
continue
}
}
if tr.currState == VarTokenType {
if tr.thisAndNextAre(r, '}') {
tr.tokens = append(tr.tokens, VariableToken{s: tr.flush()})
tr.get()
tr.hasVars = true
tr.currState = TextTokenType
continue
}
}
tr.buff += string(r)
}
if tr.currState != TextTokenType {
return errors.New("unclosed variable")
}
tr.tokens = append(tr.tokens, StringToken{s: tr.flush()})
return nil
}