Debian Codegraph @

syntax/parser.go

raw
1 // Copyright (c) 2016, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package syntax
5
6 import (
7 "fmt"
8 "io"
9 "iter"
10 "math/bits"
11 "slices"
12 "strings"
13 "unicode/utf8"
14 )
15
16 // ParserOption is a function which can be passed to NewParser
17 // to alter its behavior. To apply option to existing Parser
18 // call it directly, for example KeepComments(true)(parser).
19 type ParserOption func(*Parser)
20
21 // KeepComments makes the parser parse comments and attach them to
22 // nodes, as opposed to discarding them.
23 func KeepComments(enabled bool) ParserOption {
24 return func(p *Parser) { p.keepComments = enabled }
25 }
26
27 // LangVariant describes a shell language variant to use when tokenizing and
28 // parsing shell code. The zero value is [LangBash].
29 //
30 // This type implements [flag.Value] so that it can be used as a CLI flag.
31 type LangVariant int
32
33 // TODO(v4): the zero value should be left as an unset and invalid value.
34 // TODO(v4): the type should be uint32 now that we use this as a bitset;
35 // an unsigned integer is clearer, and being agnostic to uint size avoids issues.
36
37 const (
38 // LangBash corresponds to the GNU Bash language, as described in its
39 // manual at https://www.gnu.org/software/bash/manual/bash.html.
40 //
41 // We currently follow Bash version 5.2.
42 //
43 // Its string representation is "bash".
44 LangBash LangVariant = 1 << iota
45
46 // LangPOSIX corresponds to the POSIX Shell language, as described at
47 // https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html.
48 //
49 // Its string representation is "posix" or "sh".
50 LangPOSIX
51
52 // LangMirBSDKorn corresponds to the MirBSD Korn Shell, also known as
53 // mksh, as described at http://www.mirbsd.org/htman/i386/man1/mksh.htm.
54 // Note that it shares some features with Bash, due to the shared
55 // ancestry that is ksh.
56 //
57 // We currently follow mksh version 59.
58 //
59 // Its string representation is "mksh".
60 LangMirBSDKorn
61
62 // LangBats corresponds to the Bash Automated Testing System language,
63 // as described at https://github.com/bats-core/bats-core. Note that
64 // it's just a small extension of the Bash language.
65 //
66 // Its string representation is "bats".
67 LangBats
68
69 // LangZsh corresponds to the Z shell, as described at https://www.zsh.org/.
70 //
71 // Note that its support in the syntax package is experimental and
72 // incomplete for now. See https://github.com/mvdan/sh/issues/120.
73 //
74 // We currently follow Zsh version 5.9.
75 //
76 // Its string representation is "zsh".
77 LangZsh
78
79 // langResolvedVariantsCount is the number of variants declared above,
80 // that is, langResolvedVariants.count() as a constant.
81 langResolvedVariantsCount = iota
82
83 // LangAuto corresponds to automatic language detection,
84 // commonly used by end-user applications like shfmt,
85 // which can guess a file's language variant given its filename or shebang.
86 //
87 // At this time, [Variant] does not support LangAuto.
88 LangAuto LangVariant = 1 << langResolvedVariantsCount
89
90 // langBashLegacy is what [LangBash] used to be, when it was zero.
91 // We still support it for the sake of backwards compatibility.
92 langBashLegacy LangVariant = 0
93
94 // langResolvedVariants contains all known variants except [LangAuto],
95 // which is meant to resolve to another variant.
96 langResolvedVariants = LangBash | LangPOSIX | LangMirBSDKorn | LangBats | LangZsh
97
98 // langBashLike contains Bash plus all variants which are extensions of it.
99 langBashLike = LangBash | LangBats
100 )
101
102 // Variant changes the shell language variant that the parser will
103 // accept.
104 //
105 // The passed language variant must be one of the constant values defined in
106 // this package.
107 func Variant(l LangVariant) ParserOption {
108 switch l {
109 case langBashLegacy:
110 l = LangBash
111 case LangBash, LangPOSIX, LangMirBSDKorn, LangBats, LangZsh:
112 case LangAuto:
113 panic("LangAuto is not supported by the parser at this time")
114 default:
115 panic(fmt.Sprintf("unknown shell language variant: %#b", l))
116 }
117 return func(p *Parser) { p.lang = l }
118 }
119
120 func (l LangVariant) String() string {
121 switch l {
122 case langBashLegacy, LangBash:
123 return "bash"
124 case LangPOSIX:
125 return "posix"
126 case LangMirBSDKorn:
127 return "mksh"
128 case LangBats:
129 return "bats"
130 case LangZsh:
131 return "zsh"
132 case LangAuto:
133 return "auto"
134 }
135 return "unknown shell language variant"
136 }
137
138 func (l *LangVariant) Set(s string) error {
139 switch s {
140 case "bash":
141 *l = LangBash
142 case "posix", "sh", "dash":
143 *l = LangPOSIX
144 case "mksh":
145 *l = LangMirBSDKorn
146 case "bats":
147 *l = LangBats
148 case "zsh":
149 *l = LangZsh
150 case "auto":
151 *l = LangAuto
152 default:
153 return fmt.Errorf("unknown shell language variant: %q", s)
154 }
155 return nil
156 }
157
158 func (l LangVariant) in(l2 LangVariant) bool {
159 return l&l2 == l
160 }
161
162 func (l LangVariant) count() int {
163 return bits.OnesCount32(uint32(l))
164 }
165
166 func (l LangVariant) index() int {
167 return bits.TrailingZeros32(uint32(l))
168 }
169
170 func (l LangVariant) bits() iter.Seq[LangVariant] {
171 return func(yield func(LangVariant) bool) {
172 for n := LangVariant(1); n < langResolvedVariants; n <<= 1 {
173 if l&n == 0 {
174 continue
175 }
176 if !yield(n) {
177 return
178 }
179 }
180 }
181 }
182
183 // StopAt configures the lexer to stop at an arbitrary word, treating it
184 // as if it were the end of the input. It can contain any characters
185 // except whitespace, and cannot be over four bytes in size.
186 //
187 // This can be useful to embed shell code within another language, as
188 // one can use a special word to mark the delimiters between the two.
189 //
190 // As a word, it will only apply when following whitespace or a
191 // separating token. For example, StopAt("$$") will act on the inputs
192 // "foo $$" and "foo;$$", but not on "foo '$$'".
193 //
194 // The match is done by prefix, so the example above will also act on
195 // "foo $$bar".
196 func StopAt(word string) ParserOption {
197 if len(word) > 4 {
198 panic("stop word can't be over four bytes in size")
199 }
200 if strings.ContainsAny(word, " \t\n\r") {
201 panic("stop word can't contain whitespace characters")
202 }
203 return func(p *Parser) { p.stopAt = []byte(word) }
204 }
205
206 // RecoverErrors allows the parser to skip up to a maximum number of
207 // errors in the given input on a best-effort basis.
208 // This can be useful to tab-complete an interactive shell prompt,
209 // or when providing diagnostics on slightly incomplete shell source.
210 //
211 // Currently, this only helps with mandatory tokens from the shell grammar
212 // which are not present in the input. They result in position fields
213 // or nodes whose position report [Pos.IsRecovered] as true.
214 //
215 // For example, given the input
216 //
217 // (foo |
218 //
219 // the result will contain two recovered positions; first, the pipe requires
220 // a statement to follow, and as [Stmt.Pos] reports, the entire node is recovered.
221 // Second, the subshell needs to be closed, so [Subshell.Rparen] is recovered.
222 func RecoverErrors(maximum int) ParserOption {
223 return func(p *Parser) { p.recoverErrorsMax = maximum }
224 }
225
226 // NewParser allocates a new [Parser] and applies any number of options.
227 func NewParser(options ...ParserOption) *Parser {
228 p := &Parser{
229 lang: LangBash,
230 }
231 for _, opt := range options {
232 opt(p)
233 }
234 return p
235 }
236
237 // Parse reads and parses a shell program with an optional name. It
238 // returns the parsed program if no issues were encountered. Otherwise,
239 // an error is returned. Reads from r are buffered.
240 //
241 // Parse can be called more than once, but not concurrently. That is, a
242 // Parser can be reused once it is done working.
243 func (p *Parser) Parse(r io.Reader, name string) (*File, error) {
244 p.reset()
245 p.f = &File{Name: name}
246 p.src = r
247 p.rune()
248 p.next()
249 p.f.Stmts, p.f.Last = p.stmtList()
250 if p.err == nil {
251 // EOF immediately after heredoc word so no newline to
252 // trigger the parsing error.
253 p.doHeredocs()
254 }
255 return p.f, p.err
256 }
257
258 // Stmts is a pre-iterators API which now wraps [Parser.StmtsSeq].
259 //
260 // Deprecated: use [Parser.StmtsSeq].
261 func (p *Parser) Stmts(r io.Reader, fn func(*Stmt) bool) error {
262 for stmt, err := range p.StmtsSeq(r) {
263 if err != nil {
264 return err
265 }
266 if !fn(stmt) {
267 break
268 }
269 }
270 return nil
271 }
272
273 // StmtsSeq reads and parses statements one at a time via an iterator.
274 func (p *Parser) StmtsSeq(r io.Reader) iter.Seq2[*Stmt, error] {
275 p.reset()
276 p.f = &File{}
277 p.src = r
278 return func(yield func(*Stmt, error) bool) {
279 p.rune()
280 p.next()
281 p.stmts(yield)
282 if p.err == nil {
283 // EOF immediately after heredoc word so no newline to
284 // trigger the parsing error.
285 p.doHeredocs()
286 }
287 if p.err != nil {
288 // Yield any final error from the parser.
289 yield(nil, p.err)
290 }
291 }
292 }
293
294 type wrappedReader struct {
295 p *Parser
296 rd io.Reader
297
298 lastLine int64
299 accumulated []*Stmt
300 yield func([]*Stmt, error) bool
301 }
302
303 func (w *wrappedReader) Read(p []byte) (n int, err error) {
304 // If we lexed a newline for the first time, we just finished a line, so
305 // we may need to give a callback for the edge cases below not covered
306 // by [Parser.Stmts].
307 if (w.p.r == '\n' || w.p.r == escNewl) && w.p.line > w.lastLine {
308 if w.p.Incomplete() {
309 // Incomplete statement; call back to print "> ".
310 if !w.yield(w.accumulated, w.p.err) {
311 return 0, io.EOF
312 }
313 } else if len(w.accumulated) == 0 {
314 // Nothing was parsed; call back to print another "$ ".
315 if !w.yield(nil, w.p.err) {
316 return 0, io.EOF
317 }
318 }
319 w.lastLine = w.p.line
320 }
321 return w.rd.Read(p)
322 }
323
324 // Interactive is a pre-iterators API which now wraps [Parser.InteractiveSeq].
325 //
326 // Deprecated: use [Parser.InteractiveSeq].
327 func (p *Parser) Interactive(r io.Reader, fn func([]*Stmt) bool) error {
328 for stmts, err := range p.InteractiveSeq(r) {
329 if err != nil {
330 return err
331 }
332 if !fn(stmts) {
333 break
334 }
335 }
336 return nil
337 }
338
339 // InteractiveSeq implements what is necessary to parse statements in an
340 // interactive shell. The parser will call the given function under two
341 // circumstances outlined below.
342 //
343 // If a line containing any number of statements is parsed, the function will be
344 // called with said statements.
345 //
346 // If a line ending in an incomplete statement is parsed, the function will be
347 // called with any fully parsed statements, and [Parser.Incomplete] will return true.
348 //
349 // One can imagine a simple interactive shell implementation as follows:
350 //
351 // fmt.Fprintf(os.Stdout, "$ ")
352 // parser.Interactive(os.Stdin, func(stmts []*syntax.Stmt) bool {
353 // if parser.Incomplete() {
354 // fmt.Fprintf(os.Stdout, "> ")
355 // return true
356 // }
357 // run(stmts)
358 // fmt.Fprintf(os.Stdout, "$ ")
359 // return true
360 // }
361 //
362 // If the callback function returns false, parsing is stopped and the function
363 // is not called again.
364 func (p *Parser) InteractiveSeq(r io.Reader) iter.Seq2[[]*Stmt, error] {
365 return func(yield func([]*Stmt, error) bool) {
366 w := wrappedReader{p: p, rd: r, yield: yield}
367 for stmts, err := range p.StmtsSeq(&w) {
368 w.accumulated = append(w.accumulated, stmts)
369 if err != nil {
370 if !yield(w.accumulated, err) {
371 break
372 }
373 // If the caller wishes, they can continue in the presence of parse errors.
374 // TODO: does this even work? Write tests for it. This only came up
375 continue
376 }
377 // We finished parsing a statement and we're at a newline token,
378 // so we finished fully parsing a number of statements. Call
379 // back to run the statements and print "$ ".
380 if p.tok == _Newl {
381 if !yield(w.accumulated, nil) {
382 break
383 }
384 w.accumulated = w.accumulated[:0]
385 // The callback above would already print "$ ", so we
386 // don't want the subsequent wrappedReader.Read to cause
387 // another "$ " print thinking that nothing was parsed.
388 w.lastLine = w.p.line + 1
389 }
390 }
391 }
392 }
393
394 // Words is a pre-iterators API which now wraps [Parser.WordsSeq].
395 //
396 // Deprecated: use [Parser.WordsSeq].
397 func (p *Parser) Words(r io.Reader, fn func(*Word) bool) error {
398 for w, err := range p.WordsSeq(r) {
399 if err != nil {
400 return err
401 }
402 if !fn(w) {
403 break
404 }
405 }
406 return nil
407 }
408
409 // WordsSeq reads and parses a sequence of words alongside any error encountered.
410 //
411 // Newlines are skipped, meaning that multi-line input will work fine. If the
412 // parser encounters a token that isn't a word, such as a semicolon, an error
413 // will be returned.
414 //
415 // Note that the lexer doesn't currently tokenize spaces, so it may need to read
416 // a non-space byte such as a newline or a letter before finishing the parsing
417 // of a word. This will be fixed in the future.
418 func (p *Parser) WordsSeq(r io.Reader) iter.Seq2[*Word, error] {
419 p.reset()
420 p.f = &File{}
421 p.src = r
422 return func(yield func(*Word, error) bool) {
423 p.rune()
424 p.next()
425 for {
426 p.got(_Newl)
427 w := p.getWord()
428 if w == nil {
429 if p.tok != _EOF {
430 p.curErr("%#q is not a valid word", p.tok)
431 }
432 if p.err != nil {
433 yield(nil, p.err)
434 }
435 return
436 }
437 if !yield(w, nil) {
438 return
439 }
440 }
441 }
442 }
443
444 // Document parses a single here-document word. That is, it parses the input as
445 // if they were lines following a <<EOF redirection.
446 //
447 // In practice, this is the same as parsing the input as if it were within
448 // double quotes, but without having to escape all double quote characters.
449 // Similarly, the here-document word parsed here cannot be ended by any
450 // delimiter other than reaching the end of the input.
451 func (p *Parser) Document(r io.Reader) (*Word, error) {
452 p.reset()
453 p.f = &File{}
454 p.src = r
455 p.rune()
456 p.quote = hdocBody
457 p.hdocStops = [][]byte{[]byte("MVDAN_CC_SH_SYNTAX_EOF")}
458 p.parsingDoc = true
459 p.next()
460 w := p.getWord()
461 return w, p.err
462 }
463
464 // Arithmetic parses a single arithmetic expression. That is, as if the input
465 // were within the $(( and )) tokens.
466 func (p *Parser) Arithmetic(r io.Reader) (ArithmExpr, error) {
467 p.reset()
468 p.f = &File{}
469 p.src = r
470 p.rune()
471 p.quote = arithmExpr
472 p.next()
473 expr := p.arithmExpr(false)
474 return expr, p.err
475 }
476
477 // Parser holds the internal state of the parsing mechanism of a
478 // program.
479 type Parser struct {
480 src io.Reader
481 bs []byte // current chunk of read bytes
482 bsp uint // offset within [Parser.bs] for the rune after [Parser.r]
483 r rune // next rune; [runeEOF] when it went past EOF, or we stopped
484 w int // width of [Parser.r]
485
486 f *File
487
488 spaced bool // whether [Parser.tok] has whitespace on its left
489
490 err error // lexer/parser error
491 readErr error // got a read error, but bytes left
492 readEOF bool // [Parser.src] already gave us an [io.EOF] error
493
494 tok token // current token
495 val string // current value (valid if tok is _Lit*)
496
497 // position of [Parser.r], to be converted to [Parser.pos] later
498 offs, line, col int64
499
500 pos Pos // position of tok
501
502 quote quoteState // current lexer state
503 eqlOffs int // position of '=' in [Parser.val] when [Parser.tok].isLit is true
504
505 keepComments bool
506 lang LangVariant
507
508 stopAt []byte
509
510 recoveredErrors int
511 recoverErrorsMax int
512
513 forbidNested bool
514
515 // list of pending heredoc bodies
516 buriedHdocs int
517 heredocs []*Redirect
518
519 hdocStops [][]byte // stack of end words for open heredocs
520
521 parsingDoc bool // true if using [Parser.Document]
522
523 // openNodes tracks how many entire statements or words we're currently parsing.
524 // A non-zero number means that we require certain tokens or words before
525 // reaching EOF, used for [Parser.Incomplete].
526 openNodes int
527 // openBquotes is how many levels of backquotes are open at the moment.
528 openBquotes int
529 // openBquoteDbls is how many of those backquote levels began inside
530 // double quotes, where backslashes also escape double quotes.
531 openBquoteDbls int
532
533 // lastBquoteEsc is how many times the last backquote token was escaped
534 lastBquoteEsc int
535
536 rxOpenParens int
537 rxFirstPart bool
538
539 accComs []Comment
540 curComs *[]Comment
541
542 litBatch []Lit
543 wordBatch []wordAlloc
544
545 readBuf [bufSize]byte
546 litBuf [bufSize]byte
547 litBs []byte
548 }
549
550 // Incomplete reports whether the parser needs more input bytes
551 // to finish properly parsing a statement or word.
552 //
553 // It is only safe to call while the parser is blocked on a read. For an example
554 // use case, see [Parser.Interactive].
555 func (p *Parser) Incomplete() bool {
556 // If there are any open nodes, we need to finish them.
557 // If we're constructing a literal, we need to finish it.
558 return p.openNodes > 0 || len(p.litBs) > 0
559 }
560
561 const bufSize = 1 << 10
562
563 func (p *Parser) reset() {
564 p.tok, p.val = illegalTok, ""
565 p.eqlOffs = 0
566 p.bs, p.bsp = nil, 0
567 p.offs, p.line, p.col = 0, 1, 1
568 p.r, p.w = 0, 0
569 p.err, p.readErr, p.readEOF = nil, nil, false
570 p.quote, p.forbidNested = noState, false
571 p.openNodes = 0
572 p.recoveredErrors = 0
573 p.heredocs, p.buriedHdocs = p.heredocs[:0], 0
574 p.hdocStops = nil
575 p.parsingDoc = false
576 p.openBquotes = 0
577 p.openBquoteDbls = 0
578 p.accComs = nil
579 p.accComs, p.curComs = nil, &p.accComs
580 p.litBatch = nil
581 p.wordBatch = nil
582 p.litBs = nil
583 }
584
585 // nextPos returns the position of the next rune, [Parser.r].
586 func (p *Parser) nextPos() Pos {
587 // Basic protection against offset overflow;
588 // note that an offset of 0 is valid, so we leave the maximum.
589 offset := min(p.offs+int64(p.bsp)-int64(p.w), offsetMax)
590 var line, col uint
591 if p.line <= lineMax {
592 line = uint(p.line)
593 }
594 if p.col <= colMax {
595 col = uint(p.col)
596 }
597 return NewPos(uint(offset), line, col)
598 }
599
600 func (p *Parser) lit(pos Pos, val string) *Lit {
601 if len(p.litBatch) == 0 {
602 p.litBatch = make([]Lit, 32)
603 }
604 l := &p.litBatch[0]
605 p.litBatch = p.litBatch[1:]
606 l.ValuePos = pos
607 l.ValueEnd = p.nextPos()
608 l.Value = val
609 return l
610 }
611
612 type wordAlloc struct {
613 word Word
614 parts [1]WordPart
615 }
616
617 func (p *Parser) wordAnyNumber() *Word {
618 if len(p.wordBatch) == 0 {
619 p.wordBatch = make([]wordAlloc, 32)
620 }
621 alloc := &p.wordBatch[0]
622 p.wordBatch = p.wordBatch[1:]
623 w := &alloc.word
624 w.Parts = p.wordParts(alloc.parts[:0])
625 return w
626 }
627
628 func (p *Parser) wordOne(part WordPart) *Word {
629 if len(p.wordBatch) == 0 {
630 p.wordBatch = make([]wordAlloc, 32)
631 }
632 alloc := &p.wordBatch[0]
633 p.wordBatch = p.wordBatch[1:]
634 w := &alloc.word
635 w.Parts = alloc.parts[:1]
636 w.Parts[0] = part
637 return w
638 }
639
640 func (p *Parser) call(w *Word) *CallExpr {
641 var alloc struct {
642 ce CallExpr
643 ws [4]*Word
644 }
645 ce := &alloc.ce
646 ce.Args = alloc.ws[:1]
647 ce.Args[0] = w
648 return ce
649 }
650
651 type quoteState uint32
652
653 const (
654 // The initial state of the parser.
655 noState quoteState = 1 << iota
656
657 // Used when parsing parameter expansions; use with [Parser.rune],
658 // [Parser.next] always returns [illegalTok].
659 runeByRune
660
661 // unquotedWordCont exists purely so that the '#' in $foo#bar does not
662 // get parsed as a comment; it's a tiny variation on [noState].
663 unquotedWordCont
664
665 subCmd
666 subCmdBckquo
667 // subCmdBraces is like subCmd, but for `${ stmts;}` and `${|stmts;}`,
668 // whose bodies end at a word beginning with `}`.
669 subCmdBraces
670 dblQuotes
671 hdocWord
672 hdocBody
673 hdocBodyTabs
674 arithmExpr
675 arithmExprLet
676 arithmExprCmd
677 testExpr
678 testExprRegexp
679 switchCase
680 // paramExpArithm is a subscript like ${a[i]}, which can be a string key
681 // rather than an arithmetic expression when the array is associative.
682 paramExpArithm
683 // paramExpSlice is a slice like ${a:i:j}, which is always arithmetic.
684 paramExpSlice
685 paramExpRepl
686 paramExpExp
687 arrayElems
688
689 allKeepSpaces = runeByRune | paramExpRepl | dblQuotes | hdocBody |
690 hdocBodyTabs | paramExpRepl | paramExpExp
691 allRegTokens = noState | unquotedWordCont | subCmd | subCmdBckquo | subCmdBraces |
692 hdocWord | switchCase | arrayElems | testExpr
693 allArithmExpr = arithmExpr | arithmExprLet | arithmExprCmd |
694 paramExpArithm | paramExpSlice
695 allParamExp = paramExpArithm | paramExpSlice | paramExpRepl | paramExpExp
696 )
697
698 type saveState struct {
699 quote quoteState
700 buriedHdocs int
701 }
702
703 func (p *Parser) preNested(quote quoteState) (s saveState) {
704 s.quote, s.buriedHdocs = p.quote, p.buriedHdocs
705 p.buriedHdocs, p.quote = len(p.heredocs), quote
706 return s
707 }
708
709 func (p *Parser) postNested(s saveState) {
710 p.quote, p.buriedHdocs = s.quote, s.buriedHdocs
711 }
712
713 func (p *Parser) unquotedWordBytes(w *Word) ([]byte, bool) {
714 buf := make([]byte, 0, 4)
715 didUnquote := false
716 for _, wp := range w.Parts {
717 buf, didUnquote = p.unquotedWordPart(buf, wp, false)
718 }
719 return buf, didUnquote
720 }
721
722 func (p *Parser) unquotedWordPart(buf []byte, wp WordPart, quotes bool) (_ []byte, quoted bool) {
723 switch wp := wp.(type) {
724 case *Lit:
725 for i := 0; i < len(wp.Value); i++ {
726 if b := wp.Value[i]; b == '\\' && !quotes {
727 if i++; i < len(wp.Value) {
728 buf = append(buf, wp.Value[i])
729 }
730 quoted = true
731 } else {
732 buf = append(buf, b)
733 }
734 }
735 case *SglQuoted:
736 buf = append(buf, []byte(wp.Value)...)
737 quoted = true
738 case *DblQuoted:
739 for _, wp2 := range wp.Parts {
740 buf, _ = p.unquotedWordPart(buf, wp2, true)
741 }
742 quoted = true
743 }
744 return buf, quoted
745 }
746
747 func (p *Parser) doHeredocs() {
748 hdocs := p.heredocs[p.buriedHdocs:]
749 if len(hdocs) == 0 {
750 // Nothing do do; don't even issue a read.
751 return
752 }
753 p.rune() // consume '\n', since we know p.tok == _Newl
754 old := p.quote
755 p.heredocs = p.heredocs[:p.buriedHdocs]
756 for i, r := range hdocs {
757 if p.err != nil {
758 break
759 }
760 p.quote = hdocBody
761 if r.Op == DashHdoc {
762 p.quote = hdocBodyTabs
763 }
764 stop, quoted := p.unquotedWordBytes(r.Word)
765 p.hdocStops = append(p.hdocStops, stop)
766 if i > 0 && p.r == '\n' {
767 p.rune()
768 }
769 if quoted {
770 r.Hdoc = p.quotedHdocWord()
771 } else {
772 p.next()
773 r.Hdoc = p.getWord()
774 }
775 if stop := p.hdocStops[len(p.hdocStops)-1]; stop != nil {
776 p.posErr(r.Pos(), "unclosed here-document %#q", stop)
777 }
778 p.hdocStops = p.hdocStops[:len(p.hdocStops)-1]
779 }
780 p.quote = old
781 }
782
783 func (p *Parser) got(tok token) bool {
784 if p.tok == tok {
785 p.next()
786 return true
787 }
788 return false
789 }
790
791 func (p *Parser) gotRsrv(val string) (Pos, bool) {
792 pos := p.pos
793 if p.tok == _LitWord && p.val == val {
794 p.next()
795 return pos, true
796 }
797 return pos, false
798 }
799
800 func (p *Parser) recoverError() bool {
801 if p.recoveredErrors < p.recoverErrorsMax {
802 p.recoveredErrors++
803 return true
804 }
805 return false
806 }
807
808 type noQuote string
809
810 func (s noQuote) Format(f fmt.State, verb rune) {
811 f.Write([]byte(s))
812 }
813
814 func (t token) Format(f fmt.State, verb rune) {
815 if t < _realTokenBoundary && verb == 'q' {
816 // EOF, Lit and the others should not be quoted in error messages
817 // as they are not real shell syntax like `if` or `{`.
818 f.Write([]byte(t.String()))
819 } else {
820 fmt.Fprintf(f, fmt.FormatString(f, verb), t.String())
821 }
822 }
823
824 func (p *Parser) followErr(pos Pos, left, right any) {
825 p.posErr(pos, "%#q must be followed by %#q", left, right)
826 }
827
828 func (p *Parser) followErrExp(pos Pos, left any) {
829 p.followErr(pos, left, noQuote("an expression"))
830 }
831
832 func (p *Parser) follow(lpos Pos, left string, tok token) {
833 if !p.got(tok) {
834 p.followErr(lpos, left, tok)
835 }
836 }
837
838 func (p *Parser) followRsrv(lpos Pos, left, val string) Pos {
839 pos, ok := p.gotRsrv(val)
840 if !ok {
841 if p.recoverError() {
842 return recoveredPos
843 }
844 p.followErr(lpos, left, val)
845 }
846 return pos
847 }
848
849 func (p *Parser) followStmts(left string, lpos Pos, stops ...string) ([]*Stmt, []Comment) {
850 // Language variants disallowing empty command lists:
851 // * [LangPOSIX]: "A list is a sequence of one or more AND-OR lists...".
852 // * [LangBash]: "A list is a sequence of one or more pipelines..."
853 //
854 // Language variants allowing empty command lists:
855 // * [LangZsh]: "A list is a sequence of zero or more sublists...".
856 // * [LangMirBSDKorn]: "Lists of commands can be created by separating pipelines...";
857 // note that the man page is not explicit, but the shell clearly allows e.g. `{ }`.
858 if p.got(semicolon) {
859 if p.lang.in(LangZsh | LangMirBSDKorn) {
860 return nil, nil // allow an empty list
861 }
862 p.followErr(lpos, left, noQuote("a statement list"))
863 return nil, nil
864 }
865 stmts, last := p.stmtList(stops...)
866 if len(stmts) < 1 {
867 if p.lang.in(LangZsh | LangMirBSDKorn) {
868 return nil, nil // allow an empty list
869 }
870 if p.recoverError() {
871 return []*Stmt{{Position: recoveredPos}}, nil
872 }
873 p.followErr(lpos, left, noQuote("a statement list"))
874 }
875 return stmts, last
876 }
877
878 func (p *Parser) followWordTok(tok token, pos Pos) *Word {
879 w := p.getWord()
880 if w == nil {
881 if p.recoverError() {
882 return p.wordOne(&Lit{ValuePos: recoveredPos})
883 }
884 p.followErr(pos, tok, noQuote("a word"))
885 }
886 return w
887 }
888
889 func (p *Parser) stmtEnd(n Node, start, end string) Pos {
890 pos, ok := p.gotRsrv(end)
891 if !ok {
892 if p.recoverError() {
893 return recoveredPos
894 }
895 p.posErr(n.Pos(), "%#q statement must end with %#q", start, end)
896 }
897 return pos
898 }
899
900 func (p *Parser) quoteErr(lpos Pos, quote token) {
901 p.posErr(lpos, "reached %#q without closing quote %#q", p.tok, quote)
902 }
903
904 func (p *Parser) matchingErr(lpos Pos, left, right token) {
905 p.posErr(lpos, "reached %#q without matching %#q with %#q", p.tok, left, right)
906 }
907
908 func (p *Parser) matched(lpos Pos, left, right token) Pos {
909 pos := p.pos
910 if !p.got(right) {
911 if p.recoverError() {
912 return recoveredPos
913 }
914 p.matchingErr(lpos, left, right)
915 }
916 return pos
917 }
918
919 func (p *Parser) errPass(err error) {
920 if p.err == nil {
921 p.err = err
922 p.bsp = uint(len(p.bs)) + 1
923 p.r = runeEOF
924 p.w = 1
925 p.tok = _EOF
926 }
927 }
928
929 // IsIncomplete reports whether a Parser error could have been avoided with
930 // extra input bytes. For example, if an [io.EOF] was encountered while there was
931 // an unclosed quote or parenthesis.
932 func IsIncomplete(err error) bool {
933 perr, ok := err.(ParseError)
934 return ok && perr.Incomplete
935 }
936
937 // TODO: probably redo with a [LangVariant] argument.
938 // Perhaps offer an iterator version as well.
939
940 // IsKeyword returns true if the given word is a language keyword
941 // in POSIX Shell or Bash.
942 func IsKeyword(word string) bool {
943 // This list has been copied from the bash 5.1 source code, file y.tab.c +4460
944 // TODO: should we include entries for zsh here? e.g. "{}", "repeat", "always", ...
945 switch word {
946 case
947 "!",
948 "[[", // only if COND_COMMAND is defined
949 "]]", // only if COND_COMMAND is defined
950 "case",
951 "coproc", // only if COPROCESS_SUPPORT is defined
952 "do",
953 "done",
954 "else",
955 "esac",
956 "fi",
957 "for",
958 "function",
959 "if",
960 "in",
961 "select", // only if SELECT_COMMAND is defined
962 "then",
963 "time", // only if COMMAND_TIMING is defined
964 "until",
965 "while",
966 "{",
967 "}":
968 return true
969 }
970 return false
971 }
972
973 // ParseError represents an error found when parsing a source file, from which
974 // the parser cannot recover.
975 type ParseError struct {
976 Filename string
977 Pos Pos
978 Text string
979
980 Incomplete bool
981 }
982
983 func (e ParseError) Error() string {
984 if e.Filename == "" {
985 return fmt.Sprintf("%s: %s", e.Pos, e.Text)
986 }
987 return fmt.Sprintf("%s:%s: %s", e.Filename, e.Pos, e.Text)
988 }
989
990 // LangError is returned when the parser encounters code that is only valid in
991 // other shell language variants. The error includes what feature is not present
992 // in the current language variant, and what languages support it.
993 type LangError struct {
994 Filename string
995 Pos Pos
996
997 // TODO(v4): replace the Langs slice with a single LangVariant bitset,
998 // which is what the parser uses internally already.
999
1000 // Feature briefly describes which language feature caused the error.
1001 Feature string
1002 // Langs lists some of the language variants which support the feature.
1003 Langs []LangVariant
1004 // LangUsed is the language variant used which led to the error.
1005 LangUsed LangVariant
1006 }
1007
1008 func (e LangError) Error() string {
1009 var sb strings.Builder
1010 if e.Filename != "" {
1011 sb.WriteString(e.Filename)
1012 sb.WriteString(":")
1013 }
1014 sb.WriteString(e.Pos.String())
1015 sb.WriteString(": ")
1016 sb.WriteString(e.Feature)
1017 if strings.HasSuffix(e.Feature, "s") {
1018 sb.WriteString(" are a ")
1019 } else {
1020 sb.WriteString(" is a ")
1021 }
1022 for i, lang := range e.Langs {
1023 if i > 0 {
1024 sb.WriteString("/")
1025 }
1026 sb.WriteString(lang.String())
1027 }
1028 sb.WriteString(" feature; tried parsing as ")
1029 sb.WriteString(e.LangUsed.String())
1030 return sb.String()
1031 }
1032
1033 func (p *Parser) posErr(pos Pos, format string, args ...any) {
1034 // for i, arg := range args {
1035 // if arg, ok := arg.(fmt.Stringer); ok && arg != _EOF {
1036 // args[i] = quotedToken(arg)
1037 // }
1038 // }
1039 p.errPass(ParseError{
1040 Filename: p.f.Name,
1041 Pos: pos,
1042 Text: fmt.Sprintf(format, args...),
1043 Incomplete: p.tok == _EOF && p.Incomplete(),
1044 })
1045 }
1046
1047 func (p *Parser) curErr(format string, args ...any) {
1048 p.posErr(p.pos, format, args...)
1049 }
1050
1051 func (p *Parser) checkLang(pos Pos, langSet LangVariant, format string, a ...any) {
1052 if p.lang.in(langSet) {
1053 return
1054 }
1055 if langBashLike.in(langSet) {
1056 // If we're reporting an error because a feature is for bash-like funcs,
1057 // just mention "bash" rather than "bash/bats" for the sake of clarity.
1058 langSet &^= LangBats
1059 }
1060 p.errPass(LangError{
1061 Filename: p.f.Name,
1062 Pos: pos,
1063 Feature: fmt.Sprintf(format, a...),
1064 Langs: slices.Collect(langSet.bits()),
1065 LangUsed: p.lang,
1066 })
1067 }
1068
1069 func (p *Parser) stmts(yield func(*Stmt, error) bool, stops ...string) {
1070 gotEnd := true
1071 loop:
1072 for p.tok != _EOF {
1073 newLine := p.got(_Newl)
1074 switch p.tok {
1075 case _LitWord:
1076 for _, stop := range stops {
1077 if p.val == stop {
1078 break loop
1079 }
1080 }
1081 if p.val == "}" {
1082 p.curErr(`%#q can only be used to close a block`, rightBrace)
1083 }
1084 case rightParen:
1085 if p.quote == subCmd {
1086 break loop
1087 }
1088 case bckQuote:
1089 if p.backquoteEnd() {
1090 break loop
1091 }
1092 case dblSemicolon, semiAnd, dblSemiAnd, semiOr:
1093 if p.quote == switchCase {
1094 break loop
1095 }
1096 p.curErr("%#q can only be used in a case clause", p.tok)
1097 }
1098 if !newLine && !gotEnd {
1099 p.curErr("statements must be separated by &, ; or a newline")
1100 }
1101 if p.tok == _EOF {
1102 break
1103 }
1104 p.openNodes++
1105 s := p.getStmt(true, false, false)
1106 p.openNodes--
1107 if s == nil {
1108 p.invalidStmtStart()
1109 break
1110 }
1111 gotEnd = s.Semicolon.IsValid()
1112 if !yield(s, p.err) {
1113 break
1114 }
1115 }
1116 }
1117
1118 func (p *Parser) stmtList(stops ...string) ([]*Stmt, []Comment) {
1119 var stmts []*Stmt
1120 var last []Comment
1121 fn := func(s *Stmt, err error) bool {
1122 stmts = append(stmts, s)
1123 return true
1124 }
1125 p.stmts(fn, stops...)
1126 split := len(p.accComs)
1127 if p.tok == _LitWord && (p.val == "elif" || p.val == "else" || p.val == "fi") {
1128 // Split the comments, so that any aligned with an opening token
1129 // get attached to it. For example:
1130 //
1131 // if foo; then
1132 // # inside the body
1133 // # document the else
1134 // else
1135 // fi
1136 // TODO(mvdan): look into deduplicating this with similar logic
1137 // in caseItems.
1138 for i, c := range slices.Backward(p.accComs) {
1139 if c.Pos().Col() != p.pos.Col() {
1140 break
1141 }
1142 split = i
1143 }
1144 }
1145 if split > 0 { // keep last nil if empty
1146 last = p.accComs[:split]
1147 }
1148 p.accComs = p.accComs[split:]
1149 return stmts, last
1150 }
1151
1152 func (p *Parser) invalidStmtStart() {
1153 switch p.tok {
1154 case semicolon, and, or, andAnd, orOr, andPipe, andBang:
1155 p.curErr("%#q can only immediately follow a statement", p.tok)
1156 case rightParen:
1157 p.curErr("%#q can only be used to close a subshell", p.tok)
1158 default:
1159 p.curErr("%#q is not a valid start for a statement", p.tok)
1160 }
1161 }
1162
1163 func (p *Parser) getWord() *Word {
1164 if w := p.wordAnyNumber(); len(w.Parts) > 0 && p.err == nil {
1165 return w
1166 }
1167 return nil
1168 }
1169
1170 func (p *Parser) getLit() *Lit {
1171 if p.tok.isLit() {
1172 l := p.lit(p.pos, p.val)
1173 p.next()
1174 return l
1175 }
1176 return nil
1177 }
1178
1179 func (p *Parser) wordParts(wps []WordPart) []WordPart {
1180 if p.quote == noState {
1181 p.quote = unquotedWordCont
1182 defer func() { p.quote = noState }()
1183 }
1184 for {
1185 p.openNodes++
1186 n := p.wordPart()
1187 p.openNodes--
1188 if n == nil {
1189 if len(wps) == 0 {
1190 return nil // normalize empty lists into nil
1191 }
1192 return wps
1193 }
1194 wps = append(wps, n)
1195 if p.spaced {
1196 return wps
1197 }
1198 }
1199 }
1200
1201 func (p *Parser) ensureNoNested(pos Pos) {
1202 if p.forbidNested {
1203 p.posErr(pos, "expansions not allowed in heredoc words")
1204 }
1205 }
1206
1207 func (p *Parser) wordPart() WordPart {
1208 switch p.tok {
1209 case _Lit, _LitWord, _LitRedir:
1210 l := p.lit(p.pos, p.val)
1211 p.next()
1212 return l
1213 case dollBrace:
1214 p.ensureNoNested(p.pos)
1215 switch p.r {
1216 case '|':
1217 p.checkLang(p.pos, langBashLike|LangMirBSDKorn, "`${|stmts;}`")
1218 fallthrough
1219 case ' ', '\t', '\n':
1220 p.checkLang(p.pos, langBashLike|LangMirBSDKorn, "`${ stmts;}`")
1221 cs := &CmdSubst{
1222 Left: p.pos,
1223 TempFile: p.r != '|',
1224 ReplyVar: p.r == '|',
1225 }
1226 old := p.preNested(subCmdBraces)
1227 p.rune() // don't tokenize '|'
1228 p.next()
1229 cs.Stmts, cs.Last = p.stmtList("}")
1230 p.postNested(old)
1231 pos, ok := p.gotRsrv("}")
1232 if !ok {
1233 p.matchingErr(cs.Left, dollBrace, rightBrace)
1234 }
1235 cs.Right = pos
1236 return cs
1237 default:
1238 return p.paramExp()
1239 }
1240 case dollDblParen, dollBrack:
1241 p.ensureNoNested(p.pos)
1242 left := p.tok
1243 ar := &ArithmExp{Left: p.pos, Bracket: left == dollBrack}
1244 old := p.preNested(arithmExpr)
1245 p.next()
1246 if p.got(hash) {
1247 p.checkLang(ar.Pos(), LangMirBSDKorn, "unsigned expressions")
1248 ar.Unsigned = true
1249 }
1250 ar.X = p.followArithm(left, ar.Left)
1251 if ar.Bracket {
1252 if p.tok != rightBrack {
1253 if p.recoverError() {
1254 ar.Right = recoveredPos
1255 return ar
1256 }
1257 p.arithmMatchingErr(ar.Left, dollBrack, rightBrack)
1258 }
1259 p.postNested(old)
1260 ar.Right = p.pos
1261 p.next()
1262 } else {
1263 ar.Right = p.arithmEnd(dollDblParen, ar.Left, old)
1264 }
1265 return ar
1266 case dollParen:
1267 p.ensureNoNested(p.pos)
1268 return p.cmdSubst()
1269 case dollar:
1270 pe := p.paramExp()
1271 if pe == nil { // was not actually a parameter expansion, like: "foo$"
1272 l := p.lit(p.pos, "$")
1273 p.next()
1274 return l
1275 }
1276 p.ensureNoNested(pe.Dollar)
1277 return pe
1278 case assgnParen:
1279 p.checkLang(p.pos, LangZsh, `%#q process substitutions`, p.tok)
1280 fallthrough
1281 case cmdIn, cmdOut:
1282 p.ensureNoNested(p.pos)
1283 ps := &ProcSubst{Op: ProcOperator(p.tok), OpPos: p.pos}
1284 old := p.preNested(subCmd)
1285 p.next()
1286 ps.Stmts, ps.Last = p.stmtList()
1287 p.postNested(old)
1288 ps.Rparen = p.matched(ps.OpPos, token(ps.Op), rightParen)
1289 return ps
1290 case sglQuote, dollSglQuote:
1291 sq := &SglQuoted{Left: p.pos, Dollar: p.tok == dollSglQuote}
1292 r := p.r
1293 for p.newLit(r); ; r = p.rune() {
1294 switch r {
1295 case '\\':
1296 if sq.Dollar {
1297 p.rune()
1298 }
1299 case '\'':
1300 sq.Right = p.nextPos()
1301 sq.Value = p.endLit()
1302
1303 p.rune()
1304 p.next()
1305 return sq
1306 case escNewl:
1307 p.litBs = append(p.litBs, '\\', '\n')
1308 case runeEOF:
1309 p.tok = _EOF
1310 if p.recoverError() {
1311 sq.Right = recoveredPos
1312 return sq
1313 }
1314 p.quoteErr(sq.Pos(), sglQuote)
1315 return nil
1316 }
1317 }
1318 case dblQuote, dollDblQuote:
1319 if p.quote == dblQuotes {
1320 // p.tok == dblQuote, as "foo$" puts $ in the lit
1321 return nil
1322 }
1323 return p.dblQuoted()
1324 case bckQuote:
1325 if p.backquoteEnd() {
1326 return nil
1327 }
1328 p.ensureNoNested(p.pos)
1329 cs := &CmdSubst{Left: p.pos, Backquotes: true}
1330 old := p.preNested(subCmdBckquo)
1331 p.openBquotes++
1332 if old.quote == dblQuotes {
1333 p.openBquoteDbls++
1334 }
1335
1336 // The lexer didn't call p.rune for us, so that it could have
1337 // the right p.openBquotes to properly handle backslashes.
1338 p.rune()
1339
1340 p.next()
1341 cs.Stmts, cs.Last = p.stmtList()
1342 if p.tok == bckQuote && p.lastBquoteEsc < p.openBquotes-1 {
1343 // e.g. found ` before the nested backquote \` was closed.
1344 p.tok = _EOF
1345 p.quoteErr(cs.Pos(), bckQuote)
1346 }
1347 p.postNested(old)
1348 p.openBquotes--
1349 if old.quote == dblQuotes {
1350 p.openBquoteDbls--
1351 }
1352 cs.Right = p.pos
1353
1354 // Like above, the lexer didn't call p.rune for us.
1355 p.rune()
1356 if !p.got(bckQuote) {
1357 if p.recoverError() {
1358 cs.Right = recoveredPos
1359 } else {
1360 p.quoteErr(cs.Pos(), bckQuote)
1361 }
1362 }
1363 return cs
1364 case leftParen:
1365 if p.lang.in(LangZsh) && p.r != ')' {
1366 // Zsh glob qualifier like *(N) or .(:a); the only case where
1367 // ( immediately after a word is not a glob qualifier is ()
1368 // for a function declaration, which the parser handles earlier.
1369 pos := p.pos
1370 p.pos = p.nextPos()
1371 for p.newLit(p.r); p.r != runeEOF && p.r != ')'; p.rune() {
1372 }
1373 if p.r != ')' {
1374 p.tok = _EOF // we can only get here due to EOF
1375 p.matchingErr(pos, leftParen, rightParen)
1376 }
1377 p.rune()
1378 p.val = p.endLit()
1379 l := p.lit(pos, "("+p.val)
1380 p.next()
1381 return l
1382 }
1383 return nil
1384 case globQuest, globStar, globPlus, globAt, globExcl:
1385 p.checkLang(p.pos, langBashLike|LangMirBSDKorn, "extended globs")
1386 eg := &ExtGlob{Op: GlobOperator(p.tok), OpPos: p.pos}
1387 lparens := 1
1388 r := p.r
1389 globLoop:
1390 for p.newLit(r); ; r = p.rune() {
1391 switch r {
1392 case runeEOF:
1393 break globLoop
1394 case '(':
1395 lparens++
1396 case ')':
1397 if lparens--; lparens == 0 {
1398 break globLoop
1399 }
1400 }
1401 }
1402 eg.Pattern = p.lit(posAddCol(eg.OpPos, 2), p.endLit())
1403 p.rune()
1404 p.next()
1405 if lparens != 0 {
1406 p.matchingErr(eg.OpPos, token(eg.Op), rightParen)
1407 }
1408 return eg
1409 default:
1410 return nil
1411 }
1412 }
1413
1414 func (p *Parser) cmdSubst() *CmdSubst {
1415 cs := &CmdSubst{Left: p.pos}
1416 old := p.preNested(subCmd)
1417 p.next()
1418 cs.Stmts, cs.Last = p.stmtList()
1419 p.postNested(old)
1420 cs.Right = p.matched(cs.Left, dollParen, rightParen)
1421 return cs
1422 }
1423
1424 func (p *Parser) dblQuoted() *DblQuoted {
1425 alloc := &struct {
1426 quoted DblQuoted
1427 parts [1]WordPart
1428 }{
1429 quoted: DblQuoted{Left: p.pos, Dollar: p.tok == dollDblQuote},
1430 }
1431 q := &alloc.quoted
1432 old := p.quote
1433 p.quote = dblQuotes
1434 p.next()
1435 q.Parts = p.wordParts(alloc.parts[:0])
1436 p.quote = old
1437 q.Right = p.pos
1438 if !p.got(dblQuote) {
1439 if p.recoverError() {
1440 q.Right = recoveredPos
1441 } else {
1442 p.quoteErr(q.Pos(), dblQuote)
1443 }
1444 }
1445 return q
1446 }
1447
1448 // paramExp parses a short or full parameter expansion, depending on whether
1449 // [Parser.tok] is [dollar] or [dollBrace]. It returns nil if a [dollar] token
1450 // does not form a valid parameter expansion, in which case it should be parsed
1451 // as a literal.
1452 func (p *Parser) paramExp() *ParamExp {
1453 old := p.quote
1454 p.quote = runeByRune
1455 // [ParamExp.Short] means we are parsing $exp rather than ${exp}.
1456 pe := &ParamExp{
1457 Dollar: p.pos,
1458 Short: p.tok == dollar,
1459 }
1460 if !pe.Short && p.r == '(' {
1461 p.checkLang(pe.Pos(), LangZsh, `parameter expansion flags`)
1462 // For now, for simplicity, we parse flags as just a literal.
1463 // In the future, parsing as a word is better for cases like
1464 // `${(ps.$sep.)val}`.
1465 lparen := p.nextPos()
1466 p.rune()
1467 p.pos = p.nextPos()
1468 for p.newLit(p.r); p.r != runeEOF && p.r != ')'; p.rune() {
1469 }
1470 p.val = p.endLit()
1471 if p.r != ')' {
1472 p.tok = _EOF // we can only get here due to EOF
1473 p.matchingErr(lparen, leftParen, rightParen)
1474 }
1475 pe.Flags = p.lit(p.pos, p.val)
1476 p.rune()
1477 }
1478 // Zsh-only prefixes that change how the parameter is expanded.
1479 // They may appear in any combination, like ${=^name}.
1480 // Doubling the rune (${==a}, ${~~a}, ${^^a}) forces the option off.
1481 zshPrefixLoop:
1482 for p.lang.in(LangZsh) {
1483 var field *OptState
1484 switch p.r {
1485 case '=':
1486 field = &pe.Split
1487 case '~':
1488 field = &pe.GlobSubst
1489 case '^':
1490 field = &pe.RcExpand
1491 default:
1492 break zshPrefixLoop
1493 }
1494 next, after := p.peekTwo()
1495 state := OptOn
1496 check := next
1497 if rune(next) == p.r {
1498 state = OptOff
1499 check = after
1500 }
1501 if check == utf8.RuneSelf || check == '}' {
1502 break zshPrefixLoop
1503 }
1504 // For the short form, only treat as a prefix if followed by something
1505 // that could start a parameter name or another zsh prefix.
1506 if pe.Short && check != '=' && check != '~' && check != '^' &&
1507 !singleRuneParam(check) && !paramNameRune(check) && check != '"' {
1508 break zshPrefixLoop
1509 }
1510 if state == OptOff {
1511 p.rune() // consume the first of the doubled pair
1512 }
1513 p.rune()
1514 *field = state
1515 }
1516 if !pe.Short || p.lang.in(LangZsh) {
1517 // Prefixes, like ${#name} to get the length of a variable.
1518 // Note that in Zsh, the short form like $#name is allowed too.
1519 switch p.r {
1520 case '#':
1521 if p.paramNameStart() {
1522 pe.Length = true
1523 }
1524 case '%':
1525 if p.paramNameStart() {
1526 p.checkLang(pe.Pos(), LangMirBSDKorn, "`${%%foo}`")
1527 pe.Width = true
1528 }
1529 case '!':
1530 // Unlike the others, zsh has no $!foo prefix.
1531 if !pe.Short && p.paramNameStart() {
1532 p.checkLang(pe.Pos(), langBashLike|LangMirBSDKorn, "`${!foo}`")
1533 pe.Excl = true
1534 }
1535 case '+':
1536 if p.paramNameStart() {
1537 p.checkLang(pe.Pos(), LangZsh, "`${+foo}`")
1538 pe.IsSet = true
1539 }
1540 }
1541 }
1542 if pe = p.paramExpParameter(pe); pe == nil {
1543 p.quote = old
1544 return nil // just "$"
1545 }
1546 // In short mode, any indexing or suffixes is not allowed, and we don't require '}'.
1547 // Zsh is an exception: $foo[1] and $foo[1,3] are valid. Note that $1[x] does not qualify.
1548 if pe.Short {
1549 if p.lang.in(LangZsh) && p.r == '[' && (len(p.val) != 1 || !positionalRuneParam(p.val[0])) {
1550 p.pos = p.nextPos()
1551 p.rune()
1552 pe.Index = p.eitherIndex()
1553 }
1554 p.quote = old
1555 p.next()
1556 return pe
1557 }
1558 // Index expressions like ${foo[1]}. Note that expansion suffixes can be combined,
1559 // like ${foo[@]//replace/with}.
1560 if p.r == '[' {
1561 p.checkLang(p.nextPos(), langBashLike|LangMirBSDKorn|LangZsh, "arrays")
1562 // In zsh some of these like ${@[-1]} or ${*[1,3]} work,
1563 // so we don't do this sort of check at all.
1564 if !p.lang.in(LangZsh) && pe.Param != nil && !ValidName(pe.Param.Value) {
1565 p.posErr(p.nextPos(), "cannot index a special parameter name")
1566 }
1567 p.pos = p.nextPos()
1568 p.rune()
1569 pe.Index = p.eitherIndex()
1570 }
1571 tokRune := p.r
1572 p.pos = p.nextPos()
1573 p.tok = p.paramToken(p.r)
1574 if p.tok == rightBrace {
1575 pe.Rbrace = p.pos
1576 p.quote = old
1577 p.next()
1578 return pe
1579 }
1580 if p.tok != _EOF && (pe.Length || pe.Width || pe.IsSet) {
1581 p.curErr("cannot combine multiple parameter expansion operators")
1582 }
1583 switch p.tok {
1584 case slash, dblSlash: // pattern search and replace
1585 p.checkLang(p.pos, langBashLike|LangMirBSDKorn|LangZsh, "search and replace")
1586 pe.Repl = &Replace{All: p.tok == dblSlash}
1587 p.quote = paramExpRepl
1588 p.next()
1589 pe.Repl.Orig = p.getWord()
1590 p.quote = paramExpExp
1591 if p.got(slash) {
1592 pe.Repl.With = p.getWord()
1593 }
1594 case colon: // slicing
1595 if p.lang.in(LangZsh) && (p.r == '&' || asciiLetter(p.r)) {
1596 pos := p.pos
1597 loop:
1598 for p.newLit(p.r); ; p.rune() {
1599 switch p.r {
1600 case runeEOF:
1601 p.tok = _EOF
1602 p.matchingErr(pe.Dollar, dollBrace, rightBrace)
1603 break loop
1604 case '}':
1605 pe.Modifiers = append(pe.Modifiers, p.lit(pos, p.endLit()))
1606 pe.Rbrace = p.nextPos()
1607 p.rune()
1608 break loop
1609 case ':':
1610 pe.Modifiers = append(pe.Modifiers, p.lit(pos, p.endLit()))
1611 p.rune()
1612 pos = p.nextPos()
1613 p.newLit(p.r)
1614 }
1615 }
1616 p.quote = old
1617 p.next()
1618 return pe
1619 }
1620 p.checkLang(p.pos, langBashLike|LangMirBSDKorn|LangZsh, "slicing")
1621 pe.Slice = &Slice{}
1622 colonPos := p.pos
1623 p.quote = paramExpSlice
1624 if p.next(); p.tok != colon {
1625 pe.Slice.Offset = p.followArithm(colon, colonPos)
1626 }
1627 colonPos = p.pos
1628 if p.got(colon) {
1629 pe.Slice.Length = p.followArithm(colon, colonPos)
1630 }
1631 // Need to use a different matched style so arithm errors
1632 // get reported correctly
1633 p.quote = old
1634 pe.Rbrace = p.pos
1635 p.matchedArithm(pe.Dollar, dollBrace, rightBrace)
1636 return pe
1637 case caret, dblCaret, comma, dblComma: // upper/lower case
1638 p.checkLang(p.pos, langBashLike, "this expansion operator")
1639 pe.Exp = p.paramExpExp()
1640 case at, star:
1641 switch {
1642 case p.tok == star && !pe.Excl:
1643 p.curErr("not a valid parameter expansion operator: %#q", p.tok)
1644 case pe.Excl && p.r == '}':
1645 p.checkLang(pe.Pos(), langBashLike, "`${!foo%s}`", p.tok)
1646 pe.Names = ParNamesOperator(p.tok)
1647 p.next()
1648 case p.tok == at:
1649 p.checkLang(p.pos, langBashLike|LangMirBSDKorn, "this expansion operator")
1650 fallthrough
1651 default:
1652 pe.Exp = p.paramExpExp()
1653 }
1654 case plus, colPlus, minus, colMinus, quest, colQuest, assgn, colAssgn,
1655 perc, dblPerc, hash, dblHash, colHash, colPipe, colStar:
1656 pe.Exp = p.paramExpExp()
1657 case _EOF:
1658 default:
1659 if paramNameRune(tokRune) {
1660 if pe.Param != nil {
1661 p.curErr("%#q cannot be followed by a word", pe.Param.Value)
1662 } else {
1663 p.curErr("nested parameter expansion cannot be followed by a word")
1664 }
1665 } else {
1666 p.curErr("not a valid parameter expansion operator: %#q", string(tokRune))
1667 }
1668 }
1669 if p.tok != _EOF && p.tok != rightBrace {
1670 p.tok = p.paramToken(p.r)
1671 }
1672 p.quote = old
1673 pe.Rbrace = p.matched(pe.Dollar, dollBrace, rightBrace)
1674 return pe
1675 }
1676
1677 func (p *Parser) paramNameStart() bool {
1678 r := p.peek()
1679 if r == utf8.RuneSelf || singleRuneParam(r) || paramNameRune(r) || r == '"' {
1680 p.rune()
1681 return true
1682 }
1683 return false
1684 }
1685
1686 func (p *Parser) nestedParameterStart(pe *ParamExp) (left token, quotePos Pos) {
1687 if pe.Short {
1688 return illegalTok, Pos{}
1689 }
1690 if p.r == '"' {
1691 quotePos = p.nextPos()
1692 p.rune()
1693 }
1694 if p.r != '$' {
1695 if quotePos.IsValid() {
1696 return dollar, quotePos
1697 }
1698 return illegalTok, Pos{}
1699 }
1700 switch p1 := p.peek(); p1 {
1701 case '{', '(':
1702 p.pos = p.nextPos()
1703 p.checkLang(p.pos, LangZsh, "nested parameter expansions")
1704 if p.err != nil {
1705 return illegalTok, Pos{} // xxx given that we overwrite p.tok below
1706 }
1707 p.rune()
1708 p.rune()
1709 if p1 == '{' {
1710 left = dollBrace
1711 } else { // '('
1712 left = dollParen
1713 }
1714 }
1715 return left, quotePos
1716 }
1717
1718 func (p *Parser) paramExpParameter(pe *ParamExp) *ParamExp {
1719 // Check for Zsh nested parameter expressions like ${(f)"$(foo)"}.
1720 if left, quotePos := p.nestedParameterStart(pe); left != illegalTok {
1721 var wp WordPart
1722 switch p.tok = left; p.tok {
1723 case dollBrace: // ${#${nested parameter}}
1724 p.tok = dollBrace
1725 wp = p.paramExp()
1726 case dollParen: // ${#$(nested command)}
1727 wp = p.cmdSubst()
1728 default: // dollar
1729 p.posErr(pe.Pos(), "invalid nested parameter expansion")
1730 }
1731 if quotePos.IsValid() {
1732 if p.r != '"' {
1733 p.tok = p.paramToken(p.r)
1734 if p.tok == illegalTok {
1735 p.posErr(pe.Pos(), "invalid nested parameter expansion")
1736 } else {
1737 p.quoteErr(quotePos, dblQuote)
1738 }
1739 }
1740 pe.NestedParam = &DblQuoted{
1741 Left: quotePos,
1742 Right: p.nextPos(),
1743 Parts: []WordPart{wp},
1744 }
1745 p.rune()
1746 } else {
1747 pe.NestedParam = wp
1748 }
1749 return pe
1750 }
1751 // The parameter name itself, like $foo or $?.
1752 switch p.r {
1753 case '?', '-':
1754 if pe.Length && p.peek() != '}' {
1755 // actually ${#-default}, not ${#-}; fix the ambiguity
1756 pe.Length = false
1757 pos := p.nextPos()
1758 pe.Param = p.lit(posAddCol(pos, -1), "#")
1759 pe.Param.ValueEnd = pos
1760 break
1761 }
1762 fallthrough
1763 case '@', '*', '#', '!', '$':
1764 r, pos := p.r, p.nextPos()
1765 p.rune()
1766 pe.Param = p.lit(pos, string(r))
1767 default:
1768 // Note that $1a is equivalent to ${1}a, but ${1a} is not.
1769 // POSIX Shell says the latter is unspecified behavior, so match Bash's behavior.
1770 pos := p.nextPos()
1771 if pe.Short && singleRuneParam(p.r) {
1772 p.val = string(p.r)
1773 p.rune()
1774 } else {
1775 for p.newLit(p.r); p.r != runeEOF; p.rune() {
1776 if !paramNameRune(p.r) && p.r != escNewl {
1777 break
1778 }
1779 }
1780 p.val = p.endLit()
1781 if !numberLiteral(p.val) && !ValidName(p.val) {
1782 if pe.Short {
1783 return nil // just "$"
1784 }
1785 if p.lang.in(LangZsh) && p.val == "" {
1786 // Zsh allows omitting the parameter name, e.g. ${:-word}.
1787 return pe
1788 }
1789 p.posErr(pos, "invalid parameter name")
1790 }
1791 }
1792 pe.Param = p.lit(pos, p.val)
1793 }
1794 return pe
1795 }
1796
1797 func (p *Parser) paramExpExp() *Expansion {
1798 op := ParExpOperator(p.tok)
1799 switch op {
1800 case MatchEmpty, ArrayExclude, ArrayIntersect:
1801 p.checkLang(p.pos, LangZsh, "${name%sarg}", op)
1802 }
1803 p.quote = paramExpExp
1804 p.next()
1805 if op == OtherParamOps {
1806 if !p.tok.isLit() {
1807 p.curErr("@ expansion operator requires a literal")
1808 }
1809 switch p.val {
1810 case "a", "k", "u", "A", "E", "K", "L", "P", "U":
1811 p.checkLang(p.pos, langBashLike, "this expansion operator")
1812 case "#":
1813 p.checkLang(p.pos, LangMirBSDKorn, "this expansion operator")
1814 case "Q":
1815 default:
1816 p.curErr("invalid @ expansion operator %#q", p.val)
1817 }
1818 }
1819 return &Expansion{Op: op, Word: p.getWord()}
1820 }
1821
1822 func (p *Parser) eitherIndex() ArithmExpr {
1823 old := p.quote
1824 lpos := p.pos
1825 p.quote = paramExpArithm
1826 p.next()
1827 if p.tok == star || p.tok == at {
1828 p.tok, p.val = _LitWord, p.tok.String()
1829 }
1830 expr := p.followArithm(leftBrack, lpos)
1831 p.quote = old
1832 p.matchedArithm(lpos, leftBrack, rightBrack)
1833 return expr
1834 }
1835
1836 func (p *Parser) zshSubFlags() *FlagsArithm {
1837 zf := &FlagsArithm{}
1838 // Lex flags as raw text, like paramExp does for ${(flags)...}.
1839 lparen := p.pos
1840 old := p.quote
1841 p.quote = runeByRune
1842 p.pos = p.nextPos()
1843 for p.newLit(p.r); p.r != runeEOF && p.r != ')'; p.rune() {
1844 }
1845 p.val = p.endLit()
1846 if p.r != ')' {
1847 p.tok = _EOF
1848 p.matchingErr(lparen, leftParen, rightParen)
1849 }
1850 zf.Flags = p.lit(p.pos, p.val)
1851 p.rune()
1852 // Lex the argument as a raw pattern, stopping at ',' or ']',
1853 // since zsh treats it as a pattern rather than an arithmetic expression.
1854 argPos := p.nextPos()
1855 for p.newLit(p.r); p.r != runeEOF && p.r != ',' && p.r != ']'; p.rune() {
1856 }
1857 if val := p.endLit(); val != "" {
1858 zf.X = p.wordOne(p.lit(argPos, val))
1859 }
1860 p.quote = old
1861 p.next()
1862 return zf
1863 }
1864
1865 func (p *Parser) stopToken() bool {
1866 switch p.tok {
1867 case _EOF, _Newl, semicolon, and, or, andAnd, orOr, orAnd, andPipe, andBang,
1868 dblSemicolon, semiAnd, dblSemiAnd, semiOr, rightParen:
1869 return true
1870 case bckQuote:
1871 return p.backquoteEnd()
1872 }
1873 return false
1874 }
1875
1876 func (p *Parser) backquoteEnd() bool {
1877 return p.lastBquoteEsc < p.openBquotes
1878 }
1879
1880 // ValidName returns whether val is a valid name as per the POSIX spec.
1881 func ValidName(val string) bool {
1882 if val == "" {
1883 return false
1884 }
1885 for i, r := range val {
1886 switch {
1887 case asciiLetter(r), r == '_':
1888 case i > 0 && asciiDigit(r):
1889 default:
1890 return false
1891 }
1892 }
1893 return true
1894 }
1895
1896 func numberLiteral[T string | []byte](val T) bool {
1897 if len(val) == 0 {
1898 return false
1899 }
1900 for _, r := range string(val) {
1901 if !asciiDigit(r) {
1902 return false
1903 }
1904 }
1905 return true
1906 }
1907
1908 func (p *Parser) hasValidIdent() bool {
1909 if !p.tok.isLit() {
1910 return false
1911 }
1912 if end := p.eqlOffs; end > 0 {
1913 if p.val[end-1] == '+' && p.lang.in(langBashLike|LangMirBSDKorn|LangZsh) {
1914 end-- // a+=x
1915 }
1916 if ValidName(p.val[:end]) {
1917 return true
1918 }
1919 } else if !ValidName(p.val) {
1920 return false // *[i]=x
1921 }
1922 return p.r == '[' // a[i]=x
1923 }
1924
1925 func (p *Parser) getAssign(needEqual bool) *Assign {
1926 as := &Assign{}
1927 if p.eqlOffs > 0 { // foo=bar
1928 nameEnd := p.eqlOffs
1929 if p.lang.in(langBashLike|LangMirBSDKorn|LangZsh) && p.val[p.eqlOffs-1] == '+' {
1930 // a+=b
1931 as.Append = true
1932 nameEnd--
1933 }
1934 as.Name = p.lit(p.pos, p.val[:nameEnd])
1935 // since we're not using the entire p.val
1936 as.Name.ValueEnd = posAddCol(as.Name.ValuePos, nameEnd)
1937 left := p.lit(posAddCol(p.pos, 1), p.val[p.eqlOffs+1:])
1938 if left.Value != "" {
1939 left.ValuePos = posAddCol(left.ValuePos, p.eqlOffs)
1940 as.Value = p.wordOne(left)
1941 }
1942 p.next()
1943 } else { // foo[x]=bar
1944 as.Name = p.lit(p.pos, p.val)
1945 // hasValidIdent already checks p.r is '['
1946 p.rune()
1947 p.pos = posAddCol(p.pos, 1)
1948 as.Index = p.eitherIndex()
1949 if p.spaced || p.stopToken() {
1950 if needEqual {
1951 p.followErr(as.Pos(), "a[b]", assgn)
1952 } else {
1953 as.Naked = true
1954 return as
1955 }
1956 }
1957 if p.tok == assgnParen {
1958 if !p.lang.in(LangZsh) {
1959 p.curErr("arrays cannot be nested")
1960 return nil
1961 }
1962 // zsh allows a[i]=(values...).
1963 // assgnParen consumed both '=' and '(',
1964 // so rewrite as leftParen for array parsing below.
1965 p.tok = leftParen
1966 p.pos = posAddCol(p.pos, 1)
1967 } else {
1968 if len(p.val) > 0 && p.val[0] == '+' {
1969 as.Append = true
1970 p.val = p.val[1:]
1971 p.pos = posAddCol(p.pos, 1)
1972 }
1973 if len(p.val) < 1 || p.val[0] != '=' {
1974 if as.Append {
1975 p.followErr(as.Pos(), "a[b]+", assgn)
1976 } else {
1977 p.followErr(as.Pos(), "a[b]", assgn)
1978 }
1979 return nil
1980 }
1981 p.pos = posAddCol(p.pos, 1)
1982 p.val = p.val[1:]
1983 if p.val == "" {
1984 p.next()
1985 }
1986 }
1987 }
1988 if p.spaced || p.stopToken() {
1989 return as
1990 }
1991 if as.Value == nil && p.tok == leftParen {
1992 p.checkLang(p.pos, langBashLike|LangMirBSDKorn|LangZsh, "arrays")
1993 as.Array = &ArrayExpr{Lparen: p.pos}
1994 newQuote := p.quote
1995 if p.lang.in(langBashLike | LangZsh) {
1996 newQuote = arrayElems
1997 }
1998 old := p.preNested(newQuote)
1999 p.next()
2000 p.got(_Newl)
2001 for p.tok != _EOF && p.tok != rightParen {
2002 ae := &ArrayElem{}
2003 ae.Comments, p.accComs = p.accComs, nil
2004 if p.tok == leftBrack {
2005 left := p.pos
2006 ae.Index = p.eitherIndex()
2007 if p.tok == assgnParen {
2008 p.curErr("arrays cannot be nested")
2009 return nil
2010 }
2011 p.follow(left, `[x]`, assgn)
2012 }
2013 if ae.Value = p.getWord(); ae.Value == nil {
2014 switch p.tok {
2015 case _Newl, rightParen, leftBrack:
2016 // TODO: support [index]=[
2017 default:
2018 p.curErr("array element values must be words")
2019 return nil
2020 }
2021 }
2022 if len(p.accComs) > 0 {
2023 c := p.accComs[0]
2024 if c.Pos().Line() == ae.End().Line() {
2025 ae.Comments = append(ae.Comments, c)
2026 p.accComs = p.accComs[1:]
2027 }
2028 }
2029 as.Array.Elems = append(as.Array.Elems, ae)
2030 p.got(_Newl)
2031 }
2032 as.Array.Last, p.accComs = p.accComs, nil
2033 p.postNested(old)
2034 as.Array.Rparen = p.matched(as.Array.Lparen, leftParen, rightParen)
2035 } else if w := p.getWord(); w != nil {
2036 if as.Value == nil {
2037 as.Value = w
2038 } else {
2039 as.Value.Parts = append(as.Value.Parts, w.Parts...)
2040 }
2041 }
2042 return as
2043 }
2044
2045 func (p *Parser) peekRedir() bool {
2046 switch p.tok {
2047 case _LitRedir, rdrOut, appOut, rdrIn, rdrInOut, dplIn, dplOut,
2048 rdrClob, appClob, hdoc, dashHdoc, wordHdoc,
2049 rdrAll, rdrAllClob, appAll, appAllClob:
2050 return true
2051 }
2052 return false
2053 }
2054
2055 func (p *Parser) doRedirect(s *Stmt) {
2056 var r *Redirect
2057 if s.Redirs == nil {
2058 var alloc struct {
2059 redirs [4]*Redirect
2060 redir Redirect
2061 }
2062 s.Redirs = alloc.redirs[:0]
2063 r = &alloc.redir
2064 s.Redirs = append(s.Redirs, r)
2065 } else {
2066 r = &Redirect{}
2067 s.Redirs = append(s.Redirs, r)
2068 }
2069 r.N = p.getLit()
2070 if r.N != nil && r.N.Value[0] == '{' {
2071 p.checkLang(r.N.Pos(), langBashLike|LangZsh, "`{varname}` redirects")
2072 }
2073 r.Op, r.OpPos = RedirOperator(p.tok), p.pos
2074 switch r.Op {
2075 case RdrAll, AppAll:
2076 p.checkLang(p.pos, langBashLike|LangMirBSDKorn|LangZsh, "%#q redirects", r.Op)
2077 case AppClob, RdrAllClob, AppAllClob:
2078 p.checkLang(p.pos, LangZsh, "%#q redirects", r.Op)
2079 }
2080 p.next()
2081 switch r.Op {
2082 case Hdoc, DashHdoc:
2083 old := p.quote
2084 p.quote, p.forbidNested = hdocWord, true
2085 p.heredocs = append(p.heredocs, r)
2086 r.Word = p.followWordTok(token(r.Op), r.OpPos)
2087 p.quote, p.forbidNested = old, false
2088 if p.tok == _Newl {
2089 if len(p.accComs) > 0 {
2090 c := p.accComs[0]
2091 if c.Pos().Line() == s.End().Line() {
2092 s.Comments = append(s.Comments, c)
2093 p.accComs = p.accComs[1:]
2094 }
2095 }
2096 p.doHeredocs()
2097 }
2098 case WordHdoc:
2099 p.checkLang(r.OpPos, langBashLike|LangMirBSDKorn|LangZsh, "herestrings")
2100 fallthrough
2101 default:
2102 r.Word = p.followWordTok(token(r.Op), r.OpPos)
2103 }
2104 }
2105
2106 func (p *Parser) getStmt(readEnd, binCmd, fnBody bool) *Stmt {
2107 pos, ok := p.gotRsrv("!")
2108 s := &Stmt{Position: pos}
2109 if ok {
2110 s.Negated = true
2111 if p.stopToken() {
2112 p.posErr(s.Pos(), `%#q cannot form a statement alone`, exclMark)
2113 }
2114 if _, ok := p.gotRsrv("!"); ok {
2115 p.posErr(s.Pos(), `cannot negate a command multiple times`)
2116 }
2117 }
2118 if s = p.gotStmtPipe(s, false); s == nil || p.err != nil {
2119 return nil
2120 }
2121 // instead of using recursion, iterate manually
2122 for p.tok == andAnd || p.tok == orOr {
2123 if binCmd {
2124 // left associativity: in a list of BinaryCmds, the
2125 // right recursion should only read a single element
2126 return s
2127 }
2128 b := &BinaryCmd{
2129 OpPos: p.pos,
2130 Op: BinCmdOperator(p.tok),
2131 X: s,
2132 }
2133 p.next()
2134 p.got(_Newl)
2135 b.Y = p.getStmt(false, true, false)
2136 if b.Y == nil || p.err != nil {
2137 if p.recoverError() {
2138 b.Y = &Stmt{Position: recoveredPos}
2139 } else {
2140 p.followErr(b.OpPos, b.Op, noQuote("a statement"))
2141 return nil
2142 }
2143 }
2144 s = &Stmt{Position: s.Position}
2145 s.Cmd = b
2146 s.Comments, b.X.Comments = b.X.Comments, nil
2147 }
2148 if readEnd {
2149 switch p.tok {
2150 case semicolon:
2151 s.Semicolon = p.pos
2152 p.next()
2153 case and:
2154 s.Semicolon = p.pos
2155 p.next()
2156 s.Background = true
2157 case orAnd:
2158 s.Semicolon = p.pos
2159 p.next()
2160 s.Coprocess = true
2161 case andPipe, andBang:
2162 s.Semicolon = p.pos
2163 p.next()
2164 s.Disown = true
2165 }
2166 }
2167 if len(p.accComs) > 0 && !binCmd && !fnBody {
2168 c := p.accComs[0]
2169 if c.Pos().Line() == s.End().Line() {
2170 s.Comments = append(s.Comments, c)
2171 p.accComs = p.accComs[1:]
2172 }
2173 }
2174 return s
2175 }
2176
2177 func (p *Parser) gotStmtPipe(s *Stmt, binCmd bool) *Stmt {
2178 s.Comments, p.accComs = p.accComs, nil
2179 for p.peekRedir() {
2180 p.doRedirect(s)
2181 }
2182 redirsStart := len(s.Redirs)
2183 switch p.tok {
2184 case _LitWord:
2185 switch p.val {
2186 case "{":
2187 p.block(s)
2188 case "{}":
2189 // Zsh treats closing braces in a special way, allowing this.
2190 if p.lang.in(LangZsh) {
2191 s.Cmd = &Block{Lbrace: p.pos, Rbrace: posAddCol(p.pos, 1)}
2192 p.next()
2193 }
2194 case "if":
2195 p.ifClause(s)
2196 case "while", "until":
2197 // TODO(zsh): "repeat"
2198 p.whileClause(s, p.val == "until")
2199 case "for":
2200 p.forClause(s)
2201 case "case":
2202 p.caseClause(s)
2203 // TODO(zsh): { try-list } "always" { always-list }
2204 case "}":
2205 p.curErr(`%#q can only be used to close a block`, rightBrace)
2206 case "then", "elif":
2207 p.curErr("%#q can only be used in an `if`", p.val)
2208 case "fi":
2209 p.curErr("%#q can only be used to end an `if`", p.val)
2210 case "do":
2211 p.curErr(`%#q can only be used in a loop`, p.val)
2212 case "done":
2213 p.curErr(`%#q can only be used to end a loop`, p.val)
2214 case "esac":
2215 p.curErr("%#q can only be used to end a `case`", p.val)
2216 case "!":
2217 if !s.Negated {
2218 p.curErr(`%#q can only be used in full statements`, exclMark)
2219 break
2220 }
2221 case "[[":
2222 if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
2223 p.testClause(s)
2224 }
2225 case "]]":
2226 if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
2227 p.curErr(`%#q can only be used to close a test`, dblRightBrack)
2228 }
2229 case "let":
2230 if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
2231 p.letClause(s)
2232 }
2233 case "function":
2234 if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
2235 p.bashFuncDecl(s)
2236 }
2237 case "declare":
2238 if p.lang.in(langBashLike | LangZsh) { // Note that mksh lacks this one.
2239 p.declClause(s)
2240 }
2241 case "local", "export", "readonly", "typeset", "nameref":
2242 if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
2243 p.declClause(s)
2244 }
2245 case "time":
2246 if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
2247 p.timeClause(s)
2248 }
2249 case "coproc":
2250 if p.lang.in(langBashLike) { // Note that mksh lacks this one.
2251 p.coprocClause(s)
2252 }
2253 case "select":
2254 if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
2255 p.selectClause(s)
2256 }
2257 case "@test":
2258 if p.lang.in(LangBats) {
2259 p.testDecl(s)
2260 }
2261 }
2262 if s.Cmd != nil {
2263 break
2264 }
2265 if p.hasValidIdent() {
2266 p.callExpr(s, nil, true)
2267 break
2268 }
2269 name := p.lit(p.pos, p.val)
2270 p.next()
2271 // In zsh, ( after a word is a glob qualifier unless followed
2272 // immediately by ), which is the func declaration syntax.
2273 if p.tok == leftParen && (!p.lang.in(LangZsh) || p.r == ')') {
2274 p.next()
2275 p.follow(name.ValuePos, "foo(", rightParen)
2276 if p.lang.in(LangPOSIX) && !ValidName(name.Value) {
2277 p.posErr(name.Pos(), "invalid func name")
2278 }
2279 p.funcDecl(s, name.ValuePos, false, true, name)
2280 } else {
2281 w := p.wordOne(name)
2282 if p.lang.in(LangZsh) && !p.spaced {
2283 w.Parts = append(w.Parts, p.wordParts(nil)...)
2284 }
2285 p.callExpr(s, w, false)
2286 }
2287 case bckQuote:
2288 if p.backquoteEnd() {
2289 break
2290 }
2291 fallthrough
2292 case _Lit, dollBrace, dollDblParen, dollParen, dollar, cmdIn, assgnParen, cmdOut,
2293 sglQuote, dollSglQuote, dblQuote, dollDblQuote, dollBrack,
2294 globQuest, globStar, globPlus, globAt, globExcl:
2295 if p.hasValidIdent() {
2296 p.callExpr(s, nil, true)
2297 break
2298 }
2299 w := p.wordAnyNumber()
2300 if p.got(leftParen) {
2301 p.posErr(w.Pos(), "invalid func name")
2302 }
2303 p.callExpr(s, w, false)
2304 case leftParen:
2305 if p.r == ')' {
2306 p.rune()
2307 fpos := p.pos
2308 p.next()
2309 if p.tok == _LitWord && p.val == "{" {
2310 p.checkLang(fpos, LangZsh, "anonymous functions")
2311 }
2312 p.funcDecl(s, fpos, false, true)
2313 break
2314 }
2315 p.subshell(s)
2316 case dblLeftParen:
2317 p.arithmExpCmd(s)
2318 }
2319 if s.Cmd == nil && len(s.Redirs) == 0 {
2320 return nil // no statement found
2321 }
2322 if redirsStart > 0 && s.Cmd != nil {
2323 if _, ok := s.Cmd.(*CallExpr); !ok {
2324 p.checkLang(s.Pos(), LangZsh, "redirects before compound commands")
2325 }
2326 }
2327 for p.peekRedir() {
2328 p.doRedirect(s)
2329 }
2330 // instead of using recursion, iterate manually
2331 for p.tok == or || p.tok == orAnd {
2332 if binCmd {
2333 // left associativity: in a list of BinaryCmds, the
2334 // right recursion should only read a single element
2335 return s
2336 }
2337 if p.tok == orAnd && p.lang.in(LangMirBSDKorn) {
2338 // No need to check for LangPOSIX, as on that language
2339 // we parse |& as two tokens.
2340 break
2341 }
2342 b := &BinaryCmd{OpPos: p.pos, Op: BinCmdOperator(p.tok), X: s}
2343 p.next()
2344 p.got(_Newl)
2345 if b.Y = p.gotStmtPipe(&Stmt{Position: p.pos}, true); b.Y == nil || p.err != nil {
2346 if p.recoverError() {
2347 b.Y = &Stmt{Position: recoveredPos}
2348 } else {
2349 p.followErr(b.OpPos, b.Op, noQuote("a statement"))
2350 break
2351 }
2352 }
2353 s = &Stmt{Position: s.Position}
2354 s.Cmd = b
2355 s.Comments, b.X.Comments = b.X.Comments, nil
2356 // in "! x | y", the bang applies to the entire pipeline
2357 s.Negated = b.X.Negated
2358 b.X.Negated = false
2359 }
2360 return s
2361 }
2362
2363 func (p *Parser) subshell(s *Stmt) {
2364 sub := &Subshell{Lparen: p.pos}
2365 old := p.preNested(subCmd)
2366 p.next()
2367 sub.Stmts, sub.Last = p.followStmts("(", sub.Lparen)
2368 p.postNested(old)
2369 sub.Rparen = p.matched(sub.Lparen, leftParen, rightParen)
2370 s.Cmd = sub
2371 }
2372
2373 func (p *Parser) arithmExpCmd(s *Stmt) {
2374 ar := &ArithmCmd{Left: p.pos}
2375 old := p.preNested(arithmExprCmd)
2376 p.next()
2377 if p.got(hash) {
2378 p.checkLang(ar.Pos(), LangMirBSDKorn, "unsigned expressions")
2379 ar.Unsigned = true
2380 }
2381 ar.X = p.followArithm(dblLeftParen, ar.Left)
2382 ar.Right = p.arithmEnd(dblLeftParen, ar.Left, old)
2383 s.Cmd = ar
2384 }
2385
2386 func (p *Parser) block(s *Stmt) {
2387 b := &Block{Lbrace: p.pos}
2388 p.next()
2389 b.Stmts, b.Last = p.followStmts("{", b.Lbrace, "}")
2390 if pos, ok := p.gotRsrv("}"); ok {
2391 b.Rbrace = pos
2392 } else if p.recoverError() {
2393 b.Rbrace = recoveredPos
2394 } else {
2395 p.matchingErr(b.Lbrace, leftBrace, rightBrace)
2396 }
2397 s.Cmd = b
2398 }
2399
2400 func (p *Parser) ifClause(s *Stmt) {
2401 rootIf := &IfClause{Position: p.pos}
2402 p.next()
2403 rootIf.Cond, rootIf.CondLast = p.followStmts("if", rootIf.Position, "then")
2404 rootIf.ThenPos = p.followRsrv(rootIf.Position, "if <cond>", "then")
2405 rootIf.Then, rootIf.ThenLast = p.followStmts("then", rootIf.ThenPos, "fi", "elif", "else")
2406 curIf := rootIf
2407 for p.tok == _LitWord && p.val == "elif" {
2408 elf := &IfClause{Position: p.pos}
2409 curIf.Last = p.accComs
2410 p.accComs = nil
2411 p.next()
2412 elf.Cond, elf.CondLast = p.followStmts("elif", elf.Position, "then")
2413 elf.ThenPos = p.followRsrv(elf.Position, "elif <cond>", "then")
2414 elf.Then, elf.ThenLast = p.followStmts("then", elf.ThenPos, "fi", "elif", "else")
2415 curIf.Else = elf
2416 curIf = elf
2417 }
2418 if elsePos, ok := p.gotRsrv("else"); ok {
2419 curIf.Last = p.accComs
2420 p.accComs = nil
2421 els := &IfClause{Position: elsePos}
2422 els.Then, els.ThenLast = p.followStmts("else", els.Position, "fi")
2423 curIf.Else = els
2424 curIf = els
2425 }
2426 curIf.Last = p.accComs
2427 p.accComs = nil
2428 rootIf.FiPos = p.stmtEnd(rootIf, "if", "fi")
2429 for els := rootIf.Else; els != nil; els = els.Else {
2430 // All the nested IfClauses share the same FiPos.
2431 els.FiPos = rootIf.FiPos
2432 }
2433 s.Cmd = rootIf
2434 }
2435
2436 func (p *Parser) whileClause(s *Stmt, until bool) {
2437 wc := &WhileClause{WhilePos: p.pos, Until: until}
2438 rsrv := "while"
2439 rsrvCond := "while <cond>"
2440 if wc.Until {
2441 rsrv = "until"
2442 rsrvCond = "until <cond>"
2443 }
2444 p.next()
2445 wc.Cond, wc.CondLast = p.followStmts(rsrv, wc.WhilePos, "do")
2446 wc.DoPos = p.followRsrv(wc.WhilePos, rsrvCond, "do")
2447 wc.Do, wc.DoLast = p.followStmts("do", wc.DoPos, "done")
2448 wc.DonePos = p.stmtEnd(wc, rsrv, "done")
2449 s.Cmd = wc
2450 }
2451
2452 func (p *Parser) forClause(s *Stmt) {
2453 fc := &ForClause{ForPos: p.pos}
2454 p.next()
2455 fc.Loop = p.loop(fc.ForPos)
2456
2457 start, end := "do", "done"
2458 if pos, ok := p.gotRsrv("{"); ok {
2459 p.checkLang(pos, langBashLike|LangMirBSDKorn, "for loops with braces")
2460 fc.DoPos = pos
2461 fc.Braces = true
2462 start, end = "{", "}"
2463 } else {
2464 fc.DoPos = p.followRsrv(fc.ForPos, "for foo [in words]", start)
2465 }
2466
2467 s.Comments = append(s.Comments, p.accComs...)
2468 p.accComs = nil
2469 fc.Do, fc.DoLast = p.followStmts(start, fc.DoPos, end)
2470 fc.DonePos = p.stmtEnd(fc, "for", end)
2471 s.Cmd = fc
2472 }
2473
2474 func (p *Parser) loop(fpos Pos) Loop {
2475 switch p.tok {
2476 case leftParen, dblLeftParen:
2477 p.checkLang(p.pos, langBashLike|LangZsh, "c-style fors")
2478 }
2479 if p.tok == dblLeftParen {
2480 cl := &CStyleLoop{Lparen: p.pos}
2481 old := p.preNested(arithmExprCmd)
2482 p.next()
2483 cl.Init = p.arithmExpr(false)
2484 if !p.got(dblSemicolon) {
2485 p.follow(p.pos, "expr", semicolon)
2486 cl.Cond = p.arithmExpr(false)
2487 p.follow(p.pos, "expr", semicolon)
2488 }
2489 cl.Post = p.arithmExpr(false)
2490 cl.Rparen = p.arithmEnd(dblLeftParen, cl.Lparen, old)
2491 p.got(semicolon)
2492 p.got(_Newl)
2493 return cl
2494 }
2495 return p.wordIter("for", fpos)
2496 }
2497
2498 func (p *Parser) wordIter(ftok string, fpos Pos) *WordIter {
2499 wi := &WordIter{}
2500 if wi.Name = p.getLit(); wi.Name == nil {
2501 p.followErr(fpos, ftok, noQuote("a literal"))
2502 }
2503 if p.got(semicolon) {
2504 p.got(_Newl)
2505 return wi
2506 }
2507 p.got(_Newl)
2508 if pos, ok := p.gotRsrv("in"); ok {
2509 wi.InPos = pos
2510 for !p.stopToken() {
2511 if w := p.getWord(); w == nil {
2512 p.curErr("word list can only contain words")
2513 } else {
2514 wi.Items = append(wi.Items, w)
2515 }
2516 }
2517 p.got(semicolon)
2518 p.got(_Newl)
2519 } else if p.tok == _LitWord && p.val == "do" {
2520 } else {
2521 p.followErr(fpos, ftok+" foo", noQuote("`in`, `do`, `;`, or a newline"))
2522 }
2523 return wi
2524 }
2525
2526 func (p *Parser) selectClause(s *Stmt) {
2527 fc := &ForClause{ForPos: p.pos, Select: true}
2528 p.next()
2529 fc.Loop = p.wordIter("select", fc.ForPos)
2530 fc.DoPos = p.followRsrv(fc.ForPos, "select foo [in words]", "do")
2531 fc.Do, fc.DoLast = p.followStmts("do", fc.DoPos, "done")
2532 fc.DonePos = p.stmtEnd(fc, "select", "done")
2533 s.Cmd = fc
2534 }
2535
2536 func (p *Parser) caseClause(s *Stmt) {
2537 cc := &CaseClause{Case: p.pos}
2538 p.next()
2539 cc.Word = p.getWord()
2540 if cc.Word == nil {
2541 p.followErr(cc.Case, "case", noQuote("a word"))
2542 }
2543 end := "esac"
2544 p.got(_Newl)
2545 if pos, ok := p.gotRsrv("{"); ok {
2546 cc.In = pos
2547 cc.Braces = true
2548 p.checkLang(cc.Pos(), LangMirBSDKorn, "`case i {`")
2549 end = "}"
2550 } else {
2551 cc.In = p.followRsrv(cc.Case, "case x", "in")
2552 }
2553 cc.Items = p.caseItems(end)
2554 cc.Last, p.accComs = p.accComs, nil
2555 cc.Esac = p.stmtEnd(cc, "case", end)
2556 s.Cmd = cc
2557 }
2558
2559 func (p *Parser) caseItems(stop string) (items []*CaseItem) {
2560 p.got(_Newl)
2561 for p.tok != _EOF && (p.tok != _LitWord || p.val != stop) {
2562 ci := &CaseItem{}
2563 ci.Comments, p.accComs = p.accComs, nil
2564 p.got(leftParen)
2565 for p.tok != _EOF {
2566 if w := p.getWord(); w == nil {
2567 p.curErr("case patterns must consist of words")
2568 } else {
2569 ci.Patterns = append(ci.Patterns, w)
2570 }
2571 if p.tok == rightParen {
2572 break
2573 }
2574 if !p.got(or) {
2575 p.curErr("case patterns must be separated with %#q", or)
2576 }
2577 }
2578 old := p.preNested(switchCase)
2579 p.next()
2580 ci.Stmts, ci.Last = p.stmtList(stop)
2581 p.postNested(old)
2582 switch p.tok {
2583 case dblSemicolon, semiAnd, dblSemiAnd, semiOr:
2584 default:
2585 ci.Op = Break
2586 items = append(items, ci)
2587 return items
2588 }
2589 ci.Last = append(ci.Last, p.accComs...)
2590 p.accComs = nil
2591 ci.OpPos = p.pos
2592 ci.Op = CaseOperator(p.tok)
2593 p.next()
2594 p.got(_Newl)
2595
2596 // Split the comments:
2597 //
2598 // case x in
2599 // a)
2600 // foo
2601 // ;;
2602 // # comment for a
2603 // # comment for b
2604 // b)
2605 // [...]
2606 split := len(p.accComs)
2607 for i, c := range slices.Backward(p.accComs) {
2608 if c.Pos().Col() != p.pos.Col() {
2609 break
2610 }
2611 split = i
2612 }
2613 ci.Comments = append(ci.Comments, p.accComs[:split]...)
2614 p.accComs = p.accComs[split:]
2615
2616 items = append(items, ci)
2617 }
2618 return items
2619 }
2620
2621 func (p *Parser) testClause(s *Stmt) {
2622 tc := &TestClause{Left: p.pos}
2623 old := p.preNested(testExpr)
2624 p.next()
2625 if tc.X = p.testExprBinary(false); tc.X == nil {
2626 p.followErrExp(tc.Left, dblLeftBrack)
2627 }
2628 tc.Right = p.pos
2629 if _, ok := p.gotRsrv("]]"); !ok {
2630 p.matchingErr(tc.Left, dblLeftBrack, dblRightBrack)
2631 }
2632 p.postNested(old)
2633 s.Cmd = tc
2634 }
2635
2636 func (p *Parser) testExprBinary(pastAndOr bool) TestExpr {
2637 p.got(_Newl)
2638 var left TestExpr
2639 if pastAndOr {
2640 left = p.testExprUnary()
2641 } else {
2642 left = p.testExprBinary(true)
2643 }
2644 if left == nil {
2645 return left
2646 }
2647 p.got(_Newl)
2648 switch p.tok {
2649 case andAnd, orOr:
2650 case _LitWord:
2651 if p.val == "]]" {
2652 return left
2653 }
2654 if p.tok = token(testBinaryOp(p.val)); p.tok == illegalTok {
2655 p.curErr("not a valid test operator: %#q", p.val)
2656 }
2657 case rdrIn, rdrOut:
2658 case _EOF, rightParen:
2659 return left
2660 case _Lit:
2661 p.curErr("test operator words must consist of a single literal")
2662 default:
2663 p.curErr("not a valid test operator: %#q", p.tok)
2664 }
2665 b := &BinaryTest{
2666 OpPos: p.pos,
2667 Op: BinTestOperator(p.tok),
2668 X: left,
2669 }
2670 switch b.Op {
2671 case AndTest, OrTest:
2672 p.next()
2673 if b.Y = p.testExprBinary(false); b.Y == nil {
2674 p.followErrExp(b.OpPos, b.Op)
2675 }
2676 case TsReMatch:
2677 p.checkLang(p.pos, langBashLike|LangZsh, "regex tests")
2678 p.rxOpenParens = 0
2679 p.rxFirstPart = true
2680 // TODO(mvdan): Using nested states within a regex will break in
2681 // all sorts of ways. The better fix is likely to use a stop
2682 // token, like we do with heredocs.
2683 p.quote = testExprRegexp
2684 fallthrough
2685 default:
2686 if _, ok := b.X.(*Word); !ok {
2687 p.posErr(b.OpPos, "expected %#q, %#q or %#q after complex expr",
2688 AndTest, OrTest, dblRightBrack)
2689 }
2690 p.next()
2691 b.Y = p.followWordTok(token(b.Op), b.OpPos)
2692 }
2693 return b
2694 }
2695
2696 func (p *Parser) testExprUnary() TestExpr {
2697 switch p.tok {
2698 case _EOF, rightParen:
2699 return nil
2700 case _LitWord:
2701 op := token(testUnaryOp(p.val))
2702 switch op {
2703 case illegalTok:
2704 case tsRefVar, tsModif: // not available in mksh
2705 if p.lang.in(langBashLike) {
2706 p.tok = op
2707 }
2708 default:
2709 p.tok = op
2710 }
2711 }
2712 switch p.tok {
2713 case exclMark:
2714 u := &UnaryTest{OpPos: p.pos, Op: TsNot}
2715 p.next()
2716 if u.X = p.testExprBinary(false); u.X == nil {
2717 p.followErrExp(u.OpPos, u.Op)
2718 }
2719 return u
2720 case tsExists, tsRegFile, tsDirect, tsCharSp, tsBlckSp, tsNmPipe,
2721 tsSocket, tsSmbLink, tsSticky, tsGIDSet, tsUIDSet, tsGrpOwn,
2722 tsUsrOwn, tsModif, tsRead, tsWrite, tsExec, tsNoEmpty,
2723 tsFdTerm, tsEmpStr, tsNempStr, tsOptSet, tsVarSet, tsRefVar:
2724 u := &UnaryTest{OpPos: p.pos, Op: UnTestOperator(p.tok)}
2725 p.next()
2726 u.X = p.followWordTok(token(u.Op), u.OpPos)
2727 return u
2728 case leftParen:
2729 pe := &ParenTest{Lparen: p.pos}
2730 p.next()
2731 if pe.X = p.testExprBinary(false); pe.X == nil {
2732 p.followErrExp(pe.Lparen, leftParen)
2733 }
2734 pe.Rparen = p.matched(pe.Lparen, leftParen, rightParen)
2735 return pe
2736 case _LitWord:
2737 if p.val == "]]" {
2738 return nil
2739 }
2740 fallthrough
2741 default:
2742 if w := p.getWord(); w != nil {
2743 return w
2744 }
2745 // otherwise we'd return a typed nil above
2746 return nil
2747 }
2748 }
2749
2750 func (p *Parser) declClause(s *Stmt) {
2751 ds := &DeclClause{Variant: p.lit(p.pos, p.val)}
2752 p.next()
2753 for !p.stopToken() && !p.peekRedir() {
2754 if p.hasValidIdent() {
2755 ds.Args = append(ds.Args, p.getAssign(false))
2756 } else if p.tok.isLit() && p.eqlOffs > 0 && !strings.Contains(p.val[:p.eqlOffs], "{") {
2757 p.curErr("invalid var name")
2758 } else if p.tok == _LitWord && ValidName(p.val) {
2759 ds.Args = append(ds.Args, &Assign{
2760 Naked: true,
2761 Name: p.getLit(),
2762 })
2763 } else if w := p.getWord(); w != nil {
2764 ds.Args = append(ds.Args, &Assign{
2765 Naked: true,
2766 Value: w,
2767 })
2768 } else {
2769 p.followErr(p.pos, ds.Variant.Value, noQuote("names or assignments"))
2770 }
2771 }
2772 s.Cmd = ds
2773 }
2774
2775 func isBashCompoundCommand(tok token, val string) bool {
2776 switch tok {
2777 case leftParen, dblLeftParen:
2778 return true
2779 case _LitWord:
2780 switch val {
2781 case "{", "if", "while", "until", "for", "case", "[[",
2782 "coproc", "let", "function", "declare", "local",
2783 "export", "readonly", "typeset", "nameref":
2784 return true
2785 }
2786 }
2787 return false
2788 }
2789
2790 func (p *Parser) timeClause(s *Stmt) {
2791 tc := &TimeClause{Time: p.pos}
2792 p.next()
2793 if _, ok := p.gotRsrv("-p"); ok {
2794 tc.PosixFormat = true
2795 }
2796 tc.Stmt = p.gotStmtPipe(&Stmt{Position: p.pos}, false)
2797 s.Cmd = tc
2798 }
2799
2800 func (p *Parser) coprocClause(s *Stmt) {
2801 cc := &CoprocClause{Coproc: p.pos}
2802 if p.next(); isBashCompoundCommand(p.tok, p.val) {
2803 // has no name
2804 cc.Stmt = p.gotStmtPipe(&Stmt{Position: p.pos}, false)
2805 s.Cmd = cc
2806 return
2807 }
2808 cc.Name = p.getWord()
2809 cc.Stmt = p.gotStmtPipe(&Stmt{Position: p.pos}, false)
2810 if cc.Stmt == nil {
2811 if cc.Name == nil {
2812 p.posErr(cc.Coproc, "coproc clause requires a command")
2813 return
2814 }
2815 // name was in fact the stmt
2816 cc.Stmt = &Stmt{Position: cc.Name.Pos()}
2817 cc.Stmt.Cmd = p.call(cc.Name)
2818 cc.Name = nil
2819 } else if cc.Name != nil {
2820 if call, ok := cc.Stmt.Cmd.(*CallExpr); ok {
2821 // name was in fact the start of a call
2822 call.Args = append([]*Word{cc.Name}, call.Args...)
2823 cc.Name = nil
2824 }
2825 }
2826 s.Cmd = cc
2827 }
2828
2829 func (p *Parser) letClause(s *Stmt) {
2830 lc := &LetClause{Let: p.pos}
2831 old := p.preNested(arithmExprLet)
2832 p.next()
2833 for !p.stopToken() && !p.peekRedir() {
2834 x := p.arithmExpr(true)
2835 if x == nil {
2836 break
2837 }
2838 lc.Exprs = append(lc.Exprs, x)
2839 }
2840 if len(lc.Exprs) == 0 {
2841 p.followErrExp(lc.Let, "let")
2842 }
2843 p.postNested(old)
2844 s.Cmd = lc
2845 }
2846
2847 func (p *Parser) bashFuncDecl(s *Stmt) {
2848 fpos := p.pos
2849 p.next()
2850 names := make([]*Lit, 0, 1)
2851 for p.tok == _LitWord && p.val != "{" {
2852 names = append(names, p.lit(p.pos, p.val))
2853 p.next()
2854 }
2855 hasParens := p.got(leftParen)
2856 switch len(names) {
2857 case 0:
2858 if hasParens || (p.tok == _LitWord && p.val == "{") {
2859 p.checkLang(fpos, LangZsh, "anonymous functions")
2860 } else if !p.lang.in(LangZsh) {
2861 p.followErr(fpos, "function", noQuote("a name"))
2862 }
2863 names = nil // avoid non-nil zero-length slices
2864 case 1:
2865 // allowed in all variants
2866 default:
2867 p.checkLang(fpos, LangZsh, "multi-name functions")
2868 }
2869 if hasParens {
2870 p.follow(fpos, "function foo(", rightParen)
2871 }
2872 p.funcDecl(s, fpos, true, hasParens, names...)
2873 }
2874
2875 func (p *Parser) testDecl(s *Stmt) {
2876 td := &TestDecl{Position: p.pos}
2877 p.next()
2878 if td.Description = p.getWord(); td.Description == nil {
2879 p.followErr(td.Position, "@test", noQuote("a description word"))
2880 }
2881 if td.Body = p.getStmt(false, false, true); td.Body == nil {
2882 p.followErr(td.Position, `@test "desc"`, noQuote("a statement"))
2883 }
2884 s.Cmd = td
2885 }
2886
2887 func (p *Parser) unexpectedInCallExpr(ce *CallExpr) {
2888 // Note that we'll only keep the first error that happens.
2889 if len(ce.Args) > 0 {
2890 if cmd := ce.Args[0].Lit(); isBashCompoundCommand(_LitWord, cmd) {
2891 p.checkLang(p.pos, langBashLike, "the %#q builtin", cmd)
2892 }
2893 }
2894 p.curErr("a command can only contain words and redirects; encountered %#q", p.tok)
2895 }
2896
2897 func (p *Parser) callExpr(s *Stmt, w *Word, assign bool) {
2898 ce := p.call(w)
2899 if w == nil {
2900 ce.Args = ce.Args[:0]
2901 }
2902 if assign {
2903 ce.Assigns = append(ce.Assigns, p.getAssign(true))
2904 }
2905 loop:
2906 for {
2907 switch p.tok {
2908 case _EOF, _Newl, semicolon, and, or, andAnd, orOr, orAnd, andPipe, andBang,
2909 dblSemicolon, semiAnd, dblSemiAnd, semiOr:
2910 break loop
2911 case _LitWord:
2912 if len(ce.Args) == 0 && p.hasValidIdent() {
2913 ce.Assigns = append(ce.Assigns, p.getAssign(true))
2914 break
2915 }
2916 // Avoid failing later with the confusing "} can only be used to close a block".
2917 if p.val == "{" && w != nil && w.Lit() == "function" {
2918 p.checkLang(p.pos, langBashLike, `the "function" builtin`)
2919 }
2920 // Zsh does not require a semicolon to close a block.
2921 if p.lang.in(LangZsh) && p.val == "}" {
2922 break loop
2923 }
2924 w := p.wordOne(p.lit(p.pos, p.val))
2925 p.next()
2926 if p.lang.in(LangZsh) && !p.spaced {
2927 w.Parts = append(w.Parts, p.wordParts(nil)...)
2928 }
2929 ce.Args = append(ce.Args, w)
2930 case _Lit:
2931 if len(ce.Args) == 0 && p.hasValidIdent() {
2932 ce.Assigns = append(ce.Assigns, p.getAssign(true))
2933 break
2934 }
2935 ce.Args = append(ce.Args, p.wordAnyNumber())
2936 case bckQuote:
2937 if p.backquoteEnd() {
2938 break loop
2939 }
2940 fallthrough
2941 case dollBrace, dollDblParen, dollParen, dollar, cmdIn, assgnParen, cmdOut,
2942 sglQuote, dollSglQuote, dblQuote, dollDblQuote, dollBrack,
2943 globQuest, globStar, globPlus, globAt, globExcl:
2944 ce.Args = append(ce.Args, p.wordAnyNumber())
2945 case dblLeftParen:
2946 p.curErr("%#q can only be used to open an arithmetic cmd", p.tok)
2947 case leftParen:
2948 if p.lang.in(LangZsh) && p.r != ')' {
2949 ce.Args = append(ce.Args, p.wordAnyNumber())
2950 break
2951 }
2952 p.unexpectedInCallExpr(ce)
2953 case rightParen:
2954 if p.quote == subCmd {
2955 break loop
2956 }
2957 p.unexpectedInCallExpr(ce)
2958 default:
2959 if p.peekRedir() {
2960 p.doRedirect(s)
2961 continue
2962 }
2963 p.unexpectedInCallExpr(ce)
2964 }
2965 }
2966 if len(ce.Args) == 0 {
2967 ce.Args = nil
2968 } else {
2969 for _, asgn := range ce.Assigns {
2970 if asgn.Index != nil || asgn.Array != nil {
2971 p.posErr(asgn.Pos(), "inline variables cannot be arrays")
2972 }
2973 }
2974 }
2975 s.Cmd = ce
2976 }
2977
2978 func (p *Parser) funcDecl(s *Stmt, pos Pos, long, withParens bool, names ...*Lit) {
2979 fd := &FuncDecl{
2980 Position: pos,
2981 RsrvWord: long,
2982 Parens: withParens,
2983 }
2984 if len(names) == 1 {
2985 fd.Name = names[0]
2986 } else {
2987 fd.Names = names
2988 }
2989 p.got(_Newl)
2990 // TODO: reject any body which isn't a compound command, like a quoted word
2991 if fd.Body = p.getStmt(false, false, true); fd.Body == nil {
2992 p.followErr(fd.Pos(), "foo()", noQuote("a statement"))
2993 }
2994 s.Cmd = fd
2995 }