@sema-agent/core
Version:
Stateless, task-oriented AI agent core
2,006 lines • 100 kB
JavaScript
import { SHELL_LEX_DIALECT, argvOf, arithmeticTextIsPlain, expansionHidesRun, expansionsInHeredocBody, lexShell, literalTextOf, literalTildeSpelling, namesRedirectDescriptor, parameterArithmeticTexts } from "../../shell/lex.js";
import { shellWordsOf } from "../../shell/shell-words.js";
import { isShellSyntaxWord, LOOP_LIST_HEADS, readProgramPosition } from "./bash-program-position.js";
import { declaredAttributes, programRow, readArgRoles } from "./program-read-model.js";
import { codeBodies, descriptorTextsOf } from "./shell-reentry-text.js";
import { braceWordListsOf } from "./shell-read-brace.js";
import { BUILTIN_ENABLED, BUILTINS_ALL, ENABLE_BUILTIN, builtinKey, chainAvailability, enableBindings, isBuiltinKey, isDisabledValue, speaksFor } from "./shell-read-builtins.js";
export function judgedSpellingOf(v) {
if (v.glob !== true)
return undefined;
const judged = literalTildeSpelling(v.parts.map((p) => (p.pattern ? p.judged : p.text)).join(""));
return judged === literalTildeSpelling(v.spelled) ? undefined : judged;
}
export function floorOf(v) {
const pattern = judgedSpellingOf(v);
return v.glob === true ? { spelled: v.spelled, glob: true, ...(pattern !== undefined ? { pattern } : {}) } : { spelled: v.spelled };
}
export function bindingValues(b) {
return joinFloors({ values: b.state === "unknown" ? [] : b.state.map(floorOf), pastBound: false }, b.floor ?? NO_FLOOR);
}
export function bindingFloors(bindings) {
const out = new Map();
for (const b of bindings)
out.set(b.name, joinFloors(out.get(b.name) ?? NO_FLOOR, bindingValues(b)));
return out;
}
function sameValue(a, b) {
if (a.spelled !== b.spelled || a.fields?.length !== b.fields?.length)
return false;
if (a.glob !== true || b.glob !== true)
return a.glob === b.glob;
return a.parts.length === b.parts.length && a.parts.every((p, i) => p.text === b.parts[i].text && p.pattern === b.parts[i].pattern);
}
export const SHELL_INTEGER_VARIABLES = new Set([
"RANDOM", "SECONDS", "LINENO", "OPTIND", "MAILCHECK", "HISTCMD", "SRANDOM", "EPOCHSECONDS", "EPOCHREALTIME", "BASHPID", "BASH_MONOSECONDS",
"BASH_TRAPSIG", "COLUMNS", "LINES", "SHLVL", "ERRNO", "TMOUT", "HISTSIZE", "SAVEHIST", "TRY_BLOCK_ERROR", "TRY_BLOCK_INTERRUPT", "KEYTIMEOUT",
"LISTMAX", "LOGCHECK", "PERIOD", "FUNCNEST", "UID", "EUID", "GID", "EGID", "REPORTTIME", "REPORTMEMORY", "DIRSTACKSIZE", "BAUD",
"ZLE_RPROMPT_INDENT", "MBEGIN", "MEND", "PPID", "ARGC", "ZSH_SUBSHELL", "TTYIDLE", "status",
]);
const SHELL_SET_VARIABLES = new Set(["REPLY", "OPTARG", "MAPFILE", "BASH_REMATCH", "PIPESTATUS", "FUNCNAME", "BASH_COMMAND", "BASH_SUBSHELL", "COPROC", "GROUPS", "SHELLOPTS", "BASHOPTS", "BASH_VERSINFO", "DIRSTACK", "BASH_ARGV", "BASH_ARGC", "BASH_SOURCE", "BASH_LINENO"]);
export function shellKeepsName(name) {
return SHELL_INTEGER_VARIABLES.has(name) || SHELL_SET_VARIABLES.has(name);
}
export const WORKING_DIRECTORY_NAMES = Object.freeze(["PWD", "OLDPWD"]);
const isWorkingDirectoryName = (name) => name === "PWD" || name === "OLDPWD";
const DIRECTORY_STACK_NAME = "DIRSTACK";
const OPENING_WORDS = shellWordsOf("scope_open");
const CLOSING_WORDS = shellWordsOf("scope_close");
const SWITCHING_WORDS = shellWordsOf("scope_switch");
const GROUP_WORDS = shellWordsOf("group"), DEFINITION_WORDS = shellWordsOf("definition"), ITERATING_HEADS = shellWordsOf("loop_iterates"), BACKGROUND_WORDS = shellWordsOf("background");
export const SPECIAL_BUILTINS = new Set([":", ".", "break", "continue", "eval", "exec", "exit", "export", "readonly", "return", "set", "shift", "source", "times", "trap", "unset"]);
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
const LOCAL_DECLARATION = "local";
const BODY_SCOPED_DECLARATIONS = new Set([LOCAL_DECLARATION, "declare", "typeset"]);
const ATTRIBUTE_ONLY = new Set(["export", "readonly"]);
const FUNCTION_KEY_PREFIX = "()";
export const functionKey = (name) => FUNCTION_KEY_PREFIX + name;
const isFunctionKey = (name) => name.startsWith(FUNCTION_KEY_PREFIX);
const FUNCTION_DEFINED = [{ spelled: "defined" }];
const FUNCTION_ABSENT = [{ spelled: "absent" }];
const isDefinedValue = (v) => v.spelled === "defined";
const EXPORT_FUNCTION_BUILTINS = new Set(["export", "declare", "typeset"]);
export function exportedFunctionNames(argv) {
const program = readProgramPosition(argv).program;
const prog = program?.basename;
if (program === undefined || prog === undefined || !EXPORT_FUNCTION_BUILTINS.has(prog))
return [];
const literal = (w) => w.expansions.length === 0;
const rest = argv.slice(program.index + 1);
const flags = new Set(rest.filter((w) => literal(w) && /^-[A-Za-z]+$/.test(w.folded)).flatMap((w) => [...w.folded.slice(1)]));
if (!flags.has("f") || !(prog === "export" || flags.has("x")))
return [];
return rest.filter((w) => literal(w) && w.assignment === undefined && /^[A-Za-z_][A-Za-z0-9_]*$/.test(w.folded)).map((w) => w.folded);
}
export function envFunctionNames(argv) {
const out = [];
for (const w of argv) {
if (w.expansions.length !== 0)
continue;
const m = /^BASH_FUNC_([A-Za-z_][A-Za-z0-9_]*)(?:%%|\(\))=/.exec(w.folded);
if (m !== null)
out.push(m[1]);
}
return out;
}
export function inheritedFunctionsOf(segments, inherited) {
const defined = new Set(segments.flatMap((s) => s.defines));
const out = new Map(inherited ?? []);
for (const s of segments)
for (const name of exportedFunctionNames(s.argv))
out.set(name, defined.has(name) ? "read" : out.get(name) ?? "unread");
for (const s of segments)
for (const name of envFunctionNames(s.argv))
out.set(name, "unread");
return out;
}
export function inheritedExportedFunctions(names) {
return {
start: (key) => (isFunctionKey(key) ? (names.has(key.slice(FUNCTION_KEY_PREFIX.length)) ? FUNCTION_DEFINED : FUNCTION_ABSENT) : BUILTIN_ENABLED),
bound: "all",
};
}
const ATTRIBUTE_KINDS = { integer: "integer", transformed: "transformed", frozen: "frozen" };
const EVERY_ATTRIBUTE = Object.values(ATTRIBUTE_KINDS).map((kind) => ({ kind }));
export const NO_FLOOR_READER = () => NO_FLOOR;
export function floorReaderOf(table) {
return (word, overlay, floors) => wordFloorValues(word, overlay.size === 0 ? table : {
stateOf: (name) => overlay.get(name) ?? table.stateOf(name),
floorOf: (name) => (overlay.has(name) ? floors.get(name) ?? NO_FLOOR : table.floorOf(name)),
});
}
export function projectSegments(segments) {
const { dropped, arms } = segmentStructure(segments);
return segments.map((segment, si) => projectSegment(segment, dropped[si], arms[si]));
}
function projectSegment(segment, dropped, arm) {
let grouped = segment.tokens.some((t) => t.kind === "group");
const defines = dropped.heads.flat();
const tokens = dropped.tokens.slice(arm.own.size === 0 ? 0 : Math.max(...arm.own) + 1);
const words = tokens.filter((t) => {
if (t.kind !== "word")
return false;
if (t.raw === t.folded && GROUP_WORDS.has(t.folded)) {
grouped = true;
return false;
}
return true;
});
return { argv: words, redirects: tokens.filter((t) => t.kind === "redirect"), grouped, defines };
}
function isDefinitionName(word) {
return IDENTIFIER.test(word.folded) || (word.atCommandPosition && word.expansions.length === 0 && !/[?*+@!]$/.test(word.raw));
}
export function dropDefinitionHeads(tokens) {
const heads = Array.from({ length: tokens.length + 1 }, () => []);
const drop = (k, count, name) => {
tokens.splice(k, count);
heads.splice(k, count);
heads[k].push(name);
};
for (let k = 0; k + 1 < tokens.length; k++) {
const [a, b, c, d] = [tokens[k], tokens[k + 1], tokens[k + 2], tokens[k + 3]];
if (a.kind === "word" && DEFINITION_WORDS.has(a.raw) && a.atCommandPosition && b.kind === "word")
drop(k--, c?.kind === "group" && c.op === "(" && d?.kind === "group" && d.op === ")" ? 4 : 2, b.folded);
}
for (let k = 0; k + 2 < tokens.length; k++) {
const [a, b, c] = [tokens[k], tokens[k + 1], tokens[k + 2]];
if (a.kind === "word" && b.kind === "group" && b.op === "(" && c.kind === "group" && c.op === ")" && isDefinitionName(a))
drop(k, 3, a.folded);
}
return heads;
}
function withoutDefinitionHeads(segment) {
const tokens = [...segment.tokens];
return { tokens, heads: dropDefinitionHeads(tokens) };
}
function segmentStructure(segments) {
const dropped = segments.map((segment) => withoutDefinitionHeads(segment));
const tokens = dropped.map((d) => d.tokens);
const operands = operandsOf(tokens, segments.map((segment) => isArithmeticCommand(segment)));
return { dropped, operands, arms: caseWordsOf(tokens, segments.map((s) => s.connector), operands) };
}
function operandsOf(segments, arithmetic) {
let conditional = false;
let parens = 0;
return segments.map((tokens, si) => {
const out = new Set();
tokens.forEach((t, k) => {
if (parens === 0 && !conditional) {
if (t.kind === "word" && t.atCommandPosition && t.raw === "[[")
conditional = true;
else if (t.kind === "group" && t.op === "(" && ((k === 0 && arithmetic[si] === true) || extglobParen(tokens, k))) {
parens = 1;
out.add(k);
}
return;
}
if (parens === 0 && t.kind === "word" && t.raw === "]]") {
conditional = false;
return;
}
out.add(k);
if (parens > 0 && t.kind === "group")
parens += t.op === "(" ? 1 : -1;
});
return out;
});
}
function caseWordsOf(segments, connectors, operands) {
const frames = [];
const toPattern = (f) => { f.state = "pattern"; f.started = false; };
return segments.map((tokens, si) => {
const top = frames[frames.length - 1];
const next = connectors[si + 1];
if (top?.state === "arm" && tokens.length === 0 && connectors[si] === ";" && (next === ";" || next === "&"))
toPattern(top);
const own = new Set();
let end = -1;
tokens.forEach((t, k) => {
if (operands[si].has(k))
return;
const f = frames[frames.length - 1];
if (f === undefined || f.state === "arm") {
const keyword = t.kind === "word" && t.atCommandPosition && t.raw === t.folded ? t.folded : undefined;
if (keyword === "case")
frames.push({ state: "subject", started: false });
else if (keyword === "esac" && f !== undefined)
frames.pop();
return;
}
if (f.state === "subject") {
if (t.kind === "word") {
own.add(k);
f.state = "in";
}
else
frames.pop();
return;
}
if (f.state === "in") {
if (t.kind === "word" && t.raw === "in") {
own.add(k);
toPattern(f);
}
else
frames.pop();
return;
}
if (!f.started && t.kind === "word" && t.raw === "esac") {
frames.pop();
return;
}
own.add(k);
if (t.kind === "group" && t.op === ")") {
end = k;
f.state = "arm";
return;
}
f.started = true;
});
return { own, end };
});
}
function extglobParen(tokens, at) {
const before = tokens[at - 1];
return before?.kind === "word" && /[?*+@!]$/.test(before.raw);
}
function blockStructure(segments) {
let depth = 0;
let bodies = 0;
let subshellIds = 0;
const subshellStack = [];
const frames = [];
const deeper = () => {
depth++;
for (const f of frames)
if (!f.opened && depth > f.body.base)
f.opened = true;
};
const shallower = () => {
depth--;
while (frames.length > 0 && frames[frames.length - 1].opened && depth <= frames[frames.length - 1].body.base)
frames.pop();
};
const { dropped, operands, arms } = segmentStructure(segments);
return segments.map((segment, si) => {
const { tokens, heads } = dropped[si];
const arm = arms[si];
const operand = operands[si];
const defs = [];
const startBodies = (k) => {
for (const name of heads[k]) {
const enclosing = innermost();
defs.push({ name, standing: { ...(enclosing !== undefined ? { body: enclosing } : {}), subshells: [...subshellStack], depth } });
frames.push({ body: { id: bodies++, base: depth }, opened: false });
}
};
const arithmetic = isArithmeticCommand(segment);
let lowest = depth;
let words;
let subshells;
let body;
let within = [];
const switches = [];
const innermost = () => [...frames].reverse().find((f) => f.opened)?.body;
const openBodies = () => frames.filter((f) => f.opened).map((f) => f.body.id);
const place = () => { words ??= depth; subshells ??= [...subshellStack]; body = innermost(); within = openBodies(); };
let closed;
const visit = (t, k) => {
if (arm.own.has(k)) {
if (k === arm.end)
switches.push(depth);
return;
}
if (operand.has(k)) {
if (t.kind === "word")
place();
return;
}
if (t.kind === "group") {
if (t.op === "(") {
deeper();
subshellStack.push(subshellIds++);
return;
}
shallower();
subshellStack.pop();
lowest = Math.min(lowest, depth);
closed = { k, to: depth };
return;
}
if (t.kind !== "word")
return;
const keyword = t.atCommandPosition && t.raw === t.folded ? t.folded : undefined;
if (keyword !== undefined && OPENING_WORDS.has(keyword))
deeper();
else if (keyword !== undefined && CLOSING_WORDS.has(keyword)) {
shallower();
lowest = Math.min(lowest, depth);
closed = { k, to: depth };
}
else if (keyword !== undefined && SWITCHING_WORDS.has(keyword))
switches.push(depth);
else
place();
};
tokens.forEach((t, k) => {
startBodies(k);
visit(t, k);
let settled = false;
for (let i = frames.length - 1; i >= 0 && !frames[i].opened; i--) {
const f = frames[i];
f.opened = true;
settled = true;
if (t.kind === "word" && t.raw === "[[" && t.atCommandPosition)
f.conditional = true;
else if (t.kind === "group" && t.op === "(" && arithmetic)
f.parens = 0;
else
f.flat = true;
}
if (settled && t.kind === "word") {
body = innermost();
within = openBodies();
}
const top = frames[frames.length - 1];
if (top?.parens !== undefined && t.kind === "group") {
top.parens += t.op === "(" ? 1 : -1;
if (top.parens <= 0)
frames.pop();
}
if (t.kind === "word" && t.raw === "]]")
while (frames.length > 0 && frames[frames.length - 1].conditional === true)
frames.pop();
});
while (frames.length > 0 && frames[frames.length - 1].flat === true)
frames.pop();
startBodies(tokens.length);
const closedBy = closed;
const trailing = closedBy !== undefined && tokens.slice(closedBy.k + 1).some((t) => t.kind === "redirect" || t.kind === "heredoc") ? { trailingTo: closedBy.to } : {};
return { words: words ?? depth, after: depth, lowest, switches, subshells: subshells ?? [...subshellStack], defs, placed: words !== undefined, within, ...trailing, ...(body !== undefined ? { body } : {}) };
});
}
const READABLE_VALUE = /^[^\\~()]*$/;
const WORD_VALUES_MAX = 64;
const quotedRunsOf = (v) => v.glob === true ? v.parts.map((r) => (r.pattern ? { text: r.text, mode: "set", judged: r.judged } : { text: r.text, mode: "inactive" })) : [{ text: v.spelled, mode: "inactive" }];
function formedField(f) {
const runs = f.runs;
if (!runs.some((r) => r.mode === "active" && /[[\]*?]/.test(r.text))) {
if (!runs.some((r) => r.mode === "raw" || r.mode === "set"))
return { spelled: f.text };
return { spelled: f.text, glob: true, parts: joinRuns([], runs.map((r) => (r.mode === "raw" || r.mode === "set" ? { text: r.text, pattern: true, judged: r.judged } : { text: r.text, pattern: false }))) };
}
if (runs.some((r) => r.mode === "active" && /[ \t\n\\]/.test(r.text)) || (runs.some((r) => r.mode === "set") && runs.some((r) => r.mode === "active" && /[[\]]/.test(r.text))))
return undefined;
const escaped = runs.map((r) => (r.mode === "raw" || r.mode === "set" ? r.text : r.text.replace(r.mode === "active" ? /[^A-Za-z0-9_./*?[\]!^:=,+@%-]/g : /[^A-Za-z0-9_./]/g, (c) => `\\${c}`))).join("");
const lexed = lexShell(SHELL_LEX_DIALECT, `: ${escaped}`);
const words = "parseFailure" in lexed || lexed.segments.length !== 1 ? undefined : argvOf(lexed.segments[0]);
if (words?.length !== 2)
return undefined;
let parts = [];
for (const p of words[1].pieces) {
if (p.expansion?.pattern !== undefined)
parts = joinRuns(parts, [{ text: p.expansion.pattern.written, pattern: true, judged: p.expansion.pattern.judged }]);
else if (p.expansion === undefined && p.literal !== undefined)
parts = joinRuns(parts, [{ text: p.literal, pattern: false }]);
else
return undefined;
}
return parts.some((r) => r.pattern) ? { spelled: f.text, glob: true, parts } : { spelled: f.text };
}
export function wordValues(word, table, quoted, overlay = new Map(), split = false) {
if (!word.pieces.some((p) => p.expansion?.kind === "parameter" || p.expansion?.kind === "tilde") && namesIn(word).length === 0)
return undefined;
return valueOf(word, table, quoted, overlay, split);
}
export function namesIn(word) {
return word.pieces.flatMap((p) => {
const e = p.expansion;
if (e?.kind === "parameter" && e.name !== undefined)
return e.body === undefined || e.body === e.name ? [e.name] : [];
return e?.kind === "glob" && e.pattern === undefined ? (bracketBodyOf(e.body) ?? []).flatMap((w) => namesIn(w)) : [];
});
}
function bracketBodyOf(body) {
const lexed = body === undefined ? undefined : lexShell(SHELL_LEX_DIALECT, `""${body}`);
return lexed === undefined || "parseFailure" in lexed ? undefined : lexed.segments.flatMap((s) => argvOf(s));
}
function joinRuns(runs, more) {
const out = [...runs];
for (const r of more) {
const last = out[out.length - 1];
if (last !== undefined && last.pattern && r.pattern)
out[out.length - 1] = { text: last.text + r.text, pattern: true, judged: last.judged + r.judged };
else if (last !== undefined && !last.pattern && !r.pattern)
out[out.length - 1] = { text: last.text + r.text, pattern: false };
else if (r.text !== "")
out.push(r);
}
return out;
}
export function valueOf(word, table, quoted, overlay = new Map(), split = false) {
const stateOf = (name) => (table === undefined ? "unknown" : overlay.get(name) ?? table.stateOf(name));
if (split && table !== undefined && word.pieces.length === 1) {
const only = word.pieces[0];
const e = only.expansion;
if (only.quotedBy === '"' && e?.kind === "parameter" && e.name !== undefined && e.body === `${e.name}[@]`) {
const list = overlay.has(e.name) ? undefined : table.arrayOf(e.name);
return list === undefined ? "unknown" : [{ spelled: list.map((v) => v.spelled).join(" "), fields: list.map((v) => v.spelled) }];
}
}
const EMPTY = { text: "", runs: [] };
let combos = [{ field: EMPTY, closed: [], started: false, split: false }];
const activeRun = (text) => ({ text, mode: "active" });
const splitInto = (c, value) => {
const words = value.split(/[ \t\n]+/).filter((w) => w !== "");
if (words.length === 0)
return value === "" ? { ...c, split: true } : { ...c, field: EMPTY, started: false, closed: c.started ? [...c.closed, c.field] : c.closed, split: true };
const closed = [...c.closed];
if (/^[ \t\n]/.test(value) && c.started)
closed.push(c.field);
let field = closed.length > c.closed.length ? { text: words[0], runs: [activeRun(words[0])] } : { text: c.field.text + words[0], runs: [...c.field.runs, activeRun(words[0])] };
for (let i = 1; i < words.length; i++) {
closed.push(field);
field = { text: words[i], runs: [activeRun(words[i])] };
}
if (!/[ \t\n]$/.test(value))
return { ...c, field, started: true, closed, split: true };
closed.push(field);
return { ...c, field: EMPTY, started: false, closed, split: true };
};
const extend = (options) => {
const next = combos.flatMap((c) => options.map((o) => ({ ...c, field: { text: c.field.text + o.text, runs: [...c.field.runs, ...o.runs] }, started: true })));
if (next.length > WORD_VALUES_MAX)
return false;
combos = next;
return true;
};
const unquotedKind = (v) => v.glob === true || !READABLE_VALUE.test(v.spelled) ? undefined : !/[ \t\n]/.test(v.spelled) && v.spelled !== "" ? "run" : split ? "split" : undefined;
const walk = (pieces, unquoted) => {
for (const p of pieces) {
const e = p.expansion;
const bare = unquoted && p.quotedBy === undefined;
if (e === undefined) {
if (p.literal === undefined || !extend([{ text: p.literal, runs: [{ text: p.literal, mode: bare ? "active" : "inactive" }] }]))
return false;
}
else if (e.kind === "glob") {
const formed = e.pattern;
if (formed !== undefined) {
if (!extend([{ text: formed.folded, runs: [{ text: formed.written, mode: "raw", judged: formed.judged }] }]))
return false;
continue;
}
const words = bracketBodyOf(e.body);
if (words?.length !== 1 || !extend([{ text: "[", runs: [activeRun("[")] }]) || !walk(words[0].pieces, true) || !extend([{ text: "]", runs: [activeRun("]")] }]))
return false;
}
else if (e.kind === "tilde") {
const home = e.body === "~" ? stateOf("HOME") : "unknown";
if (home === "unknown" || !extend(home.map((v) => ({ text: v.spelled, runs: quotedRunsOf(v) }))))
return false;
}
else if (e.kind === "parameter" && e.name !== undefined && (e.body === undefined || e.body === e.name)) {
const state = stateOf(e.name);
if (state === "unknown")
return false;
if (!bare) {
if (!extend(state.map((v) => ({ text: v.spelled, runs: quotedRunsOf(v) }))))
return false;
continue;
}
const kinds = state.map(unquotedKind);
if (table?.ifsTouched === true || kinds.includes(undefined))
return false;
if (!kinds.includes("split")) {
if (!extend(state.map((v) => ({ text: v.spelled, runs: [activeRun(v.spelled)] }))))
return false;
continue;
}
const next = combos.flatMap((c) => state.map((v) => splitInto(c, v.spelled)));
if (next.length > WORD_VALUES_MAX)
return false;
combos = next;
}
else
return false;
}
return true;
};
if (!walk(word.pieces, !quoted))
return "unknown";
const out = [];
for (const c of combos) {
const fields = (c.split ? (c.started ? [...c.closed, c.field] : c.closed) : [c.field]).map(formedField);
const formed = fields.filter((f) => f !== undefined && !(c.split && f.glob === true));
if (formed.length !== fields.length)
return "unknown";
const v = !c.split ? formed[0] : formed.length !== 1 ? { spelled: formed.map((f) => f.spelled).join(" "), fields: formed.map((f) => f.spelled) } : { spelled: formed[0].spelled };
if (!out.some((x) => sameValue(x, v)))
out.push(v);
}
return out;
}
export const NO_FLOOR = { values: [], pastBound: false };
export function isEmptyFloor(f) {
return f.values.length === 0 && !f.pastBound;
}
export function joinFloors(...floors) {
return { values: floors.flatMap((f) => f.values), pastBound: floors.some((f) => f.pastBound) };
}
export function wordFloorValues(word, table) {
if (table === undefined)
return { values: [], pastBound: false };
for (let kept = Number.POSITIVE_INFINITY;; kept = Math.min(kept, WORD_VALUES_MAX) - 1) {
const combos = floorCombos(word, table, kept);
if (combos !== "past")
return kept === Number.POSITIVE_INFINITY ? combos : { values: combos.values, pastBound: true };
if (kept === 0)
return { values: [], pastBound: true };
}
}
function transformsValue(p) {
const e = p.expansion;
if (e?.kind !== "parameter" || e.name === undefined || e.body === undefined || e.body === e.name)
return false;
return !(e.body.startsWith(`${e.name}[`) && e.body.indexOf("]") === e.body.length - 1);
}
function floorCombos(word, table, kept) {
let combos = [{ spelled: "" }];
let pastBound = false;
const own = [];
const transformed = word.pieces.some(transformsValue);
const ofName = (name, whole) => {
const state = table.stateOf(name);
const known = state !== "unknown" && whole ? state : undefined;
const floor = known === undefined ? table.floorOf(name) : NO_FLOOR;
pastBound ||= floor.pastBound;
return known !== undefined ? known.map(floorOf) : [...floor.values.filter((o) => o.held !== true), ...floor.values.filter((o) => o.held === true).slice(0, kept)];
};
for (const p of word.pieces) {
const e = p.expansion;
let options = [];
if (e === undefined) {
if (p.literal !== undefined)
options = [{ spelled: p.literal }];
}
else if (e.kind === "parameter" && e.name !== undefined) {
options = e.name === DIRECTORY_STACK_NAME && /^DIRSTACK\[\d+\]$/.test(e.body ?? "") ? ofName(e.body, false) : ofName(e.name, e.body === undefined || e.body === e.name);
}
else if (e.kind === "tilde") {
options = e.body === "~" ? ofName("HOME", true) : [{ spelled: e.body ?? "~" }];
}
if (transformed)
own.push(...options.map((o) => ({ ...o, piece: true })));
if (options.length === 0)
combos = undefined;
if (combos === undefined)
continue;
const next = [];
for (const c of combos) {
for (const o of distinctSpellings(options)) {
const pattern = c.pattern !== undefined || o.pattern !== undefined ? (c.pattern ?? c.spelled) + (o.pattern ?? o.spelled) : undefined;
const piece = c.piece === true || o.piece === true ? { piece: true } : {};
next.push(c.glob === true || o.glob === true ? { spelled: c.spelled + o.spelled, glob: true, ...(pattern !== undefined ? { pattern } : {}), ...piece } : { spelled: c.spelled + o.spelled, ...piece });
}
}
combos = distinctSpellings(next);
if (combos.length > WORD_VALUES_MAX)
return "past";
}
const values = transformed ? distinctSpellings([...(combos ?? []), ...own]) : combos ?? [];
return values.length > WORD_VALUES_MAX ? "past" : { values, pastBound };
}
function distinctSpellings(values) {
const kept = new Map();
for (const v of values) {
const key = `${v.glob === true ? "g" : "l"}\u0000${v.spelled}\u0000${v.pattern ?? ""}`;
const k = kept.get(key);
if (k === undefined || (k.piece === true && v.piece !== true))
kept.set(key, v);
}
return [...kept.values()];
}
export function loopListHeadAt(argv) {
const at = isShellSyntaxWord(argv[0], LOOP_LIST_HEADS) ? 0 : readProgramPosition(argv).written;
return at !== undefined && isShellSyntaxWord(argv[at], LOOP_LIST_HEADS) ? at : undefined;
}
export function bindingEffectOf(segment, argv, shape, readValue, shadow, availability, fed, fedByLoop = false, splitUnsettled = false, readFloor = NO_FLOOR_READER) {
const effect = namesEffectOf(segment, argv, shape, readValue, shadow, availability, fed, fedByLoop, splitUnsettled, readFloor);
const last = lastArgumentOf(segment, argv, readValue);
return last === undefined ? effect : { ...effect, bindings: [...effect.bindings, last] };
}
const LAST_ARGUMENT_NAME = "_";
function lastArgumentOf(segment, argv, readValue) {
const head = argv[0];
if (head === undefined || isArithmeticCommand(segment) || loopListHeadAt(argv) !== undefined || (head.atCommandPosition && head.raw === head.folded && CLOSING_WORDS.has(head.folded)))
return undefined;
const pos = readProgramPosition(argv);
if (pos.program === undefined)
return pos.assignments.length > 0 ? { name: LAST_ARGUMENT_NAME, state: [{ spelled: "" }] } : undefined;
if (pos.program.basename === "[[")
return undefined;
const word = argv[argv.length - 1];
const unknown = { name: LAST_ARGUMENT_NAME, state: "unknown" };
if (BACKGROUND_WORDS.has(argv[0].raw) || word.assignment !== undefined || word.pieces.some((p) => p.expansion?.yields === "many"))
return unknown;
const expanded = new Map();
for (const t of segment.tokens)
if (t.kind === "word")
for (const name of assignedByPieces(t.pieces))
expanded.set(name, "unknown");
const state = readValue(word, true, expanded);
return state === "unknown" || state.some((v) => v.glob === true || v.fields !== undefined) ? unknown : { name: LAST_ARGUMENT_NAME, state };
}
export function runsAtExitOnly(argv) {
const pos = readProgramPosition(argv);
if (pos.program?.basename !== "trap")
return false;
const args = argv.slice(pos.program.index + 1).map((w) => w.folded);
const row = programRow("trap");
const operands = row === undefined ? [] : readArgRoles(row, args).flatMap((e) => (e.kind === "operand" ? [args[e.at]] : []));
return operands.length > 1 && operands.slice(1).every((s) => /^(?:(?:SIG)?EXIT|0)$/i.test(s));
}
export function exportsOf(argv) {
const program = readProgramPosition(argv).program;
if (program === undefined)
return undefined;
const args = argv.slice(program.index + 1);
const end = args.findIndex((w) => w.folded === "--");
const options = (end < 0 ? args : args.slice(0, end)).filter((w) => /^[-+]./.test(w.folded) && w.assignment === undefined);
if (program.basename === "set")
return options.some((w, i) => /^-[A-Za-z]*a[A-Za-z]*$/.test(w.folded) || (w.folded === "-o" && options[i + 1]?.folded === "allexport") || w.folded === "-oallexport") ? "allexport" : undefined;
const exporting = program.basename === "export" ? !options.some((w) => /^-.*[fn]/.test(w.folded)) : BODY_SCOPED_DECLARATIONS.has(program.basename) ? options.some((w) => /^-[A-Za-z]*x/.test(w.folded)) && !options.some((w) => w.folded.startsWith("-") && /f/.test(w.folded)) : false;
if (!exporting)
return undefined;
const names = new Set();
for (const w of args) {
if (options.includes(w) || w.folded === "--")
continue;
if (w.assignment !== undefined) {
names.add(w.assignment.name);
continue;
}
if (w.pieces.some((p) => p.expansion !== undefined || p.literal === undefined))
return "all";
const name = nameIn(w.folded);
if (name !== undefined)
names.add(name);
}
return names.size > 0 ? names : undefined;
}
function namesEffectOf(segment, argv, shape, readValue, shadow, availability, fed, fedByLoop = false, splitUnsettled = false, readFloor = NO_FLOOR_READER) {
const bindings = [];
let all = shape.defines.length > 0 ? "reset" : undefined;
const unknownAll = () => void (all = "unknown");
const overlay = new Map();
const floors = new Map();
let scope;
const bind = (b) => {
bindings.push(scope !== undefined ? { ...b, scope } : b);
if (b.prefix === true)
return;
overlay.set(b.name, b.state);
if (b.floor !== undefined)
floors.set(b.name, b.floor);
else
floors.delete(b.name);
};
const kill = (name) => bind({ name, state: "unknown" });
const floorFrom = (bound, values = overlay, held = floors) => {
const floor = sourcedFloor(bound, (w) => { const v = readValue(w, true, values); return v !== "unknown" ? { values: v.map(floorOf), pastBound: false } : readFloor(w, values, held); });
return isEmptyFloor(floor) ? {} : { floor };
};
for (const name of shape.defines)
bind({ name: functionKey(name), state: FUNCTION_DEFINED });
const nameOf = (w) => {
if (w.pieces.some((p) => p.expansion !== undefined || p.literal === undefined))
return "computed";
return nameIn(w.pieces.map((p) => p.literal).join(""));
};
const killNamed = (name) => {
if (name === "computed")
unknownAll();
else if (name !== undefined)
kill(name);
};
const wordsOfSegment = segment.tokens.flatMap((t) => (t.kind === "word" ? [t] : t.kind === "redirect" && t.target !== undefined ? [t.target] : []));
for (const w of wordsOfSegment)
for (const name of assignedByPieces(w.pieces))
kill(name);
for (const t of segment.tokens) {
if (t.kind !== "heredoc" || t.quoted)
continue;
const expansions = expansionsInHeredocBody(t.body);
const evaluatesUnseen = (x) => (x.expansion.kind === "parameter" && expansionHidesRun(x.expansion)) || (x.expansion.kind === "arithmetic" && !arithmeticTextIsPlain(x.expansion.body ?? ""));
if (expansions === undefined || expansions.some((x) => x.unresolved !== undefined || evaluatesUnseen(x)))
unknownAll();
for (const name of assignedByPieces((expansions ?? []).map((x) => ({ span: [0, 0], quotedBy: undefined, expansion: x.expansion }))))
kill(name);
}
segment.tokens.forEach((t, i) => {
if (t.kind === "word" && namesRedirectDescriptor(segment.tokens[i + 1]))
bind({ name: t.raw.slice(1, -1), state: "unknown", prefix: true });
});
const tokens = segment.tokens;
if (isArithmeticCommand(segment)) {
for (const name of arithmeticAssignedNames(argv.map((w) => w.raw).join(" ")))
kill(name);
return { bindings, all };
}
const loopAt = loopListHeadAt(argv);
if (loopAt !== undefined) {
const headWord = argv[loopAt].folded;
if (tokens.some((t) => t.kind === "group"))
unknownAll();
const name = argv[loopAt + 1] !== undefined ? nameOf(argv[loopAt + 1]) : undefined;
if (name === undefined || name === "computed") {
unknownAll();
return { bindings, all };
}
const inAt = argv.findIndex((w, i) => i >= loopAt + 2 && w.raw === "in");
let state = "unknown";
const listWords = inAt === loopAt + 2 && argv.length > loopAt + 3 ? [...new Map(braceWordListsOf(argv.slice(loopAt + 3)).flat().map((x) => [x.raw, x])).values()] : [];
if (ITERATING_HEADS.has(headWord) && listWords.length > 0) {
const values = [];
for (const w of listWords) {
const v = readValue(w, false, overlay);
if (v === "unknown") {
values.length = 0;
break;
}
values.push(...v);
}
if (values.length > 0)
state = values;
}
const splits = listWords.some((w) => w.pieces.some((p) => p.quotedBy === undefined && p.expansion?.kind === "parameter"));
bind({ name, state, loopVar: true, ...(state === "unknown" ? floorFrom({ name, sources: listWords.map(wordSource), cut: (t) => (splits ? [t, ...splitFields(plainChars(t), IFS_DEFAULT).fields] : [t]) }) : {}) });
return { bindings, all };
}
if (argv[0] !== undefined && BACKGROUND_WORDS.has(argv[0].raw) && argv[1] !== undefined)
killNamed(nameOf(argv[1]));
const pos = readProgramPosition(argv);
const program = pos.program;
const row = program === undefined ? undefined : programRow(program.basename);
const statement = assignsAsStatement(pos);
for (const k of pos.assignments) {
const a = argv[k].assignment;
if (a === undefined)
continue;
if (statement) {
const array = literalElementsOf(a);
bind({ name: a.name, ...assignedBinding(a, readValue, readFloor, overlay, floors), ...(array !== undefined ? { array } : {}) });
}
else if (program !== undefined && SPECIAL_BUILTINS.has(program.basename))
bind({ name: a.name, ...assignedBinding(a, readValue, readFloor, overlay, floors), prefix: true });
}
const programWord = program === undefined ? undefined : argv[program.index];
if (programWord !== undefined && nameOf(programWord) === "computed" && !programWord.pieces.some((p) => p.literal?.includes("/") === true)) {
unknownAll();
return { bindings, all, attributes: EVERY_ATTRIBUTE, references: true };
}
if (program === undefined || shadow === "named")
return { bindings, all };
const settled = bindings.length;
const chainIsBuiltin = program.name === program.basename && pos.launchers.every((l, i) => (l.name === "builtin" || l.name === "command") && argv[l.index].folded === l.name && l.index + 1 === (pos.launchers[i + 1]?.index ?? program.index));
const runsAsBuiltin = chainIsBuiltin && !segment.tokens.some((t) => t.kind === "redirect" || t.kind === "heredoc");
const available = runsAsBuiltin ? chainAvailability([...pos.launchers.map((l) => l.name), program.basename], availability) : "enabled";
if (available === "disabled")
return { bindings, all };
const mayNotRun = shadow === "maybe" || available === "maybe" || (!runsAsBuiltin && (row?.builtin === "declaration" || program.basename === ENABLE_BUILTIN));
const finish = (e) => (mayNotRun ? { ...e, bindings: e.bindings.map((b, i) => (i < settled ? b : { ...b, prefix: true })) } : e);
const args = argv.slice(program.index + 1);
if (program.basename === ENABLE_BUILTIN)
return finish({ bindings: [...bindings, ...enableBindings(args)], all });
const ownIfsWord = pos.assignments.map((k) => argv[k].assignment).findLast((a) => a?.name === "IFS");
const ownIfs = ownIfsWord !== undefined;
const ifs = ownIfsWord !== undefined ? (storesValueWord(ownIfsWord) ? literalTextOf(ownIfsWord.value.pieces) : undefined) : splitUnsettled ? undefined : IFS_DEFAULT;
const input = (fd) => (fd === 0 ? fed ?? [] : [...(fd === undefined ? fed ?? [] : []), ...descriptorTextsOf(segment, fd)]);
const sourced = new Map((SOURCED_BINDERS[program.basename]?.(args, input, fedByLoop, ifs) ?? []).map((b) => [b.name, { ...floorFrom(b), ...(b.keeps === true ? { keeps: true } : {}) }]));
const named = new Set();
const bindNamed = (name) => {
const floor = name === undefined || name === "computed" ? undefined : sourced.get(name);
if (floor === undefined)
return killNamed(name);
named.add(name);
bind({ name: name, state: "unknown", ...floor });
};
const bindUnasked = () => {
for (const [name, floor] of sourced)
if (!named.has(name) && floor.floor !== undefined)
bind({ name, state: "unknown", ...floor });
};
if (row === undefined) {
bindUnasked();
return finish({ bindings, all });
}
const folded = args.map((w) => w.folded);
if (row.reentry?.kind === "shell" && (row.reentry.text === "words" || row.reentry.text === "file-operand"))
unknownAll();
for (const body of runsAtExitOnly(argv) ? [] : codeBodies(program.basename, folded)) {
const inner = bindingsIn(body);
if (inner === "all")
unknownAll();
else
for (const [name, floor] of inner)
bind({ name, state: "unknown", prefix: true, ...(!isEmptyFloor(floor) ? { floor } : {}) });
}
if (row.builtin === "declaration") {
scope = args.some((w) => w.folded.startsWith("-") || w.folded.startsWith("+")) ? "unread" : BODY_SCOPED_DECLARATIONS.has(program.basename) ? "local" : undefined;
const assigns = declaredAttributes(row, folded);
const kinds = [...assigns].filter((k) => k !== "reference" && k !== "unsettled");
const storesText = [...assigns].every((k) => k === "frozen");
let references = assigns.has("reference");
const attributes = [];
const expanded = new Map(overlay);
const expandedFloors = new Map(floors);
for (const w of args) {
const a = w.assignment;
const name = a?.name ?? nameOf(w);
if (name === "computed") {
unknownAll();
attributes.push(...EVERY_ATTRIBUTE);
references = true;
continue;
}
if (name === undefined)
continue;
const refused = attributes.some((x) => x.name === undefined || x.name === name);
if (a !== undefined && bindsArrayElement(a))
bind({ name, ...assignedBinding(a, readValue, readFloor, expanded, expandedFloors) });
else if (a === undefined && scope !== "local") {
if (scope !== undefined || !ATTRIBUTE_ONLY.has(program.basename))
bind({ name, state: "unknown", prefix: true });
}
else if (a === undefined)
kill(name);
else if (!storesText || refused)
bind({ name, state: "unknown", keeps: true, ...floorFrom({ name, sources: [wordSource({ pieces: a.value.pieces })], cut: (t) => [t, t.toLowerCase(), t.toUpperCase()] }, expanded, expandedFloors) });
else
bind({ name, ...assignedBinding(a, readValue, readFloor, expanded, expandedFloors) });
attributes.push(...kinds.map((kind) => ({ name, kind })));
}
const inFunction = program.basename === LOCAL_DECLARATION ? { inFunction: true } : {};
if (references) {
unknownAll();
return finish({ bindings, all, attributes, references: true, ...inFunction });
}
return finish({ bindings, all, attributes, ...inFunction });
}
if (program.basename === "unset") {
const { operands, variablesOnly } = unsetOperands(args);
if (!variablesOnly)
for (const w of operands)
if (w.pieces.every((p) => p.literal !== undefined && p.expansion === undefined))
bind({ name: functionKey(w.folded), state: FUNCTION_ABSENT, prefix: true });
}
if (program.basename === "read" && chainIsBuiltin) {
const readAvailable = chainAvailability([...pos.launchers.map((l) => l.name), program.basename], availability);
if (readAvailable === "disabled")
return finish({ bindings, all });
const line = readBuiltinLines(args, fed, fedByLoop);
if (line !== undefined) {
const mayFail = segment.tokens.some((t) => t.kind === "redirect" && t.op !== "<<<");
if (splitUnsettled || ownIfs) {
const floor = [...line.values, ...line.raw].reduce((acc, v) => (acc.some((x) => x.spelled === v.spelled) ? acc : [...acc, { spelled: v.spelled, held: true }]), []);
bind({ name: line.name, state: "unknown", prefix: true, ...(floor.length > 0 ? { floor: { values: floor, pastBound: false } } : {}) });
return finish({ bindings, all });
}
bind({ name: line.name, state: line.values, loopVar: true, ...(mayFail || readAvailable === "maybe" || shadow === "maybe" ? { prefix: true } : {}) });
return finish({ bindings, all });
}
}
if (program.basename === "printf" && chainIsBuiltin) {
const roles = readArgRoles(row, folded);
let name;
let arrayElement = false;
let nameComputed = false;
for (const e of roles) {
const role = e.kind === "value" || e.kind === "operand" ? e.role : e.kind === "option" && typeof e.reading === "object" ? e.reading.role : undefined;
if (role?.kind !== "binds-name")
continue;
if (nameOf(args[e.at]) === "computed") {
nameComputed = true;
break;
}
const text = e.kind === "option" && typeof e.reading === "object" ? e.reading.attached : args[e.at].pieces.map((p) => p.literal).join("");
name = nameIn(text);
arrayElement = text.includes("[");
break;
}
if (nameComputed) {
unknownAll();
return finish({ bindings, all });
}
if (name !== undefined) {
const operands = roles.flatMap((e) => (e.kind === "operand" ? [e] : [])).sort((a, b) => a.ordinal - b.ordinal).map((e) => args[e.at]);
const written = { name, sources: [{ words: operands, made: ([format, ...rest]) => (format === undefined || rest.some((t) => t === undefined) ? undefined : printfBoundValue(format, rest)) }], cut: (t) => [t], ...(operands.slice(1).some((w) => w.pieces.some(joinsValues)) ? { loose: true } : {}) };
const single = (w) => {
if (w === undefined)
return undefined;
const v = readValue(w, true, overlay);
return v !== "unknown" && v.length === 1 ? v[0].spelled : undefined;
};
const formatText = operands.length > 0 ? single(operands[0]) : "";
const argTexts = operands.slice(1).map(single);
const output = !arrayElement && formatText !== undefined && argTexts.every((t) => t !== undefined) ? printfBoundValue(formatText, argTexts) : undefined;
if (name === "HOME")
bind({ name, state: "unknown", ...floorFrom(written) });
else if (output !== undefined)
bind({ name, state: [{ spelled: output }] });
else
bind({ name, state: "unknown", prefix: true, ...floorFrom(written) });
}
return finish({ bindings, all });
}
for (const e of readArgRoles(row, folded)) {
const role = e.kind === "value" || e.kind === "operand" ? e.role : e.kind === "option" && typeof e.reading === "object" ? e.reading.role : undefined;
if (role?.kind === "program-text" && role.language === "arithmetic" && e.kind !== "end-of-options" && e.kind !== "dash-word-operand") {
for (const name of arithmeticAssignedNames(e.kind === "option" && typeof e.reading === "object" ? e.reading.attached : folded[e.at]))
kill(name);
continue;
}
if (role?.kind !== "binds-name")
continue;
if (e.kind === "option" && typeof e.reading === "object") {
bindNamed(nameOf(args[e.at]) === "computed" ? "computed" : nameIn(e.reading.attached));
continue;
}
bindNamed(nameOf(args[e.at]));
}
bindUnasked();
const nameLetters = new Set(row.grammars.flatMap((g) => Object.entries(g.short).flatMap(([letter, s]) => (s.value?.kind === "binds-name" ? [letter] : []))));
if (nameLetters.size > 0 && readArgRoles(row, folded).some((e) => e.kind === "option" && e.reading === "speculative" && [...folded[e.at].slice(1)].some((ch) => nameLetters.has(ch))))
unknownAll();
return finish({ bindings, all });
}
function readBuiltinLines(args, fed, fedByLoop) {
if (fed === undefined || fed.length === 0 || fed.some((t) => t.literal === undefined))
return undefined;
if (args.some((w) => w.expansions.length > 0))
return undefined;
const words = args.map((w) => w.folded).filter((w) => w !== "--");
const options = words.filter((w) => w.startsWith("-") && w !== "-");
if (!options.every((o) => /^-r+$/.test(o)))
return undefined;
const names = words.filter((w) => !w.startsWith("-") || w === "-");
if (names.length !== 1 || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(names[0]) || names[0] === "HOME")
return undefined;
const noBackslashProcessing = options.length === 0;
for (const t of fed)
if (noBackslashProcessing && t.literal.includes("\\"))
return undefined;
const consumed = fed.flatMap((t) => { const records = readRecords(t.literal, "\n", true); return fedByLoop ? records : records.slice(0, 1); });
const uniq = (xs) => [...new Set(xs.length === 0 ? [""] : xs)].map((spelled) => ({ spelled }));
return { name: names[0], values: uniq(consumed.map((r) => nameField(splitFields(r, IFS_DEFAULT), 0, 1))), raw: uniq(consumed.map(textOf)) };
}
function printfBoundValue(format, args) {
if (format.includes("\\") || !/%[sb%]/.test(format.replace(/%%/g, ""))) {
if (format.includes("\\") || /%(?![sb%])/.test(format))
return undefined;
return format.replace(/%%/g, "%");
}
let out = "";
let ai = 0;
let guard = 0;
do {
const before = ai;
for (let i = 0; i < format.length; i++) {
if (format[i] !== "%") {
out += format[i];
continue;
}
const c = format[i + 1];
i++;
if (c === "%") {
out += "%";
continue;
}
if (c === "s" || c === "b") {
const arg = args[ai++] ?? "";
if (c === "b" && arg.includes("\\"))
return undefined;
out += arg;
continue;
}
return undefined;
}
if (ai === before)
return out;
} while (ai < args.length && ++guard < 64);
return ai < args.length ? undefined : out;
}
function nameIn(text) {
return /^([A-Za-z_][A-Za-z0-9_]*)(?:\[.*\])?$/s.exec(text)?.[1];
}
function unsetOperands(args) {
let variables = false;
let otherwise = false;
let at = 0;
for (; at < args.length; at++) {
const w = args[at].folded;
if (w === "--") {
at++;
break;
}
if (!/^-./.test(w))
break;
for (const letter of w.slice(1)) {
if (letter === "v" || letter === "n")
variables = true;
else
otherwise = true;
}
}
return { operands: args.slice(at), variablesOnly: variables && !otherwise };
}
function compoundElementWords(a) {
return (a.elements ?? []).flatMap(({ word, stored }) => {
const folded = /^\[[^\]]*\]\+?=/.exec(word.folded)?.[0];
return [stored.assignment.subscript === undefined ? word : stored.assignment.value, ...(folded !== undefined ? [{ pieces: word.pieces, folded: word.folded.slice(folded.length), tail: true }] : [])];
});
}
export function bindsArrayElement(a) {
return a.form === "compound" || a.subscript !== undefined;
}
function literalElementsOf(a) {
if (a.form !== "compound" || a.op !== "=" || a.subscript !== undefined || a.elements === undefined)
return undefined;
const out = [];
for (const { word } of a.elements) {
if (word.pieces.some((p) => p.expansion !== undefined || p.literal === undefined))
return undefined;
out.push({ spelled: word.pieces.map((p) => p.literal).join("") });
}
return out;
}
export function assignsAsStatement(pos) {
return pos.program === undefined && pos.launchers.length === 0 && pos.refusal === undefined;
}
function arrayElementFloor(a, readValue, readFloor, overlay, floors) {
const words = a.form === "compound" ? compoundElementWords(a) : [{ pieces: a.value.pieces, folded: a.value.folded }];
return joinFloors(...words.map((w) => {
const v = w.tail === true ? "unknown" : readValue(w, true, overlay);
if (v !== "unknown")
return { values: v.map(floorOf), pastBound: false };
const text = w.pieces.some((q) => q.expansion?.kind === "tilde") ? w.folded : literalTildeSpelling(w.folded);
const written = { values: [w.pieces.some((q) => q.expansion?.kind === "glob") ? { spelled: text, glob: true } : { spelled: text }], pastBound: false };
return w.tail === true ? written : joinFloors(readFloor(w, overlay, floors), written);
}));
}
function storesValueWord(a) {
return a.op === "=" && a.subscript === undefined && a.form === "scalar" && a.value.unresolved === undefined;
}
function assignedState(a, readValue, overlay) {
if (!storesValueWord(a))
return "unknown";
return readValue({ pieces: a.value.pieces }, true, overlay);
}
function assignedFloor(a, readFloor, overlay, floors) {
if (!storesValueWord(a))
return undefined;
const floor = readFloor({ pieces: a.value.pieces }, overlay, floors);
return isEmptyFloor(floor) ? undefined : floor;
}
const joinsValues = (p) => p.expansion?.kind === "parameter" && (p.expansion.name === "@" || p.expansion.name === "*" || /^!?[@*]|\[[@*]\]|^![^}]*[@*]$/.test(p.expansion.body ?? ""));
const wordSource = (word) => ({ words: [word], made: ([text]) => text });
const combinations = (lists) => lists.reduce((acc, l) => acc.flatMap((c) => l.map((x) => [...c, x])), [[]]);
export function sourcedFloor(bound, spellingsOf) {
const values = [];
let pastBound = false;
const cut = (text, as, piece) => void values.push(...as(text).map((spelled) => (piece ? { spelled, piece } : { spelled })));
for (const source of bound.sources) {
const words = source.words.map(spellingsOf);
pastBound ||= words.some((w) => w.pastBound);
const count = words.reduce((n, w) => n * w.values.length, 1);
const joins = source.words.some((w) => w.pieces.some(joinsValues));
const made = !joins && count > 0 && count <= WORD_VALUES_MAX ? combinations(words.map((w) => w.values)).map((vs) => ({ text: source.made(vs.map((v) => v.spelled)), piece: vs.some((v) => v.piece === true) })) : [];
for (const t of made)
if (t.text !== undefined)
cut(t.text, bound.cut, t.piece);
if (made.length === 0 || made.some((t) => t.text === undefined) || source.words.some((w) => w.pieces.some(transformsValue))) {
pastBound ||= count > WORD_VALUES_MAX;
for (const w of words)
for (const v of w.values)
cut(v.spelled, bound.piece ?? bound.cut, v.piece === true);
}
}
return { values: distinctSpellings(values), pastBound: pastBound || (bound.loose === true && values.length > 0) };
}
function builtinOptions(args, valued, switches) {
const options = new Map();
const words = new Map();
const set = (letter, value) => {
options.delete(letter);
options.set(letter, value);
};
let settled = true;
let i = 0;
for (; i < args.length; i++) {
const text = literalTextOf(args[i].pieces);
if (text === undefined) {
settled = false;
continue;
}
if (text === "--") {
i++;
break;
}
if (!text.startsWith("-") || text === "-")
break;
for (let j = 1; j < text.length; j++) {
const letter = text[j];
if (valued.includes(letter)) {
const attached = j + 1 < text.length;
const word = attached ? args[i] : args[++i];
const value = attached ? text.slice(j + 1) : word === undefined ? undefined : literalTextOf(word.pieces);
if (value === undefined)
settled = false;
set(letter, value);
if (word !== undefined)
words.set(letter, attached ? { words: [word], made: ([t]) => t?.slice(j + 1) } : wordSource(word));
break;
}
if (!switches.includes(letter))
settled = false;
set(letter, "");
}
}
return { options, words, operands: args.slice(i), settled };
}
const descriptorOf = (value) => (value !== undefined && /^\d+$/.test(value) ? Number(value) : undefined);
const delimiterOf = (options) => (!options.has("d") ? "\n" : options.get("d") === undefined ? undefined : options.get("d").slice(0, 1) || "\0");
const IFS_DEFAULT = " \t\n";
const plainChars = (text) => [...text].map((c) => ({ c, escaped: false }));
function readRecords(text, delimiter, raw) {
const records = [[]];
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (!raw && c === "\\" && i + 1 < text.length) {
if (text[++i] !== "\n")
records.at(-1).push({ c: text[i], escaped: true });
continue;
}
if (c === delimiter)
records.push([]);
else
records.at(-1).push({ c, escaped: false });
}
if (records.length > 1 && records.at(-1).length === 0)
records.pop();
return records;
}
const textOf = (chars) => chars.map((x) => x.c).join("");
function splitFields(record, ifs) {
const white = (x) => x !== undefined && !x.escaped && ifs.includes(x.c) && IFS_DEFAULT.includes(x.c);
const other = (x) => x !== undefined && !x.escaped && ifs.includes(x.c) && !IFS_DEFAULT.includes(x.c);
let start = 0;
let end = record.length;
while (start < end && white(record[start]))
start++;
while (end > start && white(record[end - 1]))
end--;
const fields = [];
const starts = [];
for (let i = start; i < end;) {
let j = i;
while (j < end && !white(record[j]) && !other(record[j]))
j++;
fields.push(textOf(record.slice(i, j)));
starts.push(i);
while (j < end && white(record[j]))
j++;
if (j < end && other(record[j]))
for (j++; j < end && white(record[j]);)
j++;
i = j;
}
return { fields, rest: (k) => (k < starts.length ? textOf(record.slice(starts[k], end)) : "") };
}
const restsOf = (split) => Array.from({ length: Math.min(split.fields.length, WORD_VALUES_MAX + 1) }, (_, k) => split.rest(k));
const nameField = (split, k, count) => (k < count - 1 || split.fields.length - k <= 1 ? split.fields[k] ?? "" : split.rest(k));
function readSources(args, input, byLoop, ifs) {
const { options, operands, settled } = builtinOptions(args, "adinNptu", "Eers");
const operandNames = operands.flatMap((w) => { const name = nameIn(literalTextOf(w.pieces) ?? ""); return name === undefined ? [] : [name]; });
const elements = new Set(operands.flatMap((w) => { const text = literalTextOf(w.pieces) ?? ""; const name = nameIn(text); return name !== undefined && name !== text ? [name] : []; }));
const array = options.has("a") ? nameIn(options.get("a") ?? "") : undefined;
const names = options.has("a") ? [] : operandNames.length > 0 ? operandNames : ["REPLY"];
const bound = [...names, ...(array !== undefined ? [array] : [])];
const counter = [...options.keys()].filter((k) => k === "n" || k === "N").at(-1);
const count = counter !== undefined && /^\d+$/.test(options.get(counter) ?? "") ? Number(options.get(counter)) : undefined;
const delimiter = counter === "N" ? undefined : delimiterOf(options);
const exact = settled && ifs !== undefined && (delimiter !== undefined || counter === "N");
const readsNothing = /^(0+(\.0*)?|\.0+)$/.test(options.get("t") ?? "");
const chunks = (record) => (count === undefined || count === 0 ? [record] : Array.from({ length: byLoop ? Math.max(1, Math.ceil(record.length / count)) : 1 }, (_, k) => record.slice(k * count, (k + 1) * count)));
const cuts = (text) => {
const out = new Map();
if (readsNothing)
return out;
const add = (name, ...xs) => {
out.set(name, [...(out.get(name) ?? []), ...xs]);
};
const records = readRecords(text, delimiter, options.has("r"));
for (const record of (byLoop ? records : records.slice(0, 1)).flatMap(chunks)) {
if (counter === "N") {
add(bound[0], textOf(record));
continue;
}
if (!exact) {
const split = splitFields(record, IFS_DEFAULT);
for (const name of bound)
add(name, textOf(record), ...split.fields, ...restsOf(split));
continue;
}
const split = splitFields(record, ifs);
if (array !== undefined)
add(array, ...split.fields);
const held = new Map(names.map((name, k) => [name, operandNames.length === 0 ? textOf(record) : nameField(split, k, names.length)]));
for (const [name, value] of held)
add(name, value);
}
return out;
};
const piece = (text) => (readsNothing ? [] : readRecords(text, delimiter, options.has("r")).flatMap((r) => { const split = splitFields(r, ifs ?? IFS_DEFAULT); return [textOf(r), ...split.fields, ...restsOf(split)]; }));
const sources = sourcesOf(input(options.has("u") ? descriptorOf(options.get("u")) : 0));
const loose = !exact && counter !== "N" && (bound.length > 1 || array !== undefined) ? { loose: true } : {};
return bound.map((name) => ({ name, sources, cut: (text) => cuts(text).get(name) ?? [], piece, ...loose, ...(elements.has(name) ? { keeps: true } : {}) }));
}
function lineSources(args, input) {
const { options, operands } = builtinOptions(args, "dnOsuCc", "t");
const name = operands.length === 0 ? "MAPFILE" : nameIn(literalTextOf(operands[0].pieces) ?? "");
if (name === undefined)
return [];
const delimiter = delimiterOf(options);
const countOf = (letter) => (/^\d+$/.test(options.get(letter) ?? "") ? Number(options.get(letter)) : undefined);
const skip = countOf("s") ?? 0;
const keep = countOf("n") || Number.POSITIVE_INFINITY;
const records = (text, from, count) => readRecords(text, delimiter ?? "\n", true).slice(from, from + count).flatMap((r) => (options.has("t") || delimiter === undefined ? [textOf(r)] : [textOf(r), `${textOf(r)}${delimiter}`]));
const piece = (text) => records(text, 0, Number.POSITIVE_INFINITY);
return [{ name, sources: sourcesOf(input(options.has("u") ? descriptorOf(options.get("u")) : 0)), cut: (text) => records(text, skip, keep), piece, keeps: true }];
}
const sourcesOf = (texts) => texts.flatMap((t) => (t.source !== undefined ? [t.source] : t.literal !== undefined ? [{ words: [], made: () => t.literal }] : []));
function getoptsSources(operands) {
const [optstring, nameWord, ...rest] = operands;
const name = nameWord === undefined ? undefined : nameIn(literalTextOf(nameWord.pieces) ?? "");
if (optstring === undefined)
return [];
const values = (joined) => {
const [spec = "", ...args] = joined.split("\0");
const takes = new Set([...spec.replace(/^:/, "").matchAll(/(\w)(?=:)/g)].map((m) => m[1]));
return args.flatMap((arg, k) => {
if (!/^-[^-]/.test(arg))
return [];
const at = [...arg.slice(1)].findIndex((c) => takes.has(c));
return at < 0 ? [] : at + 2 < arg.length ? [arg.slice(at + 2)] : args[k + 1] !== undefined ? [args[k + 1]] : [];
});
};
const suffixes = (t) => [t, ...(t.startsWith("-") ? Array.from({ length: Math.max(0, t.length - 2) }, (_, k) => t.slice(k + 2)) : [])];
const words = { words: [optstring, ...rest], made: (texts) => (texts.some((t) => t === undefined) ? undefined : texts.join("\0")) };
return [
{ name: "OPTARG", sources: rest.length > 0 ? [words] : [], cut: values, piece: suffixes },
...(name !== undefined ? [{ name, sources: [wordSource(optstring)], cut: (t) => [...t.replace(/:/g, ""), "?"] }] : []),
];
}
function aliasSources(args) {
const values = args.filter((w) => !/^-/.test(literalTextOf(w.pieces) ?? "")).map((w) => ({ words: [w], made: ([t]) => (t?.includes("=") === true ? t.slice(t.indexOf("=") + 1) : undefined) }));
return values.length === 0 ? [] : [{ name: "BASH_ALIASES", sources: values, cut: (t) => [t], keeps: true }];
}
function hashSources(args) {
const path = builtinOptions(args, "p", "rdlt").words.get("p");
return path === undefined ? [] : [{ name: "BASH_CMDS", sources: [path], cut: (t) => [t], keeps: true }];
}
function compgenSources(args, ifs) {
const { options, words } = builtinOptions(args, "oAGWPSXVFC", "abcdefgjksuv");
const name = nameIn(options.get("V") ?? "");
if (name === undefined)
return [];
const listed = words.get("W");
const loose = ifs === undefined || options.has("P") || options.has("S") ? { loose: true } : {};
return [{ name, sources: listed !== undefined ? [listed] : [], cut: (t) => splitFields(plainChars(t), ifs ?? IFS_DEFAULT).fields, ...loose, keeps: true }];
}
const SOURCED_BINDERS = {
read: readSources, mapfile: lineSources, readarray: lineSources, getopts: getoptsSources, alias: aliasSources, hash: hashSources,
compgen: (args, _input, _byLoop, ifs) => compgenSources(args, ifs),
};
function assignedBinding(a, readValue, readFloor, overlay, floors) {
if (bindsArrayElement(a))
return { state: "unknown", floor: arrayElementFloor(a, readValue, readFloor, overlay, floors), ...(a.subscript !== undefined || a.op === "+=" ? { keeps: true } : {}) };
const state = assignedState(a, readValue, overlay);
const floor = state === "unknown" ? assignedFloor(a, readFloor, overlay, floors) : undefined;
return { state, ...(floor !== undefined ? { floor } : {}) };
}
export function assignedByPieces(pieces) {
const out = [];
for (const p of pieces) {
const e = p.expansion;
if (e?.kind === "parameter" && e.name !== undefined && e.body !== undefined && (e.body.startsWith(`${e.name}=`) || e.body.startsWith(`${e.name}:=`)))
out.push(e.name);
if (e?.kind === "parameter" && e.body !== undefined)
out.push(...arithmeticAssignedNames(e.body));
if (e?.kind === "arithmetic" && e.body !== undefined)
out.push(...arithmeticAssignedNames(e.body));
}
return out;
}
export function arithmeticAssignedNames(text) {
const assigns = /(?:^|[^=!<>])=(?!=)|\+\+|--/.test(text);
return assigns ? [...new Set(text.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? [])] : [];
}
export function namesBoundIn(text) {
const bound = bindingsIn(text);
return bound === "all" ? "all" : new Set(bound.keys());
}
export function bindingsIn(text) {
const lexed = lexShell(SHELL_LEX_DIALECT, text);
if ("parseFailure" in lexed)
return "all";
const bound = [];
const literal = (w, quoted, overlay) => valueOf(w, undefined, quoted, overlay);
const projected = projectSegments(lexed.segments);
for (const [si, segment] of lexed.segments.entries()) {
const p = projected[si];
const effect = bindingEffectOf(segment, p.argv, p, literal);
if (effect.all === "unknown")
return "all";
bound.push(...effect.bindings);
}
return bindingFloors(bound);
}
export function textBindsHome(text) {
const names = namesBoundIn(text);
return names === "all" || names.has("HOME");
}
const NOTHING_INHERITED = { attributes: [], references: false };
const NO_FLOORS = new Map();
class FloorsByName {
names;
read;
constructor(names, read) {
this.names = names;
this.read = read;
}
get(name) {
const floor = this.read(name);
return isEmptyFloor(floor) ? undefined : floor;
}
has(name) {
return this.get(name) !== undefined;
}
get size() {
return this.all().size;
}
entries() {
return this.all().entries();
}
keys() {
return this.all().keys();
}
values() {
return this.all().values();
}
forEach(each, thisArg) {
for (const [name, floor] of this.all())
each.call(thisArg, floor, name, this);
}
[Symbol.iterator]() {
return this.all()[Symbol.iterator]();
}
all() {
const out = new Map();
for (const name of this.names()) {
if (out.has(name))
continue;
const floor = this.get(name);
if (floor !== undefined)
out.set(name, floor);
}
return out;
}
}
export function joinedFloors(...sets) {
return new FloorsByName(() => sets.flatMap((s) => [...(s?.keys() ?? [])]), (name) => joinFloors(...sets.map((s) => s?.get(name) ?? NO_FLOOR)));
}
export function joinRebound(a, b) {
if (a === "all" || b === "all")
return "all";
return new Set([...(a ?? []), ...(b ?? [])]);
}
export class BindingThread {
segments;
named;
initial;
boundAnywhere;
loops;
homeStartsTouched;
inheritedFunctions;
entries = [];
localDeclarations = [];
attributesAt;
unreadable;
blocks;
ownSubshell;
startFloors;
startRebound;
bodyRuns = { limit: -1, environment: [], points: [] };
bodiesTold = false;
trailing = new Map();
constructor(segments, named, initial, boundAnywhere, loops, homeStartsTouched = false, inherited = NOTHING_INHERITED, inheritedFunctions) {
this.segments = segments;
this.named = named;
this.initial = initial;
this.boundAnywhere = boundAnywhere;
this.loops = loops;
this.homeStartsTouched = homeStartsTouched;
this.inheritedFunctions = inheritedFunctions;
this.startFloors = inherited.floors ?? NO_FLOORS;
this.startRebound = inherited.rebound ?? new Set();
this.blocks = blockStructure(segments);
const startOf = (s) => (s === 0 ? 0 : this.blocks[s - 1].after);
this.blocks.forEach((b, k) => {
if (b.trailingTo === undefined)
return;
let h = k;
while (h > 0 && startOf(h) > b.trailingTo)
h--;
this.trailing.set(k, h);
});
this.ownSubshell = segments.map((_, i) => segments[i + 1]?.connector === "|" || segments[i + 1]?.connector === "&");
this.unreadable = [...(inherited.references ? [{ at: -1 }] : []), ...named.flatMap((effect, at) => this.unreadableBy(effect, at))];
this.attributesAt = [...inherited.attributes.map((a) => ({ ...a, at: -1 })), ...named.flatMap((effect, at) => (effect.attributes ?? []).map((a) => ({ ...a, at })))];
}
inheritedAt(j) {
const holds = (at) => j === undefined || this.mayRunBefore(at, j);
const reaches = (e) => j === undefined || ((this.mayRunBefore(e.at, j) || (e.at === j && e.opens === true)) && this.visible(e, j));
const own = new Map();
for (const e of this.entries)
if (e.name !== undefined && e.floor !== undefined && (j === undefined || (e.at < j && this.inShellOf(e, j))))
own.set(e.name, joinFloors(own.get(e.name) ?? NO_FLOOR, e.floor));
let rebound = this.startRebound;
for (const e of this.entries)
if (e.state !== "reset" && reaches(e))
rebound = joinRebound(rebound, e.name === undefined ? "all" : [e.name]);
for (const u of this.unreadable)
if (j === undefined || this.lostAt(u, j))
rebound = joinRebound(rebound, u.name === undefined ? "all" : [u.name]);
rebound = joinRebound(rebound, this.boundLater(j));
return {
attributes: this.attributesAt.filter((x) => holds(x.at)).map(({ name, kind }) => (name !== undefined ? { name, kind } : { kind })),
references: this.unreadable.some((u) => u.name === undefined && u.body === undefined && holds(u.at)),
...(own.size > 0 || this.startFloors !== NO_FLOORS ? { floors: own.size === 0 ? this.startFloors : joinedFloors(this.startFloors, own) } : {}),
rebound,
};
}
startOf(name) {
return isFunctionKey(name) ? this.inheritedFunctions?.start(name) ?? FUNCTION_ABSENT : isBuiltinKey(name) ? this.inheritedFunctions?.start(name) ?? BUILTIN_ENABLED : this.initial(name);
}
bindsInText(name) {
return this.named.some((effect) => effect.all === "unknown" || effect.bindings.some((b) => speaksFor(b.name, name)));
}
heldAnywhere() {
const start = (key) => {
const own = this.startOf(key);
if (own === "unknown")
return own;
const values = [...own];
for (const effect of this.named) {
if (effect.all === "unknown")
return "unknown";
for (const b of effect.bindings) {
if (!speaksFor(b.name, key))
continue;
if (b.state === "unknown")
return "unknown";
for (const v of b.state)
if (!values.some((x) => sameValue(x, v)))
values.push(v);
}
}
return values;
};
return { start, bound: new Set() };
}
runsBodies(runs, atEnd, environment) {
let limit = atEnd ? this.named.length - 1 : -1;
runs.forEach((r, si) => {
if (!r)
return;
limit = Math.max(limit, si);
for (const [head, end] of this.loops)
if (head <= si && si < end)
limit = Math.max(limit, end);
});
this.bodyRuns = { limit, environment, points: runs.flatMap((r, si) => (r ? [si] : [])) };
this.bodiesTold = true;
const calling = new Set(runs.flatMap((r, si) => (r && this.blocks[si].body !== undefined ? [this.blocks[si].body.id] : [])));
this.named.forEach((effect, at) => {
for (const b of effect.bindings) {
const body = this.standingOf(at, b.name).body;
if (body !== undefined && calling.has(body.id))
this.unreadable.push({ at, name: b.name, body });
}
});
}
boundLater(j) {
const out = new Set();
if (j !== undefined && this.blocks[j].body === undefined)
return out;
const limit = j === undefined ? this.named.length - 1 : this.bodyRuns.limit;
for (let s = j === undefined ? 0 : j + 1; s <= limit; s++) {
const effect = this.named[s];
if (effect.all === "unknown" || effect.references === true)
return "all";
for (const b of effect.bindings)
out.add(b.name);
const environment = this.bodyRuns.environment[s];
if (environment === "all")
return "all";
for (const name of environment ?? [])
out.add(name);
}
return out;
}
callEnvironmentValues(c, name, there) {
const environment = this.bodyRuns.environment[c];
if (environment === undefined || environment === "all" || !environment.has(name))
return undefined;
const argv = argvOf(this.segments[c]);
const words = argv.slice(0, readProgramPosition(argv).program?.index ?? argv.length);
const a = words.findLast((w) => w.assignment?.bare === true && w.assignment.name === name)?.assignment;
return a === undefined ? undefined : assignedFloor(a, floorReaderOf(there), new Map(), new Map());
}
ownSubshellAt(at, standing) {
return this.ownSubshell[at] === true && standing.depth >= this.blocks[at].after;
}
detachedAt(at, standing) {
return this.segments[at].connector === "|" || this.ownSubshellAt(at, standing);
}
visible(e, j) {
const reader = j === undefined ? undefined : this.blocks[j];
if (e.standing.body !== undefined && reader?.body?.id !== e.standing.body.id)
return false;
return this.inShellOf(e, j);
}
inShellOf(e, j) {
if (j !== e.at && this.ownSubshellAt(e.at, e.standing))
return false;
const around = j === undefined ? [] : this.blocks[j].subshells;
return e.standing.subshells.every((id) => around.includes(id));
}
standingOf(at, name) {
const own = this.blocks[at];
const head = name !== undefined && isFunctionKey(name) ? own.defs.find((d) => functionKey(d.name) === name) : undefined;
return head?.standing ?? { ...(own.body !== undefined ? { body: own.body } : {}), subshells: own.subshells, depth: own.words };
}
functionBound() {
const bound = this.functionBindings();
return bound === "all" ? "all" : new Set(bound.keys());
}
functionBindings() {
if (this.inheritedFunctions?.bound === "all")
return "all";
const out = new Map();
const add = (name, floor) => { out.set(name, joinFloors(out.get(name) ?? NO_FLOOR, floor)); };
for (const name of this.inheritedFunctions?.bound ?? [])
add(name, NO_FLOOR);
for (let at = 0; at < this.named.length; at++) {
const effect = this.named[at];
if (this.blocks[at].body !== undefined && (effect.all === "unknown" || effect.references === true))
return "all";
for (const b of effect.bindings) {
const own = this.bodyBinding(b, at);
if (own !== undefined && (b.scope === "unread" || !this.declaredLocal(b.name, at, own)))
add(b.name, bindingValues(b));
}
}
return out;
}
bodyBinding(b, at) {
const own = this.standingOf(at, b.name).body;
return own !== undefined && b.scope !== "local" ? own : undefined;
}
reaches(at, j) {
if (j !== undefined && !this.blocks[j].placed)
return true;
const s = this.standingOf(at);
const reader = j === undefined ? undefined : this.blocks[j];
if (s.body !== undefined && !(reader?.within ?? []).includes(s.body.id))
return false;
return this.inShellOf({ at, standing: s }, j);
}
closesWithRedirections(k) {
return this.trailing.has(k);
}
openCompoundsAt(h) {
for (const [k, opened] of this.trailing) {
if (opened !== h)
continue;
const closing = this.named[k];
this.kill(h, closing.all === "unknown" ? "all" : closing.bindings.map((b) => b.name), bindingFloors(closing.bindings), true);
}
}
inFunctionBody(at) {
return this.blocks[at].body !== undefined;
}
bodyOf(at) {
return this.blocks[at].body?.id;
}
runsApart(at) {
return this.blocks[at].subshells.length > 0 || this.ownSubshell[at] === true || this.blocks[at].body !== undefined;
}
runsLater(at, names) {
if (names === "all")
this.unreadable.push({ at });
else
for (const name of names)
this.unreadable.push({ at, name });
}
unreadableBy(effect, at) {
const body = this.blocks[at].body;
const out = [];
for (const b of effect.bindings) {
const own = this.bodyBinding(b, at);
if (own !== undefined)
out.push({ at, name: b.name, body: own });
}
if (body !== undefined && effect.all === "unknown")
out.push({ at, body });
if (effect.references === true)
out.push({ at });
return out;
}
mayRunBefore(x, e) {
if (x < e)
return true;
const opened = this.trailing.get(x);
if (opened !== undefined && opened <= e && e < x)
return true;
return this.blocks[e].body !== undefined || [...this.loops].some(([head, end]) => head <= e && e < end && x <= end);
}
segmentPrecedes(x, e, name) {
const reader = this.blocks[e];
if (reader.body !== undefined)
return true;
const here = (at) => this.mayRunBefore(at, e) && this.inShellOf({ at, standing: this.standingOf(at, at === x ? name : undefined) }, e);
const body = this.standingOf(x, name).body;
if (body === undefined)
return here(x);
return !this.bodiesTold || this.bodyRuns.points.some((c) => c !== x && (this.blocks[c].body !== undefined || here(c)));
}
segmentCertainlyBefore(x, e) {
const standing = this.standingOf(x);
if (x >= e || standing.body !== undefined || !this.segmentPrecedes(x, e) || this.detachedAt(x, standing) || !this.heldThrough({ at: x, standing }, e))
return false;
const joint = (k) => this.segments[k].connector;
if (joint(x) !== "&&" && joint(x) !== "||")
return true;
for (let k = x; k <= e; k++)
if (joint(k) !== "&&")
return false;
return true;
}
binders;
bindsBefore(name, e) {
if (this.binders === undefined) {
const all = [], names = new Map();
this.named.forEach((x, at) => {
if (x.all === "unknown")
all.push(at);
for (const b of x.bindings) {
const at_ = names.get(b.name);
if (at_ === undefined)
names.set(b.name, [at]);
else if (at_[at_.length - 1] !== at)
at_.push(at);
}
});
this.binders = { all, names };
}
const reader = this.blocks[e];
const precedes = (x) => this.segmentPrecedes(x, e, name);
if (reader.body !== undefined) {
const own = reader.body.id;
const callsWithin = !this.bodiesTold || this.bodyRuns.points.some((c) => this.blocks[c].within.includes(own));
const laterLocal = (x, b) => x > e && b.scope === "local" && !callsWithin && this.standingOf(x, name).body?.id === own;
return this.binders.all.length > 0 || (this.binders.names.get(name) ?? []).some((x) => this.named[x].bindings.some((b) => b.name === name && !laterLocal(x, b)));
}
return this.binders.all.some(precedes) || (this.binders.names.get(name) ?? []).some(precedes);
}
declaredLocal(name, at, body) {
return this.localDeclarations.some((d) => d.body === body.id && d.name === name && d.at < at && this.heldThrough(d, at));
}
heldThrough(e, j) {
const depth = e.standing.depth;
if (this.blocks[e.at].after < depth)
return false;
for (let k = e.at + 1; k <= j; k++)
if (this.blocks[k].lowest < depth || this.blocks[k].switches.includes(depth))
return false;
return true;
}
apply(at, effect, andRun, loopEnd, spliced = false) {
const body = this.blocks[at].body;
const refused = effect.inFunction === true && body === undefined;
if (effect.all !== undefined)
this.entries.push({ at, standing: this.standingOf(at), state: effect.all === "reset" ? "reset" : "unknown", detached: spliced || effect.all === "unknown", andRun: false });
for (const b of effect.bindings) {
const standing = this.standingOf(at, b.name);
const detached = this.detachedAt(at, standing) || b.prefix === true || b.keeps === true || spliced;
this.entries.push({
at, standing, name: b.name, state: refused ? "unknown" : b.state, detached, andRun,
...(b.loopVar === true && loopEnd !== undefined ? { certainUntil: loopEnd } : {}),
...(b.floor !== undefined && !isEmptyFloor(b.floor) ? { floor: b.floor } : {}),
...(b.array !== undefined && !refused ? { array: b.array } : {}),
});
if (b.scope === "local" && body !== undefined && !refused && !detached && !andRun)
this.localDeclarations.push({ at, name: b.name, body: body.id, standing });
}
}
lostAt(u, j) {
if (u.body === undefined)
return this.mayRunBefore(u.at, j);
const readerBody = this.blocks[j].body;
return readerBody !== undefined && readerBody.id !== u.body.id;
}
kill(at, names, carried = new Map(), opens = false) {
const standing = this.standingOf(at);
const own = opens ? { opens: true } : {};
const entry = (name) => {
const floor = carried.get(name) ?? NO_FLOOR;
return { at, standing, name, state: "unknown", detached: true, andRun: false, ...own, ...(!isEmptyFloor(floor) ? { floor } : {}) };
};
if (names !== "all") {
for (const name of names)
this.entries.push(entry(name));
return;
}
this.entries.push({ at, standing, state: "unknown", detached: true, andRun: false, ...own });
for (const name of carried.keys())
this.entries.push(entry(name));
}
tableAt(j, andRunStart, where, asked, whereAtCalls = false) {
const certain = (e) => {
if (e.certainUntil !== undefined && j < e.certainUntil)
return true;
if (e.detached || !this.heldThrough(e, j))
return false;
return !e.andRun || e.at >= andRunStart;
};
const readerBody = this.blocks[j].body;
const lost = (u) => this.lostAt(u, j);
const before = (e) => (e.at < j || (e.at === j && (e.state === "reset" || e.opens === true))) && this.visible(e, j);
const given = (name, at, kind) => this.attributesAt.some((x) => (x.name === undefined || x.name === name) && (kind === undefined || x.kind === kind) && x.at !== at && this.mayRunBefore(x.at, at));
const opensReaderBody = (e) => readerBody !== undefined && e.at === this.blocks.findIndex((b) => b.body?.id === readerBody.id);
const walk = (name, start) => {
const values = [];
const add = (vs) => { for (const v of vs)
if (!values.some((x) => sameValue(x, v)))
values.push(v); };
let unspelled = false;
for (let i = this.entries.length - 1; i >= 0; i--) {
const e = this.entries[i];
if (!before(e) || (e.name !== undefined && !speaksFor(e.name, name)))
continue;
if (e.state === "reset" && isBuiltinKey(name))
continue;
if (e.state === "reset" && isWorkingDirectoryName(name))
break;
const state = e.state === "reset" ? ((name === "HOME" && this.boundAnywhere("HOME")) || this.bindsInText(name) ? "unknown" : this.initial(name)) : e.state;
if (state === "unknown") {
const refusedByFrozen = e.name !== undefined && given(e.name, e.at, "frozen");
if (certain(e) && !refusedByFrozen)
return { state: "unknown", values, ...(e.state === "reset" && opensReaderBody(e) ? { entered: true } : {}) };
unspelled = true;
continue;
}
add(state);
if (e.name !== undefined && given(e.name, e.at)) {
if (!given(e.name, e.at, "frozen"))
return { state: "unknown", values };
unspelled = true;
continue;
}
if (certain(e))
return unspelled ? { state: "unknown", values } : { state: values, decided: e, values };
}
if (start !== "unknown")
add(start);
if (start === "unknown" || unspelled)
return { state: "unknown", values };
return { state: values, values };
};
const later = this.boundLater(j);
const boundLater = (name) => later === "all" || later.has(name) || (isBuiltinKey(name) && later.has(BUILTINS_ALL));
const atCalls = (name, calls) => {
if (readerBody === undefined)
return NO_FLOOR;
const read = calls.get(name) ?? new Set();
calls.set(name, read);
return joinFloors(...this.bodyRuns.points.filter((c) => this.mayRunBefore(j, c)).map((c) => {
if (read.has(c))
return NO_FLOOR;
read.add(c);
const there = this.tableAt(c, c, undefined, calls);
const set = this.callEnvironmentValues(c, name, there);
if (set !== undefined)
return set;
const floor = there.floorOf(name);
const held = there.stateOf(name);
return joinFloors({ values: held === "unknown" ? [] : held.map(floorOf), pastBound: false }, floor);
}));
};
const unsettledName = (name) => shellKeepsName(name) || this.unreadable.some((u) => speaksFor(u.name, name) && lost(u));
const readName = (name) => {
const unknown = (values = []) => ({ state: "unknown", floor: { values: values.map((v) => ({ ...floorOf(v), held: true })), pastBound: false } });
const entry = /^DIRSTACK\[(\d+)\]$/.exec(name);
if (name === DIRECTORY_STACK_NAME || entry !== null) {
const stack = readerBody === undefined || whereAtCalls ? where?.floor?.DIRSTACK ?? [] : [];
const spellings = entry !== null ? stack[Number(entry[1])] ?? [] : [...new Set(stack.flat())];
return unknown([...walk(DIRECTORY_STACK_NAME, this.startOf(DIRECTORY_STACK_NAME)).values, ...spellings.map((spelled) => ({ spelled }))]);
}
if (!isWorkingDirectoryName(name)) {
const walked = walk(name, this.startOf(name));
const own = walked.decided !== undefined && walked.decided.state !== "reset" && readerBody !== undefined && walked.decided.standing.body?.id === readerBody.id;
if (unsettledName(name) || (boundLater(name) && !own) || walked.entered === true)
return { state: "unknown", get floor() { return joinFloors(unknown(walked.values).floor, atCalls(name, asked ?? new Map())); } };
return walked.state === "unknown" ? unknown(walked.values) : { state: walked.state, floor: NO_FLOOR };
}
const assigned = walk(name, []);
const onThread = readerBody === undefined || (whereAtCalls && assigned.values.length === 0);
const lostAt = onThread ? (where?.floor?.[name] ?? []).map((spelled) => ({ spelled })) : [];
const mayHold = [...assigned.values, ...lostAt.filter((v) => !assigned.values.some((x) => sameValue(x, v)))];
if (unsettledName(name) || boundLater(name))
return unknown(mayHold);
if (assigned.decided !== undefined && where !== undefined && readerBody === undefined && assigned.decided.at > where.movedAt)
return { state: assigned.state, floor: NO_FLOOR };
const thread = onThread ? where?.[name] ?? "unknown" : "unknown";
if (thread === "unknown" || assigned.state === "unknown")
return unknown(mayHold);
const held = assigned.state;
return { state: [...held, ...thread.filter((v) => !held.some((x) => sameValue(x, v)))], floor: NO_FLOOR };
};
const stateOf = (name) => readName(name).state;
const arrayOf = (name) => {
if (unsettledName(name) || isWorkingDirectoryName(name))
return undefined;
for (let i = this.entries.length - 1; i >= 0; i--) {
const e = this.entries[i];
if (!before(e) || (e.name !== undefined && !speaksFor(e.name, name)))
continue;
return e.array !== undefined && e.state !== "reset" && certain(e) && !given(name, e.at) ? e.array : undefined;
}
return undefined;
};
const touched = (name) => this.entries.some((e) => before(e) && (e.name === undefined || e.name === name));
let rebound = this.startRebound;
for (const e of this.entries)
if (e.state !== "reset" && (readerBody !== undefined ? e.at !== j : before(e)))
rebound = joinRebound(rebound, e.name === undefined ? "all" : [e.name]);
for (const u of this.unreadable)
if (lost(u))
rebound = joinRebound(rebound, u.name === undefined ? "all" : [u.name]);
const settled = joinRebound(rebound, later);
const floorsRead = new Map();
const floorsOf = (name) => {
const seen = floorsRead.get(name);
if (seen !== undefined && seen.entries === this.entries.length)
return seen.floor;
const named = /^DIRSTACK\[\d+\]$/.test(name) ? DIRECTORY_STACK_NAME : name;
const own = this.entries.filter((e) => (e.at < j || (e.at === j && e.opens === true)) && e.name === named && this.inShellOf(e, j)).map((e) => e.floor ?? NO_FLOOR);
const floor = joinFloors(...own, readName(name).floor, this.startFloors.get(name) ?? NO_FLOOR);
floorsRead.set(name, { entries: this.entries.length, floor });
return floor;
};
let started;
const nestedStart = () => {
if (started !== undefined && started.entries === this.entries.length)
return started.start;
const start = this.inheritedAt(j);
const handed = readerBody === undefined ? [] : this.bodyRuns.points.flatMap((c) => { const environment = this.bodyRuns.environment[c]; return environment === undefined || environment === "all" ? [] : [...environment]; });
const names = new Set([...this.entries.flatMap((e) => (e.name !== undefined && (before(e) || readerBody !== undefined) && !isFunctionKey(e.name) && !isBuiltinKey(e.name) ? [e.name] : [])), ...handed]);
const read = new Map();
const readFloor = (name) => {
if (!names.has(name))
return NO_FLOOR;
const seen = read.get(name);
if (seen !== undefined)
return seen;
const floor = readName(name).floor;
read.set(name, floor);
return floor;
};
const asked = new FloorsByName(() => names, readFloor);
started = { entries: this.entries.length, start: names.size > 0 ? { ...start, floors: joinedFloors(start.floors, asked) } : start };
return started.start;
};
return {
stateOf,
arrayOf,
isInteger: (name) => SHELL_INTEGER_VARIABLES.has(name) || given(name, j, "integer"),
hasAttribute: (name, kind) => given(name, j, kind),
ifsTouched: touched("IFS") || boundLater("IFS"),
homeTouched: this.homeStartsTouched || touched("HOME") || boundLater("HOME"),
floorOf: floorsOf,
get inherited() {
return nestedStart();
},
rebound: settled,
providedByShell: (name) => settled !== "all" && !settled.has(name),
functionState: (name) => {
const held = stateOf(functionKey(name));
if (held === "unknown")
return "maybe";
return !held.some(isDefinedValue) ? "absent" : held.length > 1 ? "maybe" : "defined";
},
builtinState: (name) => {
const held = stateOf(builtinKey(name));
if (held === "unknown")
return "maybe";
return held.every(isDisabledValue) ? "disabled" : held.some(isDisabledValue) ? "maybe" : "enabled";
},
};
}
}
export function isArithmeticCommand(segment) {
const [a, b] = segment.tokens;
return a?.kind === "group" && a.op === "(" && b?.kind === "group" && b.op === "(";
}
export const ARITHMETIC_TEST_OPERATORS = new Set(["-eq", "-ne", "-lt", "-le", "-gt", "-ge"]);
export function parameterBodySubstitutions(body, table) {
const { subscript, offset } = parameterArithmeticTexts(body);
const out = arithmeticSubstitutions(subscript === undefined ? "" : `[${subscript}]`, table);
if (offset !== undefined)
out.push(...substitutionBodies(offset, true), ...arithmeticSubstitutions(offset, table));
return [...new Set(out)];
}
export function arithmeticSubstitutions(text, table, chain = new Set(), budget = { left: ARITHMETIC_VALUES_MAX }) {
if (--budget.left < 0)
return [text];
const out = [];
for (const subscript of subscriptsOf(text))
out.push(...substitutionBodies(subscript));
if (table !== undefined) {
for (const name of new Set(text.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? [])) {
if (chain.has(name))
continue;
const state = table.stateOf(name);
const floor = state === "unknown" ? table.floorOf(name) : { values: state, pastBound: false };
if (floor.pastBound)
out.push(text);
for (const v of floor.values)
out.push(...arithmeticSubstitutions(v.spelled, table, new Set([...chain, name]), budget));
}
}
return [...new Set(out)];
}
const ARITHMETIC_VALUES_MAX = 256;
export function subscriptsOf(text) {
const out = [];
for (let i = 0; i < text.length; i++) {
if (text[i] !== "[")
continue;
let depth = 0;
let j = i;
for (; j < text.length; j++) {
if (text[j] === "[")
depth++;
else if (text[j] === "]" && --depth === 0)
break;
}
out.push(text.slice(i + 1, j));
i = j;
}
return out;
}
export function substitutionBodies(subscript, keepQuotes = false) {
if (!/\$\(|`|[<>]\(/.test(subscript))
return [];
const unquoted = keepQuotes ? subscript : subscript.replace(/["']/g, "");
const lexed = lexShell(SHELL_LEX_DIALECT, unquoted);
if ("parseFailure" in lexed)
return [unquoted];
const bodies = lexed.segments.flatMap((s) => s.substitutions);
return bodies.length > 0 ? bodies : [unquoted];
}