@sema-agent/core
Version:
Stateless, task-oriented AI agent core
949 lines • 61.3 kB
JavaScript
import { assignedWords, expansionsInHeredocBody, descriptorNameWords, connectorReaching, lexShell, PARSE_FAILURE_SENTENCE, segmentsAroundStop, substitutionsInHeredocBody, literalTextOf, literalTildeSpelling, parameterOperandLines, parameterRereadsValue, UNRESOLVED_SENTENCE, } from "../../shell/lex.js";
import { programTextOf, readOfText, readsOf, rewritten, segmentReadingsOf, settledFieldsOf, spelledWithHome, unreadableSentenceOf } from "./shell-read-word.js";
import { braceWordListsOf } from "./shell-read-brace.js";
import { assignmentArithmetic, bare, listedVerbCandidates, pathSubcommandOf, programTextSentence, pushAssignment, roleReads, subscriptOnly, unlistedWords } from "./shell-read-argv.js";
import { ARITHMETIC_TEST_OPERATORS, BindingThread, arithmeticSubstitutions, assignsAsStatement, inheritedFunctionsOf, inheritedExportedFunctions, isArithmeticCommand, bindingEffectOf, bindingFloors, exportsOf, floorReaderOf, joinRebound, joinedFloors, loopListHeadAt, namesBoundIn, parameterBodySubstitutions, projectSegments, runsAtExitOnly, valueOf, } from "./shell-read-bindings.js";
import { commandEnvironmentNames, isShellSyntaxWord, programBasename, programPositionRunsShell, readProgramPosition, shellScanDeclineOf, } from "./bash-program-position.js";
import { WorkdirThread, baseShiftOf, textCalls, textMayMove, textMovesOf, textSetsPhysical } from "./shell-read-workdir.js";
import { childEnvironment, withCommandEnvironment } from "./shell-read-command-environment.js";
import { POLL_LOOP_MAX_BEATS, attachedOptionPayloads, isPathShapedToken, programTextSlotFiles, } from "./bash-readonly-classifier.js";
import { mayCarryGitVariables, objectPathPlacement } from "./shell-read-object-path.js";
import { BLOCK_WORD_NAMES, commandLineOf, commandLineOptionSpellings, declaredAttributes, isDeclarationBuiltin, isInertBuiltin, launcherOptionPathRole, launcherOptionStep, readOptionRole, programLanguageOf, programTextOpensOf, selectedOptions, movesBaseByStack, opensNoOperand, programDelivery, programRow, readArgRoles, runsShellText, } from "./program-read-model.js";
import { shellWordsOf } from "../../shell/shell-words.js";
import { isAbsoluteForFamily, ownProcessSpelling } from "./safety.js";
import { codeBodies, launchedInput, literalEvalText, pipedTextOf, printedByProcess, reentersShell, reentryText, scriptFileAt, stdinTextOf, stdinTextsOf } from "./shell-reentry-text.js";
import { heldAt, launchedAt, launchedInOf, nestedStartOf, plannedOnce, rebasePlan, startedAt, stdinFeeds } from "./shell-read-start.js";
import { inlineSourcedLiterals } from "./shell-read-sourced.js";
import { findHandedLines, findWordOf } from "./find-actions.js";
import { markStandardDevices } from "./shell-read-device.js";
export const READ_CANDIDATE_PROVENANCES = Object.freeze([
"operand",
"option_value",
"stdin_redirect",
"write_redirect_target",
"env_assignment",
"unlisted_word",
"traversal_root",
"cd_target",
"program_path",
"script_slot_file",
"mount_source",
"object_path",
]);
function joinedWhere(a, b, andRunStart) {
if (a === undefined)
return { where: b, andRunStart };
const join = (x, y) => (x === "unknown" || y === "unknown" ? "unknown" : [...x, ...y.filter((v) => !x.some((w) => w.spelled === v.spelled))]);
const both = (x = [], y = []) => [...new Set([...x, ...y])];
const stack = (x = [], y = []) => Array.from({ length: Math.max(x.length, y.length) }, (_, k) => both(x[k], y[k]));
const floor = { PWD: both(a.where.floor?.PWD, b.floor?.PWD), OLDPWD: both(a.where.floor?.OLDPWD, b.floor?.OLDPWD), DIRSTACK: stack(a.where.floor?.DIRSTACK, b.floor?.DIRSTACK) };
return { where: { PWD: join(a.where.PWD, b.PWD), OLDPWD: join(a.where.OLDPWD, b.OLDPWD), movedAt: Math.max(a.where.movedAt, b.movedAt), floor }, andRunStart: Math.min(a.andRunStart, andRunStart) };
}
const NESTING_MAX = 4;
const LOOP_END = shellWordsOf("loop_end"), LOOP_CONDITION = shellWordsOf("loop_condition"), COPROC = shellWordsOf("background"), RESERVED = shellWordsOf("rule_reserved");
export function planShellReads(shell, command, decl, depth = 0, start) {
const plan = planText(command, { ...decl, shell }, depth, start).plan;
return depth === 0 ? markStandardDevices(plan) : plan;
}
function planText(command, decl, depth, start, from) {
const shape = { grouped: false, backgrounded: false, strayRedirection: false };
const none = new Set();
if (depth > NESTING_MAX)
return { plan: { segments: [], unreadable: `command text nested more than ${NESTING_MAX} levels deep`, shape }, end: "unmodelled", physical: false, reached: none };
const lexedAsWritten = lexShell(decl.shell, command);
const failed = "parseFailure" in lexedAsWritten ? lexedAsWritten : undefined;
const readAround = failed !== undefined ? segmentsAroundStop(command, failed) : [];
const lexed = inlineSourcedLiterals("parseFailure" in lexedAsWritten ? { segments: readAround, substitutions: readAround.flatMap((s) => s.substitutions) } : lexedAsWritten, decl.readers);
const unreadTail = failed?.readBefore.at(-1)?.text;
const unreadable = failed !== undefined ? PARSE_FAILURE_SENTENCE[failed.parseFailure.reason] : unreadableSentenceOf(lexed, command);
const projected = projectSegments(lexed.segments);
const exportedFunctions = inheritedFunctionsOf(projected, start?.exportedFunctions), exportedNames = new Set(exportedFunctions.keys());
const loopShapes = projected.map((p) => loopShapeOf(p));
const loopEndOf = new Map();
{
const open = [];
loopShapes.forEach((l, si) => {
if (l === "head")
open.push(si);
else if (l === "end") {
const h = open.pop();
if (h !== undefined)
loopEndOf.set(h, si);
}
});
}
const fedBase = stdinFeeds(lexed.segments, start?.stdin ?? [], (si) => [pipedTextOf(lexed.segments[si - 1])]);
const loopFeedOf = (si) => {
if (lexed.segments[si].connector === "|")
return undefined;
const heads = [...loopEndOf].filter(([h, end]) => h <= si && si < end).map(([h]) => h).sort((a, b) => b - a);
const inner = [];
for (const h of heads) {
const own = stdinTextsOf(lexed.segments[loopEndOf.get(h)], []);
if (own.some((t) => t.allocated !== true))
return [...own, ...inner];
inner.unshift(...own);
}
return inner.length > 0 ? [...fedBase(si), ...inner] : undefined;
};
const fedAt = (si) => loopFeedOf(si) ?? fedBase(si);
const stdinOf = (si) => stdinTextsOf(lexed.segments[si], fedAt(si));
const declaredHome = decl.homeDir !== undefined ? [{ spelled: decl.homeDir }] : "unknown";
const declaredCdPath = decl.cdPath === "unknown" ? "unknown" : [{ spelled: (decl.cdPath ?? []).join(":") }];
const declared = (name, rebound) => (rebound ? "unknown" : name === "HOME" ? declaredHome : name === "CDPATH" ? declaredCdPath : "unknown");
const initial = start?.initial ?? ((name) => declared(name, false));
const named0 = projected.map((p, si) => bindingEffectOf(lexed.segments[si], p.argv, p, () => "unknown"));
const bindsAt = (j, name) => named0[j].all === "unknown" || named0[j].bindings.some((b) => b.name === name);
const boundAnywhere = (name) => named0.some((_, j) => bindsAt(j, name)) || start?.enclosingBinds(name) === true;
const bodies0 = new BindingThread(lexed.segments, named0, initial, boundAnywhere, loopEndOf, start?.homeTouched === true, start?.inherited, start?.names);
const moves = textMovesOf(new Set(projected.flatMap((p) => p.defines)), lexed.segments, projected.map((p) => p.argv), (si) => bodies0.inFunctionBody(si), start?.thread, exportedNames, fedAt);
const callEnvironments = moves.mayCallAt.map((c, si) => (c ? commandEnvironmentNames(projected[si].argv) : undefined));
bodies0.runsBodies(moves.runsBodyAt, moves.bodiesAt.some((b) => b.length > 0), callEnvironments);
const boundBefore = (name, si) => start?.enclosingBinds(name) === true || bodies0.bindsBefore(name, si);
const feedsItself = (si) => lexed.segments[si].tokens.some((t) => (t.kind === "heredoc" && (t.fd ?? 0) === 0) || (t.kind === "redirect" && (t.fd ?? (t.op === "<" || t.op === "<<<" || t.op === "<>" || t.op === "<&" ? 0 : 1)) === 0));
const readFeedOf = (si) => [stdinOf(si), !feedsItself(si) && loopFeedOf(si) !== undefined, boundBefore("IFS", si)];
const named = projected.map((p, si) => bindingEffectOf(lexed.segments[si], p.argv, p, (w, quoted, overlay) => valueOf(w, undefined, quoted, overlay), undefined, undefined, ...readFeedOf(si)));
const names = new BindingThread(lexed.segments, named, initial, boundAnywhere, loopEndOf, start?.homeTouched === true, start?.inherited, start?.names);
const boundAt = (name, si) => {
const environment = commandEnvironmentNames(projected[si].argv);
return boundBefore(name, si) || bindsAt(si, name) || (environment !== "all" && environment.has(name));
};
const laterStart = { initial: (name) => declared(name, boundAnywhere(name)), enclosingBinds: boundAnywhere, homeTouched: boundAnywhere("HOME"), inherited: names.inheritedAt() };
const commandTableAt = (table, si) => withCommandEnvironment(table, projected[si].argv, projected[si].redirects.flatMap((r) => (r.target !== undefined ? [r.target] : [])));
const received = start?.received ?? ((name) => (decl.receivedEnvNames === undefined ? "maybe" : decl.receivedEnvNames.includes(name) ? "yes" : "no"));
const { exportedAt, handedOn } = childEnvironment({ received, exportsAt: projected.map((p) => exportsOf(p.argv)), precedes: (at, si) => bodies0.segmentPrecedes(at, si), certainlyBefore: (at, si) => bodies0.segmentCertainlyBefore(at, si), binds: bindsAt, startValue: declared, boundAnywhere });
const childStart = (table, si, env = commandEnvironmentNames(projected[si].argv), held = commandTableAt(table, si)) => { const sets = (name) => held.commandSets.has(name) || (env !== "all" && env.has(name)), bound = (name) => boundAnywhere(name) || sets(name); return { ...laterStart, initial: (name) => (sets(name) ? held.stateOf(name) : handedOn(table, name, si, env)), enclosingBinds: bound, homeTouched: bound("HOME"), received: (name) => (sets(name) ? "yes" : env === "all" ? "maybe" : exportedAt(name, si)) }; };
const nestedTextStart = (table, si, kind, at, exported = exportedNames) => kind === "substitution" ? { initial: (name) => table.stateOf(name), enclosingBinds: (name) => boundAt(name, si), homeTouched: table.homeTouched, inherited: table.inherited, thread: heldThread(moves.functions), names: heldAt(table), ...(exportedFunctions.size > 0 ? { exportedFunctions } : {}) } : startedAt(kind === "now" && readProgramPosition(projected[si].argv).program?.basename === "eval" ? evalStart(commandTableAt(table, si), si) : kind === "now" ? { ...childStart(table, si), inherited: { ...laterStart.inherited, floors: joinedFloors(laterStart.inherited.floors, table.inherited.floors), rebound: joinRebound(table.inherited.rebound, commandEnvironmentNames(projected[si].argv)) }, ...(exportedFunctions.size > 0 ? { exportedFunctions } : {}), ...(exportedFunctions.size > 0 ? { thread: { physical: false, functions: exported, unread: exported, reached: workdir.reached }, names: inheritedExportedFunctions(exportedFunctions) } : {}) } : { ...laterStart, thread: heldThread(moves.functions, workdir.mayBePhysical || moves.physicalAt.some(Boolean)), names: names.heldAnywhere(), ...(exportedFunctions.size > 0 ? { exportedFunctions } : {}) }, at);
const nestedPlanner = (table, si) => (text, kind, at) => planShellReads(decl.shell, text, decl, depth + 1, nestedTextStart(table, si, kind, at));
const empty = lexed.segments.map((segment, si) => segmentIsEmpty(segment, projected[si]));
const facts = projected.map(() => undefined);
const tables = projected.map(() => undefined);
const inheritedFns = new Set([...(start?.exportedFunctions ?? [])].flatMap(([name, body]) => (body === "unread" ? [name] : [])));
const factsAt = (si, table) => {
tables[si] ??= table;
return (facts[si] ??= segmentFacts(lexed.segments[si], projected[si], decl, table, nestedPlanner(table, si), fedAt(si), inheritedFns));
};
const placesOf = () => ({ bases: projected.map(() => new Set()), unmodelled: projected.map(() => false), unsettledIn: projected.map(() => false), floors: projected.map(() => []) });
const written = placesOf(), later = placesOf();
const atCalls = projected.map(() => undefined);
const { bases: basesOf, unmodelled, unsettledIn } = written;
let places = written;
const stood = projected.map(() => ({ at: new Map(), lost: false }));
const keyOf = (c) => JSON.stringify([c.base, c.pwd, c.old, c.dirStack]);
names.runsBodies(moves.runsBodyAt, moves.bodiesAt.some((b) => b.length > 0), callEnvironments);
let workdir = new WorkdirThread(depth > 0 && from === undefined && start?.bases === undefined ? [nestedStartOf(decl.cwd)] : (from ?? start?.bases ?? [decl.cwd]), start?.thread?.physical === true);
if (start?.thread?.reached !== undefined)
workdir.reach(start.thread.reached);
const workdirContext = {
...(decl.homeDir !== undefined ? { homeDir: decl.homeDir } : {}),
textBinds: boundAt,
evalEnd: (text, from, table, si) => {
if (moves.bodyMoves && textCalls(text, moves.functions))
return { end: "unmodelled", physical: false, reached: new Set() };
if (!textMayMove(text, moves.functions) && !textSetsPhysical(text))
return { end: from, physical: false, reached: new Set() };
const ran = planText(text, decl, depth + 1, evalStart(table, si), from);
return { end: ran.end, physical: ran.physical, reached: ran.reached, ...(ran.unsettled === true ? { unsettled: true } : {}) };
},
};
const evalStart = (table, si) => ({ initial: (name) => table.stateOf(name), enclosingBinds: (name) => boundAt(name, si), homeTouched: table.homeTouched || table.commandSets.has("HOME"), inherited: { ...table.inherited, rebound: joinRebound(table.inherited.rebound, table.commandSets) }, thread: heldThread(moves.unread), names: heldAt(table, names.functionBound()), ...(exportedFunctions.size > 0 ? { exportedFunctions } : {}) });
const heldThread = (unread, physical = workdir.mayBePhysical) => ({ physical, functions: moves.functions, unread, reached: workdir.reached });
let andRunStart = 0;
let crossedAllAnd = true;
let crossedAnyOr = false;
let previousEmitted = -1;
const reaches = projected.map(() => undefined);
const scopes = [];
const closeScopes = (j) => {
const k = scopes.findIndex((s) => !names.reaches(s.at, j));
if (k < 0)
return;
workdir.restore(scopes[k].state);
scopes.length = k;
};
const thread = (si, replay) => {
closeScopes(si);
const connector = lexed.segments[si].connector;
if (previousEmitted >= 0) {
if (replay || connector !== "&&")
crossedAllAnd = false;
if (!replay && connector === "||")
crossedAnyOr = true;
}
if (empty[si]) {
if (!replay)
factsAt(si, names.tableAt(si, andRunStart, workdir.where(andRunStart)));
return;
}
if (previousEmitted >= 0 && !crossedAllAnd)
andRunStart = crossedAnyOr ? si + 1 : si;
if (places === later && names.inFunctionBody(si))
atCalls[si] = joinedWhere(atCalls[si], workdir.where(andRunStart), andRunStart);
const f = replay ? facts[si] : factsAt(si, names.tableAt(si, andRunStart, workdir.where(andRunStart)));
const pipeFed = f.connector === "|" || lexed.segments[si + 1]?.connector === "|", call = moves.callAt(si, tables[si]);
reaches[si] ??= { andJoined: previousEmitted >= 0 && crossedAllAnd, orBroken: !crossedAllAnd && crossedAnyOr, moveProvable: f.moveProvable && !replay && !pipeFed && !names.runsApart(si) };
crossedAllAnd = true;
crossedAnyOr = false;
previousEmitted = si;
const runsHere = places === later || !names.inFunctionBody(si);
if (workdir.lost) {
places.unmodelled[si] = true;
if (workdir.unsettled)
places.unsettledIn[si] = true;
if (runsHere)
stood[si].lost = true;
}
else
for (const c of workdir.reachable(andRunStart)) {
places.bases[si].add(c.base);
if (runsHere)
stood[si].at.set(keyOf(c), c);
}
const losesBase = moves.losesBaseAt(si, tables[si]);
if (names.runsApart(si) && (moves.physicalAt[si] || (f.shift !== undefined && call !== "named") || losesBase))
scopes.push({ at: si, state: workdir.snapshot() });
if (moves.physicalAt[si])
workdir.setPhysical();
if (f.shift !== undefined && call !== "named")
workdir.shift(si, { shift: f.shift, provable: reaches[si].moveProvable && call === undefined, andRunStart, table: commandTableAt(tables[si], si), cdable: moves.cdableFrom >= 0 && si > moves.cdableFrom }, workdirContext);
if (losesBase)
workdir.lose(si, workdir.reachable(andRunStart));
};
const bind = (si) => {
const table = tables[si];
if (table === undefined)
return;
const end = loopEndOf.get(si);
const beats = facts[si]?.loopHead?.beats;
if (end !== undefined && (beats === undefined || beats > 1)) {
const body = named.slice(si + 1, end);
const carried = bindingFloors(body.flatMap((e) => e.bindings));
names.kill(si, body.some((e) => e.all === "unknown") ? "all" : [...carried.keys(), ...(moves.mayMove.slice(si + 1, end).some(Boolean) ? ["PWD", "OLDPWD"] : [])], carried);
}
const segment = lexed.segments[si];
const effect = bindingEffectOf(segment, projected[si].argv, projected[si], (w, quoted, overlay) => valueOf(w, table, quoted, overlay), moves.callAt(si, table), (builtin) => table.builtinState(builtin), ...readFeedOf(si), floorReaderOf(table));
const { all, ...rest } = effect;
if (!names.closesWithRedirections(si))
names.apply(si, all === "reset" ? rest : effect, segment.connector === "&&" || segment.connector === "||", end, segment.spliced === true);
if (moves.callAt(si, table) !== undefined) {
const bound = names.functionBindings();
names.kill(si, moves.callsUnread(si, table) || bound === "all" ? "all" : bound.keys(), bound === "all" ? undefined : bound);
}
if (moves.bodiesAt[si].length > 0 && !runsAtExitOnly(projected[si].argv))
names.runsLater(si, moves.bodiesAt[si].reduce((held, b) => joinRebound(held, namesBoundIn(b)), names.functionBound()));
};
const walk = (run, first, within = 1) => {
const steps = [...new Set([...run, ...run.flatMap((si) => (loopShapes[si] === "head" && loopEndOf.has(si) ? [loopEndOf.get(si)] : []))])].sort((a, b) => a - b);
const loops = [];
for (const si of steps) {
const shapeOfLoop = loopShapes[si];
if (first && named[si].all === "reset")
names.apply(si, { bindings: [], all: "reset" }, false, undefined, lexed.segments[si].spliced === true);
if (first)
names.openCompoundsAt(si);
thread(si, !first);
if (first)
bind(si);
if (shapeOfLoop === "head") {
loops.push({ bodyStart: si + 1, beats: facts[si].loopHead?.beats });
continue;
}
if (shapeOfLoop !== "end")
continue;
const frame = loops.pop();
if (frame === undefined)
continue;
if (!facts.slice(frame.bodyStart, si).some((b, k) => b?.shift !== undefined || (tables[frame.bodyStart + k] !== undefined && moves.losesBaseAt(frame.bodyStart + k, tables[frame.bodyStart + k]))))
continue;
const beat = steps.filter((k) => k >= frame.bodyStart && k < si);
const around = loops.reduce((n, l) => n * (l.beats ?? 1), within);
if (frame.beats === undefined || around * frame.beats > POLL_LOOP_MAX_BEATS) {
workdir.lose(si, workdir.reachable(andRunStart), [], true);
for (const k of beat) {
places.unmodelled[k] = true;
places.unsettledIn[k] = true;
}
continue;
}
for (let n = 1; n < frame.beats && !workdir.lost; n++)
walk(beat, false, around * frame.beats);
if (workdir.lost && frame.beats > 1)
for (const k of beat) {
places.unmodelled[k] = true;
if (workdir.unsettled)
places.unsettledIn[k] = true;
}
}
};
walk(projected.map((_, si) => si), true);
closeScopes();
projected.forEach((_, si) => {
const table = tables[si];
if (!names.inFunctionBody(si) || facts[si] === undefined || table === undefined)
return;
facts[si] = undefined;
factsAt(si, table);
});
const end = workdir.end();
const gather = (ats) => {
const at = new Map();
for (const p of ats)
for (const c of p.at)
at.set(keyOf(c), c);
return { at: [...at.values()], lost: ats.some((p) => p.lost) };
};
const ended = { at: end === "unmodelled" ? [] : end, lost: end === "unmodelled" };
const after = (s) => gather([ended, ...stood.slice(s + 1).map((p) => ({ at: p.at.values(), lost: p.lost }))]);
const handedCallers = new Map();
const textCallers = (j, t, here) => {
const table = tables[j];
if (table === undefined)
return here;
const launched = t.in !== "child" ? [] : (facts[j]?.readings ?? [facts[j]]).map((g) => (g === undefined ? undefined : launchedAt(g.launchedIn, here.at.map((c) => c.base), undefined, decl.homeDir)));
const starts = launched.some((l) => l !== undefined) ? launched.map((l) => (l === undefined ? here : l.to === "unmodelled" ? { at: [], lost: true } : { at: l.to.map((base) => ({ base, skippedCd: -1 })), lost: here.lost })) : [here];
return gather(starts.map((s) => {
if (s.at.length === 0)
return s;
const key = JSON.stringify([j, t.text, t.in, s.at.map(keyOf)]);
let ran = handedCallers.get(key);
if (ran === undefined) {
const start = t.in === "shell" ? evalStart(commandTableAt(table, j), j) : nestedTextStart(table, j, t.in === "child" ? "now" : "substitution", undefined, t.functions);
ran = planText(t.text, decl, depth + 1, start, s.at).callers ?? s;
handedCallers.set(key, ran);
}
return { at: ran.at, lost: ran.lost || s.lost };
}));
};
const callers = () => gather(stood.flatMap((p, j) => {
if (!moves.runsBodyAt[j])
return [];
const runs = moves.bodyRunsAt[j], here = { at: [...p.at.values()], lost: p.lost };
return [...(runs.here ? [here] : []), ...runs.texts.map((t) => textCallers(j, t, here)), ...(moves.bodiesAt[j].length > 0 ? [after(j)] : [])];
}));
const main = workdir;
const bodies = new Map();
projected.forEach((_, si) => {
const id = names.bodyOf(si);
if (id !== undefined && facts[si] !== undefined)
bodies.set(id, [...(bodies.get(id) ?? []), si]);
});
const went = new Set();
const walkBodies = (from, floor = []) => {
for (const segs of bodies.values())
for (const start of [...(from.at.length > 0 ? [from.at] : []), ...(from.lost ? ["lost"] : [])]) {
workdir = main.fork(start, floor);
scopes.length = 0;
andRunStart = segs[0];
crossedAllAnd = true;
crossedAnyOr = false;
previousEmitted = -1;
walk(segs, false);
closeScopes();
for (const k of segs)
if (later.unmodelled[k])
later.floors[k] = [...new Set([...later.floors[k], ...(workdir.floorBases ?? [])])];
for (const p of workdir.reached)
if (!main.reached.has(p))
went.add(p);
}
};
const standing = () => stood.reduce((n, p) => n + p.at.size + (p.lost ? 1 : 0), 0);
places = later;
let grew = bodies.size > 0;
for (let pass = 0; grew && pass <= bodies.size; pass++) {
const before = standing();
walkBodies(callers());
grew = standing() > before;
}
if (grew)
walkBodies({ at: [], lost: true }, [...new Set(stood.flatMap((p) => [...p.at.values()].map((c) => c.base)))]);
workdir = main;
places = written;
main.widen(went);
projected.forEach((_, si) => {
const at = atCalls[si];
if (at === undefined || facts[si] === undefined || !names.inFunctionBody(si) || !/PWD|DIRSTACK|~[+-]/.test(lexed.segments[si].text))
return;
facts[si] = undefined;
tables[si] = undefined;
factsAt(si, names.tableAt(si, at.andRunStart, at.where, undefined, true));
});
const ownCallers = callers();
const callersOut = grew ? { at: ownCallers.at, lost: true } : ownCallers;
const planned = facts.map((f) => f);
const inert = depth === 0 && unreadable === undefined && planned.every((f) => (f.readings ?? [f]).every(segmentOpensNothing));
const settled = inert ? planned.map((f) => ({ ...f, reads: f.reads.filter((c) => c.provenance !== "env_assignment"), ...(f.readings !== undefined ? { readings: f.readings.map((g) => ({ ...g, reads: g.reads.filter((c) => c.provenance !== "env_assignment") })) } : {}) })) : planned;
shape.grouped = projected.some((p) => p.grouped);
shape.backgrounded = lexed.segments.some((s) => s.connector === "&") || settled.some((f) => (f.readings ?? [f]).some((g) => g.backgrounds === true));
shape.strayRedirection = projected.some((p) => p.argv.length === 0 && p.redirects.length > 0);
const placedRead = (c, at, atFloor, gitVariables) => {
const relative = relativeSpelling(c.spelled) || (c.provenance !== "object_path" && ownProcessSpelling(c.spelled)?.startsWith(".") === true);
if (c.provenance === "object_path" && relative) {
const { repository, ...read } = c;
return { ...read, ...objectPathPlacement(c.spelled, repository, at, atFloor, decl.homeDir, gitVariables) };
}
return { ...c, bases: relative ? at : [], ...(relative && atFloor !== undefined ? { floorBases: atFloor } : {}) };
};
const placedAt = (at, atFloor, unsettled, gitVariables = true) => (c) => {
const read = placedRead(c, at, atFloor, gitVariables);
return unsettled && read.bases === "unmodelled" ? { ...read, unsettledStart: true } : read;
};
const segments = [];
for (let si = 0; si < settled.length; si++) {
const threaded = settled[si];
if (threaded.empty)
continue;
const floorBases = workdir.floorBases ?? [];
const placed = new Set([...(unmodelled[si] ? [] : basesOf[si]), ...later.bases[si]]);
const lostFloor = [...new Set([...(unmodelled[si] ? floorBases : []), ...(later.unmodelled[si] ? later.floors[si] : [])])];
const standings = [
...(!unmodelled[si] || placed.size > 0 ? [{ bases: [...placed], unsettled: false }] : []),
...(unmodelled[si] || later.unmodelled[si] ? [{ bases: "unmodelled", ...(lostFloor.length > 0 ? { floor: lostFloor } : {}), unsettled: (unmodelled[si] === true && unsettledIn[si] === true) || (later.unmodelled[si] === true && later.unsettledIn[si] === true) }] : []),
];
const firesAt = settled[si].readings?.some((g) => g.runLater !== undefined) === true || settled[si].runLater !== undefined ? after(si) : undefined;
const firedAt = [...new Set((firesAt?.at ?? []).map((c) => c.base))].filter((b) => !placed.has(b));
const firedLost = firesAt?.lost === true && (!(unmodelled[si] || later.unmodelled[si]) || floorBases.some((b) => !lostFloor.includes(b)) || (workdir.unsettled && !standings.some((st) => st.bases === "unmodelled" && st.unsettled)));
const fired = (n) => [...(firedAt.length > 0 ? [rebasePlan(n, firedAt, firedAt)] : []), ...(firedLost ? [rebasePlan(n, "unmodelled", floorBases.length > 0 ? floorBases : undefined, workdir.unsettled)] : [])];
const move = threaded.baseMove;
for (const [k, { bases, floor, unsettled: unsettledHere }] of standings.entries())
for (const f of threaded.readings ?? [threaded]) {
const withBases = placedAt(bases, floor, unsettledHere);
const launched = launchedAt(f.launchedIn, bases, floor, decl.homeDir);
const gitVariables = mayCarryGitVariables(decl.receivedEnvNames ?? "all", tables[si]?.rebound ?? "all", commandEnvironmentNames(f.argv));
const programPlaced = launched !== undefined ? placedAt("unmodelled", launched.words, unsettledHere || launched.unsettled === true, gitVariables) : placedAt(bases, floor, unsettledHere, gitVariables);
const programRead = (c) => (c.provenance === "stdin_redirect" ? withBases(c) : programPlaced(c));
const placeNested = (n) => (f.elsewhere?.has(n) === true ? n : launched !== undefined && f.shellSide?.has(n) !== true ? rebasePlan(n, launched.to, launched.floor, unsettledHere || launched.unsettled === true) : rebasePlan(n, bases, bases === "unmodelled" ? floor : bases, unsettledHere));
segments.push({
text: f.text,
connector: connectorReaching(lexed.segments, si),
argv: f.argv,
launcherChain: f.launcherChain,
...(f.verb !== undefined ? { verb: f.verb } : {}),
...(f.reentry !== undefined ? { reentry: f.reentry } : {}),
...(f.unreadProgramText !== undefined ? { unreadProgramText: f.unreadProgramText } : {}),
...(f.stdin !== undefined ? { stdin: f.stdin.map(stdinTextOf) } : {}),
declines: f.declines,
reads: dedupe(f.reads).map(programRead),
redirects: f.redirects.map((r) => ({ op: r.op, direction: r.direction, ...(r.fd !== undefined ? { fd: r.fd } : {}), ...(r.target !== undefined ? { target: withBases(r.target) } : {}) })),
...(move !== undefined ? { baseMove: { target: typeof move.target === "string" ? move.target : withBases(move.target) } } : {}),
bases,
programStart: programPlaced({ spelled: ".", raw: ".", provenance: "unlisted_word", expands: false }),
nested: [...f.nested.map(placeNested), ...(k === 0 ? [...(f.runLater ?? [])].flatMap(fired) : [])],
...(f.printed.length > 0 ? { printed: f.printed.map(placeNested) } : {}),
reach: reaches[si] ?? { andJoined: false, orBroken: false, moveProvable: false },
rebound: tables[si]?.rebound ?? "all",
});
}
}
const reached = workdir.lost ? new Set([...workdir.reached, ...workdir.carriedFloor]) : workdir.reached;
return { plan: { segments, shape, ...(unreadable !== undefined ? { unreadable } : {}), ...(unreadTail !== undefined ? { unreadTail } : {}) }, end: unreadTail !== undefined ? "unmodelled" : workdir.end(), physical: workdir.mayBePhysical, reached, ...(workdir.unsettled ? { unsettled: true } : {}), callers: callersOut };
}
function loopShapeOf(p) {
if (p.argv[0] === undefined)
return undefined;
if (loopListHeadAt(p.argv) !== undefined)
return "head";
if (isShellSyntaxWord(p.argv[0], LOOP_END))
return "end";
const pos = readProgramPosition(p.argv);
return pos.controlWords.some((i) => LOOP_CONDITION.has(p.argv[i].folded)) ? "head" : undefined;
}
function segmentIsEmpty(segment, p) {
if (p.argv.length > 0 || p.redirects.length > 0 || segment.substitutions.length > 0)
return false;
return !segment.tokens.some((t) => t.kind === "heredoc" && !t.quoted && (substitutionsInHeredocBody(t.body)?.length ?? 1) > 0);
}
function segmentOpensNothing(f) {
if (f.empty)
return true;
const program = f.verb;
const at = program === undefined ? -1 : f.argv.findIndex((w) => w.folded === program.name);
const inertProgram = program === undefined || (program.name === program.basename && isInertBuiltin(program.basename) && !(isDeclarationBuiltin(program.basename) && f.argv.slice(at + 1).some((w) => /^[-+]/.test(w.folded))));
return inertProgram && f.argv.every((w) => !/[[\]$`]/.test(w.raw)) && f.nested.length === 0 && f.reentry === undefined && f.declines.length === 0 && f.launcherChain.length === 0 && f.redirects.every((r) => r.direction !== "in") && f.reads.every((c) => c.provenance === "env_assignment");
}
function segmentFacts(segment, p0, decl, table, nestedPlan, fed, inheritedFns = new Set()) {
const argvs = isShellSyntaxWord(p0.argv[0], BLOCK_WORD_NAMES) ? [p0.argv] : braceWordListsOf(p0.argv);
const targets = p0.redirects.flatMap((r) => (r.target === undefined ? [] : [r.target]));
const readings = argvs.flatMap((argv) => segmentReadingsOf(argv, targets, table, decl.homeDir));
if (readings.length === 1)
return readingFacts(segment, { ...p0, argv: readings[0].argv }, decl, readings[0], nestedPlan, fed, inheritedFns);
const once = plannedOnce(nestedPlan);
return readInSeveral(readings.map((reading) => readingFacts(segment, { ...p0, argv: reading.argv }, decl, reading, once, fed, inheritedFns)));
}
function readInSeveral(each) {
const first = each[0];
const move = each.find((f) => f.baseMove !== undefined)?.baseMove;
return {
...first,
moveProvable: false,
...(move !== undefined ? { baseMove: { target: typeof move.target === "string" ? move.target : { ...move.target, expands: "unresolvable" } } } : {}),
...(each.some((f) => f.shift !== undefined) ? { shift: { kind: "lost" } } : {}),
readings: each.flatMap((f) => f.readings ?? [f]),
};
}
function readingFacts(segment, p, decl, reading, nestedPlan, fed, inheritedFns = new Set()) {
const table = reading.table;
const planner = (text, kind, at) => nestedPlan(text, kind, kind !== "substitution" ? { ...at, floors: reading.floors } : at);
const facts = segmentFactsRead(segment, p, decl, table, planner, fed, reading.reads, inheritedFns);
const unresolvedRaw = new Set();
for (const t of segment.tokens) {
const w = t.kind === "word" ? t : t.kind === "redirect" ? t.target : undefined;
if (w !== undefined && w.pieces.some((p) => p.literal === undefined && p.expansion === undefined))
unresolvedRaw.add(w.raw);
}
const homeWithheld = decl.homeDir !== undefined && table.stateOf("HOME") === "unknown";
const floor = (c) => {
if (c.floorSpelled !== undefined)
return c;
const f = (c.expands === "unresolvable" || c.spelled.startsWith("./~")) && decl.homeDir !== undefined ? spelledWithHome(c.spelled, c.raw, decl.homeDir) : undefined;
return f === undefined ? c : { ...c, floorSpelled: f };
};
const unsettle = (c) => floor((unresolvedRaw.has(c.raw) || (homeWithheld && /^~(?:\/|$)/.test(c.spelled))) && c.expands !== "unresolvable" ? { ...c, expands: "unresolvable" } : c);
const each = (c) => {
const { floors, ...one } = c;
const shadows = (floors ?? []).map((v) => ({ spelled: v.spelled, ...(v.pattern !== undefined ? { pattern: v.pattern } : {}), raw: one.raw, provenance: one.provenance, expands: v.piece === true ? "unresolvable" : v.glob === true ? "glob" : false, denyOnly: true, twin: true }));
return [unsettle(one), ...shadows];
};
const move = facts.baseMove;
const shift = facts.shift;
return {
...facts,
reads: facts.reads.flatMap(each),
redirects: facts.redirects.map((r) => (r.target === undefined ? r : { ...r, target: unsettle(r.target) })),
...(move !== undefined && typeof move.target !== "string" ? { baseMove: { target: unsettle(move.target) } } : {}),
...(shift?.kind === "cd" && typeof shift.target !== "string" ? { shift: { ...shift, target: unsettle(shift.target) } } : {}),
};
}
function segmentFactsRead(segment, p, decl, table, nestedPlan, fed, toks, inheritedFns = new Set()) {
const nested = [];
const printed = [];
const elsewhere = new Set();
const runLater = new Set();
const ctx = { table, reentered: [], programTextSeen: false };
const enclosedToo = (e) => [e, ...(e.inner ?? []).flatMap(enclosedToo)];
const expansionsOf = (sg) => sg.tokens.flatMap((t) => (t.kind === "word" ? assignedWords(t) : t.kind === "redirect" && t.target !== undefined ? [t.target] : [])).flatMap((w) => w.pieces).flatMap((q) => (q.expansion !== undefined ? enclosedToo(q.expansion) : []));
const count = (list, body) => list.filter((b) => b === body).length;
const substitute = (body, here) => void (here ? ctx.reentered.push(body) : nested.push(nestedPlan(body, "substitution")));
const unread = (sentence) => void nested.push({ segments: [], unreadable: sentence, shape: { grouped: false, backgrounded: false, strayRedirection: false } });
const parameter = (e) => void (e.kind === "parameter" && e.body !== undefined && (parameterRereadsValue(e.body) && unread("a parameter expansion re-reads a value (an indirect `${!name}`, an evaluating `${name@P}`), which this station does not follow"), ctx.reentered.push(...parameterBodySubstitutions(e.body, table))));
const expandedText = (all, undelimited) => {
if (all === undefined)
return void unread(undelimited), false;
for (const x of all) {
if (x.expansion.kind === "arithmetic")
arithmeticBody(x.expansion.body ?? "");
else if (x.expansion.kind === "command")
substitute(x.expansion.body ?? "", x.currentShell === true);
else
parameter(x.expansion);
if (x.unresolved !== undefined)
void (unread(UNRESOLVED_SENTENCE[x.unresolved]), x.unresolved === "parameter_text" && expandedText(expansionsInHeredocBody(x.expansion.body ?? ""), UNRESOLVED_SENTENCE.parameter_text));
}
return all.some((x) => x.expansion.kind === "command");
};
const arithmeticBody = (body) => void (expandedText(expansionsInHeredocBody(body), "an arithmetic expansion carries a substitution this lexer cannot delimit") && unread("an arithmetic expansion evaluates what a command substitution in it prints, which this station does not read"), ctx.reentered.push(...arithmeticSubstitutions(body, table)));
const arithmetic = expansionsOf(segment).flatMap((e) => (e.kind === "arithmetic" && e.body !== undefined ? [e.body] : []));
for (const body of segment.substitutions)
(count(arithmetic, body) > 0 && count(arithmetic, body) === count(segment.substitutions, body) ? arithmeticBody(body) : substitute(body, segment.currentShell?.includes(body) === true));
for (const t of segment.tokens)
if (t.kind === "heredoc" && !t.quoted)
expandedText(expansionsInHeredocBody(t.body), "a here-document body carries a substitution this lexer cannot delimit");
for (const e of expansionsOf(segment))
parameter(e);
for (const t of segment.tokens) {
const words = t.kind === "word" ? assignedWords(t) : t.kind === "redirect" && t.target !== undefined ? [t.target] : [];
for (const q of words.flatMap((w) => w.pieces)) {
for (const e of q.expansion !== undefined ? enclosedToo(q.expansion) : [])
if (e.kind === "parameter" && e.body !== undefined)
for (const line of parameterOperandLines(e.body, q.quotedBy !== undefined))
substitute(line, false);
}
}
const shellSide = new Set(nested);
if (isArithmeticCommand(segment))
ctx.reentered.push(...arithmeticSubstitutions(p.argv.map((w) => w.folded).join(" "), table));
const redirects = p.redirects.flatMap((r) => redirectFacts(r, table, decl.homeDir));
const reads = [];
for (const r of redirects)
if (r.direction === "in" && r.target !== undefined)
reads.push(r.target);
const base = {
text: segment.text,
connector: segment.connector,
argv: p.argv,
redirects,
nested,
printed,
};
const done = (f) => {
const reentered = [...new Set(ctx.reentered)];
for (const body of reentered) {
const plan = nestedPlan(body, "later");
nested.push(plan);
shellSide.add(plan);
}
return {
...base,
...f,
...(reentered.length > 0 ? { reentry: "shell" } : {}),
...(f.unreadProgramText === undefined && ctx.programText !== undefined ? { unreadProgramText: ctx.programText } : {}),
...(elsewhere.size > 0 ? { elsewhere } : {}),
...(shellSide.size > 0 ? { shellSide } : {}),
...(runLater.size > 0 ? { runLater } : {}),
...(launchedIn !== undefined ? { launchedIn } : {}),
};
};
const head = toks[0]?.folded;
const pos = readProgramPosition(p.argv);
const launchedIn = launchedInOf(pos, toks);
const coproc = pos.written !== undefined && isShellSyntaxWord(p.argv[pos.written], COPROC) ? pos.written : undefined;
if (coproc !== undefined && toks.length > coproc + 1) {
const once = plannedOnce(nestedPlan);
const tail = (from) => ({ ...p, argv: p.argv.slice(coproc + from) });
const background = (f) => ({ ...f, backgrounds: true, ...(f.readings !== undefined ? { readings: f.readings.map((g) => ({ ...g, backgrounds: true })) } : {}) });
const first = segmentFacts(segment, tail(1), decl, table, once, fed, inheritedFns);
if (toks.length < coproc + 3 || isShellSyntaxWord(p.argv[coproc + 1], RESERVED) || readProgramPosition(tail(2).argv.slice(0, 1)).refusal !== undefined)
return background(first);
return background(readInSeveral([first, segmentFacts(segment, tail(2), decl, table, once, fed, inheritedFns)]));
}
const loop = loopShapeOf(p);
if (loopListHeadAt(p.argv) !== undefined)
return done({ empty: false, launcherChain: [], declines: [], reads, moveProvable: false, loopHead: { beats: literalBeats(toks) } });
if (head !== undefined && isShellSyntaxWord(p.argv[0], BLOCK_WORD_NAMES)) {
if (head === "[[") {
toks.forEach((r, i) => {
if (ARITHMETIC_TEST_OPERATORS.has(toks[i - 1]?.folded ?? "") || ARITHMETIC_TEST_OPERATORS.has(toks[i + 1]?.folded ?? "") || toks[i - 1]?.folded === "-v")
ctx.reentered.push(...arithmeticSubstitutions(r.folded, table));
});
}
return done({ empty: false, launcherChain: [], declines: [], reads, moveProvable: false });
}
const written = pos.written;
if (written === undefined)
return done({ empty: segmentIsEmpty(segment, p), launcherChain: [], declines: [], reads, moveProvable: false });
const loopHead = loop === "head" ? { beats: undefined } : undefined;
const launcherChain = pos.launchers.map((l) => l.name);
const launcherIndices = new Set(pos.launchers.map((l) => l.index));
const declines = [];
const decline = shellScanDeclineOf(pos, opensNoOperand);
if (decline !== undefined)
declines.push(decline);
const program = pos.program;
const basename = program?.basename;
if (program?.name === basename && basename !== undefined && inheritedFns.has(basename) && !p.defines.includes(basename))
unread("runs a function this shell inherited from its environment, whose body is text the engine did not read");
const listed = basename !== undefined && (decl.readers.has(basename) || basename === "cd");
const verb = program === undefined ? undefined : { name: program.name, basename: program.basename, listed };
for (const k of pos.assignments) {
pushAssignment(reads, toks[k].word, "env_assignment", assignsAsStatement(pos) ? "statement" : "shell");
assignmentArithmetic(toks[k].word, table.isInteger(toks[k].word.assignment?.name ?? ""), ctx);
}
for (const l of pos.launchers) {
const r = toks[l.index];
if (isPathShapedToken(r.folded))
reads.push(bare(r, "program_path"));
}
{
const controlIndices = new Set(pos.controlWords);
const assignmentIndices = new Set(pos.assignments);
const chainEnd = pos.program?.index ?? toks.length;
const launcherValueIndices = new Set();
const launcherPathValues = new Map();
for (const l of pos.launchers) {
const row = programRow(programBasename(l.name));
if (row?.launcher === undefined)
continue;
for (let j = l.index + 1; j < chainEnd; j++) {
const w = toks[j].folded;
if (!w.startsWith("-") || w === "-")
break;
const step = launcherOptionStep(row, w);
if (step === undefined || (step === 2 && j + 1 >= chainEnd))
break;
if (step === 2) {
const role = launcherOptionPathRole(row, w);
if (role === undefined)
launcherValueIndices.add(j + 1);
else
launcherPathValues.set(j + 1, { value: toks[j + 1].folded, role });
j++;
continue;
}
const own = readOptionRole(row, w);
if (own.form === "attached" && own.role?.kind === "path")
launcherPathValues.set(j, { value: literalTildeSpelling(own.value), role: own.role });
}
}
for (let j = 0; j < chainEnd; j++) {
if (launcherIndices.has(j) || controlIndices.has(j) || assignmentIndices.has(j) || launcherValueIndices.has(j) || j === written)
continue;
const r = toks[j];
const word = r.folded;
const pathValue = launcherPathValues.get(j);
if (pathValue !== undefined) {
reads.push(...roleReads(r, "option_value", pathValue.value, pathValue.role, "literal", ctx));
continue;
}
if (word.startsWith("-") && word !== "-") {
for (const payload of attachedOptionPayloads(word))
reads.push(bare(r, "unlisted_word", payload));
if (isPathShapedToken(word))
reads.push(bare(r, "unlisted_word"));
continue;
}
if (r.expands === "unresolvable") {
reads.push(bare(r, "unlisted_word"));
continue;
}
if (r.word.assignment !== undefined) {
pushAssignment(reads, r.word, "env_assignment", table);
continue;
}
reads.push(bare(r, "unlisted_word"));
}
}
let reentry;
let shift;
if (pos.argvFromStdin)
reentry = "argv";
const reenterShell = (verb, argvs) => {
const stdin = stdinTextsOf(segment, fed);
const scripts = new Map();
const prints = new Map();
const into = (to) => (text, at) => { if (text !== undefined)
to.set(JSON.stringify([text, at]), { ...at, text }); };
const script = into(scripts), print = into(prints);
for (const { shell, texts: t, args: a, as } of argvs) {
const user = as !== undefined ? { as } : {};
const argvText = [reentryText(shell, t), reentryText(shell, a)];
for (const text of argvText)
script(text, { ...user, ...(stdin.length > 0 ? { stdin } : {}) });
if (argvText.every((text) => text === undefined))
for (const s of stdin)
void (s.literal !== undefined && script(reentryText(shell, t, s.literal), user), s.printed !== undefined && print(reentryText(shell, t, s.printed), user));
}
for (const { shell, args: a, words, as } of argvs) {
const at = shell === "source" || shell === "." ? a.findIndex((w) => !w.startsWith("-") || w === "-") : scriptFileAt(shell, a);
const file = at === undefined ? undefined : words[at];
if (file !== undefined)
void (reads.push(bare(file, "operand")), print(printedByProcess(file.word), as !== undefined ? { as } : {}));
}
for (const [to, plans] of [[scripts, nested], [prints, printed]]) {
for (const { text, ...at } of to.values()) {
const plan = nestedPlan(text, "now", at);
plans.push(plan);
if (at.as?.login === true)
elsewhere.add(plan);
}
}
return done({ empty: false, launcherChain, verb, reentry: "shell", declines, reads, moveProvable: false, ...(loopHead !== undefined ? { loopHead } : {}), ...(stdin.length > 0 ? { stdin } : {}), ...(shift !== undefined ? { shift } : {}) });
};
if (pos.refusal !== undefined) {
const owner = "owner" in pos.refusal ? programRow(programBasename(pos.refusal.owner)) : undefined;
if (pos.refusal.kind === "option_at_program_position" && owner !== undefined && commandLineOptionSpellings(owner).length > 0) {
const text = commandStringValue(owner, toks, pos.refusal.option);
if (text !== undefined) {
nested.push(nestedPlan(text.value, "now"));
reentry = "shell";
unlistedWords(reads, toks, text.next, launcherIndices, "unlisted_word", ctx);
return done({ empty: false, launcherChain, ...(verb !== undefined ? { verb } : {}), reentry, declines, reads, moveProvable: false, ...(loopHead !== undefined ? { loopHead } : {}) });
}
}
if (programPositionRunsShell(pos, runsShellText)) {
const launched = launchedInput(p.argv, pos, { text: (k) => literalTextOf(toks[k].word.pieces) ?? programTextOf(toks[k]), folded: (k) => programTextOf(toks[k]), values: (k) => settledFieldsOf(toks[k]) });
for (const k of launched.programWords)
if (isPathShapedToken(toks[k].folded))
reads.push(bare(toks[k], "program_path"));
for (const text of launched.lines)
nested.push(nestedPlan(text, "substitution"));
const argvs = launched.shells.map((a) => ({ ...a, words: a.words.map((k) => (k === undefined ? undefined : toks[k])) }));
if (argvs.length === 0)
return done({ empty: false, launcherChain, reentry: "shell", declines, reads, moveProvable: false, ...(loopHead !== undefined ? { loopHead } : {}) });
return reenterShell({ name: argvs[0].shell, basename: argvs[0].shell, listed: decl.readers.has(argvs[0].shell) }, argvs);
}
const from = pos.refusal.kind === "wildcard_program_word" ? pos.refusal.at + 1 : pos.launchers[0]?.index ?? written;
if (pos.refusal.kind === "wildcard_program_word") {
const c = bare(toks[pos.refusal.at], "program_path");
reads.push(c.expands === "unresolvable" ? c : { ...c, denyOnly: true });
}
unlistedWords(reads, toks, from, launcherIndices, "unlisted_word", ctx);
return done({ empty: false, launcherChain, ...(verb !== undefined ? { verb } : {}), ...(reentry !== undefined ? { reentry } : {}), declines, reads, moveProvable: false, ...(loopHead !== undefined ? { loopHead } : {}) });
}
if (program === undefined) {
if (pos.launchers.length > 0)
unlistedWords(reads, toks, pos.launchers[0].index, launcherIndices, "unlisted_word", ctx);
return done({ empty: false, launcherChain, ...(reentry !== undefined ? { reentry } : {}), declines, reads, moveProvable: false, ...(loopHead !== undefined ? { loopHead } : {}) });
}
const argReads = toks.slice(program.index + 1);
const args = argReads.map(programTextOf);
const texts = argReads.map((r) => literalTextOf(r.word.pieces) ?? programTextOf(r));
const programRead = toks[program.index];
if (rewritten(programRead) || isPathShapedToken(programRead.folded))
reads.push(bare(programRead, "program_path"));
if (rewritten(programRead) && !programRead.word.pieces.some((p) => p.literal?.includes("/") === true))
shift = { kind: "lost" };
if (basename === "eval") {
const text = literalEvalText(argReads.map((r) => r.word));
shift = text !== undefined ? { kind: "eval", text } : { kind: "lost" };
}
if (basename === "source" || basename === ".")
shift = { kind: "lost" };
if (reentersShell(basename, args)) {
const named = descriptorNameWords(segment);
const kept = argReads.map((r) => !named.has(r.word));
const allocatedReading = kept.includes(false) ? [{ shell: basename, texts: texts.filter((_, k) => kept[k]), args: args.filter((_, k) => kept[k]), words: argReads.filter((_, k) => kept[k]) }] : [];
return reenterShell(verb, [{ shell: basename, texts, args, words: argReads }, ...allocatedReading]);
}
const row = programRow(basename);
const delivery = programDelivery(row, args);
if (delivery !== undefined)
reentry = "interpreter";
const moveProvable = pos.controlWords.length === 0 && pos.launchers.length === 0 && pos.assignments.length === 0 && program.name === basename;
let baseMove;
const moving = baseShiftOf(basename, argReads, (r) => bare(r, "cd_target"));
if (moving !== undefined)
shift = moving.shift;
if (moving?.reported !== undefined)
baseMove = { target: moving.reported };
if (basename === "cd") {
if (typeof baseMove?.target === "object")
reads.push(baseMove.target);
}
else if (movesBaseByStack(basename)) {
unlistedWords(reads, toks, program.index, launcherIndices, "unlisted_word", ctx, program);
}
else if (listed) {
listedVerbCandidates(basename, argReads, reads, ctx);
}
else if (isDeclarationBuiltin(basename) && program.name === basename) {
const integer = declaredAttributes(row, args).has("integer");
const asWritten = row?.operands?.rest?.kind === "binds-name" && row.operands.rest.asWritten === true;
for (const r of argReads) {
const a = r.word.assignment;
if (a !== undefined && (r.expands !== "unresolvable" || a.value.expansions.length > 0))
pushAssignment(reads, r.word, "env_assignment", table);
else if (r.expands === "unresolvable") {
reads.push(bare(r, "unlisted_word"));
pushAssignment(reads, r.word, "unlisted_word", table);
}
assignmentArithmetic(r.word, integer || (a !== undefined && table.isInteger(a.name)), ctx, asWritten);
}
}
else {
unlistedWords(reads, toks, program.index, launcherIndices, "unlisted_word", ctx, program);
}
for (const e of row === undefined ? [] : readArgRoles(row, args)) {
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" || role.asWritten === true)
continue;
const text = e.kind === "option" && typeof e.reading === "object" ? e.reading.attached : args[e.at];
ctx.reentered.push(...arithmeticSubstitutions(subscriptOnly(text), table));
}
const language = programLanguageOf(row);
if (language !== undefined && (delivery === "stdin" || (delivery === "text" && !ctx.programTextSeen))) {
const opens = programTextOpensOf(language);
if (opens === "any" || typeof opens !== "string")
ctx.programText ??= delivery === "stdin" ? `reads the ${language} program it runs from its standard input, which this station does not read` : programTextSentence(language);
}
const effectSub = pathSubcommandOf(row, args);
const effectRow = effectSub?.row ?? row;
const effectArgs = effectSub === undefined ? args : args.slice(effectSub.at + 1);
if (effectRow !== undefined && !runsShellText(basename) && selectedOptions(effectRow, effectArgs).some((o) => o.effect === "executes"))
reentry = "shell";
if (row?.key === "find")
for (const line of findHandedLines(row, argReads.map((r) => findWordOf(r.word))))
nested.push({ ...nestedPlan(line, "substitution"), handed: true });
let unreadProgramText;
const slot = row === undefined ? undefined : programTextSlotFiles(row, args);
if (slot !== undefined) {
for (const f of slot.reads)
reads.push(bare(readOfText(f), "script_slot_file"));
for (const f of slot.writes)
reads.push(bare(readOfText(f), "write_redirect_target"));
for (const c of slot.commands)
nested.push(nestedPlan(c, "later"));
if (slot.commands.length > 0 || slot.executesPatternSpace)
reentry = "shell";
unreadProgramText = slot.unread;
}
const bodies = new Set([...codeBodies(basename, texts), ...codeBodies(basename, args)]);
if (bodies.size > 0)
reentry = "shell";
for (const body of bodies) {
const plan = nestedPlan(body, "later");
nested.push(plan);
runLater.add(plan);
}
return done({
empty: false,
launcherChain,
verb: verb,
...(reentry !== undefined ? { reentry } : {}),
...(unreadProgramText !== undefined ? { unreadProgramText } : {}),
declines,
reads,
...(baseMove !== undefined ? { baseMove } : {}),
...(shift !== undefined ? { shift } : {}),
moveProvable,
...(loopHead !== undefined ? { loopHead } : {}),
});
}
function dedupe(reads) {
const at = new Map();
const out = [];
for (const c of reads) {
const key = `${c.provenance}\u0000${c.spelled}\u0000${c.expands}\u0000${c.raw}\u0000${c.denyOnly === true}`;
const i = at.get(key);
if (i === undefined) {
at.set(key, out.length);
out.push(c);
}
else if (c.bracket === true && out[i].bracket !== true)
out[i] = { ...out[i], bracket: true };
}
return out;
}
function relativeSpelling(spelled) {
return !(isAbsoluteForFamily("own", spelled) || spelled.startsWith("~"));
}
function redirectFacts(r, table, homeDir) {
const fd = r.fd !== undefined ? { fd: r.fd } : {};
if (r.target === undefined)
return [{ op: r.op, direction: "dup", ...fd }];
if (r.op === "<<<")
return [{ op: r.op, direction: "in", ...fd }];
const read = readsOf([r.target], table, homeDir)[0];
const inward = r.op === "<" || r.op === "<>" ? [{ op: r.op, direction: "in", ...fd, target: bare(read, "stdin_redirect") }] : [];
return r.op === "<" ? inward : [...inward, { op: r.op, direction: "out", ...fd, target: bare(read, "write_redirect_target") }];
}
function commandStringValue(row, toks, option) {
const at = toks.findIndex((r) => r.folded === option);
const line = at < 0 ? undefined : commandLineOf(row, option);
if (line === undefined)
return undefined;
if (line !== "next")
return { value: line.attached, next: at + 1 };
const value = toks[at + 1] === undefined ? undefined : programTextOf(toks[at + 1]);
return value === undefined ? undefined : { value, next: at + 2 };
}
function literalBeats(toks) {
const at = toks.findIndex((r) => r.folded === "in");
if (at < 0)
return undefined;
const words = toks.slice(at + 1);
if (words.length === 0)
return undefined;
const only = words.length === 1 && words[0].word.pieces.length === 1 ? words[0].word.pieces[0].expansion : undefined;
if (only !== undefined) {
const m = only.kind === "command" ? /^\s*seq\s+(\d+)\s+(\d+)\s*$/.exec(only.body ?? "") : null;
if (m === null)
return undefined;
const beats = Number(m[2]) - Number(m[1]) + 1;
return beats >= 1 && beats <= POLL_LOOP_MAX_BEATS ? beats : undefined;
}
for (const w of words)
if (w.expands !== false)
return undefined;
return words.length <= POLL_LOOP_MAX_BEATS ? words.length : undefined;
}