@dallaylaen/ski-interpreter 2.3.0 → 2.3.2
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 +17 -0
- package/README.md +1 -1
- package/bin/ski.js +74 -0
- package/lib/ski-interpreter.cjs.js +5 -1
- package/lib/ski-interpreter.cjs.js.map +2 -2
- package/lib/ski-interpreter.esm.js +5 -1
- 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/extras.d.ts +14 -0
package/lib/ski-quest.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";(()=>{var k=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports);var Z=k((
|
|
2
|
-
`)}toJSON(){return this.format()}},x=class i extends g{constructor(t,e){super(),this.arg=e,this.fun=t}weight(){return this.fun.weight()+this.arg.weight()}_traverse_descend(t,e){let[s,n]=y(this.fun._traverse_redo(t,e));if(n===f.stop)return f.stop(s?s.apply(this.arg):null);let[r,o]=y(this.arg._traverse_redo(t,e)),a=s||r?(s??this.fun).apply(r??this.arg):null;return o===f.stop?f.stop(a):a}any(t){return t(this)||this.fun.any(t)||this.arg.any(t)}_fold(t,e){let[s=t,n="descend"]=y(e(t,this));if(n===f.prune)return s;if(n===f.stop)return f.stop(s);let[r=s,o="descend"]=y(this.fun._fold(s,e));if(o===f.stop)return f.stop(r);let[a=r,h="descend"]=y(this.arg._fold(r,e));return h===f.stop?f.stop(a):a}subst(t,e){let s=this.fun.subst(t,e),n=this.arg.subst(t,e);return s||n?(s??this.fun).apply(n??this.arg):null}step(){if(!this.final){let t=this.fun.invoke(this.arg);if(t instanceof g)return{expr:t,steps:1,changed:!0};typeof t=="function"&&(this.invoke=t);let e=this.fun.step();if(e.changed)return{expr:e.expr.apply(this.arg),steps:e.steps,changed:!0};let s=this.arg.step();if(s.changed)return{expr:this.fun.apply(s.expr),steps:s.steps,changed:!0};this.final=!0}return{expr:this,steps:0,changed:!1}}invoke(t){let e=this.fun.invoke(this.arg);return e instanceof g?e.apply(t):typeof e=="function"?(this.invoke=e,e(t)):(this.invoke=s=>null,null)}unroll(){return[...this.fun.unroll(),this.arg]}diff(t,e=!1){if(!(t instanceof i))return super.diff(t,e);let s=this.fun.diff(t.fun,e);if(s)return s+"(...)";let n=this.arg.diff(t.arg,e);return n?this.fun+"("+n+")":null}_braced(t){return!t}_format(t,e){let s=this.fun._format(t,e+1),n=this.arg._format(t,0),r=e?["",""]:t.around;return t.terse&&!this.arg._braced(!1)?r[0]+s+(this.fun._unspaced(this.arg)?"":t.space)+n+r[1]:r[0]+s+t.brackets[0]+n+t.brackets[1]+r[1]}_unspaced(t){return this.arg._braced(!1)?!0:this.arg._unspaced(t)}},E=class i extends g{constructor(t){if(super(),typeof t!="string"||t.length===0)throw new Error("Attempt to create a named term with improper name");this.name=t}_unspaced(t){return!!(t instanceof i&&(this.name.match(/^[A-Z+]$/)&&t.name.match(/^[a-z+]/i)||this.name.match(/^[a-z+]/i)&&t.name.match(/^[A-Z+]$/)))}_format(t,e){let s=t.html?this.fancyName??this.name:this.name;return this.arity>0&&this.arity<=e?t.redex[0]+s+t.redex[1]:s}},Zt=0,v=class i extends E{constructor(t,e){super(t),this.id=++Zt,this.scope=e===void 0?this:e}weight(){return 0}diff(t,e=!1){if(!(t instanceof i))return super.diff(t,e);if(this.name===t.name&&this.scope===t.scope)return null;let s=this.name+"["+this.id+"]",n=t.name+"["+t.id+"]";return e?"["+n+" != "+s+"]":"["+s+" != "+n+"]"}subst(t,e){return t instanceof i&&t.name===this.name&&t.scope===this.scope?e:null}_format(t,e){let s=t.html?this.fancyName??this.name:this.name;return t.var[0]+s+t.var[1]}};v.global=["global"];var K=class extends E{constructor(t,e,s={}){super(t),this.invoke=e,this._setup({canonize:!0,...s})}},b=class i extends g{constructor(t,e){if(Array.isArray(t)){if(t.length===0)throw new Error("empty argument list in lambda constructor");let[n,...r]=t,o=new Set([n.name]);for(;r.length>0;){let a=r.pop();if(o.has(a.name))throw new Error("Duplicate free var name "+a+" in lambda expression");o.add(a.name),e=new i(a,e)}t=n}super();let s=new v(t.name,this);this.arg=s,this.impl=e.subst(t,s)??e,this.arity=1}weight(){return this.impl.weight()+1}invoke(t){return this.impl.subst(this.arg,t)??this.impl}_traverse_descend(t,e){let[s,n]=y(this.impl._traverse_redo(t,e)),r=s?new i(this.arg,s):null;return n===f.stop?f.stop(r):r}any(t){return t(this)||this.impl.any(t)}_fold(t,e){let[s=t,n="descend"]=y(e(t,this));if(n===f.prune)return s;if(n===f.stop)return f.stop(s);let[r,o]=y(this.impl._fold(s,e));return o===f.stop?f.stop(r):r??s}subst(t,e){if(t===this.arg)return null;let s=this.impl.subst(t,e);return s?new i(this.arg,s):null}diff(t,e=!1){if(!(t instanceof i))return super.diff(t,e);let s=new v("t"),n=this.invoke(s).diff(t.invoke(s),e);return n?"(t->"+n+")":null}_format(t,e){return(e>0?t.brackets[0]:"")+t.lambda[0]+this.arg._format(t,0)+t.lambda[1]+this.impl._format(t,0)+t.lambda[2]+(e>0?t.brackets[1]:"")}_braced(t){return!0}},j=class i extends g{constructor(t){if(t=Number.parseInt(t),!(t>=0))throw new Error("Church number must be a non-negative integer");super(),this.invoke=e=>s=>{let n=s;for(let r=t;r-- >0;)n=e.apply(n);return n},this.n=t,this.arity=2}diff(t,e=!1){return t instanceof i?this.n===t.n?null:e?"["+t.n+" != "+this.n+"]":"["+this.n+" != "+t.n+"]":super.diff(t,e)}_unspaced(t){return!1}_format(t,e){return e>=2?t.redex[0]+this.n+t.redex[1]:this.n+""}};function mt(i,t){return e=>t<=1?i.apply(e):mt(i.apply(e),t-1)}var A=class extends E{constructor(t,e,s={}){if(super(t),!(e instanceof g))throw new Error("Attempt to create an alias for a non-expression: "+e);this.impl=e,this._setup(s),this.terminal=s.terminal??this.props?.proper,this.invoke=mt(e,this.arity??0)}weight(){return this.terminal?1:this.impl.weight()}_traverse_descend(t,e){return this.impl._traverse_redo(t,e)}any(t){return t(this)||this.impl.any(t)}_fold(t,e){let[s=t,n]=y(e(t,this));if(n===f.prune)return s;if(n===f.stop)return f.stop(s);let[r,o]=y(this.impl._fold(s,e));return o===f.stop?f.stop(r):r??s}subst(t,e){return this===t?e:this.impl.subst(t,e)}step(){return this.arity>0?{expr:this,steps:0,changed:!1}:{expr:this.impl,steps:0,changed:!0}}diff(t,e=!1){return this===t?null:t.diff(this.impl,!e)}_braced(t){return this.outdated?this.impl._braced(t):!1}_format(t,e){return(t.inventory?t.inventory[this.name]!==this:this.outdated)?this.impl._format(t,e):super._format(t,e)}};function L(i,t,e){T[i]=new K(i,t,e)}L("I",i=>i);L("K",i=>t=>i);L("S",i=>t=>e=>i.apply(e,t.apply(e)));L("B",i=>t=>e=>i.apply(t.apply(e)));L("C",i=>t=>e=>i.apply(e).apply(t));L("W",i=>t=>i.apply(t).apply(t));L("+",i=>i instanceof j?new j(i.n+1):t=>e=>t.apply(i.apply(t,e)),{note:"Increase a Church numeral argument by 1, otherwise n => f => x => f(n f x)"});function Wt(i){for(;i instanceof x;)i=i.fun;return i instanceof v}function dt(i,t,e={}){let s=new Array(i.length).fill(0),n=!0;t.traverse(a=>{if(a instanceof v){let h=i.findIndex(u=>u.name===a.name);if(h>=0){s[h]++;return}}a instanceof x||(n=!1)});let r=new Set,o=new Set;for(let a=0;a<i.length;a++)s[a]===0?r.add(a):s[a]>1&&o.add(a);return{normal:!0,steps:e.steps,expr:i.length?new b(i,t):t,arity:i.length,...r.size?{skip:r}:{},...o.size?{dup:o}:{},duplicate:!!o.size||e.duplicate||!1,discard:!!r.size||e.discard||!1,proper:n}}function Jt(i){return new v("abcdefgh"[i]??"x"+i)}function Yt(i,t){if(i instanceof g&&(i=[i]),t)i||(i=Object.keys(t).sort().map(r=>t[r]));else{if(!i)return[];if(!t){t={};for(let r of i)if(r instanceof E){if(t[r.name])throw new Error("duplicate name "+r);t[r.name]=r}}}let e=[],s=new Set,n=r=>{s.has(r)||(r.fold(null,(o,a)=>{if(a!==r&&a instanceof E&&t[a.name]===a)return n(a),g.control.prune(null)}),e.push(r),s.add(r))};for(let r of i)n(r);return{list:e,env:t}}g.native=T;g.control=f;g.extras={toposort:Yt};wt.exports={Expr:g,App:x,Named:E,FreeVar:v,Lambda:b,Native:K,Alias:A,Church:j}});var X=k((Le,yt)=>{"use strict";var{Tokenizer:Gt,restrict:Y}=Z(),vt=J(),{Expr:C,Named:qe,Native:Xt,Alias:_,FreeVar:I,Lambda:te,Church:xt}=vt,{native:M}=C,$=class extends C{apply(...t){return t.length?t.shift().apply(...t):this}postParse(){throw new Error("Attempt to use empty expression () as a term")}},G=class i extends ${constructor(t,e={}){if(super(),this.impl=new $,t instanceof I)this.terms=[t];else if(t instanceof i){if(!(t.impl instanceof I))throw new Error("Expected FreeVar->...->FreeVar->Expr");this.terms=[...t.terms,t.impl]}else throw new Error("Expected FreeVar or PartialLambda")}apply(t,...e){if(t===null||e.length!==0)throw new Error("bad syntax in partial lambda expr");return this.impl=this.impl.apply(t),this}postParse(){return new te(this.terms,this.impl)}};function gt(i){return i.postParse?i.postParse():i}var ee=new Gt("[()]","[A-Z]","[a-z_][a-z_0-9]*","\\b[0-9]+\\b","->","\\+"),S=class{constructor(t={}){if(this.annotate=t.annotate??!1,this.known={...M},this.hasNumbers=!0,this.hasLambdas=!0,this.allow=new Set(Object.keys(this.known)),Array.isArray(t.terms))this.bulkAdd(t.terms);else if(t.terms)for(let e in t.terms)t.terms[e].match(/^Native:/)||this.add(e,t.terms[e]);this.hasNumbers=t.numbers??!0,this.hasLambdas=t.lambdas??!0,t.allow&&this.restrict(t.allow)}add(t,e,s){return t=this._named(t,e),typeof s=="string"&&(s={note:s,canonize:!1}),t._setup({canonize:this.annotate,...s}),this.known[t.name]&&(this.known[t.name].outdated=!0),this.known[t.name]=t,this.allow.add(t.name),this}_named(t,e){if(t instanceof _)return new _(t.name,t.impl,{canonize:!0});if(typeof t!="string")throw new Error("add(): term must be an Alias or a string");if(e===void 0)throw new Error("add(): impl must be provided when term is a string");if(typeof e=="string")return new _(t,this.parse(e),{canonize:!0});if(e instanceof C)return new _(t,e,{canonize:!0});if(typeof e=="function")return new Xt(t,e);throw new Error("add(): impl must be an Expr, a string, or a function with a signature Expr => ... => Expr")}maybeAdd(t,e){return this.known[t]?this.allow.add(t):this.add(t,e),this}bulkAdd(t){for(let e of t){let s=e.match(/^([A-Z]|[a-z][a-z_0-9]*)\s*=\s*(.*)$/s);if(!s)throw new Error("bulkAdd: invalid declaration: "+e);s[2]===""?this.remove(s[1]):this.add(s[1],this.parse(s[2]))}return this}restrict(t){return this.allow=Y(this.allow,t),this}showRestrict(t="+"){let e=[],s=!0;for(let n of[...Y(this.allow,t)].sort()){let r=n.match(/^[A-Z]$/);e.length&&!(s&&r)&&e.push(" "),e.push(n),s=r}return e.join("")}remove(t){return this.known[t].outdated=!0,delete this.known[t],this.allow.delete(t),this}getTerms(){let t={};for(let e of Object.keys(this.known))this.allow.has(e)&&(t[e]=this.known[e]);return t}declare(){let t=this.getTerms();for(let a in t)t[a]instanceof _||delete t[a];let e={},s=1;for(let a in M){if(!(t[a]instanceof _))continue;for(;"tmp"+s in t;)s++;let h=new _("tmp"+s,t[a]);e[h]=t[a],t[h]=h,delete t[a]}let n=C.extras.toposort(void 0,t).list,r=new Map;if(Object.keys(e).length){let a=h=>h.traverse(u=>{if(!(u instanceof _))return null;let p=r.get(u);return p||new _(u.name,a(u.impl))})??h;for(let h=0;h<n.length;h++)n[h]=a(n[h],r),r.set(e[n[h].name],n[h]),t[n[h].name]=n[h],console.log(`list[${h}] = ${n[h].name}=${n[h].impl};`);console.log("detour:",r)}let o=n.map(a=>e[a]?a.name+"="+e[a].name+"="+a.impl.format({inventory:t}):a.name+"="+a.impl.format({inventory:t}));for(let[a,h]of r)o.push(a+"="+h,h+"=");return o}parse(t,e={}){if(typeof t!="string")throw new Error("parse: source must be a string, got "+typeof t);let s=t.replace(/\/\/[^\n]*$/gm," ").replace(/\/\*.*?\*\//gs," ").trim().split(/\s*;[\s;]*/).filter(o=>o.match(/\S/)),n={...e.env},r=new $;for(let o of s){r instanceof _&&(r.outdated=!0);let a=o.match(/^([A-Z]|[a-z][a-z_0-9]*)\s*=(.*)$/s);if(a&&a[2]===""?r=new I(a[1],e.scope??I.global):r=this.parseLine(o,n,e),a){if(n[a[1]]!==void 0)throw new Error("Attempt to redefine a known term: "+a[1]);n[a[1]]=r}}return r.context={env:{...this.getTerms(),...n},scope:e.scope,src:t,parser:this},r}parseLine(t,e={},s={}){let n=t.match(/^\s*([A-Z]|[a-z][a-z_0-9]*)\s*=\s*(.*)$/s);if(n)return new _(n[1],this.parseLine(n[2],e,s));let r={numbers:s.numbers??this.hasNumbers,lambdas:s.lambdas??this.hasLambdas,allow:Y(this.allow,s.allow)};r.numbers?r.allow.add("+"):r.allow.delete("+");let o=ee.split(t),a=new $,h=[a],u=s.scope||I.global;for(let p of o)if(p==="(")h.push(a);else if(p===")"){if(h.length<2)throw new Error("unbalanced input: extra closing parenthesis"+t);let w=gt(h.pop()),d=h.pop();h.push(d.apply(w))}else if(p==="->"){if(!r.lambdas)throw new Error("Lambdas not supported, allow them explicitly");h.push(new G(h.pop(),e))}else if(p.match(/^[0-9]+$/)){if(!r.numbers)throw new Error("Church numbers not supported, allow them explicitly");let w=h.pop();h.push(w.apply(new xt(p)))}else{let w=h.pop();if(!e[p]&&this.known[p]&&!r.allow.has(p))throw new Error("Term '"+p+"' is not in the restricted set "+[...r.allow].sort().join(" "));let d=e[p]??this.known[p]??(e[p]=new I(p,u));h.push(w.apply(d))}if(h.length!==1)throw new Error("unbalanced input: missing "+(h.length-1)+" closing parenthesis:"+t);return gt(h.pop())}toJSON(){return{version:"1.1.1",allow:this.showRestrict("+"),numbers:this.hasNumbers,lambdas:this.hasLambdas,annotate:this.annotate,terms:this.declare()}}};S.vars=function(i={}){let t={};return new Proxy({},{get:(e,s)=>(s in t||(t[s]=new I(s,i)),t[s])})};S.church=i=>new xt(i);for(let i in M)S[i]=M[i];S.classes=vt;S.native=M;S.control=C.control;yt.exports={SKI:S}});var rt=k(($e,St)=>{var{SKI:q}=X(),{Expr:Ie,FreeVar:se,Alias:bt,Lambda:ze}=q.classes,z=class{constructor(t){let{input:e,cases:s,allow:n,numbers:r,lambdas:o,engine:a,engineFull:h,...u}=t,p=t.env??t.vars;this.engine=a??new q,this.engineFull=h??new q,this.restrict={allow:n,numbers:r??!1,lambdas:o??!1},this.env={};let w={};for(let d of p??[]){let l=this.engineFull.parse(d,{env:w,scope:this});if(l instanceof q.classes.Alias)this.env[l.name]=new bt(l.name,l.impl,{terminal:!0,canonize:!1});else if(l instanceof q.classes.FreeVar)this.env[l.name]=l;else throw new Error("Unsupported given variable type: "+d)}this.input=[];for(let d of Array.isArray(e)?e:[e])this.addInput(d);if(!this.input.length)throw new Error("Quest needs at least one input placeholder");this.envFull={...this.env,...w};for(let d of this.input){if(d.name in this.envFull)throw new Error("input placeholder name is duplicated or clashes with env: "+d.name);this.envFull[d.name]=d.placeholder}this.cases=[],this.name=u.name??u.title,u.intro=kt(u.intro??u.descr),this.intro=u.intro,this.id=u.id,this.meta=u;for(let d of s??[])this.add(...d)}allowed(){let t=this.restrict.allow??"",e=Object.keys(this.env).sort();return t?this.engine.showRestrict(t+"+"+e.join(" ")):e.map(s=>"+"+s).join(" ")}addInput(t){if(typeof t!="object"&&(t={name:t}),typeof t.name!="string")throw new Error("quest 'input' field must be a string or a {name: string, ...} object");t.placeholder=new q.classes.FreeVar(t.name),this.input.push(t)}add(t,...e){typeof t=="string"?(e.unshift(t),t={}):t={...t},t.engine=t.engine??this.engineFull,t.env=t.env??this.envFull;let s=this.input.map(n=>n.placeholder);return this.cases.push(t.caps?new et(s,t,e):new tt(s,t,e)),this}prepare(...t){if(t.length!==this.input.length)throw new Error("Solutions provided "+t.length+" terms where "+this.input.length+" are expected");let e=0,s=[],n={...this.env};for(let r=0;r<t.length;r++){let o=this.input[r],a=this.engine.parse(t[r],{env:n,allow:o.allow??this.restrict.allow,numbers:o.numbers??this.restrict.numbers,lambdas:o.lambdas??this.restrict.lambdas}),h={...this.engine.getTerms(),...n};e+=a.fold(0,(p,w)=>{if(w instanceof q.classes.Named&&h[w.name]===w)return q.control.prune(p+1)});let u=a instanceof se?a:new bt(o.fancy??o.name,a,{terminal:!0,canonize:!1});n[o.name]=u,s.push(u)}return{prepared:s,weight:e}}check(...t){try{let{prepared:e,weight:s}=this.prepare(...t),n=this.cases.map(a=>a.check(...e)),r=n.reduce((a,h)=>a&&h.pass,!0),o=n.reduce((a,h)=>a+h.steps,0);return{expr:e[0],input:e,pass:r,steps:o,details:n,weight:s}}catch(e){return{pass:!1,details:[],exception:e,steps:0,input:t}}}verify(t){let e=this.verifyMeta(t);if(t.solutions){let s=this.verifySolutions(t.solutions);s&&(e.solutions=s)}return t.seen&&(this.id||(e.seen="No id in quest "+(this.name??"(unnamed)")),t.seen.has(this.id)&&(e.seen="Duplicate quest id "+this.id),t.seen.add(this.id)),Object.keys(e).length?e:null}verifySolutions(t){if(typeof t=="object"&&!Array.isArray(t?.accepted)&&!Array.isArray(t?.rejected)&&(!this.id||!t[this.id]))return null;let{accepted:e=[],rejected:s=[]}=t[this.id]??t,n={shouldPass:[],shouldFail:[]};for(let r of e){let o=this.check(...r);o.pass||n.shouldPass.push({input:r,result:o})}for(let r of s){let o=this.check(...r);o.pass&&n.shouldFail.push({input:r,result:o})}return n.shouldFail.length+n.shouldPass.length?n:null}verifyMeta(t={}){let e={};for(let s of["name","intro"]){let n=_t(this[s]);n&&(e[s]=n)}if(t.date){let s=new Date(this.meta.created_at);isNaN(s)?e.date="invalid date format: "+this.meta.created_at:(s<new Date("2024-07-15")||s>new Date)&&(e.date="date out of range: "+this.meta.created_at)}return e}show(){return[...this.cases]}},N=class{constructor(t,e){this.max=e.max??1e3,this.note=e.note,this.env={...e.env??{}},this.input=t,this.engine=e.engine}parse(t){return new st(this.engine.parse(t,{env:this.env,scope:this}),this.input)}check(...t){throw new Error("not implemented")}},tt=class extends N{constructor(t,e,s){if(s.length!==2)throw new Error("Case accepts exactly 2 strings");super(t,e),[this.e1,this.e2]=s.map(n=>this.parse(n))}check(...t){let e=this.e1.apply(t),s=e.run({max:this.max}),r=this.e2.apply(t).run({max:this.max}),o=null;return!s.final||!r.final?o="failed to reach normal form in "+this.max+" steps":o=s.expr.diff(r.expr),{pass:!o,reason:o,steps:s.steps,start:e,found:s.expr,expected:r.expr,note:this.note,args:t,case:this}}},ne={normal:!0,proper:!0,discard:!0,duplicate:!0,linear:!0,affine:!0,arity:!0},et=class extends N{constructor(t,e,s){if(super(t,e),s.length>1)throw new Error("PropertyCase accepts exactly 1 string");if(!e.caps||typeof e.caps!="object"||!Object.keys(e.caps).length)throw new Error("PropertyCase requires a caps object with at least one capability");let n=Object.keys(e.caps).filter(r=>!ne[r]);if(n.length)throw new Error("PropertyCase: don't know how to test these capabilities: "+n.join(", "));this.expr=this.parse(s[0]),this.caps=e.caps,this.caps.linear&&(delete this.caps.linear,this.caps.duplicate=!1,this.caps.discard=!1,this.caps.normal=!0),this.caps.affine&&(delete this.caps.affine,this.caps.normal=!0,this.caps.duplicate=!1)}check(...t){let e=this.expr.apply(t),s=e.run({max:this.max}),n=s.expr.infer({max:this.max}),r=[];for(let o in this.caps)n[o]!==this.caps[o]&&r.push("expected property "+o+" to be "+this.caps[o]+", found "+n[o]);return{pass:!r.length,reason:r?r.join(`
|
|
3
|
-
`):null,steps:s.steps,start:e,found:s.expr,case:this,note:this.note,args:t}}},st=class{constructor(t,e){this.expr=t,this.env=e}apply(t){if(t.length!==this.env.length)throw new Error("Subst: expected "+this.env.length+" terms, got "+t.length);let e=this.expr;for(let s=0;s<this.env.length;s++)e=e.subst(this.env[s],t[s])??e;return e}},nt=class{constructor(t){this.name=t.name,this.intro=kt(t.intro),this.id=t.id,t.content&&(this.content=t.content.map(e=>e instanceof z?e:new z(e)))}verify(t){let e={},s=re(this.id,t.seen);s&&(e[this.id]=s);for(let n of["name","intro"]){let r=_t(this[n]);r&&(e[n]=r)}return e.content=this.content.map(n=>n.verify(t)),e}};function kt(i){return i===void 0||typeof i=="string"?i:Array.isArray(i)?i.join(" "):""+i}function re(i,t){if(i===void 0)return"missing";if(typeof i!="string"&&typeof i!="number")return"is a "+typeof i;if(t){if(t.has(i))return"duplicate id "+i;t.add(i)}}function _t(i){if(i===void 0)return"missing";if(typeof i!="string")return"not a string but "+typeof i;let t=[],e=/<\/?([a-z]+)(?:\s[^>]*)?>/gi,s;for(;(s=e.exec(i))!==null;){let[n,r]=s;if(n.startsWith("</")){if(t.length===0||t.pop()!==r)return`Unmatched closing tag: </${r}>`}else t.push(r)}return t.length>0?`Unclosed tags: ${t.join(", ")}`:null}z.Group=nt;z.Case=N;St.exports={Quest:z}});var Lt=k((Fe,qt)=>{"use strict";var{Expr:Et,Alias:ie,FreeVar:ae}=J(),{Quest:At}=rt();function oe(i,t,e){let{depth:s=16,infer:n=!0,progressInterval:r=1e3}=t,o=n&&!t.noskip,a=[[]],h=0,u=0,p={},w=l=>{h++;let m=n?l.infer({max:t.max,maxArgs:t.maxArgs}):null;if(o&&m.expr){if(p[m.expr])return{res:-1};p[m.expr]=!0}return u++,{res:e(l,m),props:m}};for(let l of i){let{res:m}=w(l);if(m>0)return{expr:l,total:h,probed:u,gen:1};if(m<0)continue;a[0].push(l)}let d;for(let l=1;l<s;l++){t.progress&&(t.progress({gen:l,total:h,probed:u,step:!0}),d=h);for(let m=0;m<l;m++)for(let ut of a[l-m-1]||[])for(let Kt of a[m]||[]){if(h>=t.tries)return{total:h,probed:u,gen:l,...t.retain?{cache:a}:{}};t.progress&&h-d>=r&&(t.progress({gen:l,total:h,probed:u,step:!1}),d=h);let B=ut.apply(Kt),{res:ft,props:Q}=w(B);if(ft>0)return{expr:B,total:h,probed:u,gen:l,...t.retain?{cache:a}:{}};if(ft<0)continue;let D=n?(Q.expr?0:3)+(Q.dup?1:0)+(Q.proper?0:1):0;a[l+D]||(a[l+D]=[]),a[l+D].push(B)}}return{total:h,probed:u,gen:s,...t.retain?{cache:a}:{}}}function it(i,t={}){if(i instanceof Et)return i.format(t);if(i instanceof At)return"Quest("+i.name+")";if(i instanceof At.Case)return"Quest.Case";if(Array.isArray(i))return i.map(it);if(typeof i!="object"||i===null||i.constructor!==Object)return i;let e={};for(let s in i)e[s]=it(i[s]);return e}function he(i,t){let e=Et.extras.toposort([i],t);return e.list.map(s=>s instanceof ie?s.name+"="+s.impl.format({inventory:e.env}):s instanceof ae?s.name+"=":s.format({inventory:e.env})).join("; ")}qt.exports={search:oe,deepFormat:it,declare:he}});var $t=k((Te,zt)=>{var{SKI:F}=X(),{Quest:It}=rt(),ce=Lt();F.Quest=It;F.extras={...ce,...F.classes.Expr.extras};typeof process=="object"&&process.env.SKI_REPL&&typeof global<"u"&&(global.SKI=F,console.log("SKI_REPL activated, try `new SKI();`"));typeof window<"u"&&(window.SKI=F);zt.exports={SKI:F,Quest:It}});var Tt=k((je,Ft)=>{var at=class{constructor(t){this.ns=t+":"}save(t,e){window.localStorage.setItem(this.ns+t,JSON.stringify(e))}load(t){return JSON.parse(window.localStorage.getItem(this.ns+t))}scan(){let t=window.localStorage,e=[];for(let s=0;s<t.length;s++){let n=t.key(s);n.startsWith(this.ns)&&e.push(n.substring(this.ns.length))}return e}delete(t){window.localStorage.removeItem(this.ns+t)}};Ft.exports={Store:at}});var ot=k((Ce,Ct)=>{"use strict";function le(...i){let t={};for(let e of i){let s=e.replace(/[A-Z]/g,n=>"-"+n.toLowerCase());if(t[e]=document.getElementById(s),!t[e])throw new Error(`View element not found: ${s}`)}return t}function ue(i,t,e={},s=null){let n=document.createElement(t);return e.class&&n.classList.add(...e.class),e.content!==void 0&&(n.innerHTML=""+e.content),e.hidden&&(n.hidden=!0),e.color&&(n.style.color=e.color),i&&i.appendChild(n),s&&s(n),n}function jt(i,t){t(i);for(let e of i.childNodes)jt(e,t)}function fe(i){typeof i!="string"&&(i=""+i);let t={"<":"<",">":">","&":"&"};return i.replace(/[<>&]/g,e=>t[e])}function pe(i){let t={"(":"%28",")":"%29"};return encodeURIComponent(i).replace(/[()]/g,e=>t[e]).replace(/%20/g,"+")}function de(i){return decodeURIComponent((""+i).replace(/\+/g," "))}Ct.exports={append:ue,decode:de,encode:pe,grabView:le,sanitize:fe,traverse:jt}});var Nt=k((Me,Mt)=>{"use strict";var{append:ht}=ot(),ct=class{constructor(t={}){this.options=t,this.height=t.height??5,this.running=!1,this.delay=t.delay??0,this.maxSteps=t.max??1/0,this.onStart=t.onStart??(()=>{}),this.onStop=t.onStop??(()=>{}),this.onStep=t.onStep??(()=>{}),this.engine=t.engine,this.format=t.format??{html:!0},this.generator=t.generator??(e=>e.walk()),this.set(t.expr),this.view={},this.view.parent=t.parent,this.view.scroll=t.scroll??t.parent,this.view.main=ht(t.parent,"ol",{class:["ski-eval-box"]})}set(t){if(typeof t=="string")this.src=t,this.expr=this.engine.parse(t);else if(Array.isArray(t)&&t.length===2)this.src=t[0],this.expr=t[1];else if(!t)this.expr=null,this.src=null;else if(typeof t=="object"&&typeof t.format=="function")this.expr=t,this.src=t.format();else throw new Error("EvalBox.set() expects a string, Expr, or [string, Expr]");return this}start(t){this.running&&this.stop();try{t!==void 0&&this.set(t),this.seq=this.generator(this.expr)}catch(e){return console.error(e),this.stop(e.message)}return this.view.main.innerHTML="",this.onStart(),this.running=!0,this.tick(),this}stop(t){this.running=!1,this.timer&&(clearTimeout(this.timer),this.timer=null),t&&this.print(t,{class:["ski-eval-error"],line:""}),this.onStop()}resume(){this.running||!this.seq||(this.running=!0,this.onStart(),this.tick())}tick(){if(!this.running)return;let{value:t,done:e}=this.seq.next();if(t&&this.print(t.expr.format(this.format),{line:t.steps}),this.onStep(t,e||t.final),e||t.final)return this.view.last&&this.view.last.classList.add("ski-eval-success"),this.seq=null,this.stop();if(t.steps>=this.maxSteps)return this.stop("Max steps reached: "+this.maxSteps);this.timer=setTimeout(()=>this.tick(),this.delay)}remove(){this.view.parent&&(this.view.parent.removeChild(this.view.main),this.view.parent=null)}clear(){this.stop(),this.view.main.innerHTML=""}setHeight(t){this.height=t}print(t,e={}){let s=ht(this.view.main,"li",e);if(e.line!==0&&!e.line?s.style["list-style"]="none":(this.view.main.style["padding-left"]=(""+e.line).length+2.5+"ch",s.value=e.line),this.view.last=s,e.raw)s.innerHTML=t;else for(ht(s,"span",{class:e.class??["ski-eval-line"],color:e.color,content:t});this.view.main.children.length>this.height;)this.view.main.removeChild(this.view.main.firstChild);return this.view.scroll&&(this.view.scroll.scrollTop=s.offsetTop),s}};Mt.exports={EvalBox:ct}});var Ht=k((Ne,Ut)=>{"use strict";var{SKI:P}=$t(),{Store:me}=Tt(),{EvalBox:we}=Nt(),{append:c}=ot(),lt=class{constructor(t){if(this.view={},this.root=t.baseUrl??".",!t.store&&!t.storePrefix)throw new Error("No storePrefix provided");this.store=t.store??new me(t.storePrefix),this.engine=t.engine??new P(this.store.load("engine")??{annotate:!0,allow:"SKI"}),t.inventoryBox&&(this.view.inventory=t.inventoryBox,this.showKnown()),this.view.content=t.contentBox,t.indexBox&&(this.view.index=c(t.indexBox,"div",{class:["ski-quest-nav"]})),this._onSolved=t.onSolved,this._onFailed=t.onFailed,this._onUnlock=t.onUnlock,this.chapters=[]}loadFromIndex(t,e,s){fetch(this.mkLink(t)).then(n=>n.json()).then(n=>this.loadChapters(n)).then(n=>{if(s&&s(n),e){let r=document.getElementById(e);r&&r.scrollIntoView()}})}async loadChapters(t){let e=0;this.chapters=[];let s=[];for(let n of t){let r=new V({number:++e,link:this.mkLink(n),engine:this.engine,store:this.store,onUnlock:o=>this.onUnlock(o),onSolved:o=>this._onSolved(o),onFailed:o=>this._onFailed(o)});this.chapters.push(r),r.attach(this.view.content,{placeholder:"loading chapter"+r.number+"..."}),this.view.index&&r.addLink(this.view.index),s.push(r.fetch().then(o=>{o.draw()}))}return Promise.all(s).then(()=>this)}mkLink(t){return t.match(/^\w+:\/\//)||t.match(/^[/.]/)?t:this.root+"/"+t}onUnlock(t){this.engine.maybeAdd(t.name,t.impl),this.store&&this.store.save("engine",this.engine),this.showKnown(),this._onUnlock&&this._onUnlock(t)}showKnown(){if(!this.view.inventory)return;this.view.inventory.innerHTML="";let t=c(this.view.inventory,"ul",{class:["ski-quest-inventory"]}),e=this.engine.getTerms();for(let s of Object.keys(e).sort().map(n=>[n,e[n]])){let n=c(t,"li",{},r=>{r.dataset.skiTerm=s[0]});c(n,"span",{content:s[0],class:["ski-quest-term-name"]}),c(n,"span",{content:": "}),c(n,"span",{content:xe(s[1]),class:["ski-quest-term-def"]})}}demolish(){for(let t of this.store.scan())this.store.delete(t)}},R=class{constructor(t,e){let s=e.engine??e.chapter?.engine;if(!s)throw new Error("QuestBox requires an engine: SKI in either options or chapter");let n=e.store??e.chapter?.store;if(!n)throw new Error("QuestBox requires a store: Store in either options or chapter");this.impl=new P.Quest({...t,engine:s}),this.name=this.impl.id?"quest-"+this.impl.id:"",this.chapter=e.chapter,this.chapter&&e.number&&(this.number=this.chapter.number+"."+e.number),this.store=n,this.engine=s,this.view={},this.input=[]}load(){let t=this.store.load(this.name)??{};return this.status={solved:t.solved??!1,steps:t.steps??0,attempts:t.attempts??0,weight:t.weight??0,total:t.total??0},this.status.solved&&this.onSolved(),this}save(){return this.store.save(this.name,this.status),this}update(t){this.status.solved||(this.status.attempts++,this.status.total+=t.steps,this.status.steps=t.steps,this.status.weight=t.weight,t.pass&&(this.status.solved=!0,this.onSolved(t)),this.save(),this.showStatus())}onSolved(t){if(this.impl.meta.unlock&&t){let e=new P.classes.Alias(this.impl.meta.unlock,t.expr.expand());this.chapter?.onUnlock(e)}this.chapter&&this.chapter.addSolved(this.impl.id)}check(){this.view.display&&(this.view.display.innerHTML="running...");let t=this.input.map(s=>s.value),e=this.impl.check(...t);this.showResult(e),this.update(e)}draw(t){this.view.frame=c(t,"div",{class:["ski-quest-box"]}),this.view.frame.id=this.name;let e=c(this.view.frame,"h3"),s=c(this.view.frame,"div"),n=c(e,"a",{content:this.number?"#"+this.number:"Quest"});n.href="#"+this.name,n.onclick=()=>Ot(s,!0),c(e,"span",{content:" "+this.impl.name});let r=this.impl.allowed();r&&c(e,"span",{content:" ["+r+"]"}),this.view.stat=c(e,"span",{class:["ski-quest-float-right"]});let o=c(s,"div");c(o,"div",{content:Pt(this.impl.intro),class:["ski-quest-intro"]}),this.impl.meta.hint&&ge(o," Hint:..."," Hint: "+this.impl.meta.hint),this.view.display=c(s,"div",{class:["ski-quest-display"],content:"....."}),this.view.solution=c(s,"div",{class:["ski-quest-input"]}),this.drawInput(this.view.solution),this.showStatus()}drawInput(t){let e=this.impl.input,s=e.length!==1;for(let r of e){if(s){let a=c(t,"div",{class:["ski-quest-label"]});c(a,"b",{content:r.name}),r.note&&c(a,"span",{content:" // "+r.note,class:["ski-quest-comment"]})}let o=c(t,"input");o.type="text",o.onkeydown=a=>{a.key==="Enter"&&(a.preventDefault(),this.check())},this.input.push(o),c(t,"br")}let n=c(t,"button",{content:"solve!"});n.onclick=()=>this.check()}showStatus(){if(this.view.stat&&this.status.attempts){let t="in "+this.status.attempts+(this.status.attempts===1?" try":" tries"),e=this.status.solved?"✓ "+this.status.steps+" steps/"+this.status.weight+" terms ":this.status.total+" total steps ";this.view.stat.innerHTML=e+" "+t}}showResult(t){if(!this.view.display)return;this.view.display.innerHTML="";let e=c(this.view.display,"div");c(e,"span",{content:"Your solution: "+ve(t.expr)+" "}),t.exception&&c(this.view.display,"div",{class:["ski-quest-error"],content:"Execution failed: "+t.exception});for(let s of t.details){let n=c(this.view.display,"div",{class:s.pass?["ski-quest-success"]:["ski-quest-error"]});c(n,"span",{content:s.pass?"✓ ":"✗ "}),c(n,"span",{content:`${s.start} → ${s.found} `});let r=c(n,"a",{content:`in ${s.steps} steps`,class:["ski-quest-control"]});c(n,"span",{content:" "});let o=c(n,"a",{content:" (hide)",class:["ski-quest-control"],hidden:!0});s.pass||(c(n,"br"),s.expected!==void 0&&(c(n,"span",{content:" expected: "+s.expected}),c(n,"br")),s.reason&&(c(n,"span",{content:" "+s.reason}),c(n,"br")));let a=c(n,"div",{});r.onclick=()=>{a.innerHTML="",o.hidden=!1,new we({parent:a,engine:this.engine,height:1/0,max:s.steps+2,headless:!0}).start(s.start)},o.onclick=()=>{a.innerHTML="",o.hidden=!0}}}},V=class{constructor(t){this.options=t,this.quests=[],this.solved=new Set,this.view={},this.number=t.number??0,this.engine=t.engine,this.store=t.store,this.onUnlock=t.onUnlock??(()=>{}),this.updateMeta()}updateMeta(t={}){this.options={...this.options,...t},this.id="chapter-"+(t.id??this.number),this.view.frame&&(this.view.frame.id=this.id),this.view.link&&(this.view.link.href="#"+this.id),this.options.name&&this.view.linkText&&(this.view.linkText.innerHTML="Chapter "+this.number+": "+this.options.name)}fetch(){return fetch(this.options.link).then(t=>t.json()).then(t=>{if(Array.isArray(t)&&(t={content:t}),!Array.isArray(t.content))throw new Error("Invalid quest list in "+this.options.link);this.updateMeta(t);let e=0;for(let s of t.content)this.quests.push(new R(s,{chapter:this,number:++e}));return this})}addSolved(t){this.solved.has(t)||(this.solved.add(t),this.showStatus())}getProgress(){return{total:this.quests.length,solved:this.solved.size,complete:this.solved.size===this.quests.length,percentage:Math.round(this.solved.size/this.quests.length*100)}}attach(t,e){return this.view.frame=c(t,"div",{class:["ski-quest-chapter"]}),this.view.frame.id=this.id,e.placeholder&&(this.view.placeholder=c(this.view.frame,"div",{content:e.placeholder})),this}draw(){this.visible=!0,this.view.placeholder?.remove();let t=c(this.view.frame,"h2"),e=c(this.view.frame,"div");c(t,"span",{content:"Chapter "+this.number+": "+this.options.name}),this.view.stat=c(t,"span",{class:["ski-quest-float-right"]}),t.onclick=()=>{Ot(e,this.visible=!this.visible)},this.view.intro=c(e,"div",{content:Pt(this.options.intro),class:["ski-quest-note","ski-quest-chapter-intro"]}),this.view.content=c(e,"div",{class:["ski-quest-chapter-content"]});for(let s of this.quests)s.load(),s.draw(this.view.content);this.showStatus()}showStatus(){if(!this.view.stat)return;let t=this.getProgress();this.view.stat.innerHTML="Progress: "+t.solved+"/"+t.total+" ("+t.percentage+"%)",t.complete&&this.view.stat.classList.add("success"),this.view.progressbar&&(this.view.progressbar.style.paddingRight=t.percentage+"%",this.view.progressbar.style.marginRight=-t.percentage+"%")}addLink(t){let e=c(t,"div",{class:["ski-quest-nav-item"]}),s=c(e,"a",{},n=>{n.style.display="flex"});s.href="#"+this.id,this.view.link=s,this.view.progressbar=c(s,"span",{class:["ski-quest-progressbar"]}),this.view.linkText=c(s,"span",{content:"Chapter "+this.number+"..."})}};function ge(i,t,e){let s=c(i,"span",{}),n=c(s,"span",{content:t,class:["ski-quest-hint"]});n.onclick=()=>{n.remove(),c(s,"span",{content:e})}}function Pt(i){return Array.isArray(i)?i.join(" "):""+i}function ve(i){return i instanceof P.classes.Expr?i instanceof P.classes.Alias?i.name+" = "+i.expand():""+i.expand():""+i}function Ot(i,t){t===void 0&&(t=i.hidden),i.hidden=!t}function xe(i){return i.note??(i.impl??i).format({html:!0,lambda:[""," ↦ ",""]})}Ut.exports={QuestPage:lt,QuestChapter:V,QuestBox:R}});var _e=k(()=>{var{QuestBox:ye,QuestChapter:be,QuestPage:ke}=Ht();typeof window<"u"&&(window.QuestBox=ye,window.QuestChapter=be,window.QuestPage=ke)});_e();})();
|
|
1
|
+
"use strict";(()=>{var k=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports);var Z=k((Ee,pt)=>{var O=class{constructor(...t){let e="$|(\\s+)|"+t.map(s=>"(?:"+s+")").sort((s,n)=>n.length-s.length).join("|");this.rex=new RegExp(e,"gys")}split(t){this.rex.lastIndex=0;let e=[...t.matchAll(this.rex)],n=e.pop()?.index??0;if(n!==t.length)throw new Error("Unknown tokens at pos "+n+"/"+t.length+" starting with "+t.substring(n));return e.filter(r=>r[1]===void 0).map(r=>r[0])}},Vt=new O("[-=+]","[A-Z]","\\b[a-z_][a-z_0-9]*\\b");function Bt(i,t){if(!t)return i;let e=new Set([...i]),s={"=":r=>{e=new Set([r]),n="+"},"+":r=>{e.add(r)},"-":r=>{e.delete(r)}},n="=";for(let r of Vt.split(t))s[r]?n=r:s[n](r);return e}var U=class{constructor(t,e){this.value=t,this.decoration=e}};function Qt(i){return i instanceof U?[i.value??void 0,i.decoration]:[i??void 0,void 0]}function Dt(i){let t=e=>new U(e,t);return t.label=i,t.toString=()=>"TraverseControl::"+i,t}pt.exports={Tokenizer:O,restrict:Bt,unwrap:Qt,prepareWrapper:Dt}});var J=k((qe,wt)=>{"use strict";var{unwrap:y,prepareWrapper:H}=Z(),W={max:1e3,maxArgs:32},Zt={"leftmost-outermost":"LO","leftmost-innermost":"LI",LO:"LO",LI:"LI"},f={descend:H("descend"),prune:H("prune"),redo:H("redo"),stop:H("stop")},T={},g=class i{_setup(t={}){if(t.fancy!==void 0&&(this.fancyName=t.fancyName),t.note!==void 0&&(this.note=t.note),t.arity!==void 0&&(this.arity=t.arity),t.canonize){let e=this.infer(t);e.normal&&(this.arity=this.arity??e.arity,this.note=this.note??e.expr.format({html:!0,lambda:[""," ↦ ",""]}),delete e.steps,this.props=e)}return this}apply(...t){let e=this;for(let s of t)e=new x(e,s);return e}expand(){return this.traverse(t=>{if(t instanceof A)return t.impl.expand()})??this}freeOnly(){return!this.any(t=>!(t instanceof v||t instanceof x))}traverse(t,e){typeof t=="function"&&(e=t,t={});let s=Zt[t.order??"LO"];if(s===void 0)throw new Error("Unknown traversal order: "+t.order);let[n,r]=y(this._traverse_redo({order:s},e));return n}_traverse_redo(t,e){let s,n=this,r;do{r=n;let o=t.order==="LI"?n._traverse_descend(t,e)??e(n):e(n)??n._traverse_descend(t,e);[n,s]=y(o)}while(n&&s===f.redo);return!n&&r!==this&&(n=r),s?s(n):n}_traverse_descend(t,e){return null}any(t){return t(this)}fold(t,e){let[s,n]=y(this._fold(t,e));return s??t}_fold(t,e){return e(t,this)}weight(){return 1}infer(t={}){return this._infer({max:t.max??W.max,maxArgs:t.maxArgs??W.maxArgs},0)}_infer(t,e){let s=[],n=0,r=this;t:for(let o=0;o<t.maxArgs;o++){let a=r.run({max:t.max-n});if(n+=a.steps,!a.final)break;if(Jt(a.expr)){if(r=a.expr,!r.any(l=>!(l instanceof v||l instanceof x)))return dt(s,r,{steps:n});let u=r.unroll(),p=!1,w=!1,d=[];for(let l=1;l<u.length;l++){let m=u[l]._infer({maxArgs:t.maxArgs-e,max:t.max-n},e+o);if(n+=m.steps,!m.expr)break t;m.discard&&(p=!0),m.duplicate&&(w=!0),d.push(m.expr)}return dt(s,u[0].apply(...d),{discard:p,duplicate:w,steps:n})}let h=Yt(e+o);s.push(h),r=a.expr.apply(h)}return{normal:!1,proper:!1,steps:n}}unroll(){return[this]}*toLambda(t={}){let e=this.traverse(r=>{if(r instanceof v||r instanceof x||r instanceof b||r instanceof A)return null;let o=r.infer({max:t.max,maxArgs:t.maxArgs});if(!o.normal)throw new Error("Failed to infer an equivalent lambda term for "+r);return o.expr})??this,s=new Set,n=0;for(;e;){let r=e.traverse({order:"LI"},o=>{if(s.has(o))return null;if(o instanceof x&&o.fun instanceof b){let a=o.infer({max:t.max,maxArgs:t.maxArgs});return n+=a.steps,a.normal?f.stop(a.expr):(s.add(o),null)}});yield{expr:e,steps:n},e=r}}*toSKI(t={}){let e=this.traverse(n=>n instanceof v||n instanceof x||n instanceof b||n instanceof A?null:n.infer().expr)??this,s=0;for(;e;){let n=e.traverse({order:"LI"},r=>{if(!(r instanceof b)||r.impl instanceof b)return null;if(r.impl===r.arg)return f.stop(T.I);if(!r.impl.any(o=>o===r.arg))return f.stop(T.K.apply(r.impl));if(!(r.impl instanceof x))throw new Error("toSKI: assert failed: lambda body is of unexpected type "+r.impl.constructor.name);return r.impl.arg===r.arg&&!r.impl.fun.any(o=>o===r.arg)?f.stop(r.impl.fun):f.stop(T.S.apply(new b(r.arg,r.impl.fun),new b(r.arg,r.impl.arg)))});yield{expr:e,steps:s,final:!n},s++,e=n}}subst(t,e){return this===t?e:null}invoke(t){return null}step(){return{expr:this,steps:0,changed:!1}}run(t={},...e){t instanceof i&&(e.unshift(t),t={});let s=e?this.apply(...e):this,n=t.steps??0,r=Math.max(t.max??W.max,1)+n,o=!1;for(;n<r;){let a=s.step();if(!a.changed){o=!0;break}n+=a.steps,s=a.expr}if(t.throw&&!o)throw new Error("Failed to compute expression in "+r+" steps");return{final:o,steps:n,expr:s}}*walk(t={}){let e=t.max??1/0,s=0,n=this,r=!1;for(;s<e;){let o=n.step();if(o.changed||(r=!0),yield{expr:n,steps:s,final:r},r)break;s+=o.steps,n=o.expr}}equals(t){return!this.diff(t)}diff(t,e=!1){return this===t?null:t instanceof A?t.impl.diff(this,!e):e?"["+t+" != "+this+"]":"["+this+" != "+t+"]"}expect(t,e=""){if(e=e?e+": ":"",!(t instanceof i))throw new Error(e+"Expected a combinator but found "+(t?.constructor?.name??typeof t));let s=this.diff(t);if(!s)return;let n=new Error(e+s);throw n.expected=this.diag(),n.actual=t.diag(),n}toString(){return this.format()}_braced(t){return!1}_unspaced(t){return this._braced(!0)}format(t={}){let e=t.html?{brackets:["(",")"],space:" ",var:["<var>","</var>"],lambda:["","->",""],around:["",""],redex:["",""]}:{brackets:["(",")"],space:" ",var:["",""],lambda:["","->",""],around:["",""],redex:["",""]};return this._format({terse:t.terse??!0,brackets:t.brackets??e.brackets,space:t.space??e.space,var:t.var??e.var,lambda:t.lambda??e.lambda,around:t.around??e.around,redex:t.redex??e.redex,inventory:t.inventory,html:t.html??!1},0)}_format(t,e){throw new Error("No _format() method defined in class "+this.constructor.name)}diag(){let t=(s,n)=>s instanceof x?[n+"App:",...s.unroll().flatMap(r=>t(r,n+" "))]:s instanceof b?[`${n}Lambda (${s.arg}[${s.arg.id}]):`,...t(s.impl,n+" ")]:s instanceof A?[`${n}Alias (${s.name}): \\`,...t(s.impl,n)]:s instanceof v?[`${n}FreeVar: ${s.name}[${s.id}]`]:[`${n}${s.constructor.name}: ${s}`];return t(this,"").join(`
|
|
2
|
+
`)}toJSON(){return this.format()}},x=class i extends g{constructor(t,e){super(),this.arg=e,this.fun=t}weight(){return this.fun.weight()+this.arg.weight()}_traverse_descend(t,e){let[s,n]=y(this.fun._traverse_redo(t,e));if(n===f.stop)return f.stop(s?s.apply(this.arg):null);let[r,o]=y(this.arg._traverse_redo(t,e)),a=s||r?(s??this.fun).apply(r??this.arg):null;return o===f.stop?f.stop(a):a}any(t){return t(this)||this.fun.any(t)||this.arg.any(t)}_fold(t,e){let[s=t,n="descend"]=y(e(t,this));if(n===f.prune)return s;if(n===f.stop)return f.stop(s);let[r=s,o="descend"]=y(this.fun._fold(s,e));if(o===f.stop)return f.stop(r);let[a=r,h="descend"]=y(this.arg._fold(r,e));return h===f.stop?f.stop(a):a}subst(t,e){let s=this.fun.subst(t,e),n=this.arg.subst(t,e);return s||n?(s??this.fun).apply(n??this.arg):null}step(){if(!this.final){let t=this.fun.invoke(this.arg);if(t instanceof g)return{expr:t,steps:1,changed:!0};typeof t=="function"&&(this.invoke=t);let e=this.fun.step();if(e.changed)return{expr:e.expr.apply(this.arg),steps:e.steps,changed:!0};let s=this.arg.step();if(s.changed)return{expr:this.fun.apply(s.expr),steps:s.steps,changed:!0};this.final=!0}return{expr:this,steps:0,changed:!1}}invoke(t){let e=this.fun.invoke(this.arg);return e instanceof g?e.apply(t):typeof e=="function"?(this.invoke=e,e(t)):(this.invoke=s=>null,null)}unroll(){return[...this.fun.unroll(),this.arg]}diff(t,e=!1){if(!(t instanceof i))return super.diff(t,e);let s=this.fun.diff(t.fun,e);if(s)return s+"(...)";let n=this.arg.diff(t.arg,e);return n?this.fun+"("+n+")":null}_braced(t){return!t}_format(t,e){let s=this.fun._format(t,e+1),n=this.arg._format(t,0),r=e?["",""]:t.around;return t.terse&&!this.arg._braced(!1)?r[0]+s+(this.fun._unspaced(this.arg)?"":t.space)+n+r[1]:r[0]+s+t.brackets[0]+n+t.brackets[1]+r[1]}_unspaced(t){return this.arg._braced(!1)?!0:this.arg._unspaced(t)}},E=class i extends g{constructor(t){if(super(),typeof t!="string"||t.length===0)throw new Error("Attempt to create a named term with improper name");this.name=t}_unspaced(t){return!!(t instanceof i&&(this.name.match(/^[A-Z+]$/)&&t.name.match(/^[a-z+]/i)||this.name.match(/^[a-z+]/i)&&t.name.match(/^[A-Z+]$/)))}_format(t,e){let s=t.html?this.fancyName??this.name:this.name;return this.arity>0&&this.arity<=e?t.redex[0]+s+t.redex[1]:s}},Wt=0,v=class i extends E{constructor(t,e){super(t),this.id=++Wt,this.scope=e===void 0?this:e}weight(){return 0}diff(t,e=!1){if(!(t instanceof i))return super.diff(t,e);if(this.name===t.name&&this.scope===t.scope)return null;let s=this.name+"["+this.id+"]",n=t.name+"["+t.id+"]";return e?"["+n+" != "+s+"]":"["+s+" != "+n+"]"}subst(t,e){return t instanceof i&&t.name===this.name&&t.scope===this.scope?e:null}_format(t,e){let s=t.html?this.fancyName??this.name:this.name;return t.var[0]+s+t.var[1]}};v.global=["global"];var K=class extends E{constructor(t,e,s={}){super(t),this.invoke=e,this._setup({canonize:!0,...s})}},b=class i extends g{constructor(t,e){if(Array.isArray(t)){if(t.length===0)throw new Error("empty argument list in lambda constructor");let[n,...r]=t,o=new Set([n.name]);for(;r.length>0;){let a=r.pop();if(o.has(a.name))throw new Error("Duplicate free var name "+a+" in lambda expression");o.add(a.name),e=new i(a,e)}t=n}super();let s=new v(t.name,this);this.arg=s,this.impl=e.subst(t,s)??e,this.arity=1}weight(){return this.impl.weight()+1}invoke(t){return this.impl.subst(this.arg,t)??this.impl}_traverse_descend(t,e){let[s,n]=y(this.impl._traverse_redo(t,e)),r=s?new i(this.arg,s):null;return n===f.stop?f.stop(r):r}any(t){return t(this)||this.impl.any(t)}_fold(t,e){let[s=t,n="descend"]=y(e(t,this));if(n===f.prune)return s;if(n===f.stop)return f.stop(s);let[r,o]=y(this.impl._fold(s,e));return o===f.stop?f.stop(r):r??s}subst(t,e){if(t===this.arg)return null;let s=this.impl.subst(t,e);return s?new i(this.arg,s):null}diff(t,e=!1){if(!(t instanceof i))return super.diff(t,e);let s=new v("t"),n=this.invoke(s).diff(t.invoke(s),e);return n?"(t->"+n+")":null}_format(t,e){return(e>0?t.brackets[0]:"")+t.lambda[0]+this.arg._format(t,0)+t.lambda[1]+this.impl._format(t,0)+t.lambda[2]+(e>0?t.brackets[1]:"")}_braced(t){return!0}},j=class i extends g{constructor(t){if(t=Number.parseInt(t),!(t>=0))throw new Error("Church number must be a non-negative integer");super(),this.invoke=e=>s=>{let n=s;for(let r=t;r-- >0;)n=e.apply(n);return n},this.n=t,this.arity=2}diff(t,e=!1){return t instanceof i?this.n===t.n?null:e?"["+t.n+" != "+this.n+"]":"["+this.n+" != "+t.n+"]":super.diff(t,e)}_unspaced(t){return!1}_format(t,e){return e>=2?t.redex[0]+this.n+t.redex[1]:this.n+""}};function mt(i,t){return e=>t<=1?i.apply(e):mt(i.apply(e),t-1)}var A=class extends E{constructor(t,e,s={}){if(super(t),!(e instanceof g))throw new Error("Attempt to create an alias for a non-expression: "+e);this.impl=e,this._setup(s),this.terminal=s.terminal??this.props?.proper,this.invoke=mt(e,this.arity??0)}weight(){return this.terminal?1:this.impl.weight()}_traverse_descend(t,e){return this.impl._traverse_redo(t,e)}any(t){return t(this)||this.impl.any(t)}_fold(t,e){let[s=t,n]=y(e(t,this));if(n===f.prune)return s;if(n===f.stop)return f.stop(s);let[r,o]=y(this.impl._fold(s,e));return o===f.stop?f.stop(r):r??s}subst(t,e){return this===t?e:this.impl.subst(t,e)}step(){return this.arity>0?{expr:this,steps:0,changed:!1}:{expr:this.impl,steps:0,changed:!0}}diff(t,e=!1){return this===t?null:t.diff(this.impl,!e)}_braced(t){return this.outdated?this.impl._braced(t):!1}_format(t,e){return(t.inventory?t.inventory[this.name]!==this:this.outdated)?this.impl._format(t,e):super._format(t,e)}};function L(i,t,e){T[i]=new K(i,t,e)}L("I",i=>i);L("K",i=>t=>i);L("S",i=>t=>e=>i.apply(e,t.apply(e)));L("B",i=>t=>e=>i.apply(t.apply(e)));L("C",i=>t=>e=>i.apply(e).apply(t));L("W",i=>t=>i.apply(t).apply(t));L("+",i=>i instanceof j?new j(i.n+1):t=>e=>t.apply(i.apply(t,e)),{note:"Increase a Church numeral argument by 1, otherwise n => f => x => f(n f x)"});function Jt(i){for(;i instanceof x;)i=i.fun;return i instanceof v}function dt(i,t,e={}){let s=new Array(i.length).fill(0),n=!0;t.traverse(a=>{if(a instanceof v){let h=i.findIndex(u=>u.name===a.name);if(h>=0){s[h]++;return}}a instanceof x||(n=!1)});let r=new Set,o=new Set;for(let a=0;a<i.length;a++)s[a]===0?r.add(a):s[a]>1&&o.add(a);return{normal:!0,steps:e.steps,expr:i.length?new b(i,t):t,arity:i.length,...r.size?{skip:r}:{},...o.size?{dup:o}:{},duplicate:!!o.size||e.duplicate||!1,discard:!!r.size||e.discard||!1,proper:n}}function Yt(i){return new v("abcdefgh"[i]??"x"+i)}function Gt(i,t){if(i instanceof g&&(i=[i]),t)i||(i=Object.keys(t).sort().map(r=>t[r]));else{if(!i)return[];if(!t){t={};for(let r of i)if(r instanceof E){if(t[r.name])throw new Error("duplicate name "+r);t[r.name]=r}}}let e=[],s=new Set,n=r=>{s.has(r)||(r.fold(null,(o,a)=>{if(a!==r&&a instanceof E&&t[a.name]===a)return n(a),g.control.prune(null)}),e.push(r),s.add(r))};for(let r of i)n(r);return{list:e,env:t}}g.native=T;g.control=f;g.extras={toposort:Gt};wt.exports={Expr:g,App:x,Named:E,FreeVar:v,Lambda:b,Native:K,Alias:A,Church:j}});var X=k((Ie,yt)=>{"use strict";var{Tokenizer:Xt,restrict:Y}=Z(),vt=J(),{Expr:C,Named:Le,Native:te,Alias:_,FreeVar:I,Lambda:ee,Church:xt}=vt,{native:M}=C,$=class extends C{apply(...t){return t.length?t.shift().apply(...t):this}postParse(){throw new Error("Attempt to use empty expression () as a term")}},G=class i extends ${constructor(t,e={}){if(super(),this.impl=new $,t instanceof I)this.terms=[t];else if(t instanceof i){if(!(t.impl instanceof I))throw new Error("Expected FreeVar->...->FreeVar->Expr");this.terms=[...t.terms,t.impl]}else throw new Error("Expected FreeVar or PartialLambda")}apply(t,...e){if(t===null||e.length!==0)throw new Error("bad syntax in partial lambda expr");return this.impl=this.impl.apply(t),this}postParse(){return new ee(this.terms,this.impl)}};function gt(i){return i.postParse?i.postParse():i}var se=new Xt("[()]","[A-Z]","[a-z_][a-z_0-9]*","\\b[0-9]+\\b","->","\\+"),S=class{constructor(t={}){if(this.annotate=t.annotate??!1,this.known={...M},this.hasNumbers=!0,this.hasLambdas=!0,this.allow=new Set(Object.keys(this.known)),Array.isArray(t.terms))this.bulkAdd(t.terms);else if(t.terms)for(let e in t.terms)t.terms[e].match(/^Native:/)||this.add(e,t.terms[e]);this.hasNumbers=t.numbers??!0,this.hasLambdas=t.lambdas??!0,t.allow&&this.restrict(t.allow)}add(t,e,s){return t=this._named(t,e),typeof s=="string"&&(s={note:s,canonize:!1}),t._setup({canonize:this.annotate,...s}),this.known[t.name]&&(this.known[t.name].outdated=!0),this.known[t.name]=t,this.allow.add(t.name),this}_named(t,e){if(t instanceof _)return new _(t.name,t.impl,{canonize:!0});if(typeof t!="string")throw new Error("add(): term must be an Alias or a string");if(e===void 0)throw new Error("add(): impl must be provided when term is a string");if(typeof e=="string")return new _(t,this.parse(e),{canonize:!0});if(e instanceof C)return new _(t,e,{canonize:!0});if(typeof e=="function")return new te(t,e);throw new Error("add(): impl must be an Expr, a string, or a function with a signature Expr => ... => Expr")}maybeAdd(t,e){return this.known[t]?this.allow.add(t):this.add(t,e),this}bulkAdd(t){for(let e of t){let s=e.match(/^([A-Z]|[a-z][a-z_0-9]*)\s*=\s*(.*)$/s);if(!s)throw new Error("bulkAdd: invalid declaration: "+e);s[2]===""?this.remove(s[1]):this.add(s[1],this.parse(s[2]))}return this}restrict(t){return this.allow=Y(this.allow,t),this}showRestrict(t="+"){let e=[],s=!0;for(let n of[...Y(this.allow,t)].sort()){let r=n.match(/^[A-Z]$/);e.length&&!(s&&r)&&e.push(" "),e.push(n),s=r}return e.join("")}remove(t){return this.known[t].outdated=!0,delete this.known[t],this.allow.delete(t),this}getTerms(){let t={};for(let e of Object.keys(this.known))this.allow.has(e)&&(t[e]=this.known[e]);return t}declare(){let t=this.getTerms();for(let a in t)t[a]instanceof _||delete t[a];let e={},s=1;for(let a in M){if(!(t[a]instanceof _))continue;for(;"tmp"+s in t;)s++;let h=new _("tmp"+s,t[a]);e[h]=t[a],t[h]=h,delete t[a]}let n=C.extras.toposort(void 0,t).list,r=new Map;if(Object.keys(e).length){let a=h=>h.traverse(u=>{if(!(u instanceof _))return null;let p=r.get(u);return p||new _(u.name,a(u.impl))})??h;for(let h=0;h<n.length;h++)n[h]=a(n[h],r),r.set(e[n[h].name],n[h]),t[n[h].name]=n[h],console.log(`list[${h}] = ${n[h].name}=${n[h].impl};`);console.log("detour:",r)}let o=n.map(a=>e[a]?a.name+"="+e[a].name+"="+a.impl.format({inventory:t}):a.name+"="+a.impl.format({inventory:t}));for(let[a,h]of r)o.push(a+"="+h,h+"=");return o}parse(t,e={}){if(typeof t!="string")throw new Error("parse: source must be a string, got "+typeof t);let s=t.replace(/\/\/[^\n]*$/gm," ").replace(/\/\*.*?\*\//gs," ").trim().split(/\s*;[\s;]*/).filter(o=>o.match(/\S/)),n={...e.env},r=new $;for(let o of s){r instanceof _&&(r.outdated=!0);let a=o.match(/^([A-Z]|[a-z][a-z_0-9]*)\s*=(.*)$/s);if(a&&a[2]===""?r=new I(a[1],e.scope??I.global):r=this.parseLine(o,n,e),a){if(n[a[1]]!==void 0)throw new Error("Attempt to redefine a known term: "+a[1]);n[a[1]]=r}}return r.context={env:{...this.getTerms(),...n},scope:e.scope,src:t,parser:this},r}parseLine(t,e={},s={}){let n=t.match(/^\s*([A-Z]|[a-z][a-z_0-9]*)\s*=\s*(.*)$/s);if(n)return new _(n[1],this.parseLine(n[2],e,s));let r={numbers:s.numbers??this.hasNumbers,lambdas:s.lambdas??this.hasLambdas,allow:Y(this.allow,s.allow)};r.numbers?r.allow.add("+"):r.allow.delete("+");let o=se.split(t),a=new $,h=[a],u=s.scope||I.global;for(let p of o)if(p==="(")h.push(a);else if(p===")"){if(h.length<2)throw new Error("unbalanced input: extra closing parenthesis"+t);let w=gt(h.pop()),d=h.pop();h.push(d.apply(w))}else if(p==="->"){if(!r.lambdas)throw new Error("Lambdas not supported, allow them explicitly");h.push(new G(h.pop(),e))}else if(p.match(/^[0-9]+$/)){if(!r.numbers)throw new Error("Church numbers not supported, allow them explicitly");let w=h.pop();h.push(w.apply(new xt(p)))}else{let w=h.pop();if(!e[p]&&this.known[p]&&!r.allow.has(p))throw new Error("Term '"+p+"' is not in the restricted set "+[...r.allow].sort().join(" "));let d=e[p]??this.known[p]??(e[p]=new I(p,u));h.push(w.apply(d))}if(h.length!==1)throw new Error("unbalanced input: missing "+(h.length-1)+" closing parenthesis:"+t);return gt(h.pop())}toJSON(){return{version:"1.1.1",allow:this.showRestrict("+"),numbers:this.hasNumbers,lambdas:this.hasLambdas,annotate:this.annotate,terms:this.declare()}}};S.vars=function(i={}){let t={};return new Proxy({},{get:(e,s)=>(s in t||(t[s]=new I(s,i)),t[s])})};S.church=i=>new xt(i);for(let i in M)S[i]=M[i];S.classes=vt;S.native=M;S.control=C.control;yt.exports={SKI:S}});var rt=k((Fe,St)=>{var{SKI:q}=X(),{Expr:ze,FreeVar:ne,Alias:bt,Lambda:$e}=q.classes,z=class{constructor(t){let{input:e,cases:s,allow:n,numbers:r,lambdas:o,engine:a,engineFull:h,...u}=t,p=t.env??t.vars;this.engine=a??new q,this.engineFull=h??new q,this.restrict={allow:n,numbers:r??!1,lambdas:o??!1},this.env={};let w={};for(let d of p??[]){let l=this.engineFull.parse(d,{env:w,scope:this});if(l instanceof q.classes.Alias)this.env[l.name]=new bt(l.name,l.impl,{terminal:!0,canonize:!1});else if(l instanceof q.classes.FreeVar)this.env[l.name]=l;else throw new Error("Unsupported given variable type: "+d)}this.input=[];for(let d of Array.isArray(e)?e:[e])this.addInput(d);if(!this.input.length)throw new Error("Quest needs at least one input placeholder");this.envFull={...this.env,...w};for(let d of this.input){if(d.name in this.envFull)throw new Error("input placeholder name is duplicated or clashes with env: "+d.name);this.envFull[d.name]=d.placeholder}this.cases=[],this.name=u.name??u.title,u.intro=kt(u.intro??u.descr),this.intro=u.intro,this.id=u.id,this.meta=u;for(let d of s??[])this.add(...d)}allowed(){let t=this.restrict.allow??"",e=Object.keys(this.env).sort();return t?this.engine.showRestrict(t+"+"+e.join(" ")):e.map(s=>"+"+s).join(" ")}addInput(t){if(typeof t!="object"&&(t={name:t}),typeof t.name!="string")throw new Error("quest 'input' field must be a string or a {name: string, ...} object");t.placeholder=new q.classes.FreeVar(t.name),this.input.push(t)}add(t,...e){typeof t=="string"?(e.unshift(t),t={}):t={...t},t.engine=t.engine??this.engineFull,t.env=t.env??this.envFull;let s=this.input.map(n=>n.placeholder);return this.cases.push(t.caps?new et(s,t,e):new tt(s,t,e)),this}prepare(...t){if(t.length!==this.input.length)throw new Error("Solutions provided "+t.length+" terms where "+this.input.length+" are expected");let e=0,s=[],n={...this.env};for(let r=0;r<t.length;r++){let o=this.input[r],a=this.engine.parse(t[r],{env:n,allow:o.allow??this.restrict.allow,numbers:o.numbers??this.restrict.numbers,lambdas:o.lambdas??this.restrict.lambdas}),h={...this.engine.getTerms(),...n};e+=a.fold(0,(p,w)=>{if(w instanceof q.classes.Named&&h[w.name]===w)return q.control.prune(p+1)});let u=a instanceof ne?a:new bt(o.fancy??o.name,a,{terminal:!0,canonize:!1});n[o.name]=u,s.push(u)}return{prepared:s,weight:e}}check(...t){try{let{prepared:e,weight:s}=this.prepare(...t),n=this.cases.map(a=>a.check(...e)),r=n.reduce((a,h)=>a&&h.pass,!0),o=n.reduce((a,h)=>a+h.steps,0);return{expr:e[0],input:e,pass:r,steps:o,details:n,weight:s}}catch(e){return{pass:!1,details:[],exception:e,steps:0,input:t}}}verify(t){let e=this.verifyMeta(t);if(t.solutions){let s=this.verifySolutions(t.solutions);s&&(e.solutions=s)}return t.seen&&(this.id||(e.seen="No id in quest "+(this.name??"(unnamed)")),t.seen.has(this.id)&&(e.seen="Duplicate quest id "+this.id),t.seen.add(this.id)),Object.keys(e).length?e:null}verifySolutions(t){if(typeof t=="object"&&!Array.isArray(t?.accepted)&&!Array.isArray(t?.rejected)&&(!this.id||!t[this.id]))return null;let{accepted:e=[],rejected:s=[]}=t[this.id]??t,n={shouldPass:[],shouldFail:[]};for(let r of e){let o=this.check(...r);o.pass||n.shouldPass.push({input:r,result:o})}for(let r of s){let o=this.check(...r);o.pass&&n.shouldFail.push({input:r,result:o})}return n.shouldFail.length+n.shouldPass.length?n:null}verifyMeta(t={}){let e={};for(let s of["name","intro"]){let n=_t(this[s]);n&&(e[s]=n)}if(t.date){let s=new Date(this.meta.created_at);isNaN(s)?e.date="invalid date format: "+this.meta.created_at:(s<new Date("2024-07-15")||s>new Date)&&(e.date="date out of range: "+this.meta.created_at)}return e}show(){return[...this.cases]}},N=class{constructor(t,e){this.max=e.max??1e3,this.note=e.note,this.env={...e.env??{}},this.input=t,this.engine=e.engine}parse(t){return new st(this.engine.parse(t,{env:this.env,scope:this}),this.input)}check(...t){throw new Error("not implemented")}},tt=class extends N{constructor(t,e,s){if(s.length!==2)throw new Error("Case accepts exactly 2 strings");super(t,e),[this.e1,this.e2]=s.map(n=>this.parse(n))}check(...t){let e=this.e1.apply(t),s=e.run({max:this.max}),r=this.e2.apply(t).run({max:this.max}),o=null;return!s.final||!r.final?o="failed to reach normal form in "+this.max+" steps":o=s.expr.diff(r.expr),{pass:!o,reason:o,steps:s.steps,start:e,found:s.expr,expected:r.expr,note:this.note,args:t,case:this}}},re={normal:!0,proper:!0,discard:!0,duplicate:!0,linear:!0,affine:!0,arity:!0},et=class extends N{constructor(t,e,s){if(super(t,e),s.length>1)throw new Error("PropertyCase accepts exactly 1 string");if(!e.caps||typeof e.caps!="object"||!Object.keys(e.caps).length)throw new Error("PropertyCase requires a caps object with at least one capability");let n=Object.keys(e.caps).filter(r=>!re[r]);if(n.length)throw new Error("PropertyCase: don't know how to test these capabilities: "+n.join(", "));this.expr=this.parse(s[0]),this.caps=e.caps,this.caps.linear&&(delete this.caps.linear,this.caps.duplicate=!1,this.caps.discard=!1,this.caps.normal=!0),this.caps.affine&&(delete this.caps.affine,this.caps.normal=!0,this.caps.duplicate=!1)}check(...t){let e=this.expr.apply(t),s=e.run({max:this.max}),n=s.expr.infer({max:this.max}),r=[];for(let o in this.caps)n[o]!==this.caps[o]&&r.push("expected property "+o+" to be "+this.caps[o]+", found "+n[o]);return{pass:!r.length,reason:r?r.join(`
|
|
3
|
+
`):null,steps:s.steps,start:e,found:s.expr,case:this,note:this.note,args:t}}},st=class{constructor(t,e){this.expr=t,this.env=e}apply(t){if(t.length!==this.env.length)throw new Error("Subst: expected "+this.env.length+" terms, got "+t.length);let e=this.expr;for(let s=0;s<this.env.length;s++)e=e.subst(this.env[s],t[s])??e;return e}},nt=class{constructor(t){this.name=t.name,this.intro=kt(t.intro),this.id=t.id,t.content&&(this.content=t.content.map(e=>e instanceof z?e:new z(e)))}verify(t){let e={},s=ie(this.id,t.seen);s&&(e[this.id]=s);for(let n of["name","intro"]){let r=_t(this[n]);r&&(e[n]=r)}return e.content=this.content.map(n=>n.verify(t)),e}};function kt(i){return i===void 0||typeof i=="string"?i:Array.isArray(i)?i.join(" "):""+i}function ie(i,t){if(i===void 0)return"missing";if(typeof i!="string"&&typeof i!="number")return"is a "+typeof i;if(t){if(t.has(i))return"duplicate id "+i;t.add(i)}}function _t(i){if(i===void 0)return"missing";if(typeof i!="string")return"not a string but "+typeof i;let t=[],e=/<\/?([a-z]+)(?:\s[^>]*)?>/gi,s;for(;(s=e.exec(i))!==null;){let[n,r]=s;if(n.startsWith("</")){if(t.length===0||t.pop()!==r)return`Unmatched closing tag: </${r}>`}else t.push(r)}return t.length>0?`Unclosed tags: ${t.join(", ")}`:null}z.Group=nt;z.Case=N;St.exports={Quest:z}});var It=k((Te,Lt)=>{"use strict";var{Expr:Et,Alias:ae,FreeVar:oe}=J(),{Quest:At}=rt();function he(i,t,e){let{depth:s=16,infer:n=!0,progressInterval:r=1e3}=t,o=n&&!t.noskip,a=[[]],h=0,u=0,p={},w=l=>{h++;let m=n?l.infer({max:t.max,maxArgs:t.maxArgs}):null;if(o&&m.expr){if(p[m.expr])return{res:-1};p[m.expr]=!0}return u++,{res:e(l,m),props:m}};for(let l of i){let{res:m}=w(l);if(m>0)return{expr:l,total:h,probed:u,gen:1};if(m<0)continue;a[0].push(l)}let d;for(let l=1;l<s;l++){t.progress&&(t.progress({gen:l,total:h,probed:u,step:!0}),d=h);for(let m=0;m<l;m++)for(let ut of a[l-m-1]||[])for(let Rt of a[m]||[]){if(h>=t.tries)return{total:h,probed:u,gen:l,...t.retain?{cache:a}:{}};t.progress&&h-d>=r&&(t.progress({gen:l,total:h,probed:u,step:!1}),d=h);let B=ut.apply(Rt),{res:ft,props:Q}=w(B);if(ft>0)return{expr:B,total:h,probed:u,gen:l,...t.retain?{cache:a}:{}};if(ft<0)continue;let D=n?(Q.expr?0:3)+(Q.dup?1:0)+(Q.proper?0:1):0;a[l+D]||(a[l+D]=[]),a[l+D].push(B)}}return{total:h,probed:u,gen:s,...t.retain?{cache:a}:{}}}function it(i,t={}){if(i instanceof Et)return i.format(t);if(i instanceof At)return"Quest("+i.name+")";if(i instanceof At.Case)return"Quest.Case";if(Array.isArray(i))return i.map(it);if(typeof i!="object"||i===null||i.constructor!==Object)return i;let e={};for(let s in i)e[s]=it(i[s]);return e}function ce(i,t){let e=Et.extras.toposort([i],t);return e.list.map(s=>s instanceof ae?s.name+"="+s.impl.format({inventory:e.env}):s instanceof oe?s.name+"=":s.format({inventory:e.env})).join("; ")}function qt(i,t){let[e,...s]=i.unroll();return t(e,s.map(n=>qt(n,t)))}Lt.exports={search:he,deepFormat:it,declare:ce,foldr:qt}});var Ft=k((je,$t)=>{var{SKI:F}=X(),{Quest:zt}=rt(),le=It();F.Quest=zt;F.extras={...le,...F.classes.Expr.extras};typeof process=="object"&&process.env.SKI_REPL&&typeof global<"u"&&(global.SKI=F,console.log("SKI_REPL activated, try `new SKI();`"));typeof window<"u"&&(window.SKI=F);$t.exports={SKI:F,Quest:zt}});var jt=k((Ce,Tt)=>{var at=class{constructor(t){this.ns=t+":"}save(t,e){window.localStorage.setItem(this.ns+t,JSON.stringify(e))}load(t){return JSON.parse(window.localStorage.getItem(this.ns+t))}scan(){let t=window.localStorage,e=[];for(let s=0;s<t.length;s++){let n=t.key(s);n.startsWith(this.ns)&&e.push(n.substring(this.ns.length))}return e}delete(t){window.localStorage.removeItem(this.ns+t)}};Tt.exports={Store:at}});var ot=k((Me,Mt)=>{"use strict";function ue(...i){let t={};for(let e of i){let s=e.replace(/[A-Z]/g,n=>"-"+n.toLowerCase());if(t[e]=document.getElementById(s),!t[e])throw new Error(`View element not found: ${s}`)}return t}function fe(i,t,e={},s=null){let n=document.createElement(t);return e.class&&n.classList.add(...e.class),e.content!==void 0&&(n.innerHTML=""+e.content),e.hidden&&(n.hidden=!0),e.color&&(n.style.color=e.color),i&&i.appendChild(n),s&&s(n),n}function Ct(i,t){t(i);for(let e of i.childNodes)Ct(e,t)}function pe(i){typeof i!="string"&&(i=""+i);let t={"<":"<",">":">","&":"&"};return i.replace(/[<>&]/g,e=>t[e])}function de(i){let t={"(":"%28",")":"%29"};return encodeURIComponent(i).replace(/[()]/g,e=>t[e]).replace(/%20/g,"+")}function me(i){return decodeURIComponent((""+i).replace(/\+/g," "))}Mt.exports={append:fe,decode:me,encode:de,grabView:ue,sanitize:pe,traverse:Ct}});var Pt=k((Ne,Nt)=>{"use strict";var{append:ht}=ot(),ct=class{constructor(t={}){this.options=t,this.height=t.height??5,this.running=!1,this.delay=t.delay??0,this.maxSteps=t.max??1/0,this.onStart=t.onStart??(()=>{}),this.onStop=t.onStop??(()=>{}),this.onStep=t.onStep??(()=>{}),this.engine=t.engine,this.format=t.format??{html:!0},this.generator=t.generator??(e=>e.walk()),this.set(t.expr),this.view={},this.view.parent=t.parent,this.view.scroll=t.scroll??t.parent,this.view.main=ht(t.parent,"ol",{class:["ski-eval-box"]})}set(t){if(typeof t=="string")this.src=t,this.expr=this.engine.parse(t);else if(Array.isArray(t)&&t.length===2)this.src=t[0],this.expr=t[1];else if(!t)this.expr=null,this.src=null;else if(typeof t=="object"&&typeof t.format=="function")this.expr=t,this.src=t.format();else throw new Error("EvalBox.set() expects a string, Expr, or [string, Expr]");return this}start(t){this.running&&this.stop();try{t!==void 0&&this.set(t),this.seq=this.generator(this.expr)}catch(e){return console.error(e),this.stop(e.message)}return this.view.main.innerHTML="",this.onStart(),this.running=!0,this.tick(),this}stop(t){this.running=!1,this.timer&&(clearTimeout(this.timer),this.timer=null),t&&this.print(t,{class:["ski-eval-error"],line:""}),this.onStop()}resume(){this.running||!this.seq||(this.running=!0,this.onStart(),this.tick())}tick(){if(!this.running)return;let{value:t,done:e}=this.seq.next();if(t&&this.print(t.expr.format(this.format),{line:t.steps}),this.onStep(t,e||t.final),e||t.final)return this.view.last&&this.view.last.classList.add("ski-eval-success"),this.seq=null,this.stop();if(t.steps>=this.maxSteps)return this.stop("Max steps reached: "+this.maxSteps);this.timer=setTimeout(()=>this.tick(),this.delay)}remove(){this.view.parent&&(this.view.parent.removeChild(this.view.main),this.view.parent=null)}clear(){this.stop(),this.view.main.innerHTML=""}setHeight(t){this.height=t}print(t,e={}){let s=ht(this.view.main,"li",e);if(e.line!==0&&!e.line?s.style["list-style"]="none":(this.view.main.style["padding-left"]=(""+e.line).length+2.5+"ch",s.value=e.line),this.view.last=s,e.raw)s.innerHTML=t;else for(ht(s,"span",{class:e.class??["ski-eval-line"],color:e.color,content:t});this.view.main.children.length>this.height;)this.view.main.removeChild(this.view.main.firstChild);return this.view.scroll&&(this.view.scroll.scrollTop=s.offsetTop),s}};Nt.exports={EvalBox:ct}});var Kt=k((Pe,Ht)=>{"use strict";var{SKI:P}=Ft(),{Store:we}=jt(),{EvalBox:ge}=Pt(),{append:c}=ot(),lt=class{constructor(t){if(this.view={},this.root=t.baseUrl??".",!t.store&&!t.storePrefix)throw new Error("No storePrefix provided");this.store=t.store??new we(t.storePrefix),this.engine=t.engine??new P(this.store.load("engine")??{annotate:!0,allow:"SKI"}),t.inventoryBox&&(this.view.inventory=t.inventoryBox,this.showKnown()),this.view.content=t.contentBox,t.indexBox&&(this.view.index=c(t.indexBox,"div",{class:["ski-quest-nav"]})),this._onSolved=t.onSolved,this._onFailed=t.onFailed,this._onUnlock=t.onUnlock,this.chapters=[]}loadFromIndex(t,e,s){fetch(this.mkLink(t)).then(n=>n.json()).then(n=>this.loadChapters(n)).then(n=>{if(s&&s(n),e){let r=document.getElementById(e);r&&r.scrollIntoView()}})}async loadChapters(t){let e=0;this.chapters=[];let s=[];for(let n of t){let r=new V({number:++e,link:this.mkLink(n),engine:this.engine,store:this.store,onUnlock:o=>this.onUnlock(o),onSolved:o=>this._onSolved(o),onFailed:o=>this._onFailed(o)});this.chapters.push(r),r.attach(this.view.content,{placeholder:"loading chapter"+r.number+"..."}),this.view.index&&r.addLink(this.view.index),s.push(r.fetch().then(o=>{o.draw()}))}return Promise.all(s).then(()=>this)}mkLink(t){return t.match(/^\w+:\/\//)||t.match(/^[/.]/)?t:this.root+"/"+t}onUnlock(t){this.engine.maybeAdd(t.name,t.impl),this.store&&this.store.save("engine",this.engine),this.showKnown(),this._onUnlock&&this._onUnlock(t)}showKnown(){if(!this.view.inventory)return;this.view.inventory.innerHTML="";let t=c(this.view.inventory,"ul",{class:["ski-quest-inventory"]}),e=this.engine.getTerms();for(let s of Object.keys(e).sort().map(n=>[n,e[n]])){let n=c(t,"li",{},r=>{r.dataset.skiTerm=s[0]});c(n,"span",{content:s[0],class:["ski-quest-term-name"]}),c(n,"span",{content:": "}),c(n,"span",{content:ye(s[1]),class:["ski-quest-term-def"]})}}demolish(){for(let t of this.store.scan())this.store.delete(t)}},R=class{constructor(t,e){let s=e.engine??e.chapter?.engine;if(!s)throw new Error("QuestBox requires an engine: SKI in either options or chapter");let n=e.store??e.chapter?.store;if(!n)throw new Error("QuestBox requires a store: Store in either options or chapter");this.impl=new P.Quest({...t,engine:s}),this.name=this.impl.id?"quest-"+this.impl.id:"",this.chapter=e.chapter,this.chapter&&e.number&&(this.number=this.chapter.number+"."+e.number),this.store=n,this.engine=s,this.view={},this.input=[]}load(){let t=this.store.load(this.name)??{};return this.status={solved:t.solved??!1,steps:t.steps??0,attempts:t.attempts??0,weight:t.weight??0,total:t.total??0},this.status.solved&&this.onSolved(),this}save(){return this.store.save(this.name,this.status),this}update(t){this.status.solved||(this.status.attempts++,this.status.total+=t.steps,this.status.steps=t.steps,this.status.weight=t.weight,t.pass&&(this.status.solved=!0,this.onSolved(t)),this.save(),this.showStatus())}onSolved(t){if(this.impl.meta.unlock&&t){let e=new P.classes.Alias(this.impl.meta.unlock,t.expr.expand());this.chapter?.onUnlock(e)}this.chapter&&this.chapter.addSolved(this.impl.id)}check(){this.view.display&&(this.view.display.innerHTML="running...");let t=this.input.map(s=>s.value),e=this.impl.check(...t);this.showResult(e),this.update(e)}draw(t){this.view.frame=c(t,"div",{class:["ski-quest-box"]}),this.view.frame.id=this.name;let e=c(this.view.frame,"h3"),s=c(this.view.frame,"div"),n=c(e,"a",{content:this.number?"#"+this.number:"Quest"});n.href="#"+this.name,n.onclick=()=>Ut(s,!0),c(e,"span",{content:" "+this.impl.name});let r=this.impl.allowed();r&&c(e,"span",{content:" ["+r+"]"}),this.view.stat=c(e,"span",{class:["ski-quest-float-right"]});let o=c(s,"div");c(o,"div",{content:Ot(this.impl.intro),class:["ski-quest-intro"]}),this.impl.meta.hint&&ve(o," Hint:..."," Hint: "+this.impl.meta.hint),this.view.display=c(s,"div",{class:["ski-quest-display"],content:"....."}),this.view.solution=c(s,"div",{class:["ski-quest-input"]}),this.drawInput(this.view.solution),this.showStatus()}drawInput(t){let e=this.impl.input,s=e.length!==1;for(let r of e){if(s){let a=c(t,"div",{class:["ski-quest-label"]});c(a,"b",{content:r.name}),r.note&&c(a,"span",{content:" // "+r.note,class:["ski-quest-comment"]})}let o=c(t,"input");o.type="text",o.onkeydown=a=>{a.key==="Enter"&&(a.preventDefault(),this.check())},this.input.push(o),c(t,"br")}let n=c(t,"button",{content:"solve!"});n.onclick=()=>this.check()}showStatus(){if(this.view.stat&&this.status.attempts){let t="in "+this.status.attempts+(this.status.attempts===1?" try":" tries"),e=this.status.solved?"✓ "+this.status.steps+" steps/"+this.status.weight+" terms ":this.status.total+" total steps ";this.view.stat.innerHTML=e+" "+t}}showResult(t){if(!this.view.display)return;this.view.display.innerHTML="";let e=c(this.view.display,"div");c(e,"span",{content:"Your solution: "+xe(t.expr)+" "}),t.exception&&c(this.view.display,"div",{class:["ski-quest-error"],content:"Execution failed: "+t.exception});for(let s of t.details){let n=c(this.view.display,"div",{class:s.pass?["ski-quest-success"]:["ski-quest-error"]});c(n,"span",{content:s.pass?"✓ ":"✗ "}),c(n,"span",{content:`${s.start} → ${s.found} `});let r=c(n,"a",{content:`in ${s.steps} steps`,class:["ski-quest-control"]});c(n,"span",{content:" "});let o=c(n,"a",{content:" (hide)",class:["ski-quest-control"],hidden:!0});s.pass||(c(n,"br"),s.expected!==void 0&&(c(n,"span",{content:" expected: "+s.expected}),c(n,"br")),s.reason&&(c(n,"span",{content:" "+s.reason}),c(n,"br")));let a=c(n,"div",{});r.onclick=()=>{a.innerHTML="",o.hidden=!1,new ge({parent:a,engine:this.engine,height:1/0,max:s.steps+2,headless:!0}).start(s.start)},o.onclick=()=>{a.innerHTML="",o.hidden=!0}}}},V=class{constructor(t){this.options=t,this.quests=[],this.solved=new Set,this.view={},this.number=t.number??0,this.engine=t.engine,this.store=t.store,this.onUnlock=t.onUnlock??(()=>{}),this.updateMeta()}updateMeta(t={}){this.options={...this.options,...t},this.id="chapter-"+(t.id??this.number),this.view.frame&&(this.view.frame.id=this.id),this.view.link&&(this.view.link.href="#"+this.id),this.options.name&&this.view.linkText&&(this.view.linkText.innerHTML="Chapter "+this.number+": "+this.options.name)}fetch(){return fetch(this.options.link).then(t=>t.json()).then(t=>{if(Array.isArray(t)&&(t={content:t}),!Array.isArray(t.content))throw new Error("Invalid quest list in "+this.options.link);this.updateMeta(t);let e=0;for(let s of t.content)this.quests.push(new R(s,{chapter:this,number:++e}));return this})}addSolved(t){this.solved.has(t)||(this.solved.add(t),this.showStatus())}getProgress(){return{total:this.quests.length,solved:this.solved.size,complete:this.solved.size===this.quests.length,percentage:Math.round(this.solved.size/this.quests.length*100)}}attach(t,e){return this.view.frame=c(t,"div",{class:["ski-quest-chapter"]}),this.view.frame.id=this.id,e.placeholder&&(this.view.placeholder=c(this.view.frame,"div",{content:e.placeholder})),this}draw(){this.visible=!0,this.view.placeholder?.remove();let t=c(this.view.frame,"h2"),e=c(this.view.frame,"div");c(t,"span",{content:"Chapter "+this.number+": "+this.options.name}),this.view.stat=c(t,"span",{class:["ski-quest-float-right"]}),t.onclick=()=>{Ut(e,this.visible=!this.visible)},this.view.intro=c(e,"div",{content:Ot(this.options.intro),class:["ski-quest-note","ski-quest-chapter-intro"]}),this.view.content=c(e,"div",{class:["ski-quest-chapter-content"]});for(let s of this.quests)s.load(),s.draw(this.view.content);this.showStatus()}showStatus(){if(!this.view.stat)return;let t=this.getProgress();this.view.stat.innerHTML="Progress: "+t.solved+"/"+t.total+" ("+t.percentage+"%)",t.complete&&this.view.stat.classList.add("success"),this.view.progressbar&&(this.view.progressbar.style.paddingRight=t.percentage+"%",this.view.progressbar.style.marginRight=-t.percentage+"%")}addLink(t){let e=c(t,"div",{class:["ski-quest-nav-item"]}),s=c(e,"a",{},n=>{n.style.display="flex"});s.href="#"+this.id,this.view.link=s,this.view.progressbar=c(s,"span",{class:["ski-quest-progressbar"]}),this.view.linkText=c(s,"span",{content:"Chapter "+this.number+"..."})}};function ve(i,t,e){let s=c(i,"span",{}),n=c(s,"span",{content:t,class:["ski-quest-hint"]});n.onclick=()=>{n.remove(),c(s,"span",{content:e})}}function Ot(i){return Array.isArray(i)?i.join(" "):""+i}function xe(i){return i instanceof P.classes.Expr?i instanceof P.classes.Alias?i.name+" = "+i.expand():""+i.expand():""+i}function Ut(i,t){t===void 0&&(t=i.hidden),i.hidden=!t}function ye(i){return i.note??(i.impl??i).format({html:!0,lambda:[""," ↦ ",""]})}Ht.exports={QuestPage:lt,QuestChapter:V,QuestBox:R}});var Se=k(()=>{var{QuestBox:be,QuestChapter:ke,QuestPage:_e}=Kt();typeof window<"u"&&(window.QuestBox=be,window.QuestChapter=ke,window.QuestPage=_e)});Se();})();
|
|
4
4
|
//# sourceMappingURL=ski-quest.min.js.map
|