-
Notifications
You must be signed in to change notification settings - Fork 10
/
lexer.go
688 lines (560 loc) · 12.3 KB
/
lexer.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
// Adapted from golang.org/src/bufio/bufio.go, with this license:
//
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file associated with
// the Go sources.
//
// Objectives
//
// - reduce the number of Read's to the underlying reader.
// - multiple byte unreads possible.
// - methods for reading Byte, Rune, String, Token, Space, etc, adapted to the needs
// of parsing OGDL text and paths
//
package ogdl
import (
"bytes"
"errors"
"io"
"strconv"
"unicode"
"unicode/utf8"
)
const (
bufSize = 4096
halfSize = 4096 / 2
)
var (
errNegativeRead = errors.New("reader returned negative count from Read")
)
// Lexer implements buffering for an io.Reader object, with multiple byte unread
// operations allowed.
type Lexer struct {
buf []byte
rd io.Reader // reader provided by the client
r int // buf read position
lastByte int // If not -1, then the buffer contains the last byte of the stream at this position.
lastRuneSize []int // used by UnreadRune.
err error
}
const maxConsecutiveEmptyReads = 100
// NewLexer returns a new Lexer whose buffer has the default size.
func NewLexer(rd io.Reader) *Lexer {
p := Lexer{}
p.rd = rd
p.lastByte = bufSize
p.buf = make([]byte, bufSize)
p.r = -1
p.fill()
return &p
}
// fill reads a new chunk into the buffer.
//
// The first time, the buffer is filled completely. After reading the last byte from
// the buffer, the last half is preserved and moved to the start, and the other
// half filled with new bytes, if available.
func (p *Lexer) fill() {
if p.r >= 0 && p.r < bufSize {
return
}
// Read new data: try a limited number of times.
// The first time read the full buffer, else only half.
offset := 0
if p.r >= 0 {
copy(p.buf, p.buf[halfSize:])
p.r = halfSize
offset = halfSize
} else {
p.r = 0
}
for i := maxConsecutiveEmptyReads; i > 0; i-- {
n, err := p.rd.Read(p.buf[offset:])
if n < 0 {
panic(errNegativeRead)
}
if err != nil {
p.err = err
break
}
offset += n
if offset >= halfSize {
break
}
}
p.lastByte = offset
}
func (p *Lexer) Error() error {
err := p.err
p.err = nil
return err
}
// PeekByte returns the next byte witohut consuming it
func (p *Lexer) PeekByte() byte {
c, err := p.Byte()
if err != nil {
return 0
}
p.UnreadByte()
return c
}
// PeekRune returns the next rune witohut consuming it
func (p *Lexer) PeekRune() (rune, error) {
r, err := p.Rune()
if err != nil {
return 0, nil
}
return r, p.UnreadRune()
}
// Byte reads and returns a single byte.
// If no byte is available, returns 0 and an error.
func (p *Lexer) Byte() (byte, error) {
if p.lastByte < bufSize && p.r >= p.lastByte {
p.r = p.lastByte + 1
return 0, ErrEOS
}
c := p.buf[p.r]
p.r++
p.fill()
return c, nil
}
// UnreadByte unreads the last byte. It can unread all buffered bytes.
func (p *Lexer) UnreadByte() {
if p.r <= 0 {
return
}
p.r--
}
// Rune reads a single UTF-8 encoded Unicode character and returns the
// rune. If the encoded rune is invalid, it consumes one byte
// and returns unicode.ReplacementChar (U+FFFD) with a size of 1.
func (p *Lexer) Rune() (rune, error) {
p.fill()
r, size := rune(p.buf[p.r]), 1
if r >= utf8.RuneSelf {
r, size = utf8.DecodeRune(p.buf[p.r:p.lastByte])
}
p.r += size
p.lastRuneSize = append(p.lastRuneSize, size)
return r, nil
}
// UnreadRune unreads the last rune.
func (p *Lexer) UnreadRune() error {
if len(p.lastRuneSize) == 0 {
return ErrInvalidUnread
}
p.r -= p.lastRuneSize[len(p.lastRuneSize)-1]
p.lastRuneSize = p.lastRuneSize[:len(p.lastRuneSize)-1]
return nil
}
// String is a concatenation of characters that are > 0x20
func (p *Lexer) String() (string, bool) {
var buf []byte
for {
c, _ := p.Byte()
if !IsTextChar(c) {
break
}
buf = append(buf, c)
}
p.UnreadByte()
return string(buf), len(buf) > 0
}
// StringStop is a concatenation of text bytes that are not in the parameter stopBytes
func (p *Lexer) StringStop(stopBytes []byte) (string, bool) {
var buf []byte
for {
c, _ := p.Byte()
if !IsTextChar(c) || bytes.IndexByte(stopBytes, c) != -1 {
break
}
buf = append(buf, c)
}
p.UnreadByte()
return string(buf), len(buf) > 0
}
// Break (= newline) is NL, CR or CR+NL
func (p *Lexer) Break() bool {
c, _ := p.Byte()
if c == '\r' {
c, _ = p.Byte()
}
if c == '\n' {
return true
}
p.UnreadByte()
return false
}
// End returns true if the end of stream has been reached.
func (p *Lexer) End() bool {
c, err := p.Byte()
if err != nil {
return true
}
if IsEndChar(c) {
return true
}
p.UnreadByte()
return false
}
// WhiteSpace is equivalent to Space | Break. It consumes all white space,
// whether spaces, tabs or newlines
func (p *Lexer) WhiteSpace() bool {
any := false
for {
c, _ := p.Byte()
if c != 13 && c != 10 && c != 9 && c != 32 {
break
}
any = true
}
p.UnreadByte()
return any
}
// Space is (0x20|0x09)+. It returns a boolean indicating
// if space has been found, and an integer indicating
// how many spaces, iff uniform (either all 0x20 or 0x09)
func (p *Lexer) Space() (int, byte) {
// Need a bufio that unreads many bytes for the Block case
n := 0
m := 0
for {
c, _ := p.Byte()
if c != '\t' && c != ' ' {
break
}
if c == ' ' {
n++
} else {
m++
}
}
p.UnreadByte()
var r byte
if m == 0 {
r = ' '
} else if n == 0 {
r = '\t'
}
return n + m, r
}
// Space is (0x20|0x09)+. It return the number of spaces found (whether
// tabs or spaces), and a byte than can have the values 0, ' ' and '\t'
// indicating mixed, all spaces or all tabs
// This version is intender for consuming max spaces at most
func (p *Lexer) SpaceMax(max int) (int, byte) {
spaces := 0
tabs := 0
for {
c, _ := p.Byte()
if c != '\t' && c != ' ' {
p.UnreadByte()
break
}
if c == ' ' {
spaces++
} else {
tabs++
}
if spaces == max || tabs == max {
break
}
}
var r byte
if tabs == 0 {
r = ' '
} else if spaces == 0 {
r = '\t'
}
return spaces + tabs, r
}
// Quoted string. Can have newlines in it. It returns the string if any, a bool
// indicating if a quoted string was found, and a possible error.
func (p *Lexer) Quoted(ind int) (string, bool, error) {
c1, _ := p.Byte()
if c1 != '"' && c1 != '\'' && c1 != '`' {
p.UnreadByte()
return "", false, nil
}
var buf []byte
var c2 byte
for {
c, _ := p.Byte()
if IsEndChar(c) {
return "", false, ErrUnterminatedQuotedString
}
if c == c1 && c1 == '`' {
break
}
if c == c1 && c2 != '\\' {
break
}
if c == '\\' {
c2 = c
continue
}
// \" -> ", \' -> '
if c2 == '\\' && c != '\'' && c != '"' {
buf = append(buf, '\\')
}
buf = append(buf, c)
if c == 10 {
n, u := p.SpaceMax(ind)
if u == 0 {
return "", false, ErrSpaceNotUniform
}
if n < ind {
break
}
// There are n spaces. Skip lnl spaces and add rest.
/*for ; n-ind > 0; n-- {
buf = append(buf, u)
}*/
}
c2 = c
}
return string(buf), true, nil
}
// Token8 reads from the Parser input stream and returns
// a token, if any. A token is defined as a sequence of
// Unicode letters and/or numbers and/or _.
func (p *Lexer) Token8() (string, bool) {
var buf []rune
for {
c, _ := p.Rune()
if !isTokenChar(c) {
break
}
buf = append(buf, c)
}
p.UnreadRune()
return string(buf), len(buf) > 0
}
// Integer returns true if it finds an (unsigned) integer at the current
// parser position. It returns also the number found.
func (p *Lexer) Integer() (string, bool) {
var buf []byte
for {
c, _ := p.Byte()
if !IsDigit(rune(c)) {
break
}
buf = append(buf, c)
}
p.UnreadByte()
return string(buf), len(buf) > 0
}
// Number returns true if it finds a number at the current
// parser position. It returns also the number found.
// TODO recognize exp notation ?
func (p *Lexer) Number() (string, bool) {
var buf []byte
var sign byte
point := false
c := p.PeekByte()
if c == '-' || c == '+' {
sign = c
p.Byte()
}
for {
c, _ := p.Byte()
if !IsDigit(rune(c)) {
if !point && c == '.' {
point = true
buf = append(buf, c)
continue
}
break
}
buf = append(buf, c)
}
p.UnreadByte()
if sign == '-' {
return "-" + string(buf), len(buf) > 0
}
return string(buf), len(buf) > 0
}
// Operator returns true if it finds an operator at the current parser position
// It returns also the operator found.
func (p *Lexer) Operator() (string, bool) {
var buf []byte
for {
c, _ := p.Byte()
if !isOperatorChar(c) {
break
}
buf = append(buf, c)
}
p.UnreadByte()
return string(buf), len(buf) > 0
}
// TemplateText parses text in a template.
func (p *Lexer) TemplateText() (string, bool) {
var buf []byte
for {
c, _ := p.Byte()
if !isTemplateTextChar(c) {
break
}
buf = append(buf, c)
}
p.UnreadByte()
return string(buf), len(buf) > 0
}
// Comment consumes anything from # up to the end of the line.
func (p *Lexer) Comment() bool {
c, _ := p.Byte()
if c == '#' {
c, _ = p.Byte()
if IsSpaceChar(c) {
for {
c, _ = p.Byte()
if IsEndChar(c) || IsBreakChar(c) {
break
}
}
return true
}
p.UnreadByte()
}
p.UnreadByte()
return false
}
// Block ::= '\\' NL LINES_OF_TEXT
func (p *Lexer) Block(nsp int) (string, bool) {
c, _ := p.Byte()
if c != '\\' {
p.UnreadByte()
return "", false
}
c, _ = p.Byte()
if c != 10 && c != 13 {
p.UnreadByte()
p.UnreadByte()
return "", false
}
// Read NL if CR was found
if c == 13 {
p.Byte()
}
buffer := &bytes.Buffer{}
// read lines while indentation is > nsp
for {
ns, u := p.Space()
if u == 0 || ns <= nsp {
break
}
// Adjust indentation if less that initial
// Read bytes until end of line
for {
c, _ = p.Byte()
if IsEndChar(c) {
break
}
if c == 13 {
continue
}
buffer.WriteByte(c)
if c == 10 {
break
}
}
}
// Remove trailing NLs
s := buffer.String()
for {
if len(s) == 0 {
break
}
c := s[len(s)-1]
if c == 10 {
s = s[0 : len(s)-1]
} else {
break
}
}
return s, true
}
// Scalar ::= quoted | string
func (p *Lexer) Scalar(n int) (string, bool) {
b, ok, _ := p.Quoted(n)
if ok {
return b, true
}
return p.String()
}
// ScalarType ::= string | int64 | float64 | bool
func (p *Lexer) ScalarType(n int) (interface{}, bool) {
b, ok, _ := p.Quoted(n)
if ok {
return b, true
}
s, ok := p.String()
if !ok {
return "", false
}
i, err := strconv.ParseInt(s, 10, 64)
if err == nil {
return i, true
}
f, err := strconv.ParseFloat(s, 64)
if err == nil {
return f, true
}
switch s {
case "true":
return true, true
case "false":
return false, true
default:
return s, true
}
}
// IsTextChar returns true for all integers > 32 and
// are not OGDL separators (parenthesis and comma)
func IsTextChar(c byte) bool {
return c > 32
}
// IsEndChar returns true for all integers < 32 that are not newline,
// carriage return or tab.
func IsEndChar(c byte) bool {
return c < 32 && c != '\t' && c != '\n' && c != '\r'
}
// IsEndRune returns true for all integers < 32 that are not newline,
// carriage return or tab.
func IsEndRune(c rune) bool {
return c < 32 && c != '\t' && c != '\n' && c != '\r'
}
// IsBreakChar returns true for 10 and 13 (newline and carriage return)
func IsBreakChar(c byte) bool {
return c == 10 || c == 13
}
// IsSpaceChar returns true for space and tab
func IsSpaceChar(c byte) bool {
return c == 32 || c == 9
}
// IsTemplateTextChar returns true for all not END chars and not $
func isTemplateTextChar(c byte) bool {
return !IsEndChar(c) && c != '$'
}
// IsOperatorChar returns true for all operator characters used in OGDL
// expressions (those parsed by NewExpression).
func isOperatorChar(c byte) bool {
if c < 0 {
return false
}
return bytes.IndexByte([]byte("+-*/%&|!<>=~^"), c) != -1
}
// ---- Following functions are the only ones that depend on Unicode --------
// IsLetter returns true if the given character is a letter, as per Unicode.
func IsLetter(c rune) bool {
return unicode.IsLetter(c) || c == '_'
}
// IsDigit returns true if the given character a numeric digit, as per Unicode.
func IsDigit(c rune) bool {
return unicode.IsDigit(c)
}
// IsTokenChar returns true for letters, digits and _ (as per Unicode).
func isTokenChar(c rune) bool {
return unicode.IsLetter(c) || unicode.IsDigit(c) || c == '_'
}