// Copyright (c) 2016, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information

package syntax

import (
	
	
	
	
	
	
	
)

// ParserOption is a function which can be passed to NewParser
// to alter its behavior. To apply option to existing Parser
// call it directly, for example KeepComments(true)(parser).
type ParserOption func(*Parser)

// KeepComments makes the parser parse comments and attach them to
// nodes, as opposed to discarding them.
func ( bool) ParserOption {
	return func( *Parser) { .keepComments =  }
}

// LangVariant describes a shell language variant to use when tokenizing and
// parsing shell code. The zero value is [LangBash].
//
// This type implements [flag.Value] so that it can be used as a CLI flag.
type LangVariant int

// TODO(v4): the zero value should be left as an unset and invalid value.
// TODO(v4): the type should be uint32 now that we use this as a bitset;
// an unsigned integer is clearer, and being agnostic to uint size avoids issues.

const (
	// LangBash corresponds to the GNU Bash language, as described in its
	// manual at https://www.gnu.org/software/bash/manual/bash.html.
	//
	// We currently follow Bash version 5.2.
	//
	// Its string representation is "bash".
	LangBash LangVariant = 1 << iota

	// LangPOSIX corresponds to the POSIX Shell language, as described at
	// https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html.
	//
	// Its string representation is "posix" or "sh".
	LangPOSIX

	// LangMirBSDKorn corresponds to the MirBSD Korn Shell, also known as
	// mksh, as described at http://www.mirbsd.org/htman/i386/man1/mksh.htm.
	// Note that it shares some features with Bash, due to the shared
	// ancestry that is ksh.
	//
	// We currently follow mksh version 59.
	//
	// Its string representation is "mksh".
	LangMirBSDKorn

	// LangBats corresponds to the Bash Automated Testing System language,
	// as described at https://github.com/bats-core/bats-core. Note that
	// it's just a small extension of the Bash language.
	//
	// Its string representation is "bats".
	LangBats

	// LangZsh corresponds to the Z shell, as described at https://www.zsh.org/.
	//
	// Note that its support in the syntax package is experimental and
	// incomplete for now. See https://github.com/mvdan/sh/issues/120.
	//
	// We currently follow Zsh version 5.9.
	//
	// Its string representation is "zsh".
	LangZsh

	// langResolvedVariantsCount is the number of variants declared above,
	// that is, langResolvedVariants.count() as a constant.
	langResolvedVariantsCount = iota

	// LangAuto corresponds to automatic language detection,
	// commonly used by end-user applications like shfmt,
	// which can guess a file's language variant given its filename or shebang.
	//
	// At this time, [Variant] does not support LangAuto.
	LangAuto LangVariant = 1 << langResolvedVariantsCount

	// langBashLegacy is what [LangBash] used to be, when it was zero.
	// We still support it for the sake of backwards compatibility.
	langBashLegacy LangVariant = 0

	// langResolvedVariants contains all known variants except [LangAuto],
	// which is meant to resolve to another variant.
	langResolvedVariants = LangBash | LangPOSIX | LangMirBSDKorn | LangBats | LangZsh

	// langBashLike contains Bash plus all variants which are extensions of it.
	langBashLike = LangBash | LangBats
)

// Variant changes the shell language variant that the parser will
// accept.
//
// The passed language variant must be one of the constant values defined in
// this package.
func ( LangVariant) ParserOption {
	switch  {
	case langBashLegacy:
		 = LangBash
	case LangBash, LangPOSIX, LangMirBSDKorn, LangBats, LangZsh:
	case LangAuto:
		panic("LangAuto is not supported by the parser at this time")
	default:
		panic(fmt.Sprintf("unknown shell language variant: %#b", ))
	}
	return func( *Parser) { .lang =  }
}

func ( LangVariant) () string {
	switch  {
	case langBashLegacy, LangBash:
		return "bash"
	case LangPOSIX:
		return "posix"
	case LangMirBSDKorn:
		return "mksh"
	case LangBats:
		return "bats"
	case LangZsh:
		return "zsh"
	case LangAuto:
		return "auto"
	}
	return "unknown shell language variant"
}

func ( *LangVariant) ( string) error {
	switch  {
	case "bash":
		* = LangBash
	case "posix", "sh", "dash":
		* = LangPOSIX
	case "mksh":
		* = LangMirBSDKorn
	case "bats":
		* = LangBats
	case "zsh":
		* = LangZsh
	case "auto":
		* = LangAuto
	default:
		return fmt.Errorf("unknown shell language variant: %q", )
	}
	return nil
}

func ( LangVariant) ( LangVariant) bool {
	return & == 
}

func ( LangVariant) () int {
	return bits.OnesCount32(uint32())
}

func ( LangVariant) () int {
	return bits.TrailingZeros32(uint32())
}

func ( LangVariant) () iter.Seq[LangVariant] {
	return func( func(LangVariant) bool) {
		for  := LangVariant(1);  < langResolvedVariants;  <<= 1 {
			if & == 0 {
				continue
			}
			if !() {
				return
			}
		}
	}
}

// StopAt configures the lexer to stop at an arbitrary word, treating it
// as if it were the end of the input. It can contain any characters
// except whitespace, and cannot be over four bytes in size.
//
// This can be useful to embed shell code within another language, as
// one can use a special word to mark the delimiters between the two.
//
// As a word, it will only apply when following whitespace or a
// separating token. For example, StopAt("$$") will act on the inputs
// "foo $$" and "foo;$$", but not on "foo '$$'".
//
// The match is done by prefix, so the example above will also act on
// "foo $$bar".
func ( string) ParserOption {
	if len() > 4 {
		panic("stop word can't be over four bytes in size")
	}
	if strings.ContainsAny(, " \t\n\r") {
		panic("stop word can't contain whitespace characters")
	}
	return func( *Parser) { .stopAt = []byte() }
}

// RecoverErrors allows the parser to skip up to a maximum number of
// errors in the given input on a best-effort basis.
// This can be useful to tab-complete an interactive shell prompt,
// or when providing diagnostics on slightly incomplete shell source.
//
// Currently, this only helps with mandatory tokens from the shell grammar
// which are not present in the input. They result in position fields
// or nodes whose position report [Pos.IsRecovered] as true.
//
// For example, given the input
//
//	(foo |
//
// the result will contain two recovered positions; first, the pipe requires
// a statement to follow, and as [Stmt.Pos] reports, the entire node is recovered.
// Second, the subshell needs to be closed, so [Subshell.Rparen] is recovered.
func ( int) ParserOption {
	return func( *Parser) { .recoverErrorsMax =  }
}

// NewParser allocates a new [Parser] and applies any number of options.
func ( ...ParserOption) *Parser {
	 := &Parser{
		lang: LangBash,
	}
	for ,  := range  {
		()
	}
	return 
}

// Parse reads and parses a shell program with an optional name. It
// returns the parsed program if no issues were encountered. Otherwise,
// an error is returned. Reads from r are buffered.
//
// Parse can be called more than once, but not concurrently. That is, a
// Parser can be reused once it is done working.
func ( *Parser) ( io.Reader,  string) (*File, error) {
	.reset()
	.f = &File{Name: }
	.src = 
	.rune()
	.next()
	.f.Stmts, .f.Last = .stmtList()
	if .err == nil {
		// EOF immediately after heredoc word so no newline to
		// trigger the parsing error.
		.doHeredocs()
	}
	return .f, .err
}

// Stmts is a pre-iterators API which now wraps [Parser.StmtsSeq].
//
// Deprecated: use [Parser.StmtsSeq].
func ( *Parser) ( io.Reader,  func(*Stmt) bool) error {
	for ,  := range .StmtsSeq() {
		if  != nil {
			return 
		}
		if !() {
			break
		}
	}
	return nil
}

// StmtsSeq reads and parses statements one at a time via an iterator.
func ( *Parser) ( io.Reader) iter.Seq2[*Stmt, error] {
	.reset()
	.f = &File{}
	.src = 
	return func( func(*Stmt, error) bool) {
		.rune()
		.next()
		.stmts()
		if .err == nil {
			// EOF immediately after heredoc word so no newline to
			// trigger the parsing error.
			.doHeredocs()
		}
		if .err != nil {
			// Yield any final error from the parser.
			(nil, .err)
		}
	}
}

type wrappedReader struct {
	p  *Parser
	rd io.Reader

	lastLine    int64
	accumulated []*Stmt
	yield       func([]*Stmt, error) bool
}

func ( *wrappedReader) ( []byte) ( int,  error) {
	// If we lexed a newline for the first time, we just finished a line, so
	// we may need to give a callback for the edge cases below not covered
	// by [Parser.Stmts].
	if (.p.r == '\n' || .p.r == escNewl) && .p.line > .lastLine {
		if .p.Incomplete() {
			// Incomplete statement; call back to print "> ".
			if !.yield(.accumulated, .p.err) {
				return 0, io.EOF
			}
		} else if len(.accumulated) == 0 {
			// Nothing was parsed; call back to print another "$ ".
			if !.yield(nil, .p.err) {
				return 0, io.EOF
			}
		}
		.lastLine = .p.line
	}
	return .rd.Read()
}

// Interactive is a pre-iterators API which now wraps [Parser.InteractiveSeq].
//
// Deprecated: use [Parser.InteractiveSeq].
func ( *Parser) ( io.Reader,  func([]*Stmt) bool) error {
	for ,  := range .InteractiveSeq() {
		if  != nil {
			return 
		}
		if !() {
			break
		}
	}
	return nil
}

// InteractiveSeq implements what is necessary to parse statements in an
// interactive shell. The parser will call the given function under two
// circumstances outlined below.
//
// If a line containing any number of statements is parsed, the function will be
// called with said statements.
//
// If a line ending in an incomplete statement is parsed, the function will be
// called with any fully parsed statements, and [Parser.Incomplete] will return true.
//
// One can imagine a simple interactive shell implementation as follows:
//
//	fmt.Fprintf(os.Stdout, "$ ")
//	parser.Interactive(os.Stdin, func(stmts []*syntax.Stmt) bool {
//		if parser.Incomplete() {
//			fmt.Fprintf(os.Stdout, "> ")
//			return true
//		}
//		run(stmts)
//		fmt.Fprintf(os.Stdout, "$ ")
//		return true
//	}
//
// If the callback function returns false, parsing is stopped and the function
// is not called again.
func ( *Parser) ( io.Reader) iter.Seq2[[]*Stmt, error] {
	return func( func([]*Stmt, error) bool) {
		 := wrappedReader{p: , rd: , yield: }
		for ,  := range .StmtsSeq(&) {
			.accumulated = append(.accumulated, )
			if  != nil {
				if !(.accumulated, ) {
					break
				}
				// If the caller wishes, they can continue in the presence of parse errors.
				// TODO: does this even work? Write tests for it. This only came up
				continue
			}
			// We finished parsing a statement and we're at a newline token,
			// so we finished fully parsing a number of statements. Call
			// back to run the statements and print "$ ".
			if .tok == _Newl {
				if !(.accumulated, nil) {
					break
				}
				.accumulated = .accumulated[:0]
				// The callback above would already print "$ ", so we
				// don't want the subsequent wrappedReader.Read to cause
				// another "$ " print thinking that nothing was parsed.
				.lastLine = .p.line + 1
			}
		}
	}
}

// Words is a pre-iterators API which now wraps [Parser.WordsSeq].
//
// Deprecated: use [Parser.WordsSeq].
func ( *Parser) ( io.Reader,  func(*Word) bool) error {
	for ,  := range .WordsSeq() {
		if  != nil {
			return 
		}
		if !() {
			break
		}
	}
	return nil
}

// WordsSeq reads and parses a sequence of words alongside any error encountered.
//
// Newlines are skipped, meaning that multi-line input will work fine. If the
// parser encounters a token that isn't a word, such as a semicolon, an error
// will be returned.
//
// Note that the lexer doesn't currently tokenize spaces, so it may need to read
// a non-space byte such as a newline or a letter before finishing the parsing
// of a word. This will be fixed in the future.
func ( *Parser) ( io.Reader) iter.Seq2[*Word, error] {
	.reset()
	.f = &File{}
	.src = 
	return func( func(*Word, error) bool) {
		.rune()
		.next()
		for {
			.got(_Newl)
			 := .getWord()
			if  == nil {
				if .tok != _EOF {
					.curErr("%#q is not a valid word", .tok)
				}
				if .err != nil {
					(nil, .err)
				}
				return
			}
			if !(, nil) {
				return
			}
		}
	}
}

// Document parses a single here-document word. That is, it parses the input as
// if they were lines following a <<EOF redirection.
//
// In practice, this is the same as parsing the input as if it were within
// double quotes, but without having to escape all double quote characters.
// Similarly, the here-document word parsed here cannot be ended by any
// delimiter other than reaching the end of the input.
func ( *Parser) ( io.Reader) (*Word, error) {
	.reset()
	.f = &File{}
	.src = 
	.rune()
	.quote = hdocBody
	.hdocStops = [][]byte{[]byte("MVDAN_CC_SH_SYNTAX_EOF")}
	.parsingDoc = true
	.next()
	 := .getWord()
	return , .err
}

// Arithmetic parses a single arithmetic expression. That is, as if the input
// were within the $(( and )) tokens.
func ( *Parser) ( io.Reader) (ArithmExpr, error) {
	.reset()
	.f = &File{}
	.src = 
	.rune()
	.quote = arithmExpr
	.next()
	 := .arithmExpr(false)
	return , .err
}

// Parser holds the internal state of the parsing mechanism of a
// program.
type Parser struct {
	src io.Reader
	bs  []byte // current chunk of read bytes
	bsp uint   // offset within [Parser.bs] for the rune after [Parser.r]
	r   rune   // next rune; [runeEOF] when it went past EOF, or we stopped
	w   int    // width of [Parser.r]

	f *File

	spaced bool // whether [Parser.tok] has whitespace on its left

	err     error // lexer/parser error
	readErr error // got a read error, but bytes left
	readEOF bool  // [Parser.src] already gave us an [io.EOF] error

	tok token  // current token
	val string // current value (valid if tok is _Lit*)

	// position of [Parser.r], to be converted to [Parser.pos] later
	offs, line, col int64

	pos Pos // position of tok

	quote   quoteState // current lexer state
	eqlOffs int        // position of '=' in [Parser.val] when [Parser.tok].isLit is true

	keepComments bool
	lang         LangVariant

	stopAt []byte

	recoveredErrors  int
	recoverErrorsMax int

	forbidNested bool

	// list of pending heredoc bodies
	buriedHdocs int
	heredocs    []*Redirect

	hdocStops [][]byte // stack of end words for open heredocs

	parsingDoc bool // true if using [Parser.Document]

	// openNodes tracks how many entire statements or words we're currently parsing.
	// A non-zero number means that we require certain tokens or words before
	// reaching EOF, used for [Parser.Incomplete].
	openNodes int
	// openBquotes is how many levels of backquotes are open at the moment.
	openBquotes int
	// openBquoteDbls is how many of those backquote levels began inside
	// double quotes, where backslashes also escape double quotes.
	openBquoteDbls int

	// lastBquoteEsc is how many times the last backquote token was escaped
	lastBquoteEsc int

	rxOpenParens int
	rxFirstPart  bool

	accComs []Comment
	curComs *[]Comment

	litBatch  []Lit
	wordBatch []wordAlloc

	readBuf [bufSize]byte
	litBuf  [bufSize]byte
	litBs   []byte
}

// Incomplete reports whether the parser needs more input bytes
// to finish properly parsing a statement or word.
//
// It is only safe to call while the parser is blocked on a read. For an example
// use case, see [Parser.Interactive].
func ( *Parser) () bool {
	// If there are any open nodes, we need to finish them.
	// If we're constructing a literal, we need to finish it.
	return .openNodes > 0 || len(.litBs) > 0
}

const bufSize = 1 << 10

func ( *Parser) () {
	.tok, .val = illegalTok, ""
	.eqlOffs = 0
	.bs, .bsp = nil, 0
	.offs, .line, .col = 0, 1, 1
	.r, .w = 0, 0
	.err, .readErr, .readEOF = nil, nil, false
	.quote, .forbidNested = noState, false
	.openNodes = 0
	.recoveredErrors = 0
	.heredocs, .buriedHdocs = .heredocs[:0], 0
	.hdocStops = nil
	.parsingDoc = false
	.openBquotes = 0
	.openBquoteDbls = 0
	.accComs = nil
	.accComs, .curComs = nil, &.accComs
	.litBatch = nil
	.wordBatch = nil
	.litBs = nil
}

// nextPos returns the position of the next rune, [Parser.r].
func ( *Parser) () Pos {
	// Basic protection against offset overflow;
	// note that an offset of 0 is valid, so we leave the maximum.
	 := min(.offs+int64(.bsp)-int64(.w), offsetMax)
	var ,  uint
	if .line <= lineMax {
		 = uint(.line)
	}
	if .col <= colMax {
		 = uint(.col)
	}
	return NewPos(uint(), , )
}

func ( *Parser) ( Pos,  string) *Lit {
	if len(.litBatch) == 0 {
		.litBatch = make([]Lit, 32)
	}
	 := &.litBatch[0]
	.litBatch = .litBatch[1:]
	.ValuePos = 
	.ValueEnd = .nextPos()
	.Value = 
	return 
}

type wordAlloc struct {
	word  Word
	parts [1]WordPart
}

func ( *Parser) () *Word {
	if len(.wordBatch) == 0 {
		.wordBatch = make([]wordAlloc, 32)
	}
	 := &.wordBatch[0]
	.wordBatch = .wordBatch[1:]
	 := &.word
	.Parts = .wordParts(.parts[:0])
	return 
}

func ( *Parser) ( WordPart) *Word {
	if len(.wordBatch) == 0 {
		.wordBatch = make([]wordAlloc, 32)
	}
	 := &.wordBatch[0]
	.wordBatch = .wordBatch[1:]
	 := &.word
	.Parts = .parts[:1]
	.Parts[0] = 
	return 
}

func ( *Parser) ( *Word) *CallExpr {
	var  struct {
		 CallExpr
		 [4]*Word
	}
	 := &.
	.Args = .[:1]
	.Args[0] = 
	return 
}

type quoteState uint32

const (
	// The initial state of the parser.
	noState quoteState = 1 << iota

	// Used when parsing parameter expansions; use with [Parser.rune],
	// [Parser.next] always returns [illegalTok].
	runeByRune

	// unquotedWordCont exists purely so that the '#' in $foo#bar does not
	// get parsed as a comment; it's a tiny variation on [noState].
	unquotedWordCont

	subCmd
	subCmdBckquo
	// subCmdBraces is like subCmd, but for `${ stmts;}` and `${|stmts;}`,
	// whose bodies end at a word beginning with `}`.
	subCmdBraces
	dblQuotes
	hdocWord
	hdocBody
	hdocBodyTabs
	arithmExpr
	arithmExprLet
	arithmExprCmd
	testExpr
	testExprRegexp
	switchCase
	// paramExpArithm is a subscript like ${a[i]}, which can be a string key
	// rather than an arithmetic expression when the array is associative.
	paramExpArithm
	// paramExpSlice is a slice like ${a:i:j}, which is always arithmetic.
	paramExpSlice
	paramExpRepl
	paramExpExp
	arrayElems

	allKeepSpaces = runeByRune | paramExpRepl | dblQuotes | hdocBody |
		hdocBodyTabs | paramExpRepl | paramExpExp
	allRegTokens = noState | unquotedWordCont | subCmd | subCmdBckquo | subCmdBraces |
		hdocWord | switchCase | arrayElems | testExpr
	allArithmExpr = arithmExpr | arithmExprLet | arithmExprCmd |
		paramExpArithm | paramExpSlice
	allParamExp = paramExpArithm | paramExpSlice | paramExpRepl | paramExpExp
)

type saveState struct {
	quote       quoteState
	buriedHdocs int
}

func ( *Parser) ( quoteState) ( saveState) {
	.quote, .buriedHdocs = .quote, .buriedHdocs
	.buriedHdocs, .quote = len(.heredocs), 
	return 
}

func ( *Parser) ( saveState) {
	.quote, .buriedHdocs = .quote, .buriedHdocs
}

func ( *Parser) ( *Word) ([]byte, bool) {
	 := make([]byte, 0, 4)
	 := false
	for ,  := range .Parts {
		,  = .unquotedWordPart(, , false)
	}
	return , 
}

func ( *Parser) ( []byte,  WordPart,  bool) ( []byte,  bool) {
	switch wp := .(type) {
	case *Lit:
		for  := 0;  < len(.Value); ++ {
			if  := .Value[];  == '\\' && ! {
				if ++;  < len(.Value) {
					 = append(, .Value[])
				}
				 = true
			} else {
				 = append(, )
			}
		}
	case *SglQuoted:
		 = append(, []byte(.Value)...)
		 = true
	case *DblQuoted:
		for ,  := range .Parts {
			, _ = .(, , true)
		}
		 = true
	}
	return , 
}

func ( *Parser) () {
	 := .heredocs[.buriedHdocs:]
	if len() == 0 {
		// Nothing do do; don't even issue a read.
		return
	}
	.rune() // consume '\n', since we know p.tok == _Newl
	 := .quote
	.heredocs = .heredocs[:.buriedHdocs]
	for ,  := range  {
		if .err != nil {
			break
		}
		.quote = hdocBody
		if .Op == DashHdoc {
			.quote = hdocBodyTabs
		}
		,  := .unquotedWordBytes(.Word)
		.hdocStops = append(.hdocStops, )
		if  > 0 && .r == '\n' {
			.rune()
		}
		if  {
			.Hdoc = .quotedHdocWord()
		} else {
			.next()
			.Hdoc = .getWord()
		}
		if  := .hdocStops[len(.hdocStops)-1];  != nil {
			.posErr(.Pos(), "unclosed here-document %#q", )
		}
		.hdocStops = .hdocStops[:len(.hdocStops)-1]
	}
	.quote = 
}

func ( *Parser) ( token) bool {
	if .tok ==  {
		.next()
		return true
	}
	return false
}

func ( *Parser) ( string) (Pos, bool) {
	 := .pos
	if .tok == _LitWord && .val ==  {
		.next()
		return , true
	}
	return , false
}

func ( *Parser) () bool {
	if .recoveredErrors < .recoverErrorsMax {
		.recoveredErrors++
		return true
	}
	return false
}

type noQuote string

func ( noQuote) ( fmt.State,  rune) {
	.Write([]byte())
}

func ( token) ( fmt.State,  rune) {
	if  < _realTokenBoundary &&  == 'q' {
		// EOF, Lit and the others should not be quoted in error messages
		// as they are not real shell syntax like `if` or `{`.
		.Write([]byte(.String()))
	} else {
		fmt.Fprintf(, fmt.FormatString(, ), .String())
	}
}

func ( *Parser) ( Pos, ,  any) {
	.posErr(, "%#q must be followed by %#q", , )
}

func ( *Parser) ( Pos,  any) {
	.followErr(, , noQuote("an expression"))
}

func ( *Parser) ( Pos,  string,  token) {
	if !.got() {
		.followErr(, , )
	}
}

func ( *Parser) ( Pos, ,  string) Pos {
	,  := .gotRsrv()
	if ! {
		if .recoverError() {
			return recoveredPos
		}
		.followErr(, , )
	}
	return 
}

func ( *Parser) ( string,  Pos,  ...string) ([]*Stmt, []Comment) {
	// Language variants disallowing empty command lists:
	// * [LangPOSIX]: "A list is a sequence of one or more AND-OR lists...".
	// * [LangBash]: "A list is a sequence of one or more pipelines..."
	//
	// Language variants allowing empty command lists:
	// * [LangZsh]: "A list is a sequence of zero or more sublists...".
	// * [LangMirBSDKorn]: "Lists of commands can be created by separating pipelines...";
	//   note that the man page is not explicit, but the shell clearly allows e.g. `{ }`.
	if .got(semicolon) {
		if .lang.in(LangZsh | LangMirBSDKorn) {
			return nil, nil // allow an empty list
		}
		.followErr(, , noQuote("a statement list"))
		return nil, nil
	}
	,  := .stmtList(...)
	if len() < 1 {
		if .lang.in(LangZsh | LangMirBSDKorn) {
			return nil, nil // allow an empty list
		}
		if .recoverError() {
			return []*Stmt{{Position: recoveredPos}}, nil
		}
		.followErr(, , noQuote("a statement list"))
	}
	return , 
}

func ( *Parser) ( token,  Pos) *Word {
	 := .getWord()
	if  == nil {
		if .recoverError() {
			return .wordOne(&Lit{ValuePos: recoveredPos})
		}
		.followErr(, , noQuote("a word"))
	}
	return 
}

func ( *Parser) ( Node, ,  string) Pos {
	,  := .gotRsrv()
	if ! {
		if .recoverError() {
			return recoveredPos
		}
		.posErr(.Pos(), "%#q statement must end with %#q", , )
	}
	return 
}

func ( *Parser) ( Pos,  token) {
	.posErr(, "reached %#q without closing quote %#q", .tok, )
}

func ( *Parser) ( Pos, ,  token) {
	.posErr(, "reached %#q without matching %#q with %#q", .tok, , )
}

func ( *Parser) ( Pos, ,  token) Pos {
	 := .pos
	if !.got() {
		if .recoverError() {
			return recoveredPos
		}
		.matchingErr(, , )
	}
	return 
}

func ( *Parser) ( error) {
	if .err == nil {
		.err = 
		.bsp = uint(len(.bs)) + 1
		.r = runeEOF
		.w = 1
		.tok = _EOF
	}
}

// IsIncomplete reports whether a Parser error could have been avoided with
// extra input bytes. For example, if an [io.EOF] was encountered while there was
// an unclosed quote or parenthesis.
func ( error) bool {
	,  := .(ParseError)
	return  && .Incomplete
}

// TODO: probably redo with a [LangVariant] argument.
// Perhaps offer an iterator version as well.

// IsKeyword returns true if the given word is a language keyword
// in POSIX Shell or Bash.
func ( string) bool {
	// This list has been copied from the bash 5.1 source code, file y.tab.c +4460
	// TODO: should we include entries for zsh here? e.g. "{}", "repeat", "always", ...
	switch  {
	case
		"!",
		"[[", // only if COND_COMMAND is defined
		"]]", // only if COND_COMMAND is defined
		"case",
		"coproc", // only if COPROCESS_SUPPORT is defined
		"do",
		"done",
		"else",
		"esac",
		"fi",
		"for",
		"function",
		"if",
		"in",
		"select", // only if SELECT_COMMAND is defined
		"then",
		"time", // only if COMMAND_TIMING is defined
		"until",
		"while",
		"{",
		"}":
		return true
	}
	return false
}

// ParseError represents an error found when parsing a source file, from which
// the parser cannot recover.
type ParseError struct {
	Filename string
	Pos      Pos
	Text     string

	Incomplete bool
}

func ( ParseError) () string {
	if .Filename == "" {
		return fmt.Sprintf("%s: %s", .Pos, .Text)
	}
	return fmt.Sprintf("%s:%s: %s", .Filename, .Pos, .Text)
}

// LangError is returned when the parser encounters code that is only valid in
// other shell language variants. The error includes what feature is not present
// in the current language variant, and what languages support it.
type LangError struct {
	Filename string
	Pos      Pos

	// TODO(v4): replace the Langs slice with a single LangVariant bitset,
	// which is what the parser uses internally already.

	// Feature briefly describes which language feature caused the error.
	Feature string
	// Langs lists some of the language variants which support the feature.
	Langs []LangVariant
	// LangUsed is the language variant used which led to the error.
	LangUsed LangVariant
}

func ( LangError) () string {
	var  strings.Builder
	if .Filename != "" {
		.WriteString(.Filename)
		.WriteString(":")
	}
	.WriteString(.Pos.String())
	.WriteString(": ")
	.WriteString(.Feature)
	if strings.HasSuffix(.Feature, "s") {
		.WriteString(" are a ")
	} else {
		.WriteString(" is a ")
	}
	for ,  := range .Langs {
		if  > 0 {
			.WriteString("/")
		}
		.WriteString(.String())
	}
	.WriteString(" feature; tried parsing as ")
	.WriteString(.LangUsed.String())
	return .String()
}

func ( *Parser) ( Pos,  string,  ...any) {
	// for i, arg := range args {
	// 	if arg, ok := arg.(fmt.Stringer); ok && arg != _EOF {
	// 		args[i] = quotedToken(arg)
	// 	}
	// }
	.errPass(ParseError{
		Filename:   .f.Name,
		Pos:        ,
		Text:       fmt.Sprintf(, ...),
		Incomplete: .tok == _EOF && .Incomplete(),
	})
}

func ( *Parser) ( string,  ...any) {
	.posErr(.pos, , ...)
}

func ( *Parser) ( Pos,  LangVariant,  string,  ...any) {
	if .lang.in() {
		return
	}
	if langBashLike.in() {
		// If we're reporting an error because a feature is for bash-like funcs,
		// just mention "bash" rather than "bash/bats" for the sake of clarity.
		 &^= LangBats
	}
	.errPass(LangError{
		Filename: .f.Name,
		Pos:      ,
		Feature:  fmt.Sprintf(, ...),
		Langs:    slices.Collect(.bits()),
		LangUsed: .lang,
	})
}

func ( *Parser) ( func(*Stmt, error) bool,  ...string) {
	 := true
:
	for .tok != _EOF {
		 := .got(_Newl)
		switch .tok {
		case _LitWord:
			for ,  := range  {
				if .val ==  {
					break 
				}
			}
			if .val == "}" {
				.curErr(`%#q can only be used to close a block`, rightBrace)
			}
		case rightParen:
			if .quote == subCmd {
				break 
			}
		case bckQuote:
			if .backquoteEnd() {
				break 
			}
		case dblSemicolon, semiAnd, dblSemiAnd, semiOr:
			if .quote == switchCase {
				break 
			}
			.curErr("%#q can only be used in a case clause", .tok)
		}
		if ! && ! {
			.curErr("statements must be separated by &, ; or a newline")
		}
		if .tok == _EOF {
			break
		}
		.openNodes++
		 := .getStmt(true, false, false)
		.openNodes--
		if  == nil {
			.invalidStmtStart()
			break
		}
		 = .Semicolon.IsValid()
		if !(, .err) {
			break
		}
	}
}

func ( *Parser) ( ...string) ([]*Stmt, []Comment) {
	var  []*Stmt
	var  []Comment
	 := func( *Stmt,  error) bool {
		 = append(, )
		return true
	}
	.stmts(, ...)
	 := len(.accComs)
	if .tok == _LitWord && (.val == "elif" || .val == "else" || .val == "fi") {
		// Split the comments, so that any aligned with an opening token
		// get attached to it. For example:
		//
		//     if foo; then
		//         # inside the body
		//     # document the else
		//     else
		//     fi
		// TODO(mvdan): look into deduplicating this with similar logic
		// in caseItems.
		for ,  := range slices.Backward(.accComs) {
			if .Pos().Col() != .pos.Col() {
				break
			}
			 = 
		}
	}
	if  > 0 { // keep last nil if empty
		 = .accComs[:]
	}
	.accComs = .accComs[:]
	return , 
}

func ( *Parser) () {
	switch .tok {
	case semicolon, and, or, andAnd, orOr, andPipe, andBang:
		.curErr("%#q can only immediately follow a statement", .tok)
	case rightParen:
		.curErr("%#q can only be used to close a subshell", .tok)
	default:
		.curErr("%#q is not a valid start for a statement", .tok)
	}
}

func ( *Parser) () *Word {
	if  := .wordAnyNumber(); len(.Parts) > 0 && .err == nil {
		return 
	}
	return nil
}

func ( *Parser) () *Lit {
	if .tok.isLit() {
		 := .lit(.pos, .val)
		.next()
		return 
	}
	return nil
}

func ( *Parser) ( []WordPart) []WordPart {
	if .quote == noState {
		.quote = unquotedWordCont
		defer func() { .quote = noState }()
	}
	for {
		.openNodes++
		 := .wordPart()
		.openNodes--
		if  == nil {
			if len() == 0 {
				return nil // normalize empty lists into nil
			}
			return 
		}
		 = append(, )
		if .spaced {
			return 
		}
	}
}

func ( *Parser) ( Pos) {
	if .forbidNested {
		.posErr(, "expansions not allowed in heredoc words")
	}
}

func ( *Parser) () WordPart {
	switch .tok {
	case _Lit, _LitWord, _LitRedir:
		 := .lit(.pos, .val)
		.next()
		return 
	case dollBrace:
		.ensureNoNested(.pos)
		switch .r {
		case '|':
			.checkLang(.pos, langBashLike|LangMirBSDKorn, "`${|stmts;}`")
			fallthrough
		case ' ', '\t', '\n':
			.checkLang(.pos, langBashLike|LangMirBSDKorn, "`${ stmts;}`")
			 := &CmdSubst{
				Left:     .pos,
				TempFile: .r != '|',
				ReplyVar: .r == '|',
			}
			 := .preNested(subCmdBraces)
			.rune() // don't tokenize '|'
			.next()
			.Stmts, .Last = .stmtList("}")
			.postNested()
			,  := .gotRsrv("}")
			if ! {
				.matchingErr(.Left, dollBrace, rightBrace)
			}
			.Right = 
			return 
		default:
			return .paramExp()
		}
	case dollDblParen, dollBrack:
		.ensureNoNested(.pos)
		 := .tok
		 := &ArithmExp{Left: .pos, Bracket:  == dollBrack}
		 := .preNested(arithmExpr)
		.next()
		if .got(hash) {
			.checkLang(.Pos(), LangMirBSDKorn, "unsigned expressions")
			.Unsigned = true
		}
		.X = .followArithm(, .Left)
		if .Bracket {
			if .tok != rightBrack {
				if .recoverError() {
					.Right = recoveredPos
					return 
				}
				.arithmMatchingErr(.Left, dollBrack, rightBrack)
			}
			.postNested()
			.Right = .pos
			.next()
		} else {
			.Right = .arithmEnd(dollDblParen, .Left, )
		}
		return 
	case dollParen:
		.ensureNoNested(.pos)
		return .cmdSubst()
	case dollar:
		 := .paramExp()
		if  == nil { // was not actually a parameter expansion, like: "foo$"
			 := .lit(.pos, "$")
			.next()
			return 
		}
		.ensureNoNested(.Dollar)
		return 
	case assgnParen:
		.checkLang(.pos, LangZsh, `%#q process substitutions`, .tok)
		fallthrough
	case cmdIn, cmdOut:
		.ensureNoNested(.pos)
		 := &ProcSubst{Op: ProcOperator(.tok), OpPos: .pos}
		 := .preNested(subCmd)
		.next()
		.Stmts, .Last = .stmtList()
		.postNested()
		.Rparen = .matched(.OpPos, token(.Op), rightParen)
		return 
	case sglQuote, dollSglQuote:
		 := &SglQuoted{Left: .pos, Dollar: .tok == dollSglQuote}
		 := .r
		for .newLit(); ;  = .rune() {
			switch  {
			case '\\':
				if .Dollar {
					.rune()
				}
			case '\'':
				.Right = .nextPos()
				.Value = .endLit()

				.rune()
				.next()
				return 
			case escNewl:
				.litBs = append(.litBs, '\\', '\n')
			case runeEOF:
				.tok = _EOF
				if .recoverError() {
					.Right = recoveredPos
					return 
				}
				.quoteErr(.Pos(), sglQuote)
				return nil
			}
		}
	case dblQuote, dollDblQuote:
		if .quote == dblQuotes {
			// p.tok == dblQuote, as "foo$" puts $ in the lit
			return nil
		}
		return .dblQuoted()
	case bckQuote:
		if .backquoteEnd() {
			return nil
		}
		.ensureNoNested(.pos)
		 := &CmdSubst{Left: .pos, Backquotes: true}
		 := .preNested(subCmdBckquo)
		.openBquotes++
		if .quote == dblQuotes {
			.openBquoteDbls++
		}

		// The lexer didn't call p.rune for us, so that it could have
		// the right p.openBquotes to properly handle backslashes.
		.rune()

		.next()
		.Stmts, .Last = .stmtList()
		if .tok == bckQuote && .lastBquoteEsc < .openBquotes-1 {
			// e.g. found ` before the nested backquote \` was closed.
			.tok = _EOF
			.quoteErr(.Pos(), bckQuote)
		}
		.postNested()
		.openBquotes--
		if .quote == dblQuotes {
			.openBquoteDbls--
		}
		.Right = .pos

		// Like above, the lexer didn't call p.rune for us.
		.rune()
		if !.got(bckQuote) {
			if .recoverError() {
				.Right = recoveredPos
			} else {
				.quoteErr(.Pos(), bckQuote)
			}
		}
		return 
	case leftParen:
		if .lang.in(LangZsh) && .r != ')' {
			// Zsh glob qualifier like *(N) or .(:a); the only case where
			// ( immediately after a word is not a glob qualifier is ()
			// for a function declaration, which the parser handles earlier.
			 := .pos
			.pos = .nextPos()
			for .newLit(.r); .r != runeEOF && .r != ')'; .rune() {
			}
			if .r != ')' {
				.tok = _EOF // we can only get here due to EOF
				.matchingErr(, leftParen, rightParen)
			}
			.rune()
			.val = .endLit()
			 := .lit(, "("+.val)
			.next()
			return 
		}
		return nil
	case globQuest, globStar, globPlus, globAt, globExcl:
		.checkLang(.pos, langBashLike|LangMirBSDKorn, "extended globs")
		 := &ExtGlob{Op: GlobOperator(.tok), OpPos: .pos}
		 := 1
		 := .r
	:
		for .newLit(); ;  = .rune() {
			switch  {
			case runeEOF:
				break 
			case '(':
				++
			case ')':
				if --;  == 0 {
					break 
				}
			}
		}
		.Pattern = .lit(posAddCol(.OpPos, 2), .endLit())
		.rune()
		.next()
		if  != 0 {
			.matchingErr(.OpPos, token(.Op), rightParen)
		}
		return 
	default:
		return nil
	}
}

func ( *Parser) () *CmdSubst {
	 := &CmdSubst{Left: .pos}
	 := .preNested(subCmd)
	.next()
	.Stmts, .Last = .stmtList()
	.postNested()
	.Right = .matched(.Left, dollParen, rightParen)
	return 
}

func ( *Parser) () *DblQuoted {
	 := &struct {
		 DblQuoted
		  [1]WordPart
	}{
		: DblQuoted{Left: .pos, Dollar: .tok == dollDblQuote},
	}
	 := &.
	 := .quote
	.quote = dblQuotes
	.next()
	.Parts = .wordParts(.[:0])
	.quote = 
	.Right = .pos
	if !.got(dblQuote) {
		if .recoverError() {
			.Right = recoveredPos
		} else {
			.quoteErr(.Pos(), dblQuote)
		}
	}
	return 
}

// paramExp parses a short or full parameter expansion, depending on whether
// [Parser.tok] is [dollar] or [dollBrace]. It returns nil if a [dollar] token
// does not form a valid parameter expansion, in which case it should be parsed
// as a literal.
func ( *Parser) () *ParamExp {
	 := .quote
	.quote = runeByRune
	// [ParamExp.Short] means we are parsing $exp rather than ${exp}.
	 := &ParamExp{
		Dollar: .pos,
		Short:  .tok == dollar,
	}
	if !.Short && .r == '(' {
		.checkLang(.Pos(), LangZsh, `parameter expansion flags`)
		// For now, for simplicity, we parse flags as just a literal.
		// In the future, parsing as a word is better for cases like
		// `${(ps.$sep.)val}`.
		 := .nextPos()
		.rune()
		.pos = .nextPos()
		for .newLit(.r); .r != runeEOF && .r != ')'; .rune() {
		}
		.val = .endLit()
		if .r != ')' {
			.tok = _EOF // we can only get here due to EOF
			.matchingErr(, leftParen, rightParen)
		}
		.Flags = .lit(.pos, .val)
		.rune()
	}
	// Zsh-only prefixes that change how the parameter is expanded.
	// They may appear in any combination, like ${=^name}.
	// Doubling the rune (${==a}, ${~~a}, ${^^a}) forces the option off.
:
	for .lang.in(LangZsh) {
		var  *OptState
		switch .r {
		case '=':
			 = &.Split
		case '~':
			 = &.GlobSubst
		case '^':
			 = &.RcExpand
		default:
			break 
		}
		,  := .peekTwo()
		 := OptOn
		 := 
		if rune() == .r {
			 = OptOff
			 = 
		}
		if  == utf8.RuneSelf ||  == '}' {
			break 
		}
		// For the short form, only treat as a prefix if followed by something
		// that could start a parameter name or another zsh prefix.
		if .Short &&  != '=' &&  != '~' &&  != '^' &&
			!paramNameStartRune() {
			break 
		}
		if  == OptOff {
			.rune() // consume the first of the doubled pair
		}
		.rune()
		* = 
	}
	if !.Short || .lang.in(LangZsh) {
		// Prefixes, like ${#name} to get the length of a variable.
		// Note that zsh allows the short forms $#name and $+name too,
		// but not $%name nor $!name.
		switch .r {
		case '#':
			if .paramNameStart() {
				.Length = true
			}
		case '%':
			if !.Short && .paramNameStart() {
				.checkLang(.Pos(), LangMirBSDKorn, "`${%%foo}`")
				.Width = true
			}
		case '!':
			if !.Short && .paramNameStart() {
				.checkLang(.Pos(), langBashLike|LangMirBSDKorn, "`${!foo}`")
				.Excl = true
			}
		case '+':
			if .paramNameStart() {
				.checkLang(.Pos(), LangZsh, "`${+foo}`")
				.IsSet = true
			}
		}
	}
	if  = .paramExpParameter();  == nil {
		.quote = 
		return nil // just "$"
	}
	// In short mode, any indexing or suffixes is not allowed, and we don't require '}'.
	// Zsh is an exception: $foo[1] and $foo[1,3] are valid. Note that $1[x] does not qualify.
	if .Short {
		if .lang.in(LangZsh) && .r == '[' && (len(.val) != 1 || !positionalRuneParam(.val[0])) {
			.pos = .nextPos()
			.rune()
			.Index = .eitherIndex()
		}
		.quote = 
		.next()
		return 
	}
	// Index expressions like ${foo[1]}. Note that expansion suffixes can be combined,
	// like ${foo[@]//replace/with}.
	if .r == '[' {
		.checkLang(.nextPos(), langBashLike|LangMirBSDKorn|LangZsh, "arrays")
		// In zsh some of these like ${@[-1]} or ${*[1,3]} work,
		// so we don't do this sort of check at all.
		if !.lang.in(LangZsh) && .Param != nil && !ValidName(.Param.Value) {
			.posErr(.nextPos(), "cannot index a special parameter name")
		}
		.pos = .nextPos()
		.rune()
		.Index = .eitherIndex()
	}
	 := .r
	.pos = .nextPos()
	.tok = .paramToken(.r)
	if .tok == rightBrace {
		.Rbrace = .pos
		.quote = 
		.next()
		return 
	}
	if .tok != _EOF && (.Length || .Width || .IsSet) {
		.curErr("cannot combine multiple parameter expansion operators")
	}
	switch .tok {
	case slash, dblSlash: // pattern search and replace
		.checkLang(.pos, langBashLike|LangMirBSDKorn|LangZsh, "search and replace")
		.Repl = &Replace{All: .tok == dblSlash}
		.quote = paramExpRepl
		.next()
		.Repl.Orig = .getWord()
		.quote = paramExpExp
		if .got(slash) {
			.Repl.With = .getWord()
		}
	case colon: // slicing
		if .lang.in(LangZsh) && (.r == '&' || asciiLetter(.r)) {
			 := .pos
		:
			for .newLit(.r); ; .rune() {
				switch .r {
				case runeEOF:
					.tok = _EOF
					.matchingErr(.Dollar, dollBrace, rightBrace)
					break 
				case '}':
					.Modifiers = append(.Modifiers, .lit(, .endLit()))
					.Rbrace = .nextPos()
					.rune()
					break 
				case ':':
					.Modifiers = append(.Modifiers, .lit(, .endLit()))
					.rune()
					 = .nextPos()
					.newLit(.r)
				}
			}
			.quote = 
			.next()
			return 
		}
		.checkLang(.pos, langBashLike|LangMirBSDKorn|LangZsh, "slicing")
		.Slice = &Slice{}
		 := .pos
		.quote = paramExpSlice
		if .next(); .tok != colon {
			.Slice.Offset = .followArithm(colon, )
		}
		 = .pos
		if .got(colon) {
			.Slice.Length = .followArithm(colon, )
		}
		// Need to use a different matched style so arithm errors
		// get reported correctly
		.quote = 
		.Rbrace = .pos
		.matchedArithm(.Dollar, dollBrace, rightBrace)
		return 
	case caret, dblCaret, comma, dblComma: // upper/lower case
		.checkLang(.pos, langBashLike, "this expansion operator")
		.Exp = .paramExpExp()
	case at, star:
		switch {
		case .tok == star && !.Excl:
			.curErr("not a valid parameter expansion operator: %#q", .tok)
		case .Excl && .r == '}':
			.checkLang(.Pos(), langBashLike, "`${!foo%s}`", .tok)
			.Names = ParNamesOperator(.tok)
			.next()
		case .tok == at:
			.checkLang(.pos, langBashLike|LangMirBSDKorn, "this expansion operator")
			fallthrough
		default:
			.Exp = .paramExpExp()
		}
	case plus, colPlus, minus, colMinus, quest, colQuest, assgn, colAssgn,
		perc, dblPerc, hash, dblHash, colHash, colPipe, colStar:
		.Exp = .paramExpExp()
	case _EOF:
	default:
		if paramNameRune() {
			if .Param != nil {
				.curErr("%#q cannot be followed by a word", .Param.Value)
			} else {
				.curErr("nested parameter expansion cannot be followed by a word")
			}
		} else {
			.curErr("not a valid parameter expansion operator: %#q", string())
		}
	}
	if .tok != _EOF && .tok != rightBrace {
		.tok = .paramToken(.r)
	}
	.quote = 
	.Rbrace = .matched(.Dollar, dollBrace, rightBrace)
	return 
}

// paramNameStart reports whether a parameter name can begin after a prefix rune
// such as the '#' in ${#foo}, consuming the prefix rune if so.
// Only the long form allows a quoted nested expansion like ${#"$(foo)"} or EOF;
// in the short form the prefix rune is the parameter itself, as in "$#" or $#"$foo".
func ( *Parser) ( *ParamExp) bool {
	 := .peek()
	if paramNameStartRune() || (!.Short && ( == '"' ||  == utf8.RuneSelf)) {
		.rune()
		return true
	}
	return false
}

func ( *Parser) ( *ParamExp) ( token,  Pos) {
	if .Short {
		return illegalTok, Pos{}
	}
	if .r == '"' {
		 = .nextPos()
		.rune()
	}
	if .r != '$' {
		if .IsValid() {
			return dollar, 
		}
		return illegalTok, Pos{}
	}
	switch  := .peek();  {
	case '{', '(':
		.pos = .nextPos()
		.checkLang(.pos, LangZsh, "nested parameter expansions")
		if .err != nil {
			return illegalTok, Pos{} // xxx given that we overwrite p.tok below
		}
		.rune()
		.rune()
		if  == '{' {
			 = dollBrace
		} else { // '('
			 = dollParen
		}
	}
	return , 
}

func ( *Parser) ( *ParamExp) *ParamExp {
	// Check for Zsh nested parameter expressions like ${(f)"$(foo)"}.
	if ,  := .nestedParameterStart();  != illegalTok {
		var  WordPart
		switch .tok = ; .tok {
		case dollBrace: // ${#${nested parameter}}
			.tok = dollBrace
			 = .paramExp()
		case dollParen: // ${#$(nested command)}
			 = .cmdSubst()
		default: // dollar
			.posErr(.Pos(), "invalid nested parameter expansion")
		}
		if .IsValid() {
			if .r != '"' {
				.tok = .paramToken(.r)
				if .tok == illegalTok {
					.posErr(.Pos(), "invalid nested parameter expansion")
				} else {
					.quoteErr(, dblQuote)
				}
			}
			.NestedParam = &DblQuoted{
				Left:  ,
				Right: .nextPos(),
				Parts: []WordPart{},
			}
			.rune()
		} else {
			.NestedParam = 
		}
		return 
	}
	// The parameter name itself, like $foo or $?.
	switch .r {
	case '?', '-':
		if .Length && .peek() != '}' {
			// actually ${#-default}, not ${#-}; fix the ambiguity
			.Length = false
			 := .nextPos()
			.Param = .lit(posAddCol(, -1), "#")
			.Param.ValueEnd = 
			break
		}
		fallthrough
	case '@', '*', '#', '!', '$':
		,  := .r, .nextPos()
		.rune()
		.Param = .lit(, string())
	default:
		// Note that $1a is equivalent to ${1}a, but ${1a} is not.
		// POSIX Shell says the latter is unspecified behavior, so match Bash's behavior.
		 := .nextPos()
		if .Short && singleRuneParam(.r) {
			.val = string(.r)
			.rune()
		} else {
			for .newLit(.r); .r != runeEOF; .rune() {
				if !paramNameRune(.r) && .r != escNewl {
					break
				}
			}
			.val = .endLit()
			if !numberLiteral(.val) && !ValidName(.val) {
				if .Short {
					return nil // just "$"
				}
				if .lang.in(LangZsh) && .val == "" {
					// Zsh allows omitting the parameter name, e.g. ${:-word}.
					return 
				}
				.posErr(, "invalid parameter name")
			}
		}
		.Param = .lit(, .val)
	}
	return 
}

func ( *Parser) () *Expansion {
	 := ParExpOperator(.tok)
	switch  {
	case MatchEmpty, ArrayExclude, ArrayIntersect:
		.checkLang(.pos, LangZsh, "${name%sarg}", )
	}
	.quote = paramExpExp
	.next()
	if  == OtherParamOps {
		if !.tok.isLit() {
			.curErr("@ expansion operator requires a literal")
		}
		switch .val {
		case "a", "k", "u", "A", "E", "K", "L", "P", "U":
			.checkLang(.pos, langBashLike, "this expansion operator")
		case "#":
			.checkLang(.pos, LangMirBSDKorn, "this expansion operator")
		case "Q":
		default:
			.curErr("invalid @ expansion operator %#q", .val)
		}
	}
	return &Expansion{Op: , Word: .getWord()}
}

func ( *Parser) () ArithmExpr {
	 := .quote
	 := .pos
	.quote = paramExpArithm
	.next()
	if .tok == star || .tok == at {
		.tok, .val = _LitWord, .tok.String()
	}
	 := .followArithm(leftBrack, )
	.quote = 
	.matchedArithm(, leftBrack, rightBrack)
	return 
}

func ( *Parser) () *FlagsArithm {
	 := &FlagsArithm{}
	// Lex flags as raw text, like paramExp does for ${(flags)...}.
	 := .pos
	 := .quote
	.quote = runeByRune
	.pos = .nextPos()
	for .newLit(.r); .r != runeEOF && .r != ')'; .rune() {
	}
	.val = .endLit()
	if .r != ')' {
		.tok = _EOF
		.matchingErr(, leftParen, rightParen)
	}
	.Flags = .lit(.pos, .val)
	.rune()
	// Lex the argument as a raw pattern, stopping at ',' or ']',
	// since zsh treats it as a pattern rather than an arithmetic expression.
	 := .nextPos()
	for .newLit(.r); .r != runeEOF && .r != ',' && .r != ']'; .rune() {
	}
	if  := .endLit();  != "" {
		.X = .wordOne(.lit(, ))
	}
	.quote = 
	.next()
	return 
}

func ( *Parser) () bool {
	switch .tok {
	case _EOF, _Newl, semicolon, and, or, andAnd, orOr, orAnd, andPipe, andBang,
		dblSemicolon, semiAnd, dblSemiAnd, semiOr, rightParen:
		return true
	case bckQuote:
		return .backquoteEnd()
	}
	return false
}

func ( *Parser) () bool {
	return .lastBquoteEsc < .openBquotes
}

// ValidName returns whether val is a valid name as per the POSIX spec.
func ( string) bool {
	if  == "" {
		return false
	}
	for ,  := range  {
		switch {
		case asciiLetter(),  == '_':
		case  > 0 && asciiDigit():
		default:
			return false
		}
	}
	return true
}

func numberLiteral[ string | []byte]( ) bool {
	if len() == 0 {
		return false
	}
	for ,  := range string() {
		if !asciiDigit() {
			return false
		}
	}
	return true
}

func ( *Parser) () bool {
	if !.tok.isLit() {
		return false
	}
	if  := .eqlOffs;  > 0 {
		if .val[-1] == '+' && .lang.in(langBashLike|LangMirBSDKorn|LangZsh) {
			-- // a+=x
		}
		if ValidName(.val[:]) {
			return true
		}
	} else if !ValidName(.val) {
		return false // *[i]=x
	}
	return .r == '[' // a[i]=x
}

func ( *Parser) ( bool) *Assign {
	 := &Assign{}
	if .eqlOffs > 0 { // foo=bar
		 := .eqlOffs
		if .lang.in(langBashLike|LangMirBSDKorn|LangZsh) && .val[.eqlOffs-1] == '+' {
			// a+=b
			.Append = true
			--
		}
		.Name = .lit(.pos, .val[:])
		// since we're not using the entire p.val
		.Name.ValueEnd = posAddCol(.Name.ValuePos, )
		 := .lit(posAddCol(.pos, 1), .val[.eqlOffs+1:])
		if .Value != "" {
			.ValuePos = posAddCol(.ValuePos, .eqlOffs)
			.Value = .wordOne()
		}
		.next()
	} else { // foo[x]=bar
		.Name = .lit(.pos, .val)
		// hasValidIdent already checks p.r is '['
		.rune()
		.pos = posAddCol(.pos, 1)
		.Index = .eitherIndex()
		if .spaced || .stopToken() {
			if  {
				.followErr(.Pos(), "a[b]", assgn)
			} else {
				.Naked = true
				return 
			}
		}
		if .tok == assgnParen {
			if !.lang.in(LangZsh) {
				.curErr("arrays cannot be nested")
				return nil
			}
			// zsh allows a[i]=(values...).
			// assgnParen consumed both '=' and '(',
			// so rewrite as leftParen for array parsing below.
			.tok = leftParen
			.pos = posAddCol(.pos, 1)
		} else {
			if len(.val) > 0 && .val[0] == '+' {
				.Append = true
				.val = .val[1:]
				.pos = posAddCol(.pos, 1)
			}
			if len(.val) < 1 || .val[0] != '=' {
				if .Append {
					.followErr(.Pos(), "a[b]+", assgn)
				} else {
					.followErr(.Pos(), "a[b]", assgn)
				}
				return nil
			}
			.pos = posAddCol(.pos, 1)
			.val = .val[1:]
			if .val == "" {
				.next()
			}
		}
	}
	if .spaced || .stopToken() {
		return 
	}
	if .Value == nil && .tok == leftParen {
		.checkLang(.pos, langBashLike|LangMirBSDKorn|LangZsh, "arrays")
		.Array = &ArrayExpr{Lparen: .pos}
		 := .quote
		if .lang.in(langBashLike | LangZsh) {
			 = arrayElems
		}
		 := .preNested()
		.next()
		.got(_Newl)
		for .tok != _EOF && .tok != rightParen {
			 := &ArrayElem{}
			.Comments, .accComs = .accComs, nil
			if .tok == leftBrack {
				 := .pos
				.Index = .eitherIndex()
				if .tok == assgnParen {
					.curErr("arrays cannot be nested")
					return nil
				}
				.follow(, `[x]`, assgn)
			}
			if .Value = .getWord(); .Value == nil {
				switch .tok {
				case _Newl, rightParen, leftBrack:
					// TODO: support [index]=[
				default:
					.curErr("array element values must be words")
					return nil
				}
			}
			if len(.accComs) > 0 {
				 := .accComs[0]
				if .Pos().Line() == .End().Line() {
					.Comments = append(.Comments, )
					.accComs = .accComs[1:]
				}
			}
			.Array.Elems = append(.Array.Elems, )
			.got(_Newl)
		}
		.Array.Last, .accComs = .accComs, nil
		.postNested()
		.Array.Rparen = .matched(.Array.Lparen, leftParen, rightParen)
	} else if  := .getWord();  != nil {
		if .Value == nil {
			.Value = 
		} else {
			.Value.Parts = append(.Value.Parts, .Parts...)
		}
	}
	return 
}

func ( *Parser) () bool {
	switch .tok {
	case _LitRedir, rdrOut, appOut, rdrIn, rdrInOut, dplIn, dplOut,
		rdrClob, appClob, hdoc, dashHdoc, wordHdoc,
		rdrAll, rdrAllClob, appAll, appAllClob:
		return true
	}
	return false
}

func ( *Parser) ( *Stmt) {
	var  *Redirect
	if .Redirs == nil {
		var  struct {
			 [4]*Redirect
			  Redirect
		}
		.Redirs = .[:0]
		 = &.
		.Redirs = append(.Redirs, )
	} else {
		 = &Redirect{}
		.Redirs = append(.Redirs, )
	}
	.N = .getLit()
	if .N != nil && .N.Value[0] == '{' {
		.checkLang(.N.Pos(), langBashLike|LangZsh, "`{varname}` redirects")
	}
	.Op, .OpPos = RedirOperator(.tok), .pos
	switch .Op {
	case RdrAll, AppAll:
		.checkLang(.pos, langBashLike|LangMirBSDKorn|LangZsh, "%#q redirects", .Op)
	case AppClob, RdrAllClob, AppAllClob:
		.checkLang(.pos, LangZsh, "%#q redirects", .Op)
	}
	.next()
	switch .Op {
	case Hdoc, DashHdoc:
		 := .quote
		.quote, .forbidNested = hdocWord, true
		.heredocs = append(.heredocs, )
		.Word = .followWordTok(token(.Op), .OpPos)
		.quote, .forbidNested = , false
		if .tok == _Newl {
			if len(.accComs) > 0 {
				 := .accComs[0]
				if .Pos().Line() == .End().Line() {
					.Comments = append(.Comments, )
					.accComs = .accComs[1:]
				}
			}
			.doHeredocs()
		}
	case WordHdoc:
		.checkLang(.OpPos, langBashLike|LangMirBSDKorn|LangZsh, "herestrings")
		fallthrough
	default:
		.Word = .followWordTok(token(.Op), .OpPos)
	}
}

func ( *Parser) (, ,  bool) *Stmt {
	,  := .gotRsrv("!")
	 := &Stmt{Position: }
	if  {
		.Negated = true
		if .stopToken() {
			.posErr(.Pos(), `%#q cannot form a statement alone`, exclMark)
		}
		if ,  := .gotRsrv("!");  {
			.posErr(.Pos(), `cannot negate a command multiple times`)
		}
	}
	if  = .gotStmtPipe(, false);  == nil || .err != nil {
		return nil
	}
	// instead of using recursion, iterate manually
	for .tok == andAnd || .tok == orOr {
		if  {
			// left associativity: in a list of BinaryCmds, the
			// right recursion should only read a single element
			return 
		}
		 := &BinaryCmd{
			OpPos: .pos,
			Op:    BinCmdOperator(.tok),
			X:     ,
		}
		.next()
		.got(_Newl)
		.Y = .(false, true, false)
		if .Y == nil || .err != nil {
			if .recoverError() {
				.Y = &Stmt{Position: recoveredPos}
			} else {
				.followErr(.OpPos, .Op, noQuote("a statement"))
				return nil
			}
		}
		 = &Stmt{Position: .Position}
		.Cmd = 
		.Comments, .X.Comments = .X.Comments, nil
	}
	if  {
		switch .tok {
		case semicolon:
			.Semicolon = .pos
			.next()
		case and:
			.Semicolon = .pos
			.next()
			.Background = true
		case orAnd:
			.Semicolon = .pos
			.next()
			.Coprocess = true
		case andPipe, andBang:
			.Semicolon = .pos
			.next()
			.Disown = true
		}
	}
	if len(.accComs) > 0 && ! && ! {
		 := .accComs[0]
		if .Pos().Line() == .End().Line() {
			.Comments = append(.Comments, )
			.accComs = .accComs[1:]
		}
	}
	return 
}

func ( *Parser) ( *Stmt,  bool) *Stmt {
	.Comments, .accComs = .accComs, nil
	for .peekRedir() {
		.doRedirect()
	}
	 := len(.Redirs)
	switch .tok {
	case _LitWord:
		switch .val {
		case "{":
			.block()
		case "{}":
			// Zsh treats closing braces in a special way, allowing this.
			if .lang.in(LangZsh) {
				.Cmd = &Block{Lbrace: .pos, Rbrace: posAddCol(.pos, 1)}
				.next()
			}
		case "if":
			.ifClause()
		case "while", "until":
			// TODO(zsh): "repeat"
			.whileClause(, .val == "until")
		case "for":
			.forClause()
		case "case":
			.caseClause()
		// TODO(zsh): { try-list } "always" { always-list }
		case "}":
			.curErr(`%#q can only be used to close a block`, rightBrace)
		case "then", "elif":
			.curErr("%#q can only be used in an `if`", .val)
		case "fi":
			.curErr("%#q can only be used to end an `if`", .val)
		case "do":
			.curErr(`%#q can only be used in a loop`, .val)
		case "done":
			.curErr(`%#q can only be used to end a loop`, .val)
		case "esac":
			.curErr("%#q can only be used to end a `case`", .val)
		case "!":
			if !.Negated {
				.curErr(`%#q can only be used in full statements`, exclMark)
				break
			}
		case "[[":
			if .lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
				.testClause()
			}
		case "]]":
			if .lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
				.curErr(`%#q can only be used to close a test`, dblRightBrack)
			}
		case "let":
			if .lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
				.letClause()
			}
		case "function":
			if .lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
				.bashFuncDecl()
			}
		case "declare":
			if .lang.in(langBashLike | LangZsh) { // Note that mksh lacks this one.
				.declClause()
			}
		case "local", "export", "readonly", "typeset", "nameref":
			if .lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
				.declClause()
			}
		case "time":
			if .lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
				.timeClause()
			}
		case "coproc":
			if .lang.in(langBashLike) { // Note that mksh lacks this one.
				.coprocClause()
			}
		case "select":
			if .lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
				.selectClause()
			}
		case "@test":
			if .lang.in(LangBats) {
				.testDecl()
			}
		}
		if .Cmd != nil {
			break
		}
		if .hasValidIdent() {
			.callExpr(, nil, true)
			break
		}
		 := .lit(.pos, .val)
		.next()
		// In zsh, ( after a word is a glob qualifier unless followed
		// immediately by ), which is the func declaration syntax.
		if .tok == leftParen && (!.lang.in(LangZsh) || .r == ')') {
			.next()
			.follow(.ValuePos, "foo(", rightParen)
			if .lang.in(LangPOSIX) && !ValidName(.Value) {
				.posErr(.Pos(), "invalid func name")
			}
			.funcDecl(, .ValuePos, false, true, )
		} else {
			 := .wordOne()
			if .lang.in(LangZsh) && !.spaced {
				.Parts = append(.Parts, .wordParts(nil)...)
			}
			.callExpr(, , false)
		}
	case bckQuote:
		if .backquoteEnd() {
			break
		}
		fallthrough
	case _Lit, dollBrace, dollDblParen, dollParen, dollar, cmdIn, assgnParen, cmdOut,
		sglQuote, dollSglQuote, dblQuote, dollDblQuote, dollBrack,
		globQuest, globStar, globPlus, globAt, globExcl:
		if .hasValidIdent() {
			.callExpr(, nil, true)
			break
		}
		 := .wordAnyNumber()
		if .got(leftParen) {
			.posErr(.Pos(), "invalid func name")
		}
		.callExpr(, , false)
	case leftParen:
		if .r == ')' {
			.rune()
			 := .pos
			.next()
			if .tok == _LitWord && .val == "{" {
				.checkLang(, LangZsh, "anonymous functions")
			}
			.funcDecl(, , false, true)
			break
		}
		.subshell()
	case dblLeftParen:
		.arithmExpCmd()
	}
	if .Cmd == nil && len(.Redirs) == 0 {
		return nil // no statement found
	}
	if  > 0 && .Cmd != nil {
		if ,  := .Cmd.(*CallExpr); ! {
			.checkLang(.Pos(), LangZsh, "redirects before compound commands")
		}
	}
	for .peekRedir() {
		.doRedirect()
	}
	// instead of using recursion, iterate manually
	for .tok == or || .tok == orAnd {
		if  {
			// left associativity: in a list of BinaryCmds, the
			// right recursion should only read a single element
			return 
		}
		if .tok == orAnd && .lang.in(LangMirBSDKorn) {
			// No need to check for LangPOSIX, as on that language
			// we parse |& as two tokens.
			break
		}
		 := &BinaryCmd{OpPos: .pos, Op: BinCmdOperator(.tok), X: }
		.next()
		.got(_Newl)
		if .Y = .(&Stmt{Position: .pos}, true); .Y == nil || .err != nil {
			if .recoverError() {
				.Y = &Stmt{Position: recoveredPos}
			} else {
				.followErr(.OpPos, .Op, noQuote("a statement"))
				break
			}
		}
		 = &Stmt{Position: .Position}
		.Cmd = 
		.Comments, .X.Comments = .X.Comments, nil
		// in "! x | y", the bang applies to the entire pipeline
		.Negated = .X.Negated
		.X.Negated = false
	}
	return 
}

func ( *Parser) ( *Stmt) {
	 := &Subshell{Lparen: .pos}
	 := .preNested(subCmd)
	.next()
	.Stmts, .Last = .followStmts("(", .Lparen)
	.postNested()
	.Rparen = .matched(.Lparen, leftParen, rightParen)
	.Cmd = 
}

func ( *Parser) ( *Stmt) {
	 := &ArithmCmd{Left: .pos}
	 := .preNested(arithmExprCmd)
	.next()
	if .got(hash) {
		.checkLang(.Pos(), LangMirBSDKorn, "unsigned expressions")
		.Unsigned = true
	}
	.X = .followArithm(dblLeftParen, .Left)
	.Right = .arithmEnd(dblLeftParen, .Left, )
	.Cmd = 
}

func ( *Parser) ( *Stmt) {
	 := &Block{Lbrace: .pos}
	.next()
	.Stmts, .Last = .followStmts("{", .Lbrace, "}")
	if ,  := .gotRsrv("}");  {
		.Rbrace = 
	} else if .recoverError() {
		.Rbrace = recoveredPos
	} else {
		.matchingErr(.Lbrace, leftBrace, rightBrace)
	}
	.Cmd = 
}

func ( *Parser) ( *Stmt) {
	 := &IfClause{Position: .pos}
	.next()
	.Cond, .CondLast = .followStmts("if", .Position, "then")
	.ThenPos = .followRsrv(.Position, "if <cond>", "then")
	.Then, .ThenLast = .followStmts("then", .ThenPos, "fi", "elif", "else")
	 := 
	for .tok == _LitWord && .val == "elif" {
		 := &IfClause{Position: .pos}
		.Last = .accComs
		.accComs = nil
		.next()
		.Cond, .CondLast = .followStmts("elif", .Position, "then")
		.ThenPos = .followRsrv(.Position, "elif <cond>", "then")
		.Then, .ThenLast = .followStmts("then", .ThenPos, "fi", "elif", "else")
		.Else = 
		 = 
	}
	if ,  := .gotRsrv("else");  {
		.Last = .accComs
		.accComs = nil
		 := &IfClause{Position: }
		.Then, .ThenLast = .followStmts("else", .Position, "fi")
		.Else = 
		 = 
	}
	.Last = .accComs
	.accComs = nil
	.FiPos = .stmtEnd(, "if", "fi")
	for  := .Else;  != nil;  = .Else {
		// All the nested IfClauses share the same FiPos.
		.FiPos = .FiPos
	}
	.Cmd = 
}

func ( *Parser) ( *Stmt,  bool) {
	 := &WhileClause{WhilePos: .pos, Until: }
	 := "while"
	 := "while <cond>"
	if .Until {
		 = "until"
		 = "until <cond>"
	}
	.next()
	.Cond, .CondLast = .followStmts(, .WhilePos, "do")
	.DoPos = .followRsrv(.WhilePos, , "do")
	.Do, .DoLast = .followStmts("do", .DoPos, "done")
	.DonePos = .stmtEnd(, , "done")
	.Cmd = 
}

func ( *Parser) ( *Stmt) {
	 := &ForClause{ForPos: .pos}
	.next()
	.Loop = .loop(.ForPos)

	,  := "do", "done"
	if ,  := .gotRsrv("{");  {
		.checkLang(, langBashLike|LangMirBSDKorn, "for loops with braces")
		.DoPos = 
		.Braces = true
		,  = "{", "}"
	} else {
		.DoPos = .followRsrv(.ForPos, "for foo [in words]", )
	}

	.Comments = append(.Comments, .accComs...)
	.accComs = nil
	.Do, .DoLast = .followStmts(, .DoPos, )
	.DonePos = .stmtEnd(, "for", )
	.Cmd = 
}

func ( *Parser) ( Pos) Loop {
	switch .tok {
	case leftParen, dblLeftParen:
		.checkLang(.pos, langBashLike|LangZsh, "c-style fors")
	}
	if .tok == dblLeftParen {
		 := &CStyleLoop{Lparen: .pos}
		 := .preNested(arithmExprCmd)
		.next()
		.Init = .arithmExpr(false)
		if !.got(dblSemicolon) {
			.follow(.pos, "expr", semicolon)
			.Cond = .arithmExpr(false)
			.follow(.pos, "expr", semicolon)
		}
		.Post = .arithmExpr(false)
		.Rparen = .arithmEnd(dblLeftParen, .Lparen, )
		.got(semicolon)
		.got(_Newl)
		return 
	}
	return .wordIter("for", )
}

func ( *Parser) ( string,  Pos) *WordIter {
	 := &WordIter{}
	if .Name = .getLit(); .Name == nil {
		.followErr(, , noQuote("a literal"))
	}
	if .got(semicolon) {
		.got(_Newl)
		return 
	}
	.got(_Newl)
	if ,  := .gotRsrv("in");  {
		.InPos = 
		for !.stopToken() {
			if  := .getWord();  == nil {
				.curErr("word list can only contain words")
			} else {
				.Items = append(.Items, )
			}
		}
		.got(semicolon)
		.got(_Newl)
	} else if .tok == _LitWord && .val == "do" {
	} else {
		.followErr(, +" foo", noQuote("`in`, `do`, `;`, or a newline"))
	}
	return 
}

func ( *Parser) ( *Stmt) {
	 := &ForClause{ForPos: .pos, Select: true}
	.next()
	.Loop = .wordIter("select", .ForPos)
	.DoPos = .followRsrv(.ForPos, "select foo [in words]", "do")
	.Do, .DoLast = .followStmts("do", .DoPos, "done")
	.DonePos = .stmtEnd(, "select", "done")
	.Cmd = 
}

func ( *Parser) ( *Stmt) {
	 := &CaseClause{Case: .pos}
	.next()
	.Word = .getWord()
	if .Word == nil {
		.followErr(.Case, "case", noQuote("a word"))
	}
	 := "esac"
	.got(_Newl)
	if ,  := .gotRsrv("{");  {
		.In = 
		.Braces = true
		.checkLang(.Pos(), LangMirBSDKorn, "`case i {`")
		 = "}"
	} else {
		.In = .followRsrv(.Case, "case x", "in")
	}
	.Items = .caseItems()
	.Last, .accComs = .accComs, nil
	.Esac = .stmtEnd(, "case", )
	.Cmd = 
}

func ( *Parser) ( string) ( []*CaseItem) {
	.got(_Newl)
	for .tok != _EOF && (.tok != _LitWord || .val != ) {
		 := &CaseItem{}
		.Comments, .accComs = .accComs, nil
		.got(leftParen)
		for .tok != _EOF {
			if  := .getWord();  == nil {
				.curErr("case patterns must consist of words")
			} else {
				.Patterns = append(.Patterns, )
			}
			if .tok == rightParen {
				break
			}
			if !.got(or) {
				.curErr("case patterns must be separated with %#q", or)
			}
		}
		 := .preNested(switchCase)
		.next()
		.Stmts, .Last = .stmtList()
		.postNested()
		switch .tok {
		case dblSemicolon, semiAnd, dblSemiAnd, semiOr:
		default:
			.Op = Break
			 = append(, )
			return 
		}
		.Last = append(.Last, .accComs...)
		.accComs = nil
		.OpPos = .pos
		.Op = CaseOperator(.tok)
		.next()
		.got(_Newl)

		// Split the comments:
		//
		// case x in
		// a)
		//   foo
		//   ;;
		//   # comment for a
		// # comment for b
		// b)
		//   [...]
		 := len(.accComs)
		for ,  := range slices.Backward(.accComs) {
			if .Pos().Col() != .pos.Col() {
				break
			}
			 = 
		}
		.Comments = append(.Comments, .accComs[:]...)
		.accComs = .accComs[:]

		 = append(, )
	}
	return 
}

func ( *Parser) ( *Stmt) {
	 := &TestClause{Left: .pos}
	 := .preNested(testExpr)
	.next()
	if .X = .testExprBinary(false); .X == nil {
		.followErrExp(.Left, dblLeftBrack)
	}
	.Right = .pos
	if ,  := .gotRsrv("]]"); ! {
		.matchingErr(.Left, dblLeftBrack, dblRightBrack)
	}
	.postNested()
	.Cmd = 
}

func ( *Parser) ( bool) TestExpr {
	.got(_Newl)
	var  TestExpr
	if  {
		 = .testExprUnary()
	} else {
		 = .(true)
	}
	if  == nil {
		return 
	}
	.got(_Newl)
	switch .tok {
	case andAnd, orOr:
	case _LitWord:
		if .val == "]]" {
			return 
		}
		if .tok = token(testBinaryOp(.val)); .tok == illegalTok {
			.curErr("not a valid test operator: %#q", .val)
		}
	case rdrIn, rdrOut:
	case _EOF, rightParen:
		return 
	case _Lit:
		.curErr("test operator words must consist of a single literal")
	default:
		.curErr("not a valid test operator: %#q", .tok)
	}
	 := &BinaryTest{
		OpPos: .pos,
		Op:    BinTestOperator(.tok),
		X:     ,
	}
	switch .Op {
	case AndTest, OrTest:
		.next()
		if .Y = .(false); .Y == nil {
			.followErrExp(.OpPos, .Op)
		}
	case TsReMatch:
		.checkLang(.pos, langBashLike|LangZsh, "regex tests")
		.rxOpenParens = 0
		.rxFirstPart = true
		// TODO(mvdan): Using nested states within a regex will break in
		// all sorts of ways. The better fix is likely to use a stop
		// token, like we do with heredocs.
		.quote = testExprRegexp
		fallthrough
	default:
		if ,  := .X.(*Word); ! {
			.posErr(.OpPos, "expected %#q, %#q or %#q after complex expr",
				AndTest, OrTest, dblRightBrack)
		}
		.next()
		.Y = .followWordTok(token(.Op), .OpPos)
	}
	return 
}

func ( *Parser) () TestExpr {
	switch .tok {
	case _EOF, rightParen:
		return nil
	case _LitWord:
		 := token(testUnaryOp(.val))
		switch  {
		case illegalTok:
		case tsRefVar, tsModif: // not available in mksh
			if .lang.in(langBashLike) {
				.tok = 
			}
		default:
			.tok = 
		}
	}
	switch .tok {
	case exclMark:
		 := &UnaryTest{OpPos: .pos, Op: TsNot}
		.next()
		if .X = .testExprBinary(false); .X == nil {
			.followErrExp(.OpPos, .Op)
		}
		return 
	case tsExists, tsRegFile, tsDirect, tsCharSp, tsBlckSp, tsNmPipe,
		tsSocket, tsSmbLink, tsSticky, tsGIDSet, tsUIDSet, tsGrpOwn,
		tsUsrOwn, tsModif, tsRead, tsWrite, tsExec, tsNoEmpty,
		tsFdTerm, tsEmpStr, tsNempStr, tsOptSet, tsVarSet, tsRefVar:
		 := &UnaryTest{OpPos: .pos, Op: UnTestOperator(.tok)}
		.next()
		.X = .followWordTok(token(.Op), .OpPos)
		return 
	case leftParen:
		 := &ParenTest{Lparen: .pos}
		.next()
		if .X = .testExprBinary(false); .X == nil {
			.followErrExp(.Lparen, leftParen)
		}
		.Rparen = .matched(.Lparen, leftParen, rightParen)
		return 
	case _LitWord:
		if .val == "]]" {
			return nil
		}
		fallthrough
	default:
		if  := .getWord();  != nil {
			return 
		}
		// otherwise we'd return a typed nil above
		return nil
	}
}

func ( *Parser) ( *Stmt) {
	 := &DeclClause{Variant: .lit(.pos, .val)}
	.next()
	for !.stopToken() && !.peekRedir() {
		if .hasValidIdent() {
			.Args = append(.Args, .getAssign(false))
		} else if .tok.isLit() && .eqlOffs > 0 && !strings.Contains(.val[:.eqlOffs], "{") {
			.curErr("invalid var name")
		} else if .tok == _LitWord && ValidName(.val) {
			.Args = append(.Args, &Assign{
				Naked: true,
				Name:  .getLit(),
			})
		} else if  := .getWord();  != nil {
			.Args = append(.Args, &Assign{
				Naked: true,
				Value: ,
			})
		} else {
			.followErr(.pos, .Variant.Value, noQuote("names or assignments"))
		}
	}
	.Cmd = 
}

func isBashCompoundCommand( token,  string) bool {
	switch  {
	case leftParen, dblLeftParen:
		return true
	case _LitWord:
		switch  {
		case "{", "if", "while", "until", "for", "case", "[[",
			"coproc", "let", "function", "declare", "local",
			"export", "readonly", "typeset", "nameref":
			return true
		}
	}
	return false
}

func ( *Parser) ( *Stmt) {
	 := &TimeClause{Time: .pos}
	.next()
	if ,  := .gotRsrv("-p");  {
		.PosixFormat = true
	}
	.Stmt = .gotStmtPipe(&Stmt{Position: .pos}, false)
	.Cmd = 
}

func ( *Parser) ( *Stmt) {
	 := &CoprocClause{Coproc: .pos}
	if .next(); isBashCompoundCommand(.tok, .val) {
		// has no name
		.Stmt = .gotStmtPipe(&Stmt{Position: .pos}, false)
		.Cmd = 
		return
	}
	.Name = .getWord()
	.Stmt = .gotStmtPipe(&Stmt{Position: .pos}, false)
	if .Stmt == nil {
		if .Name == nil {
			.posErr(.Coproc, "coproc clause requires a command")
			return
		}
		// name was in fact the stmt
		.Stmt = &Stmt{Position: .Name.Pos()}
		.Stmt.Cmd = .call(.Name)
		.Name = nil
	} else if .Name != nil {
		if ,  := .Stmt.Cmd.(*CallExpr);  {
			// name was in fact the start of a call
			.Args = append([]*Word{.Name}, .Args...)
			.Name = nil
		}
	}
	.Cmd = 
}

func ( *Parser) ( *Stmt) {
	 := &LetClause{Let: .pos}
	 := .preNested(arithmExprLet)
	.next()
	for !.stopToken() && !.peekRedir() {
		 := .arithmExpr(true)
		if  == nil {
			break
		}
		.Exprs = append(.Exprs, )
	}
	if len(.Exprs) == 0 {
		.followErrExp(.Let, "let")
	}
	.postNested()
	.Cmd = 
}

func ( *Parser) ( *Stmt) {
	 := .pos
	.next()
	 := make([]*Lit, 0, 1)
	for .tok == _LitWord && .val != "{" {
		 = append(, .lit(.pos, .val))
		.next()
	}
	 := .got(leftParen)
	switch len() {
	case 0:
		if  || (.tok == _LitWord && .val == "{") {
			.checkLang(, LangZsh, "anonymous functions")
		} else if !.lang.in(LangZsh) {
			.followErr(, "function", noQuote("a name"))
		}
		 = nil // avoid non-nil zero-length slices
	case 1:
		// allowed in all variants
	default:
		.checkLang(, LangZsh, "multi-name functions")
	}
	if  {
		.follow(, "function foo(", rightParen)
	}
	.funcDecl(, , true, , ...)
}

func ( *Parser) ( *Stmt) {
	 := &TestDecl{Position: .pos}
	.next()
	if .Description = .getWord(); .Description == nil {
		.followErr(.Position, "@test", noQuote("a description word"))
	}
	if .Body = .getStmt(false, false, true); .Body == nil {
		.followErr(.Position, `@test "desc"`, noQuote("a statement"))
	}
	.Cmd = 
}

func ( *Parser) ( *CallExpr) {
	// Note that we'll only keep the first error that happens.
	if len(.Args) > 0 {
		if  := .Args[0].Lit(); isBashCompoundCommand(_LitWord, ) {
			.checkLang(.pos, langBashLike, "the %#q builtin", )
		}
	}
	.curErr("a command can only contain words and redirects; encountered %#q", .tok)
}

func ( *Parser) ( *Stmt,  *Word,  bool) {
	 := .call()
	if  == nil {
		.Args = .Args[:0]
	}
	if  {
		.Assigns = append(.Assigns, .getAssign(true))
	}
:
	for {
		switch .tok {
		case _EOF, _Newl, semicolon, and, or, andAnd, orOr, orAnd, andPipe, andBang,
			dblSemicolon, semiAnd, dblSemiAnd, semiOr:
			break 
		case _LitWord:
			if len(.Args) == 0 && .hasValidIdent() {
				.Assigns = append(.Assigns, .getAssign(true))
				break
			}
			// Avoid failing later with the confusing "} can only be used to close a block".
			if .val == "{" &&  != nil && .Lit() == "function" {
				.checkLang(.pos, langBashLike, `the "function" builtin`)
			}
			// Zsh does not require a semicolon to close a block.
			if .lang.in(LangZsh) && .val == "}" {
				break 
			}
			 := .wordOne(.lit(.pos, .val))
			.next()
			if .lang.in(LangZsh) && !.spaced {
				.Parts = append(.Parts, .wordParts(nil)...)
			}
			.Args = append(.Args, )
		case _Lit:
			if len(.Args) == 0 && .hasValidIdent() {
				.Assigns = append(.Assigns, .getAssign(true))
				break
			}
			.Args = append(.Args, .wordAnyNumber())
		case bckQuote:
			if .backquoteEnd() {
				break 
			}
			fallthrough
		case dollBrace, dollDblParen, dollParen, dollar, cmdIn, assgnParen, cmdOut,
			sglQuote, dollSglQuote, dblQuote, dollDblQuote, dollBrack,
			globQuest, globStar, globPlus, globAt, globExcl:
			.Args = append(.Args, .wordAnyNumber())
		case dblLeftParen:
			.curErr("%#q can only be used to open an arithmetic cmd", .tok)
		case leftParen:
			if .lang.in(LangZsh) && .r != ')' {
				.Args = append(.Args, .wordAnyNumber())
				break
			}
			.unexpectedInCallExpr()
		case rightParen:
			if .quote == subCmd {
				break 
			}
			.unexpectedInCallExpr()
		default:
			if .peekRedir() {
				.doRedirect()
				continue
			}
			.unexpectedInCallExpr()
		}
	}
	if len(.Args) == 0 {
		.Args = nil
	} else {
		for ,  := range .Assigns {
			if .Index != nil || .Array != nil {
				.posErr(.Pos(), "inline variables cannot be arrays")
			}
		}
	}
	.Cmd = 
}

func ( *Parser) ( *Stmt,  Pos, ,  bool,  ...*Lit) {
	 := &FuncDecl{
		Position: ,
		RsrvWord: ,
		Parens:   ,
	}
	if len() == 1 {
		.Name = [0]
	} else {
		.Names = 
	}
	.got(_Newl)
	// TODO: reject any body which isn't a compound command, like a quoted word
	if .Body = .getStmt(false, false, true); .Body == nil {
		.followErr(.Pos(), "foo()", noQuote("a statement"))
	}
	.Cmd = 
}