forked from bufbuild/protocompile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lexer.go
1749 lines (1631 loc) · 43.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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020-2023 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package parser
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"math"
"strconv"
"strings"
"unicode/utf8"
"github.com/kralicky/protocompile/ast"
"github.com/kralicky/protocompile/reporter"
)
type runeReader struct {
data []byte
pos int
err error
mark int
// Enable this check to make input required to be valid UTF-8.
// For now, since protoc allows invalid UTF-8, default to false.
utf8Strict bool
savedPos int
savedErr error
}
func (rr *runeReader) save() {
rr.savedPos = rr.pos
rr.savedErr = rr.err
}
func (rr *runeReader) restore() {
rr.pos = rr.savedPos
rr.err = rr.savedErr
}
func (rr *runeReader) readRune() (r rune, size int, err error) {
if rr.err != nil {
return 0, 0, rr.err
}
if rr.pos == len(rr.data) {
rr.err = io.EOF
return 0, 0, rr.err
}
r, sz := utf8.DecodeRune(rr.data[rr.pos:])
if rr.utf8Strict && r == utf8.RuneError {
rr.err = fmt.Errorf("invalid UTF8 at offset %d: %x", rr.pos, rr.data[rr.pos])
return 0, 0, rr.err
}
rr.pos += sz
return r, sz, nil
}
func (rr *runeReader) offset() int {
return rr.pos
}
func (rr *runeReader) unreadRune(sz int) {
newPos := rr.pos - sz
if newPos < rr.mark {
if rr.err == io.EOF {
rr.err = nil
// un-reading EOF should not move the position
return
}
panic("unread past mark")
}
rr.pos = newPos
}
func (rr *runeReader) setMark() {
rr.mark = rr.pos
}
func (rr *runeReader) getMark() string {
return string(rr.data[rr.mark:rr.pos])
}
type insertSemiMode int
const (
atNextNewline = 1
immediate = 2 | atNextNewline
atEOF = 8
onlyIfLastTokenOnLine = 16
insertComma = 32
)
type protoLex struct {
input *runeReader
info *ast.FileInfo
handler *reporter.Handler
res *ast.FileNode
parsedSyntax string
prevSym ast.TerminalNode
prevOffset int
eof ast.Token
// if true, the lexer will insert a semicolon and set insertSemi to false
insertSemi insertSemiMode
inCompoundStringLiteral bool
inCompoundIdent bool
inExtensionIdent bool
inMethodDecl bool
inMethodTypeDecl bool
comments []ast.Token
}
var utf8Bom = []byte{0xEF, 0xBB, 0xBF}
func newLexer(in io.Reader, filename string, handler *reporter.Handler, version int32) (*protoLex, error) {
br := bufio.NewReader(in)
// if file has UTF8 byte order marker preface, consume it
marker, err := br.Peek(3)
if err == nil && bytes.Equal(marker, utf8Bom) {
_, _ = br.Discard(3)
}
contents, err := io.ReadAll(br)
if err != nil {
return nil, err
}
return &protoLex{
input: &runeReader{data: contents},
info: ast.NewFileInfo(filename, contents, version),
handler: handler,
}, nil
}
var keywords = map[string]int{
"bytes": _BYTES,
"bool": _BOOL,
"double": _DOUBLE,
"edition": _EDITION,
"enum": _ENUM,
"extend": _EXTEND,
"extensions": _EXTENSIONS,
"false": _FALSE,
"fixed32": _FIXED32,
"fixed64": _FIXED64,
"float": _FLOAT,
"group": _GROUP,
"import": _IMPORT,
"inf": _INF,
"infinity": _INF,
"int32": _INT32,
"int64": _INT64,
"map": _MAP,
"max": _MAX,
"message": _MESSAGE,
"nan": _NAN,
"oneof": _ONEOF,
"optional": _OPTIONAL,
"option": _OPTION,
"package": _PACKAGE,
"public": _PUBLIC,
"repeated": _REPEATED,
"required": _REQUIRED,
"reserved": _RESERVED,
"returns": _RETURNS,
"rpc": _RPC,
"service": _SERVICE,
"sfixed32": _SFIXED32,
"sfixed64": _SFIXED64,
"sint32": _SINT32,
"sint64": _SINT64,
"stream": _STREAM,
"string": _STRING,
"syntax": _SYNTAX,
"to": _TO,
"true": _TRUE,
"uint32": _UINT32,
"uint64": _UINT64,
"weak": _WEAK,
}
func (l *protoLex) maybeNewLine(r rune) {
if r == '\n' {
l.info.AddLine(l.input.offset())
}
}
func (l *protoLex) prev() ast.SourcePos {
return l.info.SourcePos(l.prevOffset)
}
func (l *protoLex) writeVirtualRune(lval *protoSymType, rn rune) int {
l.input.unreadRune(1)
l.setVirtualRune(lval, rn)
return int(rn)
}
func (l *protoLex) Lex(lval *protoSymType) int {
if l.handler.ReporterError() != nil {
// if error reporter already returned non-nil error,
// we can skip the rest of the input
return 0
}
l.comments = nil
for {
l.input.setMark()
l.prevOffset = l.input.offset()
c, sz, err := l.input.readRune()
if err == io.EOF {
if l.inCompoundIdent {
l.input.unreadRune(sz)
if l.inExtensionIdent {
l.endExtensionIdent(lval)
}
return l.endCompoundIdent(lval)
}
if l.insertSemi != 0 {
rn := ';'
if l.insertSemi&insertComma == insertComma {
rn = ','
}
l.insertSemi = 0
shouldInsertSemi := true
if l.prevSym != nil {
if prev, ok := l.prevSym.(*ast.RuneNode); ok && prev.Rune == rn {
shouldInsertSemi = false
}
}
if shouldInsertSemi {
return l.writeVirtualRune(lval, rn)
}
}
// insert virtual semicolons following ident tokens we might expect
// to be followed by EOF during editing ('extend', 'import')
if l.prevSym != nil {
switch prev := l.prevSym.(type) {
case *ast.IdentNode:
switch prev.Val {
case "extend", "import", "public", "weak":
return l.writeVirtualRune(lval, ';')
}
}
}
// we're not actually returning a rune, but this will associate
// accumulated comments as a trailing comment on last symbol
// (if appropriate)
l.setRune(lval, 0)
l.eof = lval.b.GetToken()
return 0
}
if err != nil {
l.setError(lval, err)
return _ERROR
}
if l.insertSemi&immediate == immediate {
rn := ';'
if l.insertSemi&insertComma == insertComma {
rn = ','
}
if c != rn {
l.insertSemi = 0
return l.writeVirtualRune(lval, rn)
}
l.insertSemi = 0
}
if strings.ContainsRune("\r\t\f\v ", c) {
// skip whitespace
continue
}
switch c {
case '}':
l.insertSemi = immediate
case '>':
l.insertSemi = immediate
case ']':
if l.prevSym != nil {
if rn, ok := l.prevSym.(*ast.RuneNode); !ok || (rn.Rune != ',' && rn.Rune != '[') {
return l.writeVirtualRune(lval, ',')
}
}
l.insertSemi = immediate
case '=':
if _, ok := l.matchNextRune(']'); ok {
l.insertSemi = immediate | insertComma
}
case ':':
if _, ok := l.matchNextRune('}'); ok {
if l.peekNewline() {
l.insertSemi = atNextNewline | onlyIfLastTokenOnLine
} else {
l.insertSemi = immediate
}
} else {
l.insertSemi = atNextNewline | onlyIfLastTokenOnLine
}
case '\n':
if l.insertSemi&atNextNewline != 0 {
rn := ';'
if l.insertSemi&insertComma == insertComma {
rn = ','
}
prev := l.prevSym
canInsert := true
switch prev := prev.(type) {
case *ast.RuneNode:
if rn == ';' {
canInsert = canDirectlyPrecedeVirtualSemi(prev.Rune)
} else {
canInsert = canDirectlyPrecedeVirtualComma(prev.Rune)
}
}
if canInsert {
if l.inCompoundIdent {
l.input.unreadRune(sz) // unread the newline
if l.inExtensionIdent {
// missing ')', as in 'foo.(bar\n'
l.endExtensionIdent(lval)
// continue here, as to end up in the else block below.
// can't return yet because we are still constructing an
// extension ident token
continue
} else {
// complete the compound ident first.
// this can happen when a '.' in a partial compound ident is
// immediately followed by a newline
return l.endCompoundIdent(lval)
}
}
l.insertSemi = 0
return l.writeVirtualRune(lval, rn)
}
l.insertSemi = 0
}
l.info.AddLine(l.input.offset())
continue
default:
if l.insertSemi&onlyIfLastTokenOnLine == onlyIfLastTokenOnLine {
if c != '/' {
l.insertSemi = 0
}
}
}
if c == '.' {
// decimal literals could start with a dot
cn, szn, err := l.input.readRune()
if err != nil {
// only recoverable situation here is if this is part of a compound
// identifier, for example 'option (foo).<EOF>'
l.input.unreadRune(szn)
if l.inCompoundIdent {
l.setRune(lval, c)
lval.cid = append(lval.cid, lval.b.AsComplexIdentComponent())
}
continue
}
if cn >= '0' && cn <= '9' {
l.readNumber()
token := l.input.getMark()
f, err := parseFloat(token)
if err != nil {
l.setError(lval, numError(err, "float", token))
return _ERROR
}
l.setFloat(lval, f, token)
if _, ok := l.matchNextRune(',', ']'); !ok {
l.insertSemi |= atNextNewline | onlyIfLastTokenOnLine
}
return _FLOAT_LIT
}
l.input.unreadRune(szn)
}
if c == '(' {
// distinguish between extension names and rpc methods
isExtensionLeftParen := true
if l.inMethodDecl {
// rpc Foo ( ... ) returns ( ... )
// ^
isExtensionLeftParen = false
} else if kw, ok := l.prevSym.(*ast.IdentNode); ok && kw.Val == "returns" {
// rpc Foo ( ... ) returns ( ... )
// ^
isExtensionLeftParen = false
}
if isExtensionLeftParen {
if l.inExtensionIdent {
// syntax error, e.g. '(('
l.setError(lval, errors.New("unexpected '(' in extension identifier"))
return _ERROR
}
l.beginExtensionIdent(lval)
l.setRune(lval, c)
lval.refp.open = lval.b
continue
} else {
l.inMethodTypeDecl = true
}
} else if c == ')' {
if l.inMethodTypeDecl {
// rpc Foo ( ... ) returns ( ... )
// ^ ^
if l.inCompoundIdent {
l.input.unreadRune(sz)
return l.endCompoundIdent(lval)
}
l.inMethodTypeDecl = false // order is important here
} else {
if l.inExtensionIdent {
l.setRune(lval, c)
lval.refp.close = lval.b
l.endExtensionIdent(lval)
} else if !l.inMethodTypeDecl {
// syntax error, e.g. '())'
l.setError(lval, errors.New("unexpected ')'"))
return _ERROR
}
r, nextDot := l.matchNextRune('.', '(')
if !nextDot {
return l.endCompoundIdent(lval)
}
if r == '(' {
// partial extension followed by another extension, e.g. from typing
// '(' to add a new extension to a compact option list (including the
// close paren inserted by the ide):
//
// int32 foo = 1 [
// (<cursor>)
// (a) = 1,
// (b) = 2
// ];
l.ErrExtendedSyntax("expected '='", CategoryMissingToken)
}
continue // continue reading compound ident
}
}
if c == '.' || c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') {
if c == '.' {
if !l.inCompoundIdent {
l.beginCompoundIdent(lval)
}
if l.peekWhitespace() {
l.maybeProcessPartialField(".")
}
l.setRune(lval, c)
lval.cid = append(lval.cid, lval.b.AsComplexIdentComponent())
continue
}
l.readIdentifier()
str := l.input.getMark()
l.maybeProcessPartialField(str)
// check if we are about to read (or continue) a compound identifier
if next, ok := l.matchNextRune('.', ')'); ok {
if !l.inCompoundIdent && next == '.' {
// need to consider whitespace here for keywords, so that we don't
// treat e.g. 'option .foo' as a compound ident 'option.foo'
if kw, ok := keywords[str]; ok {
if l.peekWhitespace() {
// this is a keyword, not a compound ident
l.setIdent(lval, str)
return kw
}
}
l.beginCompoundIdent(lval)
l.setIdent(lval, str)
lval.cid = append(lval.cid, lval.id.AsComplexIdentComponent())
continue
}
if l.inCompoundIdent {
l.setIdent(lval, str)
lval.cid = append(lval.cid, lval.id.AsComplexIdentComponent())
if next == ')' {
if l.inMethodTypeDecl {
return l.endCompoundIdent(lval)
} else if !l.inExtensionIdent {
// syntax error - something like 'foo.bar)'
l.setError(lval, errors.New("unexpected ')' in compound identifier"))
return _ERROR
}
}
continue
}
} else {
if l.inCompoundIdent {
if l.inExtensionIdent {
if l.peekNewline() {
// missing ')', as in 'foo.(bar\n'
l.setIdent(lval, str)
lval.cid = append(lval.cid, lval.id.AsComplexIdentComponent())
// this case is handled separately above, so we can just continue
// and let it encounter the newline as usual
continue
} else {
// an actual syntax error we can't recover from
l.setError(lval, fmt.Errorf("unexpected '%s' in extension identifier", string(c)))
return _ERROR
}
}
// end of compound ident
l.setIdent(lval, str)
lval.cid = append(lval.cid, lval.id.AsComplexIdentComponent())
return l.endCompoundIdent(lval)
}
}
if keyword, ok := keywords[str]; ok {
switch keyword {
case _RPC:
if l.canStartField() {
if next, nextRune := l.peekNextIdentsFast(2); len(next) == 1 && !strings.Contains(next[0], ".") && nextRune == '(' {
l.inMethodDecl = true
}
}
case _PACKAGE:
// package expressions are a bit ambiguous when no semicolon is present
if l.canStartFileElement() && l.peekWhitespace() {
l.insertSemi |= atNextNewline
}
case _OPTION:
if l.canStartFileElement() {
l.insertSemi |= atEOF
}
case _IMPORT:
if l.canStartFileElement() {
next, _ := l.peekNextIdentsFast(2)
if len(next) > 0 && next[0] == "import" {
// import
// import [public] "...";
l.insertSemi |= atNextNewline
} else if len(next) == 2 && (next[0] == "public" || next[0] == "weak") && next[1] == "import" {
// import public
// import "..."
l.insertSemi |= atNextNewline
}
}
case _EXTEND:
if l.canStartField() || l.canStartFileElement() {
next, nextRune := l.peekNextIdentsFast(2)
switch len(next) {
case 0:
if l.peekNewline() {
l.insertSemi |= atNextNewline
}
case 1:
if nextRune != '{' {
l.insertSemi |= atNextNewline
}
case 2:
l.insertSemi |= atNextNewline
}
}
case _RETURNS:
l.inMethodDecl = false
case _MAX:
// "to max" always ends a reserved expression
if l.prevSym != nil {
if ident, ok := l.prevSym.(*ast.IdentNode); ok && ident.Val == "to" {
if _, ok := l.matchNextRune(';', ',', '['); !ok {
l.insertSemi |= immediate
}
}
}
}
l.setIdent(lval, str)
return keyword
}
// inf and nan are a special case, they are case-insensitive
if ln := len(str); ln == 3 || ln == 8 {
switch strings.ToLower(str) {
case "inf", "infinity":
l.setIdent(lval, str)
return _INF
case "nan":
l.setIdent(lval, str)
return _NAN
}
}
l.setIdent(lval, str)
return _SINGULAR_IDENT
}
if c >= '0' && c <= '9' {
// integer or float literal
l.readNumber()
token := l.input.getMark()
if strings.HasPrefix(token, "0x") || strings.HasPrefix(token, "0X") {
// hexadecimal
ui, err := strconv.ParseUint(token[2:], 16, 64)
if err != nil {
l.setError(lval, numError(err, "hexadecimal integer", token[2:]))
return _ERROR
}
l.setInt(lval, ui, token)
if _, ok := l.matchNextRune(',', ']'); !ok {
l.insertSemi |= atNextNewline | onlyIfLastTokenOnLine
}
return _INT_LIT
}
if strings.ContainsAny(token, ".eE") {
// floating point!
f, err := parseFloat(token)
if err != nil {
l.setError(lval, numError(err, "float", token))
return _ERROR
}
l.setFloat(lval, f, token)
if _, ok := l.matchNextRune(',', ']'); !ok {
l.insertSemi |= atNextNewline | onlyIfLastTokenOnLine
}
return _FLOAT_LIT
}
// integer! (decimal or octal)
base := 10
if token[0] == '0' {
base = 8
}
ui, err := strconv.ParseUint(token, base, 64)
if err != nil {
kind := "integer"
if base == 8 {
kind = "octal integer"
} else if numErr, ok := err.(*strconv.NumError); ok && numErr.Err == strconv.ErrRange {
// if it's too big to be an int, parse it as a float
var f float64
kind = "float"
f, err = parseFloat(token)
if err == nil {
l.setFloat(lval, f, token)
return _FLOAT_LIT
}
}
l.setError(lval, numError(err, kind, token))
return _ERROR
}
if _, ok := l.matchNextRune('[', ',', ']'); !ok {
l.insertSemi |= atNextNewline | onlyIfLastTokenOnLine
}
l.setInt(lval, ui, token)
return _INT_LIT
}
if c == '\'' || c == '"' {
// string literal
str, raw, err := l.readStringLiteral(c)
if err != nil {
l.setError(lval, err)
return _ERROR
}
l.setString(lval, str, raw)
// check if this is a compound string literal
if _, ok := l.matchNextRune('"', '\''); ok {
l.inCompoundStringLiteral = true
// continue reading
continue
}
l.inCompoundStringLiteral = false
if _, ok := l.matchNextRune(',', ']'); !ok {
l.insertSemi |= atNextNewline | onlyIfLastTokenOnLine
}
return _STRING_LIT
}
if c == '/' {
// comment
cn, szn, err := l.input.readRune()
if err != nil {
l.setRune(lval, '/')
return int(c)
}
if cn == '/' {
if hasErr := l.skipToEndOfLineComment(lval); hasErr {
return _ERROR
}
l.comments = append(l.comments, l.newToken())
continue
}
if cn == '*' {
ok, hasErr := l.skipToEndOfBlockComment(lval)
if hasErr {
return _ERROR
}
if !ok {
l.setError(lval, errors.New("block comment never terminates, unexpected EOF"))
return _ERROR
}
l.comments = append(l.comments, l.newToken())
continue
}
l.input.unreadRune(szn)
}
if l.inCompoundIdent {
l.input.unreadRune(sz)
if l.inExtensionIdent {
l.endExtensionIdent(lval)
}
return l.endCompoundIdent(lval)
}
if c < 32 || c == 127 {
l.setError(lval, errors.New("invalid control character"))
return _ERROR
}
if !strings.ContainsRune(";,.:=-+(){}[]<>/", c) {
l.setError(lval, errors.New("invalid character"))
return _ERROR
}
l.setRune(lval, c)
return int(c)
}
}
func parseFloat(token string) (float64, error) {
// strconv.ParseFloat allows _ to separate digits, but protobuf does not
if strings.ContainsRune(token, '_') {
return 0, &strconv.NumError{
Func: "parseFloat",
Num: token,
Err: strconv.ErrSyntax,
}
}
f, err := strconv.ParseFloat(token, 64)
if err == nil {
return f, nil
}
if numErr, ok := err.(*strconv.NumError); ok && numErr.Err == strconv.ErrRange && math.IsInf(f, 1) {
// protoc doesn't complain about float overflow and instead just uses "infinity"
// so we mirror that behavior by just returning infinity and ignoring the error
return f, nil
}
return f, err
}
func (l *protoLex) newToken() ast.Token {
offset := l.input.mark
length := l.input.pos - l.input.mark
return l.info.AddToken(offset, length)
}
func (l *protoLex) setPrevAndAddComments(n ast.TerminalNode) {
comments := l.comments
l.comments = nil
var prevTrailingComments []ast.Token
if l.prevSym != nil && len(comments) > 0 {
prevEnd := l.info.NodeInfo(l.prevSym).End().Line
info := l.info.NodeInfo(n)
nStart := info.Start().Line
if nStart == prevEnd {
if rn, ok := n.(*ast.RuneNode); ok && rn.Rune == 0 {
// if current token is EOF, pretend its on separate line
// so that the logic below can attribute a final trailing
// comment to the previous token
nStart++
}
}
c := comments[0]
commentInfo := l.info.TokenInfo(c)
commentStart := commentInfo.Start().Line
if nStart > prevEnd && commentStart == prevEnd {
// Comment starts right after the previous token. If it's a
// line comment, we record that as a trailing comment.
//
// But if it's a block comment, it is only a trailing comment
// if there are multiple comments or if the block comment ends
// on a line before n.
canDonate := strings.HasPrefix(commentInfo.RawText(), "//") ||
len(comments) > 1 || commentInfo.End().Line < nStart
if canDonate {
prevTrailingComments = comments[:1]
comments = comments[1:]
}
}
}
// now we can associate comments
for _, c := range prevTrailingComments {
l.info.AddComment(c, l.prevSym.GetToken())
}
if rn, ok := n.(*ast.RuneNode); ok && rn.Virtual {
for _, c := range comments {
l.info.AddVirtualComment(c, l.prevSym.GetToken(), n.GetToken())
}
} else {
for _, c := range comments {
l.info.AddComment(c, n.GetToken())
}
}
l.prevSym = n
}
func (l *protoLex) setString(lval *protoSymType, val string, raw []byte) {
node := &ast.StringLiteralNode{
Token: l.newToken(),
Val: val,
Raw: raw,
}
if l.inCompoundStringLiteral && lval.sv != nil {
switch sv := lval.sv.Unwrap().(type) {
case *ast.StringLiteralNode:
lval.sv = (&ast.CompoundStringLiteralNode{Elements: []*ast.StringValueNode{sv.AsStringValueNode(), node.AsStringValueNode()}}).AsStringValueNode()
case *ast.CompoundStringLiteralNode:
lval.sv = (&ast.CompoundStringLiteralNode{Elements: append(sv.Elements, node.AsStringValueNode())}).AsStringValueNode()
}
} else {
lval.sv = node.AsStringValueNode()
}
l.setPrevAndAddComments(node)
}
func (l *protoLex) setIdent(lval *protoSymType, val string) {
lval.id = &ast.IdentNode{Token: l.newToken(), Val: val}
l.setPrevAndAddComments(lval.id)
}
func (l *protoLex) setInt(lval *protoSymType, val uint64, raw string) {
lval.i = &ast.UintLiteralNode{Token: l.newToken(), Val: val, Raw: raw}
l.setPrevAndAddComments(lval.i)
}
func (l *protoLex) setFloat(lval *protoSymType, val float64, raw string) {
lval.f = &ast.FloatLiteralNode{Token: l.newToken(), Val: val, Raw: raw}
l.setPrevAndAddComments(lval.f)
}
func (l *protoLex) setRune(lval *protoSymType, val rune) {
lval.b = &ast.RuneNode{Token: l.newToken(), Rune: val}
l.setPrevAndAddComments(lval.b)
}
func (l *protoLex) setVirtualRune(lval *protoSymType, val rune) {
lval.b = &ast.RuneNode{Token: l.newToken(), Rune: val, Virtual: true}
l.setPrevAndAddComments(lval.b)
}
func (l *protoLex) setError(lval *protoSymType, err error) {
lval.err, _ = l.addSourceError(err)
}
func (l *protoLex) beginCompoundIdent(lval *protoSymType) {
l.inCompoundIdent = true
lval.cid = []*ast.ComplexIdentComponent{}
}
func (l *protoLex) beginExtensionIdent(lval *protoSymType) {
if l.inExtensionIdent {
panic("bug: already in extension ident")
}
if !l.inCompoundIdent {
l.beginCompoundIdent(lval)
}
l.inExtensionIdent = true
lval.cid, lval.xid = []*ast.ComplexIdentComponent{}, lval.cid
lval.refp = &fieldRefParens{}
}
func (l *protoLex) endExtensionIdent(lval *protoSymType) {
var name *ast.IdentValueNode
var nIdents, nDots int
for _, c := range lval.cid {
switch c.GetVal().(type) {
case *ast.ComplexIdentComponent_Ident:
nIdents++
case *ast.ComplexIdentComponent_Dot:
nDots++
}
}
switch {
case nDots == 0 && nIdents == 1:
name = lval.cid[0].GetIdent().AsIdentValueNode()
case nDots > 0:
name = (&ast.CompoundIdentNode{Components: lval.cid}).AsIdentValueNode()
default:
if ast.ExtendedSyntaxEnabled {
l.ErrExtendedSyntax("extension name cannot be empty", CategoryEmptyDecl)
} else {
l.Error("extension name cannot be empty")
}
}
lval.xid = append(lval.xid, (&ast.FieldReferenceNode{Open: lval.refp.open, Name: name, Close: lval.refp.close}).AsComplexIdentComponent())
lval.cid, lval.xid = lval.xid, nil
lval.refp = nil
l.inExtensionIdent = false
}
func (l *protoLex) endCompoundIdent(lval *protoSymType) (result int) {
defer func() {
// after a qualified ident, the next token has limited valid options:
// - a singular ident, as in 'foo.Bar baz = 1;'
// - ';' (in various contexts)
// - '>' as in 'map<string, foo.Bar>'
// - '=' as in 'option foo.bar = 1;'
// - ',' as in '[foo.bar,]: xyz' (virtual comma)
// - '/' as in '[type.googleapis.com/...]
// - ')' as in 'returns (foo.bar)'
//
// importantly, it is not possible to have a qualified ident followed by
// *two* idents. this is important to help disambiguate the following
// scenario:
//
// message Foo {
// foo.bar
// string baz = 1;
// }
//
// in this case, 'foo.bar' is a partial field, and 'string baz = 1'; is
// a separate field. we can look-ahead after lexing 'foo.bar' to see if
// we can insert a semicolon immediately to split the two fields.
switch result {
case _QUALIFIED_IDENT, _FULLY_QUALIFIED_IDENT:
idents, _ := l.peekNextIdentsFast(2)
if len(idents) == 2 {
l.insertSemi = immediate
}
}
}()
// possible compound identifiers:
// 1. _QUALIFIED_IDENT: compound ident without a leading dot
// ex: 'foo.bar.baz', 'foo.Bar', 'foo.'
// 2. _FULLY_QUALIFIED_IDENT: compound ident with a leading dot
// ex: '.foo.bar.baz', '.foo.Bar', '.foo.'
// 3. _EXTENSION_NAME: compound ident where one or more components is an
// extension name. cannot start with a dot.
// ex: '(foo.bar).baz', '(foo.Bar)', '(foo.)', 'foo.(bar).'
if l.inExtensionIdent {
panic("bug (lexer): cannot call endCompoundIdent() before endExtensionIdent()")
}
if lval.cid == nil {
panic("bug (lexer): compound ident is nil")
}
var nIdents, nDots, nRefs int
for _, c := range lval.cid {
switch c.GetVal().(type) {
case *ast.ComplexIdentComponent_Ident:
nIdents++
case *ast.ComplexIdentComponent_Dot:
nDots++
case *ast.ComplexIdentComponent_FieldRef:
nRefs++
}
}
if nIdents > 0 && nDots == 0 {
panic("bug (lexer): compound ident has no dots")
}
defer func() {
lval.cid = nil
l.inCompoundIdent = false
}()
if nIdents == 0 && nRefs == 0 {
lval.idv = (&ast.CompoundIdentNode{Components: lval.cid}).AsIdentValueNode()
return _FULLY_QUALIFIED_IDENT // '.' (invalid, but important for completion)
}
if nRefs > 0 {
if len(lval.cid) > 1 {
first := lval.cid[0].GetDot()
second := lval.cid[1].GetFieldRef()
if first != nil && second != nil && second.IsExtension() {
// warn on extension idents that start with '.(foo)'