@sema-agent/core
Version:
Stateless, task-oriented AI agent core
792 lines (791 loc) • 30.1 kB
JavaScript
import { readOptionRole } from "./program-read-model.js";
import { literalTextOf } from "../../shell/lex.js";
export function findWordOf(w) {
const literal = literalTextOf(w.pieces);
return { raw: w.raw, spelled: literal ?? w.folded, ...(literal === undefined ? { rewritten: true } : {}) };
}
export const FIND_DEFAULT_START = Object.freeze({ raw: ".", spelled: "." });
const REGEX_TYPES = Object.freeze({
"findutils-default": "basic", emacs: "basic", "posix-basic": "basic", sed: "basic", ed: "basic",
"posix-extended": "extended", awk: "extended", "gnu-awk": "extended", "posix-awk": "extended",
});
const HANDS_ON = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
const OPERATOR = Object.freeze({ "(": "(", ")": ")", "!": "!", "-not": "!", "-a": "and", "-and": "and", "-o": "or", "-or": "or", ",": "," });
const isOperator = (w) => Object.hasOwn(OPERATOR, w);
const MAX_NESTING = 64;
const startsExpression = (w) => w === "(" || w === "!" || (w.startsWith("-") && w !== "-");
const LEADING_OPTION = /^-(?:[HLPEXdsx]+|D|O\d*|f)$/;
function leadingOptionWords(row, word, next) {
if (!LEADING_OPTION.test(word))
return 0;
return readOptionRole(row, word, next).form === "separated" ? 2 : 1;
}
const ALWAYS_TRUE = new Set(["-true", "-print", "-print0", "-printf", "-fprint", "-fprint0", "-fprintf", "-ls", "-fls", "-depth", "-maxdepth", "-mindepth", "-follow", "-noleaf", "-daystart", "-warn", "-nowarn", "-ignore_readdir_race", "-noignore_readdir_race", "-regextype", "-xdev", "-mount"]);
function testOf(predicate, value, dialect) {
if (predicate === "-prune" || predicate === "-quit" || predicate === "-false")
return { kind: predicate === "-prune" ? "prune" : predicate === "-quit" ? "quit" : "false" };
if (ALWAYS_TRUE.has(predicate) && (predicate !== "-depth" || value === undefined))
return { kind: "true" };
if (predicate === "-empty")
return { kind: "empty" };
if (value === undefined || value.rewritten === true)
return { kind: "other" };
if (predicate === "-type")
return value.spelled === "d" ? { kind: "dirs" } : { kind: "other" };
const caseless = predicate.startsWith("-i");
if (predicate === "-name" || predicate === "-iname")
return { kind: "name", value: value.spelled, caseless };
if (predicate === "-path" || predicate === "-ipath" || predicate === "-wholename" || predicate === "-iwholename")
return { kind: "path", value: value.spelled, caseless, regex: false };
if (predicate === "-regex" || predicate === "-iregex")
return { kind: "path", value: value.spelled, caseless, regex: true, ...(dialect !== undefined ? { dialect } : {}) };
return { kind: "other" };
}
function parseExpression(terms) {
let k = 0;
const opAt = (op) => {
const t = terms[k];
return t?.t === "op" && t.op === op;
};
const list = (op, of) => (of.length === 1 ? of[0] : { op, of });
const unary = (depth) => {
if (depth > MAX_NESTING)
return undefined;
const t = terms[k];
if (t === undefined)
return undefined;
k++;
if (t.t === "action")
return { op: "action", at: t.at };
if (t.t === "test")
return { op: "test", test: t.test };
if (t.op === "!") {
const of = unary(depth + 1);
return of === undefined ? undefined : { op: "not", of };
}
if (t.op !== "(")
return undefined;
const inner = comma(depth + 1);
if (inner === undefined || !opAt(")"))
return undefined;
k++;
return inner;
};
const and = (depth) => {
const of = [];
for (;;) {
const e = unary(depth);
if (e === undefined)
return undefined;
of.push(e);
if (opAt("and")) {
k++;
continue;
}
const t = terms[k];
if (t === undefined || (t.t === "op" && (t.op === "or" || t.op === "," || t.op === ")")))
return list("and", of);
}
};
const or = (depth) => {
const of = [];
for (;;) {
const e = and(depth);
if (e === undefined)
return undefined;
of.push(e);
if (!opAt("or"))
return list("or", of);
k++;
}
};
const comma = (depth) => {
const of = [];
for (;;) {
const e = or(depth);
if (e === undefined)
return undefined;
of.push(e);
if (!opAt(","))
return list(",", of);
k++;
}
};
if (terms.length === 0)
return undefined;
const e = comma(0);
return e !== undefined && k === terms.length ? e : undefined;
}
export function findActionsOf(row, args) {
let i = 0;
const starts = [];
let certainDepth;
const passesBy = (depth) => void (certainDepth = Math.min(certainDepth ?? depth, depth));
let dialect = "basic";
for (;;) {
const w = args[i];
if (w === undefined)
break;
if (w.spelled === "--") {
i++;
break;
}
const n = leadingOptionWords(row, w.spelled, args[i + 1]?.spelled);
if (n === 0)
break;
if (/^-[HLPEXdsx]+$/.test(w.spelled) && w.spelled.includes("x"))
passesBy(1);
if (/^-[HLPEXdsx]+$/.test(w.spelled) && w.spelled.includes("X"))
passesBy(0);
if (/^-[HLPEXdsx]+$/.test(w.spelled) && w.spelled.includes("E"))
dialect = "extended";
if (w.spelled === "-f" && n === 2)
starts.push(i + 1);
i += n;
}
for (; i < args.length && !startsExpression(args[i].spelled); i++)
starts.push(i);
const actions = [];
const terms = [];
let startsFromFile = false;
const depths = {};
while (i < args.length) {
const w = args[i].spelled;
if (w === "-files0-from")
startsFromFile = true;
if (w === "-xdev" || w === "-mount")
passesBy(w === "-xdev" ? 1 : 0);
if (HANDS_ON.has(w)) {
const from = i + 1;
let to = from;
while (to < args.length && args[to].spelled !== ";" && !(args[to].spelled === "+" && to > from && args[to - 1].spelled === "{}"))
to++;
terms.push({ t: "action", at: actions.length });
actions.push({ action: w, from, to });
i = to + 1;
continue;
}
if (w === "-delete") {
terms.push({ t: "action", at: actions.length });
actions.push({ action: "-delete" });
i++;
continue;
}
if (isOperator(w)) {
terms.push({ t: "op", op: OPERATOR[w] });
i++;
continue;
}
if (!w.startsWith("-")) {
terms.push({ t: "test", test: { kind: "other" } });
i++;
continue;
}
if (w === "-fprintf") {
terms.push({ t: "test", test: testOf(w, undefined) });
i += 3;
continue;
}
const next = args[i + 1];
const separated = readOptionRole(row, w, next?.spelled).form === "separated";
if ((w === "-mindepth" || w === "-maxdepth") && next !== undefined && separated)
depths[w === "-mindepth" ? "min" : "max"] = next.rewritten !== true && /^\d+$/.test(next.spelled) ? Number(next.spelled) : "unknown";
if (w === "-regextype")
dialect = next !== undefined && next.rewritten !== true && Object.hasOwn(REGEX_TYPES, next.spelled) ? REGEX_TYPES[next.spelled] : undefined;
terms.push({ t: "test", test: testOf(w, separated ? next : undefined, dialect) });
i += separated ? 2 : 1;
}
const handed = actions.filter((a) => a.action !== "-delete");
return { starts, startsFromFile, actions, deletes: handed.length < actions.length, handed, expr: parseExpression(terms), depths, ...(certainDepth !== undefined ? { certainDepth } : {}) };
}
function bracketEnd(p, i) {
let j = i + 1;
if (p[j] === "!" || p[j] === "^")
j++;
if (p[j] === "]")
j++;
for (; j < p.length; j++) {
if (p[j] === "\\") {
j++;
continue;
}
if (p[j] === "]")
return j;
const unit = p[j] === "[" ? p[j + 1] : undefined;
if (unit === ":" || unit === "=" || unit === ".") {
const close = p.indexOf(`${unit}]`, j + 2);
if (close >= 0)
j = close + 1;
}
}
return -1;
}
function bracketsReplaced(pattern, instead) {
let out = "";
for (let i = 0; i < pattern.length; i++) {
if (pattern[i] === "\\") {
out += pattern.slice(i, i + 2);
i++;
continue;
}
const end = pattern[i] === "[" ? bracketEnd(pattern, i) : -1;
if (end < 0)
out += pattern[i];
else {
out += instead;
i = end;
}
}
return out;
}
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const UNNAMED = "\u0001";
const MAX_PROBE_DEPTH = 32;
export function narrowsAt(t, start, forDelete) {
switch (t.kind) {
case "name":
return /[^*?]/.test(bracketsReplaced(t.value, ""));
case "path":
return narrowsOn7700(t, start) && reachProofOf(t, start) === undefined;
case "empty":
return true;
case "dirs":
return forDelete;
default:
return false;
}
}
function narrowsOn7700(t, start) {
if (t.regex)
return /[A-Za-z0-9_]|\\./.test(bracketsReplaced(regexWithoutStart7700(t, start), ""));
return start.rewritten === true ? /[^*?/]/.test(bracketsReplaced(t.value, "")) : !selectsAnyEntryBelow7700(t.value, start, t.caseless);
}
function selectsAnyEntryBelow7700(pattern, start, caseless) {
const p = bracketsReplaced(pattern, "?");
const depth = Math.min(MAX_PROBE_DEPTH, (p.match(/\//g)?.length ?? 0) + 1);
for (const s of startSpellings(start)) {
for (let d = 1; d <= depth; d++)
if (globMatches(p, `${s === "/" ? "" : s}${`/${UNNAMED}`.repeat(d)}`, caseless))
return true;
}
return false;
}
function regexWithoutStart7700(t, start) {
const re = t.value.replace(/^\^/, "");
if (start.rewritten === true)
return re;
const fold = (s) => (t.caseless ? s.toLowerCase() : s);
let longest = 0;
for (const s of startSpellings(start).flatMap((x) => [x, escapeRegex(x)]))
if (s !== "" && fold(re).startsWith(fold(s)))
longest = Math.max(longest, s.length);
return re.slice(longest);
}
const startSpellings = (start) => [...new Set([start.spelled, start.spelled.replace(/(.)\/+$/, "$1")])];
function globReachShape(pattern) {
const out = [];
for (let i = 0; i < pattern.length; i++) {
const c = pattern[i];
if (c === "[")
return undefined;
if (c === "*")
out.push("run");
else if (c === "?")
out.push("one");
else {
if (c === "\\" && ++i >= pattern.length)
return undefined;
const lit = codePointAt(pattern, i);
out.push({ lit });
i += lit.length - 1;
}
}
return out;
}
export function reachProofOf(t, start) {
const glob = t.regex ? undefined : globReachShape(t.value);
const shapes = t.regex ? reachShapes(t.value, t.dialect) : glob === undefined ? undefined : [glob];
const proof = shapes?.find((s) => shapeReachesEvery(s, start, t.caseless));
if (proof === undefined)
return undefined;
return `${t.regex ? `regex (${t.dialect})` : "path pattern"}: ${proof.every((p) => typeof p !== "object") ? "runs only (any path of two characters or more)" : "the start's own spelling, then runs"}`;
}
function shapeReachesEvery(shape, start, caseless) {
const lits = shape.flatMap((p) => (typeof p === "object" ? [p.lit] : []));
if (caseless && [start.spelled, ...lits].some((s) => /[^\x00-\x7f]/.test(s)))
return false;
const tail = (from, room) => {
const rest = shape.slice(from);
return rest.includes("run") && rest.every((p) => p === "run" || p === "one") && rest.filter((p) => p === "one").length <= room;
};
if (tail(0, 2))
return true;
if (start.rewritten === true)
return false;
const same = (a, b) => (caseless ? a.toLowerCase() === b.toLowerCase() : a === b);
return startSpellings(start).every((s) => {
const printed = s === "/" ? "/" : `${s}/`;
let k = 0;
for (; k < shape.length && k < printed.length; k++) {
const p = shape[k];
if (typeof p !== "object" || !same(p.lit, printed[k]))
break;
}
return k > 0 && tail(k, printed.length - k + 1);
});
}
const codePointAt = (s, i) => String.fromCodePoint(s.codePointAt(i));
const LITERAL_ESCAPE = /^[.[\]*^$\\/\-~,:;=@#%&!"]$/;
function reachShapes(re, dialect) {
const tokens = dialect === undefined || re.includes("\n") ? undefined : regexTokens(re);
if (tokens === undefined)
return undefined;
const [open, close, choice] = dialect === "basic" ? ["\\(", "\\)", undefined] : ["(", ")", "|"];
const countOf = (t) => t === "*" || (dialect === "extended" && (t === "?" || t === "+"));
let k = 0;
const cross = (a, b) => {
const out = a.flatMap((x) => b.map((y) => [...x, ...y]));
return out.length > MAX_BRANCHES ? undefined : out;
};
const alternatives = (inGroup) => {
let out = [];
for (;;) {
const s = sequence(inGroup);
if (s === undefined || (out = [...out, ...s]).length > MAX_BRANCHES)
return undefined;
if (choice === undefined || tokens[k] !== choice)
return out;
k++;
}
};
const sequence = (inGroup) => {
let acc = [[]];
let empty = true;
for (;;) {
const t = tokens[k];
if (t === undefined || t === choice || (inGroup && t === close))
return acc;
k++;
let item;
if (t === open) {
item = alternatives(true);
if (item === undefined || tokens[k] !== close)
return undefined;
k++;
}
else if (t === "^" || t === "$") {
const atEdge = !inGroup && (t === "^" ? empty : tokens[k] === undefined || tokens[k] === choice);
if (!atEdge)
return undefined;
continue;
}
else if (t === ".")
item = [["one"]];
else if (t.startsWith("\\")) {
if (t.length !== 2 || !LITERAL_ESCAPE.test(t[1]))
return undefined;
item = [[{ lit: t[1] }]];
}
else if (t.startsWith("[") || countOf(t) || t === "*" || (dialect === "basic" ? t === "+" || t === "?" : t === "{" || t === "}" || t === ")"))
return undefined;
else
item = [[{ lit: t }]];
const n = tokens[k];
if (countOf(n)) {
k++;
if (countOf(tokens[k]) || tokens[k] === "{" || tokens[k] === "\\{")
return undefined;
if (n !== "+")
item = t === "." && n === "*" ? [["run"]] : [[]];
else if (t === ".")
item = [["one", "run"]];
}
const next = cross(acc, item);
if (next === undefined)
return undefined;
acc = next;
empty = false;
}
};
const out = alternatives(false);
return out === undefined || k !== tokens.length ? undefined : out;
}
function regexTokens(re) {
const out = [];
for (let i = 0; i < re.length;) {
if (re[i] === "\\") {
out.push(re.slice(i, i + 2));
i += 2;
}
else if (re[i] === "[") {
const close = posixBracketEnd(re, i);
if (close < 0 || re.slice(i, close + 1).includes("\\"))
return undefined;
out.push(re.slice(i, close + 1));
i = close + 1;
}
else {
const c = codePointAt(re, i);
out.push(c);
i += c.length;
}
}
return out;
}
const COUNT_TOKENS = new Set(["*", "?", "+", "{", "\\?", "\\+", "\\{"]);
const MAX_BRANCHES = 64;
function regexBranches(re, dialect) {
const tokens = re.includes("\n") || dialect === undefined ? undefined : regexTokens(re);
if (tokens === undefined)
return undefined;
const [open, close, choice, other] = dialect === "basic" ? ["\\(", "\\)", "\\|", "|"] : ["(", ")", "|", "\\|"];
if (!tokens.includes(choice))
return [re];
if (tokens.includes(other))
return undefined;
let depth = 0;
for (const t of tokens)
if ((depth += t === open ? 1 : t === close ? -1 : 0) < 0)
return undefined;
if (depth !== 0)
return undefined;
const split = (list) => {
const out = [[]];
let d = 0;
for (const t of list) {
if (t === open)
d++;
if (t === close)
d--;
if (t === choice && d === 0)
out.push([]);
else
out.at(-1).push(t);
}
return out;
};
const out = [];
for (const top of split(tokens)) {
let partial = [[]];
for (let i = 0; i < top.length;) {
if (top[i] !== open) {
for (const p of partial)
p.push(top[i]);
i++;
continue;
}
let j = i + 1;
for (let d = 1; j < top.length; j++) {
if (top[j] === open)
d++;
if (top[j] === close && --d === 0)
break;
}
const inner = top.slice(i + 1, j);
const holds = inner.includes(choice);
if (holds && COUNT_TOKENS.has(top[j + 1] ?? ""))
return undefined;
const alternatives = holds ? split(inner) : [top.slice(i, j + 1)];
partial = partial.flatMap((p) => alternatives.map((a) => [...p, ...a]));
if (partial.length > MAX_BRANCHES)
return undefined;
i = j + 1;
}
out.push(...partial);
}
return out.length > MAX_BRANCHES ? undefined : out.map((b) => b.join(""));
}
function posixBracketEnd(re, i) {
let j = i + 1;
if (re[j] === "^")
j++;
if (re[j] === "]")
j++;
for (; j < re.length; j++) {
const unit = re[j] === "[" ? re[j + 1] : undefined;
if (unit === ":" || unit === "=" || unit === ".") {
const close = re.indexOf(`${unit}]`, j + 2);
if (close < 0)
return -1;
j = close + 1;
}
else if (re[j] === "]")
return j;
}
return -1;
}
export function failsOnStart(t, start) {
if (t.kind === "false")
return true;
if (t.kind !== "name" && t.kind !== "path")
return false;
if (start.rewritten === true)
return true;
if (t.kind === "path")
return !t.regex && !startSpellings(start).some((s) => globMatches(t.value, s, t.caseless));
const trimmed = start.spelled.replace(/\/+$/, "");
const name = trimmed === "" ? "/" : trimmed.slice(trimmed.lastIndexOf("/") + 1);
return !globMatches(t.value, name, t.caseless);
}
function globReading(pattern, name, caseless) {
const lit = (c) => c.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
let re = "";
let widened = false;
for (let i = 0; i < pattern.length; i++) {
const c = pattern[i];
const end = c === "[" ? bracketEnd(pattern, i) : -1;
if (c === "*")
re += "[\\s\\S]*";
else if (c === "?")
re += "[\\s\\S]";
else if (c === "\\" && i + 1 < pattern.length)
re += lit(pattern[++i]);
else if (end >= 0) {
const body = pattern.slice(i + 1, end);
const unit = /\[[:=.]/.test(body);
widened ||= unit;
re += unit ? "[\\s\\S]" : `[${/^[!^]/.test(body) ? "^" : ""}${body.replace(/^[!^]/, "").replace(/[\\\]]/g, "\\$&")}]`;
i = end;
}
else
re += lit(c);
}
try {
return !new RegExp(`^${re}$`, caseless ? "iu" : "u").test(name) ? "F" : widened ? "M" : "T";
}
catch {
return "M";
}
}
function globMatches(pattern, name, caseless) {
return globReading(pattern, name, caseless) !== "F";
}
function guardedActions(expr, count, holds) {
const out = new Array(count).fill(false);
const visit = (e, before) => {
switch (e.op) {
case "action":
out[e.at] = before;
return false;
case "test":
return holds(e.test);
case "not":
visit(e.of, before);
return false;
case "and": {
let held = false;
for (const c of e.of)
if (visit(c, before || held))
held = true;
return held;
}
case "or": {
let all = true;
for (const c of e.of)
if (!visit(c, before))
all = false;
return all;
}
default: {
let last = false;
for (const c of e.of)
last = visit(c, before);
return last;
}
}
};
visit(expr, false);
return out;
}
export function reachAt(a, start) {
if (a.expr === undefined)
return a.actions.map(() => ({ every: true, start: true }));
const n = a.actions.length;
const byDelete = guardedActions(a.expr, n, (t) => narrowsAt(t, start, true));
const byHand = guardedActions(a.expr, n, (t) => narrowsAt(t, start, false));
const off = guardedActions(a.expr, n, (t) => failsOnStart(t, start));
const atLevelZero = !(typeof a.depths.min === "number" && a.depths.min >= 1);
return a.actions.map((x, k) => ({ every: !(x.action === "-delete" ? byDelete[k] : byHand[k]), start: atLevelZero && !off[k] }));
}
const and3 = (a, b) => (a === "F" || b === "F" ? "F" : a === "T" && b === "T" ? "T" : "M");
const or3 = (a, b) => (a === "T" || b === "T" ? "T" : a === "F" && b === "F" ? "F" : "M");
const not3 = (a) => (a === "T" ? "F" : a === "F" ? "T" : "M");
export function findDirsDown(start, value, rel) {
const printed = start.rewritten === true ? [value.replace(/(.)\/+$/, "$1")] : startSpellings(start);
const top = (start.rewritten === true ? value : start.spelled).replace(/(.)\/+$/, "$1");
const dirs = [{ paths: printed, name: top === "/" ? "/" : top.slice(top.lastIndexOf("/") + 1), level: 0 }];
rel.forEach((name, k) => dirs.push({ paths: printed.map((p) => `${p === "/" ? "" : p}/${rel.slice(0, k + 1).join("/")}`), name, level: k + 1 }));
return { way: dirs.slice(0, -1), dir: dirs.at(-1) };
}
function plainRegex(re, caseless) {
let out = "";
let piece = false;
const end = re.endsWith("$") && !re.endsWith("\\$") ? re.length - 1 : re.length;
for (let i = re.startsWith("^") ? 1 : 0; i < end; i++) {
const c = re[i];
if (c === "*") {
if (!piece)
return undefined;
out += "*";
piece = false;
continue;
}
piece = true;
if (c === "\\") {
const n = re[i + 1];
if (n === undefined || !/[./\-_~,:;=@#%&!"]/.test(n))
return undefined;
out += escapeRegex(n);
i++;
}
else if (c === ".")
out += ".";
else if (c === "[") {
const close = re.indexOf("]", i + 1);
const body = close < 0 ? "" : re.slice(i + 1, close);
if (!/^\^?[A-Za-z0-9_./-]+$/.test(body))
return undefined;
out += `[${body}]`;
i = close;
}
else if ("+?{}()|^$]".includes(c))
return undefined;
else
out += escapeRegex(c);
}
try {
return new RegExp(`^(?:${out})$`, caseless ? "iu" : "u");
}
catch {
return undefined;
}
}
const mayReadOtherwise = (pattern, subjects) => [pattern, ...subjects].some((s) => /[^\x00-\x7f]/.test(s)) || /\[[^\]]*\\/.test(pattern);
function truthOn(t, dir) {
const on = (hits) => (hits.every((h) => h === "T") ? "T" : hits.every((h) => h === "F") ? "F" : "M");
switch (t.kind) {
case "name":
return mayReadOtherwise(t.value, [dir.name]) ? "M" : globReading(t.value, dir.name, t.caseless);
case "path": {
if (mayReadOtherwise(t.value, dir.paths))
return "M";
if (!t.regex)
return on(dir.paths.map((p) => globReading(t.value, p, t.caseless)));
if (t.dialect === undefined)
return "M";
const whole = plainRegex(t.value, t.caseless);
if (whole !== undefined)
return on(dir.paths.map((p) => (whole.test(p) ? "T" : "F")));
const branches = regexBranches(t.value, t.dialect);
if (branches === undefined)
return "M";
const plain = branches.map((b) => plainRegex(b, t.caseless));
return on(dir.paths.map((p) => plain.reduce((held, re) => or3(held, re === undefined ? "M" : re.test(p) ? "T" : "F"), "F")));
}
case "dirs":
case "true":
case "prune":
return "T";
case "false":
return "F";
default:
return "M";
}
}
function evaluatedOn(expr, count, truth) {
const actions = new Array(count).fill("F");
let prune = "F";
const visit = (e, reached) => {
switch (e.op) {
case "action":
actions[e.at] = reached;
return "M";
case "test":
if (e.test.kind === "prune")
prune = or3(prune, reached);
return truth(e.test);
case "not":
return not3(visit(e.of, reached));
case "and": {
let r = reached;
let v = "T";
for (const c of e.of) {
const x = visit(c, r);
v = and3(v, x);
r = and3(r, x);
}
return v;
}
case "or": {
let r = reached;
let v = "F";
for (const c of e.of) {
const x = visit(c, r);
v = or3(v, x);
r = and3(r, not3(x));
}
return v;
}
default: {
let v = "M";
for (const c of e.of)
v = visit(c, reached);
return v;
}
}
};
visit(expr, "T");
return { actions, prune };
}
const holdsQuit = (e) => (e.op === "test" ? e.test.kind === "quit" : e.op === "action" ? false : e.op === "not" ? holdsQuit(e.of) : e.of.some(holdsQuit));
export function certainlyRunOn(a, way, dir) {
const none = a.actions.map(() => false);
const { min = 0, max } = a.depths;
if (a.expr === undefined || holdsQuit(a.expr) || min === "unknown" || max === "unknown" || dir.level < min || (max !== undefined && dir.level > max) || (a.certainDepth !== undefined && dir.level > a.certainDepth))
return none;
const expr = a.expr;
const on = (d) => evaluatedOn(expr, a.actions.length, (t) => truthOn(t, d));
if (way.some((d) => on(d).prune !== "F"))
return none;
return on(dir).actions.map((r) => r === "T");
}
export const findStartsOf = (a, args) => (a.starts.length > 0 ? a.starts.map((k) => args[k]) : [FIND_DEFAULT_START]);
export function deletesEverythingFrom(a, args) {
if (!a.deletes)
return [];
return findStartsOf(a, args).filter((s) => reachAt(a, s).some((r, k) => a.actions[k].action === "-delete" && r.every));
}
export function findHandedLines(row, args) {
return [...new Set(findHandedCommands(row, args).map((c) => c.line))];
}
export function findHandedCommands(row, args) {
const a = findActionsOf(row, args);
if (a.handed.length === 0)
return [];
const starts = findStartsOf(a, args);
const reach = starts.map((s) => reachAt(a, s));
const out = [];
a.actions.forEach((h, k) => {
if (h.action === "-delete" || h.to <= h.from)
return;
const line = (entry) => args.slice(h.from, h.to).map((w) => withEntry(w, entry)).join(" ");
if (a.startsFromFile)
return void out.push({ line: line("{}"), action: k, start: 0, entry: "listed" });
starts.forEach((s, j) => {
const r = reach[j][k];
out.push(r.every ? { line: line(`${s.raw}/*`), action: k, start: j, entry: "every" } : { line: line(`${s.raw}/'{}'`), action: k, start: j, entry: "one" });
if (r.start)
out.push({ line: line(s.raw), action: k, start: j, entry: "start" });
});
});
return out;
}
function withEntry(w, entry) {
if (w.rewritten === true || !w.spelled.includes("{}"))
return w.raw;
if (w.spelled === "{}")
return entry;
if (w.raw === w.spelled)
return w.raw.split("{}").join(entry);
return w.spelled.split("{}").map((part) => (part === "" ? "" : `'${part.replace(/'/g, "'\\''")}'`)).join(entry);
}