Debian Codegraph @

syntax/lexer.go

raw
1 // Copyright (c) 2016, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package syntax
5
6 import (
7 "bytes"
8 "io"
9 "unicode/utf8"
10 )
11
12 func asciiLetter[T rune | byte](r T) bool {
13 return ('a' <= r && r <= 'z') || ('A' <= r && r <= 'Z')
14 }
15
16 func asciiDigit[T rune | byte](r T) bool {
17 return r >= '0' && r <= '9'
18 }
19
20 // bytes that form or start a token
21 func regOps(r rune) bool {
22 switch r {
23 case ';', '"', '\'', '(', ')', '$', '|', '&', '>', '<', '`':
24 return true
25 }
26 return false
27 }
28
29 // tokenize these inside parameter expansions
30 func paramOps(r rune) bool {
31 switch r {
32 case '}', '#', '!', ':', '-', '+', '=', '?', '%', '[', ']', '/', '^',
33 ',', '@', '*':
34 return true
35 }
36 return false
37 }
38
39 // tokenize these inside arithmetic expansions
40 func arithmOps(r rune) bool {
41 switch r {
42 case '+', '-', '!', '~', '*', '/', '%', '(', ')', '^', '<', '>', ':', '=',
43 ',', '?', '|', '&', '[', ']', '#', '.':
44 return true
45 }
46 return false
47 }
48
49 func bquoteEscaped(b byte) bool {
50 switch b {
51 case '$', '`', '\\':
52 return true
53 }
54 return false
55 }
56
57 // Sentinel rune values used by [Parser.rune]. They are above [utf8.MaxRune]
58 // so that they can never collide with runes decoded from the input.
59 const (
60 runeEOF rune = utf8.MaxRune + 1 // the input ran out, or we stopped early
61 escNewl rune = utf8.MaxRune + 2 // an escaped newline, "\\\n"
62 )
63
64 func (p *Parser) rune() rune {
65 if p.r == '\n' || p.r == escNewl {
66 // p.r instead of b so that newline
67 // character positions don't have col 0.
68 p.line++
69 p.col = 0
70 }
71 p.col += int64(p.w)
72 bquotes := 0
73 retry:
74 if p.bsp >= uint(len(p.bs)) && p.fill() == 0 {
75 if len(p.bs) == 0 {
76 // Necessary for the last position to be correct.
77 // TODO: this is not exactly intuitive; figure out a better way.
78 p.bsp = 1
79 }
80 p.r = runeEOF
81 p.w = 1
82 return p.r
83 }
84 if b := p.bs[p.bsp]; b < utf8.RuneSelf {
85 p.bsp++
86 switch b {
87 case '\x00':
88 // Ignore null bytes while parsing, like bash.
89 p.col++
90 goto retry
91 case '\r':
92 if p.peek() == '\n' { // \r\n turns into \n
93 p.col++
94 goto retry
95 }
96 case '\\':
97 if p.r == '\\' {
98 } else if p.peek() == '\n' {
99 p.bsp++
100 p.w, p.r = 1, escNewl
101 return escNewl
102 } else if p1, p2 := p.peekTwo(); p1 == '\r' && p2 == '\n' { // \\\r\n turns into \\\n
103 p.col++
104 p.bsp += 2
105 p.w, p.r = 2, escNewl
106 return escNewl
107 }
108 // TODO: why is this necessary to ensure correct position info?
109 p.readEOF = false
110 if p.openBquotes > 0 && p.bsp < uint(len(p.bs)) &&
111 ((bquotes < p.openBquotes && bquoteEscaped(p.bs[p.bsp])) ||
112 // Backquotes within double quotes also escape double quotes.
113 (bquotes < p.openBquoteDbls && p.bs[p.bsp] == '"')) {
114 // We turn backquote command substitutions into $(),
115 // so we remove the extra backslashes needed by the backquotes.
116 bquotes++
117 p.col++
118 goto retry
119 }
120 }
121 if b == '`' {
122 p.lastBquoteEsc = bquotes
123 }
124 if p.litBs != nil {
125 p.litBs = append(p.litBs, b)
126 }
127 p.w, p.r = 1, rune(b)
128 return p.r
129 }
130 decodeRune:
131 var w int
132 p.r, w = utf8.DecodeRune(p.bs[p.bsp:])
133 if p.r == utf8.RuneError && !utf8.FullRune(p.bs[p.bsp:]) {
134 // we need more bytes to read a full non-ascii rune
135 if p.fill() > 0 {
136 goto decodeRune
137 }
138 }
139 if p.litBs != nil {
140 p.litBs = append(p.litBs, p.bs[p.bsp:p.bsp+uint(w)]...)
141 }
142 p.bsp += uint(w)
143 if p.r == utf8.RuneError && w == 1 {
144 p.posErr(p.nextPos(), "invalid UTF-8 encoding")
145 }
146 p.w = w
147 return p.r
148 }
149
150 // fill reads more bytes from the input src into readBuf.
151 // Any bytes that had not yet been used at the end of the buffer
152 // are slid into the beginning of the buffer.
153 // The number of read bytes is returned, which is at least one
154 // unless a read error occurred, such as [io.EOF].
155 func (p *Parser) fill() (n int) {
156 if p.readEOF || p.r == runeEOF {
157 // If the reader already gave us [io.EOF], do not try again.
158 // If we decided to stop for any reason, do not bother reading either.
159 return 0
160 }
161 p.offs += int64(p.bsp)
162 left := len(p.bs) - int(p.bsp)
163 copy(p.readBuf[:left], p.readBuf[p.bsp:])
164 readAgain:
165 n, err := 0, p.readErr
166 if err == nil {
167 n, err = p.src.Read(p.readBuf[left:])
168 p.readErr = err
169 if err == io.EOF {
170 p.readEOF = true
171 }
172 }
173 if n == 0 {
174 if err == nil {
175 goto readAgain
176 }
177 // don't use p.errPass as we don't want to overwrite p.tok
178 if err != io.EOF {
179 p.err = err
180 }
181 if left > 0 {
182 p.bs = p.readBuf[:left]
183 } else {
184 p.bs = nil
185 }
186 } else {
187 p.bs = p.readBuf[:left+n]
188 }
189 p.bsp = 0
190 return n
191 }
192
193 func (p *Parser) nextKeepSpaces() {
194 r := p.r
195 if p.quote != hdocBody && p.quote != hdocBodyTabs {
196 // Heredocs handle escaped newlines in a special way, but others do not.
197 for r == escNewl {
198 r = p.rune()
199 }
200 }
201 p.pos = p.nextPos()
202 switch p.quote {
203 case runeByRune:
204 p.tok = illegalTok
205 case dblQuotes:
206 switch r {
207 case '`', '"', '$':
208 p.tok = p.dqToken(r)
209 default:
210 p.advanceLitDquote(r)
211 }
212 case hdocBody, hdocBodyTabs:
213 switch r {
214 case '`', '$':
215 p.tok = p.dqToken(r)
216 default:
217 p.advanceLitHdoc(r)
218 }
219 case paramExpRepl:
220 if r == '/' {
221 p.rune()
222 p.tok = slash
223 break
224 }
225 fallthrough
226 case paramExpExp:
227 switch r {
228 case '}':
229 p.tok = p.paramToken(r)
230 case '`', '"', '$', '\'':
231 p.tok = p.regToken(r)
232 default:
233 p.advanceLitOther(r)
234 }
235 }
236 if p.err != nil {
237 p.tok = _EOF
238 }
239 }
240
241 func (p *Parser) next() {
242 if p.r == runeEOF {
243 p.tok = _EOF
244 return
245 }
246 p.spaced = false
247 if p.quote&allKeepSpaces != 0 {
248 p.nextKeepSpaces()
249 return
250 }
251 r := p.r
252 for r == escNewl {
253 r = p.rune()
254 }
255 skipSpace:
256 for {
257 switch r {
258 case runeEOF:
259 p.tok = _EOF
260 return
261 case escNewl:
262 r = p.rune()
263 case ' ', '\t', '\r':
264 p.spaced = true
265 r = p.rune()
266 case '\n':
267 if p.tok == _Newl {
268 // merge consecutive newline tokens
269 r = p.rune()
270 continue
271 }
272 p.spaced = true
273 p.tok = _Newl
274 if p.quote != hdocWord && len(p.heredocs) > p.buriedHdocs {
275 p.doHeredocs()
276 }
277 return
278 default:
279 break skipSpace
280 }
281 }
282 if p.stopAt != nil && (p.spaced || p.tok == illegalTok || p.stopToken()) {
283 // Note that the buffer may have been refilled since we read r,
284 // such as when peeking at the byte which follows a backslash,
285 // in which case r's bytes are gone and we cannot match on them.
286 w := uint(utf8.RuneLen(r))
287 if p.bsp >= w && bytes.HasPrefix(p.bs[p.bsp-w:], p.stopAt) {
288 p.r = runeEOF
289 p.w = 1
290 p.tok = _EOF
291 return
292 }
293 }
294 p.pos = p.nextPos()
295 switch {
296 case p.quote&allRegTokens != 0:
297 switch r {
298 case ';', '"', '\'', '(', ')', '$', '|', '&', '>', '<', '`':
299 if r == '<' && p.lang.in(LangZsh) && p.zshNumRange() {
300 p.advanceLitNone(r)
301 return
302 }
303 p.tok = p.regToken(r)
304 case '#':
305 // If we're parsing $foo#bar, ${foo}#bar, 'foo'#bar, or "foo"#bar,
306 // #bar is a continuation of the same word, not a comment.
307 // The same applies inside [[ ]] tests, where '#' has no comment meaning.
308 if !p.spaced && (p.quote == unquotedWordCont || p.quote == testExpr) {
309 p.advanceLitNone(r)
310 return
311 }
312 r = p.rune()
313 p.newLit(r)
314 runeLoop:
315 for {
316 switch r {
317 case '\n', runeEOF:
318 break runeLoop
319 case escNewl:
320 p.litBs = append(p.litBs, '\\', '\n')
321 break runeLoop
322 case '`':
323 if p.backquoteEnd() {
324 break runeLoop
325 }
326 }
327 r = p.rune()
328 }
329 if p.keepComments {
330 *p.curComs = append(*p.curComs, Comment{
331 Hash: p.pos,
332 Text: p.endLit(),
333 })
334 } else {
335 p.litBs = nil
336 }
337 p.next()
338 case '[':
339 // `[` only starts an `[idx]=val` element when it begins a new word;
340 // otherwise it continues a glob like `foo[0-9]`.
341 if p.quote == arrayElems && (p.spaced || p.tok == leftParen || p.tok == _Newl) {
342 p.rune()
343 p.tok = leftBrack
344 } else {
345 p.advanceLitNone(r)
346 }
347 case '=':
348 if p.peek() == '(' {
349 p.rune()
350 p.rune()
351 p.tok = assgnParen
352 } else if p.quote == arrayElems {
353 p.rune()
354 p.tok = assgn
355 } else {
356 p.advanceLitNone(r)
357 }
358 case '?', '*', '+', '@', '!':
359 if p.extendedGlob() {
360 switch r {
361 case '?':
362 p.tok = globQuest
363 case '*':
364 p.tok = globStar
365 case '+':
366 p.tok = globPlus
367 case '@':
368 p.tok = globAt
369 case '!':
370 p.tok = globExcl
371 }
372 p.rune()
373 p.rune()
374 } else {
375 p.advanceLitNone(r)
376 }
377 default:
378 p.advanceLitNone(r)
379 }
380 case p.quote == paramExpArithm && r == '#':
381 // '#' is mksh's unsigned prefix, which only [ArithmExp] and [ArithmCmd]
382 // can represent, so in a subscript it starts a literal instead;
383 // it can be part of an associative array key, like in ${args[cmd,#]}.
384 p.advanceLitOther(r)
385 case p.quote&allArithmExpr != 0 && arithmOps(r):
386 p.tok = p.arithmToken(r)
387 case p.quote&allParamExp != 0 && paramOps(r):
388 p.tok = p.paramToken(r)
389 case p.quote == testExprRegexp:
390 if !p.rxFirstPart && p.spaced {
391 p.quote = testExpr
392 goto skipSpace
393 }
394 p.rxFirstPart = false
395 switch r {
396 case ';', '"', '\'', '$', '&', '>', '<', '`':
397 p.tok = p.regToken(r)
398 case ')':
399 if p.rxOpenParens > 0 {
400 // continuation of open paren
401 p.advanceLitRe(r)
402 } else {
403 p.tok = rightParen
404 p.quote = testExpr
405 p.rune() // we are tokenizing manually
406 }
407 default: // including '(', '|'
408 p.advanceLitRe(r)
409 }
410 case regOps(r):
411 p.tok = p.regToken(r)
412 default:
413 p.advanceLitOther(r)
414 }
415 if p.err != nil {
416 p.tok = _EOF
417 }
418 }
419
420 // extendedGlob determines whether we're parsing a Bash extended globbing expression.
421 // For example, whether `*` or `@` are followed by `(` to form `@(foo)`.
422 func (p *Parser) extendedGlob() bool {
423 if p.lang.in(LangZsh) {
424 // Zsh supports Bash extended globs via the KSH_GLOB option.
425 // In Bash we would parse extended globs as [ExtGlob] nodes,
426 // but trying to do that in Zsh would cause ambiguity with glob qualifiers.
427 // Just like glob qualifiers, parse extended globs as literals in Zsh.
428 return false
429 }
430 if p.val == "function" {
431 // We don't support e.g. `function @() { ... }` at the moment, but we could.
432 return false
433 }
434 if p.peek() == '(' {
435 // NOTE: empty pattern list is a valid globbing syntax like `@()`,
436 // but we'll operate on the "likelihood" that it is a function;
437 // only tokenize if its a non-empty pattern list.
438 // We do this after peeking for just one byte, so that the input `echo *`
439 // followed by a newline does not hang an interactive shell parser until
440 // another byte is input.
441 _, p2 := p.peekTwo()
442 return p2 != ')'
443 }
444 return false
445 }
446
447 func (p *Parser) peek() byte {
448 if int(p.bsp) >= len(p.bs) {
449 p.fill()
450 }
451 if int(p.bsp) >= len(p.bs) {
452 return utf8.RuneSelf
453 }
454 return p.bs[p.bsp]
455 }
456
457 func (p *Parser) peekTwo() (byte, byte) {
458 // TODO: This should loop for slow readers, e.g. those providing one byte at
459 // a time. Use a loop and test it with [testing/iotest.OneByteReader].
460 if int(p.bsp+1) >= len(p.bs) {
461 p.fill()
462 }
463 if int(p.bsp) >= len(p.bs) {
464 return utf8.RuneSelf, utf8.RuneSelf
465 }
466 if int(p.bsp+1) >= len(p.bs) {
467 return p.bs[p.bsp], utf8.RuneSelf
468 }
469 return p.bs[p.bsp], p.bs[p.bsp+1]
470 }
471
472 func (p *Parser) regToken(r rune) token {
473 switch r {
474 case '\'':
475 p.rune()
476 return sglQuote
477 case '"':
478 p.rune()
479 return dblQuote
480 case '`':
481 // Don't call p.rune, as we need to work out p.openBquotes to
482 // properly handle backslashes in the lexer.
483 return bckQuote
484 case '&':
485 switch p.rune() {
486 case '&':
487 p.rune()
488 return andAnd
489 case '>':
490 switch p.rune() {
491 case '|':
492 p.rune()
493 return rdrAllClob
494 case '!':
495 if p.lang.in(LangZsh) {
496 p.rune()
497 return rdrAllClob
498 }
499 case '>':
500 switch p.rune() {
501 case '|':
502 p.rune()
503 return appAllClob
504 case '!':
505 if p.lang.in(LangZsh) {
506 p.rune()
507 return appAllClob
508 }
509 }
510 return appAll
511 }
512 return rdrAll
513 case '|':
514 if p.lang.in(LangZsh) {
515 p.rune()
516 return andPipe
517 }
518 case '!':
519 if p.lang.in(LangZsh) {
520 p.rune()
521 return andBang
522 }
523 }
524 return and
525 case '|':
526 switch p.rune() {
527 case '|':
528 p.rune()
529 return orOr
530 case '&':
531 if !p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
532 break
533 }
534 p.rune()
535 return orAnd
536 }
537 return or
538 case '$':
539 switch p.rune() {
540 case '\'':
541 if !p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
542 break
543 }
544 p.rune()
545 return dollSglQuote
546 case '"':
547 if !p.lang.in(langBashLike | LangMirBSDKorn) {
548 break
549 }
550 p.rune()
551 return dollDblQuote
552 case '{':
553 p.rune()
554 return dollBrace
555 case '[':
556 if !p.lang.in(langBashLike) {
557 // latter to not tokenise ${$[@]} as $[
558 break
559 }
560 p.rune()
561 return dollBrack
562 case '(':
563 if p.rune() == '(' {
564 p.rune()
565 return dollDblParen
566 }
567 return dollParen
568 }
569 return dollar
570 case '(':
571 if p.rune() == '(' && p.lang.in(langBashLike|LangMirBSDKorn|LangZsh) && p.quote != testExpr {
572 p.rune()
573 return dblLeftParen
574 }
575 return leftParen
576 case ')':
577 p.rune()
578 return rightParen
579 case ';':
580 switch p.rune() {
581 case ';':
582 if p.rune() == '&' && p.lang.in(langBashLike) {
583 p.rune()
584 return dblSemiAnd
585 }
586 return dblSemicolon
587 case '&':
588 if !p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
589 break
590 }
591 p.rune()
592 return semiAnd
593 case '|':
594 if !p.lang.in(LangMirBSDKorn | LangZsh) {
595 break
596 }
597 p.rune()
598 return semiOr
599 }
600 return semicolon
601 case '<':
602 switch p.rune() {
603 case '<':
604 switch p.rune() {
605 case '-':
606 p.rune()
607 return dashHdoc
608 case '<':
609 p.rune()
610 return wordHdoc
611 }
612 return hdoc
613 case '>':
614 p.rune()
615 return rdrInOut
616 case '&':
617 p.rune()
618 return dplIn
619 case '(':
620 if !p.lang.in(langBashLike | LangZsh) {
621 break
622 }
623 p.rune()
624 return cmdIn
625 }
626 return rdrIn
627 case '>':
628 switch p.rune() {
629 case '>':
630 switch p.rune() {
631 case '|':
632 p.rune()
633 return appClob
634 case '!':
635 if p.lang.in(LangZsh) {
636 p.rune()
637 return appClob
638 }
639 case '&':
640 if !p.lang.in(LangZsh) {
641 break
642 }
643 switch p.rune() {
644 case '|':
645 p.rune()
646 return appAllClob // >>&| is an alias for &>>|
647 case '!':
648 p.rune()
649 return appAllClob // >>&! is an alias for &>>|
650 }
651 return appAll // >>& is an alias for &>>
652 }
653 return appOut
654 case '&':
655 r = p.rune()
656 if p.lang.in(LangZsh) {
657 switch r {
658 case '|':
659 p.rune()
660 return rdrAllClob // >&| is an alias for &>|
661 case '!':
662 p.rune()
663 return rdrAllClob // >&! is an alias for &>|
664 }
665 }
666 return dplOut
667 case '|':
668 p.rune()
669 return rdrClob
670 case '!':
671 if p.lang.in(LangZsh) {
672 p.rune()
673 return rdrClob
674 }
675 case '(':
676 if !p.lang.in(langBashLike | LangZsh) {
677 break
678 }
679 p.rune()
680 return cmdOut
681 }
682 return rdrOut
683 }
684 panic("unreachable")
685 }
686
687 func (p *Parser) dqToken(r rune) token {
688 switch r {
689 case '"':
690 p.rune()
691 return dblQuote
692 case '`':
693 // Don't call p.rune, as we need to work out p.openBquotes to
694 // properly handle backslashes in the lexer.
695 return bckQuote
696 case '$':
697 switch p.rune() {
698 case '{':
699 p.rune()
700 return dollBrace
701 case '[':
702 if !p.lang.in(langBashLike) {
703 break
704 }
705 p.rune()
706 return dollBrack
707 case '(':
708 if p.rune() == '(' {
709 p.rune()
710 return dollDblParen
711 }
712 return dollParen
713 }
714 return dollar
715 }
716 panic("unreachable")
717 }
718
719 func (p *Parser) paramToken(r rune) token {
720 switch r {
721 case '}':
722 p.rune()
723 return rightBrace
724 case ':':
725 switch p.rune() {
726 case '+':
727 p.rune()
728 return colPlus
729 case '-':
730 p.rune()
731 return colMinus
732 case '?':
733 p.rune()
734 return colQuest
735 case '=':
736 p.rune()
737 return colAssgn
738 case '#':
739 p.rune()
740 return colHash
741 case '|':
742 p.rune()
743 return colPipe
744 case '*':
745 p.rune()
746 return colStar
747 }
748 return colon
749 case '+':
750 p.rune()
751 return plus
752 case '-':
753 p.rune()
754 return minus
755 case '?':
756 p.rune()
757 return quest
758 case '=':
759 p.rune()
760 return assgn
761 case '%':
762 if p.rune() == '%' {
763 p.rune()
764 return dblPerc
765 }
766 return perc
767 case '#':
768 if p.rune() == '#' {
769 p.rune()
770 return dblHash
771 }
772 return hash
773 case '!':
774 p.rune()
775 return exclMark
776 case ']':
777 p.rune()
778 return rightBrack
779 case '/':
780 if p.rune() == '/' {
781 p.rune()
782 return dblSlash
783 }
784 return slash
785 case '^':
786 if p.rune() == '^' {
787 p.rune()
788 return dblCaret
789 }
790 return caret
791 case ',':
792 if p.rune() == ',' {
793 p.rune()
794 return dblComma
795 }
796 return comma
797 case '@':
798 p.rune()
799 return at
800 case '*':
801 p.rune()
802 return star
803
804 // This func gets called by the parser in [runeByRune] mode;
805 // we need to handle EOF and unexpected runes.
806 case runeEOF:
807 return _EOF
808 default:
809 return illegalTok
810 }
811 }
812
813 func (p *Parser) arithmToken(r rune) token {
814 switch r {
815 case '!':
816 if p.rune() == '=' {
817 p.rune()
818 return nequal
819 }
820 return exclMark
821 case '=':
822 if p.rune() == '=' {
823 p.rune()
824 return equal
825 }
826 return assgn
827 case '~':
828 p.rune()
829 return tilde
830 case '(':
831 p.rune()
832 return leftParen
833 case ')':
834 p.rune()
835 return rightParen
836 case '&':
837 switch p.rune() {
838 case '&':
839 if p.rune() == '=' && p.lang.in(LangZsh) {
840 p.rune()
841 return andBoolAssgn
842 }
843 return andAnd
844 case '=':
845 p.rune()
846 return andAssgn
847 }
848 return and
849 case '|':
850 switch p.rune() {
851 case '|':
852 if p.rune() == '=' && p.lang.in(LangZsh) {
853 p.rune()
854 return orBoolAssgn
855 }
856 return orOr
857 case '=':
858 p.rune()
859 return orAssgn
860 }
861 return or
862 case '<':
863 switch p.rune() {
864 case '<':
865 if p.rune() == '=' {
866 p.rune()
867 return shlAssgn
868 }
869 return hdoc
870 case '=':
871 p.rune()
872 return lequal
873 }
874 return rdrIn
875 case '>':
876 switch p.rune() {
877 case '>':
878 if p.rune() == '=' {
879 p.rune()
880 return shrAssgn
881 }
882 return appOut
883 case '=':
884 p.rune()
885 return gequal
886 }
887 return rdrOut
888 case '+':
889 switch p.rune() {
890 case '+':
891 p.rune()
892 return addAdd
893 case '=':
894 p.rune()
895 return addAssgn
896 }
897 return plus
898 case '-':
899 switch p.rune() {
900 case '-':
901 p.rune()
902 return subSub
903 case '=':
904 p.rune()
905 return subAssgn
906 }
907 return minus
908 case '%':
909 if p.rune() == '=' {
910 p.rune()
911 return remAssgn
912 }
913 return perc
914 case '*':
915 switch p.rune() {
916 case '*':
917 if p.rune() == '=' && p.lang.in(LangZsh) {
918 p.rune()
919 return powAssgn
920 }
921 return power
922 case '=':
923 p.rune()
924 return mulAssgn
925 }
926 return star
927 case '/':
928 if p.rune() == '=' {
929 p.rune()
930 return quoAssgn
931 }
932 return slash
933 case '^':
934 switch p.rune() {
935 case '^':
936 if p.rune() == '=' && p.lang.in(LangZsh) {
937 p.rune()
938 return xorBoolAssgn
939 }
940 return dblCaret
941 case '=':
942 p.rune()
943 return xorAssgn
944 }
945 return caret
946 case '[':
947 p.rune()
948 return leftBrack
949 case ']':
950 p.rune()
951 return rightBrack
952 case ',':
953 p.rune()
954 return comma
955 case '?':
956 p.rune()
957 return quest
958 case ':':
959 p.rune()
960 return colon
961 case '#':
962 p.rune()
963 return hash
964 case '.':
965 p.rune()
966 return period
967 }
968 panic("unreachable")
969 }
970
971 func (p *Parser) newLit(r rune) {
972 switch {
973 case r < utf8.RuneSelf:
974 p.litBs = p.litBuf[:1]
975 p.litBs[0] = byte(r)
976 case r == runeEOF || r == escNewl:
977 // sentinel runes not present in the input as-is
978 p.litBs = p.litBuf[:0]
979 default:
980 w := utf8.RuneLen(r)
981 p.litBs = append(p.litBuf[:0], p.bs[p.bsp-uint(w):p.bsp]...)
982 }
983 }
984
985 func (p *Parser) endLit() (s string) {
986 if p.r == runeEOF || p.r == escNewl {
987 s = string(p.litBs)
988 } else {
989 s = string(p.litBs[:len(p.litBs)-p.w])
990 }
991 p.litBs = nil
992 return s
993 }
994
995 func (p *Parser) isLitRedir() bool {
996 lit := p.litBs[:len(p.litBs)-1]
997 if lit[0] == '{' && lit[len(lit)-1] == '}' {
998 name := lit[1 : len(lit)-1]
999 // Bash also allows an array element such as {name[idx]}.
1000 if p.lang.in(langBashLike) && len(name) > 0 && name[len(name)-1] == ']' {
1001 if i := bytes.IndexByte(name, '['); i > 0 && i < len(name)-2 {
1002 name = name[:i]
1003 }
1004 }
1005 return ValidName(string(name))
1006 }
1007 return numberLiteral(lit)
1008 }
1009
1010 func positionalRuneParam[T rune | byte](r T) bool {
1011 switch r {
1012 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
1013 return true
1014 }
1015 return false
1016 }
1017
1018 func singleRuneParam[T rune | byte](r T) bool {
1019 switch r {
1020 case '@', '*', '#', '$', '?', '!', '-':
1021 return true
1022 }
1023 return positionalRuneParam(r)
1024 }
1025
1026 func paramNameRune[T rune | byte](r T) bool {
1027 return asciiLetter(r) || asciiDigit(r) || r == '_'
1028 }
1029
1030 // paramNameStartRune reports whether a parameter name can begin with r,
1031 // be it a single-rune name like $@ or a regular name like $foo.
1032 func paramNameStartRune[T rune | byte](r T) bool {
1033 return singleRuneParam(r) || paramNameRune(r)
1034 }
1035
1036 func (p *Parser) advanceLitOther(r rune) {
1037 tok := _LitWord
1038 loop:
1039 for p.newLit(r); r != runeEOF; r = p.rune() {
1040 switch r {
1041 case '\\': // escaped byte follows
1042 p.rune()
1043 case '\'', '"', '`', '$':
1044 tok = _Lit
1045 break loop
1046 case '}':
1047 if p.quote&allParamExp != 0 {
1048 break loop
1049 }
1050 case '/':
1051 if p.quote != paramExpExp {
1052 break loop
1053 }
1054 case ':', '=', '%', '^', ',', '?', '!', '~', '*':
1055 if p.quote&allArithmExpr != 0 {
1056 break loop
1057 }
1058 case '.':
1059 if !p.lang.in(LangZsh) && p.quote&allArithmExpr != 0 {
1060 break loop
1061 }
1062 case '[', ']':
1063 if p.lang.in(langBashLike|LangMirBSDKorn|LangZsh) && p.quote&allArithmExpr != 0 {
1064 break loop
1065 }
1066 fallthrough
1067 case '+', '-', ' ', '\t', ';', '&', '>', '<', '|', '(', ')', '\n', '\r':
1068 if p.quote&allKeepSpaces == 0 {
1069 break loop
1070 }
1071 }
1072 }
1073 p.tok, p.val = tok, p.endLit()
1074 }
1075
1076 // zshNumRange peeks at the bytes after '<' to check for a zsh numeric
1077 // range glob pattern like <->, <5->, <-10>, or <5-10>.
1078 func (p *Parser) zshNumRange() bool {
1079 // Peeking a handful of bytes here should be enough.
1080 // TODO: This should loop for slow readers, e.g. those providing one byte at
1081 // a time. Use a loop and test it with [testing/iotest.OneByteReader].
1082 if int(p.bsp) >= len(p.bs) {
1083 p.fill()
1084 }
1085 rest := p.bs[p.bsp:]
1086 for len(rest) > 0 && rest[0] >= '0' && rest[0] <= '9' {
1087 rest = rest[1:]
1088 }
1089 if len(rest) == 0 || rest[0] != '-' {
1090 return false
1091 }
1092 rest = rest[1:]
1093 for len(rest) > 0 && rest[0] >= '0' && rest[0] <= '9' {
1094 rest = rest[1:]
1095 }
1096 return len(rest) > 0 && rest[0] == '>'
1097 }
1098
1099 func (p *Parser) advanceLitNone(r rune) {
1100 p.eqlOffs = -1
1101 tok := _LitWord
1102 loop:
1103 for p.newLit(r); r != runeEOF; r = p.rune() {
1104 switch r {
1105 case ' ', '\t', '\n', '\r', '&', '|', ';', ')':
1106 break loop
1107 case '(':
1108 break loop
1109 case '\\': // escaped byte follows
1110 p.rune()
1111 case '>', '<':
1112 if r == '<' && p.lang.in(LangZsh) && p.zshNumRange() {
1113 // Zsh numeric range glob like <-> or <1-100>; consume until '>'.
1114 for {
1115 if r = p.rune(); r == '>' || r == runeEOF {
1116 break
1117 }
1118 }
1119 continue
1120 }
1121 if p.peek() == '(' {
1122 tok = _Lit
1123 } else if p.isLitRedir() {
1124 tok = _LitRedir
1125 }
1126 break loop
1127 case '`':
1128 if p.quote != subCmdBckquo {
1129 tok = _Lit
1130 }
1131 break loop
1132 case '"', '\'', '$':
1133 tok = _Lit
1134 break loop
1135 case '?', '*', '+', '@', '!':
1136 if p.extendedGlob() {
1137 tok = _Lit
1138 break loop
1139 }
1140 case '=':
1141 if p.eqlOffs < 0 {
1142 p.eqlOffs = len(p.litBs) - 1
1143 }
1144 case '}':
1145 if p.quote == subCmdBraces && len(p.litBs) == 1 {
1146 // A word-initial `}` closes the substitution even if
1147 // more characters follow, as in `${ foo;}bar`.
1148 p.rune()
1149 break loop
1150 }
1151 case '[':
1152 if p.litBs[0] == '{' && p.lang.in(langBashLike) {
1153 // In bash, words beginning with '{' are always kept whole,
1154 // so that {name[idx]} literals can prefix a redirect
1155 // operator below.
1156 break
1157 }
1158 if p.lang.in(langBashLike|LangMirBSDKorn|LangZsh) && len(p.litBs) > 1 && p.litBs[0] != '[' {
1159 tok = _Lit
1160 break loop
1161 }
1162 }
1163 }
1164 p.tok, p.val = tok, p.endLit()
1165 }
1166
1167 func (p *Parser) advanceLitDquote(r rune) {
1168 tok := _LitWord
1169 loop:
1170 for p.newLit(r); r != runeEOF; r = p.rune() {
1171 switch r {
1172 case '"':
1173 break loop
1174 case '\\': // escaped byte follows
1175 p.rune()
1176 case escNewl, '`', '$':
1177 tok = _Lit
1178 break loop
1179 }
1180 }
1181 p.tok, p.val = tok, p.endLit()
1182 }
1183
1184 func (p *Parser) advanceLitHdoc(r rune) {
1185 // Unlike the rest of nextKeepSpaces quote states, we handle escaped
1186 // newlines here. If lastTok==_Lit, then we know we're following an
1187 // escaped newline, so the first line can't end the heredoc.
1188 lastTok := p.tok
1189 for r == escNewl {
1190 r = p.rune()
1191 lastTok = _Lit
1192 }
1193 p.pos = p.nextPos()
1194
1195 p.tok = _Lit
1196 p.newLit(r)
1197 for p.quote == hdocBodyTabs && r == '\t' {
1198 r = p.rune()
1199 }
1200 lStart := len(p.litBs) - 1
1201 stop := p.hdocStops[len(p.hdocStops)-1]
1202 for ; ; r = p.rune() {
1203 switch r {
1204 case escNewl, '$':
1205 p.val = p.endLit()
1206 return
1207 case '\\': // escaped byte follows
1208 p.rune()
1209 case '`':
1210 if !p.backquoteEnd() {
1211 p.val = p.endLit()
1212 return
1213 }
1214 fallthrough
1215 case '\n', runeEOF:
1216 if p.parsingDoc {
1217 if r == runeEOF {
1218 p.tok = _LitWord
1219 p.val = p.endLit()
1220 return
1221 }
1222 } else if lStart == 0 && lastTok == _Lit {
1223 // This line starts right after an escaped
1224 // newline, so it should never end the heredoc.
1225 } else if lStart >= 0 {
1226 // Compare the current line with the stop word.
1227 line := p.litBs[lStart:]
1228 if r != runeEOF && len(line) > 0 {
1229 line = line[:len(line)-1] // minus trailing character
1230 }
1231 if bytes.Equal(line, stop) {
1232 p.tok = _LitWord
1233 p.val = p.endLit()[:lStart]
1234 if p.val == "" {
1235 p.tok = _Newl
1236 }
1237 p.hdocStops[len(p.hdocStops)-1] = nil
1238 return
1239 }
1240 }
1241 if r != '\n' {
1242 return // hit an unexpected EOF or closing backquote
1243 }
1244 for p.quote == hdocBodyTabs && p.peek() == '\t' {
1245 p.rune()
1246 }
1247 lStart = len(p.litBs)
1248 }
1249 }
1250 }
1251
1252 func (p *Parser) quotedHdocWord() *Word {
1253 r := p.r
1254 p.newLit(r)
1255 pos := p.nextPos()
1256 stop := p.hdocStops[len(p.hdocStops)-1]
1257 for ; ; r = p.rune() {
1258 if r == runeEOF {
1259 return nil
1260 }
1261 for p.quote == hdocBodyTabs && r == '\t' {
1262 r = p.rune()
1263 }
1264 lStart := len(p.litBs) - 1
1265 runeLoop:
1266 for {
1267 switch r {
1268 case runeEOF, '\n':
1269 break runeLoop
1270 case '`':
1271 if p.backquoteEnd() {
1272 break runeLoop
1273 }
1274 case escNewl:
1275 p.litBs = append(p.litBs, '\\', '\n')
1276 break runeLoop
1277 }
1278 r = p.rune()
1279 }
1280 if lStart < 0 {
1281 continue
1282 }
1283 // Compare the current line with the stop word.
1284 line := p.litBs[lStart:]
1285 if r != runeEOF && len(line) > 0 {
1286 line = line[:len(line)-1] // minus \n
1287 }
1288 if bytes.Equal(line, stop) {
1289 p.hdocStops[len(p.hdocStops)-1] = nil
1290 val := p.endLit()[:lStart]
1291 if val == "" {
1292 return nil
1293 }
1294 return p.wordOne(p.lit(pos, val))
1295 }
1296 }
1297 }
1298
1299 func (p *Parser) advanceLitRe(r rune) {
1300 for p.newLit(r); ; r = p.rune() {
1301 switch r {
1302 case '\\':
1303 p.rune()
1304 case '(':
1305 p.rxOpenParens++
1306 case ')':
1307 if p.rxOpenParens--; p.rxOpenParens < 0 {
1308 p.tok, p.val = _LitWord, p.endLit()
1309 p.quote = testExpr
1310 return
1311 }
1312 case ' ', '\t', '\r', '\n', ';', '&', '>', '<':
1313 if p.rxOpenParens <= 0 {
1314 p.tok, p.val = _LitWord, p.endLit()
1315 p.quote = testExpr
1316 return
1317 }
1318 case '"', '\'', '$', '`':
1319 p.tok, p.val = _Lit, p.endLit()
1320 return
1321 case runeEOF:
1322 p.tok, p.val = _LitWord, p.endLit()
1323 p.quote = noState
1324 return
1325 }
1326 }
1327 }
1328
1329 func testUnaryOp(val string) UnTestOperator {
1330 switch val {
1331 case "!":
1332 return TsNot
1333 case "-e", "-a":
1334 return TsExists
1335 case "-f":
1336 return TsRegFile
1337 case "-d":
1338 return TsDirect
1339 case "-c":
1340 return TsCharSp
1341 case "-b":
1342 return TsBlckSp
1343 case "-p":
1344 return TsNmPipe
1345 case "-S":
1346 return TsSocket
1347 case "-L", "-h":
1348 return TsSmbLink
1349 case "-k":
1350 return TsSticky
1351 case "-g":
1352 return TsGIDSet
1353 case "-u":
1354 return TsUIDSet
1355 case "-G":
1356 return TsGrpOwn
1357 case "-O":
1358 return TsUsrOwn
1359 case "-N":
1360 return TsModif
1361 case "-r":
1362 return TsRead
1363 case "-w":
1364 return TsWrite
1365 case "-x":
1366 return TsExec
1367 case "-s":
1368 return TsNoEmpty
1369 case "-t":
1370 return TsFdTerm
1371 case "-z":
1372 return TsEmpStr
1373 case "-n":
1374 return TsNempStr
1375 case "-o":
1376 return TsOptSet
1377 case "-v":
1378 return TsVarSet
1379 case "-R":
1380 return TsRefVar
1381 default:
1382 return 0
1383 }
1384 }
1385
1386 func testBinaryOp(val string) BinTestOperator {
1387 switch val {
1388 case "=":
1389 return TsMatchShort
1390 case "==":
1391 return TsMatch
1392 case "!=":
1393 return TsNoMatch
1394 case "=~":
1395 return TsReMatch
1396 case "-nt":
1397 return TsNewer
1398 case "-ot":
1399 return TsOlder
1400 case "-ef":
1401 return TsDevIno
1402 case "-eq":
1403 return TsEql
1404 case "-ne":
1405 return TsNeq
1406 case "-le":
1407 return TsLeq
1408 case "-ge":
1409 return TsGeq
1410 case "-lt":
1411 return TsLss
1412 case "-gt":
1413 return TsGtr
1414 default:
1415 return 0
1416 }
1417 }