| 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 |
!paramNameStartRune(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 zsh allows the short forms $#name and $+name too, |
| 1519 |
// but not $%name nor $!name. |
| 1520 |
switch p.r { |
| 1521 |
case '#': |
| 1522 |
if p.paramNameStart(pe) { |
| 1523 |
pe.Length = true |
| 1524 |
} |
| 1525 |
case '%': |
| 1526 |
if !pe.Short && p.paramNameStart(pe) { |
| 1527 |
p.checkLang(pe.Pos(), LangMirBSDKorn, "`${%%foo}`") |
| 1528 |
pe.Width = true |
| 1529 |
} |
| 1530 |
case '!': |
| 1531 |
if !pe.Short && p.paramNameStart(pe) { |
| 1532 |
p.checkLang(pe.Pos(), langBashLike|LangMirBSDKorn, "`${!foo}`") |
| 1533 |
pe.Excl = true |
| 1534 |
} |
| 1535 |
case '+': |
| 1536 |
if p.paramNameStart(pe) { |
| 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 |
// paramNameStart reports whether a parameter name can begin after a prefix rune |
| 1678 |
// such as the '#' in ${#foo}, consuming the prefix rune if so. |
| 1679 |
// Only the long form allows a quoted nested expansion like ${#"$(foo)"} or EOF; |
| 1680 |
// in the short form the prefix rune is the parameter itself, as in "$#" or $#"$foo". |
| 1681 |
func (p *Parser) paramNameStart(pe *ParamExp) bool { |
| 1682 |
r := p.peek() |
| 1683 |
if paramNameStartRune(r) || (!pe.Short && (r == '"' || r == utf8.RuneSelf)) { |
| 1684 |
p.rune() |
| 1685 |
return true |
| 1686 |
} |
| 1687 |
return false |
| 1688 |
} |
| 1689 |
|
| 1690 |
func (p *Parser) nestedParameterStart(pe *ParamExp) (left token, quotePos Pos) { |
| 1691 |
if pe.Short { |
| 1692 |
return illegalTok, Pos{} |
| 1693 |
} |
| 1694 |
if p.r == '"' { |
| 1695 |
quotePos = p.nextPos() |
| 1696 |
p.rune() |
| 1697 |
} |
| 1698 |
if p.r != '$' { |
| 1699 |
if quotePos.IsValid() { |
| 1700 |
return dollar, quotePos |
| 1701 |
} |
| 1702 |
return illegalTok, Pos{} |
| 1703 |
} |
| 1704 |
switch p1 := p.peek(); p1 { |
| 1705 |
case '{', '(': |
| 1706 |
p.pos = p.nextPos() |
| 1707 |
p.checkLang(p.pos, LangZsh, "nested parameter expansions") |
| 1708 |
if p.err != nil { |
| 1709 |
return illegalTok, Pos{} // xxx given that we overwrite p.tok below |
| 1710 |
} |
| 1711 |
p.rune() |
| 1712 |
p.rune() |
| 1713 |
if p1 == '{' { |
| 1714 |
left = dollBrace |
| 1715 |
} else { // '(' |
| 1716 |
left = dollParen |
| 1717 |
} |
| 1718 |
} |
| 1719 |
return left, quotePos |
| 1720 |
} |
| 1721 |
|
| 1722 |
func (p *Parser) paramExpParameter(pe *ParamExp) *ParamExp { |
| 1723 |
// Check for Zsh nested parameter expressions like ${(f)"$(foo)"}. |
| 1724 |
if left, quotePos := p.nestedParameterStart(pe); left != illegalTok { |
| 1725 |
var wp WordPart |
| 1726 |
switch p.tok = left; p.tok { |
| 1727 |
case dollBrace: // ${#${nested parameter}} |
| 1728 |
p.tok = dollBrace |
| 1729 |
wp = p.paramExp() |
| 1730 |
case dollParen: // ${#$(nested command)} |
| 1731 |
wp = p.cmdSubst() |
| 1732 |
default: // dollar |
| 1733 |
p.posErr(pe.Pos(), "invalid nested parameter expansion") |
| 1734 |
} |
| 1735 |
if quotePos.IsValid() { |
| 1736 |
if p.r != '"' { |
| 1737 |
p.tok = p.paramToken(p.r) |
| 1738 |
if p.tok == illegalTok { |
| 1739 |
p.posErr(pe.Pos(), "invalid nested parameter expansion") |
| 1740 |
} else { |
| 1741 |
p.quoteErr(quotePos, dblQuote) |
| 1742 |
} |
| 1743 |
} |
| 1744 |
pe.NestedParam = &DblQuoted{ |
| 1745 |
Left: quotePos, |
| 1746 |
Right: p.nextPos(), |
| 1747 |
Parts: []WordPart{wp}, |
| 1748 |
} |
| 1749 |
p.rune() |
| 1750 |
} else { |
| 1751 |
pe.NestedParam = wp |
| 1752 |
} |
| 1753 |
return pe |
| 1754 |
} |
| 1755 |
// The parameter name itself, like $foo or $?. |
| 1756 |
switch p.r { |
| 1757 |
case '?', '-': |
| 1758 |
if pe.Length && p.peek() != '}' { |
| 1759 |
// actually ${#-default}, not ${#-}; fix the ambiguity |
| 1760 |
pe.Length = false |
| 1761 |
pos := p.nextPos() |
| 1762 |
pe.Param = p.lit(posAddCol(pos, -1), "#") |
| 1763 |
pe.Param.ValueEnd = pos |
| 1764 |
break |
| 1765 |
} |
| 1766 |
fallthrough |
| 1767 |
case '@', '*', '#', '!', '$': |
| 1768 |
r, pos := p.r, p.nextPos() |
| 1769 |
p.rune() |
| 1770 |
pe.Param = p.lit(pos, string(r)) |
| 1771 |
default: |
| 1772 |
// Note that $1a is equivalent to ${1}a, but ${1a} is not. |
| 1773 |
// POSIX Shell says the latter is unspecified behavior, so match Bash's behavior. |
| 1774 |
pos := p.nextPos() |
| 1775 |
if pe.Short && singleRuneParam(p.r) { |
| 1776 |
p.val = string(p.r) |
| 1777 |
p.rune() |
| 1778 |
} else { |
| 1779 |
for p.newLit(p.r); p.r != runeEOF; p.rune() { |
| 1780 |
if !paramNameRune(p.r) && p.r != escNewl { |
| 1781 |
break |
| 1782 |
} |
| 1783 |
} |
| 1784 |
p.val = p.endLit() |
| 1785 |
if !numberLiteral(p.val) && !ValidName(p.val) { |
| 1786 |
if pe.Short { |
| 1787 |
return nil // just "$" |
| 1788 |
} |
| 1789 |
if p.lang.in(LangZsh) && p.val == "" { |
| 1790 |
// Zsh allows omitting the parameter name, e.g. ${:-word}. |
| 1791 |
return pe |
| 1792 |
} |
| 1793 |
p.posErr(pos, "invalid parameter name") |
| 1794 |
} |
| 1795 |
} |
| 1796 |
pe.Param = p.lit(pos, p.val) |
| 1797 |
} |
| 1798 |
return pe |
| 1799 |
} |
| 1800 |
|
| 1801 |
func (p *Parser) paramExpExp() *Expansion { |
| 1802 |
op := ParExpOperator(p.tok) |
| 1803 |
switch op { |
| 1804 |
case MatchEmpty, ArrayExclude, ArrayIntersect: |
| 1805 |
p.checkLang(p.pos, LangZsh, "${name%sarg}", op) |
| 1806 |
} |
| 1807 |
p.quote = paramExpExp |
| 1808 |
p.next() |
| 1809 |
if op == OtherParamOps { |
| 1810 |
if !p.tok.isLit() { |
| 1811 |
p.curErr("@ expansion operator requires a literal") |
| 1812 |
} |
| 1813 |
switch p.val { |
| 1814 |
case "a", "k", "u", "A", "E", "K", "L", "P", "U": |
| 1815 |
p.checkLang(p.pos, langBashLike, "this expansion operator") |
| 1816 |
case "#": |
| 1817 |
p.checkLang(p.pos, LangMirBSDKorn, "this expansion operator") |
| 1818 |
case "Q": |
| 1819 |
default: |
| 1820 |
p.curErr("invalid @ expansion operator %#q", p.val) |
| 1821 |
} |
| 1822 |
} |
| 1823 |
return &Expansion{Op: op, Word: p.getWord()} |
| 1824 |
} |
| 1825 |
|
| 1826 |
func (p *Parser) eitherIndex() ArithmExpr { |
| 1827 |
old := p.quote |
| 1828 |
lpos := p.pos |
| 1829 |
p.quote = paramExpArithm |
| 1830 |
p.next() |
| 1831 |
if p.tok == star || p.tok == at { |
| 1832 |
p.tok, p.val = _LitWord, p.tok.String() |
| 1833 |
} |
| 1834 |
expr := p.followArithm(leftBrack, lpos) |
| 1835 |
p.quote = old |
| 1836 |
p.matchedArithm(lpos, leftBrack, rightBrack) |
| 1837 |
return expr |
| 1838 |
} |
| 1839 |
|
| 1840 |
func (p *Parser) zshSubFlags() *FlagsArithm { |
| 1841 |
zf := &FlagsArithm{} |
| 1842 |
// Lex flags as raw text, like paramExp does for ${(flags)...}. |
| 1843 |
lparen := p.pos |
| 1844 |
old := p.quote |
| 1845 |
p.quote = runeByRune |
| 1846 |
p.pos = p.nextPos() |
| 1847 |
for p.newLit(p.r); p.r != runeEOF && p.r != ')'; p.rune() { |
| 1848 |
} |
| 1849 |
p.val = p.endLit() |
| 1850 |
if p.r != ')' { |
| 1851 |
p.tok = _EOF |
| 1852 |
p.matchingErr(lparen, leftParen, rightParen) |
| 1853 |
} |
| 1854 |
zf.Flags = p.lit(p.pos, p.val) |
| 1855 |
p.rune() |
| 1856 |
// Lex the argument as a raw pattern, stopping at ',' or ']', |
| 1857 |
// since zsh treats it as a pattern rather than an arithmetic expression. |
| 1858 |
argPos := p.nextPos() |
| 1859 |
for p.newLit(p.r); p.r != runeEOF && p.r != ',' && p.r != ']'; p.rune() { |
| 1860 |
} |
| 1861 |
if val := p.endLit(); val != "" { |
| 1862 |
zf.X = p.wordOne(p.lit(argPos, val)) |
| 1863 |
} |
| 1864 |
p.quote = old |
| 1865 |
p.next() |
| 1866 |
return zf |
| 1867 |
} |
| 1868 |
|
| 1869 |
func (p *Parser) stopToken() bool { |
| 1870 |
switch p.tok { |
| 1871 |
case _EOF, _Newl, semicolon, and, or, andAnd, orOr, orAnd, andPipe, andBang, |
| 1872 |
dblSemicolon, semiAnd, dblSemiAnd, semiOr, rightParen: |
| 1873 |
return true |
| 1874 |
case bckQuote: |
| 1875 |
return p.backquoteEnd() |
| 1876 |
} |
| 1877 |
return false |
| 1878 |
} |
| 1879 |
|
| 1880 |
func (p *Parser) backquoteEnd() bool { |
| 1881 |
return p.lastBquoteEsc < p.openBquotes |
| 1882 |
} |
| 1883 |
|
| 1884 |
// ValidName returns whether val is a valid name as per the POSIX spec. |
| 1885 |
func ValidName(val string) bool { |
| 1886 |
if val == "" { |
| 1887 |
return false |
| 1888 |
} |
| 1889 |
for i, r := range val { |
| 1890 |
switch { |
| 1891 |
case asciiLetter(r), r == '_': |
| 1892 |
case i > 0 && asciiDigit(r): |
| 1893 |
default: |
| 1894 |
return false |
| 1895 |
} |
| 1896 |
} |
| 1897 |
return true |
| 1898 |
} |
| 1899 |
|
| 1900 |
func numberLiteral[T string | []byte](val T) bool { |
| 1901 |
if len(val) == 0 { |
| 1902 |
return false |
| 1903 |
} |
| 1904 |
for _, r := range string(val) { |
| 1905 |
if !asciiDigit(r) { |
| 1906 |
return false |
| 1907 |
} |
| 1908 |
} |
| 1909 |
return true |
| 1910 |
} |
| 1911 |
|
| 1912 |
func (p *Parser) hasValidIdent() bool { |
| 1913 |
if !p.tok.isLit() { |
| 1914 |
return false |
| 1915 |
} |
| 1916 |
if end := p.eqlOffs; end > 0 { |
| 1917 |
if p.val[end-1] == '+' && p.lang.in(langBashLike|LangMirBSDKorn|LangZsh) { |
| 1918 |
end-- // a+=x |
| 1919 |
} |
| 1920 |
if ValidName(p.val[:end]) { |
| 1921 |
return true |
| 1922 |
} |
| 1923 |
} else if !ValidName(p.val) { |
| 1924 |
return false // *[i]=x |
| 1925 |
} |
| 1926 |
return p.r == '[' // a[i]=x |
| 1927 |
} |
| 1928 |
|
| 1929 |
func (p *Parser) getAssign(needEqual bool) *Assign { |
| 1930 |
as := &Assign{} |
| 1931 |
if p.eqlOffs > 0 { // foo=bar |
| 1932 |
nameEnd := p.eqlOffs |
| 1933 |
if p.lang.in(langBashLike|LangMirBSDKorn|LangZsh) && p.val[p.eqlOffs-1] == '+' { |
| 1934 |
// a+=b |
| 1935 |
as.Append = true |
| 1936 |
nameEnd-- |
| 1937 |
} |
| 1938 |
as.Name = p.lit(p.pos, p.val[:nameEnd]) |
| 1939 |
// since we're not using the entire p.val |
| 1940 |
as.Name.ValueEnd = posAddCol(as.Name.ValuePos, nameEnd) |
| 1941 |
left := p.lit(posAddCol(p.pos, 1), p.val[p.eqlOffs+1:]) |
| 1942 |
if left.Value != "" { |
| 1943 |
left.ValuePos = posAddCol(left.ValuePos, p.eqlOffs) |
| 1944 |
as.Value = p.wordOne(left) |
| 1945 |
} |
| 1946 |
p.next() |
| 1947 |
} else { // foo[x]=bar |
| 1948 |
as.Name = p.lit(p.pos, p.val) |
| 1949 |
// hasValidIdent already checks p.r is '[' |
| 1950 |
p.rune() |
| 1951 |
p.pos = posAddCol(p.pos, 1) |
| 1952 |
as.Index = p.eitherIndex() |
| 1953 |
if p.spaced || p.stopToken() { |
| 1954 |
if needEqual { |
| 1955 |
p.followErr(as.Pos(), "a[b]", assgn) |
| 1956 |
} else { |
| 1957 |
as.Naked = true |
| 1958 |
return as |
| 1959 |
} |
| 1960 |
} |
| 1961 |
if p.tok == assgnParen { |
| 1962 |
if !p.lang.in(LangZsh) { |
| 1963 |
p.curErr("arrays cannot be nested") |
| 1964 |
return nil |
| 1965 |
} |
| 1966 |
// zsh allows a[i]=(values...). |
| 1967 |
// assgnParen consumed both '=' and '(', |
| 1968 |
// so rewrite as leftParen for array parsing below. |
| 1969 |
p.tok = leftParen |
| 1970 |
p.pos = posAddCol(p.pos, 1) |
| 1971 |
} else { |
| 1972 |
if len(p.val) > 0 && p.val[0] == '+' { |
| 1973 |
as.Append = true |
| 1974 |
p.val = p.val[1:] |
| 1975 |
p.pos = posAddCol(p.pos, 1) |
| 1976 |
} |
| 1977 |
if len(p.val) < 1 || p.val[0] != '=' { |
| 1978 |
if as.Append { |
| 1979 |
p.followErr(as.Pos(), "a[b]+", assgn) |
| 1980 |
} else { |
| 1981 |
p.followErr(as.Pos(), "a[b]", assgn) |
| 1982 |
} |
| 1983 |
return nil |
| 1984 |
} |
| 1985 |
p.pos = posAddCol(p.pos, 1) |
| 1986 |
p.val = p.val[1:] |
| 1987 |
if p.val == "" { |
| 1988 |
p.next() |
| 1989 |
} |
| 1990 |
} |
| 1991 |
} |
| 1992 |
if p.spaced || p.stopToken() { |
| 1993 |
return as |
| 1994 |
} |
| 1995 |
if as.Value == nil && p.tok == leftParen { |
| 1996 |
p.checkLang(p.pos, langBashLike|LangMirBSDKorn|LangZsh, "arrays") |
| 1997 |
as.Array = &ArrayExpr{Lparen: p.pos} |
| 1998 |
newQuote := p.quote |
| 1999 |
if p.lang.in(langBashLike | LangZsh) { |
| 2000 |
newQuote = arrayElems |
| 2001 |
} |
| 2002 |
old := p.preNested(newQuote) |
| 2003 |
p.next() |
| 2004 |
p.got(_Newl) |
| 2005 |
for p.tok != _EOF && p.tok != rightParen { |
| 2006 |
ae := &ArrayElem{} |
| 2007 |
ae.Comments, p.accComs = p.accComs, nil |
| 2008 |
if p.tok == leftBrack { |
| 2009 |
left := p.pos |
| 2010 |
ae.Index = p.eitherIndex() |
| 2011 |
if p.tok == assgnParen { |
| 2012 |
p.curErr("arrays cannot be nested") |
| 2013 |
return nil |
| 2014 |
} |
| 2015 |
p.follow(left, `[x]`, assgn) |
| 2016 |
} |
| 2017 |
if ae.Value = p.getWord(); ae.Value == nil { |
| 2018 |
switch p.tok { |
| 2019 |
case _Newl, rightParen, leftBrack: |
| 2020 |
// TODO: support [index]=[ |
| 2021 |
default: |
| 2022 |
p.curErr("array element values must be words") |
| 2023 |
return nil |
| 2024 |
} |
| 2025 |
} |
| 2026 |
if len(p.accComs) > 0 { |
| 2027 |
c := p.accComs[0] |
| 2028 |
if c.Pos().Line() == ae.End().Line() { |
| 2029 |
ae.Comments = append(ae.Comments, c) |
| 2030 |
p.accComs = p.accComs[1:] |
| 2031 |
} |
| 2032 |
} |
| 2033 |
as.Array.Elems = append(as.Array.Elems, ae) |
| 2034 |
p.got(_Newl) |
| 2035 |
} |
| 2036 |
as.Array.Last, p.accComs = p.accComs, nil |
| 2037 |
p.postNested(old) |
| 2038 |
as.Array.Rparen = p.matched(as.Array.Lparen, leftParen, rightParen) |
| 2039 |
} else if w := p.getWord(); w != nil { |
| 2040 |
if as.Value == nil { |
| 2041 |
as.Value = w |
| 2042 |
} else { |
| 2043 |
as.Value.Parts = append(as.Value.Parts, w.Parts...) |
| 2044 |
} |
| 2045 |
} |
| 2046 |
return as |
| 2047 |
} |
| 2048 |
|
| 2049 |
func (p *Parser) peekRedir() bool { |
| 2050 |
switch p.tok { |
| 2051 |
case _LitRedir, rdrOut, appOut, rdrIn, rdrInOut, dplIn, dplOut, |
| 2052 |
rdrClob, appClob, hdoc, dashHdoc, wordHdoc, |
| 2053 |
rdrAll, rdrAllClob, appAll, appAllClob: |
| 2054 |
return true |
| 2055 |
} |
| 2056 |
return false |
| 2057 |
} |
| 2058 |
|
| 2059 |
func (p *Parser) doRedirect(s *Stmt) { |
| 2060 |
var r *Redirect |
| 2061 |
if s.Redirs == nil { |
| 2062 |
var alloc struct { |
| 2063 |
redirs [4]*Redirect |
| 2064 |
redir Redirect |
| 2065 |
} |
| 2066 |
s.Redirs = alloc.redirs[:0] |
| 2067 |
r = &alloc.redir |
| 2068 |
s.Redirs = append(s.Redirs, r) |
| 2069 |
} else { |
| 2070 |
r = &Redirect{} |
| 2071 |
s.Redirs = append(s.Redirs, r) |
| 2072 |
} |
| 2073 |
r.N = p.getLit() |
| 2074 |
if r.N != nil && r.N.Value[0] == '{' { |
| 2075 |
p.checkLang(r.N.Pos(), langBashLike|LangZsh, "`{varname}` redirects") |
| 2076 |
} |
| 2077 |
r.Op, r.OpPos = RedirOperator(p.tok), p.pos |
| 2078 |
switch r.Op { |
| 2079 |
case RdrAll, AppAll: |
| 2080 |
p.checkLang(p.pos, langBashLike|LangMirBSDKorn|LangZsh, "%#q redirects", r.Op) |
| 2081 |
case AppClob, RdrAllClob, AppAllClob: |
| 2082 |
p.checkLang(p.pos, LangZsh, "%#q redirects", r.Op) |
| 2083 |
} |
| 2084 |
p.next() |
| 2085 |
switch r.Op { |
| 2086 |
case Hdoc, DashHdoc: |
| 2087 |
old := p.quote |
| 2088 |
p.quote, p.forbidNested = hdocWord, true |
| 2089 |
p.heredocs = append(p.heredocs, r) |
| 2090 |
r.Word = p.followWordTok(token(r.Op), r.OpPos) |
| 2091 |
p.quote, p.forbidNested = old, false |
| 2092 |
if p.tok == _Newl { |
| 2093 |
if len(p.accComs) > 0 { |
| 2094 |
c := p.accComs[0] |
| 2095 |
if c.Pos().Line() == s.End().Line() { |
| 2096 |
s.Comments = append(s.Comments, c) |
| 2097 |
p.accComs = p.accComs[1:] |
| 2098 |
} |
| 2099 |
} |
| 2100 |
p.doHeredocs() |
| 2101 |
} |
| 2102 |
case WordHdoc: |
| 2103 |
p.checkLang(r.OpPos, langBashLike|LangMirBSDKorn|LangZsh, "herestrings") |
| 2104 |
fallthrough |
| 2105 |
default: |
| 2106 |
r.Word = p.followWordTok(token(r.Op), r.OpPos) |
| 2107 |
} |
| 2108 |
} |
| 2109 |
|
| 2110 |
func (p *Parser) getStmt(readEnd, binCmd, fnBody bool) *Stmt { |
| 2111 |
pos, ok := p.gotRsrv("!") |
| 2112 |
s := &Stmt{Position: pos} |
| 2113 |
if ok { |
| 2114 |
s.Negated = true |
| 2115 |
if p.stopToken() { |
| 2116 |
p.posErr(s.Pos(), `%#q cannot form a statement alone`, exclMark) |
| 2117 |
} |
| 2118 |
if _, ok := p.gotRsrv("!"); ok { |
| 2119 |
p.posErr(s.Pos(), `cannot negate a command multiple times`) |
| 2120 |
} |
| 2121 |
} |
| 2122 |
if s = p.gotStmtPipe(s, false); s == nil || p.err != nil { |
| 2123 |
return nil |
| 2124 |
} |
| 2125 |
// instead of using recursion, iterate manually |
| 2126 |
for p.tok == andAnd || p.tok == orOr { |
| 2127 |
if binCmd { |
| 2128 |
// left associativity: in a list of BinaryCmds, the |
| 2129 |
// right recursion should only read a single element |
| 2130 |
return s |
| 2131 |
} |
| 2132 |
b := &BinaryCmd{ |
| 2133 |
OpPos: p.pos, |
| 2134 |
Op: BinCmdOperator(p.tok), |
| 2135 |
X: s, |
| 2136 |
} |
| 2137 |
p.next() |
| 2138 |
p.got(_Newl) |
| 2139 |
b.Y = p.getStmt(false, true, false) |
| 2140 |
if b.Y == nil || p.err != nil { |
| 2141 |
if p.recoverError() { |
| 2142 |
b.Y = &Stmt{Position: recoveredPos} |
| 2143 |
} else { |
| 2144 |
p.followErr(b.OpPos, b.Op, noQuote("a statement")) |
| 2145 |
return nil |
| 2146 |
} |
| 2147 |
} |
| 2148 |
s = &Stmt{Position: s.Position} |
| 2149 |
s.Cmd = b |
| 2150 |
s.Comments, b.X.Comments = b.X.Comments, nil |
| 2151 |
} |
| 2152 |
if readEnd { |
| 2153 |
switch p.tok { |
| 2154 |
case semicolon: |
| 2155 |
s.Semicolon = p.pos |
| 2156 |
p.next() |
| 2157 |
case and: |
| 2158 |
s.Semicolon = p.pos |
| 2159 |
p.next() |
| 2160 |
s.Background = true |
| 2161 |
case orAnd: |
| 2162 |
s.Semicolon = p.pos |
| 2163 |
p.next() |
| 2164 |
s.Coprocess = true |
| 2165 |
case andPipe, andBang: |
| 2166 |
s.Semicolon = p.pos |
| 2167 |
p.next() |
| 2168 |
s.Disown = true |
| 2169 |
} |
| 2170 |
} |
| 2171 |
if len(p.accComs) > 0 && !binCmd && !fnBody { |
| 2172 |
c := p.accComs[0] |
| 2173 |
if c.Pos().Line() == s.End().Line() { |
| 2174 |
s.Comments = append(s.Comments, c) |
| 2175 |
p.accComs = p.accComs[1:] |
| 2176 |
} |
| 2177 |
} |
| 2178 |
return s |
| 2179 |
} |
| 2180 |
|
| 2181 |
func (p *Parser) gotStmtPipe(s *Stmt, binCmd bool) *Stmt { |
| 2182 |
s.Comments, p.accComs = p.accComs, nil |
| 2183 |
for p.peekRedir() { |
| 2184 |
p.doRedirect(s) |
| 2185 |
} |
| 2186 |
redirsStart := len(s.Redirs) |
| 2187 |
switch p.tok { |
| 2188 |
case _LitWord: |
| 2189 |
switch p.val { |
| 2190 |
case "{": |
| 2191 |
p.block(s) |
| 2192 |
case "{}": |
| 2193 |
// Zsh treats closing braces in a special way, allowing this. |
| 2194 |
if p.lang.in(LangZsh) { |
| 2195 |
s.Cmd = &Block{Lbrace: p.pos, Rbrace: posAddCol(p.pos, 1)} |
| 2196 |
p.next() |
| 2197 |
} |
| 2198 |
case "if": |
| 2199 |
p.ifClause(s) |
| 2200 |
case "while", "until": |
| 2201 |
// TODO(zsh): "repeat" |
| 2202 |
p.whileClause(s, p.val == "until") |
| 2203 |
case "for": |
| 2204 |
p.forClause(s) |
| 2205 |
case "case": |
| 2206 |
p.caseClause(s) |
| 2207 |
// TODO(zsh): { try-list } "always" { always-list } |
| 2208 |
case "}": |
| 2209 |
p.curErr(`%#q can only be used to close a block`, rightBrace) |
| 2210 |
case "then", "elif": |
| 2211 |
p.curErr("%#q can only be used in an `if`", p.val) |
| 2212 |
case "fi": |
| 2213 |
p.curErr("%#q can only be used to end an `if`", p.val) |
| 2214 |
case "do": |
| 2215 |
p.curErr(`%#q can only be used in a loop`, p.val) |
| 2216 |
case "done": |
| 2217 |
p.curErr(`%#q can only be used to end a loop`, p.val) |
| 2218 |
case "esac": |
| 2219 |
p.curErr("%#q can only be used to end a `case`", p.val) |
| 2220 |
case "!": |
| 2221 |
if !s.Negated { |
| 2222 |
p.curErr(`%#q can only be used in full statements`, exclMark) |
| 2223 |
break |
| 2224 |
} |
| 2225 |
case "[[": |
| 2226 |
if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) { |
| 2227 |
p.testClause(s) |
| 2228 |
} |
| 2229 |
case "]]": |
| 2230 |
if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) { |
| 2231 |
p.curErr(`%#q can only be used to close a test`, dblRightBrack) |
| 2232 |
} |
| 2233 |
case "let": |
| 2234 |
if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) { |
| 2235 |
p.letClause(s) |
| 2236 |
} |
| 2237 |
case "function": |
| 2238 |
if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) { |
| 2239 |
p.bashFuncDecl(s) |
| 2240 |
} |
| 2241 |
case "declare": |
| 2242 |
if p.lang.in(langBashLike | LangZsh) { // Note that mksh lacks this one. |
| 2243 |
p.declClause(s) |
| 2244 |
} |
| 2245 |
case "local", "export", "readonly", "typeset", "nameref": |
| 2246 |
if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) { |
| 2247 |
p.declClause(s) |
| 2248 |
} |
| 2249 |
case "time": |
| 2250 |
if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) { |
| 2251 |
p.timeClause(s) |
| 2252 |
} |
| 2253 |
case "coproc": |
| 2254 |
if p.lang.in(langBashLike) { // Note that mksh lacks this one. |
| 2255 |
p.coprocClause(s) |
| 2256 |
} |
| 2257 |
case "select": |
| 2258 |
if p.lang.in(langBashLike | LangMirBSDKorn | LangZsh) { |
| 2259 |
p.selectClause(s) |
| 2260 |
} |
| 2261 |
case "@test": |
| 2262 |
if p.lang.in(LangBats) { |
| 2263 |
p.testDecl(s) |
| 2264 |
} |
| 2265 |
} |
| 2266 |
if s.Cmd != nil { |
| 2267 |
break |
| 2268 |
} |
| 2269 |
if p.hasValidIdent() { |
| 2270 |
p.callExpr(s, nil, true) |
| 2271 |
break |
| 2272 |
} |
| 2273 |
name := p.lit(p.pos, p.val) |
| 2274 |
p.next() |
| 2275 |
// In zsh, ( after a word is a glob qualifier unless followed |
| 2276 |
// immediately by ), which is the func declaration syntax. |
| 2277 |
if p.tok == leftParen && (!p.lang.in(LangZsh) || p.r == ')') { |
| 2278 |
p.next() |
| 2279 |
p.follow(name.ValuePos, "foo(", rightParen) |
| 2280 |
if p.lang.in(LangPOSIX) && !ValidName(name.Value) { |
| 2281 |
p.posErr(name.Pos(), "invalid func name") |
| 2282 |
} |
| 2283 |
p.funcDecl(s, name.ValuePos, false, true, name) |
| 2284 |
} else { |
| 2285 |
w := p.wordOne(name) |
| 2286 |
if p.lang.in(LangZsh) && !p.spaced { |
| 2287 |
w.Parts = append(w.Parts, p.wordParts(nil)...) |
| 2288 |
} |
| 2289 |
p.callExpr(s, w, false) |
| 2290 |
} |
| 2291 |
case bckQuote: |
| 2292 |
if p.backquoteEnd() { |
| 2293 |
break |
| 2294 |
} |
| 2295 |
fallthrough |
| 2296 |
case _Lit, dollBrace, dollDblParen, dollParen, dollar, cmdIn, assgnParen, cmdOut, |
| 2297 |
sglQuote, dollSglQuote, dblQuote, dollDblQuote, dollBrack, |
| 2298 |
globQuest, globStar, globPlus, globAt, globExcl: |
| 2299 |
if p.hasValidIdent() { |
| 2300 |
p.callExpr(s, nil, true) |
| 2301 |
break |
| 2302 |
} |
| 2303 |
w := p.wordAnyNumber() |
| 2304 |
if p.got(leftParen) { |
| 2305 |
p.posErr(w.Pos(), "invalid func name") |
| 2306 |
} |
| 2307 |
p.callExpr(s, w, false) |
| 2308 |
case leftParen: |
| 2309 |
if p.r == ')' { |
| 2310 |
p.rune() |
| 2311 |
fpos := p.pos |
| 2312 |
p.next() |
| 2313 |
if p.tok == _LitWord && p.val == "{" { |
| 2314 |
p.checkLang(fpos, LangZsh, "anonymous functions") |
| 2315 |
} |
| 2316 |
p.funcDecl(s, fpos, false, true) |
| 2317 |
break |
| 2318 |
} |
| 2319 |
p.subshell(s) |
| 2320 |
case dblLeftParen: |
| 2321 |
p.arithmExpCmd(s) |
| 2322 |
} |
| 2323 |
if s.Cmd == nil && len(s.Redirs) == 0 { |
| 2324 |
return nil // no statement found |
| 2325 |
} |
| 2326 |
if redirsStart > 0 && s.Cmd != nil { |
| 2327 |
if _, ok := s.Cmd.(*CallExpr); !ok { |
| 2328 |
p.checkLang(s.Pos(), LangZsh, "redirects before compound commands") |
| 2329 |
} |
| 2330 |
} |
| 2331 |
for p.peekRedir() { |
| 2332 |
p.doRedirect(s) |
| 2333 |
} |
| 2334 |
// instead of using recursion, iterate manually |
| 2335 |
for p.tok == or || p.tok == orAnd { |
| 2336 |
if binCmd { |
| 2337 |
// left associativity: in a list of BinaryCmds, the |
| 2338 |
// right recursion should only read a single element |
| 2339 |
return s |
| 2340 |
} |
| 2341 |
if p.tok == orAnd && p.lang.in(LangMirBSDKorn) { |
| 2342 |
// No need to check for LangPOSIX, as on that language |
| 2343 |
// we parse |& as two tokens. |
| 2344 |
break |
| 2345 |
} |
| 2346 |
b := &BinaryCmd{OpPos: p.pos, Op: BinCmdOperator(p.tok), X: s} |
| 2347 |
p.next() |
| 2348 |
p.got(_Newl) |
| 2349 |
if b.Y = p.gotStmtPipe(&Stmt{Position: p.pos}, true); b.Y == nil || p.err != nil { |
| 2350 |
if p.recoverError() { |
| 2351 |
b.Y = &Stmt{Position: recoveredPos} |
| 2352 |
} else { |
| 2353 |
p.followErr(b.OpPos, b.Op, noQuote("a statement")) |
| 2354 |
break |
| 2355 |
} |
| 2356 |
} |
| 2357 |
s = &Stmt{Position: s.Position} |
| 2358 |
s.Cmd = b |
| 2359 |
s.Comments, b.X.Comments = b.X.Comments, nil |
| 2360 |
// in "! x | y", the bang applies to the entire pipeline |
| 2361 |
s.Negated = b.X.Negated |
| 2362 |
b.X.Negated = false |
| 2363 |
} |
| 2364 |
return s |
| 2365 |
} |
| 2366 |
|
| 2367 |
func (p *Parser) subshell(s *Stmt) { |
| 2368 |
sub := &Subshell{Lparen: p.pos} |
| 2369 |
old := p.preNested(subCmd) |
| 2370 |
p.next() |
| 2371 |
sub.Stmts, sub.Last = p.followStmts("(", sub.Lparen) |
| 2372 |
p.postNested(old) |
| 2373 |
sub.Rparen = p.matched(sub.Lparen, leftParen, rightParen) |
| 2374 |
s.Cmd = sub |
| 2375 |
} |
| 2376 |
|
| 2377 |
func (p *Parser) arithmExpCmd(s *Stmt) { |
| 2378 |
ar := &ArithmCmd{Left: p.pos} |
| 2379 |
old := p.preNested(arithmExprCmd) |
| 2380 |
p.next() |
| 2381 |
if p.got(hash) { |
| 2382 |
p.checkLang(ar.Pos(), LangMirBSDKorn, "unsigned expressions") |
| 2383 |
ar.Unsigned = true |
| 2384 |
} |
| 2385 |
ar.X = p.followArithm(dblLeftParen, ar.Left) |
| 2386 |
ar.Right = p.arithmEnd(dblLeftParen, ar.Left, old) |
| 2387 |
s.Cmd = ar |
| 2388 |
} |
| 2389 |
|
| 2390 |
func (p *Parser) block(s *Stmt) { |
| 2391 |
b := &Block{Lbrace: p.pos} |
| 2392 |
p.next() |
| 2393 |
b.Stmts, b.Last = p.followStmts("{", b.Lbrace, "}") |
| 2394 |
if pos, ok := p.gotRsrv("}"); ok { |
| 2395 |
b.Rbrace = pos |
| 2396 |
} else if p.recoverError() { |
| 2397 |
b.Rbrace = recoveredPos |
| 2398 |
} else { |
| 2399 |
p.matchingErr(b.Lbrace, leftBrace, rightBrace) |
| 2400 |
} |
| 2401 |
s.Cmd = b |
| 2402 |
} |
| 2403 |
|
| 2404 |
func (p *Parser) ifClause(s *Stmt) { |
| 2405 |
rootIf := &IfClause{Position: p.pos} |
| 2406 |
p.next() |
| 2407 |
rootIf.Cond, rootIf.CondLast = p.followStmts("if", rootIf.Position, "then") |
| 2408 |
rootIf.ThenPos = p.followRsrv(rootIf.Position, "if <cond>", "then") |
| 2409 |
rootIf.Then, rootIf.ThenLast = p.followStmts("then", rootIf.ThenPos, "fi", "elif", "else") |
| 2410 |
curIf := rootIf |
| 2411 |
for p.tok == _LitWord && p.val == "elif" { |
| 2412 |
elf := &IfClause{Position: p.pos} |
| 2413 |
curIf.Last = p.accComs |
| 2414 |
p.accComs = nil |
| 2415 |
p.next() |
| 2416 |
elf.Cond, elf.CondLast = p.followStmts("elif", elf.Position, "then") |
| 2417 |
elf.ThenPos = p.followRsrv(elf.Position, "elif <cond>", "then") |
| 2418 |
elf.Then, elf.ThenLast = p.followStmts("then", elf.ThenPos, "fi", "elif", "else") |
| 2419 |
curIf.Else = elf |
| 2420 |
curIf = elf |
| 2421 |
} |
| 2422 |
if elsePos, ok := p.gotRsrv("else"); ok { |
| 2423 |
curIf.Last = p.accComs |
| 2424 |
p.accComs = nil |
| 2425 |
els := &IfClause{Position: elsePos} |
| 2426 |
els.Then, els.ThenLast = p.followStmts("else", els.Position, "fi") |
| 2427 |
curIf.Else = els |
| 2428 |
curIf = els |
| 2429 |
} |
| 2430 |
curIf.Last = p.accComs |
| 2431 |
p.accComs = nil |
| 2432 |
rootIf.FiPos = p.stmtEnd(rootIf, "if", "fi") |
| 2433 |
for els := rootIf.Else; els != nil; els = els.Else { |
| 2434 |
// All the nested IfClauses share the same FiPos. |
| 2435 |
els.FiPos = rootIf.FiPos |
| 2436 |
} |
| 2437 |
s.Cmd = rootIf |
| 2438 |
} |
| 2439 |
|
| 2440 |
func (p *Parser) whileClause(s *Stmt, until bool) { |
| 2441 |
wc := &WhileClause{WhilePos: p.pos, Until: until} |
| 2442 |
rsrv := "while" |
| 2443 |
rsrvCond := "while <cond>" |
| 2444 |
if wc.Until { |
| 2445 |
rsrv = "until" |
| 2446 |
rsrvCond = "until <cond>" |
| 2447 |
} |
| 2448 |
p.next() |
| 2449 |
wc.Cond, wc.CondLast = p.followStmts(rsrv, wc.WhilePos, "do") |
| 2450 |
wc.DoPos = p.followRsrv(wc.WhilePos, rsrvCond, "do") |
| 2451 |
wc.Do, wc.DoLast = p.followStmts("do", wc.DoPos, "done") |
| 2452 |
wc.DonePos = p.stmtEnd(wc, rsrv, "done") |
| 2453 |
s.Cmd = wc |
| 2454 |
} |
| 2455 |
|
| 2456 |
func (p *Parser) forClause(s *Stmt) { |
| 2457 |
fc := &ForClause{ForPos: p.pos} |
| 2458 |
p.next() |
| 2459 |
fc.Loop = p.loop(fc.ForPos) |
| 2460 |
|
| 2461 |
start, end := "do", "done" |
| 2462 |
if pos, ok := p.gotRsrv("{"); ok { |
| 2463 |
p.checkLang(pos, langBashLike|LangMirBSDKorn, "for loops with braces") |
| 2464 |
fc.DoPos = pos |
| 2465 |
fc.Braces = true |
| 2466 |
start, end = "{", "}" |
| 2467 |
} else { |
| 2468 |
fc.DoPos = p.followRsrv(fc.ForPos, "for foo [in words]", start) |
| 2469 |
} |
| 2470 |
|
| 2471 |
s.Comments = append(s.Comments, p.accComs...) |
| 2472 |
p.accComs = nil |
| 2473 |
fc.Do, fc.DoLast = p.followStmts(start, fc.DoPos, end) |
| 2474 |
fc.DonePos = p.stmtEnd(fc, "for", end) |
| 2475 |
s.Cmd = fc |
| 2476 |
} |
| 2477 |
|
| 2478 |
func (p *Parser) loop(fpos Pos) Loop { |
| 2479 |
switch p.tok { |
| 2480 |
case leftParen, dblLeftParen: |
| 2481 |
p.checkLang(p.pos, langBashLike|LangZsh, "c-style fors") |
| 2482 |
} |
| 2483 |
if p.tok == dblLeftParen { |
| 2484 |
cl := &CStyleLoop{Lparen: p.pos} |
| 2485 |
old := p.preNested(arithmExprCmd) |
| 2486 |
p.next() |
| 2487 |
cl.Init = p.arithmExpr(false) |
| 2488 |
if !p.got(dblSemicolon) { |
| 2489 |
p.follow(p.pos, "expr", semicolon) |
| 2490 |
cl.Cond = p.arithmExpr(false) |
| 2491 |
p.follow(p.pos, "expr", semicolon) |
| 2492 |
} |
| 2493 |
cl.Post = p.arithmExpr(false) |
| 2494 |
cl.Rparen = p.arithmEnd(dblLeftParen, cl.Lparen, old) |
| 2495 |
p.got(semicolon) |
| 2496 |
p.got(_Newl) |
| 2497 |
return cl |
| 2498 |
} |
| 2499 |
return p.wordIter("for", fpos) |
| 2500 |
} |
| 2501 |
|
| 2502 |
func (p *Parser) wordIter(ftok string, fpos Pos) *WordIter { |
| 2503 |
wi := &WordIter{} |
| 2504 |
if wi.Name = p.getLit(); wi.Name == nil { |
| 2505 |
p.followErr(fpos, ftok, noQuote("a literal")) |
| 2506 |
} |
| 2507 |
if p.got(semicolon) { |
| 2508 |
p.got(_Newl) |
| 2509 |
return wi |
| 2510 |
} |
| 2511 |
p.got(_Newl) |
| 2512 |
if pos, ok := p.gotRsrv("in"); ok { |
| 2513 |
wi.InPos = pos |
| 2514 |
for !p.stopToken() { |
| 2515 |
if w := p.getWord(); w == nil { |
| 2516 |
p.curErr("word list can only contain words") |
| 2517 |
} else { |
| 2518 |
wi.Items = append(wi.Items, w) |
| 2519 |
} |
| 2520 |
} |
| 2521 |
p.got(semicolon) |
| 2522 |
p.got(_Newl) |
| 2523 |
} else if p.tok == _LitWord && p.val == "do" { |
| 2524 |
} else { |
| 2525 |
p.followErr(fpos, ftok+" foo", noQuote("`in`, `do`, `;`, or a newline")) |
| 2526 |
} |
| 2527 |
return wi |
| 2528 |
} |
| 2529 |
|
| 2530 |
func (p *Parser) selectClause(s *Stmt) { |
| 2531 |
fc := &ForClause{ForPos: p.pos, Select: true} |
| 2532 |
p.next() |
| 2533 |
fc.Loop = p.wordIter("select", fc.ForPos) |
| 2534 |
fc.DoPos = p.followRsrv(fc.ForPos, "select foo [in words]", "do") |
| 2535 |
fc.Do, fc.DoLast = p.followStmts("do", fc.DoPos, "done") |
| 2536 |
fc.DonePos = p.stmtEnd(fc, "select", "done") |
| 2537 |
s.Cmd = fc |
| 2538 |
} |
| 2539 |
|
| 2540 |
func (p *Parser) caseClause(s *Stmt) { |
| 2541 |
cc := &CaseClause{Case: p.pos} |
| 2542 |
p.next() |
| 2543 |
cc.Word = p.getWord() |
| 2544 |
if cc.Word == nil { |
| 2545 |
p.followErr(cc.Case, "case", noQuote("a word")) |
| 2546 |
} |
| 2547 |
end := "esac" |
| 2548 |
p.got(_Newl) |
| 2549 |
if pos, ok := p.gotRsrv("{"); ok { |
| 2550 |
cc.In = pos |
| 2551 |
cc.Braces = true |
| 2552 |
p.checkLang(cc.Pos(), LangMirBSDKorn, "`case i {`") |
| 2553 |
end = "}" |
| 2554 |
} else { |
| 2555 |
cc.In = p.followRsrv(cc.Case, "case x", "in") |
| 2556 |
} |
| 2557 |
cc.Items = p.caseItems(end) |
| 2558 |
cc.Last, p.accComs = p.accComs, nil |
| 2559 |
cc.Esac = p.stmtEnd(cc, "case", end) |
| 2560 |
s.Cmd = cc |
| 2561 |
} |
| 2562 |
|
| 2563 |
func (p *Parser) caseItems(stop string) (items []*CaseItem) { |
| 2564 |
p.got(_Newl) |
| 2565 |
for p.tok != _EOF && (p.tok != _LitWord || p.val != stop) { |
| 2566 |
ci := &CaseItem{} |
| 2567 |
ci.Comments, p.accComs = p.accComs, nil |
| 2568 |
p.got(leftParen) |
| 2569 |
for p.tok != _EOF { |
| 2570 |
if w := p.getWord(); w == nil { |
| 2571 |
p.curErr("case patterns must consist of words") |
| 2572 |
} else { |
| 2573 |
ci.Patterns = append(ci.Patterns, w) |
| 2574 |
} |
| 2575 |
if p.tok == rightParen { |
| 2576 |
break |
| 2577 |
} |
| 2578 |
if !p.got(or) { |
| 2579 |
p.curErr("case patterns must be separated with %#q", or) |
| 2580 |
} |
| 2581 |
} |
| 2582 |
old := p.preNested(switchCase) |
| 2583 |
p.next() |
| 2584 |
ci.Stmts, ci.Last = p.stmtList(stop) |
| 2585 |
p.postNested(old) |
| 2586 |
switch p.tok { |
| 2587 |
case dblSemicolon, semiAnd, dblSemiAnd, semiOr: |
| 2588 |
default: |
| 2589 |
ci.Op = Break |
| 2590 |
items = append(items, ci) |
| 2591 |
return items |
| 2592 |
} |
| 2593 |
ci.Last = append(ci.Last, p.accComs...) |
| 2594 |
p.accComs = nil |
| 2595 |
ci.OpPos = p.pos |
| 2596 |
ci.Op = CaseOperator(p.tok) |
| 2597 |
p.next() |
| 2598 |
p.got(_Newl) |
| 2599 |
|
| 2600 |
// Split the comments: |
| 2601 |
// |
| 2602 |
// case x in |
| 2603 |
// a) |
| 2604 |
// foo |
| 2605 |
// ;; |
| 2606 |
// # comment for a |
| 2607 |
// # comment for b |
| 2608 |
// b) |
| 2609 |
// [...] |
| 2610 |
split := len(p.accComs) |
| 2611 |
for i, c := range slices.Backward(p.accComs) { |
| 2612 |
if c.Pos().Col() != p.pos.Col() { |
| 2613 |
break |
| 2614 |
} |
| 2615 |
split = i |
| 2616 |
} |
| 2617 |
ci.Comments = append(ci.Comments, p.accComs[:split]...) |
| 2618 |
p.accComs = p.accComs[split:] |
| 2619 |
|
| 2620 |
items = append(items, ci) |
| 2621 |
} |
| 2622 |
return items |
| 2623 |
} |
| 2624 |
|
| 2625 |
func (p *Parser) testClause(s *Stmt) { |
| 2626 |
tc := &TestClause{Left: p.pos} |
| 2627 |
old := p.preNested(testExpr) |
| 2628 |
p.next() |
| 2629 |
if tc.X = p.testExprBinary(false); tc.X == nil { |
| 2630 |
p.followErrExp(tc.Left, dblLeftBrack) |
| 2631 |
} |
| 2632 |
tc.Right = p.pos |
| 2633 |
if _, ok := p.gotRsrv("]]"); !ok { |
| 2634 |
p.matchingErr(tc.Left, dblLeftBrack, dblRightBrack) |
| 2635 |
} |
| 2636 |
p.postNested(old) |
| 2637 |
s.Cmd = tc |
| 2638 |
} |
| 2639 |
|
| 2640 |
func (p *Parser) testExprBinary(pastAndOr bool) TestExpr { |
| 2641 |
p.got(_Newl) |
| 2642 |
var left TestExpr |
| 2643 |
if pastAndOr { |
| 2644 |
left = p.testExprUnary() |
| 2645 |
} else { |
| 2646 |
left = p.testExprBinary(true) |
| 2647 |
} |
| 2648 |
if left == nil { |
| 2649 |
return left |
| 2650 |
} |
| 2651 |
p.got(_Newl) |
| 2652 |
switch p.tok { |
| 2653 |
case andAnd, orOr: |
| 2654 |
case _LitWord: |
| 2655 |
if p.val == "]]" { |
| 2656 |
return left |
| 2657 |
} |
| 2658 |
if p.tok = token(testBinaryOp(p.val)); p.tok == illegalTok { |
| 2659 |
p.curErr("not a valid test operator: %#q", p.val) |
| 2660 |
} |
| 2661 |
case rdrIn, rdrOut: |
| 2662 |
case _EOF, rightParen: |
| 2663 |
return left |
| 2664 |
case _Lit: |
| 2665 |
p.curErr("test operator words must consist of a single literal") |
| 2666 |
default: |
| 2667 |
p.curErr("not a valid test operator: %#q", p.tok) |
| 2668 |
} |
| 2669 |
b := &BinaryTest{ |
| 2670 |
OpPos: p.pos, |
| 2671 |
Op: BinTestOperator(p.tok), |
| 2672 |
X: left, |
| 2673 |
} |
| 2674 |
switch b.Op { |
| 2675 |
case AndTest, OrTest: |
| 2676 |
p.next() |
| 2677 |
if b.Y = p.testExprBinary(false); b.Y == nil { |
| 2678 |
p.followErrExp(b.OpPos, b.Op) |
| 2679 |
} |
| 2680 |
case TsReMatch: |
| 2681 |
p.checkLang(p.pos, langBashLike|LangZsh, "regex tests") |
| 2682 |
p.rxOpenParens = 0 |
| 2683 |
p.rxFirstPart = true |
| 2684 |
// TODO(mvdan): Using nested states within a regex will break in |
| 2685 |
// all sorts of ways. The better fix is likely to use a stop |
| 2686 |
// token, like we do with heredocs. |
| 2687 |
p.quote = testExprRegexp |
| 2688 |
fallthrough |
| 2689 |
default: |
| 2690 |
if _, ok := b.X.(*Word); !ok { |
| 2691 |
p.posErr(b.OpPos, "expected %#q, %#q or %#q after complex expr", |
| 2692 |
AndTest, OrTest, dblRightBrack) |
| 2693 |
} |
| 2694 |
p.next() |
| 2695 |
b.Y = p.followWordTok(token(b.Op), b.OpPos) |
| 2696 |
} |
| 2697 |
return b |
| 2698 |
} |
| 2699 |
|
| 2700 |
func (p *Parser) testExprUnary() TestExpr { |
| 2701 |
switch p.tok { |
| 2702 |
case _EOF, rightParen: |
| 2703 |
return nil |
| 2704 |
case _LitWord: |
| 2705 |
op := token(testUnaryOp(p.val)) |
| 2706 |
switch op { |
| 2707 |
case illegalTok: |
| 2708 |
case tsRefVar, tsModif: // not available in mksh |
| 2709 |
if p.lang.in(langBashLike) { |
| 2710 |
p.tok = op |
| 2711 |
} |
| 2712 |
default: |
| 2713 |
p.tok = op |
| 2714 |
} |
| 2715 |
} |
| 2716 |
switch p.tok { |
| 2717 |
case exclMark: |
| 2718 |
u := &UnaryTest{OpPos: p.pos, Op: TsNot} |
| 2719 |
p.next() |
| 2720 |
if u.X = p.testExprBinary(false); u.X == nil { |
| 2721 |
p.followErrExp(u.OpPos, u.Op) |
| 2722 |
} |
| 2723 |
return u |
| 2724 |
case tsExists, tsRegFile, tsDirect, tsCharSp, tsBlckSp, tsNmPipe, |
| 2725 |
tsSocket, tsSmbLink, tsSticky, tsGIDSet, tsUIDSet, tsGrpOwn, |
| 2726 |
tsUsrOwn, tsModif, tsRead, tsWrite, tsExec, tsNoEmpty, |
| 2727 |
tsFdTerm, tsEmpStr, tsNempStr, tsOptSet, tsVarSet, tsRefVar: |
| 2728 |
u := &UnaryTest{OpPos: p.pos, Op: UnTestOperator(p.tok)} |
| 2729 |
p.next() |
| 2730 |
u.X = p.followWordTok(token(u.Op), u.OpPos) |
| 2731 |
return u |
| 2732 |
case leftParen: |
| 2733 |
pe := &ParenTest{Lparen: p.pos} |
| 2734 |
p.next() |
| 2735 |
if pe.X = p.testExprBinary(false); pe.X == nil { |
| 2736 |
p.followErrExp(pe.Lparen, leftParen) |
| 2737 |
} |
| 2738 |
pe.Rparen = p.matched(pe.Lparen, leftParen, rightParen) |
| 2739 |
return pe |
| 2740 |
case _LitWord: |
| 2741 |
if p.val == "]]" { |
| 2742 |
return nil |
| 2743 |
} |
| 2744 |
fallthrough |
| 2745 |
default: |
| 2746 |
if w := p.getWord(); w != nil { |
| 2747 |
return w |
| 2748 |
} |
| 2749 |
// otherwise we'd return a typed nil above |
| 2750 |
return nil |
| 2751 |
} |
| 2752 |
} |
| 2753 |
|
| 2754 |
func (p *Parser) declClause(s *Stmt) { |
| 2755 |
ds := &DeclClause{Variant: p.lit(p.pos, p.val)} |
| 2756 |
p.next() |
| 2757 |
for !p.stopToken() && !p.peekRedir() { |
| 2758 |
if p.hasValidIdent() { |
| 2759 |
ds.Args = append(ds.Args, p.getAssign(false)) |
| 2760 |
} else if p.tok.isLit() && p.eqlOffs > 0 && !strings.Contains(p.val[:p.eqlOffs], "{") { |
| 2761 |
p.curErr("invalid var name") |
| 2762 |
} else if p.tok == _LitWord && ValidName(p.val) { |
| 2763 |
ds.Args = append(ds.Args, &Assign{ |
| 2764 |
Naked: true, |
| 2765 |
Name: p.getLit(), |
| 2766 |
}) |
| 2767 |
} else if w := p.getWord(); w != nil { |
| 2768 |
ds.Args = append(ds.Args, &Assign{ |
| 2769 |
Naked: true, |
| 2770 |
Value: w, |
| 2771 |
}) |
| 2772 |
} else { |
| 2773 |
p.followErr(p.pos, ds.Variant.Value, noQuote("names or assignments")) |
| 2774 |
} |
| 2775 |
} |
| 2776 |
s.Cmd = ds |
| 2777 |
} |
| 2778 |
|
| 2779 |
func isBashCompoundCommand(tok token, val string) bool { |
| 2780 |
switch tok { |
| 2781 |
case leftParen, dblLeftParen: |
| 2782 |
return true |
| 2783 |
case _LitWord: |
| 2784 |
switch val { |
| 2785 |
case "{", "if", "while", "until", "for", "case", "[[", |
| 2786 |
"coproc", "let", "function", "declare", "local", |
| 2787 |
"export", "readonly", "typeset", "nameref": |
| 2788 |
return true |
| 2789 |
} |
| 2790 |
} |
| 2791 |
return false |
| 2792 |
} |
| 2793 |
|
| 2794 |
func (p *Parser) timeClause(s *Stmt) { |
| 2795 |
tc := &TimeClause{Time: p.pos} |
| 2796 |
p.next() |
| 2797 |
if _, ok := p.gotRsrv("-p"); ok { |
| 2798 |
tc.PosixFormat = true |
| 2799 |
} |
| 2800 |
tc.Stmt = p.gotStmtPipe(&Stmt{Position: p.pos}, false) |
| 2801 |
s.Cmd = tc |
| 2802 |
} |
| 2803 |
|
| 2804 |
func (p *Parser) coprocClause(s *Stmt) { |
| 2805 |
cc := &CoprocClause{Coproc: p.pos} |
| 2806 |
if p.next(); isBashCompoundCommand(p.tok, p.val) { |
| 2807 |
// has no name |
| 2808 |
cc.Stmt = p.gotStmtPipe(&Stmt{Position: p.pos}, false) |
| 2809 |
s.Cmd = cc |
| 2810 |
return |
| 2811 |
} |
| 2812 |
cc.Name = p.getWord() |
| 2813 |
cc.Stmt = p.gotStmtPipe(&Stmt{Position: p.pos}, false) |
| 2814 |
if cc.Stmt == nil { |
| 2815 |
if cc.Name == nil { |
| 2816 |
p.posErr(cc.Coproc, "coproc clause requires a command") |
| 2817 |
return |
| 2818 |
} |
| 2819 |
// name was in fact the stmt |
| 2820 |
cc.Stmt = &Stmt{Position: cc.Name.Pos()} |
| 2821 |
cc.Stmt.Cmd = p.call(cc.Name) |
| 2822 |
cc.Name = nil |
| 2823 |
} else if cc.Name != nil { |
| 2824 |
if call, ok := cc.Stmt.Cmd.(*CallExpr); ok { |
| 2825 |
// name was in fact the start of a call |
| 2826 |
call.Args = append([]*Word{cc.Name}, call.Args...) |
| 2827 |
cc.Name = nil |
| 2828 |
} |
| 2829 |
} |
| 2830 |
s.Cmd = cc |
| 2831 |
} |
| 2832 |
|
| 2833 |
func (p *Parser) letClause(s *Stmt) { |
| 2834 |
lc := &LetClause{Let: p.pos} |
| 2835 |
old := p.preNested(arithmExprLet) |
| 2836 |
p.next() |
| 2837 |
for !p.stopToken() && !p.peekRedir() { |
| 2838 |
x := p.arithmExpr(true) |
| 2839 |
if x == nil { |
| 2840 |
break |
| 2841 |
} |
| 2842 |
lc.Exprs = append(lc.Exprs, x) |
| 2843 |
} |
| 2844 |
if len(lc.Exprs) == 0 { |
| 2845 |
p.followErrExp(lc.Let, "let") |
| 2846 |
} |
| 2847 |
p.postNested(old) |
| 2848 |
s.Cmd = lc |
| 2849 |
} |
| 2850 |
|
| 2851 |
func (p *Parser) bashFuncDecl(s *Stmt) { |
| 2852 |
fpos := p.pos |
| 2853 |
p.next() |
| 2854 |
names := make([]*Lit, 0, 1) |
| 2855 |
for p.tok == _LitWord && p.val != "{" { |
| 2856 |
names = append(names, p.lit(p.pos, p.val)) |
| 2857 |
p.next() |
| 2858 |
} |
| 2859 |
hasParens := p.got(leftParen) |
| 2860 |
switch len(names) { |
| 2861 |
case 0: |
| 2862 |
if hasParens || (p.tok == _LitWord && p.val == "{") { |
| 2863 |
p.checkLang(fpos, LangZsh, "anonymous functions") |
| 2864 |
} else if !p.lang.in(LangZsh) { |
| 2865 |
p.followErr(fpos, "function", noQuote("a name")) |
| 2866 |
} |
| 2867 |
names = nil // avoid non-nil zero-length slices |
| 2868 |
case 1: |
| 2869 |
// allowed in all variants |
| 2870 |
default: |
| 2871 |
p.checkLang(fpos, LangZsh, "multi-name functions") |
| 2872 |
} |
| 2873 |
if hasParens { |
| 2874 |
p.follow(fpos, "function foo(", rightParen) |
| 2875 |
} |
| 2876 |
p.funcDecl(s, fpos, true, hasParens, names...) |
| 2877 |
} |
| 2878 |
|
| 2879 |
func (p *Parser) testDecl(s *Stmt) { |
| 2880 |
td := &TestDecl{Position: p.pos} |
| 2881 |
p.next() |
| 2882 |
if td.Description = p.getWord(); td.Description == nil { |
| 2883 |
p.followErr(td.Position, "@test", noQuote("a description word")) |
| 2884 |
} |
| 2885 |
if td.Body = p.getStmt(false, false, true); td.Body == nil { |
| 2886 |
p.followErr(td.Position, `@test "desc"`, noQuote("a statement")) |
| 2887 |
} |
| 2888 |
s.Cmd = td |
| 2889 |
} |
| 2890 |
|
| 2891 |
func (p *Parser) unexpectedInCallExpr(ce *CallExpr) { |
| 2892 |
// Note that we'll only keep the first error that happens. |
| 2893 |
if len(ce.Args) > 0 { |
| 2894 |
if cmd := ce.Args[0].Lit(); isBashCompoundCommand(_LitWord, cmd) { |
| 2895 |
p.checkLang(p.pos, langBashLike, "the %#q builtin", cmd) |
| 2896 |
} |
| 2897 |
} |
| 2898 |
p.curErr("a command can only contain words and redirects; encountered %#q", p.tok) |
| 2899 |
} |
| 2900 |
|
| 2901 |
func (p *Parser) callExpr(s *Stmt, w *Word, assign bool) { |
| 2902 |
ce := p.call(w) |
| 2903 |
if w == nil { |
| 2904 |
ce.Args = ce.Args[:0] |
| 2905 |
} |
| 2906 |
if assign { |
| 2907 |
ce.Assigns = append(ce.Assigns, p.getAssign(true)) |
| 2908 |
} |
| 2909 |
loop: |
| 2910 |
for { |
| 2911 |
switch p.tok { |
| 2912 |
case _EOF, _Newl, semicolon, and, or, andAnd, orOr, orAnd, andPipe, andBang, |
| 2913 |
dblSemicolon, semiAnd, dblSemiAnd, semiOr: |
| 2914 |
break loop |
| 2915 |
case _LitWord: |
| 2916 |
if len(ce.Args) == 0 && p.hasValidIdent() { |
| 2917 |
ce.Assigns = append(ce.Assigns, p.getAssign(true)) |
| 2918 |
break |
| 2919 |
} |
| 2920 |
// Avoid failing later with the confusing "} can only be used to close a block". |
| 2921 |
if p.val == "{" && w != nil && w.Lit() == "function" { |
| 2922 |
p.checkLang(p.pos, langBashLike, `the "function" builtin`) |
| 2923 |
} |
| 2924 |
// Zsh does not require a semicolon to close a block. |
| 2925 |
if p.lang.in(LangZsh) && p.val == "}" { |
| 2926 |
break loop |
| 2927 |
} |
| 2928 |
w := p.wordOne(p.lit(p.pos, p.val)) |
| 2929 |
p.next() |
| 2930 |
if p.lang.in(LangZsh) && !p.spaced { |
| 2931 |
w.Parts = append(w.Parts, p.wordParts(nil)...) |
| 2932 |
} |
| 2933 |
ce.Args = append(ce.Args, w) |
| 2934 |
case _Lit: |
| 2935 |
if len(ce.Args) == 0 && p.hasValidIdent() { |
| 2936 |
ce.Assigns = append(ce.Assigns, p.getAssign(true)) |
| 2937 |
break |
| 2938 |
} |
| 2939 |
ce.Args = append(ce.Args, p.wordAnyNumber()) |
| 2940 |
case bckQuote: |
| 2941 |
if p.backquoteEnd() { |
| 2942 |
break loop |
| 2943 |
} |
| 2944 |
fallthrough |
| 2945 |
case dollBrace, dollDblParen, dollParen, dollar, cmdIn, assgnParen, cmdOut, |
| 2946 |
sglQuote, dollSglQuote, dblQuote, dollDblQuote, dollBrack, |
| 2947 |
globQuest, globStar, globPlus, globAt, globExcl: |
| 2948 |
ce.Args = append(ce.Args, p.wordAnyNumber()) |
| 2949 |
case dblLeftParen: |
| 2950 |
p.curErr("%#q can only be used to open an arithmetic cmd", p.tok) |
| 2951 |
case leftParen: |
| 2952 |
if p.lang.in(LangZsh) && p.r != ')' { |
| 2953 |
ce.Args = append(ce.Args, p.wordAnyNumber()) |
| 2954 |
break |
| 2955 |
} |
| 2956 |
p.unexpectedInCallExpr(ce) |
| 2957 |
case rightParen: |
| 2958 |
if p.quote == subCmd { |
| 2959 |
break loop |
| 2960 |
} |
| 2961 |
p.unexpectedInCallExpr(ce) |
| 2962 |
default: |
| 2963 |
if p.peekRedir() { |
| 2964 |
p.doRedirect(s) |
| 2965 |
continue |
| 2966 |
} |
| 2967 |
p.unexpectedInCallExpr(ce) |
| 2968 |
} |
| 2969 |
} |
| 2970 |
if len(ce.Args) == 0 { |
| 2971 |
ce.Args = nil |
| 2972 |
} else { |
| 2973 |
for _, asgn := range ce.Assigns { |
| 2974 |
if asgn.Index != nil || asgn.Array != nil { |
| 2975 |
p.posErr(asgn.Pos(), "inline variables cannot be arrays") |
| 2976 |
} |
| 2977 |
} |
| 2978 |
} |
| 2979 |
s.Cmd = ce |
| 2980 |
} |
| 2981 |
|
| 2982 |
func (p *Parser) funcDecl(s *Stmt, pos Pos, long, withParens bool, names ...*Lit) { |
| 2983 |
fd := &FuncDecl{ |
| 2984 |
Position: pos, |
| 2985 |
RsrvWord: long, |
| 2986 |
Parens: withParens, |
| 2987 |
} |
| 2988 |
if len(names) == 1 { |
| 2989 |
fd.Name = names[0] |
| 2990 |
} else { |
| 2991 |
fd.Names = names |
| 2992 |
} |
| 2993 |
p.got(_Newl) |
| 2994 |
// TODO: reject any body which isn't a compound command, like a quoted word |
| 2995 |
if fd.Body = p.getStmt(false, false, true); fd.Body == nil { |
| 2996 |
p.followErr(fd.Pos(), "foo()", noQuote("a statement")) |
| 2997 |
} |
| 2998 |
s.Cmd = fd |
| 2999 |
} |