UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

2,183 lines • 90.1 kB
import { shellWordsOf } from "./shell-words.js";
import { arithmeticCommandEnd, bracePassEnd, countingPassEnd, holdsHashFrom, passesFor, whileReading } from "./counting-pass.js";
export const SHELL_LEX_DIALECT = "bash";
const STARTED_SHELL_READING = { bash: "read", zsh: "stop", unknown: "stop" };
export const QUOTE_KINDS = Object.freeze(["'", '"', "$'", '$"', "\\"]);
export const EXPANSION_KINDS = Object.freeze(["parameter", "command", "process", "arithmetic", "tilde", "brace", "glob"]);
export const UNRESOLVED_REASONS = Object.freeze(["ansi_c_escape", "locale_string", "parameter_text", "subscript_text", "compound_array_value", "trailing_backslash"]);
export const UNRESOLVED_SENTENCE = {
    ansi_c_escape: "an ANSI-C quoted word carries an escape this lexer does not fold",
    locale_string: "a locale-translated string carries text this lexer does not read",
    parameter_text: "a parameter expansion carries text this lexer does not read",
    subscript_text: "a subscript carries text this lexer does not read",
    compound_array_value: "a compound assignment value is a list this lexer does not read",
    trailing_backslash: "a backslash ends the command, which the shell versions read differently (3.2 drops it, 5 keeps it)",
};
export const PARSE_FAILURE_REASONS = Object.freeze([
    "unterminated_single_quote",
    "unterminated_double_quote",
    "unterminated_ansi_c",
    "unterminated_subscript",
    "unterminated_compound_value",
    "unterminated_command_substitution",
    "unterminated_process_substitution",
    "unterminated_parameter_expansion",
    "unterminated_arithmetic_expansion",
    "unterminated_heredoc",
    "undelimited_substitution",
    "undelimited_substitution_heredoc",
    "redirect_without_target",
    "heredoc_without_delimiter",
    "heredoc_delimiter_expands",
    "started_shell_not_bash",
]);
export const PARSE_FAILURE_SENTENCE = {
    unterminated_single_quote: "a single-quoted word never closes",
    unterminated_double_quote: "a double-quoted word never closes",
    unterminated_ansi_c: "an ANSI-C quoted word never closes",
    unterminated_subscript: "a subscript never closes",
    unterminated_compound_value: "a compound assignment value never closes",
    unterminated_command_substitution: "a command substitution never terminates",
    unterminated_process_substitution: "a process substitution never terminates",
    unterminated_parameter_expansion: "a parameter expansion never terminates",
    unterminated_arithmetic_expansion: "an arithmetic expansion never terminates",
    unterminated_heredoc: "a here-document body never terminates",
    undelimited_substitution: "a command substitution carries a construct this lexer cannot delimit",
    undelimited_substitution_heredoc: "a here-document in a command substitution that shell versions end at different places — feed the text as stdin (`git commit -F -`) or reword it",
    redirect_without_target: "a redirection names no target",
    heredoc_without_delimiter: "a here-document operator names no delimiter",
    heredoc_delimiter_expands: "a here-document delimiter is not a plain word",
    started_shell_not_bash: `the shell that runs this command is not known to be ${SHELL_LEX_DIALECT}, the one dialect this lexer reads`,
};
const STATEMENT_RUNS_PAST = new Set(["undelimited_substitution", "undelimited_substitution_heredoc", "heredoc_delimiter_expands", "started_shell_not_bash"]);
export function segmentsAroundStop(source, failure) {
    const stopped = failure.readBefore.at(-1);
    const tokens = stopped.tokens.filter((t) => t.kind !== "heredoc");
    const start = source.length - stopped.text.length;
    const runs = (e) => [...(e.kind === "command" || e.kind === "process" || e.kind === "arithmetic" ? [e.body ?? ""] : []), ...(e.inner ?? []).flatMap(runs)];
    const substitutions = tokens.flatMap((t) => (t.kind === "word" ? assignedWords(t) : t.kind === "redirect" && t.target !== undefined ? [t.target] : [])).flatMap((w) => w.pieces.flatMap((p) => (p.expansion !== undefined ? runs(p.expansion) : [])));
    const currentShell = stopped.currentShell?.filter((b) => substitutions.includes(b));
    const { currentShell: _all, ...rest } = stopped;
    const head = STATEMENT_RUNS_PAST.has(failure.parseFailure.reason) && tokens.length > 0 ? [{ ...rest, text: source.slice(start, Math.max(start, failure.parseFailure.at)), tokens, substitutions, ...(currentShell !== undefined && currentShell.length > 0 ? { currentShell } : {}), spliced: true, stopHead: true }] : [];
    return [...failure.readBefore.slice(0, -1), ...head, ...segmentsPastStop(source, failure)];
}
export const BASH_ONLY_CONSTRUCTS = Object.freeze([
    "ansi_c_quoting",
    "locale_string",
    "append_assignment",
    "subscript_assignment",
    "compound_assignment",
    "here_string",
    "process_substitution",
    "redirect_both",
    "pipe_both",
    "brace_expansion",
]);
export const ANSI_C_ESCAPES = {
    a: "\x07",
    b: "\b",
    e: "\x1b",
    E: "\x1b",
    f: "\f",
    n: "\n",
    r: "\r",
    t: "\t",
    v: "\v",
    "\\": "\\",
    "'": "'",
    '"': '"',
    "?": "?",
};
export const SUBSTITUTION_PLACEHOLDER = " subst";
export const SHELL_CONTROL_PREFIXES = shellWordsOf("control_prefix");
const COMPOUND_OPERAND_COMMANDS = new Set(["alias", "declare", "eval", "export", "let", "local", "readonly", "typeset"]);
const GROUP_WORDS = shellWordsOf("group");
const SCOPE_OPEN_WORDS = shellWordsOf("scope_open");
const DEFINITION_WORDS = shellWordsOf("definition");
const BACKGROUND_WORDS = shellWordsOf("background");
const COMPOUND_OPEN_WORDS = shellWordsOf("compound_open");
const CASE_ARM_WORDS = shellWordsOf("case_arms");
const TIMER_WORDS = shellWordsOf("timer");
export function dollarOpensQuote(text, at) {
    const next = text[past(text, at + 1)];
    if (next !== "'" && next !== '"')
        return false;
    let run = 0;
    for (let k = at - 1; k >= 0 && text[k] === "\\"; k--)
        run += 1;
    return run % 2 === 0;
}
export function ansiCQuoteClose(source, open) {
    for (let i = open + 1; i < source.length; i++) {
        if (source[i] === "\\") {
            i += 1;
            continue;
        }
        if (source[i] === "'")
            return (readUpTo(i), i);
    }
    readUpTo(source.length);
    return undefined;
}
export function literalTildeSpelling(word) {
    return word.startsWith("~") ? `./${word}` : word;
}
function decodeAnsiC(body) {
    let text = "";
    let unresolved = false;
    for (let i = 0; i < body.length; i++) {
        const c = body[i];
        if (c !== "\\" || i + 1 >= body.length) {
            text += c;
            continue;
        }
        const next = body[i + 1];
        const folded = ANSI_C_ESCAPES[next] ?? numericEscapeAt(body, i + 1);
        if (folded === undefined) {
            unresolved = true;
            text += c + next;
            i++;
        }
        else if (typeof folded === "string") {
            text += folded;
            i++;
        }
        else {
            text += folded.char;
            i += folded.length;
        }
    }
    return { text, unresolved };
}
function numericEscapeAt(body, at) {
    const m = /^(?:x([0-9A-Fa-f]{1,2})|([0-7]{1,3})|c([!-~]))/.exec(body.slice(at, at + 4));
    if (m === null || m[3] === "?" || m[3] === "\\" || m[3] === "'")
        return undefined;
    const byte = m[1] !== undefined ? parseInt(m[1], 16) : m[2] !== undefined ? parseInt(m[2], 8) & 0xff : m[3].charCodeAt(0) & 0x1f;
    return byte > 0 && byte < 0x80 ? { char: String.fromCharCode(byte), length: m[0].length } : undefined;
}
export function argvOf(segment) {
    return segment.tokens.filter((t) => t.kind === "word");
}
export function wordsOf(segment) {
    const folded = [];
    const raw = [];
    for (const t of segment.tokens) {
        if (t.kind !== "word")
            continue;
        folded.push(t.folded);
        raw.push(t.raw);
    }
    return { folded, raw };
}
let readTo = 0;
const readUpTo = (at) => {
    if (at > readTo)
        readTo = at;
};
function passReadTo(text, end) {
    if (typeof end === "number")
        readUpTo(end);
    else if (end === "unterminated")
        readUpTo(text.length);
}
function past(text, j) {
    let k = j;
    while (text[k] === "\\" && text[k + 1] === "\n")
        k += 2;
    readUpTo(k);
    return k;
}
function heredocHeaderOf(word, dash) {
    if (word.folded === "" || /[$`]/.test(word.raw))
        return undefined;
    return { delimiter: word.folded, quoted: /["'\\]/.test(word.raw), dash };
}
function documentLine(text, p, joined) {
    let nl = text.indexOf("\n", p);
    let line = nl < 0 ? text.slice(p) : text.slice(p, nl);
    if (joined) {
        while (nl >= 0 && /(?<!\\)(?:\\\\)*\\$/.test(line)) {
            const after = text.indexOf("\n", nl + 1);
            line = line.slice(0, -1) + (after < 0 ? text.slice(nl + 1) : text.slice(nl + 1, after));
            nl = after;
        }
    }
    return { line, nl };
}
function heredocBodies(text, from, headers, closer, toEnd = false) {
    const bodies = [];
    let p = from;
    for (const h of headers) {
        const lines = [];
        for (;;) {
            if (p > text.length) {
                if (toEnd)
                    break;
                return "unterminated";
            }
            const { line, nl } = documentLine(text, p, !h.quoted);
            readUpTo(nl < 0 ? text.length : nl);
            if (closer !== undefined && text.slice(p, nl < 0 ? text.length : nl + 1).includes("\\\n"))
                return "ambiguous";
            const compared = h.dash ? line.replace(/^\t+/, "") : line;
            if (compared === h.delimiter) {
                p = nl < 0 ? text.length + 1 : nl + 1;
                break;
            }
            if (closer !== undefined && compared.startsWith(h.delimiter) && (closer === ")" ? compared.indexOf(")", h.delimiter.length) >= 0 : /^[ \t]*\}/.test(compared.slice(h.delimiter.length))))
                return "ambiguous";
            if (nl < 0) {
                if (!toEnd)
                    return "unterminated";
                if (p < text.length)
                    lines.push(line);
                p = text.length + 1;
                break;
            }
            lines.push(line);
            p = nl + 1;
        }
        bodies.push(lines.join("\n"));
    }
    return { bodies, resume: Math.min(p, text.length) };
}
function heredocHeaderAt(text, from, dash, op) {
    let j = from;
    while (text[j] === " " || text[j] === "\t" || (text[j] === "\\" && text[j + 1] === "\n"))
        j += text[j] === "\\" ? 2 : 1;
    const start = j;
    let quote;
    for (; j < text.length; j++) {
        if (j > readTo)
            readTo = j;
        const c = text[j];
        if (c === "$" || c === "`")
            return fail("heredoc_delimiter_expands", start);
        if (quote === "'") {
            if (c === "'")
                quote = undefined;
            continue;
        }
        if (quote === '"') {
            if (c === "\\")
                j++;
            else if (c === '"')
                quote = undefined;
            continue;
        }
        if (c === "\\") {
            j++;
            continue;
        }
        if (c === "'" || c === '"') {
            quote = c;
            continue;
        }
        if (/[ \t\n;&|()<>]/.test(c))
            break;
    }
    if (quote !== undefined)
        return "unterminated";
    const raw = text.slice(start, Math.min(j, text.length));
    if (raw === "" || raw.startsWith("#"))
        return fail("heredoc_without_delimiter", op);
    if (/[~[]/.test(raw))
        return "undelimited";
    const lexed = scan(raw, true, [firstSegment(raw)], 0);
    const tokens = "command" in lexed && lexed.command.segments.length === 1 ? lexed.command.segments[0].tokens : [];
    const word = tokens.length === 1 ? tokens[0] : undefined;
    if (word?.kind !== "word")
        return "undelimited";
    const header = heredocHeaderOf(word, dash);
    return header === undefined ? fail("heredoc_delimiter_expands", start) : { ...header, end: j };
}
const BASH_READING = { heredoc: true, startComment: true };
const BASH32_PARSE = { heredoc: false, startComment: true };
const BASH32_EXPAND = { heredoc: false, startComment: false };
const NO_COMMENT_COUNT = { heredoc: false, startComment: false, noComments: true };
const BASH32_DOUBLE_QUOTED = { ...NO_COMMENT_COUNT };
const ARITHMETIC_READING = { heredoc: false, startComment: true, arithmetic: true };
const BODY_NESTING_MAX = 64;
function walkBody(text, open, reading, inDouble, level) {
    if (level > BODY_NESTING_MAX)
        return "undelimited";
    let depth = 0;
    let quoted;
    let wordStart = true;
    let word = "";
    let heredoc = false;
    let innerClose;
    const owed = [];
    const nested = (at, dq) => {
        const inner = walkBody(text, at, reading.arithmetic === true ? BASH_READING : reading, dq, level + 1);
        if (typeof inner === "object" && "end" in inner) {
            heredoc ||= inner.heredoc;
            return inner.end - 1;
        }
        return inner;
    };
    for (let j = open; j < text.length; j++) {
        if (j > readTo)
            readTo = j;
        const c = text[j];
        if (quoted === "'") {
            if (c === "'")
                quoted = undefined;
            continue;
        }
        if (quoted === '"') {
            if (c === "\\") {
                j++;
                continue;
            }
            if (c === '"') {
                quoted = undefined;
                continue;
            }
            if (c === "`") {
                const tick = backtickBody(text, j);
                if (tick === undefined)
                    return "unterminated";
                j = tick.close;
                continue;
            }
            const k = past(text, j + 1);
            if (c === "$" && text[k] === "(") {
                const r = nested(k, true);
                if (typeof r !== "number")
                    return r;
                j = r;
                continue;
            }
            if (c === "$" && text[k] === "{") {
                if (opensCurrentShellSubstitution(text, k)) {
                    const run = currentShellSubstitutionEnd(text, k, level + 1);
                    if (typeof run !== "object" || !("end" in run))
                        return run;
                    j = run.end - 1;
                    continue;
                }
                const close = braceExpansionEnd(text, k, true, level);
                if (close === undefined)
                    return "unterminated";
                j = close - 1;
            }
            continue;
        }
        if (c === "\\") {
            if (text[j + 1] === "\n") {
                j++;
                continue;
            }
            j++;
            wordStart = false;
            word = "";
            continue;
        }
        if (c === "#" && wordStart && reading.noComments !== true) {
            const nl = text.indexOf("\n", j);
            readUpTo(nl < 0 ? text.length : nl);
            if (nl < 0)
                return "unterminated";
            if (text[nl - 1] === "\\")
                return "undelimited";
            j = nl - 1;
            word = "";
            continue;
        }
        if (c === "'" || c === '"') {
            quoted = c;
            wordStart = false;
            word = "";
            continue;
        }
        const k = past(text, j + 1);
        if (c === "$" && text[k] === "'") {
            const close = ansiCQuoteClose(text, k);
            if (close === undefined)
                return "unterminated";
            j = close;
            wordStart = false;
            word = "";
            continue;
        }
        if (c === "`") {
            const tick = backtickBody(text, j);
            if (tick === undefined)
                return "unterminated";
            j = tick.close;
            wordStart = false;
            word = "`";
            continue;
        }
        if (reading.heredoc && c === "<" && text[k] === "<") {
            const third = past(text, k + 1);
            if (text[third] === "<") {
                j = third;
                wordStart = false;
                word = "";
                continue;
            }
            const dash = text[third] === "-";
            const header = heredocHeaderAt(text, dash ? third + 1 : third, dash, j);
            if (header === "undelimited")
                return fail("undelimited_substitution_heredoc", j);
            if (typeof header !== "object" || !("delimiter" in header))
                return header;
            owed.push(header);
            heredoc = true;
            j = header.end - 1;
            wordStart = false;
            word = "";
            continue;
        }
        if ((c === "$" || c === "<" || c === ">") && text[k] === "(") {
            const r = nested(k, false);
            if (typeof r !== "number")
                return r;
            j = r;
            wordStart = false;
            word = "$";
            continue;
        }
        if ((reading.heredoc || reading.arithmetic === true) && c === "$" && text[k] === "{") {
            if (opensCurrentShellSubstitution(text, k)) {
                const run = currentShellSubstitutionEnd(text, k, level + 1);
                if (typeof run !== "object" || !("end" in run))
                    return run;
                j = run.end - 1;
                wordStart = false;
                word = "";
                continue;
            }
            const close = braceExpansionEnd(text, k, false, level);
            if (close === undefined)
                return "unterminated";
            if (UNREADABLE_EXPANSION_TEXT.test(text.slice(k + 1, close - 1)))
                return "undelimited";
            j = close - 1;
            wordStart = false;
            word = "";
            continue;
        }
        if (c === "\n" && owed.length > 0) {
            const read = heredocBodies(text, j + 1, owed, ")");
            if (read === "unterminated")
                return fail("unterminated_heredoc", j + 1);
            if (read === "ambiguous")
                return fail("undelimited_substitution_heredoc", j + 1);
            owed.length = 0;
            j = read.resume - 1;
            wordStart = true;
            word = "";
            continue;
        }
        if (reading.heredoc && j > open && c === "(" && text[k] === "(") {
            const end = arithmeticCommandEnd(text, k);
            if (end !== undefined) {
                j = end - 1;
                wordStart = false;
                word = "";
                continue;
            }
        }
        if (c === "(")
            depth++;
        else if (c === ")") {
            depth--;
            if (depth === 1)
                innerClose ??= j;
            if (depth === 0)
                return owed.length > 0 ? fail("undelimited_substitution_heredoc", j) : { end: j + 1, heredoc, ...(innerClose !== undefined ? { innerClose } : {}) };
        }
        if (!reading.heredoc) {
            wordStart = j === open ? reading.startComment && !inDouble && level === 0 : c === " " || c === "\t" || c === "\n";
            continue;
        }
        const boundary = /[\s;|&()]/.test(c);
        if (boundary && CASE_ARM_WORDS.has(word))
            return "undelimited";
        word = boundary ? "" : word + c;
        wordStart = boundary;
    }
    return "unterminated";
}
function doubleQuotedWordHolds(text, from, to) {
    let inDq = true;
    for (let j = from; j < to; j++) {
        const c = text[j];
        if (c === "\"")
            inDq = !inDq;
        else if (inDq ? c === "`" || (c === "$" && "({[".includes(text[j + 1] ?? "")) : " \t\n;&|<>()'`$\\".includes(c))
            return false;
        else if (inDq && c === "\\")
            j++;
    }
    return inDq;
}
function substitutionBodyEnd(text, open, inDouble, level, form = "command") {
    const arithmetic = arithmeticWalk(text, open, inDouble, level);
    const read = arithmetic ?? walkBody(text, open, BASH_READING, inDouble, level);
    if (typeof read !== "object" || !("end" in read))
        return read;
    const refused = fail(read.heredoc ? "undelimited_substitution_heredoc" : "undelimited_substitution", open);
    const doubled = text[past(text, open + 1)] === "(";
    if (form !== "document")
        for (const pass of passesFor(text, open)) {
            const end = countingPassEnd(text, open, pass);
            passReadTo(text, end);
            if (end !== read.end && end !== "unterminated")
                return refused;
        }
    const counts = [...(form === "document" ? [] : [inDouble ? BASH32_DOUBLE_QUOTED : BASH32_PARSE]), BASH32_EXPAND, ...(doubled || form === "process" ? [NO_COMMENT_COUNT] : [])];
    for (const reading of holdsHashFrom(text, open) ? counts : counts.slice(-1)) {
        const counted = walkBody(text, open, reading, inDouble, level);
        if (counted === "unterminated" || (typeof counted === "object" && "end" in counted && (counted.end === read.end || (reading === BASH32_DOUBLE_QUOTED && counted.end < read.end && doubleQuotedWordHolds(text, counted.end, read.end)))))
            continue;
        return refused;
    }
    return { end: read.end, arithmetic: arithmetic !== undefined };
}
function arithmeticWalk(text, open, inDouble, level) {
    if (text[past(text, open + 1)] !== "(")
        return undefined;
    const read = walkBody(text, open, ARITHMETIC_READING, inDouble, level);
    if (typeof read !== "object" || !("end" in read) || read.heredoc || read.innerClose === undefined)
        return undefined;
    return past(text, read.innerClose + 1) === read.end - 1 ? { end: read.end, heredoc: false } : undefined;
}
function braceExpansionEnd(text, open, inDouble, level, parsed = true) {
    const before = braceQuoteClose(text, open);
    if (before !== undefined && !/[$`<>]/.test(text.slice(open + 1, before)))
        return before;
    const walked = braceWalk(text, open, inDouble, level, parsed);
    if (walked === undefined || walked === before || !parsed)
        return walked ?? before;
    return passesFor(text, open).every((pass) => { const e = bracePassEnd(text, open, pass); passReadTo(text, e); return e === walked || e === "unterminated"; }) ? walked : before;
}
function braceQuoteClose(text, open) {
    let quoted;
    for (let j = open + 1; j < text.length; j++) {
        if (j > readTo)
            readTo = j;
        const c = text[j];
        if (quoted !== undefined) {
            if (c === "\\" && quoted === '"')
                j++;
            else if (c === quoted)
                quoted = undefined;
            continue;
        }
        if (c === "\\") {
            j++;
            continue;
        }
        if (c === "'" || c === '"') {
            quoted = c;
            continue;
        }
        if (c === "}")
            return j + 1;
    }
    return undefined;
}
function braceWalk(text, open, inDouble, level, parsed) {
    if (level > BODY_NESTING_MAX)
        return undefined;
    for (let j = open + 1; j < text.length; j++) {
        if (j > readTo)
            readTo = j;
        const c = text[j];
        if (c === "\\") {
            j++;
            continue;
        }
        if (c === "}")
            return j + 1;
        if (c === "'") {
            const close = text.indexOf("'", j + 1);
            readUpTo(close < 0 ? text.length : close);
            if (close < 0)
                return undefined;
            j = close;
            continue;
        }
        const k = past(text, j + 1);
        if (c === "$" && text[k] === "'") {
            const close = ansiCQuoteClose(text, k);
            if (close === undefined)
                return undefined;
            j = close;
            continue;
        }
        if (c === '"' || (c === "$" && text[k] === '"')) {
            const close = doubleQuotedSpanClose(text, c === '"' ? j : k, level, parsed);
            if (close === undefined)
                return undefined;
            j = close;
            continue;
        }
        if ((c === "<" || c === ">") && text[k] === "(") {
            const close = substitutionBodyEnd(text, k, inDouble, level + 1, parsed ? "process" : "document");
            if (typeof close !== "object" || !("end" in close))
                return undefined;
            j = close.end - 1;
            continue;
        }
        const last = expansionLast(text, j, inDouble, level, parsed);
        if (last === undefined)
            return undefined;
        if (last !== null)
            j = last;
    }
    return undefined;
}
function doubleQuotedSpanClose(text, open, level, parsed) {
    for (let j = open + 1; j < text.length; j++) {
        if (j > readTo)
            readTo = j;
        const c = text[j];
        if (c === "\\") {
            j++;
            continue;
        }
        if (c === '"')
            return j;
        const last = expansionLast(text, j, true, level, parsed);
        if (last === undefined)
            return undefined;
        if (last !== null)
            j = last;
    }
    return undefined;
}
function expansionLast(text, j, inDouble, level, parsed) {
    const c = text[j];
    if (c === "`")
        return backtickBody(text, j, inDouble)?.close;
    if (c !== "$")
        return null;
    const k = past(text, j + 1);
    const n = text[k];
    if (n === "$")
        return k;
    if (n === "(") {
        const close = substitutionBodyEnd(text, k, inDouble, level + 1, parsed ? "command" : "document");
        return typeof close === "object" && "end" in close ? close.end - 1 : undefined;
    }
    if (n === "[") {
        const end = bracketExpansionEnd(text, k);
        return end === undefined ? undefined : end - 1;
    }
    if (n !== "{")
        return null;
    if (opensCurrentShellSubstitution(text, k)) {
        const run = currentShellSubstitutionEnd(text, k, level + 1);
        return typeof run === "object" && "end" in run ? run.end - 1 : undefined;
    }
    const end = braceWalk(text, k, inDouble, level + 1, parsed);
    return end === undefined ? undefined : end - 1;
}
function opensCurrentShellSubstitution(text, open) {
    const after = text[open + 1];
    return after === "|" || after === " " || after === "\t" || after === "\n";
}
function currentShellSubstitutionEnd(text, open, level) {
    if (level > BODY_NESTING_MAX)
        return "undelimited";
    const list = { from: open + (text[open + 1] === "|" ? 2 : 1), groups: 0 };
    const segments = [firstSegment(text)];
    const read = scan(text, false, segments, level, list);
    if ("parseFailure" in read)
        return read;
    if (list.closed === undefined)
        return "undelimited";
    const closed = list.closed;
    if (passesFor(text, open).some((pass) => { const end = bracePassEnd(text, open, pass); passReadTo(text, end); return end !== closed && end !== "unterminated"; })) {
        return fail(segments.some((s) => s.tokens.some((t) => t.kind === "heredoc")) ? "undelimited_substitution_heredoc" : "undelimited_substitution", open);
    }
    return { end: closed, from: list.from };
}
function bracketExpansionEnd(text, open) {
    let depth = 0;
    let quoted;
    for (let j = open; j < text.length; j++) {
        if (j > readTo)
            readTo = j;
        const c = text[j];
        if (quoted !== undefined) {
            if (c === "\\" && quoted === '"')
                j++;
            else if (c === quoted)
                quoted = undefined;
            continue;
        }
        if (c === "\\") {
            j++;
            continue;
        }
        if (c === "'" || c === '"') {
            quoted = c;
            continue;
        }
        if (c === "[")
            depth++;
        else if (c === "]" && --depth === 0)
            return j + 1;
    }
    return undefined;
}
function matchedParen(text, open, level) {
    let depth = 0;
    let quoted;
    for (let j = open; j < text.length; j++) {
        if (j > readTo)
            readTo = j;
        const c = text[j];
        if (quoted !== undefined) {
            if (c === "\\" && quoted === '"')
                j++;
            else if (c === quoted)
                quoted = undefined;
            continue;
        }
        if (c === "\\") {
            j++;
            continue;
        }
        if (c === "'" || c === '"') {
            quoted = c;
            continue;
        }
        if (c === "$" && text[j + 1] === "'") {
            const close = ansiCQuoteClose(text, j + 1);
            if (close === undefined)
                return undefined;
            j = close;
            continue;
        }
        if (c === "$" && text[j + 1] === "{") {
            if (opensCurrentShellSubstitution(text, j + 1)) {
                const run = currentShellSubstitutionEnd(text, j + 1, level + 1);
                if (typeof run !== "object" || !("end" in run))
                    return run === "undelimited" ? fail("undelimited_substitution", j) : run;
                j = run.end - 1;
                continue;
            }
            const close = braceExpansionEnd(text, j + 1, false, level);
            if (close === undefined)
                return undefined;
            j = close - 1;
            continue;
        }
        if (c === "(")
            depth++;
        else if (c === ")" && --depth === 0)
            return j + 1;
    }
    return undefined;
}
const UNREADABLE_EXPANSION_TEXT = /[$`()<>{\\]/;
const PARAMETER = String.raw `(?:[A-Za-z_][A-Za-z0-9_]*|\d+|[*@#?$!-])`;
const PARAMETER_HEAD = new RegExp(String.raw `^[#!]?${PARAMETER}`);
const EXPANSION_NAME = new RegExp(String.raw `^[#!]?(${PARAMETER})`);
const BARE_PARAMETER = /^(?:[A-Za-z_][A-Za-z0-9_]*|\d|[@*#?$!0-])/;
const LOCALE_NAME_HEAD = /^[^\x00-\x7f](?:[^\x00-\x7f]|\w)*/;
function bareParameterAt(text, from) {
    const window = text.slice(from, from + 64);
    const head = BARE_PARAMETER.exec(window)?.[0];
    if (head !== undefined)
        return { head, name: head };
    const local = LOCALE_NAME_HEAD.exec(window)?.[0];
    return local === undefined ? undefined : { head: local };
}
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
const PER_ELEMENT_BODY = /^!?@|\[@\]|^![^}]*@$/;
const NAME_HEAD = /^[A-Za-z_][A-Za-z0-9_]*/;
function backtickBody(source, open, inDouble = false) {
    let body = "";
    for (let j = open + 1; j < source.length; j++) {
        if (j > readTo)
            readTo = j;
        const c = source[j];
        if (c === "\\" && j + 1 < source.length) {
            const next = source[j + 1];
            if (next === "\n") {
                j++;
                continue;
            }
            body += next === "$" || next === "`" || next === "\\" || (inDouble && next === '"') ? next : c + next;
            j++;
            continue;
        }
        if (c === "`")
            return { body, close: j };
        body += c;
    }
    return undefined;
}
export function expansionsInHeredocBody(body) {
    return whileReading(body, () => expansionsInBody(body));
}
function expansionsInBody(body) {
    const out = [];
    for (let i = 0; i < body.length; i++) {
        if (body[i] === "\\") {
            i++;
            continue;
        }
        const at = bodyExpansionAt(body, i);
        if (at === undefined)
            return undefined;
        if (at === null)
            continue;
        out.push({ ...at.found, span: [i, at.last + 1] });
        i = at.last;
    }
    return out;
}
function bodyExpansionAt(body, i) {
    const ch = body[i];
    if (ch === "`") {
        const tick = backtickBody(body, i);
        return tick === undefined ? undefined : { found: { expansion: { kind: "command", yields: "one", body: tick.body } }, last: tick.close };
    }
    if (ch !== "$")
        return null;
    const open = body[i + 1];
    if (open === "(") {
        const close = substitutionBodyEnd(body, i + 1, true, 0, "document");
        if (typeof close !== "object" || !("end" in close))
            return undefined;
        return { found: { expansion: { kind: close.arithmetic ? "arithmetic" : "command", yields: "one", body: body.slice(i + 2, close.end - 1) } }, last: close.end - 1 };
    }
    if (open === "[") {
        const end = bracketExpansionEnd(body, i + 1);
        return end === undefined ? undefined : { found: { expansion: { kind: "arithmetic", yields: "one", body: body.slice(i + 2, end - 1) } }, last: end - 1 };
    }
    if (open === "{") {
        if (opensCurrentShellSubstitution(body, i + 1)) {
            const run = currentShellSubstitutionEnd(body, i + 1, 1);
            if (typeof run !== "object" || !("end" in run))
                return undefined;
            return { found: { expansion: { kind: "command", yields: "one", body: body.slice(run.from, run.end - 1) }, currentShell: true }, last: run.end - 1 };
        }
        const end = braceExpansionEnd(body, i + 1, true, 0, false);
        if (end === undefined)
            return undefined;
        const text = body.slice(i + 2, end - 1);
        const name = EXPANSION_NAME.exec(text)?.[1];
        return { found: { expansion: { kind: "parameter", yields: "one", body: text, ...(name !== undefined ? { name } : {}) }, ...(UNREADABLE_EXPANSION_TEXT.test(text) ? { unresolved: "parameter_text" } : {}) }, last: end - 1 };
    }
    const bare = bareParameterAt(body, i + 1);
    return bare === undefined ? null : { found: { expansion: { kind: "parameter", yields: "one", ...(bare.name !== undefined ? { name: bare.name } : {}) } }, last: i + bare.head.length };
}
export function substitutionsInHeredocBody(body) {
    const all = expansionsInHeredocBody(body);
    if (all === undefined)
        return undefined;
    return all.flatMap(({ expansion: e, currentShell }) => (e.kind === "command" || e.kind === "arithmetic" ? [{ body: e.body ?? "", kind: e.kind, ...(currentShell === true ? { currentShell } : {}) }] : []));
}
export function heredocRunsOf(body) {
    const all = expansionsInHeredocBody(body);
    if (all === undefined)
        return HIDDEN_RUNS;
    return joinRuns([/[<>]\(/.test(body) ? HIDDEN_RUNS : NO_RUNS, ...all.map((x) => (x.unresolved !== undefined ? joinRuns([HIDDEN_RUNS, expansionRunsOf(x.expansion)]) : expansionRunsOf(x.expansion)))]);
}
export function heredocBodyHidesRun(body) {
    return runsAny(heredocRunsOf(body));
}
const SUBSTITUTION_OPENER = /\$\(|`|<\(|>\(|\$\[|\$\{[ \t\n|]/;
export function parameterArithmeticTexts(body) {
    const { subscript, offset } = parameterBodyParts(body);
    return { ...(subscript !== undefined ? { subscript } : {}), ...(offset !== undefined ? { offset } : {}) };
}
function parameterBodyParts(body) {
    const text = body.replace(/\\\n/g, "");
    const head = PARAMETER_HEAD.exec(text);
    if (head === null)
        return { operand: text };
    let rest = text.slice(head[0].length);
    let subscript;
    if (rest.startsWith("[")) {
        const close = rest.indexOf("]");
        subscript = rest.slice(1, close < 0 ? undefined : close);
        rest = close < 0 ? "" : rest.slice(close + 1);
    }
    const offset = /^:(?![-=+?])(.*)$/s.exec(rest)?.[1];
    return { ...(subscript !== undefined ? { subscript } : {}), ...(offset !== undefined ? { offset } : rest !== "" ? { operand: rest } : {}) };
}
export function parameterOperandLines(body, quoted) {
    const operand = parameterBodyParts(body).operand;
    return operand === undefined || !/[$`<>]/.test(operand) ? [] : whileReading(operand, () => operandLines(operand, quoted, PATTERN_OPERAND.test(operand)));
}
const PATTERN_OPERAND = /^[#%/^,]/;
function operandLines(text, quoted, pattern) {
    const lines = [];
    let inDouble = false;
    for (let k = 0; k < text.length; k++) {
        const ch = text[k];
        if (ch === "\\") {
            k++;
            continue;
        }
        const bare = !quoted && !inDouble;
        if (bare && (ch === "'" || (ch === "$" && text[k + 1] === "'"))) {
            const close = ch === "'" ? text.indexOf("'", k + 1) : ansiCQuoteClose(text, k + 1);
            if (close === undefined || close < 0)
                break;
            k = close;
            continue;
        }
        if (!quoted && ch === '"') {
            inDouble = !inDouble;
            continue;
        }
        if ((bare || (quoted && pattern)) && (ch === "<" || ch === ">") && text[k + 1] === "(") {
            const close = substitutionBodyEnd(text, k + 1, false, 0, "process");
            if (typeof close !== "object" || !("end" in close))
                break;
            lines.push(text.slice(k + 2, close.end - 1));
            k = close.end - 1;
            continue;
        }
        const at = bodyExpansionAt(text, k);
        if (at === undefined)
            break;
        if (at === null)
            continue;
        const e = at.found.expansion;
        if (e.kind === "command")
            lines.push(e.body ?? "");
        else if (e.kind === "arithmetic")
            lines.push(...operandLines(e.body ?? "", true, false));
        else if (e.kind === "parameter" && e.body !== undefined)
            lines.push(...operandLines(e.body, quoted || inDouble, PATTERN_OPERAND.test(parameterBodyParts(e.body).operand ?? "")));
        k = at.last;
    }
    return lines;
}
function bodyEvaluatesText(body) {
    const { subscript, offset } = parameterArithmeticTexts(body);
    return (subscript !== undefined && /[A-Za-z_$]/.test(subscript)) || (offset !== undefined && /^[^}]*[A-Za-z_$]/.test(offset));
}
function nestedBodyEvaluatesText(text) {
    for (let i = text.indexOf("${"); i >= 0; i = text.indexOf("${", i + 1))
        if (bodyEvaluatesText(text.slice(i + 2)))
            return true;
    return false;
}
const TRANSFORM_FORM = new RegExp(String.raw `^${PARAMETER}(?:\[(?:'[^']*'|"(?:[^"\\]|\\.)*"|\\.|[^\]'"\\])*\])?@([A-Za-z])$`, "s");
const RESPELLING_TRANSFORMS = new Set(["Q", "E", "A", "K", "k", "a", "U", "u", "L"]);
const NAME_OR_KEY_LIST = /^![A-Za-z_][A-Za-z0-9_]*(?:[*@]|\[[@*]\])$/;
const PLAIN_ARITHMETIC = /^[\s\d+\-*/%&|^~!<>=?:,()]*$/;
const NO_RUNS = { lines: [], hidden: false };
const HIDDEN_RUNS = { lines: [], hidden: true };
function joinRuns(parts) {
    return { lines: parts.flatMap((p) => p.lines), hidden: parts.some((p) => p.hidden) };
}
const runsAny = (r) => r.hidden || r.lines.length > 0;
export function expansionRunsOf(e, quoted = true) {
    const inner = joinRuns((e.inner ?? []).map((x) => expansionRunsOf(x, quoted)));
    if (e.kind === "command" || e.kind === "process")
        return joinRuns([e.body === undefined ? HIDDEN_RUNS : { lines: [e.body], hidden: false }, inner]);
    const body = e.body?.replace(/\\\n/g, "");
    if (body === undefined)
        return inner;
    if (e.kind === "arithmetic")
        return joinRuns([arithmeticTextRunsOf(body), inner]);
    const hidden = SUBSTITUTION_OPENER.test(body) || (e.kind === "parameter" && (bodyEvaluatesText(body) || parameterRereadsValue(body))) || nestedBodyEvaluatesText(body);
    const operand = e.kind === "parameter" && hidden ? parameterOperandLines(body, quoted) : undefined;
    return hidden ? joinRuns([HIDDEN_RUNS, { lines: operand ?? [], hidden: false }, inner]) : inner;
}
export function arithmeticTextRunsOf(text) {
    if (arithmeticTextIsPlain(text))
        return NO_RUNS;
    const all = expansionsInHeredocBody(text);
    return all === undefined ? HIDDEN_RUNS : joinRuns([HIDDEN_RUNS, ...all.map((x) => expansionRunsOf(x.expansion))]);
}
export function expansionHidesRun(e) {
    return runsAny(expansionRunsOf(e));
}
export function assignedWords(w) {
    const elements = w.assignment?.form === "compound" ? w.assignment.elements : undefined;
    return elements !== undefined ? elements.map((e) => e.stored) : [w];
}
function compoundElementsOf(name, words) {
    if (words.some((w) => w.assignment?.form === "compound"))
        return undefined;
    const out = [];
    for (const word of words) {
        const keyed = word.raw.startsWith("[") ? scalarAssignmentOf(`${name}${word.raw}`) : undefined;
        const stored = keyed?.assignment?.subscript !== undefined ? keyed : scalarAssignmentOf(`${name}=${word.raw}`);
        if (stored === undefined || (stored !== keyed && stored.assignment?.subscript !== undefined))
            return undefined;
        out.push({ word, stored });
    }
    return out;
}
function scalarAssignmentOf(text) {
    const lexed = lexShell(SHELL_LEX_DIALECT, text);
    const argv = "parseFailure" in lexed || lexed.segments.length !== 1 ? undefined : argvOf(lexed.segments[0]);
    return argv?.length === 1 && argv[0].assignment?.form === "scalar" ? argv[0] : undefined;
}
export function transformEvaluates(body) {
    const transform = TRANSFORM_FORM.exec(body)?.[1];
    return transform !== undefined && !RESPELLING_TRANSFORMS.has(transform);
}
export function parameterRereadsValue(body) {
    const text = body.replace(/\\\n/g, "");
    return (text.startsWith("!") && !NAME_OR_KEY_LIST.test(text)) || transformEvaluates(text);
}
export function arithmeticTextIsPlain(text) {
    return PLAIN_ARITHMETIC.test(text.replace(/\\\n/g, ""));
}
export function subscriptHidesRun(w) {
    return w.assignment?.subscript !== undefined && !arithmeticTextIsPlain(w.assignment.subscript.raw);
}
export function wordRunsOf(w) {
    return joinRuns(assignedWords(w).flatMap((e) => [e.assignment?.form === "compound" || subscriptHidesRun(e) ? HIDDEN_RUNS : NO_RUNS, ...e.expansions.flatMap((p) => (p.expansion !== undefined ? [expansionRunsOf(p.expansion, p.quotedBy !== undefined)] : []))]));
}
export function wordHidesRun(w) {
    return runsAny(wordRunsOf(w));
}
export function namesRedirectDescriptor(next) {
    return (next?.kind === "redirect" || next?.kind === "heredoc") && next.allocated === true;
}
export function descriptorNameWords(segment) {
    return new Set(segment.tokens.flatMap((t, i) => (t.kind === "word" && namesRedirectDescriptor(segment.tokens[i + 1]) ? [t] : [])));
}
export function literalTextOf(pieces) {
    return pieces.every((q) => q.literal !== undefined) ? pieces.map((q) => q.literal).join("") : undefined;
}
export function literalHeredocBody(body) {
    const run = heredocLiteralRun(body);
    return run.expands ? undefined : run.text;
}
function heredocLiteralRun(text) {
    let out = "";
    let expands = false;
    for (let i = 0; i < text.length; i++) {
        const ch = text[i];
        if (ch === "$" || ch === "`")
            expands = true;
        if (ch === "\\" && i + 1 < text.length && "$`\\".includes(text[i + 1])) {
            out += text[++i];
            continue;
        }
        out += ch;
    }
    return { text: out, expands };
}
export function heredocBodyPieces(body) {
    const expansions = expansionsInHeredocBody(body);
    if (expansions === undefined)
        return undefined;
    const pieces = [];
    let at = 0;
    const literalTo = (end) => void (end > at && pieces.push({ span: [at, end], quotedBy: '"', literal: heredocLiteralRun(body.slice(at, end)).text }));
    for (const x of expansions) {
        literalTo(x.span[0]);
        pieces.push({ span: x.span, quotedBy: '"', expansion: x.expansion });
        at = x.span[1];
    }
    literalTo(body.length);
    return pieces;
}
const BLANK = /[ \t]/;
const fail = (reason, at) => ({ parseFailure: { reason, at } });
const publicPiece = (p) => ({
    span: [p.start, p.end],
    quotedBy: p.quotedBy,
    ...(p.literal !== undefined ? { literal: p.literal } : {}),
    ...(p.expansion !== undefined ? { expansion: p.expansion } : {}),
});
class WordBuilder {
    raw = "";
    folded = "";
    started = false;
    at = 0;
    pieces = [];
    rawQuoted = [];
    foldedAt = [];
    srcOfRaw = [];
    rawOfFolded = [];
    marks = [];
    subscript;
    compound = false;
    elementWords;
    widenedClasses = [];
    begin(src) { if (!this.started)
        this.at = src; }
    push(w, f, by, src) {
        const rawStart = this.raw.length;
        for (let k = 0; k < w.length; k++) {
            this.rawQuoted.push(by);
            this.foldedAt.push(this.folded.length);
            this.srcOfRaw.push(src + k);
        }
        for (let k = 0; k < f.length; k++)
            this.rawOfFolded.push(rawStart);
        this.raw += w;
        this.folded += f;
        this.started = true;
    }
    emit(w, f, by, src, srcEnd) {
        this.begin(src);
        const last = this.pieces[this.pieces.length - 1];
        if (last !== undefined && last.literal !== undefined && last.quotedBy === by && last.end === src && last.rawEnd === this.raw.length) {
            last.literal += f;
            last.end = srcEnd;
            last.rawEnd += w.length;
            last.foldedEnd += f.length;
        }
        else {
            this.pieces.push({ start: src, end: srcEnd, rawStart: this.raw.length, rawEnd: this.raw.length + w.length, foldedStart: this.folded.length, foldedEnd: this.folded.length + f.length, quotedBy: by, literal: f, expansion: undefined });
        }
        this.push(w, f, by, src);
    }
    opaque(w, f, by, src, srcEnd, exp) {
        this.begin(src);
        this.pieces.push({ start: src, end: srcEnd, rawStart: this.raw.length, rawEnd: this.raw.length + w.length, foldedStart: this.folded.length, foldedEnd: this.folded.length + f.length, quotedBy: by, literal: undefined, expansion: exp });
        this.push(w, f, by, src);
    }
    quoteChar(ch, by, src) {
        this.begin(src);
        this.rawQuoted.push(by);
        this.foldedAt.push(this.folded.length);
        this.srcOfRaw.push(src);
        this.raw += ch;
        this.started = true;
    }
    mark(reason, rawAt) { this.marks.push({ at: rawAt, reason }); }
    inSubscript() { return this.subscript !== undefined && this.subscript.rawEnd === undefined; }
    foldedOf(r) { return r >= this.foldedAt.length ? this.folded.length : this.foldedAt[r]; }
    classSpelled(from, to) {
        let out = "";
        let at = from;
        for (const [a, b] of this.widenedClasses) {
            if (a < at || b > to)
                continue;
            out += `${this.folded.slice(at, a)}?`;
            at = b;
        }
        return out + this.folded.slice(at, to);
    }
    slice(from, to) {
        const out = [];
        for (const p of this.pieces) {
            if (p.rawEnd <= from || p.rawStart >= to)
                continue;
            if (p.rawStart >= from && p.rawEnd <= to) {
                out.push(p);
                continue;
            }
            const rs = Math.max(p.rawStart, from);
            const re = Math.min(p.rawEnd, to);
            const fs = this.foldedOf(rs);
            const fe = this.foldedOf(re);
            out.push({
                ...p,
                start: this.srcOfRaw[rs],
                end: this.srcOfRaw[re - 1] + 1,
                rawStart: rs,
                rawEnd: re,
                foldedStart: fs,
                foldedEnd: fe,
                literal: p.literal === undefined ? undefined : p.literal.slice(fs - p.foldedStart, fe - p.foldedStart),
            });
        }
        return out;
    }
    expansionPiece(from, to, exp) {
        return { start: this.srcOfRaw[from], end: this.srcOfRaw[to - 1] + 1, rawStart: from, rawEnd: to, foldedStart: this.foldedOf(from), foldedEnd: this.foldedOf(to), quotedBy: undefined, literal: undefined, expansion: exp };
    }
    carve(from, to, exp, inExp) {
        this.pieces = [...this.slice(0, from), this.expansionPiece(from, to, exp), ...this.slice(to, this.raw.length)];
        if (inExp !== undefined)
            for (let k = from; k < to; k++)
                inExp[k] = true;
    }
    carveAll(ranges) {
        if (ranges.length === 0)
            return;
        const cut = (p, rs, re) => {
            if (rs === p.rawStart && re === p.rawEnd)
                return p;
            const fs = this.foldedOf(rs);
            const fe = this.foldedOf(re);
            return { ...p, start: this.srcOfRaw[rs], end: this.srcOfRaw[re - 1] + 1, rawStart: rs, rawEnd: re, foldedStart: fs, foldedEnd: fe, literal: p.literal === undefined ? undefined : p.literal.slice(fs - p.foldedStart, fe - p.foldedStart) };
        };
        const out = [];
        let r = 0;
        for (const p of this.pieces) {
            let cur = p.rawStart;
            while (r < ranges.length && ranges[r].from < p.rawEnd) {
                const rg = ranges[r];
                if (rg.from >= cur) {
                    if (rg.from > cur)
                        out.push(cut(p, cur, rg.from));
                    out.push(this.expansionPiece(rg.from, rg.to, rg.exp));
                }
                if (rg.to >= p.rawEnd) {
                    cur = p.rawEnd;
                    break;
                }
                cur = rg.to;
                r++;
            }
            if (cur < p.rawEnd)
                out.push(cut(p, cur, p.rawEnd));
            if (r < ranges.length && ranges[r].to === p.rawEnd)
                r++;
        }
        this.pieces = out;
    }
    inExpansion() {
        const out = new Array(this.raw.length).fill(false);
        for (const p of this.pieces)
            if (p.expansion !== undefined)
                for (let k = p.rawStart; k < p.rawEnd; k++)
                    out[k] = true;
        return out;
    }
    tildePrefixEnd(at, inValue) {
        if (this.raw[at] !== "~" || this.rawQuoted[at] !== undefined)
            return undefined;
        let k = at + 1;
        for (; k < this.raw.length; k++) {
            if (this.rawQuoted[k] !== undefined)
                return undefined;
            const c = this.raw[k];
            if (c === "/" || (inValue && c === ":"))
                break;
        }
        return k;
    }
    carveTilde(from, to) {
        const covering = this.pieces.find((p) => p.literal !== undefined && p.rawStart <= from && p.rawEnd >= to);
        if (covering === undefined)
            return;
        const body = this.raw.slice(from, to);
        this.carve(from, to, { kind: "tilde", yields: /[*?[]/.test(body) ? "many" : "one", body });
    }
    carveBraceAndGlob() {
        const inExp = this.inExpansion();
        const n = this.raw.length;
        const readable = (j) => this.rawQuoted[j] === undefined && !inExp[j];
        const braceClose = new Map();
        const stack = [];
        for (let j = 0; j < n; j++) {
            if (!readable(j))
                continue;
            const d = this.raw[j];
            if (d === "{")
                stack.push({ open: j, listed: false });
            else if (d === "}") {
                const top = stack.pop();
                if (top !== undefined)
                    braceClose.set(top.open, { close: j, listed: top.listed });
            }
            else if (stack.length > 0 && (d === "," || (d === "." && this.raw[j + 1] === ".")))
                stack[stack.length - 1].listed = true;
        }
        const text = this.folded;
        const nf = text.length;
        const readableAt = (f) => f < nf && readable(this.rawOfFolded[f]);
        const unitClose = (d) => {
            const at = new Array(nf + 2).fill(-1);
            for (let f = nf - 2; f >= 0; f--)
                at[f] = readableAt(f) && readableAt(f + 1) && text[f] === d && text[f + 1] === "]" ? f : at[f + 1];
            return at;
        };
        const unitCloses = new Map([":", "=", "."].map((d) => [d, unitClose(d)]));
        const lettersEnd = new Array(nf + 1).fill(nf);
        for (let f = nf - 1; f >= 0; f--) {
            const lower = text.charCodeAt(f) | 0x20;
            lettersEnd[f] = lower >= 0x61 && lower <= 0x7a && readableAt(f) ? lettersEnd[f + 1] : f;
        }
        const unitEndAt = (f) => {
            if (!(readableAt(f) && text[f] === "[" && readableAt(f + 1)))
                return -1;
            const d = text[f + 1];
            const end = unitCloses.get(d)?.[f + 2] ?? -1;
            if (end < 0)
                return -1;
            return d === ":" ? (end > f + 2 && lettersEnd[f + 2] === end ? end : -1) : end === f + 3 ? end : -1;
        };
        const nextBracketClose = new Array(nf + 2).fill(-1);
        const nextSlash = new Array(nf + 1).fill(nf);
        for (let f = nf - 1; f >= 0; f--) {
            const unitEnd = unitEndAt(f);
            nextBracketClose[f] = readableAt(f) && text[f] === "]" ? f : unitEnd >= 0 ? nextBracketClose[unitEnd + 2] : nextBracketClose[f + 1];
            nextSlash[f] = text[f] === "/" ? f : nextSlash[f + 1];
        }
        const ranges = [];
        for (let k = 0; k < n; k++) {
            if (!readable(k))
                continue;
            const c = this.raw[k];
            if (c === "{") {
                const m = braceClose.get(k);
                if (m === undefined || !m.listed)
                    continue;
                ranges.push({ from: k, to: m.close + 1, exp: { kind: "brace", yields: "many", body: this.raw.slice(k + 1, m.close) } });
                k = m.close;
                continue;
            }
            if (c === "*" || c === "?") {
                ranges.push({ from: k, to: k + 1, exp: { kind: "glob", yields: "many", pattern: { folded: c, written: c, judged: c } } });
                continue;
            }
            if (c === "[") {
                if (this.rawOfFolded[this.foldedOf(k)] !== k)
                    continue;
                let j = this.foldedOf(k) + 1;
                if ((text[j] === "!" || text[j] === "^") && readableAt(j))
                    j++;
                if (text[j] === "]" && readableAt(j))
                    j++;
                const closeAt = j < nf ? nextBracketClose[j] : -1;
                if (closeAt < 0 || nextSlash[j] < closeAt)
                    continue;
                const close = this.rawOfFolded[closeAt];
                let expands = false;
                for (let m = k + 1; m < close && !expands; m++)
                    expands = inExp[m] || braceClose.get(m)?.listed === true;
                let widened = false;
                for (let m = k + 1; m < close && !widened; m++)
                    widened = this.rawQuoted[m] !== undefined;
                for (let f = j; f < closeAt && !widened; f++)
                    widened = readableAt(f) && text[f] === "[" && readableAt(f + 1) && (text[f + 1] === ":" || text[f + 1] === "=" || text[f + 1] === ".");
                const from = this.foldedOf(k);
                const to = this.foldedOf(close + 1);
                if (!expands && widened)
                    this.widenedClasses.push([from, to]);
                const pattern = expands ? {} : { pattern: { folded: this.folded.slice(from, to), written: this.raw.slice(k, close + 1), judged: widened ? "?" : this.folded.slice(from, to) } };
                ranges.push({ from: k, to: close + 1, exp: { kind: "glob", yields: "many", body: this.raw.slice(k + 1, close), ...pattern } });
                k = close;
            }
        }
        const enclosed = this.pieces.filter((p) => p.expansion !== undefined);
        if (enclosed.length > 0) {
            for (const r of ranges) {
                const inner = enclosed.filter((p) => p.rawStart >= r.from && p.rawEnd <= r.to).map((p) => p.expansion);
                if (inner.length > 0)
                    r.exp = { ...r.exp, inner };
            }
        }
        this.carveAll(ranges);
    }
    readAssignment() {
        const m = NAME_HEAD.exec(this.folded);
        if (m === null)
            return undefined;
        const name = m[0];
        const inExp = this.inExpansion();
        const quotedF = (f) => { const r = this.rawOfFolded[f]; return r === undefined || this.rawQuoted[r] !== undefined; };
        let at = name.length;
        let sub;
        if (this.folded[at] === "[") {
            let depth = 0;
            let close = -1;
            for (let k = at; k < this.folded.length; k++) {
                const r = this.rawOfFolded[k];
                if (this.rawQuoted[r] !== undefined || inExp[r])
                    continue;
                if (this.folded[k] === "[")
                    depth++;
                else if (this.folded[k] === "]" && --depth === 0) {
                    close = k;
                    break;
                }
            }
            if (close < 0)
                return undefined;
            sub = { from: at, to: close + 1 };
            at = close + 1;
        }
        const appends = this.folded.startsWith("+=", at);
        if (!appends && this.folded[at] !== "=")
            return undefined;
        const opLen = appends ? 2 : 1;
        let bare = true;
        for (let f = 0; f < name.length; f++)
            if (quotedF(f))
                bare = false;
        if (sub !== undefined && (quotedF(sub.from) || quotedF(sub.to - 1)))
            bare = false;
        for (let f = at; f < at + opLen; f++)
            if (quotedF(f))
                bare = false;
        const opRaw = this.rawOfFolded[at];
        const valueRawFrom = opRaw + opLen;
        if (!this.compound) {
            for (let k = valueRawFrom; k < this.raw.length; k++) {
                if (k !== valueRawFrom && !(this.raw[k - 1] === ":" && this.rawQuoted[k - 1] === undefined && !inExp[k - 1]))
                    continue;
                const end = this.tildePrefixEnd(k, true);
                if (end !== undefined)
                    this.carveTilde(k, end);
            }
        }
        const valuePieces = this.slice(valueRawFrom, this.raw.length).map(publicPiece);
        const value = {
            raw: this.raw.slice(valueRawFrom),
            folded: this.folded.slice(at + opLen),
            pieces: valuePieces,
            expansions: valuePieces.filter((p) => p.expansion !== undefined),
            ...(this.compound ? { unresolved: "compound_array_value" } : {}),
        };
        const elements = this.compound && this.elementWords !== undefined ? compoundElementsOf(name, this.elementWords) : undefined;
        let subscript;
        if (sub !== undefined) {
            const rawFrom = this.rawOfFolded[sub.from] + 1;
            const rawTo = this.rawOfFolded[sub.to - 1];
            const inner = this.slice(rawFrom, rawTo).map(publicPiece);
            subscript = { raw: this.raw.slice(rawFrom, rawTo), folded: this.folded.slice(sub.from + 1, sub.to - 1), expansions: inner.filter((p) => p.expansion !== undefined) };
        }
        return {
            name,
            op: appends ? "+=" : "=",
            ...(subscript !== undefined ? { subscript } : {}),
            value,
            bare,
            form: this.compound ? "compound" : "scalar",
            settlesWholeName: !appends && sub === undefined && !this.compound,
            ...(elements !== undefined ? { elements } : {}),
        };
    }
    isAssignmentHead() {
        if (this.compound || this.inSubscript())
            return false;
        if (!/^[A-Za-z_][A-Za-z0-9_]*(?:\[[\s\S]*\])?\+?=$/.test(this.raw))
            return false;
        const sub = this.subscript;
        for (let k = 0; k < this.raw.length; k++) {
            if (sub !== undefined && k > sub.rawStart && k < sub.rawEnd - 1)
                continue;
            if (this.rawQuoted[k] !== undefined)
                return false;
        }
        return true;
    }
    finish(atCommandPosition, tildeSpelling = true) {
        const rawText = this.raw;
        let literalTilde = false;
        let assignment;
        const tildeEnd = this.tildePrefixEnd(0, false);
        if (tildeEnd !== undefined)
            this.carveTilde(0, tildeEnd);
        else {
            literalTilde = tildeSpelling;
            assignment = this.readAssignment();
        }
        if (!(assignment !== undefined && assignment.bare && atCommandPosition))
            this.carveBraceAndGlob();
        const spelled = (text) => (literalTilde ? literalTildeSpelling(text) : text);
        const foldedText = spelled(this.folded);
        const judged = this.widenedClasses.length > 0 ? spelled(this.classSpelled(0, this.folded.length)) : undefined;
        if (assignment !== undefined && this.subscript?.text)
            this.mark("subscript_text", this.subscript.rawStart);
        const marks = this.marks.filter((m) => m.reason !== "subscript_text" || assignment?.subscript !== undefined).sort((a, b) => a.at - b.at);
        const unresolved = marks[0]?.reason ?? (assignment?.value.unresolved);
        const spans = [];
        for (let i = 0; i < this.rawQuoted.length; i++) {
            const by = this.rawQuoted[i];
            if (by === undefined)
                continue;
            const last = spans[spans.length - 1];
            if (last !== undefined && last.by === by && last.end === i)
                spans[spans.length - 1] = { ...last, end: i + 1 };
            else
                spans.push({ start: i, end: i + 1, by });
        }
        const pieces = this.pieces.map(publicPiece);
        return {
            kind: "word",
            raw: rawText,
            folded: foldedText,
            ...(judged !== undefined ? { judged } : {}),
            pieces,
            quotedSpans: spans,
            expansions: pieces.filter((p) => p.expansion !== undefined),
            ...(assignment !== undefined ? { assignment } : {}),
            ...(unresolved !== undefined ? { unresolved } : {}),
            atCommandPosition,
        };
    }
}
function scan(source, connectorsAreText, segments, level, list, resumed) {
    return whileReading(source, () => scanText(source, connectorsAreText, segments, level, list, resumed));
}
function scanText(source, connectorsAreText, segments, level, list, resumed) {
    const split = !connectorsAreText;
    const current = () => segments[segments.length - 1];
    const pendingHeredocs = [];
    let pendingRedirect;
    let pendingHeredoc;
    let inSingle = false;
    let inDouble = false;
    let regionBy;
    let regionAt = 0;
    let pendingLocale = false;
    let acceptable = true;
    let timeGrammar;
    let definitionName = false;
    let coprocWord;
    let afterLeadingRedirect = false;
    let assignmentSeen = false;
    let subscriptsClosed = false;
    let commandWord;
    let arithParens = 0;
    let w = new WordBuilder();
    const next = (j) => past(source, j + 1);
    const quotedBy = () => (inSingle || inDouble ? regionBy : undefined);
    const take = (ch, src) => w.emit(ch, ch, quotedBy(), src, src + 1);
    const substitution = (from, to, body, kind) => {
        const by = quotedBy();
        w.opaque(source.slice(from, to), SUBSTITUTION_PLACEHOLDER, by, from, to, { kind, yields: kind !== "process" && by === undefined ? "many" : "one", body });
        current().substitutions.push(body);
    };
    const resetPosition = () => { acceptable = true; commandWord = undefined; afterLeadingRedirect = false; assignmentSeen = false; subscriptsClosed = false; timeGrammar = undefined; definitionName = false; coprocWord = undefined; };
    const finished = () => {
        const out = segments.map((s) => segmentView(source, s));
        return { command: { segments: out, substitutions: out.flatMap((s) => s.substitutions) } };
    };
    const metEarlier = () => {
        if (resumed === undefined || pendingHeredocs.length > 0 || arithParens > 0)
            return false;
        const at = current().start;
        resumed.fresh.add(at);
        if (!resumed.met.has(at))
            return false;
        segments.pop();
        return true;
    };
    const endWord = () => {
        if (!w.started)
            return undefined;
        if (w.inSubscript())
            return fail("unterminated_subscript", w.srcOfRaw[w.subscript.rawStart]);
        const word = w.finish(acceptable && pendingRedirect === undefined, pendingHeredoc === undefined);
        const at = w.at;
        w = new WordBuilder();
        if (pendingHeredoc !== undefined) {
            const header = heredocHeaderOf(word, pendingHeredoc.dash);
            const { fd: heredocFd, allocated } = pendingHeredoc;
            pendingHeredoc = undefined;
            if (header === undefined)
                return fail("heredoc_delimiter_expands", at);
            const token = { kind: "heredoc", delimiter: header.delimiter, quoted: header.quoted, body: "", ...(heredocFd !== undefined ? { fd: heredocFd } : {}), ...(allocated === true ? { allocated } : {}) };
            current().tokens.push(token);
            pendingHeredocs.push({ ...header, token });
            if (acceptable) {
                if (assignmentSeen)
                    subscriptsClosed = true;
                else
                    afterLeadingRedirect = true;
            }
            return undefined;
        }
        if (pendingRedirect !== undefined) {
            const { op, fd, allocated } = pendingRedirect;
            pendingRedirect = undefined;
            const target = { ...word, atCommandPosition: false };
            const written = fd !== undefined ? { fd } : allocated === true ? { allocated } : {};
            if ((op === ">&" || op === "<&") && word.raw === word.folded && /^(?:\d+-?|-)$/.test(word.folded))
                current().tokens.push({ kind: "redirect", op, ...written, dup: word.folded });
            else
                current().tokens.push({ kind: "redirect", op: op === ">&" ? "&>" : op === "<&" ? "<" : op, ...written, target });
            if (acceptable) {
                if (assignmentSeen)
                    subscriptsClosed = true;
                else
                    afterLeadingRedirect = true;
            }
            return undefined;
        }
        current().tokens.push(word);
        const bare = word.raw === word.folded;
        if (definitionName) {
            resetPosition();
            return undefined;
        }
        if (acceptable && bare && DEFINITION_WORDS.has(word.folded)) {
            acceptable = false;
            definitionName = true;
            return undefined;
        }
        if (acceptable && bare && (SHELL_CONTROL_PREFIXES.has(word.folded) || GROUP_WORDS.has(word.folded))) {
            if (list !== undefined && GROUP_WORDS.has(word.folded))
                list.groups += SCOPE_OPEN_WORDS.has(word.folded) ? 1 : -1;
            timeGrammar = TIMER_WORDS.has(word.folded) ? "opt" : undefined;
            coprocWord = undefined;
            return undefined;
        }
        if (acceptable && bare && BACKGROUND_WORDS.has(word.folded)) {
            coprocWord = "head";
            return undefined;
        }
        if (acceptable && bare && timeGrammar === "opt" && word.folded === "-p") {
            timeGrammar = "ign";
            return undefined;
        }
        if (acceptable && bare && timeGrammar !== undefined && word.folded === "--") {
            timeGrammar = undefined;
            return undefined;
        }
        timeGrammar = undefined;
        if (word.assignment !== undefined && word.assignment.bare && acceptable) {
            assignmentSeen = true;
            coprocWord = undefined;
            return undefined;
        }
        if (acceptable && coprocWord !== "name")
            commandWord = bare ? word.folded : undefined;
        if (coprocWord === "head" && !(bare && COMPOUND_OPEN_WORDS.has(word.folded))) {
            coprocWord = "name";
            return undefined;
        }
        coprocWord = undefined;
        acceptable = false;
        return undefined;
    };
    const operandOwed = (at) => pendingRedirect !== undefined ? fail("redirect_without_target", at) : pendingHeredoc !== undefined ? fail("heredoc_without_delimiter", at) : undefined;
    const closeSegment = (connector, at, from, pipesStderr = false) => {
        const refusal = endWord() ?? operandOwed(at);
        if (refusal !== undefined)
            return refusal;
        current().end = at;
        segments.push({ start: from, end: source.length, connector, ...(pipesStderr ? { pipesStderr: true } : {}), tokens: [], substitutions: [] });
        resetPosition();
        return undefined;
    };
    const readHeredocBodies = (from) => {
        const read = heredocBodies(source, from, pendingHeredocs, list === undefined ? undefined : "}");
        if (read === "ambiguous")
            return fail("undelimited_substitution_heredoc", from);
        if (typeof read !== "object")
            return unterminatedHeredocs(from, true);
        pendingHeredocs.forEach((h, k) => { h.token.body = read.bodies[k]; });
        pendingHeredocs.length = 0;
        return read.resume;
    };
    const unterminatedHeredocs = (from, lineBroken) => {
        const read = list === undefined ? heredocBodies(source, from, pendingHeredocs, undefined, true) : undefined;
        if (typeof read === "object") {
            pendingHeredocs.forEach((h, k) => { h.token.body = read.bodies[k]; });
            if (lineBroken)
                current().start = source.length;
            else
                segments.push({ start: source.length, end: source.length, connector: "\n", tokens: [], substitutions: [] });
        }
        return fail("unterminated_heredoc", from);
    };
    for (let i = list?.from ?? resumed?.from ?? 0; i < source.length; i++) {
        if (i > readTo)
            readTo = i;
        if (!inSingle) {
            const j = past(source, i);
            if (j >= source.length)
                break;
            i = j;
        }
        const ch = source[i];
        if (list !== undefined && ch === "}" && list.groups === 0 && !inSingle && !inDouble && !w.started && acceptable && pendingRedirect === undefined && pendingHeredoc === undefined) {
            if (pendingHeredocs.length > 0)
                return fail("undelimited_substitution_heredoc", i);
            list.closed = i + 1;
            return { command: { segments: [], substitutions: [] } };
        }
        if (ch === "$" && !inSingle && !inDouble && dollarOpensQuote(source, i)) {
            const q = next(i);
            if (source[q] === '"') {
                w.quoteChar("$", '$"', i);
                pendingLocale = true;
                i = q - 1;
                continue;
            }
            if (source[q] === "'") {
                const close = ansiCQuoteClose(source, q);
                if (close === undefined)
                    return fail("unterminated_ansi_c", i);
                const decoded = decodeAnsiC(source.slice(q + 1, close));
                const written = source.slice(i, close + 1);
                if (decoded.unresolved) {
                    w.mark("ansi_c_escape", w.raw.length);
                    w.opaque(written, decoded.text, "$'", i, close + 1, undefined);
                }
                else
                    w.emit(written, decoded.text, "$'", i, close + 1);
                if (w.inSubscript() && decoded.text.includes("]"))
                    w.subscript.text = true;
                i = close;
                continue;
            }
        }
        if (ch === "'" && !inDouble) {
            if (inSingle) {
                w.quoteChar(ch, "'", i);
                inSingle = false;
                regionBy = undefined;
            }
            else {
                w.quoteChar(ch, "'", i);
                inSingle = true;
                regionBy = "'";
                regionAt = i;
            }
            continue;
        }
        if (ch === '"' && !inSingle) {
            if (inDouble) {
                w.quoteChar(ch, regionBy ?? '"', i);
                inDouble = false;
                regionBy = undefined;
            }
            else {
                const by = pendingLocale ? '$"' : '"';
                pendingLocale = false;
                if (by === '$"')
                    w.mark("locale_string", w.raw.length - 1);
                w.quoteChar(ch, by, i);
                inDouble = true;
                regionBy = by;
                regionAt = i;
            }
            continue;
        }
        if (inSingle) {
            if (w.inSubscript() && ch === "]")
                w.subscript.text = true;
            take(ch, i);
            continue;
        }
        if (!inDouble && ch === "[" && w.started && w.subscript === undefined && !w.compound && acceptable && !subscriptsClosed && IDENTIFIER.test(w.raw)) {
            w.subscript = { rawStart: w.raw.length, depth: 1, text: false };
            take(ch, i);
            continue;
        }
        if (w.inSubscript() && !inDouble) {
            const sub = w.subscript;
            if (ch === "[") {
                sub.depth++;
                take(ch, i);
                continue;
            }
            if (ch === "]") {
                take(ch, i);
                if (--sub.depth === 0)
                    sub.rawEnd = w.raw.length;
                continue;
            }
            if (/[\n;|&<>]/.test(ch)) {
                sub.text = true;
                take(ch, i);
                continue;
            }
            if (BLANK.test(ch)) {
                if (afterLeadingRedirect)
                    sub.text = true;
                take(ch, i);
                continue;
            }
            if (ch === "\\" && source[i + 1] === "]")
                sub.text = true;
        }
        if (w.inSubscript() && inDouble && ch === "]")
            w.subscript.text = true;
        const n1 = next(i);
        if (ch === "\\") {
            const escaped = source[i + 1];
            if (escaped === undefined) {
                w.mark("trailing_backslash", w.raw.length);
                w.opaque(ch, ch, "\\", i, i + 1, undefined);
                continue;
            }
            if (inDouble && !"$`\"\\".includes(escaped))
                w.emit(ch + escaped, ch + escaped, quotedBy(), i, i + 2);
            else
                w.emit(ch + escaped, escaped, inDouble ? quotedBy() : "\\", i, i + 2);
            i++;
            continue;
        }
        if (ch === "`") {
            const tick = backtickBody(source, i, inDouble);
            if (tick === undefined)
                return fail("unterminated_command_substitution", i);
            substitution(i, tick.close + 1, tick.body, "command");
            i = tick.close;
            continue;
        }
        if (ch === "$" && source[n1] === "(") {
            const close = substitutionBodyEnd(source, n1, inDouble, level);
            if (typeof close !== "object" || !("end" in close))
                return close === "unterminated" ? fail("unterminated_command_substitution", i) : close === "undelimited" ? fail("undelimited_substitution", i) : close;
            substitution(i, close.end, source.slice(n1 + 1, close.end - 1), close.arithmetic ? "arithmetic" : "command");
            i = close.end - 1;
            continue;
        }
        if (ch === "$" && source[n1] === "[") {
            const end = bracketExpansionEnd(source, n1);
            if (end === undefined)
                return fail("unterminated_arithmetic_expansion", i);
            substitution(i, end, source.slice(n1 + 1, end - 1), "arithmetic");
            i = end - 1;
            continue;
        }
        if (ch === "$" && source[n1] === "{") {
            if (opensCurrentShellSubstitution(source, n1)) {
                const run = currentShellSubstitutionEnd(source, n1, level + 1);
                if (typeof run !== "object" || !("end" in run))
                    return run === "undelimited" ? fail("undelimited_substitution", i) : run;
                substitution(i, run.end, source.slice(run.from, run.end - 1), "command");
                (current().currentShell ??= []).push(source.slice(run.from, run.end - 1));
                i = run.end - 1;
                continue;
            }
            const end = braceExpansionEnd(source, n1, inDouble, level);
            if (end === undefined)
                return fail("unterminated_parameter_expansion", i);
            const body = source.slice(n1 + 1, end - 1);
            const text = source.slice(i, end);
            const name = EXPANSION_NAME.exec(body)?.[1];
            if (UNREADABLE_EXPANSION_TEXT.test(body))
                w.mark("parameter_text", w.raw.length);
            w.opaque(text, text, quotedBy(), i, end, { kind: "parameter", yields: inDouble && !PER_ELEMENT_BODY.test(body) ? "one" : "many", body, ...(name !== undefined ? { name } : {}) });
            i = end - 1;
            continue;
        }
        if (ch === "$") {
            const bare = bareParameterAt(source, n1);
            if (bare !== undefined) {
                const text = source.slice(i, n1 + bare.head.length);
                w.opaque(text, text, quotedBy(), i, n1 + bare.head.length, { kind: "parameter", yields: inDouble && bare.head !== "@" ? "one" : "many", ...(bare.name !== undefined ? { name: bare.name } : {}) });
                i = n1 + bare.head.length - 1;
                continue;
            }
        }
        if (inDouble) {
            take(ch, i);
            continue;
        }
        if ((ch === "<" || ch === ">") && source[n1] === "(") {
            const close = substitutionBodyEnd(source, n1, false, level, "process");
            if (typeof close !== "object" || !("end" in close))
                return close === "unterminated" ? fail("unterminated_process_substitution", i) : close === "undelimited" ? fail("undelimited_substitution", i) : close;
            substitution(i, close.end, source.slice(n1 + 1, close.end - 1), "process");
            i = close.end - 1;
            continue;
        }
        if (ch === "(" && w.started && w.isAssignmentHead() && (acceptable || (commandWord !== undefined && COMPOUND_OPERAND_COMMANDS.has(commandWord)))) {
            const end = matchedParen(source, i, level);
            if (end === undefined)
                return fail("unterminated_compound_value", i);
            if (typeof end !== "number")
                return end;
            const value = source.slice(i + 1, end - 1);
            const inner = scan(value, true, [firstSegment(value)], level);
            if ("parseFailure" in inner)
                return fail(inner.parseFailure.reason, i + 1 + inner.parseFailure.at);
            const text = source.slice(i, end);
            w.mark("compound_array_value", w.raw.length);
            w.opaque(text, text, undefined, i, end, undefined);
            w.compound = true;
            w.elementWords = inner.command.segments.every((sg) => sg.tokens.every((t) => t.kind === "word")) ? inner.command.segments.flatMap(argvOf) : undefined;
            current().substitutions.push(...inner.command.substitutions);
            const runsHere = inner.command.segments.flatMap((s) => s.currentShell ?? []);
            if (runsHere.length > 0)
                (current().currentShell ??= []).push(...runsHere);
            i = end - 1;
            continue;
        }
        if (w.inSubscript()) {
            take(ch, i);
            continue;
        }
        if (ch === "#" && !w.started && arithParens === 0) {
            const nl = source.indexOf("\n", i);
            readUpTo(nl < 0 ? source.length : nl);
            i = nl < 0 ? source.length : nl - 1;
            continue;
        }
        if (ch === "\n") {
            if (!split) {
                const r = endWord();
                if (r !== undefined)
                    return r;
                continue;
            }
            const refusal = closeSegment("\n", i, i + 1);
            if (refusal !== undefined)
                return refusal;
            if (pendingHeredocs.length > 0) {
                const resume = readHeredocBodies(i + 1);
                if (typeof resume !== "number")
                    return resume;
                current().start = resume;
                i = resume - 1;
            }
            if (metEarlier())
                return finished();
            continue;
        }
        if (ch === "(" || ch === ")") {
            const r = endWord() ?? operandOwed(i);
            if (r !== undefined)
                return r;
            if (ch === "(") {
                if (arithParens > 0)
                    arithParens++;
                else if (split && source[next(i)] === "(" && arithmeticCommandEnd(source, next(i)) !== undefined)
                    arithParens = 1;
            }
            else if (arithParens > 0)
                arithParens--;
            current().tokens.push({ kind: "group", op: ch });
            resetPosition();
            continue;
        }
        if (arithParens === 0 && (ch === "<" || ch === ">" || (ch === "&" && source[n1] === ">"))) {
            let fd;
            const allocated = ch !== "&" && w.started && w.raw === w.folded && /^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(w.raw);
            if (ch !== "&" && w.started && w.raw === w.folded && /^\d+$/.test(w.raw)) {
                fd = Number(w.raw);
                w = new WordBuilder();
            }
            else {
                const r = endWord() ?? operandOwed(i);
                if (r !== undefined)
                    return r;
            }
            const written = fd !== undefined ? { fd } : allocated ? { allocated: true } : {};
            const n2 = next(n1);
            if (ch === "&") {
                if (source[n2] === ">") {
                    pendingRedirect = { op: "&>>" };
                    i = n2;
                }
                else {
                    pendingRedirect = { op: "&>" };
                    i = n1;
                }
                continue;
            }
            if (ch === "<" && source[n1] === "<") {
                if (source[n2] === "<") {
                    pendingRedirect = { op: "<<<", ...written };
                    i = n2;
                    continue;
                }
                const dash = source[n2] === "-";
                pendingHeredoc = { dash, ...written };
                i = dash ? n2 : n1;
                continue;
            }
            if (source[n1] === "&") {
                pendingRedirect = { op: ch === ">" ? ">&" : "<&", ...written };
                i = n1;
                continue;
            }
            if (ch === "<" && source[n1] === ">") {
                pendingRedirect = { op: "<>", ...written };
                i = n1;
                continue;
            }
            if (ch === ">" && (source[n1] === ">" || source[n1] === "|")) {
                pendingRedirect = { op: source[n1] === ">" ? ">>" : ">", ...written };
                i = n1;
                continue;
            }
            pendingRedirect = { op: ch, ...written };
            continue;
        }
        if (split) {
            let refusal;
            if (ch === ";")
                refusal = closeSegment(";", i, i + 1);
            else if (ch === "&") {
                if (source[n1] === "&") {
                    refusal = closeSegment("&&", i, n1 + 1);
                    i = n1;
                }
                else
                    refusal = closeSegment("&", i, i + 1);
            }
            else if (ch === "|") {
                if (source[n1] === "|" || source[n1] === "&") {
                    refusal = closeSegment(source[n1] === "|" ? "||" : "|", i, n1 + 1, source[n1] === "&");
                    i = n1;
                }
                else
                    refusal = closeSegment("|", i, i + 1);
            }
            else if (BLANK.test(ch)) {
                refusal = endWord();
                if (refusal !== undefined)
                    return refusal;
                continue;
            }
            else {
                take(ch, i);
                continue;
            }
            if (refusal !== undefined)
                return refusal;
            if (metEarlier())
                return finished();
            continue;
        }
        if (BLANK.test(ch)) {
            const r = endWord();
            if (r !== undefined)
                return r;
            continue;
        }
        take(ch, i);
    }
    if (inSingle)
        return fail("unterminated_single_quote", regionAt);
    if (inDouble)
        return fail("unterminated_double_quote", regionAt);
    const tail = endWord() ?? operandOwed(source.length);
    if (tail !== undefined)
        return tail;
    if (pendingHeredocs.length > 0)
        return unterminatedHeredocs(source.length, false);
    return finished();
}
export function connectorReaching(segments, si) {
    const own = segments[si].connector;
    for (let k = si - 1; own === "\n" && k > 0 && segments[k].tokens.length === 0; k--) {
        if (segments[k].connector === "|")
            return "|";
        if (segments[k].connector !== "\n")
            break;
    }
    return own;
}
const firstSegment = (source) => ({ start: 0, end: source.length, connector: "start", tokens: [], substitutions: [] });
const segmentView = (source, s) => ({
    text: source.slice(s.start, s.end),
    connector: s.connector,
    ...(s.pipesStderr ? { pipesStderr: true } : {}),
    tokens: s.tokens,
    substitutions: s.substitutions,
    ...(s.currentShell !== undefined ? { currentShell: s.currentShell } : {}),
});
export function lexShell(shell, source) {
    const segments = [firstSegment(source)];
    const pass = scan(source, false, segments, 0);
    const readBefore = () => segments.map((s) => segmentView(source, s));
    if (shell !== SHELL_LEX_DIALECT)
        return { parseFailure: { reason: "started_shell_not_bash", at: "parseFailure" in pass ? pass.parseFailure.at : source.length }, readBefore: readBefore() };
    return "parseFailure" in pass ? { ...pass, readBefore: readBefore() } : pass.command;
}
const STATEMENT_BOUNDARY = new Set(["\n", ";", "&", "|"]);
const BOUNDARY_PAIRS = new Set(["&&", "||", "|&", ";;", ";&", "&>"]);
export const READ_PAST_STOP_BUDGET = 4 * 1024 * 1024;
export function segmentsPastStop(source, failure) {
    let boundary = failure.parseFailure.at;
    while (boundary < source.length && !STATEMENT_BOUNDARY.has(source[boundary]))
        boundary++;
    if (boundary === source.length)
        return [];
    return whileReading(source, () => {
        const read = new Map();
        const starts = new Set();
        const walked = [firstSegment(source)];
        scan(source, false, walked, 0);
        let budget = READ_PAST_STOP_BUDGET;
        let second = -1;
        for (let j = Math.max(failure.parseFailure.at, walked.at(-1).start); j < source.length && budget > 0; j++) {
            const c = source[j];
            if (!STATEMENT_BOUNDARY.has(c))
                continue;
            if (j < second)
                continue;
            if (j > second && c !== "\n") {
                const k = past(source, j + 1);
                if (BOUNDARY_PAIRS.has(c + (source[k] ?? ""))) {
                    second = k;
                    continue;
                }
            }
            if (starts.has(j + 1))
                continue;
            const from = j + 1;
            const segments = [{ ...firstSegment(source), start: from }];
            const reading = { from, met: starts, fresh: new Set([from]) };
            readTo = from;
            const pass = scan(source, false, segments, 0, undefined, reading);
            budget -= Math.max(from + 1, readTo) - from;
            const complete = "parseFailure" in pass ? segments.slice(0, -1) : segments;
            complete.forEach((s, k) => {
                if (reading.fresh.has(s.start))
                    starts.add(s.start);
                const view = segmentView(source, s);
                const key = `${s.start}:${view.text}`;
                if (!read.has(key))
                    read.set(key, { at: s.start, segment: { ...view, ...(k === 0 ? { connector: "\n" } : {}), spliced: true } });
            });
        }
        return [...read.values()].sort((a, b) => a.at - b.at || a.segment.text.length - b.segment.text.length).map((r) => r.segment);
    });
}
export function lexShellText(shell, source) {
    const lexed = lexShell(shell, source);
    if ("parseFailure" in lexed)
        return { reject: PARSE_FAILURE_SENTENCE[lexed.parseFailure.reason] };
    for (const segment of lexed.segments) {
        for (const token of segment.tokens) {
            const word = token.kind === "word" ? token : token.kind === "redirect" ? token.target : undefined;
            if (word?.unresolved !== undefined)
                return { reject: UNRESOLVED_SENTENCE[word.unresolved] };
        }
    }
    return lexed;
}
export function bashOnlyConstructsOf(command) {
    const found = new Set();
    const word = (w) => {
        for (const s of w.quotedSpans) {
            if (s.by === "$'")
                found.add("ansi_c_quoting");
            if (s.by === '$"')
                found.add("locale_string");
        }
        for (const p of w.expansions) {
            if (p.expansion?.kind === "process")
                found.add("process_substitution");
            if (p.expansion?.kind === "brace")
                found.add("brace_expansion");
        }
        if (w.assignment !== undefined) {
            if (w.assignment.op === "+=")
                found.add("append_assignment");
            if (w.assignment.subscript !== undefined)
                found.add("subscript_assignment");
            if (w.assignment.form === "compound")
                found.add("compound_assignment");
        }
    };
    for (const segment of command.segments) {
        if (segment.pipesStderr)
            found.add("pipe_both");
        for (const t of segment.tokens) {
            if (t.kind === "word")
                word(t);
            else if (t.kind === "redirect") {
                if (t.op === "<<<")
                    found.add("here_string");
                if (t.op === "&>" || t.op === "&>>")
                    found.add("redirect_both");
                if (t.target !== undefined)
                    word(t.target);
            }
        }
    }
    return BASH_ONLY_CONSTRUCTS.filter((c) => found.has(c));
}