// IS AN OPERATOR'S REGEX SAFE TO RUN ON EVERY RENDER? (demo epic D4, review // round 1, M1.) A conservative STATIC rule, checked once at compile time over // the JS source a `regex:` or `glob:` display rule compiles to — the // settings' aliases and the private scrub file's rules alike: // // - at most ONE unbounded-or-large quantifier (`*`, `+`, `{n,}`, `{n,m}` // with m > 64, lazy forms included); // - no backreference (`\1`, `\k`); // - no quantified group (one that may repeat) holding a quantifier or an // alternation; // - no lookahead or lookbehind (they read past a match, and so past the // windows display.ts cuts a long line into); // - the product of every quantifier's range (max − min + 1) AND of every // alternation's number of branches at most QUANTIFIER_PRODUCT_MAX, so // three `{0,64}` side by side, or twenty `(a|a)`, are refused too; // - at most OPTIONAL_GROUPS_MAX optional groups in a row (`(a)?(b)?…`); // - a match at most MATCH_MAX characters long: the one unbounded quantifier // is REWRITTEN to at most UNBOUNDED_CAP repeats (`.*` → `.{0,256}`), and // the longest possible match is computed and refused above MATCH_MAX — // which is what lets display.ts cut a long line into overlapping windows // that no match can straddle unseen. // // Anything else is refused; compile.ts then fails closed (the rule's literal // fragments shown as [hidden], the rule reported by its number). display.ts // also times every operator rule per call and disables one that is slow. // // Pure, no imports. export const UNBOUNDED_CAP = 256; export const LARGE_QUANTIFIER = 64; export const QUANTIFIER_PRODUCT_MAX = 1024; export const MATCH_MAX = 2048; export const OPTIONAL_GROUPS_MAX = 4; export type RegexVerdict = // capTrigger: a match at least this long MAY have used the rewritten // quantifier up to its cap — display.ts then hides to the end of the line, // never showing the rest of what the operator's pattern would have matched. // capProbe: the pattern up to and including the capped quantifier, that // quantifier at EXACTLY its cap — where it matches, the operator's pattern // may match past the cap, so display.ts hides from there to the line's end. | { ok: true; source: string; maxLen: number; capTrigger: number | null; capProbe: string | null } | { ok: false; why: string }; type Quant = { min: number; max: number; len: number; text: string }; function quantAt(re: string, i: number): Quant | null { const c = re[i]; let q: Quant | null = null; if (c === "*") q = { min: 0, max: Infinity, len: 1, text: "*" }; else if (c === "+") q = { min: 1, max: Infinity, len: 1, text: "+" }; else if (c === "?") q = { min: 0, max: 1, len: 1, text: "?" }; else if (c === "{") { const m = /^\{(\d+)(,(\d*))?\}/.exec(re.slice(i)); if (!m) return null; const min = Number(m[1]); const max = m[2] ? (m[3] === "" ? Infinity : Number(m[3])) : min; q = { min, max, len: m[0].length, text: m[0] }; } if (q && re[i + q.len] === "?") q = { ...q, len: q.len + 1, text: q.text + "?" }; return q; } type Node = { maxLen: number; minLen: number; hasQuant: boolean; hasAlt: boolean; out: string }; class Refused extends Error {} /** The verdict on one JS regex source (no flags needed: `u` is never set). */ export function analyzeRegex(re: string): RegexVerdict { let i = 0; let large = 0; let product = 1; // The capped quantifier's atom's shortest length, and its own minimum. let capped: { atomMin: number; qMin: number } | null = null; let probe: string | null = null; // The capped term's own atom, until the probe is written; top-level branches. let pendingProbeAtom: string | null = null; let topBranches = 1; // The groups open at this point: each one's prefix (what precedes it in its // own sequence, plus its head) and whether it holds the capped quantifier. const open: Array<{ prefix: string; holds: boolean }> = []; const bound = (what: string) => { if (product > QUANTIFIER_PRODUCT_MAX) throw new Refused(what); }; const quantify = (atom: Node, q: Quant, isGroup: boolean): Node => { const big = q.max === Infinity || q.max > LARGE_QUANTIFIER; if (big) large++; if (large > 1) throw new Refused("more than one unbounded or large quantifier"); if (isGroup && q.max > 1 && (atom.hasQuant || atom.hasAlt)) { throw new Refused("a repeated group holding a quantifier or an alternation"); } let max = q.max; let text = q.text; if (max === Infinity) { if (q.min > UNBOUNDED_CAP) throw new Refused("an unbounded quantifier with a minimum above the cap"); max = UNBOUNDED_CAP; text = `{${q.min},${UNBOUNDED_CAP}}${q.text.endsWith("?") && q.text !== "?" ? "?" : ""}`; // Its probe (capProbe) is the pattern up to it: well defined unless a // group around it has another branch (refused when that group closes). capped = { atomMin: atom.minLen, qMin: q.min }; pendingProbeAtom = atom.out; for (const o of open) o.holds = true; } product *= max - q.min + 1; bound("the quantifiers' ranges and alternations multiply past the bound"); return { maxLen: atom.maxLen * max, minLen: atom.minLen * q.min, hasQuant: true, hasAlt: atom.hasAlt, out: atom.out + text }; }; const parseAlternation = (inGroup: boolean): Node => { const alts: Node[] = [parseSequence()]; while (re[i] === "|") { i++; alts.push(parseSequence()); } if (inGroup && re[i] !== ")") throw new Refused("an unclosed group"); if (!inGroup) topBranches = alts.length; if (alts.length > 1) { product *= alts.length; bound("the quantifiers' ranges and alternations multiply past the bound"); } return { maxLen: Math.max(...alts.map((a) => a.maxLen)), minLen: Math.min(...alts.map((a) => a.minLen)), hasQuant: alts.some((a) => a.hasQuant), hasAlt: alts.length > 1 || alts.some((a) => a.hasAlt), out: alts.map((a) => a.out).join("|"), }; }; const parseSequence = (): Node => { const node: Node = { maxLen: 0, minLen: 0, hasQuant: false, hasAlt: false, out: "" }; let optionalRun = 0; while (i < re.length && re[i] !== "|" && re[i] !== ")") { const start = i; let atom: Node; let isGroup = false; let quantifiable = true; const c = re[i]; if (c === "(") { i++; let head = "("; if (/^\?(?:=|!|<=|)/.exec(re.slice(i)); if (m) { head += m[0]; i += m[0].length; } else if (re[i] === "?") throw new Refused("an unsupported group"); open.push({ prefix: node.out + head, holds: false }); const inner = parseAlternation(true); const closed = open.pop()!; if (closed.holds && inner.hasAlt && /\|/.test(inner.out)) { // (A conservative test: any `|` in the group's own source.) throw new Refused("an unbounded quantifier in one branch of an alternation"); } i++; // ")" atom = { maxLen: inner.maxLen, minLen: inner.minLen, hasQuant: inner.hasQuant, hasAlt: inner.hasAlt, out: `${head}${inner.out})` }; isGroup = true; } else if (c === "[") { let j = i + 1; if (re[j] === "^") j++; if (re[j] === "]") j++; while (j < re.length && re[j] !== "]") j += re[j] === "\\" ? 2 : 1; if (j >= re.length) throw new Refused("an unclosed character class"); atom = { maxLen: 1, minLen: 1, hasQuant: false, hasAlt: false, out: re.slice(i, j + 1) }; i = j + 1; } else if (c === "\\") { const n = re[i + 1]; if (n === undefined) throw new Refused("a trailing backslash"); if (/[1-9]/.test(n) || n === "k") throw new Refused("a backreference"); let len = 2; if (n === "x") len = 4; else if (n === "u") len = re[i + 2] === "{" ? re.indexOf("}", i) - i + 1 : 6; else if (n === "c") len = 3; const width = n === "b" || n === "B" ? 0 : 1; atom = { maxLen: width, minLen: width, hasQuant: false, hasAlt: false, out: re.slice(i, i + len) }; i += len; if (width === 0) quantifiable = false; } else if (c === "^" || c === "$") { atom = { maxLen: 0, minLen: 0, hasQuant: false, hasAlt: false, out: c }; i++; quantifiable = false; } else if (c === "*" || c === "+" || c === "?") { throw new Refused("a quantifier with nothing to repeat"); } else { atom = { maxLen: 1, minLen: 1, hasQuant: false, hasAlt: false, out: c }; i++; } const q = quantAt(re, i); if (q) { if (!quantifiable) throw new Refused("a quantified assertion"); i += q.len; atom = quantify(atom, q, isGroup); } // More than OPTIONAL_GROUPS_MAX optional groups in a row: refused (each // doubles the paths a failing match tries). if (isGroup && q && q.min === 0) { if (++optionalRun > OPTIONAL_GROUPS_MAX) throw new Refused(`more than ${OPTIONAL_GROUPS_MAX} optional groups in a row`); } else optionalRun = 0; if (i === start) throw new Refused("an unparsable pattern"); node.maxLen += atom.maxLen; node.minLen += atom.minLen; node.hasQuant ||= atom.hasQuant; node.hasAlt ||= atom.hasAlt; if (pendingProbeAtom !== null) { probe = `${open.map((o) => o.prefix).join("")}${node.out}${pendingProbeAtom}{${UNBOUNDED_CAP}}${")".repeat(open.length)}`; pendingProbeAtom = null; } node.out += atom.out; } return node; }; try { const top = parseAlternation(false); if (capped && topBranches > 1) throw new Refused("an unbounded quantifier in one branch of an alternation"); if (i < re.length) throw new Refused("an unbalanced parenthesis"); if (top.maxLen > MATCH_MAX) throw new Refused(`a match could be longer than ${MATCH_MAX.toLocaleString("en-US")} characters`); if (top.maxLen === 0) throw new Refused("it can only match the empty string"); // A match can only have used the capped quantifier up to its cap if it is // at least the pattern's shortest match plus the cap's extra repeats of // the atom's shortest form — a NECESSARY condition, so testing it never // misses a capped match (it may also catch an uncapped long one: strict). const c = capped as { atomMin: number; qMin: number } | null; const capTrigger = c ? top.minLen + (UNBOUNDED_CAP - c.qMin) * Math.max(1, c.atomMin) : null; return { ok: true, source: top.out, maxLen: top.maxLen, capTrigger, capProbe: c ? probe : null }; } catch (err) { if (err instanceof Refused) return { ok: false, why: err.message }; return { ok: false, why: "an unparsable pattern" }; } }