Debian Codegraph @

syntax/scan.go

raw
1 // Copyright 2017 The Bazel Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package syntax
6
7 // A lexical scanner for Starlark.
8
9 import (
10 "fmt"
11 "io"
12 "log"
13 "math/big"
14 "os"
15 "strconv"
16 "strings"
17 "unicode"
18 "unicode/utf8"
19 )
20
21 // A Token represents a Starlark lexical token.
22 type Token int8
23
24 const (
25 ILLEGAL Token = iota
26 EOF
27
28 NEWLINE
29 INDENT
30 OUTDENT
31
32 // Tokens with values
33 IDENT // x
34 INT // 123
35 FLOAT // 1.23e45
36 STRING // "foo" or 'foo' or '''foo''' or r'foo' or r"foo"
37 BYTES // b"foo", etc
38
39 // Punctuation
40 PLUS // +
41 MINUS // -
42 STAR // *
43 SLASH // /
44 SLASHSLASH // //
45 PERCENT // %
46 AMP // &
47 PIPE // |
48 CIRCUMFLEX // ^
49 LTLT // <<
50 GTGT // >>
51 TILDE // ~
52 DOT // .
53 COMMA // ,
54 EQ // =
55 SEMI // ;
56 COLON // :
57 LPAREN // (
58 RPAREN // )
59 LBRACK // [
60 RBRACK // ]
61 LBRACE // {
62 RBRACE // }
63 LT // <
64 GT // >
65 GE // >=
66 LE // <=
67 EQL // ==
68 NEQ // !=
69 PLUS_EQ // += (keep order consistent with PLUS..GTGT)
70 MINUS_EQ // -=
71 STAR_EQ // *=
72 SLASH_EQ // /=
73 SLASHSLASH_EQ // //=
74 PERCENT_EQ // %=
75 AMP_EQ // &=
76 PIPE_EQ // |=
77 CIRCUMFLEX_EQ // ^=
78 LTLT_EQ // <<=
79 GTGT_EQ // >>=
80 STARSTAR // **
81
82 // Keywords
83 AND
84 BREAK
85 CONTINUE
86 DEF
87 ELIF
88 ELSE
89 FOR
90 IF
91 IN
92 LAMBDA
93 LOAD
94 NOT
95 NOT_IN // synthesized by parser from NOT IN
96 OR
97 PASS
98 RETURN
99 WHILE
100
101 // Reserved words (following Python); unused in Starlark
102
103 AS
104 // ASSERT // heavily used in our tests
105 ASYNC
106 AWAIT
107 CLASS
108 DEL
109 EXCEPT
110 FINALLY
111 FROM
112 GLOBAL
113 IMPORT
114 IS
115 NONLOCAL
116 RAISE
117 TRY
118 WITH
119 YIELD
120
121 maxToken
122 )
123
124 func (tok Token) String() string { return tokenNames[tok] }
125
126 // GoString is like String but quotes punctuation tokens.
127 // Use Sprintf("%#v", tok) when constructing error messages.
128 func (tok Token) GoString() string {
129 if tok >= PLUS && tok <= STARSTAR {
130 return "'" + tokenNames[tok] + "'"
131 }
132 return tokenNames[tok]
133 }
134
135 var tokenNames = [...]string{
136 ILLEGAL: "illegal token",
137 EOF: "end of file",
138 NEWLINE: "newline",
139 INDENT: "indent",
140 OUTDENT: "outdent",
141 IDENT: "identifier",
142 INT: "int literal",
143 FLOAT: "float literal",
144 STRING: "string literal",
145 PLUS: "+",
146 MINUS: "-",
147 STAR: "*",
148 SLASH: "/",
149 SLASHSLASH: "//",
150 PERCENT: "%",
151 AMP: "&",
152 PIPE: "|",
153 CIRCUMFLEX: "^",
154 LTLT: "<<",
155 GTGT: ">>",
156 TILDE: "~",
157 DOT: ".",
158 COMMA: ",",
159 EQ: "=",
160 SEMI: ";",
161 COLON: ":",
162 LPAREN: "(",
163 RPAREN: ")",
164 LBRACK: "[",
165 RBRACK: "]",
166 LBRACE: "{",
167 RBRACE: "}",
168 LT: "<",
169 GT: ">",
170 GE: ">=",
171 LE: "<=",
172 EQL: "==",
173 NEQ: "!=",
174 PLUS_EQ: "+=",
175 MINUS_EQ: "-=",
176 STAR_EQ: "*=",
177 SLASH_EQ: "/=",
178 SLASHSLASH_EQ: "//=",
179 PERCENT_EQ: "%=",
180 AMP_EQ: "&=",
181 PIPE_EQ: "|=",
182 CIRCUMFLEX_EQ: "^=",
183 LTLT_EQ: "<<=",
184 GTGT_EQ: ">>=",
185 STARSTAR: "**",
186 AND: "and",
187 BREAK: "break",
188 CONTINUE: "continue",
189 DEF: "def",
190 ELIF: "elif",
191 ELSE: "else",
192 FOR: "for",
193 IF: "if",
194 IN: "in",
195 LAMBDA: "lambda",
196 LOAD: "load",
197 NOT: "not",
198 NOT_IN: "not in",
199 OR: "or",
200 PASS: "pass",
201 RETURN: "return",
202 WHILE: "while",
203
204 // Reserved words (following Python); unused in Starlark
205
206 AS: "as",
207 // ASSERT: "assert", // heavily used in our tests
208 ASYNC: "async",
209 AWAIT: "await",
210 CLASS: "class",
211 DEL: "del",
212 EXCEPT: "except",
213 FINALLY: "finally",
214 FROM: "from",
215 GLOBAL: "global",
216 IMPORT: "import",
217 IS: "is",
218 NONLOCAL: "nonlocal",
219 RAISE: "raise",
220 TRY: "try",
221 WITH: "with",
222 YIELD: "yield",
223 }
224
225 // A FilePortion describes the content of a portion of a file.
226 // Callers may provide a FilePortion for the src argument of Parse
227 // when the desired initial line and column numbers are not (1, 1),
228 // such as when an expression is parsed from within larger file.
229 type FilePortion struct {
230 Content []byte
231 FirstLine, FirstCol int32
232 }
233
234 // A Position describes the location of a rune of input.
235 type Position struct {
236 file *string // filename (indirect for compactness)
237 Line int32 // 1-based line number; 0 if line unknown
238 Col int32 // 1-based column (rune) number; 0 if column unknown
239 }
240
241 // IsValid reports whether the position is valid.
242 func (p Position) IsValid() bool { return p.file != nil }
243
244 // Filename returns the name of the file containing this position.
245 func (p Position) Filename() string {
246 if p.file != nil {
247 return *p.file
248 }
249 return "<invalid>"
250 }
251
252 // MakePosition returns position with the specified components.
253 func MakePosition(file *string, line, col int32) Position { return Position{file, line, col} }
254
255 // add returns the position at the end of s, assuming it starts at p.
256 func (p Position) add(s string) Position {
257 if n := strings.Count(s, "\n"); n > 0 {
258 p.Line += int32(n)
259 s = s[strings.LastIndex(s, "\n")+1:]
260 p.Col = 1
261 }
262 p.Col += int32(utf8.RuneCountInString(s))
263 return p
264 }
265
266 func (p Position) String() string {
267 file := p.Filename()
268 if p.Line > 0 {
269 if p.Col > 0 {
270 return fmt.Sprintf("%s:%d:%d", file, p.Line, p.Col)
271 }
272 return fmt.Sprintf("%s:%d", file, p.Line)
273 }
274 return file
275 }
276
277 func (p Position) isBefore(q Position) bool {
278 if p.Line != q.Line {
279 return p.Line < q.Line
280 }
281 return p.Col < q.Col
282 }
283
284 // An scanner represents a single input file being parsed.
285 type scanner struct {
286 rest []byte // rest of input (in REPL, a line of input)
287 token []byte // token being scanned
288 pos Position // current input position
289 depth int // nesting of [ ] { } ( )
290 indentstk []int // stack of indentation levels
291 dents int // number of saved INDENT (>0) or OUTDENT (<0) tokens to return
292 lineStart bool // after NEWLINE; convert spaces to indentation tokens
293 keepComments bool // accumulate comments in slice
294 lineComments []Comment // list of full line comments (if keepComments)
295 suffixComments []Comment // list of suffix comments (if keepComments)
296
297 readline func() ([]byte, error) // read next line of input (REPL only)
298 }
299
300 func newScanner(filename string, src any, keepComments bool) (*scanner, error) {
301 var firstLine, firstCol int32 = 1, 1
302 if portion, ok := src.(FilePortion); ok {
303 firstLine, firstCol = portion.FirstLine, portion.FirstCol
304 }
305 sc := &scanner{
306 pos: MakePosition(&filename, firstLine, firstCol),
307 indentstk: make([]int, 1, 10), // []int{0} + spare capacity
308 lineStart: true,
309 keepComments: keepComments,
310 }
311 sc.readline, _ = src.(func() ([]byte, error)) // ParseCompoundStmt (REPL) only
312 if sc.readline == nil {
313 data, err := readSource(filename, src)
314 if err != nil {
315 return nil, err
316 }
317 sc.rest = data
318 }
319 return sc, nil
320 }
321
322 func readSource(filename string, src any) ([]byte, error) {
323 switch src := src.(type) {
324 case string:
325 return []byte(src), nil
326 case []byte:
327 return src, nil
328 case io.Reader:
329 data, err := io.ReadAll(src)
330 if err != nil {
331 err = &os.PathError{Op: "read", Path: filename, Err: err}
332 return nil, err
333 }
334 return data, nil
335 case FilePortion:
336 return src.Content, nil
337 case nil:
338 return os.ReadFile(filename)
339 default:
340 return nil, fmt.Errorf("invalid source: %T", src)
341 }
342 }
343
344 // An Error describes the nature and position of a scanner or parser error.
345 type Error struct {
346 Pos Position
347 Msg string
348 }
349
350 func (e Error) Error() string { return e.Pos.String() + ": " + e.Msg }
351
352 // errorf is called to report an error.
353 // errorf does not return: it panics.
354 func (sc *scanner) error(pos Position, s string) {
355 panic(Error{pos, s})
356 }
357
358 func (sc *scanner) errorf(pos Position, format string, args ...any) {
359 sc.error(pos, fmt.Sprintf(format, args...))
360 }
361
362 func (sc *scanner) recover(err *error) {
363 // The scanner and parser panic both for routine errors like
364 // syntax errors and for programmer bugs like array index
365 // errors. Turn both into error returns. Catching bug panics
366 // is especially important when processing many files.
367 switch e := recover().(type) {
368 case nil:
369 // no panic
370 case Error:
371 *err = e
372 default:
373 *err = Error{sc.pos, fmt.Sprintf("internal error: %v", e)}
374 if debug {
375 log.Fatal(*err)
376 }
377 }
378 }
379
380 // eof reports whether the input has reached end of file.
381 func (sc *scanner) eof() bool {
382 return len(sc.rest) == 0 && !sc.readLine()
383 }
384
385 // readLine attempts to read another line of input.
386 // Precondition: len(sc.rest)==0.
387 func (sc *scanner) readLine() bool {
388 if sc.readline != nil {
389 var err error
390 sc.rest, err = sc.readline()
391 if err != nil {
392 sc.errorf(sc.pos, "%v", err) // EOF or ErrInterrupt
393 }
394 return len(sc.rest) > 0
395 }
396 return false
397 }
398
399 // peekRune returns the next rune in the input without consuming it.
400 // Newlines in Unix, DOS, or Mac format are treated as one rune, '\n'.
401 func (sc *scanner) peekRune() rune {
402 // TODO(adonovan): opt: measure and perhaps inline eof.
403 if sc.eof() {
404 return 0
405 }
406
407 // fast path: ASCII
408 if b := sc.rest[0]; b < utf8.RuneSelf {
409 if b == '\r' {
410 return '\n'
411 }
412 return rune(b)
413 }
414
415 r, _ := utf8.DecodeRune(sc.rest)
416 return r
417 }
418
419 // readRune consumes and returns the next rune in the input.
420 // Newlines in Unix, DOS, or Mac format are treated as one rune, '\n'.
421 func (sc *scanner) readRune() rune {
422 // eof() has been inlined here, both to avoid a call
423 // and to establish len(rest)>0 to avoid a bounds check.
424 if len(sc.rest) == 0 {
425 if !sc.readLine() {
426 sc.error(sc.pos, "internal scanner error: readRune at EOF")
427 }
428 // Redundant, but eliminates the bounds-check below.
429 if len(sc.rest) == 0 {
430 return 0
431 }
432 }
433
434 // fast path: ASCII
435 if b := sc.rest[0]; b < utf8.RuneSelf {
436 r := rune(b)
437 sc.rest = sc.rest[1:]
438 if r == '\r' {
439 if len(sc.rest) > 0 && sc.rest[0] == '\n' {
440 sc.rest = sc.rest[1:]
441 }
442 r = '\n'
443 }
444 if r == '\n' {
445 sc.pos.Line++
446 sc.pos.Col = 1
447 } else {
448 sc.pos.Col++
449 }
450 return r
451 }
452
453 r, size := utf8.DecodeRune(sc.rest)
454 sc.rest = sc.rest[size:]
455 sc.pos.Col++
456 return r
457 }
458
459 // tokenValue records the position and value associated with each token.
460 type tokenValue struct {
461 raw string // raw text of token
462 int int64 // decoded int
463 bigInt *big.Int // decoded integers > int64
464 float float64 // decoded float
465 string string // decoded string or bytes
466 pos Position // start position of token
467 }
468
469 // startToken marks the beginning of the next input token.
470 // It must be followed by a call to endToken once the token has
471 // been consumed using readRune.
472 func (sc *scanner) startToken(val *tokenValue) {
473 sc.token = sc.rest
474 val.raw = ""
475 val.pos = sc.pos
476 }
477
478 // endToken marks the end of an input token.
479 // It records the actual token string in val.raw if the caller
480 // has not done that already.
481 func (sc *scanner) endToken(val *tokenValue) {
482 if val.raw == "" {
483 val.raw = string(sc.token[:len(sc.token)-len(sc.rest)])
484 }
485 }
486
487 // nextToken is called by the parser to obtain the next input token.
488 // It returns the token value and sets val to the data associated with
489 // the token.
490 //
491 // For all our input tokens, the associated data is val.pos (the
492 // position where the token begins), val.raw (the input string
493 // corresponding to the token). For string and int tokens, the string
494 // and int fields additionally contain the token's interpreted value.
495 func (sc *scanner) nextToken(val *tokenValue) Token {
496
497 // The following distribution of tokens guides case ordering:
498 //
499 // COMMA 27 %
500 // STRING 23 %
501 // IDENT 15 %
502 // EQL 11 %
503 // LBRACK 5.5 %
504 // RBRACK 5.5 %
505 // NEWLINE 3 %
506 // LPAREN 2.9 %
507 // RPAREN 2.9 %
508 // INT 2 %
509 // others < 1 %
510 //
511 // Although NEWLINE tokens are infrequent, and lineStart is
512 // usually (~97%) false on entry, skipped newlines account for
513 // about 50% of all iterations of the 'start' loop.
514
515 start:
516 var c rune
517
518 // Deal with leading spaces and indentation.
519 blank := false
520 savedLineStart := sc.lineStart
521 if sc.lineStart {
522 sc.lineStart = false
523 col := 0
524 for {
525 c = sc.peekRune()
526 if c == ' ' {
527 col++
528 sc.readRune()
529 } else if c == '\t' {
530 const tab = 8
531 col += int(tab - (sc.pos.Col-1)%tab)
532 sc.readRune()
533 } else {
534 break
535 }
536 }
537
538 // The third clause matches EOF.
539 if c == '#' || c == '\n' || c == 0 {
540 blank = true
541 }
542
543 // Compute indentation level for non-blank lines not
544 // inside an expression. This is not the common case.
545 if !blank && sc.depth == 0 {
546 cur := sc.indentstk[len(sc.indentstk)-1]
547 if col > cur {
548 // indent
549 sc.dents++
550 sc.indentstk = append(sc.indentstk, col)
551 } else if col < cur {
552 // outdent(s)
553 for len(sc.indentstk) > 0 && col < sc.indentstk[len(sc.indentstk)-1] {
554 sc.dents--
555 sc.indentstk = sc.indentstk[:len(sc.indentstk)-1] // pop
556 }
557 if col != sc.indentstk[len(sc.indentstk)-1] {
558 sc.error(sc.pos, "unindent does not match any outer indentation level")
559 }
560 }
561 }
562 }
563
564 // Return saved indentation tokens.
565 if sc.dents != 0 {
566 sc.startToken(val)
567 sc.endToken(val)
568 if sc.dents < 0 {
569 sc.dents++
570 return OUTDENT
571 } else {
572 sc.dents--
573 return INDENT
574 }
575 }
576
577 // start of line proper
578 c = sc.peekRune()
579
580 // Skip spaces.
581 for c == ' ' || c == '\t' {
582 sc.readRune()
583 c = sc.peekRune()
584 }
585
586 // comment
587 if c == '#' {
588 if sc.keepComments {
589 sc.startToken(val)
590 }
591 // Consume up to newline (included).
592 for c != 0 && c != '\n' {
593 sc.readRune()
594 c = sc.peekRune()
595 }
596 if sc.keepComments {
597 sc.endToken(val)
598 if blank {
599 sc.lineComments = append(sc.lineComments, Comment{val.pos, val.raw})
600 } else {
601 sc.suffixComments = append(sc.suffixComments, Comment{val.pos, val.raw})
602 }
603 }
604 }
605
606 // newline
607 if c == '\n' {
608 sc.lineStart = true
609
610 // Ignore newlines within expressions (common case).
611 if sc.depth > 0 {
612 sc.readRune()
613 goto start
614 }
615
616 // Ignore blank lines, except in the REPL,
617 // where they emit OUTDENTs and NEWLINE.
618 if blank {
619 if sc.readline == nil {
620 sc.readRune()
621 goto start
622 } else if len(sc.indentstk) > 1 {
623 sc.dents = 1 - len(sc.indentstk)
624 sc.indentstk = sc.indentstk[:1]
625 goto start
626 }
627 }
628
629 // At top-level (not in an expression).
630 sc.startToken(val)
631 sc.readRune()
632 val.raw = "\n"
633 return NEWLINE
634 }
635
636 // end of file
637 if c == 0 {
638 // Emit OUTDENTs for unfinished indentation,
639 // preceded by a NEWLINE if we haven't just emitted one.
640 if len(sc.indentstk) > 1 {
641 if savedLineStart {
642 sc.dents = 1 - len(sc.indentstk)
643 sc.indentstk = sc.indentstk[:1]
644 goto start
645 } else {
646 sc.lineStart = true
647 sc.startToken(val)
648 val.raw = "\n"
649 return NEWLINE
650 }
651 }
652
653 sc.startToken(val)
654 sc.endToken(val)
655 return EOF
656 }
657
658 // line continuation
659 if c == '\\' {
660 sc.readRune()
661 if sc.peekRune() != '\n' {
662 sc.errorf(sc.pos, "stray backslash in program")
663 }
664 sc.readRune()
665 goto start
666 }
667
668 // start of the next token
669 sc.startToken(val)
670
671 // comma (common case)
672 if c == ',' {
673 sc.readRune()
674 sc.endToken(val)
675 return COMMA
676 }
677
678 // string literal
679 if c == '"' || c == '\'' {
680 return sc.scanString(val, c)
681 }
682
683 // identifier or keyword
684 if isIdentStart(c) {
685 if (c == 'r' || c == 'b') && len(sc.rest) > 1 && (sc.rest[1] == '"' || sc.rest[1] == '\'') {
686 // r"..."
687 // b"..."
688 sc.readRune()
689 c = sc.peekRune()
690 return sc.scanString(val, c)
691 } else if c == 'r' && len(sc.rest) > 2 && sc.rest[1] == 'b' && (sc.rest[2] == '"' || sc.rest[2] == '\'') {
692 // rb"..."
693 sc.readRune()
694 sc.readRune()
695 c = sc.peekRune()
696 return sc.scanString(val, c)
697 }
698
699 for isIdent(c) {
700 sc.readRune()
701 c = sc.peekRune()
702 }
703 sc.endToken(val)
704 if k, ok := keywordToken[val.raw]; ok {
705 return k
706 }
707
708 return IDENT
709 }
710
711 // brackets
712 switch c {
713 case '[', '(', '{':
714 sc.depth++
715 if sc.depth > 1000 {
716 sc.errorf(sc.pos, "excessive nesting")
717 }
718 sc.readRune()
719 sc.endToken(val)
720 switch c {
721 case '[':
722 return LBRACK
723 case '(':
724 return LPAREN
725 case '{':
726 return LBRACE
727 }
728 panic("unreachable")
729
730 case ']', ')', '}':
731 if sc.depth == 0 {
732 sc.errorf(sc.pos, "unexpected %q", c)
733 } else {
734 sc.depth--
735 }
736 sc.readRune()
737 sc.endToken(val)
738 switch c {
739 case ']':
740 return RBRACK
741 case ')':
742 return RPAREN
743 case '}':
744 return RBRACE
745 }
746 panic("unreachable")
747 }
748
749 // int or float literal, or period
750 if isdigit(c) || c == '.' {
751 return sc.scanNumber(val, c)
752 }
753
754 // other punctuation
755 defer sc.endToken(val)
756 switch c {
757 case '=', '<', '>', '!', '+', '-', '%', '/', '&', '|', '^': // possibly followed by '='
758 start := sc.pos
759 sc.readRune()
760 if sc.peekRune() == '=' {
761 sc.readRune()
762 switch c {
763 case '<':
764 return LE
765 case '>':
766 return GE
767 case '=':
768 return EQL
769 case '!':
770 return NEQ
771 case '+':
772 return PLUS_EQ
773 case '-':
774 return MINUS_EQ
775 case '/':
776 return SLASH_EQ
777 case '%':
778 return PERCENT_EQ
779 case '&':
780 return AMP_EQ
781 case '|':
782 return PIPE_EQ
783 case '^':
784 return CIRCUMFLEX_EQ
785 }
786 }
787 switch c {
788 case '=':
789 return EQ
790 case '<':
791 if sc.peekRune() == '<' {
792 sc.readRune()
793 if sc.peekRune() == '=' {
794 sc.readRune()
795 return LTLT_EQ
796 } else {
797 return LTLT
798 }
799 }
800 return LT
801 case '>':
802 if sc.peekRune() == '>' {
803 sc.readRune()
804 if sc.peekRune() == '=' {
805 sc.readRune()
806 return GTGT_EQ
807 } else {
808 return GTGT
809 }
810 }
811 return GT
812 case '!':
813 sc.error(start, "unexpected input character '!'")
814 case '+':
815 return PLUS
816 case '-':
817 return MINUS
818 case '/':
819 if sc.peekRune() == '/' {
820 sc.readRune()
821 if sc.peekRune() == '=' {
822 sc.readRune()
823 return SLASHSLASH_EQ
824 } else {
825 return SLASHSLASH
826 }
827 }
828 return SLASH
829 case '%':
830 return PERCENT
831 case '&':
832 return AMP
833 case '|':
834 return PIPE
835 case '^':
836 return CIRCUMFLEX
837 }
838 panic("unreachable")
839
840 case ':', ';', '~': // single-char tokens (except comma)
841 sc.readRune()
842 switch c {
843 case ':':
844 return COLON
845 case ';':
846 return SEMI
847 case '~':
848 return TILDE
849 }
850 panic("unreachable")
851
852 case '*': // possibly followed by '*' or '='
853 sc.readRune()
854 switch sc.peekRune() {
855 case '*':
856 sc.readRune()
857 return STARSTAR
858 case '=':
859 sc.readRune()
860 return STAR_EQ
861 }
862 return STAR
863 }
864
865 sc.errorf(sc.pos, "unexpected input character %#q", c)
866 panic("unreachable")
867 }
868
869 func (sc *scanner) scanString(val *tokenValue, quote rune) Token {
870 start := sc.pos
871 triple := len(sc.rest) >= 3 && sc.rest[0] == byte(quote) && sc.rest[1] == byte(quote) && sc.rest[2] == byte(quote)
872 sc.readRune()
873
874 // String literals may contain escaped or unescaped newlines,
875 // causing them to span multiple lines (gulps) of REPL input;
876 // they are the only such token. Thus we cannot call endToken,
877 // as it assumes sc.rest is unchanged since startToken.
878 // Instead, buffer the token here.
879 // TODO(adonovan): opt: buffer only if we encounter a newline.
880 raw := new(strings.Builder)
881
882 // Copy the prefix, e.g. r' or " (see startToken).
883 raw.Write(sc.token[:len(sc.token)-len(sc.rest)])
884
885 if !triple {
886 // single-quoted string literal
887 for {
888 if sc.eof() {
889 sc.error(val.pos, "unexpected EOF in string")
890 }
891 c := sc.readRune()
892 raw.WriteRune(c)
893 if c == quote {
894 break
895 }
896 if c == '\n' {
897 sc.error(val.pos, "unexpected newline in string")
898 }
899 if c == '\\' {
900 if sc.eof() {
901 sc.error(val.pos, "unexpected EOF in string")
902 }
903 c = sc.readRune()
904 raw.WriteRune(c)
905 }
906 }
907 } else {
908 // triple-quoted string literal
909 sc.readRune()
910 raw.WriteRune(quote)
911 sc.readRune()
912 raw.WriteRune(quote)
913
914 quoteCount := 0
915 for {
916 if sc.eof() {
917 sc.error(val.pos, "unexpected EOF in string")
918 }
919 c := sc.readRune()
920 raw.WriteRune(c)
921 if c == quote {
922 quoteCount++
923 if quoteCount == 3 {
924 break
925 }
926 } else {
927 quoteCount = 0
928 }
929 if c == '\\' {
930 if sc.eof() {
931 sc.error(val.pos, "unexpected EOF in string")
932 }
933 c = sc.readRune()
934 raw.WriteRune(c)
935 }
936 }
937 }
938 val.raw = raw.String()
939
940 s, _, isByte, err := unquote(val.raw)
941 if err != nil {
942 sc.error(start, err.Error())
943 }
944 val.string = s
945 if isByte {
946 return BYTES
947 } else {
948 return STRING
949 }
950 }
951
952 func (sc *scanner) scanNumber(val *tokenValue, c rune) Token {
953 // https://github.com/google/starlark-go/blob/master/doc/spec.md#lexical-elements
954 //
955 // Python features not supported:
956 // - integer literals of >64 bits of precision
957 // - 123L or 123l long suffix
958 // - traditional octal: 0755
959 // https://docs.python.org/2/reference/lexical_analysis.html#integer-and-long-integer-literals
960
961 start := sc.pos
962 fraction, exponent := false, false
963
964 if c == '.' {
965 // dot or start of fraction
966 sc.readRune()
967 c = sc.peekRune()
968 if !isdigit(c) {
969 sc.endToken(val)
970 return DOT
971 }
972 fraction = true
973 } else if c == '0' {
974 // hex, octal, binary or float
975 sc.readRune()
976 c = sc.peekRune()
977
978 if c == '.' {
979 fraction = true
980 } else if c == 'x' || c == 'X' {
981 // hex
982 sc.readRune()
983 c = sc.peekRune()
984 if !isxdigit(c) {
985 sc.error(start, "invalid hex literal")
986 }
987 for isxdigit(c) {
988 sc.readRune()
989 c = sc.peekRune()
990 }
991 } else if c == 'o' || c == 'O' {
992 // octal
993 sc.readRune()
994 c = sc.peekRune()
995 if !isodigit(c) {
996 sc.error(sc.pos, "invalid octal literal")
997 }
998 for isodigit(c) {
999 sc.readRune()
1000 c = sc.peekRune()
1001 }
1002 } else if c == 'b' || c == 'B' {
1003 // binary
1004 sc.readRune()
1005 c = sc.peekRune()
1006 if !isbdigit(c) {
1007 sc.error(sc.pos, "invalid binary literal")
1008 }
1009 for isbdigit(c) {
1010 sc.readRune()
1011 c = sc.peekRune()
1012 }
1013 } else {
1014 // float (or obsolete octal "0755")
1015 allzeros, octal := true, true
1016 for isdigit(c) {
1017 if c != '0' {
1018 allzeros = false
1019 }
1020 if c > '7' {
1021 octal = false
1022 }
1023 sc.readRune()
1024 c = sc.peekRune()
1025 }
1026 if c == '.' {
1027 fraction = true
1028 } else if c == 'e' || c == 'E' {
1029 exponent = true
1030 } else if octal && !allzeros {
1031 sc.endToken(val)
1032 sc.errorf(sc.pos, "obsolete form of octal literal; use 0o%s", val.raw[1:])
1033 }
1034 }
1035 } else {
1036 // decimal
1037 for isdigit(c) {
1038 sc.readRune()
1039 c = sc.peekRune()
1040 }
1041
1042 if c == '.' {
1043 fraction = true
1044 } else if c == 'e' || c == 'E' {
1045 exponent = true
1046 }
1047 }
1048
1049 if fraction {
1050 sc.readRune() // consume '.'
1051 c = sc.peekRune()
1052 for isdigit(c) {
1053 sc.readRune()
1054 c = sc.peekRune()
1055 }
1056
1057 if c == 'e' || c == 'E' {
1058 exponent = true
1059 }
1060 }
1061
1062 if exponent {
1063 sc.readRune() // consume [eE]
1064 c = sc.peekRune()
1065 if c == '+' || c == '-' {
1066 sc.readRune()
1067 c = sc.peekRune()
1068 if !isdigit(c) {
1069 sc.error(sc.pos, "invalid float literal")
1070 }
1071 }
1072 for isdigit(c) {
1073 sc.readRune()
1074 c = sc.peekRune()
1075 }
1076 }
1077
1078 sc.endToken(val)
1079 if fraction || exponent {
1080 var err error
1081 val.float, err = strconv.ParseFloat(val.raw, 64)
1082 if err != nil {
1083 sc.error(sc.pos, "invalid float literal")
1084 }
1085 return FLOAT
1086 } else {
1087 var err error
1088 s := val.raw
1089 val.bigInt = nil
1090 if len(s) > 2 && s[0] == '0' && (s[1] == 'o' || s[1] == 'O') {
1091 val.int, err = strconv.ParseInt(s[2:], 8, 64)
1092 } else if len(s) > 2 && s[0] == '0' && (s[1] == 'b' || s[1] == 'B') {
1093 val.int, err = strconv.ParseInt(s[2:], 2, 64)
1094 } else {
1095 val.int, err = strconv.ParseInt(s, 0, 64)
1096 if err != nil {
1097 num := new(big.Int)
1098 var ok bool
1099 val.bigInt, ok = num.SetString(s, 0)
1100 if ok {
1101 err = nil
1102 }
1103 }
1104 }
1105 if err != nil {
1106 sc.error(start, "invalid int literal")
1107 }
1108 return INT
1109 }
1110 }
1111
1112 // isIdent reports whether c is an identifier rune.
1113 func isIdent(c rune) bool {
1114 return isdigit(c) || isIdentStart(c)
1115 }
1116
1117 func isIdentStart(c rune) bool {
1118 return 'a' <= c && c <= 'z' ||
1119 'A' <= c && c <= 'Z' ||
1120 c == '_' ||
1121 unicode.IsLetter(c)
1122 }
1123
1124 func isdigit(c rune) bool { return '0' <= c && c <= '9' }
1125 func isodigit(c rune) bool { return '0' <= c && c <= '7' }
1126 func isxdigit(c rune) bool { return isdigit(c) || 'A' <= c && c <= 'F' || 'a' <= c && c <= 'f' }
1127 func isbdigit(c rune) bool { return '0' == c || c == '1' }
1128
1129 // keywordToken records the special tokens for
1130 // strings that should not be treated as ordinary identifiers.
1131 var keywordToken = map[string]Token{
1132 "and": AND,
1133 "break": BREAK,
1134 "continue": CONTINUE,
1135 "def": DEF,
1136 "elif": ELIF,
1137 "else": ELSE,
1138 "for": FOR,
1139 "if": IF,
1140 "in": IN,
1141 "lambda": LAMBDA,
1142 "load": LOAD,
1143 "not": NOT,
1144 "or": OR,
1145 "pass": PASS,
1146 "return": RETURN,
1147 "while": WHILE,
1148
1149 // reserved words:
1150 "as": AS,
1151 // "assert": ASSERT, // heavily used by our tests
1152 "async": ASYNC,
1153 "await": AWAIT,
1154 "class": CLASS,
1155 "del": DEL,
1156 "except": EXCEPT,
1157 "finally": FINALLY,
1158 "from": FROM,
1159 "global": GLOBAL,
1160 "import": IMPORT,
1161 "is": IS,
1162 "nonlocal": NONLOCAL,
1163 "raise": RAISE,
1164 "try": TRY,
1165 "with": WITH,
1166 "yield": YIELD,
1167 }