ohm-js
Version:
1 lines • 95.5 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ohm={})}(this,(function(t){"use strict";function e(t){const e=t||"";return function(){throw new Error("this method "+e+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function r(t,e){if(!t)throw new Error(e||"Assertion failed")}function n(t,e,r){let n;Object.defineProperty(t,e,{get(){return n||(n=r.call(this)),n}})}function i(t,e){const r=[];for(;e-- >0;)r.push(t());return r}function s(t,e){return new Array(e+1).join(t)}function o(t,e){return i((()=>t),e)}function a(t){const e=[];for(let r=0;r<t.length;r++){const n=t[r];t.lastIndexOf(n)!==r&&e.indexOf(n)<0&&e.push(n)}return e}function u(t){const e=[];return t.forEach((t=>{e.indexOf(t)<0&&e.push(t)})),e}function c(t){const e=t[0];return e===e.toUpperCase()}function l(t){return!c(t)}function p(t,e,r){const n=r||" ";return t.length<e?s(n,e-t.length)+t:t}function h(){this.strings=[]}h.prototype.append=function(t){this.strings.push(t)},h.prototype.contents=function(){return this.strings.join("")};const m=t=>String.fromCodePoint(parseInt(t,16));function d(t){if("\\"!==t.charAt(0))return t;switch(t.charAt(1)){case"b":return"\b";case"f":return"\f";case"n":return"\n";case"r":return"\r";case"t":return"\t";case"v":return"\v";case"x":return m(t.slice(2,4));case"u":return"{"===t.charAt(2)?m(t.slice(3,-1)):m(t.slice(2,6));default:return t.charAt(1)}}function f(t){if(null==t)return String(t);const e=Object.prototype.toString.call(t);try{let r;return r=t.constructor&&t.constructor.name?t.constructor.name:0===e.indexOf("[object ")?e.slice(8,-1):typeof t,r+": "+JSON.stringify(String(t))}catch{return e}}function g(t,e="unexpected null value"){if(null==t)throw new Error(e);return t}var v=Object.freeze({__proto__:null,abstract:e,assert:r,defineLazyProperty:n,clone:function(t){return t?Object.assign({},t):t},repeatFn:i,repeatStr:s,repeat:o,getDuplicates:a,copyWithoutDuplicates:u,isSyntactic:c,isLexical:l,padLeft:p,StringBuffer:h,unescapeCodePoint:d,unexpectedObjToString:f,checkNotNull:g});const I=t=>new RegExp(String.raw`\p{${t}}`,"u"),y=Object.fromEntries(["Cc","Cf","Cn","Co","Cs","Ll","Lm","Lo","Lt","Lu","Mc","Me","Mn","Nd","Nl","No","Pc","Pd","Pe","Pf","Pi","Po","Ps","Sc","Sk","Sm","So","Zl","Zp","Zs"].map((t=>[t,I(t)])));y.Ltmo=/\p{Lt}|\p{Lm}|\p{Lo}/u;const x=Object.fromEntries(["XID_Start","XID_Continue","White_Space"].map((t=>[t,I(t)])));class S{constructor(){if(this.constructor===S)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(t){return t&&(this.source=t.trimmed()),this}}const b=Object.create(S.prototype),_=Object.create(S.prototype);class w extends S{constructor(t){super(),this.obj=t}}class A extends S{constructor(t,e){super(),this.from=t,this.to=e,this.matchCodePoint=t.length>1||e.length>1}}class N extends S{constructor(t){super(),this.index=t}}class O extends S{constructor(t){super(),this.terms=t}}class R extends O{constructor(t,e,r){super([r,t.rules[e].body]),this.superGrammar=t,this.name=e,this.body=r}}class L extends O{constructor(t,e,r,n){const i=t.rules[e].body;super([...r,i,...n]),this.superGrammar=t,this.ruleName=e,this.expansionPos=r.length}}class P extends S{constructor(t){super(),this.factors=t}}class F extends S{constructor(t){super(),this.expr=t}}class E extends F{}class C extends F{}class T extends F{}E.prototype.operator="*",C.prototype.operator="+",T.prototype.operator="?",E.prototype.minNumMatches=0,C.prototype.minNumMatches=1,T.prototype.minNumMatches=0,E.prototype.maxNumMatches=Number.POSITIVE_INFINITY,C.prototype.maxNumMatches=Number.POSITIVE_INFINITY,T.prototype.maxNumMatches=1;class k extends S{constructor(t){super(),this.expr=t}}class D extends S{constructor(t){super(),this.expr=t}}class j extends S{constructor(t){super(),this.expr=t}}class M extends S{constructor(t,e=[]){super(),this.ruleName=t,this.args=e}isSyntactic(){return c(this.ruleName)}toMemoKey(){return this._memoKey||Object.defineProperty(this,"_memoKey",{value:this.toString()}),this._memoKey}}class G extends S{constructor(t){if(super(),this.categoryOrProp=t,t in y)this.pattern=y[t];else{if(!(t in x))throw new Error(`Invalid Unicode category or property name: ${JSON.stringify(t)}`);this.pattern=x[t]}}}function B(t,e){let r;return e?(r=new Error(e.getLineAndColumnMessage()+t),r.shortMessage=t,r.interval=e):r=new Error(t),r}function q(){return B("Interval sources don't match")}function U(t,e,r){return B("Rule "+t+" is not declared in grammar "+e,r)}function $(t,e,r,n){let i="Duplicate declaration for rule '"+t+"' in grammar '"+e+"'";return e!==r&&(i+=" (originally declared in '"+r+"')"),B(i,n)}function z(t,e,r,n){return B("Wrong number of parameters for rule "+t+" (expected "+e+", got "+r+")",n)}function K(t,e,r){return B("Duplicate parameter names in rule "+t+": "+e.join(", "),r)}function H(t,e){return B("Incorrect argument type: expected "+t,e.source)}function V(t,e){const r=e.length>0?e[e.length-1].args:[];let n="Nullable expression "+t.expr.substituteParams(r)+" is not allowed inside '"+t.operator+"' (possible infinite loop)";if(e.length>0){n+="\nApplication stack (most recent application last):\n"+e.map((t=>new M(t.ruleName,t.args))).join("\n")}return B(n,t.expr.source)}function W(t,e,r,n){return B("Rule "+t+" involves an alternation which has inconsistent arity (expected "+e+", got "+r+")",n.source)}function J(t){if(1===t.length)throw t[0];if(t.length>1)throw function(t){const e=t.map((t=>t.message));return B(["Errors:"].concat(e).join("\n- "),t[0].interval)}(t)}function Q(t,e,r){const n=t.length;return(t.slice(0,r)+e+t.slice(r+e.length)).substr(0,n)}function Z(...t){const e=this,{offset:n}=e,{repeatStr:i}=v,s=new h;s.append("Line "+e.lineNum+", col "+e.colNum+":\n");const o=function(t){let e=0;return t.map((t=>{const r=t.toString();return e=Math.max(e,r.length),r})).map((t=>p(t,e)))}([null==e.prevLine?0:e.lineNum-1,e.lineNum,null==e.nextLine?0:e.lineNum+1]),a=(t,e,r)=>{s.append(r+o[t]+" | "+e+"\n")};null!=e.prevLine&&a(0,e.prevLine," "),a(1,e.line,"> ");const u=e.line.length;let c=i(" ",u+1);for(let s=0;s<t.length;++s){let o=t[s][0],a=t[s][1];r(o>=0&&o<=a,"range start must be >= 0 and <= end");const l=n-e.colNum+1;o=Math.max(0,o-l),a=Math.min(a-l,u),c=Q(c,i("~",a-o),o)}const l=2+o[1].length+3;return s.append(i(" ",l)),c=Q(c,"^",e.colNum-1),s.append(c.replace(/ +$/,"")+"\n"),null!=e.nextLine&&a(2,e.nextLine," "),s.contents()}let X=[];function Y(t){X.push(t)}function tt(t,e){let r=1,n=1,i=0,s=0,o=null,a=null,u=-1;for(;i<e;){const e=t.charAt(i++);"\n"===e?(r++,n=1,u=s,s=i):"\r"!==e&&n++}let c=t.indexOf("\n",s);if(-1===c)c=t.length;else{const e=t.indexOf("\n",c+1);o=-1===e?t.slice(c):t.slice(c,e),o=o.replace(/^\r?\n/,"").replace(/\r$/,"")}u>=0&&(a=t.slice(u,s).replace(/\r?\n$/,""));return{offset:e,lineNum:r,colNum:n,line:t.slice(s,c).replace(/\r$/,""),prevLine:a,nextLine:o,toString:Z}}function et(t,e,...r){return tt(t,e).toString(...r)}const rt=(()=>{let t=0;return e=>""+e+t++})();class nt{constructor(t,e,r){Object.defineProperty(this,"_sourceString",{value:t,configurable:!1,enumerable:!1,writable:!1}),this.startIdx=e,this.endIdx=r}get sourceString(){return this._sourceString}get contents(){return void 0===this._contents&&(this._contents=this.sourceString.slice(this.startIdx,this.endIdx)),this._contents}get length(){return this.endIdx-this.startIdx}coverageWith(...t){return nt.coverage(...t,this)}collapsedLeft(){return new nt(this.sourceString,this.startIdx,this.startIdx)}collapsedRight(){return new nt(this.sourceString,this.endIdx,this.endIdx)}getLineAndColumn(){return tt(this.sourceString,this.startIdx)}getLineAndColumnMessage(){const t=[this.startIdx,this.endIdx];return et(this.sourceString,this.startIdx,t)}minus(t){if(this.sourceString!==t.sourceString)throw q();return this.startIdx===t.startIdx&&this.endIdx===t.endIdx?[]:this.startIdx<t.startIdx&&t.endIdx<this.endIdx?[new nt(this.sourceString,this.startIdx,t.startIdx),new nt(this.sourceString,t.endIdx,this.endIdx)]:this.startIdx<t.endIdx&&t.endIdx<this.endIdx?[new nt(this.sourceString,t.endIdx,this.endIdx)]:this.startIdx<t.startIdx&&t.startIdx<this.endIdx?[new nt(this.sourceString,this.startIdx,t.startIdx)]:[this]}relativeTo(t){if(this.sourceString!==t.sourceString)throw q();return r(this.startIdx>=t.startIdx&&this.endIdx<=t.endIdx,"other interval does not cover this one"),new nt(this.sourceString,this.startIdx-t.startIdx,this.endIdx-t.startIdx)}trimmed(){const{contents:t}=this,e=this.startIdx+t.match(/^\s*/)[0].length,r=this.endIdx-t.match(/\s*$/)[0].length;return new nt(this.sourceString,e,r)}subInterval(t,e){const r=this.startIdx+t;return new nt(this.sourceString,r,r+e)}}nt.coverage=function(t,...e){let{startIdx:r,endIdx:n}=t;for(const i of e){if(i.sourceString!==t.sourceString)throw q();r=Math.min(r,i.startIdx),n=Math.max(n,i.endIdx)}return new nt(t.sourceString,r,n)};class it{constructor(t){this.source=t,this.pos=0,this.examinedLength=0}atEnd(){const t=this.pos>=this.source.length;return this.examinedLength=Math.max(this.examinedLength,this.pos+1),t}next(){const t=this.source[this.pos++];return this.examinedLength=Math.max(this.examinedLength,this.pos),t}nextCharCode(){const t=this.next();return t&&t.charCodeAt(0)}nextCodePoint(){const t=this.source.slice(this.pos++).codePointAt(0);return t>65535&&(this.pos+=1),this.examinedLength=Math.max(this.examinedLength,this.pos),t}matchString(t,e){let r;if(e){for(r=0;r<t.length;r++){const e=this.next(),n=t[r];if(null==e||e.toUpperCase()!==n.toUpperCase())return!1}return!0}for(r=0;r<t.length;r++)if(this.next()!==t[r])return!1;return!0}sourceSlice(t,e){return this.source.slice(t,e)}interval(t,e){return new nt(this.source,t,e||this.pos)}}class st{constructor(t,e,r,i,s,o,a){this.matcher=t,this.input=e,this.startExpr=r,this._cst=i,this._cstOffset=s,this._rightmostFailurePosition=o,this._rightmostFailures=a,this.failed()&&(n(this,"message",(function(){const t="Expected "+this.getExpectedText();return et(this.input,this.getRightmostFailurePosition())+t})),n(this,"shortMessage",(function(){const t="expected "+this.getExpectedText(),e=tt(this.input,this.getRightmostFailurePosition());return"Line "+e.lineNum+", col "+e.colNum+": "+t})))}succeeded(){return!!this._cst}failed(){return!this.succeeded()}getRightmostFailurePosition(){return this._rightmostFailurePosition}getRightmostFailures(){if(!this._rightmostFailures){this.matcher.setInput(this.input);const t=this.matcher._match(this.startExpr,{tracing:!1,positionToRecordFailures:this.getRightmostFailurePosition()});this._rightmostFailures=t.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");const t=new h;let e=this.getRightmostFailures();e=e.filter((t=>!t.isFluffy()));for(let r=0;r<e.length;r++)r>0&&(r===e.length-1?t.append(e.length>2?", or ":" or "):t.append(", ")),t.append(e[r].toString());return t.contents()}getInterval(){const t=this.getRightmostFailurePosition();return new nt(this.input,t,t)}}class ot{constructor(){this.applicationMemoKeyStack=[],this.memo={},this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,this.currentLeftRecursion=void 0}isActive(t){return this.applicationMemoKeyStack.indexOf(t.toMemoKey())>=0}enter(t){this.applicationMemoKeyStack.push(t.toMemoKey())}exit(){this.applicationMemoKeyStack.pop()}startLeftRecursion(t,e){e.isLeftRecursion=!0,e.headApplication=t,e.nextLeftRecursion=this.currentLeftRecursion,this.currentLeftRecursion=e;const{applicationMemoKeyStack:r}=this,n=r.indexOf(t.toMemoKey())+1,i=r.slice(n);e.isInvolved=function(t){return i.indexOf(t)>=0},e.updateInvolvedApplicationMemoKeys=function(){for(let t=n;t<r.length;t++){const e=r[t];this.isInvolved(e)||i.push(e)}}}endLeftRecursion(){this.currentLeftRecursion=this.currentLeftRecursion.nextLeftRecursion}shouldUseMemoizedResult(t){if(!t.isLeftRecursion)return!0;const{applicationMemoKeyStack:e}=this;for(let r=0;r<e.length;r++){const n=e[r];if(t.isInvolved(n))return!1}return!0}memoize(t,e){return this.memo[t]=e,this.maxExaminedLength=Math.max(this.maxExaminedLength,e.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,e.rightmostFailureOffset),e}clearObsoleteEntries(t,e){if(t+this.maxExaminedLength<=e)return;const{memo:r}=this;this.maxExaminedLength=0,this.maxRightmostFailureOffset=-1,Object.keys(r).forEach((n=>{const i=r[n];t+i.examinedLength>e?delete r[n]:(this.maxExaminedLength=Math.max(this.maxExaminedLength,i.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,i.rightmostFailureOffset))}))}}const at={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function ut(t){return"string"==typeof t?t.replace(/ /g,"⋅").replace(/\t/g,"␉").replace(/\n/g,"␊").replace(/\r/g,"␍"):String(t)}class ct{constructor(t,e,r,n,i,s,o){this.input=t,this.pos=this.pos1=e,this.pos2=r,this.source=new nt(t,e,r),this.expr=n,this.bindings=s,this.children=o||[],this.terminatingLREntry=null,this._flags=i?at.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(t){const e=new ct(this.input,this.pos,this.pos2,t,this.succeeded,this.bindings,this.children);return e.isHeadOfLeftRecursion=this.isHeadOfLeftRecursion,e.isImplicitSpaces=this.isImplicitSpaces,e.isMemoized=this.isMemoized,e.isRootNode=this.isRootNode,e.terminatesLR=this.terminatesLR,e.terminatingLREntry=this.terminatingLREntry,e}recordLRTermination(t,e){this.terminatingLREntry=new ct(this.input,this.pos,this.pos2,this.expr,!1,[e],[t]),this.terminatingLREntry.terminatesLR=!0}walk(t,e){let r=t;function n(t,i,s){let o=!0;r.enter&&r.enter.call(e,t,i,s)===ct.prototype.SKIP&&(o=!1),o&&(t.children.forEach((e=>{n(e,t,s+1)})),r.exit&&r.exit.call(e,t,i,s))}"function"==typeof r&&(r={enter:r}),this.isRootNode?this.children.forEach((t=>{n(t,null,0)})):n(this,null,0)}toString(){const t=new h;return this.walk(((e,r,n)=>{if(!e)return this.SKIP;if("Alt"!==e.expr.constructor.name){if(t.append(function(t,e,r){const n=ut(t.slice(e,e+r));return n.length<r?n+o(" ",r-n.length).join(""):n}(e.input,e.pos,10)+o(" ",2*n+1).join("")),t.append((e.succeeded?"✓":"✗")+" "+e.displayString),e.isHeadOfLeftRecursion&&t.append(" (LR)"),e.succeeded){const r=ut(e.source.contents);t.append(" ⇒ "),t.append("string"==typeof r?'"'+r+'"':r)}t.append("\n")}})),t.contents()}}let lt,pt;ct.prototype.SKIP={},Object.keys(at).forEach((t=>{const e=at[t];Object.defineProperty(ct.prototype,t,{get(){return!!(this._flags&e)},set(t){t?this._flags|=e:this._flags&=~e}})})),S.prototype.allowsSkippingPrecedingSpace=e("allowsSkippingPrecedingSpace"),b.allowsSkippingPrecedingSpace=_.allowsSkippingPrecedingSpace=M.prototype.allowsSkippingPrecedingSpace=w.prototype.allowsSkippingPrecedingSpace=A.prototype.allowsSkippingPrecedingSpace=G.prototype.allowsSkippingPrecedingSpace=function(){return!0},O.prototype.allowsSkippingPrecedingSpace=F.prototype.allowsSkippingPrecedingSpace=j.prototype.allowsSkippingPrecedingSpace=D.prototype.allowsSkippingPrecedingSpace=k.prototype.allowsSkippingPrecedingSpace=N.prototype.allowsSkippingPrecedingSpace=P.prototype.allowsSkippingPrecedingSpace=function(){return!1},Y((t=>{lt=t})),S.prototype.assertAllApplicationsAreValid=function(t,e){pt=0,this._assertAllApplicationsAreValid(t,e)},S.prototype._assertAllApplicationsAreValid=e("_assertAllApplicationsAreValid"),b._assertAllApplicationsAreValid=_._assertAllApplicationsAreValid=w.prototype._assertAllApplicationsAreValid=A.prototype._assertAllApplicationsAreValid=N.prototype._assertAllApplicationsAreValid=G.prototype._assertAllApplicationsAreValid=function(t,e){},j.prototype._assertAllApplicationsAreValid=function(t,e){pt++,this.expr._assertAllApplicationsAreValid(t,e),pt--},O.prototype._assertAllApplicationsAreValid=function(t,e){for(let r=0;r<this.terms.length;r++)this.terms[r]._assertAllApplicationsAreValid(t,e)},P.prototype._assertAllApplicationsAreValid=function(t,e){for(let r=0;r<this.factors.length;r++)this.factors[r]._assertAllApplicationsAreValid(t,e)},F.prototype._assertAllApplicationsAreValid=k.prototype._assertAllApplicationsAreValid=D.prototype._assertAllApplicationsAreValid=function(t,e){this.expr._assertAllApplicationsAreValid(t,e)},M.prototype._assertAllApplicationsAreValid=function(t,e,r=!1){const n=e.rules[this.ruleName],i=c(t)&&0===pt;if(!n)throw U(this.ruleName,e.name,this.source);if(!r&&c(this.ruleName)&&!i)throw function(t,e){return B("Cannot apply syntactic rule "+t+" from here (inside a lexical context)",e.source)}(this.ruleName,this);const s=this.args.length,o=n.formals.length;if(s!==o)throw function(t,e,r,n){return B("Wrong number of arguments for rule "+t+" (expected "+e+", got "+r+")",n)}(this.ruleName,o,s,this.source);const a=lt&&n===lt.rules.applySyntactic;if(lt&&n===lt.rules.caseInsensitive&&!(this.args[0]instanceof w))throw H('a Terminal (e.g. "abc")',this.args[0]);if(a){const t=this.args[0];if(!(t instanceof M))throw H("a syntactic rule application",t);if(!c(t.ruleName))throw function(t){const{ruleName:e}=t;return B(`applySyntactic is for syntactic rules, but '${e}' is a lexical rule. NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. See https://ohmjs.org/d/svl for more details.`,t.source)}(t);if(i)throw B("applySyntactic is not required here (in a syntactic context)",this.source)}this.args.forEach((r=>{if(r._assertAllApplicationsAreValid(t,e,a),1!==r.getArity())throw function(t,e){return B("Invalid parameter to rule "+t+": "+e+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)}(this.ruleName,r)}))},S.prototype.assertChoicesHaveUniformArity=e("assertChoicesHaveUniformArity"),b.assertChoicesHaveUniformArity=_.assertChoicesHaveUniformArity=w.prototype.assertChoicesHaveUniformArity=A.prototype.assertChoicesHaveUniformArity=N.prototype.assertChoicesHaveUniformArity=j.prototype.assertChoicesHaveUniformArity=G.prototype.assertChoicesHaveUniformArity=function(t){},O.prototype.assertChoicesHaveUniformArity=function(t){if(0===this.terms.length)return;const e=this.terms[0].getArity();for(let r=0;r<this.terms.length;r++){const n=this.terms[r];n.assertChoicesHaveUniformArity();const i=n.getArity();if(e!==i)throw W(t,e,i,n)}},R.prototype.assertChoicesHaveUniformArity=function(t){const e=this.terms[0].getArity(),r=this.terms[1].getArity();if(e!==r)throw W(t,r,e,this.terms[0])},P.prototype.assertChoicesHaveUniformArity=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertChoicesHaveUniformArity(t)},F.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)},k.prototype.assertChoicesHaveUniformArity=function(t){},D.prototype.assertChoicesHaveUniformArity=function(t){this.expr.assertChoicesHaveUniformArity(t)},M.prototype.assertChoicesHaveUniformArity=function(t){},S.prototype.assertIteratedExprsAreNotNullable=e("assertIteratedExprsAreNotNullable"),b.assertIteratedExprsAreNotNullable=_.assertIteratedExprsAreNotNullable=w.prototype.assertIteratedExprsAreNotNullable=A.prototype.assertIteratedExprsAreNotNullable=N.prototype.assertIteratedExprsAreNotNullable=G.prototype.assertIteratedExprsAreNotNullable=function(t){},O.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.terms.length;e++)this.terms[e].assertIteratedExprsAreNotNullable(t)},P.prototype.assertIteratedExprsAreNotNullable=function(t){for(let e=0;e<this.factors.length;e++)this.factors[e].assertIteratedExprsAreNotNullable(t)},F.prototype.assertIteratedExprsAreNotNullable=function(t){if(this.expr.assertIteratedExprsAreNotNullable(t),this.expr.isNullable(t))throw V(this,[])},T.prototype.assertIteratedExprsAreNotNullable=k.prototype.assertIteratedExprsAreNotNullable=D.prototype.assertIteratedExprsAreNotNullable=j.prototype.assertIteratedExprsAreNotNullable=function(t){this.expr.assertIteratedExprsAreNotNullable(t)},M.prototype.assertIteratedExprsAreNotNullable=function(t){this.args.forEach((e=>{e.assertIteratedExprsAreNotNullable(t)}))};class ht{constructor(t){this.matchLength=t}get ctorName(){throw new Error("subclass responsibility")}numChildren(){return this.children?this.children.length:0}childAt(t){if(this.children)return this.children[t]}indexOfChild(t){return this.children.indexOf(t)}hasChildren(){return this.numChildren()>0}hasNoChildren(){return!this.hasChildren()}onlyChild(){if(1!==this.numChildren())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(t){const e=this.indexOfChild(t);if(e<0)throw new Error("Node.childBefore() called w/ an argument that is not a child");if(0===e)throw new Error("cannot get child before first child");return this.childAt(e-1)}childAfter(t){const e=this.indexOfChild(t);if(e<0)throw new Error("Node.childAfter() called w/ an argument that is not a child");if(e===this.numChildren()-1)throw new Error("cannot get child after last child");return this.childAt(e+1)}isTerminal(){return!1}isNonterminal(){return!1}isIteration(){return!1}isOptional(){return!1}}class mt extends ht{get ctorName(){return"_terminal"}isTerminal(){return!0}get primitiveValue(){throw new Error("The `primitiveValue` property was removed in Ohm v17.")}}class dt extends ht{constructor(t,e,r,n){super(n),this.ruleName=t,this.children=e,this.childOffsets=r}get ctorName(){return this.ruleName}isNonterminal(){return!0}isLexical(){return l(this.ctorName)}isSyntactic(){return c(this.ctorName)}}class ft extends ht{constructor(t,e,r,n){super(r),this.children=t,this.childOffsets=e,this.optional=n}get ctorName(){return"_iter"}isIteration(){return!0}isOptional(){return this.optional}}function gt(t,e){const r={};if(t.source&&e){const n=t.source.relativeTo(e);r.sourceInterval=[n.startIdx,n.endIdx]}return r}function vt(t){return/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)}function It(t){const e=Object.create(null);t.forEach((t=>{e[t]=(e[t]||0)+1})),Object.keys(e).forEach((r=>{if(e[r]<=1)return;let n=1;t.forEach(((e,i)=>{e===r&&(t[i]=e+"_"+n++)}))}))}S.prototype.eval=e("eval"),b.eval=function(t){const{inputStream:e}=t,r=e.pos,n=e.nextCodePoint();return void 0!==n?(t.pushBinding(new mt(String.fromCodePoint(n).length),r),!0):(t.processFailure(r,this),!1)},_.eval=function(t){const{inputStream:e}=t,r=e.pos;return e.atEnd()?(t.pushBinding(new mt(0),r),!0):(t.processFailure(r,this),!1)},w.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;return e.matchString(this.obj)?(t.pushBinding(new mt(this.obj.length),r),!0):(t.processFailure(r,this),!1)},A.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=this.matchCodePoint?e.nextCodePoint():e.nextCharCode();return void 0!==n&&this.from.codePointAt(0)<=n&&n<=this.to.codePointAt(0)?(t.pushBinding(new mt(String.fromCodePoint(n).length),r),!0):(t.processFailure(r,this),!1)},N.prototype.eval=function(t){return t.eval(t.currentApplication().args[this.index])},j.prototype.eval=function(t){t.enterLexifiedContext();const e=t.eval(this.expr);return t.exitLexifiedContext(),e},O.prototype.eval=function(t){for(let e=0;e<this.terms.length;e++)if(t.eval(this.terms[e]))return!0;return!1},P.prototype.eval=function(t){for(let e=0;e<this.factors.length;e++){const r=this.factors[e];if(!t.eval(r))return!1}return!0},F.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=this.getArity(),i=[],s=[];for(;i.length<n;)i.push([]),s.push([]);let o,a=0,u=r;for(;a<this.maxNumMatches&&t.eval(this.expr);){if(e.pos===u)throw V(this,t._applicationStack);u=e.pos,a++;const r=t._bindings.splice(t._bindings.length-n,n),c=t._bindingOffsets.splice(t._bindingOffsets.length-n,n);for(o=0;o<r.length;o++)i[o].push(r[o]),s[o].push(c[o])}if(a<this.minNumMatches)return!1;let c=t.posToOffset(r),l=0;if(a>0){const t=i[n-1],e=s[n-1],r=e[e.length-1]+t[t.length-1].matchLength;c=s[0][0],l=r-c}const p=this instanceof T;for(o=0;o<i.length;o++)t._bindings.push(new ft(i[o],s[o],l,p)),t._bindingOffsets.push(c);return!0},k.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;t.pushFailuresInfo();const n=t.eval(this.expr);return t.popFailuresInfo(),n?(t.processFailure(r,this),!1):(e.pos=r,!0)},D.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos;return!!t.eval(this.expr)&&(e.pos=r,!0)},M.prototype.eval=function(t){const e=t.currentApplication(),r=e?e.args:[],n=this.substituteParams(r),i=t.getCurrentPosInfo();if(i.isActive(n))return n.handleCycle(t);const s=n.toMemoKey(),o=i.memo[s];if(o&&i.shouldUseMemoizedResult(o)){if(t.hasNecessaryInfo(o))return t.useMemoizedResult(t.inputStream.pos,o);delete i.memo[s]}return n.reallyEval(t)},M.prototype.handleCycle=function(t){const e=t.getCurrentPosInfo(),{currentLeftRecursion:r}=e,n=this.toMemoKey();let i=e.memo[n];return r&&r.headApplication.toMemoKey()===n?i.updateInvolvedApplicationMemoKeys():i||(i=e.memoize(n,{matchLength:0,examinedLength:0,value:!1,rightmostFailureOffset:-1}),e.startLeftRecursion(this,i)),t.useMemoizedResult(t.inputStream.pos,i)},M.prototype.reallyEval=function(t){const{inputStream:e}=t,n=e.pos,i=t.getCurrentPosInfo(),s=t.grammar.rules[this.ruleName],{body:o}=s,{description:a}=s;t.enterApplication(i,this),a&&t.pushFailuresInfo();const u=e.examinedLength;e.examinedLength=0;let c=this.evalOnce(o,t);const l=i.currentLeftRecursion,p=this.toMemoKey(),h=l&&l.headApplication.toMemoKey()===p;let m;t.doNotMemoize?t.doNotMemoize=!1:h?(c=this.growSeedResult(o,t,n,l,c),i.endLeftRecursion(),m=l,m.examinedLength=e.examinedLength-n,m.rightmostFailureOffset=t._getRightmostFailureOffset(),i.memoize(p,m)):l&&l.isInvolved(p)||(m=i.memoize(p,{matchLength:e.pos-n,examinedLength:e.examinedLength-n,value:c,failuresAtRightmostPosition:t.cloneRecordedFailures(),rightmostFailureOffset:t._getRightmostFailureOffset()}));const d=!!c;if(a&&(t.popFailuresInfo(),d||t.processFailure(n,this),m&&(m.failuresAtRightmostPosition=t.cloneRecordedFailures())),t.isTracing()&&m){const e=t.getTraceEntry(n,this,d,d?[c]:[]);h&&(r(null!=e.terminatingLREntry||!d),e.isHeadOfLeftRecursion=!0),m.traceEntry=e}return e.examinedLength=Math.max(e.examinedLength,u),t.exitApplication(i,c),d},M.prototype.evalOnce=function(t,e){const{inputStream:r}=e,n=r.pos;if(e.eval(t)){const i=t.getArity(),s=e._bindings.splice(e._bindings.length-i,i),o=e._bindingOffsets.splice(e._bindingOffsets.length-i,i),a=r.pos-n;return new dt(this.ruleName,s,o,a)}return!1},M.prototype.growSeedResult=function(t,e,r,n,i){if(!i)return!1;const{inputStream:s}=e;for(;;){if(n.matchLength=s.pos-r,n.value=i,n.failuresAtRightmostPosition=e.cloneRecordedFailures(),e.isTracing()){const t=e.trace[e.trace.length-1];n.traceEntry=new ct(e.input,r,s.pos,this,!0,[i],[t.clone()])}if(s.pos=r,i=this.evalOnce(t,e),s.pos-r<=n.matchLength)break;e.isTracing()&&e.trace.splice(-2,1)}return e.isTracing()&&n.traceEntry.recordLRTermination(e.trace.pop(),i),s.pos=r+n.matchLength,n.value},G.prototype.eval=function(t){const{inputStream:e}=t,r=e.pos,n=e.nextCodePoint();if(void 0!==n&&n<=1114111){const e=String.fromCodePoint(n);if(this.pattern.test(e))return t.pushBinding(new mt(e.length),r),!0}return t.processFailure(r,this),!1},S.prototype.getArity=e("getArity"),b.getArity=_.getArity=w.prototype.getArity=A.prototype.getArity=N.prototype.getArity=M.prototype.getArity=G.prototype.getArity=function(){return 1},O.prototype.getArity=function(){return 0===this.terms.length?0:this.terms[0].getArity()},P.prototype.getArity=function(){let t=0;for(let e=0;e<this.factors.length;e++)t+=this.factors[e].getArity();return t},F.prototype.getArity=function(){return this.expr.getArity()},k.prototype.getArity=function(){return 0},D.prototype.getArity=j.prototype.getArity=function(){return this.expr.getArity()},S.prototype.outputRecipe=e("outputRecipe"),b.outputRecipe=function(t,e){return["any",gt(this,e)]},_.outputRecipe=function(t,e){return["end",gt(this,e)]},w.prototype.outputRecipe=function(t,e){return["terminal",gt(this,e),this.obj]},A.prototype.outputRecipe=function(t,e){return["range",gt(this,e),this.from,this.to]},N.prototype.outputRecipe=function(t,e){return["param",gt(this,e),this.index]},O.prototype.outputRecipe=function(t,e){return["alt",gt(this,e)].concat(this.terms.map((r=>r.outputRecipe(t,e))))},R.prototype.outputRecipe=function(t,e){return this.terms[0].outputRecipe(t,e)},L.prototype.outputRecipe=function(t,e){const r=this.terms.slice(0,this.expansionPos),n=this.terms.slice(this.expansionPos+1);return["splice",gt(this,e),r.map((r=>r.outputRecipe(t,e))),n.map((r=>r.outputRecipe(t,e)))]},P.prototype.outputRecipe=function(t,e){return["seq",gt(this,e)].concat(this.factors.map((r=>r.outputRecipe(t,e))))},E.prototype.outputRecipe=C.prototype.outputRecipe=T.prototype.outputRecipe=k.prototype.outputRecipe=D.prototype.outputRecipe=j.prototype.outputRecipe=function(t,e){return[this.constructor.name.toLowerCase(),gt(this,e),this.expr.outputRecipe(t,e)]},M.prototype.outputRecipe=function(t,e){return["app",gt(this,e),this.ruleName,this.args.map((r=>r.outputRecipe(t,e)))]},G.prototype.outputRecipe=function(t,e){return["unicodeChar",gt(this,e),this.categoryOrProp]},S.prototype.introduceParams=e("introduceParams"),b.introduceParams=_.introduceParams=w.prototype.introduceParams=A.prototype.introduceParams=N.prototype.introduceParams=G.prototype.introduceParams=function(t){return this},O.prototype.introduceParams=function(t){return this.terms.forEach(((e,r,n)=>{n[r]=e.introduceParams(t)})),this},P.prototype.introduceParams=function(t){return this.factors.forEach(((e,r,n)=>{n[r]=e.introduceParams(t)})),this},F.prototype.introduceParams=k.prototype.introduceParams=D.prototype.introduceParams=j.prototype.introduceParams=function(t){return this.expr=this.expr.introduceParams(t),this},M.prototype.introduceParams=function(t){const 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)}return this.args.forEach(((e,r,n)=>{n[r]=e.introduceParams(t)})),this},S.prototype.isNullable=function(t){return this._isNullable(t,Object.create(null))},S.prototype._isNullable=e("_isNullable"),b._isNullable=A.prototype._isNullable=N.prototype._isNullable=C.prototype._isNullable=G.prototype._isNullable=function(t,e){return!1},_._isNullable=function(t,e){return!0},w.prototype._isNullable=function(t,e){return"string"==typeof this.obj&&""===this.obj},O.prototype._isNullable=function(t,e){return 0===this.terms.length||this.terms.some((r=>r._isNullable(t,e)))},P.prototype._isNullable=function(t,e){return this.factors.every((r=>r._isNullable(t,e)))},E.prototype._isNullable=T.prototype._isNullable=k.prototype._isNullable=D.prototype._isNullable=function(t,e){return!0},j.prototype._isNullable=function(t,e){return this.expr._isNullable(t,e)},M.prototype._isNullable=function(t,e){const r=this.toMemoKey();if(!Object.prototype.hasOwnProperty.call(e,r)){const{body:n}=t.rules[this.ruleName],i=n.substituteParams(this.args);e[r]=!1,e[r]=i._isNullable(t,e)}return e[r]},S.prototype.substituteParams=e("substituteParams"),b.substituteParams=_.substituteParams=w.prototype.substituteParams=A.prototype.substituteParams=G.prototype.substituteParams=function(t){return this},N.prototype.substituteParams=function(t){return g(t[this.index])},O.prototype.substituteParams=function(t){return new O(this.terms.map((e=>e.substituteParams(t))))},P.prototype.substituteParams=function(t){return new P(this.factors.map((e=>e.substituteParams(t))))},F.prototype.substituteParams=k.prototype.substituteParams=D.prototype.substituteParams=j.prototype.substituteParams=function(t){return new this.constructor(this.expr.substituteParams(t))},M.prototype.substituteParams=function(t){if(0===this.args.length)return this;{const e=this.args.map((e=>e.substituteParams(t)));return new M(this.ruleName,e)}},S.prototype.toArgumentNameList=e("toArgumentNameList"),b.toArgumentNameList=function(t,e){return["any"]},_.toArgumentNameList=function(t,e){return["end"]},w.prototype.toArgumentNameList=function(t,e){return"string"==typeof this.obj&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+t]},A.prototype.toArgumentNameList=function(t,e){let r=this.from+"_to_"+this.to;return vt(r)||(r="_"+r),vt(r)||(r="$"+t),[r]},O.prototype.toArgumentNameList=function(t,e){const r=this.terms.map((e=>e.toArgumentNameList(t,!0))),n=[],i=r[0].length;for(let t=0;t<i;t++){const e=[];for(let n=0;n<this.terms.length;n++)e.push(r[n][t]);const i=u(e);n.push(i.join("_or_"))}return e||It(n),n},P.prototype.toArgumentNameList=function(t,e){let r=[];return this.factors.forEach((e=>{const n=e.toArgumentNameList(t,!0);r=r.concat(n),t+=n.length})),e||It(r),r},F.prototype.toArgumentNameList=function(t,e){const r=this.expr.toArgumentNameList(t,e).map((t=>"s"===t[t.length-1]?t+"es":t+"s"));return e||It(r),r},T.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e).map((t=>"opt"+t[0].toUpperCase()+t.slice(1)))},k.prototype.toArgumentNameList=function(t,e){return[]},D.prototype.toArgumentNameList=j.prototype.toArgumentNameList=function(t,e){return this.expr.toArgumentNameList(t,e)},M.prototype.toArgumentNameList=function(t,e){return[this.ruleName]},G.prototype.toArgumentNameList=function(t,e){return["$"+t]},N.prototype.toArgumentNameList=function(t,e){return["param"+this.index]},S.prototype.toDisplayString=e("toDisplayString"),O.prototype.toDisplayString=P.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"},b.toDisplayString=_.toDisplayString=F.prototype.toDisplayString=k.prototype.toDisplayString=D.prototype.toDisplayString=j.prototype.toDisplayString=w.prototype.toDisplayString=A.prototype.toDisplayString=N.prototype.toDisplayString=function(){return this.toString()},M.prototype.toDisplayString=function(){if(this.args.length>0){const t=this.args.map((t=>t.toDisplayString()));return this.ruleName+"<"+t.join(",")+">"}return this.ruleName},G.prototype.toDisplayString=function(){return"Unicode ["+this.categoryOrProp+"] character"};class yt{constructor(t,e,r){if(!function(t){return"description"===t||"string"===t||"code"===t}(r))throw new Error("invalid Failure type: "+r);this.pexpr=t,this.text=e,this.type=r,this.fluffy=!1}getPExpr(){return this.pexpr}getText(){return this.text}getType(){return this.type}isDescription(){return"description"===this.type}isStringTerminal(){return"string"===this.type}isCode(){return"code"===this.type}isFluffy(){return this.fluffy}makeFluffy(){this.fluffy=!0}clearFluffy(){this.fluffy=!1}subsumes(t){return this.getText()===t.getText()&&this.type===t.type&&(!this.isFluffy()||this.isFluffy()&&t.isFluffy())}toString(){return"string"===this.type?JSON.stringify(this.getText()):this.getText()}clone(){const t=new yt(this.pexpr,this.text,this.type);return this.isFluffy()&&t.makeFluffy(),t}toKey(){return this.toString()+"#"+this.type}}S.prototype.toFailure=e("toFailure"),b.toFailure=function(t){return new yt(this,"any object","description")},_.toFailure=function(t){return new yt(this,"end of input","description")},w.prototype.toFailure=function(t){return new yt(this,this.obj,"string")},A.prototype.toFailure=function(t){return new yt(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")},k.prototype.toFailure=function(t){const e=this.expr===b?"nothing":"not "+this.expr.toFailure(t);return new yt(this,e,"description")},D.prototype.toFailure=function(t){return this.expr.toFailure(t)},M.prototype.toFailure=function(t){let{description:e}=t.rules[this.ruleName];if(!e){e=(/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a")+" "+this.ruleName}return new yt(this,e,"description")},G.prototype.toFailure=function(t){return new yt(this,"a Unicode ["+this.categoryOrProp+"] character","description")},O.prototype.toFailure=function(t){const e="("+this.terms.map((e=>e.toFailure(t))).join(" or ")+")";return new yt(this,e,"description")},P.prototype.toFailure=function(t){const e="("+this.factors.map((e=>e.toFailure(t))).join(" ")+")";return new yt(this,e,"description")},F.prototype.toFailure=function(t){const e="("+this.expr.toFailure(t)+this.operator+")";return new yt(this,e,"description")},S.prototype.toString=e("toString"),b.toString=function(){return"any"},_.toString=function(){return"end"},w.prototype.toString=function(){return JSON.stringify(this.obj)},A.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)},N.prototype.toString=function(){return"$"+this.index},j.prototype.toString=function(){return"#("+this.expr.toString()+")"},O.prototype.toString=function(){return 1===this.terms.length?this.terms[0].toString():"("+this.terms.map((t=>t.toString())).join(" | ")+")"},P.prototype.toString=function(){return 1===this.factors.length?this.factors[0].toString():"("+this.factors.map((t=>t.toString())).join(" ")+")"},F.prototype.toString=function(){return this.expr+this.operator},k.prototype.toString=function(){return"~"+this.expr},D.prototype.toString=function(){return"&"+this.expr},M.prototype.toString=function(){if(this.args.length>0){const t=this.args.map((t=>t.toString()));return this.ruleName+"<"+t.join(",")+">"}return this.ruleName},G.prototype.toString=function(){return"\\p{"+this.categoryOrProp+"}"};class xt extends S{constructor(t){super(),this.obj=t}_getString(t){const e=t.currentApplication().args[this.obj.index];return r(e instanceof w,"expected a Terminal expression"),e.obj}allowsSkippingPrecedingSpace(){return!0}eval(t){const{inputStream:e}=t,r=e.pos,n=this._getString(t);return e.matchString(n,!0)?(t.pushBinding(new mt(n.length),r),!0):(t.processFailure(r,this),!1)}getArity(){return 1}substituteParams(t){return new xt(this.obj.substituteParams(t))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(t){return new yt(this,this.obj.toFailure(t)+" (case-insensitive)","description")}_isNullable(t,e){return this.obj._isNullable(t,e)}}var St=Object.freeze({__proto__:null,CaseInsensitiveTerminal:xt,PExpr:S,any:b,end:_,Terminal:w,Range:A,Param:N,Alt:O,Extend:R,Splice:L,Seq:P,Iter:F,Star:E,Plus:C,Opt:T,Not:k,Lookahead:D,Lex:j,Apply:M,UnicodeChar:G});let bt;Y((t=>{bt=t.rules.applySyntactic.body}));const _t=new M("spaces");class wt{constructor(t,e,r){this.matcher=t,this.startExpr=e,this.grammar=t.grammar,this.input=t.getInput(),this.inputStream=new it(this.input),this.memoTable=t._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=[],void 0!==r&&(this.positionToRecordFailures=r,this.recordedFailures=Object.create(null))}posToOffset(t){return t-this._posStack[this._posStack.length-1]}enterApplication(t,e){this._posStack.push(this.inputStream.pos),this._applicationStack.push(e),this.inLexifiedContextStack.push(!1),t.enter(e),this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this.rightmostFailurePosition=-1}exitApplication(t,e){const r=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),t.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),e&&this.pushBinding(e,r)}enterLexifiedContext(){this.inLexifiedContextStack.push(!0)}exitLexifiedContext(){this.inLexifiedContextStack.pop()}currentApplication(){return this._applicationStack[this._applicationStack.length-1]}inSyntacticContext(){const t=this.currentApplication();return t?t.isSyntactic()&&!this.inLexifiedContext():this.startExpr.factors[0].isSyntactic()}inLexifiedContext(){return this.inLexifiedContextStack[this.inLexifiedContextStack.length-1]}skipSpaces(){return this.pushFailuresInfo(),this.eval(_t),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(t){return t.allowsSkippingPrecedingSpace()&&t!==_t?this.skipSpacesIfInSyntacticContext():this.inputStream.pos}pushBinding(t,e){this._bindings.push(t),this._bindingOffsets.push(this.posToOffset(e))}popBinding(){this._bindings.pop(),this._bindingOffsets.pop()}numBindings(){return this._bindings.length}truncateBindings(t){for(;this._bindings.length>t;)this.popBinding()}getCurrentPosInfo(){return this.getPosInfo(this.inputStream.pos)}getPosInfo(t){let e=this.memoTable[t];return e||(e=this.memoTable[t]=new ot),e}processFailure(t,e){if(this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,t),this.recordedFailures&&t===this.positionToRecordFailures){const t=this.currentApplication();t&&(e=e.substituteParams(t.args)),this.recordFailure(e.toFailure(this.grammar),!1)}}recordFailure(t,e){const r=t.toKey();this.recordedFailures[r]?this.recordedFailures[r].isFluffy()&&!t.isFluffy()&&this.recordedFailures[r].clearFluffy():this.recordedFailures[r]=e?t.clone():t}recordFailures(t,e){Object.keys(t).forEach((r=>{this.recordFailure(t[r],e)}))}cloneRecordedFailures(){if(!this.recordedFailures)return;const t=Object.create(null);return Object.keys(this.recordedFailures).forEach((e=>{t[e]=this.recordedFailures[e].clone()})),t}getRightmostFailurePosition(){return this.rightmostFailurePosition}_getRightmostFailureOffset(){return this.rightmostFailurePosition>=0?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(t,e){const r=this.memoTable[t];if(r&&e instanceof M){const t=r.memo[e.toMemoKey()];if(t&&t.traceEntry){const r=t.traceEntry.cloneWithExpr(e);return r.isMemoized=!0,r}}return null}getTraceEntry(t,e,r,n){if(e instanceof M){const t=this.currentApplication(),r=t?t.args:[];e=e.substituteParams(r)}return this.getMemoizedTraceEntry(t,e)||new ct(this.input,t,this.inputStream.pos,e,r,n,this.trace)}isTracing(){return!!this.trace}hasNecessaryInfo(t){return!(this.trace&&!t.traceEntry)&&(!this.recordedFailures||this.inputStream.pos+t.rightmostFailureOffset!==this.positionToRecordFailures||!!t.failuresAtRightmostPosition)}useMemoizedResult(t,e){this.trace&&this.trace.push(e.traceEntry);const r=this.inputStream.pos+e.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,r),this.recordedFailures&&this.positionToRecordFailures===r&&e.failuresAtRightmostPosition&&this.recordFailures(e.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,e.examinedLength+t),!!e.value&&(this.inputStream.pos+=e.matchLength,this.pushBinding(e.value,t),!0)}eval(t){const{inputStream:e}=this,r=this._bindings.length,n=this.userData;let i;this.recordedFailures&&(i=this.recordedFailures,this.recordedFailures=Object.create(null));const s=e.pos,o=this.maybeSkipSpacesBefore(t);let a;this.trace&&(a=this.trace,this.trace=[]);const u=t.eval(this);if(this.trace){const e=this._bindings.slice(r),n=this.getTraceEntry(o,t,u,e);n.isImplicitSpaces=t===_t,n.isRootNode=t===this.startExpr,a.push(n),this.trace=a}return u?this.recordedFailures&&e.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach((t=>{this.recordedFailures[t].makeFluffy()})):(e.pos=s,this.truncateBindings(r),this.userData=n),this.recordedFailures&&this.recordFailures(i,!1),t===bt&&this.skipSpaces(),u}getMatchResult(){let t;this.grammar._setUpMatchState(this),this.eval(this.startExpr),this.recordedFailures&&(t=Object.keys(this.recordedFailures).map((t=>this.recordedFailures[t])));const e=this._bindings[0];return e&&(e.grammar=this.grammar),new st(this.matcher,this.input,this.startExpr,e,this._bindingOffsets[0],this.rightmostFailurePosition,t)}getTrace(){this.trace=[];const t=this.getMatchResult(),e=this.trace[this.trace.length-1];return e.result=t,e}pushFailuresInfo(){this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this._recordedFailuresStack.push(this.recordedFailures)}popFailuresInfo(){this.rightmostFailurePosition=this._rightmostFailurePositionStack.pop(),this.recordedFailures=this._recordedFailuresStack.pop()}}class At{constructor(t){this.grammar=t,this._memoTable=[],this._input="",this._isMemoTableStale=!1}_resetMemoTable(){this._memoTable=[],this._isMemoTableStale=!1}getInput(){return this._input}setInput(t){return this._input!==t&&this.replaceInputRange(0,this._input.length,t),this}replaceInputRange(t,e,r){const n=this._input,i=this._memoTable;if(t<0||t>n.length||e<0||e>n.length||t>e)throw new Error("Invalid indices: "+t+" and "+e);this._input=n.slice(0,t)+r+n.slice(e),this._input!==n&&i.length>0&&(this._isMemoTableStale=!0);const s=i.slice(e);i.length=t;for(let t=0;t<r.length;t++)i.push(void 0);for(const t of s)i.push(t);for(let e=0;e<t;e++){const r=i[e];r&&r.clearObsoleteEntries(e,t)}return this}match(t,e={incremental:!0}){return this._match(this._getStartExpr(t),{incremental:e.incremental,tracing:!1})}trace(t,e={incremental:!0}){return this._match(this._getStartExpr(t),{incremental:e.incremental,tracing:!0})}_match(t,e={}){const r={tracing:!1,incremental:!0,positionToRecordFailures:void 0,...e};if(r.incremental){if(this._isMemoTableStale&&!this.grammar.supportsIncrementalParsing)throw function(t){return B(`Grammar '${t.name}' does not support incremental parsing`)}(this.grammar)}else this._resetMemoTable();const n=new wt(this,t,r.positionToRecordFailures);return r.tracing?n.getTrace():n.getMatchResult()}_getStartExpr(t){const e=t||this.grammar.defaultStartRule;if(!e)throw new Error("Missing start rule argument -- the grammar has no default start rule.");const r=this.grammar.parseApplication(e);return new P([r,_])}}const Nt=[],Ot=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);class Rt{constructor(t,e,n){this._node=t,this.source=e,this._baseInterval=n,t.isNonterminal()&&r(e===n),this._childWrappers=[]}_forgetMemoizedResultFor(t){delete this._node[this._semantics.attributeKeys[t]],this.children.forEach((e=>{e._forgetMemoizedResultFor(t)}))}child(t){if(!(0<=t&&t<this._node.numChildren()))return;let e=this._childWrappers[t];if(!e){const r=this._node.childAt(t),n=this._node.childOffsets[t],i=this._baseInterval.subInterval(n,r.matchLength),s=r.isNonterminal()?i:this._baseInterval;e=this._childWrappers[t]=this._semantics.wrap(r,i,s)}return e}_children(){for(let t=0;t<this._node.numChildren();t++)this.child(t);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(t){const e=t||[],r=e.map((t=>t._node)),n=new ft(r,[],-1,!1),i=this._semantics.wrap(n,null,null);return i._childWrappers=e,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 Lt{constructor(t,e){const r=this;if(this.grammar=t,this.checkedActionDicts=!1,this.Wrapper=class extends(e?e.Wrapper:Rt){constructor(t,e,n){super(t,e,n),r.checkActionDictsIfHaventAlready(),this._semantics=r}toString(){return"[semantics wrapper for "+r.grammar.name+"]"}},this.super=e,e){if(!t.equals(this.super.grammar)&&!t._inheritsFrom(this.super.grammar))throw new Error("Cannot extend a semantics for grammar '"+this.super.grammar.name+"' for use with grammar '"+t.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(const t in this.attributes)Object.defineProperty(this.attributeKeys,t,{value:rt(t)})}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 t;for(t in this.operations)this.operations[t].checkActionDict(this.grammar);for(t in this.attributes)this.attributes[t].checkActionDict(this.grammar)}toRecipe(t){function e(t){return t.super!==Lt.BuiltInSemantics._getSemantics()}let r="(function(g) {\n";if(e(this)){r+=" var semantics = "+this.super.toRecipe(!0)+"(g";const t=this.super.grammar;let e=this.grammar;for(;e!==t;)r+=".superGrammar",e=e.superGrammar;r+=");\n",r+=" return g.extendSemantics(semantics)"}else r+=" return g.createSemantics()";return["Operation","Attribute"].forEach((t=>{const n=this[t.toLowerCase()+"s"];Object.keys(n).forEach((i=>{const{actionDict:s,formals:o,builtInDefault:a}=n[i];let u,c=i;o.length>0&&(c+="("+o.join(", ")+")"),u=e(this)&&this.super[t.toLowerCase()+"s"][i]?"extend"+t:"add"+t,r+="\n ."+u+"("+JSON.stringify(c)+", {";const l=[];Object.keys(s).forEach((t=>{if(s[t]!==a){let e=s[t].toString().trim();e=e.replace(/^.*\(/,"function("),l.push("\n "+JSON.stringify(t)+": "+e)}})),r+=l.join(",")+"\n })"}))})),r+=";\n })",t||(r="(function() {\n var grammar = this.fromRecipe("+this.grammar.toRecipe()+");\n var semantics = "+r+"(grammar);\n return semantics;\n});\n"),r}addOperationOrAttribute(t,e,r){const n=t+"s",i=Pt(e,t),{name:s}=i,{formals:o}=i;this.assertNewName(s,t);const a=function(t,e,r){return function(...n){const i=(this._semantics.operations[e]||this._semantics.attributes[e]).formals.map((t=>this.args[t]));if(this.isIteration()||1!==n.length)throw fun