@dallaylaen/ski-interpreter 2.3.2 → 2.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/lib/ski-interpreter.cjs.js +29 -5
- package/lib/ski-interpreter.cjs.js.map +2 -2
- package/lib/ski-interpreter.esm.js +29 -5
- package/lib/ski-interpreter.esm.js.map +2 -2
- package/lib/ski-interpreter.min.js +3 -3
- package/lib/ski-interpreter.min.js.map +3 -3
- package/lib/ski-quest.min.js +3 -3
- package/lib/ski-quest.min.js.map +3 -3
- package/package.json +1 -1
- package/types/src/expr.d.ts +25 -0
- package/types/src/extras.d.ts +0 -14
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/internal.js", "../../../src/expr.js", "../../../src/parser.js", "../../../src/quest.js", "../../../src/extras.js", "../../../index.js"],
|
|
4
|
-
"sourcesContent": ["class Tokenizer {\n /**\n * @desc Create a tokenizer that splits strings into tokens according to the given terms.\n * The terms are interpreted as regular expressions, and are sorted by length\n * to ensure that longer matches are preferred over shorter ones.\n * @param {...string|RegExp} terms\n */\n constructor (...terms) {\n const src = '$|(\\\\s+)|' + terms\n .map(s => '(?:' + s + ')')\n .sort((a, b) => b.length - a.length)\n .join('|');\n this.rex = new RegExp(src, 'gys');\n }\n\n /**\n * @desc Split the given string into tokens according to the terms specified in the constructor.\n * @param {string} str\n * @return {string[]}\n */\n split (str) {\n this.rex.lastIndex = 0;\n const list = [...str.matchAll(this.rex)];\n\n // did we parse everything?\n const eol = list.pop();\n const last = eol?.index ?? 0;\n\n if (last !== str.length) {\n throw new Error('Unknown tokens at pos ' + last + '/' + str.length\n + ' starting with ' + str.substring(last));\n }\n\n // skip whitespace\n return list.filter(x => x[1] === undefined).map(x => x[0]);\n }\n}\n\nconst tokRestrict = new Tokenizer('[-=+]', '[A-Z]', '\\\\b[a-z_][a-z_0-9]*\\\\b');\n\n/**\n * @desc Add ot remove tokens from a set according to a spec string.\n * The spec string is a sequence of tokens, with each group optionally prefixed\n * by one of the operators '=', '+', or '-'.\n * The '=' operator resets the set to contain only the following token(s).\n * @param {Set<string>} set\n * @param {string} [spec]\n * @returns {Set<string>}\n */\nfunction restrict (set, spec) {\n if (!spec)\n return set;\n let out = new Set([...set]);\n const act = {\n '=': sym => { out = new Set([sym]); mode = '+'; },\n '+': sym => { out.add(sym); },\n '-': sym => { out.delete(sym); },\n };\n\n let mode = '=';\n for (const sym of tokRestrict.split(spec)) {\n if (act[sym])\n mode = sym;\n else\n act[mode](sym);\n }\n return out;\n}\n\nclass TraverseControl {\n /**\n * @desc A wrapper for values returned by fold/traverse callbacks\n * which instructs the traversal to alter its behavior while\n * retaining the value in question.\n *\n * This class is instantiated internally be `SKI.control.*` functions,\n * and is not intended to be used directly by client code.\n *\n * @template T\n * @param {T} value\n * @param {function(T): TraverseControl<T>} decoration\n */\n constructor (value, decoration) {\n this.value = value;\n this.decoration = decoration;\n }\n}\n\n/**\n * @private\n * @template T\n * @param {T|TraverseControl<T>|null} value\n * @returns {[T?, function|undefined]}\n */\nfunction unwrap (value) {\n // `?? undefined` so that null is not 'an object'\n if (value instanceof TraverseControl)\n return [value.value ?? undefined, value.decoration];\n return [value ?? undefined, undefined];\n}\n\n/**\n * @desc Prepare a self-referencing wrapper function for use as a fold/traverse control decorator.\n *\n * If `fun` is created by `prepareWrapper`, then\n * unwrap(fun(x)) will always return exactly [x, fun], and the second value can be checked with ===.\n *\n * An optional label can be provided for debugging purposes.\n *\n * @private\n * @template T\n * @param {string} [label]\n * @returns {function(T): TraverseControl<T>}\n */\nfunction prepareWrapper (label) {\n const fun = value => new TraverseControl(value, fun);\n fun.label = label;\n fun.toString = () => 'TraverseControl::' + label;\n return fun;\n}\n\nmodule.exports = { Tokenizer, restrict, unwrap, prepareWrapper };\n", "'use strict';\n\nconst { unwrap, prepareWrapper } = require('./internal');\n\nconst DEFAULTS = {\n max: 1000,\n maxArgs: 32,\n};\n\nconst ORDER = {\n 'leftmost-outermost': 'LO',\n 'leftmost-innermost': 'LI',\n LO: 'LO',\n LI: 'LI',\n};\n\n/**\n * @template T\n * @typedef {T | TraverseControl<T> | null} TraverseValue\n */\n/**\n * @desc Control primitives for fold() and traverse() methods.\n * @template T\n * @type {{[name: string]: function(T): TraverseControl<T>}}\n */\nconst control = {\n descend: prepareWrapper('descend'),\n prune: prepareWrapper('prune'),\n redo: prepareWrapper('redo'),\n stop: prepareWrapper('stop'),\n};\n\n/**\n * @desc List of predefined native combinators.\n * This is required for toSKI() to work, otherwise could as well have been in parser.js.\n * @type {{[key: string]: Native}}\n */\nconst native = {};\n\n/**\n * @typedef {Expr | function(Expr): Partial} Partial\n */\n\n/**\n * @typedef {{\n * normal: boolean, // whether the term becomes irreducible after receiving a number of arguments.\n * // if false, other properties may be missing.\n * proper: boolean, // whether the irreducible form is only contains its arguments. implies normal.\n * arity?: number, // the number of arguments that is sufficient to reach the normal form\n * // absent unless normal.\n * discard?: boolean, // whether the term (or subterms, unless proper) can discard arguments.\n * duplicate?: boolean, // whether the term (or subterms, unless proper) can duplicate arguments.\n * skip?: Set<number>, // indices of arguments that are discarded. nonempty inplies discard.\n * dup?: Set<number>, // indices of arguments that are duplicated. nonempty implies duplicate.\n * expr?: Expr, // canonical form containing lambdas, applications, and variables, if any\n * steps?: number, // number of steps taken to obtain the aforementioned information, if applicable\n * }} TermInfo\n */\n\nclass Expr {\n /**\n * @descr A combinatory logic expression.\n *\n * Applications, variables, and other terms like combinators per se\n * are subclasses of this class.\n *\n * @abstract\n * @property {{\n * scope?: any,\n * env?: { [key: string]: Expr },\n * src?: string,\n * parser: object,\n * }} [context]\n * @property {number} [arity] - number of arguments the term is waiting for (if known)\n * @property {string} [note] - a brief description what the term does\n * @property {string} [fancyName] - how to display in html mode, e.g. φ instead of 'f'\n * Typically only applicable to descendants of Named.\n * @property {TermInfo} [props] - properties inferred from the term's behavior\n */\n\n /**\n *\n * @desc Define properties of the term based on user supplied options and/or inference results.\n * Typically useful for declaring Native and Alias terms.\n * @private\n * @param {Object} options\n * @param {string} [options.note] - a brief description what the term does\n * @param {number} [options.arity] - number of arguments the term is waiting for (if known)\n * @param {string} [options.fancy] - how to display in html mode, e.g. φ instead of 'f'\n * @param {boolean} [options.canonize] - whether to try to infer the properties\n * @param {number} [options.max] - maximum number of steps for inference, if canonize is true\n * @param {number} [options.maxArgs] - maximum number of arguments for inference, if canonize is true\n * @return {this}\n */\n _setup (options = {}) {\n // TODO better name\n\n if (options.fancy !== undefined)\n this.fancyName = options.fancyName;\n\n if (options.note !== undefined)\n this.note = options.note;\n\n if (options.arity !== undefined)\n this.arity = options.arity;\n\n if (options.canonize) {\n const guess = this.infer(options);\n if (guess.normal) {\n this.arity = this.arity ?? guess.arity;\n this.note = this.note ?? guess.expr.format({ html: true, lambda: ['', ' ↦ ', ''] });\n delete guess.steps;\n this.props = guess;\n }\n }\n return this;\n }\n\n /**\n * @desc apply self to zero or more terms and return the resulting term,\n * without performing any calculations whatsoever\n * @param {Expr} args\n * @return {Expr}\n */\n apply (...args) {\n let expr = this;\n for (const arg of args)\n expr = new App(expr, arg);\n return expr;\n }\n\n /**\n * @desc Replace all aliases in the expression with their definitions, recursively.\n * @return {Expr}\n */\n expand () {\n return this.traverse(e => {\n if (e instanceof Alias)\n return e.impl.expand();\n }) ?? this;\n }\n\n /**\n * @desc Returns true if the expression contains only free variables and applications, false otherwise.\n * @returns {boolean}\n */\n freeOnly () {\n return !this.any(e => !(e instanceof FreeVar || e instanceof App));\n }\n\n /**\n * @desc Traverse the expression tree, applying change() to each node.\n * If change() returns an Expr, the node is replaced with that value.\n * A null/undefined value is interpreted as\n * \"descend further if applicable, or leave the node unchanged\".\n *\n * Returned values may be decorated:\n *\n * SKI.control.prune will suppress further descending even if nothing was returned\n * SKI.control.stop will terminate further changes.\n * SKI.control.redo will apply the callback to the returned subtree, recursively.\n *\n * Note that if redo was applied at least once to a subtree, a null return from the same subtree\n * will be replaced by the last non-null value returned.\n *\n * The traversal order is leftmost-outermost, unless options.order = 'leftmost-innermost' is specified.\n * Short aliases 'LO' and 'LI' (case-sensitive) are also accepted.\n *\n * Returns null if no changes were made, or the new expression otherwise.\n *\n * @param {{\n * order?: 'LO' | 'LI' | 'leftmost-outermost' | 'leftmost-innermost',\n * }} [options]\n * @param {(e:Expr) => TraverseValue<Expr>} change\n * @returns {Expr|null}\n */\n traverse (options, change) {\n if (typeof options === 'function') {\n change = options;\n options = {};\n }\n const order = ORDER[options.order ?? 'LO'];\n if (order === undefined)\n throw new Error('Unknown traversal order: ' + options.order);\n const [expr, _] = unwrap(this._traverse_redo({ order }, change));\n return expr;\n }\n\n /**\n * @private\n * @param {Object} options\n * @param {(e:Expr) => TraverseValue<Expr>} change\n * @returns {TraverseValue<Expr>}\n */\n _traverse_redo (options, change) {\n let action;\n let expr = this;\n let prev;\n do {\n prev = expr;\n const next = options.order === 'LI'\n ? expr._traverse_descend(options, change) ?? change(expr)\n : change(expr) ?? expr._traverse_descend(options, change);\n [expr, action] = unwrap(next);\n } while (expr && action === control.redo);\n if (!expr && prev !== this)\n expr = prev; // we were in redo at least once\n return action ? action(expr) : expr;\n }\n\n /**\n * @private\n * @param {Object} options\n * @param {(e:Expr) => TraverseValue<Expr>} change\n * @returns {TraverseValue<Expr>}\n */\n\n _traverse_descend (options, change) {\n return null;\n }\n\n /**\n * @desc Returns true if predicate() is true for any subterm of the expression, false otherwise.\n *\n * @param {(e: Expr) => boolean} predicate\n * @returns {boolean}\n */\n any (predicate) {\n return predicate(this);\n }\n\n /**\n * @desc Fold the expression into a single value by recursively applying combine() to its subterms.\n * Nodes are traversed in leftmost-outermost order, i.e. the same order as reduction steps are taken.\n *\n * null or undefined return value from combine() means \"keep current value and descend further\".\n *\n * SKI.control provides primitives to control the folding flow:\n * - SKI.control.prune(value) means \"use value and don't descend further into this branch\";\n * - SKI.control.stop(value) means \"stop folding immediately and return value\".\n * - SKI.control.descend(value) is the default behavior, meaning \"use value and descend further\".\n *\n * This method is experimental and may change in the future.\n *\n * @experimental\n * @template T\n * @param {T} initial\n * @param {(acc: T, expr: Expr) => TraverseValue<T>} combine\n * @returns {T}\n */\n fold (initial, combine) {\n const [value, _] = unwrap(this._fold(initial, combine));\n return value ?? initial;\n }\n\n /**\n * @template T\n * @param {T} initial\n * @param {(acc: T, expr: Expr) => TraverseValue<T>} combine\n * @returns {TraverseValue<T>}\n * @private\n */\n _fold (initial, combine) {\n return combine(initial, this);\n }\n\n /**\n * @desc rough estimate of the term's complexity\n * @return {number}\n */\n weight () {\n // TODO remove in next breaking release\n return 1;\n }\n\n /**\n * @desc Try to empirically find an equivalent lambda term for the expression,\n * returning also the term's arity and some other properties.\n *\n * This is used internally when declaring a Native / Alias term,\n * unless {canonize: false} is used.\n *\n * As of current it only recognizes terms that have a normal form,\n * perhaps after adding some variables. This may change in the future.\n *\n * Use toLambda() if you want to get a lambda term in any case.\n *\n * @param {{max?: number, maxArgs?: number}} options\n * @return {TermInfo}\n */\n infer (options = {}) {\n return this._infer({\n max: options.max ?? DEFAULTS.max,\n maxArgs: options.maxArgs ?? DEFAULTS.maxArgs,\n }, 0);\n }\n\n /**\n * @desc Internal method for infer(), which performs the actual inference.\n * @param {{max: number, maxArgs: number}} options\n * @param {number} nargs - var index to avoid name clashes\n * @returns {TermInfo}\n * @private\n */\n _infer (options, nargs) {\n const probe = [];\n let steps = 0;\n let expr = this;\n // eslint-disable-next-line no-labels\n main: for (let i = 0; i < options.maxArgs; i++) {\n const next = expr.run({ max: options.max - steps });\n // console.log(`infer step ${i}, expr = ${expr}, probe = [${probe}]: `, next);\n steps += next.steps;\n if (!next.final)\n break;\n if (firstVar(next.expr)) {\n // can't append more variables, return or recurse\n expr = next.expr;\n if (!expr.any(e => !(e instanceof FreeVar || e instanceof App)))\n return maybeLambda(probe, expr, { steps });\n const list = expr.unroll();\n let discard = false;\n let duplicate = false;\n const acc = [];\n for (let j = 1; j < list.length; j++) {\n const sub = list[j]._infer(\n { maxArgs: options.maxArgs - nargs, max: options.max - steps }, // limit recursion\n nargs + i // avoid variable name clashes\n );\n steps += sub.steps;\n if (!sub.expr)\n // eslint-disable-next-line no-labels\n break main; // press f to pay respects\n if (sub.discard)\n discard = true;\n if (sub.duplicate)\n duplicate = true;\n acc.push(sub.expr);\n }\n return maybeLambda(probe, list[0].apply(...acc), { discard, duplicate, steps });\n }\n const push = nthvar(nargs + i);\n probe.push(push);\n expr = next.expr.apply(push);\n }\n return { normal: false, proper: false, steps };\n }\n\n /**\n * @desc Expand an expression into a list of terms\n * that give the initial expression when applied from left to right:\n * ((a, b), (c, d)) => [a, b, (c, d)]\n *\n * This can be thought of as an opposite of apply:\n * fun.apply(...arg).unroll() is exactly [fun, ...args]\n * (even if ...arg is in fact empty).\n *\n * @returns {Expr[]}\n */\n unroll () {\n // currently only used by infer() but may be useful\n // to convert binary App trees to n-ary or smth\n return [this];\n }\n\n /**\n * @desc Returns a series of lambda terms equivalent to the given expression,\n * up to the provided computation steps limit,\n * in decreasing weight order.\n *\n * Unlike infer(), this method will always return something,\n * even if the expression has no normal form.\n *\n * See also Expr.walk() and Expr.toSKI().\n *\n * @param {{\n * max?: number,\n * maxArgs?: number,\n * varGen?: function(void): FreeVar,\n * steps?: number,\n * html?: boolean,\n * latin?: number,\n * }} options\n * @param {number} [maxWeight] - maximum allowed weight of terms in the sequence\n * @return {IterableIterator<{expr: Expr, steps?: number, comment?: string}>}\n */\n * toLambda (options = {}) {\n let expr = this.traverse(e => {\n if (e instanceof FreeVar || e instanceof App || e instanceof Lambda || e instanceof Alias)\n return null; // no change\n const guess = e.infer({ max: options.max, maxArgs: options.maxArgs });\n if (!guess.normal)\n throw new Error('Failed to infer an equivalent lambda term for ' + e);\n return guess.expr;\n }) ?? this;\n const seen = new Set(); // prine irreducible\n let steps = 0;\n while (expr) {\n const next = expr.traverse({ order: 'LI' }, e => {\n if (seen.has(e))\n return null;\n if (e instanceof App && e.fun instanceof Lambda) {\n const guess = e.infer({ max: options.max, maxArgs: options.maxArgs });\n steps += guess.steps;\n if (!guess.normal) {\n seen.add(e);\n return null;\n }\n return control.stop(guess.expr);\n }\n });\n yield { expr, steps };\n expr = next;\n }\n }\n\n /**\n * @desc Rewrite the expression into S, K, and I combinators step by step.\n * Returns an iterator yielding the intermediate expressions,\n * along with the number of steps taken to reach them.\n *\n * See also Expr.walk() and Expr.toLambda().\n *\n * @param {{max?: number}} [options]\n * @return {IterableIterator<{final: boolean, expr: Expr, steps: number}>}\n */\n * toSKI (options = {}) {\n // TODO options.max is not actually max, it's the number of steps in one iteration\n // get rid of non-lambdas\n let expr = this.traverse(e => {\n if (e instanceof FreeVar || e instanceof App || e instanceof Lambda || e instanceof Alias)\n return null;\n // TODO infer failed for atomic term? die...\n return e.infer().expr;\n }) ?? this;\n\n let steps = 0;\n while (expr) {\n const next = expr.traverse({ order: 'LI' }, e => {\n if (!(e instanceof Lambda) || (e.impl instanceof Lambda))\n return null; // continue\n if (e.impl === e.arg)\n return control.stop(native.I);\n if (!e.impl.any(t => t === e.arg))\n return control.stop(native.K.apply(e.impl));\n // TODO use real assert here. e.impl contains e.arg and also isn't e.arg, in MUST be App.\n if (!(e.impl instanceof App))\n throw new Error('toSKI: assert failed: lambda body is of unexpected type ' + e.impl.constructor.name );\n // eta-reduction: body === (not e.arg) (e.arg)\n if (e.impl.arg === e.arg && !e.impl.fun.any(t => t === e.arg))\n return control.stop(e.impl.fun);\n // last resort, go S\n return control.stop(native.S.apply(new Lambda(e.arg, e.impl.fun), new Lambda(e.arg, e.impl.arg)));\n })\n yield { expr, steps, final: !next };\n steps++;\n expr = next;\n }\n }\n\n /**\n * Replace all instances of plug in the expression with value and return the resulting expression,\n * or null if no changes could be made.\n * Lambda terms and applications will never match if used as plug\n * as they are impossible co compare without extensive computations.\n * Typically used on variables but can also be applied to other terms, e.g. aliases.\n * See also Expr.traverse().\n * @param {Expr} search\n * @param {Expr} replace\n * @return {Expr|null}\n */\n subst (search, replace) {\n return this === search ? replace : null;\n }\n\n /**\n * @desc Apply term reduction rules, if any, to the given argument.\n * A returned value of null means no reduction is possible.\n * A returned value of Expr means the reduction is complete and the application\n * of this and arg can be replaced with the result.\n * A returned value of a function means that further arguments are needed,\n * and can be cached for when they arrive.\n *\n * This method is between apply() which merely glues terms together,\n * and step() which reduces the whole expression.\n *\n * foo.invoke(bar) is what happens inside foo.apply(bar).step() before\n * reduction of either foo or bar is attempted.\n *\n * The name 'invoke' was chosen to avoid confusion with either 'apply' or 'reduce'.\n *\n * @param {Expr} arg\n * @returns {Partial | null}\n */\n invoke (arg) {\n return null;\n }\n\n /**\n * @desc iterate one step of a calculation.\n * @return {{expr: Expr, steps: number, changed: boolean}}\n */\n step () { return { expr: this, steps: 0, changed: false } }\n\n /**\n * @desc Run uninterrupted sequence of step() applications\n * until the expression is irreducible, or max number of steps is reached.\n * Default number of steps = 1000.\n * @param {{max?: number, steps?: number, throw?: boolean}|Expr} [opt]\n * @param {Expr} args\n * @return {{expr: Expr, steps: number, final: boolean}}\n */\n run (opt = {}, ...args) {\n if (opt instanceof Expr) {\n args.unshift(opt);\n opt = {};\n }\n let expr = args ? this.apply(...args) : this;\n let steps = opt.steps ?? 0;\n // make sure we make at least 1 step, to tell whether we've reached the normal form\n const max = Math.max(opt.max ?? DEFAULTS.max, 1) + steps;\n let final = false;\n for (; steps < max; ) {\n const next = expr.step();\n if (!next.changed) {\n final = true;\n break;\n }\n steps += next.steps;\n expr = next.expr;\n }\n if (opt.throw && !final)\n throw new Error('Failed to compute expression in ' + max + ' steps');\n return { final, steps, expr };\n }\n\n /**\n * Execute step() while possible, yielding a brief description of events after each step.\n * Mnemonics: like run() but slower.\n * @param {{max?: number}} options\n * @return {IterableIterator<{final: boolean, expr: Expr, steps: number}>}\n */\n * walk (options = {}) {\n const max = options.max ?? Infinity;\n let steps = 0;\n let expr = this;\n let final = false;\n\n while (steps < max) {\n // 1. calculate\n // 2. yield _unchanged_ expression\n // 3. either advance or stop\n const next = expr.step();\n if (!next.changed)\n final = true;\n yield { expr, steps, final };\n if (final)\n break;\n steps += next.steps;\n expr = next.expr;\n }\n }\n\n /**\n * @desc True is the expressions are identical, false otherwise.\n * Aliases are expanded.\n * Bound variables in lambda terms are renamed consistently.\n * However, no reductions are attempted.\n *\n * E.g. a->b->a == x->y->x is true, but a->b->a == K is false.\n *\n * @param {Expr} other\n * @return {boolean}\n */\n equals (other) {\n return !this.diff(other);\n }\n\n /**\n * @desc Recursively compare two expressions and return a string\n * describing the first point of difference.\n * Returns null if expressions are identical.\n *\n * Aliases are expanded.\n * Bound variables in lambda terms are renamed consistently.\n * However, no reductions are attempted.\n *\n * Members of the FreeVar class are considered different\n * even if they have the same name, unless they are the same object.\n * To somewhat alleviate confusion, the output will include\n * the internal id of the variable in square brackets.\n *\n * @example \"K(S != I)\" is the result of comparing \"KS\" and \"KI\"\n * @example \"S(K([x[13] != x[14]]))K\"\n *\n * @param {Expr} other\n * @param {boolean} [swap] If true, the order of expressions is reversed in the output.\n * @returns {string|null}\n */\n diff (other, swap = false) {\n if (this === other)\n return null;\n if (other instanceof Alias)\n return other.impl.diff(this, !swap);\n return swap\n ? '[' + other + ' != ' + this + ']'\n : '[' + this + ' != ' + other + ']';\n }\n\n /**\n * @desc Assert expression equality. Can be used in tests.\n *\n * `this` is the expected value and the argument is the actual one.\n * Mnemonic: the expected value is always a combinator, the actual one may be anything.\n *\n * @param {Expr} actual\n * @param {string} comment\n */\n expect (actual, comment = '') {\n comment = comment ? comment + ': ' : '';\n if (!(actual instanceof Expr)) {\n throw new Error(comment + 'Expected a combinator but found '\n + (actual?.constructor?.name ?? typeof actual));\n }\n const diff = this.diff(actual);\n if (!diff)\n return; // all good\n\n // TODO wanna use AssertionError but browser doesn't recognize it\n // still the below hack works for mocha-based tests.\n const poorMans = new Error(comment + diff);\n poorMans.expected = this.diag();\n poorMans.actual = actual.diag();\n throw poorMans;\n }\n\n /**\n * @desc Returns string representation of the expression.\n * Same as format() without options.\n * @return {string}\n */\n toString () {\n return this.format();\n }\n\n /**\n * @desc Whether the expression needs parentheses when printed.\n * @param {boolean} [first] - whether this is the first term in a sequence\n * @return {boolean}\n */\n _braced (first) {\n return false;\n }\n\n /**\n * @desc Whether the expression can be printed without a space when followed by arg.\n * @param {Expr} arg\n * @returns {boolean}\n * @private\n */\n _unspaced (arg) {\n return this._braced(true);\n }\n\n /**\n * @desc Stringify the expression with fancy formatting options.\n * Said options mostly include wrappers around various constructs in form of ['(', ')'],\n * as well as terse and html flags that set up the defaults.\n * Format without options is equivalent to toString() and can be parsed back.\n *\n * @param {Object} [options] - formatting options\n * @param {boolean} [options.terse] - whether to use terse formatting (omitting unnecessary spaces and parentheses)\n * @param {boolean} [options.html] - whether to default to HTML tags & entities.\n * If a named term has fancyName property set, it will be used instead of name in this mode.\n * @param {[string, string]} [options.brackets] - wrappers for application arguments, typically ['(', ')']\n * @param {[string, string]} [options.var] - wrappers for variable names\n * (will default to <var> and </var> in html mode).\n * @param {[string, string, string]} [options.lambda] - wrappers for lambda abstractions, e.g. ['λ', '.', '']\n * where the middle string is placed between argument and body\n * default is ['', '->', ''] or ['', '->', ''] for html\n * @param {[string, string]} [options.around] - wrappers around (sub-)expressions.\n * individual applications will not be wrapped, i.e. (a b c) but not ((a b) c)\n * @param {[string, string]} [options.redex] - wrappers around the starting term(s) that have enough arguments to be reduced\n * @param {Object<string, Expr>} [options.inventory] - if given, output aliases in the set as their names\n * and any other aliases as the expansion of their definitions.\n * The default is a cryptic and fragile mechanism dependent on a hidden mutable property.\n * @returns {string}\n *\n * @example foo.format() // equivalent to foo.toString()\n * @example foo.format({terse: false}) // spell out all parentheses\n * @example foo.format({html: true}) // use HTML tags and entities\n * @example foo.format({ around: ['(', ')'], brackets: ['', ''], lambda: ['(', '->', ')'] }) // lisp style, still back-parsable\n * @exapmle foo.format({ lambda: ['λ', '.', ''] }) // pretty-print for the math department\n * @example foo.format({ lambda: ['', '=>', ''], terse: false }) // make it javascript\n * @example foo.format({ inventory: { T } }) // use T as a named term, expand all others\n *\n */\n format (options = {}) {\n const fallback = options.html\n ? {\n brackets: ['(', ')'],\n space: ' ',\n var: ['<var>', '</var>'],\n lambda: ['', '->', ''],\n around: ['', ''],\n redex: ['', ''],\n }\n : {\n brackets: ['(', ')'],\n space: ' ',\n var: ['', ''],\n lambda: ['', '->', ''],\n around: ['', ''],\n redex: ['', ''],\n }\n return this._format({\n terse: options.terse ?? true,\n brackets: options.brackets ?? fallback.brackets,\n space: options.space ?? fallback.space,\n var: options.var ?? fallback.var,\n lambda: options.lambda ?? fallback.lambda,\n around: options.around ?? fallback.around,\n redex: options.redex ?? fallback.redex,\n inventory: options.inventory, // TODO better name\n html: options.html ?? false,\n }, 0);\n }\n\n /**\n * @desc Internal method for format(), which performs the actual formatting.\n * @param {Object} options\n * @param {number} nargs\n * @returns {string}\n * @private\n */\n _format (options, nargs) {\n throw new Error( 'No _format() method defined in class ' + this.constructor.name );\n }\n\n /**\n * @desc Returns a string representation of the expression tree, with indentation to show structure.\n *\n * Applications are flattened to avoid excessive nesting.\n * Variables include ids to distinguish different instances of the same variable name.\n *\n * May be useful for debugging.\n *\n * @returns {string}\n *\n * @example\n * > console.log(ski.parse('C 5 x (x->x x)').diag())\n * App:\n * Native: C\n * Church: 5\n * FreeVar: x[53]\n * Lambda (x[54]):\n * App:\n * FreeVar: x[54]\n * FreeVar: x[54]\n */\n diag () {\n const rec = (e, indent) => {\n if (e instanceof App)\n return [indent + 'App:', ...e.unroll().flatMap(s => rec(s, indent + ' '))];\n if (e instanceof Lambda)\n return [`${indent}Lambda (${e.arg}[${e.arg.id}]):`, ...rec(e.impl, indent + ' ')];\n // no indent increase so that a diff between diags is consistent with how `equals` works.\n if (e instanceof Alias)\n return [`${indent}Alias (${e.name}): \\\\`, ...rec(e.impl, indent)];\n if (e instanceof FreeVar)\n return [`${indent}FreeVar: ${e.name}[${e.id}]`];\n return [`${indent}${e.constructor.name}: ${e}`];\n }\n\n const out = rec(this, '');\n return out.join('\\n');\n }\n\n /**\n * @desc Convert the expression to a JSON-serializable format.\n * @returns {string}\n */\n toJSON () {\n return this.format();\n }\n}\n\nclass App extends Expr {\n /**\n * @desc Application of fun() to args.\n * Never ever use new App(fun, arg) directly, use fun.apply(...args) instead.\n * @param {Expr} fun\n * @param {Expr} arg\n */\n constructor (fun, arg) {\n super();\n\n this.arg = arg;\n this.fun = fun;\n }\n /** @property {boolean} [final] */\n\n weight () {\n return this.fun.weight() + this.arg.weight();\n }\n\n _traverse_descend (options, change) {\n const [fun, fAction] = unwrap(this.fun._traverse_redo(options, change));\n if (fAction === control.stop)\n return control.stop(fun ? fun.apply(this.arg) : null);\n\n const [arg, aAction] = unwrap(this.arg._traverse_redo(options, change));\n\n const final = (fun || arg) ? (fun ?? this.fun).apply(arg ?? this.arg) : null;\n if (aAction === control.stop)\n return control.stop(final);\n return final;\n }\n\n any (predicate) {\n return predicate(this) || this.fun.any(predicate) || this.arg.any(predicate);\n }\n\n _fold (initial, combine) {\n const [value = initial, action = 'descend'] = unwrap(combine(initial, this));\n if (action === control.prune)\n return value;\n if (action === control.stop)\n return control.stop(value);\n const [fValue = value, fAction = 'descend'] = unwrap(this.fun._fold(value, combine));\n if (fAction === control.stop)\n return control.stop(fValue);\n const [aValue = fValue, aAction = 'descend'] = unwrap(this.arg._fold(fValue, combine));\n if (aAction === control.stop)\n return control.stop(aValue);\n return aValue;\n }\n\n subst (search, replace) {\n const fun = this.fun.subst(search, replace);\n const arg = this.arg.subst(search, replace);\n\n return (fun || arg) ? (fun ?? this.fun).apply(arg ?? this.arg) : null;\n }\n\n /**\n * @return {{expr: Expr, steps: number}}\n */\n\n step () {\n // normal reduction order: first try root, then at most 1 step\n if (!this.final) {\n // try to apply rewriting rules, if applicable, at first\n const partial = this.fun.invoke(this.arg);\n if (partial instanceof Expr)\n return { expr: partial, steps: 1, changed: true };\n else if (typeof partial === 'function')\n this.invoke = partial; // cache for next time\n\n // descend into the leftmost term\n const fun = this.fun.step();\n if (fun.changed)\n return { expr: fun.expr.apply(this.arg), steps: fun.steps, changed: true };\n\n // descend into arg\n const arg = this.arg.step();\n if (arg.changed)\n return { expr: this.fun.apply(arg.expr), steps: arg.steps, changed: true };\n\n // mark as irreducible\n this.final = true; // mark as irreducible at root\n }\n\n return { expr: this, steps: 0, changed: false };\n }\n\n invoke (arg) {\n // propagate invocation towards the root term,\n // caching partial applications as we go\n const partial = this.fun.invoke(this.arg);\n if (partial instanceof Expr)\n return partial.apply(arg);\n else if (typeof partial === 'function') {\n this.invoke = partial;\n return partial(arg);\n } else {\n // invoke = null => we're uncomputable, cache for next time\n this.invoke = _ => null;\n return null;\n }\n }\n\n unroll () {\n return [...this.fun.unroll(), this.arg];\n }\n\n diff (other, swap = false) {\n if (!(other instanceof App))\n return super.diff(other, swap);\n\n const fun = this.fun.diff(other.fun, swap);\n if (fun)\n return fun + '(...)';\n const arg = this.arg.diff(other.arg, swap);\n if (arg)\n return this.fun + '(' + arg + ')';\n return null;\n }\n\n _braced (first) {\n return !first;\n }\n\n _format (options, nargs) {\n const fun = this.fun._format(options, nargs + 1);\n const arg = this.arg._format(options, 0);\n const wrap = nargs ? ['', ''] : options.around;\n // TODO ignore terse for now\n if (options.terse && !this.arg._braced(false))\n return wrap[0] + fun + (this.fun._unspaced(this.arg) ? '' : options.space) + arg + wrap[1];\n else\n return wrap[0] + fun + options.brackets[0] + arg + options.brackets[1] + wrap[1];\n }\n\n _unspaced (arg) {\n return this.arg._braced(false) ? true : this.arg._unspaced(arg);\n }\n}\n\nclass Named extends Expr {\n /**\n * @desc An abstract class representing a term named 'name'.\n *\n * @param {String} name\n */\n constructor (name) {\n super();\n if (typeof name !== 'string' || name.length === 0)\n throw new Error('Attempt to create a named term with improper name');\n this.name = name;\n }\n\n _unspaced (arg) {\n return !!(\n (arg instanceof Named) && (\n (this.name.match(/^[A-Z+]$/) && arg.name.match(/^[a-z+]/i))\n || (this.name.match(/^[a-z+]/i) && arg.name.match(/^[A-Z+]$/))\n )\n );\n }\n\n _format (options, nargs) {\n // NOTE fancyName is not yet official and may change name or meaning\n const name = options.html ? this.fancyName ?? this.name : this.name;\n return this.arity > 0 && this.arity <= nargs\n ? options.redex[0] + name + options.redex[1]\n : name;\n }\n}\n\nlet freeId = 0;\n\nclass FreeVar extends Named {\n /**\n * @desc A named variable.\n *\n * Given the functional nature of combinatory logic, variables are treated\n * as functions that we don't know how to evaluate just yet.\n *\n * By default, two different variables even with the same name are considered different.\n * They display it via a hidden id property.\n *\n * If a scope object is given, however, two variables with the same name and scope\n * are considered identical.\n *\n * By convention, FreeVar.global is a constant denoting a global unbound variable.\n *\n * @param {string} name - name of the variable\n * @param {any} scope - an object representing where the variable belongs to.\n */\n constructor (name, scope) {\n super(name);\n this.id = ++freeId;\n // TODO temp compatibility mode\n this.scope = scope === undefined ? this : scope;\n }\n\n weight () {\n return 0;\n }\n\n diff (other, swap = false) {\n if (!(other instanceof FreeVar))\n return super.diff(other, swap);\n if (this.name === other.name && this.scope === other.scope)\n return null;\n const lhs = this.name + '[' + this.id + ']';\n const rhs = other.name + '[' + other.id + ']';\n return swap\n ? '[' + rhs + ' != ' + lhs + ']'\n : '[' + lhs + ' != ' + rhs + ']';\n }\n\n subst (search, replace) {\n if (search instanceof FreeVar && search.name === this.name && search.scope === this.scope)\n return replace;\n return null;\n }\n\n _format (options, nargs) {\n const name = options.html ? this.fancyName ?? this.name : this.name;\n return options.var[0] + name + options.var[1];\n }\n}\n\nFreeVar.global = ['global'];\n\nclass Native extends Named {\n /**\n * @desc A named term with a known rewriting rule.\n * 'impl' is a function with signature Expr => Expr => ... => Expr\n * (see typedef Partial).\n * This is how S, K, I, and company are implemented.\n *\n * Note that as of current something like a=>b=>b(a) is not possible,\n * use full form instead: a=>b=>b.apply(a).\n *\n * @example new Native('K', x => y => x); // constant\n * @example new Native('Y', function(f) { return f.apply(this.apply(f)); }); // self-application\n *\n * @param {String} name\n * @param {Partial} impl\n * @param {{note?: string, arity?: number, canonize?: boolean }} [opt]\n */\n constructor (name, impl, opt = {}) {\n super(name);\n // setup essentials\n this.invoke = impl;\n\n this._setup({ canonize: true, ...opt });\n }\n}\n\nclass Lambda extends Expr {\n /**\n * @desc Lambda abstraction of arg over impl.\n * Upon evaluation, all occurrences of 'arg' within 'impl' will be replaced\n * with the provided argument.\n *\n * Note that 'arg' will be replaced by a localized placeholder, so the original\n * variable can be used elsewhere without interference.\n * Listing symbols contained in the lambda will omit such placeholder.\n *\n * Legacy ([FreeVar], impl) constructor is supported but deprecated.\n * It will create a nested lambda expression.\n *\n * @param {FreeVar} arg\n * @param {Expr} impl\n */\n constructor (arg, impl) {\n if (Array.isArray(arg)) {\n // check args before everything\n if (arg.length === 0)\n throw new Error('empty argument list in lambda constructor');\n\n const [my, ...tail] = arg;\n const known = new Set([my.name]);\n\n while (tail.length > 0) {\n const last = tail.pop();\n if (known.has(last.name))\n throw new Error('Duplicate free var name ' + last + ' in lambda expression');\n known.add(last.name);\n\n // TODO keep track of arity to speed up execution\n impl = new Lambda(last, impl);\n }\n arg = my;\n }\n\n super();\n\n // localize argument variable and bind it to oneself\n const local = new FreeVar(arg.name, this);\n this.arg = local;\n this.impl = impl.subst(arg, local) ?? impl;\n this.arity = 1;\n }\n\n weight () {\n return this.impl.weight() + 1;\n }\n\n invoke (arg) {\n return this.impl.subst(this.arg, arg) ?? this.impl;\n }\n\n _traverse_descend (options, change) {\n // alas no proper shielding of self.arg is possible\n const [impl, iAction] = unwrap(this.impl._traverse_redo(options, change));\n\n const final = impl ? new Lambda(this.arg, impl) : null;\n\n return iAction === control.stop ? control.stop(final) : final;\n }\n\n any (predicate) {\n return predicate(this) || this.impl.any(predicate);\n }\n\n _fold (initial, combine) {\n const [value = initial, action = 'descend'] = unwrap(combine(initial, this));\n if (action === control.prune)\n return value;\n if (action === control.stop)\n return control.stop(value);\n const [iValue, iAction] = unwrap(this.impl._fold(value, combine));\n if (iAction === control.stop)\n return control.stop(iValue);\n return iValue ?? value;\n }\n\n subst (search, replace) {\n if (search === this.arg)\n return null;\n const change = this.impl.subst(search, replace);\n return change ? new Lambda(this.arg, change) : null;\n }\n\n diff (other, swap = false) {\n if (!(other instanceof Lambda))\n return super.diff(other, swap);\n\n const t = new FreeVar('t'); // TODO better placeholder name\n\n const diff = this.invoke(t).diff(other.invoke(t), swap);\n if (diff)\n return '(t->' + diff + ')'; // parentheses required to avoid ambiguity\n return null;\n }\n\n _format (options, nargs) {\n return (nargs > 0 ? options.brackets[0] : '')\n + options.lambda[0]\n + this.arg._format(options, 0) // TODO highlight redex if nargs > 0\n + options.lambda[1]\n + this.impl._format(options, 0) + options.lambda[2]\n + (nargs > 0 ? options.brackets[1] : '');\n }\n\n _braced (first) {\n return true;\n }\n}\n\nclass Church extends Expr {\n /**\n * @desc Church numeral representing non-negative integer n:\n * n f x = f(f(...(f x)...)) with f applied n times.\n * @param {number} n\n */\n constructor (n) {\n n = Number.parseInt(n);\n if (!(n >= 0))\n throw new Error('Church number must be a non-negative integer');\n super();\n this.invoke = x => y => {\n let expr = y;\n for (let i = n; i-- > 0; )\n expr = x.apply(expr);\n return expr;\n };\n\n /** @type {number} */\n this.n = n;\n this.arity = 2;\n }\n\n diff (other, swap = false) {\n if (!(other instanceof Church))\n return super.diff(other, swap);\n if (this.n === other.n)\n return null;\n return swap\n ? '[' + other.n + ' != ' + this.n + ']'\n : '[' + this.n + ' != ' + other.n + ']';\n }\n\n _unspaced (arg) {\n return false;\n }\n\n _format (options, nargs) {\n return nargs >= 2\n ? options.redex[0] + this.n + options.redex[1]\n : this.n + '';\n }\n}\n\nfunction waitn (expr, n) {\n return arg => n <= 1 ? expr.apply(arg) : waitn(expr.apply(arg), n - 1);\n}\n\nclass Alias extends Named {\n /**\n * @desc A named alias for an existing expression.\n *\n * Upon evaluation, the alias expands into the original expression,\n * unless it has a known arity > 0 and is marked terminal,\n * in which case it waits for enough arguments before expanding.\n *\n * A hidden mutable property 'outdated' is used to silently\n * replace the alias with its definition in all contexts.\n * This is used when declaring named terms in an interpreter,\n * to avoid confusion between old and new terms with the same name.\n *\n * @param {String} name\n * @param {Expr} impl\n * @param {{canonize?: boolean, max?: number, maxArgs?: number, note?: string, terminal?: boolean}} [options]\n */\n constructor (name, impl, options = {}) {\n super(name);\n if (!(impl instanceof Expr))\n throw new Error('Attempt to create an alias for a non-expression: ' + impl);\n this.impl = impl;\n\n this._setup(options);\n this.terminal = options.terminal ?? this.props?.proper;\n this.invoke = waitn(impl, this.arity ?? 0);\n }\n\n /**\n * @property {boolean} [outdated] - whether the alias is outdated\n * and should be replaced with its definition when encountered.\n * @property {boolean} [terminal] - whether the alias should behave like a standalone term\n * // TODO better name?\n * @property {boolean} [proper] - whether the alias is a proper combinator (i.e. contains no free variables or constants)\n * @property {number} [arity] - the number of arguments the alias waits for before expanding\n * @property {Expr} [canonical] - equivalent lambda term.\n */\n\n weight () {\n return this.terminal ? 1 : this.impl.weight();\n }\n\n _traverse_descend (options, change) {\n return this.impl._traverse_redo(options, change);\n }\n\n any (predicate) {\n return predicate(this) || this.impl.any(predicate);\n }\n\n _fold (initial, combine) {\n const [value = initial, action] = unwrap(combine(initial, this));\n if (action === control.prune)\n return value;\n if (action === control.stop)\n return control.stop(value);\n const [iValue, iAction] = unwrap(this.impl._fold(value, combine));\n if (iAction === control.stop)\n return control.stop(iValue);\n return iValue ?? value;\n }\n\n subst (search, replace) {\n if (this === search)\n return replace;\n return this.impl.subst(search, replace);\n }\n\n // DO NOT REMOVE TYPE or tsc chokes with\n // TS2527: The inferred type of 'Alias' references an inaccessible 'this' type.\n /**\n * @return {{expr: Expr, steps: number, changed: boolean}}\n */\n step () {\n // arity known = waiting for args to expand\n if (this.arity > 0)\n return { expr: this, steps: 0, changed: false };\n // expanding is a change but it takes 0 steps\n return { expr: this.impl, steps: 0, changed: true };\n }\n\n diff (other, swap = false) {\n if (this === other)\n return null;\n return other.diff(this.impl, !swap);\n }\n\n _braced (first) {\n return this.outdated ? this.impl._braced(first) : false;\n }\n\n _format (options, nargs) {\n const outdated = options.inventory\n ? options.inventory[this.name] !== this\n : this.outdated;\n return outdated ? this.impl._format(options, nargs) : super._format(options, nargs);\n }\n}\n\n// ----- Expr* classes end here -----\n\n// declare native combinators\n\nfunction addNative (name, impl, opt) {\n native[name] = new Native(name, impl, opt);\n}\naddNative('I', x => x);\naddNative('K', x => _ => x);\naddNative('S', x => y => z => x.apply(z, y.apply(z)));\naddNative('B', x => y => z => x.apply(y.apply(z)));\naddNative('C', x => y => z => x.apply(z).apply(y));\naddNative('W', x => y => x.apply(y).apply(y));\n\naddNative(\n '+',\n n => n instanceof Church\n ? new Church(n.n + 1)\n : f => x => f.apply(n.apply(f, x)),\n {\n note: 'Increase a Church numeral argument by 1, otherwise n => f => x => f(n f x)',\n }\n);\n\n// utility functions dependent on Expr* classes, in alphabetical order\n\nfunction firstVar (expr) {\n // yay premature optimization\n while (expr instanceof App)\n expr = expr.fun;\n return expr instanceof FreeVar;\n}\n\n/**\n * @private\n * @given a list of free variables, an expression, and some capabilities of the context,\n * return either a lambda term, or the original expression if no lambda abstraction is needed,\n * plus some metadata about the term and the context.\n *\n * Used by infer() internally.\n * @param {FreeVar[]} args\n * @param {Expr} expr\n * @param {object} caps\n * @returns {TermInfo}\n */\nfunction maybeLambda (args, expr, caps = {}) {\n const count = new Array(args.length).fill(0);\n let proper = true;\n expr.traverse(e => {\n if (e instanceof FreeVar) {\n const index = args.findIndex(a => a.name === e.name);\n if (index >= 0) {\n count[index]++;\n return;\n }\n }\n if (!(e instanceof App))\n proper = false;\n });\n\n const skip = new Set();\n const dup = new Set();\n for (let i = 0; i < args.length; i++) {\n if (count[i] === 0)\n skip.add(i);\n else if (count[i] > 1)\n dup.add(i);\n }\n\n return {\n normal: true,\n steps: caps.steps,\n expr: args.length ? new Lambda(args, expr) : expr,\n arity: args.length,\n ...(skip.size ? { skip } : {}),\n ...(dup.size ? { dup } : {}),\n duplicate: !!dup.size || caps.duplicate || false,\n discard: !!skip.size || caps.discard || false,\n proper,\n };\n}\n\nfunction nthvar (n) {\n return new FreeVar('abcdefgh'[n] ?? 'x' + n);\n}\n\n/**\n * @desc Sort a list in such a way that dependent terms come after the (named) terms they depend on.\n * If env is given, only terms listed there are taken into account.\n * If env is omitted, it will be implied from the list.\n * If list is omitted, it will default to values of env.\n * If just one term is given instead of a list, it will be coerced into a list.\n *\n * No terms outside env + list may ever appear in the result.\n *\n * The terms in env must be named and their names must match their keys.\n *\n * @param {Expr|Expr[]} list\n * @param {{[s:string]: Named}} env\n * @returns {{list: Expr[], env: {[s:string]: Named}}}\n *\n * @example\n * const expr = ski.parse(src);\n * toposort([expr], ski.getTerms()); // returns all terms appearing in Expr in correct order\n */\nfunction toposort (list, env) {\n if (list instanceof Expr)\n list = [list];\n if (env) {\n // TODO check in[name].name === name\n if (!list)\n list = Object.keys(env).sort().map(k => env[k]); // ensure deterministic order\n } else {\n if (!list)\n return [];\n if (!env) {\n env = {};\n for (const item of list) {\n if (!(item instanceof Named))\n continue;\n if (env[item.name])\n throw new Error('duplicate name ' + item);\n env[item.name] = item;\n }\n }\n }\n\n const out = [];\n const seen = new Set();\n const rec = term => {\n if (seen.has(term))\n return;\n term.fold(null, (acc, e) => {\n if (e !== term && e instanceof Named && env[e.name] === e) {\n rec(e);\n return Expr.control.prune(null);\n }\n });\n out.push(term);\n seen.add(term);\n };\n\n for (const term of list)\n rec(term);\n\n return {\n list: out,\n env,\n };\n}\n\nExpr.native = native;\nExpr.control = control;\nExpr.extras = { toposort };\n\nmodule.exports = { Expr, App, Named, FreeVar, Lambda, Native, Alias, Church };\n", "/**\n * Combinatory logic simulator\n */\n'use strict';\n\nconst { Tokenizer, restrict } = require('./internal');\nconst classes = require('./expr');\n\nconst { Expr, Named, Native, Alias, FreeVar, Lambda, Church } = classes;\nconst { native } = Expr;\n\nclass Empty extends Expr {\n apply (...args) {\n return args.length ? args.shift().apply(...args) : this;\n }\n\n postParse () {\n throw new Error('Attempt to use empty expression () as a term');\n }\n}\n\nclass PartialLambda extends Empty {\n // TODO mutable! rewrite ro when have time\n constructor (term, known = {}) {\n super();\n this.impl = new Empty();\n if (term instanceof FreeVar)\n this.terms = [term];\n else if (term instanceof PartialLambda) {\n if (!(term.impl instanceof FreeVar))\n throw new Error('Expected FreeVar->...->FreeVar->Expr');\n this.terms = [...term.terms, term.impl];\n } else\n throw new Error('Expected FreeVar or PartialLambda');\n }\n\n apply (term, ...tail) {\n if (term === null || tail.length !== 0 )\n throw new Error('bad syntax in partial lambda expr');\n this.impl = this.impl.apply(term);\n return this;\n }\n\n postParse () {\n return new Lambda(this.terms, this.impl);\n }\n\n // uncomment if debugging with prints\n /* toString () {\n return this.terms.join('->') + '->' + (this.impl ?? '???');\n } */\n}\n\nfunction postParse (expr) {\n return expr.postParse ? expr.postParse() : expr;\n}\n\nconst combChars = new Tokenizer(\n '[()]', '[A-Z]', '[a-z_][a-z_0-9]*', '\\\\b[0-9]+\\\\b', '->', '\\\\+'\n);\n\nclass SKI {\n /**\n *\n * @param {{\n * allow?: string,\n * numbers?: boolean,\n * lambdas?: boolean,\n * terms?: { [key: string]: Expr|string} | string[],\n * annotate?: boolean,\n * }} [options]\n */\n constructor (options = {}) {\n this.annotate = options.annotate ?? false;\n this.known = { ...native };\n this.hasNumbers = true;\n this.hasLambdas = true;\n /** @type {Set<string>} */\n this.allow = new Set(Object.keys(this.known));\n\n // Import terms, if any. Omit native ones\n if (Array.isArray(options.terms))\n this.bulkAdd(options.terms);\n else if (options.terms) {\n for (const name in options.terms) {\n // Native terms already handled by allow\n if (!options.terms[name].match(/^Native:/))\n this.add(name, options.terms[name]);\n }\n }\n\n // Finally, impose restrictions\n // We must do it after recreating terms, or else terms reliant on forbidden terms will fail\n this.hasNumbers = options.numbers ?? true;\n this.hasLambdas = options.lambdas ?? true;\n if (options.allow)\n this.restrict(options.allow);\n }\n\n /**\n * @desc Declare a new term\n * If the first argument is an Alias, it is added as is.\n * Otherwise, a new Alias or Native term (depending on impl type) is created.\n * If note is not provided and this.annotate is true, an automatic note is generated.\n *\n * If impl is a function, it should have signature (Expr) => ... => Expr\n * (see typedef Partial at top of expr.js)\n *\n * @example ski.add('T', 'S(K(SI))K', 'swap combinator')\n * @example ski.add( ski.parse('T = S(K(SI))K') ) // ditto but one-arg form\n * @example ski.add('T', x => y => y.apply(x), 'swap combinator') // heavy artillery\n * @example ski.add('Y', function (f) { return f.apply(this.apply(f)); }, 'Y combinator')\n *\n * @param {Alias|String} term\n * @param {String|Expr|function(Expr):Partial} [impl]\n * @param {object|string} [options]\n * @param {string} [options.note] - optional annotation for the term, default is auto-generated if this.annotate is true\n * @param {boolean} [options.canonize] - whether to canonize the term's implementation, default is this.annotate\n * @param {boolean} [options.fancy] - alternative HTML-friendly name for the term\n * @param {number} [options.arity] - custom arity for the term, default is inferred from the implementation\n * @return {SKI} chainable\n */\n add (term, impl, options ) {\n term = this._named(term, impl);\n\n // backward compat\n if (typeof options === 'string')\n options = { note: options, canonize: false };\n term._setup({ canonize: this.annotate, ...options });\n\n if (this.known[term.name])\n this.known[term.name].outdated = true;\n this.known[term.name] = term;\n this.allow.add(term.name);\n\n return this;\n }\n\n /**\n * @desc Internal helper for add() that creates an Alias or Native term from the given arguments.\n * @param {Alias|string} term\n * @param {string|Expr|function(Expr):Partial} impl\n * @returns {Native|Alias}\n * @private\n */\n _named (term, impl) {\n if (term instanceof Alias)\n return new Alias(term.name, term.impl, { canonize: true });\n if (typeof term !== 'string')\n throw new Error('add(): term must be an Alias or a string');\n if (impl === undefined)\n throw new Error('add(): impl must be provided when term is a string');\n if (typeof impl === 'string')\n return new Alias(term, this.parse(impl), { canonize: true });\n if (impl instanceof Expr)\n return new Alias(term, impl, { canonize: true });\n if (typeof impl === 'function')\n return new Native(term, impl);\n // idk what this is\n throw new Error('add(): impl must be an Expr, a string, or a function with a signature Expr => ... => Expr');\n }\n\n /**\n * @desc Declare a new term if it is not known, otherwise just allow it.\n * Currently only used by quests.\n * Use with caution, this function may change its signature, behavior, or even be removed in the future.\n *\n * @experimental\n * @param {string|Alias} name\n * @param {string|Expr|function(Expr):Partial} impl\n * @returns {SKI}\n */\n maybeAdd (name, impl) {\n if (this.known[name])\n this.allow.add(name);\n else\n this.add(name, impl);\n return this;\n }\n\n /**\n * @desc Declare and remove multiple terms at once\n * term=impl adds term\n * term= removes term\n * @param {string[]} list\n * @return {SKI} chainable\n */\n bulkAdd (list) {\n for (const item of list) {\n const m = item.match(/^([A-Z]|[a-z][a-z_0-9]*)\\s*=\\s*(.*)$/s);\n // TODO check all declarations before applying any (but we might need earlier terms for parsing later ones)\n if (!m)\n throw new Error('bulkAdd: invalid declaration: ' + item);\n if (m[2] === '')\n this.remove(m[1]);\n else\n this.add(m[1], this.parse(m[2]));\n }\n\n return this;\n }\n\n /**\n * Restrict the interpreter to given terms. Terms prepended with '+' will be added\n * and terms preceeded with '-' will be removed.\n * @example ski.restrict('SK') // use the basis\n * @example ski.restrict('+I') // allow I now\n * @example ski.restrict('-SKI +BCKW' ); // switch basis\n * @example ski.restrict('-foo -bar'); // forbid some user functions\n * @param {string} spec\n * @return {SKI} chainable\n */\n restrict (spec) {\n this.allow = restrict(this.allow, spec);\n return this;\n }\n\n /**\n *\n * @param {string} spec\n * @return {string}\n */\n showRestrict (spec = '+') {\n const out = [];\n let prevShort = true;\n for (const term of [...restrict(this.allow, spec)].sort()) {\n const nextShort = term.match(/^[A-Z]$/);\n if (out.length && !(prevShort && nextShort))\n out.push(' ');\n out.push(term);\n prevShort = nextShort;\n }\n return out.join('');\n }\n\n /**\n *\n * @param {String} name\n * @return {SKI}\n */\n remove (name) {\n this.known[name].outdated = true;\n delete this.known[name];\n this.allow.delete(name);\n return this;\n }\n\n /**\n *\n * @return {{[key:string]: Native|Alias}}\n */\n getTerms () {\n const out = {};\n for (const name of Object.keys(this.known)) {\n if (this.allow.has(name))\n out[name] = this.known[name];\n }\n return out;\n }\n\n /**\n * @desc Export term declarations for use in bulkAdd().\n * Currently only Alias terms are serialized.\n * @returns {string[]}\n */\n declare () {\n // TODO accept argument to declare specific terms only\n const env = this.getTerms();\n\n // not serializing native terms, and we don't care about free vars\n for (const name in env) {\n if (!(env[name] instanceof Alias))\n delete env[name];\n }\n\n // avert conflicts if native terms were redefined:\n // create a temporary alias for each native term that was redefined;\n // replace usage of redefined term in subexpressions;\n // finally, remove the temporary aliases from the output\n const needDetour = {};\n let i = 1;\n for (const name in native) {\n if (!(env[name] instanceof Alias))\n continue;\n while ('tmp' + i in env)\n i++;\n const temp = new Alias('tmp' + i, env[name]);\n needDetour[temp] = env[name];\n env[temp] = temp;\n delete env[name];\n }\n\n // console.log(env);\n\n const list = Expr.extras.toposort(undefined, env).list;\n\n const detour = new Map();\n if (Object.keys(needDetour).length) {\n // replace aliases with their detoured counterparts.\n // we have to go recursive, otherwise an unrelated alias may be expanded to its impl\n // and name infos will be erased\n const rework = expr => {\n return expr.traverse(e => {\n if (!(e instanceof Alias))\n return null; // continue\n const newAlias = detour.get(e);\n if (newAlias)\n return newAlias;\n return new Alias(e.name, rework(e.impl));\n }) ?? expr;\n };\n\n for (let i = 0; i < list.length; i++) {\n // upon processing list[i], only terms declared before it may be detoured\n list[i] = rework(list[i], detour);\n detour.set(needDetour[list[i].name], list[i]);\n env[list[i].name] = list[i];\n console.log(`list[${i}] = ${list[i].name}=${list[i].impl};`);\n }\n console.log('detour:', detour);\n }\n\n // console.log(res);\n const out = list.map(e => needDetour[e]\n ? e.name + '=' + needDetour[e].name + '=' + e.impl.format({ inventory: env })\n : e.name + '=' + e.impl.format({ inventory: env })\n );\n\n for (const [name, temp] of detour)\n out.push(name + '=' + temp, temp + '=');\n\n return out;\n }\n\n /**\n * @template T\n * @param {string} source\n * @param {Object} [options]\n * @param {{[keys: string]: Expr}} [options.env]\n * @param {T} [options.scope]\n * @param {boolean} [options.numbers]\n * @param {boolean} [options.lambdas]\n * @param {string} [options.allow]\n * @return {Expr}\n */\n parse (source, options = {}) {\n if (typeof source !== 'string')\n throw new Error('parse: source must be a string, got ' + typeof source);\n\n const lines = source.replace(/\\/\\/[^\\n]*$/gm, ' ')\n .replace(/\\/\\*.*?\\*\\//gs, ' ')\n .trim()\n .split(/\\s*;[\\s;]*/).filter( s => s.match(/\\S/));\n\n const jar = { ...options.env };\n\n let expr = new Empty();\n for (const item of lines) {\n if (expr instanceof Alias)\n expr.outdated = true;\n\n const def = item.match(/^([A-Z]|[a-z][a-z_0-9]*)\\s*=(.*)$/s);\n if (def && def[2] === '')\n expr = new FreeVar(def[1], options.scope ?? FreeVar.global);\n else\n expr = this.parseLine(item, jar, options);\n\n if (def) {\n if (jar[def[1]] !== undefined)\n throw new Error('Attempt to redefine a known term: ' + def[1]);\n jar[def[1]] = expr;\n }\n\n // console.log('parsed line:', item, '; got:', expr,'; jar now: ', jar);\n }\n\n expr.context = {\n env: { ...this.getTerms(), ...jar }, // also contains pre-parsed terms\n scope: options.scope,\n src: source,\n parser: this,\n };\n return expr;\n }\n\n /**\n * @desc Parse a single line of source code, without splitting it into declarations.\n * Internal, always use parse() instead.\n * @template T\n * @param {String} source S(KI)I\n * @param {{[keys: string]: Expr}} env\n * @param {Object} [options]\n * @param {{[keys: string]: Expr}} [options.env] - unused, see 'env' argument\n * @param {T} [options.scope]\n * @param {boolean} [options.numbers]\n * @param {boolean} [options.lambdas]\n * @param {string} [options.allow]\n * @return {Expr} parsed expression\n */\n parseLine (source, env = {}, options = {}) {\n const aliased = source.match(/^\\s*([A-Z]|[a-z][a-z_0-9]*)\\s*=\\s*(.*)$/s);\n if (aliased)\n return new Alias(aliased[1], this.parseLine(aliased[2], env, options));\n\n const opt = {\n numbers: options.numbers ?? this.hasNumbers,\n lambdas: options.lambdas ?? this.hasLambdas,\n allow: restrict(this.allow, options.allow),\n };\n // make sure '+' usage is in sync with numerals\n opt.numbers ? opt.allow.add('+') : opt.allow.delete('+');\n\n const tokens = combChars.split(source);\n\n const empty = new Empty();\n /** @type {Expr[]} */\n const stack = [empty];\n const context = options.scope || FreeVar.global; // default is global unbound vars\n\n // TODO each token should carry along its position in source\n for (const c of tokens) {\n // console.log(\"parseLine: found \"+c+\"; stack =\", stack.join(\", \"));\n if (c === '(')\n stack.push(empty);\n else if (c === ')') {\n if (stack.length < 2)\n throw new Error('unbalanced input: extra closing parenthesis' + source);\n const x = postParse(stack.pop());\n const f = stack.pop();\n stack.push(f.apply(x));\n } else if (c === '->') {\n if (!opt.lambdas)\n throw new Error('Lambdas not supported, allow them explicitly');\n stack.push(new PartialLambda(stack.pop(), env));\n } else if (c.match(/^[0-9]+$/)) {\n if (!opt.numbers)\n throw new Error('Church numbers not supported, allow them explicitly');\n const f = stack.pop();\n stack.push(f.apply(new Church(c)));\n } else {\n const f = stack.pop();\n if (!env[c] && this.known[c] && !opt.allow.has(c)) {\n throw new Error('Term \\'' + c + '\\' is not in the restricted set '\n + [...opt.allow].sort().join(' '));\n }\n // look in temp vars first, then in known terms, then fallback to creating free var\n const x = env[c] ?? this.known[c] ?? (env[c] = new FreeVar(c, context));\n stack.push(f.apply(x));\n }\n }\n\n if (stack.length !== 1) {\n throw new Error('unbalanced input: missing '\n + (stack.length - 1) + ' closing parenthesis:' + source);\n }\n\n return postParse(stack.pop());\n }\n\n toJSON () {\n return {\n version: '1.1.1', // set to incremented package.json version whenever SKI serialization changes\n allow: this.showRestrict('+'),\n numbers: this.hasNumbers,\n lambdas: this.hasLambdas,\n annotate: this.annotate,\n terms: this.declare(),\n }\n }\n}\n\n/**\n * Public static shortcuts to common functions (see also ./extras.js)\n */\n\n/**\n * @desc Create a proxy object that generates variables on demand,\n * with names corresponding to the property accessed.\n * Different invocations will return distinct variables,\n * even if with the same name.\n *\n *\n * @example const {x, y, z} = SKI.vars();\n * x.name; // 'x'\n * x instanceof FreeVar; // true\n * x.apply(y).apply(z); // x(y)(z)\n *\n * @template T\n * @param {T} [scope] - optional context to bind the generated variables to\n * @return {{[key: string]: FreeVar}}\n */\nSKI.vars = function (scope = {}) {\n const cache = {};\n return new Proxy({}, {\n get: (target, name) => {\n if (!(name in cache))\n cache[name] = new FreeVar(name, scope);\n return cache[name];\n }\n });\n};\n\n/**\n * Convert a number to Church encoding\n * @param {number} n\n * @return {Church}\n */\nSKI.church = n => new Church(n);\n\n/**\n *\n * @type {{[key: string]: Native}}\n */\n\nfor (const name in native)\n SKI[name] = native[name];\n\nSKI.classes = classes;\nSKI.native = native;\n/**\n * @desc Traverse control functions, used by Expr.traverse() and Expr.fold()\n * @template T\n * @type {{\n * descend: function(T): TraverseControl<T>,\n * prune: function(T): TraverseControl<T>,\n * redo: function(T): TraverseControl<T>,\n * stop: function(T): TraverseControl<T>\n * }}\n */\nSKI.control = Expr.control;\n\nmodule.exports = { SKI };\n", "const { SKI } = require('./parser');\nconst { Expr, FreeVar, Alias, Lambda } = SKI.classes;\n\n/**\n * @typedef {{\n * pass: boolean,\n * reason?: string,\n * steps: number,\n * start: Expr,\n * found: Expr,\n * expected: Expr,\n * note?: string,\n * args: Expr[],\n * case: Case\n * }} CaseResult\n */\n\n/**\n * @typedef {{\n * linear?: boolean,\n * affine?: boolean,\n * normal?: boolean,\n * proper?: boolean,\n * discard?: boolean,\n * duplicate?: boolean,\n * arity?: number,\n * }} Capability\n */\n\n/**\n * @typedef {\n * [string, string]\n * | [{max?: number}, string, string]\n * | [{caps: Capability, max?: number}, string]\n * } TestCase\n */\n\n/**\n * @typedef {string | {name: string, fancy?: string, allow?: string, numbers?: boolean, lambdas?: boolean}} InputSpec\n */\n\n/**\n * @typedef {{\n * pass: boolean,\n * details: CaseResult[],\n * expr?: Expr,\n * input: Expr[]|string[],\n * exception?: Error,\n * steps: number,\n * weight?: number\n * }} QuestResult\n */\n\n/**\n * @typedef {{\n * input: InputSpec | InputSpec[],\n * cases: TestCase[],\n *\n * // the rest is optional\n *\n * allow?: string,\n * numbers?: boolean,\n * env?: string[],\n * engine?: SKI,\n * engineFull?: SKI,\n *\n * // metadata, also any fields not listed here will go to quest.meta.???\n * id?: string|number,\n * name?: string,\n * intro?: string|string[], // multiple strings will be concatenated with spaces\n * }} QuestSpec\n */\n\n/**\n * @typedef {{ accepted?: string[][], rejected?: string[][] }} SelfCheck\n */\n\nclass Quest {\n /**\n * @description A combinator problem with a set of test cases for the proposed solution.\n * @param {QuestSpec} options\n * @example const quest = new Quest({\n * input: 'identity',\n * cases: [\n * ['identity x', 'x'],\n * ],\n * allow: 'SK',\n * intro: 'Find a combinator that behaves like the identity function.',\n * });\n * quest.check('S K K'); // { pass: true, details: [...], ... }\n * quest.check('K S'); // { pass: false, details: [...], ... }\n * quest.check('K x'); // fail! internal variable x is not equal to free variable x,\n * // despite having the same name.\n * quest.check('I'); // fail! I not in the allowed list.\n */\n constructor (options) {\n const { input, cases, allow, numbers, lambdas, engine, engineFull, ...meta } = options;\n const env = options.env ?? options.vars; // backwards compatibility\n\n //\n this.engine = engine ?? new SKI();\n this.engineFull = engineFull ?? new SKI();\n this.restrict = { allow, numbers: numbers ?? false, lambdas: lambdas ?? false };\n this.env = {};\n\n const jar = {};\n\n // option.env is a list of expressions.\n // we suck all free variables + all term declarations from there into this.env\n // to feed it later to every case's parser.\n for (const term of env ?? []) {\n const expr = this.engineFull.parse(term, { env: jar, scope: this });\n if (expr instanceof SKI.classes.Alias)\n this.env[expr.name] = new Alias(expr.name, expr.impl, { terminal: true, canonize: false });\n // Canonized aliases won't expand with insufficient arguments,\n // causing correct solutions to fail, so alas...\n else if (expr instanceof SKI.classes.FreeVar)\n this.env[expr.name] = expr;\n else\n throw new Error('Unsupported given variable type: ' + term);\n }\n\n this.input = [];\n for (const term of Array.isArray(input) ? input : [input])\n this.addInput(term);\n if (!this.input.length)\n throw new Error('Quest needs at least one input placeholder');\n\n this.envFull = { ...this.env, ...jar };\n for (const term of this.input) {\n if (term.name in this.envFull)\n throw new Error('input placeholder name is duplicated or clashes with env: ' + term.name);\n this.envFull[term.name] = term.placeholder;\n }\n\n // NOTE meta is a local variable, can mutate\n // NOTE title/descr are old name/intro respectively, kept for backwards compatibility\n this.cases = [];\n this.name = meta.name ?? meta.title;\n meta.intro = list2str(meta.intro ?? meta.descr);\n this.intro = meta.intro;\n this.id = meta.id;\n this.meta = meta;\n\n for (const c of cases ?? [])\n this.add(...c);\n }\n\n /**\n * Display allowed terms based on what engine thinks of this.env + this.restrict.allow\n * @return {string}\n */\n allowed () {\n const allow = this.restrict.allow ?? '';\n const env = Object.keys(this.env).sort();\n // In case vars are present and restrictions aren't, don't clutter the output with all the known terms\n return allow\n ? this.engine.showRestrict(allow + '+' + env.join(' '))\n : env.map( s => '+' + s).join(' ');\n }\n\n addInput (term) {\n if (typeof term !== 'object')\n term = { name: term };\n if (typeof term.name !== 'string')\n throw new Error(\"quest 'input' field must be a string or a {name: string, ...} object\");\n\n term.placeholder = new SKI.classes.FreeVar(term.name);\n // TODO more checks\n this.input.push(term);\n }\n\n /**\n *\n * @param {{} | string} opt\n * @param {string} terms\n * @return {Quest}\n */\n add (opt, ...terms) {\n if (typeof opt === 'string') {\n terms.unshift(opt);\n opt = {};\n } else\n opt = { ...opt };\n\n opt.engine = opt.engine ?? this.engineFull;\n opt.env = opt.env ?? this.envFull;\n\n const input = this.input.map( t => t.placeholder );\n this.cases.push(\n opt.caps\n ? new PropertyCase(input, opt, terms)\n : new ExprCase(input, opt, terms)\n );\n return this;\n }\n\n /**\n * @description Statefully parse a list of strings into expressions or fancy aliases thereof.\n * @param {string[]} input\n * @return {{terms: Expr[], weight: number}}\n */\n prepare (...input) {\n if (input.length !== this.input.length)\n throw new Error('Solutions provided ' + input.length + ' terms where ' + this.input.length + ' are expected');\n\n let weight = 0;\n const prepared = [];\n const jar = { ...this.env };\n for (let i = 0; i < input.length; i++) {\n const spec = this.input[i];\n const impl = this.engine.parse(input[i], {\n env: jar,\n allow: spec.allow ?? this.restrict.allow,\n numbers: spec.numbers ?? this.restrict.numbers,\n lambdas: spec.lambdas ?? this.restrict.lambdas,\n });\n const arsenal = { ...this.engine.getTerms(), ...jar };\n weight += impl.fold(0, (a, e) => {\n if (e instanceof SKI.classes.Named && arsenal[e.name] === e)\n return SKI.control.prune( a + 1);\n });\n const expr = impl instanceof FreeVar\n ? impl\n : new Alias(spec.fancy ?? spec.name, impl, { terminal: true, canonize: false });\n jar[spec.name] = expr;\n prepared.push(expr);\n }\n return {\n prepared,\n weight,\n };\n }\n\n /**\n *\n * @param {string} input\n * @return {QuestResult}\n */\n check (...input) {\n try {\n const { prepared, weight } = this.prepare(...input);\n const details = this.cases.map( c => c.check(...prepared) );\n const pass = details.reduce((acc, val) => acc && val.pass, true);\n const steps = details.reduce((acc, val) => acc + val.steps, 0);\n return {\n expr: prepared[0],\n input: prepared,\n pass,\n steps,\n details,\n weight,\n };\n } catch (e) {\n return { pass: false, details: [], exception: e, steps: 0, input };\n }\n }\n\n verify (options) {\n const findings = this.verifyMeta(options);\n if (options.solutions) {\n const solCheck = this.verifySolutions(options.solutions);\n if (solCheck)\n findings.solutions = solCheck;\n }\n if (options.seen) {\n if (!this.id)\n findings.seen = 'No id in quest ' + (this.name ?? '(unnamed)');\n if (options.seen.has(this.id))\n findings.seen = 'Duplicate quest id ' + this.id;\n options.seen.add(this.id); // mutating but who cares\n }\n return Object.keys(findings).length ? findings : null;\n }\n\n /**\n * @desc Verify that solutions that are expected to pass/fail do so.\n * @param {SelfCheck|{[key: string]: SelfCheck}} dataset\n * @return {{shouldPass: {input: string[], result: QuestResult}[], shouldFail: {input: string[], result: QuestResult}[]} | null}\n */\n verifySolutions (dataset) {\n // dataset is either a SelfCheck object or a hash of { quest_id: SelfCheck }\n if (typeof dataset === 'object' && !Array.isArray(dataset?.accepted) && !Array.isArray(dataset?.rejected)) {\n // dataset is a hash of { quest_id: SelfCheck } so extract data\n if (!this.id || !dataset[this.id])\n return null; // no self-check data for this quest, skip\n }\n\n const { accepted = [], rejected = [] } = dataset[this.id] ?? dataset;\n\n const ret = { shouldPass: [], shouldFail: [] };\n for (const input of accepted) {\n const result = this.check(...input);\n if (!result.pass)\n ret.shouldPass.push({ input, result });\n }\n for (const input of rejected) {\n const result = this.check(...input);\n if (result.pass)\n ret.shouldFail.push({ input, result });\n }\n return (ret.shouldFail.length + ret.shouldPass.length) ? ret : null; // return null if all good\n }\n\n verifyMeta (options = {}) {\n const findings = {};\n\n for (const field of ['name', 'intro']) {\n const found = checkHtml(this[field]);\n if (found)\n findings[field] = found;\n }\n if (options.date) {\n const date = new Date(this.meta.created_at);\n if (isNaN(date))\n findings.date = 'invalid date format: ' + this.meta.created_at;\n else if (date < new Date('2024-07-15') || date > new Date())\n findings.date = 'date out of range: ' + this.meta.created_at;\n }\n\n return findings;\n }\n\n /**\n *\n * @return {TestCase[]}\n */\n show () {\n return [...this.cases];\n }\n}\n\nclass Case {\n /**\n * @param {FreeVar[]} input\n * @param {{\n * max?: number,\n * note?: string,\n * env?: {[key:string]: Expr},\n * engine: SKI\n * }} options\n */\n constructor (input, options) {\n this.max = options.max ?? 1000;\n this.note = options.note;\n this.env = { ...(options.env ?? {}) }; // note: env already contains input placeholders\n this.input = input;\n this.engine = options.engine;\n }\n\n parse (src) {\n return new Subst(this.engine.parse(src, { env: this.env, scope: this }), this.input);\n }\n\n /**\n * @param {Expr} expr\n * @return {CaseResult}\n */\n check ( ...expr ) {\n throw new Error('not implemented');\n }\n}\n\nclass ExprCase extends Case {\n /**\n * @param {FreeVar[]} input\n * @param {{\n * max?: number,\n * note?: string,\n * env?: {string: Expr},\n * engine?: SKI\n * }} options\n * @param {[e1: string, e2: string]} terms\n */\n constructor (input, options, terms) {\n if (terms.length !== 2)\n throw new Error('Case accepts exactly 2 strings');\n\n super(input, options);\n\n [this.e1, this.e2] = terms.map( s => this.parse(s) );\n }\n\n check (...args) {\n const e1 = this.e1.apply(args);\n const r1 = e1.run({ max: this.max });\n const e2 = this.e2.apply(args);\n const r2 = e2.run({ max: this.max });\n\n let reason = null;\n if (!r1.final || !r2.final)\n reason = 'failed to reach normal form in ' + this.max + ' steps';\n else\n reason = r1.expr.diff(r2.expr);\n\n return {\n pass: !reason,\n reason,\n steps: r1.steps,\n start: e1,\n found: r1.expr,\n expected: r2.expr,\n note: this.note,\n args,\n case: this,\n };\n }\n}\n\nconst knownCaps = {\n normal: true,\n proper: true,\n discard: true,\n duplicate: true,\n linear: true,\n affine: true,\n arity: true,\n}\n\nclass PropertyCase extends Case {\n // test that an expression uses all of its inputs exactly once\n constructor (input, options, terms) {\n super(input, options);\n if (terms.length > 1)\n throw new Error('PropertyCase accepts exactly 1 string');\n if (!options.caps || typeof options.caps !== 'object' || !Object.keys(options.caps).length)\n throw new Error('PropertyCase requires a caps object with at least one capability');\n const unknown = Object.keys(options.caps).filter( c => !knownCaps[c] );\n if (unknown.length)\n throw new Error('PropertyCase: don\\'t know how to test these capabilities: ' + unknown.join(', '));\n\n this.expr = this.parse(terms[0]);\n this.caps = options.caps;\n\n if (this.caps.linear) {\n delete this.caps.linear;\n this.caps.duplicate = false;\n this.caps.discard = false;\n this.caps.normal = true;\n }\n\n if (this.caps.affine) {\n delete this.caps.affine;\n this.caps.normal = true;\n this.caps.duplicate = false;\n }\n }\n\n check (...expr) {\n const start = this.expr.apply(expr);\n const r = start.run({ max: this.max });\n const guess = r.expr.infer({ max: this.max });\n\n const reason = [];\n for (const cap in this.caps) {\n if (guess[cap] !== this.caps[cap])\n reason.push('expected property ' + cap + ' to be ' + this.caps[cap] + ', found ' + guess[cap]);\n }\n\n return {\n pass: !reason.length,\n reason: reason ? reason.join('\\n') : null,\n steps: r.steps,\n start,\n found: r.expr,\n case: this,\n note: this.note,\n args: expr,\n };\n }\n}\n\nclass Subst {\n /**\n * @descr A placeholder object with exactly n free variables to be substituted later.\n * @param {Expr} expr\n * @param {FreeVar[]} env\n */\n constructor (expr, env) {\n this.expr = expr;\n this.env = env;\n }\n\n apply (list) {\n if (list.length !== this.env.length)\n throw new Error('Subst: expected ' + this.env.length + ' terms, got ' + list.length);\n\n let expr = this.expr;\n for (let i = 0; i < this.env.length; i++)\n expr = expr.subst(this.env[i], list[i]) ?? expr;\n\n return expr;\n }\n}\n\n// corresponds to \"chapter\" in the quest page\nclass Group {\n constructor (options) {\n this.name = options.name;\n this.intro = list2str(options.intro);\n this.id = options.id;\n\n // TODO don't die on failed quests\n if (options.content)\n this.content = options.content.map( c => c instanceof Quest ? c : new Quest(c) );\n }\n\n verify (options) {\n const findings = {};\n const id = checkId(this.id, options.seen);\n if (id)\n findings[this.id] = id;\n for (const field of ['name', 'intro']) {\n const found = checkHtml(this[field]);\n if (found)\n findings[field] = found;\n }\n\n findings.content = this.content.map(q => q.verify(options));\n return findings;\n }\n}\n\n/**\n * @desc Concatenate long strings represented as arrays, or just pass along if already string or undefined.\n * @param {string|Array<string>|undefined} str\n * @returns {string|undefined}\n */\nfunction list2str (str) {\n if (str === undefined || typeof str === 'string')\n return str;\n return Array.isArray(str) ? str.join(' ') : '' + str;\n}\n\nfunction checkId (id, seen) {\n if (id === undefined)\n return 'missing';\n if (typeof id !== 'string' && typeof id !== 'number' )\n return 'is a ' + typeof id;\n if (seen) {\n if (seen.has(id))\n return 'duplicate id ' + id;\n seen.add(id);\n }\n // return nothing = success\n}\n\nfunction checkHtml (str) {\n if (str === undefined)\n return 'missing';\n if (typeof str !== 'string')\n return 'not a string but ' + typeof str;\n\n // very basic check for unclosed tags, just to catch common mistakes in the quest text\n const tagStack = [];\n const tagRegex = /<\\/?([a-z]+)(?:\\s[^>]*)?>/gi;\n let match;\n while ((match = tagRegex.exec(str)) !== null) {\n const [fullTag, tagName] = match;\n if (fullTag.startsWith('</')) {\n // Closing tag\n if (tagStack.length === 0 || tagStack.pop() !== tagName)\n return (`Unmatched closing tag: </${tagName}>`);\n } else {\n // Opening tag\n tagStack.push(tagName);\n }\n }\n if (tagStack.length > 0)\n return (`Unclosed tags: ${tagStack.join(', ')}`);\n\n return null; // No issues found\n}\n\nQuest.Group = Group;\nQuest.Case = Case;\n\nmodule.exports = { Quest };\n", "'use strict';\n\nconst { Expr, Alias, FreeVar } = require('./expr');\nconst { Quest } = require('./quest');\n\n/**\n * @desc Extra utilities that do not belong in the core.\n */\n\n/**\n * @experimental\n * @desc Look for an expression that matches the predicate,\n * starting with the seed and applying the terms to one another.\n *\n * A predicate returning 0 (or nothing) means \"keep looking\",\n * a positive number stands for \"found\",\n * and a negative means \"discard this term from further applications\".\n *\n * The order of search is from shortest to longest expressions.\n *\n * @param {Expr[]} seed\n * @param {object} options\n * @param {number} [options.depth] - maximum generation to search for\n * @param {number} [options.tries] - maximum number of tries before giving up\n * @param {boolean} [options.infer] - whether to call infer(), default true.\n * @param {number} [options.maxArgs] - arguments in infer()\n * @param {number} [options.max] - step limit in infer()\n * @param {boolean} [options.noskip] - prevents skipping equivalent terms. Always true if infer is false.\n * @param {boolean} [retain] - if true. also add the whole cache to returned value\n * @param {({gen: number, total: number, probed: number, step: boolean}) => void} [options.progress]\n * @param {number} [options.progressInterval] - minimum number of tries between calls to options.progress, default 1000.\n * @param {(e: Expr, props: {}) => number?} predicate\n * @return {{expr?: Expr, total: number, probed: number, gen: number, cache?: Expr[][]}}\n */\nfunction search (seed, options, predicate) {\n const {\n depth = 16,\n infer = true,\n progressInterval = 1000,\n } = options;\n const hasSeen = infer && !options.noskip;\n\n // cache[i] = ith generation, 0 is empty\n const cache = [[]];\n let total = 0;\n let probed = 0;\n const seen = {};\n\n const maybeProbe = term => {\n total++;\n const props = infer ? term.infer({ max: options.max, maxArgs: options.maxArgs }) : null;\n if (hasSeen && props.expr) {\n if (seen[props.expr])\n return { res: -1 };\n seen[props.expr] = true;\n }\n probed++;\n const res = predicate(term, props);\n return { res, props };\n };\n\n // sieve through the seed\n for (const term of seed) {\n const { res } = maybeProbe(term);\n if (res > 0)\n return { expr: term, total, probed, gen: 1 };\n else if (res < 0)\n continue;\n\n cache[0].push(term);\n }\n\n let lastProgress;\n\n for (let gen = 1; gen < depth; gen++) {\n if (options.progress) {\n options.progress({ gen, total, probed, step: true });\n lastProgress = total;\n }\n for (let i = 0; i < gen; i++) {\n for (const a of cache[gen - i - 1] || []) {\n for (const b of cache[i] || []) {\n if (total >= options.tries)\n return { total, probed, gen, ...(options.retain ? { cache } : {}) };\n if (options.progress && total - lastProgress >= progressInterval) {\n options.progress({ gen, total, probed, step: false });\n lastProgress = total;\n }\n const term = a.apply(b);\n const { res, props } = maybeProbe(term);\n\n if (res > 0)\n return { expr: term, total, probed, gen, ...(options.retain ? { cache } : {}) };\n else if (res < 0)\n continue;\n\n // if the term is not reducible, it is more likely to be a dead end, so we push it further away\n const offset = infer\n ? ((props.expr ? 0 : 3) + (props.dup ? 1 : 0) + (props.proper ? 0 : 1))\n : 0;\n if (!cache[gen + offset])\n cache[gen + offset] = [];\n cache[gen + offset].push(term);\n }\n }\n }\n }\n\n return { total, probed, gen: depth, ...(options.retain ? { cache } : {}) };\n}\n\n/**\n * @desc Recursively replace all instances of Expr in a data structure with\n * respective string representation using the format() options.\n * Objects of other types and primitive values are eft as is.\n *\n * May be useful for debugging or diagnostic output.\n *\n * @experimental\n *\n * @param {any} obj\n * @param {object} [options] - see Expr.format()\n * @returns {any}\n */\nfunction deepFormat (obj, options = {}) {\n if (obj instanceof Expr)\n return obj.format(options);\n // TODO for quests, use toJSON when it's ready\n if (obj instanceof Quest)\n return 'Quest(' + obj.name + ')';\n if (obj instanceof Quest.Case)\n return 'Quest.Case';\n if (Array.isArray(obj))\n return obj.map(deepFormat);\n if (typeof obj !== 'object' || obj === null || obj.constructor !== Object)\n return obj;\n\n // default = plain object\n const out = {};\n for (const key in obj)\n out[key] = deepFormat(obj[key]);\n\n return out;\n}\n\n/**\n * @desc Given an expression and a hash of named terms,\n * return a semicolon-separated string that declares said expression\n * unambiguously.\n *\n * @example\n * var expr = ski.parse(\"T=CI; V=BCT; V x y\");\n * SKI.extras.declare(expr, expr.context.env);\n * // 'B; C; I; T=CI; V=BC(T); x=; y=; Vx y'\n *\n * @param {Expr} expr\n * @param {{[s: string]: Named}} [env]\n * @returns {string}\n */\nfunction declare (expr, env) {\n const res = Expr.extras.toposort([expr], env);\n\n return res.list.map(s => {\n if (s instanceof Alias)\n return s.name + '=' + s.impl.format({ inventory: res.env });\n if (s instanceof FreeVar)\n return s.name + '=';\n return s.format({ inventory: res.env });\n }).join('; ');\n}\n\n/**\n * @experimental\n * @desc Fold an application tree bottom to top.\n * For each subtree, the function is given the term in the root position and\n * a list of the results of folding its arguments.\n *\n * E,g, fold('x y (z t)', f) results in f(x, [f(y, []), f(z, [f(t, [])])])\n *\n * @template T\n * @param {Expr} expr\n * @param {(head: Expr, tail: T[]) => T} fun\n * @return {T}\n */\n\nfunction foldr (expr, fun) {\n const [head, ...tail] = expr.unroll();\n return fun(head, tail.map(e => foldr(e, fun)));\n}\n\nmodule.exports = { search, deepFormat, declare, foldr };\n", "const { SKI } = require('./src/parser');\nconst { Quest } = require('./src/quest');\nconst extras = require('./src/extras');\n\nSKI.Quest = Quest;\nSKI.extras = { ...extras, ...SKI.classes.Expr.extras };\n\n// SKI_REPL=1 node -r ./index.js\nif (typeof process === 'object' && process.env.SKI_REPL && typeof global !== 'undefined') {\n global.SKI = SKI;\n console.log('SKI_REPL activated, try `new SKI();`');\n}\n\n// we're in a browser\nif (typeof window !== 'undefined')\n window.SKI = SKI;\n\nmodule.exports = { SKI, Quest }; // TODO remove Quest on next breaking release, it's in SKI already!\n"],
|
|
5
|
-
"mappings": "oEAAA,IAAAA,EAAAC,EAAA,CAAAC,GAAAC,KAAA,KAAMC,EAAN,KAAgB,CAOd,eAAgBC,EAAO,CACrB,IAAMC,EAAM,YAAcD,EACvB,IAAIE,GAAK,MAAQA,EAAI,GAAG,EACxB,KAAK,CAACC,EAAGC,IAAMA,EAAE,OAASD,EAAE,MAAM,EAClC,KAAK,GAAG,EACX,KAAK,IAAM,IAAI,OAAOF,EAAK,KAAK,CAClC,CAOA,MAAOI,EAAK,CACV,KAAK,IAAI,UAAY,EACrB,IAAMC,EAAO,CAAC,GAAGD,EAAI,SAAS,KAAK,GAAG,CAAC,EAIjCE,EADMD,EAAK,IAAI,GACH,OAAS,EAE3B,GAAIC,IAASF,EAAI,OACf,MAAM,IAAI,MAAM,yBAA2BE,EAAO,IAAMF,EAAI,OAChD,kBAAoBA,EAAI,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AAM,CAACC,EAAM,GAAGC,CAAI,EAAIN,EAAK,OAAO,EACpC,OAAOI,EAAIC,EAAMC,EAAK,IAAIC,GAAKJ,GAAMI,EAAGH,CAAG,CAAC,CAAC,CAC/C,CAEApC,GAAO,QAAU,CAAE,OAAAK,GAAQ,WAAAsB,GAAY,QAAAI,GAAS,MAAAI,EAAM,IC9LtD,IAAAK,GAAAC,EAAA,CAAAC,GAAAC,KAAA,IAAM,CAAE,IAAAC,CAAI,EAAI,IACV,CAAE,MAAAC,EAAM,EAAI,KACZC,GAAS,KAEfF,EAAI,MAAQC,GACZD,EAAI,OAAS,CAAE,GAAGE,GAAQ,GAAGF,EAAI,QAAQ,KAAK,MAAO,EAGjD,OAAO,SAAY,UAAY,QAAQ,IAAI,UAAY,OAAO,OAAW,MAC3E,OAAO,IAAMA,EACb,QAAQ,IAAI,sCAAsC,GAIhD,OAAO,OAAW,MACpB,OAAO,IAAMA,GAEfD,GAAO,QAAU,CAAE,IAAAC,EAAK,MAAAC,EAAM",
|
|
6
|
-
"names": ["require_internal", "__commonJSMin", "exports", "module", "Tokenizer", "terms", "src", "s", "a", "b", "str", "list", "last", "x", "tokRestrict", "restrict", "set", "spec", "out", "act", "sym", "mode", "TraverseControl", "value", "decoration", "unwrap", "prepareWrapper", "label", "fun", "require_expr", "__commonJSMin", "exports", "module", "unwrap", "prepareWrapper", "DEFAULTS", "ORDER", "control", "native", "Expr", "_Expr", "options", "guess", "args", "expr", "arg", "App", "Alias", "FreeVar", "change", "order", "_", "action", "prev", "next", "predicate", "initial", "combine", "value", "nargs", "probe", "steps", "main", "i", "firstVar", "
|
|
4
|
+
"sourcesContent": ["class Tokenizer {\n /**\n * @desc Create a tokenizer that splits strings into tokens according to the given terms.\n * The terms are interpreted as regular expressions, and are sorted by length\n * to ensure that longer matches are preferred over shorter ones.\n * @param {...string|RegExp} terms\n */\n constructor (...terms) {\n const src = '$|(\\\\s+)|' + terms\n .map(s => '(?:' + s + ')')\n .sort((a, b) => b.length - a.length)\n .join('|');\n this.rex = new RegExp(src, 'gys');\n }\n\n /**\n * @desc Split the given string into tokens according to the terms specified in the constructor.\n * @param {string} str\n * @return {string[]}\n */\n split (str) {\n this.rex.lastIndex = 0;\n const list = [...str.matchAll(this.rex)];\n\n // did we parse everything?\n const eol = list.pop();\n const last = eol?.index ?? 0;\n\n if (last !== str.length) {\n throw new Error('Unknown tokens at pos ' + last + '/' + str.length\n + ' starting with ' + str.substring(last));\n }\n\n // skip whitespace\n return list.filter(x => x[1] === undefined).map(x => x[0]);\n }\n}\n\nconst tokRestrict = new Tokenizer('[-=+]', '[A-Z]', '\\\\b[a-z_][a-z_0-9]*\\\\b');\n\n/**\n * @desc Add ot remove tokens from a set according to a spec string.\n * The spec string is a sequence of tokens, with each group optionally prefixed\n * by one of the operators '=', '+', or '-'.\n * The '=' operator resets the set to contain only the following token(s).\n * @param {Set<string>} set\n * @param {string} [spec]\n * @returns {Set<string>}\n */\nfunction restrict (set, spec) {\n if (!spec)\n return set;\n let out = new Set([...set]);\n const act = {\n '=': sym => { out = new Set([sym]); mode = '+'; },\n '+': sym => { out.add(sym); },\n '-': sym => { out.delete(sym); },\n };\n\n let mode = '=';\n for (const sym of tokRestrict.split(spec)) {\n if (act[sym])\n mode = sym;\n else\n act[mode](sym);\n }\n return out;\n}\n\nclass TraverseControl {\n /**\n * @desc A wrapper for values returned by fold/traverse callbacks\n * which instructs the traversal to alter its behavior while\n * retaining the value in question.\n *\n * This class is instantiated internally be `SKI.control.*` functions,\n * and is not intended to be used directly by client code.\n *\n * @template T\n * @param {T} value\n * @param {function(T): TraverseControl<T>} decoration\n */\n constructor (value, decoration) {\n this.value = value;\n this.decoration = decoration;\n }\n}\n\n/**\n * @private\n * @template T\n * @param {T|TraverseControl<T>|null} value\n * @returns {[T?, function|undefined]}\n */\nfunction unwrap (value) {\n // `?? undefined` so that null is not 'an object'\n if (value instanceof TraverseControl)\n return [value.value ?? undefined, value.decoration];\n return [value ?? undefined, undefined];\n}\n\n/**\n * @desc Prepare a self-referencing wrapper function for use as a fold/traverse control decorator.\n *\n * If `fun` is created by `prepareWrapper`, then\n * unwrap(fun(x)) will always return exactly [x, fun], and the second value can be checked with ===.\n *\n * An optional label can be provided for debugging purposes.\n *\n * @private\n * @template T\n * @param {string} [label]\n * @returns {function(T): TraverseControl<T>}\n */\nfunction prepareWrapper (label) {\n const fun = value => new TraverseControl(value, fun);\n fun.label = label;\n fun.toString = () => 'TraverseControl::' + label;\n return fun;\n}\n\nmodule.exports = { Tokenizer, restrict, unwrap, prepareWrapper };\n", "'use strict';\n\nconst { unwrap, prepareWrapper } = require('./internal');\n\nconst DEFAULTS = {\n max: 1000,\n maxArgs: 32,\n};\n\nconst ORDER = {\n 'leftmost-outermost': 'LO',\n 'leftmost-innermost': 'LI',\n LO: 'LO',\n LI: 'LI',\n};\n\n/**\n * @template T\n * @typedef {T | TraverseControl<T> | null} TraverseValue\n */\n/**\n * @desc Control primitives for fold() and traverse() methods.\n * @template T\n * @type {{[name: string]: function(T): TraverseControl<T>}}\n */\nconst control = {\n descend: prepareWrapper('descend'),\n prune: prepareWrapper('prune'),\n redo: prepareWrapper('redo'),\n stop: prepareWrapper('stop'),\n};\n\n/**\n * @desc List of predefined native combinators.\n * This is required for toSKI() to work, otherwise could as well have been in parser.js.\n * @type {{[key: string]: Native}}\n */\nconst native = {};\n\n/**\n * @typedef {Expr | function(Expr): Partial} Partial\n */\n\n/**\n * @typedef {{\n * normal: boolean, // whether the term becomes irreducible after receiving a number of arguments.\n * // if false, other properties may be missing.\n * proper: boolean, // whether the irreducible form is only contains its arguments. implies normal.\n * arity?: number, // the number of arguments that is sufficient to reach the normal form\n * // absent unless normal.\n * discard?: boolean, // whether the term (or subterms, unless proper) can discard arguments.\n * duplicate?: boolean, // whether the term (or subterms, unless proper) can duplicate arguments.\n * skip?: Set<number>, // indices of arguments that are discarded. nonempty inplies discard.\n * dup?: Set<number>, // indices of arguments that are duplicated. nonempty implies duplicate.\n * expr?: Expr, // canonical form containing lambdas, applications, and variables, if any\n * steps?: number, // number of steps taken to obtain the aforementioned information, if applicable\n * }} TermInfo\n */\n\nclass Expr {\n /**\n * @descr A combinatory logic expression.\n *\n * Applications, variables, and other terms like combinators per se\n * are subclasses of this class.\n *\n * @abstract\n * @property {{\n * scope?: any,\n * env?: { [key: string]: Expr },\n * src?: string,\n * parser: object,\n * }} [context]\n * @property {number} [arity] - number of arguments the term is waiting for (if known)\n * @property {string} [note] - a brief description what the term does\n * @property {string} [fancyName] - how to display in html mode, e.g. φ instead of 'f'\n * Typically only applicable to descendants of Named.\n * @property {TermInfo} [props] - properties inferred from the term's behavior\n */\n\n /**\n *\n * @desc Define properties of the term based on user supplied options and/or inference results.\n * Typically useful for declaring Native and Alias terms.\n * @private\n * @param {Object} options\n * @param {string} [options.note] - a brief description what the term does\n * @param {number} [options.arity] - number of arguments the term is waiting for (if known)\n * @param {string} [options.fancy] - how to display in html mode, e.g. φ instead of 'f'\n * @param {boolean} [options.canonize] - whether to try to infer the properties\n * @param {number} [options.max] - maximum number of steps for inference, if canonize is true\n * @param {number} [options.maxArgs] - maximum number of arguments for inference, if canonize is true\n * @return {this}\n */\n _setup (options = {}) {\n // TODO better name\n\n if (options.fancy !== undefined)\n this.fancyName = options.fancyName;\n\n if (options.note !== undefined)\n this.note = options.note;\n\n if (options.arity !== undefined)\n this.arity = options.arity;\n\n if (options.canonize) {\n const guess = this.infer(options);\n if (guess.normal) {\n this.arity = this.arity ?? guess.arity;\n this.note = this.note ?? guess.expr.format({ html: true, lambda: ['', ' ↦ ', ''] });\n delete guess.steps;\n this.props = guess;\n }\n }\n return this;\n }\n\n /**\n * @desc apply self to zero or more terms and return the resulting term,\n * without performing any calculations whatsoever\n * @param {Expr} args\n * @return {Expr}\n */\n apply (...args) {\n let expr = this;\n for (const arg of args)\n expr = new App(expr, arg);\n return expr;\n }\n\n /**\n * @desc Replace all aliases in the expression with their definitions, recursively.\n * @return {Expr}\n */\n expand () {\n return this.traverse(e => {\n if (e instanceof Alias)\n return e.impl.expand();\n }) ?? this;\n }\n\n /**\n * @desc Returns true if the expression contains only free variables and applications, false otherwise.\n * @returns {boolean}\n */\n freeOnly () {\n return !this.any(e => !(e instanceof FreeVar || e instanceof App));\n }\n\n /**\n * @desc Traverse the expression tree, applying change() to each node.\n * If change() returns an Expr, the node is replaced with that value.\n * A null/undefined value is interpreted as\n * \"descend further if applicable, or leave the node unchanged\".\n *\n * Returned values may be decorated:\n *\n * SKI.control.prune will suppress further descending even if nothing was returned\n * SKI.control.stop will terminate further changes.\n * SKI.control.redo will apply the callback to the returned subtree, recursively.\n *\n * Note that if redo was applied at least once to a subtree, a null return from the same subtree\n * will be replaced by the last non-null value returned.\n *\n * The traversal order is leftmost-outermost, unless options.order = 'leftmost-innermost' is specified.\n * Short aliases 'LO' and 'LI' (case-sensitive) are also accepted.\n *\n * Returns null if no changes were made, or the new expression otherwise.\n *\n * @param {{\n * order?: 'LO' | 'LI' | 'leftmost-outermost' | 'leftmost-innermost',\n * }} [options]\n * @param {(e:Expr) => TraverseValue<Expr>} change\n * @returns {Expr|null}\n */\n traverse (options, change) {\n if (typeof options === 'function') {\n change = options;\n options = {};\n }\n const order = ORDER[options.order ?? 'LO'];\n if (order === undefined)\n throw new Error('Unknown traversal order: ' + options.order);\n const [expr, _] = unwrap(this._traverse_redo({ order }, change));\n return expr;\n }\n\n /**\n * @private\n * @param {Object} options\n * @param {(e:Expr) => TraverseValue<Expr>} change\n * @returns {TraverseValue<Expr>}\n */\n _traverse_redo (options, change) {\n let action;\n let expr = this;\n let prev;\n do {\n prev = expr;\n const next = options.order === 'LI'\n ? expr._traverse_descend(options, change) ?? change(expr)\n : change(expr) ?? expr._traverse_descend(options, change);\n [expr, action] = unwrap(next);\n } while (expr && action === control.redo);\n if (!expr && prev !== this)\n expr = prev; // we were in redo at least once\n return action ? action(expr) : expr;\n }\n\n /**\n * @private\n * @param {Object} options\n * @param {(e:Expr) => TraverseValue<Expr>} change\n * @returns {TraverseValue<Expr>}\n */\n\n _traverse_descend (options, change) {\n return null;\n }\n\n /**\n * @desc Returns true if predicate() is true for any subterm of the expression, false otherwise.\n *\n * @param {(e: Expr) => boolean} predicate\n * @returns {boolean}\n */\n any (predicate) {\n return predicate(this);\n }\n\n /**\n * @desc Fold the expression into a single value by recursively applying combine() to its subterms.\n * Nodes are traversed in leftmost-outermost order, i.e. the same order as reduction steps are taken.\n *\n * null or undefined return value from combine() means \"keep current value and descend further\".\n *\n * SKI.control provides primitives to control the folding flow:\n * - SKI.control.prune(value) means \"use value and don't descend further into this branch\";\n * - SKI.control.stop(value) means \"stop folding immediately and return value\".\n * - SKI.control.descend(value) is the default behavior, meaning \"use value and descend further\".\n *\n * This method is experimental and may change in the future.\n *\n * @experimental\n * @template T\n * @param {T} initial\n * @param {(acc: T, expr: Expr) => TraverseValue<T>} combine\n * @returns {T}\n */\n fold (initial, combine) {\n const [value, _] = unwrap(this._fold(initial, combine));\n return value ?? initial;\n }\n\n /**\n * @experimental\n * @desc Fold an application tree bottom to top.\n * For each subtree, the function is given the term in the root position and\n * a list of the results of folding its arguments.\n *\n * E.g. fold('x y (z t)', f) results in f(x, [f(y, []), f(z, [f(t, [])])])\n *\n * @example expr.foldBottomUp((head, tail) => {\n * if (head.arity && head.arity <= tail.length) {\n * return '(<span class=\"redex\">'\n * + head + ' '\n * + tail.slice(0, head.arity).join(' ')\n * + '</span>'\n * + tail.slice(head.arity).join(' ')\n * + ')';\n * } else {\n * return '(' + head + ' ' + tail.join(' ') + ')';\n * }\n * });\n * @template T\n * @param {(head: Expr, tail: T[]) => T} fun\n * @return {T}\n */\n foldBottomUp (fun) {\n const [head, ...tail] = this.unroll();\n return fun(head, tail.map(e => e.foldBottomUp(fun)));\n }\n\n /**\n * @template T\n * @param {T} initial\n * @param {(acc: T, expr: Expr) => TraverseValue<T>} combine\n * @returns {TraverseValue<T>}\n * @private\n */\n _fold (initial, combine) {\n return combine(initial, this);\n }\n\n /**\n * @desc rough estimate of the term's complexity\n * @return {number}\n */\n weight () {\n // TODO remove in next breaking release\n return 1;\n }\n\n /**\n * @desc Try to empirically find an equivalent lambda term for the expression,\n * returning also the term's arity and some other properties.\n *\n * This is used internally when declaring a Native / Alias term,\n * unless {canonize: false} is used.\n *\n * As of current it only recognizes terms that have a normal form,\n * perhaps after adding some variables. This may change in the future.\n *\n * Use toLambda() if you want to get a lambda term in any case.\n *\n * @param {{max?: number, maxArgs?: number}} options\n * @return {TermInfo}\n */\n infer (options = {}) {\n return this._infer({\n max: options.max ?? DEFAULTS.max,\n maxArgs: options.maxArgs ?? DEFAULTS.maxArgs,\n }, 0);\n }\n\n /**\n * @desc Internal method for infer(), which performs the actual inference.\n * @param {{max: number, maxArgs: number}} options\n * @param {number} nargs - var index to avoid name clashes\n * @returns {TermInfo}\n * @private\n */\n _infer (options, nargs) {\n const probe = [];\n let steps = 0;\n let expr = this;\n // eslint-disable-next-line no-labels\n main: for (let i = 0; i < options.maxArgs; i++) {\n const next = expr.run({ max: options.max - steps });\n // console.log(`infer step ${i}, expr = ${expr}, probe = [${probe}]: `, next);\n steps += next.steps;\n if (!next.final)\n break;\n if (firstVar(next.expr)) {\n // can't append more variables, return or recurse\n expr = next.expr;\n if (!expr.any(e => !(e instanceof FreeVar || e instanceof App)))\n return maybeLambda(probe, expr, { steps });\n const list = expr.unroll();\n let discard = false;\n let duplicate = false;\n const acc = [];\n for (let j = 1; j < list.length; j++) {\n const sub = list[j]._infer(\n { maxArgs: options.maxArgs - nargs, max: options.max - steps }, // limit recursion\n nargs + i // avoid variable name clashes\n );\n steps += sub.steps;\n if (!sub.expr)\n // eslint-disable-next-line no-labels\n break main; // press f to pay respects\n if (sub.discard)\n discard = true;\n if (sub.duplicate)\n duplicate = true;\n acc.push(sub.expr);\n }\n return maybeLambda(probe, list[0].apply(...acc), { discard, duplicate, steps });\n }\n const push = nthvar(nargs + i);\n probe.push(push);\n expr = next.expr.apply(push);\n }\n return { normal: false, proper: false, steps };\n }\n\n /**\n * @desc Expand an expression into a list of terms\n * that give the initial expression when applied from left to right:\n * ((a, b), (c, d)) => [a, b, (c, d)]\n *\n * This can be thought of as an opposite of apply:\n * fun.apply(...arg).unroll() is exactly [fun, ...args]\n * (even if ...arg is in fact empty).\n *\n * @returns {Expr[]}\n */\n unroll () {\n // currently only used by infer() but may be useful\n // to convert binary App trees to n-ary or smth\n return [this];\n }\n\n /**\n * @desc Returns a series of lambda terms equivalent to the given expression,\n * up to the provided computation steps limit,\n * in decreasing weight order.\n *\n * Unlike infer(), this method will always return something,\n * even if the expression has no normal form.\n *\n * See also Expr.walk() and Expr.toSKI().\n *\n * @param {{\n * max?: number,\n * maxArgs?: number,\n * varGen?: function(void): FreeVar,\n * steps?: number,\n * html?: boolean,\n * latin?: number,\n * }} options\n * @param {number} [maxWeight] - maximum allowed weight of terms in the sequence\n * @return {IterableIterator<{expr: Expr, steps?: number, comment?: string}>}\n */\n * toLambda (options = {}) {\n let expr = this.traverse(e => {\n if (e instanceof FreeVar || e instanceof App || e instanceof Lambda || e instanceof Alias)\n return null; // no change\n const guess = e.infer({ max: options.max, maxArgs: options.maxArgs });\n if (!guess.normal)\n throw new Error('Failed to infer an equivalent lambda term for ' + e);\n return guess.expr;\n }) ?? this;\n const seen = new Set(); // prine irreducible\n let steps = 0;\n while (expr) {\n const next = expr.traverse({ order: 'LI' }, e => {\n if (seen.has(e))\n return null;\n if (e instanceof App && e.fun instanceof Lambda) {\n const guess = e.infer({ max: options.max, maxArgs: options.maxArgs });\n steps += guess.steps;\n if (!guess.normal) {\n seen.add(e);\n return null;\n }\n return control.stop(guess.expr);\n }\n });\n yield { expr, steps };\n expr = next;\n }\n }\n\n /**\n * @desc Rewrite the expression into S, K, and I combinators step by step.\n * Returns an iterator yielding the intermediate expressions,\n * along with the number of steps taken to reach them.\n *\n * See also Expr.walk() and Expr.toLambda().\n *\n * @param {{max?: number}} [options]\n * @return {IterableIterator<{final: boolean, expr: Expr, steps: number}>}\n */\n * toSKI (options = {}) {\n // TODO options.max is not actually max, it's the number of steps in one iteration\n // get rid of non-lambdas\n let expr = this.traverse(e => {\n if (e instanceof FreeVar || e instanceof App || e instanceof Lambda || e instanceof Alias)\n return null;\n // TODO infer failed for atomic term? die...\n return e.infer().expr;\n }) ?? this;\n\n let steps = 0;\n while (expr) {\n const next = expr.traverse({ order: 'LI' }, e => {\n if (!(e instanceof Lambda) || (e.impl instanceof Lambda))\n return null; // continue\n if (e.impl === e.arg)\n return control.stop(native.I);\n if (!e.impl.any(t => t === e.arg))\n return control.stop(native.K.apply(e.impl));\n // TODO use real assert here. e.impl contains e.arg and also isn't e.arg, in MUST be App.\n if (!(e.impl instanceof App))\n throw new Error('toSKI: assert failed: lambda body is of unexpected type ' + e.impl.constructor.name );\n // eta-reduction: body === (not e.arg) (e.arg)\n if (e.impl.arg === e.arg && !e.impl.fun.any(t => t === e.arg))\n return control.stop(e.impl.fun);\n // last resort, go S\n return control.stop(native.S.apply(new Lambda(e.arg, e.impl.fun), new Lambda(e.arg, e.impl.arg)));\n })\n yield { expr, steps, final: !next };\n steps++;\n expr = next;\n }\n }\n\n /**\n * Replace all instances of plug in the expression with value and return the resulting expression,\n * or null if no changes could be made.\n * Lambda terms and applications will never match if used as plug\n * as they are impossible co compare without extensive computations.\n * Typically used on variables but can also be applied to other terms, e.g. aliases.\n * See also Expr.traverse().\n * @param {Expr} search\n * @param {Expr} replace\n * @return {Expr|null}\n */\n subst (search, replace) {\n return this === search ? replace : null;\n }\n\n /**\n * @desc Apply term reduction rules, if any, to the given argument.\n * A returned value of null means no reduction is possible.\n * A returned value of Expr means the reduction is complete and the application\n * of this and arg can be replaced with the result.\n * A returned value of a function means that further arguments are needed,\n * and can be cached for when they arrive.\n *\n * This method is between apply() which merely glues terms together,\n * and step() which reduces the whole expression.\n *\n * foo.invoke(bar) is what happens inside foo.apply(bar).step() before\n * reduction of either foo or bar is attempted.\n *\n * The name 'invoke' was chosen to avoid confusion with either 'apply' or 'reduce'.\n *\n * @param {Expr} arg\n * @returns {Partial | null}\n */\n invoke (arg) {\n return null;\n }\n\n /**\n * @desc iterate one step of a calculation.\n * @return {{expr: Expr, steps: number, changed: boolean}}\n */\n step () { return { expr: this, steps: 0, changed: false } }\n\n /**\n * @desc Run uninterrupted sequence of step() applications\n * until the expression is irreducible, or max number of steps is reached.\n * Default number of steps = 1000.\n * @param {{max?: number, steps?: number, throw?: boolean}|Expr} [opt]\n * @param {Expr} args\n * @return {{expr: Expr, steps: number, final: boolean}}\n */\n run (opt = {}, ...args) {\n if (opt instanceof Expr) {\n args.unshift(opt);\n opt = {};\n }\n let expr = args ? this.apply(...args) : this;\n let steps = opt.steps ?? 0;\n // make sure we make at least 1 step, to tell whether we've reached the normal form\n const max = Math.max(opt.max ?? DEFAULTS.max, 1) + steps;\n let final = false;\n for (; steps < max; ) {\n const next = expr.step();\n if (!next.changed) {\n final = true;\n break;\n }\n steps += next.steps;\n expr = next.expr;\n }\n if (opt.throw && !final)\n throw new Error('Failed to compute expression in ' + max + ' steps');\n return { final, steps, expr };\n }\n\n /**\n * Execute step() while possible, yielding a brief description of events after each step.\n * Mnemonics: like run() but slower.\n * @param {{max?: number}} options\n * @return {IterableIterator<{final: boolean, expr: Expr, steps: number}>}\n */\n * walk (options = {}) {\n const max = options.max ?? Infinity;\n let steps = 0;\n let expr = this;\n let final = false;\n\n while (steps < max) {\n // 1. calculate\n // 2. yield _unchanged_ expression\n // 3. either advance or stop\n const next = expr.step();\n if (!next.changed)\n final = true;\n yield { expr, steps, final };\n if (final)\n break;\n steps += next.steps;\n expr = next.expr;\n }\n }\n\n /**\n * @desc True is the expressions are identical, false otherwise.\n * Aliases are expanded.\n * Bound variables in lambda terms are renamed consistently.\n * However, no reductions are attempted.\n *\n * E.g. a->b->a == x->y->x is true, but a->b->a == K is false.\n *\n * @param {Expr} other\n * @return {boolean}\n */\n equals (other) {\n return !this.diff(other);\n }\n\n /**\n * @desc Recursively compare two expressions and return a string\n * describing the first point of difference.\n * Returns null if expressions are identical.\n *\n * Aliases are expanded.\n * Bound variables in lambda terms are renamed consistently.\n * However, no reductions are attempted.\n *\n * Members of the FreeVar class are considered different\n * even if they have the same name, unless they are the same object.\n * To somewhat alleviate confusion, the output will include\n * the internal id of the variable in square brackets.\n *\n * @example \"K(S != I)\" is the result of comparing \"KS\" and \"KI\"\n * @example \"S(K([x[13] != x[14]]))K\"\n *\n * @param {Expr} other\n * @param {boolean} [swap] If true, the order of expressions is reversed in the output.\n * @returns {string|null}\n */\n diff (other, swap = false) {\n if (this === other)\n return null;\n if (other instanceof Alias)\n return other.impl.diff(this, !swap);\n return swap\n ? '[' + other + ' != ' + this + ']'\n : '[' + this + ' != ' + other + ']';\n }\n\n /**\n * @desc Assert expression equality. Can be used in tests.\n *\n * `this` is the expected value and the argument is the actual one.\n * Mnemonic: the expected value is always a combinator, the actual one may be anything.\n *\n * @param {Expr} actual\n * @param {string} comment\n */\n expect (actual, comment = '') {\n comment = comment ? comment + ': ' : '';\n if (!(actual instanceof Expr)) {\n throw new Error(comment + 'Expected a combinator but found '\n + (actual?.constructor?.name ?? typeof actual));\n }\n const diff = this.diff(actual);\n if (!diff)\n return; // all good\n\n // TODO wanna use AssertionError but browser doesn't recognize it\n // still the below hack works for mocha-based tests.\n const poorMans = new Error(comment + diff);\n poorMans.expected = this.diag();\n poorMans.actual = actual.diag();\n throw poorMans;\n }\n\n /**\n * @desc Returns string representation of the expression.\n * Same as format() without options.\n * @return {string}\n */\n toString () {\n return this.format();\n }\n\n /**\n * @desc Whether the expression needs parentheses when printed.\n * @param {boolean} [first] - whether this is the first term in a sequence\n * @return {boolean}\n */\n _braced (first) {\n return false;\n }\n\n /**\n * @desc Whether the expression can be printed without a space when followed by arg.\n * @param {Expr} arg\n * @returns {boolean}\n * @private\n */\n _unspaced (arg) {\n return this._braced(true);\n }\n\n /**\n * @desc Stringify the expression with fancy formatting options.\n * Said options mostly include wrappers around various constructs in form of ['(', ')'],\n * as well as terse and html flags that set up the defaults.\n * Format without options is equivalent to toString() and can be parsed back.\n *\n * @param {Object} [options] - formatting options\n * @param {boolean} [options.terse] - whether to use terse formatting (omitting unnecessary spaces and parentheses)\n * @param {boolean} [options.html] - whether to default to HTML tags & entities.\n * If a named term has fancyName property set, it will be used instead of name in this mode.\n * @param {[string, string]} [options.brackets] - wrappers for application arguments, typically ['(', ')']\n * @param {[string, string]} [options.var] - wrappers for variable names\n * (will default to <var> and </var> in html mode).\n * @param {[string, string, string]} [options.lambda] - wrappers for lambda abstractions, e.g. ['λ', '.', '']\n * where the middle string is placed between argument and body\n * default is ['', '->', ''] or ['', '->', ''] for html\n * @param {[string, string]} [options.around] - wrappers around (sub-)expressions.\n * individual applications will not be wrapped, i.e. (a b c) but not ((a b) c)\n * @param {[string, string]} [options.redex] - wrappers around the starting term(s) that have enough arguments to be reduced\n * @param {Object<string, Expr>} [options.inventory] - if given, output aliases in the set as their names\n * and any other aliases as the expansion of their definitions.\n * The default is a cryptic and fragile mechanism dependent on a hidden mutable property.\n * @returns {string}\n *\n * @example foo.format() // equivalent to foo.toString()\n * @example foo.format({terse: false}) // spell out all parentheses\n * @example foo.format({html: true}) // use HTML tags and entities\n * @example foo.format({ around: ['(', ')'], brackets: ['', ''], lambda: ['(', '->', ')'] }) // lisp style, still back-parsable\n * @exapmle foo.format({ lambda: ['λ', '.', ''] }) // pretty-print for the math department\n * @example foo.format({ lambda: ['', '=>', ''], terse: false }) // make it javascript\n * @example foo.format({ inventory: { T } }) // use T as a named term, expand all others\n *\n */\n format (options = {}) {\n const fallback = options.html\n ? {\n brackets: ['(', ')'],\n space: ' ',\n var: ['<var>', '</var>'],\n lambda: ['', '->', ''],\n around: ['', ''],\n redex: ['', ''],\n }\n : {\n brackets: ['(', ')'],\n space: ' ',\n var: ['', ''],\n lambda: ['', '->', ''],\n around: ['', ''],\n redex: ['', ''],\n }\n return this._format({\n terse: options.terse ?? true,\n brackets: options.brackets ?? fallback.brackets,\n space: options.space ?? fallback.space,\n var: options.var ?? fallback.var,\n lambda: options.lambda ?? fallback.lambda,\n around: options.around ?? fallback.around,\n redex: options.redex ?? fallback.redex,\n inventory: options.inventory, // TODO better name\n html: options.html ?? false,\n }, 0);\n }\n\n /**\n * @desc Internal method for format(), which performs the actual formatting.\n * @param {Object} options\n * @param {number} nargs\n * @returns {string}\n * @private\n */\n _format (options, nargs) {\n throw new Error( 'No _format() method defined in class ' + this.constructor.name );\n }\n\n /**\n * @desc Returns a string representation of the expression tree, with indentation to show structure.\n *\n * Applications are flattened to avoid excessive nesting.\n * Variables include ids to distinguish different instances of the same variable name.\n *\n * May be useful for debugging.\n *\n * @returns {string}\n *\n * @example\n * > console.log(ski.parse('C 5 x (x->x x)').diag())\n * App:\n * Native: C\n * Church: 5\n * FreeVar: x[53]\n * Lambda (x[54]):\n * App:\n * FreeVar: x[54]\n * FreeVar: x[54]\n */\n diag () {\n const rec = (e, indent) => {\n if (e instanceof App)\n return [indent + 'App:', ...e.unroll().flatMap(s => rec(s, indent + ' '))];\n if (e instanceof Lambda)\n return [`${indent}Lambda (${e.arg}[${e.arg.id}]):`, ...rec(e.impl, indent + ' ')];\n // no indent increase so that a diff between diags is consistent with how `equals` works.\n if (e instanceof Alias)\n return [`${indent}Alias (${e.name}): \\\\`, ...rec(e.impl, indent)];\n if (e instanceof FreeVar)\n return [`${indent}FreeVar: ${e.name}[${e.id}]`];\n return [`${indent}${e.constructor.name}: ${e}`];\n }\n\n const out = rec(this, '');\n return out.join('\\n');\n }\n\n /**\n * @desc Convert the expression to a JSON-serializable format.\n * @returns {string}\n */\n toJSON () {\n return this.format();\n }\n}\n\nclass App extends Expr {\n /**\n * @desc Application of fun() to args.\n * Never ever use new App(fun, arg) directly, use fun.apply(...args) instead.\n * @param {Expr} fun\n * @param {Expr} arg\n */\n constructor (fun, arg) {\n super();\n\n this.arg = arg;\n this.fun = fun;\n }\n /** @property {boolean} [final] */\n\n weight () {\n return this.fun.weight() + this.arg.weight();\n }\n\n _traverse_descend (options, change) {\n const [fun, fAction] = unwrap(this.fun._traverse_redo(options, change));\n if (fAction === control.stop)\n return control.stop(fun ? fun.apply(this.arg) : null);\n\n const [arg, aAction] = unwrap(this.arg._traverse_redo(options, change));\n\n const final = (fun || arg) ? (fun ?? this.fun).apply(arg ?? this.arg) : null;\n if (aAction === control.stop)\n return control.stop(final);\n return final;\n }\n\n any (predicate) {\n return predicate(this) || this.fun.any(predicate) || this.arg.any(predicate);\n }\n\n _fold (initial, combine) {\n const [value = initial, action = 'descend'] = unwrap(combine(initial, this));\n if (action === control.prune)\n return value;\n if (action === control.stop)\n return control.stop(value);\n const [fValue = value, fAction = 'descend'] = unwrap(this.fun._fold(value, combine));\n if (fAction === control.stop)\n return control.stop(fValue);\n const [aValue = fValue, aAction = 'descend'] = unwrap(this.arg._fold(fValue, combine));\n if (aAction === control.stop)\n return control.stop(aValue);\n return aValue;\n }\n\n subst (search, replace) {\n const fun = this.fun.subst(search, replace);\n const arg = this.arg.subst(search, replace);\n\n return (fun || arg) ? (fun ?? this.fun).apply(arg ?? this.arg) : null;\n }\n\n /**\n * @return {{expr: Expr, steps: number}}\n */\n\n step () {\n // normal reduction order: first try root, then at most 1 step\n if (!this.final) {\n // try to apply rewriting rules, if applicable, at first\n const partial = this.fun.invoke(this.arg);\n if (partial instanceof Expr)\n return { expr: partial, steps: 1, changed: true };\n else if (typeof partial === 'function')\n this.invoke = partial; // cache for next time\n\n // descend into the leftmost term\n const fun = this.fun.step();\n if (fun.changed)\n return { expr: fun.expr.apply(this.arg), steps: fun.steps, changed: true };\n\n // descend into arg\n const arg = this.arg.step();\n if (arg.changed)\n return { expr: this.fun.apply(arg.expr), steps: arg.steps, changed: true };\n\n // mark as irreducible\n this.final = true; // mark as irreducible at root\n }\n\n return { expr: this, steps: 0, changed: false };\n }\n\n invoke (arg) {\n // propagate invocation towards the root term,\n // caching partial applications as we go\n const partial = this.fun.invoke(this.arg);\n if (partial instanceof Expr)\n return partial.apply(arg);\n else if (typeof partial === 'function') {\n this.invoke = partial;\n return partial(arg);\n } else {\n // invoke = null => we're uncomputable, cache for next time\n this.invoke = _ => null;\n return null;\n }\n }\n\n unroll () {\n return [...this.fun.unroll(), this.arg];\n }\n\n diff (other, swap = false) {\n if (!(other instanceof App))\n return super.diff(other, swap);\n\n const fun = this.fun.diff(other.fun, swap);\n if (fun)\n return fun + '(...)';\n const arg = this.arg.diff(other.arg, swap);\n if (arg)\n return this.fun + '(' + arg + ')';\n return null;\n }\n\n _braced (first) {\n return !first;\n }\n\n _format (options, nargs) {\n const fun = this.fun._format(options, nargs + 1);\n const arg = this.arg._format(options, 0);\n const wrap = nargs ? ['', ''] : options.around;\n // TODO ignore terse for now\n if (options.terse && !this.arg._braced(false))\n return wrap[0] + fun + (this.fun._unspaced(this.arg) ? '' : options.space) + arg + wrap[1];\n else\n return wrap[0] + fun + options.brackets[0] + arg + options.brackets[1] + wrap[1];\n }\n\n _unspaced (arg) {\n return this.arg._braced(false) ? true : this.arg._unspaced(arg);\n }\n}\n\nclass Named extends Expr {\n /**\n * @desc An abstract class representing a term named 'name'.\n *\n * @param {String} name\n */\n constructor (name) {\n super();\n if (typeof name !== 'string' || name.length === 0)\n throw new Error('Attempt to create a named term with improper name');\n this.name = name;\n }\n\n _unspaced (arg) {\n return !!(\n (arg instanceof Named) && (\n (this.name.match(/^[A-Z+]$/) && arg.name.match(/^[a-z+]/i))\n || (this.name.match(/^[a-z+]/i) && arg.name.match(/^[A-Z+]$/))\n )\n );\n }\n\n _format (options, nargs) {\n // NOTE fancyName is not yet official and may change name or meaning\n const name = options.html ? this.fancyName ?? this.name : this.name;\n return this.arity > 0 && this.arity <= nargs\n ? options.redex[0] + name + options.redex[1]\n : name;\n }\n}\n\nlet freeId = 0;\n\nclass FreeVar extends Named {\n /**\n * @desc A named variable.\n *\n * Given the functional nature of combinatory logic, variables are treated\n * as functions that we don't know how to evaluate just yet.\n *\n * By default, two different variables even with the same name are considered different.\n * They display it via a hidden id property.\n *\n * If a scope object is given, however, two variables with the same name and scope\n * are considered identical.\n *\n * By convention, FreeVar.global is a constant denoting a global unbound variable.\n *\n * @param {string} name - name of the variable\n * @param {any} scope - an object representing where the variable belongs to.\n */\n constructor (name, scope) {\n super(name);\n this.id = ++freeId;\n // TODO temp compatibility mode\n this.scope = scope === undefined ? this : scope;\n }\n\n weight () {\n return 0;\n }\n\n diff (other, swap = false) {\n if (!(other instanceof FreeVar))\n return super.diff(other, swap);\n if (this.name === other.name && this.scope === other.scope)\n return null;\n const lhs = this.name + '[' + this.id + ']';\n const rhs = other.name + '[' + other.id + ']';\n return swap\n ? '[' + rhs + ' != ' + lhs + ']'\n : '[' + lhs + ' != ' + rhs + ']';\n }\n\n subst (search, replace) {\n if (search instanceof FreeVar && search.name === this.name && search.scope === this.scope)\n return replace;\n return null;\n }\n\n _format (options, nargs) {\n const name = options.html ? this.fancyName ?? this.name : this.name;\n return options.var[0] + name + options.var[1];\n }\n}\n\nFreeVar.global = ['global'];\n\nclass Native extends Named {\n /**\n * @desc A named term with a known rewriting rule.\n * 'impl' is a function with signature Expr => Expr => ... => Expr\n * (see typedef Partial).\n * This is how S, K, I, and company are implemented.\n *\n * Note that as of current something like a=>b=>b(a) is not possible,\n * use full form instead: a=>b=>b.apply(a).\n *\n * @example new Native('K', x => y => x); // constant\n * @example new Native('Y', function(f) { return f.apply(this.apply(f)); }); // self-application\n *\n * @param {String} name\n * @param {Partial} impl\n * @param {{note?: string, arity?: number, canonize?: boolean }} [opt]\n */\n constructor (name, impl, opt = {}) {\n super(name);\n // setup essentials\n this.invoke = impl;\n\n this._setup({ canonize: true, ...opt });\n }\n}\n\nclass Lambda extends Expr {\n /**\n * @desc Lambda abstraction of arg over impl.\n * Upon evaluation, all occurrences of 'arg' within 'impl' will be replaced\n * with the provided argument.\n *\n * Note that 'arg' will be replaced by a localized placeholder, so the original\n * variable can be used elsewhere without interference.\n * Listing symbols contained in the lambda will omit such placeholder.\n *\n * Legacy ([FreeVar], impl) constructor is supported but deprecated.\n * It will create a nested lambda expression.\n *\n * @param {FreeVar} arg\n * @param {Expr} impl\n */\n constructor (arg, impl) {\n if (Array.isArray(arg)) {\n // check args before everything\n if (arg.length === 0)\n throw new Error('empty argument list in lambda constructor');\n\n const [my, ...tail] = arg;\n const known = new Set([my.name]);\n\n while (tail.length > 0) {\n const last = tail.pop();\n if (known.has(last.name))\n throw new Error('Duplicate free var name ' + last + ' in lambda expression');\n known.add(last.name);\n\n // TODO keep track of arity to speed up execution\n impl = new Lambda(last, impl);\n }\n arg = my;\n }\n\n super();\n\n // localize argument variable and bind it to oneself\n const local = new FreeVar(arg.name, this);\n this.arg = local;\n this.impl = impl.subst(arg, local) ?? impl;\n this.arity = 1;\n }\n\n weight () {\n return this.impl.weight() + 1;\n }\n\n invoke (arg) {\n return this.impl.subst(this.arg, arg) ?? this.impl;\n }\n\n _traverse_descend (options, change) {\n // alas no proper shielding of self.arg is possible\n const [impl, iAction] = unwrap(this.impl._traverse_redo(options, change));\n\n const final = impl ? new Lambda(this.arg, impl) : null;\n\n return iAction === control.stop ? control.stop(final) : final;\n }\n\n any (predicate) {\n return predicate(this) || this.impl.any(predicate);\n }\n\n _fold (initial, combine) {\n const [value = initial, action = 'descend'] = unwrap(combine(initial, this));\n if (action === control.prune)\n return value;\n if (action === control.stop)\n return control.stop(value);\n const [iValue, iAction] = unwrap(this.impl._fold(value, combine));\n if (iAction === control.stop)\n return control.stop(iValue);\n return iValue ?? value;\n }\n\n subst (search, replace) {\n if (search === this.arg)\n return null;\n const change = this.impl.subst(search, replace);\n return change ? new Lambda(this.arg, change) : null;\n }\n\n diff (other, swap = false) {\n if (!(other instanceof Lambda))\n return super.diff(other, swap);\n\n const t = new FreeVar('t'); // TODO better placeholder name\n\n const diff = this.invoke(t).diff(other.invoke(t), swap);\n if (diff)\n return '(t->' + diff + ')'; // parentheses required to avoid ambiguity\n return null;\n }\n\n _format (options, nargs) {\n return (nargs > 0 ? options.brackets[0] : '')\n + options.lambda[0]\n + this.arg._format(options, 0) // TODO highlight redex if nargs > 0\n + options.lambda[1]\n + this.impl._format(options, 0) + options.lambda[2]\n + (nargs > 0 ? options.brackets[1] : '');\n }\n\n _braced (first) {\n return true;\n }\n}\n\nclass Church extends Expr {\n /**\n * @desc Church numeral representing non-negative integer n:\n * n f x = f(f(...(f x)...)) with f applied n times.\n * @param {number} n\n */\n constructor (n) {\n n = Number.parseInt(n);\n if (!(n >= 0))\n throw new Error('Church number must be a non-negative integer');\n super();\n this.invoke = x => y => {\n let expr = y;\n for (let i = n; i-- > 0; )\n expr = x.apply(expr);\n return expr;\n };\n\n /** @type {number} */\n this.n = n;\n this.arity = 2;\n }\n\n diff (other, swap = false) {\n if (!(other instanceof Church))\n return super.diff(other, swap);\n if (this.n === other.n)\n return null;\n return swap\n ? '[' + other.n + ' != ' + this.n + ']'\n : '[' + this.n + ' != ' + other.n + ']';\n }\n\n _unspaced (arg) {\n return false;\n }\n\n _format (options, nargs) {\n return nargs >= 2\n ? options.redex[0] + this.n + options.redex[1]\n : this.n + '';\n }\n}\n\nfunction waitn (expr, n) {\n return arg => n <= 1 ? expr.apply(arg) : waitn(expr.apply(arg), n - 1);\n}\n\nclass Alias extends Named {\n /**\n * @desc A named alias for an existing expression.\n *\n * Upon evaluation, the alias expands into the original expression,\n * unless it has a known arity > 0 and is marked terminal,\n * in which case it waits for enough arguments before expanding.\n *\n * A hidden mutable property 'outdated' is used to silently\n * replace the alias with its definition in all contexts.\n * This is used when declaring named terms in an interpreter,\n * to avoid confusion between old and new terms with the same name.\n *\n * @param {String} name\n * @param {Expr} impl\n * @param {{canonize?: boolean, max?: number, maxArgs?: number, note?: string, terminal?: boolean}} [options]\n */\n constructor (name, impl, options = {}) {\n super(name);\n if (!(impl instanceof Expr))\n throw new Error('Attempt to create an alias for a non-expression: ' + impl);\n this.impl = impl;\n\n this._setup(options);\n this.terminal = options.terminal ?? this.props?.proper;\n this.invoke = waitn(impl, this.arity ?? 0);\n }\n\n /**\n * @property {boolean} [outdated] - whether the alias is outdated\n * and should be replaced with its definition when encountered.\n * @property {boolean} [terminal] - whether the alias should behave like a standalone term\n * // TODO better name?\n * @property {boolean} [proper] - whether the alias is a proper combinator (i.e. contains no free variables or constants)\n * @property {number} [arity] - the number of arguments the alias waits for before expanding\n * @property {Expr} [canonical] - equivalent lambda term.\n */\n\n weight () {\n return this.terminal ? 1 : this.impl.weight();\n }\n\n _traverse_descend (options, change) {\n return this.impl._traverse_redo(options, change);\n }\n\n any (predicate) {\n return predicate(this) || this.impl.any(predicate);\n }\n\n _fold (initial, combine) {\n const [value = initial, action] = unwrap(combine(initial, this));\n if (action === control.prune)\n return value;\n if (action === control.stop)\n return control.stop(value);\n const [iValue, iAction] = unwrap(this.impl._fold(value, combine));\n if (iAction === control.stop)\n return control.stop(iValue);\n return iValue ?? value;\n }\n\n subst (search, replace) {\n if (this === search)\n return replace;\n return this.impl.subst(search, replace);\n }\n\n // DO NOT REMOVE TYPE or tsc chokes with\n // TS2527: The inferred type of 'Alias' references an inaccessible 'this' type.\n /**\n * @return {{expr: Expr, steps: number, changed: boolean}}\n */\n step () {\n // arity known = waiting for args to expand\n if (this.arity > 0)\n return { expr: this, steps: 0, changed: false };\n // expanding is a change but it takes 0 steps\n return { expr: this.impl, steps: 0, changed: true };\n }\n\n diff (other, swap = false) {\n if (this === other)\n return null;\n return other.diff(this.impl, !swap);\n }\n\n _braced (first) {\n return this.outdated ? this.impl._braced(first) : false;\n }\n\n _format (options, nargs) {\n const outdated = options.inventory\n ? options.inventory[this.name] !== this\n : this.outdated;\n return outdated ? this.impl._format(options, nargs) : super._format(options, nargs);\n }\n}\n\n// ----- Expr* classes end here -----\n\n// declare native combinators\n\nfunction addNative (name, impl, opt) {\n native[name] = new Native(name, impl, opt);\n}\naddNative('I', x => x);\naddNative('K', x => _ => x);\naddNative('S', x => y => z => x.apply(z, y.apply(z)));\naddNative('B', x => y => z => x.apply(y.apply(z)));\naddNative('C', x => y => z => x.apply(z).apply(y));\naddNative('W', x => y => x.apply(y).apply(y));\n\naddNative(\n '+',\n n => n instanceof Church\n ? new Church(n.n + 1)\n : f => x => f.apply(n.apply(f, x)),\n {\n note: 'Increase a Church numeral argument by 1, otherwise n => f => x => f(n f x)',\n }\n);\n\n// utility functions dependent on Expr* classes, in alphabetical order\n\nfunction firstVar (expr) {\n // yay premature optimization\n while (expr instanceof App)\n expr = expr.fun;\n return expr instanceof FreeVar;\n}\n\n/**\n * @private\n * @given a list of free variables, an expression, and some capabilities of the context,\n * return either a lambda term, or the original expression if no lambda abstraction is needed,\n * plus some metadata about the term and the context.\n *\n * Used by infer() internally.\n * @param {FreeVar[]} args\n * @param {Expr} expr\n * @param {object} caps\n * @returns {TermInfo}\n */\nfunction maybeLambda (args, expr, caps = {}) {\n const count = new Array(args.length).fill(0);\n let proper = true;\n expr.traverse(e => {\n if (e instanceof FreeVar) {\n const index = args.findIndex(a => a.name === e.name);\n if (index >= 0) {\n count[index]++;\n return;\n }\n }\n if (!(e instanceof App))\n proper = false;\n });\n\n const skip = new Set();\n const dup = new Set();\n for (let i = 0; i < args.length; i++) {\n if (count[i] === 0)\n skip.add(i);\n else if (count[i] > 1)\n dup.add(i);\n }\n\n return {\n normal: true,\n steps: caps.steps,\n expr: args.length ? new Lambda(args, expr) : expr,\n arity: args.length,\n ...(skip.size ? { skip } : {}),\n ...(dup.size ? { dup } : {}),\n duplicate: !!dup.size || caps.duplicate || false,\n discard: !!skip.size || caps.discard || false,\n proper,\n };\n}\n\nfunction nthvar (n) {\n return new FreeVar('abcdefgh'[n] ?? 'x' + n);\n}\n\n/**\n * @desc Sort a list in such a way that dependent terms come after the (named) terms they depend on.\n * If env is given, only terms listed there are taken into account.\n * If env is omitted, it will be implied from the list.\n * If list is omitted, it will default to values of env.\n * If just one term is given instead of a list, it will be coerced into a list.\n *\n * No terms outside env + list may ever appear in the result.\n *\n * The terms in env must be named and their names must match their keys.\n *\n * @param {Expr|Expr[]} list\n * @param {{[s:string]: Named}} env\n * @returns {{list: Expr[], env: {[s:string]: Named}}}\n *\n * @example\n * const expr = ski.parse(src);\n * toposort([expr], ski.getTerms()); // returns all terms appearing in Expr in correct order\n */\nfunction toposort (list, env) {\n if (list instanceof Expr)\n list = [list];\n if (env) {\n // TODO check in[name].name === name\n if (!list)\n list = Object.keys(env).sort().map(k => env[k]); // ensure deterministic order\n } else {\n if (!list)\n return [];\n if (!env) {\n env = {};\n for (const item of list) {\n if (!(item instanceof Named))\n continue;\n if (env[item.name])\n throw new Error('duplicate name ' + item);\n env[item.name] = item;\n }\n }\n }\n\n const out = [];\n const seen = new Set();\n const rec = term => {\n if (seen.has(term))\n return;\n term.fold(null, (acc, e) => {\n if (e !== term && e instanceof Named && env[e.name] === e) {\n rec(e);\n return Expr.control.prune(null);\n }\n });\n out.push(term);\n seen.add(term);\n };\n\n for (const term of list)\n rec(term);\n\n return {\n list: out,\n env,\n };\n}\n\nExpr.native = native;\nExpr.control = control;\nExpr.extras = { toposort };\n\nmodule.exports = { Expr, App, Named, FreeVar, Lambda, Native, Alias, Church };\n", "/**\n * Combinatory logic simulator\n */\n'use strict';\n\nconst { Tokenizer, restrict } = require('./internal');\nconst classes = require('./expr');\n\nconst { Expr, Named, Native, Alias, FreeVar, Lambda, Church } = classes;\nconst { native } = Expr;\n\nclass Empty extends Expr {\n apply (...args) {\n return args.length ? args.shift().apply(...args) : this;\n }\n\n postParse () {\n throw new Error('Attempt to use empty expression () as a term');\n }\n}\n\nclass PartialLambda extends Empty {\n // TODO mutable! rewrite ro when have time\n constructor (term, known = {}) {\n super();\n this.impl = new Empty();\n if (term instanceof FreeVar)\n this.terms = [term];\n else if (term instanceof PartialLambda) {\n if (!(term.impl instanceof FreeVar))\n throw new Error('Expected FreeVar->...->FreeVar->Expr');\n this.terms = [...term.terms, term.impl];\n } else\n throw new Error('Expected FreeVar or PartialLambda');\n }\n\n apply (term, ...tail) {\n if (term === null || tail.length !== 0 )\n throw new Error('bad syntax in partial lambda expr');\n this.impl = this.impl.apply(term);\n return this;\n }\n\n postParse () {\n return new Lambda(this.terms, this.impl);\n }\n\n // uncomment if debugging with prints\n /* toString () {\n return this.terms.join('->') + '->' + (this.impl ?? '???');\n } */\n}\n\nfunction postParse (expr) {\n return expr.postParse ? expr.postParse() : expr;\n}\n\nconst combChars = new Tokenizer(\n '[()]', '[A-Z]', '[a-z_][a-z_0-9]*', '\\\\b[0-9]+\\\\b', '->', '\\\\+'\n);\n\nclass SKI {\n /**\n *\n * @param {{\n * allow?: string,\n * numbers?: boolean,\n * lambdas?: boolean,\n * terms?: { [key: string]: Expr|string} | string[],\n * annotate?: boolean,\n * }} [options]\n */\n constructor (options = {}) {\n this.annotate = options.annotate ?? false;\n this.known = { ...native };\n this.hasNumbers = true;\n this.hasLambdas = true;\n /** @type {Set<string>} */\n this.allow = new Set(Object.keys(this.known));\n\n // Import terms, if any. Omit native ones\n if (Array.isArray(options.terms))\n this.bulkAdd(options.terms);\n else if (options.terms) {\n for (const name in options.terms) {\n // Native terms already handled by allow\n if (!options.terms[name].match(/^Native:/))\n this.add(name, options.terms[name]);\n }\n }\n\n // Finally, impose restrictions\n // We must do it after recreating terms, or else terms reliant on forbidden terms will fail\n this.hasNumbers = options.numbers ?? true;\n this.hasLambdas = options.lambdas ?? true;\n if (options.allow)\n this.restrict(options.allow);\n }\n\n /**\n * @desc Declare a new term\n * If the first argument is an Alias, it is added as is.\n * Otherwise, a new Alias or Native term (depending on impl type) is created.\n * If note is not provided and this.annotate is true, an automatic note is generated.\n *\n * If impl is a function, it should have signature (Expr) => ... => Expr\n * (see typedef Partial at top of expr.js)\n *\n * @example ski.add('T', 'S(K(SI))K', 'swap combinator')\n * @example ski.add( ski.parse('T = S(K(SI))K') ) // ditto but one-arg form\n * @example ski.add('T', x => y => y.apply(x), 'swap combinator') // heavy artillery\n * @example ski.add('Y', function (f) { return f.apply(this.apply(f)); }, 'Y combinator')\n *\n * @param {Alias|String} term\n * @param {String|Expr|function(Expr):Partial} [impl]\n * @param {object|string} [options]\n * @param {string} [options.note] - optional annotation for the term, default is auto-generated if this.annotate is true\n * @param {boolean} [options.canonize] - whether to canonize the term's implementation, default is this.annotate\n * @param {boolean} [options.fancy] - alternative HTML-friendly name for the term\n * @param {number} [options.arity] - custom arity for the term, default is inferred from the implementation\n * @return {SKI} chainable\n */\n add (term, impl, options ) {\n term = this._named(term, impl);\n\n // backward compat\n if (typeof options === 'string')\n options = { note: options, canonize: false };\n term._setup({ canonize: this.annotate, ...options });\n\n if (this.known[term.name])\n this.known[term.name].outdated = true;\n this.known[term.name] = term;\n this.allow.add(term.name);\n\n return this;\n }\n\n /**\n * @desc Internal helper for add() that creates an Alias or Native term from the given arguments.\n * @param {Alias|string} term\n * @param {string|Expr|function(Expr):Partial} impl\n * @returns {Native|Alias}\n * @private\n */\n _named (term, impl) {\n if (term instanceof Alias)\n return new Alias(term.name, term.impl, { canonize: true });\n if (typeof term !== 'string')\n throw new Error('add(): term must be an Alias or a string');\n if (impl === undefined)\n throw new Error('add(): impl must be provided when term is a string');\n if (typeof impl === 'string')\n return new Alias(term, this.parse(impl), { canonize: true });\n if (impl instanceof Expr)\n return new Alias(term, impl, { canonize: true });\n if (typeof impl === 'function')\n return new Native(term, impl);\n // idk what this is\n throw new Error('add(): impl must be an Expr, a string, or a function with a signature Expr => ... => Expr');\n }\n\n /**\n * @desc Declare a new term if it is not known, otherwise just allow it.\n * Currently only used by quests.\n * Use with caution, this function may change its signature, behavior, or even be removed in the future.\n *\n * @experimental\n * @param {string|Alias} name\n * @param {string|Expr|function(Expr):Partial} impl\n * @returns {SKI}\n */\n maybeAdd (name, impl) {\n if (this.known[name])\n this.allow.add(name);\n else\n this.add(name, impl);\n return this;\n }\n\n /**\n * @desc Declare and remove multiple terms at once\n * term=impl adds term\n * term= removes term\n * @param {string[]} list\n * @return {SKI} chainable\n */\n bulkAdd (list) {\n for (const item of list) {\n const m = item.match(/^([A-Z]|[a-z][a-z_0-9]*)\\s*=\\s*(.*)$/s);\n // TODO check all declarations before applying any (but we might need earlier terms for parsing later ones)\n if (!m)\n throw new Error('bulkAdd: invalid declaration: ' + item);\n if (m[2] === '')\n this.remove(m[1]);\n else\n this.add(m[1], this.parse(m[2]));\n }\n\n return this;\n }\n\n /**\n * Restrict the interpreter to given terms. Terms prepended with '+' will be added\n * and terms preceeded with '-' will be removed.\n * @example ski.restrict('SK') // use the basis\n * @example ski.restrict('+I') // allow I now\n * @example ski.restrict('-SKI +BCKW' ); // switch basis\n * @example ski.restrict('-foo -bar'); // forbid some user functions\n * @param {string} spec\n * @return {SKI} chainable\n */\n restrict (spec) {\n this.allow = restrict(this.allow, spec);\n return this;\n }\n\n /**\n *\n * @param {string} spec\n * @return {string}\n */\n showRestrict (spec = '+') {\n const out = [];\n let prevShort = true;\n for (const term of [...restrict(this.allow, spec)].sort()) {\n const nextShort = term.match(/^[A-Z]$/);\n if (out.length && !(prevShort && nextShort))\n out.push(' ');\n out.push(term);\n prevShort = nextShort;\n }\n return out.join('');\n }\n\n /**\n *\n * @param {String} name\n * @return {SKI}\n */\n remove (name) {\n this.known[name].outdated = true;\n delete this.known[name];\n this.allow.delete(name);\n return this;\n }\n\n /**\n *\n * @return {{[key:string]: Native|Alias}}\n */\n getTerms () {\n const out = {};\n for (const name of Object.keys(this.known)) {\n if (this.allow.has(name))\n out[name] = this.known[name];\n }\n return out;\n }\n\n /**\n * @desc Export term declarations for use in bulkAdd().\n * Currently only Alias terms are serialized.\n * @returns {string[]}\n */\n declare () {\n // TODO accept argument to declare specific terms only\n const env = this.getTerms();\n\n // not serializing native terms, and we don't care about free vars\n for (const name in env) {\n if (!(env[name] instanceof Alias))\n delete env[name];\n }\n\n // avert conflicts if native terms were redefined:\n // create a temporary alias for each native term that was redefined;\n // replace usage of redefined term in subexpressions;\n // finally, remove the temporary aliases from the output\n const needDetour = {};\n let i = 1;\n for (const name in native) {\n if (!(env[name] instanceof Alias))\n continue;\n while ('tmp' + i in env)\n i++;\n const temp = new Alias('tmp' + i, env[name]);\n needDetour[temp] = env[name];\n env[temp] = temp;\n delete env[name];\n }\n\n // console.log(env);\n\n const list = Expr.extras.toposort(undefined, env).list;\n\n const detour = new Map();\n if (Object.keys(needDetour).length) {\n // replace aliases with their detoured counterparts.\n // we have to go recursive, otherwise an unrelated alias may be expanded to its impl\n // and name infos will be erased\n const rework = expr => {\n return expr.traverse(e => {\n if (!(e instanceof Alias))\n return null; // continue\n const newAlias = detour.get(e);\n if (newAlias)\n return newAlias;\n return new Alias(e.name, rework(e.impl));\n }) ?? expr;\n };\n\n for (let i = 0; i < list.length; i++) {\n // upon processing list[i], only terms declared before it may be detoured\n list[i] = rework(list[i], detour);\n detour.set(needDetour[list[i].name], list[i]);\n env[list[i].name] = list[i];\n console.log(`list[${i}] = ${list[i].name}=${list[i].impl};`);\n }\n console.log('detour:', detour);\n }\n\n // console.log(res);\n const out = list.map(e => needDetour[e]\n ? e.name + '=' + needDetour[e].name + '=' + e.impl.format({ inventory: env })\n : e.name + '=' + e.impl.format({ inventory: env })\n );\n\n for (const [name, temp] of detour)\n out.push(name + '=' + temp, temp + '=');\n\n return out;\n }\n\n /**\n * @template T\n * @param {string} source\n * @param {Object} [options]\n * @param {{[keys: string]: Expr}} [options.env]\n * @param {T} [options.scope]\n * @param {boolean} [options.numbers]\n * @param {boolean} [options.lambdas]\n * @param {string} [options.allow]\n * @return {Expr}\n */\n parse (source, options = {}) {\n if (typeof source !== 'string')\n throw new Error('parse: source must be a string, got ' + typeof source);\n\n const lines = source.replace(/\\/\\/[^\\n]*$/gm, ' ')\n .replace(/\\/\\*.*?\\*\\//gs, ' ')\n .trim()\n .split(/\\s*;[\\s;]*/).filter( s => s.match(/\\S/));\n\n const jar = { ...options.env };\n\n let expr = new Empty();\n for (const item of lines) {\n if (expr instanceof Alias)\n expr.outdated = true;\n\n const def = item.match(/^([A-Z]|[a-z][a-z_0-9]*)\\s*=(.*)$/s);\n if (def && def[2] === '')\n expr = new FreeVar(def[1], options.scope ?? FreeVar.global);\n else\n expr = this.parseLine(item, jar, options);\n\n if (def) {\n if (jar[def[1]] !== undefined)\n throw new Error('Attempt to redefine a known term: ' + def[1]);\n jar[def[1]] = expr;\n }\n\n // console.log('parsed line:', item, '; got:', expr,'; jar now: ', jar);\n }\n\n expr.context = {\n env: { ...this.getTerms(), ...jar }, // also contains pre-parsed terms\n scope: options.scope,\n src: source,\n parser: this,\n };\n return expr;\n }\n\n /**\n * @desc Parse a single line of source code, without splitting it into declarations.\n * Internal, always use parse() instead.\n * @template T\n * @param {String} source S(KI)I\n * @param {{[keys: string]: Expr}} env\n * @param {Object} [options]\n * @param {{[keys: string]: Expr}} [options.env] - unused, see 'env' argument\n * @param {T} [options.scope]\n * @param {boolean} [options.numbers]\n * @param {boolean} [options.lambdas]\n * @param {string} [options.allow]\n * @return {Expr} parsed expression\n */\n parseLine (source, env = {}, options = {}) {\n const aliased = source.match(/^\\s*([A-Z]|[a-z][a-z_0-9]*)\\s*=\\s*(.*)$/s);\n if (aliased)\n return new Alias(aliased[1], this.parseLine(aliased[2], env, options));\n\n const opt = {\n numbers: options.numbers ?? this.hasNumbers,\n lambdas: options.lambdas ?? this.hasLambdas,\n allow: restrict(this.allow, options.allow),\n };\n // make sure '+' usage is in sync with numerals\n opt.numbers ? opt.allow.add('+') : opt.allow.delete('+');\n\n const tokens = combChars.split(source);\n\n const empty = new Empty();\n /** @type {Expr[]} */\n const stack = [empty];\n const context = options.scope || FreeVar.global; // default is global unbound vars\n\n // TODO each token should carry along its position in source\n for (const c of tokens) {\n // console.log(\"parseLine: found \"+c+\"; stack =\", stack.join(\", \"));\n if (c === '(')\n stack.push(empty);\n else if (c === ')') {\n if (stack.length < 2)\n throw new Error('unbalanced input: extra closing parenthesis' + source);\n const x = postParse(stack.pop());\n const f = stack.pop();\n stack.push(f.apply(x));\n } else if (c === '->') {\n if (!opt.lambdas)\n throw new Error('Lambdas not supported, allow them explicitly');\n stack.push(new PartialLambda(stack.pop(), env));\n } else if (c.match(/^[0-9]+$/)) {\n if (!opt.numbers)\n throw new Error('Church numbers not supported, allow them explicitly');\n const f = stack.pop();\n stack.push(f.apply(new Church(c)));\n } else {\n const f = stack.pop();\n if (!env[c] && this.known[c] && !opt.allow.has(c)) {\n throw new Error('Term \\'' + c + '\\' is not in the restricted set '\n + [...opt.allow].sort().join(' '));\n }\n // look in temp vars first, then in known terms, then fallback to creating free var\n const x = env[c] ?? this.known[c] ?? (env[c] = new FreeVar(c, context));\n stack.push(f.apply(x));\n }\n }\n\n if (stack.length !== 1) {\n throw new Error('unbalanced input: missing '\n + (stack.length - 1) + ' closing parenthesis:' + source);\n }\n\n return postParse(stack.pop());\n }\n\n toJSON () {\n return {\n version: '1.1.1', // set to incremented package.json version whenever SKI serialization changes\n allow: this.showRestrict('+'),\n numbers: this.hasNumbers,\n lambdas: this.hasLambdas,\n annotate: this.annotate,\n terms: this.declare(),\n }\n }\n}\n\n/**\n * Public static shortcuts to common functions (see also ./extras.js)\n */\n\n/**\n * @desc Create a proxy object that generates variables on demand,\n * with names corresponding to the property accessed.\n * Different invocations will return distinct variables,\n * even if with the same name.\n *\n *\n * @example const {x, y, z} = SKI.vars();\n * x.name; // 'x'\n * x instanceof FreeVar; // true\n * x.apply(y).apply(z); // x(y)(z)\n *\n * @template T\n * @param {T} [scope] - optional context to bind the generated variables to\n * @return {{[key: string]: FreeVar}}\n */\nSKI.vars = function (scope = {}) {\n const cache = {};\n return new Proxy({}, {\n get: (target, name) => {\n if (!(name in cache))\n cache[name] = new FreeVar(name, scope);\n return cache[name];\n }\n });\n};\n\n/**\n * Convert a number to Church encoding\n * @param {number} n\n * @return {Church}\n */\nSKI.church = n => new Church(n);\n\n/**\n *\n * @type {{[key: string]: Native}}\n */\n\nfor (const name in native)\n SKI[name] = native[name];\n\nSKI.classes = classes;\nSKI.native = native;\n/**\n * @desc Traverse control functions, used by Expr.traverse() and Expr.fold()\n * @template T\n * @type {{\n * descend: function(T): TraverseControl<T>,\n * prune: function(T): TraverseControl<T>,\n * redo: function(T): TraverseControl<T>,\n * stop: function(T): TraverseControl<T>\n * }}\n */\nSKI.control = Expr.control;\n\nmodule.exports = { SKI };\n", "const { SKI } = require('./parser');\nconst { Expr, FreeVar, Alias, Lambda } = SKI.classes;\n\n/**\n * @typedef {{\n * pass: boolean,\n * reason?: string,\n * steps: number,\n * start: Expr,\n * found: Expr,\n * expected: Expr,\n * note?: string,\n * args: Expr[],\n * case: Case\n * }} CaseResult\n */\n\n/**\n * @typedef {{\n * linear?: boolean,\n * affine?: boolean,\n * normal?: boolean,\n * proper?: boolean,\n * discard?: boolean,\n * duplicate?: boolean,\n * arity?: number,\n * }} Capability\n */\n\n/**\n * @typedef {\n * [string, string]\n * | [{max?: number}, string, string]\n * | [{caps: Capability, max?: number}, string]\n * } TestCase\n */\n\n/**\n * @typedef {string | {name: string, fancy?: string, allow?: string, numbers?: boolean, lambdas?: boolean}} InputSpec\n */\n\n/**\n * @typedef {{\n * pass: boolean,\n * details: CaseResult[],\n * expr?: Expr,\n * input: Expr[]|string[],\n * exception?: Error,\n * steps: number,\n * weight?: number\n * }} QuestResult\n */\n\n/**\n * @typedef {{\n * input: InputSpec | InputSpec[],\n * cases: TestCase[],\n *\n * // the rest is optional\n *\n * allow?: string,\n * numbers?: boolean,\n * env?: string[],\n * engine?: SKI,\n * engineFull?: SKI,\n *\n * // metadata, also any fields not listed here will go to quest.meta.???\n * id?: string|number,\n * name?: string,\n * intro?: string|string[], // multiple strings will be concatenated with spaces\n * }} QuestSpec\n */\n\n/**\n * @typedef {{ accepted?: string[][], rejected?: string[][] }} SelfCheck\n */\n\nclass Quest {\n /**\n * @description A combinator problem with a set of test cases for the proposed solution.\n * @param {QuestSpec} options\n * @example const quest = new Quest({\n * input: 'identity',\n * cases: [\n * ['identity x', 'x'],\n * ],\n * allow: 'SK',\n * intro: 'Find a combinator that behaves like the identity function.',\n * });\n * quest.check('S K K'); // { pass: true, details: [...], ... }\n * quest.check('K S'); // { pass: false, details: [...], ... }\n * quest.check('K x'); // fail! internal variable x is not equal to free variable x,\n * // despite having the same name.\n * quest.check('I'); // fail! I not in the allowed list.\n */\n constructor (options) {\n const { input, cases, allow, numbers, lambdas, engine, engineFull, ...meta } = options;\n const env = options.env ?? options.vars; // backwards compatibility\n\n //\n this.engine = engine ?? new SKI();\n this.engineFull = engineFull ?? new SKI();\n this.restrict = { allow, numbers: numbers ?? false, lambdas: lambdas ?? false };\n this.env = {};\n\n const jar = {};\n\n // option.env is a list of expressions.\n // we suck all free variables + all term declarations from there into this.env\n // to feed it later to every case's parser.\n for (const term of env ?? []) {\n const expr = this.engineFull.parse(term, { env: jar, scope: this });\n if (expr instanceof SKI.classes.Alias)\n this.env[expr.name] = new Alias(expr.name, expr.impl, { terminal: true, canonize: false });\n // Canonized aliases won't expand with insufficient arguments,\n // causing correct solutions to fail, so alas...\n else if (expr instanceof SKI.classes.FreeVar)\n this.env[expr.name] = expr;\n else\n throw new Error('Unsupported given variable type: ' + term);\n }\n\n this.input = [];\n for (const term of Array.isArray(input) ? input : [input])\n this.addInput(term);\n if (!this.input.length)\n throw new Error('Quest needs at least one input placeholder');\n\n this.envFull = { ...this.env, ...jar };\n for (const term of this.input) {\n if (term.name in this.envFull)\n throw new Error('input placeholder name is duplicated or clashes with env: ' + term.name);\n this.envFull[term.name] = term.placeholder;\n }\n\n // NOTE meta is a local variable, can mutate\n // NOTE title/descr are old name/intro respectively, kept for backwards compatibility\n this.cases = [];\n this.name = meta.name ?? meta.title;\n meta.intro = list2str(meta.intro ?? meta.descr);\n this.intro = meta.intro;\n this.id = meta.id;\n this.meta = meta;\n\n for (const c of cases ?? [])\n this.add(...c);\n }\n\n /**\n * Display allowed terms based on what engine thinks of this.env + this.restrict.allow\n * @return {string}\n */\n allowed () {\n const allow = this.restrict.allow ?? '';\n const env = Object.keys(this.env).sort();\n // In case vars are present and restrictions aren't, don't clutter the output with all the known terms\n return allow\n ? this.engine.showRestrict(allow + '+' + env.join(' '))\n : env.map( s => '+' + s).join(' ');\n }\n\n addInput (term) {\n if (typeof term !== 'object')\n term = { name: term };\n if (typeof term.name !== 'string')\n throw new Error(\"quest 'input' field must be a string or a {name: string, ...} object\");\n\n term.placeholder = new SKI.classes.FreeVar(term.name);\n // TODO more checks\n this.input.push(term);\n }\n\n /**\n *\n * @param {{} | string} opt\n * @param {string} terms\n * @return {Quest}\n */\n add (opt, ...terms) {\n if (typeof opt === 'string') {\n terms.unshift(opt);\n opt = {};\n } else\n opt = { ...opt };\n\n opt.engine = opt.engine ?? this.engineFull;\n opt.env = opt.env ?? this.envFull;\n\n const input = this.input.map( t => t.placeholder );\n this.cases.push(\n opt.caps\n ? new PropertyCase(input, opt, terms)\n : new ExprCase(input, opt, terms)\n );\n return this;\n }\n\n /**\n * @description Statefully parse a list of strings into expressions or fancy aliases thereof.\n * @param {string[]} input\n * @return {{terms: Expr[], weight: number}}\n */\n prepare (...input) {\n if (input.length !== this.input.length)\n throw new Error('Solutions provided ' + input.length + ' terms where ' + this.input.length + ' are expected');\n\n let weight = 0;\n const prepared = [];\n const jar = { ...this.env };\n for (let i = 0; i < input.length; i++) {\n const spec = this.input[i];\n const impl = this.engine.parse(input[i], {\n env: jar,\n allow: spec.allow ?? this.restrict.allow,\n numbers: spec.numbers ?? this.restrict.numbers,\n lambdas: spec.lambdas ?? this.restrict.lambdas,\n });\n const arsenal = { ...this.engine.getTerms(), ...jar };\n weight += impl.fold(0, (a, e) => {\n if (e instanceof SKI.classes.Named && arsenal[e.name] === e)\n return SKI.control.prune( a + 1);\n });\n const expr = impl instanceof FreeVar\n ? impl\n : new Alias(spec.fancy ?? spec.name, impl, { terminal: true, canonize: false });\n jar[spec.name] = expr;\n prepared.push(expr);\n }\n return {\n prepared,\n weight,\n };\n }\n\n /**\n *\n * @param {string} input\n * @return {QuestResult}\n */\n check (...input) {\n try {\n const { prepared, weight } = this.prepare(...input);\n const details = this.cases.map( c => c.check(...prepared) );\n const pass = details.reduce((acc, val) => acc && val.pass, true);\n const steps = details.reduce((acc, val) => acc + val.steps, 0);\n return {\n expr: prepared[0],\n input: prepared,\n pass,\n steps,\n details,\n weight,\n };\n } catch (e) {\n return { pass: false, details: [], exception: e, steps: 0, input };\n }\n }\n\n verify (options) {\n const findings = this.verifyMeta(options);\n if (options.solutions) {\n const solCheck = this.verifySolutions(options.solutions);\n if (solCheck)\n findings.solutions = solCheck;\n }\n if (options.seen) {\n if (!this.id)\n findings.seen = 'No id in quest ' + (this.name ?? '(unnamed)');\n if (options.seen.has(this.id))\n findings.seen = 'Duplicate quest id ' + this.id;\n options.seen.add(this.id); // mutating but who cares\n }\n return Object.keys(findings).length ? findings : null;\n }\n\n /**\n * @desc Verify that solutions that are expected to pass/fail do so.\n * @param {SelfCheck|{[key: string]: SelfCheck}} dataset\n * @return {{shouldPass: {input: string[], result: QuestResult}[], shouldFail: {input: string[], result: QuestResult}[]} | null}\n */\n verifySolutions (dataset) {\n // dataset is either a SelfCheck object or a hash of { quest_id: SelfCheck }\n if (typeof dataset === 'object' && !Array.isArray(dataset?.accepted) && !Array.isArray(dataset?.rejected)) {\n // dataset is a hash of { quest_id: SelfCheck } so extract data\n if (!this.id || !dataset[this.id])\n return null; // no self-check data for this quest, skip\n }\n\n const { accepted = [], rejected = [] } = dataset[this.id] ?? dataset;\n\n const ret = { shouldPass: [], shouldFail: [] };\n for (const input of accepted) {\n const result = this.check(...input);\n if (!result.pass)\n ret.shouldPass.push({ input, result });\n }\n for (const input of rejected) {\n const result = this.check(...input);\n if (result.pass)\n ret.shouldFail.push({ input, result });\n }\n return (ret.shouldFail.length + ret.shouldPass.length) ? ret : null; // return null if all good\n }\n\n verifyMeta (options = {}) {\n const findings = {};\n\n for (const field of ['name', 'intro']) {\n const found = checkHtml(this[field]);\n if (found)\n findings[field] = found;\n }\n if (options.date) {\n const date = new Date(this.meta.created_at);\n if (isNaN(date))\n findings.date = 'invalid date format: ' + this.meta.created_at;\n else if (date < new Date('2024-07-15') || date > new Date())\n findings.date = 'date out of range: ' + this.meta.created_at;\n }\n\n return findings;\n }\n\n /**\n *\n * @return {TestCase[]}\n */\n show () {\n return [...this.cases];\n }\n}\n\nclass Case {\n /**\n * @param {FreeVar[]} input\n * @param {{\n * max?: number,\n * note?: string,\n * env?: {[key:string]: Expr},\n * engine: SKI\n * }} options\n */\n constructor (input, options) {\n this.max = options.max ?? 1000;\n this.note = options.note;\n this.env = { ...(options.env ?? {}) }; // note: env already contains input placeholders\n this.input = input;\n this.engine = options.engine;\n }\n\n parse (src) {\n return new Subst(this.engine.parse(src, { env: this.env, scope: this }), this.input);\n }\n\n /**\n * @param {Expr} expr\n * @return {CaseResult}\n */\n check ( ...expr ) {\n throw new Error('not implemented');\n }\n}\n\nclass ExprCase extends Case {\n /**\n * @param {FreeVar[]} input\n * @param {{\n * max?: number,\n * note?: string,\n * env?: {string: Expr},\n * engine?: SKI\n * }} options\n * @param {[e1: string, e2: string]} terms\n */\n constructor (input, options, terms) {\n if (terms.length !== 2)\n throw new Error('Case accepts exactly 2 strings');\n\n super(input, options);\n\n [this.e1, this.e2] = terms.map( s => this.parse(s) );\n }\n\n check (...args) {\n const e1 = this.e1.apply(args);\n const r1 = e1.run({ max: this.max });\n const e2 = this.e2.apply(args);\n const r2 = e2.run({ max: this.max });\n\n let reason = null;\n if (!r1.final || !r2.final)\n reason = 'failed to reach normal form in ' + this.max + ' steps';\n else\n reason = r1.expr.diff(r2.expr);\n\n return {\n pass: !reason,\n reason,\n steps: r1.steps,\n start: e1,\n found: r1.expr,\n expected: r2.expr,\n note: this.note,\n args,\n case: this,\n };\n }\n}\n\nconst knownCaps = {\n normal: true,\n proper: true,\n discard: true,\n duplicate: true,\n linear: true,\n affine: true,\n arity: true,\n}\n\nclass PropertyCase extends Case {\n // test that an expression uses all of its inputs exactly once\n constructor (input, options, terms) {\n super(input, options);\n if (terms.length > 1)\n throw new Error('PropertyCase accepts exactly 1 string');\n if (!options.caps || typeof options.caps !== 'object' || !Object.keys(options.caps).length)\n throw new Error('PropertyCase requires a caps object with at least one capability');\n const unknown = Object.keys(options.caps).filter( c => !knownCaps[c] );\n if (unknown.length)\n throw new Error('PropertyCase: don\\'t know how to test these capabilities: ' + unknown.join(', '));\n\n this.expr = this.parse(terms[0]);\n this.caps = options.caps;\n\n if (this.caps.linear) {\n delete this.caps.linear;\n this.caps.duplicate = false;\n this.caps.discard = false;\n this.caps.normal = true;\n }\n\n if (this.caps.affine) {\n delete this.caps.affine;\n this.caps.normal = true;\n this.caps.duplicate = false;\n }\n }\n\n check (...expr) {\n const start = this.expr.apply(expr);\n const r = start.run({ max: this.max });\n const guess = r.expr.infer({ max: this.max });\n\n const reason = [];\n for (const cap in this.caps) {\n if (guess[cap] !== this.caps[cap])\n reason.push('expected property ' + cap + ' to be ' + this.caps[cap] + ', found ' + guess[cap]);\n }\n\n return {\n pass: !reason.length,\n reason: reason ? reason.join('\\n') : null,\n steps: r.steps,\n start,\n found: r.expr,\n case: this,\n note: this.note,\n args: expr,\n };\n }\n}\n\nclass Subst {\n /**\n * @descr A placeholder object with exactly n free variables to be substituted later.\n * @param {Expr} expr\n * @param {FreeVar[]} env\n */\n constructor (expr, env) {\n this.expr = expr;\n this.env = env;\n }\n\n apply (list) {\n if (list.length !== this.env.length)\n throw new Error('Subst: expected ' + this.env.length + ' terms, got ' + list.length);\n\n let expr = this.expr;\n for (let i = 0; i < this.env.length; i++)\n expr = expr.subst(this.env[i], list[i]) ?? expr;\n\n return expr;\n }\n}\n\n// corresponds to \"chapter\" in the quest page\nclass Group {\n constructor (options) {\n this.name = options.name;\n this.intro = list2str(options.intro);\n this.id = options.id;\n\n // TODO don't die on failed quests\n if (options.content)\n this.content = options.content.map( c => c instanceof Quest ? c : new Quest(c) );\n }\n\n verify (options) {\n const findings = {};\n const id = checkId(this.id, options.seen);\n if (id)\n findings[this.id] = id;\n for (const field of ['name', 'intro']) {\n const found = checkHtml(this[field]);\n if (found)\n findings[field] = found;\n }\n\n findings.content = this.content.map(q => q.verify(options));\n return findings;\n }\n}\n\n/**\n * @desc Concatenate long strings represented as arrays, or just pass along if already string or undefined.\n * @param {string|Array<string>|undefined} str\n * @returns {string|undefined}\n */\nfunction list2str (str) {\n if (str === undefined || typeof str === 'string')\n return str;\n return Array.isArray(str) ? str.join(' ') : '' + str;\n}\n\nfunction checkId (id, seen) {\n if (id === undefined)\n return 'missing';\n if (typeof id !== 'string' && typeof id !== 'number' )\n return 'is a ' + typeof id;\n if (seen) {\n if (seen.has(id))\n return 'duplicate id ' + id;\n seen.add(id);\n }\n // return nothing = success\n}\n\nfunction checkHtml (str) {\n if (str === undefined)\n return 'missing';\n if (typeof str !== 'string')\n return 'not a string but ' + typeof str;\n\n // very basic check for unclosed tags, just to catch common mistakes in the quest text\n const tagStack = [];\n const tagRegex = /<\\/?([a-z]+)(?:\\s[^>]*)?>/gi;\n let match;\n while ((match = tagRegex.exec(str)) !== null) {\n const [fullTag, tagName] = match;\n if (fullTag.startsWith('</')) {\n // Closing tag\n if (tagStack.length === 0 || tagStack.pop() !== tagName)\n return (`Unmatched closing tag: </${tagName}>`);\n } else {\n // Opening tag\n tagStack.push(tagName);\n }\n }\n if (tagStack.length > 0)\n return (`Unclosed tags: ${tagStack.join(', ')}`);\n\n return null; // No issues found\n}\n\nQuest.Group = Group;\nQuest.Case = Case;\n\nmodule.exports = { Quest };\n", "'use strict';\n\nconst { Expr, Alias, FreeVar } = require('./expr');\nconst { Quest } = require('./quest');\n\n/**\n * @desc Extra utilities that do not belong in the core.\n */\n\n/**\n * @experimental\n * @desc Look for an expression that matches the predicate,\n * starting with the seed and applying the terms to one another.\n *\n * A predicate returning 0 (or nothing) means \"keep looking\",\n * a positive number stands for \"found\",\n * and a negative means \"discard this term from further applications\".\n *\n * The order of search is from shortest to longest expressions.\n *\n * @param {Expr[]} seed\n * @param {object} options\n * @param {number} [options.depth] - maximum generation to search for\n * @param {number} [options.tries] - maximum number of tries before giving up\n * @param {boolean} [options.infer] - whether to call infer(), default true.\n * @param {number} [options.maxArgs] - arguments in infer()\n * @param {number} [options.max] - step limit in infer()\n * @param {boolean} [options.noskip] - prevents skipping equivalent terms. Always true if infer is false.\n * @param {boolean} [retain] - if true. also add the whole cache to returned value\n * @param {({gen: number, total: number, probed: number, step: boolean}) => void} [options.progress]\n * @param {number} [options.progressInterval] - minimum number of tries between calls to options.progress, default 1000.\n * @param {(e: Expr, props: {}) => number?} predicate\n * @return {{expr?: Expr, total: number, probed: number, gen: number, cache?: Expr[][]}}\n */\nfunction search (seed, options, predicate) {\n const {\n depth = 16,\n infer = true,\n progressInterval = 1000,\n } = options;\n const hasSeen = infer && !options.noskip;\n\n // cache[i] = ith generation, 0 is empty\n const cache = [[]];\n let total = 0;\n let probed = 0;\n const seen = {};\n\n const maybeProbe = term => {\n total++;\n const props = infer ? term.infer({ max: options.max, maxArgs: options.maxArgs }) : null;\n if (hasSeen && props.expr) {\n if (seen[props.expr])\n return { res: -1 };\n seen[props.expr] = true;\n }\n probed++;\n const res = predicate(term, props);\n return { res, props };\n };\n\n // sieve through the seed\n for (const term of seed) {\n const { res } = maybeProbe(term);\n if (res > 0)\n return { expr: term, total, probed, gen: 1 };\n else if (res < 0)\n continue;\n\n cache[0].push(term);\n }\n\n let lastProgress;\n\n for (let gen = 1; gen < depth; gen++) {\n if (options.progress) {\n options.progress({ gen, total, probed, step: true });\n lastProgress = total;\n }\n for (let i = 0; i < gen; i++) {\n for (const a of cache[gen - i - 1] || []) {\n for (const b of cache[i] || []) {\n if (total >= options.tries)\n return { total, probed, gen, ...(options.retain ? { cache } : {}) };\n if (options.progress && total - lastProgress >= progressInterval) {\n options.progress({ gen, total, probed, step: false });\n lastProgress = total;\n }\n const term = a.apply(b);\n const { res, props } = maybeProbe(term);\n\n if (res > 0)\n return { expr: term, total, probed, gen, ...(options.retain ? { cache } : {}) };\n else if (res < 0)\n continue;\n\n // if the term is not reducible, it is more likely to be a dead end, so we push it further away\n const offset = infer\n ? ((props.expr ? 0 : 3) + (props.dup ? 1 : 0) + (props.proper ? 0 : 1))\n : 0;\n if (!cache[gen + offset])\n cache[gen + offset] = [];\n cache[gen + offset].push(term);\n }\n }\n }\n }\n\n return { total, probed, gen: depth, ...(options.retain ? { cache } : {}) };\n}\n\n/**\n * @desc Recursively replace all instances of Expr in a data structure with\n * respective string representation using the format() options.\n * Objects of other types and primitive values are eft as is.\n *\n * May be useful for debugging or diagnostic output.\n *\n * @experimental\n *\n * @param {any} obj\n * @param {object} [options] - see Expr.format()\n * @returns {any}\n */\nfunction deepFormat (obj, options = {}) {\n if (obj instanceof Expr)\n return obj.format(options);\n // TODO for quests, use toJSON when it's ready\n if (obj instanceof Quest)\n return 'Quest(' + obj.name + ')';\n if (obj instanceof Quest.Case)\n return 'Quest.Case';\n if (Array.isArray(obj))\n return obj.map(deepFormat);\n if (typeof obj !== 'object' || obj === null || obj.constructor !== Object)\n return obj;\n\n // default = plain object\n const out = {};\n for (const key in obj)\n out[key] = deepFormat(obj[key]);\n\n return out;\n}\n\n/**\n * @desc Given an expression and a hash of named terms,\n * return a semicolon-separated string that declares said expression\n * unambiguously.\n *\n * @example\n * var expr = ski.parse(\"T=CI; V=BCT; V x y\");\n * SKI.extras.declare(expr, expr.context.env);\n * // 'B; C; I; T=CI; V=BC(T); x=; y=; Vx y'\n *\n * @param {Expr} expr\n * @param {{[s: string]: Named}} [env]\n * @returns {string}\n */\nfunction declare (expr, env) {\n const res = Expr.extras.toposort([expr], env);\n\n return res.list.map(s => {\n if (s instanceof Alias)\n return s.name + '=' + s.impl.format({ inventory: res.env });\n if (s instanceof FreeVar)\n return s.name + '=';\n return s.format({ inventory: res.env });\n }).join('; ');\n}\n\nmodule.exports = { search, deepFormat, declare };\n", "const { SKI } = require('./src/parser');\nconst { Quest } = require('./src/quest');\nconst extras = require('./src/extras');\n\nSKI.Quest = Quest;\nSKI.extras = { ...extras, ...SKI.classes.Expr.extras };\n\n// SKI_REPL=1 node -r ./index.js\nif (typeof process === 'object' && process.env.SKI_REPL && typeof global !== 'undefined') {\n global.SKI = SKI;\n console.log('SKI_REPL activated, try `new SKI();`');\n}\n\n// we're in a browser\nif (typeof window !== 'undefined')\n window.SKI = SKI;\n\nmod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in", "exports", "module", "Tokenizer", "terms", "src", "s", "a", "b", "str", "list", "last", "x", "tokRestrict", "restrict", "set", "spec", "out", "act", "sym", "mode", "TraverseControl", "value", "decoration", "unwrap", "prepareWrapper", "label", "fun", "require_expr", "__commonJSMin", "exports", "module", "unwrap", "prepareWrapper", "DEFAULTS", "ORDER", "control", "native", "Expr", "_Expr", "options", "guess", "args", "expr", "arg", "App", "Alias", "FreeVar", "change", "order", "_", "action", "prev", "next", "predicate", "initial", "combine", "value", "fun", "head", "tail", "e", "nargs", "probe", "steps", "main", "i", "firstVar", "maybeLambda", "list", "discard", "duplicate", "acc", "j", "sub", "push", "nthvar", "Lambda", "seen", "t", "search", "replace", "opt", "max", "final", "other", "swap", "actual", "comment", "diff", "poorMans", "first", "fallback", "rec", "indent", "_App", "fAction", "aAction", "fValue", "aValue", "partial", "wrap", "Named", "_Named", "name", "freeId", "_FreeVar", "scope", "lhs", "rhs", "Native", "impl", "_Lambda", "my", "known", "last", "local", "iAction", "iValue", "Church", "_Church", "n", "x", "y", "waitn", "addNative", "z", "f", "caps", "count", "proper", "index", "a", "skip", "dup", "toposort", "env", "k", "item", "out", "term", "require_parser", "__commonJSMin", "exports", "module", "Tokenizer", "restrict", "classes", "Expr", "Named", "Native", "Alias", "FreeVar", "Lambda", "Church", "native", "Empty", "args", "PartialLambda", "_PartialLambda", "term", "known", "tail", "postParse", "expr", "combChars", "SKI", "options", "name", "impl", "list", "item", "m", "spec", "out", "prevShort", "nextShort", "env", "needDetour", "i", "temp", "detour", "rework", "e", "newAlias", "source", "lines", "s", "jar", "def", "aliased", "opt", "tokens", "empty", "stack", "context", "c", "x", "f", "scope", "cache", "target", "n", "require_quest", "__commonJSMin", "exports", "module", "SKI", "Expr", "FreeVar", "Alias", "Lambda", "Quest", "options", "input", "cases", "allow", "numbers", "lambdas", "engine", "engineFull", "meta", "env", "jar", "term", "expr", "list2str", "c", "s", "opt", "terms", "t", "PropertyCase", "ExprCase", "weight", "prepared", "i", "spec", "impl", "arsenal", "a", "e", "details", "pass", "acc", "val", "steps", "findings", "solCheck", "dataset", "accepted", "rejected", "ret", "result", "field", "found", "checkHtml", "date", "Case", "src", "Subst", "args", "e1", "r1", "r2", "reason", "knownCaps", "unknown", "start", "guess", "cap", "list", "Group", "id", "checkId", "q", "str", "seen", "tagStack", "tagRegex", "match", "fullTag", "tagName", "require_extras", "__commonJSMin", "exports", "module", "Expr", "Alias", "FreeVar", "Quest", "search", "seed", "options", "predicate", "depth", "infer", "progressInterval", "hasSeen", "cache", "total", "probed", "seen", "maybeProbe", "term", "props", "res", "lastProgress", "gen", "i", "a", "b", "offset", "deepFormat", "obj", "out", "key", "declare", "expr", "env", "s", "require_index", "__commonJSMin", "exports", "module", "SKI", "Quest", "extras"]
|
|
7
7
|
}
|