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

package syntax

import (
	
	
	
)

func asciiLetter[ rune | byte]( ) bool {
	return ('a' <=  &&  <= 'z') || ('A' <=  &&  <= 'Z')
}

func asciiDigit[ rune | byte]( ) bool {
	return  >= '0' &&  <= '9'
}

// bytes that form or start a token
func regOps( rune) bool {
	switch  {
	case ';', '"', '\'', '(', ')', '$', '|', '&', '>', '<', '`':
		return true
	}
	return false
}

// tokenize these inside parameter expansions
func paramOps( rune) bool {
	switch  {
	case '}', '#', '!', ':', '-', '+', '=', '?', '%', '[', ']', '/', '^',
		',', '@', '*':
		return true
	}
	return false
}

// tokenize these inside arithmetic expansions
func arithmOps( rune) bool {
	switch  {
	case '+', '-', '!', '~', '*', '/', '%', '(', ')', '^', '<', '>', ':', '=',
		',', '?', '|', '&', '[', ']', '#', '.':
		return true
	}
	return false
}

func bquoteEscaped( byte) bool {
	switch  {
	case '$', '`', '\\':
		return true
	}
	return false
}

// Sentinel rune values used by [Parser.rune]. They are above [utf8.MaxRune]
// so that they can never collide with runes decoded from the input.
const (
	runeEOF rune = utf8.MaxRune + 1 // the input ran out, or we stopped early
	escNewl rune = utf8.MaxRune + 2 // an escaped newline, "\\\n"
)

func ( *Parser) () rune {
	if .r == '\n' || .r == escNewl {
		// p.r instead of b so that newline
		// character positions don't have col 0.
		.line++
		.col = 0
	}
	.col += int64(.w)
	 := 0
:
	if .bsp >= uint(len(.bs)) && .fill() == 0 {
		if len(.bs) == 0 {
			// Necessary for the last position to be correct.
			// TODO: this is not exactly intuitive; figure out a better way.
			.bsp = 1
		}
		.r = runeEOF
		.w = 1
		return .r
	}
	if  := .bs[.bsp];  < utf8.RuneSelf {
		.bsp++
		switch  {
		case '\x00':
			// Ignore null bytes while parsing, like bash.
			.col++
			goto 
		case '\r':
			if .peek() == '\n' { // \r\n turns into \n
				.col++
				goto 
			}
		case '\\':
			if .r == '\\' {
			} else if .peek() == '\n' {
				.bsp++
				.w, .r = 1, escNewl
				return escNewl
			} else if ,  := .peekTwo();  == '\r' &&  == '\n' { // \\\r\n turns into \\\n
				.col++
				.bsp += 2
				.w, .r = 2, escNewl
				return escNewl
			}
			// TODO: why is this necessary to ensure correct position info?
			.readEOF = false
			if .openBquotes > 0 && .bsp < uint(len(.bs)) &&
				(( < .openBquotes && bquoteEscaped(.bs[.bsp])) ||
					// Backquotes within double quotes also escape double quotes.
					( < .openBquoteDbls && .bs[.bsp] == '"')) {
				// We turn backquote command substitutions into $(),
				// so we remove the extra backslashes needed by the backquotes.
				++
				.col++
				goto 
			}
		}
		if  == '`' {
			.lastBquoteEsc = 
		}
		if .litBs != nil {
			.litBs = append(.litBs, )
		}
		.w, .r = 1, rune()
		return .r
	}
:
	var  int
	.r,  = utf8.DecodeRune(.bs[.bsp:])
	if .r == utf8.RuneError && !utf8.FullRune(.bs[.bsp:]) {
		// we need more bytes to read a full non-ascii rune
		if .fill() > 0 {
			goto 
		}
	}
	if .litBs != nil {
		.litBs = append(.litBs, .bs[.bsp:.bsp+uint()]...)
	}
	.bsp += uint()
	if .r == utf8.RuneError &&  == 1 {
		.posErr(.nextPos(), "invalid UTF-8 encoding")
	}
	.w = 
	return .r
}

// fill reads more bytes from the input src into readBuf.
// Any bytes that had not yet been used at the end of the buffer
// are slid into the beginning of the buffer.
// The number of read bytes is returned, which is at least one
// unless a read error occurred, such as [io.EOF].
func ( *Parser) () ( int) {
	if .readEOF || .r == runeEOF {
		// If the reader already gave us [io.EOF], do not try again.
		// If we decided to stop for any reason, do not bother reading either.
		return 0
	}
	.offs += int64(.bsp)
	 := len(.bs) - int(.bsp)
	copy(.readBuf[:], .readBuf[.bsp:])
:
	,  := 0, .readErr
	if  == nil {
		,  = .src.Read(.readBuf[:])
		.readErr = 
		if  == io.EOF {
			.readEOF = true
		}
	}
	if  == 0 {
		if  == nil {
			goto 
		}
		// don't use p.errPass as we don't want to overwrite p.tok
		if  != io.EOF {
			.err = 
		}
		if  > 0 {
			.bs = .readBuf[:]
		} else {
			.bs = nil
		}
	} else {
		.bs = .readBuf[:+]
	}
	.bsp = 0
	return 
}

func ( *Parser) () {
	 := .r
	if .quote != hdocBody && .quote != hdocBodyTabs {
		// Heredocs handle escaped newlines in a special way, but others do not.
		for  == escNewl {
			 = .rune()
		}
	}
	.pos = .nextPos()
	switch .quote {
	case runeByRune:
		.tok = illegalTok
	case dblQuotes:
		switch  {
		case '`', '"', '$':
			.tok = .dqToken()
		default:
			.advanceLitDquote()
		}
	case hdocBody, hdocBodyTabs:
		switch  {
		case '`', '$':
			.tok = .dqToken()
		default:
			.advanceLitHdoc()
		}
	case paramExpRepl:
		if  == '/' {
			.rune()
			.tok = slash
			break
		}
		fallthrough
	case paramExpExp:
		switch  {
		case '}':
			.tok = .paramToken()
		case '`', '"', '$', '\'':
			.tok = .regToken()
		default:
			.advanceLitOther()
		}
	}
	if .err != nil {
		.tok = _EOF
	}
}

func ( *Parser) () {
	if .r == runeEOF {
		.tok = _EOF
		return
	}
	.spaced = false
	if .quote&allKeepSpaces != 0 {
		.nextKeepSpaces()
		return
	}
	 := .r
	for  == escNewl {
		 = .rune()
	}
:
	for {
		switch  {
		case runeEOF:
			.tok = _EOF
			return
		case escNewl:
			 = .rune()
		case ' ', '\t', '\r':
			.spaced = true
			 = .rune()
		case '\n':
			if .tok == _Newl {
				// merge consecutive newline tokens
				 = .rune()
				continue
			}
			.spaced = true
			.tok = _Newl
			if .quote != hdocWord && len(.heredocs) > .buriedHdocs {
				.doHeredocs()
			}
			return
		default:
			break 
		}
	}
	if .stopAt != nil && (.spaced || .tok == illegalTok || .stopToken()) {
		// Note that the buffer may have been refilled since we read r,
		// such as when peeking at the byte which follows a backslash,
		// in which case r's bytes are gone and we cannot match on them.
		 := uint(utf8.RuneLen())
		if .bsp >=  && bytes.HasPrefix(.bs[.bsp-:], .stopAt) {
			.r = runeEOF
			.w = 1
			.tok = _EOF
			return
		}
	}
	.pos = .nextPos()
	switch {
	case .quote&allRegTokens != 0:
		switch  {
		case ';', '"', '\'', '(', ')', '$', '|', '&', '>', '<', '`':
			if  == '<' && .lang.in(LangZsh) && .zshNumRange() {
				.advanceLitNone()
				return
			}
			.tok = .regToken()
		case '#':
			// If we're parsing $foo#bar, ${foo}#bar, 'foo'#bar, or "foo"#bar,
			// #bar is a continuation of the same word, not a comment.
			// The same applies inside [[ ]] tests, where '#' has no comment meaning.
			if !.spaced && (.quote == unquotedWordCont || .quote == testExpr) {
				.advanceLitNone()
				return
			}
			 = .rune()
			.newLit()
		:
			for {
				switch  {
				case '\n', runeEOF:
					break 
				case escNewl:
					.litBs = append(.litBs, '\\', '\n')
					break 
				case '`':
					if .backquoteEnd() {
						break 
					}
				}
				 = .rune()
			}
			if .keepComments {
				*.curComs = append(*.curComs, Comment{
					Hash: .pos,
					Text: .endLit(),
				})
			} else {
				.litBs = nil
			}
			.()
		case '[':
			// `[` only starts an `[idx]=val` element when it begins a new word;
			// otherwise it continues a glob like `foo[0-9]`.
			if .quote == arrayElems && (.spaced || .tok == leftParen || .tok == _Newl) {
				.rune()
				.tok = leftBrack
			} else {
				.advanceLitNone()
			}
		case '=':
			if .peek() == '(' {
				.rune()
				.rune()
				.tok = assgnParen
			} else if .quote == arrayElems {
				.rune()
				.tok = assgn
			} else {
				.advanceLitNone()
			}
		case '?', '*', '+', '@', '!':
			if .extendedGlob() {
				switch  {
				case '?':
					.tok = globQuest
				case '*':
					.tok = globStar
				case '+':
					.tok = globPlus
				case '@':
					.tok = globAt
				case '!':
					.tok = globExcl
				}
				.rune()
				.rune()
			} else {
				.advanceLitNone()
			}
		default:
			.advanceLitNone()
		}
	case .quote == paramExpArithm &&  == '#':
		// '#' is mksh's unsigned prefix, which only [ArithmExp] and [ArithmCmd]
		// can represent, so in a subscript it starts a literal instead;
		// it can be part of an associative array key, like in ${args[cmd,#]}.
		.advanceLitOther()
	case .quote&allArithmExpr != 0 && arithmOps():
		.tok = .arithmToken()
	case .quote&allParamExp != 0 && paramOps():
		.tok = .paramToken()
	case .quote == testExprRegexp:
		if !.rxFirstPart && .spaced {
			.quote = testExpr
			goto 
		}
		.rxFirstPart = false
		switch  {
		case ';', '"', '\'', '$', '&', '>', '<', '`':
			.tok = .regToken()
		case ')':
			if .rxOpenParens > 0 {
				// continuation of open paren
				.advanceLitRe()
			} else {
				.tok = rightParen
				.quote = testExpr
				.rune() // we are tokenizing manually
			}
		default: // including '(', '|'
			.advanceLitRe()
		}
	case regOps():
		.tok = .regToken()
	default:
		.advanceLitOther()
	}
	if .err != nil {
		.tok = _EOF
	}
}

// extendedGlob determines whether we're parsing a Bash extended globbing expression.
// For example, whether `*` or `@` are followed by `(` to form `@(foo)`.
func ( *Parser) () bool {
	if .lang.in(LangZsh) {
		// Zsh supports Bash extended globs via the KSH_GLOB option.
		// In Bash we would parse extended globs as [ExtGlob] nodes,
		// but trying to do that in Zsh would cause ambiguity with glob qualifiers.
		// Just like glob qualifiers, parse extended globs as literals in Zsh.
		return false
	}
	if .val == "function" {
		// We don't support e.g. `function @() { ... }` at the moment, but we could.
		return false
	}
	if .peek() == '(' {
		// NOTE: empty pattern list is a valid globbing syntax like `@()`,
		// but we'll operate on the "likelihood" that it is a function;
		// only tokenize if its a non-empty pattern list.
		// We do this after peeking for just one byte, so that the input `echo *`
		// followed by a newline does not hang an interactive shell parser until
		// another byte is input.
		,  := .peekTwo()
		return  != ')'
	}
	return false
}

func ( *Parser) () byte {
	if int(.bsp) >= len(.bs) {
		.fill()
	}
	if int(.bsp) >= len(.bs) {
		return utf8.RuneSelf
	}
	return .bs[.bsp]
}

func ( *Parser) () (byte, byte) {
	// TODO: This should loop for slow readers, e.g. those providing one byte at
	// a time. Use a loop and test it with [testing/iotest.OneByteReader].
	if int(.bsp+1) >= len(.bs) {
		.fill()
	}
	if int(.bsp) >= len(.bs) {
		return utf8.RuneSelf, utf8.RuneSelf
	}
	if int(.bsp+1) >= len(.bs) {
		return .bs[.bsp], utf8.RuneSelf
	}
	return .bs[.bsp], .bs[.bsp+1]
}

func ( *Parser) ( rune) token {
	switch  {
	case '\'':
		.rune()
		return sglQuote
	case '"':
		.rune()
		return dblQuote
	case '`':
		// Don't call p.rune, as we need to work out p.openBquotes to
		// properly handle backslashes in the lexer.
		return bckQuote
	case '&':
		switch .rune() {
		case '&':
			.rune()
			return andAnd
		case '>':
			switch .rune() {
			case '|':
				.rune()
				return rdrAllClob
			case '!':
				if .lang.in(LangZsh) {
					.rune()
					return rdrAllClob
				}
			case '>':
				switch .rune() {
				case '|':
					.rune()
					return appAllClob
				case '!':
					if .lang.in(LangZsh) {
						.rune()
						return appAllClob
					}
				}
				return appAll
			}
			return rdrAll
		case '|':
			if .lang.in(LangZsh) {
				.rune()
				return andPipe
			}
		case '!':
			if .lang.in(LangZsh) {
				.rune()
				return andBang
			}
		}
		return and
	case '|':
		switch .rune() {
		case '|':
			.rune()
			return orOr
		case '&':
			if !.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
				break
			}
			.rune()
			return orAnd
		}
		return or
	case '$':
		switch .rune() {
		case '\'':
			if !.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
				break
			}
			.rune()
			return dollSglQuote
		case '"':
			if !.lang.in(langBashLike | LangMirBSDKorn) {
				break
			}
			.rune()
			return dollDblQuote
		case '{':
			.rune()
			return dollBrace
		case '[':
			if !.lang.in(langBashLike) {
				// latter to not tokenise ${$[@]} as $[
				break
			}
			.rune()
			return dollBrack
		case '(':
			if .rune() == '(' {
				.rune()
				return dollDblParen
			}
			return dollParen
		}
		return dollar
	case '(':
		if .rune() == '(' && .lang.in(langBashLike|LangMirBSDKorn|LangZsh) && .quote != testExpr {
			.rune()
			return dblLeftParen
		}
		return leftParen
	case ')':
		.rune()
		return rightParen
	case ';':
		switch .rune() {
		case ';':
			if .rune() == '&' && .lang.in(langBashLike) {
				.rune()
				return dblSemiAnd
			}
			return dblSemicolon
		case '&':
			if !.lang.in(langBashLike | LangMirBSDKorn | LangZsh) {
				break
			}
			.rune()
			return semiAnd
		case '|':
			if !.lang.in(LangMirBSDKorn | LangZsh) {
				break
			}
			.rune()
			return semiOr
		}
		return semicolon
	case '<':
		switch .rune() {
		case '<':
			switch .rune() {
			case '-':
				.rune()
				return dashHdoc
			case '<':
				.rune()
				return wordHdoc
			}
			return hdoc
		case '>':
			.rune()
			return rdrInOut
		case '&':
			.rune()
			return dplIn
		case '(':
			if !.lang.in(langBashLike | LangZsh) {
				break
			}
			.rune()
			return cmdIn
		}
		return rdrIn
	case '>':
		switch .rune() {
		case '>':
			switch .rune() {
			case '|':
				.rune()
				return appClob
			case '!':
				if .lang.in(LangZsh) {
					.rune()
					return appClob
				}
			case '&':
				if !.lang.in(LangZsh) {
					break
				}
				switch .rune() {
				case '|':
					.rune()
					return appAllClob // >>&| is an alias for &>>|
				case '!':
					.rune()
					return appAllClob // >>&! is an alias for &>>|
				}
				return appAll // >>& is an alias for &>>
			}
			return appOut
		case '&':
			 = .rune()
			if .lang.in(LangZsh) {
				switch  {
				case '|':
					.rune()
					return rdrAllClob // >&| is an alias for &>|
				case '!':
					.rune()
					return rdrAllClob // >&! is an alias for &>|
				}
			}
			return dplOut
		case '|':
			.rune()
			return rdrClob
		case '!':
			if .lang.in(LangZsh) {
				.rune()
				return rdrClob
			}
		case '(':
			if !.lang.in(langBashLike | LangZsh) {
				break
			}
			.rune()
			return cmdOut
		}
		return rdrOut
	}
	panic("unreachable")
}

func ( *Parser) ( rune) token {
	switch  {
	case '"':
		.rune()
		return dblQuote
	case '`':
		// Don't call p.rune, as we need to work out p.openBquotes to
		// properly handle backslashes in the lexer.
		return bckQuote
	case '$':
		switch .rune() {
		case '{':
			.rune()
			return dollBrace
		case '[':
			if !.lang.in(langBashLike) {
				break
			}
			.rune()
			return dollBrack
		case '(':
			if .rune() == '(' {
				.rune()
				return dollDblParen
			}
			return dollParen
		}
		return dollar
	}
	panic("unreachable")
}

func ( *Parser) ( rune) token {
	switch  {
	case '}':
		.rune()
		return rightBrace
	case ':':
		switch .rune() {
		case '+':
			.rune()
			return colPlus
		case '-':
			.rune()
			return colMinus
		case '?':
			.rune()
			return colQuest
		case '=':
			.rune()
			return colAssgn
		case '#':
			.rune()
			return colHash
		case '|':
			.rune()
			return colPipe
		case '*':
			.rune()
			return colStar
		}
		return colon
	case '+':
		.rune()
		return plus
	case '-':
		.rune()
		return minus
	case '?':
		.rune()
		return quest
	case '=':
		.rune()
		return assgn
	case '%':
		if .rune() == '%' {
			.rune()
			return dblPerc
		}
		return perc
	case '#':
		if .rune() == '#' {
			.rune()
			return dblHash
		}
		return hash
	case '!':
		.rune()
		return exclMark
	case ']':
		.rune()
		return rightBrack
	case '/':
		if .rune() == '/' {
			.rune()
			return dblSlash
		}
		return slash
	case '^':
		if .rune() == '^' {
			.rune()
			return dblCaret
		}
		return caret
	case ',':
		if .rune() == ',' {
			.rune()
			return dblComma
		}
		return comma
	case '@':
		.rune()
		return at
	case '*':
		.rune()
		return star

	// This func gets called by the parser in [runeByRune] mode;
	// we need to handle EOF and unexpected runes.
	case runeEOF:
		return _EOF
	default:
		return illegalTok
	}
}

func ( *Parser) ( rune) token {
	switch  {
	case '!':
		if .rune() == '=' {
			.rune()
			return nequal
		}
		return exclMark
	case '=':
		if .rune() == '=' {
			.rune()
			return equal
		}
		return assgn
	case '~':
		.rune()
		return tilde
	case '(':
		.rune()
		return leftParen
	case ')':
		.rune()
		return rightParen
	case '&':
		switch .rune() {
		case '&':
			if .rune() == '=' && .lang.in(LangZsh) {
				.rune()
				return andBoolAssgn
			}
			return andAnd
		case '=':
			.rune()
			return andAssgn
		}
		return and
	case '|':
		switch .rune() {
		case '|':
			if .rune() == '=' && .lang.in(LangZsh) {
				.rune()
				return orBoolAssgn
			}
			return orOr
		case '=':
			.rune()
			return orAssgn
		}
		return or
	case '<':
		switch .rune() {
		case '<':
			if .rune() == '=' {
				.rune()
				return shlAssgn
			}
			return hdoc
		case '=':
			.rune()
			return lequal
		}
		return rdrIn
	case '>':
		switch .rune() {
		case '>':
			if .rune() == '=' {
				.rune()
				return shrAssgn
			}
			return appOut
		case '=':
			.rune()
			return gequal
		}
		return rdrOut
	case '+':
		switch .rune() {
		case '+':
			.rune()
			return addAdd
		case '=':
			.rune()
			return addAssgn
		}
		return plus
	case '-':
		switch .rune() {
		case '-':
			.rune()
			return subSub
		case '=':
			.rune()
			return subAssgn
		}
		return minus
	case '%':
		if .rune() == '=' {
			.rune()
			return remAssgn
		}
		return perc
	case '*':
		switch .rune() {
		case '*':
			if .rune() == '=' && .lang.in(LangZsh) {
				.rune()
				return powAssgn
			}
			return power
		case '=':
			.rune()
			return mulAssgn
		}
		return star
	case '/':
		if .rune() == '=' {
			.rune()
			return quoAssgn
		}
		return slash
	case '^':
		switch .rune() {
		case '^':
			if .rune() == '=' && .lang.in(LangZsh) {
				.rune()
				return xorBoolAssgn
			}
			return dblCaret
		case '=':
			.rune()
			return xorAssgn
		}
		return caret
	case '[':
		.rune()
		return leftBrack
	case ']':
		.rune()
		return rightBrack
	case ',':
		.rune()
		return comma
	case '?':
		.rune()
		return quest
	case ':':
		.rune()
		return colon
	case '#':
		.rune()
		return hash
	case '.':
		.rune()
		return period
	}
	panic("unreachable")
}

func ( *Parser) ( rune) {
	switch {
	case  < utf8.RuneSelf:
		.litBs = .litBuf[:1]
		.litBs[0] = byte()
	case  == runeEOF ||  == escNewl:
		// sentinel runes not present in the input as-is
		.litBs = .litBuf[:0]
	default:
		 := utf8.RuneLen()
		.litBs = append(.litBuf[:0], .bs[.bsp-uint():.bsp]...)
	}
}

func ( *Parser) () ( string) {
	if .r == runeEOF || .r == escNewl {
		 = string(.litBs)
	} else {
		 = string(.litBs[:len(.litBs)-.w])
	}
	.litBs = nil
	return 
}

func ( *Parser) () bool {
	 := .litBs[:len(.litBs)-1]
	if [0] == '{' && [len()-1] == '}' {
		 := [1 : len()-1]
		// Bash also allows an array element such as {name[idx]}.
		if .lang.in(langBashLike) && len() > 0 && [len()-1] == ']' {
			if  := bytes.IndexByte(, '[');  > 0 &&  < len()-2 {
				 = [:]
			}
		}
		return ValidName(string())
	}
	return numberLiteral()
}

func positionalRuneParam[ rune | byte]( ) bool {
	switch  {
	case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
		return true
	}
	return false
}

func singleRuneParam[ rune | byte]( ) bool {
	switch  {
	case '@', '*', '#', '$', '?', '!', '-':
		return true
	}
	return positionalRuneParam()
}

func paramNameRune[ rune | byte]( ) bool {
	return asciiLetter() || asciiDigit() ||  == '_'
}

// paramNameStartRune reports whether a parameter name can begin with r,
// be it a single-rune name like $@ or a regular name like $foo.
func paramNameStartRune[ rune | byte]( ) bool {
	return singleRuneParam() || paramNameRune()
}

func ( *Parser) ( rune) {
	 := _LitWord
:
	for .newLit();  != runeEOF;  = .rune() {
		switch  {
		case '\\': // escaped byte follows
			.rune()
		case '\'', '"', '`', '$':
			 = _Lit
			break 
		case '}':
			if .quote&allParamExp != 0 {
				break 
			}
		case '/':
			if .quote != paramExpExp {
				break 
			}
		case ':', '=', '%', '^', ',', '?', '!', '~', '*':
			if .quote&allArithmExpr != 0 {
				break 
			}
		case '.':
			if !.lang.in(LangZsh) && .quote&allArithmExpr != 0 {
				break 
			}
		case '[', ']':
			if .lang.in(langBashLike|LangMirBSDKorn|LangZsh) && .quote&allArithmExpr != 0 {
				break 
			}
			fallthrough
		case '+', '-', ' ', '\t', ';', '&', '>', '<', '|', '(', ')', '\n', '\r':
			if .quote&allKeepSpaces == 0 {
				break 
			}
		}
	}
	.tok, .val = , .endLit()
}

// zshNumRange peeks at the bytes after '<' to check for a zsh numeric
// range glob pattern like <->, <5->, <-10>, or <5-10>.
func ( *Parser) () bool {
	// Peeking a handful of bytes here should be enough.
	// TODO: This should loop for slow readers, e.g. those providing one byte at
	// a time. Use a loop and test it with [testing/iotest.OneByteReader].
	if int(.bsp) >= len(.bs) {
		.fill()
	}
	 := .bs[.bsp:]
	for len() > 0 && [0] >= '0' && [0] <= '9' {
		 = [1:]
	}
	if len() == 0 || [0] != '-' {
		return false
	}
	 = [1:]
	for len() > 0 && [0] >= '0' && [0] <= '9' {
		 = [1:]
	}
	return len() > 0 && [0] == '>'
}

func ( *Parser) ( rune) {
	.eqlOffs = -1
	 := _LitWord
:
	for .newLit();  != runeEOF;  = .rune() {
		switch  {
		case ' ', '\t', '\n', '\r', '&', '|', ';', ')':
			break 
		case '(':
			break 
		case '\\': // escaped byte follows
			.rune()
		case '>', '<':
			if  == '<' && .lang.in(LangZsh) && .zshNumRange() {
				// Zsh numeric range glob like <-> or <1-100>; consume until '>'.
				for {
					if  = .rune();  == '>' ||  == runeEOF {
						break
					}
				}
				continue
			}
			if .peek() == '(' {
				 = _Lit
			} else if .isLitRedir() {
				 = _LitRedir
			}
			break 
		case '`':
			if .quote != subCmdBckquo {
				 = _Lit
			}
			break 
		case '"', '\'', '$':
			 = _Lit
			break 
		case '?', '*', '+', '@', '!':
			if .extendedGlob() {
				 = _Lit
				break 
			}
		case '=':
			if .eqlOffs < 0 {
				.eqlOffs = len(.litBs) - 1
			}
		case '}':
			if .quote == subCmdBraces && len(.litBs) == 1 {
				// A word-initial `}` closes the substitution even if
				// more characters follow, as in `${ foo;}bar`.
				.rune()
				break 
			}
		case '[':
			if .litBs[0] == '{' && .lang.in(langBashLike) {
				// In bash, words beginning with '{' are always kept whole,
				// so that {name[idx]} literals can prefix a redirect
				// operator below.
				break
			}
			if .lang.in(langBashLike|LangMirBSDKorn|LangZsh) && len(.litBs) > 1 && .litBs[0] != '[' {
				 = _Lit
				break 
			}
		}
	}
	.tok, .val = , .endLit()
}

func ( *Parser) ( rune) {
	 := _LitWord
:
	for .newLit();  != runeEOF;  = .rune() {
		switch  {
		case '"':
			break 
		case '\\': // escaped byte follows
			.rune()
		case escNewl, '`', '$':
			 = _Lit
			break 
		}
	}
	.tok, .val = , .endLit()
}

func ( *Parser) ( rune) {
	// Unlike the rest of nextKeepSpaces quote states, we handle escaped
	// newlines here. If lastTok==_Lit, then we know we're following an
	// escaped newline, so the first line can't end the heredoc.
	 := .tok
	for  == escNewl {
		 = .rune()
		 = _Lit
	}
	.pos = .nextPos()

	.tok = _Lit
	.newLit()
	for .quote == hdocBodyTabs &&  == '\t' {
		 = .rune()
	}
	 := len(.litBs) - 1
	 := .hdocStops[len(.hdocStops)-1]
	for ; ;  = .rune() {
		switch  {
		case escNewl, '$':
			.val = .endLit()
			return
		case '\\': // escaped byte follows
			.rune()
		case '`':
			if !.backquoteEnd() {
				.val = .endLit()
				return
			}
			fallthrough
		case '\n', runeEOF:
			if .parsingDoc {
				if  == runeEOF {
					.tok = _LitWord
					.val = .endLit()
					return
				}
			} else if  == 0 &&  == _Lit {
				// This line starts right after an escaped
				// newline, so it should never end the heredoc.
			} else if  >= 0 {
				// Compare the current line with the stop word.
				 := .litBs[:]
				if  != runeEOF && len() > 0 {
					 = [:len()-1] // minus trailing character
				}
				if bytes.Equal(, ) {
					.tok = _LitWord
					.val = .endLit()[:]
					if .val == "" {
						.tok = _Newl
					}
					.hdocStops[len(.hdocStops)-1] = nil
					return
				}
			}
			if  != '\n' {
				return // hit an unexpected EOF or closing backquote
			}
			for .quote == hdocBodyTabs && .peek() == '\t' {
				.rune()
			}
			 = len(.litBs)
		}
	}
}

func ( *Parser) () *Word {
	 := .r
	.newLit()
	 := .nextPos()
	 := .hdocStops[len(.hdocStops)-1]
	for ; ;  = .rune() {
		if  == runeEOF {
			return nil
		}
		for .quote == hdocBodyTabs &&  == '\t' {
			 = .rune()
		}
		 := len(.litBs) - 1
	:
		for {
			switch  {
			case runeEOF, '\n':
				break 
			case '`':
				if .backquoteEnd() {
					break 
				}
			case escNewl:
				.litBs = append(.litBs, '\\', '\n')
				break 
			}
			 = .rune()
		}
		if  < 0 {
			continue
		}
		// Compare the current line with the stop word.
		 := .litBs[:]
		if  != runeEOF && len() > 0 {
			 = [:len()-1] // minus \n
		}
		if bytes.Equal(, ) {
			.hdocStops[len(.hdocStops)-1] = nil
			 := .endLit()[:]
			if  == "" {
				return nil
			}
			return .wordOne(.lit(, ))
		}
	}
}

func ( *Parser) ( rune) {
	for .newLit(); ;  = .rune() {
		switch  {
		case '\\':
			.rune()
		case '(':
			.rxOpenParens++
		case ')':
			if .rxOpenParens--; .rxOpenParens < 0 {
				.tok, .val = _LitWord, .endLit()
				.quote = testExpr
				return
			}
		case ' ', '\t', '\r', '\n', ';', '&', '>', '<':
			if .rxOpenParens <= 0 {
				.tok, .val = _LitWord, .endLit()
				.quote = testExpr
				return
			}
		case '"', '\'', '$', '`':
			.tok, .val = _Lit, .endLit()
			return
		case runeEOF:
			.tok, .val = _LitWord, .endLit()
			.quote = noState
			return
		}
	}
}

func testUnaryOp( string) UnTestOperator {
	switch  {
	case "!":
		return TsNot
	case "-e", "-a":
		return TsExists
	case "-f":
		return TsRegFile
	case "-d":
		return TsDirect
	case "-c":
		return TsCharSp
	case "-b":
		return TsBlckSp
	case "-p":
		return TsNmPipe
	case "-S":
		return TsSocket
	case "-L", "-h":
		return TsSmbLink
	case "-k":
		return TsSticky
	case "-g":
		return TsGIDSet
	case "-u":
		return TsUIDSet
	case "-G":
		return TsGrpOwn
	case "-O":
		return TsUsrOwn
	case "-N":
		return TsModif
	case "-r":
		return TsRead
	case "-w":
		return TsWrite
	case "-x":
		return TsExec
	case "-s":
		return TsNoEmpty
	case "-t":
		return TsFdTerm
	case "-z":
		return TsEmpStr
	case "-n":
		return TsNempStr
	case "-o":
		return TsOptSet
	case "-v":
		return TsVarSet
	case "-R":
		return TsRefVar
	default:
		return 0
	}
}

func testBinaryOp( string) BinTestOperator {
	switch  {
	case "=":
		return TsMatchShort
	case "==":
		return TsMatch
	case "!=":
		return TsNoMatch
	case "=~":
		return TsReMatch
	case "-nt":
		return TsNewer
	case "-ot":
		return TsOlder
	case "-ef":
		return TsDevIno
	case "-eq":
		return TsEql
	case "-ne":
		return TsNeq
	case "-le":
		return TsLeq
	case "-ge":
		return TsGeq
	case "-lt":
		return TsLss
	case "-gt":
		return TsGtr
	default:
		return 0
	}
}