gram/playground/dist/app.js

462 lines
132 KiB
JavaScript

(()=>{var fn=Object.create;var It=Object.defineProperty;var dn=Object.getOwnPropertyDescriptor;var mn=Object.getOwnPropertyNames;var gn=Object.getPrototypeOf,yn=Object.prototype.hasOwnProperty;var ae=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var vn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of mn(e))!yn.call(t,s)&&s!==n&&It(t,s,{get:()=>e[s],enumerable:!(r=dn(e,s))||r.enumerable});return t};var In=(t,e,n)=>(n=t!=null?fn(gn(t)):{},vn(e||!t||!t.__esModule?It(n,"default",{value:t,enumerable:!0}):n,t));var Jt=ae(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});function F(t){let e=t||"";return function(){throw new Error("this method "+e+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function se(t,e){if(!t)throw new Error(e||"Assertion failed")}function Ve(t,e,n){let r;Object.defineProperty(t,e,{get(){return r||(r=n.call(this)),r}})}function xn(t){return t&&Object.assign({},t)}function Rt(t,e){let n=[];for(;e-- >0;)n.push(t());return n}function Tt(t,e){return new Array(e+1).join(t)}function ke(t,e){return Rt(()=>t,e)}function Ke(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];t.lastIndexOf(r)!==n&&e.indexOf(r)<0&&e.push(r)}return e}function Pt(t){let e=[];return t.forEach(n=>{e.indexOf(n)<0&&e.push(n)}),e}function oe(t){let e=t[0];return e===e.toUpperCase()}function kt(t){return!oe(t)}function Ft(t,e,n){let r=n||" ";return t.length<e?Tt(r,e-t.length)+t:t}function he(){this.strings=[]}he.prototype.append=function(t){this.strings.push(t)};he.prototype.contents=function(){return this.strings.join("")};var Ue=t=>String.fromCodePoint(parseInt(t,16));function $t(t){if(t.charAt(0)==="\\")switch(t.charAt(1)){case"b":return"\b";case"f":return"\f";case"n":return`
`;case"r":return"\r";case"t":return" ";case"v":return"\v";case"x":return Ue(t.slice(2,4));case"u":return t.charAt(2)==="{"?Ue(t.slice(3,-1)):Ue(t.slice(2,6));default:return t.charAt(1)}else return t}function rt(t){if(t==null)return String(t);let e=Object.prototype.toString.call(t);try{let n;return t.constructor&&t.constructor.name?n=t.constructor.name:e.indexOf("[object ")===0?n=e.slice(8,-1):n=typeof t,n+": "+JSON.stringify(String(t))}catch{return e}}function Dt(t,e="unexpected null value"){if(t==null)throw new Error(e);return t}var Sn=Object.freeze({__proto__:null,abstract:F,assert:se,defineLazyProperty:Ve,clone:xn,repeatFn:Rt,repeatStr:Tt,repeat:ke,getDuplicates:Ke,copyWithoutDuplicates:Pt,isSyntactic:oe,isLexical:kt,padLeft:Ft,StringBuffer:he,unescapeCodePoint:$t,unexpectedObjToString:rt,checkNotNull:Dt}),_n={Lu:/\p{Lu}/u,Ll:/\p{Ll}/u,Lt:/\p{Lt}/u,Lm:/\p{Lm}/u,Lo:/\p{Lo}/u,Nl:/\p{Nl}/u,Nd:/\p{Nd}/u,Mn:/\p{Mn}/u,Mc:/\p{Mc}/u,Pc:/\p{Pc}/u,Zs:/\p{Zs}/u,L:/\p{Letter}/u,Ltmo:/\p{Lt}|\p{Lm}|\p{Lo}/u},y=class t{constructor(){if(this.constructor===t)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(e){return e&&(this.source=e.trimmed()),this}},T=Object.create(y.prototype),P=Object.create(y.prototype),A=class extends y{constructor(e){super(),this.obj=e}},O=class extends y{constructor(e,n){super(),this.from=e,this.to=n,this.matchCodePoint=e.length>1||n.length>1}},N=class extends y{constructor(e){super(),this.index=e}},x=class extends y{constructor(e){super(),this.terms=e}},le=class extends x{constructor(e,n,r){let s=e.rules[n].body;super([r,s]),this.superGrammar=e,this.name=n,this.body=r}},ue=class extends x{constructor(e,n,r,s){let i=e.rules[n].body;super([...r,i,...s]),this.superGrammar=e,this.ruleName=n,this.expansionPos=r.length}},b=class extends y{constructor(e){super(),this.factors=e}},L=class extends y{constructor(e){super(),this.expr=e}},K=class extends L{},ee=class extends L{},U=class extends L{};K.prototype.operator="*";ee.prototype.operator="+";U.prototype.operator="?";K.prototype.minNumMatches=0;ee.prototype.minNumMatches=1;U.prototype.minNumMatches=0;K.prototype.maxNumMatches=Number.POSITIVE_INFINITY;ee.prototype.maxNumMatches=Number.POSITIVE_INFINITY;U.prototype.maxNumMatches=1;var E=class extends y{constructor(e){super(),this.expr=e}},C=class extends y{constructor(e){super(),this.expr=e}},R=class extends y{constructor(e){super(),this.expr=e}},v=class extends y{constructor(e,n=[]){super(),this.ruleName=e,this.args=n}isSyntactic(){return oe(this.ruleName)}toMemoKey(){return this._memoKey||Object.defineProperty(this,"_memoKey",{value:this.toString()}),this._memoKey}},w=class extends y{constructor(e){super(),this.category=e,this.pattern=_n[e]}};function S(t,e){let n;return e?(n=new Error(e.getLineAndColumnMessage()+t),n.shortMessage=t,n.interval=e):n=new Error(t),n}function ze(){return S("Interval sources don't match")}function bn(t){let e=new Error;return Object.defineProperty(e,"message",{enumerable:!0,get(){return t.message}}),Object.defineProperty(e,"shortMessage",{enumerable:!0,get(){return"Expected "+t.getExpectedText()}}),e.interval=t.getInterval(),e}function wn(t,e,n){let r=e?`Grammar ${t} is not declared in namespace '${e}'`:"Undeclared grammar "+t;return S(r,n)}function An(t,e){return S("Grammar "+t.name+" is already declared in this namespace")}function On(t){return S(`Grammar '${t.name}' does not support incremental parsing`)}function jt(t,e,n){return S("Rule "+t+" is not declared in grammar "+e,n)}function Nn(t,e,n){return S("Cannot override rule "+t+" because it is not declared in "+e,n)}function Ln(t,e,n){return S("Cannot extend rule "+t+" because it is not declared in "+e,n)}function xt(t,e,n,r){let s="Duplicate declaration for rule '"+t+"' in grammar '"+e+"'";return e!==n&&(s+=" (originally declared in '"+n+"')"),S(s,r)}function Mt(t,e,n,r){return S("Wrong number of parameters for rule "+t+" (expected "+e+", got "+n+")",r)}function En(t,e,n,r){return S("Wrong number of arguments for rule "+t+" (expected "+e+", got "+n+")",r)}function St(t,e,n){return S("Duplicate parameter names in rule "+t+": "+e.join(", "),n)}function Cn(t,e){return S("Invalid parameter to rule "+t+": "+e+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)}var Rn="NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. See https://ohmjs.org/d/svl for more details.";function Tn(t,e){return S("Cannot apply syntactic rule "+t+" from here (inside a lexical context)",e.source)}function Pn(t){let{ruleName:e}=t;return S(`applySyntactic is for syntactic rules, but '${e}' is a lexical rule. `+Rn,t.source)}function kn(t){return S("applySyntactic is not required here (in a syntactic context)",t.source)}function _t(t,e){return S("Incorrect argument type: expected "+t,e.source)}function Fn(t){return S("'...' can appear at most once in a rule body",t.source)}function $n(t){let e=t._node;se(e&&e.isNonterminal()&&e.ctorName==="escapeChar_unicodeCodePoint");let n=t.children.slice(1,-1).map(s=>s.source),r=n[0].coverageWith(...n.slice(1));return S(`U+${r.contents} is not a valid Unicode code point`,r)}function qt(t,e){let n=e.length>0?e[e.length-1].args:[],s="Nullable expression "+t.expr.substituteParams(n)+" is not allowed inside '"+t.operator+"' (possible infinite loop)";if(e.length>0){let i=e.map(a=>new v(a.ruleName,a.args)).join(`
`);s+=`
Application stack (most recent application last):
`+i}return S(s,t.expr.source)}function Bt(t,e,n,r){return S("Rule "+t+" involves an alternation which has inconsistent arity (expected "+e+", got "+n+")",r.source)}function Dn(t){let e=t.map(n=>n.message);return S(["Errors:"].concat(e).join(`
- `),t[0].interval)}function jn(t,e,n,r){let s=r.slice(0,-1).map(o=>{let p=" "+o[0].name+" > "+o[1];return o.length===3?p+" for '"+o[2]+"'":p}).join(`
`);s+=`
`+e+" > "+t;let i="";t==="_iter"&&(i=[`
NOTE: as of Ohm v16, there is no default action for iteration nodes \u2014 see `," https://ohmjs.org/d/dsa for details."].join(`
`));let a=[`Missing semantic action for '${t}' in ${n} '${e}'.${i}`,"Action stack (most recent call last):",s].join(`
`),l=S(a);return l.name="missingSemanticAction",l}function Mn(t){if(t.length===1)throw t[0];if(t.length>1)throw Dn(t)}function qn(t){let e=0;return t.map(r=>{let s=r.toString();return e=Math.max(e,s.length),s}).map(r=>Ft(r,e))}function bt(t,e,n){let r=t.length,s=t.slice(0,n),i=t.slice(n+e.length);return(s+e+i).substr(0,r)}function Bn(...t){let e=this,{offset:n}=e,{repeatStr:r}=Sn,s=new he;s.append("Line "+e.lineNum+", col "+e.colNum+`:
`);let i=qn([e.prevLine==null?0:e.lineNum-1,e.lineNum,e.nextLine==null?0:e.lineNum+1]),a=(u,c,h)=>{s.append(h+i[u]+" | "+c+`
`)};e.prevLine!=null&&a(0,e.prevLine," "),a(1,e.line,"> ");let l=e.line.length,o=r(" ",l+1);for(let u=0;u<t.length;++u){let c=t[u][0],h=t[u][1];se(c>=0&&c<=h,"range start must be >= 0 and <= end");let f=n-e.colNum+1;c=Math.max(0,c-f),h=Math.min(h-f,l),o=bt(o,r("~",h-c),c)}let p=2+i[1].length+3;return s.append(r(" ",p)),o=bt(o,"^",e.colNum-1),s.append(o.replace(/ +$/,"")+`
`),e.nextLine!=null&&a(2,e.nextLine," "),s.contents()}var We=[];function Gt(t){We.push(t)}function Gn(t){We.forEach(e=>{e(t)}),We=null}function st(t,e){let n=1,r=1,s=0,i=0,a=null,l=null,o=-1;for(;s<e;){let c=t.charAt(s++);c===`
`?(n++,r=1,o=i,i=s):c!=="\r"&&r++}let p=t.indexOf(`
`,i);if(p===-1)p=t.length;else{let c=t.indexOf(`
`,p+1);a=c===-1?t.slice(p):t.slice(p,c),a=a.replace(/^\r?\n/,"").replace(/\r$/,"")}o>=0&&(l=t.slice(o,i).replace(/\r?\n$/,""));let u=t.slice(i,p).replace(/\r$/,"");return{offset:e,lineNum:n,colNum:r,line:u,prevLine:l,nextLine:a,toString:Bn}}function it(t,e,...n){return st(t,e).toString(...n)}var wt=(()=>{let t=0;return e=>""+e+t++})(),ce=class t{constructor(e,n,r){this.sourceString=e,this.startIdx=n,this.endIdx=r}get contents(){return this._contents===void 0&&(this._contents=this.sourceString.slice(this.startIdx,this.endIdx)),this._contents}get length(){return this.endIdx-this.startIdx}coverageWith(...e){return t.coverage(...e,this)}collapsedLeft(){return new t(this.sourceString,this.startIdx,this.startIdx)}collapsedRight(){return new t(this.sourceString,this.endIdx,this.endIdx)}getLineAndColumn(){return st(this.sourceString,this.startIdx)}getLineAndColumnMessage(){let e=[this.startIdx,this.endIdx];return it(this.sourceString,this.startIdx,e)}minus(e){if(this.sourceString!==e.sourceString)throw ze();return this.startIdx===e.startIdx&&this.endIdx===e.endIdx?[]:this.startIdx<e.startIdx&&e.endIdx<this.endIdx?[new t(this.sourceString,this.startIdx,e.startIdx),new t(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.endIdx&&e.endIdx<this.endIdx?[new t(this.sourceString,e.endIdx,this.endIdx)]:this.startIdx<e.startIdx&&e.startIdx<this.endIdx?[new t(this.sourceString,this.startIdx,e.startIdx)]:[this]}relativeTo(e){if(this.sourceString!==e.sourceString)throw ze();return se(this.startIdx>=e.startIdx&&this.endIdx<=e.endIdx,"other interval does not cover this one"),new t(this.sourceString,this.startIdx-e.startIdx,this.endIdx-e.startIdx)}trimmed(){let{contents:e}=this,n=this.startIdx+e.match(/^\s*/)[0].length,r=this.endIdx-e.match(/\s*$/)[0].length;return new t(this.sourceString,n,r)}subInterval(e,n){let r=this.startIdx+e;return new t(this.sourceString,r,r+n)}};ce.coverage=function(t,...e){let{startIdx:n,endIdx:r}=t;for(let s of e){if(s.sourceString!==t.sourceString)throw ze();n=Math.min(n,s.startIdx),r=Math.max(r,s.endIdx)}return new ce(t.sourceString,n,r)};var Un=65535,fe=class{constructor(e){this.source=e,this.pos=0,this.examinedLength=0}atEnd(){let e=this.pos>=this.source.length;return this.examinedLength=Math.max(this.examinedLength,this.pos+1),e}next(){let e=this.source[this.pos++];return this.examinedLength=Math.max(this.examinedLength,this.pos),e}nextCharCode(){let e=this.next();return e&&e.charCodeAt(0)}nextCodePoint(){let e=this.source.slice(this.pos++).codePointAt(0);return e>Un&&(this.pos+=1),this.examinedLength=Math.max(this.examinedLength,this.pos),e}matchString(e,n){let r;if(n){for(r=0;r<e.length;r++){let s=this.next(),i=e[r];if(s==null||s.toUpperCase()!==i.toUpperCase())return!1}return!0}for(r=0;r<e.length;r++)if(this.next()!==e[r])return!1;return!0}sourceSlice(e,n){return this.source.slice(e,n)}interval(e,n){return new ce(this.source,e,n||this.pos)}},Ne=class{constructor(e,n,r,s,i,a,l){this.matcher=e,this.input=n,this.startExpr=r,this._cst=s,this._cstOffset=i,this._rightmostFailurePosition=a,this._rightmostFailures=l,this.failed()&&(Ve(this,"message",function(){let o="Expected "+this.getExpectedText();return it(this.input,this.getRightmostFailurePosition())+o}),Ve(this,"shortMessage",function(){let o="expected "+this.getExpectedText(),p=st(this.input,this.getRightmostFailurePosition());return"Line "+p.lineNum+", col "+p.colNum+": "+o}))}succeeded(){return!!this._cst}failed(){return!this.succeeded()}getRightmostFailurePosition(){return this._rightmostFailurePosition}getRightmostFailures(){if(!this._rightmostFailures){this.matcher.setInput(this.input);let e=this.matcher._match(this.startExpr,{tracing:!1,positionToRecordFailures:this.getRightmostFailurePosition()});this._rightmostFailures=e.getRightmostFailures()}return this._rightmostFailures}toString(){return this.succeeded()?"[match succeeded]":"[match failed at position "+this.getRightmostFailurePosition()+"]"}getExpectedText(){if(this.succeeded())throw new Error("cannot get expected text of a successful MatchResult");let e=new he,n=this.getRightmostFailures();n=n.filter(r=>!r.isFluffy());for(let r=0;r<n.length;r++)r>0&&(r===n.length-1?e.append(n.length>2?", or ":" or "):e.append(", ")),e.append(n[r].toString());return e.contents()}getInterval(){let e=this.getRightmostFailurePosition();return new ce(this.input,e,e)}},Ze=class{constructor(){this.applicationMemoKeyStack=[],this.memo={},this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,this.currentLeftRecursion=void 0}isActive(e){return this.applicationMemoKeyStack.indexOf(e.toMemoKey())>=0}enter(e){this.applicationMemoKeyStack.push(e.toMemoKey())}exit(){this.applicationMemoKeyStack.pop()}startLeftRecursion(e,n){n.isLeftRecursion=!0,n.headApplication=e,n.nextLeftRecursion=this.currentLeftRecursion,this.currentLeftRecursion=n;let{applicationMemoKeyStack:r}=this,s=r.indexOf(e.toMemoKey())+1,i=r.slice(s);n.isInvolved=function(a){return i.indexOf(a)>=0},n.updateInvolvedApplicationMemoKeys=function(){for(let a=s;a<r.length;a++){let l=r[a];this.isInvolved(l)||i.push(l)}}}endLeftRecursion(){this.currentLeftRecursion=this.currentLeftRecursion.nextLeftRecursion}shouldUseMemoizedResult(e){if(!e.isLeftRecursion)return!0;let{applicationMemoKeyStack:n}=this;for(let r=0;r<n.length;r++){let s=n[r];if(e.isInvolved(s))return!1}return!0}memoize(e,n){return this.memo[e]=n,this.maxExaminedLength=Math.max(this.maxExaminedLength,n.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,n.rightmostFailureOffset),n}clearObsoleteEntries(e,n){if(e+this.maxExaminedLength<=n)return;let{memo:r}=this;this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,Object.keys(r).forEach(s=>{let i=r[s];e+i.examinedLength>n?delete r[s]:(this.maxExaminedLength=Math.max(this.maxExaminedLength,i.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,i.rightmostFailureOffset))})}},Hn="\u2717",Qn="\u2713",Vn="\u22C5",Kn="\u21D2",zn="\u2409",Wn="\u240A",Zn="\u240D",Je={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function Jn(t){return ke(" ",t).join("")}function Yn(t,e,n){let r=Ut(t.slice(e,e+n));return r.length<n?r+ke(" ",n-r.length).join(""):r}function Ut(t){return typeof t=="string"?t.replace(/ /g,Vn).replace(/\t/g,zn).replace(/\n/g,Wn).replace(/\r/g,Zn):String(t)}var de=class t{constructor(e,n,r,s,i,a,l){this.input=e,this.pos=this.pos1=n,this.pos2=r,this.source=new ce(e,n,r),this.expr=s,this.bindings=a,this.children=l||[],this.terminatingLREntry=null,this._flags=i?Je.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(e){let n=new t(this.input,this.pos,this.pos2,e,this.succeeded,this.bindings,this.children);return n.isHeadOfLeftRecursion=this.isHeadOfLeftRecursion,n.isImplicitSpaces=this.isImplicitSpaces,n.isMemoized=this.isMemoized,n.isRootNode=this.isRootNode,n.terminatesLR=this.terminatesLR,n.terminatingLREntry=this.terminatingLREntry,n}recordLRTermination(e,n){this.terminatingLREntry=new t(this.input,this.pos,this.pos2,this.expr,!1,[n],[e]),this.terminatingLREntry.terminatesLR=!0}walk(e,n){let r=e;typeof r=="function"&&(r={enter:r});function s(i,a,l){let o=!0;r.enter&&r.enter.call(n,i,a,l)===t.prototype.SKIP&&(o=!1),o&&(i.children.forEach(p=>{s(p,i,l+1)}),r.exit&&r.exit.call(n,i,a,l))}this.isRootNode?this.children.forEach(i=>{s(i,null,0)}):s(this,null,0)}toString(){let e=new he;return this.walk((n,r,s)=>{if(!n)return this.SKIP;if(n.expr.constructor.name!=="Alt"){if(e.append(Yn(n.input,n.pos,10)+Jn(s*2+1)),e.append((n.succeeded?Qn:Hn)+" "+n.displayString),n.isHeadOfLeftRecursion&&e.append(" (LR)"),n.succeeded){let a=Ut(n.source.contents);e.append(" "+Kn+" "),e.append(typeof a=="string"?'"'+a+'"':a)}e.append(`
`)}}),e.contents()}};de.prototype.SKIP={};Object.keys(Je).forEach(t=>{let e=Je[t];Object.defineProperty(de.prototype,t,{get(){return(this._flags&e)!==0},set(n){n?this._flags|=e:this._flags&=~e}})});y.prototype.allowsSkippingPrecedingSpace=F("allowsSkippingPrecedingSpace");T.allowsSkippingPrecedingSpace=P.allowsSkippingPrecedingSpace=v.prototype.allowsSkippingPrecedingSpace=A.prototype.allowsSkippingPrecedingSpace=O.prototype.allowsSkippingPrecedingSpace=w.prototype.allowsSkippingPrecedingSpace=function(){return!0};x.prototype.allowsSkippingPrecedingSpace=L.prototype.allowsSkippingPrecedingSpace=R.prototype.allowsSkippingPrecedingSpace=C.prototype.allowsSkippingPrecedingSpace=E.prototype.allowsSkippingPrecedingSpace=N.prototype.allowsSkippingPrecedingSpace=b.prototype.allowsSkippingPrecedingSpace=function(){return!1};var Ie;Gt(t=>{Ie=t});var Le;y.prototype.assertAllApplicationsAreValid=function(t,e){Le=0,this._assertAllApplicationsAreValid(t,e)};y.prototype._assertAllApplicationsAreValid=F("_assertAllApplicationsAreValid");T._assertAllApplicationsAreValid=P._assertAllApplicationsAreValid=A.prototype._assertAllApplicationsAreValid=O.prototype._assertAllApplicationsAreValid=N.prototype._assertAllApplicationsAreValid=w.prototype._assertAllApplicationsAreValid=function(t,e){};R.prototype._assertAllApplicationsAreValid=function(t,e){Le++,this.expr._assertAllApplicationsAreValid(t,e),Le--};x.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.terms.length;n++)this.terms[n]._assertAllApplicationsAreValid(t,e)};b.prototype._assertAllApplicationsAreValid=function(t,e){for(let n=0;n<this.factors.length;n++)this.factors[n]._assertAllApplicationsAreValid(t,e)};L.prototype._assertAllApplicationsAreValid=E.prototype._assertAllApplicationsAreValid=C.prototype._assertAllApplicationsAreValid=function(t,e){this.expr._assertAllApplicationsAreValid(t,e)};v.prototype._assertAllApplicationsAreValid=function(t,e,n=!1){let r=e.rules[this.ruleName],s=oe(t)&&Le===0;if(!r)throw jt(this.ruleName,e.name,this.source);if(!n&&oe(this.ruleName)&&!s)throw Tn(this.ruleName,this);let i=this.args.length,a=r.formals.length;if(i!==a)throw En(this.ruleName,a,i,this.source);let l=Ie&&r===Ie.rules.applySyntactic;if(Ie&&r===Ie.rules.caseInsensitive&&!(this.args[0]instanceof A))throw _t('a Terminal (e.g. "abc")',this.args[0]);if(l){let p=this.args[0];if(!(p instanceof v))throw _t("a syntactic rule application",p);if(!oe(p.ruleName))throw Pn(p);if(s)throw kn(this)}this.args.forEach(p=>{if(p._assertAllApplicationsAreValid(t,e,l),p.getArity()!==1)throw Cn(this.ruleName,p)})};y.prototype.assertChoicesHaveUniformArity=F("assertChoicesHaveUniformArity");T.assertChoicesHaveUniformArity=P.assertChoicesHaveUniformArity=A.prototype.assertChoicesHaveUniformArity=O.prototype.assertChoicesHaveUniformArity=N.prototype.assertChoicesHaveUniformArity=R.prototype.assertChoicesHaveUniformArity=w.prototype.assertChoicesHaveUniformArity=function(t){};x.prototype.assertChoicesHaveUniformArity=function(t){if(this.terms.length===0)return;let e=this.terms[0].getArity();for(let n=0;n<this.terms.length;n++){let r=this.terms[n];r.assertChoicesHaveUniformArity();let s=r.getArity();if(e!==s)throw Bt(t,e,s,r)}};le.prototype.assertChoicesHaveUniformArity=function(t){let e=this.terms[0].getArity(),n=this.terms[1].getArity();if(e!==n)throw Bt(t,n,e,this.terms[0])};b.prototype.assertChoicesHaveUniformArity=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertChoicesHaveUniformArity(t)};L.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};E.prototype.assertChoicesHaveUniformArity=function(t){};C.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)};v.prototype.assertChoicesHaveUniformArity=function(t){};y.prototype.assertIteratedExprsAreNotNullable=F("assertIteratedExprsAreNotNullable");T.assertIteratedExprsAreNotNullable=P.assertIteratedExprsAreNotNullable=A.prototype.assertIteratedExprsAreNotNullable=O.prototype.assertIteratedExprsAreNotNullable=N.prototype.assertIteratedExprsAreNotNullable=w.prototype.assertIteratedExprsAreNotNullable=function(t){};x.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.terms.length;e++)this.terms[e].assertIteratedExprsAreNotNullable(t)};b.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertIteratedExprsAreNotNullable(t)};L.prototype.assertIteratedExprsAreNotNullable=function(t){if(this.expr.assertIteratedExprsAreNotNullable(t),this.expr.isNullable(t))throw qt(this,[])};U.prototype.assertIteratedExprsAreNotNullable=E.prototype.assertIteratedExprsAreNotNullable=C.prototype.assertIteratedExprsAreNotNullable=R.prototype.assertIteratedExprsAreNotNullable=function(t){this.expr.assertIteratedExprsAreNotNullable(t)};v.prototype.assertIteratedExprsAreNotNullable=function(t){this.args.forEach(e=>{e.assertIteratedExprsAreNotNullable(t)})};var Se=class{constructor(e){this.matchLength=e}get ctorName(){throw new Error("subclass responsibility")}numChildren(){return this.children?this.children.length:0}childAt(e){if(this.children)return this.children[e]}indexOfChild(e){return this.children.indexOf(e)}hasChildren(){return this.numChildren()>0}hasNoChildren(){return!this.hasChildren()}onlyChild(){if(this.numChildren()!==1)throw new Error("cannot get only child of a node of type "+this.ctorName+" (it has "+this.numChildren()+" children)");return this.firstChild()}firstChild(){if(this.hasNoChildren())throw new Error("cannot get first child of a "+this.ctorName+" node, which has no children");return this.childAt(0)}lastChild(){if(this.hasNoChildren())throw new Error("cannot get last child of a "+this.ctorName+" node, which has no children");return this.childAt(this.numChildren()-1)}childBefore(e){let n=this.indexOfChild(e);if(n<0)throw new Error("Node.childBefore() called w/ an argument that is not a child");if(n===0)throw new Error("cannot get child before first child");return this.childAt(n-1)}childAfter(e){let n=this.indexOfChild(e);if(n<0)throw new Error("Node.childAfter() called w/ an argument that is not a child");if(n===this.numChildren()-1)throw new Error("cannot get child after last child");return this.childAt(n+1)}isTerminal(){return!1}isNonterminal(){return!1}isIteration(){return!1}isOptional(){return!1}},te=class extends Se{get ctorName(){return"_terminal"}isTerminal(){return!0}get primitiveValue(){throw new Error("The `primitiveValue` property was removed in Ohm v17.")}},Ye=class extends Se{constructor(e,n,r,s){super(s),this.ruleName=e,this.children=n,this.childOffsets=r}get ctorName(){return this.ruleName}isNonterminal(){return!0}isLexical(){return kt(this.ctorName)}isSyntactic(){return oe(this.ctorName)}},Ee=class extends Se{constructor(e,n,r,s){super(r),this.children=e,this.childOffsets=n,this.optional=s}get ctorName(){return"_iter"}isIteration(){return!0}isOptional(){return this.optional}};y.prototype.eval=F("eval");T.eval=function(t){let{inputStream:e}=t,n=e.pos,r=e.nextCodePoint();return r!==void 0?(t.pushBinding(new te(String.fromCodePoint(r).length),n),!0):(t.processFailure(n,this),!1)};P.eval=function(t){let{inputStream:e}=t,n=e.pos;return e.atEnd()?(t.pushBinding(new te(0),n),!0):(t.processFailure(n,this),!1)};A.prototype.eval=function(t){let{inputStream:e}=t,n=e.pos;return e.matchString(this.obj)?(t.pushBinding(new te(this.obj.length),n),!0):(t.processFailure(n,this),!1)};O.prototype.eval=function(t){let{inputStream:e}=t,n=e.pos,r=this.matchCodePoint?e.nextCodePoint():e.nextCharCode();return r!==void 0&&this.from.codePointAt(0)<=r&&r<=this.to.codePointAt(0)?(t.pushBinding(new te(String.fromCodePoint(r).length),n),!0):(t.processFailure(n,this),!1)};N.prototype.eval=function(t){return t.eval(t.currentApplication().args[this.index])};R.prototype.eval=function(t){t.enterLexifiedContext();let e=t.eval(this.expr);return t.exitLexifiedContext(),e};x.prototype.eval=function(t){for(let e=0;e<this.terms.length;e++)if(t.eval(this.terms[e]))return!0;return!1};b.prototype.eval=function(t){for(let e=0;e<this.factors.length;e++){let n=this.factors[e];if(!t.eval(n))return!1}return!0};L.prototype.eval=function(t){let{inputStream:e}=t,n=e.pos,r=this.getArity(),s=[],i=[];for(;s.length<r;)s.push([]),i.push([]);let a=0,l=n,o;for(;a<this.maxNumMatches&&t.eval(this.expr);){if(e.pos===l)throw qt(this,t._applicationStack);l=e.pos,a++;let h=t._bindings.splice(t._bindings.length-r,r),f=t._bindingOffsets.splice(t._bindingOffsets.length-r,r);for(o=0;o<h.length;o++)s[o].push(h[o]),i[o].push(f[o])}if(a<this.minNumMatches)return!1;let p=t.posToOffset(n),u=0;if(a>0){let h=s[r-1],f=i[r-1],d=f[f.length-1]+h[h.length-1].matchLength;p=i[0][0],u=d-p}let c=this instanceof U;for(o=0;o<s.length;o++)t._bindings.push(new Ee(s[o],i[o],u,c)),t._bindingOffsets.push(p);return!0};E.prototype.eval=function(t){let{inputStream:e}=t,n=e.pos;t.pushFailuresInfo();let r=t.eval(this.expr);return t.popFailuresInfo(),r?(t.processFailure(n,this),!1):(e.pos=n,!0)};C.prototype.eval=function(t){let{inputStream:e}=t,n=e.pos;return t.eval(this.expr)?(e.pos=n,!0):!1};v.prototype.eval=function(t){let e=t.currentApplication(),n=e?e.args:[],r=this.substituteParams(n),s=t.getCurrentPosInfo();if(s.isActive(r))return r.handleCycle(t);let i=r.toMemoKey(),a=s.memo[i];if(a&&s.shouldUseMemoizedResult(a)){if(t.hasNecessaryInfo(a))return t.useMemoizedResult(t.inputStream.pos,a);delete s.memo[i]}return r.reallyEval(t)};v.prototype.handleCycle=function(t){let e=t.getCurrentPosInfo(),{currentLeftRecursion:n}=e,r=this.toMemoKey(),s=e.memo[r];return n&&n.headApplication.toMemoKey()===r?s.updateInvolvedApplicationMemoKeys():s||(s=e.memoize(r,{matchLength:0,examinedLength:0,value:!1,rightmostFailureOffset:-1}),e.startLeftRecursion(this,s)),t.useMemoizedResult(t.inputStream.pos,s)};v.prototype.reallyEval=function(t){let{inputStream:e}=t,n=e.pos,r=t.getCurrentPosInfo(),s=t.grammar.rules[this.ruleName],{body:i}=s,{description:a}=s;t.enterApplication(r,this),a&&t.pushFailuresInfo();let l=e.examinedLength;e.examinedLength=0;let o=this.evalOnce(i,t),p=r.currentLeftRecursion,u=this.toMemoKey(),c=p&&p.headApplication.toMemoKey()===u,h;t.doNotMemoize?t.doNotMemoize=!1:c?(o=this.growSeedResult(i,t,n,p,o),r.endLeftRecursion(),h=p,h.examinedLength=e.examinedLength-n,h.rightmostFailureOffset=t._getRightmostFailureOffset(),r.memoize(u,h)):(!p||!p.isInvolved(u))&&(h=r.memoize(u,{matchLength:e.pos-n,examinedLength:e.examinedLength-n,value:o,failuresAtRightmostPosition:t.cloneRecordedFailures(),rightmostFailureOffset:t._getRightmostFailureOffset()}));let f=!!o;if(a&&(t.popFailuresInfo(),f||t.processFailure(n,this),h&&(h.failuresAtRightmostPosition=t.cloneRecordedFailures())),t.isTracing()&&h){let d=t.getTraceEntry(n,this,f,f?[o]:[]);c&&(se(d.terminatingLREntry!=null||!f),d.isHeadOfLeftRecursion=!0),h.traceEntry=d}return e.examinedLength=Math.max(e.examinedLength,l),t.exitApplication(r,o),f};v.prototype.evalOnce=function(t,e){let{inputStream:n}=e,r=n.pos;if(e.eval(t)){let s=t.getArity(),i=e._bindings.splice(e._bindings.length-s,s),a=e._bindingOffsets.splice(e._bindingOffsets.length-s,s),l=n.pos-r;return new Ye(this.ruleName,i,a,l)}else return!1};v.prototype.growSeedResult=function(t,e,n,r,s){if(!s)return!1;let{inputStream:i}=e;for(;;){if(r.matchLength=i.pos-n,r.value=s,r.failuresAtRightmostPosition=e.cloneRecordedFailures(),e.isTracing()){let a=e.trace[e.trace.length-1];r.traceEntry=new de(e.input,n,i.pos,this,!0,[s],[a.clone()])}if(i.pos=n,s=this.evalOnce(t,e),i.pos-n<=r.matchLength)break;e.isTracing()&&e.trace.splice(-2,1)}return e.isTracing()&&r.traceEntry.recordLRTermination(e.trace.pop(),s),i.pos=n+r.matchLength,r.value};w.prototype.eval=function(t){let{inputStream:e}=t,n=e.pos,r=e.next();return r&&this.pattern.test(r)?(t.pushBinding(new te(r.length),n),!0):(t.processFailure(n,this),!1)};y.prototype.getArity=F("getArity");T.getArity=P.getArity=A.prototype.getArity=O.prototype.getArity=N.prototype.getArity=v.prototype.getArity=w.prototype.getArity=function(){return 1};x.prototype.getArity=function(){return this.terms.length===0?0:this.terms[0].getArity()};b.prototype.getArity=function(){let t=0;for(let e=0;e<this.factors.length;e++)t+=this.factors[e].getArity();return t};L.prototype.getArity=function(){return this.expr.getArity()};E.prototype.getArity=function(){return 0};C.prototype.getArity=R.prototype.getArity=function(){return this.expr.getArity()};function Q(t,e){let n={};if(t.source&&e){let r=t.source.relativeTo(e);n.sourceInterval=[r.startIdx,r.endIdx]}return n}y.prototype.outputRecipe=F("outputRecipe");T.outputRecipe=function(t,e){return["any",Q(this,e)]};P.outputRecipe=function(t,e){return["end",Q(this,e)]};A.prototype.outputRecipe=function(t,e){return["terminal",Q(this,e),this.obj]};O.prototype.outputRecipe=function(t,e){return["range",Q(this,e),this.from,this.to]};N.prototype.outputRecipe=function(t,e){return["param",Q(this,e),this.index]};x.prototype.outputRecipe=function(t,e){return["alt",Q(this,e)].concat(this.terms.map(n=>n.outputRecipe(t,e)))};le.prototype.outputRecipe=function(t,e){return this.terms[0].outputRecipe(t,e)};ue.prototype.outputRecipe=function(t,e){let n=this.terms.slice(0,this.expansionPos),r=this.terms.slice(this.expansionPos+1);return["splice",Q(this,e),n.map(s=>s.outputRecipe(t,e)),r.map(s=>s.outputRecipe(t,e))]};b.prototype.outputRecipe=function(t,e){return["seq",Q(this,e)].concat(this.factors.map(n=>n.outputRecipe(t,e)))};K.prototype.outputRecipe=ee.prototype.outputRecipe=U.prototype.outputRecipe=E.prototype.outputRecipe=C.prototype.outputRecipe=R.prototype.outputRecipe=function(t,e){return[this.constructor.name.toLowerCase(),Q(this,e),this.expr.outputRecipe(t,e)]};v.prototype.outputRecipe=function(t,e){return["app",Q(this,e),this.ruleName,this.args.map(n=>n.outputRecipe(t,e))]};w.prototype.outputRecipe=function(t,e){return["unicodeChar",Q(this,e),this.category]};y.prototype.introduceParams=F("introduceParams");T.introduceParams=P.introduceParams=A.prototype.introduceParams=O.prototype.introduceParams=N.prototype.introduceParams=w.prototype.introduceParams=function(t){return this};x.prototype.introduceParams=function(t){return this.terms.forEach((e,n,r)=>{r[n]=e.introduceParams(t)}),this};b.prototype.introduceParams=function(t){return this.factors.forEach((e,n,r)=>{r[n]=e.introduceParams(t)}),this};L.prototype.introduceParams=E.prototype.introduceParams=C.prototype.introduceParams=R.prototype.introduceParams=function(t){return this.expr=this.expr.introduceParams(t),this};v.prototype.introduceParams=function(t){let e=t.indexOf(this.ruleName);if(e>=0){if(this.args.length>0)throw new Error("Parameterized rules cannot be passed as arguments to another rule.");return new N(e).withSource(this.source)}else return this.args.forEach((n,r,s)=>{s[r]=n.introduceParams(t)}),this};y.prototype.isNullable=function(t){return this._isNullable(t,Object.create(null))};y.prototype._isNullable=F("_isNullable");T._isNullable=O.prototype._isNullable=N.prototype._isNullable=ee.prototype._isNullable=w.prototype._isNullable=function(t,e){return!1};P._isNullable=function(t,e){return!0};A.prototype._isNullable=function(t,e){return typeof this.obj=="string"?this.obj==="":!1};x.prototype._isNullable=function(t,e){return this.terms.length===0||this.terms.some(n=>n._isNullable(t,e))};b.prototype._isNullable=function(t,e){return this.factors.every(n=>n._isNullable(t,e))};K.prototype._isNullable=U.prototype._isNullable=E.prototype._isNullable=C.prototype._isNullable=function(t,e){return!0};R.prototype._isNullable=function(t,e){return this.expr._isNullable(t,e)};v.prototype._isNullable=function(t,e){let n=this.toMemoKey();if(!Object.prototype.hasOwnProperty.call(e,n)){let{body:r}=t.rules[this.ruleName],s=r.substituteParams(this.args);e[n]=!1,e[n]=s._isNullable(t,e)}return e[n]};y.prototype.substituteParams=F("substituteParams");T.substituteParams=P.substituteParams=A.prototype.substituteParams=O.prototype.substituteParams=w.prototype.substituteParams=function(t){return this};N.prototype.substituteParams=function(t){return Dt(t[this.index])};x.prototype.substituteParams=function(t){return new x(this.terms.map(e=>e.substituteParams(t)))};b.prototype.substituteParams=function(t){return new b(this.factors.map(e=>e.substituteParams(t)))};L.prototype.substituteParams=E.prototype.substituteParams=C.prototype.substituteParams=R.prototype.substituteParams=function(t){return new this.constructor(this.expr.substituteParams(t))};v.prototype.substituteParams=function(t){if(this.args.length===0)return this;{let e=this.args.map(n=>n.substituteParams(t));return new v(this.ruleName,e)}};function At(t){return/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)}function at(t){let e=Object.create(null);t.forEach(n=>{e[n]=(e[n]||0)+1}),Object.keys(e).forEach(n=>{if(e[n]<=1)return;let r=1;t.forEach((s,i)=>{s===n&&(t[i]=s+"_"+r++)})})}y.prototype.toArgumentNameList=F("toArgumentNameList");T.toArgumentNameList=function(t,e){return["any"]};P.toArgumentNameList=function(t,e){return["end"]};A.prototype.toArgumentNameList=function(t,e){return typeof this.obj=="string"&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+t]};O.prototype.toArgumentNameList=function(t,e){let n=this.from+"_to_"+this.to;return At(n)||(n="_"+n),At(n)||(n="$"+t),[n]};x.prototype.toArgumentNameList=function(t,e){let n=this.terms.map(i=>i.toArgumentNameList(t,!0)),r=[],s=n[0].length;for(let i=0;i<s;i++){let a=[];for(let o=0;o<this.terms.length;o++)a.push(n[o][i]);let l=Pt(a);r.push(l.join("_or_"))}return e||at(r),r};b.prototype.toArgumentNameList=function(t,e){let n=[];return this.factors.forEach(r=>{let s=r.toArgumentNameList(t,!0);n=n.concat(s),t+=s.length}),e||at(n),n};L.prototype.toArgumentNameList=function(t,e){let n=this.expr.toArgumentNameList(t,e).map(r=>r[r.length-1]==="s"?r+"es":r+"s");return e||at(n),n};U.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e).map(n=>"opt"+n[0].toUpperCase()+n.slice(1))};E.prototype.toArgumentNameList=function(t,e){return[]};C.prototype.toArgumentNameList=R.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e)};v.prototype.toArgumentNameList=function(t,e){return[this.ruleName]};w.prototype.toArgumentNameList=function(t,e){return["$"+t]};N.prototype.toArgumentNameList=function(t,e){return["param"+this.index]};y.prototype.toDisplayString=F("toDisplayString");x.prototype.toDisplayString=b.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"};T.toDisplayString=P.toDisplayString=L.prototype.toDisplayString=E.prototype.toDisplayString=C.prototype.toDisplayString=R.prototype.toDisplayString=A.prototype.toDisplayString=O.prototype.toDisplayString=N.prototype.toDisplayString=function(){return this.toString()};v.prototype.toDisplayString=function(){if(this.args.length>0){let t=this.args.map(e=>e.toDisplayString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};w.prototype.toDisplayString=function(){return"Unicode ["+this.category+"] character"};function Xn(t){return t==="description"||t==="string"||t==="code"}var j=class t{constructor(e,n,r){if(!Xn(r))throw new Error("invalid Failure type: "+r);this.pexpr=e,this.text=n,this.type=r,this.fluffy=!1}getPExpr(){return this.pexpr}getText(){return this.text}getType(){return this.type}isDescription(){return this.type==="description"}isStringTerminal(){return this.type==="string"}isCode(){return this.type==="code"}isFluffy(){return this.fluffy}makeFluffy(){this.fluffy=!0}clearFluffy(){this.fluffy=!1}subsumes(e){return this.getText()===e.getText()&&this.type===e.type&&(!this.isFluffy()||this.isFluffy()&&e.isFluffy())}toString(){return this.type==="string"?JSON.stringify(this.getText()):this.getText()}clone(){let e=new t(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}};y.prototype.toFailure=F("toFailure");T.toFailure=function(t){return new j(this,"any object","description")};P.toFailure=function(t){return new j(this,"end of input","description")};A.prototype.toFailure=function(t){return new j(this,this.obj,"string")};O.prototype.toFailure=function(t){return new j(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")};E.prototype.toFailure=function(t){let e=this.expr===T?"nothing":"not "+this.expr.toFailure(t);return new j(this,e,"description")};C.prototype.toFailure=function(t){return this.expr.toFailure(t)};v.prototype.toFailure=function(t){let{description:e}=t.rules[this.ruleName];return e||(e=(/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a")+" "+this.ruleName),new j(this,e,"description")};w.prototype.toFailure=function(t){return new j(this,"a Unicode ["+this.category+"] character","description")};x.prototype.toFailure=function(t){let n="("+this.terms.map(r=>r.toFailure(t)).join(" or ")+")";return new j(this,n,"description")};b.prototype.toFailure=function(t){let n="("+this.factors.map(r=>r.toFailure(t)).join(" ")+")";return new j(this,n,"description")};L.prototype.toFailure=function(t){let e="("+this.expr.toFailure(t)+this.operator+")";return new j(this,e,"description")};y.prototype.toString=F("toString");T.toString=function(){return"any"};P.toString=function(){return"end"};A.prototype.toString=function(){return JSON.stringify(this.obj)};O.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)};N.prototype.toString=function(){return"$"+this.index};R.prototype.toString=function(){return"#("+this.expr.toString()+")"};x.prototype.toString=function(){return this.terms.length===1?this.terms[0].toString():"("+this.terms.map(t=>t.toString()).join(" | ")+")"};b.prototype.toString=function(){return this.factors.length===1?this.factors[0].toString():"("+this.factors.map(t=>t.toString()).join(" ")+")"};L.prototype.toString=function(){return this.expr+this.operator};E.prototype.toString=function(){return"~"+this.expr};C.prototype.toString=function(){return"&"+this.expr};v.prototype.toString=function(){if(this.args.length>0){let t=this.args.map(e=>e.toString());return this.ruleName+"<"+t.join(",")+">"}else return this.ruleName};w.prototype.toString=function(){return"\\p{"+this.category+"}"};var Ce=class t extends y{constructor(e){super(),this.obj=e}_getString(e){let n=e.currentApplication().args[this.obj.index];return se(n instanceof A,"expected a Terminal expression"),n.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){let{inputStream:n}=e,r=n.pos,s=this._getString(e);return n.matchString(s,!0)?(e.pushBinding(new te(s.length),r),!0):(e.processFailure(r,this),!1)}getArity(){return 1}substituteParams(e){return new t(this.obj.substituteParams(e))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(e){return new j(this,this.obj.toFailure(e)+" (case-insensitive)","description")}_isNullable(e,n){return this.obj._isNullable(e,n)}},er=Object.freeze({__proto__:null,CaseInsensitiveTerminal:Ce,PExpr:y,any:T,end:P,Terminal:A,Range:O,Param:N,Alt:x,Extend:le,Splice:ue,Seq:b,Iter:L,Star:K,Plus:ee,Opt:U,Not:E,Lookahead:C,Lex:R,Apply:v,UnicodeChar:w}),Ht;Gt(t=>{Ht=t.rules.applySyntactic.body});var He=new v("spaces"),Xe=class{constructor(e,n,r){this.matcher=e,this.startExpr=n,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new fe(this.input),this.memoTable=e._memoTable,this.userData=void 0,this.doNotMemoize=!1,this._bindings=[],this._bindingOffsets=[],this._applicationStack=[],this._posStack=[0],this.inLexifiedContextStack=[!1],this.rightmostFailurePosition=-1,this._rightmostFailurePositionStack=[],this._recordedFailuresStack=[],r!==void 0&&(this.positionToRecordFailures=r,this.recordedFailures=Object.create(null))}posToOffset(e){return e-this._posStack[this._posStack.length-1]}enterApplication(e,n){this._posStack.push(this.inputStream.pos),this._applicationStack.push(n),this.inLexifiedContextStack.push(!1),e.enter(n),this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this.rightmostFailurePosition=-1}exitApplication(e,n){let r=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),e.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),n&&this.pushBinding(n,r)}enterLexifiedContext(){this.inLexifiedContextStack.push(!0)}exitLexifiedContext(){this.inLexifiedContextStack.pop()}currentApplication(){return this._applicationStack[this._applicationStack.length-1]}inSyntacticContext(){let e=this.currentApplication();return e?e.isSyntactic()&&!this.inLexifiedContext():this.startExpr.factors[0].isSyntactic()}inLexifiedContext(){return this.inLexifiedContextStack[this.inLexifiedContextStack.length-1]}skipSpaces(){return this.pushFailuresInfo(),this.eval(He),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==He?this.skipSpacesIfInSyntacticContext():this.inputStream.pos}pushBinding(e,n){this._bindings.push(e),this._bindingOffsets.push(this.posToOffset(n))}popBinding(){this._bindings.pop(),this._bindingOffsets.pop()}numBindings(){return this._bindings.length}truncateBindings(e){for(;this._bindings.length>e;)this.popBinding()}getCurrentPosInfo(){return this.getPosInfo(this.inputStream.pos)}getPosInfo(e){let n=this.memoTable[e];return n||(n=this.memoTable[e]=new Ze),n}processFailure(e,n){if(this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures){let r=this.currentApplication();r&&(n=n.substituteParams(r.args)),this.recordFailure(n.toFailure(this.grammar),!1)}}recordFailure(e,n){let r=e.toKey();this.recordedFailures[r]?this.recordedFailures[r].isFluffy()&&!e.isFluffy()&&this.recordedFailures[r].clearFluffy():this.recordedFailures[r]=n?e.clone():e}recordFailures(e,n){Object.keys(e).forEach(r=>{this.recordFailure(e[r],n)})}cloneRecordedFailures(){if(!this.recordedFailures)return;let e=Object.create(null);return Object.keys(this.recordedFailures).forEach(n=>{e[n]=this.recordedFailures[n].clone()}),e}getRightmostFailurePosition(){return this.rightmostFailurePosition}_getRightmostFailureOffset(){return this.rightmostFailurePosition>=0?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(e,n){let r=this.memoTable[e];if(r&&n instanceof v){let s=r.memo[n.toMemoKey()];if(s&&s.traceEntry){let i=s.traceEntry.cloneWithExpr(n);return i.isMemoized=!0,i}}return null}getTraceEntry(e,n,r,s){if(n instanceof v){let i=this.currentApplication(),a=i?i.args:[];n=n.substituteParams(a)}return this.getMemoizedTraceEntry(e,n)||new de(this.input,e,this.inputStream.pos,n,r,s,this.trace)}isTracing(){return!!this.trace}hasNecessaryInfo(e){return this.trace&&!e.traceEntry?!1:this.recordedFailures&&this.inputStream.pos+e.rightmostFailureOffset===this.positionToRecordFailures?!!e.failuresAtRightmostPosition:!0}useMemoizedResult(e,n){this.trace&&this.trace.push(n.traceEntry);let r=this.inputStream.pos+n.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,r),this.recordedFailures&&this.positionToRecordFailures===r&&n.failuresAtRightmostPosition&&this.recordFailures(n.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,n.examinedLength+e),n.value?(this.inputStream.pos+=n.matchLength,this.pushBinding(n.value,e),!0):!1}eval(e){let{inputStream:n}=this,r=this._bindings.length,s=this.userData,i;this.recordedFailures&&(i=this.recordedFailures,this.recordedFailures=Object.create(null));let a=n.pos,l=this.maybeSkipSpacesBefore(e),o;this.trace&&(o=this.trace,this.trace=[]);let p=e.eval(this);if(this.trace){let u=this._bindings.slice(r),c=this.getTraceEntry(l,e,p,u);c.isImplicitSpaces=e===He,c.isRootNode=e===this.startExpr,o.push(c),this.trace=o}return p?this.recordedFailures&&n.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(u=>{this.recordedFailures[u].makeFluffy()}):(n.pos=a,this.truncateBindings(r),this.userData=s),this.recordedFailures&&this.recordFailures(i,!1),e===Ht&&this.skipSpaces(),p}getMatchResult(){this.grammar._setUpMatchState(this),this.eval(this.startExpr);let e;this.recordedFailures&&(e=Object.keys(this.recordedFailures).map(r=>this.recordedFailures[r]));let n=this._bindings[0];return n&&(n.grammar=this.grammar),new Ne(this.matcher,this.input,this.startExpr,n,this._bindingOffsets[0],this.rightmostFailurePosition,e)}getTrace(){this.trace=[];let e=this.getMatchResult(),n=this.trace[this.trace.length-1];return n.result=e,n}pushFailuresInfo(){this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this._recordedFailuresStack.push(this.recordedFailures)}popFailuresInfo(){this.rightmostFailurePosition=this._rightmostFailurePositionStack.pop(),this.recordedFailures=this._recordedFailuresStack.pop()}},et=class{constructor(e){this.grammar=e,this._memoTable=[],this._input="",this._isMemoTableStale=!1}_resetMemoTable(){this._memoTable=[],this._isMemoTableStale=!1}getInput(){return this._input}setInput(e){return this._input!==e&&this.replaceInputRange(0,this._input.length,e),this}replaceInputRange(e,n,r){let s=this._input,i=this._memoTable;if(e<0||e>s.length||n<0||n>s.length||e>n)throw new Error("Invalid indices: "+e+" and "+n);this._input=s.slice(0,e)+r+s.slice(n),this._input!==s&&i.length>0&&(this._isMemoTableStale=!0);let a=i.slice(n);i.length=e;for(let l=0;l<r.length;l++)i.push(void 0);for(let l of a)i.push(l);for(let l=0;l<e;l++){let o=i[l];o&&o.clearObsoleteEntries(l,e)}return this}match(e,n={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:n.incremental,tracing:!1})}trace(e,n={incremental:!0}){return this._match(this._getStartExpr(e),{incremental:n.incremental,tracing:!0})}_match(e,n={}){let r={tracing:!1,incremental:!0,positionToRecordFailures:void 0,...n};if(!r.incremental)this._resetMemoTable();else if(this._isMemoTableStale&&!this.grammar.supportsIncrementalParsing)throw On(this.grammar);let s=new Xe(this,e,r.positionToRecordFailures);return r.tracing?s.getTrace():s.getMatchResult()}_getStartExpr(e){let n=e||this.grammar.defaultStartRule;if(!n)throw new Error("Missing start rule argument -- the grammar has no default start rule.");let r=this.grammar.parseApplication(n);return new b([r,P])}},xe=[],tt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Re=class{constructor(e,n,r){this._node=e,this.source=n,this._baseInterval=r,e.isNonterminal()&&se(n===r),this._childWrappers=[]}_forgetMemoizedResultFor(e){delete this._node[this._semantics.attributeKeys[e]],this.children.forEach(n=>{n._forgetMemoizedResultFor(e)})}child(e){if(!(0<=e&&e<this._node.numChildren()))return;let n=this._childWrappers[e];if(!n){let r=this._node.childAt(e),s=this._node.childOffsets[e],i=this._baseInterval.subInterval(s,r.matchLength),a=r.isNonterminal()?i:this._baseInterval;n=this._childWrappers[e]=this._semantics.wrap(r,i,a)}return n}_children(){for(let e=0;e<this._node.numChildren();e++)this.child(e);return this._childWrappers}isIteration(){return this._node.isIteration()}isTerminal(){return this._node.isTerminal()}isNonterminal(){return this._node.isNonterminal()}isSyntactic(){return this.isNonterminal()&&this._node.isSyntactic()}isLexical(){return this.isNonterminal()&&this._node.isLexical()}isOptional(){return this._node.isOptional()}iteration(e){let n=e||[],r=n.map(a=>a._node),s=new Ee(r,[],-1,!1),i=this._semantics.wrap(s,null,null);return i._childWrappers=n,i}get children(){return this._children()}get ctorName(){return this._node.ctorName}get numChildren(){return this._node.numChildren()}get sourceString(){return this.source.contents}},$=class t{constructor(e,n){let r=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(n?n.Wrapper:Re){constructor(s,i,a){super(s,i,a),r.checkActionDictsIfHaventAlready(),this._semantics=r}toString(){return"[semantics wrapper for "+r.grammar.name+"]"}},this.super=n,n){if(!(e.equals(this.super.grammar)||e._inheritsFrom(this.super.grammar)))throw new Error("Cannot extend a semantics for grammar '"+this.super.grammar.name+"' for use with grammar '"+e.name+"' (not a sub-grammar)");this.operations=Object.create(this.super.operations),this.attributes=Object.create(this.super.attributes),this.attributeKeys=Object.create(null);for(let s in this.attributes)Object.defineProperty(this.attributeKeys,s,{value:wt(s)})}else this.operations=Object.create(null),this.attributes=Object.create(null),this.attributeKeys=Object.create(null)}toString(){return"[semantics for "+this.grammar.name+"]"}checkActionDictsIfHaventAlready(){this.checkedActionDicts||(this.checkActionDicts(),this.checkedActionDicts=!0)}checkActionDicts(){let e;for(e in this.operations)this.operations[e].checkActionDict(this.grammar);for(e in this.attributes)this.attributes[e].checkActionDict(this.grammar)}toRecipe(e){function n(s){return s.super!==t.BuiltInSemantics._getSemantics()}let r=`(function(g) {
`;if(n(this)){r+=" var semantics = "+this.super.toRecipe(!0)+"(g";let s=this.super.grammar,i=this.grammar;for(;i!==s;)r+=".superGrammar",i=i.superGrammar;r+=`);
`,r+=" return g.extendSemantics(semantics)"}else r+=" return g.createSemantics()";return["Operation","Attribute"].forEach(s=>{let i=this[s.toLowerCase()+"s"];Object.keys(i).forEach(a=>{let{actionDict:l,formals:o,builtInDefault:p}=i[a],u=a;o.length>0&&(u+="("+o.join(", ")+")");let c;n(this)&&this.super[s.toLowerCase()+"s"][a]?c="extend"+s:c="add"+s,r+=`
.`+c+"("+JSON.stringify(u)+", {";let h=[];Object.keys(l).forEach(f=>{if(l[f]!==p){let d=l[f].toString().trim();d=d.replace(/^.*\(/,"function("),h.push(`
`+JSON.stringify(f)+": "+d)}}),r+=h.join(",")+`
})`})}),r+=`;
})`,e||(r=`(function() {
var grammar = this.fromRecipe(`+this.grammar.toRecipe()+`);
var semantics = `+r+`(grammar);
return semantics;
});
`),r}addOperationOrAttribute(e,n,r){let s=e+"s",i=Ot(n,e),{name:a}=i,{formals:l}=i;this.assertNewName(a,e);let o=tr(e,a,c),p={_default:o};Object.keys(r).forEach(h=>{p[h]=r[h]});let u=e==="operation"?new pe(a,l,p,o):new _e(a,p,o);u.checkActionDict(this.grammar),this[s][a]=u;function c(...h){let f=this._semantics[s][a];if(arguments.length!==f.formals.length)throw new Error("Invalid number of arguments passed to "+a+" "+e+" (expected "+f.formals.length+", got "+arguments.length+")");let d=Object.create(null);for(let[I,k]of Object.entries(h)){let V=f.formals[I];d[V]=k}let g=this.args;this.args=d;let m=f.execute(this._semantics,this);return this.args=g,m}e==="operation"?(this.Wrapper.prototype[a]=c,this.Wrapper.prototype[a].toString=function(){return"["+a+" operation]"}):(Object.defineProperty(this.Wrapper.prototype,a,{get:c,configurable:!0}),Object.defineProperty(this.attributeKeys,a,{value:wt(a)}))}extendOperationOrAttribute(e,n,r){let s=e+"s";if(Ot(n,"attribute"),!(this.super&&n in this.super[s]))throw new Error("Cannot extend "+e+" '"+n+"': did not inherit an "+e+" with that name");if(tt(this[s],n))throw new Error("Cannot extend "+e+" '"+n+"' again");let i=this[s][n].formals,a=this[s][n].actionDict,l=Object.create(a);Object.keys(r).forEach(o=>{l[o]=r[o]}),this[s][n]=e==="operation"?new pe(n,i,l):new _e(n,l),this[s][n].checkActionDict(this.grammar)}assertNewName(e,n){if(tt(Re.prototype,e))throw new Error("Cannot add "+n+" '"+e+"': that's a reserved name");if(e in this.operations)throw new Error("Cannot add "+n+" '"+e+"': an operation with that name already exists");if(e in this.attributes)throw new Error("Cannot add "+n+" '"+e+"': an attribute with that name already exists")}wrap(e,n,r){let s=r||n;return e instanceof this.Wrapper?e:new this.Wrapper(e,n,s)}};function Ot(t,e){if(!$.prototypeGrammar)return se(t.indexOf("(")===-1),{name:t,formals:[]};let n=$.prototypeGrammar.match(t,e==="operation"?"OperationSignature":"AttributeSignature");if(n.failed())throw new Error(n.message);return $.prototypeGrammarSemantics(n).parse()}function tr(t,e,n){return function(...r){let i=(this._semantics.operations[e]||this._semantics.attributes[e]).formals.map(a=>this.args[a]);if(!this.isIteration()&&r.length===1)return n.apply(r[0],i);throw jn(this.ctorName,e,t,xe)}}$.createSemantics=function(t,e){let n=new $(t,e!==void 0?e:$.BuiltInSemantics._getSemantics()),r=function(i){if(!(i instanceof Ne))throw new TypeError("Semantics expected a MatchResult, but got "+rt(i));if(i.failed())throw new TypeError("cannot apply Semantics to "+i.toString());let a=i._cst;if(a.grammar!==t)throw new Error("Cannot use a MatchResult from grammar '"+a.grammar.name+"' with a semantics for '"+t.name+"'");let l=new fe(i.input);return n.wrap(a,l.interval(i._cstOffset,i.input.length))};return r.addOperation=function(s,i){return n.addOperationOrAttribute("operation",s,i),r},r.extendOperation=function(s,i){return n.extendOperationOrAttribute("operation",s,i),r},r.addAttribute=function(s,i){return n.addOperationOrAttribute("attribute",s,i),r},r.extendAttribute=function(s,i){return n.extendOperationOrAttribute("attribute",s,i),r},r._getActionDict=function(s){let i=n.operations[s]||n.attributes[s];if(!i)throw new Error('"'+s+'" is not a valid operation or attribute name in this semantics for "'+t.name+'"');return i.actionDict},r._remove=function(s){let i;return s in n.operations?(i=n.operations[s],delete n.operations[s]):s in n.attributes&&(i=n.attributes[s],delete n.attributes[s]),delete n.Wrapper.prototype[s],i},r.getOperationNames=function(){return Object.keys(n.operations)},r.getAttributeNames=function(){return Object.keys(n.attributes)},r.getGrammar=function(){return n.grammar},r.toRecipe=function(s){return n.toRecipe(s)},r.toString=n.toString.bind(n),r._getSemantics=function(){return n},r};var pe=class{constructor(e,n,r,s){this.name=e,this.formals=n,this.actionDict=r,this.builtInDefault=s}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,n){try{let{ctorName:r}=n._node,s=this.actionDict[r];return s?(xe.push([this,r]),s.apply(n,n._children())):n.isNonterminal()&&(s=this.actionDict._nonterminal,s)?(xe.push([this,"_nonterminal",r]),s.apply(n,n._children())):(xe.push([this,"default action",r]),this.actionDict._default.apply(n,n._children()))}finally{xe.pop()}}};pe.prototype.typeName="operation";var _e=class extends pe{constructor(e,n,r){super(e,[],n,r)}execute(e,n){let r=n._node,s=e.attributeKeys[this.name];return tt(r,s)||(r[s]=pe.prototype.execute.call(this,e,n)),r[s]}};_e.prototype.typeName="attribute";var Nt=["_iter","_terminal","_nonterminal","_default"];function Lt(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}var nr=t=>t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"),Qt,Vt,D=class t{constructor(e,n,r,s){if(this.name=e,this.superGrammar=n,this.rules=r,s){if(!(s in r))throw new Error("Invalid start rule: '"+s+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=s}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new et(this)}isBuiltIn(){return this===t.ProtoBuiltInRules||this===t.BuiltInRules}equals(e){if(this===e)return!0;if(e==null||this.name!==e.name||this.defaultStartRule!==e.defaultStartRule||!(this.superGrammar===e.superGrammar||this.superGrammar.equals(e.superGrammar)))return!1;let n=Lt(this),r=Lt(e);return n.length===r.length&&n.every((s,i)=>s.description===r[i].description&&s.formals.join(",")===r[i].formals.join(",")&&s.body.toString()===r[i].body.toString())}match(e,n){let r=this.matcher();return r.replaceInputRange(0,0,e),r.match(n)}trace(e,n){let r=this.matcher();return r.replaceInputRange(0,0,e),r.trace(n)}createSemantics(){return $.createSemantics(this)}extendSemantics(e){return $.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,n,r){let s=[];for(let i in r){let a=r[i];if(!Nt.includes(i)&&!(i in this.rules)){s.push(`'${i}' is not a valid semantic action for '${this.name}'`);continue}if(typeof a!="function"){s.push(`'${i}' must be a function in an action dictionary for '${this.name}'`);continue}let o=a.length,p=this._topDownActionArity(i);if(o!==p){let u;i==="_iter"||i==="_nonterminal"?u=`it should use a rest parameter, e.g. \`${i}(...children) {}\`. NOTE: this is new in Ohm v16 \u2014 see https://ohmjs.org/d/ati for details.`:u=`expected ${p}, got ${o}`,s.push(`Semantic action '${i}' has the wrong arity: ${u}`)}}if(s.length>0){let i=s.map(l=>"- "+l),a=new Error([`Found errors in the action dictionary of the '${n}' ${e}:`,...i].join(`
`));throw a.problems=s,a}}_topDownActionArity(e){return Nt.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let n=this.superGrammar;for(;n;){if(n.equals(e,!0))return!0;n=n.superGrammar}return!1}toRecipe(e=void 0){let n={};this.source&&(n.source=this.source.contents);let r=null;this.defaultStartRule&&(r=this.defaultStartRule);let s={};Object.keys(this.rules).forEach(l=>{let o=this.rules[l],{body:p}=o,u=!this.superGrammar||!this.superGrammar.rules[l],c;u?c="define":c=p instanceof le?"extend":"override";let h={};if(o.source&&this.source){let g=o.source.relativeTo(this.source);h.sourceInterval=[g.startIdx,g.endIdx]}let f=u?o.description:null,d=p.outputRecipe(o.formals,this.source);s[l]=[c,h,f,o.formals,d]});let i="null";e?i=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(i=this.superGrammar.toRecipe());let a=[...["grammar",n,this.name].map(JSON.stringify),i,...[r,s].map(JSON.stringify)];return nr(`[${a.join(",")}]`)}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){let e=new he;e.append("{");let n=!0;for(let r in this.rules){let{body:s}=this.rules[r];n?n=!1:e.append(","),e.append(`
`),e.append(" "),this.addSemanticActionTemplate(r,s,e)}return e.append(`
}`),e.contents()}addSemanticActionTemplate(e,n,r){r.append(e),r.append(": function(");let s=this._topDownActionArity(e);r.append(ke("_",s).join(", ")),r.append(`) {
`),r.append(" }")}parseApplication(e){let n;if(e.indexOf("<")===-1)n=new v(e);else{let s=Qt.match(e,"Base_application");n=Vt(s,{})}if(!(n.ruleName in this.rules))throw jt(n.ruleName,this.name);let{formals:r}=this.rules[n.ruleName];if(r.length!==n.args.length){let{source:s}=this.rules[n.ruleName];throw Mt(n.ruleName,r.length,n.args.length,s)}return n}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}};D.ProtoBuiltInRules=new D("ProtoBuiltInRules",void 0,{any:{body:T,formals:[],description:"any character",primitive:!0},end:{body:P,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new Ce(new N(0)),formals:["str"],primitive:!0},lower:{body:new w("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new w("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new w("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new K(new v("space")),formals:[]},space:{body:new O("\0"," "),formals:[],description:"a space"}});D.initApplicationParser=function(t,e){Qt=t,Vt=e};var Te=class{constructor(e){this.name=e}sourceInterval(e,n){return this.source.subInterval(e,n-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar(this.name==="BuiltInRules"?D.ProtoBuiltInRules:D.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,n){let r=this.ensureSuperGrammar().rules[e];if(!r)throw Nn(e,this.superGrammar.name,n);return r}installOverriddenOrExtendedRule(e,n,r,s){let i=Ke(n);if(i.length>0)throw St(e,i,s);let a=this.ensureSuperGrammar().rules[e],l=a.formals,o=l?l.length:0;if(n.length!==o)throw Mt(e,o,n.length,s);return this.install(e,n,r,a.description,s)}install(e,n,r,s,i,a=!1){return this.rules[e]={body:r.introduceParams(n),formals:n,description:s,source:i,primitive:a},this}withSuperGrammar(e){if(this.superGrammar)throw new Error("the super grammar of a GrammarDecl cannot be set more than once");return this.superGrammar=e,this.rules=Object.create(e.rules),e.isBuiltIn()||(this.defaultStartRule=e.defaultStartRule),this}withDefaultStartRule(e){return this.defaultStartRule=e,this}withSource(e){return this.source=new fe(e).interval(0,e.length),this}build(){let e=new D(this.name,this.ensureSuperGrammar(),this.rules,this.defaultStartRule);e._matchStateInitializer=e.superGrammar._matchStateInitializer,e.supportsIncrementalParsing=e.superGrammar.supportsIncrementalParsing;let n=[],r=!1;return Object.keys(e.rules).forEach(s=>{let{body:i}=e.rules[s];try{i.assertChoicesHaveUniformArity(s)}catch(a){n.push(a)}try{i.assertAllApplicationsAreValid(s,e)}catch(a){n.push(a),r=!0}}),r||Object.keys(e.rules).forEach(s=>{let{body:i}=e.rules[s];try{i.assertIteratedExprsAreNotNullable(e,[])}catch(a){n.push(a)}}),n.length>0&&Mn(n),this.source&&(e.source=this.source),e}define(e,n,r,s,i,a){if(this.ensureSuperGrammar(),this.superGrammar.rules[e])throw xt(e,this.name,this.superGrammar.name,i);if(this.rules[e])throw xt(e,this.name,this.name,i);let l=Ke(n);if(l.length>0)throw St(e,l,i);return this.install(e,n,r,s,i,a)}override(e,n,r,s,i){return this.ensureSuperGrammarRuleForOverriding(e,i),this.installOverriddenOrExtendedRule(e,n,r,i),this}extend(e,n,r,s,i){if(!this.ensureSuperGrammar().rules[e])throw Ln(e,this.superGrammar.name,i);let l=new le(this.superGrammar,e,r);return l.source=r.source,this.installOverriddenOrExtendedRule(e,n,l,i),this}},me=class{constructor(){this.currentDecl=null,this.currentRuleName=null}newGrammar(e){return new Te(e)}grammar(e,n,r,s,i){let a=new Te(n);return r&&a.withSuperGrammar(r instanceof D?r:this.fromRecipe(r)),s&&a.withDefaultStartRule(s),e&&e.source&&a.withSource(e.source),this.currentDecl=a,Object.keys(i).forEach(l=>{this.currentRuleName=l;let o=i[l],p=o[0],u=o[1],c=o[2],h=o[3],f=this.fromRecipe(o[4]),d;a.source&&u&&u.sourceInterval&&(d=a.source.subInterval(u.sourceInterval[0],u.sourceInterval[1]-u.sourceInterval[0])),a[p](l,h,f,c,d)}),this.currentRuleName=this.currentDecl=null,a.build()}terminal(e){return new A(e)}range(e,n){return new O(e,n)}param(e){return new N(e)}alt(...e){let n=[];for(let r of e)r instanceof y||(r=this.fromRecipe(r)),r instanceof x?n=n.concat(r.terms):n.push(r);return n.length===1?n[0]:new x(n)}seq(...e){let n=[];for(let r of e)r instanceof y||(r=this.fromRecipe(r)),r instanceof b?n=n.concat(r.factors):n.push(r);return n.length===1?n[0]:new b(n)}star(e){return e instanceof y||(e=this.fromRecipe(e)),new K(e)}plus(e){return e instanceof y||(e=this.fromRecipe(e)),new ee(e)}opt(e){return e instanceof y||(e=this.fromRecipe(e)),new U(e)}not(e){return e instanceof y||(e=this.fromRecipe(e)),new E(e)}lookahead(e){return e instanceof y||(e=this.fromRecipe(e)),new C(e)}lex(e){return e instanceof y||(e=this.fromRecipe(e)),new R(e)}app(e,n){return n&&n.length>0&&(n=n.map(function(r){return r instanceof y?r:this.fromRecipe(r)},this)),new v(e,n)}splice(e,n){return new ue(this.currentDecl.superGrammar,this.currentRuleName,e.map(r=>this.fromRecipe(r)),n.map(r=>this.fromRecipe(r)))}fromRecipe(e){let n=e[0]==="grammar"?e.slice(1):e.slice(2),r=this[e[0]](...n),s=e[1];return s&&s.sourceInterval&&this.currentDecl&&r.withSource(this.currentDecl.sourceInterval(...s.sourceInterval)),r}};function Fe(t){return typeof t=="function"?t.call(new me):(typeof t=="string"&&(t=JSON.parse(t)),new me().fromRecipe(t))}var ot=Fe(["grammar",{source:`BuiltInRules {
alnum (an alpha-numeric character)
= letter
| digit
letter (a letter)
= lower
| upper
| unicodeLtmo
digit (a digit)
= "0".."9"
hexDigit (a hexadecimal digit)
= digit
| "a".."f"
| "A".."F"
ListOf<elem, sep>
= NonemptyListOf<elem, sep>
| EmptyListOf<elem, sep>
NonemptyListOf<elem, sep>
= elem (sep elem)*
EmptyListOf<elem, sep>
= /* nothing */
listOf<elem, sep>
= nonemptyListOf<elem, sep>
| emptyListOf<elem, sep>
nonemptyListOf<elem, sep>
= elem (sep elem)*
emptyListOf<elem, sep>
= /* nothing */
// Allows a syntactic rule application within a lexical context.
applySyntactic<app> = app
}`},"BuiltInRules",null,null,{alnum:["define",{sourceInterval:[18,78]},"an alpha-numeric character",[],["alt",{sourceInterval:[60,78]},["app",{sourceInterval:[60,66]},"letter",[]],["app",{sourceInterval:[73,78]},"digit",[]]]],letter:["define",{sourceInterval:[82,142]},"a letter",[],["alt",{sourceInterval:[107,142]},["app",{sourceInterval:[107,112]},"lower",[]],["app",{sourceInterval:[119,124]},"upper",[]],["app",{sourceInterval:[131,142]},"unicodeLtmo",[]]]],digit:["define",{sourceInterval:[146,177]},"a digit",[],["range",{sourceInterval:[169,177]},"0","9"]],hexDigit:["define",{sourceInterval:[181,254]},"a hexadecimal digit",[],["alt",{sourceInterval:[219,254]},["app",{sourceInterval:[219,224]},"digit",[]],["range",{sourceInterval:[231,239]},"a","f"],["range",{sourceInterval:[246,254]},"A","F"]]],ListOf:["define",{sourceInterval:[258,336]},null,["elem","sep"],["alt",{sourceInterval:[282,336]},["app",{sourceInterval:[282,307]},"NonemptyListOf",[["param",{sourceInterval:[297,301]},0],["param",{sourceInterval:[303,306]},1]]],["app",{sourceInterval:[314,336]},"EmptyListOf",[["param",{sourceInterval:[326,330]},0],["param",{sourceInterval:[332,335]},1]]]]],NonemptyListOf:["define",{sourceInterval:[340,388]},null,["elem","sep"],["seq",{sourceInterval:[372,388]},["param",{sourceInterval:[372,376]},0],["star",{sourceInterval:[377,388]},["seq",{sourceInterval:[378,386]},["param",{sourceInterval:[378,381]},1],["param",{sourceInterval:[382,386]},0]]]]],EmptyListOf:["define",{sourceInterval:[392,434]},null,["elem","sep"],["seq",{sourceInterval:[438,438]}]],listOf:["define",{sourceInterval:[438,516]},null,["elem","sep"],["alt",{sourceInterval:[462,516]},["app",{sourceInterval:[462,487]},"nonemptyListOf",[["param",{sourceInterval:[477,481]},0],["param",{sourceInterval:[483,486]},1]]],["app",{sourceInterval:[494,516]},"emptyListOf",[["param",{sourceInterval:[506,510]},0],["param",{sourceInterval:[512,515]},1]]]]],nonemptyListOf:["define",{sourceInterval:[520,568]},null,["elem","sep"],["seq",{sourceInterval:[552,568]},["param",{sourceInterval:[552,556]},0],["star",{sourceInterval:[557,568]},["seq",{sourceInterval:[558,566]},["param",{sourceInterval:[558,561]},1],["param",{sourceInterval:[562,566]},0]]]]],emptyListOf:["define",{sourceInterval:[572,682]},null,["elem","sep"],["seq",{sourceInterval:[685,685]}]],applySyntactic:["define",{sourceInterval:[685,710]},null,["app"],["param",{sourceInterval:[707,710]},0]]}]);D.BuiltInRules=ot;Gn(D.BuiltInRules);var $e=Fe(["grammar",{source:`Ohm {
Grammars
= Grammar*
Grammar
= ident SuperGrammar? "{" Rule* "}"
SuperGrammar
= "<:" ident
Rule
= ident Formals? ruleDescr? "=" RuleBody -- define
| ident Formals? ":=" OverrideRuleBody -- override
| ident Formals? "+=" RuleBody -- extend
RuleBody
= "|"? NonemptyListOf<TopLevelTerm, "|">
TopLevelTerm
= Seq caseName -- inline
| Seq
OverrideRuleBody
= "|"? NonemptyListOf<OverrideTopLevelTerm, "|">
OverrideTopLevelTerm
= "..." -- superSplice
| TopLevelTerm
Formals
= "<" ListOf<ident, ","> ">"
Params
= "<" ListOf<Seq, ","> ">"
Alt
= NonemptyListOf<Seq, "|">
Seq
= Iter*
Iter
= Pred "*" -- star
| Pred "+" -- plus
| Pred "?" -- opt
| Pred
Pred
= "~" Lex -- not
| "&" Lex -- lookahead
| Lex
Lex
= "#" Base -- lex
| Base
Base
= ident Params? ~(ruleDescr? "=" | ":=" | "+=") -- application
| oneCharTerminal ".." oneCharTerminal -- range
| terminal -- terminal
| "(" Alt ")" -- paren
ruleDescr (a rule description)
= "(" ruleDescrText ")"
ruleDescrText
= (~")" any)*
caseName
= "--" (~"\\n" space)* name (~"\\n" space)* ("\\n" | &"}")
name (a name)
= nameFirst nameRest*
nameFirst
= "_"
| letter
nameRest
= "_"
| alnum
ident (an identifier)
= name
terminal
= "\\"" terminalChar* "\\""
oneCharTerminal
= "\\"" terminalChar "\\""
terminalChar
= escapeChar
| ~"\\\\" ~"\\"" ~"\\n" "\\u{0}".."\\u{10FFFF}"
escapeChar (an escape sequence)
= "\\\\\\\\" -- backslash
| "\\\\\\"" -- doubleQuote
| "\\\\\\'" -- singleQuote
| "\\\\b" -- backspace
| "\\\\n" -- lineFeed
| "\\\\r" -- carriageReturn
| "\\\\t" -- tab
| "\\\\u{" hexDigit hexDigit? hexDigit?
hexDigit? hexDigit? hexDigit? "}" -- unicodeCodePoint
| "\\\\u" hexDigit hexDigit hexDigit hexDigit -- unicodeEscape
| "\\\\x" hexDigit hexDigit -- hexEscape
space
+= comment
comment
= "//" (~"\\n" any)* &("\\n" | end) -- singleLine
| "/*" (~"*/" any)* "*/" -- multiLine
tokens = token*
token = caseName | comment | ident | operator | punctuation | terminal | any
operator = "<:" | "=" | ":=" | "+=" | "*" | "+" | "?" | "~" | "&"
punctuation = "<" | ">" | "," | "--"
}`},"Ohm",null,"Grammars",{Grammars:["define",{sourceInterval:[9,32]},null,[],["star",{sourceInterval:[24,32]},["app",{sourceInterval:[24,31]},"Grammar",[]]]],Grammar:["define",{sourceInterval:[36,83]},null,[],["seq",{sourceInterval:[50,83]},["app",{sourceInterval:[50,55]},"ident",[]],["opt",{sourceInterval:[56,69]},["app",{sourceInterval:[56,68]},"SuperGrammar",[]]],["terminal",{sourceInterval:[70,73]},"{"],["star",{sourceInterval:[74,79]},["app",{sourceInterval:[74,78]},"Rule",[]]],["terminal",{sourceInterval:[80,83]},"}"]]],SuperGrammar:["define",{sourceInterval:[87,116]},null,[],["seq",{sourceInterval:[106,116]},["terminal",{sourceInterval:[106,110]},"<:"],["app",{sourceInterval:[111,116]},"ident",[]]]],Rule_define:["define",{sourceInterval:[131,181]},null,[],["seq",{sourceInterval:[131,170]},["app",{sourceInterval:[131,136]},"ident",[]],["opt",{sourceInterval:[137,145]},["app",{sourceInterval:[137,144]},"Formals",[]]],["opt",{sourceInterval:[146,156]},["app",{sourceInterval:[146,155]},"ruleDescr",[]]],["terminal",{sourceInterval:[157,160]},"="],["app",{sourceInterval:[162,170]},"RuleBody",[]]]],Rule_override:["define",{sourceInterval:[188,248]},null,[],["seq",{sourceInterval:[188,235]},["app",{sourceInterval:[188,193]},"ident",[]],["opt",{sourceInterval:[194,202]},["app",{sourceInterval:[194,201]},"Formals",[]]],["terminal",{sourceInterval:[214,218]},":="],["app",{sourceInterval:[219,235]},"OverrideRuleBody",[]]]],Rule_extend:["define",{sourceInterval:[255,305]},null,[],["seq",{sourceInterval:[255,294]},["app",{sourceInterval:[255,260]},"ident",[]],["opt",{sourceInterval:[261,269]},["app",{sourceInterval:[261,268]},"Formals",[]]],["terminal",{sourceInterval:[281,285]},"+="],["app",{sourceInterval:[286,294]},"RuleBody",[]]]],Rule:["define",{sourceInterval:[120,305]},null,[],["alt",{sourceInterval:[131,305]},["app",{sourceInterval:[131,170]},"Rule_define",[]],["app",{sourceInterval:[188,235]},"Rule_override",[]],["app",{sourceInterval:[255,294]},"Rule_extend",[]]]],RuleBody:["define",{sourceInterval:[309,362]},null,[],["seq",{sourceInterval:[324,362]},["opt",{sourceInterval:[324,328]},["terminal",{sourceInterval:[324,327]},"|"]],["app",{sourceInterval:[329,362]},"NonemptyListOf",[["app",{sourceInterval:[344,356]},"TopLevelTerm",[]],["terminal",{sourceInterval:[358,361]},"|"]]]]],TopLevelTerm_inline:["define",{sourceInterval:[385,408]},null,[],["seq",{sourceInterval:[385,397]},["app",{sourceInterval:[385,388]},"Seq",[]],["app",{sourceInterval:[389,397]},"caseName",[]]]],TopLevelTerm:["define",{sourceInterval:[366,418]},null,[],["alt",{sourceInterval:[385,418]},["app",{sourceInterval:[385,397]},"TopLevelTerm_inline",[]],["app",{sourceInterval:[415,418]},"Seq",[]]]],OverrideRuleBody:["define",{sourceInterval:[422,491]},null,[],["seq",{sourceInterval:[445,491]},["opt",{sourceInterval:[445,449]},["terminal",{sourceInterval:[445,448]},"|"]],["app",{sourceInterval:[450,491]},"NonemptyListOf",[["app",{sourceInterval:[465,485]},"OverrideTopLevelTerm",[]],["terminal",{sourceInterval:[487,490]},"|"]]]]],OverrideTopLevelTerm_superSplice:["define",{sourceInterval:[522,543]},null,[],["terminal",{sourceInterval:[522,527]},"..."]],OverrideTopLevelTerm:["define",{sourceInterval:[495,562]},null,[],["alt",{sourceInterval:[522,562]},["app",{sourceInterval:[522,527]},"OverrideTopLevelTerm_superSplice",[]],["app",{sourceInterval:[550,562]},"TopLevelTerm",[]]]],Formals:["define",{sourceInterval:[566,606]},null,[],["seq",{sourceInterval:[580,606]},["terminal",{sourceInterval:[580,583]},"<"],["app",{sourceInterval:[584,602]},"ListOf",[["app",{sourceInterval:[591,596]},"ident",[]],["terminal",{sourceInterval:[598,601]},","]]],["terminal",{sourceInterval:[603,606]},">"]]],Params:["define",{sourceInterval:[610,647]},null,[],["seq",{sourceInterval:[623,647]},["terminal",{sourceInterval:[623,626]},"<"],["app",{sourceInterval:[627,643]},"ListOf",[["app",{sourceInterval:[634,637]},"Seq",[]],["terminal",{sourceInterval:[639,642]},","]]],["terminal",{sourceInterval:[644,647]},">"]]],Alt:["define",{sourceInterval:[651,685]},null,[],["app",{sourceInterval:[661,685]},"NonemptyListOf",[["app",{sourceInterval:[676,679]},"Seq",[]],["terminal",{sourceInterval:[681,684]},"|"]]]],Seq:["define",{sourceInterval:[689,704]},null,[],["star",{sourceInterval:[699,704]},["app",{sourceInterval:[699,703]},"Iter",[]]]],Iter_star:["define",{sourceInterval:[719,736]},null,[],["seq",{sourceInterval:[719,727]},["app",{sourceInterval:[719,723]},"Pred",[]],["terminal",{sourceInterval:[724,727]},"*"]]],Iter_plus:["define",{sourceInterval:[743,760]},null,[],["seq",{sourceInterval:[743,751]},["app",{sourceInterval:[743,747]},"Pred",[]],["terminal",{sourceInterval:[748,751]},"+"]]],Iter_opt:["define",{sourceInterval:[767,783]},null,[],["seq",{sourceInterval:[767,775]},["app",{sourceInterval:[767,771]},"Pred",[]],["terminal",{sourceInterval:[772,775]},"?"]]],Iter:["define",{sourceInterval:[708,794]},null,[],["alt",{sourceInterval:[719,794]},["app",{sourceInterval:[719,727]},"Iter_star",[]],["app",{sourceInterval:[743,751]},"Iter_plus",[]],["app",{sourceInterval:[767,775]},"Iter_opt",[]],["app",{sourceInterval:[790,794]},"Pred",[]]]],Pred_not:["define",{sourceInterval:[809,824]},null,[],["seq",{sourceInterval:[809,816]},["terminal",{sourceInterval:[809,812]},"~"],["app",{sourceInterval:[813,816]},"Lex",[]]]],Pred_lookahead:["define",{sourceInterval:[831,852]},null,[],["seq",{sourceInterval:[831,838]},["terminal",{sourceInterval:[831,834]},"&"],["app",{sourceInterval:[835,838]},"Lex",[]]]],Pred:["define",{sourceInterval:[798,862]},null,[],["alt",{sourceInterval:[809,862]},["app",{sourceInterval:[809,816]},"Pred_not",[]],["app",{sourceInterval:[831,838]},"Pred_lookahead",[]],["app",{sourceInterval:[859,862]},"Lex",[]]]],Lex_lex:["define",{sourceInterval:[876,892]},null,[],["seq",{sourceInterval:[876,884]},["terminal",{sourceInterval:[876,879]},"#"],["app",{sourceInterval:[880,884]},"Base",[]]]],Lex:["define",{sourceInterval:[866,903]},null,[],["alt",{sourceInterval:[876,903]},["app",{sourceInterval:[876,884]},"Lex_lex",[]],["app",{sourceInterval:[899,903]},"Base",[]]]],Base_application:["define",{sourceInterval:[918,979]},null,[],["seq",{sourceInterval:[918,963]},["app",{sourceInterval:[918,923]},"ident",[]],["opt",{sourceInterval:[924,931]},["app",{sourceInterval:[924,930]},"Params",[]]],["not",{sourceInterval:[932,963]},["alt",{sourceInterval:[934,962]},["seq",{sourceInterval:[934,948]},["opt",{sourceInterval:[934,944]},["app",{sourceInterval:[934,943]},"ruleDescr",[]]],["terminal",{sourceInterval:[945,948]},"="]],["terminal",{sourceInterval:[951,955]},":="],["terminal",{sourceInterval:[958,962]},"+="]]]]],Base_range:["define",{sourceInterval:[986,1041]},null,[],["seq",{sourceInterval:[986,1022]},["app",{sourceInterval:[986,1001]},"oneCharTerminal",[]],["terminal",{sourceInterval:[1002,1006]},".."],["app",{sourceInterval:[1007,1022]},"oneCharTerminal",[]]]],Base_terminal:["define",{sourceInterval:[1048,1106]},null,[],["app",{sourceInterval:[1048,1056]},"terminal",[]]],Base_paren:["define",{sourceInterval:[1113,1168]},null,[],["seq",{sourceInterval:[1113,1124]},["terminal",{sourceInterval:[1113,1116]},"("],["app",{sourceInterval:[1117,1120]},"Alt",[]],["terminal",{sourceInterval:[1121,1124]},")"]]],Base:["define",{sourceInterval:[907,1168]},null,[],["alt",{sourceInterval:[918,1168]},["app",{sourceInterval:[918,963]},"Base_application",[]],["app",{sourceInterval:[986,1022]},"Base_range",[]],["app",{sourceInterval:[1048,1056]},"Base_terminal",[]],["app",{sourceInterval:[1113,1124]},"Base_paren",[]]]],ruleDescr:["define",{sourceInterval:[1172,1231]},"a rule description",[],["seq",{sourceInterval:[1210,1231]},["terminal",{sourceInterval:[1210,1213]},"("],["app",{sourceInterval:[1214,1227]},"ruleDescrText",[]],["terminal",{sourceInterval:[1228,1231]},")"]]],ruleDescrText:["define",{sourceInterval:[1235,1266]},null,[],["star",{sourceInterval:[1255,1266]},["seq",{sourceInterval:[1256,1264]},["not",{sourceInterval:[1256,1260]},["terminal",{sourceInterval:[1257,1260]},")"]],["app",{sourceInterval:[1261,1264]},"any",[]]]]],caseName:["define",{sourceInterval:[1270,1338]},null,[],["seq",{sourceInterval:[1285,1338]},["terminal",{sourceInterval:[1285,1289]},"--"],["star",{sourceInterval:[1290,1304]},["seq",{sourceInterval:[1291,1302]},["not",{sourceInterval:[1291,1296]},["terminal",{sourceInterval:[1292,1296]},`
`]],["app",{sourceInterval:[1297,1302]},"space",[]]]],["app",{sourceInterval:[1305,1309]},"name",[]],["star",{sourceInterval:[1310,1324]},["seq",{sourceInterval:[1311,1322]},["not",{sourceInterval:[1311,1316]},["terminal",{sourceInterval:[1312,1316]},`
`]],["app",{sourceInterval:[1317,1322]},"space",[]]]],["alt",{sourceInterval:[1326,1337]},["terminal",{sourceInterval:[1326,1330]},`
`],["lookahead",{sourceInterval:[1333,1337]},["terminal",{sourceInterval:[1334,1337]},"}"]]]]],name:["define",{sourceInterval:[1342,1382]},"a name",[],["seq",{sourceInterval:[1363,1382]},["app",{sourceInterval:[1363,1372]},"nameFirst",[]],["star",{sourceInterval:[1373,1382]},["app",{sourceInterval:[1373,1381]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[1386,1418]},null,[],["alt",{sourceInterval:[1402,1418]},["terminal",{sourceInterval:[1402,1405]},"_"],["app",{sourceInterval:[1412,1418]},"letter",[]]]],nameRest:["define",{sourceInterval:[1422,1452]},null,[],["alt",{sourceInterval:[1437,1452]},["terminal",{sourceInterval:[1437,1440]},"_"],["app",{sourceInterval:[1447,1452]},"alnum",[]]]],ident:["define",{sourceInterval:[1456,1489]},"an identifier",[],["app",{sourceInterval:[1485,1489]},"name",[]]],terminal:["define",{sourceInterval:[1493,1531]},null,[],["seq",{sourceInterval:[1508,1531]},["terminal",{sourceInterval:[1508,1512]},'"'],["star",{sourceInterval:[1513,1526]},["app",{sourceInterval:[1513,1525]},"terminalChar",[]]],["terminal",{sourceInterval:[1527,1531]},'"']]],oneCharTerminal:["define",{sourceInterval:[1535,1579]},null,[],["seq",{sourceInterval:[1557,1579]},["terminal",{sourceInterval:[1557,1561]},'"'],["app",{sourceInterval:[1562,1574]},"terminalChar",[]],["terminal",{sourceInterval:[1575,1579]},'"']]],terminalChar:["define",{sourceInterval:[1583,1660]},null,[],["alt",{sourceInterval:[1602,1660]},["app",{sourceInterval:[1602,1612]},"escapeChar",[]],["seq",{sourceInterval:[1621,1660]},["not",{sourceInterval:[1621,1626]},["terminal",{sourceInterval:[1622,1626]},"\\"]],["not",{sourceInterval:[1627,1632]},["terminal",{sourceInterval:[1628,1632]},'"']],["not",{sourceInterval:[1633,1638]},["terminal",{sourceInterval:[1634,1638]},`
`]],["range",{sourceInterval:[1639,1660]},"\0","\u{10FFFF}"]]]],escapeChar_backslash:["define",{sourceInterval:[1703,1758]},null,[],["terminal",{sourceInterval:[1703,1709]},"\\\\"]],escapeChar_doubleQuote:["define",{sourceInterval:[1765,1822]},null,[],["terminal",{sourceInterval:[1765,1771]},'\\"']],escapeChar_singleQuote:["define",{sourceInterval:[1829,1886]},null,[],["terminal",{sourceInterval:[1829,1835]},"\\'"]],escapeChar_backspace:["define",{sourceInterval:[1893,1948]},null,[],["terminal",{sourceInterval:[1893,1898]},"\\b"]],escapeChar_lineFeed:["define",{sourceInterval:[1955,2009]},null,[],["terminal",{sourceInterval:[1955,1960]},"\\n"]],escapeChar_carriageReturn:["define",{sourceInterval:[2016,2076]},null,[],["terminal",{sourceInterval:[2016,2021]},"\\r"]],escapeChar_tab:["define",{sourceInterval:[2083,2132]},null,[],["terminal",{sourceInterval:[2083,2088]},"\\t"]],escapeChar_unicodeCodePoint:["define",{sourceInterval:[2139,2243]},null,[],["seq",{sourceInterval:[2139,2221]},["terminal",{sourceInterval:[2139,2145]},"\\u{"],["app",{sourceInterval:[2146,2154]},"hexDigit",[]],["opt",{sourceInterval:[2155,2164]},["app",{sourceInterval:[2155,2163]},"hexDigit",[]]],["opt",{sourceInterval:[2165,2174]},["app",{sourceInterval:[2165,2173]},"hexDigit",[]]],["opt",{sourceInterval:[2188,2197]},["app",{sourceInterval:[2188,2196]},"hexDigit",[]]],["opt",{sourceInterval:[2198,2207]},["app",{sourceInterval:[2198,2206]},"hexDigit",[]]],["opt",{sourceInterval:[2208,2217]},["app",{sourceInterval:[2208,2216]},"hexDigit",[]]],["terminal",{sourceInterval:[2218,2221]},"}"]]],escapeChar_unicodeEscape:["define",{sourceInterval:[2250,2309]},null,[],["seq",{sourceInterval:[2250,2291]},["terminal",{sourceInterval:[2250,2255]},"\\u"],["app",{sourceInterval:[2256,2264]},"hexDigit",[]],["app",{sourceInterval:[2265,2273]},"hexDigit",[]],["app",{sourceInterval:[2274,2282]},"hexDigit",[]],["app",{sourceInterval:[2283,2291]},"hexDigit",[]]]],escapeChar_hexEscape:["define",{sourceInterval:[2316,2371]},null,[],["seq",{sourceInterval:[2316,2339]},["terminal",{sourceInterval:[2316,2321]},"\\x"],["app",{sourceInterval:[2322,2330]},"hexDigit",[]],["app",{sourceInterval:[2331,2339]},"hexDigit",[]]]],escapeChar:["define",{sourceInterval:[1664,2371]},"an escape sequence",[],["alt",{sourceInterval:[1703,2371]},["app",{sourceInterval:[1703,1709]},"escapeChar_backslash",[]],["app",{sourceInterval:[1765,1771]},"escapeChar_doubleQuote",[]],["app",{sourceInterval:[1829,1835]},"escapeChar_singleQuote",[]],["app",{sourceInterval:[1893,1898]},"escapeChar_backspace",[]],["app",{sourceInterval:[1955,1960]},"escapeChar_lineFeed",[]],["app",{sourceInterval:[2016,2021]},"escapeChar_carriageReturn",[]],["app",{sourceInterval:[2083,2088]},"escapeChar_tab",[]],["app",{sourceInterval:[2139,2221]},"escapeChar_unicodeCodePoint",[]],["app",{sourceInterval:[2250,2291]},"escapeChar_unicodeEscape",[]],["app",{sourceInterval:[2316,2339]},"escapeChar_hexEscape",[]]]],space:["extend",{sourceInterval:[2375,2394]},null,[],["app",{sourceInterval:[2387,2394]},"comment",[]]],comment_singleLine:["define",{sourceInterval:[2412,2458]},null,[],["seq",{sourceInterval:[2412,2443]},["terminal",{sourceInterval:[2412,2416]},"//"],["star",{sourceInterval:[2417,2429]},["seq",{sourceInterval:[2418,2427]},["not",{sourceInterval:[2418,2423]},["terminal",{sourceInterval:[2419,2423]},`
`]],["app",{sourceInterval:[2424,2427]},"any",[]]]],["lookahead",{sourceInterval:[2430,2443]},["alt",{sourceInterval:[2432,2442]},["terminal",{sourceInterval:[2432,2436]},`
`],["app",{sourceInterval:[2439,2442]},"end",[]]]]]],comment_multiLine:["define",{sourceInterval:[2465,2501]},null,[],["seq",{sourceInterval:[2465,2487]},["terminal",{sourceInterval:[2465,2469]},"/*"],["star",{sourceInterval:[2470,2482]},["seq",{sourceInterval:[2471,2480]},["not",{sourceInterval:[2471,2476]},["terminal",{sourceInterval:[2472,2476]},"*/"]],["app",{sourceInterval:[2477,2480]},"any",[]]]],["terminal",{sourceInterval:[2483,2487]},"*/"]]],comment:["define",{sourceInterval:[2398,2501]},null,[],["alt",{sourceInterval:[2412,2501]},["app",{sourceInterval:[2412,2443]},"comment_singleLine",[]],["app",{sourceInterval:[2465,2487]},"comment_multiLine",[]]]],tokens:["define",{sourceInterval:[2505,2520]},null,[],["star",{sourceInterval:[2514,2520]},["app",{sourceInterval:[2514,2519]},"token",[]]]],token:["define",{sourceInterval:[2524,2600]},null,[],["alt",{sourceInterval:[2532,2600]},["app",{sourceInterval:[2532,2540]},"caseName",[]],["app",{sourceInterval:[2543,2550]},"comment",[]],["app",{sourceInterval:[2553,2558]},"ident",[]],["app",{sourceInterval:[2561,2569]},"operator",[]],["app",{sourceInterval:[2572,2583]},"punctuation",[]],["app",{sourceInterval:[2586,2594]},"terminal",[]],["app",{sourceInterval:[2597,2600]},"any",[]]]],operator:["define",{sourceInterval:[2604,2669]},null,[],["alt",{sourceInterval:[2615,2669]},["terminal",{sourceInterval:[2615,2619]},"<:"],["terminal",{sourceInterval:[2622,2625]},"="],["terminal",{sourceInterval:[2628,2632]},":="],["terminal",{sourceInterval:[2635,2639]},"+="],["terminal",{sourceInterval:[2642,2645]},"*"],["terminal",{sourceInterval:[2648,2651]},"+"],["terminal",{sourceInterval:[2654,2657]},"?"],["terminal",{sourceInterval:[2660,2663]},"~"],["terminal",{sourceInterval:[2666,2669]},"&"]]],punctuation:["define",{sourceInterval:[2673,2709]},null,[],["alt",{sourceInterval:[2687,2709]},["terminal",{sourceInterval:[2687,2690]},"<"],["terminal",{sourceInterval:[2693,2696]},">"],["terminal",{sourceInterval:[2699,2702]},","],["terminal",{sourceInterval:[2705,2709]},"--"]]]}]),Qe=Object.create(y.prototype);function Et(t,e){for(let n in t)if(n===e)return!0;return!1}function lt(t,e,n){let r=new me,s,i,a,l=!1;return(n||$e).createSemantics().addOperation("visit",{Grammars(u){return u.children.map(c=>c.visit())},Grammar(u,c,h,f,d){let g=u.visit();s=r.newGrammar(g),c.child(0)&&c.child(0).visit(),f.children.map(I=>I.visit());let m=s.build();if(m.source=this.source.trimmed(),Et(e,g))throw An(m);return e[g]=m,m},SuperGrammar(u,c){let h=c.visit();if(h==="null")s.withSuperGrammar(null);else{if(!e||!Et(e,h))throw wn(h,e,c.source);s.withSuperGrammar(e[h])}},Rule_define(u,c,h,f,d){i=u.visit(),a=c.children.map(k=>k.visit())[0]||[],!s.defaultStartRule&&s.ensureSuperGrammar()!==D.ProtoBuiltInRules&&s.withDefaultStartRule(i);let g=d.visit(),m=h.children.map(k=>k.visit())[0],I=this.source.trimmed();return s.define(i,a,g,m,I)},Rule_override(u,c,h,f){i=u.visit(),a=c.children.map(m=>m.visit())[0]||[];let d=this.source.trimmed();s.ensureSuperGrammarRuleForOverriding(i,d),l=!0;let g=f.visit();return l=!1,s.override(i,a,g,null,d)},Rule_extend(u,c,h,f){i=u.visit(),a=c.children.map(m=>m.visit())[0]||[];let d=f.visit(),g=this.source.trimmed();return s.extend(i,a,d,null,g)},RuleBody(u,c){return r.alt(...c.visit()).withSource(this.source)},OverrideRuleBody(u,c){let h=c.visit(),f=h.indexOf(Qe);if(f>=0){let d=h.slice(0,f),g=h.slice(f+1);return g.forEach(m=>{if(m===Qe)throw Fn(m)}),new ue(s.superGrammar,i,d,g).withSource(this.source)}else return r.alt(...h).withSource(this.source)},Formals(u,c,h){return c.visit()},Params(u,c,h){return c.visit()},Alt(u){return r.alt(...u.visit()).withSource(this.source)},TopLevelTerm_inline(u,c){let h=i+"_"+c.visit(),f=u.visit(),d=this.source.trimmed(),g=!(s.superGrammar&&s.superGrammar.rules[h]);l&&!g?s.override(h,a,f,null,d):s.define(h,a,f,null,d);let m=a.map(I=>r.app(I));return r.app(h,m).withSource(f.source)},OverrideTopLevelTerm_superSplice(u){return Qe},Seq(u){return r.seq(...u.children.map(c=>c.visit())).withSource(this.source)},Iter_star(u,c){return r.star(u.visit()).withSource(this.source)},Iter_plus(u,c){return r.plus(u.visit()).withSource(this.source)},Iter_opt(u,c){return r.opt(u.visit()).withSource(this.source)},Pred_not(u,c){return r.not(c.visit()).withSource(this.source)},Pred_lookahead(u,c){return r.lookahead(c.visit()).withSource(this.source)},Lex_lex(u,c){return r.lex(c.visit()).withSource(this.source)},Base_application(u,c){let h=c.children.map(f=>f.visit())[0]||[];return r.app(u.visit(),h).withSource(this.source)},Base_range(u,c,h){return r.range(u.visit(),h.visit()).withSource(this.source)},Base_terminal(u){return r.terminal(u.visit()).withSource(this.source)},Base_paren(u,c,h){return c.visit()},ruleDescr(u,c,h){return c.visit()},ruleDescrText(u){return this.sourceString.trim()},caseName(u,c,h,f,d){return h.visit()},name(u,c){return this.sourceString},nameFirst(u){},nameRest(u){},terminal(u,c,h){return c.children.map(f=>f.visit()).join("")},oneCharTerminal(u,c,h){return c.visit()},escapeChar(u){try{return $t(this.sourceString)}catch(c){throw c instanceof RangeError&&c.message.startsWith("Invalid code point ")?$n(u):c}},NonemptyListOf(u,c,h){return[u.visit()].concat(h.children.map(f=>f.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(t).visit()}var rr=Fe(["grammar",{source:`OperationsAndAttributes {
AttributeSignature =
name
OperationSignature =
name Formals?
Formals
= "(" ListOf<name, ","> ")"
name (a name)
= nameFirst nameRest*
nameFirst
= "_"
| letter
nameRest
= "_"
| alnum
}`},"OperationsAndAttributes",null,"AttributeSignature",{AttributeSignature:["define",{sourceInterval:[29,58]},null,[],["app",{sourceInterval:[54,58]},"name",[]]],OperationSignature:["define",{sourceInterval:[62,100]},null,[],["seq",{sourceInterval:[87,100]},["app",{sourceInterval:[87,91]},"name",[]],["opt",{sourceInterval:[92,100]},["app",{sourceInterval:[92,99]},"Formals",[]]]]],Formals:["define",{sourceInterval:[104,143]},null,[],["seq",{sourceInterval:[118,143]},["terminal",{sourceInterval:[118,121]},"("],["app",{sourceInterval:[122,139]},"ListOf",[["app",{sourceInterval:[129,133]},"name",[]],["terminal",{sourceInterval:[135,138]},","]]],["terminal",{sourceInterval:[140,143]},")"]]],name:["define",{sourceInterval:[147,187]},"a name",[],["seq",{sourceInterval:[168,187]},["app",{sourceInterval:[168,177]},"nameFirst",[]],["star",{sourceInterval:[178,187]},["app",{sourceInterval:[178,186]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[191,223]},null,[],["alt",{sourceInterval:[207,223]},["terminal",{sourceInterval:[207,210]},"_"],["app",{sourceInterval:[217,223]},"letter",[]]]],nameRest:["define",{sourceInterval:[227,257]},null,[],["alt",{sourceInterval:[242,257]},["terminal",{sourceInterval:[242,245]},"_"],["app",{sourceInterval:[252,257]},"alnum",[]]]]}]);sr(D.BuiltInRules);ir(rr);function sr(t){let e={empty(){return this.iteration()},nonEmpty(n,r,s){return this.iteration([n].concat(s.children))},self(...n){return this}};$.BuiltInSemantics=$.createSemantics(t,null).addOperation("asIteration",{emptyListOf:e.empty,nonemptyListOf:e.nonEmpty,EmptyListOf:e.empty,NonemptyListOf:e.nonEmpty,_iter:e.self})}function ir(t){$.prototypeGrammarSemantics=t.createSemantics().addOperation("parse",{AttributeSignature(e){return{name:e.parse(),formals:[]}},OperationSignature(e,n){return{name:e.parse(),formals:n.children.map(r=>r.parse())[0]||[]}},Formals(e,n,r){return n.asIteration().children.map(s=>s.parse())},name(e,n){return this.sourceString}}),$.prototypeGrammar=t}function ar(t){let e=0,n=[0],r=()=>n[n.length-1],s={},i=/( *).*(?:$|\r?\n|\r)/g,a;for(;(a=i.exec(t))!=null;){let[l,o]=a;if(l.length===0)break;let p=o.length,u=r(),c=e+p;if(p>u)n.push(p),s[c]=1;else if(p<u){let h=n.length;for(;r()!==p;)n.pop();s[c]=-1*(h-n.length)}e+=l.length}return n.length>1&&(s[e]=1-n.length),s}var Kt="an indented block",zt="a dedent",Ct=1114112,nt=class extends fe{constructor(e){super(e.input),this.state=e}_indentationAt(e){return this.state.userData[e]||0}atEnd(){return super.atEnd()&&this._indentationAt(this.pos)===0}next(){if(this._indentationAt(this.pos)!==0){this.examinedLength=Math.max(this.examinedLength,this.pos);return}return super.next()}nextCharCode(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),Ct):super.nextCharCode()}nextCodePoint(){return this._indentationAt(this.pos)!==0?(this.examinedLength=Math.max(this.examinedLength,this.pos),Ct):super.nextCodePoint()}},Pe=class extends y{constructor(e=!0){super(),this.isIndent=e}allowsSkippingPrecedingSpace(){return!0}eval(e){let{inputStream:n}=e,r=e.userData;e.doNotMemoize=!0;let s=n.pos,i=this.isIndent?1:-1;return(r[s]||0)*i>0?(e.userData=Object.create(r),e.userData[s]-=i,e.pushBinding(new te(0),s),!0):(e.processFailure(s,this),!1)}getArity(){return 1}_assertAllApplicationsAreValid(e,n){}_isNullable(e,n){return!1}assertChoicesHaveUniformArity(e){}assertIteratedExprsAreNotNullable(e){}introduceParams(e){return this}substituteParams(e){return this}toString(){return this.isIndent?"indent":"dedent"}toDisplayString(){return this.toString()}toFailure(e){let n=this.isIndent?Kt:zt;return new j(this,n,"description")}},or=new v("indent"),lr=new v("dedent"),ur=new ue(ot,"any",[or,lr],[]),Wt=new me().newGrammar("IndentationSensitive").withSuperGrammar(ot).define("indent",[],new Pe(!0),Kt,void 0,!0).define("dedent",[],new Pe(!1),zt,void 0,!0).extend("any",[],ur,"any character",void 0).build();Object.assign(Wt,{_matchStateInitializer(t){t.userData=ar(t.input),t.inputStream=new nt(t)},supportsIncrementalParsing:!1});var cr="17.2.1";D.initApplicationParser($e,lt);var pr=t=>!!t.constructor&&typeof t.constructor.isBuffer=="function"&&t.constructor.isBuffer(t);function hr(t,e){let n=$e.match(t,"Grammars");if(n.failed())throw bn(n);return lt(n,e)}function fr(t,e){let n=Zt(t,e),r=Object.keys(n);if(r.length===0)throw new Error("Missing grammar definition");if(r.length>1){let i=n[r[1]].source;throw new Error(it(i.sourceString,i.startIdx)+"Found more than one grammar definition -- use ohm.grammars() instead.")}return n[r[0]]}function Zt(t,e){let n=Object.create(e||{});if(typeof t!="string")if(pr(t))t=t.toString();else throw new TypeError("Expected string as first argument, got "+rt(t));return hr(t,n),n}z.ExperimentalIndentationSensitive=Wt;z._buildGrammar=lt;z.grammar=fr;z.grammars=Zt;z.makeRecipe=Fe;z.ohmGrammar=$e;z.pexprs=er;z.version=cr});var ut=ae(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.getMass=G.normalizeUnit=G.UNIT_CONVERSIONS=void 0;G.UNIT_CONVERSIONS={mass:{base:"g",map:{kg:1e3,mg:.001,g:1}},volume:{base:"ml",map:{l:1e3,liter:1e3,litre:1e3,dl:100,cl:10,ml:1}}};var dr=(t,e)=>{if(!t)return{quantity:0,unit:e||null};let n=(e||"").toLowerCase().trim(),r=t;if(typeof t=="object"&&t.value!==void 0&&(r=t.value),typeof r!="number")return{quantity:t,unit:n};for(let{base:s,map:i}of Object.values(G.UNIT_CONVERSIONS))if(i[n])return{quantity:r*i[n],unit:s};return{quantity:r,unit:n}};G.normalizeUnit=dr;var mr=(t,e)=>{let n=t;if(typeof t=="object"&&t!==null)if(t.type==="fraction")n=t.value;else if(t.type==="range")n=t.value;else if(t.type==="single")n=t.value;else return{mass:0,valid:!1};if(typeof n!="number")return{mass:0,valid:!1};let r=(e||"").toLowerCase().trim();return G.UNIT_CONVERSIONS.mass.map[r]?{mass:n*G.UNIT_CONVERSIONS.mass.map[r],valid:!0}:G.UNIT_CONVERSIONS.volume.map[r]?{mass:n*G.UNIT_CONVERSIONS.volume.map[r],valid:!0}:{mass:0,valid:!1}};G.getMass=mr});var ct=ae(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.cleanObject=M.createCleanUsage=M.minifyQuantity=M.slugify=void 0;var gr=t=>t.toString().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"unknown";M.slugify=gr;var yr=t=>{if(t){if(typeof t=="number")return t;if(t.type==="single"&&t.value!==void 0)return t.value;if(t.type==="range"||t.type==="fraction")return t;if(t.type==="Quantity")return t.value&&t.value.type==="single"?t.value.value:t.value;if(t.type!=="RelativeQuantity")return t}};M.minifyQuantity=yr;var vr=(t,e)=>{let n={id:e},r=t.quantity,s;if(r&&(r.type==="TextQuantity"?s=r.value:s=(0,M.minifyQuantity)(r.value||r)),s!==void 0&&(n.qty=s),r&&r.unit&&(n.unit=r.unit),t.modifiers&&t.modifiers.length>0){let i={"?":"optional","-":"hidden","&":"reference","*":"bakers_percentage"};n.modifiers=t.modifiers.map(a=>i[a]||a)}if(t.type==="Cookware"?r&&r.fixed===!1&&(n.fixed=!1):r&&r.fixed===!0&&(n.fixed=!0),r&&r.type==="TextQuantity"&&(n.qty=r.value,n.fixed=!0),t.alias&&(n.alias=t.alias),t.preparation&&(n.preparation=t.preparation),t.composite){let i={};if(t.composite.parent&&(i.parent=t.composite.parent),t.composite.quantity){let a=t.composite.quantity,l=(0,M.minifyQuantity)(a);l!==void 0&&(i.quantity=l),a.unit&&(i.unit=a.unit)}n.composite=i}return n};M.createCleanUsage=vr;var Ir=t=>{if(t!=null){if(Array.isArray(t))return t.map(M.cleanObject).filter(n=>n!=null);if(typeof t=="object"){let e={};for(let n in t){let r=t[n],s=(0,M.cleanObject)(r);if(s!=null){if(Array.isArray(s)&&s.length===0)continue;e[n]=s}}return e}return t}};M.cleanObject=Ir});var Yt=ae(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.detectCycles=xr;function xr(t){let e=new Map;t.forEach(a=>{a.ingredients.forEach(l=>{l.dependencies&&(e.has(l.id)||e.set(l.id,new Set),l.dependencies.forEach(o=>e.get(l.id)?.add(o)))})});let n=new Set,r=new Set,s=new Set;function i(a){n.add(a),r.add(a);let l=e.get(a);if(l)for(let o of l)n.has(o)?r.has(o)&&(s.add(a),s.add(o)):i(o);r.delete(a)}for(let[a]of e)n.has(a)||i(a);return s}});var en=ae(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.generateShoppingList=wr;var Xt=ct(),Sr=ut(),_r=Yt();function br(t){return t?typeof t=="number"?t:t.type==="single"?t.value:t.type==="range"?t.text||`${t.value}`:t.type==="fraction"?t.text||`${t.value}`:JSON.stringify(t):""}function wr(t,e){let n=new Map,r=new Map,s=[],i=(0,_r.detectCycles)(t);t.forEach(o=>{o.ingredients.forEach(p=>{if(p.type==="alternative"){s.push(p);return}if(i.has(p.id)&&(p.isCircular=!0),p.composite){let m=(0,Xt.slugify)(p.composite.parent);r.has(m)||r.set(m,{type:"composite",id:m,qty:0,usage:[],_maxQty:0});let I=r.get(m),k={id:p.id},V=0,X=p.composite;if(X&&X.quantity){let Oe=(0,Xt.minifyQuantity)(X.quantity);Oe!==void 0&&(k.qty=Oe),typeof Oe=="number"&&(V=Oe)}V>I._maxQty&&(I._maxQty=V,I.qty=V),p.qty;let ie={id:p.id};p.qty!==void 0&&(ie.qty=p.qty),p.unit&&(ie.unit=p.unit),p.alias&&(ie.alias=p.alias),I.usage.push(ie);return}let u=p.id,c=u;n.has(c)||n.set(c,{id:u,name:e.ingredients.get(u)?.name||p.name,sureMass:0,otherUnits:{},variableParts:[],_hasSure:!1});let h=n.get(c),f=null,d=p.unit||"",g=!1;if(p.formula)p.formula.isGhost?g=!0:typeof p.qty=="number"&&(f=p.qty);else if(typeof p.qty=="number")f=p.qty;else if(p.qty&&typeof p.qty=="object"){let m=p.qty;(m.type==="fraction"||m.type==="range"||m.type==="single")&&(f=m.value)}if(g){let m=p.formula?p.formula.raw:p.qty&&p.qty.value||"";p.type,p.formula&&(m=p.formula.raw);let I=`${m} \u2753`;h.variableParts.push(`(${I})`)}else if(f!==null){let m=(0,Sr.getMass)(f,d);if(m.valid)h.sureMass+=m.mass,h._hasSure=!0;else{let I=d;h.otherUnits[I]||(h.otherUnits[I]=0),h.otherUnits[I]+=f}}else if(!p.formula){if(p.qty){let m=br(p.qty),I=d?` ${d}`:"";h.variableParts.push(`${m}${I}`)}}!g&&p.isCircular&&h.variableParts.push("\u26A0\uFE0F Ref. Circulaire")})});let a=[...n.values()].map(o=>{let p={id:o.id,name:o.name};if(o.sureMass>0)p.qty=parseFloat(o.sureMass.toFixed(2)),p.unit="g";else{let d=Object.keys(o.otherUnits);d.length>0&&(p.qty=parseFloat(o.otherUnits[d[0]].toFixed(2)),p.unit=d[0]||null)}let u=o.sureMass>0,c=Object.keys(o.otherUnits).length>0,h=[];if(u)for(let[d,g]of Object.entries(o.otherUnits)){let m=d?` ${d}`:"";h.push(`${parseFloat(g.toFixed(2))}${m}`)}else if(c){let d=Object.keys(o.otherUnits);for(let g=1;g<d.length;g++){let m=d[g],I=m?` ${m}`:"";h.push(`${parseFloat(o.otherUnits[m].toFixed(2))}${I}`)}}let f=[...h,...o.variableParts||[]];return f.length>0&&(p.variable_entries=f),p}),l=[...r.values()].map(o=>{let{_maxQty:p,...u}=o;return u});return[...a,...l,...s]}});var tn=ae(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.processBlockItem=dt;De.compile=Nr;var ft=ut(),q=ct(),Ar=en();function dt(t,e,n,r,s){if(!t)return null;if(t.type==="Ingredient"){let i=(0,q.slugify)(t.name);if(!n.ingredients.has(i)){let o=null;t.quantity&&t.quantity.unit&&(o=t.quantity.unit),n.ingredients.set(i,{id:i,name:t.name,default_unit:o})}let a=n.ingredients.get(i);if(a&&t.quantity&&t.quantity.unit&&!a.default_unit&&(a.default_unit=t.quantity.unit),t.composite){a&&(a.is_composite=!0);let o=(0,q.slugify)(t.composite.parent);if(a&&(a.parent=o),!n.ingredients.has(o))n.ingredients.set(o,{id:o,name:t.composite.parent,is_composite:!0});else{let p=n.ingredients.get(o);p&&(p.is_composite=!0)}}if(t.quantity&&t.quantity.type==="RelativeQuantity"){let o=t.quantity,p=o.target,u=(0,q.slugify)(p),c=o.percent,h=0,f=null,d=!1,g=o.referenceType==="variable"?"&":"@",m=`${c}% de ${g}${p}`;if(o.referenceType==="variable")if(e.variableWeights.has(u)){let V=e.variableWeights.get(u);V&&(h=V.mass,f="g")}else d=!0,e.warnings.push({code:"VARIABLE_NOT_FOUND",message:`Variable '&${p}' not found or has undefined mass.`,item:t.name});else if(!r.some(X=>X.id===u))d=!0,e.warnings.push({code:"RELATIVE_QUANTITY_UNRESOLVED",message:`Could not resolve relative quantity for '@${p}'. Source not found.`,item:t.name});else{for(let X of r)if(X.id===u){let ie=(0,ft.getMass)(X.qty,X.unit);ie.valid&&(h+=ie.mass,f||(f="g"))}f||(d=!0,e.warnings.push({code:"RELATIVE_NO_MASS",message:`Source '@${p}' has no mass (unitless or incompatible). Calculation impossible.`,item:t.name}))}let I=h*(c/100),k=(0,q.createCleanUsage)(t,i);return k.qty=parseFloat(I.toFixed(2)),k.unit=f||"g",u===i&&(k.isCircular=!0,e.warnings.push({code:"CIRCULAR_REFERENCE",message:`Circular reference detected: ${t.name} depends on itself.`,item:t.name})),k.dependencies=[u],k.formula={raw:m,target:p,percent:c,isGhost:d},r.push(k),k}let l=(0,q.createCleanUsage)(t,i);return t.modifiers&&t.modifiers.includes("&")?(e.seenNames.has(t.name)||e.warnings.push({code:"UNDEFINED_REFERENCE",message:`Reference to undefined ingredient '@&${t.name}'.`,item:t.name}),e.definedIntermediates.has(t.name)&&e.usedIntermediates.add(t.name)):e.seenNames.add(t.name),(!t.modifiers||!t.modifiers.includes("&")||t.quantity)&&r.push(l),l}if(t.type==="Cookware"){let i=(0,q.slugify)(t.name);n.cookware.has(i)||n.cookware.set(i,{id:i,name:t.name});let a=(0,q.createCleanUsage)(t,i);return s.push(a),a}if(t.type==="Alternative"){let a={id:"alternative",type:"alternative",options:t.options.map(l=>dt(l,e,n,[],[]))};return t.options.length>0&&(t.options[0].type==="Ingredient"?r.push(a):t.options[0].type==="Cookware"&&s.push(a)),a}if(t.type==="Reference"){let i=(0,q.slugify)(t.name);n.ingredients.has(i)||e.warnings.push({code:"UNDEFINED_REFERENCE",message:`Reference to undefined ingredient '&${t.name}'.`,item:t.name}),e.definedIntermediates.has(t.name)&&e.usedIntermediates.add(t.name);let a={type:"reference",id:i};if(t.quantity){let l=(0,q.minifyQuantity)(t.quantity);l!==void 0&&(a.qty=l),t.quantity.unit&&(a.unit=t.quantity.unit),t.quantity.type==="TextQuantity"&&(a.qty=t.quantity.value)}return a}if(t.type==="IntermediateDecl"){let i=(0,q.slugify)(t.name);if(e.intermediateDecl=i,!n.ingredients.has(i))n.ingredients.set(i,{id:i,name:t.name,is_intermediate:!0});else{let a=n.ingredients.get(i);a&&(a.is_intermediate=!0)}return null}if(t.type==="Text")return t.value;if(t.type==="Timer"||t.type==="Temperature"){let i={type:t.type.toLowerCase()};if(t.name&&(i.name=t.name),t.quantity){let a=t.quantity;a.value&&(i.quantity=a.value);let l=a.unit;t.type==="Timer"&&(l==="m"||l==="minutes")&&(l="min"),l&&(i.unit=l),a.type==="TextQuantity"?(e.warnings.push({code:"INVALID_UNIT",message:`Invalid text content in ${t.type}.`,item:a.value}),i.quantity={type:"text",value:a.value}):l||e.warnings.push({code:"MISSING_UNIT",message:`${t.type} must have an explicit unit.`,item:t.name||t.type})}return i}return t.type==="Comment"?{type:"comment",value:t.value,kind:t.kind}:t}function Or(t,e){let n={warnings:e.warnings,intermediateDecl:null,seenNames:new Set,definedIntermediates:new Set,usedIntermediates:new Set,variableWeights:new Map,globalScopes:new Map},r=[],s=t;return s.length>0&&s[0].type!=="Section"&&(s=[{type:"Section",title:null,children:t}]),s.forEach(i=>{if(i.type!=="Section")return;if(i.intermediateDecl){let u=i.intermediateDecl.name;n.globalScopes.has(u)?e.warnings.push({code:"SCOPE_CONFLICT",message:`La variable globale '&${u}' est red\xE9finie.`,section:i.title}):n.globalScopes.set(u,i.title);let c=(0,q.slugify)(u);e.ingredients.has(c)||e.ingredients.set(c,{id:c,name:u,is_intermediate:!0}),n.definedIntermediates.add(u)}let a=[],l=[],o=[];i.children.forEach(u=>{if(u.type==="Step"){let c={type:"step",content:[]};if(u.action&&(c.action=u.action),n.intermediateDecl=null,u.children.forEach(h=>{let f=dt(h,n,e,a,l);if(f){c.content.push(f);let d=0,g=!1;if(typeof f!="string"){let m=f;if(m.qty&&typeof m.qty=="number"){let I=(0,ft.getMass)(m.qty,m.unit);d=I.mass,g=I.valid}else m.type==="reference"&&m.formula&&m.qty&&(d=m.qty,g=!0);if(m.type==="reference"&&!m.qty&&n.variableWeights.has(m.id)){let I=n.variableWeights.get(m.id);I&&(d=I.mass,g=!I.isPartial)}}c._accumulatedMass=(c._accumulatedMass||0)+d,g||(c._hasPartialStats=!0)}}),n.intermediateDecl){c.intermediate_preparation=n.intermediateDecl;let h=n.intermediateDecl,f=c._accumulatedMass||0,d=!!c._hasPartialStats;n.variableWeights.set(h,{mass:f,isPartial:d})}delete c._accumulatedMass,delete c._hasPartialStats,o.push(c)}else u.type==="Comment"&&o.push({type:"comment",value:u.value,kind:u.kind})});let p={title:i.title,ingredients:a,cookware:l,steps:o};if(i.intermediateDecl){p.intermediate_preparation=i.intermediateDecl.name;let u=0,c=!1;p.ingredients.forEach(f=>{let d=(0,ft.getMass)(f.qty,f.unit);u+=d.mass,d.valid||(c=!0)});let h=(0,q.slugify)(i.intermediateDecl.name);n.variableWeights.set(h,{mass:u,isPartial:c})}i.retroPlanning&&(p.retro_planning=i.retroPlanning),r.push(p)}),r}function Nr(t){if(t.type!=="Recipe")throw new Error("Compiler expects Recipe AST");let e={ingredients:new Map,cookware:new Map,warnings:[]},n=Or(t.children,e),r=(0,Ar.generateShoppingList)(n,e),s=[];n.forEach(a=>{a.cookware.forEach(l=>{(!l.modifiers||!l.modifiers.includes("reference"))&&s.push(l)})});let i={title:t.meta.title||null,slug:t.meta.title?(0,q.slugify)(t.meta.title):null,meta:t.meta,registry:{ingredients:Object.fromEntries(e.ingredients),cookware:Object.fromEntries(e.cookware)},shopping_list:r,cookware:s,sections:n,warnings:e.warnings};return(0,q.cleanObject)(i)}});var an=ae(W=>{"use strict";var Lr=W&&W.__createBinding||(Object.create?function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}:function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}),Er=W&&W.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),gt=W&&W.__importStar||function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&Lr(n,e,r[s]);return Er(n,e),n}}();Object.defineProperty(W,"__esModule",{value:!0});W.getAST=sn;W.parse=kr;var Jr=gt({}),Yr=gt({}),Cr=gt(Jt()),Rr=tn(),Tr=`GRAM {
Recipe = Frontmatter? Content?
Content =
| (nl* Section)+ -- explicit
| (nl* Block)+ -- implicit
Frontmatter = "---" nl KeyValue* "---" (nl | end)
KeyValue = key ":" sp* value nl
key = (alnum | "_" | "-")+
value = (~nl any)*
Section = header Block*
header = "##" sp+ title headerExtension? sp* nl+
headerExtension =
| retroPlanning sp* intermediateDecl? -- retro
| intermediateDecl -- decl
titleStop = nl | "->&" | "{T-"
title = (~titleStop any)*
retroPlanning = "{T-" (~"}" any)+ "}"
Block =
| Comment nl* -- comment
| (~header step) -- step
step = startAction? line (nl line)* (nl+ | end)
startAction = "[" (~"]" any)+ "]" sp*
line = stepContent+
stepContent =
| text
| ws
| intermediateDecl
| applySyntactic<Element>
| fallback
ws = space+
fallback = ~nl any
Element =
| Ingredient
| Cookware
| Timer
| Temperature
| Reference
| CommentBlock
| Comment
intermediateDecl = "->&" name "{}"
// Ingredients
Ingredient =
| Alternative
| simpleIngredient
Alternative = simpleIngredient ("|" simpleIngredient)+
// Rule: Quantity is mandatory (it's the delimiter)
simpleIngredient = "@" modifier* name alias? ingredientQuantity preparation? composite?
modifier = "?" | "-" | "*" | "&"
alias = "[" space* name space* "]"
ingredientQuantity = "{" space* (relativeQuantity | absoluteQuantity) space* "}"
relativeQuantity = number space* "%" space* ("@" | "&") space* name
absoluteQuantity = (fixed space*)? (range | number)? space* (unit space*)?
textQuantity = "{" space* (~"}" any)+ space* "}"
fixed = "="
unit = unitName
unitName = (alnum | sp | "\xB0" | "%")+
preparation = "(" (~")" any)* ")"
composite = "<" space* "@" space* name space* ingredientQuantity?
// Cookware
// Specs say use braces too.
Cookware =
| CookwareAlternative
| simpleCookware
CookwareAlternative = simpleCookware ("|" simpleCookware)+
simpleCookware = "#" modifier* name alias? cookwareQuantity preparation?
// Restrict cookware quantity to only numbers/fixed, NO UNITS.
// Allowed: {}, {2}, {=1}
cookwareQuantity = "{" space* (fixed space*)? number? space* "}"
// Timer
Timer = "~" name? ingredientQuantity
// Temperature
Temperature = "!" name? (ingredientQuantity | textQuantity)
// Comments
Comment = "//" (~nl any)*
CommentBlock = "/*" (~"*/" any)* "*/"
// Primitives
name = (~(syntaxChar | nl) any)+
number = digit+ ("." digit+)? ("/" digit+)?
range = number space* "-" space* number
text = space* (~(elementStart | nl) any)+
Reference = "&" name ingredientQuantity
// SyntaxChar used for name content exclusion
// Restricted to true delimiters that start a new component
syntaxChar = "{" | "}" | "[" | "]" | "(" | ")" | "<" | "|"
// Name can contain '&' or '@' or other symbols, as long as it doesn't look like a start of a new element if specific context requires it?
// Actually, standard grammar strategy: consume until a known delimiter.
// The delimiters are:
// - \`{\` (start of quantity)
// - \`[\` (start of alias)
// - \`(\` (start of preparation)
// - \`<\` (start of composite)
// - \`|\` (start of alternative)
// - newline
// We removed @, #, ~, !, &, ?, * from syntaxChar list effectively allowing them in names.
// ElementStart used for text content exclusion
// This remains strict to identify WHERE an element starts in free text.
elementStart = "@" | "#" | "~" | "!" | "//" | "/*" | "->&" | "&"
nl = "\\r"? "\\n"
sp = " " | "\\t"
space := sp
}
`,nn=Cr.grammar(Tr),H=t=>t.trim(),B=t=>t.children.length>0?t.children[0].toAST():null,mt=t=>{if(!t)return null;let[e,n]=t.split("/");if(n){let r=parseInt(e),s=parseInt(n);return{type:"fraction",value:r/s,numerator:r,denominator:s,text:t}}else return{type:"single",value:parseFloat(t),text:t}},Pr=t=>{t=t.trim();let e=n=>n&&(n.startsWith("'")||n.startsWith('"'))&&n[0]===n[n.length-1]?n.slice(1,-1):n;if(t.startsWith("[")&&t.endsWith("]")){let n=t.slice(1,-1).trim();return n?n.split(",").map(r=>e(r.trim())):[]}return e(t)},rn=nn.createSemantics();rn.addOperation("toAST",{Recipe(t,e){let n=B(t)||{},r=B(e)||[];return{type:"Recipe",meta:n,children:r}},Frontmatter(t,e,n,r,s){return n.children.map(i=>i.toAST()).reduce((i,a)=>({...i,...a}),{})},KeyValue(t,e,n,r,s){return{[t.sourceString]:Pr(r.sourceString)}},Content_explicit(t,e){return e.children.map(n=>n.toAST())},Content_implicit(t,e){return e.children.map(n=>n.toAST())},Section(t,e){let n=t.toAST();return{type:"Section",title:n.title,retroPlanning:n.retroPlanning,intermediateDecl:n.intermediateDecl,children:e.children.map(r=>r.toAST()),loc:{start:this.source.startIdx,end:this.source.endIdx}}},header(t,e,n,r,s,i){let a=null,l=null,o=B(r);return o&&(a=o.retroPlanning,l=o.intermediateDecl),{title:H(n.sourceString).replace(/^##\s*/,""),retroPlanning:a,intermediateDecl:l}},headerExtension_retro(t,e,n){let r=B(n);return{retroPlanning:t.toAST(),intermediateDecl:r}},headerExtension_decl(t){return{retroPlanning:null,intermediateDecl:t.toAST()}},retroPlanning(t,e,n){return H(e.sourceString)},Block_comment(t,e){return t.toAST()},Block_step(t){return t.toAST()},step(t,e,n,r,s){let i=B(t),a=[e.toAST()];r.children.forEach(o=>{a.push([{type:"Text",value:" "}]),a.push(o.toAST())});let l=a.flat().filter(o=>o!==null);return{type:"Step",action:i,children:l,loc:{start:this.source.startIdx,end:this.source.endIdx}}},startAction(t,e,n,r){return H(e.sourceString)},line(t){return t.children.map(e=>e.toAST())},stepContent(t){return t.toAST()},intermediateDecl(t,e,n){return{type:"IntermediateDecl",name:H(e.sourceString)}},text(t,e){return{type:"Text",value:t.sourceString+e.sourceString,loc:{start:this.source.startIdx,end:this.source.endIdx}}},fallback(t){return{type:"Text",value:t.sourceString,fallback:!0,loc:{start:this.source.startIdx,end:this.source.endIdx}}},nl(t,e){return null},ws(t){return{type:"Text",value:t.sourceString}},Ingredient(t){return t.toAST()},Alternative(t,e,n){return{type:"Alternative",options:[t.toAST(),...n.children.map(s=>s.toAST())],loc:{start:this.source.startIdx,end:this.source.endIdx}}},simpleIngredient(t,e,n,r,s,i,a){let l=e.children.map(o=>o.sourceString);return{type:"Ingredient",name:n.sourceString.trim(),modifiers:l,quantity:s.toAST(),alias:B(r),preparation:B(i),composite:B(a),loc:{start:this.source.startIdx,end:this.source.endIdx}}},composite(t,e,n,r,s,i,a){return{type:"Composite",parent:s.sourceString,quantity:B(a)}},alias(t,e,n,r,s){return H(n.sourceString)},preparation(t,e,n){return H(e.sourceString)},unit(t){return H(t.sourceString)},ingredientQuantity(t,e,n,r,s){return n.toAST()},relativeQuantity(t,e,n,r,s,i,a){return{type:"RelativeQuantity",percent:parseFloat(t.sourceString),target:H(a.sourceString),referenceType:s.sourceString==="&"?"variable":"ingredient",loc:{start:this.source.startIdx,end:this.source.endIdx}}},absoluteQuantity(t,e,n,r,s,i){return{type:"Quantity",value:B(n),unit:B(s),fixed:t.children.length>0,loc:{start:this.source.startIdx,end:this.source.endIdx}}},cookwareQuantity(t,e,n,r,s,i,a){return{type:"Quantity",value:B(s),unit:null,fixed:n.children.length>0,loc:{start:this.source.startIdx,end:this.source.endIdx}}},textQuantity(t,e,n,r,s){return{type:"TextQuantity",value:H(n.sourceString),loc:{start:this.source.startIdx,end:this.source.endIdx}}},number(t,e,n,r,s){return mt(this.sourceString)},range(t,e,n,r,s){let i=mt(t.sourceString),a=mt(s.sourceString);return i&&a?{type:"range",value:(i.value+a.value)/2,range:{min:i.value,max:a.value},text:this.sourceString}:null},CookwareAlternative(t,e,n){return{type:"Alternative",options:[t.toAST(),...n.children.map(r=>r.toAST())],loc:{start:this.source.startIdx,end:this.source.endIdx}}},simpleCookware(t,e,n,r,s,i){let a=e.children.map(l=>l.sourceString);return{type:"Cookware",name:H(n.sourceString),modifiers:a,alias:B(r),quantity:s.toAST(),preparation:B(i),loc:{start:this.source.startIdx,end:this.source.endIdx}}},Reference(t,e,n){return{type:"Reference",name:e.sourceString,quantity:n.toAST(),loc:{start:this.source.startIdx,end:this.source.endIdx}}},Timer(t,e,n){return{type:"Timer",name:e.children.length>0?H(e.children[0].sourceString):null,quantity:n.toAST(),loc:{start:this.source.startIdx,end:this.source.endIdx}}},Temperature(t,e,n){return{type:"Temperature",name:e.children.length>0?H(e.children[0].sourceString):null,quantity:n.toAST(),loc:{start:this.source.startIdx,end:this.source.endIdx}}},Comment(t,e){return{type:"Comment",value:e.sourceString,kind:"line",loc:{start:this.source.startIdx,end:this.source.endIdx}}},CommentBlock(t,e,n){return{type:"Comment",value:e.sourceString,kind:"block",loc:{start:this.source.startIdx,end:this.source.endIdx}}},_terminal(){return null}});function sn(t){let e=nn.match(t);if(e.failed())throw new Error(e.message);return rn(e).toAST()}function kr(t){let e=sn(t);return(0,Rr.compile)(e)}});var cn=In(an()),Y=document.getElementById("input"),J=document.getElementById("output"),je=document.getElementById("status"),pn=document.getElementById("theme-toggle"),we=document.getElementById("warnings"),on=document.querySelectorAll(".tab-btn[data-mode]");on.forEach(t=>{t.addEventListener("click",()=>{on.forEach(e=>e.classList.remove("active")),t.classList.add("active"),re=t.dataset.mode,Ge()})});pn.addEventListener("click",()=>{document.body.classList.toggle("light");let t=document.body.classList.contains("light");localStorage.setItem("theme",t?"light":"dark"),yt(t)});function yt(t){pn.innerHTML=t?'<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#000000" viewBox="0 0 256 256"><path d="M236.37,139.4a12,12,0,0,0-12-3A84.07,84.07,0,0,1,119.6,31.59a12,12,0,0,0-15-15A108.86,108.86,0,0,0,49.69,55.07,108,108,0,0,0,136,228a107.09,107.09,0,0,0,64.93-21.69,108.86,108.86,0,0,0,38.44-54.94A12,12,0,0,0,236.37,139.4Zm-49.88,47.74A84,84,0,0,1,68.86,69.51,84.93,84.93,0,0,1,92.27,48.29Q92,52.13,92,56A108.12,108.12,0,0,0,200,164q3.87,0,7.71-.27A84.79,84.79,0,0,1,186.49,187.14Z"></path></svg>':'<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="#ffffff" viewBox="0 0 256 256"><path d="M116,36V20a12,12,0,0,1,24,0V36a12,12,0,0,1-24,0Zm80,92a68,68,0,1,1-68-68A68.07,68.07,0,0,1,196,128Zm-24,0a44,44,0,1,0-44,44A44.05,44.05,0,0,0,172,128ZM51.51,68.49a12,12,0,1,0,17-17l-12-12a12,12,0,0,0-17,17Zm0,119-12,12a12,12,0,0,0,17,17l12-12a12,12,0,1,0-17-17ZM196,72a12,12,0,0,0,8.49-3.51l12-12a12,12,0,0,0-17-17l-12,12A12,12,0,0,0,196,72Zm8.49,115.51a12,12,0,0,0-17,17l12,12a12,12,0,0,0,17-17ZM48,128a12,12,0,0,0-12-12H20a12,12,0,0,0,0,24H36A12,12,0,0,0,48,128Zm80,80a12,12,0,0,0-12,12v16a12,12,0,0,0,24,0V220A12,12,0,0,0,128,208Zm108-92H220a12,12,0,0,0,0,24h16a12,12,0,0,0,0-24Z"></path></svg>'}var Fr=localStorage.getItem("theme");Fr==="light"?(document.body.classList.add("light"),yt(!0)):yt(!1);function $r(t,e){let n;return function(...s){let i=()=>{clearTimeout(n),t(...s)};clearTimeout(n),n=setTimeout(i,e)}}var re="json";function ve(t){return t.qty!==void 0?typeof t.qty=="number"?{value:t.qty,text:String(t.qty)}:t.qty:t.quantity}function Be(t){return t?t.type==="range"&&t.text||t.text?t.text:t.value!==void 0?t.value:t:""}function Dr(t){let e=t.registry||{ingredients:{},cookware:{}},n="";if(t.title&&(n+=`# ${t.title}
`),t.meta&&Object.keys(t.meta).length>0){n+=`> **Metadata**
`;for(let[r,s]of Object.entries(t.meta))r!=="title"&&(n+=`> - ${r}: ${s}
`);n+=`
`}return t.shopping_list&&t.shopping_list.length>0&&(n+=`## \u{1F6D2} Shopping List
`,t.shopping_list.forEach(r=>{if(r.type==="alternative"||r.type==="group")n+=`- **Alternative Group**:
`,r.options.forEach(s=>{n+=` - ${Z(s,e)}
`});else if(r.type==="composite"){let s=Z(r,e);n+=`- **${s}** (Composite):
`,r.usage.forEach(i=>{n+=` - ${Z(i,e)}
`})}else r.display?n+=`- ${r.display}
`:n+=`- ${Z(r,e)}
`}),n+=`
`),t.cookware&&t.cookware.length>0&&(n+=`## \u{1F373} Cookware
`,t.cookware.forEach(r=>{r.type==="alternative"||r.type==="group"?(n+=`- **Alternative Group**:
`,r.options.forEach(s=>{n+=` - ${ge(s,e)}
`})):n+=`- ${ge(r,e)}
`}),n+=`
`),t.sections&&t.sections.length>0&&(n+=`## \u{1F468}\u200D\u{1F373} Instructions
`,t.sections.forEach(r=>{r.title&&(n+=`### ${r.title}`,r.retro_planning&&(n+=` {T-${r.retro_planning}}`),n+=`
`),r.ingredients&&r.ingredients.length>0&&(n+=`**Ingredients**:
`,r.ingredients.forEach(s=>{s.type==="alternative"||s.type==="group"?(n+=`- **Alternative Group**:
`,s.options.forEach(i=>{n+=` - ${Z(i,e)}
`})):n+=`- ${Z(s,e)}
`}),n+=`
`),r.steps.forEach((s,i)=>{if(s.type==="comment"){n+=`> *${s.value?s.value.trim():""}*
`;return}let a=i+1,l="";s.action&&(l+=`**[${s.action}]** `),s.type==="text"?l+=s.value:s.type==="step"&&(l+=s.content.map((o,p,u)=>{let c="";if(typeof o=="string")c=o;else if(o.type==="text")c=o.value;else if(o.type==="timer")c=`\u23F2\uFE0F${Be(o.quantity)}${o.unit?" "+o.unit:""}`;else if(o.type==="temperature")c=`\u{1F525}${Be(o.quantity)}${o.unit?" "+o.unit:""}`;else if(o.type==="reference"){c=`\u{1F449}*${e.ingredients[o.id]?.name||o.id}*`;let d=ve(o);d&&(c+=` (${d.text||d.value}`,o.unit&&(c+=` ${o.unit}`),c+=")")}else!o.type&&o.id?e.cookware[o.id]?c=`*${ge(o,e)}*`:c=`**${Z(o,e)}**`:o.type==="ingredient"?c=`**${Z(o,e)}**`:o.type==="cookware"?c=`*${ge(o,e)}*`:o.type==="alternative"?c=o.options.map(f=>f.type==="cookware"||e.cookware[f.id]?`*${ge(f,e)}*`:`**${Z(f,e)}**`).join(" or "):o.type==="group"?c=o.options.map(f=>f.type==="cookware"||e.cookware[f.id]?`*${ge(f,e)}*`:`**${Z(f,e)}**`).join(" or "):o.type==="comment"&&(c=` *${o.value.trim()}*`);if(typeof o!="string"&&o.type!=="text"&&o.type!=="comment"){let f=u[p+1];if(f){let d="";typeof f=="string"?d=f[0]:f.type==="text"&&(d=f.value?f.value[0]:""),d&&/^[.,!?:;)]/.test(d)||d&&/^\s/.test(d)||(c+=" ")}}return c}).join("")),n+=`${a}. ${l}
`}),n+=`
`})),n}function Z(t,e){let n=e.ingredients[t.id],r=n?n.name:t.id;t.alias&&(r=t.alias);let s=ve(t),i=t.formula?`${t.formula.percent}% of ${t.formula.target}`:null;if(t.formula&&t.formula.is_partial)r+=` (${i} \u26A0\uFE0F)`;else{let l=[];if(s){let o=s.text||s.value;t.unit&&(o+=` ${t.unit}`),l.push(o)}t.variable_entries&&t.variable_entries.length>0&&l.push(...t.variable_entries),l.length>0&&(r+=` (${l.join(" + ")})`),i&&(r+=` [${i}]`)}return t.preparation&&(r+=` (${t.preparation})`),t.modifiers&&t.modifiers.includes("optional")&&(r+=" (optional)"),r}function ge(t,e){let n=e.cookware[t.id],r=n?n.name:t.id;t.alias&&(r=t.alias);let s=ve(t);return s&&(r+=` (${s.value})`),r}function Ge(){let t=Y.value;try{let e=(0,cn.parse)(t),n="";re==="json"?(n=JSON.stringify(e,null,2),e.warnings&&e.warnings.length>0?Me(e.warnings):qe()):re==="markdown"?(n=Dr(e),e.warnings&&e.warnings.length>0?Me(e.warnings):qe()):re==="json-tree"?(n=Mr(e),e.warnings&&e.warnings.length>0?Me(e.warnings):qe()):re==="preview"&&(n=jr(e),e.warnings&&e.warnings.length>0?Me(e.warnings):qe());let r=document.getElementById("preview-output"),s=document.getElementById("output").parentElement;if(re==="preview"||re==="json-tree"){if(s.style.display="none",r.style.display="block",r.innerHTML=n,re==="json-tree"){let i=r.querySelector("#btn-expand-all"),a=r.querySelector("#btn-collapse-all");i&&a&&(i.addEventListener("click",()=>{r.querySelectorAll(".json-node").forEach(p=>{p.classList.remove("collapsed");let u=p.querySelector(".json-toggle");u&&(u.textContent="\u25BC")})}),a.addEventListener("click",()=>{r.querySelectorAll(".json-node").forEach((p,u)=>{if(u===0)return;p.classList.add("collapsed");let c=p.querySelector(".json-toggle");c&&(c.textContent="\u25B6")})})),r.querySelectorAll(".json-header").forEach(o=>{o.addEventListener("click",p=>{p.stopPropagation();let u=o.parentElement;u.classList.toggle("collapsed");let c=o.querySelector(".json-toggle");c&&(u.classList.contains("collapsed")?c.textContent="\u25B6":c.textContent="\u25BC")})})}}else s.style.display="block",s.style.removeProperty("display"),r.style.display="none",re==="json"?(J.textContent=n,J.className="language-json"):(J.textContent=n,J.className="language-markdown"),J.removeAttribute("data-highlighted"),hljs.highlightElement(J),hljs.lineNumbersBlock(J);je.textContent="Valid",je.className="status success"}catch(e){J.textContent=e.message,J.textContent=e.message,je.textContent="Error",je.className="status error"}}function jr(t){let e=t.registry||{ingredients:{},cookware:{}},n="";if(t.title&&(n+=`<h1>${_(t.title)}</h1>
`),t.meta&&Object.keys(t.meta).length>0){n+=`<div class="metadata">
`,n+=` <ul>
`;for(let[r,s]of Object.entries(t.meta))r!=="title"&&(n+=` <li><strong>${_(r)}</strong>: ${_(s)}</li>
`);n+=` </ul>
`,n+=`</div>
`}return t.shopping_list&&t.shopping_list.length>0&&(n+=`<div class="shopping-list">
`,n+=` <h2>Shopping List</h2>
`,n+=` <ul>
`,t.shopping_list.forEach(r=>{r.type==="alternative"||r.type==="group"?(n+=` <li>
`,n+=` <strong>Alternative Group</strong>:
`,n+=` <ul>
`,r.options.forEach(s=>{n+=` <li>${ne(s,e)}</li>
`}),n+=` </ul>
`,n+=` </li>
`):r.type==="composite"?(n+=` <li>
`,n+=` <strong>${ne(r,e)}</strong> (Composite):
`,n+=` <ul>
`,r.usage.forEach(s=>{n+=` <li>${ne(s,e)}</li>
`}),n+=` </ul>
`,n+=` </li>
`):r.display?n+=` <li>${_(r.display)}</li>
`:n+=` <li>${ne(r,e)}</li>
`}),n+=` </ul>
`,n+=`</div>
`),t.cookware&&t.cookware.length>0&&(n+=`<div class="cookware">
`,n+=` <h2>Cookware</h2>
`,n+=` <ul>
`,t.cookware.forEach(r=>{r.type==="alternative"||r.type==="group"?(n+=` <li>
`,n+=` <strong>Alternative Group</strong>:
`,n+=` <ul>
`,r.options.forEach(s=>{n+=` <li>${be(s,e)}</li>
`}),n+=` </ul>
`,n+=` </li>
`):n+=` <li>${be(r,e)}</li>
`}),n+=` </ul>
`,n+=`</div>
`),t.sections&&t.sections.length>0&&(n+=`<div class="instructions">
`,t.sections.forEach(r=>{if(n+=` <section>
`,r.title){let s=_(r.title);r.retro_planning&&(s+=` <small style="font-size:0.6em;opacity:0.8;border:1px solid currentColor;border-radius:4px;padding:2px 6px;vertical-align:middle;">\u23F1 ${_(r.retro_planning)}</small>`),n+=` <h3>${s}</h3>
`}r.ingredients&&r.ingredients.length>0&&(n+=` <div class="section-ingredients">
`,n+=` <h4>Ingredients</h4>
`,n+=` <ul>
`,r.ingredients.forEach(s=>{s.type==="alternative"||s.type==="group"?(n+=` <li>
`,n+=` <strong>Alternative Group</strong>:
`,n+=` <ul>
`,s.options.forEach(i=>{n+=` <li>${ne(i,e)}</li>
`}),n+=` </ul>
`,n+=` </li>
`):n+=` <li>${ne(s,e)}</li>
`}),n+=` </ul>
`,n+=` </div>
`),n+=` <ol class="steps">
`,r.steps.forEach((s,i)=>{if(s.type==="comment"){n+=` <li style="list-style: none; margin-left: -1em; color: gray; font-style: italic;">
`,n+=` ${_(s.value)}
`,n+=` </li>
`;return}n+=` <li>
`,s.action&&(n+=` <span class="action">[${_(s.action)}]</span> `);let a="";s.type==="text"?a=_(s.value):s.type==="step"&&(a=s.content.map((l,o,p)=>{let u="";if(typeof l=="string")u=_(l);else if(l.type==="text")u=_(l.value);else if(l.type==="timer"){let h=l.quantity||{value:""},f=Be(h);u=`<span class="timer" data-value="${h.value}" data-unit="${l.unit||""}">${f}${l.unit?" "+l.unit:""}</span>`}else if(l.type==="temperature"){let h=l.quantity||{value:""},f=Be(h);u=`<span class="temp" data-value="${h.value}" data-unit="${l.unit||""}">${f}${l.unit?" "+l.unit:""}</span>`}else if(l.type==="reference"){let h=e.ingredients[l.id]?.name||l.id,f=`<span class="reference">${_(h)}`,d=ve(l);d&&(f+=` <span class="quantity">${d.text||d.value}`,l.unit&&(f+=` <span class="unit">${l.unit}</span>`),f+="</span>"),f+="</span>",u=f}else!l.type&&l.id?e.cookware[l.id]?u=be(l,e):u=ne(l,e):l.type==="ingredient"?u=ne(l,e):l.type==="cookware"?u=be(l,e):l.type==="alternative"||l.type==="group"?u=l.options.map(h=>h.type==="cookware"||e.cookware[h.id]?be(h,e):ne(h,e)).join(' <span class="keyword">or</span> '):l.type==="comment"&&(u=`<!-- ${_(l.value.trim())} -->`);if(typeof l!="string"&&l.type!=="text"&&l.type!=="comment"){let h=p[o+1];if(h){let f="";typeof h=="string"?f=h[0]:h.type==="text"&&(f=h.value?h.value[0]:""),f&&/^[.,!?:;)]/.test(f)||f&&/^\s/.test(f)||(u+=" ")}}return u}).join("")),n+=` ${a}
`,n+=` </li>
`}),n+=` </ol>
`,n+=` </section>
`}),n+=`</div>
`),n}function Mr(t){let e=`<div class="json-controls">
<button id="btn-expand-all" class="tree-btn">Expand All</button>
<button id="btn-collapse-all" class="tree-btn">Collapse All</button>
</div>`;return e+=`<div class="json-tree">${hn(t,null,!1)}</div>`,e}function hn(t,e=null,n=!1){let r=n?'<span class="json-comma">,</span>':"",s=e?`<span class="json-key">"${_(e)}"</span>: `:"";if(t===null||typeof t!="object"){let f="";t===null&&(f='<span class="json-null">null</span>'),typeof t=="boolean"&&(f=`<span class="json-bool">${t}</span>`),typeof t=="number"&&(f=`<span class="json-num">${t}</span>`),typeof t=="string"&&(f=`<span class="json-str">"${_(t)}"</span>`);let d=`${s}${f}${r}`;return`<div class="${e?"json-prop":"json-item"}">${d}</div>`}let i=Array.isArray(t),a=i?t:Object.keys(t),l=a.length===0,o=i?"[":"{",p=i?"]":"}",u=i?"json-bracket":"json-brace",c=`${a.length} items`;if(l)return`<div class="${e?"json-prop":"json-item"}">${s}<span class="${u}">${o}${p}</span>${r}</div>`;let h='<div class="json-node expanded">';return h+='<div class="json-header">',h+='<span class="json-toggle">\u25BC</span>',h+=s,h+=`<span class="${u}">${o}</span>`,h+=`<span class="json-count">${c}</span>`,h+="</div>",h+='<div class="json-children">',a.forEach((f,d)=>{let g=i?f:t[f];h+=hn(g,i?null:f,d<a.length-1)}),h+="</div>",h+=`<div class="json-footer"><span class="${u}">${p}</span>${r}</div>`,h+="</div>",h}function _(t){return t==null?"":String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function ne(t,e){let n=e.ingredients[t.id],r=n?n.name:t.id,s=r;t.alias&&(s=t.alias);let i=`<span class="ingredient" data-name="${_(r)}">${_(s)}`,a=ve(t),l=t.formula?`${t.formula.percent}% of ${_(t.formula.target)}`:null;if(t.formula&&t.formula.is_partial)i+=` <span class="quantity formula-qty" title="Calculation partial or failed">(${l} \u26A0\uFE0F)</span>`;else{let p="";if(a&&(p+=a.text||a.value,t.unit&&(p+=` <span class="unit">${_(t.unit)}</span>`)),t.variable_entries&&t.variable_entries.length>0){let u=t.variable_entries.join(" + ");p?p+=` + ${u}`:p=u}p&&(i+=` <span class="quantity">(${p})</span>`),l&&(i+=` <span class="formula" title="Base Mass Used: ${t.formula?t.formula.base_mass_used:""}g">[${l}]</span>`)}return t.preparation&&(i+=` <span class="prep">(${_(t.preparation)})</span>`),t.modifiers&&t.modifiers.includes("optional")&&(i+=' <span class="opt">(optional)</span>'),t.modifiers&&t.modifiers.includes("reference")&&(i+=' <span class="ref" title="Reference to existing ingredient">\u21A9\uFE0F</span>'),i+="</span>",i}function be(t,e){let n=e.cookware[t.id],r=n?n.name:t.id,s=r;t.alias&&(s=t.alias);let i=`<span class="cookware" data-name="${_(r)}">${_(s)}`,a=ve(t);return a&&(i+=` <span class="quantity">(${a.value})</span>`),i+="</span>",i}var Ae=document.getElementById("highlights");function vt(t){let e=t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return e=e.replace(/(\/\/.*)/g,'<span class="token-comment">$1</span>'),t.split(`
`).map(s=>{let i=s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return i.trim().startsWith("//")?`<span class="token-comment">${i}</span>`:i.trim().startsWith("##")?`<span class="token-header">${i.replace(/(\{T-.*?\})/,'<span class="token-timer">$1</span>')}</span>`:i.trim()==="---"?`<span class="token-frontmatter">${i}</span>`:(i=i.replace(/^(\s*)(\[)([^\]]+)(\])/,'$1<span class="token-action">$2$3$4</span>'),i=i.replace(/(-&gt;&amp;|[@#~!&])((?:\[.*?\]|[^\{\[\<\(\|\@\#\~\!\n])*)(\{.*?\})?/g,(a,l,o,p)=>{if(l==="!"&&!p&&(!o||!o.trim().match(/[a-zA-Z0-9]/)))return a;let u=l,c=o;if(l==="&"){if(o==="lt;"||o==="gt;"||o==="amp;")return a;o.startsWith("amp;")&&(c=o.slice(4))}l==="-&gt;&amp;"&&(u="->&");let h="token-ingredient";l==="#"&&(h="token-cookware"),l==="~"&&(h="token-timer"),l==="!"&&(h="token-temp"),(l==="&"||l==="-&gt;&amp;")&&(h="token-decl");let f=`<span class="${h}">${u}</span>`,d=`<span class="${h}">${c}</span>`,g="";return p&&(g=`<span class="${h}">${p}</span>`,g=g.replace(/(\d+(?:\.\d+)?)/g,'<span class="token-qty">$1</span>'),g=g.replace(/(%)([\w°]+)/g,'<span class="token-syntax">$1</span><span class="token-unit">$2</span>')),`${f}${d}${g}`}),i)}).join(`
`)+"<br>"}function qr(){let t=Y.value;Ae.innerHTML=vt(t),Ge()}function Br(){Ae.scrollTop=Y.scrollTop,Ae.scrollLeft=Y.scrollLeft}Y.addEventListener("scroll",Br);Y.addEventListener("input",()=>{Ae.innerHTML=vt(Y.value)});var Gr=$r(Ge,300);Y.addEventListener("input",Gr);Ae.innerHTML=vt(Y.value);Ge();function Me(t){if(!we)return;we.style.display="block";let e='<div style="color: #ef4444; font-weight: bold; margin-bottom: 0.5rem;">\u26A0\uFE0F Compiler Warnings</div>';e+='<ul style="margin: 0; padding-left: 1.5rem; color: #ef4444;">',t.forEach(n=>{e+=`<li>[${n.code}] ${n.message}</li>`}),e+="</ul>",we.innerHTML=e}function qe(){we&&(we.style.display="none")}var ye=document.getElementById("copy-btn");ye.addEventListener("click",()=>{let t=J.textContent;navigator.clipboard.writeText(t).then(()=>{let e=ye.innerHTML;ye.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 256 256"><path d="M229.66,55.51a8,8,0,0,0-11.32,0L102.5,171.34,49.66,118.51a8,8,0,0,0-11.32,11.32l58.5,58.5a8,8,0,0,0,11.32,0L229.66,66.83A8,8,0,0,0,229.66,55.51Z"></path></svg>',ye.style.color="var(--token-def)",setTimeout(()=>{ye.innerHTML=e,ye.style.color=""},2e3)}).catch(e=>{console.error("Failed to copy: ",e)})});var ln=document.getElementById("examples-select"),un={pancakes:"examples/pancakes.gram",spaghetti:"examples/spaghetti.gram",torture:"examples/torture.gram"};ln&&ln.addEventListener("change",t=>{let e=t.target.value;un[e]&&fetch(un[e]).then(n=>{if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return n.text()}).then(n=>{Y.value=n,qr()}).catch(n=>{console.error("Could not load example:",n),alert("Error loading example file.")}),t.target.value=""});})();
//# sourceMappingURL=app.js.map