Debian Codegraph @

token/lexer.go

raw
1 package token
2
3 import (
4 "bytes"
5 "fmt"
6 "strconv"
7 )
8
9 const (
10 eof = 0
11 dataElementDelimiter = '+'
12 groupDataElementDelimiter = ':'
13 segmentDelimiter = '\''
14 escapeCharacter = '?'
15 binaryIdentifier = '@'
16 )
17
18 // LexerStateFn represents a state function for the lexer.
19 type LexerStateFn func(*Lexer) LexerStateFn
20
21 // NewLexer creates a new scanner for the input string.
22 func NewLexer(name string, input []byte) *Lexer {
23 l := &Lexer{
24 name: name,
25 input: input,
26 state: lexStart,
27 tokens: make(chan Token, 2), // Two token sufficient.
28 }
29 return l
30 }
31
32 // A Lexer is a HBCI data element lexer based on an input string
33 type Lexer struct {
34 name string // the name of the input; used only for error reports.
35 input []byte // the data being scanned.
36 state LexerStateFn // the next lexing function to enter
37 pos int // current position in the input.
38 start int // start position of this item.
39 tokens chan Token // channel of scanned tokens.
40 }
41
42 // SetEntryPoint sets the initial state of the lexer. The lexer will reset itself to use the
43 // new entryPoint properly
44 func (l *Lexer) SetEntryPoint(entryPoint LexerStateFn) {
45 l.reset()
46 l.state = entryPoint
47 }
48
49 func (l *Lexer) reset() {
50 l.pos = 0
51 l.start = 0
52 l.tokens = make(chan Token, 2)
53 }
54
55 func (l *Lexer) run() {
56 for state := lexStart; state != nil; {
57 state = state(l)
58 }
59 close(l.tokens) // No more tokens will be delivered.
60 }
61
62 // Next returns the next item from the input.
63 func (l *Lexer) Next() Token {
64 for {
65 select {
66 case item, ok := <-l.tokens:
67 if ok {
68 return item
69 }
70
71 panic(fmt.Errorf("No items left"))
72 default:
73 l.state = l.state(l)
74 if l.state == nil {
75 close(l.tokens)
76 }
77 }
78 }
79 }
80
81 // HasNext returns true if there are tokens left, false if EOF has reached
82 func (l *Lexer) HasNext() bool {
83 return l.state != nil
84 }
85
86 // emit passes a token back to the client.
87 func (l *Lexer) emit(t Type) {
88 val := l.input[l.start:l.pos]
89 l.tokens <- New(t, val, l.start)
90 l.start = l.pos
91 }
92
93 // next returns the next byte in the input.
94 func (l *Lexer) next() byte {
95 if l.pos >= len(l.input) {
96 return eof
97 }
98 b := l.input[l.pos]
99 l.pos++
100 return b
101 }
102
103 // ignore skips over the pending input before this point.
104 func (l *Lexer) ignore() {
105 l.start = l.pos
106 }
107
108 // backup steps back one byte.
109 // Can be called only once per call of next.
110 func (l *Lexer) backup() {
111 l.pos--
112 }
113
114 // peek returns but does not consume
115 // the next byte in the input.
116 func (l *Lexer) peek() byte {
117 r := l.next()
118 l.backup()
119 return r
120 }
121
122 // accept consumes the next byte
123 // if it's from the valid set.
124 func (l *Lexer) accept(valid ...byte) bool {
125 if bytes.IndexByte(valid, l.next()) >= 0 {
126 return true
127 }
128 l.backup()
129 return false
130 }
131
132 // acceptRun consumes a run of bytes from the valid set.
133 func (l *Lexer) acceptRun(valid []byte) {
134 for bytes.IndexByte(valid, l.next()) >= 0 {
135 }
136 l.backup()
137 }
138
139 // error returns an error token and terminates the scan by passing
140 // back a nil pointer that will be the next state, terminating l.run.
141 func (l *Lexer) errorf(format string, args ...interface{}) LexerStateFn {
142 err := fmt.Sprintf(format, args...)
143 l.tokens <- New(ERROR, []byte(err), l.start)
144 return nil
145 }
146
147 // state functions
148
149 func lexStart(l *Lexer) LexerStateFn {
150 switch r := l.next(); {
151 case r == dataElementDelimiter:
152 l.emit(DATA_ELEMENT_SEPARATOR)
153 return lexStart
154 case r == segmentDelimiter:
155 l.emit(SEGMENT_END_MARKER)
156 return lexStart
157 case r == groupDataElementDelimiter:
158 l.emit(GROUP_DATA_ELEMENT_SEPARATOR)
159 return lexStart
160 case r == binaryIdentifier:
161 l.backup()
162 return lexBinaryData
163 case r == eof:
164 // Correctly reached EOF.
165 l.emit(EOF)
166 return nil
167 case r == '0':
168 l.backup()
169 return lexDigit
170 case ('1' <= r && r <= '9'):
171 l.backup()
172 return lexNumber
173 default:
174 l.backup()
175 return lexAlphaNumeric
176 }
177 }
178
179 func lexAlphaNumeric(l *Lexer) LexerStateFn {
180 text := false
181 for {
182 switch r := l.next(); {
183 case r == escapeCharacter:
184 if p := l.peek(); isSyntaxSymbol(p) {
185 l.next()
186 } else {
187 return l.errorf("Unexpected escape character")
188 }
189 case isDelimiter(r):
190 l.backup()
191 if text {
192 l.emit(TEXT)
193 } else {
194 l.emit(ALPHA_NUMERIC)
195 }
196 return lexStart
197 case r == eof:
198 return l.errorf("Unexpected end of input")
199 case (r == '\n' || r == '\r'):
200 text = true
201 }
202 }
203 }
204
205 func lexBinaryData(l *Lexer) LexerStateFn {
206 l.accept('@')
207 digits := []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
208 binaryLengthStart := l.pos
209 l.acceptRun(digits)
210 binaryLengthEnd := l.pos
211 if binaryLengthEnd == binaryLengthStart {
212 return l.errorf("Binary length can't be empty")
213 }
214 lengthBytes := l.input[binaryLengthStart:binaryLengthEnd]
215 length, err := strconv.Atoi(string(lengthBytes))
216 if err != nil {
217 return l.errorf("Binary length must contain of digits only")
218 }
219 if !l.accept('@') {
220 return l.errorf("Binary length must contain of digits only")
221 }
222 l.pos += length
223 p := l.peek()
224 if isDelimiter(p) {
225 l.emit(BINARY_DATA)
226 return lexStart
227 }
228 if p == eof {
229 return l.errorf("Unexpected end of input")
230 }
231 return l.errorf("Expected syntax symbol after binary data")
232 }
233
234 func lexDigit(l *Lexer) LexerStateFn {
235 digits := []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
236 l.accept('0')
237 // Only valid number with leading 0 is 0
238 if r := l.peek(); isDelimiter(r) {
239 l.emit(NUMERIC)
240 return lexStart
241 }
242 // Only valid float with leading 0 is value smaller than 1
243 if l.accept(',') {
244 l.acceptRun(digits)
245 if p := l.peek(); isDelimiter(p) {
246 l.emit(FLOAT)
247 return lexStart
248 }
249 return lexAlphaNumeric
250 }
251 l.acceptRun(digits)
252 if p := l.peek(); p == ',' {
253 return l.errorf("Malformed float")
254 }
255 if p := l.peek(); isDelimiter(p) {
256 l.emit(DIGIT)
257 return lexStart
258 }
259 return lexAlphaNumeric
260 }
261
262 func lexNumber(l *Lexer) LexerStateFn {
263 digits := []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
264 l.acceptRun(digits)
265 // is it a float?
266 if l.accept(',') {
267 l.acceptRun(digits)
268 if p := l.peek(); isDelimiter(p) {
269 l.emit(FLOAT)
270 return lexStart
271 }
272 return lexAlphaNumeric
273 }
274 if p := l.peek(); isDelimiter(p) {
275 l.emit(NUMERIC)
276 return lexStart
277 }
278 return lexAlphaNumeric
279
280 }
281
282 func isDelimiter(r byte) bool {
283 return r == dataElementDelimiter || r == segmentDelimiter || r == groupDataElementDelimiter
284 }
285
286 func isSyntaxSymbol(r byte) bool {
287 return r == dataElementDelimiter || r == segmentDelimiter || r == groupDataElementDelimiter || r == escapeCharacter || r == binaryIdentifier
288 }