UNPKG

chevrotain

Version:

Chevrotain is a high performance fault tolerant javascript parsing DSL for building recursive decent parsers

86 lines 113 kB
var tt="12.0.0";function Te(n){console&&console.error&&console.error(`Error: ${n}`)}function we(n){console&&console.warn&&console.warn(`Warning: ${n}`)}function Fe(n){let e=new Date().getTime(),t=n();return{time:new Date().getTime()-e,value:t}}function Ue(n){function e(){}e.prototype=n;let t=new e;function r(){return typeof t.bar}return r(),r(),n;(0,eval)(n)}function Kr(n){return Wr(n)?n.LABEL:n.name}function Wr(n){return typeof n.LABEL=="string"&&n.LABEL!==""}var $=class{get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){this._definition=e}accept(e){e.visit(this),this.definition.forEach(t=>{t.accept(e)})}},S=class extends ${constructor(e){super([]),this.idx=1,Object.assign(this,q(e))}set definition(e){}get definition(){return this.referencedRule!==void 0?this.referencedRule.definition:[]}accept(e){e.visit(this)}},G=class extends ${constructor(e){super(e.definition),this.orgText="",Object.assign(this,q(e))}},x=class extends ${constructor(e){super(e.definition),this.ignoreAmbiguities=!1,Object.assign(this,q(e))}},_=class extends ${constructor(e){super(e.definition),this.idx=1,Object.assign(this,q(e))}},P=class extends ${constructor(e){super(e.definition),this.idx=1,Object.assign(this,q(e))}},M=class extends ${constructor(e){super(e.definition),this.idx=1,Object.assign(this,q(e))}},N=class extends ${constructor(e){super(e.definition),this.idx=1,Object.assign(this,q(e))}},L=class extends ${constructor(e){super(e.definition),this.idx=1,Object.assign(this,q(e))}},y=class extends ${get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){super(e.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,Object.assign(this,q(e))}},I=class{constructor(e){this.idx=1,Object.assign(this,q(e))}accept(e){e.visit(this)}};function nt(n){return n.map(ge)}function ge(n){function e(t){return t.map(ge)}if(n instanceof S){let t={type:"NonTerminal",name:n.nonTerminalName,idx:n.idx};return typeof n.label=="string"&&(t.label=n.label),t}else{if(n instanceof x)return{type:"Alternative",definition:e(n.definition)};if(n instanceof _)return{type:"Option",idx:n.idx,definition:e(n.definition)};if(n instanceof P)return{type:"RepetitionMandatory",idx:n.idx,definition:e(n.definition)};if(n instanceof M)return{type:"RepetitionMandatoryWithSeparator",idx:n.idx,separator:ge(new I({terminalType:n.separator})),definition:e(n.definition)};if(n instanceof L)return{type:"RepetitionWithSeparator",idx:n.idx,separator:ge(new I({terminalType:n.separator})),definition:e(n.definition)};if(n instanceof N)return{type:"Repetition",idx:n.idx,definition:e(n.definition)};if(n instanceof y)return{type:"Alternation",idx:n.idx,definition:e(n.definition)};if(n instanceof I){let t={type:"Terminal",name:n.terminalType.name,label:Kr(n.terminalType),idx:n.idx};typeof n.label=="string"&&(t.terminalLabel=n.label);let r=n.terminalType.PATTERN;return n.terminalType.PATTERN&&(t.pattern=r instanceof RegExp?r.source:r),t}else{if(n instanceof G)return{type:"Rule",name:n.name,orgText:n.orgText,definition:e(n.definition)};throw Error("non exhaustive match")}}}function q(n){return Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0))}var F=class{visit(e){let t=e;switch(t.constructor){case S:return this.visitNonTerminal(t);case x:return this.visitAlternative(t);case _:return this.visitOption(t);case P:return this.visitRepetitionMandatory(t);case M:return this.visitRepetitionMandatoryWithSeparator(t);case L:return this.visitRepetitionWithSeparator(t);case N:return this.visitRepetition(t);case y:return this.visitAlternation(t);case I:return this.visitTerminal(t);case G:return this.visitRule(t);default:throw Error("non exhaustive match")}}visitNonTerminal(e){}visitAlternative(e){}visitOption(e){}visitRepetition(e){}visitRepetitionMandatory(e){}visitRepetitionMandatoryWithSeparator(e){}visitRepetitionWithSeparator(e){}visitAlternation(e){}visitTerminal(e){}visitRule(e){}};function Bt(n){return n instanceof x||n instanceof _||n instanceof N||n instanceof P||n instanceof M||n instanceof L||n instanceof I||n instanceof G}function he(n,e=[]){return n instanceof _||n instanceof N||n instanceof L?!0:n instanceof y?n.definition.some(r=>he(r,e)):n instanceof S&&e.includes(n)?!1:n instanceof $?(n instanceof S&&e.push(n),n.definition.every(r=>he(r,e))):!1}function jt(n){return n instanceof y}function j(n){if(n instanceof S)return"SUBRULE";if(n instanceof _)return"OPTION";if(n instanceof y)return"OR";if(n instanceof P)return"AT_LEAST_ONE";if(n instanceof M)return"AT_LEAST_ONE_SEP";if(n instanceof L)return"MANY_SEP";if(n instanceof N)return"MANY";if(n instanceof I)return"CONSUME";throw Error("non exhaustive match")}var J=class{walk(e,t=[]){e.definition.forEach((r,i)=>{let s=e.definition.slice(i+1);if(r instanceof S)this.walkProdRef(r,s,t);else if(r instanceof I)this.walkTerminal(r,s,t);else if(r instanceof x)this.walkFlat(r,s,t);else if(r instanceof _)this.walkOption(r,s,t);else if(r instanceof P)this.walkAtLeastOne(r,s,t);else if(r instanceof M)this.walkAtLeastOneSep(r,s,t);else if(r instanceof L)this.walkManySep(r,s,t);else if(r instanceof N)this.walkMany(r,s,t);else if(r instanceof y)this.walkOr(r,s,t);else throw Error("non exhaustive match")})}walkTerminal(e,t,r){}walkProdRef(e,t,r){}walkFlat(e,t,r){let i=t.concat(r);this.walk(e,i)}walkOption(e,t,r){let i=t.concat(r);this.walk(e,i)}walkAtLeastOne(e,t,r){let i=[new _({definition:e.definition})].concat(t,r);this.walk(e,i)}walkAtLeastOneSep(e,t,r){let i=_n(e,t,r);this.walk(e,i)}walkMany(e,t,r){let i=[new _({definition:e.definition})].concat(t,r);this.walk(e,i)}walkManySep(e,t,r){let i=_n(e,t,r);this.walk(e,i)}walkOr(e,t,r){let i=t.concat(r);e.definition.forEach(s=>{let o=new x({definition:[s]});this.walk(o,i)})}};function _n(n,e,t){return[new _({definition:[new I({terminalType:n.separator})].concat(n.definition)})].concat(e,t)}function ue(n){if(n instanceof S)return ue(n.referencedRule);if(n instanceof I)return Xr(n);if(Bt(n))return Vr(n);if(jt(n))return Hr(n);throw Error("non exhaustive match")}function Vr(n){let e=[],t=n.definition,r=0,i=t.length>r,s,o=!0;for(;i&&o;)s=t[r],o=he(s),e=e.concat(ue(s)),r=r+1,i=t.length>r;return[...new Set(e)]}function Hr(n){let e=n.definition.map(t=>ue(t));return[...new Set(e.flat())]}function Xr(n){return[n.terminalType]}var rt="_~IN~_";var $t=class extends J{constructor(e){super(),this.topProd=e,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(e,t,r){}walkProdRef(e,t,r){let i=zr(e.referencedRule,e.idx)+this.topProd.name,s=t.concat(r),o=new x({definition:s}),a=ue(o);this.follows[i]=a}};function Cn(n){let e={};return n.forEach(t=>{let r=new $t(t).startWalking();Object.assign(e,r)}),e}function zr(n,e){return n.name+e+rt}function g(n){return n.charCodeAt(0)}function it(n,e){Array.isArray(n)?n.forEach(function(t){e.push(t)}):e.push(n)}function Ae(n,e){if(n[e]===!0)throw"duplicate flag "+e;let t=n[e];n[e]=!0}function de(n){if(n===void 0)throw Error("Internal Error - Should never get here!");return!0}function De(){throw Error("Internal Error - Should never get here!")}function Kt(n){return n.type==="Character"}var Ge=[];for(let n=g("0");n<=g("9");n++)Ge.push(n);var Be=[g("_")].concat(Ge);for(let n=g("a");n<=g("z");n++)Be.push(n);for(let n=g("A");n<=g("Z");n++)Be.push(n);var Wt=[g(" "),g("\f"),g(` `),g("\r"),g(" "),g("\v"),g(" "),g("\xA0"),g("\u1680"),g("\u2000"),g("\u2001"),g("\u2002"),g("\u2003"),g("\u2004"),g("\u2005"),g("\u2006"),g("\u2007"),g("\u2008"),g("\u2009"),g("\u200A"),g("\u2028"),g("\u2029"),g("\u202F"),g("\u205F"),g("\u3000"),g("\uFEFF")];var Yr=/[0-9a-fA-F]/,st=/[0-9]/,qr=/[1-9]/,je=class{constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(e){this.idx=e.idx,this.input=e.input,this.groupIdx=e.groupIdx}pattern(e){this.idx=0,this.input=e,this.groupIdx=0,this.consumeChar("/");let t=this.disjunction();this.consumeChar("/");let r={type:"Flags",loc:{begin:this.idx,end:e.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":Ae(r,"global");break;case"i":Ae(r,"ignoreCase");break;case"m":Ae(r,"multiLine");break;case"u":Ae(r,"unicode");break;case"y":Ae(r,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:r,value:t,loc:this.loc(0)}}disjunction(){let e=[],t=this.idx;for(e.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),e.push(this.alternative());return{type:"Disjunction",value:e,loc:this.loc(t)}}alternative(){let e=[],t=this.idx;for(;this.isTerm();)e.push(this.term());return{type:"Alternative",value:e,loc:this.loc(t)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){let e=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(e)};case"$":return{type:"EndAnchor",loc:this.loc(e)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(e)};case"B":return{type:"NonWordBoundary",loc:this.loc(e)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");let t;switch(this.popChar()){case"=":t="Lookahead";break;case"!":t="NegativeLookahead";break;case"<":{switch(this.popChar()){case"=":t="Lookbehind";break;case"!":t="NegativeLookbehind"}break}}de(t);let r=this.disjunction();return this.consumeChar(")"),{type:t,value:r,loc:this.loc(e)}}return De()}quantifier(e=!1){let t,r=this.idx;switch(this.popChar()){case"*":t={atLeast:0,atMost:1/0};break;case"+":t={atLeast:1,atMost:1/0};break;case"?":t={atLeast:0,atMost:1};break;case"{":let i=this.integerIncludingZero();switch(this.popChar()){case"}":t={atLeast:i,atMost:i};break;case",":let s;this.isDigit()?(s=this.integerIncludingZero(),t={atLeast:i,atMost:s}):t={atLeast:i,atMost:1/0},this.consumeChar("}");break}if(e===!0&&t===void 0)return;de(t);break}if(!(e===!0&&t===void 0)&&de(t))return this.peekChar(0)==="?"?(this.consumeChar("?"),t.greedy=!1):t.greedy=!0,t.type="Quantifier",t.loc=this.loc(r),t}atom(){let e,t=this.idx;switch(this.peekChar()){case".":e=this.dotAll();break;case"\\":e=this.atomEscape();break;case"[":e=this.characterClass();break;case"(":e=this.group();break}return e===void 0&&this.isPatternCharacter()&&(e=this.patternCharacter()),de(e)?(e.loc=this.loc(t),this.isQuantifier()&&(e.quantifier=this.quantifier()),e):De()}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[g(` `),g("\r"),g("\u2028"),g("\u2029")]}}atomEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){return{type:"GroupBackReference",value:this.positiveInteger()}}characterClassEscape(){let e,t=!1;switch(this.popChar()){case"d":e=Ge;break;case"D":e=Ge,t=!0;break;case"s":e=Wt;break;case"S":e=Wt,t=!0;break;case"w":e=Be;break;case"W":e=Be,t=!0;break}return de(e)?{type:"Set",value:e,complement:t}:De()}controlEscapeAtom(){let e;switch(this.popChar()){case"f":e=g("\f");break;case"n":e=g(` `);break;case"r":e=g("\r");break;case"t":e=g(" ");break;case"v":e=g("\v");break}return de(e)?{type:"Character",value:e}:De()}controlLetterEscapeAtom(){this.consumeChar("c");let e=this.popChar();if(/[a-zA-Z]/.test(e)===!1)throw Error("Invalid ");return{type:"Character",value:e.toUpperCase().charCodeAt(0)-64}}nulCharacterAtom(){return this.consumeChar("0"),{type:"Character",value:g("\0")}}hexEscapeSequenceAtom(){return this.consumeChar("x"),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar("u"),this.parseHexDigits(4)}identityEscapeAtom(){let e=this.popChar();return{type:"Character",value:g(e)}}classPatternCharacterAtom(){switch(this.peekChar()){case` `:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:let e=this.popChar();return{type:"Character",value:g(e)}}}characterClass(){let e=[],t=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),t=!0);this.isClassAtom();){let r=this.classAtom(),i=r.type==="Character";if(Kt(r)&&this.isRangeDash()){this.consumeChar("-");let s=this.classAtom(),o=s.type==="Character";if(Kt(s)){if(s.value<r.value)throw Error("Range out of order in character class");e.push({from:r.value,to:s.value})}else it(r.value,e),e.push(g("-")),it(s.value,e)}else it(r.value,e)}return this.consumeChar("]"),{type:"Set",complement:t,value:e}}classAtom(){switch(this.peekChar()){case"]":case` `:case"\r":case"\u2028":case"\u2029":throw Error("TBD");case"\\":return this.classEscape();default:return this.classPatternCharacterAtom()}}classEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"b":return this.consumeChar("b"),{type:"Character",value:g("\b")};case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}group(){let e=!0;this.consumeChar("("),this.peekChar(0)==="?"?(this.consumeChar("?"),this.consumeChar(":"),e=!1):this.groupIdx++;let t=this.disjunction();this.consumeChar(")");let r={type:"Group",capturing:e,value:t};return e&&(r.idx=this.groupIdx),r}positiveInteger(){let e=this.popChar();if(qr.test(e)===!1)throw Error("Expecting a positive integer");for(;st.test(this.peekChar(0));)e+=this.popChar();return parseInt(e,10)}integerIncludingZero(){let e=this.popChar();if(st.test(e)===!1)throw Error("Expecting an integer");for(;st.test(this.peekChar(0));)e+=this.popChar();return parseInt(e,10)}patternCharacter(){let e=this.popChar();switch(e){case` `:case"\r":case"\u2028":case"\u2029":case"^":case"$":case"\\":case".":case"*":case"+":case"?":case"(":case")":case"[":case"|":throw Error("TBD");default:return{type:"Character",value:g(e)}}}isRegExpFlag(){switch(this.peekChar(0)){case"g":case"i":case"m":case"u":case"y":return!0;default:return!1}}isRangeDash(){return this.peekChar()==="-"&&this.isClassAtom(1)}isDigit(){return st.test(this.peekChar(0))}isClassAtom(e=0){switch(this.peekChar(e)){case"]":case` `:case"\r":case"\u2028":case"\u2029":return!1;default:return!0}}isTerm(){return this.isAtom()||this.isAssertion()}isAtom(){if(this.isPatternCharacter())return!0;switch(this.peekChar(0)){case".":case"\\":case"[":case"(":return!0;default:return!1}}isAssertion(){switch(this.peekChar(0)){case"^":case"$":return!0;case"\\":switch(this.peekChar(1)){case"b":case"B":return!0;default:return!1}case"(":return this.peekChar(1)==="?"&&(this.peekChar(2)==="="||this.peekChar(2)==="!"||this.peekChar(2)==="<"&&(this.peekChar(3)==="="||this.peekChar(3)==="!"));default:return!1}}isQuantifier(){let e=this.saveState();try{return this.quantifier(!0)!==void 0}catch{return!1}finally{this.restoreState(e)}}isPatternCharacter(){switch(this.peekChar()){case"^":case"$":case"\\":case".":case"*":case"+":case"?":case"(":case")":case"[":case"|":case"/":case` `:case"\r":case"\u2028":case"\u2029":return!1;default:return!0}}parseHexDigits(e){let t="";for(let i=0;i<e;i++){let s=this.popChar();if(Yr.test(s)===!1)throw Error("Expecting a HexDecimal digits");t+=s}return{type:"Character",value:parseInt(t,16)}}peekChar(e=0){return this.input[this.idx+e]}popChar(){let e=this.peekChar(0);return this.consumeChar(void 0),e}consumeChar(e){if(e!==void 0&&this.input[this.idx]!==e)throw Error("Expected: '"+e+"' but found: '"+this.input[this.idx]+"' at offset: "+this.idx);if(this.idx>=this.input.length)throw Error("Unexpected end of input");this.idx++}loc(e){return{begin:e,end:this.idx}}};var oe=class{visitChildren(e){for(let t in e){let r=e[t];e.hasOwnProperty(t)&&(r.type!==void 0?this.visit(r):Array.isArray(r)&&r.forEach(i=>{this.visit(i)},this))}}visit(e){switch(e.type){case"Pattern":this.visitPattern(e);break;case"Flags":this.visitFlags(e);break;case"Disjunction":this.visitDisjunction(e);break;case"Alternative":this.visitAlternative(e);break;case"StartAnchor":this.visitStartAnchor(e);break;case"EndAnchor":this.visitEndAnchor(e);break;case"WordBoundary":this.visitWordBoundary(e);break;case"NonWordBoundary":this.visitNonWordBoundary(e);break;case"Lookahead":this.visitLookahead(e);break;case"NegativeLookahead":this.visitNegativeLookahead(e);break;case"Lookbehind":this.visitLookbehind(e);break;case"NegativeLookbehind":this.visitNegativeLookbehind(e);break;case"Character":this.visitCharacter(e);break;case"Set":this.visitSet(e);break;case"Group":this.visitGroup(e);break;case"GroupBackReference":this.visitGroupBackReference(e);break;case"Quantifier":this.visitQuantifier(e);break}this.visitChildren(e)}visitPattern(e){}visitFlags(e){}visitDisjunction(e){}visitAlternative(e){}visitStartAnchor(e){}visitEndAnchor(e){}visitWordBoundary(e){}visitNonWordBoundary(e){}visitLookahead(e){}visitNegativeLookahead(e){}visitLookbehind(e){}visitNegativeLookbehind(e){}visitCharacter(e){}visitSet(e){}visitGroup(e){}visitGroupBackReference(e){}visitQuantifier(e){}};var ot={},Qr=new je;function Re(n){let e=n.toString();if(ot.hasOwnProperty(e))return ot[e];{let t=Qr.pattern(e);return ot[e]=t,t}}function kn(){ot={}}var yn="Complement Sets are not supported for first char optimization",$e=`Unable to use "first char" lexer optimizations: `;function vn(n,e=!1){try{let t=Re(n);return Vt(t.value,{},t.flags.ignoreCase)}catch(t){if(t.message===yn)e&&we(`${$e} Unable to optimize: < ${n.toString()} > Complement Sets cannot be automatically optimized. This will disable the lexer's first char optimizations. See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let r="";e&&(r=` This will disable the lexer's first char optimizations. See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),Te(`${$e} Failed parsing: < ${n.toString()} > Using the @chevrotain/regexp-to-ast library Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+r)}}return[]}function Vt(n,e,t){switch(n.type){case"Disjunction":for(let i=0;i<n.value.length;i++)Vt(n.value[i],e,t);break;case"Alternative":let r=n.value;for(let i=0;i<r.length;i++){let s=r[i];switch(s.type){case"EndAnchor":case"GroupBackReference":case"Lookahead":case"NegativeLookahead":case"Lookbehind":case"NegativeLookbehind":case"StartAnchor":case"WordBoundary":case"NonWordBoundary":continue}let o=s;switch(o.type){case"Character":at(o.value,e,t);break;case"Set":if(o.complement===!0)throw Error(yn);o.value.forEach(c=>{if(typeof c=="number")at(c,e,t);else{let l=c;if(t===!0)for(let u=l.from;u<=l.to;u++)at(u,e,t);else{for(let u=l.from;u<=l.to&&u<Ie;u++)at(u,e,t);if(l.to>=Ie){let u=l.from>=Ie?l.from:Ie,h=l.to,f=Q(u),T=Q(h);for(let A=f;A<=T;A++)e[A]=A}}}});break;case"Group":Vt(o.value,e,t);break;default:throw Error("Non Exhaustive Match")}let a=o.quantifier!==void 0&&o.quantifier.atLeast===0;if(o.type==="Group"&&Ht(o)===!1||o.type!=="Group"&&a===!1)break}break;default:throw Error("non exhaustive match!")}return Object.values(e)}function at(n,e,t){let r=Q(n);e[r]=r,t===!0&&Zr(n,e)}function Zr(n,e){let t=String.fromCharCode(n),r=t.toUpperCase();if(r!==t){let i=Q(r.charCodeAt(0));e[i]=i}else{let i=t.toLowerCase();if(i!==t){let s=Q(i.charCodeAt(0));e[s]=s}}}function Ln(n,e){return n.value.find(t=>{if(typeof t=="number")return e.includes(t);{let r=t;return e.find(i=>r.from<=i&&i<=r.to)!==void 0}})}function Ht(n){let e=n.quantifier;return e&&e.atLeast===0?!0:n.value?Array.isArray(n.value)?n.value.every(Ht):Ht(n.value):!1}var Xt=class extends oe{constructor(e){super(),this.targetCharCodes=e,this.found=!1}visitChildren(e){if(this.found!==!0){switch(e.type){case"Lookahead":this.visitLookahead(e);return;case"NegativeLookahead":this.visitNegativeLookahead(e);return;case"Lookbehind":this.visitLookbehind(e);return;case"NegativeLookbehind":this.visitNegativeLookbehind(e);return}super.visitChildren(e)}}visitCharacter(e){this.targetCharCodes.includes(e.value)&&(this.found=!0)}visitSet(e){e.complement?Ln(e,this.targetCharCodes)===void 0&&(this.found=!0):Ln(e,this.targetCharCodes)!==void 0&&(this.found=!0)}};function ct(n,e){if(e instanceof RegExp){let t=Re(e),r=new Xt(n);return r.visit(t),r.found}else{for(let t of e){let r=t.charCodeAt(0);if(n.includes(r))return!0}return!1}}var fe="PATTERN",Oe="defaultMode",lt="modes";function Mn(n,e){e=Object.assign({safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` `],tracer:(m,d)=>d()},e);let t=e.tracer;t("initCharCodeToOptimizedIndexMap",()=>{Ti()});let r;t("Reject Lexer.NA",()=>{r=n.filter(m=>m[fe]!==w.NA)});let i=!1,s;t("Transform Patterns",()=>{i=!1,s=r.map(m=>{let d=m[fe];if(d instanceof RegExp){let p=d.source;return p.length===1&&p!=="^"&&p!=="$"&&p!=="."&&!d.ignoreCase?p:p.length===2&&p[0]==="\\"&&!["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"].includes(p[1])?p[1]:Pn(d)}else{if(typeof d=="function")return i=!0,{exec:d};if(typeof d=="object")return i=!0,d;if(typeof d=="string"){if(d.length===1)return d;{let p=d.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),v=new RegExp(p);return Pn(v)}}else throw Error("non exhaustive match")}})});let o,a,c,l,u;t("misc mapping",()=>{o=r.map(m=>m.tokenTypeIdx),a=r.map(m=>{let d=m.GROUP;if(d!==w.SKIPPED){if(typeof d=="string")return d;if(d===void 0)return!1;throw Error("non exhaustive match")}}),c=r.map(m=>{let d=m.LONGER_ALT;if(d)return Array.isArray(d)?d.map(v=>r.indexOf(v)):[r.indexOf(d)]}),l=r.map(m=>m.PUSH_MODE),u=r.map(m=>Object.hasOwn(m,"POP_MODE"))});let h;t("Line Terminator Handling",()=>{let m=jn(e.lineTerminatorCharacters);h=r.map(d=>!1),e.positionTracking!=="onlyOffset"&&(h=r.map(d=>Object.hasOwn(d,"LINE_BREAKS")?!!d.LINE_BREAKS:Bn(d,m)===!1&&ct(m,d.PATTERN)))});let f,T,A,R;t("Misc Mapping #2",()=>{f=r.map(Dn),T=s.map(mi),A=r.reduce((m,d)=>{let p=d.GROUP;return typeof p=="string"&&p!==w.SKIPPED&&(m[p]=[]),m},{}),R=s.map((m,d)=>({pattern:s[d],longerAlt:c[d],canLineTerminator:h[d],isCustom:f[d],short:T[d],group:a[d],push:l[d],pop:u[d],tokenTypeIdx:o[d],tokenType:r[d]}))});let O=!0,E=[];return e.safeMode||t("First Char Optimization",()=>{E=r.reduce((m,d,p)=>{if(typeof d.PATTERN=="string"){let v=d.PATTERN.charCodeAt(0),V=Q(v);zt(m,V,R[p])}else if(Array.isArray(d.START_CHARS_HINT)){let v;d.START_CHARS_HINT.forEach(V=>{let re=typeof V=="string"?V.charCodeAt(0):V,ce=Q(re);v!==ce&&(v=ce,zt(m,ce,R[p]))})}else if(d.PATTERN instanceof RegExp)if(d.PATTERN.unicode)O=!1,e.ensureOptimizations&&Te(`${$e} Unable to analyze < ${d.PATTERN.toString()} > pattern. The regexp unicode flag is not currently supported by the regexp-to-ast library. This will disable the lexer's first char optimizations. For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{let v=vn(d.PATTERN,e.ensureOptimizations);v.length===0&&(O=!1),v.forEach(V=>{zt(m,V,R[p])})}else e.ensureOptimizations&&Te(`${$e} TokenType: <${d.name}> is using a custom token pattern without providing <start_chars_hint> parameter. This will disable the lexer's first char optimizations. For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),O=!1;return m},[])}),{emptyGroups:A,patternIdxToConfig:R,charCodeToPatternIdxToConfig:E,hasCustom:i,canBeOptimized:O}}function bn(n,e){let t=[],r=ei(n);t=t.concat(r.errors);let i=ti(r.valid),s=i.valid;return t=t.concat(i.errors),t=t.concat(Jr(s)),t=t.concat(li(s)),t=t.concat(hi(s,e)),t=t.concat(ui(s)),t}function Jr(n){let e=[],t=n.filter(r=>r[fe]instanceof RegExp);return e=e.concat(ri(t)),e=e.concat(oi(t)),e=e.concat(ai(t)),e=e.concat(ci(t)),e=e.concat(ii(t)),e}function ei(n){let e=n.filter(i=>!Object.hasOwn(i,fe)),t=e.map(i=>({message:"Token Type: ->"+i.name+"<- missing static 'PATTERN' property",type:C.MISSING_PATTERN,tokenTypes:[i]})),r=n.filter(i=>!e.includes(i));return{errors:t,valid:r}}function ti(n){let e=n.filter(i=>{let s=i[fe];return!(s instanceof RegExp)&&typeof s!="function"&&!Object.hasOwn(s,"exec")&&typeof s!="string"}),t=e.map(i=>({message:"Token Type: ->"+i.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:C.INVALID_PATTERN,tokenTypes:[i]})),r=n.filter(i=>!e.includes(i));return{errors:t,valid:r}}var ni=/[^\\][$]/;function ri(n){class e extends oe{constructor(){super(...arguments),this.found=!1}visitEndAnchor(s){this.found=!0}}return n.filter(i=>{let s=i.PATTERN;try{let o=Re(s),a=new e;return a.visit(o),a.found}catch{return ni.test(s.source)}}).map(i=>({message:`Unexpected RegExp Anchor Error: Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain end of input anchor '$' See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:C.EOI_ANCHOR_FOUND,tokenTypes:[i]}))}function ii(n){return n.filter(r=>r.PATTERN.test("")).map(r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' must not match an empty string",type:C.EMPTY_MATCH_PATTERN,tokenTypes:[r]}))}var si=/[^\\[][\^]|^\^/;function oi(n){class e extends oe{constructor(){super(...arguments),this.found=!1}visitStartAnchor(s){this.found=!0}}return n.filter(i=>{let s=i.PATTERN;try{let o=Re(s),a=new e;return a.visit(o),a.found}catch{return si.test(s.source)}}).map(i=>({message:`Unexpected RegExp Anchor Error: Token Type: ->`+i.name+`<- static 'PATTERN' cannot contain start of input anchor '^' See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:C.SOI_ANCHOR_FOUND,tokenTypes:[i]}))}function ai(n){return n.filter(r=>{let i=r[fe];return i instanceof RegExp&&(i.multiline||i.global)}).map(r=>({message:"Token Type: ->"+r.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:C.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[r]}))}function ci(n){let e=[],t=n.map(s=>n.reduce((o,a)=>(s.PATTERN.source===a.PATTERN.source&&!e.includes(a)&&a.PATTERN!==w.NA&&(e.push(a),o.push(a)),o),[]));return t=t.filter(Boolean),t.filter(s=>s.length>1).map(s=>{let o=s.map(c=>c.name);return{message:`The same RegExp pattern ->${s[0].PATTERN}<-has been used in all of the following Token Types: ${o.join(", ")} <-`,type:C.DUPLICATE_PATTERNS_FOUND,tokenTypes:s}})}function li(n){return n.filter(r=>{if(!Object.hasOwn(r,"GROUP"))return!1;let i=r.GROUP;return i!==w.SKIPPED&&i!==w.NA&&typeof i!="string"}).map(r=>({message:"Token Type: ->"+r.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:C.INVALID_GROUP_TYPE_FOUND,tokenTypes:[r]}))}function hi(n,e){return n.filter(i=>i.PUSH_MODE!==void 0&&!e.includes(i.PUSH_MODE)).map(i=>({message:`Token Type: ->${i.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${i.PUSH_MODE}<-which does not exist`,type:C.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[i]}))}function ui(n){let e=[],t=n.reduce((r,i,s)=>{let o=i.PATTERN;return o===w.NA||(typeof o=="string"?r.push({str:o,idx:s,tokenType:i}):o instanceof RegExp&&fi(o)&&r.push({str:o.source,idx:s,tokenType:i})),r},[]);return n.forEach((r,i)=>{t.forEach(({str:s,idx:o,tokenType:a})=>{if(i<o&&di(s,r.PATTERN)){let c=`Token: ->${a.name}<- can never be matched. Because it appears AFTER the Token Type ->${r.name}<-in the lexer's definition. See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;e.push({message:c,type:C.UNREACHABLE_PATTERN,tokenTypes:[r,a]})}})}),e}function di(n,e){if(e instanceof RegExp){if(pi(e))return!1;let t=e.exec(n);return t!==null&&t.index===0}else{if(typeof e=="function")return e(n,0,[],{});if(Object.hasOwn(e,"exec"))return e.exec(n,0,[],{});if(typeof e=="string")return e===n;throw Error("non exhaustive match")}}function fi(n){return[".","\\","[","]","|","^","$","(",")","?","*","+","{"].find(t=>n.source.indexOf(t)!==-1)===void 0}function pi(n){return/(\(\?=)|(\(\?!)|(\(\?<=)|(\(\?<!)/.test(n.source)}function Pn(n){let e=n.ignoreCase?"iy":"y";return new RegExp(`${n.source}`,e)}function wn(n,e,t){let r=[];return Object.hasOwn(n,Oe)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+Oe+`> property in its definition `,type:C.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),Object.hasOwn(n,lt)||r.push({message:"A MultiMode Lexer cannot be initialized without a <"+lt+`> property in its definition `,type:C.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),Object.hasOwn(n,lt)&&Object.hasOwn(n,Oe)&&!Object.hasOwn(n.modes,n.defaultMode)&&r.push({message:`A MultiMode Lexer cannot be initialized with a ${Oe}: <${n.defaultMode}>which does not exist `,type:C.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),Object.hasOwn(n,lt)&&Object.keys(n.modes).forEach(i=>{let s=n.modes[i];s.forEach((o,a)=>{o===void 0?r.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${i}> at index: <${a}> `,type:C.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED}):Object.hasOwn(o,"LONGER_ALT")&&(Array.isArray(o.LONGER_ALT)?o.LONGER_ALT:[o.LONGER_ALT]).forEach(l=>{l!==void 0&&!s.includes(l)&&r.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${l.name}> on token <${o.name}> outside of mode <${i}> `,type:C.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})})}),r}function Fn(n,e,t){let r=[],i=!1,o=Object.values(n.modes||{}).flat().filter(Boolean).filter(c=>c[fe]!==w.NA),a=jn(t);return e&&o.forEach(c=>{let l=Bn(c,a);if(l!==!1){let h={message:Ei(c,l),type:l.issue,tokenType:c};r.push(h)}else Object.hasOwn(c,"LINE_BREAKS")?c.LINE_BREAKS===!0&&(i=!0):ct(a,c.PATTERN)&&(i=!0)}),e&&!i&&r.push({message:`Warning: No LINE_BREAKS Found. This Lexer has been defined to track line and column information, But none of the Token Types can be identified as matching a line terminator. See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS for details.`,type:C.NO_LINE_BREAKS_FLAGS}),r}function Un(n){let e={};return Object.keys(n).forEach(r=>{let i=n[r];if(Array.isArray(i))e[r]=[];else throw Error("non exhaustive match")}),e}function Dn(n){let e=n.PATTERN;if(e instanceof RegExp)return!1;if(typeof e=="function")return!0;if(Object.hasOwn(e,"exec"))return!0;if(typeof e=="string")return!1;throw Error("non exhaustive match")}function mi(n){return typeof n=="string"&&n.length===1?n.charCodeAt(0):!1}var Gn={test:function(n){let e=n.length;for(let t=this.lastIndex;t<e;t++){let r=n.charCodeAt(t);if(r===10)return this.lastIndex=t+1,!0;if(r===13)return n.charCodeAt(t+1)===10?this.lastIndex=t+2:this.lastIndex=t+1,!0}return!1},lastIndex:0};function Bn(n,e){if(Object.hasOwn(n,"LINE_BREAKS"))return!1;if(n.PATTERN instanceof RegExp){try{ct(e,n.PATTERN)}catch(t){return{issue:C.IDENTIFY_TERMINATOR,errMsg:t.message}}return!1}else{if(typeof n.PATTERN=="string")return!1;if(Dn(n))return{issue:C.CUSTOM_LINE_BREAK};throw Error("non exhaustive match")}}function Ei(n,e){if(e.issue===C.IDENTIFY_TERMINATOR)return`Warning: unable to identify line terminator usage in pattern. The problem is in the <${n.name}> Token Type Root cause: ${e.errMsg}. For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(e.issue===C.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the <line_breaks> option. The problem is in the <${n.name}> Token Type For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}function jn(n){return n.map(t=>typeof t=="string"?t.charCodeAt(0):t)}function zt(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}var Ie=256,ht=[];function Q(n){return n<Ie?n:ht[n]}function Ti(){if(ht.length===0){ht=new Array(65536);for(let n=0;n<65536;n++)ht[n]=n>255?255+~~(n/255):n}}function ee(n,e){let t=n.tokenTypeIdx;return t===e.tokenTypeIdx?!0:e.isParent===!0&&e.categoryMatchesMap[t]===!0}function Ne(n,e){return n.tokenTypeIdx===e.tokenTypeIdx}var $n=1,Wn={};function te(n){let e=gi(n);Ai(e),Ii(e),Ri(e),e.forEach(t=>{t.isParent=t.categoryMatches.length>0})}function gi(n){let e=[...n],t=n,r=!0;for(;r;){t=t.map(s=>s.CATEGORIES).flat().filter(Boolean);let i=t.filter(s=>!e.includes(s));e=e.concat(i),i.length===0?r=!1:t=i}return e}function Ai(n){n.forEach(e=>{Yt(e)||(Wn[$n]=e,e.tokenTypeIdx=$n++),Kn(e)&&!Array.isArray(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),Kn(e)||(e.CATEGORIES=[]),Oi(e)||(e.categoryMatches=[]),Ni(e)||(e.categoryMatchesMap={})})}function Ri(n){n.forEach(e=>{e.categoryMatches=[],Object.keys(e.categoryMatchesMap).forEach(t=>{e.categoryMatches.push(Wn[t].tokenTypeIdx)})})}function Ii(n){n.forEach(e=>{Vn([],e)})}function Vn(n,e){n.forEach(t=>{e.categoryMatchesMap[t.tokenTypeIdx]=!0}),e.CATEGORIES.forEach(t=>{let r=n.concat(e);r.includes(t)||Vn(r,t)})}function Yt(n){return Object.hasOwn(n??{},"tokenTypeIdx")}function Kn(n){return Object.hasOwn(n??{},"CATEGORIES")}function Oi(n){return Object.hasOwn(n??{},"categoryMatches")}function Ni(n){return Object.hasOwn(n??{},"categoryMatchesMap")}function Hn(n){return Object.hasOwn(n??{},"tokenTypeIdx")}var qt={buildUnableToPopLexerModeMessage(n){return`Unable to pop Lexer Mode after encountering Token ->${n.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(n,e,t,r,i,s){return`unexpected character: ->${n.charAt(e)}<- at offset: ${e}, skipped ${t} characters.`}};var C;(function(n){n[n.MISSING_PATTERN=0]="MISSING_PATTERN",n[n.INVALID_PATTERN=1]="INVALID_PATTERN",n[n.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",n[n.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",n[n.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",n[n.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",n[n.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",n[n.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",n[n.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",n[n.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",n[n.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",n[n.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",n[n.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",n[n.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",n[n.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",n[n.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",n[n.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",n[n.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"})(C||(C={}));var Ke={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` `,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:qt,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(Ke);var w=class{constructor(e,t=Ke){if(this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(i,s)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;let o=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent<this.traceInitMaxIdent&&console.log(`${o}--> <${i}>`);let{time:a,value:c}=Fe(s),l=a>10?console.warn:console.log;return this.traceInitIndent<this.traceInitMaxIdent&&l(`${o}<-- <${i}> time: ${a}ms`),this.traceInitIndent--,c}else return s()},typeof t=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. a boolean 2nd argument is no longer supported`);this.config=Object.assign({},Ke,t);let r=this.config.traceInitPerf;r===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof r=="number"&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let i,s=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===Ke.lineTerminatorsPattern)this.config.lineTerminatorsPattern=Gn;else if(this.config.lineTerminatorCharacters===Ke.lineTerminatorCharacters)throw Error(`Error: Missing <lineTerminatorCharacters> property on the Lexer config. For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(t.safeMode&&t.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),Array.isArray(e)?i={modes:{defaultMode:[...e]},defaultMode:Oe}:(s=!1,i=Object.assign({},e))}),this.config.skipValidations===!1&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(wn(i,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(Fn(i,this.trackStartLines,this.config.lineTerminatorCharacters))})),i.modes=i.modes?i.modes:{},Object.entries(i.modes).forEach(([a,c])=>{i.modes[a]=c.filter(l=>l!==void 0)});let o=Object.keys(i.modes);if(Object.entries(i.modes).forEach(([a,c])=>{this.TRACE_INIT(`Mode: <${a}> processing`,()=>{if(this.modes.push(a),this.config.skipValidations===!1&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(bn(c,o))}),this.lexerDefinitionErrors.length===0){te(c);let l;this.TRACE_INIT("analyzeTokenTypes",()=>{l=Mn(c,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:t.positionTracking,ensureOptimizations:t.ensureOptimizations,safeMode:t.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[a]=l.patternIdxToConfig,this.charCodeToPatternIdxToConfig[a]=l.charCodeToPatternIdxToConfig,this.emptyGroups=Object.assign({},this.emptyGroups,l.emptyGroups),this.hasCustom=l.hasCustom||this.hasCustom,this.canModeBeOptimized[a]=l.canBeOptimized}})}),this.defaultMode=i.defaultMode,this.lexerDefinitionErrors.length>0&&!this.config.deferDefinitionErrorsHandling){let c=this.lexerDefinitionErrors.map(l=>l.message).join(`----------------------- `);throw new Error(`Errors detected in definition of Lexer: `+c)}this.lexerDefinitionWarning.forEach(a=>{we(a.message)}),this.TRACE_INIT("Choosing sub-methods implementations",()=>{if(s&&(this.handleModes=()=>{}),this.trackStartLines===!1&&(this.computeNewColumn=a=>a),this.trackEndLines===!1&&(this.updateTokenEndLineColumnLocation=()=>{}),/full/i.test(this.config.positionTracking))this.createTokenInstance=this.createFullToken;else if(/onlyStart/i.test(this.config.positionTracking))this.createTokenInstance=this.createStartOnlyToken;else if(/onlyOffset/i.test(this.config.positionTracking))this.createTokenInstance=this.createOffsetOnlyToken;else throw Error(`Invalid <positionTracking> config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT("Failed Optimization Warnings",()=>{let a=Object.entries(this.canModeBeOptimized).reduce((c,[l,u])=>(u===!1&&c.push(l),c),[]);if(t.ensureOptimizations&&a.length>0)throw Error(`Lexer Modes: < ${a.join(", ")} > cannot be optimized. Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{kn()}),this.TRACE_INIT("toFastProperties",()=>{Ue(this)})})}tokenize(e,t=this.defaultMode){if(this.lexerDefinitionErrors.length>0){let i=this.lexerDefinitionErrors.map(s=>s.message).join(`----------------------- `);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: `+i)}return this.tokenizeInternal(e,t)}tokenizeInternal(e,t){let r,i,s,o,a,c,l,u,h,f,T,A,R,O,E,m=e,d=m.length,p=0,v=0,V=this.hasCustom?0:Math.floor(e.length/10),re=new Array(V),ce=[],ye=this.trackStartLines?1:void 0,Y=this.trackStartLines?1:void 0,ve=Un(this.emptyGroups),jr=this.trackStartLines,Ut=this.config.lineTerminatorsPattern,et=0,ie=[],Pe=[],Me=[],On=[];Object.freeze(On);let be=!1,$r=B=>{if(Me.length===1&&B.tokenType.PUSH_MODE===void 0){let K=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(B);ce.push({offset:B.startOffset,line:B.startLine,column:B.startColumn,length:B.image.length,message:K})}else{Me.pop();let K=Me.at(-1);ie=this.patternIdxToConfig[K],Pe=this.charCodeToPatternIdxToConfig[K],et=ie.length;let Dt=this.canModeBeOptimized[K]&&this.config.safeMode===!1;Pe&&Dt?be=!0:be=!1}};function Nn(B){Me.push(B),Pe=this.charCodeToPatternIdxToConfig[B],ie=this.patternIdxToConfig[B],et=ie.length,et=ie.length;let K=this.canModeBeOptimized[B]&&this.config.safeMode===!1;Pe&&K?be=!0:be=!1}Nn.call(this,t);let H,Sn=this.config.recoveryEnabled;for(;p<d;){c=null,h=-1;let B=m.charCodeAt(p),K;if(be){let D=Q(B),W=Pe[D];K=W!==void 0?W:On}else K=ie;let Dt=K.length;for(r=0;r<Dt;r++){H=K[r];let D=H.pattern;l=null;let W=H.short;if(W!==!1?B===W&&(h=1,c=D):H.isCustom===!0?(E=D.exec(m,p,re,ve),E!==null?(c=E[0],h=c.length,E.payload!==void 0&&(l=E.payload)):c=null):(D.lastIndex=p,h=this.matchLength(D,e,p)),h!==-1){if(a=H.longerAlt,a!==void 0){c=e.substring(p,p+h);let se=a.length;for(s=0;s<se;s++){let Z=ie[a[s]],le=Z.pattern;if(u=null,Z.isCustom===!0?(E=le.exec(m,p,re,ve),E!==null?(o=E[0],E.payload!==void 0&&(u=E.payload)):o=null):(le.lastIndex=p,o=this.match(le,e,p)),o&&o.length>c.length){c=o,h=o.length,l=u,H=Z;break}}}break}}if(h!==-1){if(f=H.group,f!==void 0&&(c=c!==null?c:e.substring(p,p+h),T=H.tokenTypeIdx,A=this.createTokenInstance(c,p,T,H.tokenType,ye,Y,h),this.handlePayload(A,l),f===!1?v=this.addToken(re,v,A):ve[f].push(A)),jr===!0&&H.canLineTerminator===!0){let D=0,W,se;Ut.lastIndex=0;do c=c!==null?c:e.substring(p,p+h),W=Ut.test(c),W===!0&&(se=Ut.lastIndex-1,D++);while(W===!0);D!==0?(ye=ye+D,Y=h-se,this.updateTokenEndLineColumnLocation(A,f,se,D,ye,Y,h)):Y=this.computeNewColumn(Y,h)}else Y=this.computeNewColumn(Y,h);p=p+h,this.handleModes(H,$r,Nn,A)}else{let D=p,W=ye,se=Y,Z=Sn===!1;for(;Z===!1&&p<d;)for(p++,i=0;i<et;i++){let le=ie[i],Gt=le.pattern,xn=le.short;if(xn!==!1?m.charCodeAt(p)===xn&&(Z=!0):le.isCustom===!0?Z=Gt.exec(m,p,re,ve)!==null:(Gt.lastIndex=p,Z=Gt.exec(e)!==null),Z===!0)break}if(R=p-D,Y=this.computeNewColumn(Y,R),O=this.config.errorMessageProvider.buildUnexpectedCharactersMessage(m,D,R,W,se,Me.at(-1)),ce.push({offset:D,line:W,column:se,length:R,message:O}),Sn===!1)break}}return this.hasCustom||(re.length=v),{tokens:re,groups:ve,errors:ce}}handleModes(e,t,r,i){if(e.pop===!0){let s=e.push;t(i),s!==void 0&&r.call(this,s)}else e.push!==void 0&&r.call(this,e.push)}updateTokenEndLineColumnLocation(e,t,r,i,s,o,a){let c,l;t!==void 0&&(c=r===a-1,l=c?-1:0,i===1&&c===!0||(e.endLine=s+l,e.endColumn=o-1+-l))}computeNewColumn(e,t){return e+t}createOffsetOnlyToken(e,t,r,i){return{image:e,startOffset:t,tokenTypeIdx:r,tokenType:i}}createStartOnlyToken(e,t,r,i,s,o){return{image:e,startOffset:t,startLine:s,startColumn:o,tokenTypeIdx:r,tokenType:i}}createFullToken(e,t,r,i,s,o,a){return{image:e,startOffset:t,endOffset:t+a-1,startLine:s,endLine:s,startColumn:o,endColumn:o+a-1,tokenTypeIdx:r,tokenType:i}}addTokenUsingPush(e,t,r){return e.push(r),t}addTokenUsingMemberAccess(e,t,r){return e[t]=r,t++,t}handlePayloadNoCustom(e,t){}handlePayloadWithCustom(e,t){t!==null&&(e.payload=t)}match(e,t,r){return e.test(t)===!0?t.substring(r,e.lastIndex):null}matchLength(e,t,r){return e.test(t)===!0?e.lastIndex-r:-1}};w.SKIPPED="This marks a skipped Token pattern, this means each token identified by it will be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.";w.NA=/NOT_APPLICABLE/;function pe(n){return Qt(n)?n.LABEL:n.name}function Si(n){return n.name}function Qt(n){return typeof n.LABEL=="string"&&n.LABEL!==""}var xi="parent",Xn="categories",zn="label",Yn="group",qn="push_mode",Qn="pop_mode",Zn="longer_alt",Jn="line_breaks",er="start_chars_hint";function ut(n){return _i(n)}function _i(n){let e=n.pattern,t={};if(t.name=n.name,e!==void 0&&(t.PATTERN=e),Object.hasOwn(n,xi))throw`The parent property is no longer supported. See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.`;return Object.hasOwn(n,Xn)&&(t.CATEGORIES=n[Xn]),te([t]),Object.hasOwn(n,zn)&&(t.LABEL=n[zn]),Object.hasOwn(n,Yn)&&(t.GROUP=n[Yn]),Object.hasOwn(n,Qn)&&(t.POP_MODE=n[Qn]),Object.hasOwn(n,qn)&&(t.PUSH_MODE=n[qn]),Object.hasOwn(n,Zn)&&(t.LONGER_ALT=n[Zn]),Object.hasOwn(n,Jn)&&(t.LINE_BREAKS=n[Jn]),Object.hasOwn(n,er)&&(t.START_CHARS_HINT=n[er]),t}var X=ut({name:"EOF",pattern:w.NA});te([X]);function me(n,e,t,r,i,s,o,a){return{image:e,startOffset:t,endOffset:r,startLine:i,endLine:s,startColumn:o,endColumn:a,tokenTypeIdx:n.tokenTypeIdx,tokenType:n}}function Zt(n,e){return ee(n,e)}var dt={buildMismatchTokenMessage({expected:n,actual:e,previous:t,ruleName:r}){return`Expecting ${Qt(n)?`--> ${pe(n)} <--`:`token of type --> ${n.name} <--`} but found --> '${e.image}' <--`},buildNotAllInputParsedMessage({firstRedundant:n,ruleName:e}){return"Redundant input, expecting EOF but found: "+n.image},buildNoViableAltMessage({expectedPathsPerAlt:n,actual:e,previous:t,customUserDescription:r,ruleName:i}){let s="Expecting: ",a=` but found: '`+e[0].image+"'";if(r)return s+r+a;{let h=`one of these possible Token sequences: ${n.reduce((f,T)=>f.concat(T),[]).map(f=>`[${f.map(T=>pe(T)).join(", ")}]`).map((f,T)=>` ${T+1}. ${f}`).join(` `)}`;return s+h+a}},buildEarlyExitMessage({expectedIterationPaths:n,actual:e,customUserDescription:t,ruleName:r}){let i="Expecting: ",o=` but found: '`+e[0].image+"'";if(t)return i+t+o;{let c=`expecting at least one iteration which starts with one of these possible Token sequences:: <${n.map(l=>`[${l.map(u=>pe(u)).join(",")}]`).join(" ,")}>`;return i+c+o}}};Object.freeze(dt);var tr={buildRuleNotFoundError(n,e){return"Invalid grammar, reference to a rule which is not defined: ->"+e.nonTerminalName+`<- inside top level rule: ->`+n.name+"<-"}},z={buildDuplicateFoundError(n,e){function t(u){return u instanceof I?u.terminalType.name:u instanceof S?u.nonTerminalName:""}let r=n.name,i=e[0],s=i.idx,o=j(i),a=t(i),c=s>0,l=`->${o}${c?s:""}<- ${a?`with argument: ->${a}<-`:""} appears more than once (${e.length} times) in the top level rule: ->${r}<-. For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES `;return l=l.replace(/[ \t]+/g," "),l=l.replace(/\s\s+/g,` `),l},buildNamespaceConflictError(n){return`Namespace conflict found in grammar. The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${n.name}>. To resolve this make sure each Terminal and Non-Terminal names are unique This is easy to accomplish by using the convention that Terminal names start with an uppercase letter and Non-Terminal names start with a lower case letter.`},buildAlternationPrefixAmbiguityError(n){let e=n.prefixPath.map(i=>pe(i)).join(", "),t=n.alternation.idx===0?"":n.alternation.idx;return`Ambiguous alternatives: <${n.ambiguityIndices.join(" ,")}> due to common lookahead prefix in <OR${t}> inside <${n.topLevelRule.name}> Rule, <${e}> may appears as a prefix path in all these alternatives. See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX For Further details.`},buildAlternationAmbiguityError(n){let e=n.alternation.idx===0?"":n.alternation.idx,t=n.prefixPath.length===0,r=`Ambiguous Alternatives Detected: <${n.ambiguityIndices.join(" ,")}> in <OR${e}> inside <${n.topLevelRule.name}> Rule, `;if(t)r+=`These alternatives are all empty (match no tokens), making them indistinguishable. Only the last alternative may be empty. `;else{let i=n.prefixPath.map(s=>pe(s)).join(", ");r+=`<${i}> may appears as a prefix path in all these alternatives. `}return r+=`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES For Further details.`,r},buildEmptyRepetitionError(n){let e=j(n.repetition);return n.repetition.idx!==0&&(e+=n.repetition.idx),`The repetition <${e}> within Rule <${n.topLevelRule.name}> can never consume any tokens. This could lead to an infinite loop.`},buildTokenNameError(n){return"deprecated"},buildEmptyAlternationError(n){return`Ambiguous empty alternative: <${n.emptyChoiceIdx+1}> in <OR${n.alternation.idx}> inside <${n.topLevelRule.name}> Rule. Only the last alternative may be an empty alternative.`},buildTooManyAlternativesError(n){return`An Alternation cannot have more than 256 alternatives: <OR${n.alternation.idx}> inside <${n.topLevelRule.name}> Rule. has ${n.alternation.definition.length+1} alternatives.`},buildLeftRecursionError(n){let e=n.topLevelRule.name,t=n.leftRecursionPath.map(s=>s.name),r=`${e} --> ${t.concat([e]).join(" --> ")}`;return`Left Recursion found in grammar. rule: <${e}> can be invoked from itself (directly or indirectly) without consuming any Tokens. The grammar path that causes this is: ${r} To fix this refactor your grammar to remove the left recursion. see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(n){return"deprecated"},buildDuplicateRuleNameError(n){let e;return n.topLevelRule instanceof G?e=n.topLevelRule.name:e=n.topLevelRule,`Duplicate definition, rule: ->${e}<- is already defined in the grammar: ->${n.grammarName}<-`}};function nr(n,e){let t=new Jt(n,e);return t.resolveRefs(),t.errors}var Jt=class extends F