From 7caf924703cf7c54b432afbe373fe39f9bcfaee2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Pinz=C3=B3n?= Date: Mon, 18 Mar 2024 17:50:58 +0100 Subject: [PATCH] Updated kwargs handling --- demo-2.html | 155 ++++++++++++++++++++ dist/caph1993-numpy-js.js | 2 +- dist/caph1993-numpy-js.js.map | 2 +- src/NDArray-class.ts | 94 +++++++----- src/NDArray/elementwise.ts | 7 +- src/NDArray/kwargs.ts | 61 ++++++++ src/NDArray/reduce.ts | 266 ++++++++++++++++++++++++++++------ src/NDArray/transform.ts | 13 +- src/index.ts | 3 +- src/modules/constructors.ts | 1 + src/modules/grammar.ts | 6 +- tests/tests_october.ts | 2 + 12 files changed, 518 insertions(+), 94 deletions(-) create mode 100644 demo-2.html create mode 100644 src/NDArray/kwargs.ts diff --git a/demo-2.html b/demo-2.html new file mode 100644 index 0000000..22f6191 --- /dev/null +++ b/demo-2.html @@ -0,0 +1,155 @@ + + + + + Numpy JS Demo 2 + + + + + + + + + + + + + + + + +
+

Demo of caph1993-numpy-js

+ +

Header:

+
+ + +
+

Your code (modify at will):

+
+ +
+
+
+ +
+
+
+ +
+
+

Errors:

+ +
+
+

Console output:

+ +
+
+ + + + + + \ No newline at end of file diff --git a/dist/caph1993-numpy-js.js b/dist/caph1993-numpy-js.js index 5806715..09f124a 100644 --- a/dist/caph1993-numpy-js.js +++ b/dist/caph1993-numpy-js.js @@ -1,2 +1,2 @@ -!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r,n=t();for(r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(self,()=>(()=>{"use strict";var n={209:function(e,t,r){var n=this&&this.__generator||function(n,i){var a,o,s,u={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},l={next:e(0),throw:e(1),return:e(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function e(r){return function(e){var t=[r,e];if(a)throw new TypeError("Generator is already executing.");for(;u=l&&t[l=0]?0:u;)try{if(a=1,o&&(s=2&t[0]?o.return:t[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,t[1])).done)return s;switch(o=0,(t=s?[2&t[0],s.value]:t)[0]){case 0:case 1:s=t;break;case 4:return u.label++,{value:t[1],done:!1};case 5:u.label++,o=t[1],t=[0];continue;case 7:t=u.ops.pop(),u.trys.pop();continue;default:if(!(s=0<(s=u.trys).length&&s[s.length-1])&&(6===t[0]||2===t[0])){u=0;continue}if(3===t[0]&&(!s||t[1]>s[0]&&t[1]>"]),s.prototype.logical_or=p(u.modules.operators.op_binary.or),s.prototype.logical_and=p(u.modules.operators.op_binary.and),s.prototype.logical_xor=p(u.modules.operators.op_binary.xor),s.prototype.greater=p(u.modules.operators.op_binary[">"]),s.prototype.less=p(u.modules.operators.op_binary["<"]),s.prototype.greater_equal=p(u.modules.operators.op_binary[">="]),s.prototype.less_equal=p(u.modules.operators.op_binary["<="]),s.prototype.equal=p(u.modules.operators.op_binary["=="]),s.prototype.not_equal=p(u.modules.operators.op_binary["!="]),s.prototype.bitwise_or=h(u.modules.operators.op_unary["~"]),s.prototype.logical_or=h(u.modules.operators.op_unary.not),s.prototype.isclose=u.modules.operators.isclose,s.prototype.allclose=u.modules.operators.allclose,s.prototype.assign=m(u.modules.operators.op_assign["="]),s.prototype.add_assign=m(u.modules.operators.op_assign["+="]),s.prototype.subtract_assign=m(u.modules.operators.op_assign["-="]),s.prototype.multiply_assign=m(u.modules.operators.op_assign["*="]),s.prototype.divide_assign=m(u.modules.operators.op_assign["/="]),s.prototype.mod_assign=m(u.modules.operators.op_assign["%="]),s.prototype.divide_int_assign=m(u.modules.operators.op_assign["//="]),s.prototype.pow_assign=m(u.modules.operators.op_assign["**="]),s.prototype.maximum_assign=m(u.modules.operators.op_assign["↑="]),s.prototype.minimum_assign=m(u.modules.operators.op_assign["↓="]),s.prototype.bitwise_or_assign=m(u.modules.operators.op_assign["|="]),s.prototype.bitwise_and_assign=m(u.modules.operators.op_assign["&="]),s.prototype.bitwise_shift_left_assign=m(u.modules.operators.op_assign["<<="]),s.prototype.bitwise_shift_right_assign=m(u.modules.operators.op_assign[">>="]),s.prototype.logical_or_assign=m(u.modules.operators.op_assign["or="]),s.prototype.logical_and_assign=m(u.modules.operators.op_assign["and="]),s.prototype.tolist=function(){return u.modules.jsInterface.tolist(this)},s.prototype.round=function(e){return void 0===e&&(e=0),e=Object.assign({decimals:e},this.__popKwArgs()).decimals,u.modules.elementwise.round(this,e)},s.prototype.transpose=function(e){return void 0===e&&(e=null),e=Object.assign({axes:e},this.__popKwArgs()).axes,u.modules.transform.transpose(this,e)},s.prototype.sort=function(e){return void 0===e&&(e=-1),e=Object.assign({axis:e},this.__popKwArgs()).axis,u.modules.transform.sort(this,e),null};s.prototype.op=function(){for(var e=[],t=0;t{Object.defineProperty(t,"__esModule",{value:!0}),t.ops=t.__make_elementwise=t.logical_not=t.bitwise_not=t.round=t.elementwise=void 0;var n=r(870);function i(e,t,r){return e=(0,n.asarray)(e),(0,n.new_NDArray)(e.flat.map(t),e.shape,r)}function a(e,t){return 0==(t=void 0===t?0:t)&&i(e,Math.round,Number),i(e,function(e){return parseFloat(e.toFixed(t))},Number)}function o(t,r){return void 0===r&&(r=Number),function(e){return i(e,t,r)}}t.elementwise=i,t.round=a,t.bitwise_not=function(e){return i(e,function(e){return~e},Number)},t.logical_not=function(e){return i(e,function(e){return!e},Boolean)},t.__make_elementwise=o,t.ops={sign:o(Math.sign),sqrt:o(Math.sqrt),square:o(function(e){return e*e}),abs:o(Math.abs),exp:o(Math.exp),log:o(Math.log),log2:o(Math.log2),log10:o(Math.log10),log1p:o(Math.log1p),sin:o(Math.sin),cos:o(Math.cos),tan:o(Math.tan),asin:o(Math.asin),acos:o(Math.acos),atan:o(Math.atan),atan2:o(Math.atan2),cosh:o(Math.cosh),sinh:o(Math.sinh),tanh:o(Math.tanh),acosh:o(Math.acosh),asinh:o(Math.asinh),atanh:o(Math.atanh),round:a}},350:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.modules=void 0,r(290);var n=r(870),i=r(591),a=r(545),o=r(525),s=r(194),u=r(307),l=r(737),r=r(728);t.modules={basic:n,jsInterface:a,indexes:i,elementwise:o,print:s,reduce:u,operators:l,transform:r}},591:function(e,t,r){var y=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,a=r.call(e),o=[];try{for(;(void 0===t||0=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},g=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var n,i=0,a=t.length;i=r.length)&&(c=":"),l--,s+=i,"None"==c||null===c){n.apparentShape.push(1);continue}if("..."==c){if(-1==i)throw new Error("Index can only have a single ellipsis. Found index(".concat(t,")"));for(var p in i=-1,a)a[p]=n[p].length;s=r.length-1,o=e.length-1;continue}}else c=":";for(var c=_.prototype.parse(c,e[o]),h=c.axisIndex,m=c.span,d=(u-=m,1),f=0;f=e.length)throw new Error("Index spans over more dimensions than available in shape [".concat(e,"]: index(").concat(t,")"));d*=e[o],o+=i}n.axisIndexes.push(h),"number"!=h.spec.type&&n.apparentShape.push(h.size),n.internalShape.push(d)}if(-1==i)for(var p in n)n[p].splice(0,a[p]).concat(n[p].reverse());return new v(n.apparentShape,n.internalShape,n.axisIndexes)}},545:function(e,t,r){var f=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,a=r.call(e),o=[];try{for(;(void 0===t||0=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},h=(Object.defineProperty(t,"__esModule",{value:!0}),t.allclose=t.isclose=t.op_assign=t.__make_assignment_operator=t._assign_operation_toJS=t.assign_operation=t.op_unary=t.op_binary=t.__make_operator_special=t.__make_operator=t._broadcast_shapes=t.binary_operation=void 0,r(591)),n=r(525),x=r(870),o=r(545);function m(e,t,r,n,i){if(void 0===i&&(i=null),(0,x.isarray)(this))return r.bind(x._NDArray.prototype).apply(void 0,b([this],_(arguments),!1));e=(0,x.asarray)(e),t=(0,x.asarray)(t);var a=_(I(e.shape,t.shape),3),o=a[0],s=a[1],u=a[2];if(null==i)i=(0,x.new_from)(o,function(e){},n);else if(!(0,x.isarray)(i))throw new Error("Out must be of type ".concat(x._NDArray,". Got ").concat(typeof i));for(var l=[],c=(0,x.shape_shifts)(s),p=(0,x.shape_shifts)(u),h=e.flat,m=t.flat,d=0;d>="|"//="|"or="|"and="|"xor="|"max="|"min="\n \n /* Declaration in precedence order (weakest first) */\n ArithmeticLogicExp = Precedence11\n\n /* https://docs.python.org/3/reference/expressions.html */\n Operator11 = "<" | "<=" | ">" | ">=" | "!=" | "=="\n Operator10 = "|"\n Operator09 = "^"\n Operator08 = "&"\n Operator07 = "<<" | ">>"\n Operator06 = "+" | "-"\n Operator05 = "*" | "@" | "/" | "//" | "%"\n Operator04 = "~" /* Unary */\n Operator03 = "+" | "-" /* Unary. Special treatment to prevent "-1.3" to be "-(array of 1.3)" */\n Operator02 = "**"\n /* Operator01 = "x[index]" | "x[index:index]" | "x(arguments...)" | "x.attribute" */\n /* Operator00 = "(expressions...)" */\n\n Precedence11 = Precedence11 Operator11 Precedence10 | "" "" Precedence10\n Precedence10 = Precedence10 Operator10 Precedence09 | "" "" Precedence09\n Precedence09 = Precedence09 Operator09 Precedence08 | "" "" Precedence08\n Precedence08 = Precedence08 Operator08 Precedence07 | "" "" Precedence07\n Precedence07 = Precedence07 Operator07 Precedence06 | "" "" Precedence06\n Precedence06 = Precedence06 Operator06 Precedence05 | "" "" Precedence05\n Precedence05 = Precedence05 Operator05 Precedence04 | "" "" Precedence04\n Precedence04 = "" Operator04 Precedence03 | "" "" Precedence03 /* Unary */\n Precedence03 = "" Operator03 Precedence02 | "" "" Precedence02 /* Special */\n Precedence02 = Precedence02 Operator02 Precedence03 | "" "" Precedence01\n Precedence01 = Arr\n \n Parenthesis = "(" ArithmeticLogicExp ")"\n Arr\n = Arr "." Name CallArgs -- method\n | Arr "." Name -- attribute\n | Arr "[" Slice "]" -- slice\n | Parenthesis\n | Name ("." Name)* CallArgs -- call\n | number\n | Variable\n\n Name (an identifier)\n = (letter|"_") (letter|"_"|digit)*\n\n number (a number)\n = ("+"|"-")? digit* "." digit+ "E" ("+"|"-")? "digit+"\n | ("+"|"-")? digit* "." digit+ "e" ("+"|"-")? "digit+"\n | ("+"|"-")? digit* "." digit+ "" "" ""\n | ("+"|"-")? digit+ "" "" "" "" ""\n \n int (an integer) = "" digit+ | "-" digit+ | "+" digit+\n\n CallArgs // Using empty strings instead of separate rules\n = "(" Args "," KwArgs ","? ")"\n | "(" Args ","? "" "" ")"\n | "(" "" ","? KwArgs ","? ")"\n | "(" "" "" "" "" ")"\n \n Args = NonemptyListOf\n KwArgs = NonemptyListOf\n KwArg = Name "=" ArgValue\n\n ArgValue = Constant | JsArray | ArithmeticLogicExp | String\n Constant = "True" | "False" | "None" | "np.nan" | "np.inf"\n JsArray\n = "[" ListOf ","? "]"\n | "(" ListOf ","? ")"\n\n String = "\'" any* "\'" | """ any* """\n \n Slice = NonemptyListOf\n SliceTerm\n = SliceRange\n | (":" | "..." | "None") -- constant\n | JsArray\n | ArithmeticLogicExp\n \n SliceRange\n = int ":" int ":" int\n | int ":" int "" ""\n | int ":" "" ":" int\n | int ":" "" "" ""\n | "" ":" int ":" int\n | "" ":" int "" ""\n | "" ":" "" ":" int\n | "" ":" "" "" ""\n}\n'],['\nArrayGrammar {\n Instruction\n = Variable "[" Slice "]" AssignSymbol ArithmeticLogicExp -- sliceAssignment\n | ArithmeticLogicExp -- expression\n \n Variable\n = "#" digit+ "#"\n \n AssignSymbol\n ="="|"+="|"-="|"*="|"/="|"%="|"&="|"|="|"^="|"@="|"**="|"<<="|">>="|"//="|"or="|"and="|"xor="|"max="|"min="\n \n /* Declaration in precedence order (weakest first) */\n ArithmeticLogicExp = Precedence11\n\n /* https://docs.python.org/3/reference/expressions.html */\n Operator11 = "<" | "<=" | ">" | ">=" | "!=" | "=="\n Operator10 = "|"\n Operator09 = "^"\n Operator08 = "&"\n Operator07 = "<<" | ">>"\n Operator06 = "+" | "-"\n Operator05 = "*" | "@" | "/" | "//" | "%"\n Operator04 = "~" /* Unary */\n Operator03 = "+" | "-" /* Unary. Special treatment to prevent "-1.3" to be "-(array of 1.3)" */\n Operator02 = "**"\n /* Operator01 = "x[index]" | "x[index:index]" | "x(arguments...)" | "x.attribute" */\n /* Operator00 = "(expressions...)" */\n\n Precedence11 = Precedence11 Operator11 Precedence10 | "" "" Precedence10\n Precedence10 = Precedence10 Operator10 Precedence09 | "" "" Precedence09\n Precedence09 = Precedence09 Operator09 Precedence08 | "" "" Precedence08\n Precedence08 = Precedence08 Operator08 Precedence07 | "" "" Precedence07\n Precedence07 = Precedence07 Operator07 Precedence06 | "" "" Precedence06\n Precedence06 = Precedence06 Operator06 Precedence05 | "" "" Precedence05\n Precedence05 = Precedence05 Operator05 Precedence04 | "" "" Precedence04\n Precedence04 = "" Operator04 Precedence03 | "" "" Precedence03 /* Unary */\n Precedence03 = "" Operator03 Precedence02 | "" "" Precedence02 /* Special */\n Precedence02 = Precedence02 Operator02 Precedence03 | "" "" Precedence01\n Precedence01 = Arr\n \n Parenthesis = "(" ArithmeticLogicExp ")"\n Arr\n = Arr "." Name CallArgs -- method\n | Arr "." Name -- attribute\n | Arr "[" Slice "]" -- slice\n | Parenthesis\n | Name ("." Name)* CallArgs -- call\n | number\n | Variable\n\n Name (an identifier)\n = (letter|"_") (letter|"_"|digit)*\n\n number (a number)\n = ("+"|"-")? digit* "." digit+ "E" ("+"|"-")? "digit+"\n | ("+"|"-")? digit* "." digit+ "e" ("+"|"-")? "digit+"\n | ("+"|"-")? digit* "." digit+ "" "" ""\n | ("+"|"-")? digit+ "" "" "" "" ""\n \n int (an integer) = "" digit+ | "-" digit+ | "+" digit+\n\n CallArgs // Using empty strings instead of separate rules\n = "(" Args "," KwArgs ","? ")"\n | "(" Args ","? "" "" ")"\n | "(" "" ","? KwArgs ","? ")"\n | "(" "" "" "" "" ")"\n \n Args = NonemptyListOf\n KwArgs = NonemptyListOf\n KwArg = Name "=" ArgValue\n\n ArgValue = Constant | JsArray | ArithmeticLogicExp | String\n Constant = "True" | "False" | "None" | "np.nan" | "np.inf"\n JsArray\n = "[" ListOf ","? "]"\n | "(" ListOf ","? ")"\n\n String = "\\\'" any* "\\\'" | "\\"" any* "\\""\n \n Slice = NonemptyListOf\n SliceTerm\n = SliceRange\n | (":" | "..." | "None") -- constant\n | JsArray\n | ArithmeticLogicExp\n \n SliceRange\n = int ":" int ":" int\n | int ":" int "" ""\n | int ":" "" ":" int\n | int ":" "" "" ""\n | "" ":" int ":" int\n | "" ":" int "" ""\n | "" ":" "" ":" int\n | "" ":" "" "" ""\n}\n'])),o.ohmGrammar=t.grammar(o.grammar),o.__makeSemantics=function(){var i=[],e={Instruction_sliceAssignment:function(e,t,r,n,i,a){var o=e.parse(),e=a.parse(),a=i.sourceString,i=r.parse(),r=l.nd_modules.basic.asarray(o);if(l.nd_modules.operators.op_assign[a](o,i,e),r!==o){for(l.nd_modules.jsInterface.tolist(r);o.length;)o.pop();o.push.apply(o,u([],s(o),!1))}return null},Instruction_expression:function(e){e=e.parse();return"number"==typeof e||"boolean"==typeof e||Array.isArray(e)||l.nd_modules.basic.isarray(e)&&(e=l.nd_modules.basic.number_collapse(e)),e},Precedence11:t,Precedence10:t,Precedence09:t,Precedence08:t,Precedence07:t,Precedence06:t,Precedence05:t,Precedence04:r,Precedence03:r,Precedence02:t,number:function(e,t,r,n,i,a,o){return parseFloat(this.sourceString)},Arr_slice:function(e,t,r,n){e=e.parse(),r=r.parse();return e.index.apply(e,u([],s(r),!1))},SliceTerm_constant:function(e){return e.sourceString},Arr_call:function(e,t,r,n){e=e.sourceString+t.sourceString,t=(e="np."==e.slice(0,3)?e.slice(3):e).split(".").reduce(function(e,t){return e[t]},l.np);if(void 0===t)throw new Error("Unrecognized function ".concat(e));e=n.parse(),n=e.args,e=e.kwArgs;return t.bind(e).apply(void 0,u([],s(n),!1))},Arr_method:function(e,t,r,n){var e=e.parse(),r=r.sourceString,n=n.parse(),i=n.args,n=n.kwArgs;if(void 0===e[r])throw new Error("Unrecognized method ".concat(r));return(e=e.withKwArgs(n))[r].apply(e,u([],s(i),!1))},Parenthesis:function(e,t,r){return t.parse()},Arr_attribute:function(e,t,r){return e.parse()[r.sourceString]},Variable:function(e,t,r){var t=parseInt(t.sourceString),t=i[t],n=Array.isArray(t)&&t.length&&l.nd_modules.basic.isarray(t[0]);return t=Array.isArray(t)&&!n?l.nd_modules.basic.array(t):t},int:function(e,t){t=parseInt(t.sourceString);return"-"==e.sourceString?-t:t},SliceRange:function(e,t,r,n,i){return this.sourceString},Constant:function(e){switch(e.sourceString){case"True":return!0;case"False":return!1;case"None":return null;case"np.nan":return Number.NaN;case"np.inf":return Number.POSITIVE_INFINITY}throw new Error("Unrecognized constant ".concat(e.sourceString))},String:function(e,t,r){return t.sourceString},CallArgs:function(e,t,r,n,i,a){t=t.parse()||[],n=n.parse()||[];return{args:t,kwArgs:Object.fromEntries(n.map(function(e){var e=s(e,2),t=e[0],e=e[1];return[t,e=l.nd_modules.basic.isarray(e)?l.nd_modules.basic.number_collapse(e):e]}))}},KwArg:function(e,t,r){return[e.sourceString,r.parse()]},NonemptyListOf:function(e,t,r){return u([e],s(r.children),!1).map(function(e){return e.parse()})},JsArray:function(e,t,r,n){var i,a=t.parse(),o=l.nd_modules.jsInterface.tolist;for(i in a)l.nd_modules.basic.isarray(a[i])&&(a[i]=o(a[i]));return a},_terminal:function(){return null}};function t(e,t,r){e=e.parse(),r=r.parse(),t=t.sourceString;return""==t&&null===e?r:l.nd_modules.operators.op_binary[t](e,r)}function r(e,t,r){var n=r.parse(),r=t.sourceString;if(""==r)return n;var i=l.nd_modules.operators.op_unary;switch(r){case"+":return i["+"](n);case"-":return i["-"](n);case"~":return i["~"](n);case"!":return i.not(n)}throw new Error("Programming Error: ".concat(r))}var a=o.ohmGrammar.createSemantics();return a.addOperation("parse",e),{parse:function(e){for(var t=[],r=1;r{Object.defineProperty(t,"__esModule",{value:!0}),t.modules=void 0,r(167);var n=r(942),i=r(70),r=r(373);t.modules={constructors:n,grammar:i,random:r}},373:function(e,t,r){var i=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,a=r.call(e),o=[];try{for(;(void 0===t||0{function t(e){const t=e||"";return function(){throw new Error("this method "+t+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function m(e,t){if(!e)throw new Error(t||"Assertion failed")}function D(e,t,r){let n;Object.defineProperty(e,t,{get(){return n=n||r.call(this)}})}function T(e,t){for(var r=[];0e,t)}function q(t){var r=[];for(let e=0;e{t.indexOf(e)<0&&t.push(e)}),t}function l(e){e=e[0];return e===e.toUpperCase()}function U(e){return!l(e)}function K(e,t,r){return e.lengthString.fromCodePoint(parseInt(e,16));function $(e){if("\\"!==e.charAt(0))return e;switch(e.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 V(e.slice(2,4));case"u":return"{"===e.charAt(2)?V(e.slice(3,-1)):V(e.slice(2,6));default:return e.charAt(1)}}function H(t){if(null==t)return String(t);var r=Object.prototype.toString.call(t);try{let e;return(e=t.constructor&&t.constructor.name?t.constructor.name:0===r.indexOf("[object ")?r.slice(8,-1):typeof t)+": "+JSON.stringify(String(t))}catch(e){return r}}var W=Object.freeze({__proto__:null,abstract:t,assert:m,defineLazyProperty:D,clone:function(e){return e&&Object.assign({},e)},repeatFn:T,repeatStr:B,repeat:G,getDuplicates:q,copyWithoutDuplicates:z,isSyntactic:l,isLexical:U,padLeft:K,StringBuffer:d,unescapeCodePoint:$,unexpectedObjToString:H});const J={Lu:/\p{Lu}/u,Ll:/\p{Ll}/u,Lt:/\p{Lt}/u,Lm:/\p{Lm}/u,Lo:/\p{Lo}/u,Nl:/\p{Nl}/u,Nd:/\p{Nd}/u,Mn:/\p{Mn}/u,Mc:/\p{Mc}/u,Pc:/\p{Pc}/u,Zs:/\p{Zs}/u,L:/\p{Letter}/u,Ltmo:/\p{Lt}|\p{Lm}|\p{Lo}/u};class n{constructor(){if(this.constructor===n)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(e){return e&&(this.source=e.trimmed()),this}}const r=Object.create(n.prototype),i=Object.create(n.prototype);class c extends n{constructor(e){super(),this.obj=e}}class a extends n{constructor(e,t){super(),this.from=e,this.to=t,this.matchCodePoint=1new I(e.ruleName,e.args)).join("\n"),n+="\nApplication stack (most recent application last):\n"+r),A(n,e.expr.source)}function ne(e,t,r,n){return A("Rule "+e+" involves an alternation which has inconsistent arity (expected "+t+", got "+r+")",n.source)}function ie(e){if(1===e.length)throw e[0];if(1e.message),A(["Errors:"].concat(t).join("\n- "),e[0].interval);var t}function ae(e,t,r){var n=e.length;return(e.slice(0,r)+t+e.slice(r+t.length)).substr(0,n)}function oe(...t){var r=this,n=r["offset"],i=W["repeatStr"];const a=new d,o=(a.append("Line "+r.lineNum+", col "+r.colNum+":\n"),function(e){let t=0;return e.map(e=>{e=e.toString();return t=Math.max(t,e.length),e}).map(e=>K(e,t))}([null==r.prevLine?0:r.lineNum-1,r.lineNum,null==r.nextLine?0:r.lineNum+1]));var e=(e,t,r)=>{a.append(r+o[e]+" | "+t+"\n")},s=(null!=r.prevLine&&e(0,r.prevLine," "),e(1,r.line,"> "),r.line.length);let u=i(" ",s+1);for(let e=0;e= 0 and <= end"),n-r.colNum+1),l=Math.max(0,l-p),c=Math.min(c-p,s);u=ae(u,i("~",c-l),l)}var h=2+o[1].length+3;return a.append(i(" ",h)),u=ae(u,"^",r.colNum-1),a.append(u.replace(/ +$/,"")+"\n"),null!=r.nextLine&&e(2,r.nextLine," "),a.contents()}let se=[];function ue(e){se.push(e)}function le(e,t){let r=1,n=1,i=0,a=0,o=null,s=null,u=-1;for(;i{let t=0;return e=>""+e+t++})();class S{constructor(e,t,r){this.sourceString=e,this.startIdx=t,this.endIdx=r}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(...e){return S.coverage(...e,this)}collapsedLeft(){return new S(this.sourceString,this.startIdx,this.startIdx)}collapsedRight(){return new S(this.sourceString,this.endIdx,this.endIdx)}getLineAndColumn(){return le(this.sourceString,this.startIdx)}getLineAndColumnMessage(){var e=[this.startIdx,this.endIdx];return ce(this.sourceString,this.startIdx,e)}minus(e){if(this.sourceString!==e.sourceString)throw Q();return this.startIdx===e.startIdx&&this.endIdx===e.endIdx?[]:this.startIdx=e.startIdx&&this.endIdx<=e.endIdx,"other interval does not cover this one"),new S(this.sourceString,this.startIdx-e.startIdx,this.endIdx-e.startIdx)}trimmed(){var e=this["contents"],t=this.startIdx+e.match(/^\s*/)[0].length,e=this.endIdx-e.match(/\s*$/)[0].length;return new S(this.sourceString,t,e)}subInterval(e,t){e=this.startIdx+e;return new S(this.sourceString,e,e+t)}}S.coverage=function(e,...t){let{startIdx:r,endIdx:n}=e;for(const i of t){if(i.sourceString!==e.sourceString)throw Q();r=Math.min(r,i.startIdx),n=Math.max(n,i.endIdx)}return new S(e.sourceString,r,n)};class he{constructor(e){this.source=e,this.pos=0,this.examinedLength=0}atEnd(){var e=this.pos>=this.source.length;return this.examinedLength=Math.max(this.examinedLength,this.pos+1),e}next(){var e=this.source[this.pos++];return this.examinedLength=Math.max(this.examinedLength,this.pos),e}nextCharCode(){var e=this.next();return e&&e.charCodeAt(0)}nextCodePoint(){var e=this.source.slice(this.pos++).codePointAt(0);return 65535!e.isFluffy());for(let e=0;e{var t=i[e];r+t.examinedLength>n?delete i[e]:(this.maxExaminedLength=Math.max(this.maxExaminedLength,t.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,t.rightmostFailureOffset))})}}}const fe="⋅",ye="␉",ge="␊",ve="␍",_e={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function be(e){return"string"==typeof e?e.replace(/ /g,fe).replace(/\t/g,ye).replace(/\n/g,ge).replace(/\r/g,ve):String(e)}class N{constructor(e,t,r,n,i,a,o){this.input=e,this.pos=this.pos1=t,this.pos2=r,this.source=new S(e,t,r),this.expr=n,this.bindings=a,this.children=o||[],this.terminatingLREntry=null,this._flags=i?_e.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(e){e=new N(this.input,this.pos,this.pos2,e,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(e,t){this.terminatingLREntry=new N(this.input,this.pos,this.pos2,this.expr,!1,[t],[e]),this.terminatingLREntry.terminatesLR=!0}walk(e,i){let a=e;function o(t,e,r){let n=!0;(n=a.enter&&a.enter.call(i,t,e,r)===N.prototype.SKIP?!1:n)&&(t.children.forEach(e=>{o(e,t,r+1)}),a.exit)&&a.exit.call(i,t,e,r)}"function"==typeof a&&(a={enter:a}),this.isRootNode?this.children.forEach(e=>{o(e,null,0)}):o(this,null,0)}toString(){const o=new d;return this.walk((e,t,r)=>{if(!e)return this.SKIP;var n,i,a;"Alt"!==e.expr.constructor.name&&(o.append((n=e.input,a=e.pos,i=10,((n=be(n.slice(a,a+i))).length{const t=_e[e];Object.defineProperty(N.prototype,e,{get(){return 0!=(this._flags&t)},set(e){e?this._flags|=t:this._flags&=~t}})}),n.prototype.allowsSkippingPrecedingSpace=t("allowsSkippingPrecedingSpace"),r.allowsSkippingPrecedingSpace=i.allowsSkippingPrecedingSpace=I.prototype.allowsSkippingPrecedingSpace=c.prototype.allowsSkippingPrecedingSpace=a.prototype.allowsSkippingPrecedingSpace=w.prototype.allowsSkippingPrecedingSpace=function(){return!0},s.prototype.allowsSkippingPrecedingSpace=f.prototype.allowsSkippingPrecedingSpace=x.prototype.allowsSkippingPrecedingSpace=b.prototype.allowsSkippingPrecedingSpace=_.prototype.allowsSkippingPrecedingSpace=o.prototype.allowsSkippingPrecedingSpace=h.prototype.allowsSkippingPrecedingSpace=function(){return!1};let O;ue(e=>{O=e});let xe;n.prototype.assertAllApplicationsAreValid=function(e,t){xe=0,this._assertAllApplicationsAreValid(e,t)},n.prototype._assertAllApplicationsAreValid=t("_assertAllApplicationsAreValid"),r._assertAllApplicationsAreValid=i._assertAllApplicationsAreValid=c.prototype._assertAllApplicationsAreValid=a.prototype._assertAllApplicationsAreValid=o.prototype._assertAllApplicationsAreValid=w.prototype._assertAllApplicationsAreValid=function(e,t){},x.prototype._assertAllApplicationsAreValid=function(e,t){xe++,this.expr._assertAllApplicationsAreValid(e,t),xe--},s.prototype._assertAllApplicationsAreValid=function(t,r){for(let e=0;e{if(e._assertAllApplicationsAreValid(t,r,s),1!==e.getArity())throw A("Invalid parameter to rule "+this.ruleName+": "+(e=e)+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)})},n.prototype.assertChoicesHaveUniformArity=t("assertChoicesHaveUniformArity"),r.assertChoicesHaveUniformArity=i.assertChoicesHaveUniformArity=c.prototype.assertChoicesHaveUniformArity=a.prototype.assertChoicesHaveUniformArity=o.prototype.assertChoicesHaveUniformArity=x.prototype.assertChoicesHaveUniformArity=w.prototype.assertChoicesHaveUniformArity=function(e){},s.prototype.assertChoicesHaveUniformArity=function(t){if(0!==this.terms.length){var r=this.terms[0].getArity();for(let e=0;e{e.assertIteratedExprsAreNotNullable(t)})};class Ie{constructor(e){this.matchLength=e}get ctorName(){throw new Error("subclass responsibility")}numChildren(){return this.children?this.children.length:0}childAt(e){if(this.children)return this.children[e]}indexOfChild(e){return this.children.indexOf(e)}hasChildren(){return 0{t[e]=(t[e]||0)+1}),Object.keys(t).forEach(n=>{if(!(t[n]<=1)){let r=1;i.forEach((e,t)=>{e===n&&(i[t]=e+"_"+r++)})}})}n.prototype.eval=t("eval"),r.eval=function(e){var t=e["inputStream"],r=t.pos,t=t.nextCodePoint();return void 0!==t?(e.pushBinding(new P(String.fromCodePoint(t).length),r),!0):(e.processFailure(r,this),!1)},i.eval=function(e){var t=e["inputStream"],r=t.pos;return t.atEnd()?(e.pushBinding(new P(0),r),!0):(e.processFailure(r,this),!1)},c.prototype.eval=function(e){var t=e["inputStream"],r=t.pos;return t.matchString(this.obj)?(e.pushBinding(new P(this.obj.length),r),!0):(e.processFailure(r,this),!1)},a.prototype.eval=function(e){var t=e["inputStream"],r=t.pos,t=this.matchCodePoint?t.nextCodePoint():t.nextCharCode();return void 0!==t&&this.from.codePointAt(0)<=t&&t<=this.to.codePointAt(0)?(e.pushBinding(new P(String.fromCodePoint(t).length),r),!0):(e.processFailure(r,this),!1)},o.prototype.eval=function(e){return e.eval(e.currentApplication().args[this.index])},x.prototype.eval=function(e){e.enterLexifiedContext();var t=e.eval(this.expr);return e.exitLexifiedContext(),t},s.prototype.eval=function(t){for(let e=0;ee.outputRecipe(t,r)))},u.prototype.outputRecipe=function(e,t){return this.terms[0].outputRecipe(e,t)},p.prototype.outputRecipe=function(t,r){var e=this.terms.slice(0,this.expansionPos),n=this.terms.slice(this.expansionPos+1);return["splice",E(this,r),e.map(e=>e.outputRecipe(t,r)),n.map(e=>e.outputRecipe(t,r))]},h.prototype.outputRecipe=function(t,r){return["seq",E(this,r)].concat(this.factors.map(e=>e.outputRecipe(t,r)))},y.prototype.outputRecipe=g.prototype.outputRecipe=v.prototype.outputRecipe=_.prototype.outputRecipe=b.prototype.outputRecipe=x.prototype.outputRecipe=function(e,t){return[this.constructor.name.toLowerCase(),E(this,t),this.expr.outputRecipe(e,t)]},I.prototype.outputRecipe=function(t,r){return["app",E(this,r),this.ruleName,this.args.map(e=>e.outputRecipe(t,r))]},w.prototype.outputRecipe=function(e,t){return["unicodeChar",E(this,t),this.category]},n.prototype.introduceParams=t("introduceParams"),r.introduceParams=i.introduceParams=c.prototype.introduceParams=a.prototype.introduceParams=o.prototype.introduceParams=w.prototype.introduceParams=function(e){return this},s.prototype.introduceParams=function(n){return this.terms.forEach((e,t,r)=>{r[t]=e.introduceParams(n)}),this},h.prototype.introduceParams=function(n){return this.factors.forEach((e,t,r)=>{r[t]=e.introduceParams(n)}),this},f.prototype.introduceParams=_.prototype.introduceParams=b.prototype.introduceParams=x.prototype.introduceParams=function(e){return this.expr=this.expr.introduceParams(e),this},I.prototype.introduceParams=function(n){var e=n.indexOf(this.ruleName);if(0<=e){if(0{r[t]=e.introduceParams(n)}),this},n.prototype.isNullable=function(e){return this._isNullable(e,Object.create(null))},n.prototype._isNullable=t("_isNullable"),r._isNullable=a.prototype._isNullable=o.prototype._isNullable=g.prototype._isNullable=w.prototype._isNullable=function(e,t){return!1},i._isNullable=function(e,t){return!0},c.prototype._isNullable=function(e,t){return"string"==typeof this.obj&&""===this.obj},s.prototype._isNullable=function(t,r){return 0===this.terms.length||this.terms.some(e=>e._isNullable(t,r))},h.prototype._isNullable=function(t,r){return this.factors.every(e=>e._isNullable(t,r))},y.prototype._isNullable=v.prototype._isNullable=_.prototype._isNullable=b.prototype._isNullable=function(e,t){return!0},x.prototype._isNullable=function(e,t){return this.expr._isNullable(e,t)},I.prototype._isNullable=function(e,t){var r,n=this.toMemoKey();return Object.prototype.hasOwnProperty.call(t,n)||(r=e.rules[this.ruleName]["body"],r=r.substituteParams(this.args),t[n]=!1,t[n]=r._isNullable(e,t)),t[n]},n.prototype.substituteParams=t("substituteParams"),r.substituteParams=i.substituteParams=c.prototype.substituteParams=a.prototype.substituteParams=w.prototype.substituteParams=function(e){return this},o.prototype.substituteParams=function(e){return e[this.index]},s.prototype.substituteParams=function(t){return new s(this.terms.map(e=>e.substituteParams(t)))},h.prototype.substituteParams=function(t){return new h(this.factors.map(e=>e.substituteParams(t)))},f.prototype.substituteParams=_.prototype.substituteParams=b.prototype.substituteParams=x.prototype.substituteParams=function(e){return new this.constructor(this.expr.substituteParams(e))},I.prototype.substituteParams=function(t){var e;return 0===this.args.length?this:(e=this.args.map(e=>e.substituteParams(t)),new I(this.ruleName,e))},n.prototype.toArgumentNameList=t("toArgumentNameList"),r.toArgumentNameList=function(e,t){return["any"]},i.toArgumentNameList=function(e,t){return["end"]},c.prototype.toArgumentNameList=function(e,t){return"string"==typeof this.obj&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+e]},a.prototype.toArgumentNameList=function(e,t){let r=this.from+"_to_"+this.to;return Se(r)||(r="_"+r),[r=Se(r)?r:"$"+e]},s.prototype.toArgumentNameList=function(t,e){var r=this.terms.map(e=>e.toArgumentNameList(t,!0)),n=[],i=r[0].length;for(let t=0;t{e=e.toArgumentNameList(t,!0);r=r.concat(e),t+=e.length}),e||Ne(r),r},f.prototype.toArgumentNameList=function(e,t){e=this.expr.toArgumentNameList(e,t).map(e=>"s"===e[e.length-1]?e+"es":e+"s");return t||Ne(e),e},v.prototype.toArgumentNameList=function(e,t){return this.expr.toArgumentNameList(e,t).map(e=>"opt"+e[0].toUpperCase()+e.slice(1))},_.prototype.toArgumentNameList=function(e,t){return[]},b.prototype.toArgumentNameList=x.prototype.toArgumentNameList=function(e,t){return this.expr.toArgumentNameList(e,t)},I.prototype.toArgumentNameList=function(e,t){return[this.ruleName]},w.prototype.toArgumentNameList=function(e,t){return["$"+e]},o.prototype.toArgumentNameList=function(e,t){return["param"+this.index]},n.prototype.toDisplayString=t("toDisplayString"),s.prototype.toDisplayString=h.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"},r.toDisplayString=i.toDisplayString=f.prototype.toDisplayString=_.prototype.toDisplayString=b.prototype.toDisplayString=x.prototype.toDisplayString=c.prototype.toDisplayString=a.prototype.toDisplayString=o.prototype.toDisplayString=function(){return this.toString()},I.prototype.toDisplayString=function(){var e;return 0e.toDisplayString()),this.ruleName+"<"+e.join(",")+">"):this.ruleName},w.prototype.toDisplayString=function(){return"Unicode ["+this.category+"] character"};class L{constructor(e,t,r){if("description"!==(n=r)&&"string"!==n&&"code"!==n)throw new Error("invalid Failure type: "+r);var n;this.pexpr=e,this.text=t,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(e){return this.getText()===e.getText()&&this.type===e.type&&(!this.isFluffy()||this.isFluffy()&&e.isFluffy())}toString(){return"string"===this.type?JSON.stringify(this.getText()):this.getText()}clone(){var e=new L(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}}n.prototype.toFailure=t("toFailure"),r.toFailure=function(e){return new L(this,"any object","description")},i.toFailure=function(e){return new L(this,"end of input","description")},c.prototype.toFailure=function(e){return new L(this,this.obj,"string")},a.prototype.toFailure=function(e){return new L(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")},_.prototype.toFailure=function(e){e=this.expr===r?"nothing":"not "+this.expr.toFailure(e);return new L(this,e,"description")},b.prototype.toFailure=function(e){return this.expr.toFailure(e)},I.prototype.toFailure=function(e){let t=e.rules[this.ruleName]["description"];return t||(e=/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a",t=e+" "+this.ruleName),new L(this,t,"description")},w.prototype.toFailure=function(e){return new L(this,"a Unicode ["+this.category+"] character","description")},s.prototype.toFailure=function(t){var e="("+this.terms.map(e=>e.toFailure(t)).join(" or ")+")";return new L(this,e,"description")},h.prototype.toFailure=function(t){var e="("+this.factors.map(e=>e.toFailure(t)).join(" ")+")";return new L(this,e,"description")},f.prototype.toFailure=function(e){e="("+this.expr.toFailure(e)+this.operator+")";return new L(this,e,"description")},n.prototype.toString=t("toString"),r.toString=function(){return"any"},i.toString=function(){return"end"},c.prototype.toString=function(){return JSON.stringify(this.obj)},a.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)},o.prototype.toString=function(){return"$"+this.index},x.prototype.toString=function(){return"#("+this.expr.toString()+")"},s.prototype.toString=function(){return 1===this.terms.length?this.terms[0].toString():"("+this.terms.map(e=>e.toString()).join(" | ")+")"},h.prototype.toString=function(){return 1===this.factors.length?this.factors[0].toString():"("+this.factors.map(e=>e.toString()).join(" ")+")"},f.prototype.toString=function(){return this.expr+this.operator},_.prototype.toString=function(){return"~"+this.expr},b.prototype.toString=function(){return"&"+this.expr},I.prototype.toString=function(){var e;return 0e.toString()),this.ruleName+"<"+e.join(",")+">"):this.ruleName},w.prototype.toString=function(){return"\\p{"+this.category+"}"};class Oe extends n{constructor(e){super(),this.obj=e}_getString(e){e=e.currentApplication().args[this.obj.index];return m(e instanceof c,"expected a Terminal expression"),e.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){var t=e["inputStream"],r=t.pos,n=this._getString(e);return t.matchString(n,!0)?(e.pushBinding(new P(n.length),r),!0):(e.processFailure(r,this),!1)}getArity(){return 1}substituteParams(e){return new Oe(this.obj.substituteParams(e))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(e){return new L(this,this.obj.toFailure(e)+" (case-insensitive)","description")}_isNullable(e,t){return this.obj._isNullable(e,t)}}var Pe=Object.freeze({__proto__:null,CaseInsensitiveTerminal:Oe,PExpr:n,any:r,end:i,Terminal:c,Range:a,Param:o,Alt:s,Extend:u,Splice:p,Seq:h,Iter:f,Star:y,Plus:g,Opt:v,Not:_,Lookahead:b,Lex:x,Apply:I,UnicodeChar:w});let Ee;ue(e=>{Ee=e.rules.applySyntactic.body});const Le=new I("spaces");class Re{constructor(e,t,r){this.matcher=e,this.startExpr=t,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new he(this.input),this.memoTable=e._memoTable,this.userData=void 0,this.doNotMemoize=!1,this._bindings=[],this._bindingOffsets=[],this._applicationStack=[],this._posStack=[0],this.inLexifiedContextStack=[!1],this.rightmostFailurePosition=-1,this._rightmostFailurePositionStack=[],this._recordedFailuresStack=[],void 0!==r&&(this.positionToRecordFailures=r,this.recordedFailures=Object.create(null))}posToOffset(e){return e-this._posStack[this._posStack.length-1]}enterApplication(e,t){this._posStack.push(this.inputStream.pos),this._applicationStack.push(t),this.inLexifiedContextStack.push(!1),e.enter(t),this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this.rightmostFailurePosition=-1}exitApplication(e,t){var r=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),e.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),t&&this.pushBinding(t,r)}enterLexifiedContext(){this.inLexifiedContextStack.push(!0)}exitLexifiedContext(){this.inLexifiedContextStack.pop()}currentApplication(){return this._applicationStack[this._applicationStack.length-1]}inSyntacticContext(){var e=this.currentApplication();return e?e.isSyntactic()&&!this.inLexifiedContext():this.startExpr.factors[0].isSyntactic()}inLexifiedContext(){return this.inLexifiedContextStack[this.inLexifiedContextStack.length-1]}skipSpaces(){return this.pushFailuresInfo(),this.eval(Le),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==Le?this.skipSpacesIfInSyntacticContext():this.inputStream.pos}pushBinding(e,t){this._bindings.push(e),this._bindingOffsets.push(this.posToOffset(t))}popBinding(){this._bindings.pop(),this._bindingOffsets.pop()}numBindings(){return this._bindings.length}truncateBindings(e){for(;this._bindings.length>e;)this.popBinding()}getCurrentPosInfo(){return this.getPosInfo(this.inputStream.pos)}getPosInfo(e){let t=this.memoTable[e];return t=t||(this.memoTable[e]=new de)}processFailure(e,t){this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures&&((e=this.currentApplication())&&(t=t.substituteParams(e.args)),this.recordFailure(t.toFailure(this.grammar),!1))}recordFailure(e,t){var r=e.toKey();this.recordedFailures[r]?this.recordedFailures[r].isFluffy()&&!e.isFluffy()&&this.recordedFailures[r].clearFluffy():this.recordedFailures[r]=t?e.clone():e}recordFailures(t,r){Object.keys(t).forEach(e=>{this.recordFailure(t[e],r)})}cloneRecordedFailures(){if(this.recordedFailures){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 0<=this.rightmostFailurePosition?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(e,t){e=this.memoTable[e];if(e&&t instanceof I){var e=e.memo[t.toMemoKey()];if(e&&e.traceEntry)return(e=e.traceEntry.cloneWithExpr(t)).isMemoized=!0,e}return null}getTraceEntry(e,t,r,n){var i;return t instanceof I&&(i=(i=this.currentApplication())?i.args:[],t=t.substituteParams(i)),this.getMemoizedTraceEntry(e,t)||new N(this.input,e,this.inputStream.pos,t,r,n,this.trace)}isTracing(){return!!this.trace}hasNecessaryInfo(e){return!(this.trace&&!e.traceEntry||this.recordedFailures&&this.inputStream.pos+e.rightmostFailureOffset===this.positionToRecordFailures&&!e.failuresAtRightmostPosition)}useMemoizedResult(e,t){this.trace&&this.trace.push(t.traceEntry);var r=this.inputStream.pos+t.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,r),this.recordedFailures&&this.positionToRecordFailures===r&&t.failuresAtRightmostPosition&&this.recordFailures(t.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,t.examinedLength+e),!!t.value&&(this.inputStream.pos+=t.matchLength,this.pushBinding(t.value,e),!0)}eval(e){var t=this["inputStream"],r=this._bindings.length,n=this.userData;let i;this.recordedFailures&&(i=this.recordedFailures,this.recordedFailures=Object.create(null));var a=t.pos,o=this.maybeSkipSpacesBefore(e);let s;this.trace&&(s=this.trace,this.trace=[]);var u,l=e.eval(this);return this.trace&&(u=this._bindings.slice(r),(o=this.getTraceEntry(o,e,l,u)).isImplicitSpaces=e===Le,o.isRootNode=e===this.startExpr,s.push(o),this.trace=s),l?this.recordedFailures&&t.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(e=>{this.recordedFailures[e].makeFluffy()}):(t.pos=a,this.truncateBindings(r),this.userData=n),this.recordedFailures&&this.recordFailures(i,!1),e===Ee&&this.skipSpaces(),l}getMatchResult(){this.grammar._setUpMatchState(this),this.eval(this.startExpr);let e;this.recordedFailures&&(e=Object.keys(this.recordedFailures).map(e=>this.recordedFailures[e]));var t=this._bindings[0];return t&&(t.grammar=this.grammar),new me(this.matcher,this.input,this.startExpr,t,this._bindingOffsets[0],this.rightmostFailurePosition,e)}getTrace(){this.trace=[];var e=this.getMatchResult(),t=this.trace[this.trace.length-1];return t.result=e,t}pushFailuresInfo(){this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this._recordedFailuresStack.push(this.recordedFailures)}popFailuresInfo(){this.rightmostFailurePosition=this._rightmostFailurePositionStack.pop(),this.recordedFailures=this._recordedFailuresStack.pop()}}class Fe{constructor(e){this.grammar=e,this._memoTable=[],this._input="",this._isMemoTableStale=!1}_resetMemoTable(){this._memoTable=[],this._isMemoTableStale=!1}getInput(){return this._input}setInput(e){return this._input!==e&&this.replaceInputRange(0,this._input.length,e),this}replaceInputRange(t,e,r){var n=this._input,i=this._memoTable;if(t<0||t>n.length||e<0||e>n.length||eObject.prototype.hasOwnProperty.call(e,t);class Me{constructor(e,t,r){this._node=e,this.source=t,this._baseInterval=r,e.isNonterminal()&&m(t===r),this._childWrappers=[]}_forgetMemoizedResultFor(t){delete this._node[this._semantics.attributeKeys[t]],this.children.forEach(e=>{e._forgetMemoizedResultFor(t)})}child(t){if(0<=t&&te._node),t=new Ae(t,[],-1,!1),t=this._semantics.wrap(t,null,null);return t._childWrappers=e,t}get children(){return this._children()}get ctorName(){return this._node.ctorName}get numChildren(){return this._node.numChildren()}get sourceString(){return this.source.contents}}class F{constructor(e,t){const n=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(t?t.Wrapper:Me){constructor(e,t,r){super(e,t,r),n.checkActionDictsIfHaventAlready(),this._semantics=n}toString(){return"[semantics wrapper for "+n.grammar.name+"]"}},this.super=t){if(!e.equals(this.super.grammar)&&!e._inheritsFrom(this.super.grammar))throw new Error("Cannot extend a semantics for grammar '"+this.super.grammar.name+"' for use with grammar '"+e.name+"' (not a sub-grammar)");this.operations=Object.create(this.super.operations),this.attributes=Object.create(this.super.attributes),this.attributeKeys=Object.create(null);for(const r in this.attributes)Object.defineProperty(this.attributeKeys,r,{value:pe(r)})}else this.operations=Object.create(null),this.attributes=Object.create(null),this.attributeKeys=Object.create(null)}toString(){return"[semantics for "+this.grammar.name+"]"}checkActionDictsIfHaventAlready(){this.checkedActionDicts||(this.checkActionDicts(),this.checkedActionDicts=!0)}checkActionDicts(){let e;for(e in this.operations)this.operations[e].checkActionDict(this.grammar);for(e in this.attributes)this.attributes[e].checkActionDict(this.grammar)}toRecipe(e){function l(e){return e.super!==F.BuiltInSemantics._getSemantics()}let c="(function(g) {\n";if(l(this)){c+=" var semantics = "+this.super.toRecipe(!0)+"(g";var t=this.super.grammar;let e=this.grammar;for(;e!==t;)c+=".superGrammar",e=e.superGrammar;c=c+");\n"+" return g.extendSemantics(semantics)"}else c+=" return g.createSemantics()";return["Operation","Attribute"].forEach(s=>{const u=this[s.toLowerCase()+"s"];Object.keys(u).forEach(e=>{const{actionDict:r,formals:t,builtInDefault:n}=u[e];let i=e;0{if(r[t]!==n){let e=r[t].toString().trim();e=e.replace(/^.*\(/,"function("),o.push("\n "+JSON.stringify(t)+": "+e)}}),c+=o.join(",")+"\n })"})}),c+=";\n })",c=e?c:"(function() {\n var grammar = this.fromRecipe("+this.grammar.toRecipe()+");\n var semantics = "+c+"(grammar);\n return semantics;\n});\n"}addOperationOrAttribute(o,e,t){const s=o+"s";e=Ce(e,o);const u=e["name"];function r(...e){var t=(this._semantics.operations[i]||this._semantics.attributes[i]).formals.map(e=>this.args[e]);if(this.isIteration()||1!==e.length)throw function(e,t,r,n){n=n.slice(0,-1).map(e=>{var t=" "+e[0].name+" > "+e[1];return 3===e.length?t+" for '"+e[2]+"'":t}).join("\n"),n+="\n "+t+" > "+e;let i="";return(r=A([`Missing semantic action for '${e}' in ${r} '${t}'.`+(i="_iter"===e?["\nNOTE: as of Ohm v16, there is no default action for iteration nodes — see "," https://ohmjs.org/d/dsa for details."].join("\n"):i),"Action stack (most recent call last):",n].join("\n"))).name="missingSemanticAction",r}(this.ctorName,i,n,R);return a.apply(e[0],t)}var n,i,a,e=e["formals"];this.assertNewName(u,o),n=o,i=u,a=c;const l={_default:r};Object.keys(t).forEach(e=>{l[e]=t[e]});e="operation"===o?new ke(u,e,l,r):new De(u,l,r);function c(...e){var t=this._semantics[s][u];if(arguments.length!==t.formals.length)throw new Error("Invalid number of arguments passed to "+u+" "+o+" (expected "+t.formals.length+", got "+arguments.length+")");var r,n,i=Object.create(null);for([r,n]of Object.entries(e))i[t.formals[r]]=n;var e=this.args,a=(this.args=i,t.execute(this._semantics,this));return this.args=e,a}e.checkActionDict(this.grammar),this[s][u]=e,"operation"===o?(this.Wrapper.prototype[u]=c,this.Wrapper.prototype[u].toString=function(){return"["+u+" operation]"}):(Object.defineProperty(this.Wrapper.prototype,u,{get:c,configurable:!0}),Object.defineProperty(this.attributeKeys,u,{value:pe(u)}))}extendOperationOrAttribute(e,t,r){var n=e+"s";if(Ce(t,"attribute"),!(this.super&&t in this.super[n]))throw new Error("Cannot extend "+e+" '"+t+"': did not inherit an "+e+" with that name");if(je(this[n],t))throw new Error("Cannot extend "+e+" '"+t+"' again");var i=this[n][t].formals,a=this[n][t].actionDict;const o=Object.create(a);Object.keys(r).forEach(e=>{o[e]=r[e]}),this[n][t]="operation"===e?new ke(t,i,o):new De(t,o),this[n][t].checkActionDict(this.grammar)}assertNewName(e,t){if(je(Me.prototype,e))throw new Error("Cannot add "+t+" '"+e+"': that's a reserved name");if(e in this.operations)throw new Error("Cannot add "+t+" '"+e+"': an operation with that name already exists");if(e in this.attributes)throw new Error("Cannot add "+t+" '"+e+"': an attribute with that name already exists")}wrap(e,t,r){r=r||t;return e instanceof this.Wrapper?e:new this.Wrapper(e,t,r)}}function Ce(e,t){if(!F.prototypeGrammar)return m(-1===e.indexOf("(")),{name:e,formals:[]};e=F.prototypeGrammar.match(e,"operation"===t?"OperationSignature":"AttributeSignature");if(e.failed())throw new Error(e.message);return F.prototypeGrammarSemantics(e).parse()}F.createSemantics=function(n,e){function r(e){if(!(e instanceof me))throw new TypeError("Semantics expected a MatchResult, but got "+H(e));if(e.failed())throw new TypeError("cannot apply Semantics to "+e.toString());var t=e._cst;if(t.grammar!==n)throw new Error("Cannot use a MatchResult from grammar '"+t.grammar.name+"' with a semantics for '"+n.name+"'");var r=new he(e.input);return i.wrap(t,r.interval(e._cstOffset,e.input.length))}const i=new F(n,void 0!==e?e:F.BuiltInSemantics._getSemantics());return r.addOperation=function(e,t){return i.addOperationOrAttribute("operation",e,t),r},r.extendOperation=function(e,t){return i.extendOperationOrAttribute("operation",e,t),r},r.addAttribute=function(e,t){return i.addOperationOrAttribute("attribute",e,t),r},r.extendAttribute=function(e,t){return i.extendOperationOrAttribute("attribute",e,t),r},r._getActionDict=function(e){var t=i.operations[e]||i.attributes[e];if(t)return t.actionDict;throw new Error('"'+e+'" is not a valid operation or attribute name in this semantics for "'+n.name+'"')},r._remove=function(e){let t;return e in i.operations?(t=i.operations[e],delete i.operations[e]):e in i.attributes&&(t=i.attributes[e],delete i.attributes[e]),delete i.Wrapper.prototype[e],t},r.getOperationNames=function(){return Object.keys(i.operations)},r.getAttributeNames=function(){return Object.keys(i.attributes)},r.getGrammar=function(){return i.grammar},r.toRecipe=function(e){return i.toRecipe(e)},r.toString=i.toString.bind(i),r._getSemantics=function(){return i},r};class ke{constructor(e,t,r,n){this.name=e,this.formals=t,this.actionDict=r,this.builtInDefault=n}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,t){try{var r=t._node["ctorName"];let e=this.actionDict[r];return e?(R.push([this,r]),e.apply(t,t._children())):(t.isNonterminal()&&(e=this.actionDict._nonterminal)?(R.push([this,"_nonterminal",r]),e):(R.push([this,"default action",r]),this.actionDict._default)).apply(t,t._children())}finally{R.pop()}}}ke.prototype.typeName="operation";class De extends ke{constructor(e,t,r){super(e,[],t,r)}execute(e,t){var r=t._node,n=e.attributeKeys[this.name];return je(r,n)||(r[n]=ke.prototype.execute.call(this,e,t)),r[n]}}De.prototype.typeName="attribute";const Te=["_iter","_terminal","_nonterminal","_default"];function Be(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}let Ge,qe;class j{constructor(e,t,r,n){if(this.name=e,this.superGrammar=t,this.rules=r,n){if(!(n in r))throw new Error("Invalid start rule: '"+n+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=n}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new Fe(this)}isBuiltIn(){return this===j.ProtoBuiltInRules||this===j.BuiltInRules}equals(e){if(this===e)return!0;if(null==e||this.name!==e.name||this.defaultStartRule!==e.defaultStartRule||this.superGrammar!==e.superGrammar&&!this.superGrammar.equals(e.superGrammar))return!1;var t=Be(this);const r=Be(e);return t.length===r.length&&t.every((e,t)=>e.description===r[t].description&&e.formals.join(",")===r[t].formals.join(",")&&e.body.toString()===r[t].body.toString())}match(e,t){var r=this.matcher();return r.replaceInputRange(0,0,e),r.match(t)}trace(e,t){var r=this.matcher();return r.replaceInputRange(0,0,e),r.trace(t)}createSemantics(){return F.createSemantics(this)}extendSemantics(e){return F.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,t,r){var n,i=[];for(const s in r){var a=r[s];if(Te.includes(s)||s in this.rules)if("function"!=typeof a)i.push(`'${s}' must be a function in an action dictionary for '${this.name}'`);else{var a=a.length,o=this._topDownActionArity(s);if(a!==o){let e;e="_iter"===s||"_nonterminal"===s?`it should use a rest parameter, e.g. \`${s}(...children) {}\`. `+"NOTE: this is new in Ohm v16 — see https://ohmjs.org/d/ati for details.":`expected ${o}, got `+a,i.push(`Semantic action '${s}' has the wrong arity: `+e)}}else i.push(`'${s}' is not a valid semantic action for '${this.name}'`)}if(0"- "+e),(t=new Error([`Found errors in the action dictionary of the '${t}' ${e}:`,...n].join("\n"))).problems=i,t}_topDownActionArity(e){return Te.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let t=this.superGrammar;for(;t;){if(t.equals(e,!0))return!0;t=t.superGrammar}return!1}toRecipe(e=void 0){var t={};this.source&&(t.source=this.source.contents);let r=null;this.defaultStartRule&&(r=this.defaultStartRule);const s={};Object.keys(this.rules).forEach(e=>{var t=this.rules[e],r=t["body"],n=!this.superGrammar||!this.superGrammar.rules[e];let i;i=n?"define":r instanceof u?"extend":"override";var a={},o=(t.source&&this.source&&(o=t.source.relativeTo(this.source),a.sourceInterval=[o.startIdx,o.endIdx]),n?t.description:null),n=r.outputRecipe(t.formals,this.source);s[e]=[i,a,o,t.formals,n]});let n="null";return e?n=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(n=this.superGrammar.toRecipe()),`[${[...["grammar",t,this.name].map(JSON.stringify),n,...[r,s].map(JSON.stringify)].join(",")}]`.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){var e=new d;e.append("{");let t=!0;for(const n in this.rules){var r=this.rules[n]["body"];t?t=!1:e.append(","),e.append("\n"),e.append(" "),this.addSemanticActionTemplate(n,r,e)}return e.append("\n}"),e.contents()}addSemanticActionTemplate(e,t,r){r.append(e),r.append(": function(");e=this._topDownActionArity(e);r.append(G("_",e).join(", ")),r.append(") {\n"),r.append(" }")}parseApplication(e){let t;if(!((t=-1===e.indexOf("<")?new I(e):(e=Ge.match(e,"Base_application"),qe(e,{}))).ruleName in this.rules))throw Z(t.ruleName,this.name);var r,e=this.rules[t.ruleName]["formals"];if(e.length!==t.args.length)throw r=this.rules[t.ruleName]["source"],X(t.ruleName,e.length,t.args.length,r);return t}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}j.ProtoBuiltInRules=new j("ProtoBuiltInRules",void 0,{any:{body:r,formals:[],description:"any character",primitive:!0},end:{body:i,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new Oe(new o(0)),formals:["str"],primitive:!0},lower:{body:new w("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new w("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new w("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new y(new I("space")),formals:[]},space:{body:new a("\0"," "),formals:[],description:"a space"}}),j.initApplicationParser=function(e,t){Ge=e,qe=t};class ze{constructor(e){this.name=e}sourceInterval(e,t){return this.source.subInterval(e,t-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar("BuiltInRules"===this.name?j.ProtoBuiltInRules:j.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,t){var r=this.ensureSuperGrammar().rules[e];if(r)return r;throw r=this.superGrammar.name,A("Cannot override rule "+e+" because it is not declared in "+r,t)}installOverriddenOrExtendedRule(e,t,r,n){var i=q(t);if(0{var t=r.rules[e]["body"];try{t.assertChoicesHaveUniformArity(e)}catch(e){n.push(e)}try{t.assertAllApplicationsAreValid(e,r)}catch(e){n.push(e),i=!0}}),i||Object.keys(r.rules).forEach(e=>{e=r.rules[e].body;try{e.assertIteratedExprsAreNotNullable(r,[])}catch(e){n.push(e)}}),0{this.currentRuleName=e;var t=s[e],r=t[0],n=t[1],i=t[2],a=t[3],t=this.fromRecipe(t[4]);let o;u.source&&n&&n.sourceInterval&&(o=u.source.subInterval(n.sourceInterval[0],n.sourceInterval[1]-n.sourceInterval[0])),u[r](e,a,t,i,o)}),this.currentRuleName=this.currentDecl=null,u.build()}terminal(e){return new c(e)}range(e,t){return new a(e,t)}param(e){return new o(e)}alt(...e){let t=[];for(var r of e)(r=r instanceof n?r:this.fromRecipe(r))instanceof s?t=t.concat(r.terms):t.push(r);return 1===t.length?t[0]:new s(t)}seq(...e){let t=[];for(var r of e)(r=r instanceof n?r:this.fromRecipe(r))instanceof h?t=t.concat(r.factors):t.push(r);return 1===t.length?t[0]:new h(t)}star(e){return e instanceof n||(e=this.fromRecipe(e)),new y(e)}plus(e){return e instanceof n||(e=this.fromRecipe(e)),new g(e)}opt(e){return e instanceof n||(e=this.fromRecipe(e)),new v(e)}not(e){return e instanceof n||(e=this.fromRecipe(e)),new _(e)}lookahead(e){return e instanceof n||(e=this.fromRecipe(e)),new b(e)}lex(e){return e instanceof n||(e=this.fromRecipe(e)),new x(e)}app(e,t){return t&&0this.fromRecipe(e)),t.map(e=>this.fromRecipe(e)))}fromRecipe(e){var t="grammar"===e[0]?e.slice(1):e.slice(2),t=this[e[0]](...t),e=e[1];return e&&e.sourceInterval&&this.currentDecl&&t.withSource(this.currentDecl.sourceInterval(...e.sourceInterval)),t}}function Ke(e){return"function"==typeof e?e.call(new Ue):("string"==typeof e&&(e=JSON.parse(e)),(new Ue).fromRecipe(e))}var Ve,$e=Ke(["grammar",{source:'BuiltInRules {\n\n alnum (an alpha-numeric character)\n = letter\n | digit\n\n letter (a letter)\n = lower\n | upper\n | unicodeLtmo\n\n digit (a digit)\n = "0".."9"\n\n hexDigit (a hexadecimal digit)\n = digit\n | "a".."f"\n | "A".."F"\n\n ListOf\n = NonemptyListOf\n | EmptyListOf\n\n NonemptyListOf\n = elem (sep elem)*\n\n EmptyListOf\n = /* nothing */\n\n listOf\n = nonemptyListOf\n | emptyListOf\n\n nonemptyListOf\n = elem (sep elem)*\n\n emptyListOf\n = /* nothing */\n\n // Allows a syntactic rule application within a lexical context.\n applySyntactic = app\n}'},"BuiltInRules",null,null,{alnum:["define",{sourceInterval:[18,78]},"an alpha-numeric character",[],["alt",{sourceInterval:[60,78]},["app",{sourceInterval:[60,66]},"letter",[]],["app",{sourceInterval:[73,78]},"digit",[]]]],letter:["define",{sourceInterval:[82,142]},"a letter",[],["alt",{sourceInterval:[107,142]},["app",{sourceInterval:[107,112]},"lower",[]],["app",{sourceInterval:[119,124]},"upper",[]],["app",{sourceInterval:[131,142]},"unicodeLtmo",[]]]],digit:["define",{sourceInterval:[146,177]},"a digit",[],["range",{sourceInterval:[169,177]},"0","9"]],hexDigit:["define",{sourceInterval:[181,254]},"a hexadecimal digit",[],["alt",{sourceInterval:[219,254]},["app",{sourceInterval:[219,224]},"digit",[]],["range",{sourceInterval:[231,239]},"a","f"],["range",{sourceInterval:[246,254]},"A","F"]]],ListOf:["define",{sourceInterval:[258,336]},null,["elem","sep"],["alt",{sourceInterval:[282,336]},["app",{sourceInterval:[282,307]},"NonemptyListOf",[["param",{sourceInterval:[297,301]},0],["param",{sourceInterval:[303,306]},1]]],["app",{sourceInterval:[314,336]},"EmptyListOf",[["param",{sourceInterval:[326,330]},0],["param",{sourceInterval:[332,335]},1]]]]],NonemptyListOf:["define",{sourceInterval:[340,388]},null,["elem","sep"],["seq",{sourceInterval:[372,388]},["param",{sourceInterval:[372,376]},0],["star",{sourceInterval:[377,388]},["seq",{sourceInterval:[378,386]},["param",{sourceInterval:[378,381]},1],["param",{sourceInterval:[382,386]},0]]]]],EmptyListOf:["define",{sourceInterval:[392,434]},null,["elem","sep"],["seq",{sourceInterval:[438,438]}]],listOf:["define",{sourceInterval:[438,516]},null,["elem","sep"],["alt",{sourceInterval:[462,516]},["app",{sourceInterval:[462,487]},"nonemptyListOf",[["param",{sourceInterval:[477,481]},0],["param",{sourceInterval:[483,486]},1]]],["app",{sourceInterval:[494,516]},"emptyListOf",[["param",{sourceInterval:[506,510]},0],["param",{sourceInterval:[512,515]},1]]]]],nonemptyListOf:["define",{sourceInterval:[520,568]},null,["elem","sep"],["seq",{sourceInterval:[552,568]},["param",{sourceInterval:[552,556]},0],["star",{sourceInterval:[557,568]},["seq",{sourceInterval:[558,566]},["param",{sourceInterval:[558,561]},1],["param",{sourceInterval:[562,566]},0]]]]],emptyListOf:["define",{sourceInterval:[572,682]},null,["elem","sep"],["seq",{sourceInterval:[685,685]}]],applySyntactic:["define",{sourceInterval:[685,710]},null,["app"],["param",{sourceInterval:[707,710]},0]]}]),He=(j.BuiltInRules=$e,Ve=j.BuiltInRules,se.forEach(e=>{e(Ve)}),Ke(["grammar",{source:'Ohm {\n\n Grammars\n = Grammar*\n\n Grammar\n = ident SuperGrammar? "{" Rule* "}"\n\n SuperGrammar\n = "<:" ident\n\n Rule\n = ident Formals? ruleDescr? "=" RuleBody -- define\n | ident Formals? ":=" OverrideRuleBody -- override\n | ident Formals? "+=" RuleBody -- extend\n\n RuleBody\n = "|"? NonemptyListOf\n\n TopLevelTerm\n = Seq caseName -- inline\n | Seq\n\n OverrideRuleBody\n = "|"? NonemptyListOf\n\n OverrideTopLevelTerm\n = "..." -- superSplice\n | TopLevelTerm\n\n Formals\n = "<" ListOf ">"\n\n Params\n = "<" ListOf ">"\n\n Alt\n = NonemptyListOf\n\n Seq\n = Iter*\n\n Iter\n = Pred "*" -- star\n | Pred "+" -- plus\n | Pred "?" -- opt\n | Pred\n\n Pred\n = "~" Lex -- not\n | "&" Lex -- lookahead\n | Lex\n\n Lex\n = "#" Base -- lex\n | Base\n\n Base\n = ident Params? ~(ruleDescr? "=" | ":=" | "+=") -- application\n | oneCharTerminal ".." oneCharTerminal -- range\n | terminal -- terminal\n | "(" Alt ")" -- paren\n\n ruleDescr (a rule description)\n = "(" ruleDescrText ")"\n\n ruleDescrText\n = (~")" any)*\n\n caseName\n = "--" (~"\\n" space)* name (~"\\n" space)* ("\\n" | &"}")\n\n name (a name)\n = nameFirst nameRest*\n\n nameFirst\n = "_"\n | letter\n\n nameRest\n = "_"\n | alnum\n\n ident (an identifier)\n = name\n\n terminal\n = "\\"" terminalChar* "\\""\n\n oneCharTerminal\n = "\\"" terminalChar "\\""\n\n terminalChar\n = escapeChar\n | ~"\\\\" ~"\\"" ~"\\n" "\\u{0}".."\\u{10FFFF}"\n\n escapeChar (an escape sequence)\n = "\\\\\\\\" -- backslash\n | "\\\\\\"" -- doubleQuote\n | "\\\\\\\'" -- singleQuote\n | "\\\\b" -- backspace\n | "\\\\n" -- lineFeed\n | "\\\\r" -- carriageReturn\n | "\\\\t" -- tab\n | "\\\\u{" hexDigit hexDigit? hexDigit?\n hexDigit? hexDigit? hexDigit? "}" -- unicodeCodePoint\n | "\\\\u" hexDigit hexDigit hexDigit hexDigit -- unicodeEscape\n | "\\\\x" hexDigit hexDigit -- hexEscape\n\n space\n += comment\n\n comment\n = "//" (~"\\n" any)* &("\\n" | end) -- singleLine\n | "/*" (~"*/" any)* "*/" -- multiLine\n\n tokens = token*\n\n token = caseName | comment | ident | operator | punctuation | terminal | any\n\n operator = "<:" | "=" | ":=" | "+=" | "*" | "+" | "?" | "~" | "&"\n\n punctuation = "<" | ">" | "," | "--"\n}'},"Ohm",se=null,"Grammars",{Grammars:["define",{sourceInterval:[9,32]},null,[],["star",{sourceInterval:[24,32]},["app",{sourceInterval:[24,31]},"Grammar",[]]]],Grammar:["define",{sourceInterval:[36,83]},null,[],["seq",{sourceInterval:[50,83]},["app",{sourceInterval:[50,55]},"ident",[]],["opt",{sourceInterval:[56,69]},["app",{sourceInterval:[56,68]},"SuperGrammar",[]]],["terminal",{sourceInterval:[70,73]},"{"],["star",{sourceInterval:[74,79]},["app",{sourceInterval:[74,78]},"Rule",[]]],["terminal",{sourceInterval:[80,83]},"}"]]],SuperGrammar:["define",{sourceInterval:[87,116]},null,[],["seq",{sourceInterval:[106,116]},["terminal",{sourceInterval:[106,110]},"<:"],["app",{sourceInterval:[111,116]},"ident",[]]]],Rule_define:["define",{sourceInterval:[131,181]},null,[],["seq",{sourceInterval:[131,170]},["app",{sourceInterval:[131,136]},"ident",[]],["opt",{sourceInterval:[137,145]},["app",{sourceInterval:[137,144]},"Formals",[]]],["opt",{sourceInterval:[146,156]},["app",{sourceInterval:[146,155]},"ruleDescr",[]]],["terminal",{sourceInterval:[157,160]},"="],["app",{sourceInterval:[162,170]},"RuleBody",[]]]],Rule_override:["define",{sourceInterval:[188,248]},null,[],["seq",{sourceInterval:[188,235]},["app",{sourceInterval:[188,193]},"ident",[]],["opt",{sourceInterval:[194,202]},["app",{sourceInterval:[194,201]},"Formals",[]]],["terminal",{sourceInterval:[214,218]},":="],["app",{sourceInterval:[219,235]},"OverrideRuleBody",[]]]],Rule_extend:["define",{sourceInterval:[255,305]},null,[],["seq",{sourceInterval:[255,294]},["app",{sourceInterval:[255,260]},"ident",[]],["opt",{sourceInterval:[261,269]},["app",{sourceInterval:[261,268]},"Formals",[]]],["terminal",{sourceInterval:[281,285]},"+="],["app",{sourceInterval:[286,294]},"RuleBody",[]]]],Rule:["define",{sourceInterval:[120,305]},null,[],["alt",{sourceInterval:[131,305]},["app",{sourceInterval:[131,170]},"Rule_define",[]],["app",{sourceInterval:[188,235]},"Rule_override",[]],["app",{sourceInterval:[255,294]},"Rule_extend",[]]]],RuleBody:["define",{sourceInterval:[309,362]},null,[],["seq",{sourceInterval:[324,362]},["opt",{sourceInterval:[324,328]},["terminal",{sourceInterval:[324,327]},"|"]],["app",{sourceInterval:[329,362]},"NonemptyListOf",[["app",{sourceInterval:[344,356]},"TopLevelTerm",[]],["terminal",{sourceInterval:[358,361]},"|"]]]]],TopLevelTerm_inline:["define",{sourceInterval:[385,408]},null,[],["seq",{sourceInterval:[385,397]},["app",{sourceInterval:[385,388]},"Seq",[]],["app",{sourceInterval:[389,397]},"caseName",[]]]],TopLevelTerm:["define",{sourceInterval:[366,418]},null,[],["alt",{sourceInterval:[385,418]},["app",{sourceInterval:[385,397]},"TopLevelTerm_inline",[]],["app",{sourceInterval:[415,418]},"Seq",[]]]],OverrideRuleBody:["define",{sourceInterval:[422,491]},null,[],["seq",{sourceInterval:[445,491]},["opt",{sourceInterval:[445,449]},["terminal",{sourceInterval:[445,448]},"|"]],["app",{sourceInterval:[450,491]},"NonemptyListOf",[["app",{sourceInterval:[465,485]},"OverrideTopLevelTerm",[]],["terminal",{sourceInterval:[487,490]},"|"]]]]],OverrideTopLevelTerm_superSplice:["define",{sourceInterval:[522,543]},null,[],["terminal",{sourceInterval:[522,527]},"..."]],OverrideTopLevelTerm:["define",{sourceInterval:[495,562]},null,[],["alt",{sourceInterval:[522,562]},["app",{sourceInterval:[522,527]},"OverrideTopLevelTerm_superSplice",[]],["app",{sourceInterval:[550,562]},"TopLevelTerm",[]]]],Formals:["define",{sourceInterval:[566,606]},null,[],["seq",{sourceInterval:[580,606]},["terminal",{sourceInterval:[580,583]},"<"],["app",{sourceInterval:[584,602]},"ListOf",[["app",{sourceInterval:[591,596]},"ident",[]],["terminal",{sourceInterval:[598,601]},","]]],["terminal",{sourceInterval:[603,606]},">"]]],Params:["define",{sourceInterval:[610,647]},null,[],["seq",{sourceInterval:[623,647]},["terminal",{sourceInterval:[623,626]},"<"],["app",{sourceInterval:[627,643]},"ListOf",[["app",{sourceInterval:[634,637]},"Seq",[]],["terminal",{sourceInterval:[639,642]},","]]],["terminal",{sourceInterval:[644,647]},">"]]],Alt:["define",{sourceInterval:[651,685]},null,[],["app",{sourceInterval:[661,685]},"NonemptyListOf",[["app",{sourceInterval:[676,679]},"Seq",[]],["terminal",{sourceInterval:[681,684]},"|"]]]],Seq:["define",{sourceInterval:[689,704]},null,[],["star",{sourceInterval:[699,704]},["app",{sourceInterval:[699,703]},"Iter",[]]]],Iter_star:["define",{sourceInterval:[719,736]},null,[],["seq",{sourceInterval:[719,727]},["app",{sourceInterval:[719,723]},"Pred",[]],["terminal",{sourceInterval:[724,727]},"*"]]],Iter_plus:["define",{sourceInterval:[743,760]},null,[],["seq",{sourceInterval:[743,751]},["app",{sourceInterval:[743,747]},"Pred",[]],["terminal",{sourceInterval:[748,751]},"+"]]],Iter_opt:["define",{sourceInterval:[767,783]},null,[],["seq",{sourceInterval:[767,775]},["app",{sourceInterval:[767,771]},"Pred",[]],["terminal",{sourceInterval:[772,775]},"?"]]],Iter:["define",{sourceInterval:[708,794]},null,[],["alt",{sourceInterval:[719,794]},["app",{sourceInterval:[719,727]},"Iter_star",[]],["app",{sourceInterval:[743,751]},"Iter_plus",[]],["app",{sourceInterval:[767,775]},"Iter_opt",[]],["app",{sourceInterval:[790,794]},"Pred",[]]]],Pred_not:["define",{sourceInterval:[809,824]},null,[],["seq",{sourceInterval:[809,816]},["terminal",{sourceInterval:[809,812]},"~"],["app",{sourceInterval:[813,816]},"Lex",[]]]],Pred_lookahead:["define",{sourceInterval:[831,852]},null,[],["seq",{sourceInterval:[831,838]},["terminal",{sourceInterval:[831,834]},"&"],["app",{sourceInterval:[835,838]},"Lex",[]]]],Pred:["define",{sourceInterval:[798,862]},null,[],["alt",{sourceInterval:[809,862]},["app",{sourceInterval:[809,816]},"Pred_not",[]],["app",{sourceInterval:[831,838]},"Pred_lookahead",[]],["app",{sourceInterval:[859,862]},"Lex",[]]]],Lex_lex:["define",{sourceInterval:[876,892]},null,[],["seq",{sourceInterval:[876,884]},["terminal",{sourceInterval:[876,879]},"#"],["app",{sourceInterval:[880,884]},"Base",[]]]],Lex:["define",{sourceInterval:[866,903]},null,[],["alt",{sourceInterval:[876,903]},["app",{sourceInterval:[876,884]},"Lex_lex",[]],["app",{sourceInterval:[899,903]},"Base",[]]]],Base_application:["define",{sourceInterval:[918,979]},null,[],["seq",{sourceInterval:[918,963]},["app",{sourceInterval:[918,923]},"ident",[]],["opt",{sourceInterval:[924,931]},["app",{sourceInterval:[924,930]},"Params",[]]],["not",{sourceInterval:[932,963]},["alt",{sourceInterval:[934,962]},["seq",{sourceInterval:[934,948]},["opt",{sourceInterval:[934,944]},["app",{sourceInterval:[934,943]},"ruleDescr",[]]],["terminal",{sourceInterval:[945,948]},"="]],["terminal",{sourceInterval:[951,955]},":="],["terminal",{sourceInterval:[958,962]},"+="]]]]],Base_range:["define",{sourceInterval:[986,1041]},null,[],["seq",{sourceInterval:[986,1022]},["app",{sourceInterval:[986,1001]},"oneCharTerminal",[]],["terminal",{sourceInterval:[1002,1006]},".."],["app",{sourceInterval:[1007,1022]},"oneCharTerminal",[]]]],Base_terminal:["define",{sourceInterval:[1048,1106]},null,[],["app",{sourceInterval:[1048,1056]},"terminal",[]]],Base_paren:["define",{sourceInterval:[1113,1168]},null,[],["seq",{sourceInterval:[1113,1124]},["terminal",{sourceInterval:[1113,1116]},"("],["app",{sourceInterval:[1117,1120]},"Alt",[]],["terminal",{sourceInterval:[1121,1124]},")"]]],Base:["define",{sourceInterval:[907,1168]},null,[],["alt",{sourceInterval:[918,1168]},["app",{sourceInterval:[918,963]},"Base_application",[]],["app",{sourceInterval:[986,1022]},"Base_range",[]],["app",{sourceInterval:[1048,1056]},"Base_terminal",[]],["app",{sourceInterval:[1113,1124]},"Base_paren",[]]]],ruleDescr:["define",{sourceInterval:[1172,1231]},"a rule description",[],["seq",{sourceInterval:[1210,1231]},["terminal",{sourceInterval:[1210,1213]},"("],["app",{sourceInterval:[1214,1227]},"ruleDescrText",[]],["terminal",{sourceInterval:[1228,1231]},")"]]],ruleDescrText:["define",{sourceInterval:[1235,1266]},null,[],["star",{sourceInterval:[1255,1266]},["seq",{sourceInterval:[1256,1264]},["not",{sourceInterval:[1256,1260]},["terminal",{sourceInterval:[1257,1260]},")"]],["app",{sourceInterval:[1261,1264]},"any",[]]]]],caseName:["define",{sourceInterval:[1270,1338]},null,[],["seq",{sourceInterval:[1285,1338]},["terminal",{sourceInterval:[1285,1289]},"--"],["star",{sourceInterval:[1290,1304]},["seq",{sourceInterval:[1291,1302]},["not",{sourceInterval:[1291,1296]},["terminal",{sourceInterval:[1292,1296]},"\n"]],["app",{sourceInterval:[1297,1302]},"space",[]]]],["app",{sourceInterval:[1305,1309]},"name",[]],["star",{sourceInterval:[1310,1324]},["seq",{sourceInterval:[1311,1322]},["not",{sourceInterval:[1311,1316]},["terminal",{sourceInterval:[1312,1316]},"\n"]],["app",{sourceInterval:[1317,1322]},"space",[]]]],["alt",{sourceInterval:[1326,1337]},["terminal",{sourceInterval:[1326,1330]},"\n"],["lookahead",{sourceInterval:[1333,1337]},["terminal",{sourceInterval:[1334,1337]},"}"]]]]],name:["define",{sourceInterval:[1342,1382]},"a name",[],["seq",{sourceInterval:[1363,1382]},["app",{sourceInterval:[1363,1372]},"nameFirst",[]],["star",{sourceInterval:[1373,1382]},["app",{sourceInterval:[1373,1381]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[1386,1418]},null,[],["alt",{sourceInterval:[1402,1418]},["terminal",{sourceInterval:[1402,1405]},"_"],["app",{sourceInterval:[1412,1418]},"letter",[]]]],nameRest:["define",{sourceInterval:[1422,1452]},null,[],["alt",{sourceInterval:[1437,1452]},["terminal",{sourceInterval:[1437,1440]},"_"],["app",{sourceInterval:[1447,1452]},"alnum",[]]]],ident:["define",{sourceInterval:[1456,1489]},"an identifier",[],["app",{sourceInterval:[1485,1489]},"name",[]]],terminal:["define",{sourceInterval:[1493,1531]},null,[],["seq",{sourceInterval:[1508,1531]},["terminal",{sourceInterval:[1508,1512]},'"'],["star",{sourceInterval:[1513,1526]},["app",{sourceInterval:[1513,1525]},"terminalChar",[]]],["terminal",{sourceInterval:[1527,1531]},'"']]],oneCharTerminal:["define",{sourceInterval:[1535,1579]},null,[],["seq",{sourceInterval:[1557,1579]},["terminal",{sourceInterval:[1557,1561]},'"'],["app",{sourceInterval:[1562,1574]},"terminalChar",[]],["terminal",{sourceInterval:[1575,1579]},'"']]],terminalChar:["define",{sourceInterval:[1583,1660]},null,[],["alt",{sourceInterval:[1602,1660]},["app",{sourceInterval:[1602,1612]},"escapeChar",[]],["seq",{sourceInterval:[1621,1660]},["not",{sourceInterval:[1621,1626]},["terminal",{sourceInterval:[1622,1626]},"\\"]],["not",{sourceInterval:[1627,1632]},["terminal",{sourceInterval:[1628,1632]},'"']],["not",{sourceInterval:[1633,1638]},["terminal",{sourceInterval:[1634,1638]},"\n"]],["range",{sourceInterval:[1639,1660]},"\0","􏿿"]]]],escapeChar_backslash:["define",{sourceInterval:[1703,1758]},null,[],["terminal",{sourceInterval:[1703,1709]},"\\\\"]],escapeChar_doubleQuote:["define",{sourceInterval:[1765,1822]},null,[],["terminal",{sourceInterval:[1765,1771]},'\\"']],escapeChar_singleQuote:["define",{sourceInterval:[1829,1886]},null,[],["terminal",{sourceInterval:[1829,1835]},"\\'"]],escapeChar_backspace:["define",{sourceInterval:[1893,1948]},null,[],["terminal",{sourceInterval:[1893,1898]},"\\b"]],escapeChar_lineFeed:["define",{sourceInterval:[1955,2009]},null,[],["terminal",{sourceInterval:[1955,1960]},"\\n"]],escapeChar_carriageReturn:["define",{sourceInterval:[2016,2076]},null,[],["terminal",{sourceInterval:[2016,2021]},"\\r"]],escapeChar_tab:["define",{sourceInterval:[2083,2132]},null,[],["terminal",{sourceInterval:[2083,2088]},"\\t"]],escapeChar_unicodeCodePoint:["define",{sourceInterval:[2139,2243]},null,[],["seq",{sourceInterval:[2139,2221]},["terminal",{sourceInterval:[2139,2145]},"\\u{"],["app",{sourceInterval:[2146,2154]},"hexDigit",[]],["opt",{sourceInterval:[2155,2164]},["app",{sourceInterval:[2155,2163]},"hexDigit",[]]],["opt",{sourceInterval:[2165,2174]},["app",{sourceInterval:[2165,2173]},"hexDigit",[]]],["opt",{sourceInterval:[2188,2197]},["app",{sourceInterval:[2188,2196]},"hexDigit",[]]],["opt",{sourceInterval:[2198,2207]},["app",{sourceInterval:[2198,2206]},"hexDigit",[]]],["opt",{sourceInterval:[2208,2217]},["app",{sourceInterval:[2208,2216]},"hexDigit",[]]],["terminal",{sourceInterval:[2218,2221]},"}"]]],escapeChar_unicodeEscape:["define",{sourceInterval:[2250,2309]},null,[],["seq",{sourceInterval:[2250,2291]},["terminal",{sourceInterval:[2250,2255]},"\\u"],["app",{sourceInterval:[2256,2264]},"hexDigit",[]],["app",{sourceInterval:[2265,2273]},"hexDigit",[]],["app",{sourceInterval:[2274,2282]},"hexDigit",[]],["app",{sourceInterval:[2283,2291]},"hexDigit",[]]]],escapeChar_hexEscape:["define",{sourceInterval:[2316,2371]},null,[],["seq",{sourceInterval:[2316,2339]},["terminal",{sourceInterval:[2316,2321]},"\\x"],["app",{sourceInterval:[2322,2330]},"hexDigit",[]],["app",{sourceInterval:[2331,2339]},"hexDigit",[]]]],escapeChar:["define",{sourceInterval:[1664,2371]},"an escape sequence",[],["alt",{sourceInterval:[1703,2371]},["app",{sourceInterval:[1703,1709]},"escapeChar_backslash",[]],["app",{sourceInterval:[1765,1771]},"escapeChar_doubleQuote",[]],["app",{sourceInterval:[1829,1835]},"escapeChar_singleQuote",[]],["app",{sourceInterval:[1893,1898]},"escapeChar_backspace",[]],["app",{sourceInterval:[1955,1960]},"escapeChar_lineFeed",[]],["app",{sourceInterval:[2016,2021]},"escapeChar_carriageReturn",[]],["app",{sourceInterval:[2083,2088]},"escapeChar_tab",[]],["app",{sourceInterval:[2139,2221]},"escapeChar_unicodeCodePoint",[]],["app",{sourceInterval:[2250,2291]},"escapeChar_unicodeEscape",[]],["app",{sourceInterval:[2316,2339]},"escapeChar_hexEscape",[]]]],space:["extend",{sourceInterval:[2375,2394]},null,[],["app",{sourceInterval:[2387,2394]},"comment",[]]],comment_singleLine:["define",{sourceInterval:[2412,2458]},null,[],["seq",{sourceInterval:[2412,2443]},["terminal",{sourceInterval:[2412,2416]},"//"],["star",{sourceInterval:[2417,2429]},["seq",{sourceInterval:[2418,2427]},["not",{sourceInterval:[2418,2423]},["terminal",{sourceInterval:[2419,2423]},"\n"]],["app",{sourceInterval:[2424,2427]},"any",[]]]],["lookahead",{sourceInterval:[2430,2443]},["alt",{sourceInterval:[2432,2442]},["terminal",{sourceInterval:[2432,2436]},"\n"],["app",{sourceInterval:[2439,2442]},"end",[]]]]]],comment_multiLine:["define",{sourceInterval:[2465,2501]},null,[],["seq",{sourceInterval:[2465,2487]},["terminal",{sourceInterval:[2465,2469]},"/*"],["star",{sourceInterval:[2470,2482]},["seq",{sourceInterval:[2471,2480]},["not",{sourceInterval:[2471,2476]},["terminal",{sourceInterval:[2472,2476]},"*/"]],["app",{sourceInterval:[2477,2480]},"any",[]]]],["terminal",{sourceInterval:[2483,2487]},"*/"]]],comment:["define",{sourceInterval:[2398,2501]},null,[],["alt",{sourceInterval:[2412,2501]},["app",{sourceInterval:[2412,2443]},"comment_singleLine",[]],["app",{sourceInterval:[2465,2487]},"comment_multiLine",[]]]],tokens:["define",{sourceInterval:[2505,2520]},null,[],["star",{sourceInterval:[2514,2520]},["app",{sourceInterval:[2514,2519]},"token",[]]]],token:["define",{sourceInterval:[2524,2600]},null,[],["alt",{sourceInterval:[2532,2600]},["app",{sourceInterval:[2532,2540]},"caseName",[]],["app",{sourceInterval:[2543,2550]},"comment",[]],["app",{sourceInterval:[2553,2558]},"ident",[]],["app",{sourceInterval:[2561,2569]},"operator",[]],["app",{sourceInterval:[2572,2583]},"punctuation",[]],["app",{sourceInterval:[2586,2594]},"terminal",[]],["app",{sourceInterval:[2597,2600]},"any",[]]]],operator:["define",{sourceInterval:[2604,2669]},null,[],["alt",{sourceInterval:[2615,2669]},["terminal",{sourceInterval:[2615,2619]},"<:"],["terminal",{sourceInterval:[2622,2625]},"="],["terminal",{sourceInterval:[2628,2632]},":="],["terminal",{sourceInterval:[2635,2639]},"+="],["terminal",{sourceInterval:[2642,2645]},"*"],["terminal",{sourceInterval:[2648,2651]},"+"],["terminal",{sourceInterval:[2654,2657]},"?"],["terminal",{sourceInterval:[2660,2663]},"~"],["terminal",{sourceInterval:[2666,2669]},"&"]]],punctuation:["define",{sourceInterval:[2673,2709]},null,[],["alt",{sourceInterval:[2687,2709]},["terminal",{sourceInterval:[2687,2690]},"<"],["terminal",{sourceInterval:[2693,2696]},">"],["terminal",{sourceInterval:[2699,2702]},","],["terminal",{sourceInterval:[2705,2709]},"--"]]]}]));const We=Object.create(n.prototype);function Je(e,t){for(const r in e)if(r===t)return 1}function Qe(e,a,t){const o=new Ue;let s,u,l,i=!1;return(t||He).createSemantics().addOperation("visit",{Grammars(e){return e.children.map(e=>e.visit())},Grammar(e,t,r,n,i){e=e.visit(),s=o.newGrammar(e),t.child(0)&&t.child(0).visit(),n.children.map(e=>e.visit()),t=s.build();if(t.source=this.source.trimmed(),Je(a,e))throw A("Grammar "+t.name+" is already declared in this namespace");return a[e]=t},SuperGrammar(e,t){var r,n,i=t.visit();if("null"===i)s.withSuperGrammar(null);else{if(!a||!Je(a,i))throw r=i,n=a,t=t.source,A(n?`Grammar ${r} is not declared in namespace '${n}'`:"Undeclared grammar "+r,t);s.withSuperGrammar(a[i])}},Rule_define(e,t,r,n,i){u=e.visit(),l=t.children.map(e=>e.visit())[0]||[],s.defaultStartRule||s.ensureSuperGrammar()===j.ProtoBuiltInRules||s.withDefaultStartRule(u);e=i.visit(),t=r.children.map(e=>e.visit())[0],i=this.source.trimmed();return s.define(u,l,e,t,i)},Rule_override(e,t,r,n){u=e.visit(),l=t.children.map(e=>e.visit())[0]||[];e=this.source.trimmed(),s.ensureSuperGrammarRuleForOverriding(u,e),i=!0,t=n.visit();return i=!1,s.override(u,l,t,null,e)},Rule_extend(e,t,r,n){u=e.visit(),l=t.children.map(e=>e.visit())[0]||[];e=n.visit(),t=this.source.trimmed();return s.extend(u,l,e,null,t)},RuleBody(e,t){return o.alt(...t.visit()).withSource(this.source)},OverrideRuleBody(e,t){var r,t=t.visit(),n=t.indexOf(We);return(0<=n?(r=t.slice(0,n),(n=t.slice(n+1)).forEach(e=>{if(e===We)throw A("'...' can appear at most once in a rule body",e.source)}),new p(s.superGrammar,u,r,n)):o.alt(...t)).withSource(this.source)},Formals(e,t,r){return t.visit()},Params(e,t,r){return t.visit()},Alt(e){return o.alt(...e.visit()).withSource(this.source)},TopLevelTerm_inline(e,t){var t=u+"_"+t.visit(),e=e.visit(),r=this.source.trimmed(),n=!(s.superGrammar&&s.superGrammar.rules[t]),n=(i&&!n?s.override(t,l,e,null,r):s.define(t,l,e,null,r),l.map(e=>o.app(e)));return o.app(t,n).withSource(e.source)},OverrideTopLevelTerm_superSplice(e){return We},Seq(e){return o.seq(...e.children.map(e=>e.visit())).withSource(this.source)},Iter_star(e,t){return o.star(e.visit()).withSource(this.source)},Iter_plus(e,t){return o.plus(e.visit()).withSource(this.source)},Iter_opt(e,t){return o.opt(e.visit()).withSource(this.source)},Pred_not(e,t){return o.not(t.visit()).withSource(this.source)},Pred_lookahead(e,t){return o.lookahead(t.visit()).withSource(this.source)},Lex_lex(e,t){return o.lex(t.visit()).withSource(this.source)},Base_application(e,t){t=t.children.map(e=>e.visit())[0]||[];return o.app(e.visit(),t).withSource(this.source)},Base_range(e,t,r){return o.range(e.visit(),r.visit()).withSource(this.source)},Base_terminal(e){return o.terminal(e.visit()).withSource(this.source)},Base_paren(e,t,r){return t.visit()},ruleDescr(e,t,r){return t.visit()},ruleDescrText(e){return this.sourceString.trim()},caseName(e,t,r,n,i){return r.visit()},name(e,t){return this.sourceString},nameFirst(e){},nameRest(e){},terminal(e,t,r){return t.children.map(e=>e.visit()).join("")},oneCharTerminal(e,t,r){return t.visit()},escapeChar(t){try{return $(this.sourceString)}catch(e){if(e instanceof RangeError&&e.message.startsWith("Invalid code point "))throw m((r=(t=t)._node)&&r.isNonterminal()&&"escapeChar_unicodeCodePoint"===r.ctorName),A(`U+${(t=(r=t.children.slice(1,-1).map(e=>e.source))[0].coverageWith(...r.slice(1))).contents} is not a valid Unicode code point`,t);throw e}var r},NonemptyListOf(e,t,r){return[e.visit()].concat(r.children.map(e=>e.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(e).visit()}var Ze=Ke(["grammar",{source:'OperationsAndAttributes {\n\n AttributeSignature =\n name\n\n OperationSignature =\n name Formals?\n\n Formals\n = "(" ListOf ")"\n\n name (a name)\n = nameFirst nameRest*\n\n nameFirst\n = "_"\n | letter\n\n nameRest\n = "_"\n | alnum\n\n}'},"OperationsAndAttributes",null,"AttributeSignature",{AttributeSignature:["define",{sourceInterval:[29,58]},null,[],["app",{sourceInterval:[54,58]},"name",[]]],OperationSignature:["define",{sourceInterval:[62,100]},null,[],["seq",{sourceInterval:[87,100]},["app",{sourceInterval:[87,91]},"name",[]],["opt",{sourceInterval:[92,100]},["app",{sourceInterval:[92,99]},"Formals",[]]]]],Formals:["define",{sourceInterval:[104,143]},null,[],["seq",{sourceInterval:[118,143]},["terminal",{sourceInterval:[118,121]},"("],["app",{sourceInterval:[122,139]},"ListOf",[["app",{sourceInterval:[129,133]},"name",[]],["terminal",{sourceInterval:[135,138]},","]]],["terminal",{sourceInterval:[140,143]},")"]]],name:["define",{sourceInterval:[147,187]},"a name",[],["seq",{sourceInterval:[168,187]},["app",{sourceInterval:[168,177]},"nameFirst",[]],["star",{sourceInterval:[178,187]},["app",{sourceInterval:[178,186]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[191,223]},null,[],["alt",{sourceInterval:[207,223]},["terminal",{sourceInterval:[207,210]},"_"],["app",{sourceInterval:[217,223]},"letter",[]]]],nameRest:["define",{sourceInterval:[227,257]},null,[],["alt",{sourceInterval:[242,257]},["terminal",{sourceInterval:[242,245]},"_"],["app",{sourceInterval:[252,257]},"alnum",[]]]]}]);C=j.BuiltInRules,M={empty(){return this.iteration()},nonEmpty(e,t,r){return this.iteration([e].concat(r.children))}},F.BuiltInSemantics=F.createSemantics(C,null).addOperation("asIteration",{emptyListOf:M.empty,nonemptyListOf:M.nonEmpty,EmptyListOf:M.empty,NonemptyListOf:M.nonEmpty}),C=Ze,F.prototypeGrammarSemantics=C.createSemantics().addOperation("parse",{AttributeSignature(e){return{name:e.parse(),formals:[]}},OperationSignature(e,t){return{name:e.parse(),formals:t.children.map(e=>e.parse())[0]||[]}},Formals(e,t,r){return t.asIteration().children.map(e=>e.parse())},name(e,t){return this.sourceString}}),F.prototypeGrammar=C;const Ye="an indented block",Xe="a dedent";class et extends he{constructor(e){super(e.input),this.state=e}_indentationAt(e){return this.state.userData[e]||0}atEnd(){return super.atEnd()&&0===this._indentationAt(this.pos)}next(){if(0===this._indentationAt(this.pos))return super.next();this.examinedLength=Math.max(this.examinedLength,this.pos)}nextCharCode(){return 0!==this._indentationAt(this.pos)?(this.examinedLength=Math.max(this.examinedLength,this.pos),1114112):super.nextCharCode()}nextCodePoint(){return 0!==this._indentationAt(this.pos)?(this.examinedLength=Math.max(this.examinedLength,this.pos),1114112):super.nextCodePoint()}}class tt extends n{constructor(e=!0){super(),this.isIndent=e}allowsSkippingPrecedingSpace(){return!0}eval(e){var t=e["inputStream"],r=e.userData,t=(e.doNotMemoize=!0,t.pos),n=this.isIndent?1:-1;return 0<(r[t]||0)*n?(e.userData=Object.create(r),e.userData[t]-=n,e.pushBinding(new P(0),t),!0):(e.processFailure(t,this),!1)}getArity(){return 1}_assertAllApplicationsAreValid(e,t){}_isNullable(e,t){return!1}assertChoicesHaveUniformArity(e){}assertIteratedExprsAreNotNullable(e){}introduceParams(e){return this}substituteParams(e){return this}toString(){return this.isIndent?"indent":"dedent"}toDisplayString(){return this.toString()}toFailure(e){var t=this.isIndent?Ye:Xe;return new L(this,t,"description")}}var M=new I("indent"),Ze=new I("dedent"),C=new p($e,"any",[M,Ze],[]),M=(new Ue).newGrammar("IndentationSensitive").withSuperGrammar($e).define("indent",[],new tt(!0),Ye,void 0,!0).define("dedent",[],new tt(!1),Xe,void 0,!0).extend("any",[],C,"any character",void 0).build();Object.assign(M,{_matchStateInitializer(e){e.userData=function(e){let t=0;const r=[0];for(var n=()=>r[r.length-1],i={},a=/( *).*(?:$|\r?\n|\r)/g;null!=(o=a.exec(e));){var[o,s]=o;if(0===o.length)break;var u=s.length,s=n(),l=t+u;if(s!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e);function nt(e,t){var r,n,e=He.match(e,"Grammars");if(e.failed())throw r=e,n=new Error,Object.defineProperty(n,"message",{enumerable:!0,get(){return r.message}}),Object.defineProperty(n,"shortMessage",{enumerable:!0,get(){return"Expected "+r.getExpectedText()}}),n.interval=r.getInterval(),n;Qe(e,t)}function it(e,t){t=Object.create(t||{});if("string"!=typeof e){if(!rt(e))throw new TypeError("Expected string as first argument, got "+H(e));e=e.toString()}return nt(e,t),t}e.ExperimentalIndentationSensitive=M,e._buildGrammar=Qe,e.grammar=function(e,t){var r,e=it(e,t);if(0===(t=Object.keys(e)).length)throw new Error("Missing grammar definition");if(1(()=>{"use strict";var n={209:function(e,t,r){var n=this&&this.__generator||function(n,i){var a,o,s,u={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},l={next:e(0),throw:e(1),return:e(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function e(r){return function(e){var t=[r,e];if(a)throw new TypeError("Generator is already executing.");for(;u=l&&t[l=0]?0:u;)try{if(a=1,o&&(s=2&t[0]?o.return:t[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,t[1])).done)return s;switch(o=0,(t=s?[2&t[0],s.value]:t)[0]){case 0:case 1:s=t;break;case 4:return u.label++,{value:t[1],done:!1};case 5:u.label++,o=t[1],t=[0];continue;case 7:t=u.ops.pop(),u.trys.pop();continue;default:if(!(s=0<(s=u.trys).length&&s[s.length-1])&&(6===t[0]||2===t[0])){u=0;continue}if(3===t[0]&&(!s||t[1]>s[0]&&t[1]>"]),s.prototype.logical_or=p(u.modules.operators.op_binary.or),s.prototype.logical_and=p(u.modules.operators.op_binary.and),s.prototype.logical_xor=p(u.modules.operators.op_binary.xor),s.prototype.greater=p(u.modules.operators.op_binary[">"]),s.prototype.less=p(u.modules.operators.op_binary["<"]),s.prototype.greater_equal=p(u.modules.operators.op_binary[">="]),s.prototype.less_equal=p(u.modules.operators.op_binary["<="]),s.prototype.equal=p(u.modules.operators.op_binary["=="]),s.prototype.not_equal=p(u.modules.operators.op_binary["!="]),s.prototype.bitwise_or=h(u.modules.operators.op_unary["~"]),s.prototype.logical_or=h(u.modules.operators.op_unary.not),s.prototype.abs=h(u.modules.operators.op_unary.abs),s.prototype.isclose=u.modules.operators.isclose,s.prototype.allclose=u.modules.operators.allclose,s.prototype.assign=m(u.modules.operators.op_assign["="]),s.prototype.add_assign=m(u.modules.operators.op_assign["+="]),s.prototype.subtract_assign=m(u.modules.operators.op_assign["-="]),s.prototype.multiply_assign=m(u.modules.operators.op_assign["*="]),s.prototype.divide_assign=m(u.modules.operators.op_assign["/="]),s.prototype.mod_assign=m(u.modules.operators.op_assign["%="]),s.prototype.divide_int_assign=m(u.modules.operators.op_assign["//="]),s.prototype.pow_assign=m(u.modules.operators.op_assign["**="]),s.prototype.maximum_assign=m(u.modules.operators.op_assign["↑="]),s.prototype.minimum_assign=m(u.modules.operators.op_assign["↓="]),s.prototype.bitwise_or_assign=m(u.modules.operators.op_assign["|="]),s.prototype.bitwise_and_assign=m(u.modules.operators.op_assign["&="]),s.prototype.bitwise_shift_left_assign=m(u.modules.operators.op_assign["<<="]),s.prototype.bitwise_shift_right_assign=m(u.modules.operators.op_assign[">>="]),s.prototype.logical_or_assign=m(u.modules.operators.op_assign["or="]),s.prototype.logical_and_assign=m(u.modules.operators.op_assign["and="]),s.prototype.tolist=function(){return u.modules.jsInterface.tolist(this)},s.prototype.round=function(e){return void 0===e&&(e=0),e=Object.assign({decimals:e},this.__popKwArgs()).decimals,u.modules.elementwise.round(this,e)},s.prototype.transpose=function(e){return void 0===e&&(e=null),e=Object.assign({axes:e},this.__popKwArgs()).axes,u.modules.transform.transpose(this,e)},s.prototype.sort=function(e){return void 0===e&&(e=-1),e=Object.assign({axis:e},this.__popKwArgs()).axis,u.modules.transform.sort(this,e),null};s.prototype.op=function(){for(var e=[],t=0;t{Object.defineProperty(t,"__esModule",{value:!0}),t.ops=t.__make_elementwise=t.logical_not=t.bitwise_not=t.round=t.elementwise=void 0;var n=r(870);function i(e,t,r){return e=(0,n.asarray)(e),(0,n.new_NDArray)(e.flat.map(t),e.shape,r)}function a(e,t){return 0==(t=void 0===t?0:t)&&i(e,Math.round,Number),i(e,function(e){return parseFloat(e.toFixed(t))},Number)}function o(t,r){return void 0===r&&(r=Number),function(e){return i(e,t,r)}}t.elementwise=i,t.round=a,t.bitwise_not=function(e){return i(e,function(e){return~e},Number)},t.logical_not=function(e){return i(e,function(e){return!e},Boolean)},t.__make_elementwise=o,t.ops={sign:o(Math.sign),sqrt:o(Math.sqrt),square:o(function(e){return e*e}),abs:o(Math.abs),exp:o(Math.exp),log:o(Math.log),log2:o(Math.log2),log10:o(Math.log10),log1p:o(Math.log1p),sin:o(Math.sin),cos:o(Math.cos),tan:o(Math.tan),asin:o(Math.asin),acos:o(Math.acos),atan:o(Math.atan),atan2:o(Math.atan2),cosh:o(Math.cosh),sinh:o(Math.sinh),tanh:o(Math.tanh),acosh:o(Math.acosh),asinh:o(Math.asinh),atanh:o(Math.atanh),round:a}},350:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.modules=void 0,r(290);var n=r(870),i=r(591),a=r(545),o=r(525),s=r(194),u=r(307),l=r(737),r=r(728);t.modules={basic:n,jsInterface:a,indexes:i,elementwise:o,print:s,reduce:u,operators:l,transform:r}},591:function(e,t,r){var y=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,a=r.call(e),o=[];try{for(;(void 0===t||0=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},g=this&&this.__spreadArray||function(e,t,r){if(r||2===arguments.length)for(var n,i=0,a=t.length;i=r.length)&&(c=":"),l--,s+=i,"None"==c||null===c){n.apparentShape.push(1);continue}if("..."==c){if(-1==i)throw new Error("Index can only have a single ellipsis. Found index(".concat(t,")"));for(var p in i=-1,a)a[p]=n[p].length;s=r.length-1,o=e.length-1;continue}}else c=":";for(var c=_.prototype.parse(c,e[o]),h=c.axisIndex,m=c.span,d=(u-=m,1),f=0;f=e.length)throw new Error("Index spans over more dimensions than available in shape [".concat(e,"]: index(").concat(t,")"));d*=e[o],o+=i}n.axisIndexes.push(h),"number"!=h.spec.type&&n.apparentShape.push(h.size),n.internalShape.push(d)}if(-1==i)for(var p in n)n[p].splice(0,a[p]).concat(n[p].reverse());return new v(n.apparentShape,n.internalShape,n.axisIndexes)}},545:function(e,t,r){var f=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return{value:(e=e&&n>=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,a=r.call(e),o=[];try{for(;(void 0===t||0=e.length?void 0:e)&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},h=(Object.defineProperty(t,"__esModule",{value:!0}),t.allclose=t.isclose=t.op_assign=t.__make_assignment_operator=t._assign_operation_toJS=t.assign_operation=t.op_unary=t.op_binary=t.__make_operator_special=t.__make_operator=t._broadcast_shapes=t.binary_operation=void 0,r(591)),n=r(525),x=r(870),o=r(545);function m(e,t,r,n,i){if(void 0===i&&(i=null),(0,x.isarray)(this))return r.bind(x._NDArray.prototype).apply(void 0,b([this],_(arguments),!1));e=(0,x.asarray)(e),t=(0,x.asarray)(t);var a=_(I(e.shape,t.shape),3),o=a[0],s=a[1],u=a[2];if(null==i)i=(0,x.new_from)(o,function(e){},n);else if(!(0,x.isarray)(i))throw new Error("Out must be of type ".concat(x._NDArray,". Got ").concat(typeof i));for(var l=[],c=(0,x.shape_shifts)(s),p=(0,x.shape_shifts)(u),h=e.flat,m=t.flat,d=0;d>="|"//="|"or="|"and="|"xor="|"max="|"min="\n \n /* Declaration in precedence order (weakest first) */\n ArithmeticLogicExp = Precedence11\n\n /* https://docs.python.org/3/reference/expressions.html */\n Operator11 = "<" | "<=" | ">" | ">=" | "!=" | "=="\n Operator10 = "|"\n Operator09 = "^"\n Operator08 = "&"\n Operator07 = "<<" | ">>"\n Operator06 = "+" | "-"\n Operator05 = "*" | "@" | "/" | "//" | "%"\n Operator04 = "~" /* Unary */\n Operator03 = "+" | "-" /* Unary. Special treatment to prevent "-1.3" to be "-(array of 1.3)" */\n Operator02 = "**"\n /* Operator01 = "x[index]" | "x[index:index]" | "x(arguments...)" | "x.attribute" */\n /* Operator00 = "(expressions...)" */\n\n Precedence11 = Precedence11 Operator11 Precedence10 | "" "" Precedence10\n Precedence10 = Precedence10 Operator10 Precedence09 | "" "" Precedence09\n Precedence09 = Precedence09 Operator09 Precedence08 | "" "" Precedence08\n Precedence08 = Precedence08 Operator08 Precedence07 | "" "" Precedence07\n Precedence07 = Precedence07 Operator07 Precedence06 | "" "" Precedence06\n Precedence06 = Precedence06 Operator06 Precedence05 | "" "" Precedence05\n Precedence05 = Precedence05 Operator05 Precedence04 | "" "" Precedence04\n Precedence04 = "" Operator04 Precedence03 | "" "" Precedence03 /* Unary */\n Precedence03 = "" Operator03 Precedence02 | "" "" Precedence02 /* Special */\n Precedence02 = Precedence02 Operator02 Precedence03 | "" "" Precedence01\n Precedence01 = Arr\n \n Parenthesis = "(" ArithmeticLogicExp ")"\n Arr\n = Arr "." Name CallArgs -- method\n | Arr "." Name -- attribute\n | Arr "[" Slice "]" -- slice\n | Parenthesis\n | Name ("." Name)* CallArgs -- call\n | number\n | Variable\n\n Name (an identifier)\n = (letter|"_") (letter|"_"|digit)*\n\n number (a number)\n = ("+"|"-")? digit* "." digit+ "E" ("+"|"-")? "digit+"\n | ("+"|"-")? digit* "." digit+ "e" ("+"|"-")? "digit+"\n | ("+"|"-")? digit* "." digit+ "" "" ""\n | ("+"|"-")? digit+ "" "" "" "" ""\n \n int (an integer) = "" digit+ | "-" digit+ | "+" digit+\n\n CallArgs // Using empty strings instead of separate rules\n = "(" Args "," KwArgs ","? ")"\n | "(" Args ","? "" "" ")"\n | "(" "" ","? KwArgs ","? ")"\n | "(" "" "" "" "" ")"\n \n Args = NonemptyListOf\n KwArgs = NonemptyListOf\n KwArg = Name "=" ArgValue\n\n ArgValue = Constant | JsArray | ArithmeticLogicExp | String\n Constant = "True" | "False" | "None" | "np.nan" | "np.inf"\n JsArray\n = "[" ListOf ","? "]"\n | "(" ListOf ","? ")"\n\n String = "\'" any* "\'" | """ any* """\n \n Slice = NonemptyListOf\n SliceTerm\n = SliceRange\n | (":" | "..." | "None") -- constant\n | JsArray\n | ArithmeticLogicExp\n \n SliceRange\n = int ":" int ":" int\n | int ":" int "" ""\n | int ":" "" ":" int\n | int ":" "" "" ""\n | "" ":" int ":" int\n | "" ":" int "" ""\n | "" ":" "" ":" int\n | "" ":" "" "" ""\n}\n'],['\nArrayGrammar {\n Instruction\n = Variable "[" Slice "]" AssignSymbol ArithmeticLogicExp -- sliceAssignment\n | ArithmeticLogicExp -- expression\n \n Variable\n = "#" digit+ "#"\n \n AssignSymbol\n ="="|"+="|"-="|"*="|"/="|"%="|"&="|"|="|"^="|"@="|"**="|"<<="|">>="|"//="|"or="|"and="|"xor="|"max="|"min="\n \n /* Declaration in precedence order (weakest first) */\n ArithmeticLogicExp = Precedence11\n\n /* https://docs.python.org/3/reference/expressions.html */\n Operator11 = "<" | "<=" | ">" | ">=" | "!=" | "=="\n Operator10 = "|"\n Operator09 = "^"\n Operator08 = "&"\n Operator07 = "<<" | ">>"\n Operator06 = "+" | "-"\n Operator05 = "*" | "@" | "/" | "//" | "%"\n Operator04 = "~" /* Unary */\n Operator03 = "+" | "-" /* Unary. Special treatment to prevent "-1.3" to be "-(array of 1.3)" */\n Operator02 = "**"\n /* Operator01 = "x[index]" | "x[index:index]" | "x(arguments...)" | "x.attribute" */\n /* Operator00 = "(expressions...)" */\n\n Precedence11 = Precedence11 Operator11 Precedence10 | "" "" Precedence10\n Precedence10 = Precedence10 Operator10 Precedence09 | "" "" Precedence09\n Precedence09 = Precedence09 Operator09 Precedence08 | "" "" Precedence08\n Precedence08 = Precedence08 Operator08 Precedence07 | "" "" Precedence07\n Precedence07 = Precedence07 Operator07 Precedence06 | "" "" Precedence06\n Precedence06 = Precedence06 Operator06 Precedence05 | "" "" Precedence05\n Precedence05 = Precedence05 Operator05 Precedence04 | "" "" Precedence04\n Precedence04 = "" Operator04 Precedence03 | "" "" Precedence03 /* Unary */\n Precedence03 = "" Operator03 Precedence02 | "" "" Precedence02 /* Special */\n Precedence02 = Precedence02 Operator02 Precedence03 | "" "" Precedence01\n Precedence01 = Arr\n \n Parenthesis = "(" ArithmeticLogicExp ")"\n Arr\n = Arr "." Name CallArgs -- method\n | Arr "." Name -- attribute\n | Arr "[" Slice "]" -- slice\n | Parenthesis\n | Name ("." Name)* CallArgs -- call\n | number\n | Variable\n\n Name (an identifier)\n = (letter|"_") (letter|"_"|digit)*\n\n number (a number)\n = ("+"|"-")? digit* "." digit+ "E" ("+"|"-")? "digit+"\n | ("+"|"-")? digit* "." digit+ "e" ("+"|"-")? "digit+"\n | ("+"|"-")? digit* "." digit+ "" "" ""\n | ("+"|"-")? digit+ "" "" "" "" ""\n \n int (an integer) = "" digit+ | "-" digit+ | "+" digit+\n\n CallArgs // Using empty strings instead of separate rules\n = "(" Args "," KwArgs ","? ")"\n | "(" Args ","? "" "" ")"\n | "(" "" ","? KwArgs ","? ")"\n | "(" "" "" "" "" ")"\n \n Args = NonemptyListOf\n KwArgs = NonemptyListOf\n KwArg = Name "=" ArgValue\n\n ArgValue = Constant | JsArray | ArithmeticLogicExp | String\n Constant = "True" | "False" | "None" | "np.nan" | "np.inf"\n JsArray\n = "[" ListOf ","? "]"\n | "(" ListOf ","? ")"\n\n String = "\\\'" any* "\\\'" | "\\"" any* "\\""\n \n Slice = NonemptyListOf\n SliceTerm\n = SliceRange\n | (":" | "..." | "None") -- constant\n | JsArray\n | ArithmeticLogicExp\n \n SliceRange\n = int ":" int ":" int\n | int ":" int "" ""\n | int ":" "" ":" int\n | int ":" "" "" ""\n | "" ":" int ":" int\n | "" ":" int "" ""\n | "" ":" "" ":" int\n | "" ":" "" "" ""\n}\n'])),o.ohmGrammar=t.grammar(o.grammar),o.__makeSemantics=function(){var i=[],e={Instruction_sliceAssignment:function(e,t,r,n,i,a){var o=e.parse(),e=a.parse(),a=i.sourceString,i=r.parse(),r=l.nd_modules.basic.asarray(o);if(l.nd_modules.operators.op_assign[a](o,i,e),r!==o){for(l.nd_modules.jsInterface.tolist(r);o.length;)o.pop();o.push.apply(o,u([],s(o),!1))}return null},Instruction_expression:function(e){e=e.parse();return"number"==typeof e||"boolean"==typeof e||Array.isArray(e)||l.nd_modules.basic.isarray(e)&&(e=l.nd_modules.basic.number_collapse(e)),e},Precedence11:t,Precedence10:t,Precedence09:t,Precedence08:t,Precedence07:t,Precedence06:t,Precedence05:t,Precedence04:r,Precedence03:r,Precedence02:t,number:function(e,t,r,n,i,a,o){return parseFloat(this.sourceString)},Arr_slice:function(e,t,r,n){e=e.parse(),r=r.parse();return e.index.apply(e,u([],s(r),!1))},SliceTerm_constant:function(e){return e.sourceString},Arr_call:function(e,t,r,n){e=e.sourceString+t.sourceString,t=(e="np."==e.slice(0,3)?e.slice(3):e).split(".").reduce(function(e,t){return e[t]},l.np);if(void 0===t)throw new Error("Unrecognized function ".concat(e));e=n.parse(),n=e.args,e=e.kwArgs;return t.bind(e).apply(void 0,u([],s(n),!1))},Arr_method:function(e,t,r,n){var e=e.parse(),r=r.sourceString,n=n.parse(),i=n.args,n=n.kwArgs;if(void 0===e[r])throw new Error("Unrecognized method ".concat(r));return(e=e.withKwArgs(n))[r].apply(e,u([],s(i),!1))},Parenthesis:function(e,t,r){return t.parse()},Arr_attribute:function(e,t,r){return e.parse()[r.sourceString]},Variable:function(e,t,r){var t=parseInt(t.sourceString),t=i[t],n=Array.isArray(t)&&t.length&&l.nd_modules.basic.isarray(t[0]);return t=Array.isArray(t)&&!n?l.nd_modules.basic.array(t):t},int:function(e,t){t=parseInt(t.sourceString);return"-"==e.sourceString?-t:t},SliceRange:function(e,t,r,n,i){return this.sourceString},Constant:function(e){switch(e.sourceString){case"True":return!0;case"False":return!1;case"None":return null;case"np.nan":return Number.NaN;case"np.inf":return Number.POSITIVE_INFINITY}throw new Error("Unrecognized constant ".concat(e.sourceString))},String:function(e,t,r){return t.sourceString},CallArgs:function(e,t,r,n,i,a){t=t.parse()||[],n=n.parse()||[];return{args:t,kwArgs:Object.fromEntries(n.map(function(e){var e=s(e,2),t=e[0],e=e[1];return[t,e=l.nd_modules.basic.isarray(e)?l.nd_modules.basic.number_collapse(e):e]}))}},KwArg:function(e,t,r){return[e.sourceString,r.parse()]},NonemptyListOf:function(e,t,r){return u([e],s(r.children),!1).map(function(e){return e.parse()})},JsArray:function(e,t,r,n){var i,a=t.parse(),o=l.nd_modules.jsInterface.tolist;for(i in a)l.nd_modules.basic.isarray(a[i])&&(a[i]=o(a[i]));return a},_terminal:function(){return null}};function t(e,t,r){e=e.parse(),r=r.parse(),t=t.sourceString;return""==t&&null===e?r:l.nd_modules.operators.op_binary[t](e,r)}function r(e,t,r){var n=r.parse(),r=t.sourceString;if(""==r)return n;var i=l.nd_modules.operators.op_unary;switch(r){case"+":return i["+"](n);case"-":return i["-"](n);case"~":return i["~"](n);case"!":return i.not(n)}throw new Error("Programming Error: ".concat(r))}var a=o.ohmGrammar.createSemantics();return a.addOperation("parse",e),{parse:function(e){for(var t=[],r=1;r{Object.defineProperty(t,"__esModule",{value:!0}),t.modules=void 0,r(167);var n=r(942),i=r(70),r=r(373);t.modules={constructors:n,grammar:i,random:r}},373:function(e,t,r){var i=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,a=r.call(e),o=[];try{for(;(void 0===t||0{function t(e){const t=e||"";return function(){throw new Error("this method "+t+" is abstract! (it has no implementation in class "+this.constructor.name+")")}}function m(e,t){if(!e)throw new Error(t||"Assertion failed")}function D(e,t,r){let n;Object.defineProperty(e,t,{get(){return n=n||r.call(this)}})}function T(e,t){for(var r=[];0e,t)}function q(t){var r=[];for(let e=0;e{t.indexOf(e)<0&&t.push(e)}),t}function l(e){e=e[0];return e===e.toUpperCase()}function K(e){return!l(e)}function U(e,t,r){return e.lengthString.fromCodePoint(parseInt(e,16));function $(e){if("\\"!==e.charAt(0))return e;switch(e.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 V(e.slice(2,4));case"u":return"{"===e.charAt(2)?V(e.slice(3,-1)):V(e.slice(2,6));default:return e.charAt(1)}}function H(t){if(null==t)return String(t);var r=Object.prototype.toString.call(t);try{let e;return(e=t.constructor&&t.constructor.name?t.constructor.name:0===r.indexOf("[object ")?r.slice(8,-1):typeof t)+": "+JSON.stringify(String(t))}catch(e){return r}}var W=Object.freeze({__proto__:null,abstract:t,assert:m,defineLazyProperty:D,clone:function(e){return e&&Object.assign({},e)},repeatFn:T,repeatStr:B,repeat:G,getDuplicates:q,copyWithoutDuplicates:z,isSyntactic:l,isLexical:K,padLeft:U,StringBuffer:d,unescapeCodePoint:$,unexpectedObjToString:H});const J={Lu:/\p{Lu}/u,Ll:/\p{Ll}/u,Lt:/\p{Lt}/u,Lm:/\p{Lm}/u,Lo:/\p{Lo}/u,Nl:/\p{Nl}/u,Nd:/\p{Nd}/u,Mn:/\p{Mn}/u,Mc:/\p{Mc}/u,Pc:/\p{Pc}/u,Zs:/\p{Zs}/u,L:/\p{Letter}/u,Ltmo:/\p{Lt}|\p{Lm}|\p{Lo}/u};class n{constructor(){if(this.constructor===n)throw new Error("PExpr cannot be instantiated -- it's abstract")}withSource(e){return e&&(this.source=e.trimmed()),this}}const r=Object.create(n.prototype),i=Object.create(n.prototype);class c extends n{constructor(e){super(),this.obj=e}}class a extends n{constructor(e,t){super(),this.from=e,this.to=t,this.matchCodePoint=1new I(e.ruleName,e.args)).join("\n"),n+="\nApplication stack (most recent application last):\n"+r),A(n,e.expr.source)}function ne(e,t,r,n){return A("Rule "+e+" involves an alternation which has inconsistent arity (expected "+t+", got "+r+")",n.source)}function ie(e){if(1===e.length)throw e[0];if(1e.message),A(["Errors:"].concat(t).join("\n- "),e[0].interval);var t}function ae(e,t,r){var n=e.length;return(e.slice(0,r)+t+e.slice(r+t.length)).substr(0,n)}function oe(...t){var r=this,n=r["offset"],i=W["repeatStr"];const a=new d,o=(a.append("Line "+r.lineNum+", col "+r.colNum+":\n"),function(e){let t=0;return e.map(e=>{e=e.toString();return t=Math.max(t,e.length),e}).map(e=>U(e,t))}([null==r.prevLine?0:r.lineNum-1,r.lineNum,null==r.nextLine?0:r.lineNum+1]));var e=(e,t,r)=>{a.append(r+o[e]+" | "+t+"\n")},s=(null!=r.prevLine&&e(0,r.prevLine," "),e(1,r.line,"> "),r.line.length);let u=i(" ",s+1);for(let e=0;e= 0 and <= end"),n-r.colNum+1),l=Math.max(0,l-p),c=Math.min(c-p,s);u=ae(u,i("~",c-l),l)}var h=2+o[1].length+3;return a.append(i(" ",h)),u=ae(u,"^",r.colNum-1),a.append(u.replace(/ +$/,"")+"\n"),null!=r.nextLine&&e(2,r.nextLine," "),a.contents()}let se=[];function ue(e){se.push(e)}function le(e,t){let r=1,n=1,i=0,a=0,o=null,s=null,u=-1;for(;i{let t=0;return e=>""+e+t++})();class S{constructor(e,t,r){this.sourceString=e,this.startIdx=t,this.endIdx=r}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(...e){return S.coverage(...e,this)}collapsedLeft(){return new S(this.sourceString,this.startIdx,this.startIdx)}collapsedRight(){return new S(this.sourceString,this.endIdx,this.endIdx)}getLineAndColumn(){return le(this.sourceString,this.startIdx)}getLineAndColumnMessage(){var e=[this.startIdx,this.endIdx];return ce(this.sourceString,this.startIdx,e)}minus(e){if(this.sourceString!==e.sourceString)throw Q();return this.startIdx===e.startIdx&&this.endIdx===e.endIdx?[]:this.startIdx=e.startIdx&&this.endIdx<=e.endIdx,"other interval does not cover this one"),new S(this.sourceString,this.startIdx-e.startIdx,this.endIdx-e.startIdx)}trimmed(){var e=this["contents"],t=this.startIdx+e.match(/^\s*/)[0].length,e=this.endIdx-e.match(/\s*$/)[0].length;return new S(this.sourceString,t,e)}subInterval(e,t){e=this.startIdx+e;return new S(this.sourceString,e,e+t)}}S.coverage=function(e,...t){let{startIdx:r,endIdx:n}=e;for(const i of t){if(i.sourceString!==e.sourceString)throw Q();r=Math.min(r,i.startIdx),n=Math.max(n,i.endIdx)}return new S(e.sourceString,r,n)};class he{constructor(e){this.source=e,this.pos=0,this.examinedLength=0}atEnd(){var e=this.pos>=this.source.length;return this.examinedLength=Math.max(this.examinedLength,this.pos+1),e}next(){var e=this.source[this.pos++];return this.examinedLength=Math.max(this.examinedLength,this.pos),e}nextCharCode(){var e=this.next();return e&&e.charCodeAt(0)}nextCodePoint(){var e=this.source.slice(this.pos++).codePointAt(0);return 65535!e.isFluffy());for(let e=0;e{var t=i[e];r+t.examinedLength>n?delete i[e]:(this.maxExaminedLength=Math.max(this.maxExaminedLength,t.examinedLength),this.maxRightmostFailureOffset=Math.max(this.maxRightmostFailureOffset,t.rightmostFailureOffset))})}}}const fe="⋅",ye="␉",ge="␊",ve="␍",_e={succeeded:1,isRootNode:2,isImplicitSpaces:4,isMemoized:8,isHeadOfLeftRecursion:16,terminatesLR:32};function be(e){return"string"==typeof e?e.replace(/ /g,fe).replace(/\t/g,ye).replace(/\n/g,ge).replace(/\r/g,ve):String(e)}class N{constructor(e,t,r,n,i,a,o){this.input=e,this.pos=this.pos1=t,this.pos2=r,this.source=new S(e,t,r),this.expr=n,this.bindings=a,this.children=o||[],this.terminatingLREntry=null,this._flags=i?_e.succeeded:0}get displayString(){return this.expr.toDisplayString()}clone(){return this.cloneWithExpr(this.expr)}cloneWithExpr(e){e=new N(this.input,this.pos,this.pos2,e,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(e,t){this.terminatingLREntry=new N(this.input,this.pos,this.pos2,this.expr,!1,[t],[e]),this.terminatingLREntry.terminatesLR=!0}walk(e,i){let a=e;function o(t,e,r){let n=!0;(n=a.enter&&a.enter.call(i,t,e,r)===N.prototype.SKIP?!1:n)&&(t.children.forEach(e=>{o(e,t,r+1)}),a.exit)&&a.exit.call(i,t,e,r)}"function"==typeof a&&(a={enter:a}),this.isRootNode?this.children.forEach(e=>{o(e,null,0)}):o(this,null,0)}toString(){const o=new d;return this.walk((e,t,r)=>{if(!e)return this.SKIP;var n,i,a;"Alt"!==e.expr.constructor.name&&(o.append((n=e.input,a=e.pos,i=10,((n=be(n.slice(a,a+i))).length{const t=_e[e];Object.defineProperty(N.prototype,e,{get(){return 0!=(this._flags&t)},set(e){e?this._flags|=t:this._flags&=~t}})}),n.prototype.allowsSkippingPrecedingSpace=t("allowsSkippingPrecedingSpace"),r.allowsSkippingPrecedingSpace=i.allowsSkippingPrecedingSpace=I.prototype.allowsSkippingPrecedingSpace=c.prototype.allowsSkippingPrecedingSpace=a.prototype.allowsSkippingPrecedingSpace=w.prototype.allowsSkippingPrecedingSpace=function(){return!0},s.prototype.allowsSkippingPrecedingSpace=f.prototype.allowsSkippingPrecedingSpace=x.prototype.allowsSkippingPrecedingSpace=b.prototype.allowsSkippingPrecedingSpace=_.prototype.allowsSkippingPrecedingSpace=o.prototype.allowsSkippingPrecedingSpace=h.prototype.allowsSkippingPrecedingSpace=function(){return!1};let O;ue(e=>{O=e});let xe;n.prototype.assertAllApplicationsAreValid=function(e,t){xe=0,this._assertAllApplicationsAreValid(e,t)},n.prototype._assertAllApplicationsAreValid=t("_assertAllApplicationsAreValid"),r._assertAllApplicationsAreValid=i._assertAllApplicationsAreValid=c.prototype._assertAllApplicationsAreValid=a.prototype._assertAllApplicationsAreValid=o.prototype._assertAllApplicationsAreValid=w.prototype._assertAllApplicationsAreValid=function(e,t){},x.prototype._assertAllApplicationsAreValid=function(e,t){xe++,this.expr._assertAllApplicationsAreValid(e,t),xe--},s.prototype._assertAllApplicationsAreValid=function(t,r){for(let e=0;e{if(e._assertAllApplicationsAreValid(t,r,s),1!==e.getArity())throw A("Invalid parameter to rule "+this.ruleName+": "+(e=e)+" has arity "+e.getArity()+", but parameter expressions must have arity 1",e.source)})},n.prototype.assertChoicesHaveUniformArity=t("assertChoicesHaveUniformArity"),r.assertChoicesHaveUniformArity=i.assertChoicesHaveUniformArity=c.prototype.assertChoicesHaveUniformArity=a.prototype.assertChoicesHaveUniformArity=o.prototype.assertChoicesHaveUniformArity=x.prototype.assertChoicesHaveUniformArity=w.prototype.assertChoicesHaveUniformArity=function(e){},s.prototype.assertChoicesHaveUniformArity=function(t){if(0!==this.terms.length){var r=this.terms[0].getArity();for(let e=0;e{e.assertIteratedExprsAreNotNullable(t)})};class Ie{constructor(e){this.matchLength=e}get ctorName(){throw new Error("subclass responsibility")}numChildren(){return this.children?this.children.length:0}childAt(e){if(this.children)return this.children[e]}indexOfChild(e){return this.children.indexOf(e)}hasChildren(){return 0{t[e]=(t[e]||0)+1}),Object.keys(t).forEach(n=>{if(!(t[n]<=1)){let r=1;i.forEach((e,t)=>{e===n&&(i[t]=e+"_"+r++)})}})}n.prototype.eval=t("eval"),r.eval=function(e){var t=e["inputStream"],r=t.pos,t=t.nextCodePoint();return void 0!==t?(e.pushBinding(new P(String.fromCodePoint(t).length),r),!0):(e.processFailure(r,this),!1)},i.eval=function(e){var t=e["inputStream"],r=t.pos;return t.atEnd()?(e.pushBinding(new P(0),r),!0):(e.processFailure(r,this),!1)},c.prototype.eval=function(e){var t=e["inputStream"],r=t.pos;return t.matchString(this.obj)?(e.pushBinding(new P(this.obj.length),r),!0):(e.processFailure(r,this),!1)},a.prototype.eval=function(e){var t=e["inputStream"],r=t.pos,t=this.matchCodePoint?t.nextCodePoint():t.nextCharCode();return void 0!==t&&this.from.codePointAt(0)<=t&&t<=this.to.codePointAt(0)?(e.pushBinding(new P(String.fromCodePoint(t).length),r),!0):(e.processFailure(r,this),!1)},o.prototype.eval=function(e){return e.eval(e.currentApplication().args[this.index])},x.prototype.eval=function(e){e.enterLexifiedContext();var t=e.eval(this.expr);return e.exitLexifiedContext(),t},s.prototype.eval=function(t){for(let e=0;ee.outputRecipe(t,r)))},u.prototype.outputRecipe=function(e,t){return this.terms[0].outputRecipe(e,t)},p.prototype.outputRecipe=function(t,r){var e=this.terms.slice(0,this.expansionPos),n=this.terms.slice(this.expansionPos+1);return["splice",E(this,r),e.map(e=>e.outputRecipe(t,r)),n.map(e=>e.outputRecipe(t,r))]},h.prototype.outputRecipe=function(t,r){return["seq",E(this,r)].concat(this.factors.map(e=>e.outputRecipe(t,r)))},y.prototype.outputRecipe=g.prototype.outputRecipe=v.prototype.outputRecipe=_.prototype.outputRecipe=b.prototype.outputRecipe=x.prototype.outputRecipe=function(e,t){return[this.constructor.name.toLowerCase(),E(this,t),this.expr.outputRecipe(e,t)]},I.prototype.outputRecipe=function(t,r){return["app",E(this,r),this.ruleName,this.args.map(e=>e.outputRecipe(t,r))]},w.prototype.outputRecipe=function(e,t){return["unicodeChar",E(this,t),this.category]},n.prototype.introduceParams=t("introduceParams"),r.introduceParams=i.introduceParams=c.prototype.introduceParams=a.prototype.introduceParams=o.prototype.introduceParams=w.prototype.introduceParams=function(e){return this},s.prototype.introduceParams=function(n){return this.terms.forEach((e,t,r)=>{r[t]=e.introduceParams(n)}),this},h.prototype.introduceParams=function(n){return this.factors.forEach((e,t,r)=>{r[t]=e.introduceParams(n)}),this},f.prototype.introduceParams=_.prototype.introduceParams=b.prototype.introduceParams=x.prototype.introduceParams=function(e){return this.expr=this.expr.introduceParams(e),this},I.prototype.introduceParams=function(n){var e=n.indexOf(this.ruleName);if(0<=e){if(0{r[t]=e.introduceParams(n)}),this},n.prototype.isNullable=function(e){return this._isNullable(e,Object.create(null))},n.prototype._isNullable=t("_isNullable"),r._isNullable=a.prototype._isNullable=o.prototype._isNullable=g.prototype._isNullable=w.prototype._isNullable=function(e,t){return!1},i._isNullable=function(e,t){return!0},c.prototype._isNullable=function(e,t){return"string"==typeof this.obj&&""===this.obj},s.prototype._isNullable=function(t,r){return 0===this.terms.length||this.terms.some(e=>e._isNullable(t,r))},h.prototype._isNullable=function(t,r){return this.factors.every(e=>e._isNullable(t,r))},y.prototype._isNullable=v.prototype._isNullable=_.prototype._isNullable=b.prototype._isNullable=function(e,t){return!0},x.prototype._isNullable=function(e,t){return this.expr._isNullable(e,t)},I.prototype._isNullable=function(e,t){var r,n=this.toMemoKey();return Object.prototype.hasOwnProperty.call(t,n)||(r=e.rules[this.ruleName]["body"],r=r.substituteParams(this.args),t[n]=!1,t[n]=r._isNullable(e,t)),t[n]},n.prototype.substituteParams=t("substituteParams"),r.substituteParams=i.substituteParams=c.prototype.substituteParams=a.prototype.substituteParams=w.prototype.substituteParams=function(e){return this},o.prototype.substituteParams=function(e){return e[this.index]},s.prototype.substituteParams=function(t){return new s(this.terms.map(e=>e.substituteParams(t)))},h.prototype.substituteParams=function(t){return new h(this.factors.map(e=>e.substituteParams(t)))},f.prototype.substituteParams=_.prototype.substituteParams=b.prototype.substituteParams=x.prototype.substituteParams=function(e){return new this.constructor(this.expr.substituteParams(e))},I.prototype.substituteParams=function(t){var e;return 0===this.args.length?this:(e=this.args.map(e=>e.substituteParams(t)),new I(this.ruleName,e))},n.prototype.toArgumentNameList=t("toArgumentNameList"),r.toArgumentNameList=function(e,t){return["any"]},i.toArgumentNameList=function(e,t){return["end"]},c.prototype.toArgumentNameList=function(e,t){return"string"==typeof this.obj&&/^[_a-zA-Z0-9]+$/.test(this.obj)?["_"+this.obj]:["$"+e]},a.prototype.toArgumentNameList=function(e,t){let r=this.from+"_to_"+this.to;return Se(r)||(r="_"+r),[r=Se(r)?r:"$"+e]},s.prototype.toArgumentNameList=function(t,e){var r=this.terms.map(e=>e.toArgumentNameList(t,!0)),n=[],i=r[0].length;for(let t=0;t{e=e.toArgumentNameList(t,!0);r=r.concat(e),t+=e.length}),e||Ne(r),r},f.prototype.toArgumentNameList=function(e,t){e=this.expr.toArgumentNameList(e,t).map(e=>"s"===e[e.length-1]?e+"es":e+"s");return t||Ne(e),e},v.prototype.toArgumentNameList=function(e,t){return this.expr.toArgumentNameList(e,t).map(e=>"opt"+e[0].toUpperCase()+e.slice(1))},_.prototype.toArgumentNameList=function(e,t){return[]},b.prototype.toArgumentNameList=x.prototype.toArgumentNameList=function(e,t){return this.expr.toArgumentNameList(e,t)},I.prototype.toArgumentNameList=function(e,t){return[this.ruleName]},w.prototype.toArgumentNameList=function(e,t){return["$"+e]},o.prototype.toArgumentNameList=function(e,t){return["param"+this.index]},n.prototype.toDisplayString=t("toDisplayString"),s.prototype.toDisplayString=h.prototype.toDisplayString=function(){return this.source?this.source.trimmed().contents:"["+this.constructor.name+"]"},r.toDisplayString=i.toDisplayString=f.prototype.toDisplayString=_.prototype.toDisplayString=b.prototype.toDisplayString=x.prototype.toDisplayString=c.prototype.toDisplayString=a.prototype.toDisplayString=o.prototype.toDisplayString=function(){return this.toString()},I.prototype.toDisplayString=function(){var e;return 0e.toDisplayString()),this.ruleName+"<"+e.join(",")+">"):this.ruleName},w.prototype.toDisplayString=function(){return"Unicode ["+this.category+"] character"};class L{constructor(e,t,r){if("description"!==(n=r)&&"string"!==n&&"code"!==n)throw new Error("invalid Failure type: "+r);var n;this.pexpr=e,this.text=t,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(e){return this.getText()===e.getText()&&this.type===e.type&&(!this.isFluffy()||this.isFluffy()&&e.isFluffy())}toString(){return"string"===this.type?JSON.stringify(this.getText()):this.getText()}clone(){var e=new L(this.pexpr,this.text,this.type);return this.isFluffy()&&e.makeFluffy(),e}toKey(){return this.toString()+"#"+this.type}}n.prototype.toFailure=t("toFailure"),r.toFailure=function(e){return new L(this,"any object","description")},i.toFailure=function(e){return new L(this,"end of input","description")},c.prototype.toFailure=function(e){return new L(this,this.obj,"string")},a.prototype.toFailure=function(e){return new L(this,JSON.stringify(this.from)+".."+JSON.stringify(this.to),"code")},_.prototype.toFailure=function(e){e=this.expr===r?"nothing":"not "+this.expr.toFailure(e);return new L(this,e,"description")},b.prototype.toFailure=function(e){return this.expr.toFailure(e)},I.prototype.toFailure=function(e){let t=e.rules[this.ruleName]["description"];return t||(e=/^[aeiouAEIOU]/.test(this.ruleName)?"an":"a",t=e+" "+this.ruleName),new L(this,t,"description")},w.prototype.toFailure=function(e){return new L(this,"a Unicode ["+this.category+"] character","description")},s.prototype.toFailure=function(t){var e="("+this.terms.map(e=>e.toFailure(t)).join(" or ")+")";return new L(this,e,"description")},h.prototype.toFailure=function(t){var e="("+this.factors.map(e=>e.toFailure(t)).join(" ")+")";return new L(this,e,"description")},f.prototype.toFailure=function(e){e="("+this.expr.toFailure(e)+this.operator+")";return new L(this,e,"description")},n.prototype.toString=t("toString"),r.toString=function(){return"any"},i.toString=function(){return"end"},c.prototype.toString=function(){return JSON.stringify(this.obj)},a.prototype.toString=function(){return JSON.stringify(this.from)+".."+JSON.stringify(this.to)},o.prototype.toString=function(){return"$"+this.index},x.prototype.toString=function(){return"#("+this.expr.toString()+")"},s.prototype.toString=function(){return 1===this.terms.length?this.terms[0].toString():"("+this.terms.map(e=>e.toString()).join(" | ")+")"},h.prototype.toString=function(){return 1===this.factors.length?this.factors[0].toString():"("+this.factors.map(e=>e.toString()).join(" ")+")"},f.prototype.toString=function(){return this.expr+this.operator},_.prototype.toString=function(){return"~"+this.expr},b.prototype.toString=function(){return"&"+this.expr},I.prototype.toString=function(){var e;return 0e.toString()),this.ruleName+"<"+e.join(",")+">"):this.ruleName},w.prototype.toString=function(){return"\\p{"+this.category+"}"};class Oe extends n{constructor(e){super(),this.obj=e}_getString(e){e=e.currentApplication().args[this.obj.index];return m(e instanceof c,"expected a Terminal expression"),e.obj}allowsSkippingPrecedingSpace(){return!0}eval(e){var t=e["inputStream"],r=t.pos,n=this._getString(e);return t.matchString(n,!0)?(e.pushBinding(new P(n.length),r),!0):(e.processFailure(r,this),!1)}getArity(){return 1}substituteParams(e){return new Oe(this.obj.substituteParams(e))}toDisplayString(){return this.obj.toDisplayString()+" (case-insensitive)"}toFailure(e){return new L(this,this.obj.toFailure(e)+" (case-insensitive)","description")}_isNullable(e,t){return this.obj._isNullable(e,t)}}var Pe=Object.freeze({__proto__:null,CaseInsensitiveTerminal:Oe,PExpr:n,any:r,end:i,Terminal:c,Range:a,Param:o,Alt:s,Extend:u,Splice:p,Seq:h,Iter:f,Star:y,Plus:g,Opt:v,Not:_,Lookahead:b,Lex:x,Apply:I,UnicodeChar:w});let Ee;ue(e=>{Ee=e.rules.applySyntactic.body});const Le=new I("spaces");class Re{constructor(e,t,r){this.matcher=e,this.startExpr=t,this.grammar=e.grammar,this.input=e.getInput(),this.inputStream=new he(this.input),this.memoTable=e._memoTable,this.userData=void 0,this.doNotMemoize=!1,this._bindings=[],this._bindingOffsets=[],this._applicationStack=[],this._posStack=[0],this.inLexifiedContextStack=[!1],this.rightmostFailurePosition=-1,this._rightmostFailurePositionStack=[],this._recordedFailuresStack=[],void 0!==r&&(this.positionToRecordFailures=r,this.recordedFailures=Object.create(null))}posToOffset(e){return e-this._posStack[this._posStack.length-1]}enterApplication(e,t){this._posStack.push(this.inputStream.pos),this._applicationStack.push(t),this.inLexifiedContextStack.push(!1),e.enter(t),this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this.rightmostFailurePosition=-1}exitApplication(e,t){var r=this._posStack.pop();this._applicationStack.pop(),this.inLexifiedContextStack.pop(),e.exit(),this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,this._rightmostFailurePositionStack.pop()),t&&this.pushBinding(t,r)}enterLexifiedContext(){this.inLexifiedContextStack.push(!0)}exitLexifiedContext(){this.inLexifiedContextStack.pop()}currentApplication(){return this._applicationStack[this._applicationStack.length-1]}inSyntacticContext(){var e=this.currentApplication();return e?e.isSyntactic()&&!this.inLexifiedContext():this.startExpr.factors[0].isSyntactic()}inLexifiedContext(){return this.inLexifiedContextStack[this.inLexifiedContextStack.length-1]}skipSpaces(){return this.pushFailuresInfo(),this.eval(Le),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==Le?this.skipSpacesIfInSyntacticContext():this.inputStream.pos}pushBinding(e,t){this._bindings.push(e),this._bindingOffsets.push(this.posToOffset(t))}popBinding(){this._bindings.pop(),this._bindingOffsets.pop()}numBindings(){return this._bindings.length}truncateBindings(e){for(;this._bindings.length>e;)this.popBinding()}getCurrentPosInfo(){return this.getPosInfo(this.inputStream.pos)}getPosInfo(e){let t=this.memoTable[e];return t=t||(this.memoTable[e]=new de)}processFailure(e,t){this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,e),this.recordedFailures&&e===this.positionToRecordFailures&&((e=this.currentApplication())&&(t=t.substituteParams(e.args)),this.recordFailure(t.toFailure(this.grammar),!1))}recordFailure(e,t){var r=e.toKey();this.recordedFailures[r]?this.recordedFailures[r].isFluffy()&&!e.isFluffy()&&this.recordedFailures[r].clearFluffy():this.recordedFailures[r]=t?e.clone():e}recordFailures(t,r){Object.keys(t).forEach(e=>{this.recordFailure(t[e],r)})}cloneRecordedFailures(){if(this.recordedFailures){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 0<=this.rightmostFailurePosition?this.posToOffset(this.rightmostFailurePosition):-1}getMemoizedTraceEntry(e,t){e=this.memoTable[e];if(e&&t instanceof I){var e=e.memo[t.toMemoKey()];if(e&&e.traceEntry)return(e=e.traceEntry.cloneWithExpr(t)).isMemoized=!0,e}return null}getTraceEntry(e,t,r,n){var i;return t instanceof I&&(i=(i=this.currentApplication())?i.args:[],t=t.substituteParams(i)),this.getMemoizedTraceEntry(e,t)||new N(this.input,e,this.inputStream.pos,t,r,n,this.trace)}isTracing(){return!!this.trace}hasNecessaryInfo(e){return!(this.trace&&!e.traceEntry||this.recordedFailures&&this.inputStream.pos+e.rightmostFailureOffset===this.positionToRecordFailures&&!e.failuresAtRightmostPosition)}useMemoizedResult(e,t){this.trace&&this.trace.push(t.traceEntry);var r=this.inputStream.pos+t.rightmostFailureOffset;return this.rightmostFailurePosition=Math.max(this.rightmostFailurePosition,r),this.recordedFailures&&this.positionToRecordFailures===r&&t.failuresAtRightmostPosition&&this.recordFailures(t.failuresAtRightmostPosition,!0),this.inputStream.examinedLength=Math.max(this.inputStream.examinedLength,t.examinedLength+e),!!t.value&&(this.inputStream.pos+=t.matchLength,this.pushBinding(t.value,e),!0)}eval(e){var t=this["inputStream"],r=this._bindings.length,n=this.userData;let i;this.recordedFailures&&(i=this.recordedFailures,this.recordedFailures=Object.create(null));var a=t.pos,o=this.maybeSkipSpacesBefore(e);let s;this.trace&&(s=this.trace,this.trace=[]);var u,l=e.eval(this);return this.trace&&(u=this._bindings.slice(r),(o=this.getTraceEntry(o,e,l,u)).isImplicitSpaces=e===Le,o.isRootNode=e===this.startExpr,s.push(o),this.trace=s),l?this.recordedFailures&&t.pos===this.positionToRecordFailures&&Object.keys(this.recordedFailures).forEach(e=>{this.recordedFailures[e].makeFluffy()}):(t.pos=a,this.truncateBindings(r),this.userData=n),this.recordedFailures&&this.recordFailures(i,!1),e===Ee&&this.skipSpaces(),l}getMatchResult(){this.grammar._setUpMatchState(this),this.eval(this.startExpr);let e;this.recordedFailures&&(e=Object.keys(this.recordedFailures).map(e=>this.recordedFailures[e]));var t=this._bindings[0];return t&&(t.grammar=this.grammar),new me(this.matcher,this.input,this.startExpr,t,this._bindingOffsets[0],this.rightmostFailurePosition,e)}getTrace(){this.trace=[];var e=this.getMatchResult(),t=this.trace[this.trace.length-1];return t.result=e,t}pushFailuresInfo(){this._rightmostFailurePositionStack.push(this.rightmostFailurePosition),this._recordedFailuresStack.push(this.recordedFailures)}popFailuresInfo(){this.rightmostFailurePosition=this._rightmostFailurePositionStack.pop(),this.recordedFailures=this._recordedFailuresStack.pop()}}class Fe{constructor(e){this.grammar=e,this._memoTable=[],this._input="",this._isMemoTableStale=!1}_resetMemoTable(){this._memoTable=[],this._isMemoTableStale=!1}getInput(){return this._input}setInput(e){return this._input!==e&&this.replaceInputRange(0,this._input.length,e),this}replaceInputRange(t,e,r){var n=this._input,i=this._memoTable;if(t<0||t>n.length||e<0||e>n.length||eObject.prototype.hasOwnProperty.call(e,t);class ke{constructor(e,t,r){this._node=e,this.source=t,this._baseInterval=r,e.isNonterminal()&&m(t===r),this._childWrappers=[]}_forgetMemoizedResultFor(t){delete this._node[this._semantics.attributeKeys[t]],this.children.forEach(e=>{e._forgetMemoizedResultFor(t)})}child(t){if(0<=t&&te._node),t=new Ae(t,[],-1,!1),t=this._semantics.wrap(t,null,null);return t._childWrappers=e,t}get children(){return this._children()}get ctorName(){return this._node.ctorName}get numChildren(){return this._node.numChildren()}get sourceString(){return this.source.contents}}class F{constructor(e,t){const n=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(t?t.Wrapper:ke){constructor(e,t,r){super(e,t,r),n.checkActionDictsIfHaventAlready(),this._semantics=n}toString(){return"[semantics wrapper for "+n.grammar.name+"]"}},this.super=t){if(!e.equals(this.super.grammar)&&!e._inheritsFrom(this.super.grammar))throw new Error("Cannot extend a semantics for grammar '"+this.super.grammar.name+"' for use with grammar '"+e.name+"' (not a sub-grammar)");this.operations=Object.create(this.super.operations),this.attributes=Object.create(this.super.attributes),this.attributeKeys=Object.create(null);for(const r in this.attributes)Object.defineProperty(this.attributeKeys,r,{value:pe(r)})}else this.operations=Object.create(null),this.attributes=Object.create(null),this.attributeKeys=Object.create(null)}toString(){return"[semantics for "+this.grammar.name+"]"}checkActionDictsIfHaventAlready(){this.checkedActionDicts||(this.checkActionDicts(),this.checkedActionDicts=!0)}checkActionDicts(){let e;for(e in this.operations)this.operations[e].checkActionDict(this.grammar);for(e in this.attributes)this.attributes[e].checkActionDict(this.grammar)}toRecipe(e){function l(e){return e.super!==F.BuiltInSemantics._getSemantics()}let c="(function(g) {\n";if(l(this)){c+=" var semantics = "+this.super.toRecipe(!0)+"(g";var t=this.super.grammar;let e=this.grammar;for(;e!==t;)c+=".superGrammar",e=e.superGrammar;c=c+");\n"+" return g.extendSemantics(semantics)"}else c+=" return g.createSemantics()";return["Operation","Attribute"].forEach(s=>{const u=this[s.toLowerCase()+"s"];Object.keys(u).forEach(e=>{const{actionDict:r,formals:t,builtInDefault:n}=u[e];let i=e;0{if(r[t]!==n){let e=r[t].toString().trim();e=e.replace(/^.*\(/,"function("),o.push("\n "+JSON.stringify(t)+": "+e)}}),c+=o.join(",")+"\n })"})}),c+=";\n })",c=e?c:"(function() {\n var grammar = this.fromRecipe("+this.grammar.toRecipe()+");\n var semantics = "+c+"(grammar);\n return semantics;\n});\n"}addOperationOrAttribute(o,e,t){const s=o+"s";e=Me(e,o);const u=e["name"];function r(...e){var t=(this._semantics.operations[i]||this._semantics.attributes[i]).formals.map(e=>this.args[e]);if(this.isIteration()||1!==e.length)throw function(e,t,r,n){n=n.slice(0,-1).map(e=>{var t=" "+e[0].name+" > "+e[1];return 3===e.length?t+" for '"+e[2]+"'":t}).join("\n"),n+="\n "+t+" > "+e;let i="";return(r=A([`Missing semantic action for '${e}' in ${r} '${t}'.`+(i="_iter"===e?["\nNOTE: as of Ohm v16, there is no default action for iteration nodes — see "," https://ohmjs.org/d/dsa for details."].join("\n"):i),"Action stack (most recent call last):",n].join("\n"))).name="missingSemanticAction",r}(this.ctorName,i,n,R);return a.apply(e[0],t)}var n,i,a,e=e["formals"];this.assertNewName(u,o),n=o,i=u,a=c;const l={_default:r};Object.keys(t).forEach(e=>{l[e]=t[e]});e="operation"===o?new Ce(u,e,l,r):new De(u,l,r);function c(...e){var t=this._semantics[s][u];if(arguments.length!==t.formals.length)throw new Error("Invalid number of arguments passed to "+u+" "+o+" (expected "+t.formals.length+", got "+arguments.length+")");var r,n,i=Object.create(null);for([r,n]of Object.entries(e))i[t.formals[r]]=n;var e=this.args,a=(this.args=i,t.execute(this._semantics,this));return this.args=e,a}e.checkActionDict(this.grammar),this[s][u]=e,"operation"===o?(this.Wrapper.prototype[u]=c,this.Wrapper.prototype[u].toString=function(){return"["+u+" operation]"}):(Object.defineProperty(this.Wrapper.prototype,u,{get:c,configurable:!0}),Object.defineProperty(this.attributeKeys,u,{value:pe(u)}))}extendOperationOrAttribute(e,t,r){var n=e+"s";if(Me(t,"attribute"),!(this.super&&t in this.super[n]))throw new Error("Cannot extend "+e+" '"+t+"': did not inherit an "+e+" with that name");if(je(this[n],t))throw new Error("Cannot extend "+e+" '"+t+"' again");var i=this[n][t].formals,a=this[n][t].actionDict;const o=Object.create(a);Object.keys(r).forEach(e=>{o[e]=r[e]}),this[n][t]="operation"===e?new Ce(t,i,o):new De(t,o),this[n][t].checkActionDict(this.grammar)}assertNewName(e,t){if(je(ke.prototype,e))throw new Error("Cannot add "+t+" '"+e+"': that's a reserved name");if(e in this.operations)throw new Error("Cannot add "+t+" '"+e+"': an operation with that name already exists");if(e in this.attributes)throw new Error("Cannot add "+t+" '"+e+"': an attribute with that name already exists")}wrap(e,t,r){r=r||t;return e instanceof this.Wrapper?e:new this.Wrapper(e,t,r)}}function Me(e,t){if(!F.prototypeGrammar)return m(-1===e.indexOf("(")),{name:e,formals:[]};e=F.prototypeGrammar.match(e,"operation"===t?"OperationSignature":"AttributeSignature");if(e.failed())throw new Error(e.message);return F.prototypeGrammarSemantics(e).parse()}F.createSemantics=function(n,e){function r(e){if(!(e instanceof me))throw new TypeError("Semantics expected a MatchResult, but got "+H(e));if(e.failed())throw new TypeError("cannot apply Semantics to "+e.toString());var t=e._cst;if(t.grammar!==n)throw new Error("Cannot use a MatchResult from grammar '"+t.grammar.name+"' with a semantics for '"+n.name+"'");var r=new he(e.input);return i.wrap(t,r.interval(e._cstOffset,e.input.length))}const i=new F(n,void 0!==e?e:F.BuiltInSemantics._getSemantics());return r.addOperation=function(e,t){return i.addOperationOrAttribute("operation",e,t),r},r.extendOperation=function(e,t){return i.extendOperationOrAttribute("operation",e,t),r},r.addAttribute=function(e,t){return i.addOperationOrAttribute("attribute",e,t),r},r.extendAttribute=function(e,t){return i.extendOperationOrAttribute("attribute",e,t),r},r._getActionDict=function(e){var t=i.operations[e]||i.attributes[e];if(t)return t.actionDict;throw new Error('"'+e+'" is not a valid operation or attribute name in this semantics for "'+n.name+'"')},r._remove=function(e){let t;return e in i.operations?(t=i.operations[e],delete i.operations[e]):e in i.attributes&&(t=i.attributes[e],delete i.attributes[e]),delete i.Wrapper.prototype[e],t},r.getOperationNames=function(){return Object.keys(i.operations)},r.getAttributeNames=function(){return Object.keys(i.attributes)},r.getGrammar=function(){return i.grammar},r.toRecipe=function(e){return i.toRecipe(e)},r.toString=i.toString.bind(i),r._getSemantics=function(){return i},r};class Ce{constructor(e,t,r,n){this.name=e,this.formals=t,this.actionDict=r,this.builtInDefault=n}checkActionDict(e){e._checkTopDownActionDict(this.typeName,this.name,this.actionDict)}execute(e,t){try{var r=t._node["ctorName"];let e=this.actionDict[r];return e?(R.push([this,r]),e.apply(t,t._children())):(t.isNonterminal()&&(e=this.actionDict._nonterminal)?(R.push([this,"_nonterminal",r]),e):(R.push([this,"default action",r]),this.actionDict._default)).apply(t,t._children())}finally{R.pop()}}}Ce.prototype.typeName="operation";class De extends Ce{constructor(e,t,r){super(e,[],t,r)}execute(e,t){var r=t._node,n=e.attributeKeys[this.name];return je(r,n)||(r[n]=Ce.prototype.execute.call(this,e,t)),r[n]}}De.prototype.typeName="attribute";const Te=["_iter","_terminal","_nonterminal","_default"];function Be(t){return Object.keys(t.rules).sort().map(e=>t.rules[e])}let Ge,qe;class j{constructor(e,t,r,n){if(this.name=e,this.superGrammar=t,this.rules=r,n){if(!(n in r))throw new Error("Invalid start rule: '"+n+"' is not a rule in grammar '"+e+"'");this.defaultStartRule=n}this._matchStateInitializer=void 0,this.supportsIncrementalParsing=!0}matcher(){return new Fe(this)}isBuiltIn(){return this===j.ProtoBuiltInRules||this===j.BuiltInRules}equals(e){if(this===e)return!0;if(null==e||this.name!==e.name||this.defaultStartRule!==e.defaultStartRule||this.superGrammar!==e.superGrammar&&!this.superGrammar.equals(e.superGrammar))return!1;var t=Be(this);const r=Be(e);return t.length===r.length&&t.every((e,t)=>e.description===r[t].description&&e.formals.join(",")===r[t].formals.join(",")&&e.body.toString()===r[t].body.toString())}match(e,t){var r=this.matcher();return r.replaceInputRange(0,0,e),r.match(t)}trace(e,t){var r=this.matcher();return r.replaceInputRange(0,0,e),r.trace(t)}createSemantics(){return F.createSemantics(this)}extendSemantics(e){return F.createSemantics(this,e._getSemantics())}_checkTopDownActionDict(e,t,r){var n,i=[];for(const s in r){var a=r[s];if(Te.includes(s)||s in this.rules)if("function"!=typeof a)i.push(`'${s}' must be a function in an action dictionary for '${this.name}'`);else{var a=a.length,o=this._topDownActionArity(s);if(a!==o){let e;e="_iter"===s||"_nonterminal"===s?`it should use a rest parameter, e.g. \`${s}(...children) {}\`. `+"NOTE: this is new in Ohm v16 — see https://ohmjs.org/d/ati for details.":`expected ${o}, got `+a,i.push(`Semantic action '${s}' has the wrong arity: `+e)}}else i.push(`'${s}' is not a valid semantic action for '${this.name}'`)}if(0"- "+e),(t=new Error([`Found errors in the action dictionary of the '${t}' ${e}:`,...n].join("\n"))).problems=i,t}_topDownActionArity(e){return Te.includes(e)?0:this.rules[e].body.getArity()}_inheritsFrom(e){let t=this.superGrammar;for(;t;){if(t.equals(e,!0))return!0;t=t.superGrammar}return!1}toRecipe(e=void 0){var t={};this.source&&(t.source=this.source.contents);let r=null;this.defaultStartRule&&(r=this.defaultStartRule);const s={};Object.keys(this.rules).forEach(e=>{var t=this.rules[e],r=t["body"],n=!this.superGrammar||!this.superGrammar.rules[e];let i;i=n?"define":r instanceof u?"extend":"override";var a={},o=(t.source&&this.source&&(o=t.source.relativeTo(this.source),a.sourceInterval=[o.startIdx,o.endIdx]),n?t.description:null),n=r.outputRecipe(t.formals,this.source);s[e]=[i,a,o,t.formals,n]});let n="null";return e?n=e:this.superGrammar&&!this.superGrammar.isBuiltIn()&&(n=this.superGrammar.toRecipe()),`[${[...["grammar",t,this.name].map(JSON.stringify),n,...[r,s].map(JSON.stringify)].join(",")}]`.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}toOperationActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}toAttributeActionDictionaryTemplate(){return this._toOperationOrAttributeActionDictionaryTemplate()}_toOperationOrAttributeActionDictionaryTemplate(){var e=new d;e.append("{");let t=!0;for(const n in this.rules){var r=this.rules[n]["body"];t?t=!1:e.append(","),e.append("\n"),e.append(" "),this.addSemanticActionTemplate(n,r,e)}return e.append("\n}"),e.contents()}addSemanticActionTemplate(e,t,r){r.append(e),r.append(": function(");e=this._topDownActionArity(e);r.append(G("_",e).join(", ")),r.append(") {\n"),r.append(" }")}parseApplication(e){let t;if(!((t=-1===e.indexOf("<")?new I(e):(e=Ge.match(e,"Base_application"),qe(e,{}))).ruleName in this.rules))throw Z(t.ruleName,this.name);var r,e=this.rules[t.ruleName]["formals"];if(e.length!==t.args.length)throw r=this.rules[t.ruleName]["source"],X(t.ruleName,e.length,t.args.length,r);return t}_setUpMatchState(e){this._matchStateInitializer&&this._matchStateInitializer(e)}}j.ProtoBuiltInRules=new j("ProtoBuiltInRules",void 0,{any:{body:r,formals:[],description:"any character",primitive:!0},end:{body:i,formals:[],description:"end of input",primitive:!0},caseInsensitive:{body:new Oe(new o(0)),formals:["str"],primitive:!0},lower:{body:new w("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new w("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new w("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new y(new I("space")),formals:[]},space:{body:new a("\0"," "),formals:[],description:"a space"}}),j.initApplicationParser=function(e,t){Ge=e,qe=t};class ze{constructor(e){this.name=e}sourceInterval(e,t){return this.source.subInterval(e,t-e)}ensureSuperGrammar(){return this.superGrammar||this.withSuperGrammar("BuiltInRules"===this.name?j.ProtoBuiltInRules:j.BuiltInRules),this.superGrammar}ensureSuperGrammarRuleForOverriding(e,t){var r=this.ensureSuperGrammar().rules[e];if(r)return r;throw r=this.superGrammar.name,A("Cannot override rule "+e+" because it is not declared in "+r,t)}installOverriddenOrExtendedRule(e,t,r,n){var i=q(t);if(0{var t=r.rules[e]["body"];try{t.assertChoicesHaveUniformArity(e)}catch(e){n.push(e)}try{t.assertAllApplicationsAreValid(e,r)}catch(e){n.push(e),i=!0}}),i||Object.keys(r.rules).forEach(e=>{e=r.rules[e].body;try{e.assertIteratedExprsAreNotNullable(r,[])}catch(e){n.push(e)}}),0{this.currentRuleName=e;var t=s[e],r=t[0],n=t[1],i=t[2],a=t[3],t=this.fromRecipe(t[4]);let o;u.source&&n&&n.sourceInterval&&(o=u.source.subInterval(n.sourceInterval[0],n.sourceInterval[1]-n.sourceInterval[0])),u[r](e,a,t,i,o)}),this.currentRuleName=this.currentDecl=null,u.build()}terminal(e){return new c(e)}range(e,t){return new a(e,t)}param(e){return new o(e)}alt(...e){let t=[];for(var r of e)(r=r instanceof n?r:this.fromRecipe(r))instanceof s?t=t.concat(r.terms):t.push(r);return 1===t.length?t[0]:new s(t)}seq(...e){let t=[];for(var r of e)(r=r instanceof n?r:this.fromRecipe(r))instanceof h?t=t.concat(r.factors):t.push(r);return 1===t.length?t[0]:new h(t)}star(e){return e instanceof n||(e=this.fromRecipe(e)),new y(e)}plus(e){return e instanceof n||(e=this.fromRecipe(e)),new g(e)}opt(e){return e instanceof n||(e=this.fromRecipe(e)),new v(e)}not(e){return e instanceof n||(e=this.fromRecipe(e)),new _(e)}lookahead(e){return e instanceof n||(e=this.fromRecipe(e)),new b(e)}lex(e){return e instanceof n||(e=this.fromRecipe(e)),new x(e)}app(e,t){return t&&0this.fromRecipe(e)),t.map(e=>this.fromRecipe(e)))}fromRecipe(e){var t="grammar"===e[0]?e.slice(1):e.slice(2),t=this[e[0]](...t),e=e[1];return e&&e.sourceInterval&&this.currentDecl&&t.withSource(this.currentDecl.sourceInterval(...e.sourceInterval)),t}}function Ue(e){return"function"==typeof e?e.call(new Ke):("string"==typeof e&&(e=JSON.parse(e)),(new Ke).fromRecipe(e))}var Ve,$e=Ue(["grammar",{source:'BuiltInRules {\n\n alnum (an alpha-numeric character)\n = letter\n | digit\n\n letter (a letter)\n = lower\n | upper\n | unicodeLtmo\n\n digit (a digit)\n = "0".."9"\n\n hexDigit (a hexadecimal digit)\n = digit\n | "a".."f"\n | "A".."F"\n\n ListOf\n = NonemptyListOf\n | EmptyListOf\n\n NonemptyListOf\n = elem (sep elem)*\n\n EmptyListOf\n = /* nothing */\n\n listOf\n = nonemptyListOf\n | emptyListOf\n\n nonemptyListOf\n = elem (sep elem)*\n\n emptyListOf\n = /* nothing */\n\n // Allows a syntactic rule application within a lexical context.\n applySyntactic = app\n}'},"BuiltInRules",null,null,{alnum:["define",{sourceInterval:[18,78]},"an alpha-numeric character",[],["alt",{sourceInterval:[60,78]},["app",{sourceInterval:[60,66]},"letter",[]],["app",{sourceInterval:[73,78]},"digit",[]]]],letter:["define",{sourceInterval:[82,142]},"a letter",[],["alt",{sourceInterval:[107,142]},["app",{sourceInterval:[107,112]},"lower",[]],["app",{sourceInterval:[119,124]},"upper",[]],["app",{sourceInterval:[131,142]},"unicodeLtmo",[]]]],digit:["define",{sourceInterval:[146,177]},"a digit",[],["range",{sourceInterval:[169,177]},"0","9"]],hexDigit:["define",{sourceInterval:[181,254]},"a hexadecimal digit",[],["alt",{sourceInterval:[219,254]},["app",{sourceInterval:[219,224]},"digit",[]],["range",{sourceInterval:[231,239]},"a","f"],["range",{sourceInterval:[246,254]},"A","F"]]],ListOf:["define",{sourceInterval:[258,336]},null,["elem","sep"],["alt",{sourceInterval:[282,336]},["app",{sourceInterval:[282,307]},"NonemptyListOf",[["param",{sourceInterval:[297,301]},0],["param",{sourceInterval:[303,306]},1]]],["app",{sourceInterval:[314,336]},"EmptyListOf",[["param",{sourceInterval:[326,330]},0],["param",{sourceInterval:[332,335]},1]]]]],NonemptyListOf:["define",{sourceInterval:[340,388]},null,["elem","sep"],["seq",{sourceInterval:[372,388]},["param",{sourceInterval:[372,376]},0],["star",{sourceInterval:[377,388]},["seq",{sourceInterval:[378,386]},["param",{sourceInterval:[378,381]},1],["param",{sourceInterval:[382,386]},0]]]]],EmptyListOf:["define",{sourceInterval:[392,434]},null,["elem","sep"],["seq",{sourceInterval:[438,438]}]],listOf:["define",{sourceInterval:[438,516]},null,["elem","sep"],["alt",{sourceInterval:[462,516]},["app",{sourceInterval:[462,487]},"nonemptyListOf",[["param",{sourceInterval:[477,481]},0],["param",{sourceInterval:[483,486]},1]]],["app",{sourceInterval:[494,516]},"emptyListOf",[["param",{sourceInterval:[506,510]},0],["param",{sourceInterval:[512,515]},1]]]]],nonemptyListOf:["define",{sourceInterval:[520,568]},null,["elem","sep"],["seq",{sourceInterval:[552,568]},["param",{sourceInterval:[552,556]},0],["star",{sourceInterval:[557,568]},["seq",{sourceInterval:[558,566]},["param",{sourceInterval:[558,561]},1],["param",{sourceInterval:[562,566]},0]]]]],emptyListOf:["define",{sourceInterval:[572,682]},null,["elem","sep"],["seq",{sourceInterval:[685,685]}]],applySyntactic:["define",{sourceInterval:[685,710]},null,["app"],["param",{sourceInterval:[707,710]},0]]}]),He=(j.BuiltInRules=$e,Ve=j.BuiltInRules,se.forEach(e=>{e(Ve)}),Ue(["grammar",{source:'Ohm {\n\n Grammars\n = Grammar*\n\n Grammar\n = ident SuperGrammar? "{" Rule* "}"\n\n SuperGrammar\n = "<:" ident\n\n Rule\n = ident Formals? ruleDescr? "=" RuleBody -- define\n | ident Formals? ":=" OverrideRuleBody -- override\n | ident Formals? "+=" RuleBody -- extend\n\n RuleBody\n = "|"? NonemptyListOf\n\n TopLevelTerm\n = Seq caseName -- inline\n | Seq\n\n OverrideRuleBody\n = "|"? NonemptyListOf\n\n OverrideTopLevelTerm\n = "..." -- superSplice\n | TopLevelTerm\n\n Formals\n = "<" ListOf ">"\n\n Params\n = "<" ListOf ">"\n\n Alt\n = NonemptyListOf\n\n Seq\n = Iter*\n\n Iter\n = Pred "*" -- star\n | Pred "+" -- plus\n | Pred "?" -- opt\n | Pred\n\n Pred\n = "~" Lex -- not\n | "&" Lex -- lookahead\n | Lex\n\n Lex\n = "#" Base -- lex\n | Base\n\n Base\n = ident Params? ~(ruleDescr? "=" | ":=" | "+=") -- application\n | oneCharTerminal ".." oneCharTerminal -- range\n | terminal -- terminal\n | "(" Alt ")" -- paren\n\n ruleDescr (a rule description)\n = "(" ruleDescrText ")"\n\n ruleDescrText\n = (~")" any)*\n\n caseName\n = "--" (~"\\n" space)* name (~"\\n" space)* ("\\n" | &"}")\n\n name (a name)\n = nameFirst nameRest*\n\n nameFirst\n = "_"\n | letter\n\n nameRest\n = "_"\n | alnum\n\n ident (an identifier)\n = name\n\n terminal\n = "\\"" terminalChar* "\\""\n\n oneCharTerminal\n = "\\"" terminalChar "\\""\n\n terminalChar\n = escapeChar\n | ~"\\\\" ~"\\"" ~"\\n" "\\u{0}".."\\u{10FFFF}"\n\n escapeChar (an escape sequence)\n = "\\\\\\\\" -- backslash\n | "\\\\\\"" -- doubleQuote\n | "\\\\\\\'" -- singleQuote\n | "\\\\b" -- backspace\n | "\\\\n" -- lineFeed\n | "\\\\r" -- carriageReturn\n | "\\\\t" -- tab\n | "\\\\u{" hexDigit hexDigit? hexDigit?\n hexDigit? hexDigit? hexDigit? "}" -- unicodeCodePoint\n | "\\\\u" hexDigit hexDigit hexDigit hexDigit -- unicodeEscape\n | "\\\\x" hexDigit hexDigit -- hexEscape\n\n space\n += comment\n\n comment\n = "//" (~"\\n" any)* &("\\n" | end) -- singleLine\n | "/*" (~"*/" any)* "*/" -- multiLine\n\n tokens = token*\n\n token = caseName | comment | ident | operator | punctuation | terminal | any\n\n operator = "<:" | "=" | ":=" | "+=" | "*" | "+" | "?" | "~" | "&"\n\n punctuation = "<" | ">" | "," | "--"\n}'},"Ohm",se=null,"Grammars",{Grammars:["define",{sourceInterval:[9,32]},null,[],["star",{sourceInterval:[24,32]},["app",{sourceInterval:[24,31]},"Grammar",[]]]],Grammar:["define",{sourceInterval:[36,83]},null,[],["seq",{sourceInterval:[50,83]},["app",{sourceInterval:[50,55]},"ident",[]],["opt",{sourceInterval:[56,69]},["app",{sourceInterval:[56,68]},"SuperGrammar",[]]],["terminal",{sourceInterval:[70,73]},"{"],["star",{sourceInterval:[74,79]},["app",{sourceInterval:[74,78]},"Rule",[]]],["terminal",{sourceInterval:[80,83]},"}"]]],SuperGrammar:["define",{sourceInterval:[87,116]},null,[],["seq",{sourceInterval:[106,116]},["terminal",{sourceInterval:[106,110]},"<:"],["app",{sourceInterval:[111,116]},"ident",[]]]],Rule_define:["define",{sourceInterval:[131,181]},null,[],["seq",{sourceInterval:[131,170]},["app",{sourceInterval:[131,136]},"ident",[]],["opt",{sourceInterval:[137,145]},["app",{sourceInterval:[137,144]},"Formals",[]]],["opt",{sourceInterval:[146,156]},["app",{sourceInterval:[146,155]},"ruleDescr",[]]],["terminal",{sourceInterval:[157,160]},"="],["app",{sourceInterval:[162,170]},"RuleBody",[]]]],Rule_override:["define",{sourceInterval:[188,248]},null,[],["seq",{sourceInterval:[188,235]},["app",{sourceInterval:[188,193]},"ident",[]],["opt",{sourceInterval:[194,202]},["app",{sourceInterval:[194,201]},"Formals",[]]],["terminal",{sourceInterval:[214,218]},":="],["app",{sourceInterval:[219,235]},"OverrideRuleBody",[]]]],Rule_extend:["define",{sourceInterval:[255,305]},null,[],["seq",{sourceInterval:[255,294]},["app",{sourceInterval:[255,260]},"ident",[]],["opt",{sourceInterval:[261,269]},["app",{sourceInterval:[261,268]},"Formals",[]]],["terminal",{sourceInterval:[281,285]},"+="],["app",{sourceInterval:[286,294]},"RuleBody",[]]]],Rule:["define",{sourceInterval:[120,305]},null,[],["alt",{sourceInterval:[131,305]},["app",{sourceInterval:[131,170]},"Rule_define",[]],["app",{sourceInterval:[188,235]},"Rule_override",[]],["app",{sourceInterval:[255,294]},"Rule_extend",[]]]],RuleBody:["define",{sourceInterval:[309,362]},null,[],["seq",{sourceInterval:[324,362]},["opt",{sourceInterval:[324,328]},["terminal",{sourceInterval:[324,327]},"|"]],["app",{sourceInterval:[329,362]},"NonemptyListOf",[["app",{sourceInterval:[344,356]},"TopLevelTerm",[]],["terminal",{sourceInterval:[358,361]},"|"]]]]],TopLevelTerm_inline:["define",{sourceInterval:[385,408]},null,[],["seq",{sourceInterval:[385,397]},["app",{sourceInterval:[385,388]},"Seq",[]],["app",{sourceInterval:[389,397]},"caseName",[]]]],TopLevelTerm:["define",{sourceInterval:[366,418]},null,[],["alt",{sourceInterval:[385,418]},["app",{sourceInterval:[385,397]},"TopLevelTerm_inline",[]],["app",{sourceInterval:[415,418]},"Seq",[]]]],OverrideRuleBody:["define",{sourceInterval:[422,491]},null,[],["seq",{sourceInterval:[445,491]},["opt",{sourceInterval:[445,449]},["terminal",{sourceInterval:[445,448]},"|"]],["app",{sourceInterval:[450,491]},"NonemptyListOf",[["app",{sourceInterval:[465,485]},"OverrideTopLevelTerm",[]],["terminal",{sourceInterval:[487,490]},"|"]]]]],OverrideTopLevelTerm_superSplice:["define",{sourceInterval:[522,543]},null,[],["terminal",{sourceInterval:[522,527]},"..."]],OverrideTopLevelTerm:["define",{sourceInterval:[495,562]},null,[],["alt",{sourceInterval:[522,562]},["app",{sourceInterval:[522,527]},"OverrideTopLevelTerm_superSplice",[]],["app",{sourceInterval:[550,562]},"TopLevelTerm",[]]]],Formals:["define",{sourceInterval:[566,606]},null,[],["seq",{sourceInterval:[580,606]},["terminal",{sourceInterval:[580,583]},"<"],["app",{sourceInterval:[584,602]},"ListOf",[["app",{sourceInterval:[591,596]},"ident",[]],["terminal",{sourceInterval:[598,601]},","]]],["terminal",{sourceInterval:[603,606]},">"]]],Params:["define",{sourceInterval:[610,647]},null,[],["seq",{sourceInterval:[623,647]},["terminal",{sourceInterval:[623,626]},"<"],["app",{sourceInterval:[627,643]},"ListOf",[["app",{sourceInterval:[634,637]},"Seq",[]],["terminal",{sourceInterval:[639,642]},","]]],["terminal",{sourceInterval:[644,647]},">"]]],Alt:["define",{sourceInterval:[651,685]},null,[],["app",{sourceInterval:[661,685]},"NonemptyListOf",[["app",{sourceInterval:[676,679]},"Seq",[]],["terminal",{sourceInterval:[681,684]},"|"]]]],Seq:["define",{sourceInterval:[689,704]},null,[],["star",{sourceInterval:[699,704]},["app",{sourceInterval:[699,703]},"Iter",[]]]],Iter_star:["define",{sourceInterval:[719,736]},null,[],["seq",{sourceInterval:[719,727]},["app",{sourceInterval:[719,723]},"Pred",[]],["terminal",{sourceInterval:[724,727]},"*"]]],Iter_plus:["define",{sourceInterval:[743,760]},null,[],["seq",{sourceInterval:[743,751]},["app",{sourceInterval:[743,747]},"Pred",[]],["terminal",{sourceInterval:[748,751]},"+"]]],Iter_opt:["define",{sourceInterval:[767,783]},null,[],["seq",{sourceInterval:[767,775]},["app",{sourceInterval:[767,771]},"Pred",[]],["terminal",{sourceInterval:[772,775]},"?"]]],Iter:["define",{sourceInterval:[708,794]},null,[],["alt",{sourceInterval:[719,794]},["app",{sourceInterval:[719,727]},"Iter_star",[]],["app",{sourceInterval:[743,751]},"Iter_plus",[]],["app",{sourceInterval:[767,775]},"Iter_opt",[]],["app",{sourceInterval:[790,794]},"Pred",[]]]],Pred_not:["define",{sourceInterval:[809,824]},null,[],["seq",{sourceInterval:[809,816]},["terminal",{sourceInterval:[809,812]},"~"],["app",{sourceInterval:[813,816]},"Lex",[]]]],Pred_lookahead:["define",{sourceInterval:[831,852]},null,[],["seq",{sourceInterval:[831,838]},["terminal",{sourceInterval:[831,834]},"&"],["app",{sourceInterval:[835,838]},"Lex",[]]]],Pred:["define",{sourceInterval:[798,862]},null,[],["alt",{sourceInterval:[809,862]},["app",{sourceInterval:[809,816]},"Pred_not",[]],["app",{sourceInterval:[831,838]},"Pred_lookahead",[]],["app",{sourceInterval:[859,862]},"Lex",[]]]],Lex_lex:["define",{sourceInterval:[876,892]},null,[],["seq",{sourceInterval:[876,884]},["terminal",{sourceInterval:[876,879]},"#"],["app",{sourceInterval:[880,884]},"Base",[]]]],Lex:["define",{sourceInterval:[866,903]},null,[],["alt",{sourceInterval:[876,903]},["app",{sourceInterval:[876,884]},"Lex_lex",[]],["app",{sourceInterval:[899,903]},"Base",[]]]],Base_application:["define",{sourceInterval:[918,979]},null,[],["seq",{sourceInterval:[918,963]},["app",{sourceInterval:[918,923]},"ident",[]],["opt",{sourceInterval:[924,931]},["app",{sourceInterval:[924,930]},"Params",[]]],["not",{sourceInterval:[932,963]},["alt",{sourceInterval:[934,962]},["seq",{sourceInterval:[934,948]},["opt",{sourceInterval:[934,944]},["app",{sourceInterval:[934,943]},"ruleDescr",[]]],["terminal",{sourceInterval:[945,948]},"="]],["terminal",{sourceInterval:[951,955]},":="],["terminal",{sourceInterval:[958,962]},"+="]]]]],Base_range:["define",{sourceInterval:[986,1041]},null,[],["seq",{sourceInterval:[986,1022]},["app",{sourceInterval:[986,1001]},"oneCharTerminal",[]],["terminal",{sourceInterval:[1002,1006]},".."],["app",{sourceInterval:[1007,1022]},"oneCharTerminal",[]]]],Base_terminal:["define",{sourceInterval:[1048,1106]},null,[],["app",{sourceInterval:[1048,1056]},"terminal",[]]],Base_paren:["define",{sourceInterval:[1113,1168]},null,[],["seq",{sourceInterval:[1113,1124]},["terminal",{sourceInterval:[1113,1116]},"("],["app",{sourceInterval:[1117,1120]},"Alt",[]],["terminal",{sourceInterval:[1121,1124]},")"]]],Base:["define",{sourceInterval:[907,1168]},null,[],["alt",{sourceInterval:[918,1168]},["app",{sourceInterval:[918,963]},"Base_application",[]],["app",{sourceInterval:[986,1022]},"Base_range",[]],["app",{sourceInterval:[1048,1056]},"Base_terminal",[]],["app",{sourceInterval:[1113,1124]},"Base_paren",[]]]],ruleDescr:["define",{sourceInterval:[1172,1231]},"a rule description",[],["seq",{sourceInterval:[1210,1231]},["terminal",{sourceInterval:[1210,1213]},"("],["app",{sourceInterval:[1214,1227]},"ruleDescrText",[]],["terminal",{sourceInterval:[1228,1231]},")"]]],ruleDescrText:["define",{sourceInterval:[1235,1266]},null,[],["star",{sourceInterval:[1255,1266]},["seq",{sourceInterval:[1256,1264]},["not",{sourceInterval:[1256,1260]},["terminal",{sourceInterval:[1257,1260]},")"]],["app",{sourceInterval:[1261,1264]},"any",[]]]]],caseName:["define",{sourceInterval:[1270,1338]},null,[],["seq",{sourceInterval:[1285,1338]},["terminal",{sourceInterval:[1285,1289]},"--"],["star",{sourceInterval:[1290,1304]},["seq",{sourceInterval:[1291,1302]},["not",{sourceInterval:[1291,1296]},["terminal",{sourceInterval:[1292,1296]},"\n"]],["app",{sourceInterval:[1297,1302]},"space",[]]]],["app",{sourceInterval:[1305,1309]},"name",[]],["star",{sourceInterval:[1310,1324]},["seq",{sourceInterval:[1311,1322]},["not",{sourceInterval:[1311,1316]},["terminal",{sourceInterval:[1312,1316]},"\n"]],["app",{sourceInterval:[1317,1322]},"space",[]]]],["alt",{sourceInterval:[1326,1337]},["terminal",{sourceInterval:[1326,1330]},"\n"],["lookahead",{sourceInterval:[1333,1337]},["terminal",{sourceInterval:[1334,1337]},"}"]]]]],name:["define",{sourceInterval:[1342,1382]},"a name",[],["seq",{sourceInterval:[1363,1382]},["app",{sourceInterval:[1363,1372]},"nameFirst",[]],["star",{sourceInterval:[1373,1382]},["app",{sourceInterval:[1373,1381]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[1386,1418]},null,[],["alt",{sourceInterval:[1402,1418]},["terminal",{sourceInterval:[1402,1405]},"_"],["app",{sourceInterval:[1412,1418]},"letter",[]]]],nameRest:["define",{sourceInterval:[1422,1452]},null,[],["alt",{sourceInterval:[1437,1452]},["terminal",{sourceInterval:[1437,1440]},"_"],["app",{sourceInterval:[1447,1452]},"alnum",[]]]],ident:["define",{sourceInterval:[1456,1489]},"an identifier",[],["app",{sourceInterval:[1485,1489]},"name",[]]],terminal:["define",{sourceInterval:[1493,1531]},null,[],["seq",{sourceInterval:[1508,1531]},["terminal",{sourceInterval:[1508,1512]},'"'],["star",{sourceInterval:[1513,1526]},["app",{sourceInterval:[1513,1525]},"terminalChar",[]]],["terminal",{sourceInterval:[1527,1531]},'"']]],oneCharTerminal:["define",{sourceInterval:[1535,1579]},null,[],["seq",{sourceInterval:[1557,1579]},["terminal",{sourceInterval:[1557,1561]},'"'],["app",{sourceInterval:[1562,1574]},"terminalChar",[]],["terminal",{sourceInterval:[1575,1579]},'"']]],terminalChar:["define",{sourceInterval:[1583,1660]},null,[],["alt",{sourceInterval:[1602,1660]},["app",{sourceInterval:[1602,1612]},"escapeChar",[]],["seq",{sourceInterval:[1621,1660]},["not",{sourceInterval:[1621,1626]},["terminal",{sourceInterval:[1622,1626]},"\\"]],["not",{sourceInterval:[1627,1632]},["terminal",{sourceInterval:[1628,1632]},'"']],["not",{sourceInterval:[1633,1638]},["terminal",{sourceInterval:[1634,1638]},"\n"]],["range",{sourceInterval:[1639,1660]},"\0","􏿿"]]]],escapeChar_backslash:["define",{sourceInterval:[1703,1758]},null,[],["terminal",{sourceInterval:[1703,1709]},"\\\\"]],escapeChar_doubleQuote:["define",{sourceInterval:[1765,1822]},null,[],["terminal",{sourceInterval:[1765,1771]},'\\"']],escapeChar_singleQuote:["define",{sourceInterval:[1829,1886]},null,[],["terminal",{sourceInterval:[1829,1835]},"\\'"]],escapeChar_backspace:["define",{sourceInterval:[1893,1948]},null,[],["terminal",{sourceInterval:[1893,1898]},"\\b"]],escapeChar_lineFeed:["define",{sourceInterval:[1955,2009]},null,[],["terminal",{sourceInterval:[1955,1960]},"\\n"]],escapeChar_carriageReturn:["define",{sourceInterval:[2016,2076]},null,[],["terminal",{sourceInterval:[2016,2021]},"\\r"]],escapeChar_tab:["define",{sourceInterval:[2083,2132]},null,[],["terminal",{sourceInterval:[2083,2088]},"\\t"]],escapeChar_unicodeCodePoint:["define",{sourceInterval:[2139,2243]},null,[],["seq",{sourceInterval:[2139,2221]},["terminal",{sourceInterval:[2139,2145]},"\\u{"],["app",{sourceInterval:[2146,2154]},"hexDigit",[]],["opt",{sourceInterval:[2155,2164]},["app",{sourceInterval:[2155,2163]},"hexDigit",[]]],["opt",{sourceInterval:[2165,2174]},["app",{sourceInterval:[2165,2173]},"hexDigit",[]]],["opt",{sourceInterval:[2188,2197]},["app",{sourceInterval:[2188,2196]},"hexDigit",[]]],["opt",{sourceInterval:[2198,2207]},["app",{sourceInterval:[2198,2206]},"hexDigit",[]]],["opt",{sourceInterval:[2208,2217]},["app",{sourceInterval:[2208,2216]},"hexDigit",[]]],["terminal",{sourceInterval:[2218,2221]},"}"]]],escapeChar_unicodeEscape:["define",{sourceInterval:[2250,2309]},null,[],["seq",{sourceInterval:[2250,2291]},["terminal",{sourceInterval:[2250,2255]},"\\u"],["app",{sourceInterval:[2256,2264]},"hexDigit",[]],["app",{sourceInterval:[2265,2273]},"hexDigit",[]],["app",{sourceInterval:[2274,2282]},"hexDigit",[]],["app",{sourceInterval:[2283,2291]},"hexDigit",[]]]],escapeChar_hexEscape:["define",{sourceInterval:[2316,2371]},null,[],["seq",{sourceInterval:[2316,2339]},["terminal",{sourceInterval:[2316,2321]},"\\x"],["app",{sourceInterval:[2322,2330]},"hexDigit",[]],["app",{sourceInterval:[2331,2339]},"hexDigit",[]]]],escapeChar:["define",{sourceInterval:[1664,2371]},"an escape sequence",[],["alt",{sourceInterval:[1703,2371]},["app",{sourceInterval:[1703,1709]},"escapeChar_backslash",[]],["app",{sourceInterval:[1765,1771]},"escapeChar_doubleQuote",[]],["app",{sourceInterval:[1829,1835]},"escapeChar_singleQuote",[]],["app",{sourceInterval:[1893,1898]},"escapeChar_backspace",[]],["app",{sourceInterval:[1955,1960]},"escapeChar_lineFeed",[]],["app",{sourceInterval:[2016,2021]},"escapeChar_carriageReturn",[]],["app",{sourceInterval:[2083,2088]},"escapeChar_tab",[]],["app",{sourceInterval:[2139,2221]},"escapeChar_unicodeCodePoint",[]],["app",{sourceInterval:[2250,2291]},"escapeChar_unicodeEscape",[]],["app",{sourceInterval:[2316,2339]},"escapeChar_hexEscape",[]]]],space:["extend",{sourceInterval:[2375,2394]},null,[],["app",{sourceInterval:[2387,2394]},"comment",[]]],comment_singleLine:["define",{sourceInterval:[2412,2458]},null,[],["seq",{sourceInterval:[2412,2443]},["terminal",{sourceInterval:[2412,2416]},"//"],["star",{sourceInterval:[2417,2429]},["seq",{sourceInterval:[2418,2427]},["not",{sourceInterval:[2418,2423]},["terminal",{sourceInterval:[2419,2423]},"\n"]],["app",{sourceInterval:[2424,2427]},"any",[]]]],["lookahead",{sourceInterval:[2430,2443]},["alt",{sourceInterval:[2432,2442]},["terminal",{sourceInterval:[2432,2436]},"\n"],["app",{sourceInterval:[2439,2442]},"end",[]]]]]],comment_multiLine:["define",{sourceInterval:[2465,2501]},null,[],["seq",{sourceInterval:[2465,2487]},["terminal",{sourceInterval:[2465,2469]},"/*"],["star",{sourceInterval:[2470,2482]},["seq",{sourceInterval:[2471,2480]},["not",{sourceInterval:[2471,2476]},["terminal",{sourceInterval:[2472,2476]},"*/"]],["app",{sourceInterval:[2477,2480]},"any",[]]]],["terminal",{sourceInterval:[2483,2487]},"*/"]]],comment:["define",{sourceInterval:[2398,2501]},null,[],["alt",{sourceInterval:[2412,2501]},["app",{sourceInterval:[2412,2443]},"comment_singleLine",[]],["app",{sourceInterval:[2465,2487]},"comment_multiLine",[]]]],tokens:["define",{sourceInterval:[2505,2520]},null,[],["star",{sourceInterval:[2514,2520]},["app",{sourceInterval:[2514,2519]},"token",[]]]],token:["define",{sourceInterval:[2524,2600]},null,[],["alt",{sourceInterval:[2532,2600]},["app",{sourceInterval:[2532,2540]},"caseName",[]],["app",{sourceInterval:[2543,2550]},"comment",[]],["app",{sourceInterval:[2553,2558]},"ident",[]],["app",{sourceInterval:[2561,2569]},"operator",[]],["app",{sourceInterval:[2572,2583]},"punctuation",[]],["app",{sourceInterval:[2586,2594]},"terminal",[]],["app",{sourceInterval:[2597,2600]},"any",[]]]],operator:["define",{sourceInterval:[2604,2669]},null,[],["alt",{sourceInterval:[2615,2669]},["terminal",{sourceInterval:[2615,2619]},"<:"],["terminal",{sourceInterval:[2622,2625]},"="],["terminal",{sourceInterval:[2628,2632]},":="],["terminal",{sourceInterval:[2635,2639]},"+="],["terminal",{sourceInterval:[2642,2645]},"*"],["terminal",{sourceInterval:[2648,2651]},"+"],["terminal",{sourceInterval:[2654,2657]},"?"],["terminal",{sourceInterval:[2660,2663]},"~"],["terminal",{sourceInterval:[2666,2669]},"&"]]],punctuation:["define",{sourceInterval:[2673,2709]},null,[],["alt",{sourceInterval:[2687,2709]},["terminal",{sourceInterval:[2687,2690]},"<"],["terminal",{sourceInterval:[2693,2696]},">"],["terminal",{sourceInterval:[2699,2702]},","],["terminal",{sourceInterval:[2705,2709]},"--"]]]}]));const We=Object.create(n.prototype);function Je(e,t){for(const r in e)if(r===t)return 1}function Qe(e,a,t){const o=new Ke;let s,u,l,i=!1;return(t||He).createSemantics().addOperation("visit",{Grammars(e){return e.children.map(e=>e.visit())},Grammar(e,t,r,n,i){e=e.visit(),s=o.newGrammar(e),t.child(0)&&t.child(0).visit(),n.children.map(e=>e.visit()),t=s.build();if(t.source=this.source.trimmed(),Je(a,e))throw A("Grammar "+t.name+" is already declared in this namespace");return a[e]=t},SuperGrammar(e,t){var r,n,i=t.visit();if("null"===i)s.withSuperGrammar(null);else{if(!a||!Je(a,i))throw r=i,n=a,t=t.source,A(n?`Grammar ${r} is not declared in namespace '${n}'`:"Undeclared grammar "+r,t);s.withSuperGrammar(a[i])}},Rule_define(e,t,r,n,i){u=e.visit(),l=t.children.map(e=>e.visit())[0]||[],s.defaultStartRule||s.ensureSuperGrammar()===j.ProtoBuiltInRules||s.withDefaultStartRule(u);e=i.visit(),t=r.children.map(e=>e.visit())[0],i=this.source.trimmed();return s.define(u,l,e,t,i)},Rule_override(e,t,r,n){u=e.visit(),l=t.children.map(e=>e.visit())[0]||[];e=this.source.trimmed(),s.ensureSuperGrammarRuleForOverriding(u,e),i=!0,t=n.visit();return i=!1,s.override(u,l,t,null,e)},Rule_extend(e,t,r,n){u=e.visit(),l=t.children.map(e=>e.visit())[0]||[];e=n.visit(),t=this.source.trimmed();return s.extend(u,l,e,null,t)},RuleBody(e,t){return o.alt(...t.visit()).withSource(this.source)},OverrideRuleBody(e,t){var r,t=t.visit(),n=t.indexOf(We);return(0<=n?(r=t.slice(0,n),(n=t.slice(n+1)).forEach(e=>{if(e===We)throw A("'...' can appear at most once in a rule body",e.source)}),new p(s.superGrammar,u,r,n)):o.alt(...t)).withSource(this.source)},Formals(e,t,r){return t.visit()},Params(e,t,r){return t.visit()},Alt(e){return o.alt(...e.visit()).withSource(this.source)},TopLevelTerm_inline(e,t){var t=u+"_"+t.visit(),e=e.visit(),r=this.source.trimmed(),n=!(s.superGrammar&&s.superGrammar.rules[t]),n=(i&&!n?s.override(t,l,e,null,r):s.define(t,l,e,null,r),l.map(e=>o.app(e)));return o.app(t,n).withSource(e.source)},OverrideTopLevelTerm_superSplice(e){return We},Seq(e){return o.seq(...e.children.map(e=>e.visit())).withSource(this.source)},Iter_star(e,t){return o.star(e.visit()).withSource(this.source)},Iter_plus(e,t){return o.plus(e.visit()).withSource(this.source)},Iter_opt(e,t){return o.opt(e.visit()).withSource(this.source)},Pred_not(e,t){return o.not(t.visit()).withSource(this.source)},Pred_lookahead(e,t){return o.lookahead(t.visit()).withSource(this.source)},Lex_lex(e,t){return o.lex(t.visit()).withSource(this.source)},Base_application(e,t){t=t.children.map(e=>e.visit())[0]||[];return o.app(e.visit(),t).withSource(this.source)},Base_range(e,t,r){return o.range(e.visit(),r.visit()).withSource(this.source)},Base_terminal(e){return o.terminal(e.visit()).withSource(this.source)},Base_paren(e,t,r){return t.visit()},ruleDescr(e,t,r){return t.visit()},ruleDescrText(e){return this.sourceString.trim()},caseName(e,t,r,n,i){return r.visit()},name(e,t){return this.sourceString},nameFirst(e){},nameRest(e){},terminal(e,t,r){return t.children.map(e=>e.visit()).join("")},oneCharTerminal(e,t,r){return t.visit()},escapeChar(t){try{return $(this.sourceString)}catch(e){if(e instanceof RangeError&&e.message.startsWith("Invalid code point "))throw m((r=(t=t)._node)&&r.isNonterminal()&&"escapeChar_unicodeCodePoint"===r.ctorName),A(`U+${(t=(r=t.children.slice(1,-1).map(e=>e.source))[0].coverageWith(...r.slice(1))).contents} is not a valid Unicode code point`,t);throw e}var r},NonemptyListOf(e,t,r){return[e.visit()].concat(r.children.map(e=>e.visit()))},EmptyListOf(){return[]},_terminal(){return this.sourceString}})(e).visit()}var Ze=Ue(["grammar",{source:'OperationsAndAttributes {\n\n AttributeSignature =\n name\n\n OperationSignature =\n name Formals?\n\n Formals\n = "(" ListOf ")"\n\n name (a name)\n = nameFirst nameRest*\n\n nameFirst\n = "_"\n | letter\n\n nameRest\n = "_"\n | alnum\n\n}'},"OperationsAndAttributes",null,"AttributeSignature",{AttributeSignature:["define",{sourceInterval:[29,58]},null,[],["app",{sourceInterval:[54,58]},"name",[]]],OperationSignature:["define",{sourceInterval:[62,100]},null,[],["seq",{sourceInterval:[87,100]},["app",{sourceInterval:[87,91]},"name",[]],["opt",{sourceInterval:[92,100]},["app",{sourceInterval:[92,99]},"Formals",[]]]]],Formals:["define",{sourceInterval:[104,143]},null,[],["seq",{sourceInterval:[118,143]},["terminal",{sourceInterval:[118,121]},"("],["app",{sourceInterval:[122,139]},"ListOf",[["app",{sourceInterval:[129,133]},"name",[]],["terminal",{sourceInterval:[135,138]},","]]],["terminal",{sourceInterval:[140,143]},")"]]],name:["define",{sourceInterval:[147,187]},"a name",[],["seq",{sourceInterval:[168,187]},["app",{sourceInterval:[168,177]},"nameFirst",[]],["star",{sourceInterval:[178,187]},["app",{sourceInterval:[178,186]},"nameRest",[]]]]],nameFirst:["define",{sourceInterval:[191,223]},null,[],["alt",{sourceInterval:[207,223]},["terminal",{sourceInterval:[207,210]},"_"],["app",{sourceInterval:[217,223]},"letter",[]]]],nameRest:["define",{sourceInterval:[227,257]},null,[],["alt",{sourceInterval:[242,257]},["terminal",{sourceInterval:[242,245]},"_"],["app",{sourceInterval:[252,257]},"alnum",[]]]]}]);M=j.BuiltInRules,k={empty(){return this.iteration()},nonEmpty(e,t,r){return this.iteration([e].concat(r.children))}},F.BuiltInSemantics=F.createSemantics(M,null).addOperation("asIteration",{emptyListOf:k.empty,nonemptyListOf:k.nonEmpty,EmptyListOf:k.empty,NonemptyListOf:k.nonEmpty}),M=Ze,F.prototypeGrammarSemantics=M.createSemantics().addOperation("parse",{AttributeSignature(e){return{name:e.parse(),formals:[]}},OperationSignature(e,t){return{name:e.parse(),formals:t.children.map(e=>e.parse())[0]||[]}},Formals(e,t,r){return t.asIteration().children.map(e=>e.parse())},name(e,t){return this.sourceString}}),F.prototypeGrammar=M;const Ye="an indented block",Xe="a dedent";class et extends he{constructor(e){super(e.input),this.state=e}_indentationAt(e){return this.state.userData[e]||0}atEnd(){return super.atEnd()&&0===this._indentationAt(this.pos)}next(){if(0===this._indentationAt(this.pos))return super.next();this.examinedLength=Math.max(this.examinedLength,this.pos)}nextCharCode(){return 0!==this._indentationAt(this.pos)?(this.examinedLength=Math.max(this.examinedLength,this.pos),1114112):super.nextCharCode()}nextCodePoint(){return 0!==this._indentationAt(this.pos)?(this.examinedLength=Math.max(this.examinedLength,this.pos),1114112):super.nextCodePoint()}}class tt extends n{constructor(e=!0){super(),this.isIndent=e}allowsSkippingPrecedingSpace(){return!0}eval(e){var t=e["inputStream"],r=e.userData,t=(e.doNotMemoize=!0,t.pos),n=this.isIndent?1:-1;return 0<(r[t]||0)*n?(e.userData=Object.create(r),e.userData[t]-=n,e.pushBinding(new P(0),t),!0):(e.processFailure(t,this),!1)}getArity(){return 1}_assertAllApplicationsAreValid(e,t){}_isNullable(e,t){return!1}assertChoicesHaveUniformArity(e){}assertIteratedExprsAreNotNullable(e){}introduceParams(e){return this}substituteParams(e){return this}toString(){return this.isIndent?"indent":"dedent"}toDisplayString(){return this.toString()}toFailure(e){var t=this.isIndent?Ye:Xe;return new L(this,t,"description")}}var k=new I("indent"),Ze=new I("dedent"),M=new p($e,"any",[k,Ze],[]),k=(new Ke).newGrammar("IndentationSensitive").withSuperGrammar($e).define("indent",[],new tt(!0),Ye,void 0,!0).define("dedent",[],new tt(!1),Xe,void 0,!0).extend("any",[],M,"any character",void 0).build();Object.assign(k,{_matchStateInitializer(e){e.userData=function(e){let t=0;const r=[0];for(var n=()=>r[r.length-1],i={},a=/( *).*(?:$|\r?\n|\r)/g;null!=(o=a.exec(e));){var[o,s]=o;if(0===o.length)break;var u=s.length,s=n(),l=t+u;if(s!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e);function nt(e,t){var r,n,e=He.match(e,"Grammars");if(e.failed())throw r=e,n=new Error,Object.defineProperty(n,"message",{enumerable:!0,get(){return r.message}}),Object.defineProperty(n,"shortMessage",{enumerable:!0,get(){return"Expected "+r.getExpectedText()}}),n.interval=r.getInterval(),n;Qe(e,t)}function it(e,t){t=Object.create(t||{});if("string"!=typeof e){if(!rt(e))throw new TypeError("Expected string as first argument, got "+H(e));e=e.toString()}return nt(e,t),t}e.ExperimentalIndentationSensitive=k,e._buildGrammar=Qe,e.grammar=function(e,t){var r,e=it(e,t);if(0===(t=Object.keys(e)).length)throw new Error("Missing grammar definition");if(1 {\nreturn ","\"use strict\";\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NDArray = void 0;\nvar NDArray = /** @class */ (function () {\n function NDArray(flat, shape, dtype) {\n if (dtype === void 0) { dtype = Number; }\n this.shape = shape; // invariant: immutable\n this._flat = flat;\n this.dtype = dtype;\n this._simpleIndexes = null;\n }\n Object.defineProperty(NDArray.prototype, \"size\", {\n get: function () {\n return this._simpleIndexes == null ? this._flat.length : this._simpleIndexes.size;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(NDArray.prototype, \"flat\", {\n get: function () {\n var _this = this;\n if (this._simpleIndexes == null)\n return this._flat;\n var indices = this._simpleIndexes.indices;\n return indices.map(function (i) { return _this._flat[i]; });\n },\n set: function (list) {\n if (list.length != this.size)\n throw new Error(\"Length mismatch. Can't write \".concat(list.length, \" values into \").concat(this.size, \" available positions.\"));\n var n = this.size;\n if (this._simpleIndexes == null) {\n for (var i = 0; i < n; i++)\n this._flat[i] = list[i];\n }\n else {\n var indices = this._simpleIndexes.indices;\n for (var i = 0; i < n; i++)\n this._flat[indices[i]] = list[i];\n }\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(NDArray.prototype, \"T\", {\n get: function () {\n return this.transpose();\n },\n enumerable: false,\n configurable: true\n });\n NDArray.prototype.__popKwArgs = function () {\n var out = this['__kwArgs'];\n if (out === undefined)\n return {};\n delete this['__kwArgs'];\n return out;\n };\n /** @param {Object} kwArgs */\n NDArray.prototype.withKwArgs = function (kwArgs) {\n this['__kwArgs'] = kwArgs;\n return this;\n };\n NDArray.prototype[Symbol.iterator] = function () {\n var i;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n i = 0;\n _a.label = 1;\n case 1:\n if (!(i < this.shape[0])) return [3 /*break*/, 4];\n return [4 /*yield*/, this.index(i)];\n case 2:\n _a.sent();\n _a.label = 3;\n case 3:\n i++;\n return [3 /*break*/, 1];\n case 4: return [2 /*return*/];\n }\n });\n };\n Object.defineProperty(NDArray.prototype, \"length\", {\n get: function () {\n return this.shape[0] || 0;\n },\n enumerable: false,\n configurable: true\n });\n NDArray.prototype.item = function () {\n if (this.size != 1)\n throw new Error(\"Can't convert array of size \".concat(this.size, \" to scalar\"));\n return this._flat[0];\n };\n return NDArray;\n}());\nexports.NDArray = NDArray;\nvar _globals_1 = require(\"./_globals\");\n_globals_1.GLOBALS.NDArray = NDArray;\nvar NDArray_1 = require(\"./NDArray\");\nNDArray.prototype.modules = NDArray_1.modules;\n// ==============================\n// Basic methods\n// ==============================\nvar basic = NDArray_1.modules.basic;\nNDArray.prototype.reshape = function (shape) {\n var more_shape = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n more_shape[_i - 1] = arguments[_i];\n }\n return basic.reshape.apply(basic, __spreadArray([this, shape], __read(more_shape), false));\n};\nNDArray.prototype.ravel = function () {\n return basic.ravel(this);\n};\nNDArray.prototype.copy = function () {\n return basic.copy(this);\n};\n// ==============================\n// Indexing\n// ==============================\nNDArray.prototype.index = function () {\n var where = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n where[_i] = arguments[_i];\n }\n return NDArray_1.modules.indexes.index(this, where);\n};\n// ==============================\n// Printing\n// ==============================\nNDArray.prototype.toString = function () {\n return NDArray_1.modules.print.humanReadable(this);\n};\n// ==============================\n// Reduce\n// ==============================\nfunction reduceDecorator(func) {\n return function (axis, keepdims) {\n var _a;\n if (axis === void 0) { axis = null; }\n if (keepdims === void 0) { keepdims = false; }\n (_a = Object.assign({ axis: axis, keepdims: keepdims }, this.__popKwArgs()), axis = _a.axis, keepdims = _a.keepdims);\n return func(this, axis, keepdims);\n };\n}\nNDArray.prototype.sum = reduceDecorator(NDArray_1.modules.reduce.reducers.sum);\nNDArray.prototype.product = reduceDecorator(NDArray_1.modules.reduce.reducers.product);\nNDArray.prototype.any = reduceDecorator(NDArray_1.modules.reduce.reducers.any);\nNDArray.prototype.all = reduceDecorator(NDArray_1.modules.reduce.reducers.all);\nNDArray.prototype.max = reduceDecorator(NDArray_1.modules.reduce.reducers.max);\nNDArray.prototype.min = reduceDecorator(NDArray_1.modules.reduce.reducers.min);\nNDArray.prototype.argmax = reduceDecorator(NDArray_1.modules.reduce.reducers.argmax);\nNDArray.prototype.argmin = reduceDecorator(NDArray_1.modules.reduce.reducers.argmin);\nNDArray.prototype.mean = reduceDecorator(NDArray_1.modules.reduce.reducers.mean);\nNDArray.prototype.var = reduceDecorator(NDArray_1.modules.reduce.reducers.var);\nNDArray.prototype.std = reduceDecorator(NDArray_1.modules.reduce.reducers.std);\n// ==============================\n// Operators: Binary operations, assignment operations and unary boolean_not\n// ==============================\nfunction binaryOpDecorator(func) {\n return function (other, out) {\n if (out === void 0) { out = null; }\n (out = Object.assign({ out: out }, this.__popKwArgs()).out);\n return func(this, other, out);\n };\n}\nNDArray.prototype.add = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"+\"]);\nNDArray.prototype.subtract = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"-\"]);\nNDArray.prototype.multiply = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"*\"]);\nNDArray.prototype.divide = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"/\"]);\nNDArray.prototype.mod = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"%\"]);\nNDArray.prototype.divide_int = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"//\"]);\nNDArray.prototype.pow = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"**\"]);\nNDArray.prototype.maximum = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"↑\"]);\nNDArray.prototype.minimum = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"↓\"]);\nNDArray.prototype.bitwise_or = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"|\"]);\nNDArray.prototype.bitwise_and = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"&\"]);\nNDArray.prototype.bitwise_or = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"^\"]);\nNDArray.prototype.bitwise_shift_right = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"<<\"]);\nNDArray.prototype.bitwise_shift_right = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\">>\"]);\nNDArray.prototype.logical_or = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"or\"]);\nNDArray.prototype.logical_and = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"and\"]);\nNDArray.prototype.logical_xor = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"xor\"]);\nNDArray.prototype.greater = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\">\"]);\nNDArray.prototype.less = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"<\"]);\nNDArray.prototype.greater_equal = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\">=\"]);\nNDArray.prototype.less_equal = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"<=\"]);\nNDArray.prototype.equal = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"==\"]);\nNDArray.prototype.not_equal = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"!=\"]);\nfunction unaryOpDecorator(func) {\n return function (out) {\n if (out === void 0) { out = null; }\n (out = Object.assign({ out: out }, this.__popKwArgs()).out);\n return func(this, out);\n };\n}\n// Unary operations: only boolean_not. Positive is useless and negative is almost useless\nNDArray.prototype.bitwise_or = unaryOpDecorator(NDArray_1.modules.operators.op_unary[\"~\"]);\nNDArray.prototype.logical_or = unaryOpDecorator(NDArray_1.modules.operators.op_unary[\"not\"]);\nNDArray.prototype.isclose = NDArray_1.modules.operators.isclose;\nNDArray.prototype.allclose = NDArray_1.modules.operators.allclose;\nfunction assignOpDecorator(func) {\n //@ts-ignore\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return func.apply(void 0, __spreadArray([this], __read(args), false));\n };\n}\nNDArray.prototype.assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"=\"]);\nNDArray.prototype.add_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"+=\"]);\nNDArray.prototype.subtract_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"-=\"]);\nNDArray.prototype.multiply_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"*=\"]);\nNDArray.prototype.divide_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"/=\"]);\nNDArray.prototype.mod_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"%=\"]);\nNDArray.prototype.divide_int_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"//=\"]);\nNDArray.prototype.pow_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"**=\"]);\nNDArray.prototype.maximum_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"↑=\"]);\nNDArray.prototype.minimum_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"↓=\"]);\nNDArray.prototype.bitwise_or_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"|=\"]);\nNDArray.prototype.bitwise_and_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"&=\"]);\nNDArray.prototype.bitwise_shift_left_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"<<=\"]);\nNDArray.prototype.bitwise_shift_right_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\">>=\"]);\nNDArray.prototype.logical_or_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"or=\"]);\nNDArray.prototype.logical_and_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"and=\"]);\n// ==============================\n// array instantiation and reshaping\n// ==============================\nNDArray.prototype.tolist = function () {\n return NDArray_1.modules.jsInterface.tolist(this);\n};\n// NDArray.prototype.fromJS = function (A) {\n// return modules.jsInterface.fromJS(A);\n// }\n// ==============================\n// elementwise methods\n// ==============================\nNDArray.prototype.round = function (decimals) {\n if (decimals === void 0) { decimals = 0; }\n (decimals = Object.assign({ decimals: decimals }, this.__popKwArgs()).decimals);\n return NDArray_1.modules.elementwise.round(this, decimals);\n};\n// ==============================\n// transform methods\n// ==============================\n/** @param {null|number[]} axes */\nNDArray.prototype.transpose = function (axes) {\n if (axes === void 0) { axes = null; }\n (axes = Object.assign({ axes: axes }, this.__popKwArgs()).axes);\n return NDArray_1.modules.transform.transpose(this, axes);\n};\nNDArray.prototype.sort = function (axis) {\n if (axis === void 0) { axis = -1; }\n (axis = Object.assign({ axis: axis }, this.__popKwArgs()).axis);\n NDArray_1.modules.transform.sort(this, axis);\n return null;\n};\nvar op = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n if (!args.length)\n return this;\n if (typeof args[0] == \"string\") {\n var symbol_1 = args[0];\n if (args.length == 1) {\n var func_1 = NDArray_1.modules.operators.op_unary[symbol_1];\n if (!func_1)\n throw new Error(\"Unknown unary operator \\\"\".concat(symbol_1, \"\\\". Options:\").concat(__spreadArray([], __read(Object.keys(NDArray_1.modules.operators.op_unary)), false)));\n return func_1(this, symbol_1);\n }\n if (args.length > 2)\n throw new Error(\"Too many arguments provided: \".concat(__spreadArray([], __read(args), false)));\n var other_1 = args[1];\n var func_2 = NDArray_1.modules.operators.op_binary[symbol_1];\n if (func_2)\n return func_2(this, other_1);\n func_2 = NDArray_1.modules.operators.op_assign[symbol_1];\n if (func_2)\n return func_2(this, other_1);\n if (symbol_1.includes(':'))\n throw new Error(\"Expected index or operator symbol. Found \\\"\".concat(symbol_1, \"\\\". Did you mean \").concat([symbol_1], \"?\"));\n throw new Error(\"Expected index or operator symbol. Found \\\"\".concat(symbol_1, \"\\\"\"));\n }\n var where = args[0];\n if (where instanceof NDArray)\n throw new Error(\"Expected operator or index. Found numpy array\");\n if (args.length == 1)\n return this.index(where);\n var symbol = args[1];\n var func = NDArray_1.modules.operators.op_assign[symbol];\n if (!func)\n throw new Error(\"Unknown unary operator \\\"\".concat(symbol, \"\\\". Options:\").concat(__spreadArray([], __read(Object.keys(NDArray_1.modules.operators.op_unary)), false)));\n if (args.length > 3)\n throw new Error(\"Too many arguments provided: \".concat(__spreadArray([], __read(args), false)));\n var other = args[2];\n return func(this, where, other);\n};\nNDArray.prototype.op = op;\nexports.default = NDArray;\n","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.array = exports.asarray = exports.new_NDArray = exports.isarray = exports._NDArray = void 0;\nvar _globals_1 = require(\"../_globals\");\nvar np = _globals_1.GLOBALS.np, __NDArray = _globals_1.GLOBALS.NDArray;\nif (!__NDArray)\n throw new Error(\"Programming error: NDArray not defined\");\n// Functions to avoid importing NDArray (because if I import NDArray, I can't use it as a type annotation in the same file)\nexports._NDArray = __NDArray;\nfunction isarray(A) {\n return A instanceof exports._NDArray;\n}\nexports.isarray = isarray;\nvar new_NDArray = function (flat, shape, dtype) { return new exports._NDArray(flat, shape, dtype); };\nexports.new_NDArray = new_NDArray;\nfunction asarray(A) {\n if (isarray(A))\n return A;\n else\n return np.fromlist(A);\n}\nexports.asarray = asarray;\nfunction array(A) {\n if (isarray(A)) { // shallow copy of A\n var flat = A._simpleIndexes == null ? __spreadArray([], __read(A.flat), false) : A.flat;\n return (0, exports.new_NDArray)(flat, A.shape, A.dtype);\n }\n else\n return asarray(A);\n}\nexports.array = array;\n","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.copy = exports.empty = exports.new_from = exports.ravel = exports.reshape = exports.parse_shape = exports.shape_shifts = exports.as_number = exports.as_boolean = exports.number_collapse = exports._NDArray = exports.new_NDArray = exports.array = exports.asarray = exports.isarray = void 0;\nvar _globals_1 = require(\"./_globals\");\nObject.defineProperty(exports, \"isarray\", { enumerable: true, get: function () { return _globals_1.isarray; } });\nObject.defineProperty(exports, \"asarray\", { enumerable: true, get: function () { return _globals_1.asarray; } });\nObject.defineProperty(exports, \"array\", { enumerable: true, get: function () { return _globals_1.array; } });\nObject.defineProperty(exports, \"new_NDArray\", { enumerable: true, get: function () { return _globals_1.new_NDArray; } });\nObject.defineProperty(exports, \"_NDArray\", { enumerable: true, get: function () { return _globals_1._NDArray; } });\n// Functions to avoid importing NDArray (because if I import NDArray, I can't use it as a type annotation in the same file)\n/**\n * If the array is 0D, it returns it's unique element (number or boolean).\n * The signature is kept as NDArray for type consistency, even though the\n * output is a number or a boolean. This is consistent with the facts that\n * (1) all functions requiring arrays work with numbers as well because they call asarray,\n * and (2) semantically, a constant is an array.\n */\nfunction number_collapse(arr, expect) {\n if (expect === void 0) { expect = false; }\n if (!arr.shape.length)\n return arr.flat[0];\n if (expect)\n throw new Error(\"Expected constant. Got array with shape \".concat(arr.shape));\n return arr;\n}\nexports.number_collapse = number_collapse;\nfunction as_boolean(obj) {\n if ((0, _globals_1.isarray)(obj))\n obj = number_collapse(obj, true);\n else if (typeof obj == 'string')\n throw new Error(\"'string' object can not be interpreted as boolean: \".concat(obj));\n return !!(0 + obj);\n}\nexports.as_boolean = as_boolean;\nfunction as_number(obj) {\n if ((0, _globals_1.isarray)(obj))\n obj = number_collapse(obj, true);\n else if (typeof obj == 'string')\n throw new Error(\"'string' object can not be interpreted as boolean: \".concat(obj));\n return parseFloat(obj);\n}\nexports.as_number = as_number;\n// ====================\n// Reshape and shape shifts for indexing\n// ====================\nfunction shape_shifts(shape) {\n // increasing one by one on a given axis is increasing by shifts[axis] in flat representation\n var shifts = Array.from({ length: shape.length }, function (_) { return 0; });\n shifts[shape.length - 1] = 1;\n for (var i = shape.length - 2; i >= 0; i--)\n shifts[i] = shifts[i + 1] * shape[i + 1];\n return shifts;\n}\nexports.shape_shifts = shape_shifts;\nfunction parse_shape(list) {\n if (typeof list == \"number\")\n return [list];\n if ((0, _globals_1.isarray)(list)) {\n if (list.shape.length > 1) {\n throw new Error(\"Expected flat list. Got array with shape \".concat(list.shape));\n }\n return list.flat;\n }\n if (Array.isArray(list))\n return list;\n throw new Error(\"Expected list. Got \".concat(list));\n}\nexports.parse_shape = parse_shape;\nfunction reshape(A, shape_or_first) {\n var more_shape = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n more_shape[_i - 2] = arguments[_i];\n }\n A = (0, _globals_1.asarray)(A);\n var shape;\n if (!more_shape.length)\n shape = parse_shape(shape_or_first);\n else\n shape = __spreadArray([shape_or_first], __read(more_shape), false).map(as_number);\n var n = A.size;\n // Find -1\n var inferredIndex = shape.indexOf(-1);\n if (inferredIndex !== -1) {\n var known = shape.filter(function (dim) { return dim !== -1; }).reduce(function (acc, val) { return acc * val; }, 1);\n if (n % known !== 0) {\n throw new Error(\"Invalid shape. The total number of elements must match the product of the known dimensions.\");\n }\n shape[inferredIndex] = n / known;\n }\n return (0, _globals_1.new_NDArray)(A.flat, shape, A.dtype);\n}\nexports.reshape = reshape;\n;\nfunction ravel(A) {\n A = (0, _globals_1.asarray)(A);\n return (0, _globals_1.new_NDArray)(A.flat, [A.size], A.dtype);\n}\nexports.ravel = ravel;\n;\n// ====================\n// Constructors\n// ====================\nfunction new_from(shape, f, dtype) {\n if (f === void 0) { f = undefined; }\n if (dtype === void 0) { dtype = Number; }\n shape = parse_shape(shape);\n var size = shape.reduce(function (a, b) { return a * b; }, 1);\n var flat = Array.from({ length: size }, f);\n return (0, _globals_1.new_NDArray)(flat, shape, dtype);\n}\nexports.new_from = new_from;\n;\nfunction empty(shape, dtype) {\n if (dtype === void 0) { dtype = Number; }\n return new_from(shape, function (_) { return undefined; }, dtype);\n}\nexports.empty = empty;\n;\nfunction copy(A) {\n return (0, _globals_1.new_NDArray)(__spreadArray([], __read(A.flat), false), A.shape, A.dtype);\n}\nexports.copy = copy;\n","\"use strict\";\n//@ts-check\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ops = exports.__make_elementwise = exports.logical_not = exports.bitwise_not = exports.round = exports.elementwise = void 0;\nvar basic_1 = require(\"./basic\");\n// Here, we declare only the core functions (those that are methods)\nfunction elementwise(A, func, dtype) {\n A = (0, basic_1.asarray)(A);\n return (0, basic_1.new_NDArray)(A.flat.map(func), A.shape, dtype);\n}\nexports.elementwise = elementwise;\nfunction round(A, decimals) {\n if (decimals === void 0) { decimals = 0; }\n if (decimals == 0)\n elementwise(A, Math.round, Number);\n return elementwise(A, function (x) { return parseFloat(x.toFixed(decimals)); }, Number);\n}\nexports.round = round;\n;\nfunction bitwise_not(A) {\n return elementwise(A, function (x) { return ~x; }, Number);\n}\nexports.bitwise_not = bitwise_not;\n;\nfunction logical_not(A) {\n return elementwise(A, function (x) { return !x; }, Boolean);\n}\nexports.logical_not = logical_not;\n;\nfunction __make_elementwise(func, dtype) {\n if (dtype === void 0) { dtype = Number; }\n return function (A) {\n return elementwise(A, func, dtype);\n };\n}\nexports.__make_elementwise = __make_elementwise;\nexports.ops = {\n sign: __make_elementwise(Math.sign),\n sqrt: __make_elementwise(Math.sqrt),\n square: __make_elementwise(function (a) { return a * a; }),\n abs: __make_elementwise(Math.abs),\n exp: __make_elementwise(Math.exp),\n log: __make_elementwise(Math.log),\n log2: __make_elementwise(Math.log2),\n log10: __make_elementwise(Math.log10),\n log1p: __make_elementwise(Math.log1p),\n sin: __make_elementwise(Math.sin),\n cos: __make_elementwise(Math.cos),\n tan: __make_elementwise(Math.tan),\n asin: __make_elementwise(Math.asin),\n acos: __make_elementwise(Math.acos),\n atan: __make_elementwise(Math.atan),\n atan2: __make_elementwise(Math.atan2),\n cosh: __make_elementwise(Math.cosh),\n sinh: __make_elementwise(Math.sinh),\n tanh: __make_elementwise(Math.tanh),\n acosh: __make_elementwise(Math.acosh),\n asinh: __make_elementwise(Math.asinh),\n atanh: __make_elementwise(Math.atanh),\n round: round,\n};\n","\"use strict\";\n//@ts-check\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.modules = void 0;\n// Import core-globals first!\nrequire(\"./_globals\");\nvar basic = require(\"./basic\");\nvar indexes = require(\"./indexes\");\nvar jsInterface = require(\"./js-interface\");\nvar elementwise = require(\"./elementwise\");\nvar print = require(\"./print\");\nvar reduce = require(\"./reduce\");\nvar operators = require(\"./operators\");\nvar transform = require(\"./transform\");\nexports.modules = {\n basic: basic,\n jsInterface: jsInterface,\n indexes: indexes,\n elementwise: elementwise,\n print: print,\n reduce: reduce,\n operators: operators,\n transform: transform,\n};\n","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AxisIndex = exports.__parse_sliceRange = exports.AxesIndex = exports.index = void 0;\n//@ts-check\nvar basic_1 = require(\"./basic\");\nfunction index(arr, where) {\n // This can result either in a value, a view, a copy.\n // The index is simple if there are only ranges, numbers, \":\" and at most one \"...\"\n // If index is simple, don't call \".indices\" and make view\n // If index is advanced, get indices and make copy\n var copy = Object.assign({ copy: false }, arr.__popKwArgs()).copy;\n if (!((0, basic_1.isarray)(arr)))\n throw new Error(\"Expected NDArray. Found \".concat(typeof arr, \": \").concat(arr));\n var axesIndex = AxesIndex.prototype.parse(arr.shape, where);\n if (axesIndex.isConstant) {\n var _a = __read(axesIndex.indices, 1), index_1 = _a[0];\n return arr.flat[index_1];\n }\n else if (axesIndex.isSimple) {\n var composition = __compose_simpleIndexes(arr._simpleIndexes, axesIndex);\n var out = (0, basic_1.new_NDArray)(arr._flat, axesIndex.shape, arr.dtype);\n out._simpleIndexes = composition;\n if (arr['__warnAssignments'])\n out['__warnAssignments'] = true;\n return copy ? out.copy() : out;\n }\n else {\n var src_flat_1 = arr.flat;\n var flat = axesIndex.indices.map(function (i) { return src_flat_1[i]; });\n var out = (0, basic_1.new_NDArray)(flat, axesIndex.shape, arr.dtype);\n if (!copy)\n out['__warnAssignments'] = true;\n return out;\n }\n}\nexports.index = index;\n// type SimpleIndexes = null | { size: number, ranges: { refSize: number, range: null | number | [number, number, number] }[], indices: null | number[] };\nvar AxesIndex = /** @class */ (function () {\n /**\n * @param {AxisIndex[]} axisIndexes\n */\n function AxesIndex(apparentShape, internalShape, axisIndexes) {\n this.shape = apparentShape;\n this.internalShape = internalShape;\n this.axisIndexes = axisIndexes;\n this._indices = null;\n this._size = null;\n this.isSimple = this.axisIndexes.map(function (idx) { return idx.isSimple; }).reduce(function (a, b) { return a && b; }, true);\n this.isConstant = this.axisIndexes.map(function (idx) { return idx.isConstant; }).reduce(function (a, b) { return a && b; }, true);\n }\n Object.defineProperty(AxesIndex.prototype, \"indices\", {\n get: function () {\n if (this._indices)\n return this._indices;\n var indices = __slices_to_indices(this.internalShape, this.__slices);\n return this._indices = indices;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(AxesIndex.prototype, \"__slices\", {\n get: function () {\n return this.axisIndexes.map(function (idx) { return idx.indices; });\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(AxesIndex.prototype, \"size\", {\n get: function () {\n if (this._size)\n return this._size;\n return this._size = this.axisIndexes.map(function (idx) { return idx.size; }).reduce(function (a, b) { return a * b; }, 0);\n },\n enumerable: false,\n configurable: true\n });\n return AxesIndex;\n}());\nexports.AxesIndex = AxesIndex;\nfunction __compose_simpleIndexes(first, second) {\n if (first == null)\n return second;\n var axisIndexes = [];\n // console.log({ first, second })\n var j = 0;\n for (var i = 0; i < first.axisIndexes.length; i++) {\n var specA = first.axisIndexes[i].spec;\n var specB = second.axisIndexes[j].spec;\n if (specA.type == \"array\")\n throw new Error(\"Expected simple index. Found advanced: \".concat(specA.type));\n if (specB.type == \"array\")\n throw new Error(\"Expected simple index. Found advanced: \".concat(specB.type));\n var /**@type {AxisIndexSpec} */ spec = void 0;\n if (specA.type == \"number\")\n spec = specA;\n else {\n j++;\n if (specA.type == \":\")\n spec = specB;\n else if (specB.type == \":\")\n spec = specA;\n else {\n var _a = specA.range, startA = _a.start, stepA = _a.step, nStepsA = _a.nSteps;\n if (specB.type == \"number\") {\n var index_2 = specB.index;\n if (index_2 < 0)\n index_2 = nStepsA + index_2;\n if (index_2 < 0 || index_2 >= nStepsA)\n throw new Error(\"Index \".concat(index_2, \" out of bounds [0..\").concat(nStepsA, \")\"));\n index_2 = startA + index_2 * stepA;\n spec = { type: \"number\", index: index_2 };\n }\n else {\n var _b = specB.range, startB = _b.start, stepB = _b.step, nStepsB = _b.nSteps;\n var sub = AxisIndex.prototype.parse_range(nStepsA, startB, startB + nStepsB * stepB, stepB);\n var step = sub.step * stepA;\n var start = startA + sub.start * step;\n var nSteps = sub.nSteps;\n spec = { type: \"range\", range: { start: start, step: step, nSteps: nSteps } };\n }\n }\n }\n axisIndexes.push(new AxisIndex(spec));\n }\n if (j < second.axisIndexes.length)\n throw new Error(\"Index too long. Expected \".concat(j, \" axes. Found \").concat(second.axisIndexes.length));\n var apparentShape = second.shape;\n var internalShape = first.internalShape;\n return new AxesIndex(apparentShape, internalShape, axisIndexes);\n}\n/**\n * Computes the indices wr to shape of the cartesian products of the slices.\n * We have shape.length==slices.length, and the elements in slices[axis] are\n * integers between 0 and shape[axis]-1\n * @param {number[]} shape\n * @param {number[][]} slices\n * @returns {number[]}\n */\nfunction __slices_to_indices(shape, slices) {\n var e_1, _a;\n try {\n for (var slices_1 = __values(slices), slices_1_1 = slices_1.next(); !slices_1_1.done; slices_1_1 = slices_1.next()) {\n var slice = slices_1_1.value;\n if (slice.length == 0)\n return [];\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (slices_1_1 && !slices_1_1.done && (_a = slices_1.return)) _a.call(slices_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n var shifts = (0, basic_1.shape_shifts)(shape);\n var iShifts = slices.map(function (indices, axis) {\n // out[i] = How much does the cursor increase if we change from [...,indices[i],...] to [...,indices[(i+1)%n],...]\n var out = [], n = indices.length;\n for (var i = 0; i < n - 1; i++)\n out.push(shifts[axis] * (indices[i + 1] - indices[i]));\n out[n - 1] = shifts[axis] * (indices[0] - indices[n - 1]);\n return out;\n });\n var indices = [];\n var lastAxis = shape.length - 1;\n var tuple = new Array(shape.length).fill(0);\n var cursor = slices.map(function (l, i) { return l[tuple[i]] * shifts[i]; }).reduce(function (a, b) { return a + b; }, 0);\n while (true) {\n if (!isFinite(cursor))\n throw new Error(\"Programming error\");\n indices.push(cursor);\n var axis = lastAxis;\n while (axis >= 0) {\n cursor += iShifts[axis][tuple[axis]++];\n if (tuple[axis] < iShifts[axis].length)\n break;\n tuple[axis--] = 0; // Overflow\n }\n ;\n if (axis < 0)\n break;\n }\n return indices;\n}\n// =========================================\n// Slicing\n// =========================================\nfunction __parse_sliceRange(axis_size, _a) {\n var start = _a.start, stop = _a.stop, step = _a.step;\n if (start == null)\n start = 0;\n else if (start < 0)\n start = axis_size + start;\n if (stop == null)\n stop = axis_size;\n else if (stop < 0)\n stop = axis_size + stop;\n if (step == null)\n step = 1;\n else if (step == 0)\n throw new Error(\"Slice range with step size of zero\");\n if (!isFinite(start) || !isFinite(stop) || !isFinite(step))\n throw new Error(\"Invalid slice \".concat([start, stop, step], \". Axis size \").concat(axis_size));\n var indices = [];\n if (step > 0) {\n start = Math.max(start, 0);\n stop = Math.min(stop, axis_size);\n for (var i = start; i < stop; i += step)\n indices.push(i);\n }\n else {\n stop = Math.max(stop, 0);\n start = Math.min(start, axis_size);\n for (var i = start; i > stop; i += step)\n indices.push(i);\n }\n return indices;\n}\nexports.__parse_sliceRange = __parse_sliceRange;\nvar AxisIndex = /** @class */ (function () {\n /**\n * Invariant: Immutable\n * @param {AxisIndexSpec} spec\n */\n function AxisIndex(spec) {\n this.spec = spec;\n this._indices = null;\n this.isSimple = (this.spec.type != \"array\");\n this.isConstant = (this.spec.type == \"number\");\n }\n Object.defineProperty(AxisIndex.prototype, \"indices\", {\n get: function () {\n if (this._indices)\n return this._indices;\n var indices;\n if (this.spec.type == ':')\n indices = Array.from({ length: this.spec.size }, function (_, i) { return i; });\n else if (this.spec.type === \"number\")\n indices = [this.spec.index];\n else if (this.spec.type === \"array\")\n indices = this.spec.indices;\n else if (this.spec.type == \"range\") {\n var _a = this.spec.range, nSteps = _a.nSteps, step_1 = _a.step, start_1 = _a.start;\n indices = Array.from({ length: nSteps }, function (_, i) { return start_1 + i * step_1; });\n }\n else\n throw new Error(\"Unknown spec type \".concat(this.spec['type']));\n return this._indices = indices;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(AxisIndex.prototype, \"size\", {\n get: function () {\n if (this.spec.type == ':')\n return this.spec.size;\n else if (this.spec.type === \"number\")\n return 1;\n else if (this.spec.type === \"array\")\n return this.spec.indices.length;\n else if (this.spec.type == \"range\")\n return this.spec.range.nSteps;\n else\n throw new Error(\"Unknown spec type \".concat(this.spec['type']));\n },\n enumerable: false,\n configurable: true\n });\n return AxisIndex;\n}());\nexports.AxisIndex = AxisIndex;\nAxisIndex.prototype.parse_range = function (size, start, stop, step) {\n if (start === void 0) { start = null; }\n if (stop === void 0) { stop = null; }\n if (step === void 0) { step = null; }\n if (step == null)\n step = 1;\n else if (step == 0)\n throw new Error(\"Index specification error. Step must be different from zero.\");\n /**\n * @param {number|null} i @param {number} ifNull @param {number} min @param {number} max */\n var parse = function (i, ifNull, min, max) {\n if (i == null)\n return ifNull;\n if (i < 0)\n i = Math.max(0, size - i);\n return Math.min(max, Math.max(min, i));\n };\n var nSteps;\n if (step > 0)\n start = parse(start, 0, 0, size - 1), stop = parse(stop, size, 0, size);\n else\n start = parse(start, size - 1, 0, size - 1), stop = parse(stop, size - 1, -1, size - 1);\n stop = Math.max(stop, start);\n nSteps = Math.floor(Math.abs(stop - start) / step);\n return { start: start, step: step, nSteps: nSteps };\n};\n/**\n *\n * @param {string} rangeString\n * @returns {{start:(number|null), stop:(number|null), step:(number|null)}}\n */\nAxisIndex.prototype.parse_range_spec = function (rangeString) {\n var numbers = rangeString.split(':').map(function (s) {\n s = s.trim();\n if (s == \"\")\n return null;\n var n = parseInt(s);\n if (!Number.isInteger(n))\n throw new Error(\"Wrong input. Slice index unrecognized: \".concat(s));\n return n;\n });\n if (numbers.length == 0)\n throw new Error('Unexpected empty index. Expected colons.');\n if (numbers.length > 3)\n throw new Error(\"Too many colons in index \".concat(rangeString));\n var _a = __read(__spreadArray(__spreadArray([], __read(numbers), false), [null, null, null], false)), start = _a[0], stop = _a[1], step = _a[2], _ = _a.slice(3);\n return { start: start, stop: stop, step: step };\n};\n/**\n * We are reading `indexSpec` and `shape` in parallel, in the reading direction readDir.\n * With respect to `shape` we are at the given `axis`.\n * With respect to `indexSpec`, we found `indexSpec`, which we should process.\n * @param {indexSpec|undefined} indexSpec\n */\nAxisIndex.prototype.parse = function (indexSpec, size) {\n /**\n *\n * span (virtual shape) matches shape unless there are boolean masks spanning\n * over several axes/dimensions.\n * For example, in `np.ones((2,3,4,5))[:, np.arange(12).reshape((3,4))>5, 1]`,\n * the boolean mask is spanning over axes 1 and 2. In this case, the output should\n * merge these axes, resulting in an a vShape of (2, 12, 5).\n * The boolean mask is then converted to indices in the flattened merged axis.\n */\n /**@type {AxisIndexSpec} */\n var spec;\n var span = 1;\n if (indexSpec == ':' || indexSpec === undefined) {\n spec = { type: ':', size: size };\n }\n else if (typeof indexSpec === \"number\") {\n var index_3 = indexSpec;\n if (index_3 < 0)\n index_3 = size + index_3;\n if (index_3 < 0 || index_3 >= size)\n throw new Error(\"Index \".concat(index_3, \" out of bounds [0..\").concat(size, \")\"));\n spec = { type: 'number', index: index_3 };\n }\n else if ((0, basic_1.isarray)(indexSpec) || Array.isArray(indexSpec)) {\n var arr = (0, basic_1.asarray)(indexSpec);\n var indices_1;\n if (arr.dtype == Number) {\n // Array of indices\n if (arr.shape.length > 1)\n throw new Error(\"Expected 1D array of indices or nD array of booleans. \" +\n \"Found shape=\".concat(arr.shape, \" and dtype=\").concat(arr.dtype));\n indices_1 = arr.flat;\n }\n else {\n // Boolean mask\n indices_1 = [];\n arr.flat.forEach(function (if_value, i) { return if_value && indices_1.push(i); });\n // Next lines: the boolean mask spans over more than 1 axis\n span = Math.max(1, arr.shape.length);\n // Multiply the (possibly inverted) interval\n }\n spec = { type: 'array', indices: indices_1 };\n }\n else if (typeof indexSpec == \"string\") {\n var _a = AxisIndex.prototype.parse_range_spec(indexSpec), start = _a.start, stop_1 = _a.stop, step = _a.step;\n var range = AxisIndex.prototype.parse_range(size, start, stop_1, step);\n if (range.start == 0 && range.nSteps == size && range.step == 1) {\n // Small optimization: all of these are just \":\": [\"::\",\"0::1\", \":axisSize:\", etc.]\n spec = { type: ':', size: size };\n }\n else {\n spec = { type: 'range', range: range };\n }\n }\n else\n throw new Error(\"Unknown index type. Found \".concat(typeof indexSpec, \": \").concat(indexSpec));\n var axisIndex = new AxisIndex(spec);\n return { axisIndex: axisIndex, span: span };\n};\n/**\n * @param {Where} where\n * @returns {AxesIndex}\n */\nAxesIndex.prototype.parse = function (shape, where) {\n /**@type {Array}*/\n var _where = where == null ? [] : __spreadArray([], __read(where), false);\n var buffers = {\n axisIndexes: /**@type {AxisIndex[]}*/ ([]),\n apparentShape: /**@type {number[]}*/ ([]),\n internalShape: /**@type {number[]}*/ ([]),\n };\n var readDir = 1;\n var reversedAfter = { axisIndexes: NaN, apparentShape: NaN, internalShape: NaN };\n var axis = 0, j = 0, remainingAxes = shape.length, remainingWhere = _where.length;\n while (remainingWhere > 0 || remainingAxes > 0) {\n var axisWhere = _where[j];\n if (remainingWhere > 0) {\n if (j < 0 || j >= _where.length)\n axisWhere = \":\";\n remainingWhere--;\n //else _where[j] = undefined; // For ellipsis to avoid reading twice in opposite reading directions\n j += readDir;\n if (axisWhere == \"None\" || axisWhere === null) {\n buffers.apparentShape.push(1);\n continue;\n }\n else if (axisWhere == \"...\") {\n if (readDir == -1)\n throw new Error(\"Index can only have a single ellipsis. Found index(\".concat(where, \")\"));\n readDir = -1;\n for (var key in reversedAfter)\n reversedAfter[key] = buffers[key].length;\n j = _where.length - 1;\n axis = shape.length - 1;\n continue;\n }\n }\n else {\n axisWhere = \":\"; // If there are no more axes, fill with \":\"\n }\n // if (remainingAxes <= 0) throw Error(`Too many axes`);\n var _a = AxisIndex.prototype.parse(axisWhere, shape[axis]), axisIndex = _a.axisIndex, span = _a.span;\n // Advance the axis cursor span axes in readDir and compute the total size of consumed axes\n remainingAxes -= span;\n var refSize = 1;\n for (var i = 0; i < span; i++) {\n if (axis < 0 || axis >= shape.length)\n throw new Error(\"Index spans over more dimensions than available in shape [\".concat(shape, \"]: index(\").concat(where, \")\"));\n refSize *= shape[axis];\n axis += readDir;\n }\n buffers.axisIndexes.push(axisIndex);\n if (axisIndex.spec.type != \"number\")\n buffers.apparentShape.push(axisIndex.size);\n buffers.internalShape.push(refSize);\n }\n if (readDir == -1) { // reverse the right to left elements\n for (var key in buffers)\n buffers[key].splice(0, reversedAfter[key]).concat(buffers[key].reverse());\n }\n var axesIndex = new AxesIndex(buffers.apparentShape, buffers.internalShape, buffers.axisIndexes);\n return axesIndex;\n};\n","\"use strict\";\n//@ts-check\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.tolist = exports.fromlist = void 0;\nvar basic_1 = require(\"./basic\");\nfunction fromlist(arr, dtype) {\n if (dtype === void 0) { dtype = null; }\n if ((0, basic_1.isarray)(arr))\n return arr;\n if (typeof arr === \"number\")\n return (0, basic_1.new_NDArray)([arr], [], Number);\n if (typeof arr === \"boolean\")\n return (0, basic_1.new_NDArray)([arr ? 1 : 0], [], Boolean);\n if (arr === basic_1._NDArray.prototype)\n throw new Error(\"Programming error\");\n if (!Array.isArray(arr))\n throw new Error(\"Can't parse input of type \".concat(typeof arr, \": \").concat(arr));\n var shape = [];\n var root = arr;\n while (Array.isArray(root)) {\n shape.push(root.length);\n root = root[0];\n if (shape.length > 256)\n throw new Error(\"Circular reference or excessive array depth\");\n }\n dtype = dtype !== null ? dtype : typeof root === \"boolean\" ? Boolean : Number;\n var flat = [];\n var pushToFlat = function (arr, axis) {\n var e_1, _a, e_2, _b;\n // Check consistency\n if (axis == shape.length - 1) {\n try {\n for (var arr_1 = __values(arr), arr_1_1 = arr_1.next(); !arr_1_1.done; arr_1_1 = arr_1.next()) {\n var elem = arr_1_1.value;\n if (Array.isArray(elem))\n throw new Error(\"Inconsistent shape\");\n flat.push(elem);\n // Update dtype\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (arr_1_1 && !arr_1_1.done && (_a = arr_1.return)) _a.call(arr_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n else {\n if (!Array.isArray(arr))\n throw new Error(\"Inconsistent shape\");\n try {\n for (var arr_2 = __values(arr), arr_2_1 = arr_2.next(); !arr_2_1.done; arr_2_1 = arr_2.next()) {\n var sub = arr_2_1.value;\n if (sub.length != shape[axis + 1])\n throw new Error(\"Inconsistent shape: found sibling arrays of lengths \".concat(sub.length, \" and \").concat(shape[axis + 1]));\n pushToFlat(sub, axis + 1);\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (arr_2_1 && !arr_2_1.done && (_b = arr_2.return)) _b.call(arr_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n };\n pushToFlat(arr, 0);\n return (0, basic_1.new_NDArray)(flat, shape, dtype);\n}\nexports.fromlist = fromlist;\nfunction tolist(arr) {\n if ((0, basic_1.isarray)(this))\n return tolist;\n if (arr === null || typeof arr == \"number\" || typeof arr == \"boolean\")\n return arr;\n if (Array.isArray(arr))\n return arr.map(tolist);\n if (!((0, basic_1.isarray)(arr)))\n throw new Error(\"Expected MyArray. Got \".concat(typeof arr, \": \").concat(arr));\n arr = (0, basic_1.number_collapse)(arr);\n if (!((0, basic_1.isarray)(arr)))\n return arr;\n // let out = [], top;\n // let q = /**@type {[MyArray, any][]}*/([[arr, out]])\n // while (top = q.pop()) {\n // let [arr, out] = top;\n // if (arr.shape.length <= 1) {\n // out.push(...arr.flat);\n // } else {\n // for (let i = 0; i < arr.shape[0]; i++) {\n // let l = []\n // out.push(l);\n // q.push([arr.index(i), l]);\n // }\n // }\n // }\n // return out;\n function recursiveReshape(flatArr, shapeArr) {\n if (shapeArr.length === 0) {\n return flatArr.shift();\n }\n var innerShape = shapeArr.slice(1);\n var outerSize = shapeArr[0];\n var innerArray = [];\n for (var i = 0; i < outerSize; i++) {\n innerArray.push(recursiveReshape(flatArr, innerShape));\n }\n return innerArray;\n }\n var out = recursiveReshape(__spreadArray([], __read(arr.flat), false), arr.shape);\n return out;\n}\nexports.tolist = tolist;\n","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.allclose = exports.isclose = exports.op_assign = exports.__make_assignment_operator = exports._assign_operation_toJS = exports.assign_operation = exports.op_unary = exports.op_binary = exports.__make_operator_special = exports.__make_operator = exports._broadcast_shapes = exports.binary_operation = void 0;\n//@ts-check\nvar indexes = require(\"./indexes\");\nvar elementwise = require(\"./elementwise\");\nvar basic_1 = require(\"./basic\");\nvar js_interface_1 = require(\"./js-interface\");\nfunction binary_operation(A, B, func, dtype, out) {\n if (out === void 0) { out = null; }\n if ((0, basic_1.isarray)(this))\n return func.bind(basic_1._NDArray.prototype).apply(void 0, __spreadArray([this], __read(arguments), false));\n // Find output shape and input broadcast shapes\n A = (0, basic_1.asarray)(A);\n B = (0, basic_1.asarray)(B);\n var _a = __read(_broadcast_shapes(A.shape, B.shape), 3), shape = _a[0], shapeA = _a[1], shapeB = _a[2];\n if (out == null)\n out = (0, basic_1.new_from)(shape, function (_) { return undefined; }, dtype);\n else if (!((0, basic_1.isarray)(out)))\n throw new Error(\"Out must be of type \".concat(basic_1._NDArray, \". Got \").concat(typeof out));\n // Iterate with broadcasted indices\n var flatOut = [];\n var shiftsA = (0, basic_1.shape_shifts)(shapeA);\n var shiftsB = (0, basic_1.shape_shifts)(shapeB);\n var flatA = A.flat;\n var flatB = B.flat;\n for (var i = 0; i < out.size; i++) {\n var idxA = 0, idxB = 0, idx = i;\n for (var axis = shape.length - 1; axis >= 0; axis--) {\n idxA += shiftsA[axis] * (idx % shapeA[axis]);\n idxB += shiftsB[axis] * (idx % shapeB[axis]);\n idx = Math.floor(idx / shape[axis]);\n }\n flatOut.push(func(flatA[idxA], flatB[idxB]));\n }\n ;\n out.flat = flatOut;\n return (0, basic_1.number_collapse)(out);\n}\nexports.binary_operation = binary_operation;\nfunction _broadcast_shapes(shapeA, shapeB) {\n var shape = [];\n var maxDim = Math.max(shapeA.length, shapeB.length);\n shapeA = __spreadArray(__spreadArray([], __read(Array.from({ length: maxDim - shapeA.length }, function () { return 1; })), false), __read(shapeA), false);\n shapeB = __spreadArray(__spreadArray([], __read(Array.from({ length: maxDim - shapeB.length }, function () { return 1; })), false), __read(shapeB), false);\n for (var axis = maxDim - 1; axis >= 0; axis--) {\n var dim1 = shapeA[axis];\n var dim2 = shapeB[axis];\n if (dim1 !== 1 && dim2 !== 1 && dim1 !== dim2)\n throw new Error(\"Can not broadcast axis \".concat(axis, \" with sizes \").concat(dim1, \" and \").concat(dim2));\n shape.unshift(Math.max(dim1, dim2));\n }\n return [shape, shapeA, shapeB];\n}\nexports._broadcast_shapes = _broadcast_shapes;\nfunction __make_operator(dtype, func) {\n function operator(A, B, out) {\n if (out === void 0) { out = null; }\n if ((0, basic_1.isarray)(this))\n return operator.bind(basic_1._NDArray.prototype).apply(void 0, __spreadArray([this], __read(arguments), false));\n return binary_operation(A, B, func, dtype, out);\n }\n ;\n return operator;\n}\nexports.__make_operator = __make_operator;\nfunction __make_operator_special(funcNum, funcBool) {\n function operator(A, B, out) {\n if (out === void 0) { out = null; }\n if ((0, basic_1.isarray)(this))\n return operator.bind(basic_1._NDArray.prototype).apply(void 0, __spreadArray([this], __read(arguments), false));\n A = (0, basic_1.asarray)(A);\n B = (0, basic_1.asarray)(B);\n var dtype = A.dtype, func;\n if (A.dtype != B.dtype)\n console.warn(\"Warning: operating arrays of different dtypes. Using \".concat(dtype));\n if (dtype == Boolean)\n func = funcBool;\n else\n func = funcNum;\n return binary_operation(A, B, func, dtype, out);\n }\n ;\n return operator;\n}\nexports.__make_operator_special = __make_operator_special;\nexports.op_binary = {\n \"+\": __make_operator(Number, function (a, b) { return a + b; }),\n \"-\": __make_operator(Number, function (a, b) { return a - b; }),\n \"*\": __make_operator(Number, function (a, b) { return a * b; }),\n \"/\": __make_operator(Number, function (a, b) { return a / b; }),\n \"%\": __make_operator(Number, function (a, b) { return (a % b); }),\n \"//\": __make_operator(Number, function (a, b) { return Math.floor(a / b); }),\n \"**\": __make_operator(Number, function (a, b) { return Math.pow(a, b); }),\n \"<\": __make_operator(Boolean, function (a, b) { return a < b; }),\n \">\": __make_operator(Boolean, function (a, b) { return a > b; }),\n \">=\": __make_operator(Boolean, function (a, b) { return a >= b; }),\n \"<=\": __make_operator(Boolean, function (a, b) { return a <= b; }),\n \"==\": __make_operator(Boolean, function (a, b) { return a == b; }),\n \"!=\": __make_operator(Boolean, function (a, b) { return a != b; }),\n \"|\": __make_operator_special(function (a, b) { return a | b; }, function (a, b) { return a || b; }),\n \"&\": __make_operator_special(function (a, b) { return a & b; }, function (a, b) { return a && b; }),\n \"^\": __make_operator(Number, function (a, b) { return a ^ b; }),\n \"<<\": __make_operator(Number, function (a, b) { return a << b; }),\n \">>\": __make_operator(Number, function (a, b) { return a >> b; }),\n // Operators with custom ascii identifiers:\n \"or\": __make_operator(Boolean, function (a, b) { return a || b; }),\n \"and\": __make_operator(Boolean, function (a, b) { return a && b; }),\n \"xor\": __make_operator(Boolean, function (a, b) { return (!a) != (!b); }),\n \"max\": __make_operator(Number, function (a, b) { return Math.max(a, b); }),\n \"min\": __make_operator(Number, function (a, b) { return Math.min(a, b); }),\n // \"isclose\": ,\n};\nexports.op_binary[\"↑\"] = exports.op_binary[\"max\"];\nexports.op_binary[\"↓\"] = exports.op_binary[\"min\"];\nexports.op_binary[\"≤\"] = exports.op_binary[\"leq\"];\nexports.op_binary[\"≥\"] = exports.op_binary[\"geq\"];\nexports.op_binary[\"≠\"] = exports.op_binary[\"neq\"];\nexports.op_unary = {\n // Unary operators:\n \"~\": elementwise.bitwise_not,\n \"not\": elementwise.logical_not,\n \"+\": elementwise.__make_elementwise(function (x) { return x; }),\n \"-\": elementwise.__make_elementwise(function (x) { return -x; }, Number),\n};\nfunction assign_operation(tgt, src, where, func, dtype) {\n var e_1, _a;\n if (tgt['__warnAssignment']) {\n console.warn(\"Warning: You are assigning on a copy that resulted from an advanced index on a source array.\\nIf this is intentional, use yourArray = source.withKwArgs({copy:true}).index(...yourIndex) to make explicit your awareness of the copy operation.\\nInstead, if you want to assign to the source array, use source.op('=', other) or source.op(['::3', -1, '...', [5,4]], '*=', other).\\n\");\n delete tgt['__warnAssignment'];\n }\n if (!((0, basic_1.isarray)(tgt)))\n return _assign_operation_toJS(/**@type {*}*/ (tgt), src, where, func, dtype);\n if (!where) {\n binary_operation(tgt, src, func, dtype, tgt);\n }\n else {\n src = (0, basic_1.asarray)(src);\n var indices = indexes.AxesIndex.prototype.parse(tgt.shape, where).indices;\n var tmpTgt = void 0;\n if (func == null) {\n // Small optimization: unlike \"+=\", \"*=\", etc., for \"=\", we don't need to reed the target\n func = function (a, b) { return b; };\n tmpTgt = (0, basic_1.new_from)(indices.length, function () { return undefined; }, tgt.dtype);\n }\n else {\n tmpTgt = (0, basic_1.asarray)(indices.map(function (i) { return tgt._flat[i]; }));\n }\n binary_operation(tmpTgt, (0, basic_1.ravel)(src), func, dtype, tmpTgt);\n try {\n for (var indices_1 = __values(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {\n var i = indices_1_1.value;\n tgt._flat[i] = tmpTgt._flat[i];\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (indices_1_1 && !indices_1_1.done && (_a = indices_1.return)) _a.call(indices_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n}\nexports.assign_operation = assign_operation;\n;\nfunction _assign_operation_toJS(tgtJS, src, where, func, dtype) {\n if (!Array.isArray(tgtJS))\n throw new Error(\"Can not assign to a non-array. Found \".concat(typeof tgtJS, \": \").concat(tgtJS));\n console.warn('Assignment to JS array is experimental and slow.');\n // Parse the whole array\n var cpy = (0, basic_1.asarray)(tgtJS);\n assign_operation(cpy, src, where, func, dtype);\n // WARNING: Creates a copy. This is terrible for arr[2, 4, 3] = 5\n var outJS = (0, js_interface_1.tolist)(cpy);\n while (tgtJS.length)\n tgtJS.pop();\n // @ts-ignore\n tgtJS.push.apply(tgtJS, __spreadArray([], __read(outJS), false));\n}\nexports._assign_operation_toJS = _assign_operation_toJS;\nfunction __make_assignment_operator(dtype, func) {\n function operator() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n if ((0, basic_1.isarray)(this))\n return operator.bind(basic_1._NDArray.prototype).apply(void 0, __spreadArray([this], __read(args), false));\n if (args.length < 2)\n throw new Error(\"Not enough arguments for assignment operator\");\n if (args.length > 3)\n throw new Error(\"Too many arguments for assignment operator\");\n var tgt = args[0];\n var src = args[args.length == 3 ? 2 : 1];\n var where = args.length == 3 ? args[1] : null;\n return assign_operation(tgt, src, where, func, dtype);\n }\n return operator;\n}\nexports.__make_assignment_operator = __make_assignment_operator;\nexports.op_assign = {\n \"=\": __make_assignment_operator(Number, function (a, b) { return b; }),\n \"+=\": __make_assignment_operator(Number, function (a, b) { return a + b; }),\n \"-=\": __make_assignment_operator(Number, function (a, b) { return a - b; }),\n \"*=\": __make_assignment_operator(Number, function (a, b) { return a * b; }),\n \"/=\": __make_assignment_operator(Number, function (a, b) { return a / b; }),\n \"%=\": __make_assignment_operator(Number, function (a, b) { return (a % b); }),\n \"//=\": __make_assignment_operator(Number, function (a, b) { return Math.floor(a / b); }),\n \"**=\": __make_assignment_operator(Number, function (a, b) { return Math.pow(a, b); }),\n \"|=\": __make_assignment_operator(Number, function (a, b) { return a | b; }),\n \"&=\": __make_assignment_operator(Number, function (a, b) { return a & b; }),\n \"^=\": __make_assignment_operator(Number, function (a, b) { return a ^ b; }),\n \"<<=\": __make_assignment_operator(Number, function (a, b) { return a << b; }),\n \">>=\": __make_assignment_operator(Number, function (a, b) { return a >> b; }),\n // Operators with custom ascii identifiers:\n \"max=\": __make_assignment_operator(Number, function (a, b) { return Math.max(a, b); }),\n \"min=\": __make_assignment_operator(Number, function (a, b) { return Math.min(a, b); }),\n \"or=\": __make_assignment_operator(Boolean, function (a, b) { return a || b; }),\n \"and=\": __make_assignment_operator(Boolean, function (a, b) { return a && b; }),\n};\nexports.op_assign[\"↑=\"] = exports.op_assign[\"max=\"];\nexports.op_assign[\"↓=\"] = exports.op_assign[\"min=\"];\n// ====================================\nfunction isclose(A, B, rtol, atol, equal_nan) {\n var _a;\n if (rtol === void 0) { rtol = 1.e-5; }\n if (atol === void 0) { atol = 1.e-8; }\n if (equal_nan === void 0) { equal_nan = false; }\n (_a = Object.assign({ rtol: rtol, atol: atol, equal_nan: equal_nan }, this), rtol = _a.rtol, atol = _a.atol, equal_nan = _a.equal_nan);\n var func = function (a, b) {\n if (Number.isFinite(a) && Number.isFinite(b))\n return Math.abs(a - b) <= atol + rtol * b;\n return (a == b) || (equal_nan && Number.isNaN(a) && Number.isNaN(b));\n };\n return binary_operation(A, B, func, Boolean);\n}\nexports.isclose = isclose;\nfunction allclose(A, B, rtol, atol, equal_nan) {\n var _a;\n if (rtol === void 0) { rtol = 1.e-5; }\n if (atol === void 0) { atol = 1.e-8; }\n if (equal_nan === void 0) { equal_nan = false; }\n (_a = Object.assign({ rtol: rtol, atol: atol, equal_nan: equal_nan }, this), rtol = _a.rtol, atol = _a.atol, equal_nan = _a.equal_nan);\n // Equivalent to all(isclose(A, B, rtol, atol, equal_nan)), but shortcutting if false \n var func = function (a, b) {\n if (Number.isFinite(a) && Number.isFinite(b))\n return Math.abs(a - b) <= atol + rtol * b;\n return (a == b) || (equal_nan && Number.isNaN(a) && Number.isNaN(b));\n };\n var different = new Error('');\n var wrapper = function (a, b) {\n if (!func(a, b))\n throw different;\n return 0;\n };\n try {\n binary_operation(A, B, wrapper, Number);\n }\n catch (err) {\n if (err === different)\n return false;\n else\n throw err;\n }\n return true;\n}\nexports.allclose = allclose;\n//op_binary[\"≈≈\"] = op[MyArray.prototype.isclose,\n","\"use strict\";\n//@ts-check\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.humanReadable = void 0;\nvar elementwise_1 = require(\"./elementwise\");\nvar js_interface_1 = require(\"./js-interface\");\nfunction humanReadable(arr) {\n if (arr.shape.length == 0)\n return arr.flat[0].toString();\n var budgets = arr.shape.map(function (_) { return 1; });\n var lBudget = 30;\n for (var i = 0; i < arr.shape.length; i++) {\n var before = budgets[i];\n budgets[i] = Math.min(arr.shape[i], lBudget);\n if (budgets[i] > before)\n lBudget = Math.floor(lBudget / (budgets[i] - before));\n }\n var rBudget = 30;\n for (var i = arr.shape.length - 1; i >= 0; i--) {\n var before = budgets[i];\n budgets[i] = Math.min(arr.shape[i], rBudget);\n if (budgets[i] > before)\n rBudget = Math.floor(rBudget / (budgets[i] - before));\n }\n function simplify(list, depth) {\n if (depth === void 0) { depth = 0; }\n if (depth == arr.shape.length)\n return list;\n if (2 * budgets[depth] >= list.length) {\n return list.map(function (l) { return simplify(l, depth + 1); });\n }\n var left = list.slice(0, budgets[depth]).map(function (l) { return simplify(l, depth + 1); });\n var right = list.slice(-budgets[depth]).map(function (l) { return simplify(l, depth + 1); });\n return __spreadArray(__spreadArray(__spreadArray([], __read(left), false), ['...'], false), __read(right), false);\n }\n var rLimit = arr.shape.length - 1;\n while (rLimit > 0 && arr.shape[rLimit] == 1) {\n rLimit--;\n }\n if (arr.dtype == Number)\n arr = (0, elementwise_1.round)(arr, 2);\n var list = (0, js_interface_1.tolist)(arr);\n function str(list, indent, depth) {\n if (indent === void 0) { indent = 0; }\n if (depth === void 0) { depth = 0; }\n if (list == '...' || depth >= arr.shape.length)\n return list;\n if (depth == arr.shape.length - 1)\n return \"[\".concat(list.join(', '), \"]\");\n var sep = depth >= rLimit ? ' ' : '\\n' + ' '.repeat(indent + 1);\n var out = [];\n for (var i = 0; i < list.length; i++) {\n var s = str(list[i], indent + 1, depth + 1) + ',';\n out.push(i < list.length - 1 ? s : s.slice(0, -1));\n }\n return \"[\".concat(out.join(sep), \"]\");\n }\n var prefix = 'np';\n var suffix = \", shape=(\".concat(arr.shape, \"), dtype=\").concat(arr.dtype.name);\n var out = str(simplify(list), 1 + prefix.length);\n function alignColumns(inputString, delimiter) {\n var e_1, _a, e_2, _b;\n if (delimiter === void 0) { delimiter = ','; }\n // Split the input string into rows\n var rows = inputString.split('\\n');\n // Initialize an array to store the maximum width of each column\n var columnWidths = Array(rows[0].split(delimiter).length).fill(0);\n try {\n // Find the maximum width for each column\n for (var rows_1 = __values(rows), rows_1_1 = rows_1.next(); !rows_1_1.done; rows_1_1 = rows_1.next()) {\n var row = rows_1_1.value;\n var columns = row.split(delimiter);\n for (var i = 0; i < columns.length; i++) {\n columnWidths[i] = Math.max(columnWidths[i], columns[i].trim().length);\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (rows_1_1 && !rows_1_1.done && (_a = rows_1.return)) _a.call(rows_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // Build the formatted outputs\n var formattedString = '';\n var _loop_1 = function (row) {\n var columns = row.split(delimiter);\n columns = columns.map(function (s, i) { return i == columns.length - 1 ? s : s + delimiter; });\n for (var i = 0; i < columns.length; i++) {\n var column = columns[i].trim();\n formattedString += column.padStart(columnWidths[i] + 1).padEnd(columnWidths[i] + 2); // Add 1 for padding\n }\n formattedString += '\\n';\n };\n try {\n for (var rows_2 = __values(rows), rows_2_1 = rows_2.next(); !rows_2_1.done; rows_2_1 = rows_2.next()) {\n var row = rows_2_1.value;\n _loop_1(row);\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (rows_2_1 && !rows_2_1.done && (_b = rows_2.return)) _b.call(rows_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n return formattedString;\n }\n out = out.replace(/.*?(\\n|$)/g, function (match) {\n // Split with a newline every 0 characters, but only after a comma,\n return match.replace(/(.{60,}?,)/g, '$1\\n');\n }).replace(/\\n+/g, '\\n');\n out = alignColumns(\"\".concat(prefix, \"(\").concat(out)).trim();\n out = \"\".concat(out).concat(suffix, \")\");\n return out;\n}\nexports.humanReadable = humanReadable;\n","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.reducers = exports.reduce = void 0;\n//@ts-check\nvar basic_1 = require(\"./basic\");\nvar operators_1 = require(\"./operators\");\n// ==============================\n// Reducing functions\n// ==============================\nfunction reduce(arr, axis, keepdims, reducer, dtype) {\n if (dtype === void 0) { dtype = Number; }\n keepdims = (0, basic_1.as_boolean)(keepdims);\n // console.log({ arr })\n arr = (0, basic_1.asarray)(arr);\n if (axis == null)\n return reducer(arr.flat);\n if (axis < 0)\n axis = arr.shape.length - 1;\n var m = arr.shape[axis];\n var shift = (0, basic_1.shape_shifts)(arr.shape)[axis];\n var groups = Array.from({ length: m }, function (_) { /**@type {number[]}*/ return ([]); });\n arr.flat.forEach(function (value, i) { return groups[(Math.floor(i / shift)) % m].push(value); });\n // Transpose it:\n var nCols = arr.size / m;\n var groupsT = [];\n for (var j = 0; j < nCols; j++) {\n var newRow = [];\n for (var i = 0; i < m; i++)\n newRow.push(groups[i][j]);\n groupsT.push(newRow);\n }\n var flat = groupsT.map(reducer);\n var shape = __spreadArray([], __read(arr.shape), false);\n if (keepdims)\n shape[axis] = 1;\n else\n shape = shape.filter(function (_, i) { return i != axis; });\n var out = (0, basic_1.new_NDArray)(flat, shape, dtype);\n return (0, basic_1.number_collapse)(out);\n}\nexports.reduce = reduce;\n;\nfunction __make_reducer(dtype, reducer) {\n return function (arr, axis, keepdims) {\n var _a, _b, _c;\n if (axis === void 0) { axis = null; }\n if (keepdims === void 0) { keepdims = false; }\n // Parse kwargs from right to left to overwrite (right has priority)\n if (keepdims instanceof Object)\n (_a = Object.assign({ axis: axis, keepdims: keepdims }, keepdims), axis = _a.axis, keepdims = _a.keepdims);\n if (axis instanceof Object)\n (_b = Object.assign({ axis: axis, keepdims: keepdims }, axis), axis = _b.axis, keepdims = _b.keepdims);\n (_c = Object.assign({ axis: axis, keepdims: keepdims }, this), axis = _c.axis, keepdims = _c.keepdims);\n return reduce(arr, axis, keepdims, reducer, dtype);\n };\n}\nexports.reducers = {\n sum: __make_reducer(Number, function (arr) { return arr.reduce(function (a, b) { return a + b; }, 0); }),\n product: __make_reducer(Number, function (arr) { return arr.reduce(function (a, b) { return a * b; }, 1); }),\n any: __make_reducer(Boolean, function (arr) {\n var e_1, _a;\n try {\n for (var arr_1 = __values(arr), arr_1_1 = arr_1.next(); !arr_1_1.done; arr_1_1 = arr_1.next()) {\n var x = arr_1_1.value;\n if (x)\n return true;\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (arr_1_1 && !arr_1_1.done && (_a = arr_1.return)) _a.call(arr_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return false;\n }),\n all: __make_reducer(Boolean, function (arr) {\n var e_2, _a;\n try {\n for (var arr_2 = __values(arr), arr_2_1 = arr_2.next(); !arr_2_1.done; arr_2_1 = arr_2.next()) {\n var x = arr_2_1.value;\n if (!x)\n return false;\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (arr_2_1 && !arr_2_1.done && (_a = arr_2.return)) _a.call(arr_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n return true;\n }),\n max: __make_reducer(Number, function (arr) { return Math.max.apply(Math, __spreadArray([], __read(arr), false)); }),\n min: __make_reducer(Number, function (arr) { return Math.min.apply(Math, __spreadArray([], __read(arr), false)); }),\n argmax: __make_reducer(Number, function (arr) { return arr.indexOf(Math.max.apply(Math, __spreadArray([], __read(arr), false))); }),\n argmin: __make_reducer(Number, function (arr) { return arr.indexOf(Math.min.apply(Math, __spreadArray([], __read(arr), false))); }),\n mean: __make_reducer(Number, function (arr) { return arr.reduce(function (a, b) { return a + b; }, 0) / arr.length; }),\n var: function (arr, axis, keepdims) {\n var _a;\n if (axis === void 0) { axis = null; }\n if (keepdims === void 0) { keepdims = false; }\n (_a = Object.assign({ axis: axis, keepdims: keepdims }, this), axis = _a.axis, keepdims = _a.keepdims);\n var arrMean = exports.reducers.mean.bind({ axis: axis, keepdims: true })(arr);\n arr = operators_1.op_binary[\"-\"](arr, arrMean);\n arr = operators_1.op_binary[\"*\"](arr, arr);\n return exports.reducers.mean.bind({ axis: axis, keepdims: keepdims })(arr);\n },\n std: function (arr, axis, keepdims) {\n var _a;\n if (axis === void 0) { axis = null; }\n if (keepdims === void 0) { keepdims = false; }\n (_a = Object.assign({ axis: axis, keepdims: keepdims }, this), axis = _a.axis, keepdims = _a.keepdims);\n var variance = exports.reducers.var.bind({ axis: axis, keepdims: keepdims })(arr);\n return operators_1.op_binary[\"**\"](variance, 0.5);\n },\n};\n","\"use strict\";\n//@ts-check\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.stack = exports.concatenate = exports.swapAxes = exports.transpose = exports.sort = exports.apply_along_axis = void 0;\nvar basic_1 = require(\"./basic\");\nvar js_interface_1 = require(\"./js-interface\");\nvar utils_js_1 = require(\"../utils-js\");\nfunction apply_along_axis(arr, axis, transform, dtype) {\n if (dtype === void 0) { dtype = Number; }\n arr = (0, basic_1.asarray)(arr);\n if (axis == null)\n return transform(arr.flat);\n var nDims = arr.shape.length;\n if (axis < 0)\n axis = nDims + axis;\n if (axis !== nDims - 1) {\n // Transpose to end, apply, and transpose back:\n var tmp_1 = swapAxes(arr, axis, -1);\n var out_1 = apply_along_axis(tmp_1, -1, transform, dtype);\n //@ts-ignore\n return swapAxes(out_1, axis, -1);\n }\n var m = arr.shape[axis];\n var shift = (0, basic_1.shape_shifts)(arr.shape)[axis];\n var groups = Array.from({ length: m }, function (_) { /**@type {number[]}*/ return ([]); });\n arr.flat.forEach(function (value, i) { return groups[(Math.floor(i / shift)) % m].push(value); });\n // Transpose it:\n var nCols = arr.size / m;\n var groupsT = [];\n for (var j = 0; j < nCols; j++) {\n var newRow = [];\n for (var i = 0; i < m; i++)\n newRow.push(groups[i][j]);\n groupsT.push(newRow);\n }\n var data = groupsT.map(transform);\n var tmp = (0, js_interface_1.fromlist)(data);\n var shape = __spreadArray(__spreadArray(__spreadArray([], __read(arr.shape.slice(0, axis)), false), __read(tmp.shape.slice(1)), false), __read(arr.shape.slice(axis + 1)), false);\n var out = (0, basic_1.new_NDArray)(tmp.flat, shape, dtype);\n return (0, basic_1.number_collapse)(out);\n}\nexports.apply_along_axis = apply_along_axis;\nfunction sort(A, axis) {\n if (axis === void 0) { axis = -1; }\n (axis = Object.assign({ axis: axis }, this).axis);\n return apply_along_axis(A, axis, function (arr) {\n var cpy = __spreadArray([], __read(arr), false);\n cpy.sort(function (a, b) { return a - b; });\n return cpy;\n }, A.dtype);\n}\nexports.sort = sort;\nfunction transpose(arr, axes) {\n if (axes === void 0) { axes = null; }\n (axes = Object.assign({ axes: axes }, this).axes);\n var nDims = arr.shape.length;\n if (axes == null)\n return transpose(arr, Array.from({ length: nDims }, function (_, i) { return i; }).reverse());\n if (axes.length !== nDims)\n throw new Error(\"Axes must have length \".concat(nDims, \". Found \").concat(axes.length));\n var inv = Array.from({ length: nDims }, function () { return -1; });\n for (var i = 0; i < nDims; i++) {\n if (axes[i] < 0 || axes[i] >= nDims)\n throw new Error(\"Expected axis in [0..\".concat(nDims, \"). Found \").concat(axes[i]));\n inv[axes[i]] = i;\n }\n for (var i = 0; i < nDims; i++)\n if (inv[i] == -1)\n throw new Error(\"Axes must contain all dimensions. [\".concat(axes.join(\", \"), \"] is missing \").concat(i, \".\"));\n var srcShifts = (0, basic_1.shape_shifts)(arr.shape);\n var shape = axes.map(function (j) { return arr.shape[j]; });\n var shifts = axes.map(function (j) { return srcShifts[j]; });\n // Copied from slice:\n var indices = [];\n var tuple = new Array(shape.length).fill(0);\n var cursor = 0;\n while (true) {\n if (!isFinite(cursor))\n throw new Error(\"Programming error\");\n indices.push(cursor);\n var axis = nDims - 1;\n while (axis >= 0) {\n tuple[axis]++;\n cursor += shifts[axis];\n if (tuple[axis] < shape[axis])\n break;\n // Overflow\n cursor -= shifts[axis] * shape[axis];\n tuple[axis] = 0;\n axis--;\n }\n ;\n if (axis < 0)\n break;\n }\n // Now, just copy the data:\n var src = arr.flat;\n return (0, basic_1.new_NDArray)(indices.map(function (i) { return src[i]; }), shape, arr.dtype);\n}\nexports.transpose = transpose;\nfunction swapAxes(arr, axisA, axisB) {\n arr = (0, basic_1.asarray)(arr);\n var nDims = arr.shape.length;\n if (axisA < 0)\n axisA = nDims + axisA;\n if (axisB < 0)\n axisB = nDims + axisB;\n var perm = Array.from({ length: nDims }, function (_, i) { return i; });\n perm[axisA] = axisB;\n perm[axisB] = axisA;\n return transpose(arr, perm);\n}\nexports.swapAxes = swapAxes;\nfunction concatenate(arrays, axis) {\n var e_1, _a;\n if (axis === void 0) { axis = null; }\n (axis = Object.assign({ axis: axis }, this).axis);\n if ((0, basic_1.isarray)(arrays))\n arrays = __spreadArray([], __read(arrays), false);\n arrays = arrays.map(basic_1.asarray);\n if (axis == null) {\n arrays = arrays.map(function (arr) { return (0, basic_1.ravel)(arr); });\n axis = 0;\n }\n if (!arrays.length)\n throw new Error(\"Expected at least two arrays\");\n var nDims = arrays[0].shape.length;\n if (axis < 0)\n axis = nDims + axis;\n var shapeIn = __spreadArray([], __read(arrays[0].shape), false);\n var flat = [];\n var shape = shapeIn.map(function (_, i) { return i == 0 ? 0 : shapeIn[i == axis ? 0 : i]; });\n try {\n for (var arrays_1 = __values(arrays), arrays_1_1 = arrays_1.next(); !arrays_1_1.done; arrays_1_1 = arrays_1.next()) {\n var arr = arrays_1_1.value;\n if (!(0, utils_js_1.allEq)(arr.shape.filter(function (_, i) { return i != axis; }), shapeIn.filter(function (_, i) { return i != axis; })))\n throw new Error(\"Inconsistent input shape \".concat(shapeIn, \" with respect to \").concat(arr.shape.map(function (v, i) { return i == axis ? '?' : v; })));\n shape[0] += arr.shape[axis];\n arr = axis == 0 ? arr : swapAxes(arr, axis, 0);\n flat.push.apply(flat, __spreadArray([], __read(arr.flat), false));\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (arrays_1_1 && !arrays_1_1.done && (_a = arrays_1.return)) _a.call(arrays_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // TO DO: infer or expect dtype here:\n var out = (0, basic_1.new_NDArray)(flat, shape, arrays[0].dtype);\n if (axis == 0)\n return out;\n else\n return swapAxes(out, axis, 0);\n}\nexports.concatenate = concatenate;\nfunction stack(arrays, axis) {\n var e_2, _a;\n if (axis === void 0) { axis = 0; }\n (axis = Object.assign({ axis: axis }, this).axis);\n if ((0, basic_1.isarray)(arrays))\n arrays = __spreadArray([], __read(arrays), false);\n if (!Array.isArray(arrays))\n throw new Error(\"Expected list of arrays. Found \".concat(typeof arrays));\n arrays = arrays.map(basic_1.asarray);\n if (!arrays.length)\n throw new Error(\"Expected at least two arrays\");\n var shapeIn = __spreadArray([], __read(arrays[0].shape), false);\n if (axis < 0)\n axis = shapeIn.length + 1 + axis;\n var shapeBroadcast = __spreadArray(__spreadArray(__spreadArray([], __read(shapeIn.slice(0, axis)), false), [1], false), __read(shapeIn.slice(axis)), false);\n var bArrays = [];\n try {\n for (var arrays_2 = __values(arrays), arrays_2_1 = arrays_2.next(); !arrays_2_1.done; arrays_2_1 = arrays_2.next()) {\n var arr = arrays_2_1.value;\n if (!(0, utils_js_1.allEq)(arr.shape, shapeIn))\n throw new Error(\"Inconsistent input shape \".concat(arr.shape, \" with respect to \").concat(arr.shape));\n bArrays.push((0, basic_1.reshape)(arr, shapeBroadcast));\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (arrays_2_1 && !arrays_2_1.done && (_a = arrays_2.return)) _a.call(arrays_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n return concatenate(bArrays, axis);\n}\nexports.stack = stack;\n","\"use strict\";\n//@ts-check\n/**\n * This file exists for the sole purpose splitting the class methods across multiple files\n * while preserving all features of intellisense or JSDoc without errors.\n * The main issue is that the implementation of the methods require NDArray very often.\n * It resolves circular dependencies by using a global variable imported in each module.\n * The main file must define `require('./core-globals').GLOBALS.NDArray = NDArray;` before\n * importing any of the files that use it.\n *\n * A template header for files importing NDArray from this file is given below.\n * DO NOT use `const NDArray = require(\"./core-globals\").GLOBALS.NDArray;`.\n * Use const {NDArray} = ... instead as indicated. (Intellisense stops working otherwise)\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GLOBALS = void 0;\n//@ts-ignore\nvar _np = null, _array = null;\nexports.GLOBALS = {\n NDArray: _array,\n np: _np,\n};\n","\"use strict\";\n//@ts-check\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.np = void 0;\nvar np = function (template) {\n var _a;\n var variables = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n variables[_i - 1] = arguments[_i];\n }\n var usage = 'Usage example: np`np.arange(10)+${5}` or np([0,1,2]).';\n if (typeof template == \"number\")\n return template;\n if (template instanceof np.NDArray)\n return template;\n if (!Array.isArray(template))\n throw new Error(\"Expected template or array. \".concat(usage));\n if (!template.length)\n throw new Error(\"Expected argument. \".concat(usage));\n if (typeof template[0] == \"string\") {\n if (variables.length + 1 != template.length)\n throw new Error(\"Wrong input. \".concat(usage));\n //@ts-ignore\n return (_a = np.modules.grammar).parse.apply(_a, __spreadArray([/**@type {*}*/ (template)], __read(variables), false));\n }\n else {\n if (variables.length)\n throw new Error(\"Wrong input. \".concat(usage));\n //@ts-ignore\n return np.asarray(template);\n }\n};\nexports.np = np;\n// ==============================\n// Define Global before importing any module\n// ==============================\nvar _globals_1 = require(\"./_globals\");\n_globals_1.GLOBALS.np = np;\n// ==============================\n// Define casting and core before importing any other module\n// ==============================\nvar NDArray_class_1 = require(\"./NDArray-class\");\nnp.NDArray = NDArray_class_1.default;\n// ==============================\n// Define core-related functions\n// ==============================\nvar tolist = NDArray_class_1.default.prototype.modules.jsInterface.tolist;\nnp.tolist = function (template) {\n var variables = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n variables[_i - 1] = arguments[_i];\n }\n return tolist(np.apply(void 0, __spreadArray([template], __read(variables), false)));\n};\nnp.fromlist = NDArray_class_1.default.prototype.modules.jsInterface.fromlist;\nnp.ravel = NDArray_class_1.default.prototype.modules.basic.ravel;\nnp.reshape = NDArray_class_1.default.prototype.modules.basic.reshape;\nnp.array = NDArray_class_1.default.prototype.modules.basic.array;\nnp.asarray = NDArray_class_1.default.prototype.modules.basic.asarray;\nvar reduce = NDArray_class_1.default.prototype.modules.reduce;\nnp.sum = reduce.reducers.sum;\nnp.product = reduce.reducers.product;\nnp.prod = np.product;\nnp.any = reduce.reducers.any;\nnp.all = reduce.reducers.all;\nnp.max = reduce.reducers.max;\nnp.min = reduce.reducers.min;\nnp.argmax = reduce.reducers.argmax;\nnp.argmin = reduce.reducers.argmin;\nnp.mean = reduce.reducers.mean;\nnp.var = reduce.reducers.var;\nnp.std = reduce.reducers.std;\nvar transform = NDArray_class_1.default.prototype.modules.transform;\nnp.transpose = transform.transpose;\nnp.apply_along_axis = transform.apply_along_axis;\nnp.sort = transform.sort;\nnp.concatenate = transform.concatenate;\nnp.stack = transform.stack;\nvar operators = NDArray_class_1.default.prototype.modules.operators;\nnp.add = operators.op_binary[\"+\"];\nnp.subtract = operators.op_binary[\"-\"];\nnp.multiply = operators.op_binary[\"*\"];\nnp.divide = operators.op_binary[\"/\"];\nnp.mod = operators.op_binary[\"%\"];\nnp.divide_int = operators.op_binary[\"//\"];\nnp.pow = operators.op_binary[\"**\"];\nnp.bitwise_or = operators.op_binary[\"|\"];\nnp.bitwise_and = operators.op_binary[\"&\"];\nnp.bitwise_xor = operators.op_binary[\"^\"];\nnp.bitwise_shift_left = operators.op_binary[\"<<\"];\nnp.bitwise_shift_right = operators.op_binary[\">>\"];\nnp.greater = operators.op_binary[\">\"];\nnp.less = operators.op_binary[\"<\"];\nnp.greater_equal = operators.op_binary[\">=\"];\nnp.less_equal = operators.op_binary[\"<=\"];\nnp.equal = operators.op_binary[\"==\"];\nnp.not_equal = operators.op_binary[\"!=\"];\nnp.maximum = operators.op_binary[\"↑\"];\nnp.minimum = operators.op_binary[\"↓\"];\nnp.logical_or = operators.op_binary[\"or\"];\nnp.logical_and = operators.op_binary[\"and\"];\nnp.bitwise_not = operators.op_unary[\"~\"];\nnp.logical_not = operators.op_unary[\"not\"];\nnp.allclose = operators.allclose;\nnp.isclose = operators.isclose;\nvar ew = NDArray_class_1.default.prototype.modules.elementwise;\nnp.sign = ew.ops.sign;\nnp.sqrt = ew.ops.sqrt;\nnp.square = ew.ops.square;\nnp.abs = ew.ops.abs;\nnp.exp = ew.ops.exp;\nnp.log = ew.ops.log;\nnp.log2 = ew.ops.log2;\nnp.log10 = ew.ops.log10;\nnp.log1p = ew.ops.log1p;\nnp.sin = ew.ops.sin;\nnp.cos = ew.ops.cos;\nnp.tan = ew.ops.tan;\nnp.asin = ew.ops.asin;\nnp.acos = ew.ops.acos;\nnp.atan = ew.ops.atan;\nnp.atan2 = ew.ops.atan2;\nnp.cosh = ew.ops.cosh;\nnp.sinh = ew.ops.sinh;\nnp.tanh = ew.ops.tanh;\nnp.acosh = ew.ops.acosh;\nnp.asinh = ew.ops.asinh;\nnp.atanh = ew.ops.atanh;\nnp.round = ew.ops.round;\n// ==============================\n// import np modules\n// ============================== \nvar modules_1 = require(\"./modules\");\nnp.modules = modules_1.modules;\nnp.empty = np.modules.constructors.empty;\nnp.zeros = np.modules.constructors.zeros;\nnp.ones = np.modules.constructors.ones;\nnp.arange = np.modules.constructors.arange;\nnp.linspace = np.modules.constructors.linspace;\nnp.geomspace = np.modules.constructors.geomspace;\nnp.random = np.modules.random;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.nd_modules = exports.np = void 0;\n//@ts-check\nvar _globals_1 = require(\"../_globals\");\nvar np = _globals_1.GLOBALS.np, _NDArray = _globals_1.GLOBALS.NDArray;\nexports.np = np;\nif (!np)\n throw new Error(\"Programming error: np not defined\");\nexports.nd_modules = _NDArray.prototype.modules;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.geomspace = exports.linspace = exports.arange = exports.ones = exports.zeros = exports.empty = void 0;\n//@ts-check\nvar NDArray_class_1 = require(\"../NDArray-class\");\nvar _a = NDArray_class_1.default.prototype.modules, basic = _a.basic, elementwise = _a.elementwise;\nfunction empty(shape, dtype) {\n if (dtype === void 0) { dtype = Number; }\n return basic.new_from(shape, undefined, dtype);\n}\nexports.empty = empty;\n;\nfunction zeros(shape, dtype) {\n if (dtype === void 0) { dtype = Number; }\n var c = dtype == Boolean ? false : 0;\n return basic.new_from(shape, function (_) { return c; }, dtype);\n}\nexports.zeros = zeros;\n;\nfunction ones(shape, dtype) {\n if (dtype === void 0) { dtype = Number; }\n var c = dtype == Boolean ? true : 1;\n return basic.new_from(shape, function (_) { return c; }, dtype);\n}\nexports.ones = ones;\n;\nfunction arange(arg0, arg1) {\n if (arg1 === void 0) { arg1 = null; }\n var start, end;\n if (arg1 === null)\n start = 0, end = arg0;\n else\n start = arg0, end = arg1;\n return basic.new_from(end - start, function (_, i) { return start + i; }, Number);\n}\nexports.arange = arange;\n;\nfunction linspace(start, stop, num, endpoint) {\n var _a;\n if (num === void 0) { num = 50; }\n if (endpoint === void 0) { endpoint = true; }\n (_a = Object.assign({ stop: stop, num: num, endpoint: endpoint }, this), stop = _a.stop, num = _a.num, endpoint = _a.endpoint);\n start = basic.as_number(start);\n stop = basic.as_number(stop);\n var n = (num - (endpoint ? 1 : 0));\n var arr = arange(num).multiply((stop - start) / n).add(start);\n return arr;\n}\nexports.linspace = linspace;\nfunction geomspace(start, stop, num, endpoint) {\n var _a;\n if (num === void 0) { num = 50; }\n if (endpoint === void 0) { endpoint = true; }\n (_a = Object.assign({ stop: stop, num: num, endpoint: endpoint }, this), stop = _a.stop, num = _a.num, endpoint = _a.endpoint);\n start = elementwise.ops.log(start);\n stop = elementwise.ops.log(stop);\n return elementwise.ops.exp(linspace(start, stop, num, endpoint));\n}\nexports.geomspace = geomspace;\n","\"use strict\";\nvar __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.parse = exports.__parser_pool = exports.__makeSemantics = exports.ohmGrammar = exports.grammar = void 0;\n//@ts-check\nvar _globals_1 = require(\"./_globals\");\nvar ohm = require(\"ohm-js\");\nexports.grammar = String.raw(templateObject_1 || (templateObject_1 = __makeTemplateObject([\"\\nArrayGrammar {\\n Instruction\\n = Variable \\\"[\\\" Slice \\\"]\\\" AssignSymbol ArithmeticLogicExp -- sliceAssignment\\n | ArithmeticLogicExp -- expression\\n \\n Variable\\n = \\\"#\\\" digit+ \\\"#\\\"\\n \\n AssignSymbol\\n =\\\"=\\\"|\\\"+=\\\"|\\\"-=\\\"|\\\"*=\\\"|\\\"/=\\\"|\\\"%=\\\"|\\\"&=\\\"|\\\"|=\\\"|\\\"^=\\\"|\\\"@=\\\"|\\\"**=\\\"|\\\"<<=\\\"|\\\">>=\\\"|\\\"//=\\\"|\\\"or=\\\"|\\\"and=\\\"|\\\"xor=\\\"|\\\"max=\\\"|\\\"min=\\\"\\n \\n /* Declaration in precedence order (weakest first) */\\n ArithmeticLogicExp = Precedence11\\n\\n /* https://docs.python.org/3/reference/expressions.html */\\n Operator11 = \\\"<\\\" | \\\"<=\\\" | \\\">\\\" | \\\">=\\\" | \\\"!=\\\" | \\\"==\\\"\\n Operator10 = \\\"|\\\"\\n Operator09 = \\\"^\\\"\\n Operator08 = \\\"&\\\"\\n Operator07 = \\\"<<\\\" | \\\">>\\\"\\n Operator06 = \\\"+\\\" | \\\"-\\\"\\n Operator05 = \\\"*\\\" | \\\"@\\\" | \\\"/\\\" | \\\"//\\\" | \\\"%\\\"\\n Operator04 = \\\"~\\\" /* Unary */\\n Operator03 = \\\"+\\\" | \\\"-\\\" /* Unary. Special treatment to prevent \\\"-1.3\\\" to be \\\"-(array of 1.3)\\\" */\\n Operator02 = \\\"**\\\"\\n /* Operator01 = \\\"x[index]\\\" | \\\"x[index:index]\\\" | \\\"x(arguments...)\\\" | \\\"x.attribute\\\" */\\n /* Operator00 = \\\"(expressions...)\\\" */\\n\\n Precedence11 = Precedence11 Operator11 Precedence10 | \\\"\\\" \\\"\\\" Precedence10\\n Precedence10 = Precedence10 Operator10 Precedence09 | \\\"\\\" \\\"\\\" Precedence09\\n Precedence09 = Precedence09 Operator09 Precedence08 | \\\"\\\" \\\"\\\" Precedence08\\n Precedence08 = Precedence08 Operator08 Precedence07 | \\\"\\\" \\\"\\\" Precedence07\\n Precedence07 = Precedence07 Operator07 Precedence06 | \\\"\\\" \\\"\\\" Precedence06\\n Precedence06 = Precedence06 Operator06 Precedence05 | \\\"\\\" \\\"\\\" Precedence05\\n Precedence05 = Precedence05 Operator05 Precedence04 | \\\"\\\" \\\"\\\" Precedence04\\n Precedence04 = \\\"\\\" Operator04 Precedence03 | \\\"\\\" \\\"\\\" Precedence03 /* Unary */\\n Precedence03 = \\\"\\\" Operator03 Precedence02 | \\\"\\\" \\\"\\\" Precedence02 /* Special */\\n Precedence02 = Precedence02 Operator02 Precedence03 | \\\"\\\" \\\"\\\" Precedence01\\n Precedence01 = Arr\\n \\n Parenthesis = \\\"(\\\" ArithmeticLogicExp \\\")\\\"\\n Arr\\n = Arr \\\".\\\" Name CallArgs -- method\\n | Arr \\\".\\\" Name -- attribute\\n | Arr \\\"[\\\" Slice \\\"]\\\" -- slice\\n | Parenthesis\\n | Name (\\\".\\\" Name)* CallArgs -- call\\n | number\\n | Variable\\n\\n Name (an identifier)\\n = (letter|\\\"_\\\") (letter|\\\"_\\\"|digit)*\\n\\n number (a number)\\n = (\\\"+\\\"|\\\"-\\\")? digit* \\\".\\\" digit+ \\\"E\\\" (\\\"+\\\"|\\\"-\\\")? \\\"digit+\\\"\\n | (\\\"+\\\"|\\\"-\\\")? digit* \\\".\\\" digit+ \\\"e\\\" (\\\"+\\\"|\\\"-\\\")? \\\"digit+\\\"\\n | (\\\"+\\\"|\\\"-\\\")? digit* \\\".\\\" digit+ \\\"\\\" \\\"\\\" \\\"\\\"\\n | (\\\"+\\\"|\\\"-\\\")? digit+ \\\"\\\" \\\"\\\" \\\"\\\" \\\"\\\" \\\"\\\"\\n \\n int (an integer) = \\\"\\\" digit+ | \\\"-\\\" digit+ | \\\"+\\\" digit+\\n\\n CallArgs // Using empty strings instead of separate rules\\n = \\\"(\\\" Args \\\",\\\" KwArgs \\\",\\\"? \\\")\\\"\\n | \\\"(\\\" Args \\\",\\\"? \\\"\\\" \\\"\\\" \\\")\\\"\\n | \\\"(\\\" \\\"\\\" \\\",\\\"? KwArgs \\\",\\\"? \\\")\\\"\\n | \\\"(\\\" \\\"\\\" \\\"\\\" \\\"\\\" \\\"\\\" \\\")\\\"\\n \\n Args = NonemptyListOf\\n KwArgs = NonemptyListOf\\n KwArg = Name \\\"=\\\" ArgValue\\n\\n ArgValue = Constant | JsArray | ArithmeticLogicExp | String\\n Constant = \\\"True\\\" | \\\"False\\\" | \\\"None\\\" | \\\"np.nan\\\" | \\\"np.inf\\\"\\n JsArray\\n = \\\"[\\\" ListOf \\\",\\\"? \\\"]\\\"\\n | \\\"(\\\" ListOf \\\",\\\"? \\\")\\\"\\n\\n String = \\\"'\\\" any* \\\"'\\\" | \\\"\\\"\\\" any* \\\"\\\"\\\"\\n \\n Slice = NonemptyListOf\\n SliceTerm\\n = SliceRange\\n | (\\\":\\\" | \\\"...\\\" | \\\"None\\\") -- constant\\n | JsArray\\n | ArithmeticLogicExp\\n \\n SliceRange\\n = int \\\":\\\" int \\\":\\\" int\\n | int \\\":\\\" int \\\"\\\" \\\"\\\"\\n | int \\\":\\\" \\\"\\\" \\\":\\\" int\\n | int \\\":\\\" \\\"\\\" \\\"\\\" \\\"\\\"\\n | \\\"\\\" \\\":\\\" int \\\":\\\" int\\n | \\\"\\\" \\\":\\\" int \\\"\\\" \\\"\\\"\\n | \\\"\\\" \\\":\\\" \\\"\\\" \\\":\\\" int\\n | \\\"\\\" \\\":\\\" \\\"\\\" \\\"\\\" \\\"\\\"\\n}\\n\"], [\"\\nArrayGrammar {\\n Instruction\\n = Variable \\\"[\\\" Slice \\\"]\\\" AssignSymbol ArithmeticLogicExp -- sliceAssignment\\n | ArithmeticLogicExp -- expression\\n \\n Variable\\n = \\\"#\\\" digit+ \\\"#\\\"\\n \\n AssignSymbol\\n =\\\"=\\\"|\\\"+=\\\"|\\\"-=\\\"|\\\"*=\\\"|\\\"/=\\\"|\\\"%=\\\"|\\\"&=\\\"|\\\"|=\\\"|\\\"^=\\\"|\\\"@=\\\"|\\\"**=\\\"|\\\"<<=\\\"|\\\">>=\\\"|\\\"//=\\\"|\\\"or=\\\"|\\\"and=\\\"|\\\"xor=\\\"|\\\"max=\\\"|\\\"min=\\\"\\n \\n /* Declaration in precedence order (weakest first) */\\n ArithmeticLogicExp = Precedence11\\n\\n /* https://docs.python.org/3/reference/expressions.html */\\n Operator11 = \\\"<\\\" | \\\"<=\\\" | \\\">\\\" | \\\">=\\\" | \\\"!=\\\" | \\\"==\\\"\\n Operator10 = \\\"|\\\"\\n Operator09 = \\\"^\\\"\\n Operator08 = \\\"&\\\"\\n Operator07 = \\\"<<\\\" | \\\">>\\\"\\n Operator06 = \\\"+\\\" | \\\"-\\\"\\n Operator05 = \\\"*\\\" | \\\"@\\\" | \\\"/\\\" | \\\"//\\\" | \\\"%\\\"\\n Operator04 = \\\"~\\\" /* Unary */\\n Operator03 = \\\"+\\\" | \\\"-\\\" /* Unary. Special treatment to prevent \\\"-1.3\\\" to be \\\"-(array of 1.3)\\\" */\\n Operator02 = \\\"**\\\"\\n /* Operator01 = \\\"x[index]\\\" | \\\"x[index:index]\\\" | \\\"x(arguments...)\\\" | \\\"x.attribute\\\" */\\n /* Operator00 = \\\"(expressions...)\\\" */\\n\\n Precedence11 = Precedence11 Operator11 Precedence10 | \\\"\\\" \\\"\\\" Precedence10\\n Precedence10 = Precedence10 Operator10 Precedence09 | \\\"\\\" \\\"\\\" Precedence09\\n Precedence09 = Precedence09 Operator09 Precedence08 | \\\"\\\" \\\"\\\" Precedence08\\n Precedence08 = Precedence08 Operator08 Precedence07 | \\\"\\\" \\\"\\\" Precedence07\\n Precedence07 = Precedence07 Operator07 Precedence06 | \\\"\\\" \\\"\\\" Precedence06\\n Precedence06 = Precedence06 Operator06 Precedence05 | \\\"\\\" \\\"\\\" Precedence05\\n Precedence05 = Precedence05 Operator05 Precedence04 | \\\"\\\" \\\"\\\" Precedence04\\n Precedence04 = \\\"\\\" Operator04 Precedence03 | \\\"\\\" \\\"\\\" Precedence03 /* Unary */\\n Precedence03 = \\\"\\\" Operator03 Precedence02 | \\\"\\\" \\\"\\\" Precedence02 /* Special */\\n Precedence02 = Precedence02 Operator02 Precedence03 | \\\"\\\" \\\"\\\" Precedence01\\n Precedence01 = Arr\\n \\n Parenthesis = \\\"(\\\" ArithmeticLogicExp \\\")\\\"\\n Arr\\n = Arr \\\".\\\" Name CallArgs -- method\\n | Arr \\\".\\\" Name -- attribute\\n | Arr \\\"[\\\" Slice \\\"]\\\" -- slice\\n | Parenthesis\\n | Name (\\\".\\\" Name)* CallArgs -- call\\n | number\\n | Variable\\n\\n Name (an identifier)\\n = (letter|\\\"_\\\") (letter|\\\"_\\\"|digit)*\\n\\n number (a number)\\n = (\\\"+\\\"|\\\"-\\\")? digit* \\\".\\\" digit+ \\\"E\\\" (\\\"+\\\"|\\\"-\\\")? \\\"digit+\\\"\\n | (\\\"+\\\"|\\\"-\\\")? digit* \\\".\\\" digit+ \\\"e\\\" (\\\"+\\\"|\\\"-\\\")? \\\"digit+\\\"\\n | (\\\"+\\\"|\\\"-\\\")? digit* \\\".\\\" digit+ \\\"\\\" \\\"\\\" \\\"\\\"\\n | (\\\"+\\\"|\\\"-\\\")? digit+ \\\"\\\" \\\"\\\" \\\"\\\" \\\"\\\" \\\"\\\"\\n \\n int (an integer) = \\\"\\\" digit+ | \\\"-\\\" digit+ | \\\"+\\\" digit+\\n\\n CallArgs // Using empty strings instead of separate rules\\n = \\\"(\\\" Args \\\",\\\" KwArgs \\\",\\\"? \\\")\\\"\\n | \\\"(\\\" Args \\\",\\\"? \\\"\\\" \\\"\\\" \\\")\\\"\\n | \\\"(\\\" \\\"\\\" \\\",\\\"? KwArgs \\\",\\\"? \\\")\\\"\\n | \\\"(\\\" \\\"\\\" \\\"\\\" \\\"\\\" \\\"\\\" \\\")\\\"\\n \\n Args = NonemptyListOf\\n KwArgs = NonemptyListOf\\n KwArg = Name \\\"=\\\" ArgValue\\n\\n ArgValue = Constant | JsArray | ArithmeticLogicExp | String\\n Constant = \\\"True\\\" | \\\"False\\\" | \\\"None\\\" | \\\"np.nan\\\" | \\\"np.inf\\\"\\n JsArray\\n = \\\"[\\\" ListOf \\\",\\\"? \\\"]\\\"\\n | \\\"(\\\" ListOf \\\",\\\"? \\\")\\\"\\n\\n String = \\\"\\\\'\\\" any* \\\"\\\\'\\\" | \\\"\\\\\\\"\\\" any* \\\"\\\\\\\"\\\"\\n \\n Slice = NonemptyListOf\\n SliceTerm\\n = SliceRange\\n | (\\\":\\\" | \\\"...\\\" | \\\"None\\\") -- constant\\n | JsArray\\n | ArithmeticLogicExp\\n \\n SliceRange\\n = int \\\":\\\" int \\\":\\\" int\\n | int \\\":\\\" int \\\"\\\" \\\"\\\"\\n | int \\\":\\\" \\\"\\\" \\\":\\\" int\\n | int \\\":\\\" \\\"\\\" \\\"\\\" \\\"\\\"\\n | \\\"\\\" \\\":\\\" int \\\":\\\" int\\n | \\\"\\\" \\\":\\\" int \\\"\\\" \\\"\\\"\\n | \\\"\\\" \\\":\\\" \\\"\\\" \\\":\\\" int\\n | \\\"\\\" \\\":\\\" \\\"\\\" \\\"\\\" \\\"\\\"\\n}\\n\"])));\nexports.ohmGrammar = ohm.grammar(exports.grammar);\nvar __makeSemantics = function () {\n var semanticVariables = [];\n var semantics = {\n Instruction_sliceAssignment: function ($tgt, _open, $where, _close, $symbol, $src) {\n var _tgt = $tgt.parse();\n var _src = $src.parse();\n var symbol = $symbol.sourceString;\n var where = $where.parse();\n var tgt = _globals_1.nd_modules.basic.asarray(_tgt);\n _globals_1.nd_modules.operators.op_assign[symbol](_tgt, where, _src);\n if (tgt !== _tgt) {\n // WARNING: Creates a copy. This is terrible for arr[2, 4, 3] = 5\n tgt = _globals_1.nd_modules.jsInterface.tolist(tgt);\n while (_tgt.length)\n _tgt.pop();\n // @ts-ignore\n _tgt.push.apply(_tgt, __spreadArray([], __read(_tgt), false));\n }\n return null;\n },\n Instruction_expression: function ($arr) {\n var arr = $arr.parse();\n if (typeof arr === \"number\")\n return arr;\n if (typeof arr === \"boolean\")\n return arr;\n if (Array.isArray(arr))\n return arr;\n if (_globals_1.nd_modules.basic.isarray(arr))\n arr = _globals_1.nd_modules.basic.number_collapse(arr);\n return arr;\n },\n Precedence11: BinaryOperation,\n Precedence10: BinaryOperation,\n Precedence09: BinaryOperation,\n Precedence08: BinaryOperation,\n Precedence07: BinaryOperation,\n Precedence06: BinaryOperation,\n Precedence05: BinaryOperation,\n Precedence04: UnaryOperation,\n Precedence03: UnaryOperation,\n Precedence02: BinaryOperation,\n number: function (arg1, arg2, arg3, arg4, arg5, arg6, arg7) {\n return parseFloat(this.sourceString);\n },\n Arr_slice: function ($arr, _open, $where, _close) {\n var arr = $arr.parse();\n var where = $where.parse();\n return arr.index.apply(arr, __spreadArray([], __read(where), false));\n },\n SliceTerm_constant: function ($x) {\n return $x.sourceString;\n },\n Arr_call: function ($name, $names, _, $callArgs) {\n var name = $name.sourceString + $names.sourceString;\n if (name.slice(0, 3) == \"np.\")\n name = name.slice(3);\n var func = name.split('.').reduce(function (obj, name) { return obj[name]; }, _globals_1.np);\n if (func === undefined)\n throw new Error(\"Unrecognized function \".concat(name));\n var _a = $callArgs.parse(), args = _a.args, kwArgs = _a.kwArgs;\n return func.bind(kwArgs).apply(void 0, __spreadArray([], __read(args), false));\n },\n Arr_method: function ($arr, _dot, $name, $callArgs) {\n var _a;\n var arr = $arr.parse();\n var name = $name.sourceString;\n var _b = $callArgs.parse(), args = _b.args, kwArgs = _b.kwArgs;\n if (arr[name] === undefined)\n throw new Error(\"Unrecognized method \".concat(name));\n return (_a = arr.withKwArgs(kwArgs))[name].apply(_a, __spreadArray([], __read(args), false));\n },\n Parenthesis: function (_, $arr, __) { return $arr.parse(); },\n Arr_attribute: function ($arr, _, $name) { return $arr.parse()[$name.sourceString]; },\n Variable: function (_, $i, __) {\n var i = parseInt($i.sourceString);\n var value = semanticVariables[i];\n var isListOfArrays = Array.isArray(value) && value.length && _globals_1.nd_modules.basic.isarray(value[0]);\n if (Array.isArray(value) && !isListOfArrays)\n value = _globals_1.nd_modules.basic.array(value);\n return value;\n },\n int: function ($sign, $value) {\n var value = parseInt($value.sourceString);\n if ($sign.sourceString == '-')\n return -value;\n else\n return value;\n },\n SliceRange: function ($start, _, $stop, __, $step) {\n return this.sourceString;\n },\n Constant: function ($x) {\n switch ($x.sourceString) {\n case \"True\": return true;\n case \"False\": return false;\n case \"None\": return null;\n case \"np.nan\": return Number.NaN;\n case \"np.inf\": return Number.POSITIVE_INFINITY;\n }\n throw new Error(\"Unrecognized constant \".concat($x.sourceString));\n },\n String: function (_open, $str, _close) {\n return $str.sourceString;\n },\n CallArgs: function (_open, $args, _comma, $kwArgs, _trailing, _close) {\n var args = $args.parse() || [];\n var entries = $kwArgs.parse() || [];\n var kwArgs = Object.fromEntries(entries.map(function (_a) {\n var _b = __read(_a, 2), k = _b[0], v = _b[1];\n // The following is needed because minus integer gets parsed as array.\n if (_globals_1.nd_modules.basic.isarray(v))\n v = _globals_1.nd_modules.basic.number_collapse(v);\n return [k, v];\n }));\n return { args: args, kwArgs: kwArgs };\n },\n KwArg: function ($key, _equals, $value) {\n var key = $key.sourceString;\n var value = $value.parse();\n return [key, value];\n },\n NonemptyListOf: function (first, _, more) {\n return __spreadArray([first], __read(more.children), false).map(function (c) { return c.parse(); });\n },\n JsArray: function (_open, $list, _trailing, _close) {\n var list = $list.parse();\n // Downcast arrays (needed because, e.g., for [-1, 3, -2], -1 and -2 are interpreted as MyArray rather than int)\n var tolist = _globals_1.nd_modules.jsInterface.tolist;\n for (var i in list)\n if (_globals_1.nd_modules.basic.isarray(list[i]))\n list[i] = tolist(list[i]);\n return list;\n },\n _terminal: function () { return null; },\n };\n function BinaryOperation($A, $symbol, $B) {\n var A = $A.parse();\n var B = $B.parse();\n var symbol = $symbol.sourceString;\n if (symbol == \"\" && A === null)\n return B;\n var op = _globals_1.nd_modules.operators.op_binary;\n return op[symbol](A, B);\n }\n function UnaryOperation(_, $symbol, $B) {\n var B = $B.parse();\n var symbol = $symbol.sourceString;\n if (symbol == \"\")\n return B;\n var op_unary = _globals_1.nd_modules.operators.op_unary;\n switch (symbol) {\n case \"+\": return op_unary[\"+\"](B);\n case \"-\": return op_unary[\"-\"](B);\n case \"~\": return op_unary[\"~\"](B);\n case \"!\": return op_unary[\"not\"](B);\n }\n throw new Error(\"Programming Error: \".concat(symbol));\n }\n var ohmSemantics = exports.ohmGrammar.createSemantics();\n ohmSemantics.addOperation('parse', semantics);\n /**\n * @param {TemplateStringsArray} template\n * @param {any[]} variables\n */\n function parse(template) {\n var variables = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n variables[_i - 1] = arguments[_i];\n }\n // Replace variables in template with #0# #1# #2#, ...\n var idx = 0;\n var template_with_placeholders = template.join('###').replace(/###/g, function () { return \"#\".concat(idx++, \"#\"); });\n semanticVariables.length = 0;\n semanticVariables.push.apply(semanticVariables, __spreadArray([], __read(variables), false));\n var match = exports.ohmGrammar.match(template_with_placeholders);\n if (!match.succeeded())\n throw new Error(match.message);\n return ohmSemantics(match).parse();\n }\n return { parse: parse, ohmSemantics: ohmSemantics, semantics: semantics, semanticVariables: semanticVariables, busy: 0 };\n};\nexports.__makeSemantics = __makeSemantics;\nexports.__parser_pool = [(0, exports.__makeSemantics)()];\n/**\n * @param {TemplateStringsArray} template\n * @param {any[]} variables\n */\nvar parse = function (template) {\n var variables = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n variables[_i - 1] = arguments[_i];\n }\n // Thread control, because the parser depends on semanticVariables,\n // but we don't want to waste CPU time recreating the parser on each call\n // No cleaning is done (we assume that the number of threads is negligible compared to the memory size)\n var pool = exports.__parser_pool;\n for (var i = 0; i < pool.length; i++) {\n var parser = pool[i];\n if (parser.busy++ == 0) {\n try {\n return parser.parse.apply(parser, __spreadArray([template], __read(variables), false));\n }\n finally {\n parser.busy = 0;\n }\n }\n if (i == pool.length)\n pool.push((0, exports.__makeSemantics)());\n }\n};\nexports.parse = parse;\nvar templateObject_1;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.modules = void 0;\n//@ts-check\nrequire(\"./_globals\");\nvar constructors = require(\"./constructors\");\nvar grammar = require(\"./grammar\");\nvar random = require(\"./random\");\nexports.modules = {\n constructors: constructors,\n grammar: grammar,\n random: random,\n};\n","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.shuffle = exports.shuffled = exports._shuffled = exports._shuffle = exports.normal = exports.randn = exports.__normal = exports.exponential = exports.uniform = exports.random = void 0;\n//@ts-check\nvar _globals_1 = require(\"./_globals\");\nfunction random(shape) {\n return _globals_1.nd_modules.basic.new_from(shape, function (_) { return Math.random(); }, Number);\n}\nexports.random = random;\n;\nfunction uniform(a, b, shape) {\n return random(shape).multiply(b - a).add(a);\n}\nexports.uniform = uniform;\n;\nfunction exponential(mean, shape) {\n return _globals_1.np.multiply(mean, _globals_1.np.subtract(0, _globals_1.np.log(random(shape))));\n}\nexports.exponential = exponential;\n;\n/** @param {number} n */\nfunction __normal(n) {\n var out = [];\n while (out.length < n) {\n var u = Math.random() * 2 - 1;\n var v = Math.random() * 2 - 1;\n var s = u * u + v * v;\n if (s >= 1)\n continue;\n var x = Math.sqrt(-2 * Math.log(s) / s) * u;\n var y = Math.sqrt(-2 * Math.log(s) / s) * v;\n out.push(x);\n out.push(y);\n }\n if (out.length > n)\n out.pop();\n return out;\n}\nexports.__normal = __normal;\nfunction randn(shape) {\n var flat = __normal(_globals_1.np.prod(shape));\n return new _globals_1.np.NDArray(flat, shape, Number);\n}\nexports.randn = randn;\n;\nfunction normal(mean, std, shape) {\n return _globals_1.np.add(mean, _globals_1.np.multiply(std, shape));\n}\nexports.normal = normal;\n;\n/** @param {any[]} list */\nfunction _shuffle(list) {\n var _a;\n // Fisher-Yates (aka Knuth) shuffle.\n // https://stackoverflow.com/a/2450976\n for (var i = list.length - 1; i >= 0; i--) {\n var j = Math.floor(Math.random() * (i + 1));\n _a = __read([list[j], list[i]], 2), list[i] = _a[0], list[j] = _a[1];\n }\n}\nexports._shuffle = _shuffle;\n/** @param {any[]} list */\nfunction _shuffled(list) {\n var out = __spreadArray([], __read(list), false);\n _shuffle(out);\n return out;\n}\nexports._shuffled = _shuffled;\n/** @param {NDArray} arr @returns {NDArray} */\nfunction shuffled(arr) {\n if (arr.shape.length == 0)\n return arr;\n if (arr.shape.length == 1) {\n var flat = _shuffled(arr.flat);\n return new _globals_1.np.NDArray(flat, arr.shape, arr.dtype);\n }\n var perm = _shuffled(Array.from({ length: arr.length }, function (_, i) { return i; }));\n var out = _globals_1.np.empty(arr.shape, arr.dtype);\n for (var i = 0; i < arr.length; i++)\n out.assign([i], arr.index(perm[i]));\n return out;\n}\nexports.shuffled = shuffled;\n/**\n * @param {NDArray} arr\n */\nfunction shuffle(arr) {\n arr.assign(shuffled(arr));\n}\nexports.shuffle = shuffle;\n","\"use strict\";\n//@ts-check\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.allClose = exports.allEq = exports.ravel = exports.binary_operation = void 0;\nfunction binary_operation(A, B, func) {\n // Pointwise check for equality for arbitrary js arrays (without broadcasting)\n var C = [];\n var q = [[A, B, C, 0]];\n var seen;\n while (true) {\n var _next = q.pop();\n if (!_next)\n return true;\n var _a = __read(_next, 4), a = _a[0], b = _a[1], c = _a[2], depth = _a[3];\n if (Array.isArray(a) && Array.isArray(b) && a.length == b.length) {\n for (var i in a) {\n var c_i = [];\n c.push(c_i);\n q.push([a[i], b[i], c_i, depth + 1]);\n }\n }\n else\n c.push(func(a, b));\n if (depth > 10000 && Array.isArray(a)) { // Activate circular reference detection\n // Checking only A suffices (the other will exhaust otherwise)\n seen = /**@type {any[]}*/ (seen || []);\n if (seen.includes(a))\n throw new Error(\"Circular reference found. \".concat(a));\n seen[depth - 10000] = a;\n }\n }\n}\nexports.binary_operation = binary_operation;\n;\nfunction ravel(A) {\n // Flatten js array\n var q = [[A, 0]], flat = [];\n var seen;\n var _loop_1 = function () {\n var _next = q.pop();\n if (!_next)\n return \"break\";\n var _a = __read(_next, 2), a = _a[0], depth = _a[1];\n if (depth > 10000 && Array.isArray(a)) { // Activate circular reference detection\n seen = /**@type {any[]}*/ (seen || []);\n if (seen.includes(a))\n throw new Error(\"Circular reference found. \".concat(a));\n seen[depth - 10000] = a;\n }\n if (Array.isArray(a)) {\n q.push.apply(q, __spreadArray([], __read(a.map(function (v) { return [v, depth + 1]; })), false));\n return \"continue\";\n }\n flat.push(a);\n };\n while (true) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n return flat;\n}\nexports.ravel = ravel;\n;\nfunction allEq(A, B, nan_equal) {\n if (nan_equal === void 0) { nan_equal = false; }\n var different = new Error('');\n var func = function (a, b) {\n if (a !== b && !(nan_equal && Number.isNaN(a) && Number.isNaN(b)))\n throw different;\n return 0;\n };\n try {\n binary_operation(A, B, func);\n }\n catch (err) {\n if (err === different)\n return false;\n else\n throw err;\n }\n return true;\n}\nexports.allEq = allEq;\n;\nfunction allClose(A, B, rtol, atol, nan_equal) {\n if (rtol === void 0) { rtol = 1.e-5; }\n if (atol === void 0) { atol = 1.e-8; }\n if (nan_equal === void 0) { nan_equal = false; }\n var func = function (a, b) {\n if (Number.isFinite(a) && Number.isFinite(b))\n return Math.abs(a - b) <= atol + rtol * Math.abs(b);\n return (a === b) || (nan_equal && Number.isNaN(a) && Number.isNaN(b));\n };\n var different = new Error('');\n var wrapper = function (a, b) {\n if (!func(a, b))\n throw different;\n return 0;\n };\n try {\n binary_operation(A, B, wrapper);\n }\n catch (err) {\n if (err === different)\n return false;\n else\n throw err;\n }\n return true;\n}\nexports.allClose = allClose;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n// --------------------------------------------------------------------\n\n// --------------------------------------------------------------------\n// Exports\n// --------------------------------------------------------------------\n\nfunction abstract(optMethodName) {\n const methodName = optMethodName || '';\n return function() {\n throw new Error(\n 'this method ' +\n methodName +\n ' is abstract! ' +\n '(it has no implementation in class ' +\n this.constructor.name +\n ')',\n );\n };\n}\n\nfunction assert(cond, message) {\n if (!cond) {\n throw new Error(message || 'Assertion failed');\n }\n}\n\n// Define a lazily-computed, non-enumerable property named `propName`\n// on the object `obj`. `getterFn` will be called to compute the value the\n// first time the property is accessed.\nfunction defineLazyProperty(obj, propName, getterFn) {\n let memo;\n Object.defineProperty(obj, propName, {\n get() {\n if (!memo) {\n memo = getterFn.call(this);\n }\n return memo;\n },\n });\n}\n\nfunction clone(obj) {\n if (obj) {\n return Object.assign({}, obj);\n }\n return obj;\n}\n\nfunction repeatFn(fn, n) {\n const arr = [];\n while (n-- > 0) {\n arr.push(fn());\n }\n return arr;\n}\n\nfunction repeatStr(str, n) {\n return new Array(n + 1).join(str);\n}\n\nfunction repeat(x, n) {\n return repeatFn(() => x, n);\n}\n\nfunction getDuplicates(array) {\n const duplicates = [];\n for (let idx = 0; idx < array.length; idx++) {\n const x = array[idx];\n if (array.lastIndexOf(x) !== idx && duplicates.indexOf(x) < 0) {\n duplicates.push(x);\n }\n }\n return duplicates;\n}\n\nfunction copyWithoutDuplicates(array) {\n const noDuplicates = [];\n array.forEach(entry => {\n if (noDuplicates.indexOf(entry) < 0) {\n noDuplicates.push(entry);\n }\n });\n return noDuplicates;\n}\n\nfunction isSyntactic(ruleName) {\n const firstChar = ruleName[0];\n return firstChar === firstChar.toUpperCase();\n}\n\nfunction isLexical(ruleName) {\n return !isSyntactic(ruleName);\n}\n\nfunction padLeft(str, len, optChar) {\n const ch = optChar || ' ';\n if (str.length < len) {\n return repeatStr(ch, len - str.length) + str;\n }\n return str;\n}\n\n// StringBuffer\n\nfunction StringBuffer() {\n this.strings = [];\n}\n\nStringBuffer.prototype.append = function(str) {\n this.strings.push(str);\n};\n\nStringBuffer.prototype.contents = function() {\n return this.strings.join('');\n};\n\nconst escapeUnicode = str => String.fromCodePoint(parseInt(str, 16));\n\nfunction unescapeCodePoint(s) {\n if (s.charAt(0) === '\\\\') {\n switch (s.charAt(1)) {\n case 'b':\n return '\\b';\n case 'f':\n return '\\f';\n case 'n':\n return '\\n';\n case 'r':\n return '\\r';\n case 't':\n return '\\t';\n case 'v':\n return '\\v';\n case 'x':\n return escapeUnicode(s.slice(2, 4));\n case 'u':\n return s.charAt(2) === '{' ?\n escapeUnicode(s.slice(3, -1)) :\n escapeUnicode(s.slice(2, 6));\n default:\n return s.charAt(1);\n }\n } else {\n return s;\n }\n}\n\n// Helper for producing a description of an unknown object in a safe way.\n// Especially useful for error messages where an unexpected type of object was encountered.\nfunction unexpectedObjToString(obj) {\n if (obj == null) {\n return String(obj);\n }\n const baseToString = Object.prototype.toString.call(obj);\n try {\n let typeName;\n if (obj.constructor && obj.constructor.name) {\n typeName = obj.constructor.name;\n } else if (baseToString.indexOf('[object ') === 0) {\n typeName = baseToString.slice(8, -1); // Extract e.g. \"Array\" from \"[object Array]\".\n } else {\n typeName = typeof obj;\n }\n return typeName + ': ' + JSON.stringify(String(obj));\n } catch (e) {\n return baseToString;\n }\n}\n\nvar common = /*#__PURE__*/Object.freeze({\n __proto__: null,\n abstract: abstract,\n assert: assert,\n defineLazyProperty: defineLazyProperty,\n clone: clone,\n repeatFn: repeatFn,\n repeatStr: repeatStr,\n repeat: repeat,\n getDuplicates: getDuplicates,\n copyWithoutDuplicates: copyWithoutDuplicates,\n isSyntactic: isSyntactic,\n isLexical: isLexical,\n padLeft: padLeft,\n StringBuffer: StringBuffer,\n unescapeCodePoint: unescapeCodePoint,\n unexpectedObjToString: unexpectedObjToString\n});\n\n// These are just categories that are used in ES5/ES2015.\n// The full list of Unicode categories is here: http://www.fileformat.info/info/unicode/category/index.htm.\nconst UnicodeCategories = {\n // Letters\n Lu: /\\p{Lu}/u,\n Ll: /\\p{Ll}/u,\n Lt: /\\p{Lt}/u,\n Lm: /\\p{Lm}/u,\n Lo: /\\p{Lo}/u,\n\n // Numbers\n Nl: /\\p{Nl}/u,\n Nd: /\\p{Nd}/u,\n\n // Marks\n Mn: /\\p{Mn}/u,\n Mc: /\\p{Mc}/u,\n\n // Punctuation, Connector\n Pc: /\\p{Pc}/u,\n\n // Separator, Space\n Zs: /\\p{Zs}/u,\n\n // These two are not real Unicode categories, but our useful for Ohm.\n // L is a combination of all the letter categories.\n // Ltmo is a combination of Lt, Lm, and Lo.\n L: /\\p{Letter}/u,\n Ltmo: /\\p{Lt}|\\p{Lm}|\\p{Lo}/u,\n};\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\n// General stuff\n\nclass PExpr {\n constructor() {\n if (this.constructor === PExpr) {\n throw new Error(\"PExpr cannot be instantiated -- it's abstract\");\n }\n }\n\n // Set the `source` property to the interval containing the source for this expression.\n withSource(interval) {\n if (interval) {\n this.source = interval.trimmed();\n }\n return this;\n }\n}\n\n// Any\n\nconst any = Object.create(PExpr.prototype);\n\n// End\n\nconst end = Object.create(PExpr.prototype);\n\n// Terminals\n\nclass Terminal extends PExpr {\n constructor(obj) {\n super();\n this.obj = obj;\n }\n}\n\n// Ranges\n\nclass Range extends PExpr {\n constructor(from, to) {\n super();\n this.from = from;\n this.to = to;\n // If either `from` or `to` is made up of multiple code units, then\n // the range should consume a full code point, not a single code unit.\n this.matchCodePoint = from.length > 1 || to.length > 1;\n }\n}\n\n// Parameters\n\nclass Param extends PExpr {\n constructor(index) {\n super();\n this.index = index;\n }\n}\n\n// Alternation\n\nclass Alt extends PExpr {\n constructor(terms) {\n super();\n this.terms = terms;\n }\n}\n\n// Extend is an implementation detail of rule extension\n\nclass Extend extends Alt {\n constructor(superGrammar, name, body) {\n const origBody = superGrammar.rules[name].body;\n super([body, origBody]);\n\n this.superGrammar = superGrammar;\n this.name = name;\n this.body = body;\n }\n}\n\n// Splice is an implementation detail of rule overriding with the `...` operator.\nclass Splice extends Alt {\n constructor(superGrammar, ruleName, beforeTerms, afterTerms) {\n const origBody = superGrammar.rules[ruleName].body;\n super([...beforeTerms, origBody, ...afterTerms]);\n\n this.superGrammar = superGrammar;\n this.ruleName = ruleName;\n this.expansionPos = beforeTerms.length;\n }\n}\n\n// Sequences\n\nclass Seq extends PExpr {\n constructor(factors) {\n super();\n this.factors = factors;\n }\n}\n\n// Iterators and optionals\n\nclass Iter extends PExpr {\n constructor(expr) {\n super();\n this.expr = expr;\n }\n}\n\nclass Star extends Iter {}\nclass Plus extends Iter {}\nclass Opt extends Iter {}\n\nStar.prototype.operator = '*';\nPlus.prototype.operator = '+';\nOpt.prototype.operator = '?';\n\nStar.prototype.minNumMatches = 0;\nPlus.prototype.minNumMatches = 1;\nOpt.prototype.minNumMatches = 0;\n\nStar.prototype.maxNumMatches = Number.POSITIVE_INFINITY;\nPlus.prototype.maxNumMatches = Number.POSITIVE_INFINITY;\nOpt.prototype.maxNumMatches = 1;\n\n// Predicates\n\nclass Not extends PExpr {\n constructor(expr) {\n super();\n this.expr = expr;\n }\n}\n\nclass Lookahead extends PExpr {\n constructor(expr) {\n super();\n this.expr = expr;\n }\n}\n\n// \"Lexification\"\n\nclass Lex extends PExpr {\n constructor(expr) {\n super();\n this.expr = expr;\n }\n}\n\n// Rule application\n\nclass Apply extends PExpr {\n constructor(ruleName, args = []) {\n super();\n this.ruleName = ruleName;\n this.args = args;\n }\n\n isSyntactic() {\n return isSyntactic(this.ruleName);\n }\n\n // This method just caches the result of `this.toString()` in a non-enumerable property.\n toMemoKey() {\n if (!this._memoKey) {\n Object.defineProperty(this, '_memoKey', {value: this.toString()});\n }\n return this._memoKey;\n }\n}\n\n// Unicode character\n\nclass UnicodeChar extends PExpr {\n constructor(category) {\n super();\n this.category = category;\n this.pattern = UnicodeCategories[category];\n }\n}\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nfunction createError(message, optInterval) {\n let e;\n if (optInterval) {\n e = new Error(optInterval.getLineAndColumnMessage() + message);\n e.shortMessage = message;\n e.interval = optInterval;\n } else {\n e = new Error(message);\n }\n return e;\n}\n\n// ----------------- errors about intervals -----------------\n\nfunction intervalSourcesDontMatch() {\n return createError(\"Interval sources don't match\");\n}\n\n// ----------------- errors about grammars -----------------\n\n// Grammar syntax error\n\nfunction grammarSyntaxError(matchFailure) {\n const e = new Error();\n Object.defineProperty(e, 'message', {\n enumerable: true,\n get() {\n return matchFailure.message;\n },\n });\n Object.defineProperty(e, 'shortMessage', {\n enumerable: true,\n get() {\n return 'Expected ' + matchFailure.getExpectedText();\n },\n });\n e.interval = matchFailure.getInterval();\n return e;\n}\n\n// Undeclared grammar\n\nfunction undeclaredGrammar(grammarName, namespace, interval) {\n const message = namespace ?\n `Grammar ${grammarName} is not declared in namespace '${namespace}'` :\n 'Undeclared grammar ' + grammarName;\n return createError(message, interval);\n}\n\n// Duplicate grammar declaration\n\nfunction duplicateGrammarDeclaration(grammar, namespace) {\n return createError('Grammar ' + grammar.name + ' is already declared in this namespace');\n}\n\nfunction grammarDoesNotSupportIncrementalParsing(grammar) {\n return createError(`Grammar '${grammar.name}' does not support incremental parsing`);\n}\n\n// ----------------- rules -----------------\n\n// Undeclared rule\n\nfunction undeclaredRule(ruleName, grammarName, optInterval) {\n return createError(\n 'Rule ' + ruleName + ' is not declared in grammar ' + grammarName,\n optInterval,\n );\n}\n\n// Cannot override undeclared rule\n\nfunction cannotOverrideUndeclaredRule(ruleName, grammarName, optSource) {\n return createError(\n 'Cannot override rule ' + ruleName + ' because it is not declared in ' + grammarName,\n optSource,\n );\n}\n\n// Cannot extend undeclared rule\n\nfunction cannotExtendUndeclaredRule(ruleName, grammarName, optSource) {\n return createError(\n 'Cannot extend rule ' + ruleName + ' because it is not declared in ' + grammarName,\n optSource,\n );\n}\n\n// Duplicate rule declaration\n\nfunction duplicateRuleDeclaration(ruleName, grammarName, declGrammarName, optSource) {\n let message =\n \"Duplicate declaration for rule '\" + ruleName + \"' in grammar '\" + grammarName + \"'\";\n if (grammarName !== declGrammarName) {\n message += \" (originally declared in '\" + declGrammarName + \"')\";\n }\n return createError(message, optSource);\n}\n\n// Wrong number of parameters\n\nfunction wrongNumberOfParameters(ruleName, expected, actual, source) {\n return createError(\n 'Wrong number of parameters for rule ' +\n ruleName +\n ' (expected ' +\n expected +\n ', got ' +\n actual +\n ')',\n source,\n );\n}\n\n// Wrong number of arguments\n\nfunction wrongNumberOfArguments(ruleName, expected, actual, expr) {\n return createError(\n 'Wrong number of arguments for rule ' +\n ruleName +\n ' (expected ' +\n expected +\n ', got ' +\n actual +\n ')',\n expr,\n );\n}\n\n// Duplicate parameter names\n\nfunction duplicateParameterNames(ruleName, duplicates, source) {\n return createError(\n 'Duplicate parameter names in rule ' + ruleName + ': ' + duplicates.join(', '),\n source,\n );\n}\n\n// Invalid parameter expression\n\nfunction invalidParameter(ruleName, expr) {\n return createError(\n 'Invalid parameter to rule ' +\n ruleName +\n ': ' +\n expr +\n ' has arity ' +\n expr.getArity() +\n ', but parameter expressions must have arity 1',\n expr.source,\n );\n}\n\n// Application of syntactic rule from lexical rule\n\nconst syntacticVsLexicalNote =\n 'NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. ' +\n 'See https://ohmjs.org/d/svl for more details.';\n\nfunction applicationOfSyntacticRuleFromLexicalContext(ruleName, applyExpr) {\n return createError(\n 'Cannot apply syntactic rule ' + ruleName + ' from here (inside a lexical context)',\n applyExpr.source,\n );\n}\n\n// Lexical rule application used with applySyntactic\n\nfunction applySyntacticWithLexicalRuleApplication(applyExpr) {\n const {ruleName} = applyExpr;\n return createError(\n `applySyntactic is for syntactic rules, but '${ruleName}' is a lexical rule. ` +\n syntacticVsLexicalNote,\n applyExpr.source,\n );\n}\n\n// Application of applySyntactic in a syntactic context\n\nfunction unnecessaryExperimentalApplySyntactic(applyExpr) {\n return createError(\n 'applySyntactic is not required here (in a syntactic context)',\n applyExpr.source,\n );\n}\n\n// Incorrect argument type\n\nfunction incorrectArgumentType(expectedType, expr) {\n return createError('Incorrect argument type: expected ' + expectedType, expr.source);\n}\n\n// Multiple instances of the super-splice operator (`...`) in the rule body.\n\nfunction multipleSuperSplices(expr) {\n return createError(\"'...' can appear at most once in a rule body\", expr.source);\n}\n\n// Unicode code point escapes\n\nfunction invalidCodePoint(applyWrapper) {\n const node = applyWrapper._node;\n assert(node && node.isNonterminal() && node.ctorName === 'escapeChar_unicodeCodePoint');\n\n // Get an interval that covers all of the hex digits.\n const digitIntervals = applyWrapper.children.slice(1, -1).map(d => d.source);\n const fullInterval = digitIntervals[0].coverageWith(...digitIntervals.slice(1));\n return createError(\n `U+${fullInterval.contents} is not a valid Unicode code point`,\n fullInterval,\n );\n}\n\n// ----------------- Kleene operators -----------------\n\nfunction kleeneExprHasNullableOperand(kleeneExpr, applicationStack) {\n const actuals =\n applicationStack.length > 0 ? applicationStack[applicationStack.length - 1].args : [];\n const expr = kleeneExpr.expr.substituteParams(actuals);\n let message =\n 'Nullable expression ' +\n expr +\n \" is not allowed inside '\" +\n kleeneExpr.operator +\n \"' (possible infinite loop)\";\n if (applicationStack.length > 0) {\n const stackTrace = applicationStack\n .map(app => new Apply(app.ruleName, app.args))\n .join('\\n');\n message += '\\nApplication stack (most recent application last):\\n' + stackTrace;\n }\n return createError(message, kleeneExpr.expr.source);\n}\n\n// ----------------- arity -----------------\n\nfunction inconsistentArity(ruleName, expected, actual, expr) {\n return createError(\n 'Rule ' +\n ruleName +\n ' involves an alternation which has inconsistent arity ' +\n '(expected ' +\n expected +\n ', got ' +\n actual +\n ')',\n expr.source,\n );\n}\n\n// ----------------- convenience -----------------\n\nfunction multipleErrors(errors) {\n const messages = errors.map(e => e.message);\n return createError(['Errors:'].concat(messages).join('\\n- '), errors[0].interval);\n}\n\n// ----------------- semantic -----------------\n\nfunction missingSemanticAction(ctorName, name, type, stack) {\n let stackTrace = stack\n .slice(0, -1)\n .map(info => {\n const ans = ' ' + info[0].name + ' > ' + info[1];\n return info.length === 3 ? ans + \" for '\" + info[2] + \"'\" : ans;\n })\n .join('\\n');\n stackTrace += '\\n ' + name + ' > ' + ctorName;\n\n let moreInfo = '';\n if (ctorName === '_iter') {\n moreInfo = [\n '\\nNOTE: as of Ohm v16, there is no default action for iteration nodes — see ',\n ' https://ohmjs.org/d/dsa for details.',\n ].join('\\n');\n }\n\n const message = [\n `Missing semantic action for '${ctorName}' in ${type} '${name}'.${moreInfo}`,\n 'Action stack (most recent call last):',\n stackTrace,\n ].join('\\n');\n\n const e = createError(message);\n e.name = 'missingSemanticAction';\n return e;\n}\n\nfunction throwErrors(errors) {\n if (errors.length === 1) {\n throw errors[0];\n }\n if (errors.length > 1) {\n throw multipleErrors(errors);\n }\n}\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\n// Given an array of numbers `arr`, return an array of the numbers as strings,\n// right-justified and padded to the same length.\nfunction padNumbersToEqualLength(arr) {\n let maxLen = 0;\n const strings = arr.map(n => {\n const str = n.toString();\n maxLen = Math.max(maxLen, str.length);\n return str;\n });\n return strings.map(s => padLeft(s, maxLen));\n}\n\n// Produce a new string that would be the result of copying the contents\n// of the string `src` onto `dest` at offset `offest`.\nfunction strcpy(dest, src, offset) {\n const origDestLen = dest.length;\n const start = dest.slice(0, offset);\n const end = dest.slice(offset + src.length);\n return (start + src + end).substr(0, origDestLen);\n}\n\n// Casts the underlying lineAndCol object to a formatted message string,\n// highlighting `ranges`.\nfunction lineAndColumnToMessage(...ranges) {\n const lineAndCol = this;\n const {offset} = lineAndCol;\n const {repeatStr} = common;\n\n const sb = new StringBuffer();\n sb.append('Line ' + lineAndCol.lineNum + ', col ' + lineAndCol.colNum + ':\\n');\n\n // An array of the previous, current, and next line numbers as strings of equal length.\n const lineNumbers = padNumbersToEqualLength([\n lineAndCol.prevLine == null ? 0 : lineAndCol.lineNum - 1,\n lineAndCol.lineNum,\n lineAndCol.nextLine == null ? 0 : lineAndCol.lineNum + 1,\n ]);\n\n // Helper for appending formatting input lines to the buffer.\n const appendLine = (num, content, prefix) => {\n sb.append(prefix + lineNumbers[num] + ' | ' + content + '\\n');\n };\n\n // Include the previous line for context if possible.\n if (lineAndCol.prevLine != null) {\n appendLine(0, lineAndCol.prevLine, ' ');\n }\n // Line that the error occurred on.\n appendLine(1, lineAndCol.line, '> ');\n\n // Build up the line that points to the offset and possible indicates one or more ranges.\n // Start with a blank line, and indicate each range by overlaying a string of `~` chars.\n const lineLen = lineAndCol.line.length;\n let indicationLine = repeatStr(' ', lineLen + 1);\n for (let i = 0; i < ranges.length; ++i) {\n let startIdx = ranges[i][0];\n let endIdx = ranges[i][1];\n assert(startIdx >= 0 && startIdx <= endIdx, 'range start must be >= 0 and <= end');\n\n const lineStartOffset = offset - lineAndCol.colNum + 1;\n startIdx = Math.max(0, startIdx - lineStartOffset);\n endIdx = Math.min(endIdx - lineStartOffset, lineLen);\n\n indicationLine = strcpy(indicationLine, repeatStr('~', endIdx - startIdx), startIdx);\n }\n const gutterWidth = 2 + lineNumbers[1].length + 3;\n sb.append(repeatStr(' ', gutterWidth));\n indicationLine = strcpy(indicationLine, '^', lineAndCol.colNum - 1);\n sb.append(indicationLine.replace(/ +$/, '') + '\\n');\n\n // Include the next line for context if possible.\n if (lineAndCol.nextLine != null) {\n appendLine(2, lineAndCol.nextLine, ' ');\n }\n return sb.contents();\n}\n\n// --------------------------------------------------------------------\n// Exports\n// --------------------------------------------------------------------\n\nlet builtInRulesCallbacks = [];\n\n// Since Grammar.BuiltInRules is bootstrapped, most of Ohm can't directly depend it.\n// This function allows modules that do depend on the built-in rules to register a callback\n// that will be called later in the initialization process.\nfunction awaitBuiltInRules(cb) {\n builtInRulesCallbacks.push(cb);\n}\n\nfunction announceBuiltInRules(grammar) {\n builtInRulesCallbacks.forEach(cb => {\n cb(grammar);\n });\n builtInRulesCallbacks = null;\n}\n\n// Return an object with the line and column information for the given\n// offset in `str`.\nfunction getLineAndColumn(str, offset) {\n let lineNum = 1;\n let colNum = 1;\n\n let currOffset = 0;\n let lineStartOffset = 0;\n\n let nextLine = null;\n let prevLine = null;\n let prevLineStartOffset = -1;\n\n while (currOffset < offset) {\n const c = str.charAt(currOffset++);\n if (c === '\\n') {\n lineNum++;\n colNum = 1;\n prevLineStartOffset = lineStartOffset;\n lineStartOffset = currOffset;\n } else if (c !== '\\r') {\n colNum++;\n }\n }\n\n // Find the end of the target line.\n let lineEndOffset = str.indexOf('\\n', lineStartOffset);\n if (lineEndOffset === -1) {\n lineEndOffset = str.length;\n } else {\n // Get the next line.\n const nextLineEndOffset = str.indexOf('\\n', lineEndOffset + 1);\n nextLine =\n nextLineEndOffset === -1 ?\n str.slice(lineEndOffset) :\n str.slice(lineEndOffset, nextLineEndOffset);\n // Strip leading and trailing EOL char(s).\n nextLine = nextLine.replace(/^\\r?\\n/, '').replace(/\\r$/, '');\n }\n\n // Get the previous line.\n if (prevLineStartOffset >= 0) {\n // Strip trailing EOL char(s).\n prevLine = str.slice(prevLineStartOffset, lineStartOffset).replace(/\\r?\\n$/, '');\n }\n\n // Get the target line, stripping a trailing carriage return if necessary.\n const line = str.slice(lineStartOffset, lineEndOffset).replace(/\\r$/, '');\n\n return {\n offset,\n lineNum,\n colNum,\n line,\n prevLine,\n nextLine,\n toString: lineAndColumnToMessage,\n };\n}\n\n// Return a nicely-formatted string describing the line and column for the\n// given offset in `str` highlighting `ranges`.\nfunction getLineAndColumnMessage(str, offset, ...ranges) {\n return getLineAndColumn(str, offset).toString(...ranges);\n}\n\nconst uniqueId = (() => {\n let idCounter = 0;\n return prefix => '' + prefix + idCounter++;\n})();\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nclass Interval {\n constructor(sourceString, startIdx, endIdx) {\n this.sourceString = sourceString;\n this.startIdx = startIdx;\n this.endIdx = endIdx;\n }\n\n get contents() {\n if (this._contents === undefined) {\n this._contents = this.sourceString.slice(this.startIdx, this.endIdx);\n }\n return this._contents;\n }\n\n get length() {\n return this.endIdx - this.startIdx;\n }\n\n coverageWith(...intervals) {\n return Interval.coverage(...intervals, this);\n }\n\n collapsedLeft() {\n return new Interval(this.sourceString, this.startIdx, this.startIdx);\n }\n\n collapsedRight() {\n return new Interval(this.sourceString, this.endIdx, this.endIdx);\n }\n\n getLineAndColumn() {\n return getLineAndColumn(this.sourceString, this.startIdx);\n }\n\n getLineAndColumnMessage() {\n const range = [this.startIdx, this.endIdx];\n return getLineAndColumnMessage(this.sourceString, this.startIdx, range);\n }\n\n // Returns an array of 0, 1, or 2 intervals that represents the result of the\n // interval difference operation.\n minus(that) {\n if (this.sourceString !== that.sourceString) {\n throw intervalSourcesDontMatch();\n } else if (this.startIdx === that.startIdx && this.endIdx === that.endIdx) {\n // `this` and `that` are the same interval!\n return [];\n } else if (this.startIdx < that.startIdx && that.endIdx < this.endIdx) {\n // `that` splits `this` into two intervals\n return [\n new Interval(this.sourceString, this.startIdx, that.startIdx),\n new Interval(this.sourceString, that.endIdx, this.endIdx),\n ];\n } else if (this.startIdx < that.endIdx && that.endIdx < this.endIdx) {\n // `that` contains a prefix of `this`\n return [new Interval(this.sourceString, that.endIdx, this.endIdx)];\n } else if (this.startIdx < that.startIdx && that.startIdx < this.endIdx) {\n // `that` contains a suffix of `this`\n return [new Interval(this.sourceString, this.startIdx, that.startIdx)];\n } else {\n // `that` and `this` do not overlap\n return [this];\n }\n }\n\n // Returns a new Interval that has the same extent as this one, but which is relative\n // to `that`, an Interval that fully covers this one.\n relativeTo(that) {\n if (this.sourceString !== that.sourceString) {\n throw intervalSourcesDontMatch();\n }\n assert(\n this.startIdx >= that.startIdx && this.endIdx <= that.endIdx,\n 'other interval does not cover this one',\n );\n return new Interval(\n this.sourceString,\n this.startIdx - that.startIdx,\n this.endIdx - that.startIdx,\n );\n }\n\n // Returns a new Interval which contains the same contents as this one,\n // but with whitespace trimmed from both ends.\n trimmed() {\n const {contents} = this;\n const startIdx = this.startIdx + contents.match(/^\\s*/)[0].length;\n const endIdx = this.endIdx - contents.match(/\\s*$/)[0].length;\n return new Interval(this.sourceString, startIdx, endIdx);\n }\n\n subInterval(offset, len) {\n const newStartIdx = this.startIdx + offset;\n return new Interval(this.sourceString, newStartIdx, newStartIdx + len);\n }\n}\n\nInterval.coverage = function(firstInterval, ...intervals) {\n let {startIdx, endIdx} = firstInterval;\n for (const interval of intervals) {\n if (interval.sourceString !== firstInterval.sourceString) {\n throw intervalSourcesDontMatch();\n } else {\n startIdx = Math.min(startIdx, interval.startIdx);\n endIdx = Math.max(endIdx, interval.endIdx);\n }\n }\n return new Interval(firstInterval.sourceString, startIdx, endIdx);\n};\n\nconst MAX_CHAR_CODE = 0xffff;\n\nclass InputStream {\n constructor(source) {\n this.source = source;\n this.pos = 0;\n this.examinedLength = 0;\n }\n\n atEnd() {\n const ans = this.pos >= this.source.length;\n this.examinedLength = Math.max(this.examinedLength, this.pos + 1);\n return ans;\n }\n\n next() {\n const ans = this.source[this.pos++];\n this.examinedLength = Math.max(this.examinedLength, this.pos);\n return ans;\n }\n\n nextCharCode() {\n const nextChar = this.next();\n return nextChar && nextChar.charCodeAt(0);\n }\n\n nextCodePoint() {\n const cp = this.source.slice(this.pos++).codePointAt(0);\n // If the code point is beyond plane 0, it takes up two characters.\n if (cp > MAX_CHAR_CODE) {\n this.pos += 1;\n }\n this.examinedLength = Math.max(this.examinedLength, this.pos);\n return cp;\n }\n\n matchString(s, optIgnoreCase) {\n let idx;\n if (optIgnoreCase) {\n /*\n Case-insensitive comparison is a tricky business. Some notable gotchas include the\n \"Turkish I\" problem (http://www.i18nguy.com/unicode/turkish-i18n.html) and the fact\n that the German Esszet (ß) turns into \"SS\" in upper case.\n\n This is intended to be a locale-invariant comparison, which means it may not obey\n locale-specific expectations (e.g. \"i\" => \"İ\").\n */\n for (idx = 0; idx < s.length; idx++) {\n const actual = this.next();\n const expected = s[idx];\n if (actual == null || actual.toUpperCase() !== expected.toUpperCase()) {\n return false;\n }\n }\n return true;\n }\n // Default is case-sensitive comparison.\n for (idx = 0; idx < s.length; idx++) {\n if (this.next() !== s[idx]) {\n return false;\n }\n }\n return true;\n }\n\n sourceSlice(startIdx, endIdx) {\n return this.source.slice(startIdx, endIdx);\n }\n\n interval(startIdx, optEndIdx) {\n return new Interval(this.source, startIdx, optEndIdx ? optEndIdx : this.pos);\n }\n}\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nclass MatchResult {\n constructor(\n matcher,\n input,\n startExpr,\n cst,\n cstOffset,\n rightmostFailurePosition,\n optRecordedFailures,\n ) {\n this.matcher = matcher;\n this.input = input;\n this.startExpr = startExpr;\n this._cst = cst;\n this._cstOffset = cstOffset;\n this._rightmostFailurePosition = rightmostFailurePosition;\n this._rightmostFailures = optRecordedFailures;\n\n if (this.failed()) {\n /* eslint-disable no-invalid-this */\n defineLazyProperty(this, 'message', function() {\n const detail = 'Expected ' + this.getExpectedText();\n return (\n getLineAndColumnMessage(this.input, this.getRightmostFailurePosition()) + detail\n );\n });\n defineLazyProperty(this, 'shortMessage', function() {\n const detail = 'expected ' + this.getExpectedText();\n const errorInfo = getLineAndColumn(\n this.input,\n this.getRightmostFailurePosition(),\n );\n return 'Line ' + errorInfo.lineNum + ', col ' + errorInfo.colNum + ': ' + detail;\n });\n /* eslint-enable no-invalid-this */\n }\n }\n\n succeeded() {\n return !!this._cst;\n }\n\n failed() {\n return !this.succeeded();\n }\n\n getRightmostFailurePosition() {\n return this._rightmostFailurePosition;\n }\n\n getRightmostFailures() {\n if (!this._rightmostFailures) {\n this.matcher.setInput(this.input);\n const matchResultWithFailures = this.matcher._match(this.startExpr, {\n tracing: false,\n positionToRecordFailures: this.getRightmostFailurePosition(),\n });\n this._rightmostFailures = matchResultWithFailures.getRightmostFailures();\n }\n return this._rightmostFailures;\n }\n\n toString() {\n return this.succeeded() ?\n '[match succeeded]' :\n '[match failed at position ' + this.getRightmostFailurePosition() + ']';\n }\n\n // Return a string summarizing the expected contents of the input stream when\n // the match failure occurred.\n getExpectedText() {\n if (this.succeeded()) {\n throw new Error('cannot get expected text of a successful MatchResult');\n }\n\n const sb = new StringBuffer();\n let failures = this.getRightmostFailures();\n\n // Filter out the fluffy failures to make the default error messages more useful\n failures = failures.filter(failure => !failure.isFluffy());\n\n for (let idx = 0; idx < failures.length; idx++) {\n if (idx > 0) {\n if (idx === failures.length - 1) {\n sb.append(failures.length > 2 ? ', or ' : ' or ');\n } else {\n sb.append(', ');\n }\n }\n sb.append(failures[idx].toString());\n }\n return sb.contents();\n }\n\n getInterval() {\n const pos = this.getRightmostFailurePosition();\n return new Interval(this.input, pos, pos);\n }\n}\n\nclass PosInfo {\n constructor() {\n this.applicationMemoKeyStack = []; // active applications at this position\n this.memo = {};\n this.maxExaminedLength = 0;\n this.maxRightmostFailureOffset = -1;\n this.currentLeftRecursion = undefined;\n }\n\n isActive(application) {\n return this.applicationMemoKeyStack.indexOf(application.toMemoKey()) >= 0;\n }\n\n enter(application) {\n this.applicationMemoKeyStack.push(application.toMemoKey());\n }\n\n exit() {\n this.applicationMemoKeyStack.pop();\n }\n\n startLeftRecursion(headApplication, memoRec) {\n memoRec.isLeftRecursion = true;\n memoRec.headApplication = headApplication;\n memoRec.nextLeftRecursion = this.currentLeftRecursion;\n this.currentLeftRecursion = memoRec;\n\n const {applicationMemoKeyStack} = this;\n const indexOfFirstInvolvedRule =\n applicationMemoKeyStack.indexOf(headApplication.toMemoKey()) + 1;\n const involvedApplicationMemoKeys = applicationMemoKeyStack.slice(\n indexOfFirstInvolvedRule,\n );\n\n memoRec.isInvolved = function(applicationMemoKey) {\n return involvedApplicationMemoKeys.indexOf(applicationMemoKey) >= 0;\n };\n\n memoRec.updateInvolvedApplicationMemoKeys = function() {\n for (let idx = indexOfFirstInvolvedRule; idx < applicationMemoKeyStack.length; idx++) {\n const applicationMemoKey = applicationMemoKeyStack[idx];\n if (!this.isInvolved(applicationMemoKey)) {\n involvedApplicationMemoKeys.push(applicationMemoKey);\n }\n }\n };\n }\n\n endLeftRecursion() {\n this.currentLeftRecursion = this.currentLeftRecursion.nextLeftRecursion;\n }\n\n // Note: this method doesn't get called for the \"head\" of a left recursion -- for LR heads,\n // the memoized result (which starts out being a failure) is always used.\n shouldUseMemoizedResult(memoRec) {\n if (!memoRec.isLeftRecursion) {\n return true;\n }\n const {applicationMemoKeyStack} = this;\n for (let idx = 0; idx < applicationMemoKeyStack.length; idx++) {\n const applicationMemoKey = applicationMemoKeyStack[idx];\n if (memoRec.isInvolved(applicationMemoKey)) {\n return false;\n }\n }\n return true;\n }\n\n memoize(memoKey, memoRec) {\n this.memo[memoKey] = memoRec;\n this.maxExaminedLength = Math.max(this.maxExaminedLength, memoRec.examinedLength);\n this.maxRightmostFailureOffset = Math.max(\n this.maxRightmostFailureOffset,\n memoRec.rightmostFailureOffset,\n );\n return memoRec;\n }\n\n clearObsoleteEntries(pos, invalidatedIdx) {\n if (pos + this.maxExaminedLength <= invalidatedIdx) {\n // Optimization: none of the rule applications that were memoized here examined the\n // interval of the input that changed, so nothing has to be invalidated.\n return;\n }\n\n const {memo} = this;\n this.maxExaminedLength = 0;\n this.maxRightmostFailureOffset = -1;\n Object.keys(memo).forEach(k => {\n const memoRec = memo[k];\n if (pos + memoRec.examinedLength > invalidatedIdx) {\n delete memo[k];\n } else {\n this.maxExaminedLength = Math.max(this.maxExaminedLength, memoRec.examinedLength);\n this.maxRightmostFailureOffset = Math.max(\n this.maxRightmostFailureOffset,\n memoRec.rightmostFailureOffset,\n );\n }\n });\n }\n}\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\n// Unicode characters that are used in the `toString` output.\nconst BALLOT_X = '\\u2717';\nconst CHECK_MARK = '\\u2713';\nconst DOT_OPERATOR = '\\u22C5';\nconst RIGHTWARDS_DOUBLE_ARROW = '\\u21D2';\nconst SYMBOL_FOR_HORIZONTAL_TABULATION = '\\u2409';\nconst SYMBOL_FOR_LINE_FEED = '\\u240A';\nconst SYMBOL_FOR_CARRIAGE_RETURN = '\\u240D';\n\nconst Flags = {\n succeeded: 1 << 0,\n isRootNode: 1 << 1,\n isImplicitSpaces: 1 << 2,\n isMemoized: 1 << 3,\n isHeadOfLeftRecursion: 1 << 4,\n terminatesLR: 1 << 5,\n};\n\nfunction spaces(n) {\n return repeat(' ', n).join('');\n}\n\n// Return a string representation of a portion of `input` at offset `pos`.\n// The result will contain exactly `len` characters.\nfunction getInputExcerpt(input, pos, len) {\n const excerpt = asEscapedString(input.slice(pos, pos + len));\n\n // Pad the output if necessary.\n if (excerpt.length < len) {\n return excerpt + repeat(' ', len - excerpt.length).join('');\n }\n return excerpt;\n}\n\nfunction asEscapedString(obj) {\n if (typeof obj === 'string') {\n // Replace non-printable characters with visible symbols.\n return obj\n .replace(/ /g, DOT_OPERATOR)\n .replace(/\\t/g, SYMBOL_FOR_HORIZONTAL_TABULATION)\n .replace(/\\n/g, SYMBOL_FOR_LINE_FEED)\n .replace(/\\r/g, SYMBOL_FOR_CARRIAGE_RETURN);\n }\n return String(obj);\n}\n\n// ----------------- Trace -----------------\n\nclass Trace {\n constructor(input, pos1, pos2, expr, succeeded, bindings, optChildren) {\n this.input = input;\n this.pos = this.pos1 = pos1;\n this.pos2 = pos2;\n this.source = new Interval(input, pos1, pos2);\n this.expr = expr;\n this.bindings = bindings;\n this.children = optChildren || [];\n this.terminatingLREntry = null;\n\n this._flags = succeeded ? Flags.succeeded : 0;\n }\n\n get displayString() {\n return this.expr.toDisplayString();\n }\n\n clone() {\n return this.cloneWithExpr(this.expr);\n }\n\n cloneWithExpr(expr) {\n const ans = new Trace(\n this.input,\n this.pos,\n this.pos2,\n expr,\n this.succeeded,\n this.bindings,\n this.children,\n );\n\n ans.isHeadOfLeftRecursion = this.isHeadOfLeftRecursion;\n ans.isImplicitSpaces = this.isImplicitSpaces;\n ans.isMemoized = this.isMemoized;\n ans.isRootNode = this.isRootNode;\n ans.terminatesLR = this.terminatesLR;\n ans.terminatingLREntry = this.terminatingLREntry;\n return ans;\n }\n\n // Record the trace information for the terminating condition of the LR loop.\n recordLRTermination(ruleBodyTrace, value) {\n this.terminatingLREntry = new Trace(\n this.input,\n this.pos,\n this.pos2,\n this.expr,\n false,\n [value],\n [ruleBodyTrace],\n );\n this.terminatingLREntry.terminatesLR = true;\n }\n\n // Recursively traverse this trace node and all its descendents, calling a visitor function\n // for each node that is visited. If `vistorObjOrFn` is an object, then its 'enter' property\n // is a function to call before visiting the children of a node, and its 'exit' property is\n // a function to call afterwards. If `visitorObjOrFn` is a function, it represents the 'enter'\n // function.\n //\n // The functions are called with three arguments: the Trace node, its parent Trace, and a number\n // representing the depth of the node in the tree. (The root node has depth 0.) `optThisArg`, if\n // specified, is the value to use for `this` when executing the visitor functions.\n walk(visitorObjOrFn, optThisArg) {\n let visitor = visitorObjOrFn;\n if (typeof visitor === 'function') {\n visitor = {enter: visitor};\n }\n\n function _walk(node, parent, depth) {\n let recurse = true;\n if (visitor.enter) {\n if (visitor.enter.call(optThisArg, node, parent, depth) === Trace.prototype.SKIP) {\n recurse = false;\n }\n }\n if (recurse) {\n node.children.forEach(child => {\n _walk(child, node, depth + 1);\n });\n if (visitor.exit) {\n visitor.exit.call(optThisArg, node, parent, depth);\n }\n }\n }\n if (this.isRootNode) {\n // Don't visit the root node itself, only its children.\n this.children.forEach(c => {\n _walk(c, null, 0);\n });\n } else {\n _walk(this, null, 0);\n }\n }\n\n // Return a string representation of the trace.\n // Sample:\n // 12⋅+⋅2⋅*⋅3 ✓ exp ⇒ \"12\"\n // 12⋅+⋅2⋅*⋅3 ✓ addExp (LR) ⇒ \"12\"\n // 12⋅+⋅2⋅*⋅3 ✗ addExp_plus\n toString() {\n const sb = new StringBuffer();\n this.walk((node, parent, depth) => {\n if (!node) {\n return this.SKIP;\n }\n const ctorName = node.expr.constructor.name;\n // Don't print anything for Alt nodes.\n if (ctorName === 'Alt') {\n return; // eslint-disable-line consistent-return\n }\n sb.append(getInputExcerpt(node.input, node.pos, 10) + spaces(depth * 2 + 1));\n sb.append((node.succeeded ? CHECK_MARK : BALLOT_X) + ' ' + node.displayString);\n if (node.isHeadOfLeftRecursion) {\n sb.append(' (LR)');\n }\n if (node.succeeded) {\n const contents = asEscapedString(node.source.contents);\n sb.append(' ' + RIGHTWARDS_DOUBLE_ARROW + ' ');\n sb.append(typeof contents === 'string' ? '\"' + contents + '\"' : contents);\n }\n sb.append('\\n');\n });\n return sb.contents();\n }\n}\n\n// A value that can be returned from visitor functions to indicate that a\n// node should not be recursed into.\nTrace.prototype.SKIP = {};\n\n// For convenience, create a getter and setter for the boolean flags in `Flags`.\nObject.keys(Flags).forEach(name => {\n const mask = Flags[name];\n Object.defineProperty(Trace.prototype, name, {\n get() {\n return (this._flags & mask) !== 0;\n },\n set(val) {\n if (val) {\n this._flags |= mask;\n } else {\n this._flags &= ~mask;\n }\n },\n });\n});\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n/*\n Return true if we should skip spaces preceding this expression in a syntactic context.\n*/\nPExpr.prototype.allowsSkippingPrecedingSpace = abstract('allowsSkippingPrecedingSpace');\n\n/*\n Generally, these are all first-order expressions and (with the exception of Apply)\n directly read from the input stream.\n*/\nany.allowsSkippingPrecedingSpace =\n end.allowsSkippingPrecedingSpace =\n Apply.prototype.allowsSkippingPrecedingSpace =\n Terminal.prototype.allowsSkippingPrecedingSpace =\n Range.prototype.allowsSkippingPrecedingSpace =\n UnicodeChar.prototype.allowsSkippingPrecedingSpace =\n function() {\n return true;\n };\n\n/*\n Higher-order expressions that don't directly consume input.\n*/\nAlt.prototype.allowsSkippingPrecedingSpace =\n Iter.prototype.allowsSkippingPrecedingSpace =\n Lex.prototype.allowsSkippingPrecedingSpace =\n Lookahead.prototype.allowsSkippingPrecedingSpace =\n Not.prototype.allowsSkippingPrecedingSpace =\n Param.prototype.allowsSkippingPrecedingSpace =\n Seq.prototype.allowsSkippingPrecedingSpace =\n function() {\n return false;\n };\n\nlet BuiltInRules$1;\n\nawaitBuiltInRules(g => {\n BuiltInRules$1 = g;\n});\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\nlet lexifyCount;\n\nPExpr.prototype.assertAllApplicationsAreValid = function(ruleName, grammar) {\n lexifyCount = 0;\n this._assertAllApplicationsAreValid(ruleName, grammar);\n};\n\nPExpr.prototype._assertAllApplicationsAreValid = abstract(\n '_assertAllApplicationsAreValid',\n);\n\nany._assertAllApplicationsAreValid =\n end._assertAllApplicationsAreValid =\n Terminal.prototype._assertAllApplicationsAreValid =\n Range.prototype._assertAllApplicationsAreValid =\n Param.prototype._assertAllApplicationsAreValid =\n UnicodeChar.prototype._assertAllApplicationsAreValid =\n function(ruleName, grammar) {\n // no-op\n };\n\nLex.prototype._assertAllApplicationsAreValid = function(ruleName, grammar) {\n lexifyCount++;\n this.expr._assertAllApplicationsAreValid(ruleName, grammar);\n lexifyCount--;\n};\n\nAlt.prototype._assertAllApplicationsAreValid = function(ruleName, grammar) {\n for (let idx = 0; idx < this.terms.length; idx++) {\n this.terms[idx]._assertAllApplicationsAreValid(ruleName, grammar);\n }\n};\n\nSeq.prototype._assertAllApplicationsAreValid = function(ruleName, grammar) {\n for (let idx = 0; idx < this.factors.length; idx++) {\n this.factors[idx]._assertAllApplicationsAreValid(ruleName, grammar);\n }\n};\n\nIter.prototype._assertAllApplicationsAreValid =\n Not.prototype._assertAllApplicationsAreValid =\n Lookahead.prototype._assertAllApplicationsAreValid =\n function(ruleName, grammar) {\n this.expr._assertAllApplicationsAreValid(ruleName, grammar);\n };\n\nApply.prototype._assertAllApplicationsAreValid = function(\n ruleName,\n grammar,\n skipSyntacticCheck = false,\n) {\n const ruleInfo = grammar.rules[this.ruleName];\n const isContextSyntactic = isSyntactic(ruleName) && lexifyCount === 0;\n\n // Make sure that the rule exists...\n if (!ruleInfo) {\n throw undeclaredRule(this.ruleName, grammar.name, this.source);\n }\n\n // ...and that this application is allowed\n if (!skipSyntacticCheck && isSyntactic(this.ruleName) && !isContextSyntactic) {\n throw applicationOfSyntacticRuleFromLexicalContext(this.ruleName, this);\n }\n\n // ...and that this application has the correct number of arguments.\n const actual = this.args.length;\n const expected = ruleInfo.formals.length;\n if (actual !== expected) {\n throw wrongNumberOfArguments(this.ruleName, expected, actual, this.source);\n }\n\n const isBuiltInApplySyntactic =\n BuiltInRules$1 && ruleInfo === BuiltInRules$1.rules.applySyntactic;\n const isBuiltInCaseInsensitive =\n BuiltInRules$1 && ruleInfo === BuiltInRules$1.rules.caseInsensitive;\n\n // If it's an application of 'caseInsensitive', ensure that the argument is a Terminal.\n if (isBuiltInCaseInsensitive) {\n if (!(this.args[0] instanceof Terminal)) {\n throw incorrectArgumentType('a Terminal (e.g. \"abc\")', this.args[0]);\n }\n }\n\n if (isBuiltInApplySyntactic) {\n const arg = this.args[0];\n if (!(arg instanceof Apply)) {\n throw incorrectArgumentType('a syntactic rule application', arg);\n }\n if (!isSyntactic(arg.ruleName)) {\n throw applySyntacticWithLexicalRuleApplication(arg);\n }\n if (isContextSyntactic) {\n throw unnecessaryExperimentalApplySyntactic(this);\n }\n }\n\n // ...and that all of the argument expressions only have valid applications and have arity 1.\n // If `this` is an application of the built-in applySyntactic rule, then its arg is\n // allowed (and expected) to be a syntactic rule, even if we're in a lexical context.\n this.args.forEach(arg => {\n arg._assertAllApplicationsAreValid(ruleName, grammar, isBuiltInApplySyntactic);\n if (arg.getArity() !== 1) {\n throw invalidParameter(this.ruleName, arg);\n }\n });\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\nPExpr.prototype.assertChoicesHaveUniformArity = abstract(\n 'assertChoicesHaveUniformArity',\n);\n\nany.assertChoicesHaveUniformArity =\n end.assertChoicesHaveUniformArity =\n Terminal.prototype.assertChoicesHaveUniformArity =\n Range.prototype.assertChoicesHaveUniformArity =\n Param.prototype.assertChoicesHaveUniformArity =\n Lex.prototype.assertChoicesHaveUniformArity =\n UnicodeChar.prototype.assertChoicesHaveUniformArity =\n function(ruleName) {\n // no-op\n };\n\nAlt.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n if (this.terms.length === 0) {\n return;\n }\n const arity = this.terms[0].getArity();\n for (let idx = 0; idx < this.terms.length; idx++) {\n const term = this.terms[idx];\n term.assertChoicesHaveUniformArity();\n const otherArity = term.getArity();\n if (arity !== otherArity) {\n throw inconsistentArity(ruleName, arity, otherArity, term);\n }\n }\n};\n\nExtend.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n // Extend is a special case of Alt that's guaranteed to have exactly two\n // cases: [extensions, origBody].\n const actualArity = this.terms[0].getArity();\n const expectedArity = this.terms[1].getArity();\n if (actualArity !== expectedArity) {\n throw inconsistentArity(ruleName, expectedArity, actualArity, this.terms[0]);\n }\n};\n\nSeq.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n for (let idx = 0; idx < this.factors.length; idx++) {\n this.factors[idx].assertChoicesHaveUniformArity(ruleName);\n }\n};\n\nIter.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n this.expr.assertChoicesHaveUniformArity(ruleName);\n};\n\nNot.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n // no-op (not required b/c the nested expr doesn't show up in the CST)\n};\n\nLookahead.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n this.expr.assertChoicesHaveUniformArity(ruleName);\n};\n\nApply.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n // The arities of the parameter expressions is required to be 1 by\n // `assertAllApplicationsAreValid()`.\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\nPExpr.prototype.assertIteratedExprsAreNotNullable = abstract(\n 'assertIteratedExprsAreNotNullable',\n);\n\nany.assertIteratedExprsAreNotNullable =\n end.assertIteratedExprsAreNotNullable =\n Terminal.prototype.assertIteratedExprsAreNotNullable =\n Range.prototype.assertIteratedExprsAreNotNullable =\n Param.prototype.assertIteratedExprsAreNotNullable =\n UnicodeChar.prototype.assertIteratedExprsAreNotNullable =\n function(grammar) {\n // no-op\n };\n\nAlt.prototype.assertIteratedExprsAreNotNullable = function(grammar) {\n for (let idx = 0; idx < this.terms.length; idx++) {\n this.terms[idx].assertIteratedExprsAreNotNullable(grammar);\n }\n};\n\nSeq.prototype.assertIteratedExprsAreNotNullable = function(grammar) {\n for (let idx = 0; idx < this.factors.length; idx++) {\n this.factors[idx].assertIteratedExprsAreNotNullable(grammar);\n }\n};\n\nIter.prototype.assertIteratedExprsAreNotNullable = function(grammar) {\n // Note: this is the implementation of this method for `Star` and `Plus` expressions.\n // It is overridden for `Opt` below.\n this.expr.assertIteratedExprsAreNotNullable(grammar);\n if (this.expr.isNullable(grammar)) {\n throw kleeneExprHasNullableOperand(this, []);\n }\n};\n\nOpt.prototype.assertIteratedExprsAreNotNullable =\n Not.prototype.assertIteratedExprsAreNotNullable =\n Lookahead.prototype.assertIteratedExprsAreNotNullable =\n Lex.prototype.assertIteratedExprsAreNotNullable =\n function(grammar) {\n this.expr.assertIteratedExprsAreNotNullable(grammar);\n };\n\nApply.prototype.assertIteratedExprsAreNotNullable = function(grammar) {\n this.args.forEach(arg => {\n arg.assertIteratedExprsAreNotNullable(grammar);\n });\n};\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nclass Node {\n constructor(matchLength) {\n this.matchLength = matchLength;\n }\n\n get ctorName() {\n throw new Error('subclass responsibility');\n }\n\n numChildren() {\n return this.children ? this.children.length : 0;\n }\n\n childAt(idx) {\n if (this.children) {\n return this.children[idx];\n }\n }\n\n indexOfChild(arg) {\n return this.children.indexOf(arg);\n }\n\n hasChildren() {\n return this.numChildren() > 0;\n }\n\n hasNoChildren() {\n return !this.hasChildren();\n }\n\n onlyChild() {\n if (this.numChildren() !== 1) {\n throw new Error(\n 'cannot get only child of a node of type ' +\n this.ctorName +\n ' (it has ' +\n this.numChildren() +\n ' children)',\n );\n } else {\n return this.firstChild();\n }\n }\n\n firstChild() {\n if (this.hasNoChildren()) {\n throw new Error(\n 'cannot get first child of a ' + this.ctorName + ' node, which has no children',\n );\n } else {\n return this.childAt(0);\n }\n }\n\n lastChild() {\n if (this.hasNoChildren()) {\n throw new Error(\n 'cannot get last child of a ' + this.ctorName + ' node, which has no children',\n );\n } else {\n return this.childAt(this.numChildren() - 1);\n }\n }\n\n childBefore(child) {\n const childIdx = this.indexOfChild(child);\n if (childIdx < 0) {\n throw new Error('Node.childBefore() called w/ an argument that is not a child');\n } else if (childIdx === 0) {\n throw new Error('cannot get child before first child');\n } else {\n return this.childAt(childIdx - 1);\n }\n }\n\n childAfter(child) {\n const childIdx = this.indexOfChild(child);\n if (childIdx < 0) {\n throw new Error('Node.childAfter() called w/ an argument that is not a child');\n } else if (childIdx === this.numChildren() - 1) {\n throw new Error('cannot get child after last child');\n } else {\n return this.childAt(childIdx + 1);\n }\n }\n\n isTerminal() {\n return false;\n }\n\n isNonterminal() {\n return false;\n }\n\n isIteration() {\n return false;\n }\n\n isOptional() {\n return false;\n }\n}\n\n// Terminals\n\nclass TerminalNode extends Node {\n get ctorName() {\n return '_terminal';\n }\n\n isTerminal() {\n return true;\n }\n\n get primitiveValue() {\n throw new Error('The `primitiveValue` property was removed in Ohm v17.');\n }\n}\n\n// Nonterminals\n\nclass NonterminalNode extends Node {\n constructor(ruleName, children, childOffsets, matchLength) {\n super(matchLength);\n this.ruleName = ruleName;\n this.children = children;\n this.childOffsets = childOffsets;\n }\n\n get ctorName() {\n return this.ruleName;\n }\n\n isNonterminal() {\n return true;\n }\n\n isLexical() {\n return isLexical(this.ctorName);\n }\n\n isSyntactic() {\n return isSyntactic(this.ctorName);\n }\n}\n\n// Iterations\n\nclass IterationNode extends Node {\n constructor(children, childOffsets, matchLength, isOptional) {\n super(matchLength);\n this.children = children;\n this.childOffsets = childOffsets;\n this.optional = isOptional;\n }\n\n get ctorName() {\n return '_iter';\n }\n\n isIteration() {\n return true;\n }\n\n isOptional() {\n return this.optional;\n }\n}\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n/*\n Evaluate the expression and return `true` if it succeeds, `false` otherwise. This method should\n only be called directly by `State.prototype.eval(expr)`, which also updates the data structures\n that are used for tracing. (Making those updates in a method of `State` enables the trace-specific\n data structures to be \"secrets\" of that class, which is good for modularity.)\n\n The contract of this method is as follows:\n * When the return value is `true`,\n - the state object will have `expr.getArity()` more bindings than it did before the call.\n * When the return value is `false`,\n - the state object may have more bindings than it did before the call, and\n - its input stream's position may be anywhere.\n\n Note that `State.prototype.eval(expr)`, unlike this method, guarantees that neither the state\n object's bindings nor its input stream's position will change if the expression fails to match.\n*/\nPExpr.prototype.eval = abstract('eval'); // function(state) { ... }\n\nany.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n const cp = inputStream.nextCodePoint();\n if (cp !== undefined) {\n state.pushBinding(new TerminalNode(String.fromCodePoint(cp).length), origPos);\n return true;\n } else {\n state.processFailure(origPos, this);\n return false;\n }\n};\n\nend.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n if (inputStream.atEnd()) {\n state.pushBinding(new TerminalNode(0), origPos);\n return true;\n } else {\n state.processFailure(origPos, this);\n return false;\n }\n};\n\nTerminal.prototype.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n if (!inputStream.matchString(this.obj)) {\n state.processFailure(origPos, this);\n return false;\n } else {\n state.pushBinding(new TerminalNode(this.obj.length), origPos);\n return true;\n }\n};\n\nRange.prototype.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n\n // A range can operate in one of two modes: matching a single, 16-bit _code unit_,\n // or matching a _code point_. (Code points over 0xFFFF take up two 16-bit code units.)\n const cp = this.matchCodePoint ? inputStream.nextCodePoint() : inputStream.nextCharCode();\n\n // Always compare by code point value to get the correct result in all scenarios.\n // Note that for strings of length 1, codePointAt(0) and charPointAt(0) are equivalent.\n if (cp !== undefined && this.from.codePointAt(0) <= cp && cp <= this.to.codePointAt(0)) {\n state.pushBinding(new TerminalNode(String.fromCodePoint(cp).length), origPos);\n return true;\n } else {\n state.processFailure(origPos, this);\n return false;\n }\n};\n\nParam.prototype.eval = function(state) {\n return state.eval(state.currentApplication().args[this.index]);\n};\n\nLex.prototype.eval = function(state) {\n state.enterLexifiedContext();\n const ans = state.eval(this.expr);\n state.exitLexifiedContext();\n return ans;\n};\n\nAlt.prototype.eval = function(state) {\n for (let idx = 0; idx < this.terms.length; idx++) {\n if (state.eval(this.terms[idx])) {\n return true;\n }\n }\n return false;\n};\n\nSeq.prototype.eval = function(state) {\n for (let idx = 0; idx < this.factors.length; idx++) {\n const factor = this.factors[idx];\n if (!state.eval(factor)) {\n return false;\n }\n }\n return true;\n};\n\nIter.prototype.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n const arity = this.getArity();\n const cols = [];\n const colOffsets = [];\n while (cols.length < arity) {\n cols.push([]);\n colOffsets.push([]);\n }\n\n let numMatches = 0;\n let prevPos = origPos;\n let idx;\n while (numMatches < this.maxNumMatches && state.eval(this.expr)) {\n if (inputStream.pos === prevPos) {\n throw kleeneExprHasNullableOperand(this, state._applicationStack);\n }\n prevPos = inputStream.pos;\n numMatches++;\n const row = state._bindings.splice(state._bindings.length - arity, arity);\n const rowOffsets = state._bindingOffsets.splice(\n state._bindingOffsets.length - arity,\n arity,\n );\n for (idx = 0; idx < row.length; idx++) {\n cols[idx].push(row[idx]);\n colOffsets[idx].push(rowOffsets[idx]);\n }\n }\n if (numMatches < this.minNumMatches) {\n return false;\n }\n let offset = state.posToOffset(origPos);\n let matchLength = 0;\n if (numMatches > 0) {\n const lastCol = cols[arity - 1];\n const lastColOffsets = colOffsets[arity - 1];\n\n const endOffset =\n lastColOffsets[lastColOffsets.length - 1] + lastCol[lastCol.length - 1].matchLength;\n offset = colOffsets[0][0];\n matchLength = endOffset - offset;\n }\n const isOptional = this instanceof Opt;\n for (idx = 0; idx < cols.length; idx++) {\n state._bindings.push(\n new IterationNode(cols[idx], colOffsets[idx], matchLength, isOptional),\n );\n state._bindingOffsets.push(offset);\n }\n return true;\n};\n\nNot.prototype.eval = function(state) {\n /*\n TODO:\n - Right now we're just throwing away all of the failures that happen inside a `not`, and\n recording `this` as a failed expression.\n - Double negation should be equivalent to lookahead, but that's not the case right now wrt\n failures. E.g., ~~'foo' produces a failure for ~~'foo', but maybe it should produce\n a failure for 'foo' instead.\n */\n\n const {inputStream} = state;\n const origPos = inputStream.pos;\n state.pushFailuresInfo();\n\n const ans = state.eval(this.expr);\n\n state.popFailuresInfo();\n if (ans) {\n state.processFailure(origPos, this);\n return false;\n }\n\n inputStream.pos = origPos;\n return true;\n};\n\nLookahead.prototype.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n if (state.eval(this.expr)) {\n inputStream.pos = origPos;\n return true;\n } else {\n return false;\n }\n};\n\nApply.prototype.eval = function(state) {\n const caller = state.currentApplication();\n const actuals = caller ? caller.args : [];\n const app = this.substituteParams(actuals);\n\n const posInfo = state.getCurrentPosInfo();\n if (posInfo.isActive(app)) {\n // This rule is already active at this position, i.e., it is left-recursive.\n return app.handleCycle(state);\n }\n\n const memoKey = app.toMemoKey();\n const memoRec = posInfo.memo[memoKey];\n\n if (memoRec && posInfo.shouldUseMemoizedResult(memoRec)) {\n if (state.hasNecessaryInfo(memoRec)) {\n return state.useMemoizedResult(state.inputStream.pos, memoRec);\n }\n delete posInfo.memo[memoKey];\n }\n return app.reallyEval(state);\n};\n\nApply.prototype.handleCycle = function(state) {\n const posInfo = state.getCurrentPosInfo();\n const {currentLeftRecursion} = posInfo;\n const memoKey = this.toMemoKey();\n let memoRec = posInfo.memo[memoKey];\n\n if (currentLeftRecursion && currentLeftRecursion.headApplication.toMemoKey() === memoKey) {\n // We already know about this left recursion, but it's possible there are \"involved\n // applications\" that we don't already know about, so...\n memoRec.updateInvolvedApplicationMemoKeys();\n } else if (!memoRec) {\n // New left recursion detected! Memoize a failure to try to get a seed parse.\n memoRec = posInfo.memoize(memoKey, {\n matchLength: 0,\n examinedLength: 0,\n value: false,\n rightmostFailureOffset: -1,\n });\n posInfo.startLeftRecursion(this, memoRec);\n }\n return state.useMemoizedResult(state.inputStream.pos, memoRec);\n};\n\nApply.prototype.reallyEval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n const origPosInfo = state.getCurrentPosInfo();\n const ruleInfo = state.grammar.rules[this.ruleName];\n const {body} = ruleInfo;\n const {description} = ruleInfo;\n\n state.enterApplication(origPosInfo, this);\n\n if (description) {\n state.pushFailuresInfo();\n }\n\n // Reset the input stream's examinedLength property so that we can track\n // the examined length of this particular application.\n const origInputStreamExaminedLength = inputStream.examinedLength;\n inputStream.examinedLength = 0;\n\n let value = this.evalOnce(body, state);\n const currentLR = origPosInfo.currentLeftRecursion;\n const memoKey = this.toMemoKey();\n const isHeadOfLeftRecursion = currentLR && currentLR.headApplication.toMemoKey() === memoKey;\n let memoRec;\n\n if (state.doNotMemoize) {\n state.doNotMemoize = false;\n } else if (isHeadOfLeftRecursion) {\n value = this.growSeedResult(body, state, origPos, currentLR, value);\n origPosInfo.endLeftRecursion();\n memoRec = currentLR;\n memoRec.examinedLength = inputStream.examinedLength - origPos;\n memoRec.rightmostFailureOffset = state._getRightmostFailureOffset();\n origPosInfo.memoize(memoKey, memoRec); // updates origPosInfo's maxExaminedLength\n } else if (!currentLR || !currentLR.isInvolved(memoKey)) {\n // This application is not involved in left recursion, so it's ok to memoize it.\n memoRec = origPosInfo.memoize(memoKey, {\n matchLength: inputStream.pos - origPos,\n examinedLength: inputStream.examinedLength - origPos,\n value,\n failuresAtRightmostPosition: state.cloneRecordedFailures(),\n rightmostFailureOffset: state._getRightmostFailureOffset(),\n });\n }\n const succeeded = !!value;\n\n if (description) {\n state.popFailuresInfo();\n if (!succeeded) {\n state.processFailure(origPos, this);\n }\n if (memoRec) {\n memoRec.failuresAtRightmostPosition = state.cloneRecordedFailures();\n }\n }\n\n // Record trace information in the memo table, so that it is available if the memoized result\n // is used later.\n if (state.isTracing() && memoRec) {\n const entry = state.getTraceEntry(origPos, this, succeeded, succeeded ? [value] : []);\n if (isHeadOfLeftRecursion) {\n assert(entry.terminatingLREntry != null || !succeeded);\n entry.isHeadOfLeftRecursion = true;\n }\n memoRec.traceEntry = entry;\n }\n\n // Fix the input stream's examinedLength -- it should be the maximum examined length\n // across all applications, not just this one.\n inputStream.examinedLength = Math.max(\n inputStream.examinedLength,\n origInputStreamExaminedLength,\n );\n\n state.exitApplication(origPosInfo, value);\n\n return succeeded;\n};\n\nApply.prototype.evalOnce = function(expr, state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n\n if (state.eval(expr)) {\n const arity = expr.getArity();\n const bindings = state._bindings.splice(state._bindings.length - arity, arity);\n const offsets = state._bindingOffsets.splice(state._bindingOffsets.length - arity, arity);\n const matchLength = inputStream.pos - origPos;\n return new NonterminalNode(this.ruleName, bindings, offsets, matchLength);\n } else {\n return false;\n }\n};\n\nApply.prototype.growSeedResult = function(body, state, origPos, lrMemoRec, newValue) {\n if (!newValue) {\n return false;\n }\n\n const {inputStream} = state;\n\n while (true) {\n lrMemoRec.matchLength = inputStream.pos - origPos;\n lrMemoRec.value = newValue;\n lrMemoRec.failuresAtRightmostPosition = state.cloneRecordedFailures();\n\n if (state.isTracing()) {\n // Before evaluating the body again, add a trace node for this application to the memo entry.\n // Its only child is a copy of the trace node from `newValue`, which will always be the last\n // element in `state.trace`.\n const seedTrace = state.trace[state.trace.length - 1];\n lrMemoRec.traceEntry = new Trace(\n state.input,\n origPos,\n inputStream.pos,\n this,\n true,\n [newValue],\n [seedTrace.clone()],\n );\n }\n inputStream.pos = origPos;\n newValue = this.evalOnce(body, state);\n if (inputStream.pos - origPos <= lrMemoRec.matchLength) {\n break;\n }\n if (state.isTracing()) {\n state.trace.splice(-2, 1); // Drop the trace for the old seed.\n }\n }\n if (state.isTracing()) {\n // The last entry is for an unused result -- pop it and save it in the \"real\" entry.\n lrMemoRec.traceEntry.recordLRTermination(state.trace.pop(), newValue);\n }\n inputStream.pos = origPos + lrMemoRec.matchLength;\n return lrMemoRec.value;\n};\n\nUnicodeChar.prototype.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n const ch = inputStream.next();\n if (ch && this.pattern.test(ch)) {\n state.pushBinding(new TerminalNode(ch.length), origPos);\n return true;\n } else {\n state.processFailure(origPos, this);\n return false;\n }\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\nPExpr.prototype.getArity = abstract('getArity');\n\nany.getArity =\n end.getArity =\n Terminal.prototype.getArity =\n Range.prototype.getArity =\n Param.prototype.getArity =\n Apply.prototype.getArity =\n UnicodeChar.prototype.getArity =\n function() {\n return 1;\n };\n\nAlt.prototype.getArity = function() {\n // This is ok b/c all terms must have the same arity -- this property is\n // checked by the Grammar constructor.\n return this.terms.length === 0 ? 0 : this.terms[0].getArity();\n};\n\nSeq.prototype.getArity = function() {\n let arity = 0;\n for (let idx = 0; idx < this.factors.length; idx++) {\n arity += this.factors[idx].getArity();\n }\n return arity;\n};\n\nIter.prototype.getArity = function() {\n return this.expr.getArity();\n};\n\nNot.prototype.getArity = function() {\n return 0;\n};\n\nLookahead.prototype.getArity = Lex.prototype.getArity = function() {\n return this.expr.getArity();\n};\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nfunction getMetaInfo(expr, grammarInterval) {\n const metaInfo = {};\n if (expr.source && grammarInterval) {\n const adjusted = expr.source.relativeTo(grammarInterval);\n metaInfo.sourceInterval = [adjusted.startIdx, adjusted.endIdx];\n }\n return metaInfo;\n}\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\nPExpr.prototype.outputRecipe = abstract('outputRecipe');\n\nany.outputRecipe = function(formals, grammarInterval) {\n return ['any', getMetaInfo(this, grammarInterval)];\n};\n\nend.outputRecipe = function(formals, grammarInterval) {\n return ['end', getMetaInfo(this, grammarInterval)];\n};\n\nTerminal.prototype.outputRecipe = function(formals, grammarInterval) {\n return ['terminal', getMetaInfo(this, grammarInterval), this.obj];\n};\n\nRange.prototype.outputRecipe = function(formals, grammarInterval) {\n return ['range', getMetaInfo(this, grammarInterval), this.from, this.to];\n};\n\nParam.prototype.outputRecipe = function(formals, grammarInterval) {\n return ['param', getMetaInfo(this, grammarInterval), this.index];\n};\n\nAlt.prototype.outputRecipe = function(formals, grammarInterval) {\n return ['alt', getMetaInfo(this, grammarInterval)].concat(\n this.terms.map(term => term.outputRecipe(formals, grammarInterval)),\n );\n};\n\nExtend.prototype.outputRecipe = function(formals, grammarInterval) {\n const extension = this.terms[0]; // [extension, original]\n return extension.outputRecipe(formals, grammarInterval);\n};\n\nSplice.prototype.outputRecipe = function(formals, grammarInterval) {\n const beforeTerms = this.terms.slice(0, this.expansionPos);\n const afterTerms = this.terms.slice(this.expansionPos + 1);\n return [\n 'splice',\n getMetaInfo(this, grammarInterval),\n beforeTerms.map(term => term.outputRecipe(formals, grammarInterval)),\n afterTerms.map(term => term.outputRecipe(formals, grammarInterval)),\n ];\n};\n\nSeq.prototype.outputRecipe = function(formals, grammarInterval) {\n return ['seq', getMetaInfo(this, grammarInterval)].concat(\n this.factors.map(factor => factor.outputRecipe(formals, grammarInterval)),\n );\n};\n\nStar.prototype.outputRecipe =\n Plus.prototype.outputRecipe =\n Opt.prototype.outputRecipe =\n Not.prototype.outputRecipe =\n Lookahead.prototype.outputRecipe =\n Lex.prototype.outputRecipe =\n function(formals, grammarInterval) {\n return [\n this.constructor.name.toLowerCase(),\n getMetaInfo(this, grammarInterval),\n this.expr.outputRecipe(formals, grammarInterval),\n ];\n };\n\nApply.prototype.outputRecipe = function(formals, grammarInterval) {\n return [\n 'app',\n getMetaInfo(this, grammarInterval),\n this.ruleName,\n this.args.map(arg => arg.outputRecipe(formals, grammarInterval)),\n ];\n};\n\nUnicodeChar.prototype.outputRecipe = function(formals, grammarInterval) {\n return ['unicodeChar', getMetaInfo(this, grammarInterval), this.category];\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n/*\n Called at grammar creation time to rewrite a rule body, replacing each reference to a formal\n parameter with a `Param` node. Returns a PExpr -- either a new one, or the original one if\n it was modified in place.\n*/\nPExpr.prototype.introduceParams = abstract('introduceParams');\n\nany.introduceParams =\n end.introduceParams =\n Terminal.prototype.introduceParams =\n Range.prototype.introduceParams =\n Param.prototype.introduceParams =\n UnicodeChar.prototype.introduceParams =\n function(formals) {\n return this;\n };\n\nAlt.prototype.introduceParams = function(formals) {\n this.terms.forEach((term, idx, terms) => {\n terms[idx] = term.introduceParams(formals);\n });\n return this;\n};\n\nSeq.prototype.introduceParams = function(formals) {\n this.factors.forEach((factor, idx, factors) => {\n factors[idx] = factor.introduceParams(formals);\n });\n return this;\n};\n\nIter.prototype.introduceParams =\n Not.prototype.introduceParams =\n Lookahead.prototype.introduceParams =\n Lex.prototype.introduceParams =\n function(formals) {\n this.expr = this.expr.introduceParams(formals);\n return this;\n };\n\nApply.prototype.introduceParams = function(formals) {\n const index = formals.indexOf(this.ruleName);\n if (index >= 0) {\n if (this.args.length > 0) {\n // TODO: Should this be supported? See issue #64.\n throw new Error('Parameterized rules cannot be passed as arguments to another rule.');\n }\n return new Param(index).withSource(this.source);\n } else {\n this.args.forEach((arg, idx, args) => {\n args[idx] = arg.introduceParams(formals);\n });\n return this;\n }\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n// Returns `true` if this parsing expression may accept without consuming any input.\nPExpr.prototype.isNullable = function(grammar) {\n return this._isNullable(grammar, Object.create(null));\n};\n\nPExpr.prototype._isNullable = abstract('_isNullable');\n\nany._isNullable =\n Range.prototype._isNullable =\n Param.prototype._isNullable =\n Plus.prototype._isNullable =\n UnicodeChar.prototype._isNullable =\n function(grammar, memo) {\n return false;\n };\n\nend._isNullable = function(grammar, memo) {\n return true;\n};\n\nTerminal.prototype._isNullable = function(grammar, memo) {\n if (typeof this.obj === 'string') {\n // This is an over-simplification: it's only correct if the input is a string. If it's an array\n // or an object, then the empty string parsing expression is not nullable.\n return this.obj === '';\n } else {\n return false;\n }\n};\n\nAlt.prototype._isNullable = function(grammar, memo) {\n return this.terms.length === 0 || this.terms.some(term => term._isNullable(grammar, memo));\n};\n\nSeq.prototype._isNullable = function(grammar, memo) {\n return this.factors.every(factor => factor._isNullable(grammar, memo));\n};\n\nStar.prototype._isNullable =\n Opt.prototype._isNullable =\n Not.prototype._isNullable =\n Lookahead.prototype._isNullable =\n function(grammar, memo) {\n return true;\n };\n\nLex.prototype._isNullable = function(grammar, memo) {\n return this.expr._isNullable(grammar, memo);\n};\n\nApply.prototype._isNullable = function(grammar, memo) {\n const key = this.toMemoKey();\n if (!Object.prototype.hasOwnProperty.call(memo, key)) {\n const {body} = grammar.rules[this.ruleName];\n const inlined = body.substituteParams(this.args);\n memo[key] = false; // Prevent infinite recursion for recursive rules.\n memo[key] = inlined._isNullable(grammar, memo);\n }\n return memo[key];\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n/*\n Returns a PExpr that results from recursively replacing every formal parameter (i.e., instance\n of `Param`) inside this PExpr with its actual value from `actuals` (an Array).\n\n The receiver must not be modified; a new PExpr must be returned if any replacement is necessary.\n*/\n// function(actuals) { ... }\nPExpr.prototype.substituteParams = abstract('substituteParams');\n\nany.substituteParams =\n end.substituteParams =\n Terminal.prototype.substituteParams =\n Range.prototype.substituteParams =\n UnicodeChar.prototype.substituteParams =\n function(actuals) {\n return this;\n };\n\nParam.prototype.substituteParams = function(actuals) {\n return actuals[this.index];\n};\n\nAlt.prototype.substituteParams = function(actuals) {\n return new Alt(this.terms.map(term => term.substituteParams(actuals)));\n};\n\nSeq.prototype.substituteParams = function(actuals) {\n return new Seq(this.factors.map(factor => factor.substituteParams(actuals)));\n};\n\nIter.prototype.substituteParams =\n Not.prototype.substituteParams =\n Lookahead.prototype.substituteParams =\n Lex.prototype.substituteParams =\n function(actuals) {\n return new this.constructor(this.expr.substituteParams(actuals));\n };\n\nApply.prototype.substituteParams = function(actuals) {\n if (this.args.length === 0) {\n // Avoid making a copy of this application, as an optimization\n return this;\n } else {\n const args = this.args.map(arg => arg.substituteParams(actuals));\n return new Apply(this.ruleName, args);\n }\n};\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nfunction isRestrictedJSIdentifier(str) {\n return /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(str);\n}\n\nfunction resolveDuplicatedNames(argumentNameList) {\n // `count` is used to record the number of times each argument name occurs in the list,\n // this is useful for checking duplicated argument name. It maps argument names to ints.\n const count = Object.create(null);\n argumentNameList.forEach(argName => {\n count[argName] = (count[argName] || 0) + 1;\n });\n\n // Append subscripts ('_1', '_2', ...) to duplicate argument names.\n Object.keys(count).forEach(dupArgName => {\n if (count[dupArgName] <= 1) {\n return;\n }\n\n // This name shows up more than once, so add subscripts.\n let subscript = 1;\n argumentNameList.forEach((argName, idx) => {\n if (argName === dupArgName) {\n argumentNameList[idx] = argName + '_' + subscript++;\n }\n });\n });\n}\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n/*\n Returns a list of strings that will be used as the default argument names for its receiver\n (a pexpr) in a semantic action. This is used exclusively by the Semantics Editor.\n\n `firstArgIndex` is the 1-based index of the first argument name that will be generated for this\n pexpr. It enables us to name arguments positionally, e.g., if the second argument is a\n non-alphanumeric terminal like \"+\", it will be named '$2'.\n\n `noDupCheck` is true if the caller of `toArgumentNameList` is not a top level caller. It enables\n us to avoid nested duplication subscripts appending, e.g., '_1_1', '_1_2', by only checking\n duplicates at the top level.\n\n Here is a more elaborate example that illustrates how this method works:\n `(a \"+\" b).toArgumentNameList(1)` evaluates to `['a', '$2', 'b']` with the following recursive\n calls:\n\n (a).toArgumentNameList(1) -> ['a'],\n (\"+\").toArgumentNameList(2) -> ['$2'],\n (b).toArgumentNameList(3) -> ['b']\n\n Notes:\n * This method must only be called on well-formed expressions, e.g., the receiver must\n not have any Alt sub-expressions with inconsistent arities.\n * e.getArity() === e.toArgumentNameList(1).length\n*/\n// function(firstArgIndex, noDupCheck) { ... }\nPExpr.prototype.toArgumentNameList = abstract('toArgumentNameList');\n\nany.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return ['any'];\n};\n\nend.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return ['end'];\n};\n\nTerminal.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n if (typeof this.obj === 'string' && /^[_a-zA-Z0-9]+$/.test(this.obj)) {\n // If this terminal is a valid suffix for a JS identifier, just prepend it with '_'\n return ['_' + this.obj];\n } else {\n // Otherwise, name it positionally.\n return ['$' + firstArgIndex];\n }\n};\n\nRange.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n let argName = this.from + '_to_' + this.to;\n // If the `argName` is not valid then try to prepend a `_`.\n if (!isRestrictedJSIdentifier(argName)) {\n argName = '_' + argName;\n }\n // If the `argName` still not valid after prepending a `_`, then name it positionally.\n if (!isRestrictedJSIdentifier(argName)) {\n argName = '$' + firstArgIndex;\n }\n return [argName];\n};\n\nAlt.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n // `termArgNameLists` is an array of arrays where each row is the\n // argument name list that corresponds to a term in this alternation.\n const termArgNameLists = this.terms.map(term =>\n term.toArgumentNameList(firstArgIndex, true),\n );\n\n const argumentNameList = [];\n const numArgs = termArgNameLists[0].length;\n for (let colIdx = 0; colIdx < numArgs; colIdx++) {\n const col = [];\n for (let rowIdx = 0; rowIdx < this.terms.length; rowIdx++) {\n col.push(termArgNameLists[rowIdx][colIdx]);\n }\n const uniqueNames = copyWithoutDuplicates(col);\n argumentNameList.push(uniqueNames.join('_or_'));\n }\n\n if (!noDupCheck) {\n resolveDuplicatedNames(argumentNameList);\n }\n return argumentNameList;\n};\n\nSeq.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n // Generate the argument name list, without worrying about duplicates.\n let argumentNameList = [];\n this.factors.forEach(factor => {\n const factorArgumentNameList = factor.toArgumentNameList(firstArgIndex, true);\n argumentNameList = argumentNameList.concat(factorArgumentNameList);\n\n // Shift the firstArgIndex to take this factor's argument names into account.\n firstArgIndex += factorArgumentNameList.length;\n });\n if (!noDupCheck) {\n resolveDuplicatedNames(argumentNameList);\n }\n return argumentNameList;\n};\n\nIter.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n const argumentNameList = this.expr\n .toArgumentNameList(firstArgIndex, noDupCheck)\n .map(exprArgumentString =>\n exprArgumentString[exprArgumentString.length - 1] === 's' ?\n exprArgumentString + 'es' :\n exprArgumentString + 's',\n );\n if (!noDupCheck) {\n resolveDuplicatedNames(argumentNameList);\n }\n return argumentNameList;\n};\n\nOpt.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return this.expr.toArgumentNameList(firstArgIndex, noDupCheck).map(argName => {\n return 'opt' + argName[0].toUpperCase() + argName.slice(1);\n });\n};\n\nNot.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return [];\n};\n\nLookahead.prototype.toArgumentNameList = Lex.prototype.toArgumentNameList =\n function(firstArgIndex, noDupCheck) {\n return this.expr.toArgumentNameList(firstArgIndex, noDupCheck);\n };\n\nApply.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return [this.ruleName];\n};\n\nUnicodeChar.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return ['$' + firstArgIndex];\n};\n\nParam.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return ['param' + this.index];\n};\n\n// \"Value pexprs\" (Value, Str, Arr, Obj) are going away soon, so we don't worry about them here.\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n// Returns a string representing the PExpr, for use as a UI label, etc.\nPExpr.prototype.toDisplayString = abstract('toDisplayString');\n\nAlt.prototype.toDisplayString = Seq.prototype.toDisplayString = function() {\n if (this.source) {\n return this.source.trimmed().contents;\n }\n return '[' + this.constructor.name + ']';\n};\n\nany.toDisplayString =\n end.toDisplayString =\n Iter.prototype.toDisplayString =\n Not.prototype.toDisplayString =\n Lookahead.prototype.toDisplayString =\n Lex.prototype.toDisplayString =\n Terminal.prototype.toDisplayString =\n Range.prototype.toDisplayString =\n Param.prototype.toDisplayString =\n function() {\n return this.toString();\n };\n\nApply.prototype.toDisplayString = function() {\n if (this.args.length > 0) {\n const ps = this.args.map(arg => arg.toDisplayString());\n return this.ruleName + '<' + ps.join(',') + '>';\n } else {\n return this.ruleName;\n }\n};\n\nUnicodeChar.prototype.toDisplayString = function() {\n return 'Unicode [' + this.category + '] character';\n};\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\n/*\n `Failure`s represent expressions that weren't matched while parsing. They are used to generate\n error messages automatically. The interface of `Failure`s includes the collowing methods:\n\n - getText() : String\n - getType() : String (one of {\"description\", \"string\", \"code\"})\n - isDescription() : bool\n - isStringTerminal() : bool\n - isCode() : bool\n - isFluffy() : bool\n - makeFluffy() : void\n - subsumes(Failure) : bool\n*/\n\nfunction isValidType(type) {\n return type === 'description' || type === 'string' || type === 'code';\n}\n\nclass Failure {\n constructor(pexpr, text, type) {\n if (!isValidType(type)) {\n throw new Error('invalid Failure type: ' + type);\n }\n this.pexpr = pexpr;\n this.text = text;\n this.type = type;\n this.fluffy = false;\n }\n\n getPExpr() {\n return this.pexpr;\n }\n\n getText() {\n return this.text;\n }\n\n getType() {\n return this.type;\n }\n\n isDescription() {\n return this.type === 'description';\n }\n\n isStringTerminal() {\n return this.type === 'string';\n }\n\n isCode() {\n return this.type === 'code';\n }\n\n isFluffy() {\n return this.fluffy;\n }\n\n makeFluffy() {\n this.fluffy = true;\n }\n\n clearFluffy() {\n this.fluffy = false;\n }\n\n subsumes(that) {\n return (\n this.getText() === that.getText() &&\n this.type === that.type &&\n (!this.isFluffy() || (this.isFluffy() && that.isFluffy()))\n );\n }\n\n toString() {\n return this.type === 'string' ? JSON.stringify(this.getText()) : this.getText();\n }\n\n clone() {\n const failure = new Failure(this.pexpr, this.text, this.type);\n if (this.isFluffy()) {\n failure.makeFluffy();\n }\n return failure;\n }\n\n toKey() {\n return this.toString() + '#' + this.type;\n }\n}\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\nPExpr.prototype.toFailure = abstract('toFailure');\n\nany.toFailure = function(grammar) {\n return new Failure(this, 'any object', 'description');\n};\n\nend.toFailure = function(grammar) {\n return new Failure(this, 'end of input', 'description');\n};\n\nTerminal.prototype.toFailure = function(grammar) {\n return new Failure(this, this.obj, 'string');\n};\n\nRange.prototype.toFailure = function(grammar) {\n // TODO: come up with something better\n return new Failure(this, JSON.stringify(this.from) + '..' + JSON.stringify(this.to), 'code');\n};\n\nNot.prototype.toFailure = function(grammar) {\n const description =\n this.expr === any ? 'nothing' : 'not ' + this.expr.toFailure(grammar);\n return new Failure(this, description, 'description');\n};\n\nLookahead.prototype.toFailure = function(grammar) {\n return this.expr.toFailure(grammar);\n};\n\nApply.prototype.toFailure = function(grammar) {\n let {description} = grammar.rules[this.ruleName];\n if (!description) {\n const article = /^[aeiouAEIOU]/.test(this.ruleName) ? 'an' : 'a';\n description = article + ' ' + this.ruleName;\n }\n return new Failure(this, description, 'description');\n};\n\nUnicodeChar.prototype.toFailure = function(grammar) {\n return new Failure(this, 'a Unicode [' + this.category + '] character', 'description');\n};\n\nAlt.prototype.toFailure = function(grammar) {\n const fs = this.terms.map(t => t.toFailure(grammar));\n const description = '(' + fs.join(' or ') + ')';\n return new Failure(this, description, 'description');\n};\n\nSeq.prototype.toFailure = function(grammar) {\n const fs = this.factors.map(f => f.toFailure(grammar));\n const description = '(' + fs.join(' ') + ')';\n return new Failure(this, description, 'description');\n};\n\nIter.prototype.toFailure = function(grammar) {\n const description = '(' + this.expr.toFailure(grammar) + this.operator + ')';\n return new Failure(this, description, 'description');\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n/*\n e1.toString() === e2.toString() ==> e1 and e2 are semantically equivalent.\n Note that this is not an iff (<==>): e.g.,\n (~\"b\" \"a\").toString() !== (\"a\").toString(), even though\n ~\"b\" \"a\" and \"a\" are interchangeable in any grammar,\n both in terms of the languages they accept and their arities.\n*/\nPExpr.prototype.toString = abstract('toString');\n\nany.toString = function() {\n return 'any';\n};\n\nend.toString = function() {\n return 'end';\n};\n\nTerminal.prototype.toString = function() {\n return JSON.stringify(this.obj);\n};\n\nRange.prototype.toString = function() {\n return JSON.stringify(this.from) + '..' + JSON.stringify(this.to);\n};\n\nParam.prototype.toString = function() {\n return '$' + this.index;\n};\n\nLex.prototype.toString = function() {\n return '#(' + this.expr.toString() + ')';\n};\n\nAlt.prototype.toString = function() {\n return this.terms.length === 1 ?\n this.terms[0].toString() :\n '(' + this.terms.map(term => term.toString()).join(' | ') + ')';\n};\n\nSeq.prototype.toString = function() {\n return this.factors.length === 1 ?\n this.factors[0].toString() :\n '(' + this.factors.map(factor => factor.toString()).join(' ') + ')';\n};\n\nIter.prototype.toString = function() {\n return this.expr + this.operator;\n};\n\nNot.prototype.toString = function() {\n return '~' + this.expr;\n};\n\nLookahead.prototype.toString = function() {\n return '&' + this.expr;\n};\n\nApply.prototype.toString = function() {\n if (this.args.length > 0) {\n const ps = this.args.map(arg => arg.toString());\n return this.ruleName + '<' + ps.join(',') + '>';\n } else {\n return this.ruleName;\n }\n};\n\nUnicodeChar.prototype.toString = function() {\n return '\\\\p{' + this.category + '}';\n};\n\nclass CaseInsensitiveTerminal extends PExpr {\n constructor(param) {\n super();\n this.obj = param;\n }\n\n _getString(state) {\n const terminal = state.currentApplication().args[this.obj.index];\n assert(terminal instanceof Terminal, 'expected a Terminal expression');\n return terminal.obj;\n }\n\n // Implementation of the PExpr API\n\n allowsSkippingPrecedingSpace() {\n return true;\n }\n\n eval(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n const matchStr = this._getString(state);\n if (!inputStream.matchString(matchStr, true)) {\n state.processFailure(origPos, this);\n return false;\n } else {\n state.pushBinding(new TerminalNode(matchStr.length), origPos);\n return true;\n }\n }\n\n getArity() {\n return 1;\n }\n\n substituteParams(actuals) {\n return new CaseInsensitiveTerminal(this.obj.substituteParams(actuals));\n }\n\n toDisplayString() {\n return this.obj.toDisplayString() + ' (case-insensitive)';\n }\n\n toFailure(grammar) {\n return new Failure(\n this,\n this.obj.toFailure(grammar) + ' (case-insensitive)',\n 'description',\n );\n }\n\n _isNullable(grammar, memo) {\n return this.obj._isNullable(grammar, memo);\n }\n}\n\n// --------------------------------------------------------------------\n\nvar pexprs = /*#__PURE__*/Object.freeze({\n __proto__: null,\n CaseInsensitiveTerminal: CaseInsensitiveTerminal,\n PExpr: PExpr,\n any: any,\n end: end,\n Terminal: Terminal,\n Range: Range,\n Param: Param,\n Alt: Alt,\n Extend: Extend,\n Splice: Splice,\n Seq: Seq,\n Iter: Iter,\n Star: Star,\n Plus: Plus,\n Opt: Opt,\n Not: Not,\n Lookahead: Lookahead,\n Lex: Lex,\n Apply: Apply,\n UnicodeChar: UnicodeChar\n});\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nlet builtInApplySyntacticBody;\n\nawaitBuiltInRules(builtInRules => {\n builtInApplySyntacticBody = builtInRules.rules.applySyntactic.body;\n});\n\nconst applySpaces = new Apply('spaces');\n\nclass MatchState {\n constructor(matcher, startExpr, optPositionToRecordFailures) {\n this.matcher = matcher;\n this.startExpr = startExpr;\n\n this.grammar = matcher.grammar;\n this.input = matcher.getInput();\n this.inputStream = new InputStream(this.input);\n this.memoTable = matcher._memoTable;\n\n this.userData = undefined;\n this.doNotMemoize = false;\n\n this._bindings = [];\n this._bindingOffsets = [];\n this._applicationStack = [];\n this._posStack = [0];\n this.inLexifiedContextStack = [false];\n\n this.rightmostFailurePosition = -1;\n this._rightmostFailurePositionStack = [];\n this._recordedFailuresStack = [];\n\n if (optPositionToRecordFailures !== undefined) {\n this.positionToRecordFailures = optPositionToRecordFailures;\n this.recordedFailures = Object.create(null);\n }\n }\n\n posToOffset(pos) {\n return pos - this._posStack[this._posStack.length - 1];\n }\n\n enterApplication(posInfo, app) {\n this._posStack.push(this.inputStream.pos);\n this._applicationStack.push(app);\n this.inLexifiedContextStack.push(false);\n posInfo.enter(app);\n this._rightmostFailurePositionStack.push(this.rightmostFailurePosition);\n this.rightmostFailurePosition = -1;\n }\n\n exitApplication(posInfo, optNode) {\n const origPos = this._posStack.pop();\n this._applicationStack.pop();\n this.inLexifiedContextStack.pop();\n posInfo.exit();\n\n this.rightmostFailurePosition = Math.max(\n this.rightmostFailurePosition,\n this._rightmostFailurePositionStack.pop(),\n );\n\n if (optNode) {\n this.pushBinding(optNode, origPos);\n }\n }\n\n enterLexifiedContext() {\n this.inLexifiedContextStack.push(true);\n }\n\n exitLexifiedContext() {\n this.inLexifiedContextStack.pop();\n }\n\n currentApplication() {\n return this._applicationStack[this._applicationStack.length - 1];\n }\n\n inSyntacticContext() {\n const currentApplication = this.currentApplication();\n if (currentApplication) {\n return currentApplication.isSyntactic() && !this.inLexifiedContext();\n } else {\n // The top-level context is syntactic if the start application is.\n return this.startExpr.factors[0].isSyntactic();\n }\n }\n\n inLexifiedContext() {\n return this.inLexifiedContextStack[this.inLexifiedContextStack.length - 1];\n }\n\n skipSpaces() {\n this.pushFailuresInfo();\n this.eval(applySpaces);\n this.popBinding();\n this.popFailuresInfo();\n return this.inputStream.pos;\n }\n\n skipSpacesIfInSyntacticContext() {\n return this.inSyntacticContext() ? this.skipSpaces() : this.inputStream.pos;\n }\n\n maybeSkipSpacesBefore(expr) {\n if (expr.allowsSkippingPrecedingSpace() && expr !== applySpaces) {\n return this.skipSpacesIfInSyntacticContext();\n } else {\n return this.inputStream.pos;\n }\n }\n\n pushBinding(node, origPos) {\n this._bindings.push(node);\n this._bindingOffsets.push(this.posToOffset(origPos));\n }\n\n popBinding() {\n this._bindings.pop();\n this._bindingOffsets.pop();\n }\n\n numBindings() {\n return this._bindings.length;\n }\n\n truncateBindings(newLength) {\n // Yes, this is this really faster than setting the `length` property (tested with\n // bin/es5bench on Node v6.1.0).\n // Update 2021-10-25: still true on v14.15.5 — it's ~20% speedup on es5bench.\n while (this._bindings.length > newLength) {\n this.popBinding();\n }\n }\n\n getCurrentPosInfo() {\n return this.getPosInfo(this.inputStream.pos);\n }\n\n getPosInfo(pos) {\n let posInfo = this.memoTable[pos];\n if (!posInfo) {\n posInfo = this.memoTable[pos] = new PosInfo();\n }\n return posInfo;\n }\n\n processFailure(pos, expr) {\n this.rightmostFailurePosition = Math.max(this.rightmostFailurePosition, pos);\n\n if (this.recordedFailures && pos === this.positionToRecordFailures) {\n const app = this.currentApplication();\n if (app) {\n // Substitute parameters with the actual pexprs that were passed to\n // the current rule.\n expr = expr.substituteParams(app.args);\n }\n\n this.recordFailure(expr.toFailure(this.grammar), false);\n }\n }\n\n recordFailure(failure, shouldCloneIfNew) {\n const key = failure.toKey();\n if (!this.recordedFailures[key]) {\n this.recordedFailures[key] = shouldCloneIfNew ? failure.clone() : failure;\n } else if (this.recordedFailures[key].isFluffy() && !failure.isFluffy()) {\n this.recordedFailures[key].clearFluffy();\n }\n }\n\n recordFailures(failures, shouldCloneIfNew) {\n Object.keys(failures).forEach(key => {\n this.recordFailure(failures[key], shouldCloneIfNew);\n });\n }\n\n cloneRecordedFailures() {\n if (!this.recordedFailures) {\n return undefined;\n }\n\n const ans = Object.create(null);\n Object.keys(this.recordedFailures).forEach(key => {\n ans[key] = this.recordedFailures[key].clone();\n });\n return ans;\n }\n\n getRightmostFailurePosition() {\n return this.rightmostFailurePosition;\n }\n\n _getRightmostFailureOffset() {\n return this.rightmostFailurePosition >= 0 ?\n this.posToOffset(this.rightmostFailurePosition) :\n -1;\n }\n\n // Returns the memoized trace entry for `expr` at `pos`, if one exists, `null` otherwise.\n getMemoizedTraceEntry(pos, expr) {\n const posInfo = this.memoTable[pos];\n if (posInfo && expr instanceof Apply) {\n const memoRec = posInfo.memo[expr.toMemoKey()];\n if (memoRec && memoRec.traceEntry) {\n const entry = memoRec.traceEntry.cloneWithExpr(expr);\n entry.isMemoized = true;\n return entry;\n }\n }\n return null;\n }\n\n // Returns a new trace entry, with the currently active trace array as its children.\n getTraceEntry(pos, expr, succeeded, bindings) {\n if (expr instanceof Apply) {\n const app = this.currentApplication();\n const actuals = app ? app.args : [];\n expr = expr.substituteParams(actuals);\n }\n return (\n this.getMemoizedTraceEntry(pos, expr) ||\n new Trace(this.input, pos, this.inputStream.pos, expr, succeeded, bindings, this.trace)\n );\n }\n\n isTracing() {\n return !!this.trace;\n }\n\n hasNecessaryInfo(memoRec) {\n if (this.trace && !memoRec.traceEntry) {\n return false;\n }\n\n if (\n this.recordedFailures &&\n this.inputStream.pos + memoRec.rightmostFailureOffset === this.positionToRecordFailures\n ) {\n return !!memoRec.failuresAtRightmostPosition;\n }\n\n return true;\n }\n\n useMemoizedResult(origPos, memoRec) {\n if (this.trace) {\n this.trace.push(memoRec.traceEntry);\n }\n\n const memoRecRightmostFailurePosition =\n this.inputStream.pos + memoRec.rightmostFailureOffset;\n this.rightmostFailurePosition = Math.max(\n this.rightmostFailurePosition,\n memoRecRightmostFailurePosition,\n );\n if (\n this.recordedFailures &&\n this.positionToRecordFailures === memoRecRightmostFailurePosition &&\n memoRec.failuresAtRightmostPosition\n ) {\n this.recordFailures(memoRec.failuresAtRightmostPosition, true);\n }\n\n this.inputStream.examinedLength = Math.max(\n this.inputStream.examinedLength,\n memoRec.examinedLength + origPos,\n );\n\n if (memoRec.value) {\n this.inputStream.pos += memoRec.matchLength;\n this.pushBinding(memoRec.value, origPos);\n return true;\n }\n return false;\n }\n\n // Evaluate `expr` and return `true` if it succeeded, `false` otherwise. On success, `bindings`\n // will have `expr.getArity()` more elements than before, and the input stream's position may\n // have increased. On failure, `bindings` and position will be unchanged.\n eval(expr) {\n const {inputStream} = this;\n const origNumBindings = this._bindings.length;\n const origUserData = this.userData;\n\n let origRecordedFailures;\n if (this.recordedFailures) {\n origRecordedFailures = this.recordedFailures;\n this.recordedFailures = Object.create(null);\n }\n\n const origPos = inputStream.pos;\n const memoPos = this.maybeSkipSpacesBefore(expr);\n\n let origTrace;\n if (this.trace) {\n origTrace = this.trace;\n this.trace = [];\n }\n\n // Do the actual evaluation.\n const ans = expr.eval(this);\n\n if (this.trace) {\n const bindings = this._bindings.slice(origNumBindings);\n const traceEntry = this.getTraceEntry(memoPos, expr, ans, bindings);\n traceEntry.isImplicitSpaces = expr === applySpaces;\n traceEntry.isRootNode = expr === this.startExpr;\n origTrace.push(traceEntry);\n this.trace = origTrace;\n }\n\n if (ans) {\n if (this.recordedFailures && inputStream.pos === this.positionToRecordFailures) {\n Object.keys(this.recordedFailures).forEach(key => {\n this.recordedFailures[key].makeFluffy();\n });\n }\n } else {\n // Reset the position, bindings, and userData.\n inputStream.pos = origPos;\n this.truncateBindings(origNumBindings);\n this.userData = origUserData;\n }\n\n if (this.recordedFailures) {\n this.recordFailures(origRecordedFailures, false);\n }\n\n // The built-in applySyntactic rule needs special handling: we want to skip\n // trailing spaces, just as with the top-level application of a syntactic rule.\n if (expr === builtInApplySyntacticBody) {\n this.skipSpaces();\n }\n\n return ans;\n }\n\n getMatchResult() {\n this.grammar._setUpMatchState(this);\n this.eval(this.startExpr);\n let rightmostFailures;\n if (this.recordedFailures) {\n rightmostFailures = Object.keys(this.recordedFailures).map(\n key => this.recordedFailures[key],\n );\n }\n const cst = this._bindings[0];\n if (cst) {\n cst.grammar = this.grammar;\n }\n return new MatchResult(\n this.matcher,\n this.input,\n this.startExpr,\n cst,\n this._bindingOffsets[0],\n this.rightmostFailurePosition,\n rightmostFailures,\n );\n }\n\n getTrace() {\n this.trace = [];\n const matchResult = this.getMatchResult();\n\n // The trace node for the start rule is always the last entry. If it is a syntactic rule,\n // the first entry is for an application of 'spaces'.\n // TODO(pdubroy): Clean this up by introducing a special `Match` rule, which will\n // ensure that there is always a single root trace node.\n const rootTrace = this.trace[this.trace.length - 1];\n rootTrace.result = matchResult;\n return rootTrace;\n }\n\n pushFailuresInfo() {\n this._rightmostFailurePositionStack.push(this.rightmostFailurePosition);\n this._recordedFailuresStack.push(this.recordedFailures);\n }\n\n popFailuresInfo() {\n this.rightmostFailurePosition = this._rightmostFailurePositionStack.pop();\n this.recordedFailures = this._recordedFailuresStack.pop();\n }\n}\n\nclass Matcher {\n constructor(grammar) {\n this.grammar = grammar;\n this._memoTable = [];\n this._input = '';\n this._isMemoTableStale = false;\n }\n\n _resetMemoTable() {\n this._memoTable = [];\n this._isMemoTableStale = false;\n }\n\n getInput() {\n return this._input;\n }\n\n setInput(str) {\n if (this._input !== str) {\n this.replaceInputRange(0, this._input.length, str);\n }\n return this;\n }\n\n replaceInputRange(startIdx, endIdx, str) {\n const prevInput = this._input;\n const memoTable = this._memoTable;\n if (\n startIdx < 0 ||\n startIdx > prevInput.length ||\n endIdx < 0 ||\n endIdx > prevInput.length ||\n startIdx > endIdx\n ) {\n throw new Error('Invalid indices: ' + startIdx + ' and ' + endIdx);\n }\n\n // update input\n this._input = prevInput.slice(0, startIdx) + str + prevInput.slice(endIdx);\n if (this._input !== prevInput && memoTable.length > 0) {\n this._isMemoTableStale = true;\n }\n\n // update memo table (similar to the above)\n const restOfMemoTable = memoTable.slice(endIdx);\n memoTable.length = startIdx;\n for (let idx = 0; idx < str.length; idx++) {\n memoTable.push(undefined);\n }\n for (const posInfo of restOfMemoTable) {\n memoTable.push(posInfo);\n }\n\n // Invalidate memoRecs\n for (let pos = 0; pos < startIdx; pos++) {\n const posInfo = memoTable[pos];\n if (posInfo) {\n posInfo.clearObsoleteEntries(pos, startIdx);\n }\n }\n\n return this;\n }\n\n match(optStartApplicationStr, options = {incremental: true}) {\n return this._match(this._getStartExpr(optStartApplicationStr), {\n incremental: options.incremental,\n tracing: false,\n });\n }\n\n trace(optStartApplicationStr, options = {incremental: true}) {\n return this._match(this._getStartExpr(optStartApplicationStr), {\n incremental: options.incremental,\n tracing: true,\n });\n }\n\n _match(startExpr, options = {}) {\n const opts = {\n tracing: false,\n incremental: true,\n positionToRecordFailures: undefined,\n ...options,\n };\n if (!opts.incremental) {\n this._resetMemoTable();\n } else if (this._isMemoTableStale && !this.grammar.supportsIncrementalParsing) {\n throw grammarDoesNotSupportIncrementalParsing(this.grammar);\n }\n\n const state = new MatchState(this, startExpr, opts.positionToRecordFailures);\n return opts.tracing ? state.getTrace() : state.getMatchResult();\n }\n\n /*\n Returns the starting expression for this Matcher's associated grammar. If\n `optStartApplicationStr` is specified, it is a string expressing a rule application in the\n grammar. If not specified, the grammar's default start rule will be used.\n */\n _getStartExpr(optStartApplicationStr) {\n const applicationStr = optStartApplicationStr || this.grammar.defaultStartRule;\n if (!applicationStr) {\n throw new Error('Missing start rule argument -- the grammar has no default start rule.');\n }\n\n const startApp = this.grammar.parseApplication(applicationStr);\n return new Seq([startApp, end]);\n }\n}\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nconst globalActionStack = [];\n\nconst hasOwnProperty = (x, prop) => Object.prototype.hasOwnProperty.call(x, prop);\n\n// ----------------- Wrappers -----------------\n\n// Wrappers decorate CST nodes with all of the functionality (i.e., operations and attributes)\n// provided by a Semantics (see below). `Wrapper` is the abstract superclass of all wrappers. A\n// `Wrapper` must have `_node` and `_semantics` instance variables, which refer to the CST node and\n// Semantics (resp.) for which it was created, and a `_childWrappers` instance variable which is\n// used to cache the wrapper instances that are created for its child nodes. Setting these instance\n// variables is the responsibility of the constructor of each Semantics-specific subclass of\n// `Wrapper`.\nclass Wrapper {\n constructor(node, sourceInterval, baseInterval) {\n this._node = node;\n this.source = sourceInterval;\n\n // The interval that the childOffsets of `node` are relative to. It should be the source\n // of the closest Nonterminal node.\n this._baseInterval = baseInterval;\n\n if (node.isNonterminal()) {\n assert(sourceInterval === baseInterval);\n }\n this._childWrappers = [];\n }\n\n _forgetMemoizedResultFor(attributeName) {\n // Remove the memoized attribute from the cstNode and all its children.\n delete this._node[this._semantics.attributeKeys[attributeName]];\n this.children.forEach(child => {\n child._forgetMemoizedResultFor(attributeName);\n });\n }\n\n // Returns the wrapper of the specified child node. Child wrappers are created lazily and\n // cached in the parent wrapper's `_childWrappers` instance variable.\n child(idx) {\n if (!(0 <= idx && idx < this._node.numChildren())) {\n // TODO: Consider throwing an exception here.\n return undefined;\n }\n let childWrapper = this._childWrappers[idx];\n if (!childWrapper) {\n const childNode = this._node.childAt(idx);\n const offset = this._node.childOffsets[idx];\n\n const source = this._baseInterval.subInterval(offset, childNode.matchLength);\n const base = childNode.isNonterminal() ? source : this._baseInterval;\n childWrapper = this._childWrappers[idx] = this._semantics.wrap(childNode, source, base);\n }\n return childWrapper;\n }\n\n // Returns an array containing the wrappers of all of the children of the node associated\n // with this wrapper.\n _children() {\n // Force the creation of all child wrappers\n for (let idx = 0; idx < this._node.numChildren(); idx++) {\n this.child(idx);\n }\n return this._childWrappers;\n }\n\n // Returns `true` if the CST node associated with this wrapper corresponds to an iteration\n // expression, i.e., a Kleene-*, Kleene-+, or an optional. Returns `false` otherwise.\n isIteration() {\n return this._node.isIteration();\n }\n\n // Returns `true` if the CST node associated with this wrapper is a terminal node, `false`\n // otherwise.\n isTerminal() {\n return this._node.isTerminal();\n }\n\n // Returns `true` if the CST node associated with this wrapper is a nonterminal node, `false`\n // otherwise.\n isNonterminal() {\n return this._node.isNonterminal();\n }\n\n // Returns `true` if the CST node associated with this wrapper is a nonterminal node\n // corresponding to a syntactic rule, `false` otherwise.\n isSyntactic() {\n return this.isNonterminal() && this._node.isSyntactic();\n }\n\n // Returns `true` if the CST node associated with this wrapper is a nonterminal node\n // corresponding to a lexical rule, `false` otherwise.\n isLexical() {\n return this.isNonterminal() && this._node.isLexical();\n }\n\n // Returns `true` if the CST node associated with this wrapper is an iterator node\n // having either one or no child (? operator), `false` otherwise.\n // Otherwise, throws an exception.\n isOptional() {\n return this._node.isOptional();\n }\n\n // Create a new _iter wrapper in the same semantics as this wrapper.\n iteration(optChildWrappers) {\n const childWrappers = optChildWrappers || [];\n\n const childNodes = childWrappers.map(c => c._node);\n const iter = new IterationNode(childNodes, [], -1, false);\n\n const wrapper = this._semantics.wrap(iter, null, null);\n wrapper._childWrappers = childWrappers;\n return wrapper;\n }\n\n // Returns an array containing the children of this CST node.\n get children() {\n return this._children();\n }\n\n // Returns the name of grammar rule that created this CST node.\n get ctorName() {\n return this._node.ctorName;\n }\n\n // Returns the number of children of this CST node.\n get numChildren() {\n return this._node.numChildren();\n }\n\n // Returns the contents of the input stream consumed by this CST node.\n get sourceString() {\n return this.source.contents;\n }\n}\n\n// ----------------- Semantics -----------------\n\n// A Semantics is a container for a family of Operations and Attributes for a given grammar.\n// Semantics enable modularity (different clients of a grammar can create their set of operations\n// and attributes in isolation) and extensibility even when operations and attributes are mutually-\n// recursive. This constructor should not be called directly except from\n// `Semantics.createSemantics`. The normal ways to create a Semantics, given a grammar 'g', are\n// `g.createSemantics()` and `g.extendSemantics(parentSemantics)`.\nclass Semantics {\n constructor(grammar, superSemantics) {\n const self = this;\n this.grammar = grammar;\n this.checkedActionDicts = false;\n\n // Constructor for wrapper instances, which are passed as the arguments to the semantic actions\n // of an operation or attribute. Operations and attributes require double dispatch: the semantic\n // action is chosen based on both the node's type and the semantics. Wrappers ensure that\n // the `execute` method is called with the correct (most specific) semantics object as an\n // argument.\n this.Wrapper = class extends (superSemantics ? superSemantics.Wrapper : Wrapper) {\n constructor(node, sourceInterval, baseInterval) {\n super(node, sourceInterval, baseInterval);\n self.checkActionDictsIfHaventAlready();\n this._semantics = self;\n }\n\n toString() {\n return '[semantics wrapper for ' + self.grammar.name + ']';\n }\n };\n\n this.super = superSemantics;\n if (superSemantics) {\n if (!(grammar.equals(this.super.grammar) || grammar._inheritsFrom(this.super.grammar))) {\n throw new Error(\n \"Cannot extend a semantics for grammar '\" +\n this.super.grammar.name +\n \"' for use with grammar '\" +\n grammar.name +\n \"' (not a sub-grammar)\",\n );\n }\n this.operations = Object.create(this.super.operations);\n this.attributes = Object.create(this.super.attributes);\n this.attributeKeys = Object.create(null);\n\n // Assign unique symbols for each of the attributes inherited from the super-semantics so that\n // they are memoized independently.\n // eslint-disable-next-line guard-for-in\n for (const attributeName in this.attributes) {\n Object.defineProperty(this.attributeKeys, attributeName, {\n value: uniqueId(attributeName),\n });\n }\n } else {\n this.operations = Object.create(null);\n this.attributes = Object.create(null);\n this.attributeKeys = Object.create(null);\n }\n }\n\n toString() {\n return '[semantics for ' + this.grammar.name + ']';\n }\n\n checkActionDictsIfHaventAlready() {\n if (!this.checkedActionDicts) {\n this.checkActionDicts();\n this.checkedActionDicts = true;\n }\n }\n\n // Checks that the action dictionaries for all operations and attributes in this semantics,\n // including the ones that were inherited from the super-semantics, agree with the grammar.\n // Throws an exception if one or more of them doesn't.\n checkActionDicts() {\n let name;\n // eslint-disable-next-line guard-for-in\n for (name in this.operations) {\n this.operations[name].checkActionDict(this.grammar);\n }\n // eslint-disable-next-line guard-for-in\n for (name in this.attributes) {\n this.attributes[name].checkActionDict(this.grammar);\n }\n }\n\n toRecipe(semanticsOnly) {\n function hasSuperSemantics(s) {\n return s.super !== Semantics.BuiltInSemantics._getSemantics();\n }\n\n let str = '(function(g) {\\n';\n if (hasSuperSemantics(this)) {\n str += ' var semantics = ' + this.super.toRecipe(true) + '(g';\n\n const superSemanticsGrammar = this.super.grammar;\n let relatedGrammar = this.grammar;\n while (relatedGrammar !== superSemanticsGrammar) {\n str += '.superGrammar';\n relatedGrammar = relatedGrammar.superGrammar;\n }\n\n str += ');\\n';\n str += ' return g.extendSemantics(semantics)';\n } else {\n str += ' return g.createSemantics()';\n }\n ['Operation', 'Attribute'].forEach(type => {\n const semanticOperations = this[type.toLowerCase() + 's'];\n Object.keys(semanticOperations).forEach(name => {\n const {actionDict, formals, builtInDefault} = semanticOperations[name];\n\n let signature = name;\n if (formals.length > 0) {\n signature += '(' + formals.join(', ') + ')';\n }\n\n let method;\n if (hasSuperSemantics(this) && this.super[type.toLowerCase() + 's'][name]) {\n method = 'extend' + type;\n } else {\n method = 'add' + type;\n }\n str += '\\n .' + method + '(' + JSON.stringify(signature) + ', {';\n\n const srcArray = [];\n Object.keys(actionDict).forEach(actionName => {\n if (actionDict[actionName] !== builtInDefault) {\n let source = actionDict[actionName].toString().trim();\n\n // Convert method shorthand to plain old function syntax.\n // https://github.com/ohmjs/ohm/issues/263\n source = source.replace(/^.*\\(/, 'function(');\n\n srcArray.push('\\n ' + JSON.stringify(actionName) + ': ' + source);\n }\n });\n str += srcArray.join(',') + '\\n })';\n });\n });\n str += ';\\n })';\n\n if (!semanticsOnly) {\n str =\n '(function() {\\n' +\n ' var grammar = this.fromRecipe(' +\n this.grammar.toRecipe() +\n ');\\n' +\n ' var semantics = ' +\n str +\n '(grammar);\\n' +\n ' return semantics;\\n' +\n '});\\n';\n }\n\n return str;\n }\n\n addOperationOrAttribute(type, signature, actionDict) {\n const typePlural = type + 's';\n\n const parsedNameAndFormalArgs = parseSignature(signature, type);\n const {name} = parsedNameAndFormalArgs;\n const {formals} = parsedNameAndFormalArgs;\n\n // TODO: check that there are no duplicate formal arguments\n\n this.assertNewName(name, type);\n\n // Create the action dictionary for this operation / attribute that contains a `_default` action\n // which defines the default behavior of iteration, terminal, and non-terminal nodes...\n const builtInDefault = newDefaultAction(type, name, doIt);\n const realActionDict = {_default: builtInDefault};\n // ... and add in the actions supplied by the programmer, which may override some or all of the\n // default ones.\n Object.keys(actionDict).forEach(name => {\n realActionDict[name] = actionDict[name];\n });\n\n const entry =\n type === 'operation' ?\n new Operation(name, formals, realActionDict, builtInDefault) :\n new Attribute(name, realActionDict, builtInDefault);\n\n // The following check is not strictly necessary (it will happen later anyway) but it's better\n // to catch errors early.\n entry.checkActionDict(this.grammar);\n\n this[typePlural][name] = entry;\n\n function doIt(...args) {\n // Dispatch to most specific version of this operation / attribute -- it may have been\n // overridden by a sub-semantics.\n const thisThing = this._semantics[typePlural][name];\n\n // Check that the caller passed the correct number of arguments.\n if (arguments.length !== thisThing.formals.length) {\n throw new Error(\n 'Invalid number of arguments passed to ' +\n name +\n ' ' +\n type +\n ' (expected ' +\n thisThing.formals.length +\n ', got ' +\n arguments.length +\n ')',\n );\n }\n\n // Create an \"arguments object\" from the arguments that were passed to this\n // operation / attribute.\n const argsObj = Object.create(null);\n for (const [idx, val] of Object.entries(args)) {\n const formal = thisThing.formals[idx];\n argsObj[formal] = val;\n }\n\n const oldArgs = this.args;\n this.args = argsObj;\n const ans = thisThing.execute(this._semantics, this);\n this.args = oldArgs;\n return ans;\n }\n\n if (type === 'operation') {\n this.Wrapper.prototype[name] = doIt;\n this.Wrapper.prototype[name].toString = function() {\n return '[' + name + ' operation]';\n };\n } else {\n Object.defineProperty(this.Wrapper.prototype, name, {\n get: doIt,\n configurable: true, // So the property can be deleted.\n });\n Object.defineProperty(this.attributeKeys, name, {\n value: uniqueId(name),\n });\n }\n }\n\n extendOperationOrAttribute(type, name, actionDict) {\n const typePlural = type + 's';\n\n // Make sure that `name` really is just a name, i.e., that it doesn't also contain formals.\n parseSignature(name, 'attribute');\n\n if (!(this.super && name in this.super[typePlural])) {\n throw new Error(\n 'Cannot extend ' +\n type +\n \" '\" +\n name +\n \"': did not inherit an \" +\n type +\n ' with that name',\n );\n }\n if (hasOwnProperty(this[typePlural], name)) {\n throw new Error('Cannot extend ' + type + \" '\" + name + \"' again\");\n }\n\n // Create a new operation / attribute whose actionDict delegates to the super operation /\n // attribute's actionDict, and which has all the keys from `inheritedActionDict`.\n const inheritedFormals = this[typePlural][name].formals;\n const inheritedActionDict = this[typePlural][name].actionDict;\n const newActionDict = Object.create(inheritedActionDict);\n Object.keys(actionDict).forEach(name => {\n newActionDict[name] = actionDict[name];\n });\n\n this[typePlural][name] =\n type === 'operation' ?\n new Operation(name, inheritedFormals, newActionDict) :\n new Attribute(name, newActionDict);\n\n // The following check is not strictly necessary (it will happen later anyway) but it's better\n // to catch errors early.\n this[typePlural][name].checkActionDict(this.grammar);\n }\n\n assertNewName(name, type) {\n if (hasOwnProperty(Wrapper.prototype, name)) {\n throw new Error('Cannot add ' + type + \" '\" + name + \"': that's a reserved name\");\n }\n if (name in this.operations) {\n throw new Error(\n 'Cannot add ' + type + \" '\" + name + \"': an operation with that name already exists\",\n );\n }\n if (name in this.attributes) {\n throw new Error(\n 'Cannot add ' + type + \" '\" + name + \"': an attribute with that name already exists\",\n );\n }\n }\n\n // Returns a wrapper for the given CST `node` in this semantics.\n // If `node` is already a wrapper, returns `node` itself. // TODO: why is this needed?\n wrap(node, source, optBaseInterval) {\n const baseInterval = optBaseInterval || source;\n return node instanceof this.Wrapper ? node : new this.Wrapper(node, source, baseInterval);\n }\n}\n\nfunction parseSignature(signature, type) {\n if (!Semantics.prototypeGrammar) {\n // The Operations and Attributes grammar won't be available while Ohm is loading,\n // but we can get away the following simplification b/c none of the operations\n // that are used while loading take arguments.\n assert(signature.indexOf('(') === -1);\n return {\n name: signature,\n formals: [],\n };\n }\n\n const r = Semantics.prototypeGrammar.match(\n signature,\n type === 'operation' ? 'OperationSignature' : 'AttributeSignature',\n );\n if (r.failed()) {\n throw new Error(r.message);\n }\n\n return Semantics.prototypeGrammarSemantics(r).parse();\n}\n\nfunction newDefaultAction(type, name, doIt) {\n return function(...children) {\n const thisThing = this._semantics.operations[name] || this._semantics.attributes[name];\n const args = thisThing.formals.map(formal => this.args[formal]);\n\n if (!this.isIteration() && children.length === 1) {\n // This CST node corresponds to a non-terminal in the grammar (e.g., AddExpr). The fact that\n // we got here means that this action dictionary doesn't have an action for this particular\n // non-terminal or a generic `_nonterminal` action.\n // As a convenience, if this node only has one child, we just return the result of applying\n // this operation / attribute to the child node.\n return doIt.apply(children[0], args);\n } else {\n // Otherwise, we throw an exception to let the programmer know that we don't know what\n // to do with this node.\n throw missingSemanticAction(this.ctorName, name, type, globalActionStack);\n }\n };\n}\n\n// Creates a new Semantics instance for `grammar`, inheriting operations and attributes from\n// `optSuperSemantics`, if it is specified. Returns a function that acts as a proxy for the new\n// Semantics instance. When that function is invoked with a CST node as an argument, it returns\n// a wrapper for that node which gives access to the operations and attributes provided by this\n// semantics.\nSemantics.createSemantics = function(grammar, optSuperSemantics) {\n const s = new Semantics(\n grammar,\n optSuperSemantics !== undefined ?\n optSuperSemantics :\n Semantics.BuiltInSemantics._getSemantics(),\n );\n\n // To enable clients to invoke a semantics like a function, return a function that acts as a proxy\n // for `s`, which is the real `Semantics` instance.\n const proxy = function ASemantics(matchResult) {\n if (!(matchResult instanceof MatchResult)) {\n throw new TypeError(\n 'Semantics expected a MatchResult, but got ' +\n unexpectedObjToString(matchResult),\n );\n }\n if (matchResult.failed()) {\n throw new TypeError('cannot apply Semantics to ' + matchResult.toString());\n }\n\n const cst = matchResult._cst;\n if (cst.grammar !== grammar) {\n throw new Error(\n \"Cannot use a MatchResult from grammar '\" +\n cst.grammar.name +\n \"' with a semantics for '\" +\n grammar.name +\n \"'\",\n );\n }\n const inputStream = new InputStream(matchResult.input);\n return s.wrap(cst, inputStream.interval(matchResult._cstOffset, matchResult.input.length));\n };\n\n // Forward public methods from the proxy to the semantics instance.\n proxy.addOperation = function(signature, actionDict) {\n s.addOperationOrAttribute('operation', signature, actionDict);\n return proxy;\n };\n proxy.extendOperation = function(name, actionDict) {\n s.extendOperationOrAttribute('operation', name, actionDict);\n return proxy;\n };\n proxy.addAttribute = function(name, actionDict) {\n s.addOperationOrAttribute('attribute', name, actionDict);\n return proxy;\n };\n proxy.extendAttribute = function(name, actionDict) {\n s.extendOperationOrAttribute('attribute', name, actionDict);\n return proxy;\n };\n proxy._getActionDict = function(operationOrAttributeName) {\n const action =\n s.operations[operationOrAttributeName] || s.attributes[operationOrAttributeName];\n if (!action) {\n throw new Error(\n '\"' +\n operationOrAttributeName +\n '\" is not a valid operation or attribute ' +\n 'name in this semantics for \"' +\n grammar.name +\n '\"',\n );\n }\n return action.actionDict;\n };\n proxy._remove = function(operationOrAttributeName) {\n let semantic;\n if (operationOrAttributeName in s.operations) {\n semantic = s.operations[operationOrAttributeName];\n delete s.operations[operationOrAttributeName];\n } else if (operationOrAttributeName in s.attributes) {\n semantic = s.attributes[operationOrAttributeName];\n delete s.attributes[operationOrAttributeName];\n }\n delete s.Wrapper.prototype[operationOrAttributeName];\n return semantic;\n };\n proxy.getOperationNames = function() {\n return Object.keys(s.operations);\n };\n proxy.getAttributeNames = function() {\n return Object.keys(s.attributes);\n };\n proxy.getGrammar = function() {\n return s.grammar;\n };\n proxy.toRecipe = function(semanticsOnly) {\n return s.toRecipe(semanticsOnly);\n };\n\n // Make the proxy's toString() work.\n proxy.toString = s.toString.bind(s);\n\n // Returns the semantics for the proxy.\n proxy._getSemantics = function() {\n return s;\n };\n\n return proxy;\n};\n\n// ----------------- Operation -----------------\n\n// An Operation represents a function to be applied to a concrete syntax tree (CST) -- it's very\n// similar to a Visitor (http://en.wikipedia.org/wiki/Visitor_pattern). An operation is executed by\n// recursively walking the CST, and at each node, invoking the matching semantic action from\n// `actionDict`. See `Operation.prototype.execute` for details of how a CST node's matching semantic\n// action is found.\nclass Operation {\n constructor(name, formals, actionDict, builtInDefault) {\n this.name = name;\n this.formals = formals;\n this.actionDict = actionDict;\n this.builtInDefault = builtInDefault;\n }\n\n checkActionDict(grammar) {\n grammar._checkTopDownActionDict(this.typeName, this.name, this.actionDict);\n }\n\n // Execute this operation on the CST node associated with `nodeWrapper` in the context of the\n // given Semantics instance.\n execute(semantics, nodeWrapper) {\n try {\n // Look for a semantic action whose name matches the node's constructor name, which is either\n // the name of a rule in the grammar, or '_terminal' (for a terminal node), or '_iter' (for an\n // iteration node).\n const {ctorName} = nodeWrapper._node;\n let actionFn = this.actionDict[ctorName];\n if (actionFn) {\n globalActionStack.push([this, ctorName]);\n return actionFn.apply(nodeWrapper, nodeWrapper._children());\n }\n\n // The action dictionary does not contain a semantic action for this specific type of node.\n // If this is a nonterminal node and the programmer has provided a `_nonterminal` semantic\n // action, we invoke it:\n if (nodeWrapper.isNonterminal()) {\n actionFn = this.actionDict._nonterminal;\n if (actionFn) {\n globalActionStack.push([this, '_nonterminal', ctorName]);\n return actionFn.apply(nodeWrapper, nodeWrapper._children());\n }\n }\n\n // Otherwise, we invoke the '_default' semantic action.\n globalActionStack.push([this, 'default action', ctorName]);\n return this.actionDict._default.apply(nodeWrapper, nodeWrapper._children());\n } finally {\n globalActionStack.pop();\n }\n }\n}\n\nOperation.prototype.typeName = 'operation';\n\n// ----------------- Attribute -----------------\n\n// Attributes are Operations whose results are memoized. This means that, for any given semantics,\n// the semantic action for a CST node will be invoked no more than once.\nclass Attribute extends Operation {\n constructor(name, actionDict, builtInDefault) {\n super(name, [], actionDict, builtInDefault);\n }\n\n execute(semantics, nodeWrapper) {\n const node = nodeWrapper._node;\n const key = semantics.attributeKeys[this.name];\n if (!hasOwnProperty(node, key)) {\n // The following is a super-send -- isn't JS beautiful? :/\n node[key] = Operation.prototype.execute.call(this, semantics, nodeWrapper);\n }\n return node[key];\n }\n}\n\nAttribute.prototype.typeName = 'attribute';\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nconst SPECIAL_ACTION_NAMES = ['_iter', '_terminal', '_nonterminal', '_default'];\n\nfunction getSortedRuleValues(grammar) {\n return Object.keys(grammar.rules)\n .sort()\n .map(name => grammar.rules[name]);\n}\n\n// Until ES2019, JSON was not a valid subset of JavaScript because U+2028 (line separator)\n// and U+2029 (paragraph separator) are allowed in JSON string literals, but not in JS.\n// This function properly encodes those two characters so that the resulting string is\n// represents both valid JSON, and valid JavaScript (for ES2018 and below).\n// See https://v8.dev/features/subsume-json for more details.\nconst jsonToJS = str => str.replace(/\\u2028/g, '\\\\u2028').replace(/\\u2029/g, '\\\\u2029');\n\nlet ohmGrammar$1;\nlet buildGrammar$1;\n\nclass Grammar {\n constructor(name, superGrammar, rules, optDefaultStartRule) {\n this.name = name;\n this.superGrammar = superGrammar;\n this.rules = rules;\n if (optDefaultStartRule) {\n if (!(optDefaultStartRule in rules)) {\n throw new Error(\n \"Invalid start rule: '\" +\n optDefaultStartRule +\n \"' is not a rule in grammar '\" +\n name +\n \"'\",\n );\n }\n this.defaultStartRule = optDefaultStartRule;\n }\n this._matchStateInitializer = undefined;\n this.supportsIncrementalParsing = true;\n }\n\n matcher() {\n return new Matcher(this);\n }\n\n // Return true if the grammar is a built-in grammar, otherwise false.\n // NOTE: This might give an unexpected result if called before BuiltInRules is defined!\n isBuiltIn() {\n return this === Grammar.ProtoBuiltInRules || this === Grammar.BuiltInRules;\n }\n\n equals(g) {\n if (this === g) {\n return true;\n }\n // Do the cheapest comparisons first.\n if (\n g == null ||\n this.name !== g.name ||\n this.defaultStartRule !== g.defaultStartRule ||\n !(this.superGrammar === g.superGrammar || this.superGrammar.equals(g.superGrammar))\n ) {\n return false;\n }\n const myRules = getSortedRuleValues(this);\n const otherRules = getSortedRuleValues(g);\n return (\n myRules.length === otherRules.length &&\n myRules.every((rule, i) => {\n return (\n rule.description === otherRules[i].description &&\n rule.formals.join(',') === otherRules[i].formals.join(',') &&\n rule.body.toString() === otherRules[i].body.toString()\n );\n })\n );\n }\n\n match(input, optStartApplication) {\n const m = this.matcher();\n m.replaceInputRange(0, 0, input);\n return m.match(optStartApplication);\n }\n\n trace(input, optStartApplication) {\n const m = this.matcher();\n m.replaceInputRange(0, 0, input);\n return m.trace(optStartApplication);\n }\n\n createSemantics() {\n return Semantics.createSemantics(this);\n }\n\n extendSemantics(superSemantics) {\n return Semantics.createSemantics(this, superSemantics._getSemantics());\n }\n\n // Check that every key in `actionDict` corresponds to a semantic action, and that it maps to\n // a function of the correct arity. If not, throw an exception.\n _checkTopDownActionDict(what, name, actionDict) {\n const problems = [];\n\n // eslint-disable-next-line guard-for-in\n for (const k in actionDict) {\n const v = actionDict[k];\n const isSpecialAction = SPECIAL_ACTION_NAMES.includes(k);\n\n if (!isSpecialAction && !(k in this.rules)) {\n problems.push(`'${k}' is not a valid semantic action for '${this.name}'`);\n continue;\n }\n if (typeof v !== 'function') {\n problems.push(`'${k}' must be a function in an action dictionary for '${this.name}'`);\n continue;\n }\n const actual = v.length;\n const expected = this._topDownActionArity(k);\n if (actual !== expected) {\n let details;\n if (k === '_iter' || k === '_nonterminal') {\n details =\n `it should use a rest parameter, e.g. \\`${k}(...children) {}\\`. ` +\n 'NOTE: this is new in Ohm v16 — see https://ohmjs.org/d/ati for details.';\n } else {\n details = `expected ${expected}, got ${actual}`;\n }\n problems.push(`Semantic action '${k}' has the wrong arity: ${details}`);\n }\n }\n if (problems.length > 0) {\n const prettyProblems = problems.map(problem => '- ' + problem);\n const error = new Error(\n [\n `Found errors in the action dictionary of the '${name}' ${what}:`,\n ...prettyProblems,\n ].join('\\n'),\n );\n error.problems = problems;\n throw error;\n }\n }\n\n // Return the expected arity for a semantic action named `actionName`, which\n // is either a rule name or a special action name like '_nonterminal'.\n _topDownActionArity(actionName) {\n // All special actions have an expected arity of 0, though all but _terminal\n // are expected to use the rest parameter syntax (e.g. `_iter(...children)`).\n // This is considered to have arity 0, i.e. `((...args) => {}).length` is 0.\n return SPECIAL_ACTION_NAMES.includes(actionName) ?\n 0 :\n this.rules[actionName].body.getArity();\n }\n\n _inheritsFrom(grammar) {\n let g = this.superGrammar;\n while (g) {\n if (g.equals(grammar, true)) {\n return true;\n }\n g = g.superGrammar;\n }\n return false;\n }\n\n toRecipe(superGrammarExpr = undefined) {\n const metaInfo = {};\n // Include the grammar source if it is available.\n if (this.source) {\n metaInfo.source = this.source.contents;\n }\n\n let startRule = null;\n if (this.defaultStartRule) {\n startRule = this.defaultStartRule;\n }\n\n const rules = {};\n Object.keys(this.rules).forEach(ruleName => {\n const ruleInfo = this.rules[ruleName];\n const {body} = ruleInfo;\n const isDefinition = !this.superGrammar || !this.superGrammar.rules[ruleName];\n\n let operation;\n if (isDefinition) {\n operation = 'define';\n } else {\n operation = body instanceof Extend ? 'extend' : 'override';\n }\n\n const metaInfo = {};\n if (ruleInfo.source && this.source) {\n const adjusted = ruleInfo.source.relativeTo(this.source);\n metaInfo.sourceInterval = [adjusted.startIdx, adjusted.endIdx];\n }\n\n const description = isDefinition ? ruleInfo.description : null;\n const bodyRecipe = body.outputRecipe(ruleInfo.formals, this.source);\n\n rules[ruleName] = [\n operation, // \"define\"/\"extend\"/\"override\"\n metaInfo,\n description,\n ruleInfo.formals,\n bodyRecipe,\n ];\n });\n\n // If the caller provided an expression to use for the supergrammar, use that.\n // Otherwise, if the supergrammar is a user grammar, use its recipe inline.\n let superGrammarOutput = 'null';\n if (superGrammarExpr) {\n superGrammarOutput = superGrammarExpr;\n } else if (this.superGrammar && !this.superGrammar.isBuiltIn()) {\n superGrammarOutput = this.superGrammar.toRecipe();\n }\n\n const recipeElements = [\n ...['grammar', metaInfo, this.name].map(JSON.stringify),\n superGrammarOutput,\n ...[startRule, rules].map(JSON.stringify),\n ];\n return jsonToJS(`[${recipeElements.join(',')}]`);\n }\n\n // TODO: Come up with better names for these methods.\n // TODO: Write the analog of these methods for inherited attributes.\n toOperationActionDictionaryTemplate() {\n return this._toOperationOrAttributeActionDictionaryTemplate();\n }\n toAttributeActionDictionaryTemplate() {\n return this._toOperationOrAttributeActionDictionaryTemplate();\n }\n\n _toOperationOrAttributeActionDictionaryTemplate() {\n // TODO: add the super-grammar's templates at the right place, e.g., a case for AddExpr_plus\n // should appear next to other cases of AddExpr.\n\n const sb = new StringBuffer();\n sb.append('{');\n\n let first = true;\n // eslint-disable-next-line guard-for-in\n for (const ruleName in this.rules) {\n const {body} = this.rules[ruleName];\n if (first) {\n first = false;\n } else {\n sb.append(',');\n }\n sb.append('\\n');\n sb.append(' ');\n this.addSemanticActionTemplate(ruleName, body, sb);\n }\n\n sb.append('\\n}');\n return sb.contents();\n }\n\n addSemanticActionTemplate(ruleName, body, sb) {\n sb.append(ruleName);\n sb.append(': function(');\n const arity = this._topDownActionArity(ruleName);\n sb.append(repeat('_', arity).join(', '));\n sb.append(') {\\n');\n sb.append(' }');\n }\n\n // Parse a string which expresses a rule application in this grammar, and return the\n // resulting Apply node.\n parseApplication(str) {\n let app;\n if (str.indexOf('<') === -1) {\n // simple application\n app = new Apply(str);\n } else {\n // parameterized application\n const cst = ohmGrammar$1.match(str, 'Base_application');\n app = buildGrammar$1(cst, {});\n }\n\n // Ensure that the application is valid.\n if (!(app.ruleName in this.rules)) {\n throw undeclaredRule(app.ruleName, this.name);\n }\n const {formals} = this.rules[app.ruleName];\n if (formals.length !== app.args.length) {\n const {source} = this.rules[app.ruleName];\n throw wrongNumberOfParameters(\n app.ruleName,\n formals.length,\n app.args.length,\n source,\n );\n }\n return app;\n }\n\n _setUpMatchState(state) {\n if (this._matchStateInitializer) {\n this._matchStateInitializer(state);\n }\n }\n}\n\n// The following grammar contains a few rules that couldn't be written in \"userland\".\n// At the bottom of src/main.js, we create a sub-grammar of this grammar that's called\n// `BuiltInRules`. That grammar contains several convenience rules, e.g., `letter` and\n// `digit`, and is implicitly the super-grammar of any grammar whose super-grammar\n// isn't specified.\nGrammar.ProtoBuiltInRules = new Grammar(\n 'ProtoBuiltInRules', // name\n undefined, // supergrammar\n {\n any: {\n body: any,\n formals: [],\n description: 'any character',\n primitive: true,\n },\n end: {\n body: end,\n formals: [],\n description: 'end of input',\n primitive: true,\n },\n\n caseInsensitive: {\n body: new CaseInsensitiveTerminal(new Param(0)),\n formals: ['str'],\n primitive: true,\n },\n lower: {\n body: new UnicodeChar('Ll'),\n formals: [],\n description: 'a lowercase letter',\n primitive: true,\n },\n upper: {\n body: new UnicodeChar('Lu'),\n formals: [],\n description: 'an uppercase letter',\n primitive: true,\n },\n // Union of Lt (titlecase), Lm (modifier), and Lo (other), i.e. any letter not in Ll or Lu.\n unicodeLtmo: {\n body: new UnicodeChar('Ltmo'),\n formals: [],\n description: 'a Unicode character in Lt, Lm, or Lo',\n primitive: true,\n },\n\n // These rules are not truly primitive (they could be written in userland) but are defined\n // here for bootstrapping purposes.\n spaces: {\n body: new Star(new Apply('space')),\n formals: [],\n },\n space: {\n body: new Range('\\x00', ' '),\n formals: [],\n description: 'a space',\n },\n },\n);\n\n// This method is called from main.js once Ohm has loaded.\nGrammar.initApplicationParser = function(grammar, builderFn) {\n ohmGrammar$1 = grammar;\n buildGrammar$1 = builderFn;\n};\n\n// --------------------------------------------------------------------\n// Private Stuff\n// --------------------------------------------------------------------\n\n// Constructors\n\nclass GrammarDecl {\n constructor(name) {\n this.name = name;\n }\n\n // Helpers\n\n sourceInterval(startIdx, endIdx) {\n return this.source.subInterval(startIdx, endIdx - startIdx);\n }\n\n ensureSuperGrammar() {\n if (!this.superGrammar) {\n this.withSuperGrammar(\n // TODO: The conditional expression below is an ugly hack. It's kind of ok because\n // I doubt anyone will ever try to declare a grammar called `BuiltInRules`. Still,\n // we should try to find a better way to do this.\n this.name === 'BuiltInRules' ? Grammar.ProtoBuiltInRules : Grammar.BuiltInRules,\n );\n }\n return this.superGrammar;\n }\n\n ensureSuperGrammarRuleForOverriding(name, source) {\n const ruleInfo = this.ensureSuperGrammar().rules[name];\n if (!ruleInfo) {\n throw cannotOverrideUndeclaredRule(name, this.superGrammar.name, source);\n }\n return ruleInfo;\n }\n\n installOverriddenOrExtendedRule(name, formals, body, source) {\n const duplicateParameterNames$1 = getDuplicates(formals);\n if (duplicateParameterNames$1.length > 0) {\n throw duplicateParameterNames(name, duplicateParameterNames$1, source);\n }\n const ruleInfo = this.ensureSuperGrammar().rules[name];\n const expectedFormals = ruleInfo.formals;\n const expectedNumFormals = expectedFormals ? expectedFormals.length : 0;\n if (formals.length !== expectedNumFormals) {\n throw wrongNumberOfParameters(name, expectedNumFormals, formals.length, source);\n }\n return this.install(name, formals, body, ruleInfo.description, source);\n }\n\n install(name, formals, body, description, source, primitive = false) {\n this.rules[name] = {\n body: body.introduceParams(formals),\n formals,\n description,\n source,\n primitive,\n };\n return this;\n }\n\n // Stuff that you should only do once\n\n withSuperGrammar(superGrammar) {\n if (this.superGrammar) {\n throw new Error('the super grammar of a GrammarDecl cannot be set more than once');\n }\n this.superGrammar = superGrammar;\n this.rules = Object.create(superGrammar.rules);\n\n // Grammars with an explicit supergrammar inherit a default start rule.\n if (!superGrammar.isBuiltIn()) {\n this.defaultStartRule = superGrammar.defaultStartRule;\n }\n return this;\n }\n\n withDefaultStartRule(ruleName) {\n this.defaultStartRule = ruleName;\n return this;\n }\n\n withSource(source) {\n this.source = new InputStream(source).interval(0, source.length);\n return this;\n }\n\n // Creates a Grammar instance, and if it passes the sanity checks, returns it.\n build() {\n const grammar = new Grammar(\n this.name,\n this.ensureSuperGrammar(),\n this.rules,\n this.defaultStartRule,\n );\n // Initialize internal props that are inherited from the super grammar.\n grammar._matchStateInitializer = grammar.superGrammar._matchStateInitializer;\n grammar.supportsIncrementalParsing = grammar.superGrammar.supportsIncrementalParsing;\n\n // TODO: change the pexpr.prototype.assert... methods to make them add\n // exceptions to an array that's provided as an arg. Then we'll be able to\n // show more than one error of the same type at a time.\n // TODO: include the offending pexpr in the errors, that way we can show\n // the part of the source that caused it.\n const grammarErrors = [];\n let grammarHasInvalidApplications = false;\n Object.keys(grammar.rules).forEach(ruleName => {\n const {body} = grammar.rules[ruleName];\n try {\n body.assertChoicesHaveUniformArity(ruleName);\n } catch (e) {\n grammarErrors.push(e);\n }\n try {\n body.assertAllApplicationsAreValid(ruleName, grammar);\n } catch (e) {\n grammarErrors.push(e);\n grammarHasInvalidApplications = true;\n }\n });\n if (!grammarHasInvalidApplications) {\n // The following check can only be done if the grammar has no invalid applications.\n Object.keys(grammar.rules).forEach(ruleName => {\n const {body} = grammar.rules[ruleName];\n try {\n body.assertIteratedExprsAreNotNullable(grammar, []);\n } catch (e) {\n grammarErrors.push(e);\n }\n });\n }\n if (grammarErrors.length > 0) {\n throwErrors(grammarErrors);\n }\n if (this.source) {\n grammar.source = this.source;\n }\n\n return grammar;\n }\n\n // Rule declarations\n\n define(name, formals, body, description, source, primitive) {\n this.ensureSuperGrammar();\n if (this.superGrammar.rules[name]) {\n throw duplicateRuleDeclaration(name, this.name, this.superGrammar.name, source);\n } else if (this.rules[name]) {\n throw duplicateRuleDeclaration(name, this.name, this.name, source);\n }\n const duplicateParameterNames$1 = getDuplicates(formals);\n if (duplicateParameterNames$1.length > 0) {\n throw duplicateParameterNames(name, duplicateParameterNames$1, source);\n }\n return this.install(name, formals, body, description, source, primitive);\n }\n\n override(name, formals, body, descIgnored, source) {\n this.ensureSuperGrammarRuleForOverriding(name, source);\n this.installOverriddenOrExtendedRule(name, formals, body, source);\n return this;\n }\n\n extend(name, formals, fragment, descIgnored, source) {\n const ruleInfo = this.ensureSuperGrammar().rules[name];\n if (!ruleInfo) {\n throw cannotExtendUndeclaredRule(name, this.superGrammar.name, source);\n }\n const body = new Extend(this.superGrammar, name, fragment);\n body.source = fragment.source;\n this.installOverriddenOrExtendedRule(name, formals, body, source);\n return this;\n }\n}\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nclass Builder {\n constructor() {\n this.currentDecl = null;\n this.currentRuleName = null;\n }\n\n newGrammar(name) {\n return new GrammarDecl(name);\n }\n\n grammar(metaInfo, name, superGrammar, defaultStartRule, rules) {\n const gDecl = new GrammarDecl(name);\n if (superGrammar) {\n // `superGrammar` may be a recipe (i.e. an Array), or an actual grammar instance.\n gDecl.withSuperGrammar(\n superGrammar instanceof Grammar ? superGrammar : this.fromRecipe(superGrammar),\n );\n }\n if (defaultStartRule) {\n gDecl.withDefaultStartRule(defaultStartRule);\n }\n if (metaInfo && metaInfo.source) {\n gDecl.withSource(metaInfo.source);\n }\n\n this.currentDecl = gDecl;\n Object.keys(rules).forEach(ruleName => {\n this.currentRuleName = ruleName;\n const ruleRecipe = rules[ruleName];\n\n const action = ruleRecipe[0]; // define/extend/override\n const metaInfo = ruleRecipe[1];\n const description = ruleRecipe[2];\n const formals = ruleRecipe[3];\n const body = this.fromRecipe(ruleRecipe[4]);\n\n let source;\n if (gDecl.source && metaInfo && metaInfo.sourceInterval) {\n source = gDecl.source.subInterval(\n metaInfo.sourceInterval[0],\n metaInfo.sourceInterval[1] - metaInfo.sourceInterval[0],\n );\n }\n gDecl[action](ruleName, formals, body, description, source);\n });\n this.currentRuleName = this.currentDecl = null;\n return gDecl.build();\n }\n\n terminal(x) {\n return new Terminal(x);\n }\n\n range(from, to) {\n return new Range(from, to);\n }\n\n param(index) {\n return new Param(index);\n }\n\n alt(...termArgs) {\n let terms = [];\n for (let arg of termArgs) {\n if (!(arg instanceof PExpr)) {\n arg = this.fromRecipe(arg);\n }\n if (arg instanceof Alt) {\n terms = terms.concat(arg.terms);\n } else {\n terms.push(arg);\n }\n }\n return terms.length === 1 ? terms[0] : new Alt(terms);\n }\n\n seq(...factorArgs) {\n let factors = [];\n for (let arg of factorArgs) {\n if (!(arg instanceof PExpr)) {\n arg = this.fromRecipe(arg);\n }\n if (arg instanceof Seq) {\n factors = factors.concat(arg.factors);\n } else {\n factors.push(arg);\n }\n }\n return factors.length === 1 ? factors[0] : new Seq(factors);\n }\n\n star(expr) {\n if (!(expr instanceof PExpr)) {\n expr = this.fromRecipe(expr);\n }\n return new Star(expr);\n }\n\n plus(expr) {\n if (!(expr instanceof PExpr)) {\n expr = this.fromRecipe(expr);\n }\n return new Plus(expr);\n }\n\n opt(expr) {\n if (!(expr instanceof PExpr)) {\n expr = this.fromRecipe(expr);\n }\n return new Opt(expr);\n }\n\n not(expr) {\n if (!(expr instanceof PExpr)) {\n expr = this.fromRecipe(expr);\n }\n return new Not(expr);\n }\n\n lookahead(expr) {\n if (!(expr instanceof PExpr)) {\n expr = this.fromRecipe(expr);\n }\n return new Lookahead(expr);\n }\n\n lex(expr) {\n if (!(expr instanceof PExpr)) {\n expr = this.fromRecipe(expr);\n }\n return new Lex(expr);\n }\n\n app(ruleName, optParams) {\n if (optParams && optParams.length > 0) {\n optParams = optParams.map(function(param) {\n return param instanceof PExpr ? param : this.fromRecipe(param);\n }, this);\n }\n return new Apply(ruleName, optParams);\n }\n\n // Note that unlike other methods in this class, this method cannot be used as a\n // convenience constructor. It only works with recipes, because it relies on\n // `this.currentDecl` and `this.currentRuleName` being set.\n splice(beforeTerms, afterTerms) {\n return new Splice(\n this.currentDecl.superGrammar,\n this.currentRuleName,\n beforeTerms.map(term => this.fromRecipe(term)),\n afterTerms.map(term => this.fromRecipe(term)),\n );\n }\n\n fromRecipe(recipe) {\n // the meta-info of 'grammar' is processed in Builder.grammar\n const args = recipe[0] === 'grammar' ? recipe.slice(1) : recipe.slice(2);\n const result = this[recipe[0]](...args);\n\n const metaInfo = recipe[1];\n if (metaInfo) {\n if (metaInfo.sourceInterval && this.currentDecl) {\n result.withSource(this.currentDecl.sourceInterval(...metaInfo.sourceInterval));\n }\n }\n return result;\n }\n}\n\nfunction makeRecipe(recipe) {\n if (typeof recipe === 'function') {\n return recipe.call(new Builder());\n } else {\n if (typeof recipe === 'string') {\n // stringified JSON recipe\n recipe = JSON.parse(recipe);\n }\n return new Builder().fromRecipe(recipe);\n }\n}\n\nvar BuiltInRules = makeRecipe([\"grammar\",{\"source\":\"BuiltInRules {\\n\\n alnum (an alpha-numeric character)\\n = letter\\n | digit\\n\\n letter (a letter)\\n = lower\\n | upper\\n | unicodeLtmo\\n\\n digit (a digit)\\n = \\\"0\\\"..\\\"9\\\"\\n\\n hexDigit (a hexadecimal digit)\\n = digit\\n | \\\"a\\\"..\\\"f\\\"\\n | \\\"A\\\"..\\\"F\\\"\\n\\n ListOf\\n = NonemptyListOf\\n | EmptyListOf\\n\\n NonemptyListOf\\n = elem (sep elem)*\\n\\n EmptyListOf\\n = /* nothing */\\n\\n listOf\\n = nonemptyListOf\\n | emptyListOf\\n\\n nonemptyListOf\\n = elem (sep elem)*\\n\\n emptyListOf\\n = /* nothing */\\n\\n // Allows a syntactic rule application within a lexical context.\\n applySyntactic = app\\n}\"},\"BuiltInRules\",null,null,{\"alnum\":[\"define\",{\"sourceInterval\":[18,78]},\"an alpha-numeric character\",[],[\"alt\",{\"sourceInterval\":[60,78]},[\"app\",{\"sourceInterval\":[60,66]},\"letter\",[]],[\"app\",{\"sourceInterval\":[73,78]},\"digit\",[]]]],\"letter\":[\"define\",{\"sourceInterval\":[82,142]},\"a letter\",[],[\"alt\",{\"sourceInterval\":[107,142]},[\"app\",{\"sourceInterval\":[107,112]},\"lower\",[]],[\"app\",{\"sourceInterval\":[119,124]},\"upper\",[]],[\"app\",{\"sourceInterval\":[131,142]},\"unicodeLtmo\",[]]]],\"digit\":[\"define\",{\"sourceInterval\":[146,177]},\"a digit\",[],[\"range\",{\"sourceInterval\":[169,177]},\"0\",\"9\"]],\"hexDigit\":[\"define\",{\"sourceInterval\":[181,254]},\"a hexadecimal digit\",[],[\"alt\",{\"sourceInterval\":[219,254]},[\"app\",{\"sourceInterval\":[219,224]},\"digit\",[]],[\"range\",{\"sourceInterval\":[231,239]},\"a\",\"f\"],[\"range\",{\"sourceInterval\":[246,254]},\"A\",\"F\"]]],\"ListOf\":[\"define\",{\"sourceInterval\":[258,336]},null,[\"elem\",\"sep\"],[\"alt\",{\"sourceInterval\":[282,336]},[\"app\",{\"sourceInterval\":[282,307]},\"NonemptyListOf\",[[\"param\",{\"sourceInterval\":[297,301]},0],[\"param\",{\"sourceInterval\":[303,306]},1]]],[\"app\",{\"sourceInterval\":[314,336]},\"EmptyListOf\",[[\"param\",{\"sourceInterval\":[326,330]},0],[\"param\",{\"sourceInterval\":[332,335]},1]]]]],\"NonemptyListOf\":[\"define\",{\"sourceInterval\":[340,388]},null,[\"elem\",\"sep\"],[\"seq\",{\"sourceInterval\":[372,388]},[\"param\",{\"sourceInterval\":[372,376]},0],[\"star\",{\"sourceInterval\":[377,388]},[\"seq\",{\"sourceInterval\":[378,386]},[\"param\",{\"sourceInterval\":[378,381]},1],[\"param\",{\"sourceInterval\":[382,386]},0]]]]],\"EmptyListOf\":[\"define\",{\"sourceInterval\":[392,434]},null,[\"elem\",\"sep\"],[\"seq\",{\"sourceInterval\":[438,438]}]],\"listOf\":[\"define\",{\"sourceInterval\":[438,516]},null,[\"elem\",\"sep\"],[\"alt\",{\"sourceInterval\":[462,516]},[\"app\",{\"sourceInterval\":[462,487]},\"nonemptyListOf\",[[\"param\",{\"sourceInterval\":[477,481]},0],[\"param\",{\"sourceInterval\":[483,486]},1]]],[\"app\",{\"sourceInterval\":[494,516]},\"emptyListOf\",[[\"param\",{\"sourceInterval\":[506,510]},0],[\"param\",{\"sourceInterval\":[512,515]},1]]]]],\"nonemptyListOf\":[\"define\",{\"sourceInterval\":[520,568]},null,[\"elem\",\"sep\"],[\"seq\",{\"sourceInterval\":[552,568]},[\"param\",{\"sourceInterval\":[552,556]},0],[\"star\",{\"sourceInterval\":[557,568]},[\"seq\",{\"sourceInterval\":[558,566]},[\"param\",{\"sourceInterval\":[558,561]},1],[\"param\",{\"sourceInterval\":[562,566]},0]]]]],\"emptyListOf\":[\"define\",{\"sourceInterval\":[572,682]},null,[\"elem\",\"sep\"],[\"seq\",{\"sourceInterval\":[685,685]}]],\"applySyntactic\":[\"define\",{\"sourceInterval\":[685,710]},null,[\"app\"],[\"param\",{\"sourceInterval\":[707,710]},0]]}]);\n\nGrammar.BuiltInRules = BuiltInRules;\nannounceBuiltInRules(Grammar.BuiltInRules);\n\nvar ohmGrammar = makeRecipe([\"grammar\",{\"source\":\"Ohm {\\n\\n Grammars\\n = Grammar*\\n\\n Grammar\\n = ident SuperGrammar? \\\"{\\\" Rule* \\\"}\\\"\\n\\n SuperGrammar\\n = \\\"<:\\\" ident\\n\\n Rule\\n = ident Formals? ruleDescr? \\\"=\\\" RuleBody -- define\\n | ident Formals? \\\":=\\\" OverrideRuleBody -- override\\n | ident Formals? \\\"+=\\\" RuleBody -- extend\\n\\n RuleBody\\n = \\\"|\\\"? NonemptyListOf\\n\\n TopLevelTerm\\n = Seq caseName -- inline\\n | Seq\\n\\n OverrideRuleBody\\n = \\\"|\\\"? NonemptyListOf\\n\\n OverrideTopLevelTerm\\n = \\\"...\\\" -- superSplice\\n | TopLevelTerm\\n\\n Formals\\n = \\\"<\\\" ListOf \\\">\\\"\\n\\n Params\\n = \\\"<\\\" ListOf \\\">\\\"\\n\\n Alt\\n = NonemptyListOf\\n\\n Seq\\n = Iter*\\n\\n Iter\\n = Pred \\\"*\\\" -- star\\n | Pred \\\"+\\\" -- plus\\n | Pred \\\"?\\\" -- opt\\n | Pred\\n\\n Pred\\n = \\\"~\\\" Lex -- not\\n | \\\"&\\\" Lex -- lookahead\\n | Lex\\n\\n Lex\\n = \\\"#\\\" Base -- lex\\n | Base\\n\\n Base\\n = ident Params? ~(ruleDescr? \\\"=\\\" | \\\":=\\\" | \\\"+=\\\") -- application\\n | oneCharTerminal \\\"..\\\" oneCharTerminal -- range\\n | terminal -- terminal\\n | \\\"(\\\" Alt \\\")\\\" -- paren\\n\\n ruleDescr (a rule description)\\n = \\\"(\\\" ruleDescrText \\\")\\\"\\n\\n ruleDescrText\\n = (~\\\")\\\" any)*\\n\\n caseName\\n = \\\"--\\\" (~\\\"\\\\n\\\" space)* name (~\\\"\\\\n\\\" space)* (\\\"\\\\n\\\" | &\\\"}\\\")\\n\\n name (a name)\\n = nameFirst nameRest*\\n\\n nameFirst\\n = \\\"_\\\"\\n | letter\\n\\n nameRest\\n = \\\"_\\\"\\n | alnum\\n\\n ident (an identifier)\\n = name\\n\\n terminal\\n = \\\"\\\\\\\"\\\" terminalChar* \\\"\\\\\\\"\\\"\\n\\n oneCharTerminal\\n = \\\"\\\\\\\"\\\" terminalChar \\\"\\\\\\\"\\\"\\n\\n terminalChar\\n = escapeChar\\n | ~\\\"\\\\\\\\\\\" ~\\\"\\\\\\\"\\\" ~\\\"\\\\n\\\" \\\"\\\\u{0}\\\"..\\\"\\\\u{10FFFF}\\\"\\n\\n escapeChar (an escape sequence)\\n = \\\"\\\\\\\\\\\\\\\\\\\" -- backslash\\n | \\\"\\\\\\\\\\\\\\\"\\\" -- doubleQuote\\n | \\\"\\\\\\\\\\\\'\\\" -- singleQuote\\n | \\\"\\\\\\\\b\\\" -- backspace\\n | \\\"\\\\\\\\n\\\" -- lineFeed\\n | \\\"\\\\\\\\r\\\" -- carriageReturn\\n | \\\"\\\\\\\\t\\\" -- tab\\n | \\\"\\\\\\\\u{\\\" hexDigit hexDigit? hexDigit?\\n hexDigit? hexDigit? hexDigit? \\\"}\\\" -- unicodeCodePoint\\n | \\\"\\\\\\\\u\\\" hexDigit hexDigit hexDigit hexDigit -- unicodeEscape\\n | \\\"\\\\\\\\x\\\" hexDigit hexDigit -- hexEscape\\n\\n space\\n += comment\\n\\n comment\\n = \\\"//\\\" (~\\\"\\\\n\\\" any)* &(\\\"\\\\n\\\" | end) -- singleLine\\n | \\\"/*\\\" (~\\\"*/\\\" any)* \\\"*/\\\" -- multiLine\\n\\n tokens = token*\\n\\n token = caseName | comment | ident | operator | punctuation | terminal | any\\n\\n operator = \\\"<:\\\" | \\\"=\\\" | \\\":=\\\" | \\\"+=\\\" | \\\"*\\\" | \\\"+\\\" | \\\"?\\\" | \\\"~\\\" | \\\"&\\\"\\n\\n punctuation = \\\"<\\\" | \\\">\\\" | \\\",\\\" | \\\"--\\\"\\n}\"},\"Ohm\",null,\"Grammars\",{\"Grammars\":[\"define\",{\"sourceInterval\":[9,32]},null,[],[\"star\",{\"sourceInterval\":[24,32]},[\"app\",{\"sourceInterval\":[24,31]},\"Grammar\",[]]]],\"Grammar\":[\"define\",{\"sourceInterval\":[36,83]},null,[],[\"seq\",{\"sourceInterval\":[50,83]},[\"app\",{\"sourceInterval\":[50,55]},\"ident\",[]],[\"opt\",{\"sourceInterval\":[56,69]},[\"app\",{\"sourceInterval\":[56,68]},\"SuperGrammar\",[]]],[\"terminal\",{\"sourceInterval\":[70,73]},\"{\"],[\"star\",{\"sourceInterval\":[74,79]},[\"app\",{\"sourceInterval\":[74,78]},\"Rule\",[]]],[\"terminal\",{\"sourceInterval\":[80,83]},\"}\"]]],\"SuperGrammar\":[\"define\",{\"sourceInterval\":[87,116]},null,[],[\"seq\",{\"sourceInterval\":[106,116]},[\"terminal\",{\"sourceInterval\":[106,110]},\"<:\"],[\"app\",{\"sourceInterval\":[111,116]},\"ident\",[]]]],\"Rule_define\":[\"define\",{\"sourceInterval\":[131,181]},null,[],[\"seq\",{\"sourceInterval\":[131,170]},[\"app\",{\"sourceInterval\":[131,136]},\"ident\",[]],[\"opt\",{\"sourceInterval\":[137,145]},[\"app\",{\"sourceInterval\":[137,144]},\"Formals\",[]]],[\"opt\",{\"sourceInterval\":[146,156]},[\"app\",{\"sourceInterval\":[146,155]},\"ruleDescr\",[]]],[\"terminal\",{\"sourceInterval\":[157,160]},\"=\"],[\"app\",{\"sourceInterval\":[162,170]},\"RuleBody\",[]]]],\"Rule_override\":[\"define\",{\"sourceInterval\":[188,248]},null,[],[\"seq\",{\"sourceInterval\":[188,235]},[\"app\",{\"sourceInterval\":[188,193]},\"ident\",[]],[\"opt\",{\"sourceInterval\":[194,202]},[\"app\",{\"sourceInterval\":[194,201]},\"Formals\",[]]],[\"terminal\",{\"sourceInterval\":[214,218]},\":=\"],[\"app\",{\"sourceInterval\":[219,235]},\"OverrideRuleBody\",[]]]],\"Rule_extend\":[\"define\",{\"sourceInterval\":[255,305]},null,[],[\"seq\",{\"sourceInterval\":[255,294]},[\"app\",{\"sourceInterval\":[255,260]},\"ident\",[]],[\"opt\",{\"sourceInterval\":[261,269]},[\"app\",{\"sourceInterval\":[261,268]},\"Formals\",[]]],[\"terminal\",{\"sourceInterval\":[281,285]},\"+=\"],[\"app\",{\"sourceInterval\":[286,294]},\"RuleBody\",[]]]],\"Rule\":[\"define\",{\"sourceInterval\":[120,305]},null,[],[\"alt\",{\"sourceInterval\":[131,305]},[\"app\",{\"sourceInterval\":[131,170]},\"Rule_define\",[]],[\"app\",{\"sourceInterval\":[188,235]},\"Rule_override\",[]],[\"app\",{\"sourceInterval\":[255,294]},\"Rule_extend\",[]]]],\"RuleBody\":[\"define\",{\"sourceInterval\":[309,362]},null,[],[\"seq\",{\"sourceInterval\":[324,362]},[\"opt\",{\"sourceInterval\":[324,328]},[\"terminal\",{\"sourceInterval\":[324,327]},\"|\"]],[\"app\",{\"sourceInterval\":[329,362]},\"NonemptyListOf\",[[\"app\",{\"sourceInterval\":[344,356]},\"TopLevelTerm\",[]],[\"terminal\",{\"sourceInterval\":[358,361]},\"|\"]]]]],\"TopLevelTerm_inline\":[\"define\",{\"sourceInterval\":[385,408]},null,[],[\"seq\",{\"sourceInterval\":[385,397]},[\"app\",{\"sourceInterval\":[385,388]},\"Seq\",[]],[\"app\",{\"sourceInterval\":[389,397]},\"caseName\",[]]]],\"TopLevelTerm\":[\"define\",{\"sourceInterval\":[366,418]},null,[],[\"alt\",{\"sourceInterval\":[385,418]},[\"app\",{\"sourceInterval\":[385,397]},\"TopLevelTerm_inline\",[]],[\"app\",{\"sourceInterval\":[415,418]},\"Seq\",[]]]],\"OverrideRuleBody\":[\"define\",{\"sourceInterval\":[422,491]},null,[],[\"seq\",{\"sourceInterval\":[445,491]},[\"opt\",{\"sourceInterval\":[445,449]},[\"terminal\",{\"sourceInterval\":[445,448]},\"|\"]],[\"app\",{\"sourceInterval\":[450,491]},\"NonemptyListOf\",[[\"app\",{\"sourceInterval\":[465,485]},\"OverrideTopLevelTerm\",[]],[\"terminal\",{\"sourceInterval\":[487,490]},\"|\"]]]]],\"OverrideTopLevelTerm_superSplice\":[\"define\",{\"sourceInterval\":[522,543]},null,[],[\"terminal\",{\"sourceInterval\":[522,527]},\"...\"]],\"OverrideTopLevelTerm\":[\"define\",{\"sourceInterval\":[495,562]},null,[],[\"alt\",{\"sourceInterval\":[522,562]},[\"app\",{\"sourceInterval\":[522,527]},\"OverrideTopLevelTerm_superSplice\",[]],[\"app\",{\"sourceInterval\":[550,562]},\"TopLevelTerm\",[]]]],\"Formals\":[\"define\",{\"sourceInterval\":[566,606]},null,[],[\"seq\",{\"sourceInterval\":[580,606]},[\"terminal\",{\"sourceInterval\":[580,583]},\"<\"],[\"app\",{\"sourceInterval\":[584,602]},\"ListOf\",[[\"app\",{\"sourceInterval\":[591,596]},\"ident\",[]],[\"terminal\",{\"sourceInterval\":[598,601]},\",\"]]],[\"terminal\",{\"sourceInterval\":[603,606]},\">\"]]],\"Params\":[\"define\",{\"sourceInterval\":[610,647]},null,[],[\"seq\",{\"sourceInterval\":[623,647]},[\"terminal\",{\"sourceInterval\":[623,626]},\"<\"],[\"app\",{\"sourceInterval\":[627,643]},\"ListOf\",[[\"app\",{\"sourceInterval\":[634,637]},\"Seq\",[]],[\"terminal\",{\"sourceInterval\":[639,642]},\",\"]]],[\"terminal\",{\"sourceInterval\":[644,647]},\">\"]]],\"Alt\":[\"define\",{\"sourceInterval\":[651,685]},null,[],[\"app\",{\"sourceInterval\":[661,685]},\"NonemptyListOf\",[[\"app\",{\"sourceInterval\":[676,679]},\"Seq\",[]],[\"terminal\",{\"sourceInterval\":[681,684]},\"|\"]]]],\"Seq\":[\"define\",{\"sourceInterval\":[689,704]},null,[],[\"star\",{\"sourceInterval\":[699,704]},[\"app\",{\"sourceInterval\":[699,703]},\"Iter\",[]]]],\"Iter_star\":[\"define\",{\"sourceInterval\":[719,736]},null,[],[\"seq\",{\"sourceInterval\":[719,727]},[\"app\",{\"sourceInterval\":[719,723]},\"Pred\",[]],[\"terminal\",{\"sourceInterval\":[724,727]},\"*\"]]],\"Iter_plus\":[\"define\",{\"sourceInterval\":[743,760]},null,[],[\"seq\",{\"sourceInterval\":[743,751]},[\"app\",{\"sourceInterval\":[743,747]},\"Pred\",[]],[\"terminal\",{\"sourceInterval\":[748,751]},\"+\"]]],\"Iter_opt\":[\"define\",{\"sourceInterval\":[767,783]},null,[],[\"seq\",{\"sourceInterval\":[767,775]},[\"app\",{\"sourceInterval\":[767,771]},\"Pred\",[]],[\"terminal\",{\"sourceInterval\":[772,775]},\"?\"]]],\"Iter\":[\"define\",{\"sourceInterval\":[708,794]},null,[],[\"alt\",{\"sourceInterval\":[719,794]},[\"app\",{\"sourceInterval\":[719,727]},\"Iter_star\",[]],[\"app\",{\"sourceInterval\":[743,751]},\"Iter_plus\",[]],[\"app\",{\"sourceInterval\":[767,775]},\"Iter_opt\",[]],[\"app\",{\"sourceInterval\":[790,794]},\"Pred\",[]]]],\"Pred_not\":[\"define\",{\"sourceInterval\":[809,824]},null,[],[\"seq\",{\"sourceInterval\":[809,816]},[\"terminal\",{\"sourceInterval\":[809,812]},\"~\"],[\"app\",{\"sourceInterval\":[813,816]},\"Lex\",[]]]],\"Pred_lookahead\":[\"define\",{\"sourceInterval\":[831,852]},null,[],[\"seq\",{\"sourceInterval\":[831,838]},[\"terminal\",{\"sourceInterval\":[831,834]},\"&\"],[\"app\",{\"sourceInterval\":[835,838]},\"Lex\",[]]]],\"Pred\":[\"define\",{\"sourceInterval\":[798,862]},null,[],[\"alt\",{\"sourceInterval\":[809,862]},[\"app\",{\"sourceInterval\":[809,816]},\"Pred_not\",[]],[\"app\",{\"sourceInterval\":[831,838]},\"Pred_lookahead\",[]],[\"app\",{\"sourceInterval\":[859,862]},\"Lex\",[]]]],\"Lex_lex\":[\"define\",{\"sourceInterval\":[876,892]},null,[],[\"seq\",{\"sourceInterval\":[876,884]},[\"terminal\",{\"sourceInterval\":[876,879]},\"#\"],[\"app\",{\"sourceInterval\":[880,884]},\"Base\",[]]]],\"Lex\":[\"define\",{\"sourceInterval\":[866,903]},null,[],[\"alt\",{\"sourceInterval\":[876,903]},[\"app\",{\"sourceInterval\":[876,884]},\"Lex_lex\",[]],[\"app\",{\"sourceInterval\":[899,903]},\"Base\",[]]]],\"Base_application\":[\"define\",{\"sourceInterval\":[918,979]},null,[],[\"seq\",{\"sourceInterval\":[918,963]},[\"app\",{\"sourceInterval\":[918,923]},\"ident\",[]],[\"opt\",{\"sourceInterval\":[924,931]},[\"app\",{\"sourceInterval\":[924,930]},\"Params\",[]]],[\"not\",{\"sourceInterval\":[932,963]},[\"alt\",{\"sourceInterval\":[934,962]},[\"seq\",{\"sourceInterval\":[934,948]},[\"opt\",{\"sourceInterval\":[934,944]},[\"app\",{\"sourceInterval\":[934,943]},\"ruleDescr\",[]]],[\"terminal\",{\"sourceInterval\":[945,948]},\"=\"]],[\"terminal\",{\"sourceInterval\":[951,955]},\":=\"],[\"terminal\",{\"sourceInterval\":[958,962]},\"+=\"]]]]],\"Base_range\":[\"define\",{\"sourceInterval\":[986,1041]},null,[],[\"seq\",{\"sourceInterval\":[986,1022]},[\"app\",{\"sourceInterval\":[986,1001]},\"oneCharTerminal\",[]],[\"terminal\",{\"sourceInterval\":[1002,1006]},\"..\"],[\"app\",{\"sourceInterval\":[1007,1022]},\"oneCharTerminal\",[]]]],\"Base_terminal\":[\"define\",{\"sourceInterval\":[1048,1106]},null,[],[\"app\",{\"sourceInterval\":[1048,1056]},\"terminal\",[]]],\"Base_paren\":[\"define\",{\"sourceInterval\":[1113,1168]},null,[],[\"seq\",{\"sourceInterval\":[1113,1124]},[\"terminal\",{\"sourceInterval\":[1113,1116]},\"(\"],[\"app\",{\"sourceInterval\":[1117,1120]},\"Alt\",[]],[\"terminal\",{\"sourceInterval\":[1121,1124]},\")\"]]],\"Base\":[\"define\",{\"sourceInterval\":[907,1168]},null,[],[\"alt\",{\"sourceInterval\":[918,1168]},[\"app\",{\"sourceInterval\":[918,963]},\"Base_application\",[]],[\"app\",{\"sourceInterval\":[986,1022]},\"Base_range\",[]],[\"app\",{\"sourceInterval\":[1048,1056]},\"Base_terminal\",[]],[\"app\",{\"sourceInterval\":[1113,1124]},\"Base_paren\",[]]]],\"ruleDescr\":[\"define\",{\"sourceInterval\":[1172,1231]},\"a rule description\",[],[\"seq\",{\"sourceInterval\":[1210,1231]},[\"terminal\",{\"sourceInterval\":[1210,1213]},\"(\"],[\"app\",{\"sourceInterval\":[1214,1227]},\"ruleDescrText\",[]],[\"terminal\",{\"sourceInterval\":[1228,1231]},\")\"]]],\"ruleDescrText\":[\"define\",{\"sourceInterval\":[1235,1266]},null,[],[\"star\",{\"sourceInterval\":[1255,1266]},[\"seq\",{\"sourceInterval\":[1256,1264]},[\"not\",{\"sourceInterval\":[1256,1260]},[\"terminal\",{\"sourceInterval\":[1257,1260]},\")\"]],[\"app\",{\"sourceInterval\":[1261,1264]},\"any\",[]]]]],\"caseName\":[\"define\",{\"sourceInterval\":[1270,1338]},null,[],[\"seq\",{\"sourceInterval\":[1285,1338]},[\"terminal\",{\"sourceInterval\":[1285,1289]},\"--\"],[\"star\",{\"sourceInterval\":[1290,1304]},[\"seq\",{\"sourceInterval\":[1291,1302]},[\"not\",{\"sourceInterval\":[1291,1296]},[\"terminal\",{\"sourceInterval\":[1292,1296]},\"\\n\"]],[\"app\",{\"sourceInterval\":[1297,1302]},\"space\",[]]]],[\"app\",{\"sourceInterval\":[1305,1309]},\"name\",[]],[\"star\",{\"sourceInterval\":[1310,1324]},[\"seq\",{\"sourceInterval\":[1311,1322]},[\"not\",{\"sourceInterval\":[1311,1316]},[\"terminal\",{\"sourceInterval\":[1312,1316]},\"\\n\"]],[\"app\",{\"sourceInterval\":[1317,1322]},\"space\",[]]]],[\"alt\",{\"sourceInterval\":[1326,1337]},[\"terminal\",{\"sourceInterval\":[1326,1330]},\"\\n\"],[\"lookahead\",{\"sourceInterval\":[1333,1337]},[\"terminal\",{\"sourceInterval\":[1334,1337]},\"}\"]]]]],\"name\":[\"define\",{\"sourceInterval\":[1342,1382]},\"a name\",[],[\"seq\",{\"sourceInterval\":[1363,1382]},[\"app\",{\"sourceInterval\":[1363,1372]},\"nameFirst\",[]],[\"star\",{\"sourceInterval\":[1373,1382]},[\"app\",{\"sourceInterval\":[1373,1381]},\"nameRest\",[]]]]],\"nameFirst\":[\"define\",{\"sourceInterval\":[1386,1418]},null,[],[\"alt\",{\"sourceInterval\":[1402,1418]},[\"terminal\",{\"sourceInterval\":[1402,1405]},\"_\"],[\"app\",{\"sourceInterval\":[1412,1418]},\"letter\",[]]]],\"nameRest\":[\"define\",{\"sourceInterval\":[1422,1452]},null,[],[\"alt\",{\"sourceInterval\":[1437,1452]},[\"terminal\",{\"sourceInterval\":[1437,1440]},\"_\"],[\"app\",{\"sourceInterval\":[1447,1452]},\"alnum\",[]]]],\"ident\":[\"define\",{\"sourceInterval\":[1456,1489]},\"an identifier\",[],[\"app\",{\"sourceInterval\":[1485,1489]},\"name\",[]]],\"terminal\":[\"define\",{\"sourceInterval\":[1493,1531]},null,[],[\"seq\",{\"sourceInterval\":[1508,1531]},[\"terminal\",{\"sourceInterval\":[1508,1512]},\"\\\"\"],[\"star\",{\"sourceInterval\":[1513,1526]},[\"app\",{\"sourceInterval\":[1513,1525]},\"terminalChar\",[]]],[\"terminal\",{\"sourceInterval\":[1527,1531]},\"\\\"\"]]],\"oneCharTerminal\":[\"define\",{\"sourceInterval\":[1535,1579]},null,[],[\"seq\",{\"sourceInterval\":[1557,1579]},[\"terminal\",{\"sourceInterval\":[1557,1561]},\"\\\"\"],[\"app\",{\"sourceInterval\":[1562,1574]},\"terminalChar\",[]],[\"terminal\",{\"sourceInterval\":[1575,1579]},\"\\\"\"]]],\"terminalChar\":[\"define\",{\"sourceInterval\":[1583,1660]},null,[],[\"alt\",{\"sourceInterval\":[1602,1660]},[\"app\",{\"sourceInterval\":[1602,1612]},\"escapeChar\",[]],[\"seq\",{\"sourceInterval\":[1621,1660]},[\"not\",{\"sourceInterval\":[1621,1626]},[\"terminal\",{\"sourceInterval\":[1622,1626]},\"\\\\\"]],[\"not\",{\"sourceInterval\":[1627,1632]},[\"terminal\",{\"sourceInterval\":[1628,1632]},\"\\\"\"]],[\"not\",{\"sourceInterval\":[1633,1638]},[\"terminal\",{\"sourceInterval\":[1634,1638]},\"\\n\"]],[\"range\",{\"sourceInterval\":[1639,1660]},\"\\u0000\",\"􏿿\"]]]],\"escapeChar_backslash\":[\"define\",{\"sourceInterval\":[1703,1758]},null,[],[\"terminal\",{\"sourceInterval\":[1703,1709]},\"\\\\\\\\\"]],\"escapeChar_doubleQuote\":[\"define\",{\"sourceInterval\":[1765,1822]},null,[],[\"terminal\",{\"sourceInterval\":[1765,1771]},\"\\\\\\\"\"]],\"escapeChar_singleQuote\":[\"define\",{\"sourceInterval\":[1829,1886]},null,[],[\"terminal\",{\"sourceInterval\":[1829,1835]},\"\\\\'\"]],\"escapeChar_backspace\":[\"define\",{\"sourceInterval\":[1893,1948]},null,[],[\"terminal\",{\"sourceInterval\":[1893,1898]},\"\\\\b\"]],\"escapeChar_lineFeed\":[\"define\",{\"sourceInterval\":[1955,2009]},null,[],[\"terminal\",{\"sourceInterval\":[1955,1960]},\"\\\\n\"]],\"escapeChar_carriageReturn\":[\"define\",{\"sourceInterval\":[2016,2076]},null,[],[\"terminal\",{\"sourceInterval\":[2016,2021]},\"\\\\r\"]],\"escapeChar_tab\":[\"define\",{\"sourceInterval\":[2083,2132]},null,[],[\"terminal\",{\"sourceInterval\":[2083,2088]},\"\\\\t\"]],\"escapeChar_unicodeCodePoint\":[\"define\",{\"sourceInterval\":[2139,2243]},null,[],[\"seq\",{\"sourceInterval\":[2139,2221]},[\"terminal\",{\"sourceInterval\":[2139,2145]},\"\\\\u{\"],[\"app\",{\"sourceInterval\":[2146,2154]},\"hexDigit\",[]],[\"opt\",{\"sourceInterval\":[2155,2164]},[\"app\",{\"sourceInterval\":[2155,2163]},\"hexDigit\",[]]],[\"opt\",{\"sourceInterval\":[2165,2174]},[\"app\",{\"sourceInterval\":[2165,2173]},\"hexDigit\",[]]],[\"opt\",{\"sourceInterval\":[2188,2197]},[\"app\",{\"sourceInterval\":[2188,2196]},\"hexDigit\",[]]],[\"opt\",{\"sourceInterval\":[2198,2207]},[\"app\",{\"sourceInterval\":[2198,2206]},\"hexDigit\",[]]],[\"opt\",{\"sourceInterval\":[2208,2217]},[\"app\",{\"sourceInterval\":[2208,2216]},\"hexDigit\",[]]],[\"terminal\",{\"sourceInterval\":[2218,2221]},\"}\"]]],\"escapeChar_unicodeEscape\":[\"define\",{\"sourceInterval\":[2250,2309]},null,[],[\"seq\",{\"sourceInterval\":[2250,2291]},[\"terminal\",{\"sourceInterval\":[2250,2255]},\"\\\\u\"],[\"app\",{\"sourceInterval\":[2256,2264]},\"hexDigit\",[]],[\"app\",{\"sourceInterval\":[2265,2273]},\"hexDigit\",[]],[\"app\",{\"sourceInterval\":[2274,2282]},\"hexDigit\",[]],[\"app\",{\"sourceInterval\":[2283,2291]},\"hexDigit\",[]]]],\"escapeChar_hexEscape\":[\"define\",{\"sourceInterval\":[2316,2371]},null,[],[\"seq\",{\"sourceInterval\":[2316,2339]},[\"terminal\",{\"sourceInterval\":[2316,2321]},\"\\\\x\"],[\"app\",{\"sourceInterval\":[2322,2330]},\"hexDigit\",[]],[\"app\",{\"sourceInterval\":[2331,2339]},\"hexDigit\",[]]]],\"escapeChar\":[\"define\",{\"sourceInterval\":[1664,2371]},\"an escape sequence\",[],[\"alt\",{\"sourceInterval\":[1703,2371]},[\"app\",{\"sourceInterval\":[1703,1709]},\"escapeChar_backslash\",[]],[\"app\",{\"sourceInterval\":[1765,1771]},\"escapeChar_doubleQuote\",[]],[\"app\",{\"sourceInterval\":[1829,1835]},\"escapeChar_singleQuote\",[]],[\"app\",{\"sourceInterval\":[1893,1898]},\"escapeChar_backspace\",[]],[\"app\",{\"sourceInterval\":[1955,1960]},\"escapeChar_lineFeed\",[]],[\"app\",{\"sourceInterval\":[2016,2021]},\"escapeChar_carriageReturn\",[]],[\"app\",{\"sourceInterval\":[2083,2088]},\"escapeChar_tab\",[]],[\"app\",{\"sourceInterval\":[2139,2221]},\"escapeChar_unicodeCodePoint\",[]],[\"app\",{\"sourceInterval\":[2250,2291]},\"escapeChar_unicodeEscape\",[]],[\"app\",{\"sourceInterval\":[2316,2339]},\"escapeChar_hexEscape\",[]]]],\"space\":[\"extend\",{\"sourceInterval\":[2375,2394]},null,[],[\"app\",{\"sourceInterval\":[2387,2394]},\"comment\",[]]],\"comment_singleLine\":[\"define\",{\"sourceInterval\":[2412,2458]},null,[],[\"seq\",{\"sourceInterval\":[2412,2443]},[\"terminal\",{\"sourceInterval\":[2412,2416]},\"//\"],[\"star\",{\"sourceInterval\":[2417,2429]},[\"seq\",{\"sourceInterval\":[2418,2427]},[\"not\",{\"sourceInterval\":[2418,2423]},[\"terminal\",{\"sourceInterval\":[2419,2423]},\"\\n\"]],[\"app\",{\"sourceInterval\":[2424,2427]},\"any\",[]]]],[\"lookahead\",{\"sourceInterval\":[2430,2443]},[\"alt\",{\"sourceInterval\":[2432,2442]},[\"terminal\",{\"sourceInterval\":[2432,2436]},\"\\n\"],[\"app\",{\"sourceInterval\":[2439,2442]},\"end\",[]]]]]],\"comment_multiLine\":[\"define\",{\"sourceInterval\":[2465,2501]},null,[],[\"seq\",{\"sourceInterval\":[2465,2487]},[\"terminal\",{\"sourceInterval\":[2465,2469]},\"/*\"],[\"star\",{\"sourceInterval\":[2470,2482]},[\"seq\",{\"sourceInterval\":[2471,2480]},[\"not\",{\"sourceInterval\":[2471,2476]},[\"terminal\",{\"sourceInterval\":[2472,2476]},\"*/\"]],[\"app\",{\"sourceInterval\":[2477,2480]},\"any\",[]]]],[\"terminal\",{\"sourceInterval\":[2483,2487]},\"*/\"]]],\"comment\":[\"define\",{\"sourceInterval\":[2398,2501]},null,[],[\"alt\",{\"sourceInterval\":[2412,2501]},[\"app\",{\"sourceInterval\":[2412,2443]},\"comment_singleLine\",[]],[\"app\",{\"sourceInterval\":[2465,2487]},\"comment_multiLine\",[]]]],\"tokens\":[\"define\",{\"sourceInterval\":[2505,2520]},null,[],[\"star\",{\"sourceInterval\":[2514,2520]},[\"app\",{\"sourceInterval\":[2514,2519]},\"token\",[]]]],\"token\":[\"define\",{\"sourceInterval\":[2524,2600]},null,[],[\"alt\",{\"sourceInterval\":[2532,2600]},[\"app\",{\"sourceInterval\":[2532,2540]},\"caseName\",[]],[\"app\",{\"sourceInterval\":[2543,2550]},\"comment\",[]],[\"app\",{\"sourceInterval\":[2553,2558]},\"ident\",[]],[\"app\",{\"sourceInterval\":[2561,2569]},\"operator\",[]],[\"app\",{\"sourceInterval\":[2572,2583]},\"punctuation\",[]],[\"app\",{\"sourceInterval\":[2586,2594]},\"terminal\",[]],[\"app\",{\"sourceInterval\":[2597,2600]},\"any\",[]]]],\"operator\":[\"define\",{\"sourceInterval\":[2604,2669]},null,[],[\"alt\",{\"sourceInterval\":[2615,2669]},[\"terminal\",{\"sourceInterval\":[2615,2619]},\"<:\"],[\"terminal\",{\"sourceInterval\":[2622,2625]},\"=\"],[\"terminal\",{\"sourceInterval\":[2628,2632]},\":=\"],[\"terminal\",{\"sourceInterval\":[2635,2639]},\"+=\"],[\"terminal\",{\"sourceInterval\":[2642,2645]},\"*\"],[\"terminal\",{\"sourceInterval\":[2648,2651]},\"+\"],[\"terminal\",{\"sourceInterval\":[2654,2657]},\"?\"],[\"terminal\",{\"sourceInterval\":[2660,2663]},\"~\"],[\"terminal\",{\"sourceInterval\":[2666,2669]},\"&\"]]],\"punctuation\":[\"define\",{\"sourceInterval\":[2673,2709]},null,[],[\"alt\",{\"sourceInterval\":[2687,2709]},[\"terminal\",{\"sourceInterval\":[2687,2690]},\"<\"],[\"terminal\",{\"sourceInterval\":[2693,2696]},\">\"],[\"terminal\",{\"sourceInterval\":[2699,2702]},\",\"],[\"terminal\",{\"sourceInterval\":[2705,2709]},\"--\"]]]}]);\n\nconst superSplicePlaceholder = Object.create(PExpr.prototype);\n\nfunction namespaceHas(ns, name) {\n // Look for an enumerable property, anywhere in the prototype chain.\n for (const prop in ns) {\n if (prop === name) return true;\n }\n return false;\n}\n\n// Returns a Grammar instance (i.e., an object with a `match` method) for\n// `tree`, which is the concrete syntax tree of a user-written grammar.\n// The grammar will be assigned into `namespace` under the name of the grammar\n// as specified in the source.\nfunction buildGrammar(match, namespace, optOhmGrammarForTesting) {\n const builder = new Builder();\n let decl;\n let currentRuleName;\n let currentRuleFormals;\n let overriding = false;\n const metaGrammar = optOhmGrammarForTesting || ohmGrammar;\n\n // A visitor that produces a Grammar instance from the CST.\n const helpers = metaGrammar.createSemantics().addOperation('visit', {\n Grammars(grammarIter) {\n return grammarIter.children.map(c => c.visit());\n },\n Grammar(id, s, _open, rules, _close) {\n const grammarName = id.visit();\n decl = builder.newGrammar(grammarName);\n s.child(0) && s.child(0).visit();\n rules.children.map(c => c.visit());\n const g = decl.build();\n g.source = this.source.trimmed();\n if (namespaceHas(namespace, grammarName)) {\n throw duplicateGrammarDeclaration(g);\n }\n namespace[grammarName] = g;\n return g;\n },\n\n SuperGrammar(_, n) {\n const superGrammarName = n.visit();\n if (superGrammarName === 'null') {\n decl.withSuperGrammar(null);\n } else {\n if (!namespace || !namespaceHas(namespace, superGrammarName)) {\n throw undeclaredGrammar(superGrammarName, namespace, n.source);\n }\n decl.withSuperGrammar(namespace[superGrammarName]);\n }\n },\n\n Rule_define(n, fs, d, _, b) {\n currentRuleName = n.visit();\n currentRuleFormals = fs.children.map(c => c.visit())[0] || [];\n // If there is no default start rule yet, set it now. This must be done before visiting\n // the body, because it might contain an inline rule definition.\n if (!decl.defaultStartRule && decl.ensureSuperGrammar() !== Grammar.ProtoBuiltInRules) {\n decl.withDefaultStartRule(currentRuleName);\n }\n const body = b.visit();\n const description = d.children.map(c => c.visit())[0];\n const source = this.source.trimmed();\n return decl.define(currentRuleName, currentRuleFormals, body, description, source);\n },\n Rule_override(n, fs, _, b) {\n currentRuleName = n.visit();\n currentRuleFormals = fs.children.map(c => c.visit())[0] || [];\n\n const source = this.source.trimmed();\n decl.ensureSuperGrammarRuleForOverriding(currentRuleName, source);\n\n overriding = true;\n const body = b.visit();\n overriding = false;\n return decl.override(currentRuleName, currentRuleFormals, body, null, source);\n },\n Rule_extend(n, fs, _, b) {\n currentRuleName = n.visit();\n currentRuleFormals = fs.children.map(c => c.visit())[0] || [];\n const body = b.visit();\n const source = this.source.trimmed();\n return decl.extend(currentRuleName, currentRuleFormals, body, null, source);\n },\n RuleBody(_, terms) {\n return builder.alt(...terms.visit()).withSource(this.source);\n },\n OverrideRuleBody(_, terms) {\n const args = terms.visit();\n\n // Check if the super-splice operator (`...`) appears in the terms.\n const expansionPos = args.indexOf(superSplicePlaceholder);\n if (expansionPos >= 0) {\n const beforeTerms = args.slice(0, expansionPos);\n const afterTerms = args.slice(expansionPos + 1);\n\n // Ensure it appears no more than once.\n afterTerms.forEach(t => {\n if (t === superSplicePlaceholder) throw multipleSuperSplices(t);\n });\n\n return new Splice(\n decl.superGrammar,\n currentRuleName,\n beforeTerms,\n afterTerms,\n ).withSource(this.source);\n } else {\n return builder.alt(...args).withSource(this.source);\n }\n },\n Formals(opointy, fs, cpointy) {\n return fs.visit();\n },\n\n Params(opointy, ps, cpointy) {\n return ps.visit();\n },\n\n Alt(seqs) {\n return builder.alt(...seqs.visit()).withSource(this.source);\n },\n\n TopLevelTerm_inline(b, n) {\n const inlineRuleName = currentRuleName + '_' + n.visit();\n const body = b.visit();\n const source = this.source.trimmed();\n const isNewRuleDeclaration = !(\n decl.superGrammar && decl.superGrammar.rules[inlineRuleName]\n );\n if (overriding && !isNewRuleDeclaration) {\n decl.override(inlineRuleName, currentRuleFormals, body, null, source);\n } else {\n decl.define(inlineRuleName, currentRuleFormals, body, null, source);\n }\n const params = currentRuleFormals.map(formal => builder.app(formal));\n return builder.app(inlineRuleName, params).withSource(body.source);\n },\n OverrideTopLevelTerm_superSplice(_) {\n return superSplicePlaceholder;\n },\n\n Seq(expr) {\n return builder.seq(...expr.children.map(c => c.visit())).withSource(this.source);\n },\n\n Iter_star(x, _) {\n return builder.star(x.visit()).withSource(this.source);\n },\n Iter_plus(x, _) {\n return builder.plus(x.visit()).withSource(this.source);\n },\n Iter_opt(x, _) {\n return builder.opt(x.visit()).withSource(this.source);\n },\n\n Pred_not(_, x) {\n return builder.not(x.visit()).withSource(this.source);\n },\n Pred_lookahead(_, x) {\n return builder.lookahead(x.visit()).withSource(this.source);\n },\n\n Lex_lex(_, x) {\n return builder.lex(x.visit()).withSource(this.source);\n },\n\n Base_application(rule, ps) {\n const params = ps.children.map(c => c.visit())[0] || [];\n return builder.app(rule.visit(), params).withSource(this.source);\n },\n Base_range(from, _, to) {\n return builder.range(from.visit(), to.visit()).withSource(this.source);\n },\n Base_terminal(expr) {\n return builder.terminal(expr.visit()).withSource(this.source);\n },\n Base_paren(open, x, close) {\n return x.visit();\n },\n\n ruleDescr(open, t, close) {\n return t.visit();\n },\n ruleDescrText(_) {\n return this.sourceString.trim();\n },\n\n caseName(_, space1, n, space2, end) {\n return n.visit();\n },\n\n name(first, rest) {\n return this.sourceString;\n },\n nameFirst(expr) {},\n nameRest(expr) {},\n\n terminal(open, cs, close) {\n return cs.children.map(c => c.visit()).join('');\n },\n\n oneCharTerminal(open, c, close) {\n return c.visit();\n },\n\n escapeChar(c) {\n try {\n return unescapeCodePoint(this.sourceString);\n } catch (err) {\n if (err instanceof RangeError && err.message.startsWith('Invalid code point ')) {\n throw invalidCodePoint(c);\n }\n throw err; // Rethrow\n }\n },\n\n NonemptyListOf(x, _, xs) {\n return [x.visit()].concat(xs.children.map(c => c.visit()));\n },\n EmptyListOf() {\n return [];\n },\n\n _terminal() {\n return this.sourceString;\n },\n });\n return helpers(match).visit();\n}\n\nvar operationsAndAttributesGrammar = makeRecipe([\"grammar\",{\"source\":\"OperationsAndAttributes {\\n\\n AttributeSignature =\\n name\\n\\n OperationSignature =\\n name Formals?\\n\\n Formals\\n = \\\"(\\\" ListOf \\\")\\\"\\n\\n name (a name)\\n = nameFirst nameRest*\\n\\n nameFirst\\n = \\\"_\\\"\\n | letter\\n\\n nameRest\\n = \\\"_\\\"\\n | alnum\\n\\n}\"},\"OperationsAndAttributes\",null,\"AttributeSignature\",{\"AttributeSignature\":[\"define\",{\"sourceInterval\":[29,58]},null,[],[\"app\",{\"sourceInterval\":[54,58]},\"name\",[]]],\"OperationSignature\":[\"define\",{\"sourceInterval\":[62,100]},null,[],[\"seq\",{\"sourceInterval\":[87,100]},[\"app\",{\"sourceInterval\":[87,91]},\"name\",[]],[\"opt\",{\"sourceInterval\":[92,100]},[\"app\",{\"sourceInterval\":[92,99]},\"Formals\",[]]]]],\"Formals\":[\"define\",{\"sourceInterval\":[104,143]},null,[],[\"seq\",{\"sourceInterval\":[118,143]},[\"terminal\",{\"sourceInterval\":[118,121]},\"(\"],[\"app\",{\"sourceInterval\":[122,139]},\"ListOf\",[[\"app\",{\"sourceInterval\":[129,133]},\"name\",[]],[\"terminal\",{\"sourceInterval\":[135,138]},\",\"]]],[\"terminal\",{\"sourceInterval\":[140,143]},\")\"]]],\"name\":[\"define\",{\"sourceInterval\":[147,187]},\"a name\",[],[\"seq\",{\"sourceInterval\":[168,187]},[\"app\",{\"sourceInterval\":[168,177]},\"nameFirst\",[]],[\"star\",{\"sourceInterval\":[178,187]},[\"app\",{\"sourceInterval\":[178,186]},\"nameRest\",[]]]]],\"nameFirst\":[\"define\",{\"sourceInterval\":[191,223]},null,[],[\"alt\",{\"sourceInterval\":[207,223]},[\"terminal\",{\"sourceInterval\":[207,210]},\"_\"],[\"app\",{\"sourceInterval\":[217,223]},\"letter\",[]]]],\"nameRest\":[\"define\",{\"sourceInterval\":[227,257]},null,[],[\"alt\",{\"sourceInterval\":[242,257]},[\"terminal\",{\"sourceInterval\":[242,245]},\"_\"],[\"app\",{\"sourceInterval\":[252,257]},\"alnum\",[]]]]}]);\n\ninitBuiltInSemantics(Grammar.BuiltInRules);\ninitPrototypeParser(operationsAndAttributesGrammar); // requires BuiltInSemantics\n\nfunction initBuiltInSemantics(builtInRules) {\n const actions = {\n empty() {\n return this.iteration();\n },\n nonEmpty(first, _, rest) {\n return this.iteration([first].concat(rest.children));\n },\n };\n\n Semantics.BuiltInSemantics = Semantics.createSemantics(builtInRules, null).addOperation(\n 'asIteration',\n {\n emptyListOf: actions.empty,\n nonemptyListOf: actions.nonEmpty,\n EmptyListOf: actions.empty,\n NonemptyListOf: actions.nonEmpty,\n },\n );\n}\n\nfunction initPrototypeParser(grammar) {\n Semantics.prototypeGrammarSemantics = grammar.createSemantics().addOperation('parse', {\n AttributeSignature(name) {\n return {\n name: name.parse(),\n formals: [],\n };\n },\n OperationSignature(name, optFormals) {\n return {\n name: name.parse(),\n formals: optFormals.children.map(c => c.parse())[0] || [],\n };\n },\n Formals(oparen, fs, cparen) {\n return fs.asIteration().children.map(c => c.parse());\n },\n name(first, rest) {\n return this.sourceString;\n },\n });\n Semantics.prototypeGrammar = grammar;\n}\n\nfunction findIndentation(input) {\n let pos = 0;\n const stack = [0];\n const topOfStack = () => stack[stack.length - 1];\n\n const result = {};\n\n const regex = /( *).*(?:$|\\r?\\n|\\r)/g;\n let match;\n while ((match = regex.exec(input)) != null) {\n const [line, indent] = match;\n\n // The last match will always have length 0. In every other case, some\n // characters will be matched (possibly only the end of line chars).\n if (line.length === 0) break;\n\n const indentSize = indent.length;\n const prevSize = topOfStack();\n\n const indentPos = pos + indentSize;\n\n if (indentSize > prevSize) {\n // Indent -- always only 1.\n stack.push(indentSize);\n result[indentPos] = 1;\n } else if (indentSize < prevSize) {\n // Dedent -- can be multiple levels.\n const prevLength = stack.length;\n while (topOfStack() !== indentSize) {\n stack.pop();\n }\n result[indentPos] = -1 * (prevLength - stack.length);\n }\n pos += line.length;\n }\n // Ensure that there is a matching DEDENT for every remaining INDENT.\n if (stack.length > 1) {\n result[pos] = 1 - stack.length;\n }\n return result;\n}\n\nconst INDENT_DESCRIPTION = 'an indented block';\nconst DEDENT_DESCRIPTION = 'a dedent';\n\n// A sentinel value that is out of range for both charCodeAt() and codePointAt().\nconst INVALID_CODE_POINT = 0x10ffff + 1;\n\nclass InputStreamWithIndentation extends InputStream {\n constructor(state) {\n super(state.input);\n this.state = state;\n }\n\n _indentationAt(pos) {\n return this.state.userData[pos] || 0;\n }\n\n atEnd() {\n return super.atEnd() && this._indentationAt(this.pos) === 0;\n }\n\n next() {\n if (this._indentationAt(this.pos) !== 0) {\n this.examinedLength = Math.max(this.examinedLength, this.pos);\n return undefined;\n }\n return super.next();\n }\n\n nextCharCode() {\n if (this._indentationAt(this.pos) !== 0) {\n this.examinedLength = Math.max(this.examinedLength, this.pos);\n return INVALID_CODE_POINT;\n }\n return super.nextCharCode();\n }\n\n nextCodePoint() {\n if (this._indentationAt(this.pos) !== 0) {\n this.examinedLength = Math.max(this.examinedLength, this.pos);\n return INVALID_CODE_POINT;\n }\n return super.nextCodePoint();\n }\n}\n\nclass Indentation extends PExpr {\n constructor(isIndent = true) {\n super();\n this.isIndent = isIndent;\n }\n\n allowsSkippingPrecedingSpace() {\n return true;\n }\n\n eval(state) {\n const {inputStream} = state;\n const pseudoTokens = state.userData;\n state.doNotMemoize = true;\n\n const origPos = inputStream.pos;\n\n const sign = this.isIndent ? 1 : -1;\n const count = (pseudoTokens[origPos] || 0) * sign;\n if (count > 0) {\n // Update the count to consume the pseudotoken.\n state.userData = Object.create(pseudoTokens);\n state.userData[origPos] -= sign;\n\n state.pushBinding(new TerminalNode(0), origPos);\n return true;\n } else {\n state.processFailure(origPos, this);\n return false;\n }\n }\n\n getArity() {\n return 1;\n }\n\n _assertAllApplicationsAreValid(ruleName, grammar) {}\n\n _isNullable(grammar, memo) {\n return false;\n }\n\n assertChoicesHaveUniformArity(ruleName) {}\n\n assertIteratedExprsAreNotNullable(grammar) {}\n\n introduceParams(formals) {\n return this;\n }\n\n substituteParams(actuals) {\n return this;\n }\n\n toString() {\n return this.isIndent ? 'indent' : 'dedent';\n }\n\n toDisplayString() {\n return this.toString();\n }\n\n toFailure(grammar) {\n const description = this.isIndent ? INDENT_DESCRIPTION : DEDENT_DESCRIPTION;\n return new Failure(this, description, 'description');\n }\n}\n\n// Create a new definition for `any` that can consume indent & dedent.\nconst applyIndent = new Apply('indent');\nconst applyDedent = new Apply('dedent');\nconst newAnyBody = new Splice(BuiltInRules, 'any', [applyIndent, applyDedent], []);\n\nconst IndentationSensitive = new Builder()\n .newGrammar('IndentationSensitive')\n .withSuperGrammar(BuiltInRules)\n .define('indent', [], new Indentation(true), INDENT_DESCRIPTION, undefined, true)\n .define('dedent', [], new Indentation(false), DEDENT_DESCRIPTION, undefined, true)\n .extend('any', [], newAnyBody, 'any character', undefined)\n .build();\n\nObject.assign(IndentationSensitive, {\n _matchStateInitializer(state) {\n state.userData = findIndentation(state.input);\n state.inputStream = new InputStreamWithIndentation(state);\n },\n supportsIncrementalParsing: false,\n});\n\n// Generated by scripts/prebuild.js\nconst version = '17.1.0';\n\nGrammar.initApplicationParser(ohmGrammar, buildGrammar);\n\nconst isBuffer = obj =>\n !!obj.constructor &&\n typeof obj.constructor.isBuffer === 'function' &&\n obj.constructor.isBuffer(obj);\n\nfunction compileAndLoad(source, namespace) {\n const m = ohmGrammar.match(source, 'Grammars');\n if (m.failed()) {\n throw grammarSyntaxError(m);\n }\n return buildGrammar(m, namespace);\n}\n\nfunction grammar(source, optNamespace) {\n const ns = grammars(source, optNamespace);\n\n // Ensure that the source contained no more than one grammar definition.\n const grammarNames = Object.keys(ns);\n if (grammarNames.length === 0) {\n throw new Error('Missing grammar definition');\n } else if (grammarNames.length > 1) {\n const secondGrammar = ns[grammarNames[1]];\n const interval = secondGrammar.source;\n throw new Error(\n getLineAndColumnMessage(interval.sourceString, interval.startIdx) +\n 'Found more than one grammar definition -- use ohm.grammars() instead.',\n );\n }\n return ns[grammarNames[0]]; // Return the one and only grammar.\n}\n\nfunction grammars(source, optNamespace) {\n const ns = Object.create(optNamespace || {});\n if (typeof source !== 'string') {\n // For convenience, detect Node.js Buffer objects and automatically call toString().\n if (isBuffer(source)) {\n source = source.toString();\n } else {\n throw new TypeError(\n 'Expected string as first argument, got ' + unexpectedObjToString(source),\n );\n }\n }\n compileAndLoad(source, ns);\n return ns;\n}\n\nexports.ExperimentalIndentationSensitive = IndentationSensitive;\nexports._buildGrammar = buildGrammar;\nexports.grammar = grammar;\nexports.grammars = grammars;\nexports.makeRecipe = makeRecipe;\nexports.ohmGrammar = ohmGrammar;\nexports.pexprs = pexprs;\nexports.version = version;\n//# sourceMappingURL=ohm.cjs.map\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(341);\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack://@caph1993/numpy-js/webpack/universalModuleDefinition","webpack://@caph1993/numpy-js/./src/NDArray-class.ts","webpack://@caph1993/numpy-js/./src/NDArray/_globals.ts","webpack://@caph1993/numpy-js/./src/NDArray/basic.ts","webpack://@caph1993/numpy-js/./src/NDArray/elementwise.ts","webpack://@caph1993/numpy-js/./src/NDArray/index.ts","webpack://@caph1993/numpy-js/./src/NDArray/indexes.ts","webpack://@caph1993/numpy-js/./src/NDArray/js-interface.ts","webpack://@caph1993/numpy-js/./src/NDArray/operators.ts","webpack://@caph1993/numpy-js/./src/NDArray/print.ts","webpack://@caph1993/numpy-js/./src/NDArray/reduce.ts","webpack://@caph1993/numpy-js/./src/NDArray/transform.ts","webpack://@caph1993/numpy-js/./src/_globals.ts","webpack://@caph1993/numpy-js/./src/index.ts","webpack://@caph1993/numpy-js/./src/modules/_globals.ts","webpack://@caph1993/numpy-js/./src/modules/constructors.ts","webpack://@caph1993/numpy-js/./src/modules/grammar.ts","webpack://@caph1993/numpy-js/./src/modules/index.ts","webpack://@caph1993/numpy-js/./src/modules/random.ts","webpack://@caph1993/numpy-js/./src/utils-js.ts","webpack://@caph1993/numpy-js/./node_modules/.pnpm/ohm-js@17.1.0/node_modules/ohm-js/dist/ohm.cjs","webpack://@caph1993/numpy-js/webpack/bootstrap","webpack://@caph1993/numpy-js/webpack/startup"],"names":["root","factory","exports","module","define","amd","i","a","self","__generator","this","thisArg","body","f","y","t","_","label","sent","trys","ops","g","next","verb","Symbol","iterator","n","v","step","op","TypeError","call","done","value","pop","length","push","e","__read","o","m","r","ar","error","__spreadArray","to","from","pack","arguments","l","Array","prototype","slice","concat","NDArray","Object","defineProperty","get","_simpleIndexes","_flat","size","enumerable","configurable","_this","indices","map","set","list","Error","transpose","__popKwArgs","out","undefined","withKwArgs","kwArgs","_a","shape","index","item","flat","dtype","Number","GLOBALS","NDArray_1","basic","modules","reduceDecorator","func","axis","keepdims","assign","binaryOpDecorator","other","unaryOpDecorator","assignOpDecorator","args","_i","apply","reshape","more_shape","ravel","copy","where","indexes","toString","print","humanReadable","any","reduce","reducersBool","all","sum","reducers","product","max","min","argmax","argmin","mean","var","reducersExtra","norm","ord","std","ddof","add","operators","op_binary","subtract","multiply","divide","mod","divide_int","pow","maximum","minimum","bitwise_or","bitwise_and","bitwise_shift_right","logical_or","logical_and","logical_xor","greater","less","greater_equal","less_equal","equal","not_equal","op_unary","abs","isclose","allclose","op_assign","add_assign","subtract_assign","multiply_assign","divide_assign","mod_assign","divide_int_assign","pow_assign","maximum_assign","minimum_assign","bitwise_or_assign","bitwise_and_assign","bitwise_shift_left_assign","bitwise_shift_right_assign","logical_or_assign","logical_and_assign","tolist","jsInterface","round","decimals","elementwise","axes","transform","sort","symbol_1","func_1","keys","other_1","func_2","includes","symbol","_globals_1","array","asarray","new_NDArray","isarray","_NDArray","np","__NDArray","A","fromlist","empty","new_from","parse_shape","shape_shifts","as_number","as_boolean","number_collapse","arr","expect","obj","parseFloat","isArray","b","shifts","shape_or_first","inferredIndex","indexOf","known","filter","dim","acc","val","__make_elementwise","logical_not","bitwise_not","basic_1","Math","x","toFixed","Boolean","sign","sqrt","square","exp","log","log2","log10","log1p","sin","cos","tan","asin","acos","atan","atan2","cosh","sinh","tanh","acosh","asinh","atanh","__values","s","AxisIndex","__parse_sliceRange","AxesIndex","src_flat_1","axesIndex","parse","isConstant","index_1","isSimple","composition","first","second","axisIndexes","j","specA","spec","specB","type","range","startA","start","stepA","nStepsA","nSteps","index_2","_b","startB","stepB","nStepsB","sub","parse_range","apparentShape","internalShape","_indices","slices","e_1","slices_1","slices_1_1","e_1_1","return","iShifts","lastAxis","tuple","fill","cursor","isFinite","__slices","idx","_size","axis_size","stop","step_1","start_1","ifNull","floor","parse_range_spec","rangeString","numbers","split","trim","parseInt","isInteger","indexSpec","span","index_3","indices_1","forEach","if_value","stop_1","axisIndex","_where","buffers","readDir","reversedAfter","NaN","remainingAxes","remainingWhere","axisWhere","key","refSize","splice","reverse","pushToFlat","e_2","arr_1","arr_1_1","elem","arr_2","arr_2_1","e_2_1","recursiveReshape","flatArr","shapeArr","shift","innerShape","outerSize","innerArray","__make_assignment_operator","_assign_operation_toJS","assign_operation","__make_operator_special","__make_operator","_broadcast_shapes","binary_operation","js_interface_1","B","bind","shapeA","shapeB","flatOut","shiftsA","shiftsB","flatA","flatB","idxA","idxB","maxDim","dim1","dim2","unshift","operator","funcNum","funcBool","console","warn","tgt","src","tmpTgt","indices_1_1","tgtJS","cpy","outJS","rtol","atol","equal_nan","isNaN","different","err","elementwise_1","budgets","lBudget","before","rBudget","rLimit","suffix","name","str","indent","depth","join","sep","repeat","simplify","left","right","replace","match","inputString","delimiter","rows","columnWidths","rows_1","rows_1_1","columns","formattedString","rows_2","rows_2_1","_loop_1","row","column","padStart","padEnd","operators_1","reducer","groups","nCols","groupsT","newRow","__make_reducer","_c","len","Infinity","arrMean","_sum","variance","_len","stack","concatenate","swapAxes","apply_along_axis","utils_js_1","nDims","tmp_1","data","tmp","inv","srcShifts","axisA","axisB","perm","arrays","shapeIn","arrays_1","arrays_1_1","allEq","shapeBroadcast","bArrays","arrays_2","arrays_2_1","template","variables","usage","grammar","NDArray_class_1","default","prod","ew","bitwise_xor","bitwise_shift_left","modules_1","constructors","zeros","ones","arange","linspace","geomspace","random","nd_modules","arg0","arg1","end","num","endpoint","c","__makeTemplateObject","cooked","raw","__parser_pool","__makeSemantics","ohmGrammar","ohm","String","semanticVariables","semantics","Instruction_sliceAssignment","$tgt","_open","$where","_close","$symbol","$src","_tgt","_src","sourceString","Instruction_expression","$arr","Precedence11","BinaryOperation","Precedence10","Precedence09","Precedence08","Precedence07","Precedence06","Precedence05","Precedence04","UnaryOperation","Precedence03","Precedence02","number","arg2","arg3","arg4","arg5","arg6","arg7","Arr_slice","SliceTerm_constant","$x","Arr_call","$name","$names","$callArgs","Arr_method","_dot","Parenthesis","__","Arr_attribute","Variable","$i","isListOfArrays","int","$sign","$value","SliceRange","$start","$stop","$step","Constant","POSITIVE_INFINITY","$str","CallArgs","$args","_comma","$kwArgs","_trailing","entries","fromEntries","k","KwArg","$key","_equals","NonemptyListOf","more","children","JsArray","$list","_terminal","$A","$B","ohmSemantics","createSemantics","addOperation","template_with_placeholders","succeeded","message","busy","pool","parser","shuffle","shuffled","_shuffled","_shuffle","normal","randn","__normal","exponential","uniform","u","seen","q","_next","c_i","allClose","nan_equal","wrapper","abstract","optMethodName","methodName","constructor","assert","cond","defineLazyProperty","propName","getterFn","let","memo","repeatFn","fn","repeatStr","getDuplicates","duplicates","lastIndexOf","copyWithoutDuplicates","noDuplicates","entry","isSyntactic","ruleName","firstChar","toUpperCase","isLexical","padLeft","optChar","StringBuffer","strings","append","contents","escapeUnicode","fromCodePoint","unescapeCodePoint","charAt","unexpectedObjToString","baseToString","typeName","JSON","stringify","common","freeze","__proto__","clone","UnicodeCategories","Lu","Ll","Lt","Lm","Lo","Nl","Nd","Mn","Mc","Pc","Zs","L","Ltmo","PExpr","withSource","interval","source","trimmed","create","Terminal","super","Range","matchCodePoint","Param","Alt","terms","Extend","superGrammar","rules","Splice","beforeTerms","afterTerms","origBody","expansionPos","Seq","factors","Iter","expr","Star","Plus","Opt","minNumMatches","maxNumMatches","Not","Lookahead","Lex","Apply","toMemoKey","_memoKey","UnicodeChar","category","pattern","createError","optInterval","getLineAndColumnMessage","shortMessage","intervalSourcesDontMatch","undeclaredRule","grammarName","duplicateRuleDeclaration","declGrammarName","optSource","wrongNumberOfParameters","expected","actual","duplicateParameterNames","incorrectArgumentType","expectedType","kleeneExprHasNullableOperand","kleeneExpr","applicationStack","actuals","substituteParams","stackTrace","app","inconsistentArity","throwErrors","errors","messages","strcpy","dest","offset","origDestLen","substr","lineAndColumnToMessage","ranges","lineAndCol","sb","lineNumbers","lineNum","colNum","maxLen","prevLine","nextLine","appendLine","content","prefix","lineLen","line","indicationLine","startIdx","endIdx","lineStartOffset","gutterWidth","builtInRulesCallbacks","awaitBuiltInRules","cb","getLineAndColumn","currOffset","prevLineStartOffset","lineEndOffset","nextLineEndOffset","uniqueId","idCounter","Interval","_contents","coverageWith","intervals","coverage","collapsedLeft","collapsedRight","minus","that","relativeTo","subInterval","newStartIdx","firstInterval","InputStream","pos","examinedLength","atEnd","ans","nextCharCode","nextChar","charCodeAt","nextCodePoint","cp","codePointAt","matchString","optIgnoreCase","sourceSlice","optEndIdx","MatchResult","matcher","input","startExpr","cst","cstOffset","rightmostFailurePosition","optRecordedFailures","_cst","_cstOffset","_rightmostFailurePosition","_rightmostFailures","failed","detail","getExpectedText","getRightmostFailurePosition","errorInfo","getRightmostFailures","matchResultWithFailures","setInput","_match","tracing","positionToRecordFailures","failures","failure","isFluffy","getInterval","PosInfo","applicationMemoKeyStack","maxExaminedLength","maxRightmostFailureOffset","currentLeftRecursion","isActive","application","enter","exit","startLeftRecursion","headApplication","memoRec","isLeftRecursion","nextLeftRecursion","indexOfFirstInvolvedRule","involvedApplicationMemoKeys","isInvolved","applicationMemoKey","updateInvolvedApplicationMemoKeys","endLeftRecursion","shouldUseMemoizedResult","memoize","memoKey","rightmostFailureOffset","clearObsoleteEntries","invalidatedIdx","DOT_OPERATOR","SYMBOL_FOR_HORIZONTAL_TABULATION","SYMBOL_FOR_LINE_FEED","SYMBOL_FOR_CARRIAGE_RETURN","Flags","isRootNode","isImplicitSpaces","isMemoized","isHeadOfLeftRecursion","terminatesLR","asEscapedString","Trace","pos1","pos2","bindings","optChildren","terminatingLREntry","_flags","toDisplayString","cloneWithExpr","recordLRTermination","ruleBodyTrace","walk","visitorObjOrFn","optThisArg","visitor","_walk","node","parent","recurse","SKIP","child","excerpt","displayString","mask","allowsSkippingPrecedingSpace","BuiltInRules$1","lexifyCount","assertAllApplicationsAreValid","_assertAllApplicationsAreValid","skipSyntacticCheck","ruleInfo","isContextSyntactic","formals","isBuiltInApplySyntactic","applySyntactic","isBuiltInCaseInsensitive","caseInsensitive","arg","getArity","assertChoicesHaveUniformArity","arity","term","otherArity","actualArity","expectedArity","assertIteratedExprsAreNotNullable","isNullable","Node","matchLength","numChildren","childAt","indexOfChild","hasChildren","hasNoChildren","onlyChild","ctorName","firstChild","lastChild","childBefore","childIdx","childAfter","isTerminal","isNonterminal","isIteration","isOptional","TerminalNode","NonterminalNode","childOffsets","IterationNode","optional","getMetaInfo","grammarInterval","metaInfo","adjusted","sourceInterval","isRestrictedJSIdentifier","test","resolveDuplicatedNames","argumentNameList","count","argName","dupArgName","subscript","eval","state","inputStream","origPos","pushBinding","processFailure","currentApplication","enterLexifiedContext","exitLexifiedContext","factor","cols","colOffsets","numMatches","prevPos","_applicationStack","_bindings","rowOffsets","_bindingOffsets","posToOffset","endOffset","lastColOffsets","lastCol","pushFailuresInfo","popFailuresInfo","caller","posInfo","getCurrentPosInfo","handleCycle","hasNecessaryInfo","useMemoizedResult","reallyEval","origPosInfo","description","origInputStreamExaminedLength","enterApplication","evalOnce","currentLR","doNotMemoize","growSeedResult","_getRightmostFailureOffset","failuresAtRightmostPosition","cloneRecordedFailures","isTracing","getTraceEntry","traceEntry","exitApplication","offsets","lrMemoRec","newValue","seedTrace","trace","ch","outputRecipe","toLowerCase","introduceParams","_isNullable","some","every","inlined","hasOwnProperty","toArgumentNameList","firstArgIndex","noDupCheck","termArgNameLists","numArgs","colIdx","col","rowIdx","uniqueNames","factorArgumentNameList","exprArgumentString","ps","Failure","pexpr","text","fluffy","getPExpr","getText","getType","isDescription","isStringTerminal","isCode","makeFluffy","clearFluffy","subsumes","toKey","toFailure","article","CaseInsensitiveTerminal","param","_getString","terminal","matchStr","pexprs","builtInApplySyntacticBody","builtInRules","applySpaces","MatchState","optPositionToRecordFailures","getInput","memoTable","_memoTable","userData","_posStack","inLexifiedContextStack","_rightmostFailurePositionStack","_recordedFailuresStack","recordedFailures","optNode","inSyntacticContext","inLexifiedContext","skipSpaces","popBinding","skipSpacesIfInSyntacticContext","maybeSkipSpacesBefore","numBindings","truncateBindings","newLength","getPosInfo","recordFailure","shouldCloneIfNew","recordFailures","getMemoizedTraceEntry","memoRecRightmostFailurePosition","origNumBindings","origUserData","origRecordedFailures","memoPos","origTrace","getMatchResult","_setUpMatchState","rightmostFailures","getTrace","matchResult","rootTrace","result","Matcher","_input","_isMemoTableStale","_resetMemoTable","replaceInputRange","prevInput","restOfMemoTable","optStartApplicationStr","options","incremental","_getStartExpr","opts","supportsIncrementalParsing","applicationStr","defaultStartRule","startApp","parseApplication","globalActionStack","prop","Wrapper","baseInterval","_node","_baseInterval","_childWrappers","_forgetMemoizedResultFor","attributeName","_semantics","attributeKeys","childWrapper","childNode","base","wrap","_children","iteration","optChildWrappers","childWrappers","childNodes","iter","Semantics","superSemantics","checkedActionDicts","checkActionDictsIfHaventAlready","equals","_inheritsFrom","operations","attributes","checkActionDicts","checkActionDict","toRecipe","semanticsOnly","hasSuperSemantics","BuiltInSemantics","_getSemantics","superSemanticsGrammar","relatedGrammar","semanticOperations","actionDict","builtInDefault","signature","method","srcArray","actionName","addOperationOrAttribute","typePlural","parsedNameAndFormalArgs","parseSignature","formal","info","moreInfo","doIt","assertNewName","realActionDict","_default","Operation","Attribute","thisThing","argsObj","oldArgs","execute","extendOperationOrAttribute","inheritedFormals","inheritedActionDict","newActionDict","optBaseInterval","prototypeGrammar","prototypeGrammarSemantics","optSuperSemantics","proxy","extendOperation","addAttribute","extendAttribute","_getActionDict","operationOrAttributeName","action","_remove","semantic","getOperationNames","getAttributeNames","getGrammar","_checkTopDownActionDict","nodeWrapper","actionFn","_nonterminal","SPECIAL_ACTION_NAMES","getSortedRuleValues","ohmGrammar$1","buildGrammar$1","Grammar","optDefaultStartRule","_matchStateInitializer","isBuiltIn","ProtoBuiltInRules","BuiltInRules","myRules","otherRules","rule","optStartApplication","extendSemantics","what","prettyProblems","problems","_topDownActionArity","details","problem","superGrammarExpr","startRule","isDefinition","operation","bodyRecipe","superGrammarOutput","toOperationActionDictionaryTemplate","_toOperationOrAttributeActionDictionaryTemplate","toAttributeActionDictionaryTemplate","addSemanticActionTemplate","primitive","lower","upper","unicodeLtmo","spaces","space","initApplicationParser","builderFn","GrammarDecl","ensureSuperGrammar","withSuperGrammar","ensureSuperGrammarRuleForOverriding","installOverriddenOrExtendedRule","duplicateParameterNames$1","expectedFormals","expectedNumFormals","install","withDefaultStartRule","build","grammarErrors","grammarHasInvalidApplications","override","descIgnored","extend","fragment","Builder","currentDecl","currentRuleName","newGrammar","gDecl","fromRecipe","ruleRecipe","alt","termArgs","seq","factorArgs","star","plus","opt","not","lookahead","lex","optParams","recipe","makeRecipe","superSplicePlaceholder","namespaceHas","ns","buildGrammar","namespace","optOhmGrammarForTesting","builder","decl","currentRuleFormals","overriding","Grammars","grammarIter","visit","id","SuperGrammar","superGrammarName","Rule_define","fs","d","Rule_override","Rule_extend","RuleBody","OverrideRuleBody","Formals","opointy","cpointy","Params","seqs","TopLevelTerm_inline","inlineRuleName","isNewRuleDeclaration","params","OverrideTopLevelTerm_superSplice","Iter_star","Iter_plus","Iter_opt","Pred_not","Pred_lookahead","Lex_lex","Base_application","Base_range","Base_terminal","Base_paren","open","close","ruleDescr","ruleDescrText","caseName","space1","space2","rest","nameFirst","nameRest","cs","oneCharTerminal","escapeChar","RangeError","startsWith","applyWrapper","fullInterval","digitIntervals","xs","EmptyListOf","operationsAndAttributesGrammar","actions","nonEmpty","emptyListOf","nonemptyListOf","AttributeSignature","OperationSignature","optFormals","oparen","cparen","asIteration","INDENT_DESCRIPTION","DEDENT_DESCRIPTION","InputStreamWithIndentation","_indentationAt","Indentation","isIndent","pseudoTokens","applyIndent","applyDedent","newAnyBody","IndentationSensitive","topOfStack","regex","exec","indentSize","prevSize","indentPos","prevLength","isBuffer","compileAndLoad","matchFailure","grammars","optNamespace","ExperimentalIndentationSensitive","_buildGrammar","grammarNames","version","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__"],"mappings":"AAAA,UAA2CA,EAAMC,GAChD,GAAsB,UAAnB,OAAOC,SAA0C,UAAlB,OAAOC,OACxCA,OAAOD,QAAUD,EAAQ,OACrB,GAAqB,YAAlB,OAAOG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,CAAO,MACd,CACJ,IACQK,EADJC,EAAIN,EAAQ,EAChB,IAAQK,KAAKC,GAAuB,UAAnB,OAAOL,QAAuBA,QAAUF,GAAMM,GAAKC,EAAED,EACvE,CACA,EAAEE,KAAM,K,6CCRT,IAAIC,EAAeC,MAAQA,KAAKD,aAAgB,SAAUE,EAASC,GAC/D,IAAsGC,EAAGC,EAAGC,EAAxGC,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EAAa,GACzB,EAqBAzzC,EAAQqzC,SAAWA,GACnBrzC,EAAQqtC,WAAaA,GACrBrtC,EAAQme,WAAaA,GACrBne,EAAQw/B,OAASA,GACjBx/B,EAAQ0zC,QA1DQ,Q,GCt6KZC,EAA2B,G,OAG/B,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,OAAqBvvC,SAAjBwvC,IAIA7zC,EAAS0zC,EAAyBE,GAAY,CAGjD7zC,QAAS,EACV,EAGA+zC,EAAoBF,GAAUhyC,KAAK5B,EAAOD,QAASC,EAAQA,EAAOD,QAAS4zC,CAAmB,GAGvF3zC,EAAOD,OACf,ECnB8C,GAAG,C","file":"caph1993-numpy-js.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse {\n\t\tvar a = factory();\n\t\tfor(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n\t}\n})(self, () => {\nreturn ","\"use strict\";\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NDArray = void 0;\nvar NDArray = /** @class */ (function () {\n function NDArray(flat, shape, dtype) {\n if (dtype === void 0) { dtype = Number; }\n this.shape = shape; // invariant: immutable\n this._flat = flat;\n this.dtype = dtype;\n this._simpleIndexes = null;\n }\n Object.defineProperty(NDArray.prototype, \"size\", {\n get: function () {\n return this._simpleIndexes == null ? this._flat.length : this._simpleIndexes.size;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(NDArray.prototype, \"flat\", {\n get: function () {\n var _this = this;\n if (this._simpleIndexes == null)\n return this._flat;\n var indices = this._simpleIndexes.indices;\n return indices.map(function (i) { return _this._flat[i]; });\n },\n set: function (list) {\n if (list.length != this.size)\n throw new Error(\"Length mismatch. Can't write \".concat(list.length, \" values into \").concat(this.size, \" available positions.\"));\n var n = this.size;\n if (this._simpleIndexes == null) {\n for (var i = 0; i < n; i++)\n this._flat[i] = list[i];\n }\n else {\n var indices = this._simpleIndexes.indices;\n for (var i = 0; i < n; i++)\n this._flat[indices[i]] = list[i];\n }\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(NDArray.prototype, \"T\", {\n get: function () {\n return this.transpose();\n },\n enumerable: false,\n configurable: true\n });\n NDArray.prototype.__popKwArgs = function () {\n var out = this['__kwArgs'];\n if (out === undefined)\n return {};\n delete this['__kwArgs'];\n return out;\n };\n /** @param {Object} kwArgs */\n NDArray.prototype.withKwArgs = function (kwArgs) {\n this['__kwArgs'] = kwArgs;\n return this;\n };\n NDArray.prototype[Symbol.iterator] = function () {\n var i;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n i = 0;\n _a.label = 1;\n case 1:\n if (!(i < this.shape[0])) return [3 /*break*/, 4];\n return [4 /*yield*/, this.index(i)];\n case 2:\n _a.sent();\n _a.label = 3;\n case 3:\n i++;\n return [3 /*break*/, 1];\n case 4: return [2 /*return*/];\n }\n });\n };\n Object.defineProperty(NDArray.prototype, \"length\", {\n get: function () {\n return this.shape[0] || 0;\n },\n enumerable: false,\n configurable: true\n });\n NDArray.prototype.item = function () {\n if (this.size != 1)\n throw new Error(\"Can't convert array of size \".concat(this.size, \" to scalar\"));\n return this._flat[0];\n };\n return NDArray;\n}());\nexports.NDArray = NDArray;\nvar _globals_1 = require(\"./_globals\");\n_globals_1.GLOBALS.NDArray = NDArray;\nvar NDArray_1 = require(\"./NDArray\");\nNDArray.prototype.modules = NDArray_1.modules;\n// ==============================\n// Basic methods\n// ==============================\nvar basic = NDArray_1.modules.basic;\nNDArray.prototype.reshape = function (shape) {\n var more_shape = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n more_shape[_i - 1] = arguments[_i];\n }\n return basic.reshape.apply(basic, __spreadArray([this, shape], __read(more_shape), false));\n};\nNDArray.prototype.ravel = function () {\n return basic.ravel(this);\n};\nNDArray.prototype.copy = function () {\n return basic.copy(this);\n};\n// ==============================\n// Indexing\n// ==============================\nNDArray.prototype.index = function () {\n var where = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n where[_i] = arguments[_i];\n }\n return NDArray_1.modules.indexes.index(this, where);\n};\n// ==============================\n// Printing\n// ==============================\nNDArray.prototype.toString = function () {\n return NDArray_1.modules.print.humanReadable(this);\n};\n// ==============================\n// Reduce\n// ==============================\nfunction reduceDecorator(func) {\n return function (axis, keepdims) {\n var _a;\n if (axis === void 0) { axis = null; }\n if (keepdims === void 0) { keepdims = false; }\n (_a = Object.assign({ axis: axis, keepdims: keepdims }, this.__popKwArgs()), axis = _a.axis, keepdims = _a.keepdims);\n return func(this, axis, keepdims);\n };\n}\nNDArray.prototype.any = reduceDecorator(NDArray_1.modules.reduce.reducersBool.any);\nNDArray.prototype.all = reduceDecorator(NDArray_1.modules.reduce.reducersBool.all);\nNDArray.prototype.sum = reduceDecorator(NDArray_1.modules.reduce.reducers.sum);\nNDArray.prototype.product = reduceDecorator(NDArray_1.modules.reduce.reducers.product);\nNDArray.prototype.max = reduceDecorator(NDArray_1.modules.reduce.reducers.max);\nNDArray.prototype.min = reduceDecorator(NDArray_1.modules.reduce.reducers.min);\nNDArray.prototype.argmax = reduceDecorator(NDArray_1.modules.reduce.reducers.argmax);\nNDArray.prototype.argmin = reduceDecorator(NDArray_1.modules.reduce.reducers.argmin);\nNDArray.prototype.mean = reduceDecorator(NDArray_1.modules.reduce.reducers.mean);\n// reducersExtra\nNDArray.prototype.var = reduceDecorator(NDArray_1.modules.reduce.reducersExtra.var);\nNDArray.prototype.norm = function (axis, keepdims, ord) {\n var _a;\n if (axis === void 0) { axis = null; }\n if (keepdims === void 0) { keepdims = false; }\n if (ord === void 0) { ord = 2; }\n (_a = Object.assign({ axis: axis, keepdims: keepdims, ord: ord }, this.__popKwArgs()), axis = _a.axis, keepdims = _a.keepdims, ord = _a.ord);\n return NDArray_1.modules.reduce.reducersExtra.norm(this, axis, keepdims, ord);\n};\nNDArray.prototype.std = function (axis, keepdims, ddof) {\n var _a;\n if (axis === void 0) { axis = null; }\n if (keepdims === void 0) { keepdims = false; }\n if (ddof === void 0) { ddof = 0; }\n (_a = Object.assign({ axis: axis, keepdims: keepdims, ddof: ddof }, this.__popKwArgs()), axis = _a.axis, keepdims = _a.keepdims, ddof = _a.ddof);\n return NDArray_1.modules.reduce.reducersExtra.std(this, axis, keepdims, ddof);\n};\n// ==============================\n// Operators: Binary operations, assignment operations and unary boolean_not\n// ==============================\nfunction binaryOpDecorator(func) {\n return function (other, out) {\n if (out === void 0) { out = null; }\n (out = Object.assign({ out: out }, this.__popKwArgs()).out);\n return func(this, other, out);\n };\n}\nNDArray.prototype.add = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"+\"]);\nNDArray.prototype.subtract = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"-\"]);\nNDArray.prototype.multiply = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"*\"]);\nNDArray.prototype.divide = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"/\"]);\nNDArray.prototype.mod = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"%\"]);\nNDArray.prototype.divide_int = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"//\"]);\nNDArray.prototype.pow = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"**\"]);\nNDArray.prototype.maximum = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"↑\"]);\nNDArray.prototype.minimum = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"↓\"]);\nNDArray.prototype.bitwise_or = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"|\"]);\nNDArray.prototype.bitwise_and = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"&\"]);\nNDArray.prototype.bitwise_or = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"^\"]);\nNDArray.prototype.bitwise_shift_right = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"<<\"]);\nNDArray.prototype.bitwise_shift_right = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\">>\"]);\nNDArray.prototype.logical_or = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"or\"]);\nNDArray.prototype.logical_and = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"and\"]);\nNDArray.prototype.logical_xor = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"xor\"]);\nNDArray.prototype.greater = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\">\"]);\nNDArray.prototype.less = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"<\"]);\nNDArray.prototype.greater_equal = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\">=\"]);\nNDArray.prototype.less_equal = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"<=\"]);\nNDArray.prototype.equal = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"==\"]);\nNDArray.prototype.not_equal = binaryOpDecorator(NDArray_1.modules.operators.op_binary[\"!=\"]);\nfunction unaryOpDecorator(func) {\n return function (out) {\n if (out === void 0) { out = null; }\n (out = Object.assign({ out: out }, this.__popKwArgs()).out);\n return func(this, out);\n };\n}\n// Unary operations: only boolean_not. Positive is useless and negative is almost useless\nNDArray.prototype.bitwise_or = unaryOpDecorator(NDArray_1.modules.operators.op_unary[\"~\"]);\nNDArray.prototype.logical_or = unaryOpDecorator(NDArray_1.modules.operators.op_unary[\"not\"]);\nNDArray.prototype.abs = unaryOpDecorator(NDArray_1.modules.operators.op_unary[\"abs\"]);\nNDArray.prototype.isclose = NDArray_1.modules.operators.isclose;\nNDArray.prototype.allclose = NDArray_1.modules.operators.allclose;\nfunction assignOpDecorator(func) {\n //@ts-ignore\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return func.apply(void 0, __spreadArray([this], __read(args), false));\n };\n}\nNDArray.prototype.assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"=\"]);\nNDArray.prototype.add_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"+=\"]);\nNDArray.prototype.subtract_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"-=\"]);\nNDArray.prototype.multiply_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"*=\"]);\nNDArray.prototype.divide_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"/=\"]);\nNDArray.prototype.mod_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"%=\"]);\nNDArray.prototype.divide_int_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"//=\"]);\nNDArray.prototype.pow_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"**=\"]);\nNDArray.prototype.maximum_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"↑=\"]);\nNDArray.prototype.minimum_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"↓=\"]);\nNDArray.prototype.bitwise_or_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"|=\"]);\nNDArray.prototype.bitwise_and_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"&=\"]);\nNDArray.prototype.bitwise_shift_left_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"<<=\"]);\nNDArray.prototype.bitwise_shift_right_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\">>=\"]);\nNDArray.prototype.logical_or_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"or=\"]);\nNDArray.prototype.logical_and_assign = assignOpDecorator(NDArray_1.modules.operators.op_assign[\"and=\"]);\n// ==============================\n// array instantiation and reshaping\n// ==============================\nNDArray.prototype.tolist = function () {\n return NDArray_1.modules.jsInterface.tolist(this);\n};\n// NDArray.prototype.fromJS = function (A) {\n// return modules.jsInterface.fromJS(A);\n// }\n// ==============================\n// elementwise methods\n// ==============================\nNDArray.prototype.round = function (decimals) {\n if (decimals === void 0) { decimals = 0; }\n (decimals = Object.assign({ decimals: decimals }, this.__popKwArgs()).decimals);\n return NDArray_1.modules.elementwise.round(this, decimals);\n};\n// ==============================\n// transform methods\n// ==============================\n/** @param {null|number[]} axes */\nNDArray.prototype.transpose = function (axes) {\n if (axes === void 0) { axes = null; }\n (axes = Object.assign({ axes: axes }, this.__popKwArgs()).axes);\n return NDArray_1.modules.transform.transpose(this, axes);\n};\nNDArray.prototype.sort = function (axis) {\n if (axis === void 0) { axis = -1; }\n (axis = Object.assign({ axis: axis }, this.__popKwArgs()).axis);\n NDArray_1.modules.transform.sort(this, axis);\n return null;\n};\nvar op = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n if (!args.length)\n return this;\n if (typeof args[0] == \"string\") {\n var symbol_1 = args[0];\n if (args.length == 1) {\n var func_1 = NDArray_1.modules.operators.op_unary[symbol_1];\n if (!func_1)\n throw new Error(\"Unknown unary operator \\\"\".concat(symbol_1, \"\\\". Options:\").concat(__spreadArray([], __read(Object.keys(NDArray_1.modules.operators.op_unary)), false)));\n return func_1(this, symbol_1);\n }\n if (args.length > 2)\n throw new Error(\"Too many arguments provided: \".concat(__spreadArray([], __read(args), false)));\n var other_1 = args[1];\n var func_2 = NDArray_1.modules.operators.op_binary[symbol_1];\n if (func_2)\n return func_2(this, other_1);\n func_2 = NDArray_1.modules.operators.op_assign[symbol_1];\n if (func_2)\n return func_2(this, other_1);\n if (symbol_1.includes(':'))\n throw new Error(\"Expected index or operator symbol. Found \\\"\".concat(symbol_1, \"\\\". Did you mean \").concat([symbol_1], \"?\"));\n throw new Error(\"Expected index or operator symbol. Found \\\"\".concat(symbol_1, \"\\\"\"));\n }\n var where = args[0];\n if (where instanceof NDArray)\n throw new Error(\"Expected operator or index. Found numpy array\");\n if (args.length == 1)\n return this.index(where);\n var symbol = args[1];\n var func = NDArray_1.modules.operators.op_assign[symbol];\n if (!func)\n throw new Error(\"Unknown unary operator \\\"\".concat(symbol, \"\\\". Options:\").concat(__spreadArray([], __read(Object.keys(NDArray_1.modules.operators.op_unary)), false)));\n if (args.length > 3)\n throw new Error(\"Too many arguments provided: \".concat(__spreadArray([], __read(args), false)));\n var other = args[2];\n return func(this, where, other);\n};\nNDArray.prototype.op = op;\nexports.default = NDArray;\n","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.array = exports.asarray = exports.new_NDArray = exports.isarray = exports._NDArray = void 0;\nvar _globals_1 = require(\"../_globals\");\nvar np = _globals_1.GLOBALS.np, __NDArray = _globals_1.GLOBALS.NDArray;\nif (!__NDArray)\n throw new Error(\"Programming error: NDArray not defined\");\n// Functions to avoid importing NDArray (because if I import NDArray, I can't use it as a type annotation in the same file)\nexports._NDArray = __NDArray;\nfunction isarray(A) {\n return A instanceof exports._NDArray;\n}\nexports.isarray = isarray;\nvar new_NDArray = function (flat, shape, dtype) { return new exports._NDArray(flat, shape, dtype); };\nexports.new_NDArray = new_NDArray;\nfunction asarray(A) {\n if (isarray(A))\n return A;\n else\n return np.fromlist(A);\n}\nexports.asarray = asarray;\nfunction array(A) {\n if (isarray(A)) { // shallow copy of A\n var flat = A._simpleIndexes == null ? __spreadArray([], __read(A.flat), false) : A.flat;\n return (0, exports.new_NDArray)(flat, A.shape, A.dtype);\n }\n else\n return asarray(A);\n}\nexports.array = array;\n","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.copy = exports.empty = exports.new_from = exports.ravel = exports.reshape = exports.parse_shape = exports.shape_shifts = exports.as_number = exports.as_boolean = exports.number_collapse = exports._NDArray = exports.new_NDArray = exports.array = exports.asarray = exports.isarray = void 0;\nvar _globals_1 = require(\"./_globals\");\nObject.defineProperty(exports, \"isarray\", { enumerable: true, get: function () { return _globals_1.isarray; } });\nObject.defineProperty(exports, \"asarray\", { enumerable: true, get: function () { return _globals_1.asarray; } });\nObject.defineProperty(exports, \"array\", { enumerable: true, get: function () { return _globals_1.array; } });\nObject.defineProperty(exports, \"new_NDArray\", { enumerable: true, get: function () { return _globals_1.new_NDArray; } });\nObject.defineProperty(exports, \"_NDArray\", { enumerable: true, get: function () { return _globals_1._NDArray; } });\n// Functions to avoid importing NDArray (because if I import NDArray, I can't use it as a type annotation in the same file)\n/**\n * If the array is 0D, it returns it's unique element (number or boolean).\n * The signature is kept as NDArray for type consistency, even though the\n * output is a number or a boolean. This is consistent with the facts that\n * (1) all functions requiring arrays work with numbers as well because they call asarray,\n * and (2) semantically, a constant is an array.\n */\nfunction number_collapse(arr, expect) {\n if (expect === void 0) { expect = false; }\n if (!arr.shape.length)\n return arr.flat[0];\n if (expect)\n throw new Error(\"Expected constant. Got array with shape \".concat(arr.shape));\n return arr;\n}\nexports.number_collapse = number_collapse;\nfunction as_boolean(obj) {\n if ((0, _globals_1.isarray)(obj))\n obj = number_collapse(obj, true);\n else if (typeof obj == 'string')\n throw new Error(\"'string' object can not be interpreted as boolean: \".concat(obj));\n return !!(0 + obj);\n}\nexports.as_boolean = as_boolean;\nfunction as_number(obj) {\n if ((0, _globals_1.isarray)(obj))\n obj = number_collapse(obj, true);\n else if (typeof obj == 'string')\n throw new Error(\"'string' object can not be interpreted as boolean: \".concat(obj));\n return parseFloat(obj);\n}\nexports.as_number = as_number;\n// ====================\n// Reshape and shape shifts for indexing\n// ====================\nfunction shape_shifts(shape) {\n // increasing one by one on a given axis is increasing by shifts[axis] in flat representation\n var shifts = Array.from({ length: shape.length }, function (_) { return 0; });\n shifts[shape.length - 1] = 1;\n for (var i = shape.length - 2; i >= 0; i--)\n shifts[i] = shifts[i + 1] * shape[i + 1];\n return shifts;\n}\nexports.shape_shifts = shape_shifts;\nfunction parse_shape(list) {\n if (typeof list == \"number\")\n return [list];\n if ((0, _globals_1.isarray)(list)) {\n if (list.shape.length > 1) {\n throw new Error(\"Expected flat list. Got array with shape \".concat(list.shape));\n }\n return list.flat;\n }\n if (Array.isArray(list))\n return list;\n throw new Error(\"Expected list. Got \".concat(list));\n}\nexports.parse_shape = parse_shape;\nfunction reshape(A, shape_or_first) {\n var more_shape = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n more_shape[_i - 2] = arguments[_i];\n }\n A = (0, _globals_1.asarray)(A);\n var shape;\n if (!more_shape.length)\n shape = parse_shape(shape_or_first);\n else\n shape = __spreadArray([shape_or_first], __read(more_shape), false).map(as_number);\n var n = A.size;\n // Find -1\n var inferredIndex = shape.indexOf(-1);\n if (inferredIndex !== -1) {\n var known = shape.filter(function (dim) { return dim !== -1; }).reduce(function (acc, val) { return acc * val; }, 1);\n if (n % known !== 0) {\n throw new Error(\"Invalid shape. The total number of elements must match the product of the known dimensions.\");\n }\n shape[inferredIndex] = n / known;\n }\n return (0, _globals_1.new_NDArray)(A.flat, shape, A.dtype);\n}\nexports.reshape = reshape;\n;\nfunction ravel(A) {\n A = (0, _globals_1.asarray)(A);\n return (0, _globals_1.new_NDArray)(A.flat, [A.size], A.dtype);\n}\nexports.ravel = ravel;\n;\n// ====================\n// Constructors\n// ====================\nfunction new_from(shape, f, dtype) {\n if (f === void 0) { f = undefined; }\n if (dtype === void 0) { dtype = Number; }\n shape = parse_shape(shape);\n var size = shape.reduce(function (a, b) { return a * b; }, 1);\n var flat = Array.from({ length: size }, f);\n return (0, _globals_1.new_NDArray)(flat, shape, dtype);\n}\nexports.new_from = new_from;\n;\nfunction empty(shape, dtype) {\n if (dtype === void 0) { dtype = Number; }\n return new_from(shape, function (_) { return undefined; }, dtype);\n}\nexports.empty = empty;\n;\nfunction copy(A) {\n return (0, _globals_1.new_NDArray)(__spreadArray([], __read(A.flat), false), A.shape, A.dtype);\n}\nexports.copy = copy;\n","\"use strict\";\n//@ts-check\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ops = exports.__make_elementwise = exports.logical_not = exports.bitwise_not = exports.round = exports.elementwise = void 0;\nvar basic_1 = require(\"./basic\");\n// Here, we declare only the core functions (those that are methods)\nfunction elementwise(A, func, dtype) {\n A = (0, basic_1.asarray)(A);\n return (0, basic_1.new_NDArray)(A.flat.map(func), A.shape, dtype);\n}\nexports.elementwise = elementwise;\nfunction round(A, decimals) {\n if (decimals === void 0) { decimals = 0; }\n if (decimals == 0)\n elementwise(A, Math.round, Number);\n return elementwise(A, function (x) { return parseFloat(x.toFixed(decimals)); }, Number);\n}\nexports.round = round;\n;\nfunction bitwise_not(A) {\n return elementwise(A, function (x) { return ~x; }, Number);\n}\nexports.bitwise_not = bitwise_not;\n;\nfunction logical_not(A) {\n return elementwise(A, function (x) { return !x; }, Boolean);\n}\nexports.logical_not = logical_not;\n;\nfunction __make_elementwise(func, dtype) {\n if (dtype === void 0) { dtype = Number; }\n return function (A) {\n return elementwise(A, func, dtype);\n };\n}\nexports.__make_elementwise = __make_elementwise;\nexports.ops = {\n sign: __make_elementwise(Math.sign),\n sqrt: __make_elementwise(Math.sqrt),\n square: __make_elementwise(function (a) { return a * a; }),\n abs: __make_elementwise(Math.abs),\n exp: __make_elementwise(Math.exp),\n log: __make_elementwise(Math.log),\n log2: __make_elementwise(Math.log2),\n log10: __make_elementwise(Math.log10),\n log1p: __make_elementwise(Math.log1p),\n sin: __make_elementwise(Math.sin),\n cos: __make_elementwise(Math.cos),\n tan: __make_elementwise(Math.tan),\n asin: __make_elementwise(Math.asin),\n acos: __make_elementwise(Math.acos),\n atan: __make_elementwise(Math.atan),\n atan2: __make_elementwise(Math.atan2),\n cosh: __make_elementwise(Math.cosh),\n sinh: __make_elementwise(Math.sinh),\n tanh: __make_elementwise(Math.tanh),\n acosh: __make_elementwise(Math.acosh),\n asinh: __make_elementwise(Math.asinh),\n atanh: __make_elementwise(Math.atanh),\n round: round,\n};\n","\"use strict\";\n//@ts-check\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.modules = void 0;\n// Import core-globals first!\nrequire(\"./_globals\");\nvar basic = require(\"./basic\");\nvar indexes = require(\"./indexes\");\nvar jsInterface = require(\"./js-interface\");\nvar elementwise = require(\"./elementwise\");\nvar print = require(\"./print\");\nvar reduce = require(\"./reduce\");\nvar operators = require(\"./operators\");\nvar transform = require(\"./transform\");\nexports.modules = {\n basic: basic,\n jsInterface: jsInterface,\n indexes: indexes,\n elementwise: elementwise,\n print: print,\n reduce: reduce,\n operators: operators,\n transform: transform,\n};\n","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AxisIndex = exports.__parse_sliceRange = exports.AxesIndex = exports.index = void 0;\n//@ts-check\nvar basic_1 = require(\"./basic\");\nfunction index(arr, where) {\n // This can result either in a value, a view, a copy.\n // The index is simple if there are only ranges, numbers, \":\" and at most one \"...\"\n // If index is simple, don't call \".indices\" and make view\n // If index is advanced, get indices and make copy\n var copy = Object.assign({ copy: false }, arr.__popKwArgs()).copy;\n if (!((0, basic_1.isarray)(arr)))\n throw new Error(\"Expected NDArray. Found \".concat(typeof arr, \": \").concat(arr));\n var axesIndex = AxesIndex.prototype.parse(arr.shape, where);\n if (axesIndex.isConstant) {\n var _a = __read(axesIndex.indices, 1), index_1 = _a[0];\n return arr.flat[index_1];\n }\n else if (axesIndex.isSimple) {\n var composition = __compose_simpleIndexes(arr._simpleIndexes, axesIndex);\n var out = (0, basic_1.new_NDArray)(arr._flat, axesIndex.shape, arr.dtype);\n out._simpleIndexes = composition;\n if (arr['__warnAssignments'])\n out['__warnAssignments'] = true;\n return copy ? out.copy() : out;\n }\n else {\n var src_flat_1 = arr.flat;\n var flat = axesIndex.indices.map(function (i) { return src_flat_1[i]; });\n var out = (0, basic_1.new_NDArray)(flat, axesIndex.shape, arr.dtype);\n if (!copy)\n out['__warnAssignments'] = true;\n return out;\n }\n}\nexports.index = index;\n// type SimpleIndexes = null | { size: number, ranges: { refSize: number, range: null | number | [number, number, number] }[], indices: null | number[] };\nvar AxesIndex = /** @class */ (function () {\n /**\n * @param {AxisIndex[]} axisIndexes\n */\n function AxesIndex(apparentShape, internalShape, axisIndexes) {\n this.shape = apparentShape;\n this.internalShape = internalShape;\n this.axisIndexes = axisIndexes;\n this._indices = null;\n this._size = null;\n this.isSimple = this.axisIndexes.map(function (idx) { return idx.isSimple; }).reduce(function (a, b) { return a && b; }, true);\n this.isConstant = this.axisIndexes.map(function (idx) { return idx.isConstant; }).reduce(function (a, b) { return a && b; }, true);\n }\n Object.defineProperty(AxesIndex.prototype, \"indices\", {\n get: function () {\n if (this._indices)\n return this._indices;\n var indices = __slices_to_indices(this.internalShape, this.__slices);\n return this._indices = indices;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(AxesIndex.prototype, \"__slices\", {\n get: function () {\n return this.axisIndexes.map(function (idx) { return idx.indices; });\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(AxesIndex.prototype, \"size\", {\n get: function () {\n if (this._size)\n return this._size;\n return this._size = this.axisIndexes.map(function (idx) { return idx.size; }).reduce(function (a, b) { return a * b; }, 0);\n },\n enumerable: false,\n configurable: true\n });\n return AxesIndex;\n}());\nexports.AxesIndex = AxesIndex;\nfunction __compose_simpleIndexes(first, second) {\n if (first == null)\n return second;\n var axisIndexes = [];\n // console.log({ first, second })\n var j = 0;\n for (var i = 0; i < first.axisIndexes.length; i++) {\n var specA = first.axisIndexes[i].spec;\n var specB = second.axisIndexes[j].spec;\n if (specA.type == \"array\")\n throw new Error(\"Expected simple index. Found advanced: \".concat(specA.type));\n if (specB.type == \"array\")\n throw new Error(\"Expected simple index. Found advanced: \".concat(specB.type));\n var /**@type {AxisIndexSpec} */ spec = void 0;\n if (specA.type == \"number\")\n spec = specA;\n else {\n j++;\n if (specA.type == \":\")\n spec = specB;\n else if (specB.type == \":\")\n spec = specA;\n else {\n var _a = specA.range, startA = _a.start, stepA = _a.step, nStepsA = _a.nSteps;\n if (specB.type == \"number\") {\n var index_2 = specB.index;\n if (index_2 < 0)\n index_2 = nStepsA + index_2;\n if (index_2 < 0 || index_2 >= nStepsA)\n throw new Error(\"Index \".concat(index_2, \" out of bounds [0..\").concat(nStepsA, \")\"));\n index_2 = startA + index_2 * stepA;\n spec = { type: \"number\", index: index_2 };\n }\n else {\n var _b = specB.range, startB = _b.start, stepB = _b.step, nStepsB = _b.nSteps;\n var sub = AxisIndex.prototype.parse_range(nStepsA, startB, startB + nStepsB * stepB, stepB);\n var step = sub.step * stepA;\n var start = startA + sub.start * step;\n var nSteps = sub.nSteps;\n spec = { type: \"range\", range: { start: start, step: step, nSteps: nSteps } };\n }\n }\n }\n axisIndexes.push(new AxisIndex(spec));\n }\n if (j < second.axisIndexes.length)\n throw new Error(\"Index too long. Expected \".concat(j, \" axes. Found \").concat(second.axisIndexes.length));\n var apparentShape = second.shape;\n var internalShape = first.internalShape;\n return new AxesIndex(apparentShape, internalShape, axisIndexes);\n}\n/**\n * Computes the indices wr to shape of the cartesian products of the slices.\n * We have shape.length==slices.length, and the elements in slices[axis] are\n * integers between 0 and shape[axis]-1\n * @param {number[]} shape\n * @param {number[][]} slices\n * @returns {number[]}\n */\nfunction __slices_to_indices(shape, slices) {\n var e_1, _a;\n try {\n for (var slices_1 = __values(slices), slices_1_1 = slices_1.next(); !slices_1_1.done; slices_1_1 = slices_1.next()) {\n var slice = slices_1_1.value;\n if (slice.length == 0)\n return [];\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (slices_1_1 && !slices_1_1.done && (_a = slices_1.return)) _a.call(slices_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n var shifts = (0, basic_1.shape_shifts)(shape);\n var iShifts = slices.map(function (indices, axis) {\n // out[i] = How much does the cursor increase if we change from [...,indices[i],...] to [...,indices[(i+1)%n],...]\n var out = [], n = indices.length;\n for (var i = 0; i < n - 1; i++)\n out.push(shifts[axis] * (indices[i + 1] - indices[i]));\n out[n - 1] = shifts[axis] * (indices[0] - indices[n - 1]);\n return out;\n });\n var indices = [];\n var lastAxis = shape.length - 1;\n var tuple = new Array(shape.length).fill(0);\n var cursor = slices.map(function (l, i) { return l[tuple[i]] * shifts[i]; }).reduce(function (a, b) { return a + b; }, 0);\n while (true) {\n if (!isFinite(cursor))\n throw new Error(\"Programming error\");\n indices.push(cursor);\n var axis = lastAxis;\n while (axis >= 0) {\n cursor += iShifts[axis][tuple[axis]++];\n if (tuple[axis] < iShifts[axis].length)\n break;\n tuple[axis--] = 0; // Overflow\n }\n ;\n if (axis < 0)\n break;\n }\n return indices;\n}\n// =========================================\n// Slicing\n// =========================================\nfunction __parse_sliceRange(axis_size, _a) {\n var start = _a.start, stop = _a.stop, step = _a.step;\n if (start == null)\n start = 0;\n else if (start < 0)\n start = axis_size + start;\n if (stop == null)\n stop = axis_size;\n else if (stop < 0)\n stop = axis_size + stop;\n if (step == null)\n step = 1;\n else if (step == 0)\n throw new Error(\"Slice range with step size of zero\");\n if (!isFinite(start) || !isFinite(stop) || !isFinite(step))\n throw new Error(\"Invalid slice \".concat([start, stop, step], \". Axis size \").concat(axis_size));\n var indices = [];\n if (step > 0) {\n start = Math.max(start, 0);\n stop = Math.min(stop, axis_size);\n for (var i = start; i < stop; i += step)\n indices.push(i);\n }\n else {\n stop = Math.max(stop, 0);\n start = Math.min(start, axis_size);\n for (var i = start; i > stop; i += step)\n indices.push(i);\n }\n return indices;\n}\nexports.__parse_sliceRange = __parse_sliceRange;\nvar AxisIndex = /** @class */ (function () {\n /**\n * Invariant: Immutable\n * @param {AxisIndexSpec} spec\n */\n function AxisIndex(spec) {\n this.spec = spec;\n this._indices = null;\n this.isSimple = (this.spec.type != \"array\");\n this.isConstant = (this.spec.type == \"number\");\n }\n Object.defineProperty(AxisIndex.prototype, \"indices\", {\n get: function () {\n if (this._indices)\n return this._indices;\n var indices;\n if (this.spec.type == ':')\n indices = Array.from({ length: this.spec.size }, function (_, i) { return i; });\n else if (this.spec.type === \"number\")\n indices = [this.spec.index];\n else if (this.spec.type === \"array\")\n indices = this.spec.indices;\n else if (this.spec.type == \"range\") {\n var _a = this.spec.range, nSteps = _a.nSteps, step_1 = _a.step, start_1 = _a.start;\n indices = Array.from({ length: nSteps }, function (_, i) { return start_1 + i * step_1; });\n }\n else\n throw new Error(\"Unknown spec type \".concat(this.spec['type']));\n return this._indices = indices;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(AxisIndex.prototype, \"size\", {\n get: function () {\n if (this.spec.type == ':')\n return this.spec.size;\n else if (this.spec.type === \"number\")\n return 1;\n else if (this.spec.type === \"array\")\n return this.spec.indices.length;\n else if (this.spec.type == \"range\")\n return this.spec.range.nSteps;\n else\n throw new Error(\"Unknown spec type \".concat(this.spec['type']));\n },\n enumerable: false,\n configurable: true\n });\n return AxisIndex;\n}());\nexports.AxisIndex = AxisIndex;\nAxisIndex.prototype.parse_range = function (size, start, stop, step) {\n if (start === void 0) { start = null; }\n if (stop === void 0) { stop = null; }\n if (step === void 0) { step = null; }\n if (step == null)\n step = 1;\n else if (step == 0)\n throw new Error(\"Index specification error. Step must be different from zero.\");\n /**\n * @param {number|null} i @param {number} ifNull @param {number} min @param {number} max */\n var parse = function (i, ifNull, min, max) {\n if (i == null)\n return ifNull;\n if (i < 0)\n i = Math.max(0, size - i);\n return Math.min(max, Math.max(min, i));\n };\n var nSteps;\n if (step > 0)\n start = parse(start, 0, 0, size - 1), stop = parse(stop, size, 0, size);\n else\n start = parse(start, size - 1, 0, size - 1), stop = parse(stop, size - 1, -1, size - 1);\n stop = Math.max(stop, start);\n nSteps = Math.floor(Math.abs(stop - start) / step);\n return { start: start, step: step, nSteps: nSteps };\n};\n/**\n *\n * @param {string} rangeString\n * @returns {{start:(number|null), stop:(number|null), step:(number|null)}}\n */\nAxisIndex.prototype.parse_range_spec = function (rangeString) {\n var numbers = rangeString.split(':').map(function (s) {\n s = s.trim();\n if (s == \"\")\n return null;\n var n = parseInt(s);\n if (!Number.isInteger(n))\n throw new Error(\"Wrong input. Slice index unrecognized: \".concat(s));\n return n;\n });\n if (numbers.length == 0)\n throw new Error('Unexpected empty index. Expected colons.');\n if (numbers.length > 3)\n throw new Error(\"Too many colons in index \".concat(rangeString));\n var _a = __read(__spreadArray(__spreadArray([], __read(numbers), false), [null, null, null], false)), start = _a[0], stop = _a[1], step = _a[2], _ = _a.slice(3);\n return { start: start, stop: stop, step: step };\n};\n/**\n * We are reading `indexSpec` and `shape` in parallel, in the reading direction readDir.\n * With respect to `shape` we are at the given `axis`.\n * With respect to `indexSpec`, we found `indexSpec`, which we should process.\n * @param {indexSpec|undefined} indexSpec\n */\nAxisIndex.prototype.parse = function (indexSpec, size) {\n /**\n *\n * span (virtual shape) matches shape unless there are boolean masks spanning\n * over several axes/dimensions.\n * For example, in `np.ones((2,3,4,5))[:, np.arange(12).reshape((3,4))>5, 1]`,\n * the boolean mask is spanning over axes 1 and 2. In this case, the output should\n * merge these axes, resulting in an a vShape of (2, 12, 5).\n * The boolean mask is then converted to indices in the flattened merged axis.\n */\n /**@type {AxisIndexSpec} */\n var spec;\n var span = 1;\n if (indexSpec == ':' || indexSpec === undefined) {\n spec = { type: ':', size: size };\n }\n else if (typeof indexSpec === \"number\") {\n var index_3 = indexSpec;\n if (index_3 < 0)\n index_3 = size + index_3;\n if (index_3 < 0 || index_3 >= size)\n throw new Error(\"Index \".concat(index_3, \" out of bounds [0..\").concat(size, \")\"));\n spec = { type: 'number', index: index_3 };\n }\n else if ((0, basic_1.isarray)(indexSpec) || Array.isArray(indexSpec)) {\n var arr = (0, basic_1.asarray)(indexSpec);\n var indices_1;\n if (arr.dtype == Number) {\n // Array of indices\n if (arr.shape.length > 1)\n throw new Error(\"Expected 1D array of indices or nD array of booleans. \" +\n \"Found shape=\".concat(arr.shape, \" and dtype=\").concat(arr.dtype));\n indices_1 = arr.flat;\n }\n else {\n // Boolean mask\n indices_1 = [];\n arr.flat.forEach(function (if_value, i) { return if_value && indices_1.push(i); });\n // Next lines: the boolean mask spans over more than 1 axis\n span = Math.max(1, arr.shape.length);\n // Multiply the (possibly inverted) interval\n }\n spec = { type: 'array', indices: indices_1 };\n }\n else if (typeof indexSpec == \"string\") {\n var _a = AxisIndex.prototype.parse_range_spec(indexSpec), start = _a.start, stop_1 = _a.stop, step = _a.step;\n var range = AxisIndex.prototype.parse_range(size, start, stop_1, step);\n if (range.start == 0 && range.nSteps == size && range.step == 1) {\n // Small optimization: all of these are just \":\": [\"::\",\"0::1\", \":axisSize:\", etc.]\n spec = { type: ':', size: size };\n }\n else {\n spec = { type: 'range', range: range };\n }\n }\n else\n throw new Error(\"Unknown index type. Found \".concat(typeof indexSpec, \": \").concat(indexSpec));\n var axisIndex = new AxisIndex(spec);\n return { axisIndex: axisIndex, span: span };\n};\n/**\n * @param {Where} where\n * @returns {AxesIndex}\n */\nAxesIndex.prototype.parse = function (shape, where) {\n /**@type {Array}*/\n var _where = where == null ? [] : __spreadArray([], __read(where), false);\n var buffers = {\n axisIndexes: /**@type {AxisIndex[]}*/ ([]),\n apparentShape: /**@type {number[]}*/ ([]),\n internalShape: /**@type {number[]}*/ ([]),\n };\n var readDir = 1;\n var reversedAfter = { axisIndexes: NaN, apparentShape: NaN, internalShape: NaN };\n var axis = 0, j = 0, remainingAxes = shape.length, remainingWhere = _where.length;\n while (remainingWhere > 0 || remainingAxes > 0) {\n var axisWhere = _where[j];\n if (remainingWhere > 0) {\n if (j < 0 || j >= _where.length)\n axisWhere = \":\";\n remainingWhere--;\n //else _where[j] = undefined; // For ellipsis to avoid reading twice in opposite reading directions\n j += readDir;\n if (axisWhere == \"None\" || axisWhere === null) {\n buffers.apparentShape.push(1);\n continue;\n }\n else if (axisWhere == \"...\") {\n if (readDir == -1)\n throw new Error(\"Index can only have a single ellipsis. Found index(\".concat(where, \")\"));\n readDir = -1;\n for (var key in reversedAfter)\n reversedAfter[key] = buffers[key].length;\n j = _where.length - 1;\n axis = shape.length - 1;\n continue;\n }\n }\n else {\n axisWhere = \":\"; // If there are no more axes, fill with \":\"\n }\n // if (remainingAxes <= 0) throw Error(`Too many axes`);\n var _a = AxisIndex.prototype.parse(axisWhere, shape[axis]), axisIndex = _a.axisIndex, span = _a.span;\n // Advance the axis cursor span axes in readDir and compute the total size of consumed axes\n remainingAxes -= span;\n var refSize = 1;\n for (var i = 0; i < span; i++) {\n if (axis < 0 || axis >= shape.length)\n throw new Error(\"Index spans over more dimensions than available in shape [\".concat(shape, \"]: index(\").concat(where, \")\"));\n refSize *= shape[axis];\n axis += readDir;\n }\n buffers.axisIndexes.push(axisIndex);\n if (axisIndex.spec.type != \"number\")\n buffers.apparentShape.push(axisIndex.size);\n buffers.internalShape.push(refSize);\n }\n if (readDir == -1) { // reverse the right to left elements\n for (var key in buffers)\n buffers[key].splice(0, reversedAfter[key]).concat(buffers[key].reverse());\n }\n var axesIndex = new AxesIndex(buffers.apparentShape, buffers.internalShape, buffers.axisIndexes);\n return axesIndex;\n};\n","\"use strict\";\n//@ts-check\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.tolist = exports.fromlist = void 0;\nvar basic_1 = require(\"./basic\");\nfunction fromlist(arr, dtype) {\n if (dtype === void 0) { dtype = null; }\n if ((0, basic_1.isarray)(arr))\n return arr;\n if (typeof arr === \"number\")\n return (0, basic_1.new_NDArray)([arr], [], Number);\n if (typeof arr === \"boolean\")\n return (0, basic_1.new_NDArray)([arr ? 1 : 0], [], Boolean);\n if (arr === basic_1._NDArray.prototype)\n throw new Error(\"Programming error\");\n if (!Array.isArray(arr))\n throw new Error(\"Can't parse input of type \".concat(typeof arr, \": \").concat(arr));\n var shape = [];\n var root = arr;\n while (Array.isArray(root)) {\n shape.push(root.length);\n root = root[0];\n if (shape.length > 256)\n throw new Error(\"Circular reference or excessive array depth\");\n }\n dtype = dtype !== null ? dtype : typeof root === \"boolean\" ? Boolean : Number;\n var flat = [];\n var pushToFlat = function (arr, axis) {\n var e_1, _a, e_2, _b;\n // Check consistency\n if (axis == shape.length - 1) {\n try {\n for (var arr_1 = __values(arr), arr_1_1 = arr_1.next(); !arr_1_1.done; arr_1_1 = arr_1.next()) {\n var elem = arr_1_1.value;\n if (Array.isArray(elem))\n throw new Error(\"Inconsistent shape\");\n flat.push(elem);\n // Update dtype\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (arr_1_1 && !arr_1_1.done && (_a = arr_1.return)) _a.call(arr_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n else {\n if (!Array.isArray(arr))\n throw new Error(\"Inconsistent shape\");\n try {\n for (var arr_2 = __values(arr), arr_2_1 = arr_2.next(); !arr_2_1.done; arr_2_1 = arr_2.next()) {\n var sub = arr_2_1.value;\n if (sub.length != shape[axis + 1])\n throw new Error(\"Inconsistent shape: found sibling arrays of lengths \".concat(sub.length, \" and \").concat(shape[axis + 1]));\n pushToFlat(sub, axis + 1);\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (arr_2_1 && !arr_2_1.done && (_b = arr_2.return)) _b.call(arr_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n };\n pushToFlat(arr, 0);\n return (0, basic_1.new_NDArray)(flat, shape, dtype);\n}\nexports.fromlist = fromlist;\nfunction tolist(arr) {\n if ((0, basic_1.isarray)(this))\n return tolist;\n if (arr === null || typeof arr == \"number\" || typeof arr == \"boolean\")\n return arr;\n if (Array.isArray(arr))\n return arr.map(tolist);\n if (!((0, basic_1.isarray)(arr)))\n throw new Error(\"Expected MyArray. Got \".concat(typeof arr, \": \").concat(arr));\n arr = (0, basic_1.number_collapse)(arr);\n if (!((0, basic_1.isarray)(arr)))\n return arr;\n // let out = [], top;\n // let q = /**@type {[MyArray, any][]}*/([[arr, out]])\n // while (top = q.pop()) {\n // let [arr, out] = top;\n // if (arr.shape.length <= 1) {\n // out.push(...arr.flat);\n // } else {\n // for (let i = 0; i < arr.shape[0]; i++) {\n // let l = []\n // out.push(l);\n // q.push([arr.index(i), l]);\n // }\n // }\n // }\n // return out;\n function recursiveReshape(flatArr, shapeArr) {\n if (shapeArr.length === 0) {\n return flatArr.shift();\n }\n var innerShape = shapeArr.slice(1);\n var outerSize = shapeArr[0];\n var innerArray = [];\n for (var i = 0; i < outerSize; i++) {\n innerArray.push(recursiveReshape(flatArr, innerShape));\n }\n return innerArray;\n }\n var out = recursiveReshape(__spreadArray([], __read(arr.flat), false), arr.shape);\n return out;\n}\nexports.tolist = tolist;\n","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.allclose = exports.isclose = exports.op_assign = exports.__make_assignment_operator = exports._assign_operation_toJS = exports.assign_operation = exports.op_unary = exports.op_binary = exports.__make_operator_special = exports.__make_operator = exports._broadcast_shapes = exports.binary_operation = void 0;\n//@ts-check\nvar indexes = require(\"./indexes\");\nvar elementwise = require(\"./elementwise\");\nvar basic_1 = require(\"./basic\");\nvar js_interface_1 = require(\"./js-interface\");\nfunction binary_operation(A, B, func, dtype, out) {\n if (out === void 0) { out = null; }\n if ((0, basic_1.isarray)(this))\n return func.bind(basic_1._NDArray.prototype).apply(void 0, __spreadArray([this], __read(arguments), false));\n // Find output shape and input broadcast shapes\n A = (0, basic_1.asarray)(A);\n B = (0, basic_1.asarray)(B);\n var _a = __read(_broadcast_shapes(A.shape, B.shape), 3), shape = _a[0], shapeA = _a[1], shapeB = _a[2];\n if (out == null)\n out = (0, basic_1.new_from)(shape, function (_) { return undefined; }, dtype);\n else if (!((0, basic_1.isarray)(out)))\n throw new Error(\"Out must be of type \".concat(basic_1._NDArray, \". Got \").concat(typeof out));\n // Iterate with broadcasted indices\n var flatOut = [];\n var shiftsA = (0, basic_1.shape_shifts)(shapeA);\n var shiftsB = (0, basic_1.shape_shifts)(shapeB);\n var flatA = A.flat;\n var flatB = B.flat;\n for (var i = 0; i < out.size; i++) {\n var idxA = 0, idxB = 0, idx = i;\n for (var axis = shape.length - 1; axis >= 0; axis--) {\n idxA += shiftsA[axis] * (idx % shapeA[axis]);\n idxB += shiftsB[axis] * (idx % shapeB[axis]);\n idx = Math.floor(idx / shape[axis]);\n }\n flatOut.push(func(flatA[idxA], flatB[idxB]));\n }\n ;\n out.flat = flatOut;\n return (0, basic_1.number_collapse)(out);\n}\nexports.binary_operation = binary_operation;\nfunction _broadcast_shapes(shapeA, shapeB) {\n var shape = [];\n var maxDim = Math.max(shapeA.length, shapeB.length);\n shapeA = __spreadArray(__spreadArray([], __read(Array.from({ length: maxDim - shapeA.length }, function () { return 1; })), false), __read(shapeA), false);\n shapeB = __spreadArray(__spreadArray([], __read(Array.from({ length: maxDim - shapeB.length }, function () { return 1; })), false), __read(shapeB), false);\n for (var axis = maxDim - 1; axis >= 0; axis--) {\n var dim1 = shapeA[axis];\n var dim2 = shapeB[axis];\n if (dim1 !== 1 && dim2 !== 1 && dim1 !== dim2)\n throw new Error(\"Can not broadcast axis \".concat(axis, \" with sizes \").concat(dim1, \" and \").concat(dim2));\n shape.unshift(Math.max(dim1, dim2));\n }\n return [shape, shapeA, shapeB];\n}\nexports._broadcast_shapes = _broadcast_shapes;\nfunction __make_operator(dtype, func) {\n function operator(A, B, out) {\n if (out === void 0) { out = null; }\n if ((0, basic_1.isarray)(this))\n return operator.bind(basic_1._NDArray.prototype).apply(void 0, __spreadArray([this], __read(arguments), false));\n return binary_operation(A, B, func, dtype, out);\n }\n ;\n return operator;\n}\nexports.__make_operator = __make_operator;\nfunction __make_operator_special(funcNum, funcBool) {\n function operator(A, B, out) {\n if (out === void 0) { out = null; }\n if ((0, basic_1.isarray)(this))\n return operator.bind(basic_1._NDArray.prototype).apply(void 0, __spreadArray([this], __read(arguments), false));\n A = (0, basic_1.asarray)(A);\n B = (0, basic_1.asarray)(B);\n var dtype = A.dtype, func;\n if (A.dtype != B.dtype)\n console.warn(\"Warning: operating arrays of different dtypes. Using \".concat(dtype));\n if (dtype == Boolean)\n func = funcBool;\n else\n func = funcNum;\n return binary_operation(A, B, func, dtype, out);\n }\n ;\n return operator;\n}\nexports.__make_operator_special = __make_operator_special;\nexports.op_binary = {\n \"+\": __make_operator(Number, function (a, b) { return a + b; }),\n \"-\": __make_operator(Number, function (a, b) { return a - b; }),\n \"*\": __make_operator(Number, function (a, b) { return a * b; }),\n \"/\": __make_operator(Number, function (a, b) { return a / b; }),\n \"%\": __make_operator(Number, function (a, b) { return (a % b); }),\n \"//\": __make_operator(Number, function (a, b) { return Math.floor(a / b); }),\n \"**\": __make_operator(Number, function (a, b) { return Math.pow(a, b); }),\n \"<\": __make_operator(Boolean, function (a, b) { return a < b; }),\n \">\": __make_operator(Boolean, function (a, b) { return a > b; }),\n \">=\": __make_operator(Boolean, function (a, b) { return a >= b; }),\n \"<=\": __make_operator(Boolean, function (a, b) { return a <= b; }),\n \"==\": __make_operator(Boolean, function (a, b) { return a == b; }),\n \"!=\": __make_operator(Boolean, function (a, b) { return a != b; }),\n \"|\": __make_operator_special(function (a, b) { return a | b; }, function (a, b) { return a || b; }),\n \"&\": __make_operator_special(function (a, b) { return a & b; }, function (a, b) { return a && b; }),\n \"^\": __make_operator(Number, function (a, b) { return a ^ b; }),\n \"<<\": __make_operator(Number, function (a, b) { return a << b; }),\n \">>\": __make_operator(Number, function (a, b) { return a >> b; }),\n // Operators with custom ascii identifiers:\n \"or\": __make_operator(Boolean, function (a, b) { return a || b; }),\n \"and\": __make_operator(Boolean, function (a, b) { return a && b; }),\n \"xor\": __make_operator(Boolean, function (a, b) { return (!a) != (!b); }),\n \"max\": __make_operator(Number, function (a, b) { return Math.max(a, b); }),\n \"min\": __make_operator(Number, function (a, b) { return Math.min(a, b); }),\n // \"isclose\": ,\n};\nexports.op_binary[\"↑\"] = exports.op_binary[\"max\"];\nexports.op_binary[\"↓\"] = exports.op_binary[\"min\"];\nexports.op_binary[\"≤\"] = exports.op_binary[\"leq\"];\nexports.op_binary[\"≥\"] = exports.op_binary[\"geq\"];\nexports.op_binary[\"≠\"] = exports.op_binary[\"neq\"];\nexports.op_unary = {\n // Unary operators:\n \"~\": elementwise.bitwise_not,\n \"not\": elementwise.logical_not,\n \"+\": elementwise.__make_elementwise(function (x) { return x; }),\n \"-\": elementwise.__make_elementwise(function (x) { return -x; }, Number),\n};\nfunction assign_operation(tgt, src, where, func, dtype) {\n var e_1, _a;\n if (tgt['__warnAssignment']) {\n console.warn(\"Warning: You are assigning on a copy that resulted from an advanced index on a source array.\\nIf this is intentional, use yourArray = source.withKwArgs({copy:true}).index(...yourIndex) to make explicit your awareness of the copy operation.\\nInstead, if you want to assign to the source array, use source.op('=', other) or source.op(['::3', -1, '...', [5,4]], '*=', other).\\n\");\n delete tgt['__warnAssignment'];\n }\n if (!((0, basic_1.isarray)(tgt)))\n return _assign_operation_toJS(/**@type {*}*/ (tgt), src, where, func, dtype);\n if (!where) {\n binary_operation(tgt, src, func, dtype, tgt);\n }\n else {\n src = (0, basic_1.asarray)(src);\n var indices = indexes.AxesIndex.prototype.parse(tgt.shape, where).indices;\n var tmpTgt = void 0;\n if (func == null) {\n // Small optimization: unlike \"+=\", \"*=\", etc., for \"=\", we don't need to reed the target\n func = function (a, b) { return b; };\n tmpTgt = (0, basic_1.new_from)(indices.length, function () { return undefined; }, tgt.dtype);\n }\n else {\n tmpTgt = (0, basic_1.asarray)(indices.map(function (i) { return tgt._flat[i]; }));\n }\n binary_operation(tmpTgt, (0, basic_1.ravel)(src), func, dtype, tmpTgt);\n try {\n for (var indices_1 = __values(indices), indices_1_1 = indices_1.next(); !indices_1_1.done; indices_1_1 = indices_1.next()) {\n var i = indices_1_1.value;\n tgt._flat[i] = tmpTgt._flat[i];\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (indices_1_1 && !indices_1_1.done && (_a = indices_1.return)) _a.call(indices_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n}\nexports.assign_operation = assign_operation;\n;\nfunction _assign_operation_toJS(tgtJS, src, where, func, dtype) {\n if (!Array.isArray(tgtJS))\n throw new Error(\"Can not assign to a non-array. Found \".concat(typeof tgtJS, \": \").concat(tgtJS));\n console.warn('Assignment to JS array is experimental and slow.');\n // Parse the whole array\n var cpy = (0, basic_1.asarray)(tgtJS);\n assign_operation(cpy, src, where, func, dtype);\n // WARNING: Creates a copy. This is terrible for arr[2, 4, 3] = 5\n var outJS = (0, js_interface_1.tolist)(cpy);\n while (tgtJS.length)\n tgtJS.pop();\n // @ts-ignore\n tgtJS.push.apply(tgtJS, __spreadArray([], __read(outJS), false));\n}\nexports._assign_operation_toJS = _assign_operation_toJS;\nfunction __make_assignment_operator(dtype, func) {\n function operator() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n if ((0, basic_1.isarray)(this))\n return operator.bind(basic_1._NDArray.prototype).apply(void 0, __spreadArray([this], __read(args), false));\n if (args.length < 2)\n throw new Error(\"Not enough arguments for assignment operator\");\n if (args.length > 3)\n throw new Error(\"Too many arguments for assignment operator\");\n var tgt = args[0];\n var src = args[args.length == 3 ? 2 : 1];\n var where = args.length == 3 ? args[1] : null;\n return assign_operation(tgt, src, where, func, dtype);\n }\n return operator;\n}\nexports.__make_assignment_operator = __make_assignment_operator;\nexports.op_assign = {\n \"=\": __make_assignment_operator(Number, function (a, b) { return b; }),\n \"+=\": __make_assignment_operator(Number, function (a, b) { return a + b; }),\n \"-=\": __make_assignment_operator(Number, function (a, b) { return a - b; }),\n \"*=\": __make_assignment_operator(Number, function (a, b) { return a * b; }),\n \"/=\": __make_assignment_operator(Number, function (a, b) { return a / b; }),\n \"%=\": __make_assignment_operator(Number, function (a, b) { return (a % b); }),\n \"//=\": __make_assignment_operator(Number, function (a, b) { return Math.floor(a / b); }),\n \"**=\": __make_assignment_operator(Number, function (a, b) { return Math.pow(a, b); }),\n \"|=\": __make_assignment_operator(Number, function (a, b) { return a | b; }),\n \"&=\": __make_assignment_operator(Number, function (a, b) { return a & b; }),\n \"^=\": __make_assignment_operator(Number, function (a, b) { return a ^ b; }),\n \"<<=\": __make_assignment_operator(Number, function (a, b) { return a << b; }),\n \">>=\": __make_assignment_operator(Number, function (a, b) { return a >> b; }),\n // Operators with custom ascii identifiers:\n \"max=\": __make_assignment_operator(Number, function (a, b) { return Math.max(a, b); }),\n \"min=\": __make_assignment_operator(Number, function (a, b) { return Math.min(a, b); }),\n \"or=\": __make_assignment_operator(Boolean, function (a, b) { return a || b; }),\n \"and=\": __make_assignment_operator(Boolean, function (a, b) { return a && b; }),\n};\nexports.op_assign[\"↑=\"] = exports.op_assign[\"max=\"];\nexports.op_assign[\"↓=\"] = exports.op_assign[\"min=\"];\n// ====================================\nfunction isclose(A, B, rtol, atol, equal_nan) {\n var _a;\n if (rtol === void 0) { rtol = 1.e-5; }\n if (atol === void 0) { atol = 1.e-8; }\n if (equal_nan === void 0) { equal_nan = false; }\n (_a = Object.assign({ rtol: rtol, atol: atol, equal_nan: equal_nan }, this), rtol = _a.rtol, atol = _a.atol, equal_nan = _a.equal_nan);\n var func = function (a, b) {\n if (Number.isFinite(a) && Number.isFinite(b))\n return Math.abs(a - b) <= atol + rtol * b;\n return (a == b) || (equal_nan && Number.isNaN(a) && Number.isNaN(b));\n };\n return binary_operation(A, B, func, Boolean);\n}\nexports.isclose = isclose;\nfunction allclose(A, B, rtol, atol, equal_nan) {\n var _a;\n if (rtol === void 0) { rtol = 1.e-5; }\n if (atol === void 0) { atol = 1.e-8; }\n if (equal_nan === void 0) { equal_nan = false; }\n (_a = Object.assign({ rtol: rtol, atol: atol, equal_nan: equal_nan }, this), rtol = _a.rtol, atol = _a.atol, equal_nan = _a.equal_nan);\n // Equivalent to all(isclose(A, B, rtol, atol, equal_nan)), but shortcutting if false \n var func = function (a, b) {\n if (Number.isFinite(a) && Number.isFinite(b))\n return Math.abs(a - b) <= atol + rtol * b;\n return (a == b) || (equal_nan && Number.isNaN(a) && Number.isNaN(b));\n };\n var different = new Error('');\n var wrapper = function (a, b) {\n if (!func(a, b))\n throw different;\n return 0;\n };\n try {\n binary_operation(A, B, wrapper, Number);\n }\n catch (err) {\n if (err === different)\n return false;\n else\n throw err;\n }\n return true;\n}\nexports.allclose = allclose;\n//op_binary[\"≈≈\"] = op[MyArray.prototype.isclose,\n","\"use strict\";\n//@ts-check\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.humanReadable = void 0;\nvar elementwise_1 = require(\"./elementwise\");\nvar js_interface_1 = require(\"./js-interface\");\nfunction humanReadable(arr) {\n if (arr.shape.length == 0)\n return arr.flat[0].toString();\n var budgets = arr.shape.map(function (_) { return 1; });\n var lBudget = 30;\n for (var i = 0; i < arr.shape.length; i++) {\n var before = budgets[i];\n budgets[i] = Math.min(arr.shape[i], lBudget);\n if (budgets[i] > before)\n lBudget = Math.floor(lBudget / (budgets[i] - before));\n }\n var rBudget = 30;\n for (var i = arr.shape.length - 1; i >= 0; i--) {\n var before = budgets[i];\n budgets[i] = Math.min(arr.shape[i], rBudget);\n if (budgets[i] > before)\n rBudget = Math.floor(rBudget / (budgets[i] - before));\n }\n function simplify(list, depth) {\n if (depth === void 0) { depth = 0; }\n if (depth == arr.shape.length)\n return list;\n if (2 * budgets[depth] >= list.length) {\n return list.map(function (l) { return simplify(l, depth + 1); });\n }\n var left = list.slice(0, budgets[depth]).map(function (l) { return simplify(l, depth + 1); });\n var right = list.slice(-budgets[depth]).map(function (l) { return simplify(l, depth + 1); });\n return __spreadArray(__spreadArray(__spreadArray([], __read(left), false), ['...'], false), __read(right), false);\n }\n var rLimit = arr.shape.length - 1;\n while (rLimit > 0 && arr.shape[rLimit] == 1) {\n rLimit--;\n }\n if (arr.dtype == Number)\n arr = (0, elementwise_1.round)(arr, 2);\n var list = (0, js_interface_1.tolist)(arr);\n function str(list, indent, depth) {\n if (indent === void 0) { indent = 0; }\n if (depth === void 0) { depth = 0; }\n if (list == '...' || depth >= arr.shape.length)\n return list;\n if (depth == arr.shape.length - 1)\n return \"[\".concat(list.join(', '), \"]\");\n var sep = depth >= rLimit ? ' ' : '\\n' + ' '.repeat(indent + 1);\n var out = [];\n for (var i = 0; i < list.length; i++) {\n var s = str(list[i], indent + 1, depth + 1) + ',';\n out.push(i < list.length - 1 ? s : s.slice(0, -1));\n }\n return \"[\".concat(out.join(sep), \"]\");\n }\n var prefix = 'np';\n var suffix = \", shape=(\".concat(arr.shape, \"), dtype=\").concat(arr.dtype.name);\n var out = str(simplify(list), 1 + prefix.length);\n function alignColumns(inputString, delimiter) {\n var e_1, _a, e_2, _b;\n if (delimiter === void 0) { delimiter = ','; }\n // Split the input string into rows\n var rows = inputString.split('\\n');\n // Initialize an array to store the maximum width of each column\n var columnWidths = Array(rows[0].split(delimiter).length).fill(0);\n try {\n // Find the maximum width for each column\n for (var rows_1 = __values(rows), rows_1_1 = rows_1.next(); !rows_1_1.done; rows_1_1 = rows_1.next()) {\n var row = rows_1_1.value;\n var columns = row.split(delimiter);\n for (var i = 0; i < columns.length; i++) {\n columnWidths[i] = Math.max(columnWidths[i], columns[i].trim().length);\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (rows_1_1 && !rows_1_1.done && (_a = rows_1.return)) _a.call(rows_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // Build the formatted outputs\n var formattedString = '';\n var _loop_1 = function (row) {\n var columns = row.split(delimiter);\n columns = columns.map(function (s, i) { return i == columns.length - 1 ? s : s + delimiter; });\n for (var i = 0; i < columns.length; i++) {\n var column = columns[i].trim();\n formattedString += column.padStart(columnWidths[i] + 1).padEnd(columnWidths[i] + 2); // Add 1 for padding\n }\n formattedString += '\\n';\n };\n try {\n for (var rows_2 = __values(rows), rows_2_1 = rows_2.next(); !rows_2_1.done; rows_2_1 = rows_2.next()) {\n var row = rows_2_1.value;\n _loop_1(row);\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (rows_2_1 && !rows_2_1.done && (_b = rows_2.return)) _b.call(rows_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n return formattedString;\n }\n out = out.replace(/.*?(\\n|$)/g, function (match) {\n // Split with a newline every 0 characters, but only after a comma,\n return match.replace(/(.{60,}?,)/g, '$1\\n');\n }).replace(/\\n+/g, '\\n');\n out = alignColumns(\"\".concat(prefix, \"(\").concat(out)).trim();\n out = \"\".concat(out).concat(suffix, \")\");\n return out;\n}\nexports.humanReadable = humanReadable;\n","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.reducersExtra = exports.reducers = exports.reducersBool = exports.reduce = void 0;\n//@ts-check\nvar basic_1 = require(\"./basic\");\nvar operators_1 = require(\"./operators\");\n// ==============================\n// Reducing functions\n// ==============================\nfunction reduce(arr, axis, keepdims, reducer, dtype) {\n if (dtype === void 0) { dtype = Number; }\n keepdims = (0, basic_1.as_boolean)(keepdims);\n // console.log({ arr })\n arr = (0, basic_1.asarray)(arr);\n if (axis == null)\n return reducer(arr.flat);\n if (axis < 0)\n axis = arr.shape.length - 1;\n var m = arr.shape[axis];\n var shift = (0, basic_1.shape_shifts)(arr.shape)[axis];\n var groups = Array.from({ length: m }, function (_) { /**@type {number[]}*/ return ([]); });\n arr.flat.forEach(function (value, i) { return groups[(Math.floor(i / shift)) % m].push(value); });\n // Transpose it:\n var nCols = arr.size / m;\n var groupsT = [];\n for (var j = 0; j < nCols; j++) {\n var newRow = [];\n for (var i = 0; i < m; i++)\n newRow.push(groups[i][j]);\n groupsT.push(newRow);\n }\n var flat = groupsT.map(reducer);\n var shape = __spreadArray([], __read(arr.shape), false);\n if (keepdims)\n shape[axis] = 1;\n else\n shape = shape.filter(function (_, i) { return i != axis; });\n var out = (0, basic_1.new_NDArray)(flat, shape, dtype);\n return (0, basic_1.number_collapse)(out);\n}\nexports.reduce = reduce;\n;\nfunction __make_reducer(dtype, reducer) {\n return function (arr, axis, keepdims) {\n var _a, _b, _c;\n if (axis === void 0) { axis = null; }\n if (keepdims === void 0) { keepdims = false; }\n // Parse kwargs from right to left to overwrite (right has priority)\n if (keepdims instanceof Object)\n (_a = Object.assign({ axis: axis, keepdims: keepdims }, keepdims), axis = _a.axis, keepdims = _a.keepdims);\n if (axis instanceof Object)\n (_b = Object.assign({ axis: axis, keepdims: keepdims }, axis), axis = _b.axis, keepdims = _b.keepdims);\n (_c = Object.assign({ axis: axis, keepdims: keepdims }, this), axis = _c.axis, keepdims = _c.keepdims);\n return reduce(arr, axis, keepdims, reducer, dtype);\n };\n}\nexports.reducersBool = {\n any: __make_reducer(Boolean, function (arr) {\n var e_1, _a;\n try {\n for (var arr_1 = __values(arr), arr_1_1 = arr_1.next(); !arr_1_1.done; arr_1_1 = arr_1.next()) {\n var x = arr_1_1.value;\n if (x)\n return true;\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (arr_1_1 && !arr_1_1.done && (_a = arr_1.return)) _a.call(arr_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return false;\n }),\n all: __make_reducer(Boolean, function (arr) {\n var e_2, _a;\n try {\n for (var arr_2 = __values(arr), arr_2_1 = arr_2.next(); !arr_2_1.done; arr_2_1 = arr_2.next()) {\n var x = arr_2_1.value;\n if (!x)\n return false;\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (arr_2_1 && !arr_2_1.done && (_a = arr_2.return)) _a.call(arr_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n return true;\n }),\n};\nexports.reducers = {\n sum: __make_reducer(Number, function (arr) { return arr.reduce(function (a, b) { return a + b; }, 0); }),\n product: __make_reducer(Number, function (arr) { return arr.reduce(function (a, b) { return a * b; }, 1); }),\n mean: __make_reducer(Number, function (arr) { return arr.reduce(function (a, b) { return a + b; }, 0) / arr.length; }),\n max: __make_reducer(Number, function (arr) { return Math.max.apply(Math, __spreadArray([], __read(arr), false)); }),\n min: __make_reducer(Number, function (arr) { return Math.min.apply(Math, __spreadArray([], __read(arr), false)); }),\n argmax: __make_reducer(Number, function (arr) { return arr.indexOf(Math.max.apply(Math, __spreadArray([], __read(arr), false))); }),\n argmin: __make_reducer(Number, function (arr) { return arr.indexOf(Math.min.apply(Math, __spreadArray([], __read(arr), false))); }),\n len: __make_reducer(Number, function (arr) { return arr.length; }),\n};\nexports.reducersExtra = {\n norm: function (arr, axis, keepdims, ord) {\n var _a;\n if (axis === void 0) { axis = null; }\n if (keepdims === void 0) { keepdims = false; }\n if (ord === void 0) { ord = 2; }\n (_a = Object.assign({ axis: axis, keepdims: keepdims, ord: ord }, this), axis = _a.axis, keepdims = _a.keepdims, ord = _a.ord);\n if (ord % 2 != 0)\n arr = arr.abs();\n if (ord == Infinity)\n return exports.reducers.max(arr, axis, keepdims);\n if (ord == 1)\n return exports.reducers.sum(arr, axis, keepdims);\n var pow = operators_1.op_binary[\"**\"];\n return pow(pow(arr, ord).sum(axis, keepdims), 1 / ord);\n },\n var: function (arr, axis, keepdims) {\n var _a;\n if (axis === void 0) { axis = null; }\n if (keepdims === void 0) { keepdims = false; }\n (_a = Object.assign({ axis: axis, keepdims: keepdims }, this), axis = _a.axis, keepdims = _a.keepdims);\n var arrMean = exports.reducers.mean.bind({ axis: axis, keepdims: true })(arr);\n arr = operators_1.op_binary[\"-\"](arr, arrMean);\n arr = operators_1.op_binary[\"*\"](arr, arr);\n return exports.reducers.mean.bind({ axis: axis, keepdims: keepdims })(arr);\n },\n std: function (arr, axis, keepdims, ddof) {\n var _a;\n if (axis === void 0) { axis = null; }\n if (keepdims === void 0) { keepdims = false; }\n if (ddof === void 0) { ddof = 0; }\n (_a = Object.assign({ axis: axis, keepdims: keepdims }, this), axis = _a.axis, keepdims = _a.keepdims);\n if (ddof == 0) {\n var variance = exports.reducersExtra.var.bind({ axis: axis, keepdims: keepdims })(arr);\n return operators_1.op_binary[\"**\"](variance, 0.5);\n }\n var _sum = exports.reducers.sum.bind({ axis: axis, keepdims: keepdims })(operators_1.op_binary[\"**\"](arr, 2));\n var _len = exports.reducers.len.bind({ axis: axis, keepdims: keepdims })(arr);\n return operators_1.op_binary[\"**\"](operators_1.op_binary[\"/\"](_sum, operators_1.op_binary[\"-\"](_len, ddof)), 0.5);\n },\n};\n","\"use strict\";\n//@ts-check\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.stack = exports.concatenate = exports.swapAxes = exports.transpose = exports.sort = exports.apply_along_axis = void 0;\nvar basic_1 = require(\"./basic\");\nvar js_interface_1 = require(\"./js-interface\");\nvar utils_js_1 = require(\"../utils-js\");\nfunction apply_along_axis(arr, axis, transform, dtype) {\n if (dtype === void 0) { dtype = Number; }\n arr = (0, basic_1.asarray)(arr);\n if (axis == null)\n return transform(arr.flat);\n var nDims = arr.shape.length;\n if (axis < 0)\n axis = nDims + axis;\n if (axis !== nDims - 1) {\n // Transpose to end, apply, and transpose back:\n var tmp_1 = swapAxes(arr, axis, -1);\n var out_1 = apply_along_axis(tmp_1, -1, transform, dtype);\n //@ts-ignore\n return swapAxes(out_1, axis, -1);\n }\n var m = arr.shape[axis];\n var shift = (0, basic_1.shape_shifts)(arr.shape)[axis];\n var groups = Array.from({ length: m }, function (_) { /**@type {number[]}*/ return ([]); });\n arr.flat.forEach(function (value, i) { return groups[(Math.floor(i / shift)) % m].push(value); });\n // Transpose it:\n var nCols = arr.size / m;\n var groupsT = [];\n for (var j = 0; j < nCols; j++) {\n var newRow = [];\n for (var i = 0; i < m; i++)\n newRow.push(groups[i][j]);\n groupsT.push(newRow);\n }\n var data = groupsT.map(transform);\n var tmp = (0, js_interface_1.fromlist)(data);\n var shape = __spreadArray(__spreadArray(__spreadArray([], __read(arr.shape.slice(0, axis)), false), __read(tmp.shape.slice(1)), false), __read(arr.shape.slice(axis + 1)), false);\n var out = (0, basic_1.new_NDArray)(tmp.flat, shape, dtype);\n return (0, basic_1.number_collapse)(out);\n}\nexports.apply_along_axis = apply_along_axis;\nfunction sort(A, axis) {\n if (axis === void 0) { axis = -1; }\n (axis = Object.assign({ axis: axis }, this).axis);\n return apply_along_axis(A, axis, function (arr) {\n var cpy = __spreadArray([], __read(arr), false);\n cpy.sort(function (a, b) { return a - b; });\n return cpy;\n }, A.dtype);\n}\nexports.sort = sort;\nfunction transpose(arr, axes) {\n if (axes === void 0) { axes = null; }\n (axes = Object.assign({ axes: axes }, this).axes);\n var nDims = arr.shape.length;\n if (axes == null)\n return transpose(arr, Array.from({ length: nDims }, function (_, i) { return i; }).reverse());\n if (axes.length !== nDims)\n throw new Error(\"Axes must have length \".concat(nDims, \". Found \").concat(axes.length));\n var inv = Array.from({ length: nDims }, function () { return -1; });\n for (var i = 0; i < nDims; i++) {\n if (axes[i] < 0 || axes[i] >= nDims)\n throw new Error(\"Expected axis in [0..\".concat(nDims, \"). Found \").concat(axes[i]));\n inv[axes[i]] = i;\n }\n for (var i = 0; i < nDims; i++)\n if (inv[i] == -1)\n throw new Error(\"Axes must contain all dimensions. [\".concat(axes.join(\", \"), \"] is missing \").concat(i, \".\"));\n var srcShifts = (0, basic_1.shape_shifts)(arr.shape);\n var shape = axes.map(function (j) { return arr.shape[j]; });\n var shifts = axes.map(function (j) { return srcShifts[j]; });\n // Copied from slice:\n var indices = [];\n var tuple = new Array(shape.length).fill(0);\n var cursor = 0;\n while (true) {\n if (!isFinite(cursor))\n throw new Error(\"Programming error\");\n indices.push(cursor);\n var axis = nDims - 1;\n while (axis >= 0) {\n tuple[axis]++;\n cursor += shifts[axis];\n if (tuple[axis] < shape[axis])\n break;\n // Overflow\n cursor -= shifts[axis] * shape[axis];\n tuple[axis] = 0;\n axis--;\n }\n ;\n if (axis < 0)\n break;\n }\n // Now, just copy the data:\n var src = arr.flat;\n return (0, basic_1.new_NDArray)(indices.map(function (i) { return src[i]; }), shape, arr.dtype);\n}\nexports.transpose = transpose;\nfunction swapAxes(arr, axisA, axisB) {\n arr = (0, basic_1.asarray)(arr);\n var nDims = arr.shape.length;\n if (axisA < 0)\n axisA = nDims + axisA;\n if (axisB < 0)\n axisB = nDims + axisB;\n var perm = Array.from({ length: nDims }, function (_, i) { return i; });\n perm[axisA] = axisB;\n perm[axisB] = axisA;\n return transpose(arr, perm);\n}\nexports.swapAxes = swapAxes;\nfunction concatenate(arrays, axis) {\n var e_1, _a;\n if (axis === void 0) { axis = null; }\n (axis = Object.assign({ axis: axis }, this).axis);\n if ((0, basic_1.isarray)(arrays))\n arrays = __spreadArray([], __read(arrays), false);\n arrays = arrays.map(basic_1.asarray);\n if (axis == null) {\n arrays = arrays.map(function (arr) { return (0, basic_1.ravel)(arr); });\n axis = 0;\n }\n if (!arrays.length)\n throw new Error(\"Expected at least two arrays\");\n var nDims = arrays[0].shape.length;\n if (axis < 0)\n axis = nDims + axis;\n var shapeIn = __spreadArray([], __read(arrays[0].shape), false);\n var flat = [];\n var shape = shapeIn.map(function (_, i) { return i == 0 ? 0 : shapeIn[i == axis ? 0 : i]; });\n try {\n for (var arrays_1 = __values(arrays), arrays_1_1 = arrays_1.next(); !arrays_1_1.done; arrays_1_1 = arrays_1.next()) {\n var arr = arrays_1_1.value;\n if (!(0, utils_js_1.allEq)(arr.shape.filter(function (_, i) { return i != axis; }), shapeIn.filter(function (_, i) { return i != axis; })))\n throw new Error(\"Inconsistent input shape \".concat(shapeIn, \" with respect to \").concat(arr.shape.map(function (v, i) { return i == axis ? '?' : v; })));\n shape[0] += arr.shape[axis];\n arr = axis == 0 ? arr : swapAxes(arr, axis, 0);\n flat.push.apply(flat, __spreadArray([], __read(arr.flat), false));\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (arrays_1_1 && !arrays_1_1.done && (_a = arrays_1.return)) _a.call(arrays_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // TO DO: infer or expect dtype here:\n var out = (0, basic_1.new_NDArray)(flat, shape, arrays[0].dtype);\n if (axis == 0)\n return out;\n else\n return swapAxes(out, axis, 0);\n}\nexports.concatenate = concatenate;\nfunction stack(arrays, axis) {\n var e_2, _a;\n if (axis === void 0) { axis = 0; }\n (axis = Object.assign({ axis: axis }, this).axis);\n if ((0, basic_1.isarray)(arrays))\n arrays = __spreadArray([], __read(arrays), false);\n if (!Array.isArray(arrays))\n throw new Error(\"Expected list of arrays. Found \".concat(typeof arrays));\n arrays = arrays.map(basic_1.asarray);\n if (!arrays.length)\n throw new Error(\"Expected at least two arrays\");\n var shapeIn = __spreadArray([], __read(arrays[0].shape), false);\n if (axis < 0)\n axis = shapeIn.length + 1 + axis;\n var shapeBroadcast = __spreadArray(__spreadArray(__spreadArray([], __read(shapeIn.slice(0, axis)), false), [1], false), __read(shapeIn.slice(axis)), false);\n var bArrays = [];\n try {\n for (var arrays_2 = __values(arrays), arrays_2_1 = arrays_2.next(); !arrays_2_1.done; arrays_2_1 = arrays_2.next()) {\n var arr = arrays_2_1.value;\n if (!(0, utils_js_1.allEq)(arr.shape, shapeIn))\n throw new Error(\"Inconsistent input shape \".concat(arr.shape, \" with respect to \").concat(arr.shape));\n bArrays.push((0, basic_1.reshape)(arr, shapeBroadcast));\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (arrays_2_1 && !arrays_2_1.done && (_a = arrays_2.return)) _a.call(arrays_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n return concatenate(bArrays, axis);\n}\nexports.stack = stack;\n","\"use strict\";\n//@ts-check\n/**\n * This file exists for the sole purpose splitting the class methods across multiple files\n * while preserving all features of intellisense or JSDoc without errors.\n * The main issue is that the implementation of the methods require NDArray very often.\n * It resolves circular dependencies by using a global variable imported in each module.\n * The main file must define `require('./core-globals').GLOBALS.NDArray = NDArray;` before\n * importing any of the files that use it.\n *\n * A template header for files importing NDArray from this file is given below.\n * DO NOT use `const NDArray = require(\"./core-globals\").GLOBALS.NDArray;`.\n * Use const {NDArray} = ... instead as indicated. (Intellisense stops working otherwise)\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.GLOBALS = void 0;\n//@ts-ignore\nvar _np = null, _array = null;\nexports.GLOBALS = {\n NDArray: _array,\n np: _np,\n};\n","\"use strict\";\n//@ts-check\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.np = void 0;\nvar np = function (template) {\n var _a;\n var variables = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n variables[_i - 1] = arguments[_i];\n }\n var usage = 'Usage example: np`np.arange(10)+${5}` or np([0,1,2]).';\n if (typeof template == \"number\")\n return template;\n if (template instanceof np.NDArray)\n return template;\n if (!Array.isArray(template))\n throw new Error(\"Expected template or array. \".concat(usage));\n if (!template.length)\n throw new Error(\"Expected argument. \".concat(usage));\n if (typeof template[0] == \"string\") {\n if (variables.length + 1 != template.length)\n throw new Error(\"Wrong input. \".concat(usage));\n //@ts-ignore\n return (_a = np.modules.grammar).parse.apply(_a, __spreadArray([/**@type {*}*/ (template)], __read(variables), false));\n }\n else {\n if (variables.length)\n throw new Error(\"Wrong input. \".concat(usage));\n //@ts-ignore\n return np.asarray(template);\n }\n};\nexports.np = np;\n// ==============================\n// Define Global before importing any module\n// ==============================\nvar _globals_1 = require(\"./_globals\");\n_globals_1.GLOBALS.np = np;\n// ==============================\n// Define casting and core before importing any other module\n// ==============================\nvar NDArray_class_1 = require(\"./NDArray-class\");\nnp.NDArray = NDArray_class_1.default;\n// ==============================\n// Define core-related functions\n// ==============================\nvar tolist = NDArray_class_1.default.prototype.modules.jsInterface.tolist;\nnp.tolist = function (template) {\n var variables = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n variables[_i - 1] = arguments[_i];\n }\n return tolist(np.apply(void 0, __spreadArray([template], __read(variables), false)));\n};\nnp.fromlist = NDArray_class_1.default.prototype.modules.jsInterface.fromlist;\nnp.ravel = NDArray_class_1.default.prototype.modules.basic.ravel;\nnp.reshape = NDArray_class_1.default.prototype.modules.basic.reshape;\nnp.array = NDArray_class_1.default.prototype.modules.basic.array;\nnp.asarray = NDArray_class_1.default.prototype.modules.basic.asarray;\nvar reduce = NDArray_class_1.default.prototype.modules.reduce;\nnp.sum = reduce.reducers.sum;\nnp.product = reduce.reducers.product;\nnp.prod = np.product;\nnp.any = reduce.reducersBool.any;\nnp.all = reduce.reducersBool.all;\nnp.max = reduce.reducers.max;\nnp.min = reduce.reducers.min;\nnp.argmax = reduce.reducers.argmax;\nnp.argmin = reduce.reducers.argmin;\nnp.mean = reduce.reducers.mean;\nnp.norm = reduce.reducersExtra.norm;\nnp.var = reduce.reducersExtra.var;\nnp.std = reduce.reducersExtra.std;\nvar transform = NDArray_class_1.default.prototype.modules.transform;\nnp.transpose = transform.transpose;\nnp.apply_along_axis = transform.apply_along_axis;\nnp.sort = transform.sort;\nnp.concatenate = transform.concatenate;\nnp.stack = transform.stack;\nvar operators = NDArray_class_1.default.prototype.modules.operators;\nnp.add = operators.op_binary[\"+\"];\nnp.subtract = operators.op_binary[\"-\"];\nnp.multiply = operators.op_binary[\"*\"];\nnp.divide = operators.op_binary[\"/\"];\nnp.mod = operators.op_binary[\"%\"];\nnp.divide_int = operators.op_binary[\"//\"];\nnp.pow = operators.op_binary[\"**\"];\nnp.bitwise_or = operators.op_binary[\"|\"];\nnp.bitwise_and = operators.op_binary[\"&\"];\nnp.bitwise_xor = operators.op_binary[\"^\"];\nnp.bitwise_shift_left = operators.op_binary[\"<<\"];\nnp.bitwise_shift_right = operators.op_binary[\">>\"];\nnp.greater = operators.op_binary[\">\"];\nnp.less = operators.op_binary[\"<\"];\nnp.greater_equal = operators.op_binary[\">=\"];\nnp.less_equal = operators.op_binary[\"<=\"];\nnp.equal = operators.op_binary[\"==\"];\nnp.not_equal = operators.op_binary[\"!=\"];\nnp.maximum = operators.op_binary[\"↑\"];\nnp.minimum = operators.op_binary[\"↓\"];\nnp.logical_or = operators.op_binary[\"or\"];\nnp.logical_and = operators.op_binary[\"and\"];\nnp.bitwise_not = operators.op_unary[\"~\"];\nnp.logical_not = operators.op_unary[\"not\"];\nnp.allclose = operators.allclose;\nnp.isclose = operators.isclose;\nvar ew = NDArray_class_1.default.prototype.modules.elementwise;\nnp.sign = ew.ops.sign;\nnp.sqrt = ew.ops.sqrt;\nnp.square = ew.ops.square;\nnp.abs = ew.ops.abs;\nnp.exp = ew.ops.exp;\nnp.log = ew.ops.log;\nnp.log2 = ew.ops.log2;\nnp.log10 = ew.ops.log10;\nnp.log1p = ew.ops.log1p;\nnp.sin = ew.ops.sin;\nnp.cos = ew.ops.cos;\nnp.tan = ew.ops.tan;\nnp.asin = ew.ops.asin;\nnp.acos = ew.ops.acos;\nnp.atan = ew.ops.atan;\nnp.atan2 = ew.ops.atan2;\nnp.cosh = ew.ops.cosh;\nnp.sinh = ew.ops.sinh;\nnp.tanh = ew.ops.tanh;\nnp.acosh = ew.ops.acosh;\nnp.asinh = ew.ops.asinh;\nnp.atanh = ew.ops.atanh;\nnp.round = ew.ops.round;\n// ==============================\n// import np modules\n// ============================== \nvar modules_1 = require(\"./modules\");\nnp.modules = modules_1.modules;\nnp.empty = np.modules.constructors.empty;\nnp.zeros = np.modules.constructors.zeros;\nnp.ones = np.modules.constructors.ones;\nnp.arange = np.modules.constructors.arange;\nnp.linspace = np.modules.constructors.linspace;\nnp.geomspace = np.modules.constructors.geomspace;\nnp.random = np.modules.random;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.nd_modules = exports.np = void 0;\n//@ts-check\nvar _globals_1 = require(\"../_globals\");\nvar np = _globals_1.GLOBALS.np, _NDArray = _globals_1.GLOBALS.NDArray;\nexports.np = np;\nif (!np)\n throw new Error(\"Programming error: np not defined\");\nexports.nd_modules = _NDArray.prototype.modules;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.geomspace = exports.linspace = exports.arange = exports.ones = exports.zeros = exports.empty = void 0;\n//@ts-check\nvar NDArray_class_1 = require(\"../NDArray-class\");\nvar _a = NDArray_class_1.default.prototype.modules, basic = _a.basic, elementwise = _a.elementwise;\nfunction empty(shape, dtype) {\n if (dtype === void 0) { dtype = Number; }\n return basic.new_from(shape, undefined, dtype);\n}\nexports.empty = empty;\n;\nfunction zeros(shape, dtype) {\n if (dtype === void 0) { dtype = Number; }\n var c = dtype == Boolean ? false : 0;\n return basic.new_from(shape, function (_) { return c; }, dtype);\n}\nexports.zeros = zeros;\n;\nfunction ones(shape, dtype) {\n if (dtype === void 0) { dtype = Number; }\n var c = dtype == Boolean ? true : 1;\n return basic.new_from(shape, function (_) { return c; }, dtype);\n}\nexports.ones = ones;\n;\nfunction arange(arg0, arg1) {\n if (arg1 === void 0) { arg1 = null; }\n var start, end;\n if (arg1 === null)\n start = 0, end = arg0;\n else\n start = arg0, end = arg1;\n return basic.new_from(end - start, function (_, i) { return start + i; }, Number);\n}\nexports.arange = arange;\n;\nfunction linspace(start, stop, num, endpoint) {\n var _a;\n if (num === void 0) { num = 50; }\n if (endpoint === void 0) { endpoint = true; }\n (_a = Object.assign({ stop: stop, num: num, endpoint: endpoint }, this), stop = _a.stop, num = _a.num, endpoint = _a.endpoint);\n start = basic.as_number(start);\n stop = basic.as_number(stop);\n var n = (num - (endpoint ? 1 : 0));\n var arr = arange(num).multiply((stop - start) / n).add(start);\n return arr;\n}\nexports.linspace = linspace;\nfunction geomspace(start, stop, num, endpoint) {\n var _a;\n if (num === void 0) { num = 50; }\n if (endpoint === void 0) { endpoint = true; }\n (_a = Object.assign({ stop: stop, num: num, endpoint: endpoint }, this), stop = _a.stop, num = _a.num, endpoint = _a.endpoint);\n start = elementwise.ops.log(start);\n stop = elementwise.ops.log(stop);\n return elementwise.ops.exp(linspace(start, stop, num, endpoint));\n}\nexports.geomspace = geomspace;\n","\"use strict\";\nvar __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.parse = exports.__parser_pool = exports.__makeSemantics = exports.ohmGrammar = exports.grammar = void 0;\n//@ts-check\nvar _globals_1 = require(\"./_globals\");\nvar ohm = require(\"ohm-js\");\nexports.grammar = String.raw(templateObject_1 || (templateObject_1 = __makeTemplateObject([\"\\nArrayGrammar {\\n Instruction\\n = Variable \\\"[\\\" Slice \\\"]\\\" AssignSymbol ArithmeticLogicExp -- sliceAssignment\\n | ArithmeticLogicExp -- expression\\n \\n Variable\\n = \\\"#\\\" digit+ \\\"#\\\"\\n \\n AssignSymbol\\n =\\\"=\\\"|\\\"+=\\\"|\\\"-=\\\"|\\\"*=\\\"|\\\"/=\\\"|\\\"%=\\\"|\\\"&=\\\"|\\\"|=\\\"|\\\"^=\\\"|\\\"@=\\\"|\\\"**=\\\"|\\\"<<=\\\"|\\\">>=\\\"|\\\"//=\\\"|\\\"or=\\\"|\\\"and=\\\"|\\\"xor=\\\"|\\\"max=\\\"|\\\"min=\\\"\\n \\n /* Declaration in precedence order (weakest first) */\\n ArithmeticLogicExp = Precedence11\\n\\n /* https://docs.python.org/3/reference/expressions.html */\\n Operator11 = \\\"<\\\" | \\\"<=\\\" | \\\">\\\" | \\\">=\\\" | \\\"!=\\\" | \\\"==\\\"\\n Operator10 = \\\"|\\\"\\n Operator09 = \\\"^\\\"\\n Operator08 = \\\"&\\\"\\n Operator07 = \\\"<<\\\" | \\\">>\\\"\\n Operator06 = \\\"+\\\" | \\\"-\\\"\\n Operator05 = \\\"*\\\" | \\\"@\\\" | \\\"/\\\" | \\\"//\\\" | \\\"%\\\"\\n Operator04 = \\\"~\\\" /* Unary */\\n Operator03 = \\\"+\\\" | \\\"-\\\" /* Unary. Special treatment to prevent \\\"-1.3\\\" to be \\\"-(array of 1.3)\\\" */\\n Operator02 = \\\"**\\\"\\n /* Operator01 = \\\"x[index]\\\" | \\\"x[index:index]\\\" | \\\"x(arguments...)\\\" | \\\"x.attribute\\\" */\\n /* Operator00 = \\\"(expressions...)\\\" */\\n\\n Precedence11 = Precedence11 Operator11 Precedence10 | \\\"\\\" \\\"\\\" Precedence10\\n Precedence10 = Precedence10 Operator10 Precedence09 | \\\"\\\" \\\"\\\" Precedence09\\n Precedence09 = Precedence09 Operator09 Precedence08 | \\\"\\\" \\\"\\\" Precedence08\\n Precedence08 = Precedence08 Operator08 Precedence07 | \\\"\\\" \\\"\\\" Precedence07\\n Precedence07 = Precedence07 Operator07 Precedence06 | \\\"\\\" \\\"\\\" Precedence06\\n Precedence06 = Precedence06 Operator06 Precedence05 | \\\"\\\" \\\"\\\" Precedence05\\n Precedence05 = Precedence05 Operator05 Precedence04 | \\\"\\\" \\\"\\\" Precedence04\\n Precedence04 = \\\"\\\" Operator04 Precedence03 | \\\"\\\" \\\"\\\" Precedence03 /* Unary */\\n Precedence03 = \\\"\\\" Operator03 Precedence02 | \\\"\\\" \\\"\\\" Precedence02 /* Special */\\n Precedence02 = Precedence02 Operator02 Precedence03 | \\\"\\\" \\\"\\\" Precedence01\\n Precedence01 = Arr\\n \\n Parenthesis = \\\"(\\\" ArithmeticLogicExp \\\")\\\"\\n Arr\\n = Arr \\\".\\\" Name CallArgs -- method\\n | Arr \\\".\\\" Name -- attribute\\n | Arr \\\"[\\\" Slice \\\"]\\\" -- slice\\n | Parenthesis\\n | Name (\\\".\\\" Name)* CallArgs -- call\\n | number\\n | Variable\\n\\n Name (an identifier)\\n = (letter|\\\"_\\\") (letter|\\\"_\\\"|digit)*\\n\\n number (a number)\\n = (\\\"+\\\"|\\\"-\\\")? digit* \\\".\\\" digit+ \\\"E\\\" (\\\"+\\\"|\\\"-\\\")? \\\"digit+\\\"\\n | (\\\"+\\\"|\\\"-\\\")? digit* \\\".\\\" digit+ \\\"e\\\" (\\\"+\\\"|\\\"-\\\")? \\\"digit+\\\"\\n | (\\\"+\\\"|\\\"-\\\")? digit* \\\".\\\" digit+ \\\"\\\" \\\"\\\" \\\"\\\"\\n | (\\\"+\\\"|\\\"-\\\")? digit+ \\\"\\\" \\\"\\\" \\\"\\\" \\\"\\\" \\\"\\\"\\n \\n int (an integer) = \\\"\\\" digit+ | \\\"-\\\" digit+ | \\\"+\\\" digit+\\n\\n CallArgs // Using empty strings instead of separate rules\\n = \\\"(\\\" Args \\\",\\\" KwArgs \\\",\\\"? \\\")\\\"\\n | \\\"(\\\" Args \\\",\\\"? \\\"\\\" \\\"\\\" \\\")\\\"\\n | \\\"(\\\" \\\"\\\" \\\",\\\"? KwArgs \\\",\\\"? \\\")\\\"\\n | \\\"(\\\" \\\"\\\" \\\"\\\" \\\"\\\" \\\"\\\" \\\")\\\"\\n \\n Args = NonemptyListOf\\n KwArgs = NonemptyListOf\\n KwArg = Name \\\"=\\\" ArgValue\\n\\n ArgValue = Constant | JsArray | ArithmeticLogicExp | String\\n Constant = \\\"True\\\" | \\\"False\\\" | \\\"None\\\" | \\\"np.nan\\\" | \\\"np.inf\\\"\\n JsArray\\n = \\\"[\\\" ListOf \\\",\\\"? \\\"]\\\"\\n | \\\"(\\\" ListOf \\\",\\\"? \\\")\\\"\\n\\n String = \\\"'\\\" any* \\\"'\\\" | \\\"\\\"\\\" any* \\\"\\\"\\\"\\n \\n Slice = NonemptyListOf\\n SliceTerm\\n = SliceRange\\n | (\\\":\\\" | \\\"...\\\" | \\\"None\\\") -- constant\\n | JsArray\\n | ArithmeticLogicExp\\n \\n SliceRange\\n = int \\\":\\\" int \\\":\\\" int\\n | int \\\":\\\" int \\\"\\\" \\\"\\\"\\n | int \\\":\\\" \\\"\\\" \\\":\\\" int\\n | int \\\":\\\" \\\"\\\" \\\"\\\" \\\"\\\"\\n | \\\"\\\" \\\":\\\" int \\\":\\\" int\\n | \\\"\\\" \\\":\\\" int \\\"\\\" \\\"\\\"\\n | \\\"\\\" \\\":\\\" \\\"\\\" \\\":\\\" int\\n | \\\"\\\" \\\":\\\" \\\"\\\" \\\"\\\" \\\"\\\"\\n}\\n\"], [\"\\nArrayGrammar {\\n Instruction\\n = Variable \\\"[\\\" Slice \\\"]\\\" AssignSymbol ArithmeticLogicExp -- sliceAssignment\\n | ArithmeticLogicExp -- expression\\n \\n Variable\\n = \\\"#\\\" digit+ \\\"#\\\"\\n \\n AssignSymbol\\n =\\\"=\\\"|\\\"+=\\\"|\\\"-=\\\"|\\\"*=\\\"|\\\"/=\\\"|\\\"%=\\\"|\\\"&=\\\"|\\\"|=\\\"|\\\"^=\\\"|\\\"@=\\\"|\\\"**=\\\"|\\\"<<=\\\"|\\\">>=\\\"|\\\"//=\\\"|\\\"or=\\\"|\\\"and=\\\"|\\\"xor=\\\"|\\\"max=\\\"|\\\"min=\\\"\\n \\n /* Declaration in precedence order (weakest first) */\\n ArithmeticLogicExp = Precedence11\\n\\n /* https://docs.python.org/3/reference/expressions.html */\\n Operator11 = \\\"<\\\" | \\\"<=\\\" | \\\">\\\" | \\\">=\\\" | \\\"!=\\\" | \\\"==\\\"\\n Operator10 = \\\"|\\\"\\n Operator09 = \\\"^\\\"\\n Operator08 = \\\"&\\\"\\n Operator07 = \\\"<<\\\" | \\\">>\\\"\\n Operator06 = \\\"+\\\" | \\\"-\\\"\\n Operator05 = \\\"*\\\" | \\\"@\\\" | \\\"/\\\" | \\\"//\\\" | \\\"%\\\"\\n Operator04 = \\\"~\\\" /* Unary */\\n Operator03 = \\\"+\\\" | \\\"-\\\" /* Unary. Special treatment to prevent \\\"-1.3\\\" to be \\\"-(array of 1.3)\\\" */\\n Operator02 = \\\"**\\\"\\n /* Operator01 = \\\"x[index]\\\" | \\\"x[index:index]\\\" | \\\"x(arguments...)\\\" | \\\"x.attribute\\\" */\\n /* Operator00 = \\\"(expressions...)\\\" */\\n\\n Precedence11 = Precedence11 Operator11 Precedence10 | \\\"\\\" \\\"\\\" Precedence10\\n Precedence10 = Precedence10 Operator10 Precedence09 | \\\"\\\" \\\"\\\" Precedence09\\n Precedence09 = Precedence09 Operator09 Precedence08 | \\\"\\\" \\\"\\\" Precedence08\\n Precedence08 = Precedence08 Operator08 Precedence07 | \\\"\\\" \\\"\\\" Precedence07\\n Precedence07 = Precedence07 Operator07 Precedence06 | \\\"\\\" \\\"\\\" Precedence06\\n Precedence06 = Precedence06 Operator06 Precedence05 | \\\"\\\" \\\"\\\" Precedence05\\n Precedence05 = Precedence05 Operator05 Precedence04 | \\\"\\\" \\\"\\\" Precedence04\\n Precedence04 = \\\"\\\" Operator04 Precedence03 | \\\"\\\" \\\"\\\" Precedence03 /* Unary */\\n Precedence03 = \\\"\\\" Operator03 Precedence02 | \\\"\\\" \\\"\\\" Precedence02 /* Special */\\n Precedence02 = Precedence02 Operator02 Precedence03 | \\\"\\\" \\\"\\\" Precedence01\\n Precedence01 = Arr\\n \\n Parenthesis = \\\"(\\\" ArithmeticLogicExp \\\")\\\"\\n Arr\\n = Arr \\\".\\\" Name CallArgs -- method\\n | Arr \\\".\\\" Name -- attribute\\n | Arr \\\"[\\\" Slice \\\"]\\\" -- slice\\n | Parenthesis\\n | Name (\\\".\\\" Name)* CallArgs -- call\\n | number\\n | Variable\\n\\n Name (an identifier)\\n = (letter|\\\"_\\\") (letter|\\\"_\\\"|digit)*\\n\\n number (a number)\\n = (\\\"+\\\"|\\\"-\\\")? digit* \\\".\\\" digit+ \\\"E\\\" (\\\"+\\\"|\\\"-\\\")? \\\"digit+\\\"\\n | (\\\"+\\\"|\\\"-\\\")? digit* \\\".\\\" digit+ \\\"e\\\" (\\\"+\\\"|\\\"-\\\")? \\\"digit+\\\"\\n | (\\\"+\\\"|\\\"-\\\")? digit* \\\".\\\" digit+ \\\"\\\" \\\"\\\" \\\"\\\"\\n | (\\\"+\\\"|\\\"-\\\")? digit+ \\\"\\\" \\\"\\\" \\\"\\\" \\\"\\\" \\\"\\\"\\n \\n int (an integer) = \\\"\\\" digit+ | \\\"-\\\" digit+ | \\\"+\\\" digit+\\n\\n CallArgs // Using empty strings instead of separate rules\\n = \\\"(\\\" Args \\\",\\\" KwArgs \\\",\\\"? \\\")\\\"\\n | \\\"(\\\" Args \\\",\\\"? \\\"\\\" \\\"\\\" \\\")\\\"\\n | \\\"(\\\" \\\"\\\" \\\",\\\"? KwArgs \\\",\\\"? \\\")\\\"\\n | \\\"(\\\" \\\"\\\" \\\"\\\" \\\"\\\" \\\"\\\" \\\")\\\"\\n \\n Args = NonemptyListOf\\n KwArgs = NonemptyListOf\\n KwArg = Name \\\"=\\\" ArgValue\\n\\n ArgValue = Constant | JsArray | ArithmeticLogicExp | String\\n Constant = \\\"True\\\" | \\\"False\\\" | \\\"None\\\" | \\\"np.nan\\\" | \\\"np.inf\\\"\\n JsArray\\n = \\\"[\\\" ListOf \\\",\\\"? \\\"]\\\"\\n | \\\"(\\\" ListOf \\\",\\\"? \\\")\\\"\\n\\n String = \\\"\\\\'\\\" any* \\\"\\\\'\\\" | \\\"\\\\\\\"\\\" any* \\\"\\\\\\\"\\\"\\n \\n Slice = NonemptyListOf\\n SliceTerm\\n = SliceRange\\n | (\\\":\\\" | \\\"...\\\" | \\\"None\\\") -- constant\\n | JsArray\\n | ArithmeticLogicExp\\n \\n SliceRange\\n = int \\\":\\\" int \\\":\\\" int\\n | int \\\":\\\" int \\\"\\\" \\\"\\\"\\n | int \\\":\\\" \\\"\\\" \\\":\\\" int\\n | int \\\":\\\" \\\"\\\" \\\"\\\" \\\"\\\"\\n | \\\"\\\" \\\":\\\" int \\\":\\\" int\\n | \\\"\\\" \\\":\\\" int \\\"\\\" \\\"\\\"\\n | \\\"\\\" \\\":\\\" \\\"\\\" \\\":\\\" int\\n | \\\"\\\" \\\":\\\" \\\"\\\" \\\"\\\" \\\"\\\"\\n}\\n\"])));\nexports.ohmGrammar = ohm.grammar(exports.grammar);\nvar __makeSemantics = function () {\n var semanticVariables = [];\n var semantics = {\n Instruction_sliceAssignment: function ($tgt, _open, $where, _close, $symbol, $src) {\n var _tgt = $tgt.parse();\n var _src = $src.parse();\n var symbol = $symbol.sourceString;\n var where = $where.parse();\n var tgt = _globals_1.nd_modules.basic.asarray(_tgt);\n _globals_1.nd_modules.operators.op_assign[symbol](_tgt, where, _src);\n if (tgt !== _tgt) {\n // WARNING: Creates a copy. This is terrible for arr[2, 4, 3] = 5\n tgt = _globals_1.nd_modules.jsInterface.tolist(tgt);\n while (_tgt.length)\n _tgt.pop();\n // @ts-ignore\n _tgt.push.apply(_tgt, __spreadArray([], __read(_tgt), false));\n }\n return null;\n },\n Instruction_expression: function ($arr) {\n var arr = $arr.parse();\n if (typeof arr === \"number\")\n return arr;\n if (typeof arr === \"boolean\")\n return arr;\n if (Array.isArray(arr))\n return arr;\n if (_globals_1.nd_modules.basic.isarray(arr))\n arr = _globals_1.nd_modules.basic.number_collapse(arr);\n return arr;\n },\n Precedence11: BinaryOperation,\n Precedence10: BinaryOperation,\n Precedence09: BinaryOperation,\n Precedence08: BinaryOperation,\n Precedence07: BinaryOperation,\n Precedence06: BinaryOperation,\n Precedence05: BinaryOperation,\n Precedence04: UnaryOperation,\n Precedence03: UnaryOperation,\n Precedence02: BinaryOperation,\n number: function (arg1, arg2, arg3, arg4, arg5, arg6, arg7) {\n return parseFloat(this.sourceString);\n },\n Arr_slice: function ($arr, _open, $where, _close) {\n var arr = $arr.parse();\n var where = $where.parse();\n return arr.index.apply(arr, __spreadArray([], __read(where), false));\n },\n SliceTerm_constant: function ($x) {\n return $x.sourceString;\n },\n Arr_call: function ($name, $names, _, $callArgs) {\n var name = $name.sourceString + $names.sourceString;\n if (name.slice(0, 3) == \"np.\")\n name = name.slice(3);\n var func = name.split('.').reduce(function (obj, name) { return obj[name]; }, _globals_1.np);\n if (func === undefined)\n throw new Error(\"Unrecognized function \".concat(name));\n var _a = $callArgs.parse(), args = _a.args, kwArgs = _a.kwArgs;\n return func.bind(kwArgs).apply(void 0, __spreadArray([], __read(args), false));\n },\n Arr_method: function ($arr, _dot, $name, $callArgs) {\n var _a;\n var arr = $arr.parse();\n var name = $name.sourceString;\n var _b = $callArgs.parse(), args = _b.args, kwArgs = _b.kwArgs;\n if (arr[name] === undefined)\n throw new Error(\"Unrecognized method \".concat(name));\n return (_a = arr.withKwArgs(kwArgs))[name].apply(_a, __spreadArray([], __read(args), false));\n },\n Parenthesis: function (_, $arr, __) { return $arr.parse(); },\n Arr_attribute: function ($arr, _, $name) { return $arr.parse()[$name.sourceString]; },\n Variable: function (_, $i, __) {\n var i = parseInt($i.sourceString);\n var value = semanticVariables[i];\n var isListOfArrays = Array.isArray(value) && value.length && _globals_1.nd_modules.basic.isarray(value[0]);\n if (Array.isArray(value) && !isListOfArrays)\n value = _globals_1.nd_modules.basic.array(value);\n return value;\n },\n int: function ($sign, $value) {\n var value = parseInt($value.sourceString);\n if ($sign.sourceString == '-')\n return -value;\n else\n return value;\n },\n SliceRange: function ($start, _, $stop, __, $step) {\n return this.sourceString;\n },\n Constant: function ($x) {\n switch ($x.sourceString) {\n case \"True\": return true;\n case \"False\": return false;\n case \"None\": return null;\n case \"np.nan\": return Number.NaN;\n case \"np.inf\": return Number.POSITIVE_INFINITY;\n }\n throw new Error(\"Unrecognized constant \".concat($x.sourceString));\n },\n String: function (_open, $str, _close) {\n return $str.sourceString;\n },\n CallArgs: function (_open, $args, _comma, $kwArgs, _trailing, _close) {\n var args = $args.parse() || [];\n var entries = $kwArgs.parse() || [];\n var kwArgs = Object.fromEntries(entries.map(function (_a) {\n var _b = __read(_a, 2), k = _b[0], v = _b[1];\n // The following is needed because minus integer gets parsed as array.\n if (_globals_1.nd_modules.basic.isarray(v))\n v = _globals_1.nd_modules.basic.number_collapse(v);\n return [k, v];\n }));\n return { args: args, kwArgs: kwArgs };\n },\n KwArg: function ($key, _equals, $value) {\n var key = $key.sourceString;\n var value = $value.parse();\n return [key, value];\n },\n NonemptyListOf: function (first, _, more) {\n return __spreadArray([first], __read(more.children), false).map(function (c) { return c.parse(); });\n },\n JsArray: function (_open, $list, _trailing, _close) {\n var list = $list.parse();\n // Downcast arrays (needed because, e.g., for [-1, 3, -2], -1 and -2 are interpreted as MyArray rather than int)\n var tolist = _globals_1.nd_modules.jsInterface.tolist;\n for (var i in list)\n if (_globals_1.nd_modules.basic.isarray(list[i]))\n list[i] = tolist(list[i]);\n return list;\n },\n _terminal: function () { return null; },\n };\n function BinaryOperation($A, $symbol, $B) {\n var A = $A.parse();\n var B = $B.parse();\n var symbol = $symbol.sourceString;\n if (symbol == \"\" && A === null)\n return B;\n var op = _globals_1.nd_modules.operators.op_binary;\n return op[symbol](A, B);\n }\n function UnaryOperation(_, $symbol, $B) {\n var B = $B.parse();\n var symbol = $symbol.sourceString;\n if (symbol == \"\")\n return B;\n var op_unary = _globals_1.nd_modules.operators.op_unary;\n switch (symbol) {\n case \"+\": return op_unary[\"+\"](B);\n case \"-\": return op_unary[\"-\"](B);\n case \"~\": return op_unary[\"~\"](B);\n case \"!\": return op_unary[\"not\"](B);\n }\n throw new Error(\"Programming Error: \".concat(symbol));\n }\n var ohmSemantics = exports.ohmGrammar.createSemantics();\n ohmSemantics.addOperation('parse', semantics);\n /**\n * @param {TemplateStringsArray} template\n * @param {any[]} variables\n */\n function parse(template) {\n var variables = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n variables[_i - 1] = arguments[_i];\n }\n // Replace variables in template with #0# #1# #2#, ...\n var idx = 0;\n var template_with_placeholders = template.join('###').replace(/###/g, function () { return \"#\".concat(idx++, \"#\"); });\n semanticVariables.length = 0;\n semanticVariables.push.apply(semanticVariables, __spreadArray([], __read(variables), false));\n var match = exports.ohmGrammar.match(template_with_placeholders);\n if (!match.succeeded())\n throw new Error(match.message);\n return ohmSemantics(match).parse();\n }\n return { parse: parse, ohmSemantics: ohmSemantics, semantics: semantics, semanticVariables: semanticVariables, busy: 0 };\n};\nexports.__makeSemantics = __makeSemantics;\nexports.__parser_pool = [(0, exports.__makeSemantics)()];\n/**\n * @param {TemplateStringsArray} template\n * @param {any[]} variables\n */\nvar parse = function (template) {\n var variables = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n variables[_i - 1] = arguments[_i];\n }\n // Thread control, because the parser depends on semanticVariables,\n // but we don't want to waste CPU time recreating the parser on each call\n // No cleaning is done (we assume that the number of threads is negligible compared to the memory size)\n var pool = exports.__parser_pool;\n for (var i = 0; i < pool.length; i++) {\n var parser = pool[i];\n if (parser.busy++ == 0) {\n try {\n return parser.parse.apply(parser, __spreadArray([template], __read(variables), false));\n }\n finally {\n parser.busy = 0;\n }\n }\n if (i == pool.length)\n pool.push((0, exports.__makeSemantics)());\n }\n};\nexports.parse = parse;\nvar templateObject_1;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.modules = void 0;\n//@ts-check\nrequire(\"./_globals\");\nvar constructors = require(\"./constructors\");\nvar grammar = require(\"./grammar\");\nvar random = require(\"./random\");\nexports.modules = {\n constructors: constructors,\n grammar: grammar,\n random: random,\n};\n","\"use strict\";\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.shuffle = exports.shuffled = exports._shuffled = exports._shuffle = exports.normal = exports.randn = exports.__normal = exports.exponential = exports.uniform = exports.random = void 0;\n//@ts-check\nvar _globals_1 = require(\"./_globals\");\nfunction random(shape) {\n return _globals_1.nd_modules.basic.new_from(shape, function (_) { return Math.random(); }, Number);\n}\nexports.random = random;\n;\nfunction uniform(a, b, shape) {\n return random(shape).multiply(b - a).add(a);\n}\nexports.uniform = uniform;\n;\nfunction exponential(mean, shape) {\n return _globals_1.np.multiply(mean, _globals_1.np.subtract(0, _globals_1.np.log(random(shape))));\n}\nexports.exponential = exponential;\n;\n/** @param {number} n */\nfunction __normal(n) {\n var out = [];\n while (out.length < n) {\n var u = Math.random() * 2 - 1;\n var v = Math.random() * 2 - 1;\n var s = u * u + v * v;\n if (s >= 1)\n continue;\n var x = Math.sqrt(-2 * Math.log(s) / s) * u;\n var y = Math.sqrt(-2 * Math.log(s) / s) * v;\n out.push(x);\n out.push(y);\n }\n if (out.length > n)\n out.pop();\n return out;\n}\nexports.__normal = __normal;\nfunction randn(shape) {\n var flat = __normal(_globals_1.np.prod(shape));\n return new _globals_1.np.NDArray(flat, shape, Number);\n}\nexports.randn = randn;\n;\nfunction normal(mean, std, shape) {\n return _globals_1.np.add(mean, _globals_1.np.multiply(std, shape));\n}\nexports.normal = normal;\n;\n/** @param {any[]} list */\nfunction _shuffle(list) {\n var _a;\n // Fisher-Yates (aka Knuth) shuffle.\n // https://stackoverflow.com/a/2450976\n for (var i = list.length - 1; i >= 0; i--) {\n var j = Math.floor(Math.random() * (i + 1));\n _a = __read([list[j], list[i]], 2), list[i] = _a[0], list[j] = _a[1];\n }\n}\nexports._shuffle = _shuffle;\n/** @param {any[]} list */\nfunction _shuffled(list) {\n var out = __spreadArray([], __read(list), false);\n _shuffle(out);\n return out;\n}\nexports._shuffled = _shuffled;\n/** @param {NDArray} arr @returns {NDArray} */\nfunction shuffled(arr) {\n if (arr.shape.length == 0)\n return arr;\n if (arr.shape.length == 1) {\n var flat = _shuffled(arr.flat);\n return new _globals_1.np.NDArray(flat, arr.shape, arr.dtype);\n }\n var perm = _shuffled(Array.from({ length: arr.length }, function (_, i) { return i; }));\n var out = _globals_1.np.empty(arr.shape, arr.dtype);\n for (var i = 0; i < arr.length; i++)\n out.assign([i], arr.index(perm[i]));\n return out;\n}\nexports.shuffled = shuffled;\n/**\n * @param {NDArray} arr\n */\nfunction shuffle(arr) {\n arr.assign(shuffled(arr));\n}\nexports.shuffle = shuffle;\n","\"use strict\";\n//@ts-check\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.allClose = exports.allEq = exports.ravel = exports.binary_operation = void 0;\nfunction binary_operation(A, B, func) {\n // Pointwise check for equality for arbitrary js arrays (without broadcasting)\n var C = [];\n var q = [[A, B, C, 0]];\n var seen;\n while (true) {\n var _next = q.pop();\n if (!_next)\n return true;\n var _a = __read(_next, 4), a = _a[0], b = _a[1], c = _a[2], depth = _a[3];\n if (Array.isArray(a) && Array.isArray(b) && a.length == b.length) {\n for (var i in a) {\n var c_i = [];\n c.push(c_i);\n q.push([a[i], b[i], c_i, depth + 1]);\n }\n }\n else\n c.push(func(a, b));\n if (depth > 10000 && Array.isArray(a)) { // Activate circular reference detection\n // Checking only A suffices (the other will exhaust otherwise)\n seen = /**@type {any[]}*/ (seen || []);\n if (seen.includes(a))\n throw new Error(\"Circular reference found. \".concat(a));\n seen[depth - 10000] = a;\n }\n }\n}\nexports.binary_operation = binary_operation;\n;\nfunction ravel(A) {\n // Flatten js array\n var q = [[A, 0]], flat = [];\n var seen;\n var _loop_1 = function () {\n var _next = q.pop();\n if (!_next)\n return \"break\";\n var _a = __read(_next, 2), a = _a[0], depth = _a[1];\n if (depth > 10000 && Array.isArray(a)) { // Activate circular reference detection\n seen = /**@type {any[]}*/ (seen || []);\n if (seen.includes(a))\n throw new Error(\"Circular reference found. \".concat(a));\n seen[depth - 10000] = a;\n }\n if (Array.isArray(a)) {\n q.push.apply(q, __spreadArray([], __read(a.map(function (v) { return [v, depth + 1]; })), false));\n return \"continue\";\n }\n flat.push(a);\n };\n while (true) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n return flat;\n}\nexports.ravel = ravel;\n;\nfunction allEq(A, B, nan_equal) {\n if (nan_equal === void 0) { nan_equal = false; }\n var different = new Error('');\n var func = function (a, b) {\n if (a !== b && !(nan_equal && Number.isNaN(a) && Number.isNaN(b)))\n throw different;\n return 0;\n };\n try {\n binary_operation(A, B, func);\n }\n catch (err) {\n if (err === different)\n return false;\n else\n throw err;\n }\n return true;\n}\nexports.allEq = allEq;\n;\nfunction allClose(A, B, rtol, atol, nan_equal) {\n if (rtol === void 0) { rtol = 1.e-5; }\n if (atol === void 0) { atol = 1.e-8; }\n if (nan_equal === void 0) { nan_equal = false; }\n var func = function (a, b) {\n if (Number.isFinite(a) && Number.isFinite(b))\n return Math.abs(a - b) <= atol + rtol * Math.abs(b);\n return (a === b) || (nan_equal && Number.isNaN(a) && Number.isNaN(b));\n };\n var different = new Error('');\n var wrapper = function (a, b) {\n if (!func(a, b))\n throw different;\n return 0;\n };\n try {\n binary_operation(A, B, wrapper);\n }\n catch (err) {\n if (err === different)\n return false;\n else\n throw err;\n }\n return true;\n}\nexports.allClose = allClose;\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n// --------------------------------------------------------------------\n\n// --------------------------------------------------------------------\n// Exports\n// --------------------------------------------------------------------\n\nfunction abstract(optMethodName) {\n const methodName = optMethodName || '';\n return function() {\n throw new Error(\n 'this method ' +\n methodName +\n ' is abstract! ' +\n '(it has no implementation in class ' +\n this.constructor.name +\n ')',\n );\n };\n}\n\nfunction assert(cond, message) {\n if (!cond) {\n throw new Error(message || 'Assertion failed');\n }\n}\n\n// Define a lazily-computed, non-enumerable property named `propName`\n// on the object `obj`. `getterFn` will be called to compute the value the\n// first time the property is accessed.\nfunction defineLazyProperty(obj, propName, getterFn) {\n let memo;\n Object.defineProperty(obj, propName, {\n get() {\n if (!memo) {\n memo = getterFn.call(this);\n }\n return memo;\n },\n });\n}\n\nfunction clone(obj) {\n if (obj) {\n return Object.assign({}, obj);\n }\n return obj;\n}\n\nfunction repeatFn(fn, n) {\n const arr = [];\n while (n-- > 0) {\n arr.push(fn());\n }\n return arr;\n}\n\nfunction repeatStr(str, n) {\n return new Array(n + 1).join(str);\n}\n\nfunction repeat(x, n) {\n return repeatFn(() => x, n);\n}\n\nfunction getDuplicates(array) {\n const duplicates = [];\n for (let idx = 0; idx < array.length; idx++) {\n const x = array[idx];\n if (array.lastIndexOf(x) !== idx && duplicates.indexOf(x) < 0) {\n duplicates.push(x);\n }\n }\n return duplicates;\n}\n\nfunction copyWithoutDuplicates(array) {\n const noDuplicates = [];\n array.forEach(entry => {\n if (noDuplicates.indexOf(entry) < 0) {\n noDuplicates.push(entry);\n }\n });\n return noDuplicates;\n}\n\nfunction isSyntactic(ruleName) {\n const firstChar = ruleName[0];\n return firstChar === firstChar.toUpperCase();\n}\n\nfunction isLexical(ruleName) {\n return !isSyntactic(ruleName);\n}\n\nfunction padLeft(str, len, optChar) {\n const ch = optChar || ' ';\n if (str.length < len) {\n return repeatStr(ch, len - str.length) + str;\n }\n return str;\n}\n\n// StringBuffer\n\nfunction StringBuffer() {\n this.strings = [];\n}\n\nStringBuffer.prototype.append = function(str) {\n this.strings.push(str);\n};\n\nStringBuffer.prototype.contents = function() {\n return this.strings.join('');\n};\n\nconst escapeUnicode = str => String.fromCodePoint(parseInt(str, 16));\n\nfunction unescapeCodePoint(s) {\n if (s.charAt(0) === '\\\\') {\n switch (s.charAt(1)) {\n case 'b':\n return '\\b';\n case 'f':\n return '\\f';\n case 'n':\n return '\\n';\n case 'r':\n return '\\r';\n case 't':\n return '\\t';\n case 'v':\n return '\\v';\n case 'x':\n return escapeUnicode(s.slice(2, 4));\n case 'u':\n return s.charAt(2) === '{' ?\n escapeUnicode(s.slice(3, -1)) :\n escapeUnicode(s.slice(2, 6));\n default:\n return s.charAt(1);\n }\n } else {\n return s;\n }\n}\n\n// Helper for producing a description of an unknown object in a safe way.\n// Especially useful for error messages where an unexpected type of object was encountered.\nfunction unexpectedObjToString(obj) {\n if (obj == null) {\n return String(obj);\n }\n const baseToString = Object.prototype.toString.call(obj);\n try {\n let typeName;\n if (obj.constructor && obj.constructor.name) {\n typeName = obj.constructor.name;\n } else if (baseToString.indexOf('[object ') === 0) {\n typeName = baseToString.slice(8, -1); // Extract e.g. \"Array\" from \"[object Array]\".\n } else {\n typeName = typeof obj;\n }\n return typeName + ': ' + JSON.stringify(String(obj));\n } catch (e) {\n return baseToString;\n }\n}\n\nvar common = /*#__PURE__*/Object.freeze({\n __proto__: null,\n abstract: abstract,\n assert: assert,\n defineLazyProperty: defineLazyProperty,\n clone: clone,\n repeatFn: repeatFn,\n repeatStr: repeatStr,\n repeat: repeat,\n getDuplicates: getDuplicates,\n copyWithoutDuplicates: copyWithoutDuplicates,\n isSyntactic: isSyntactic,\n isLexical: isLexical,\n padLeft: padLeft,\n StringBuffer: StringBuffer,\n unescapeCodePoint: unescapeCodePoint,\n unexpectedObjToString: unexpectedObjToString\n});\n\n// These are just categories that are used in ES5/ES2015.\n// The full list of Unicode categories is here: http://www.fileformat.info/info/unicode/category/index.htm.\nconst UnicodeCategories = {\n // Letters\n Lu: /\\p{Lu}/u,\n Ll: /\\p{Ll}/u,\n Lt: /\\p{Lt}/u,\n Lm: /\\p{Lm}/u,\n Lo: /\\p{Lo}/u,\n\n // Numbers\n Nl: /\\p{Nl}/u,\n Nd: /\\p{Nd}/u,\n\n // Marks\n Mn: /\\p{Mn}/u,\n Mc: /\\p{Mc}/u,\n\n // Punctuation, Connector\n Pc: /\\p{Pc}/u,\n\n // Separator, Space\n Zs: /\\p{Zs}/u,\n\n // These two are not real Unicode categories, but our useful for Ohm.\n // L is a combination of all the letter categories.\n // Ltmo is a combination of Lt, Lm, and Lo.\n L: /\\p{Letter}/u,\n Ltmo: /\\p{Lt}|\\p{Lm}|\\p{Lo}/u,\n};\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\n// General stuff\n\nclass PExpr {\n constructor() {\n if (this.constructor === PExpr) {\n throw new Error(\"PExpr cannot be instantiated -- it's abstract\");\n }\n }\n\n // Set the `source` property to the interval containing the source for this expression.\n withSource(interval) {\n if (interval) {\n this.source = interval.trimmed();\n }\n return this;\n }\n}\n\n// Any\n\nconst any = Object.create(PExpr.prototype);\n\n// End\n\nconst end = Object.create(PExpr.prototype);\n\n// Terminals\n\nclass Terminal extends PExpr {\n constructor(obj) {\n super();\n this.obj = obj;\n }\n}\n\n// Ranges\n\nclass Range extends PExpr {\n constructor(from, to) {\n super();\n this.from = from;\n this.to = to;\n // If either `from` or `to` is made up of multiple code units, then\n // the range should consume a full code point, not a single code unit.\n this.matchCodePoint = from.length > 1 || to.length > 1;\n }\n}\n\n// Parameters\n\nclass Param extends PExpr {\n constructor(index) {\n super();\n this.index = index;\n }\n}\n\n// Alternation\n\nclass Alt extends PExpr {\n constructor(terms) {\n super();\n this.terms = terms;\n }\n}\n\n// Extend is an implementation detail of rule extension\n\nclass Extend extends Alt {\n constructor(superGrammar, name, body) {\n const origBody = superGrammar.rules[name].body;\n super([body, origBody]);\n\n this.superGrammar = superGrammar;\n this.name = name;\n this.body = body;\n }\n}\n\n// Splice is an implementation detail of rule overriding with the `...` operator.\nclass Splice extends Alt {\n constructor(superGrammar, ruleName, beforeTerms, afterTerms) {\n const origBody = superGrammar.rules[ruleName].body;\n super([...beforeTerms, origBody, ...afterTerms]);\n\n this.superGrammar = superGrammar;\n this.ruleName = ruleName;\n this.expansionPos = beforeTerms.length;\n }\n}\n\n// Sequences\n\nclass Seq extends PExpr {\n constructor(factors) {\n super();\n this.factors = factors;\n }\n}\n\n// Iterators and optionals\n\nclass Iter extends PExpr {\n constructor(expr) {\n super();\n this.expr = expr;\n }\n}\n\nclass Star extends Iter {}\nclass Plus extends Iter {}\nclass Opt extends Iter {}\n\nStar.prototype.operator = '*';\nPlus.prototype.operator = '+';\nOpt.prototype.operator = '?';\n\nStar.prototype.minNumMatches = 0;\nPlus.prototype.minNumMatches = 1;\nOpt.prototype.minNumMatches = 0;\n\nStar.prototype.maxNumMatches = Number.POSITIVE_INFINITY;\nPlus.prototype.maxNumMatches = Number.POSITIVE_INFINITY;\nOpt.prototype.maxNumMatches = 1;\n\n// Predicates\n\nclass Not extends PExpr {\n constructor(expr) {\n super();\n this.expr = expr;\n }\n}\n\nclass Lookahead extends PExpr {\n constructor(expr) {\n super();\n this.expr = expr;\n }\n}\n\n// \"Lexification\"\n\nclass Lex extends PExpr {\n constructor(expr) {\n super();\n this.expr = expr;\n }\n}\n\n// Rule application\n\nclass Apply extends PExpr {\n constructor(ruleName, args = []) {\n super();\n this.ruleName = ruleName;\n this.args = args;\n }\n\n isSyntactic() {\n return isSyntactic(this.ruleName);\n }\n\n // This method just caches the result of `this.toString()` in a non-enumerable property.\n toMemoKey() {\n if (!this._memoKey) {\n Object.defineProperty(this, '_memoKey', {value: this.toString()});\n }\n return this._memoKey;\n }\n}\n\n// Unicode character\n\nclass UnicodeChar extends PExpr {\n constructor(category) {\n super();\n this.category = category;\n this.pattern = UnicodeCategories[category];\n }\n}\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nfunction createError(message, optInterval) {\n let e;\n if (optInterval) {\n e = new Error(optInterval.getLineAndColumnMessage() + message);\n e.shortMessage = message;\n e.interval = optInterval;\n } else {\n e = new Error(message);\n }\n return e;\n}\n\n// ----------------- errors about intervals -----------------\n\nfunction intervalSourcesDontMatch() {\n return createError(\"Interval sources don't match\");\n}\n\n// ----------------- errors about grammars -----------------\n\n// Grammar syntax error\n\nfunction grammarSyntaxError(matchFailure) {\n const e = new Error();\n Object.defineProperty(e, 'message', {\n enumerable: true,\n get() {\n return matchFailure.message;\n },\n });\n Object.defineProperty(e, 'shortMessage', {\n enumerable: true,\n get() {\n return 'Expected ' + matchFailure.getExpectedText();\n },\n });\n e.interval = matchFailure.getInterval();\n return e;\n}\n\n// Undeclared grammar\n\nfunction undeclaredGrammar(grammarName, namespace, interval) {\n const message = namespace ?\n `Grammar ${grammarName} is not declared in namespace '${namespace}'` :\n 'Undeclared grammar ' + grammarName;\n return createError(message, interval);\n}\n\n// Duplicate grammar declaration\n\nfunction duplicateGrammarDeclaration(grammar, namespace) {\n return createError('Grammar ' + grammar.name + ' is already declared in this namespace');\n}\n\nfunction grammarDoesNotSupportIncrementalParsing(grammar) {\n return createError(`Grammar '${grammar.name}' does not support incremental parsing`);\n}\n\n// ----------------- rules -----------------\n\n// Undeclared rule\n\nfunction undeclaredRule(ruleName, grammarName, optInterval) {\n return createError(\n 'Rule ' + ruleName + ' is not declared in grammar ' + grammarName,\n optInterval,\n );\n}\n\n// Cannot override undeclared rule\n\nfunction cannotOverrideUndeclaredRule(ruleName, grammarName, optSource) {\n return createError(\n 'Cannot override rule ' + ruleName + ' because it is not declared in ' + grammarName,\n optSource,\n );\n}\n\n// Cannot extend undeclared rule\n\nfunction cannotExtendUndeclaredRule(ruleName, grammarName, optSource) {\n return createError(\n 'Cannot extend rule ' + ruleName + ' because it is not declared in ' + grammarName,\n optSource,\n );\n}\n\n// Duplicate rule declaration\n\nfunction duplicateRuleDeclaration(ruleName, grammarName, declGrammarName, optSource) {\n let message =\n \"Duplicate declaration for rule '\" + ruleName + \"' in grammar '\" + grammarName + \"'\";\n if (grammarName !== declGrammarName) {\n message += \" (originally declared in '\" + declGrammarName + \"')\";\n }\n return createError(message, optSource);\n}\n\n// Wrong number of parameters\n\nfunction wrongNumberOfParameters(ruleName, expected, actual, source) {\n return createError(\n 'Wrong number of parameters for rule ' +\n ruleName +\n ' (expected ' +\n expected +\n ', got ' +\n actual +\n ')',\n source,\n );\n}\n\n// Wrong number of arguments\n\nfunction wrongNumberOfArguments(ruleName, expected, actual, expr) {\n return createError(\n 'Wrong number of arguments for rule ' +\n ruleName +\n ' (expected ' +\n expected +\n ', got ' +\n actual +\n ')',\n expr,\n );\n}\n\n// Duplicate parameter names\n\nfunction duplicateParameterNames(ruleName, duplicates, source) {\n return createError(\n 'Duplicate parameter names in rule ' + ruleName + ': ' + duplicates.join(', '),\n source,\n );\n}\n\n// Invalid parameter expression\n\nfunction invalidParameter(ruleName, expr) {\n return createError(\n 'Invalid parameter to rule ' +\n ruleName +\n ': ' +\n expr +\n ' has arity ' +\n expr.getArity() +\n ', but parameter expressions must have arity 1',\n expr.source,\n );\n}\n\n// Application of syntactic rule from lexical rule\n\nconst syntacticVsLexicalNote =\n 'NOTE: A _syntactic rule_ is a rule whose name begins with a capital letter. ' +\n 'See https://ohmjs.org/d/svl for more details.';\n\nfunction applicationOfSyntacticRuleFromLexicalContext(ruleName, applyExpr) {\n return createError(\n 'Cannot apply syntactic rule ' + ruleName + ' from here (inside a lexical context)',\n applyExpr.source,\n );\n}\n\n// Lexical rule application used with applySyntactic\n\nfunction applySyntacticWithLexicalRuleApplication(applyExpr) {\n const {ruleName} = applyExpr;\n return createError(\n `applySyntactic is for syntactic rules, but '${ruleName}' is a lexical rule. ` +\n syntacticVsLexicalNote,\n applyExpr.source,\n );\n}\n\n// Application of applySyntactic in a syntactic context\n\nfunction unnecessaryExperimentalApplySyntactic(applyExpr) {\n return createError(\n 'applySyntactic is not required here (in a syntactic context)',\n applyExpr.source,\n );\n}\n\n// Incorrect argument type\n\nfunction incorrectArgumentType(expectedType, expr) {\n return createError('Incorrect argument type: expected ' + expectedType, expr.source);\n}\n\n// Multiple instances of the super-splice operator (`...`) in the rule body.\n\nfunction multipleSuperSplices(expr) {\n return createError(\"'...' can appear at most once in a rule body\", expr.source);\n}\n\n// Unicode code point escapes\n\nfunction invalidCodePoint(applyWrapper) {\n const node = applyWrapper._node;\n assert(node && node.isNonterminal() && node.ctorName === 'escapeChar_unicodeCodePoint');\n\n // Get an interval that covers all of the hex digits.\n const digitIntervals = applyWrapper.children.slice(1, -1).map(d => d.source);\n const fullInterval = digitIntervals[0].coverageWith(...digitIntervals.slice(1));\n return createError(\n `U+${fullInterval.contents} is not a valid Unicode code point`,\n fullInterval,\n );\n}\n\n// ----------------- Kleene operators -----------------\n\nfunction kleeneExprHasNullableOperand(kleeneExpr, applicationStack) {\n const actuals =\n applicationStack.length > 0 ? applicationStack[applicationStack.length - 1].args : [];\n const expr = kleeneExpr.expr.substituteParams(actuals);\n let message =\n 'Nullable expression ' +\n expr +\n \" is not allowed inside '\" +\n kleeneExpr.operator +\n \"' (possible infinite loop)\";\n if (applicationStack.length > 0) {\n const stackTrace = applicationStack\n .map(app => new Apply(app.ruleName, app.args))\n .join('\\n');\n message += '\\nApplication stack (most recent application last):\\n' + stackTrace;\n }\n return createError(message, kleeneExpr.expr.source);\n}\n\n// ----------------- arity -----------------\n\nfunction inconsistentArity(ruleName, expected, actual, expr) {\n return createError(\n 'Rule ' +\n ruleName +\n ' involves an alternation which has inconsistent arity ' +\n '(expected ' +\n expected +\n ', got ' +\n actual +\n ')',\n expr.source,\n );\n}\n\n// ----------------- convenience -----------------\n\nfunction multipleErrors(errors) {\n const messages = errors.map(e => e.message);\n return createError(['Errors:'].concat(messages).join('\\n- '), errors[0].interval);\n}\n\n// ----------------- semantic -----------------\n\nfunction missingSemanticAction(ctorName, name, type, stack) {\n let stackTrace = stack\n .slice(0, -1)\n .map(info => {\n const ans = ' ' + info[0].name + ' > ' + info[1];\n return info.length === 3 ? ans + \" for '\" + info[2] + \"'\" : ans;\n })\n .join('\\n');\n stackTrace += '\\n ' + name + ' > ' + ctorName;\n\n let moreInfo = '';\n if (ctorName === '_iter') {\n moreInfo = [\n '\\nNOTE: as of Ohm v16, there is no default action for iteration nodes — see ',\n ' https://ohmjs.org/d/dsa for details.',\n ].join('\\n');\n }\n\n const message = [\n `Missing semantic action for '${ctorName}' in ${type} '${name}'.${moreInfo}`,\n 'Action stack (most recent call last):',\n stackTrace,\n ].join('\\n');\n\n const e = createError(message);\n e.name = 'missingSemanticAction';\n return e;\n}\n\nfunction throwErrors(errors) {\n if (errors.length === 1) {\n throw errors[0];\n }\n if (errors.length > 1) {\n throw multipleErrors(errors);\n }\n}\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\n// Given an array of numbers `arr`, return an array of the numbers as strings,\n// right-justified and padded to the same length.\nfunction padNumbersToEqualLength(arr) {\n let maxLen = 0;\n const strings = arr.map(n => {\n const str = n.toString();\n maxLen = Math.max(maxLen, str.length);\n return str;\n });\n return strings.map(s => padLeft(s, maxLen));\n}\n\n// Produce a new string that would be the result of copying the contents\n// of the string `src` onto `dest` at offset `offest`.\nfunction strcpy(dest, src, offset) {\n const origDestLen = dest.length;\n const start = dest.slice(0, offset);\n const end = dest.slice(offset + src.length);\n return (start + src + end).substr(0, origDestLen);\n}\n\n// Casts the underlying lineAndCol object to a formatted message string,\n// highlighting `ranges`.\nfunction lineAndColumnToMessage(...ranges) {\n const lineAndCol = this;\n const {offset} = lineAndCol;\n const {repeatStr} = common;\n\n const sb = new StringBuffer();\n sb.append('Line ' + lineAndCol.lineNum + ', col ' + lineAndCol.colNum + ':\\n');\n\n // An array of the previous, current, and next line numbers as strings of equal length.\n const lineNumbers = padNumbersToEqualLength([\n lineAndCol.prevLine == null ? 0 : lineAndCol.lineNum - 1,\n lineAndCol.lineNum,\n lineAndCol.nextLine == null ? 0 : lineAndCol.lineNum + 1,\n ]);\n\n // Helper for appending formatting input lines to the buffer.\n const appendLine = (num, content, prefix) => {\n sb.append(prefix + lineNumbers[num] + ' | ' + content + '\\n');\n };\n\n // Include the previous line for context if possible.\n if (lineAndCol.prevLine != null) {\n appendLine(0, lineAndCol.prevLine, ' ');\n }\n // Line that the error occurred on.\n appendLine(1, lineAndCol.line, '> ');\n\n // Build up the line that points to the offset and possible indicates one or more ranges.\n // Start with a blank line, and indicate each range by overlaying a string of `~` chars.\n const lineLen = lineAndCol.line.length;\n let indicationLine = repeatStr(' ', lineLen + 1);\n for (let i = 0; i < ranges.length; ++i) {\n let startIdx = ranges[i][0];\n let endIdx = ranges[i][1];\n assert(startIdx >= 0 && startIdx <= endIdx, 'range start must be >= 0 and <= end');\n\n const lineStartOffset = offset - lineAndCol.colNum + 1;\n startIdx = Math.max(0, startIdx - lineStartOffset);\n endIdx = Math.min(endIdx - lineStartOffset, lineLen);\n\n indicationLine = strcpy(indicationLine, repeatStr('~', endIdx - startIdx), startIdx);\n }\n const gutterWidth = 2 + lineNumbers[1].length + 3;\n sb.append(repeatStr(' ', gutterWidth));\n indicationLine = strcpy(indicationLine, '^', lineAndCol.colNum - 1);\n sb.append(indicationLine.replace(/ +$/, '') + '\\n');\n\n // Include the next line for context if possible.\n if (lineAndCol.nextLine != null) {\n appendLine(2, lineAndCol.nextLine, ' ');\n }\n return sb.contents();\n}\n\n// --------------------------------------------------------------------\n// Exports\n// --------------------------------------------------------------------\n\nlet builtInRulesCallbacks = [];\n\n// Since Grammar.BuiltInRules is bootstrapped, most of Ohm can't directly depend it.\n// This function allows modules that do depend on the built-in rules to register a callback\n// that will be called later in the initialization process.\nfunction awaitBuiltInRules(cb) {\n builtInRulesCallbacks.push(cb);\n}\n\nfunction announceBuiltInRules(grammar) {\n builtInRulesCallbacks.forEach(cb => {\n cb(grammar);\n });\n builtInRulesCallbacks = null;\n}\n\n// Return an object with the line and column information for the given\n// offset in `str`.\nfunction getLineAndColumn(str, offset) {\n let lineNum = 1;\n let colNum = 1;\n\n let currOffset = 0;\n let lineStartOffset = 0;\n\n let nextLine = null;\n let prevLine = null;\n let prevLineStartOffset = -1;\n\n while (currOffset < offset) {\n const c = str.charAt(currOffset++);\n if (c === '\\n') {\n lineNum++;\n colNum = 1;\n prevLineStartOffset = lineStartOffset;\n lineStartOffset = currOffset;\n } else if (c !== '\\r') {\n colNum++;\n }\n }\n\n // Find the end of the target line.\n let lineEndOffset = str.indexOf('\\n', lineStartOffset);\n if (lineEndOffset === -1) {\n lineEndOffset = str.length;\n } else {\n // Get the next line.\n const nextLineEndOffset = str.indexOf('\\n', lineEndOffset + 1);\n nextLine =\n nextLineEndOffset === -1 ?\n str.slice(lineEndOffset) :\n str.slice(lineEndOffset, nextLineEndOffset);\n // Strip leading and trailing EOL char(s).\n nextLine = nextLine.replace(/^\\r?\\n/, '').replace(/\\r$/, '');\n }\n\n // Get the previous line.\n if (prevLineStartOffset >= 0) {\n // Strip trailing EOL char(s).\n prevLine = str.slice(prevLineStartOffset, lineStartOffset).replace(/\\r?\\n$/, '');\n }\n\n // Get the target line, stripping a trailing carriage return if necessary.\n const line = str.slice(lineStartOffset, lineEndOffset).replace(/\\r$/, '');\n\n return {\n offset,\n lineNum,\n colNum,\n line,\n prevLine,\n nextLine,\n toString: lineAndColumnToMessage,\n };\n}\n\n// Return a nicely-formatted string describing the line and column for the\n// given offset in `str` highlighting `ranges`.\nfunction getLineAndColumnMessage(str, offset, ...ranges) {\n return getLineAndColumn(str, offset).toString(...ranges);\n}\n\nconst uniqueId = (() => {\n let idCounter = 0;\n return prefix => '' + prefix + idCounter++;\n})();\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nclass Interval {\n constructor(sourceString, startIdx, endIdx) {\n this.sourceString = sourceString;\n this.startIdx = startIdx;\n this.endIdx = endIdx;\n }\n\n get contents() {\n if (this._contents === undefined) {\n this._contents = this.sourceString.slice(this.startIdx, this.endIdx);\n }\n return this._contents;\n }\n\n get length() {\n return this.endIdx - this.startIdx;\n }\n\n coverageWith(...intervals) {\n return Interval.coverage(...intervals, this);\n }\n\n collapsedLeft() {\n return new Interval(this.sourceString, this.startIdx, this.startIdx);\n }\n\n collapsedRight() {\n return new Interval(this.sourceString, this.endIdx, this.endIdx);\n }\n\n getLineAndColumn() {\n return getLineAndColumn(this.sourceString, this.startIdx);\n }\n\n getLineAndColumnMessage() {\n const range = [this.startIdx, this.endIdx];\n return getLineAndColumnMessage(this.sourceString, this.startIdx, range);\n }\n\n // Returns an array of 0, 1, or 2 intervals that represents the result of the\n // interval difference operation.\n minus(that) {\n if (this.sourceString !== that.sourceString) {\n throw intervalSourcesDontMatch();\n } else if (this.startIdx === that.startIdx && this.endIdx === that.endIdx) {\n // `this` and `that` are the same interval!\n return [];\n } else if (this.startIdx < that.startIdx && that.endIdx < this.endIdx) {\n // `that` splits `this` into two intervals\n return [\n new Interval(this.sourceString, this.startIdx, that.startIdx),\n new Interval(this.sourceString, that.endIdx, this.endIdx),\n ];\n } else if (this.startIdx < that.endIdx && that.endIdx < this.endIdx) {\n // `that` contains a prefix of `this`\n return [new Interval(this.sourceString, that.endIdx, this.endIdx)];\n } else if (this.startIdx < that.startIdx && that.startIdx < this.endIdx) {\n // `that` contains a suffix of `this`\n return [new Interval(this.sourceString, this.startIdx, that.startIdx)];\n } else {\n // `that` and `this` do not overlap\n return [this];\n }\n }\n\n // Returns a new Interval that has the same extent as this one, but which is relative\n // to `that`, an Interval that fully covers this one.\n relativeTo(that) {\n if (this.sourceString !== that.sourceString) {\n throw intervalSourcesDontMatch();\n }\n assert(\n this.startIdx >= that.startIdx && this.endIdx <= that.endIdx,\n 'other interval does not cover this one',\n );\n return new Interval(\n this.sourceString,\n this.startIdx - that.startIdx,\n this.endIdx - that.startIdx,\n );\n }\n\n // Returns a new Interval which contains the same contents as this one,\n // but with whitespace trimmed from both ends.\n trimmed() {\n const {contents} = this;\n const startIdx = this.startIdx + contents.match(/^\\s*/)[0].length;\n const endIdx = this.endIdx - contents.match(/\\s*$/)[0].length;\n return new Interval(this.sourceString, startIdx, endIdx);\n }\n\n subInterval(offset, len) {\n const newStartIdx = this.startIdx + offset;\n return new Interval(this.sourceString, newStartIdx, newStartIdx + len);\n }\n}\n\nInterval.coverage = function(firstInterval, ...intervals) {\n let {startIdx, endIdx} = firstInterval;\n for (const interval of intervals) {\n if (interval.sourceString !== firstInterval.sourceString) {\n throw intervalSourcesDontMatch();\n } else {\n startIdx = Math.min(startIdx, interval.startIdx);\n endIdx = Math.max(endIdx, interval.endIdx);\n }\n }\n return new Interval(firstInterval.sourceString, startIdx, endIdx);\n};\n\nconst MAX_CHAR_CODE = 0xffff;\n\nclass InputStream {\n constructor(source) {\n this.source = source;\n this.pos = 0;\n this.examinedLength = 0;\n }\n\n atEnd() {\n const ans = this.pos >= this.source.length;\n this.examinedLength = Math.max(this.examinedLength, this.pos + 1);\n return ans;\n }\n\n next() {\n const ans = this.source[this.pos++];\n this.examinedLength = Math.max(this.examinedLength, this.pos);\n return ans;\n }\n\n nextCharCode() {\n const nextChar = this.next();\n return nextChar && nextChar.charCodeAt(0);\n }\n\n nextCodePoint() {\n const cp = this.source.slice(this.pos++).codePointAt(0);\n // If the code point is beyond plane 0, it takes up two characters.\n if (cp > MAX_CHAR_CODE) {\n this.pos += 1;\n }\n this.examinedLength = Math.max(this.examinedLength, this.pos);\n return cp;\n }\n\n matchString(s, optIgnoreCase) {\n let idx;\n if (optIgnoreCase) {\n /*\n Case-insensitive comparison is a tricky business. Some notable gotchas include the\n \"Turkish I\" problem (http://www.i18nguy.com/unicode/turkish-i18n.html) and the fact\n that the German Esszet (ß) turns into \"SS\" in upper case.\n\n This is intended to be a locale-invariant comparison, which means it may not obey\n locale-specific expectations (e.g. \"i\" => \"İ\").\n */\n for (idx = 0; idx < s.length; idx++) {\n const actual = this.next();\n const expected = s[idx];\n if (actual == null || actual.toUpperCase() !== expected.toUpperCase()) {\n return false;\n }\n }\n return true;\n }\n // Default is case-sensitive comparison.\n for (idx = 0; idx < s.length; idx++) {\n if (this.next() !== s[idx]) {\n return false;\n }\n }\n return true;\n }\n\n sourceSlice(startIdx, endIdx) {\n return this.source.slice(startIdx, endIdx);\n }\n\n interval(startIdx, optEndIdx) {\n return new Interval(this.source, startIdx, optEndIdx ? optEndIdx : this.pos);\n }\n}\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nclass MatchResult {\n constructor(\n matcher,\n input,\n startExpr,\n cst,\n cstOffset,\n rightmostFailurePosition,\n optRecordedFailures,\n ) {\n this.matcher = matcher;\n this.input = input;\n this.startExpr = startExpr;\n this._cst = cst;\n this._cstOffset = cstOffset;\n this._rightmostFailurePosition = rightmostFailurePosition;\n this._rightmostFailures = optRecordedFailures;\n\n if (this.failed()) {\n /* eslint-disable no-invalid-this */\n defineLazyProperty(this, 'message', function() {\n const detail = 'Expected ' + this.getExpectedText();\n return (\n getLineAndColumnMessage(this.input, this.getRightmostFailurePosition()) + detail\n );\n });\n defineLazyProperty(this, 'shortMessage', function() {\n const detail = 'expected ' + this.getExpectedText();\n const errorInfo = getLineAndColumn(\n this.input,\n this.getRightmostFailurePosition(),\n );\n return 'Line ' + errorInfo.lineNum + ', col ' + errorInfo.colNum + ': ' + detail;\n });\n /* eslint-enable no-invalid-this */\n }\n }\n\n succeeded() {\n return !!this._cst;\n }\n\n failed() {\n return !this.succeeded();\n }\n\n getRightmostFailurePosition() {\n return this._rightmostFailurePosition;\n }\n\n getRightmostFailures() {\n if (!this._rightmostFailures) {\n this.matcher.setInput(this.input);\n const matchResultWithFailures = this.matcher._match(this.startExpr, {\n tracing: false,\n positionToRecordFailures: this.getRightmostFailurePosition(),\n });\n this._rightmostFailures = matchResultWithFailures.getRightmostFailures();\n }\n return this._rightmostFailures;\n }\n\n toString() {\n return this.succeeded() ?\n '[match succeeded]' :\n '[match failed at position ' + this.getRightmostFailurePosition() + ']';\n }\n\n // Return a string summarizing the expected contents of the input stream when\n // the match failure occurred.\n getExpectedText() {\n if (this.succeeded()) {\n throw new Error('cannot get expected text of a successful MatchResult');\n }\n\n const sb = new StringBuffer();\n let failures = this.getRightmostFailures();\n\n // Filter out the fluffy failures to make the default error messages more useful\n failures = failures.filter(failure => !failure.isFluffy());\n\n for (let idx = 0; idx < failures.length; idx++) {\n if (idx > 0) {\n if (idx === failures.length - 1) {\n sb.append(failures.length > 2 ? ', or ' : ' or ');\n } else {\n sb.append(', ');\n }\n }\n sb.append(failures[idx].toString());\n }\n return sb.contents();\n }\n\n getInterval() {\n const pos = this.getRightmostFailurePosition();\n return new Interval(this.input, pos, pos);\n }\n}\n\nclass PosInfo {\n constructor() {\n this.applicationMemoKeyStack = []; // active applications at this position\n this.memo = {};\n this.maxExaminedLength = 0;\n this.maxRightmostFailureOffset = -1;\n this.currentLeftRecursion = undefined;\n }\n\n isActive(application) {\n return this.applicationMemoKeyStack.indexOf(application.toMemoKey()) >= 0;\n }\n\n enter(application) {\n this.applicationMemoKeyStack.push(application.toMemoKey());\n }\n\n exit() {\n this.applicationMemoKeyStack.pop();\n }\n\n startLeftRecursion(headApplication, memoRec) {\n memoRec.isLeftRecursion = true;\n memoRec.headApplication = headApplication;\n memoRec.nextLeftRecursion = this.currentLeftRecursion;\n this.currentLeftRecursion = memoRec;\n\n const {applicationMemoKeyStack} = this;\n const indexOfFirstInvolvedRule =\n applicationMemoKeyStack.indexOf(headApplication.toMemoKey()) + 1;\n const involvedApplicationMemoKeys = applicationMemoKeyStack.slice(\n indexOfFirstInvolvedRule,\n );\n\n memoRec.isInvolved = function(applicationMemoKey) {\n return involvedApplicationMemoKeys.indexOf(applicationMemoKey) >= 0;\n };\n\n memoRec.updateInvolvedApplicationMemoKeys = function() {\n for (let idx = indexOfFirstInvolvedRule; idx < applicationMemoKeyStack.length; idx++) {\n const applicationMemoKey = applicationMemoKeyStack[idx];\n if (!this.isInvolved(applicationMemoKey)) {\n involvedApplicationMemoKeys.push(applicationMemoKey);\n }\n }\n };\n }\n\n endLeftRecursion() {\n this.currentLeftRecursion = this.currentLeftRecursion.nextLeftRecursion;\n }\n\n // Note: this method doesn't get called for the \"head\" of a left recursion -- for LR heads,\n // the memoized result (which starts out being a failure) is always used.\n shouldUseMemoizedResult(memoRec) {\n if (!memoRec.isLeftRecursion) {\n return true;\n }\n const {applicationMemoKeyStack} = this;\n for (let idx = 0; idx < applicationMemoKeyStack.length; idx++) {\n const applicationMemoKey = applicationMemoKeyStack[idx];\n if (memoRec.isInvolved(applicationMemoKey)) {\n return false;\n }\n }\n return true;\n }\n\n memoize(memoKey, memoRec) {\n this.memo[memoKey] = memoRec;\n this.maxExaminedLength = Math.max(this.maxExaminedLength, memoRec.examinedLength);\n this.maxRightmostFailureOffset = Math.max(\n this.maxRightmostFailureOffset,\n memoRec.rightmostFailureOffset,\n );\n return memoRec;\n }\n\n clearObsoleteEntries(pos, invalidatedIdx) {\n if (pos + this.maxExaminedLength <= invalidatedIdx) {\n // Optimization: none of the rule applications that were memoized here examined the\n // interval of the input that changed, so nothing has to be invalidated.\n return;\n }\n\n const {memo} = this;\n this.maxExaminedLength = 0;\n this.maxRightmostFailureOffset = -1;\n Object.keys(memo).forEach(k => {\n const memoRec = memo[k];\n if (pos + memoRec.examinedLength > invalidatedIdx) {\n delete memo[k];\n } else {\n this.maxExaminedLength = Math.max(this.maxExaminedLength, memoRec.examinedLength);\n this.maxRightmostFailureOffset = Math.max(\n this.maxRightmostFailureOffset,\n memoRec.rightmostFailureOffset,\n );\n }\n });\n }\n}\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\n// Unicode characters that are used in the `toString` output.\nconst BALLOT_X = '\\u2717';\nconst CHECK_MARK = '\\u2713';\nconst DOT_OPERATOR = '\\u22C5';\nconst RIGHTWARDS_DOUBLE_ARROW = '\\u21D2';\nconst SYMBOL_FOR_HORIZONTAL_TABULATION = '\\u2409';\nconst SYMBOL_FOR_LINE_FEED = '\\u240A';\nconst SYMBOL_FOR_CARRIAGE_RETURN = '\\u240D';\n\nconst Flags = {\n succeeded: 1 << 0,\n isRootNode: 1 << 1,\n isImplicitSpaces: 1 << 2,\n isMemoized: 1 << 3,\n isHeadOfLeftRecursion: 1 << 4,\n terminatesLR: 1 << 5,\n};\n\nfunction spaces(n) {\n return repeat(' ', n).join('');\n}\n\n// Return a string representation of a portion of `input` at offset `pos`.\n// The result will contain exactly `len` characters.\nfunction getInputExcerpt(input, pos, len) {\n const excerpt = asEscapedString(input.slice(pos, pos + len));\n\n // Pad the output if necessary.\n if (excerpt.length < len) {\n return excerpt + repeat(' ', len - excerpt.length).join('');\n }\n return excerpt;\n}\n\nfunction asEscapedString(obj) {\n if (typeof obj === 'string') {\n // Replace non-printable characters with visible symbols.\n return obj\n .replace(/ /g, DOT_OPERATOR)\n .replace(/\\t/g, SYMBOL_FOR_HORIZONTAL_TABULATION)\n .replace(/\\n/g, SYMBOL_FOR_LINE_FEED)\n .replace(/\\r/g, SYMBOL_FOR_CARRIAGE_RETURN);\n }\n return String(obj);\n}\n\n// ----------------- Trace -----------------\n\nclass Trace {\n constructor(input, pos1, pos2, expr, succeeded, bindings, optChildren) {\n this.input = input;\n this.pos = this.pos1 = pos1;\n this.pos2 = pos2;\n this.source = new Interval(input, pos1, pos2);\n this.expr = expr;\n this.bindings = bindings;\n this.children = optChildren || [];\n this.terminatingLREntry = null;\n\n this._flags = succeeded ? Flags.succeeded : 0;\n }\n\n get displayString() {\n return this.expr.toDisplayString();\n }\n\n clone() {\n return this.cloneWithExpr(this.expr);\n }\n\n cloneWithExpr(expr) {\n const ans = new Trace(\n this.input,\n this.pos,\n this.pos2,\n expr,\n this.succeeded,\n this.bindings,\n this.children,\n );\n\n ans.isHeadOfLeftRecursion = this.isHeadOfLeftRecursion;\n ans.isImplicitSpaces = this.isImplicitSpaces;\n ans.isMemoized = this.isMemoized;\n ans.isRootNode = this.isRootNode;\n ans.terminatesLR = this.terminatesLR;\n ans.terminatingLREntry = this.terminatingLREntry;\n return ans;\n }\n\n // Record the trace information for the terminating condition of the LR loop.\n recordLRTermination(ruleBodyTrace, value) {\n this.terminatingLREntry = new Trace(\n this.input,\n this.pos,\n this.pos2,\n this.expr,\n false,\n [value],\n [ruleBodyTrace],\n );\n this.terminatingLREntry.terminatesLR = true;\n }\n\n // Recursively traverse this trace node and all its descendents, calling a visitor function\n // for each node that is visited. If `vistorObjOrFn` is an object, then its 'enter' property\n // is a function to call before visiting the children of a node, and its 'exit' property is\n // a function to call afterwards. If `visitorObjOrFn` is a function, it represents the 'enter'\n // function.\n //\n // The functions are called with three arguments: the Trace node, its parent Trace, and a number\n // representing the depth of the node in the tree. (The root node has depth 0.) `optThisArg`, if\n // specified, is the value to use for `this` when executing the visitor functions.\n walk(visitorObjOrFn, optThisArg) {\n let visitor = visitorObjOrFn;\n if (typeof visitor === 'function') {\n visitor = {enter: visitor};\n }\n\n function _walk(node, parent, depth) {\n let recurse = true;\n if (visitor.enter) {\n if (visitor.enter.call(optThisArg, node, parent, depth) === Trace.prototype.SKIP) {\n recurse = false;\n }\n }\n if (recurse) {\n node.children.forEach(child => {\n _walk(child, node, depth + 1);\n });\n if (visitor.exit) {\n visitor.exit.call(optThisArg, node, parent, depth);\n }\n }\n }\n if (this.isRootNode) {\n // Don't visit the root node itself, only its children.\n this.children.forEach(c => {\n _walk(c, null, 0);\n });\n } else {\n _walk(this, null, 0);\n }\n }\n\n // Return a string representation of the trace.\n // Sample:\n // 12⋅+⋅2⋅*⋅3 ✓ exp ⇒ \"12\"\n // 12⋅+⋅2⋅*⋅3 ✓ addExp (LR) ⇒ \"12\"\n // 12⋅+⋅2⋅*⋅3 ✗ addExp_plus\n toString() {\n const sb = new StringBuffer();\n this.walk((node, parent, depth) => {\n if (!node) {\n return this.SKIP;\n }\n const ctorName = node.expr.constructor.name;\n // Don't print anything for Alt nodes.\n if (ctorName === 'Alt') {\n return; // eslint-disable-line consistent-return\n }\n sb.append(getInputExcerpt(node.input, node.pos, 10) + spaces(depth * 2 + 1));\n sb.append((node.succeeded ? CHECK_MARK : BALLOT_X) + ' ' + node.displayString);\n if (node.isHeadOfLeftRecursion) {\n sb.append(' (LR)');\n }\n if (node.succeeded) {\n const contents = asEscapedString(node.source.contents);\n sb.append(' ' + RIGHTWARDS_DOUBLE_ARROW + ' ');\n sb.append(typeof contents === 'string' ? '\"' + contents + '\"' : contents);\n }\n sb.append('\\n');\n });\n return sb.contents();\n }\n}\n\n// A value that can be returned from visitor functions to indicate that a\n// node should not be recursed into.\nTrace.prototype.SKIP = {};\n\n// For convenience, create a getter and setter for the boolean flags in `Flags`.\nObject.keys(Flags).forEach(name => {\n const mask = Flags[name];\n Object.defineProperty(Trace.prototype, name, {\n get() {\n return (this._flags & mask) !== 0;\n },\n set(val) {\n if (val) {\n this._flags |= mask;\n } else {\n this._flags &= ~mask;\n }\n },\n });\n});\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n/*\n Return true if we should skip spaces preceding this expression in a syntactic context.\n*/\nPExpr.prototype.allowsSkippingPrecedingSpace = abstract('allowsSkippingPrecedingSpace');\n\n/*\n Generally, these are all first-order expressions and (with the exception of Apply)\n directly read from the input stream.\n*/\nany.allowsSkippingPrecedingSpace =\n end.allowsSkippingPrecedingSpace =\n Apply.prototype.allowsSkippingPrecedingSpace =\n Terminal.prototype.allowsSkippingPrecedingSpace =\n Range.prototype.allowsSkippingPrecedingSpace =\n UnicodeChar.prototype.allowsSkippingPrecedingSpace =\n function() {\n return true;\n };\n\n/*\n Higher-order expressions that don't directly consume input.\n*/\nAlt.prototype.allowsSkippingPrecedingSpace =\n Iter.prototype.allowsSkippingPrecedingSpace =\n Lex.prototype.allowsSkippingPrecedingSpace =\n Lookahead.prototype.allowsSkippingPrecedingSpace =\n Not.prototype.allowsSkippingPrecedingSpace =\n Param.prototype.allowsSkippingPrecedingSpace =\n Seq.prototype.allowsSkippingPrecedingSpace =\n function() {\n return false;\n };\n\nlet BuiltInRules$1;\n\nawaitBuiltInRules(g => {\n BuiltInRules$1 = g;\n});\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\nlet lexifyCount;\n\nPExpr.prototype.assertAllApplicationsAreValid = function(ruleName, grammar) {\n lexifyCount = 0;\n this._assertAllApplicationsAreValid(ruleName, grammar);\n};\n\nPExpr.prototype._assertAllApplicationsAreValid = abstract(\n '_assertAllApplicationsAreValid',\n);\n\nany._assertAllApplicationsAreValid =\n end._assertAllApplicationsAreValid =\n Terminal.prototype._assertAllApplicationsAreValid =\n Range.prototype._assertAllApplicationsAreValid =\n Param.prototype._assertAllApplicationsAreValid =\n UnicodeChar.prototype._assertAllApplicationsAreValid =\n function(ruleName, grammar) {\n // no-op\n };\n\nLex.prototype._assertAllApplicationsAreValid = function(ruleName, grammar) {\n lexifyCount++;\n this.expr._assertAllApplicationsAreValid(ruleName, grammar);\n lexifyCount--;\n};\n\nAlt.prototype._assertAllApplicationsAreValid = function(ruleName, grammar) {\n for (let idx = 0; idx < this.terms.length; idx++) {\n this.terms[idx]._assertAllApplicationsAreValid(ruleName, grammar);\n }\n};\n\nSeq.prototype._assertAllApplicationsAreValid = function(ruleName, grammar) {\n for (let idx = 0; idx < this.factors.length; idx++) {\n this.factors[idx]._assertAllApplicationsAreValid(ruleName, grammar);\n }\n};\n\nIter.prototype._assertAllApplicationsAreValid =\n Not.prototype._assertAllApplicationsAreValid =\n Lookahead.prototype._assertAllApplicationsAreValid =\n function(ruleName, grammar) {\n this.expr._assertAllApplicationsAreValid(ruleName, grammar);\n };\n\nApply.prototype._assertAllApplicationsAreValid = function(\n ruleName,\n grammar,\n skipSyntacticCheck = false,\n) {\n const ruleInfo = grammar.rules[this.ruleName];\n const isContextSyntactic = isSyntactic(ruleName) && lexifyCount === 0;\n\n // Make sure that the rule exists...\n if (!ruleInfo) {\n throw undeclaredRule(this.ruleName, grammar.name, this.source);\n }\n\n // ...and that this application is allowed\n if (!skipSyntacticCheck && isSyntactic(this.ruleName) && !isContextSyntactic) {\n throw applicationOfSyntacticRuleFromLexicalContext(this.ruleName, this);\n }\n\n // ...and that this application has the correct number of arguments.\n const actual = this.args.length;\n const expected = ruleInfo.formals.length;\n if (actual !== expected) {\n throw wrongNumberOfArguments(this.ruleName, expected, actual, this.source);\n }\n\n const isBuiltInApplySyntactic =\n BuiltInRules$1 && ruleInfo === BuiltInRules$1.rules.applySyntactic;\n const isBuiltInCaseInsensitive =\n BuiltInRules$1 && ruleInfo === BuiltInRules$1.rules.caseInsensitive;\n\n // If it's an application of 'caseInsensitive', ensure that the argument is a Terminal.\n if (isBuiltInCaseInsensitive) {\n if (!(this.args[0] instanceof Terminal)) {\n throw incorrectArgumentType('a Terminal (e.g. \"abc\")', this.args[0]);\n }\n }\n\n if (isBuiltInApplySyntactic) {\n const arg = this.args[0];\n if (!(arg instanceof Apply)) {\n throw incorrectArgumentType('a syntactic rule application', arg);\n }\n if (!isSyntactic(arg.ruleName)) {\n throw applySyntacticWithLexicalRuleApplication(arg);\n }\n if (isContextSyntactic) {\n throw unnecessaryExperimentalApplySyntactic(this);\n }\n }\n\n // ...and that all of the argument expressions only have valid applications and have arity 1.\n // If `this` is an application of the built-in applySyntactic rule, then its arg is\n // allowed (and expected) to be a syntactic rule, even if we're in a lexical context.\n this.args.forEach(arg => {\n arg._assertAllApplicationsAreValid(ruleName, grammar, isBuiltInApplySyntactic);\n if (arg.getArity() !== 1) {\n throw invalidParameter(this.ruleName, arg);\n }\n });\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\nPExpr.prototype.assertChoicesHaveUniformArity = abstract(\n 'assertChoicesHaveUniformArity',\n);\n\nany.assertChoicesHaveUniformArity =\n end.assertChoicesHaveUniformArity =\n Terminal.prototype.assertChoicesHaveUniformArity =\n Range.prototype.assertChoicesHaveUniformArity =\n Param.prototype.assertChoicesHaveUniformArity =\n Lex.prototype.assertChoicesHaveUniformArity =\n UnicodeChar.prototype.assertChoicesHaveUniformArity =\n function(ruleName) {\n // no-op\n };\n\nAlt.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n if (this.terms.length === 0) {\n return;\n }\n const arity = this.terms[0].getArity();\n for (let idx = 0; idx < this.terms.length; idx++) {\n const term = this.terms[idx];\n term.assertChoicesHaveUniformArity();\n const otherArity = term.getArity();\n if (arity !== otherArity) {\n throw inconsistentArity(ruleName, arity, otherArity, term);\n }\n }\n};\n\nExtend.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n // Extend is a special case of Alt that's guaranteed to have exactly two\n // cases: [extensions, origBody].\n const actualArity = this.terms[0].getArity();\n const expectedArity = this.terms[1].getArity();\n if (actualArity !== expectedArity) {\n throw inconsistentArity(ruleName, expectedArity, actualArity, this.terms[0]);\n }\n};\n\nSeq.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n for (let idx = 0; idx < this.factors.length; idx++) {\n this.factors[idx].assertChoicesHaveUniformArity(ruleName);\n }\n};\n\nIter.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n this.expr.assertChoicesHaveUniformArity(ruleName);\n};\n\nNot.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n // no-op (not required b/c the nested expr doesn't show up in the CST)\n};\n\nLookahead.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n this.expr.assertChoicesHaveUniformArity(ruleName);\n};\n\nApply.prototype.assertChoicesHaveUniformArity = function(ruleName) {\n // The arities of the parameter expressions is required to be 1 by\n // `assertAllApplicationsAreValid()`.\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\nPExpr.prototype.assertIteratedExprsAreNotNullable = abstract(\n 'assertIteratedExprsAreNotNullable',\n);\n\nany.assertIteratedExprsAreNotNullable =\n end.assertIteratedExprsAreNotNullable =\n Terminal.prototype.assertIteratedExprsAreNotNullable =\n Range.prototype.assertIteratedExprsAreNotNullable =\n Param.prototype.assertIteratedExprsAreNotNullable =\n UnicodeChar.prototype.assertIteratedExprsAreNotNullable =\n function(grammar) {\n // no-op\n };\n\nAlt.prototype.assertIteratedExprsAreNotNullable = function(grammar) {\n for (let idx = 0; idx < this.terms.length; idx++) {\n this.terms[idx].assertIteratedExprsAreNotNullable(grammar);\n }\n};\n\nSeq.prototype.assertIteratedExprsAreNotNullable = function(grammar) {\n for (let idx = 0; idx < this.factors.length; idx++) {\n this.factors[idx].assertIteratedExprsAreNotNullable(grammar);\n }\n};\n\nIter.prototype.assertIteratedExprsAreNotNullable = function(grammar) {\n // Note: this is the implementation of this method for `Star` and `Plus` expressions.\n // It is overridden for `Opt` below.\n this.expr.assertIteratedExprsAreNotNullable(grammar);\n if (this.expr.isNullable(grammar)) {\n throw kleeneExprHasNullableOperand(this, []);\n }\n};\n\nOpt.prototype.assertIteratedExprsAreNotNullable =\n Not.prototype.assertIteratedExprsAreNotNullable =\n Lookahead.prototype.assertIteratedExprsAreNotNullable =\n Lex.prototype.assertIteratedExprsAreNotNullable =\n function(grammar) {\n this.expr.assertIteratedExprsAreNotNullable(grammar);\n };\n\nApply.prototype.assertIteratedExprsAreNotNullable = function(grammar) {\n this.args.forEach(arg => {\n arg.assertIteratedExprsAreNotNullable(grammar);\n });\n};\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nclass Node {\n constructor(matchLength) {\n this.matchLength = matchLength;\n }\n\n get ctorName() {\n throw new Error('subclass responsibility');\n }\n\n numChildren() {\n return this.children ? this.children.length : 0;\n }\n\n childAt(idx) {\n if (this.children) {\n return this.children[idx];\n }\n }\n\n indexOfChild(arg) {\n return this.children.indexOf(arg);\n }\n\n hasChildren() {\n return this.numChildren() > 0;\n }\n\n hasNoChildren() {\n return !this.hasChildren();\n }\n\n onlyChild() {\n if (this.numChildren() !== 1) {\n throw new Error(\n 'cannot get only child of a node of type ' +\n this.ctorName +\n ' (it has ' +\n this.numChildren() +\n ' children)',\n );\n } else {\n return this.firstChild();\n }\n }\n\n firstChild() {\n if (this.hasNoChildren()) {\n throw new Error(\n 'cannot get first child of a ' + this.ctorName + ' node, which has no children',\n );\n } else {\n return this.childAt(0);\n }\n }\n\n lastChild() {\n if (this.hasNoChildren()) {\n throw new Error(\n 'cannot get last child of a ' + this.ctorName + ' node, which has no children',\n );\n } else {\n return this.childAt(this.numChildren() - 1);\n }\n }\n\n childBefore(child) {\n const childIdx = this.indexOfChild(child);\n if (childIdx < 0) {\n throw new Error('Node.childBefore() called w/ an argument that is not a child');\n } else if (childIdx === 0) {\n throw new Error('cannot get child before first child');\n } else {\n return this.childAt(childIdx - 1);\n }\n }\n\n childAfter(child) {\n const childIdx = this.indexOfChild(child);\n if (childIdx < 0) {\n throw new Error('Node.childAfter() called w/ an argument that is not a child');\n } else if (childIdx === this.numChildren() - 1) {\n throw new Error('cannot get child after last child');\n } else {\n return this.childAt(childIdx + 1);\n }\n }\n\n isTerminal() {\n return false;\n }\n\n isNonterminal() {\n return false;\n }\n\n isIteration() {\n return false;\n }\n\n isOptional() {\n return false;\n }\n}\n\n// Terminals\n\nclass TerminalNode extends Node {\n get ctorName() {\n return '_terminal';\n }\n\n isTerminal() {\n return true;\n }\n\n get primitiveValue() {\n throw new Error('The `primitiveValue` property was removed in Ohm v17.');\n }\n}\n\n// Nonterminals\n\nclass NonterminalNode extends Node {\n constructor(ruleName, children, childOffsets, matchLength) {\n super(matchLength);\n this.ruleName = ruleName;\n this.children = children;\n this.childOffsets = childOffsets;\n }\n\n get ctorName() {\n return this.ruleName;\n }\n\n isNonterminal() {\n return true;\n }\n\n isLexical() {\n return isLexical(this.ctorName);\n }\n\n isSyntactic() {\n return isSyntactic(this.ctorName);\n }\n}\n\n// Iterations\n\nclass IterationNode extends Node {\n constructor(children, childOffsets, matchLength, isOptional) {\n super(matchLength);\n this.children = children;\n this.childOffsets = childOffsets;\n this.optional = isOptional;\n }\n\n get ctorName() {\n return '_iter';\n }\n\n isIteration() {\n return true;\n }\n\n isOptional() {\n return this.optional;\n }\n}\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n/*\n Evaluate the expression and return `true` if it succeeds, `false` otherwise. This method should\n only be called directly by `State.prototype.eval(expr)`, which also updates the data structures\n that are used for tracing. (Making those updates in a method of `State` enables the trace-specific\n data structures to be \"secrets\" of that class, which is good for modularity.)\n\n The contract of this method is as follows:\n * When the return value is `true`,\n - the state object will have `expr.getArity()` more bindings than it did before the call.\n * When the return value is `false`,\n - the state object may have more bindings than it did before the call, and\n - its input stream's position may be anywhere.\n\n Note that `State.prototype.eval(expr)`, unlike this method, guarantees that neither the state\n object's bindings nor its input stream's position will change if the expression fails to match.\n*/\nPExpr.prototype.eval = abstract('eval'); // function(state) { ... }\n\nany.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n const cp = inputStream.nextCodePoint();\n if (cp !== undefined) {\n state.pushBinding(new TerminalNode(String.fromCodePoint(cp).length), origPos);\n return true;\n } else {\n state.processFailure(origPos, this);\n return false;\n }\n};\n\nend.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n if (inputStream.atEnd()) {\n state.pushBinding(new TerminalNode(0), origPos);\n return true;\n } else {\n state.processFailure(origPos, this);\n return false;\n }\n};\n\nTerminal.prototype.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n if (!inputStream.matchString(this.obj)) {\n state.processFailure(origPos, this);\n return false;\n } else {\n state.pushBinding(new TerminalNode(this.obj.length), origPos);\n return true;\n }\n};\n\nRange.prototype.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n\n // A range can operate in one of two modes: matching a single, 16-bit _code unit_,\n // or matching a _code point_. (Code points over 0xFFFF take up two 16-bit code units.)\n const cp = this.matchCodePoint ? inputStream.nextCodePoint() : inputStream.nextCharCode();\n\n // Always compare by code point value to get the correct result in all scenarios.\n // Note that for strings of length 1, codePointAt(0) and charPointAt(0) are equivalent.\n if (cp !== undefined && this.from.codePointAt(0) <= cp && cp <= this.to.codePointAt(0)) {\n state.pushBinding(new TerminalNode(String.fromCodePoint(cp).length), origPos);\n return true;\n } else {\n state.processFailure(origPos, this);\n return false;\n }\n};\n\nParam.prototype.eval = function(state) {\n return state.eval(state.currentApplication().args[this.index]);\n};\n\nLex.prototype.eval = function(state) {\n state.enterLexifiedContext();\n const ans = state.eval(this.expr);\n state.exitLexifiedContext();\n return ans;\n};\n\nAlt.prototype.eval = function(state) {\n for (let idx = 0; idx < this.terms.length; idx++) {\n if (state.eval(this.terms[idx])) {\n return true;\n }\n }\n return false;\n};\n\nSeq.prototype.eval = function(state) {\n for (let idx = 0; idx < this.factors.length; idx++) {\n const factor = this.factors[idx];\n if (!state.eval(factor)) {\n return false;\n }\n }\n return true;\n};\n\nIter.prototype.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n const arity = this.getArity();\n const cols = [];\n const colOffsets = [];\n while (cols.length < arity) {\n cols.push([]);\n colOffsets.push([]);\n }\n\n let numMatches = 0;\n let prevPos = origPos;\n let idx;\n while (numMatches < this.maxNumMatches && state.eval(this.expr)) {\n if (inputStream.pos === prevPos) {\n throw kleeneExprHasNullableOperand(this, state._applicationStack);\n }\n prevPos = inputStream.pos;\n numMatches++;\n const row = state._bindings.splice(state._bindings.length - arity, arity);\n const rowOffsets = state._bindingOffsets.splice(\n state._bindingOffsets.length - arity,\n arity,\n );\n for (idx = 0; idx < row.length; idx++) {\n cols[idx].push(row[idx]);\n colOffsets[idx].push(rowOffsets[idx]);\n }\n }\n if (numMatches < this.minNumMatches) {\n return false;\n }\n let offset = state.posToOffset(origPos);\n let matchLength = 0;\n if (numMatches > 0) {\n const lastCol = cols[arity - 1];\n const lastColOffsets = colOffsets[arity - 1];\n\n const endOffset =\n lastColOffsets[lastColOffsets.length - 1] + lastCol[lastCol.length - 1].matchLength;\n offset = colOffsets[0][0];\n matchLength = endOffset - offset;\n }\n const isOptional = this instanceof Opt;\n for (idx = 0; idx < cols.length; idx++) {\n state._bindings.push(\n new IterationNode(cols[idx], colOffsets[idx], matchLength, isOptional),\n );\n state._bindingOffsets.push(offset);\n }\n return true;\n};\n\nNot.prototype.eval = function(state) {\n /*\n TODO:\n - Right now we're just throwing away all of the failures that happen inside a `not`, and\n recording `this` as a failed expression.\n - Double negation should be equivalent to lookahead, but that's not the case right now wrt\n failures. E.g., ~~'foo' produces a failure for ~~'foo', but maybe it should produce\n a failure for 'foo' instead.\n */\n\n const {inputStream} = state;\n const origPos = inputStream.pos;\n state.pushFailuresInfo();\n\n const ans = state.eval(this.expr);\n\n state.popFailuresInfo();\n if (ans) {\n state.processFailure(origPos, this);\n return false;\n }\n\n inputStream.pos = origPos;\n return true;\n};\n\nLookahead.prototype.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n if (state.eval(this.expr)) {\n inputStream.pos = origPos;\n return true;\n } else {\n return false;\n }\n};\n\nApply.prototype.eval = function(state) {\n const caller = state.currentApplication();\n const actuals = caller ? caller.args : [];\n const app = this.substituteParams(actuals);\n\n const posInfo = state.getCurrentPosInfo();\n if (posInfo.isActive(app)) {\n // This rule is already active at this position, i.e., it is left-recursive.\n return app.handleCycle(state);\n }\n\n const memoKey = app.toMemoKey();\n const memoRec = posInfo.memo[memoKey];\n\n if (memoRec && posInfo.shouldUseMemoizedResult(memoRec)) {\n if (state.hasNecessaryInfo(memoRec)) {\n return state.useMemoizedResult(state.inputStream.pos, memoRec);\n }\n delete posInfo.memo[memoKey];\n }\n return app.reallyEval(state);\n};\n\nApply.prototype.handleCycle = function(state) {\n const posInfo = state.getCurrentPosInfo();\n const {currentLeftRecursion} = posInfo;\n const memoKey = this.toMemoKey();\n let memoRec = posInfo.memo[memoKey];\n\n if (currentLeftRecursion && currentLeftRecursion.headApplication.toMemoKey() === memoKey) {\n // We already know about this left recursion, but it's possible there are \"involved\n // applications\" that we don't already know about, so...\n memoRec.updateInvolvedApplicationMemoKeys();\n } else if (!memoRec) {\n // New left recursion detected! Memoize a failure to try to get a seed parse.\n memoRec = posInfo.memoize(memoKey, {\n matchLength: 0,\n examinedLength: 0,\n value: false,\n rightmostFailureOffset: -1,\n });\n posInfo.startLeftRecursion(this, memoRec);\n }\n return state.useMemoizedResult(state.inputStream.pos, memoRec);\n};\n\nApply.prototype.reallyEval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n const origPosInfo = state.getCurrentPosInfo();\n const ruleInfo = state.grammar.rules[this.ruleName];\n const {body} = ruleInfo;\n const {description} = ruleInfo;\n\n state.enterApplication(origPosInfo, this);\n\n if (description) {\n state.pushFailuresInfo();\n }\n\n // Reset the input stream's examinedLength property so that we can track\n // the examined length of this particular application.\n const origInputStreamExaminedLength = inputStream.examinedLength;\n inputStream.examinedLength = 0;\n\n let value = this.evalOnce(body, state);\n const currentLR = origPosInfo.currentLeftRecursion;\n const memoKey = this.toMemoKey();\n const isHeadOfLeftRecursion = currentLR && currentLR.headApplication.toMemoKey() === memoKey;\n let memoRec;\n\n if (state.doNotMemoize) {\n state.doNotMemoize = false;\n } else if (isHeadOfLeftRecursion) {\n value = this.growSeedResult(body, state, origPos, currentLR, value);\n origPosInfo.endLeftRecursion();\n memoRec = currentLR;\n memoRec.examinedLength = inputStream.examinedLength - origPos;\n memoRec.rightmostFailureOffset = state._getRightmostFailureOffset();\n origPosInfo.memoize(memoKey, memoRec); // updates origPosInfo's maxExaminedLength\n } else if (!currentLR || !currentLR.isInvolved(memoKey)) {\n // This application is not involved in left recursion, so it's ok to memoize it.\n memoRec = origPosInfo.memoize(memoKey, {\n matchLength: inputStream.pos - origPos,\n examinedLength: inputStream.examinedLength - origPos,\n value,\n failuresAtRightmostPosition: state.cloneRecordedFailures(),\n rightmostFailureOffset: state._getRightmostFailureOffset(),\n });\n }\n const succeeded = !!value;\n\n if (description) {\n state.popFailuresInfo();\n if (!succeeded) {\n state.processFailure(origPos, this);\n }\n if (memoRec) {\n memoRec.failuresAtRightmostPosition = state.cloneRecordedFailures();\n }\n }\n\n // Record trace information in the memo table, so that it is available if the memoized result\n // is used later.\n if (state.isTracing() && memoRec) {\n const entry = state.getTraceEntry(origPos, this, succeeded, succeeded ? [value] : []);\n if (isHeadOfLeftRecursion) {\n assert(entry.terminatingLREntry != null || !succeeded);\n entry.isHeadOfLeftRecursion = true;\n }\n memoRec.traceEntry = entry;\n }\n\n // Fix the input stream's examinedLength -- it should be the maximum examined length\n // across all applications, not just this one.\n inputStream.examinedLength = Math.max(\n inputStream.examinedLength,\n origInputStreamExaminedLength,\n );\n\n state.exitApplication(origPosInfo, value);\n\n return succeeded;\n};\n\nApply.prototype.evalOnce = function(expr, state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n\n if (state.eval(expr)) {\n const arity = expr.getArity();\n const bindings = state._bindings.splice(state._bindings.length - arity, arity);\n const offsets = state._bindingOffsets.splice(state._bindingOffsets.length - arity, arity);\n const matchLength = inputStream.pos - origPos;\n return new NonterminalNode(this.ruleName, bindings, offsets, matchLength);\n } else {\n return false;\n }\n};\n\nApply.prototype.growSeedResult = function(body, state, origPos, lrMemoRec, newValue) {\n if (!newValue) {\n return false;\n }\n\n const {inputStream} = state;\n\n while (true) {\n lrMemoRec.matchLength = inputStream.pos - origPos;\n lrMemoRec.value = newValue;\n lrMemoRec.failuresAtRightmostPosition = state.cloneRecordedFailures();\n\n if (state.isTracing()) {\n // Before evaluating the body again, add a trace node for this application to the memo entry.\n // Its only child is a copy of the trace node from `newValue`, which will always be the last\n // element in `state.trace`.\n const seedTrace = state.trace[state.trace.length - 1];\n lrMemoRec.traceEntry = new Trace(\n state.input,\n origPos,\n inputStream.pos,\n this,\n true,\n [newValue],\n [seedTrace.clone()],\n );\n }\n inputStream.pos = origPos;\n newValue = this.evalOnce(body, state);\n if (inputStream.pos - origPos <= lrMemoRec.matchLength) {\n break;\n }\n if (state.isTracing()) {\n state.trace.splice(-2, 1); // Drop the trace for the old seed.\n }\n }\n if (state.isTracing()) {\n // The last entry is for an unused result -- pop it and save it in the \"real\" entry.\n lrMemoRec.traceEntry.recordLRTermination(state.trace.pop(), newValue);\n }\n inputStream.pos = origPos + lrMemoRec.matchLength;\n return lrMemoRec.value;\n};\n\nUnicodeChar.prototype.eval = function(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n const ch = inputStream.next();\n if (ch && this.pattern.test(ch)) {\n state.pushBinding(new TerminalNode(ch.length), origPos);\n return true;\n } else {\n state.processFailure(origPos, this);\n return false;\n }\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\nPExpr.prototype.getArity = abstract('getArity');\n\nany.getArity =\n end.getArity =\n Terminal.prototype.getArity =\n Range.prototype.getArity =\n Param.prototype.getArity =\n Apply.prototype.getArity =\n UnicodeChar.prototype.getArity =\n function() {\n return 1;\n };\n\nAlt.prototype.getArity = function() {\n // This is ok b/c all terms must have the same arity -- this property is\n // checked by the Grammar constructor.\n return this.terms.length === 0 ? 0 : this.terms[0].getArity();\n};\n\nSeq.prototype.getArity = function() {\n let arity = 0;\n for (let idx = 0; idx < this.factors.length; idx++) {\n arity += this.factors[idx].getArity();\n }\n return arity;\n};\n\nIter.prototype.getArity = function() {\n return this.expr.getArity();\n};\n\nNot.prototype.getArity = function() {\n return 0;\n};\n\nLookahead.prototype.getArity = Lex.prototype.getArity = function() {\n return this.expr.getArity();\n};\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nfunction getMetaInfo(expr, grammarInterval) {\n const metaInfo = {};\n if (expr.source && grammarInterval) {\n const adjusted = expr.source.relativeTo(grammarInterval);\n metaInfo.sourceInterval = [adjusted.startIdx, adjusted.endIdx];\n }\n return metaInfo;\n}\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\nPExpr.prototype.outputRecipe = abstract('outputRecipe');\n\nany.outputRecipe = function(formals, grammarInterval) {\n return ['any', getMetaInfo(this, grammarInterval)];\n};\n\nend.outputRecipe = function(formals, grammarInterval) {\n return ['end', getMetaInfo(this, grammarInterval)];\n};\n\nTerminal.prototype.outputRecipe = function(formals, grammarInterval) {\n return ['terminal', getMetaInfo(this, grammarInterval), this.obj];\n};\n\nRange.prototype.outputRecipe = function(formals, grammarInterval) {\n return ['range', getMetaInfo(this, grammarInterval), this.from, this.to];\n};\n\nParam.prototype.outputRecipe = function(formals, grammarInterval) {\n return ['param', getMetaInfo(this, grammarInterval), this.index];\n};\n\nAlt.prototype.outputRecipe = function(formals, grammarInterval) {\n return ['alt', getMetaInfo(this, grammarInterval)].concat(\n this.terms.map(term => term.outputRecipe(formals, grammarInterval)),\n );\n};\n\nExtend.prototype.outputRecipe = function(formals, grammarInterval) {\n const extension = this.terms[0]; // [extension, original]\n return extension.outputRecipe(formals, grammarInterval);\n};\n\nSplice.prototype.outputRecipe = function(formals, grammarInterval) {\n const beforeTerms = this.terms.slice(0, this.expansionPos);\n const afterTerms = this.terms.slice(this.expansionPos + 1);\n return [\n 'splice',\n getMetaInfo(this, grammarInterval),\n beforeTerms.map(term => term.outputRecipe(formals, grammarInterval)),\n afterTerms.map(term => term.outputRecipe(formals, grammarInterval)),\n ];\n};\n\nSeq.prototype.outputRecipe = function(formals, grammarInterval) {\n return ['seq', getMetaInfo(this, grammarInterval)].concat(\n this.factors.map(factor => factor.outputRecipe(formals, grammarInterval)),\n );\n};\n\nStar.prototype.outputRecipe =\n Plus.prototype.outputRecipe =\n Opt.prototype.outputRecipe =\n Not.prototype.outputRecipe =\n Lookahead.prototype.outputRecipe =\n Lex.prototype.outputRecipe =\n function(formals, grammarInterval) {\n return [\n this.constructor.name.toLowerCase(),\n getMetaInfo(this, grammarInterval),\n this.expr.outputRecipe(formals, grammarInterval),\n ];\n };\n\nApply.prototype.outputRecipe = function(formals, grammarInterval) {\n return [\n 'app',\n getMetaInfo(this, grammarInterval),\n this.ruleName,\n this.args.map(arg => arg.outputRecipe(formals, grammarInterval)),\n ];\n};\n\nUnicodeChar.prototype.outputRecipe = function(formals, grammarInterval) {\n return ['unicodeChar', getMetaInfo(this, grammarInterval), this.category];\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n/*\n Called at grammar creation time to rewrite a rule body, replacing each reference to a formal\n parameter with a `Param` node. Returns a PExpr -- either a new one, or the original one if\n it was modified in place.\n*/\nPExpr.prototype.introduceParams = abstract('introduceParams');\n\nany.introduceParams =\n end.introduceParams =\n Terminal.prototype.introduceParams =\n Range.prototype.introduceParams =\n Param.prototype.introduceParams =\n UnicodeChar.prototype.introduceParams =\n function(formals) {\n return this;\n };\n\nAlt.prototype.introduceParams = function(formals) {\n this.terms.forEach((term, idx, terms) => {\n terms[idx] = term.introduceParams(formals);\n });\n return this;\n};\n\nSeq.prototype.introduceParams = function(formals) {\n this.factors.forEach((factor, idx, factors) => {\n factors[idx] = factor.introduceParams(formals);\n });\n return this;\n};\n\nIter.prototype.introduceParams =\n Not.prototype.introduceParams =\n Lookahead.prototype.introduceParams =\n Lex.prototype.introduceParams =\n function(formals) {\n this.expr = this.expr.introduceParams(formals);\n return this;\n };\n\nApply.prototype.introduceParams = function(formals) {\n const index = formals.indexOf(this.ruleName);\n if (index >= 0) {\n if (this.args.length > 0) {\n // TODO: Should this be supported? See issue #64.\n throw new Error('Parameterized rules cannot be passed as arguments to another rule.');\n }\n return new Param(index).withSource(this.source);\n } else {\n this.args.forEach((arg, idx, args) => {\n args[idx] = arg.introduceParams(formals);\n });\n return this;\n }\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n// Returns `true` if this parsing expression may accept without consuming any input.\nPExpr.prototype.isNullable = function(grammar) {\n return this._isNullable(grammar, Object.create(null));\n};\n\nPExpr.prototype._isNullable = abstract('_isNullable');\n\nany._isNullable =\n Range.prototype._isNullable =\n Param.prototype._isNullable =\n Plus.prototype._isNullable =\n UnicodeChar.prototype._isNullable =\n function(grammar, memo) {\n return false;\n };\n\nend._isNullable = function(grammar, memo) {\n return true;\n};\n\nTerminal.prototype._isNullable = function(grammar, memo) {\n if (typeof this.obj === 'string') {\n // This is an over-simplification: it's only correct if the input is a string. If it's an array\n // or an object, then the empty string parsing expression is not nullable.\n return this.obj === '';\n } else {\n return false;\n }\n};\n\nAlt.prototype._isNullable = function(grammar, memo) {\n return this.terms.length === 0 || this.terms.some(term => term._isNullable(grammar, memo));\n};\n\nSeq.prototype._isNullable = function(grammar, memo) {\n return this.factors.every(factor => factor._isNullable(grammar, memo));\n};\n\nStar.prototype._isNullable =\n Opt.prototype._isNullable =\n Not.prototype._isNullable =\n Lookahead.prototype._isNullable =\n function(grammar, memo) {\n return true;\n };\n\nLex.prototype._isNullable = function(grammar, memo) {\n return this.expr._isNullable(grammar, memo);\n};\n\nApply.prototype._isNullable = function(grammar, memo) {\n const key = this.toMemoKey();\n if (!Object.prototype.hasOwnProperty.call(memo, key)) {\n const {body} = grammar.rules[this.ruleName];\n const inlined = body.substituteParams(this.args);\n memo[key] = false; // Prevent infinite recursion for recursive rules.\n memo[key] = inlined._isNullable(grammar, memo);\n }\n return memo[key];\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n/*\n Returns a PExpr that results from recursively replacing every formal parameter (i.e., instance\n of `Param`) inside this PExpr with its actual value from `actuals` (an Array).\n\n The receiver must not be modified; a new PExpr must be returned if any replacement is necessary.\n*/\n// function(actuals) { ... }\nPExpr.prototype.substituteParams = abstract('substituteParams');\n\nany.substituteParams =\n end.substituteParams =\n Terminal.prototype.substituteParams =\n Range.prototype.substituteParams =\n UnicodeChar.prototype.substituteParams =\n function(actuals) {\n return this;\n };\n\nParam.prototype.substituteParams = function(actuals) {\n return actuals[this.index];\n};\n\nAlt.prototype.substituteParams = function(actuals) {\n return new Alt(this.terms.map(term => term.substituteParams(actuals)));\n};\n\nSeq.prototype.substituteParams = function(actuals) {\n return new Seq(this.factors.map(factor => factor.substituteParams(actuals)));\n};\n\nIter.prototype.substituteParams =\n Not.prototype.substituteParams =\n Lookahead.prototype.substituteParams =\n Lex.prototype.substituteParams =\n function(actuals) {\n return new this.constructor(this.expr.substituteParams(actuals));\n };\n\nApply.prototype.substituteParams = function(actuals) {\n if (this.args.length === 0) {\n // Avoid making a copy of this application, as an optimization\n return this;\n } else {\n const args = this.args.map(arg => arg.substituteParams(actuals));\n return new Apply(this.ruleName, args);\n }\n};\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nfunction isRestrictedJSIdentifier(str) {\n return /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(str);\n}\n\nfunction resolveDuplicatedNames(argumentNameList) {\n // `count` is used to record the number of times each argument name occurs in the list,\n // this is useful for checking duplicated argument name. It maps argument names to ints.\n const count = Object.create(null);\n argumentNameList.forEach(argName => {\n count[argName] = (count[argName] || 0) + 1;\n });\n\n // Append subscripts ('_1', '_2', ...) to duplicate argument names.\n Object.keys(count).forEach(dupArgName => {\n if (count[dupArgName] <= 1) {\n return;\n }\n\n // This name shows up more than once, so add subscripts.\n let subscript = 1;\n argumentNameList.forEach((argName, idx) => {\n if (argName === dupArgName) {\n argumentNameList[idx] = argName + '_' + subscript++;\n }\n });\n });\n}\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n/*\n Returns a list of strings that will be used as the default argument names for its receiver\n (a pexpr) in a semantic action. This is used exclusively by the Semantics Editor.\n\n `firstArgIndex` is the 1-based index of the first argument name that will be generated for this\n pexpr. It enables us to name arguments positionally, e.g., if the second argument is a\n non-alphanumeric terminal like \"+\", it will be named '$2'.\n\n `noDupCheck` is true if the caller of `toArgumentNameList` is not a top level caller. It enables\n us to avoid nested duplication subscripts appending, e.g., '_1_1', '_1_2', by only checking\n duplicates at the top level.\n\n Here is a more elaborate example that illustrates how this method works:\n `(a \"+\" b).toArgumentNameList(1)` evaluates to `['a', '$2', 'b']` with the following recursive\n calls:\n\n (a).toArgumentNameList(1) -> ['a'],\n (\"+\").toArgumentNameList(2) -> ['$2'],\n (b).toArgumentNameList(3) -> ['b']\n\n Notes:\n * This method must only be called on well-formed expressions, e.g., the receiver must\n not have any Alt sub-expressions with inconsistent arities.\n * e.getArity() === e.toArgumentNameList(1).length\n*/\n// function(firstArgIndex, noDupCheck) { ... }\nPExpr.prototype.toArgumentNameList = abstract('toArgumentNameList');\n\nany.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return ['any'];\n};\n\nend.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return ['end'];\n};\n\nTerminal.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n if (typeof this.obj === 'string' && /^[_a-zA-Z0-9]+$/.test(this.obj)) {\n // If this terminal is a valid suffix for a JS identifier, just prepend it with '_'\n return ['_' + this.obj];\n } else {\n // Otherwise, name it positionally.\n return ['$' + firstArgIndex];\n }\n};\n\nRange.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n let argName = this.from + '_to_' + this.to;\n // If the `argName` is not valid then try to prepend a `_`.\n if (!isRestrictedJSIdentifier(argName)) {\n argName = '_' + argName;\n }\n // If the `argName` still not valid after prepending a `_`, then name it positionally.\n if (!isRestrictedJSIdentifier(argName)) {\n argName = '$' + firstArgIndex;\n }\n return [argName];\n};\n\nAlt.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n // `termArgNameLists` is an array of arrays where each row is the\n // argument name list that corresponds to a term in this alternation.\n const termArgNameLists = this.terms.map(term =>\n term.toArgumentNameList(firstArgIndex, true),\n );\n\n const argumentNameList = [];\n const numArgs = termArgNameLists[0].length;\n for (let colIdx = 0; colIdx < numArgs; colIdx++) {\n const col = [];\n for (let rowIdx = 0; rowIdx < this.terms.length; rowIdx++) {\n col.push(termArgNameLists[rowIdx][colIdx]);\n }\n const uniqueNames = copyWithoutDuplicates(col);\n argumentNameList.push(uniqueNames.join('_or_'));\n }\n\n if (!noDupCheck) {\n resolveDuplicatedNames(argumentNameList);\n }\n return argumentNameList;\n};\n\nSeq.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n // Generate the argument name list, without worrying about duplicates.\n let argumentNameList = [];\n this.factors.forEach(factor => {\n const factorArgumentNameList = factor.toArgumentNameList(firstArgIndex, true);\n argumentNameList = argumentNameList.concat(factorArgumentNameList);\n\n // Shift the firstArgIndex to take this factor's argument names into account.\n firstArgIndex += factorArgumentNameList.length;\n });\n if (!noDupCheck) {\n resolveDuplicatedNames(argumentNameList);\n }\n return argumentNameList;\n};\n\nIter.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n const argumentNameList = this.expr\n .toArgumentNameList(firstArgIndex, noDupCheck)\n .map(exprArgumentString =>\n exprArgumentString[exprArgumentString.length - 1] === 's' ?\n exprArgumentString + 'es' :\n exprArgumentString + 's',\n );\n if (!noDupCheck) {\n resolveDuplicatedNames(argumentNameList);\n }\n return argumentNameList;\n};\n\nOpt.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return this.expr.toArgumentNameList(firstArgIndex, noDupCheck).map(argName => {\n return 'opt' + argName[0].toUpperCase() + argName.slice(1);\n });\n};\n\nNot.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return [];\n};\n\nLookahead.prototype.toArgumentNameList = Lex.prototype.toArgumentNameList =\n function(firstArgIndex, noDupCheck) {\n return this.expr.toArgumentNameList(firstArgIndex, noDupCheck);\n };\n\nApply.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return [this.ruleName];\n};\n\nUnicodeChar.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return ['$' + firstArgIndex];\n};\n\nParam.prototype.toArgumentNameList = function(firstArgIndex, noDupCheck) {\n return ['param' + this.index];\n};\n\n// \"Value pexprs\" (Value, Str, Arr, Obj) are going away soon, so we don't worry about them here.\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n// Returns a string representing the PExpr, for use as a UI label, etc.\nPExpr.prototype.toDisplayString = abstract('toDisplayString');\n\nAlt.prototype.toDisplayString = Seq.prototype.toDisplayString = function() {\n if (this.source) {\n return this.source.trimmed().contents;\n }\n return '[' + this.constructor.name + ']';\n};\n\nany.toDisplayString =\n end.toDisplayString =\n Iter.prototype.toDisplayString =\n Not.prototype.toDisplayString =\n Lookahead.prototype.toDisplayString =\n Lex.prototype.toDisplayString =\n Terminal.prototype.toDisplayString =\n Range.prototype.toDisplayString =\n Param.prototype.toDisplayString =\n function() {\n return this.toString();\n };\n\nApply.prototype.toDisplayString = function() {\n if (this.args.length > 0) {\n const ps = this.args.map(arg => arg.toDisplayString());\n return this.ruleName + '<' + ps.join(',') + '>';\n } else {\n return this.ruleName;\n }\n};\n\nUnicodeChar.prototype.toDisplayString = function() {\n return 'Unicode [' + this.category + '] character';\n};\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\n/*\n `Failure`s represent expressions that weren't matched while parsing. They are used to generate\n error messages automatically. The interface of `Failure`s includes the collowing methods:\n\n - getText() : String\n - getType() : String (one of {\"description\", \"string\", \"code\"})\n - isDescription() : bool\n - isStringTerminal() : bool\n - isCode() : bool\n - isFluffy() : bool\n - makeFluffy() : void\n - subsumes(Failure) : bool\n*/\n\nfunction isValidType(type) {\n return type === 'description' || type === 'string' || type === 'code';\n}\n\nclass Failure {\n constructor(pexpr, text, type) {\n if (!isValidType(type)) {\n throw new Error('invalid Failure type: ' + type);\n }\n this.pexpr = pexpr;\n this.text = text;\n this.type = type;\n this.fluffy = false;\n }\n\n getPExpr() {\n return this.pexpr;\n }\n\n getText() {\n return this.text;\n }\n\n getType() {\n return this.type;\n }\n\n isDescription() {\n return this.type === 'description';\n }\n\n isStringTerminal() {\n return this.type === 'string';\n }\n\n isCode() {\n return this.type === 'code';\n }\n\n isFluffy() {\n return this.fluffy;\n }\n\n makeFluffy() {\n this.fluffy = true;\n }\n\n clearFluffy() {\n this.fluffy = false;\n }\n\n subsumes(that) {\n return (\n this.getText() === that.getText() &&\n this.type === that.type &&\n (!this.isFluffy() || (this.isFluffy() && that.isFluffy()))\n );\n }\n\n toString() {\n return this.type === 'string' ? JSON.stringify(this.getText()) : this.getText();\n }\n\n clone() {\n const failure = new Failure(this.pexpr, this.text, this.type);\n if (this.isFluffy()) {\n failure.makeFluffy();\n }\n return failure;\n }\n\n toKey() {\n return this.toString() + '#' + this.type;\n }\n}\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\nPExpr.prototype.toFailure = abstract('toFailure');\n\nany.toFailure = function(grammar) {\n return new Failure(this, 'any object', 'description');\n};\n\nend.toFailure = function(grammar) {\n return new Failure(this, 'end of input', 'description');\n};\n\nTerminal.prototype.toFailure = function(grammar) {\n return new Failure(this, this.obj, 'string');\n};\n\nRange.prototype.toFailure = function(grammar) {\n // TODO: come up with something better\n return new Failure(this, JSON.stringify(this.from) + '..' + JSON.stringify(this.to), 'code');\n};\n\nNot.prototype.toFailure = function(grammar) {\n const description =\n this.expr === any ? 'nothing' : 'not ' + this.expr.toFailure(grammar);\n return new Failure(this, description, 'description');\n};\n\nLookahead.prototype.toFailure = function(grammar) {\n return this.expr.toFailure(grammar);\n};\n\nApply.prototype.toFailure = function(grammar) {\n let {description} = grammar.rules[this.ruleName];\n if (!description) {\n const article = /^[aeiouAEIOU]/.test(this.ruleName) ? 'an' : 'a';\n description = article + ' ' + this.ruleName;\n }\n return new Failure(this, description, 'description');\n};\n\nUnicodeChar.prototype.toFailure = function(grammar) {\n return new Failure(this, 'a Unicode [' + this.category + '] character', 'description');\n};\n\nAlt.prototype.toFailure = function(grammar) {\n const fs = this.terms.map(t => t.toFailure(grammar));\n const description = '(' + fs.join(' or ') + ')';\n return new Failure(this, description, 'description');\n};\n\nSeq.prototype.toFailure = function(grammar) {\n const fs = this.factors.map(f => f.toFailure(grammar));\n const description = '(' + fs.join(' ') + ')';\n return new Failure(this, description, 'description');\n};\n\nIter.prototype.toFailure = function(grammar) {\n const description = '(' + this.expr.toFailure(grammar) + this.operator + ')';\n return new Failure(this, description, 'description');\n};\n\n// --------------------------------------------------------------------\n// Operations\n// --------------------------------------------------------------------\n\n/*\n e1.toString() === e2.toString() ==> e1 and e2 are semantically equivalent.\n Note that this is not an iff (<==>): e.g.,\n (~\"b\" \"a\").toString() !== (\"a\").toString(), even though\n ~\"b\" \"a\" and \"a\" are interchangeable in any grammar,\n both in terms of the languages they accept and their arities.\n*/\nPExpr.prototype.toString = abstract('toString');\n\nany.toString = function() {\n return 'any';\n};\n\nend.toString = function() {\n return 'end';\n};\n\nTerminal.prototype.toString = function() {\n return JSON.stringify(this.obj);\n};\n\nRange.prototype.toString = function() {\n return JSON.stringify(this.from) + '..' + JSON.stringify(this.to);\n};\n\nParam.prototype.toString = function() {\n return '$' + this.index;\n};\n\nLex.prototype.toString = function() {\n return '#(' + this.expr.toString() + ')';\n};\n\nAlt.prototype.toString = function() {\n return this.terms.length === 1 ?\n this.terms[0].toString() :\n '(' + this.terms.map(term => term.toString()).join(' | ') + ')';\n};\n\nSeq.prototype.toString = function() {\n return this.factors.length === 1 ?\n this.factors[0].toString() :\n '(' + this.factors.map(factor => factor.toString()).join(' ') + ')';\n};\n\nIter.prototype.toString = function() {\n return this.expr + this.operator;\n};\n\nNot.prototype.toString = function() {\n return '~' + this.expr;\n};\n\nLookahead.prototype.toString = function() {\n return '&' + this.expr;\n};\n\nApply.prototype.toString = function() {\n if (this.args.length > 0) {\n const ps = this.args.map(arg => arg.toString());\n return this.ruleName + '<' + ps.join(',') + '>';\n } else {\n return this.ruleName;\n }\n};\n\nUnicodeChar.prototype.toString = function() {\n return '\\\\p{' + this.category + '}';\n};\n\nclass CaseInsensitiveTerminal extends PExpr {\n constructor(param) {\n super();\n this.obj = param;\n }\n\n _getString(state) {\n const terminal = state.currentApplication().args[this.obj.index];\n assert(terminal instanceof Terminal, 'expected a Terminal expression');\n return terminal.obj;\n }\n\n // Implementation of the PExpr API\n\n allowsSkippingPrecedingSpace() {\n return true;\n }\n\n eval(state) {\n const {inputStream} = state;\n const origPos = inputStream.pos;\n const matchStr = this._getString(state);\n if (!inputStream.matchString(matchStr, true)) {\n state.processFailure(origPos, this);\n return false;\n } else {\n state.pushBinding(new TerminalNode(matchStr.length), origPos);\n return true;\n }\n }\n\n getArity() {\n return 1;\n }\n\n substituteParams(actuals) {\n return new CaseInsensitiveTerminal(this.obj.substituteParams(actuals));\n }\n\n toDisplayString() {\n return this.obj.toDisplayString() + ' (case-insensitive)';\n }\n\n toFailure(grammar) {\n return new Failure(\n this,\n this.obj.toFailure(grammar) + ' (case-insensitive)',\n 'description',\n );\n }\n\n _isNullable(grammar, memo) {\n return this.obj._isNullable(grammar, memo);\n }\n}\n\n// --------------------------------------------------------------------\n\nvar pexprs = /*#__PURE__*/Object.freeze({\n __proto__: null,\n CaseInsensitiveTerminal: CaseInsensitiveTerminal,\n PExpr: PExpr,\n any: any,\n end: end,\n Terminal: Terminal,\n Range: Range,\n Param: Param,\n Alt: Alt,\n Extend: Extend,\n Splice: Splice,\n Seq: Seq,\n Iter: Iter,\n Star: Star,\n Plus: Plus,\n Opt: Opt,\n Not: Not,\n Lookahead: Lookahead,\n Lex: Lex,\n Apply: Apply,\n UnicodeChar: UnicodeChar\n});\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nlet builtInApplySyntacticBody;\n\nawaitBuiltInRules(builtInRules => {\n builtInApplySyntacticBody = builtInRules.rules.applySyntactic.body;\n});\n\nconst applySpaces = new Apply('spaces');\n\nclass MatchState {\n constructor(matcher, startExpr, optPositionToRecordFailures) {\n this.matcher = matcher;\n this.startExpr = startExpr;\n\n this.grammar = matcher.grammar;\n this.input = matcher.getInput();\n this.inputStream = new InputStream(this.input);\n this.memoTable = matcher._memoTable;\n\n this.userData = undefined;\n this.doNotMemoize = false;\n\n this._bindings = [];\n this._bindingOffsets = [];\n this._applicationStack = [];\n this._posStack = [0];\n this.inLexifiedContextStack = [false];\n\n this.rightmostFailurePosition = -1;\n this._rightmostFailurePositionStack = [];\n this._recordedFailuresStack = [];\n\n if (optPositionToRecordFailures !== undefined) {\n this.positionToRecordFailures = optPositionToRecordFailures;\n this.recordedFailures = Object.create(null);\n }\n }\n\n posToOffset(pos) {\n return pos - this._posStack[this._posStack.length - 1];\n }\n\n enterApplication(posInfo, app) {\n this._posStack.push(this.inputStream.pos);\n this._applicationStack.push(app);\n this.inLexifiedContextStack.push(false);\n posInfo.enter(app);\n this._rightmostFailurePositionStack.push(this.rightmostFailurePosition);\n this.rightmostFailurePosition = -1;\n }\n\n exitApplication(posInfo, optNode) {\n const origPos = this._posStack.pop();\n this._applicationStack.pop();\n this.inLexifiedContextStack.pop();\n posInfo.exit();\n\n this.rightmostFailurePosition = Math.max(\n this.rightmostFailurePosition,\n this._rightmostFailurePositionStack.pop(),\n );\n\n if (optNode) {\n this.pushBinding(optNode, origPos);\n }\n }\n\n enterLexifiedContext() {\n this.inLexifiedContextStack.push(true);\n }\n\n exitLexifiedContext() {\n this.inLexifiedContextStack.pop();\n }\n\n currentApplication() {\n return this._applicationStack[this._applicationStack.length - 1];\n }\n\n inSyntacticContext() {\n const currentApplication = this.currentApplication();\n if (currentApplication) {\n return currentApplication.isSyntactic() && !this.inLexifiedContext();\n } else {\n // The top-level context is syntactic if the start application is.\n return this.startExpr.factors[0].isSyntactic();\n }\n }\n\n inLexifiedContext() {\n return this.inLexifiedContextStack[this.inLexifiedContextStack.length - 1];\n }\n\n skipSpaces() {\n this.pushFailuresInfo();\n this.eval(applySpaces);\n this.popBinding();\n this.popFailuresInfo();\n return this.inputStream.pos;\n }\n\n skipSpacesIfInSyntacticContext() {\n return this.inSyntacticContext() ? this.skipSpaces() : this.inputStream.pos;\n }\n\n maybeSkipSpacesBefore(expr) {\n if (expr.allowsSkippingPrecedingSpace() && expr !== applySpaces) {\n return this.skipSpacesIfInSyntacticContext();\n } else {\n return this.inputStream.pos;\n }\n }\n\n pushBinding(node, origPos) {\n this._bindings.push(node);\n this._bindingOffsets.push(this.posToOffset(origPos));\n }\n\n popBinding() {\n this._bindings.pop();\n this._bindingOffsets.pop();\n }\n\n numBindings() {\n return this._bindings.length;\n }\n\n truncateBindings(newLength) {\n // Yes, this is this really faster than setting the `length` property (tested with\n // bin/es5bench on Node v6.1.0).\n // Update 2021-10-25: still true on v14.15.5 — it's ~20% speedup on es5bench.\n while (this._bindings.length > newLength) {\n this.popBinding();\n }\n }\n\n getCurrentPosInfo() {\n return this.getPosInfo(this.inputStream.pos);\n }\n\n getPosInfo(pos) {\n let posInfo = this.memoTable[pos];\n if (!posInfo) {\n posInfo = this.memoTable[pos] = new PosInfo();\n }\n return posInfo;\n }\n\n processFailure(pos, expr) {\n this.rightmostFailurePosition = Math.max(this.rightmostFailurePosition, pos);\n\n if (this.recordedFailures && pos === this.positionToRecordFailures) {\n const app = this.currentApplication();\n if (app) {\n // Substitute parameters with the actual pexprs that were passed to\n // the current rule.\n expr = expr.substituteParams(app.args);\n }\n\n this.recordFailure(expr.toFailure(this.grammar), false);\n }\n }\n\n recordFailure(failure, shouldCloneIfNew) {\n const key = failure.toKey();\n if (!this.recordedFailures[key]) {\n this.recordedFailures[key] = shouldCloneIfNew ? failure.clone() : failure;\n } else if (this.recordedFailures[key].isFluffy() && !failure.isFluffy()) {\n this.recordedFailures[key].clearFluffy();\n }\n }\n\n recordFailures(failures, shouldCloneIfNew) {\n Object.keys(failures).forEach(key => {\n this.recordFailure(failures[key], shouldCloneIfNew);\n });\n }\n\n cloneRecordedFailures() {\n if (!this.recordedFailures) {\n return undefined;\n }\n\n const ans = Object.create(null);\n Object.keys(this.recordedFailures).forEach(key => {\n ans[key] = this.recordedFailures[key].clone();\n });\n return ans;\n }\n\n getRightmostFailurePosition() {\n return this.rightmostFailurePosition;\n }\n\n _getRightmostFailureOffset() {\n return this.rightmostFailurePosition >= 0 ?\n this.posToOffset(this.rightmostFailurePosition) :\n -1;\n }\n\n // Returns the memoized trace entry for `expr` at `pos`, if one exists, `null` otherwise.\n getMemoizedTraceEntry(pos, expr) {\n const posInfo = this.memoTable[pos];\n if (posInfo && expr instanceof Apply) {\n const memoRec = posInfo.memo[expr.toMemoKey()];\n if (memoRec && memoRec.traceEntry) {\n const entry = memoRec.traceEntry.cloneWithExpr(expr);\n entry.isMemoized = true;\n return entry;\n }\n }\n return null;\n }\n\n // Returns a new trace entry, with the currently active trace array as its children.\n getTraceEntry(pos, expr, succeeded, bindings) {\n if (expr instanceof Apply) {\n const app = this.currentApplication();\n const actuals = app ? app.args : [];\n expr = expr.substituteParams(actuals);\n }\n return (\n this.getMemoizedTraceEntry(pos, expr) ||\n new Trace(this.input, pos, this.inputStream.pos, expr, succeeded, bindings, this.trace)\n );\n }\n\n isTracing() {\n return !!this.trace;\n }\n\n hasNecessaryInfo(memoRec) {\n if (this.trace && !memoRec.traceEntry) {\n return false;\n }\n\n if (\n this.recordedFailures &&\n this.inputStream.pos + memoRec.rightmostFailureOffset === this.positionToRecordFailures\n ) {\n return !!memoRec.failuresAtRightmostPosition;\n }\n\n return true;\n }\n\n useMemoizedResult(origPos, memoRec) {\n if (this.trace) {\n this.trace.push(memoRec.traceEntry);\n }\n\n const memoRecRightmostFailurePosition =\n this.inputStream.pos + memoRec.rightmostFailureOffset;\n this.rightmostFailurePosition = Math.max(\n this.rightmostFailurePosition,\n memoRecRightmostFailurePosition,\n );\n if (\n this.recordedFailures &&\n this.positionToRecordFailures === memoRecRightmostFailurePosition &&\n memoRec.failuresAtRightmostPosition\n ) {\n this.recordFailures(memoRec.failuresAtRightmostPosition, true);\n }\n\n this.inputStream.examinedLength = Math.max(\n this.inputStream.examinedLength,\n memoRec.examinedLength + origPos,\n );\n\n if (memoRec.value) {\n this.inputStream.pos += memoRec.matchLength;\n this.pushBinding(memoRec.value, origPos);\n return true;\n }\n return false;\n }\n\n // Evaluate `expr` and return `true` if it succeeded, `false` otherwise. On success, `bindings`\n // will have `expr.getArity()` more elements than before, and the input stream's position may\n // have increased. On failure, `bindings` and position will be unchanged.\n eval(expr) {\n const {inputStream} = this;\n const origNumBindings = this._bindings.length;\n const origUserData = this.userData;\n\n let origRecordedFailures;\n if (this.recordedFailures) {\n origRecordedFailures = this.recordedFailures;\n this.recordedFailures = Object.create(null);\n }\n\n const origPos = inputStream.pos;\n const memoPos = this.maybeSkipSpacesBefore(expr);\n\n let origTrace;\n if (this.trace) {\n origTrace = this.trace;\n this.trace = [];\n }\n\n // Do the actual evaluation.\n const ans = expr.eval(this);\n\n if (this.trace) {\n const bindings = this._bindings.slice(origNumBindings);\n const traceEntry = this.getTraceEntry(memoPos, expr, ans, bindings);\n traceEntry.isImplicitSpaces = expr === applySpaces;\n traceEntry.isRootNode = expr === this.startExpr;\n origTrace.push(traceEntry);\n this.trace = origTrace;\n }\n\n if (ans) {\n if (this.recordedFailures && inputStream.pos === this.positionToRecordFailures) {\n Object.keys(this.recordedFailures).forEach(key => {\n this.recordedFailures[key].makeFluffy();\n });\n }\n } else {\n // Reset the position, bindings, and userData.\n inputStream.pos = origPos;\n this.truncateBindings(origNumBindings);\n this.userData = origUserData;\n }\n\n if (this.recordedFailures) {\n this.recordFailures(origRecordedFailures, false);\n }\n\n // The built-in applySyntactic rule needs special handling: we want to skip\n // trailing spaces, just as with the top-level application of a syntactic rule.\n if (expr === builtInApplySyntacticBody) {\n this.skipSpaces();\n }\n\n return ans;\n }\n\n getMatchResult() {\n this.grammar._setUpMatchState(this);\n this.eval(this.startExpr);\n let rightmostFailures;\n if (this.recordedFailures) {\n rightmostFailures = Object.keys(this.recordedFailures).map(\n key => this.recordedFailures[key],\n );\n }\n const cst = this._bindings[0];\n if (cst) {\n cst.grammar = this.grammar;\n }\n return new MatchResult(\n this.matcher,\n this.input,\n this.startExpr,\n cst,\n this._bindingOffsets[0],\n this.rightmostFailurePosition,\n rightmostFailures,\n );\n }\n\n getTrace() {\n this.trace = [];\n const matchResult = this.getMatchResult();\n\n // The trace node for the start rule is always the last entry. If it is a syntactic rule,\n // the first entry is for an application of 'spaces'.\n // TODO(pdubroy): Clean this up by introducing a special `Match` rule, which will\n // ensure that there is always a single root trace node.\n const rootTrace = this.trace[this.trace.length - 1];\n rootTrace.result = matchResult;\n return rootTrace;\n }\n\n pushFailuresInfo() {\n this._rightmostFailurePositionStack.push(this.rightmostFailurePosition);\n this._recordedFailuresStack.push(this.recordedFailures);\n }\n\n popFailuresInfo() {\n this.rightmostFailurePosition = this._rightmostFailurePositionStack.pop();\n this.recordedFailures = this._recordedFailuresStack.pop();\n }\n}\n\nclass Matcher {\n constructor(grammar) {\n this.grammar = grammar;\n this._memoTable = [];\n this._input = '';\n this._isMemoTableStale = false;\n }\n\n _resetMemoTable() {\n this._memoTable = [];\n this._isMemoTableStale = false;\n }\n\n getInput() {\n return this._input;\n }\n\n setInput(str) {\n if (this._input !== str) {\n this.replaceInputRange(0, this._input.length, str);\n }\n return this;\n }\n\n replaceInputRange(startIdx, endIdx, str) {\n const prevInput = this._input;\n const memoTable = this._memoTable;\n if (\n startIdx < 0 ||\n startIdx > prevInput.length ||\n endIdx < 0 ||\n endIdx > prevInput.length ||\n startIdx > endIdx\n ) {\n throw new Error('Invalid indices: ' + startIdx + ' and ' + endIdx);\n }\n\n // update input\n this._input = prevInput.slice(0, startIdx) + str + prevInput.slice(endIdx);\n if (this._input !== prevInput && memoTable.length > 0) {\n this._isMemoTableStale = true;\n }\n\n // update memo table (similar to the above)\n const restOfMemoTable = memoTable.slice(endIdx);\n memoTable.length = startIdx;\n for (let idx = 0; idx < str.length; idx++) {\n memoTable.push(undefined);\n }\n for (const posInfo of restOfMemoTable) {\n memoTable.push(posInfo);\n }\n\n // Invalidate memoRecs\n for (let pos = 0; pos < startIdx; pos++) {\n const posInfo = memoTable[pos];\n if (posInfo) {\n posInfo.clearObsoleteEntries(pos, startIdx);\n }\n }\n\n return this;\n }\n\n match(optStartApplicationStr, options = {incremental: true}) {\n return this._match(this._getStartExpr(optStartApplicationStr), {\n incremental: options.incremental,\n tracing: false,\n });\n }\n\n trace(optStartApplicationStr, options = {incremental: true}) {\n return this._match(this._getStartExpr(optStartApplicationStr), {\n incremental: options.incremental,\n tracing: true,\n });\n }\n\n _match(startExpr, options = {}) {\n const opts = {\n tracing: false,\n incremental: true,\n positionToRecordFailures: undefined,\n ...options,\n };\n if (!opts.incremental) {\n this._resetMemoTable();\n } else if (this._isMemoTableStale && !this.grammar.supportsIncrementalParsing) {\n throw grammarDoesNotSupportIncrementalParsing(this.grammar);\n }\n\n const state = new MatchState(this, startExpr, opts.positionToRecordFailures);\n return opts.tracing ? state.getTrace() : state.getMatchResult();\n }\n\n /*\n Returns the starting expression for this Matcher's associated grammar. If\n `optStartApplicationStr` is specified, it is a string expressing a rule application in the\n grammar. If not specified, the grammar's default start rule will be used.\n */\n _getStartExpr(optStartApplicationStr) {\n const applicationStr = optStartApplicationStr || this.grammar.defaultStartRule;\n if (!applicationStr) {\n throw new Error('Missing start rule argument -- the grammar has no default start rule.');\n }\n\n const startApp = this.grammar.parseApplication(applicationStr);\n return new Seq([startApp, end]);\n }\n}\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nconst globalActionStack = [];\n\nconst hasOwnProperty = (x, prop) => Object.prototype.hasOwnProperty.call(x, prop);\n\n// ----------------- Wrappers -----------------\n\n// Wrappers decorate CST nodes with all of the functionality (i.e., operations and attributes)\n// provided by a Semantics (see below). `Wrapper` is the abstract superclass of all wrappers. A\n// `Wrapper` must have `_node` and `_semantics` instance variables, which refer to the CST node and\n// Semantics (resp.) for which it was created, and a `_childWrappers` instance variable which is\n// used to cache the wrapper instances that are created for its child nodes. Setting these instance\n// variables is the responsibility of the constructor of each Semantics-specific subclass of\n// `Wrapper`.\nclass Wrapper {\n constructor(node, sourceInterval, baseInterval) {\n this._node = node;\n this.source = sourceInterval;\n\n // The interval that the childOffsets of `node` are relative to. It should be the source\n // of the closest Nonterminal node.\n this._baseInterval = baseInterval;\n\n if (node.isNonterminal()) {\n assert(sourceInterval === baseInterval);\n }\n this._childWrappers = [];\n }\n\n _forgetMemoizedResultFor(attributeName) {\n // Remove the memoized attribute from the cstNode and all its children.\n delete this._node[this._semantics.attributeKeys[attributeName]];\n this.children.forEach(child => {\n child._forgetMemoizedResultFor(attributeName);\n });\n }\n\n // Returns the wrapper of the specified child node. Child wrappers are created lazily and\n // cached in the parent wrapper's `_childWrappers` instance variable.\n child(idx) {\n if (!(0 <= idx && idx < this._node.numChildren())) {\n // TODO: Consider throwing an exception here.\n return undefined;\n }\n let childWrapper = this._childWrappers[idx];\n if (!childWrapper) {\n const childNode = this._node.childAt(idx);\n const offset = this._node.childOffsets[idx];\n\n const source = this._baseInterval.subInterval(offset, childNode.matchLength);\n const base = childNode.isNonterminal() ? source : this._baseInterval;\n childWrapper = this._childWrappers[idx] = this._semantics.wrap(childNode, source, base);\n }\n return childWrapper;\n }\n\n // Returns an array containing the wrappers of all of the children of the node associated\n // with this wrapper.\n _children() {\n // Force the creation of all child wrappers\n for (let idx = 0; idx < this._node.numChildren(); idx++) {\n this.child(idx);\n }\n return this._childWrappers;\n }\n\n // Returns `true` if the CST node associated with this wrapper corresponds to an iteration\n // expression, i.e., a Kleene-*, Kleene-+, or an optional. Returns `false` otherwise.\n isIteration() {\n return this._node.isIteration();\n }\n\n // Returns `true` if the CST node associated with this wrapper is a terminal node, `false`\n // otherwise.\n isTerminal() {\n return this._node.isTerminal();\n }\n\n // Returns `true` if the CST node associated with this wrapper is a nonterminal node, `false`\n // otherwise.\n isNonterminal() {\n return this._node.isNonterminal();\n }\n\n // Returns `true` if the CST node associated with this wrapper is a nonterminal node\n // corresponding to a syntactic rule, `false` otherwise.\n isSyntactic() {\n return this.isNonterminal() && this._node.isSyntactic();\n }\n\n // Returns `true` if the CST node associated with this wrapper is a nonterminal node\n // corresponding to a lexical rule, `false` otherwise.\n isLexical() {\n return this.isNonterminal() && this._node.isLexical();\n }\n\n // Returns `true` if the CST node associated with this wrapper is an iterator node\n // having either one or no child (? operator), `false` otherwise.\n // Otherwise, throws an exception.\n isOptional() {\n return this._node.isOptional();\n }\n\n // Create a new _iter wrapper in the same semantics as this wrapper.\n iteration(optChildWrappers) {\n const childWrappers = optChildWrappers || [];\n\n const childNodes = childWrappers.map(c => c._node);\n const iter = new IterationNode(childNodes, [], -1, false);\n\n const wrapper = this._semantics.wrap(iter, null, null);\n wrapper._childWrappers = childWrappers;\n return wrapper;\n }\n\n // Returns an array containing the children of this CST node.\n get children() {\n return this._children();\n }\n\n // Returns the name of grammar rule that created this CST node.\n get ctorName() {\n return this._node.ctorName;\n }\n\n // Returns the number of children of this CST node.\n get numChildren() {\n return this._node.numChildren();\n }\n\n // Returns the contents of the input stream consumed by this CST node.\n get sourceString() {\n return this.source.contents;\n }\n}\n\n// ----------------- Semantics -----------------\n\n// A Semantics is a container for a family of Operations and Attributes for a given grammar.\n// Semantics enable modularity (different clients of a grammar can create their set of operations\n// and attributes in isolation) and extensibility even when operations and attributes are mutually-\n// recursive. This constructor should not be called directly except from\n// `Semantics.createSemantics`. The normal ways to create a Semantics, given a grammar 'g', are\n// `g.createSemantics()` and `g.extendSemantics(parentSemantics)`.\nclass Semantics {\n constructor(grammar, superSemantics) {\n const self = this;\n this.grammar = grammar;\n this.checkedActionDicts = false;\n\n // Constructor for wrapper instances, which are passed as the arguments to the semantic actions\n // of an operation or attribute. Operations and attributes require double dispatch: the semantic\n // action is chosen based on both the node's type and the semantics. Wrappers ensure that\n // the `execute` method is called with the correct (most specific) semantics object as an\n // argument.\n this.Wrapper = class extends (superSemantics ? superSemantics.Wrapper : Wrapper) {\n constructor(node, sourceInterval, baseInterval) {\n super(node, sourceInterval, baseInterval);\n self.checkActionDictsIfHaventAlready();\n this._semantics = self;\n }\n\n toString() {\n return '[semantics wrapper for ' + self.grammar.name + ']';\n }\n };\n\n this.super = superSemantics;\n if (superSemantics) {\n if (!(grammar.equals(this.super.grammar) || grammar._inheritsFrom(this.super.grammar))) {\n throw new Error(\n \"Cannot extend a semantics for grammar '\" +\n this.super.grammar.name +\n \"' for use with grammar '\" +\n grammar.name +\n \"' (not a sub-grammar)\",\n );\n }\n this.operations = Object.create(this.super.operations);\n this.attributes = Object.create(this.super.attributes);\n this.attributeKeys = Object.create(null);\n\n // Assign unique symbols for each of the attributes inherited from the super-semantics so that\n // they are memoized independently.\n // eslint-disable-next-line guard-for-in\n for (const attributeName in this.attributes) {\n Object.defineProperty(this.attributeKeys, attributeName, {\n value: uniqueId(attributeName),\n });\n }\n } else {\n this.operations = Object.create(null);\n this.attributes = Object.create(null);\n this.attributeKeys = Object.create(null);\n }\n }\n\n toString() {\n return '[semantics for ' + this.grammar.name + ']';\n }\n\n checkActionDictsIfHaventAlready() {\n if (!this.checkedActionDicts) {\n this.checkActionDicts();\n this.checkedActionDicts = true;\n }\n }\n\n // Checks that the action dictionaries for all operations and attributes in this semantics,\n // including the ones that were inherited from the super-semantics, agree with the grammar.\n // Throws an exception if one or more of them doesn't.\n checkActionDicts() {\n let name;\n // eslint-disable-next-line guard-for-in\n for (name in this.operations) {\n this.operations[name].checkActionDict(this.grammar);\n }\n // eslint-disable-next-line guard-for-in\n for (name in this.attributes) {\n this.attributes[name].checkActionDict(this.grammar);\n }\n }\n\n toRecipe(semanticsOnly) {\n function hasSuperSemantics(s) {\n return s.super !== Semantics.BuiltInSemantics._getSemantics();\n }\n\n let str = '(function(g) {\\n';\n if (hasSuperSemantics(this)) {\n str += ' var semantics = ' + this.super.toRecipe(true) + '(g';\n\n const superSemanticsGrammar = this.super.grammar;\n let relatedGrammar = this.grammar;\n while (relatedGrammar !== superSemanticsGrammar) {\n str += '.superGrammar';\n relatedGrammar = relatedGrammar.superGrammar;\n }\n\n str += ');\\n';\n str += ' return g.extendSemantics(semantics)';\n } else {\n str += ' return g.createSemantics()';\n }\n ['Operation', 'Attribute'].forEach(type => {\n const semanticOperations = this[type.toLowerCase() + 's'];\n Object.keys(semanticOperations).forEach(name => {\n const {actionDict, formals, builtInDefault} = semanticOperations[name];\n\n let signature = name;\n if (formals.length > 0) {\n signature += '(' + formals.join(', ') + ')';\n }\n\n let method;\n if (hasSuperSemantics(this) && this.super[type.toLowerCase() + 's'][name]) {\n method = 'extend' + type;\n } else {\n method = 'add' + type;\n }\n str += '\\n .' + method + '(' + JSON.stringify(signature) + ', {';\n\n const srcArray = [];\n Object.keys(actionDict).forEach(actionName => {\n if (actionDict[actionName] !== builtInDefault) {\n let source = actionDict[actionName].toString().trim();\n\n // Convert method shorthand to plain old function syntax.\n // https://github.com/ohmjs/ohm/issues/263\n source = source.replace(/^.*\\(/, 'function(');\n\n srcArray.push('\\n ' + JSON.stringify(actionName) + ': ' + source);\n }\n });\n str += srcArray.join(',') + '\\n })';\n });\n });\n str += ';\\n })';\n\n if (!semanticsOnly) {\n str =\n '(function() {\\n' +\n ' var grammar = this.fromRecipe(' +\n this.grammar.toRecipe() +\n ');\\n' +\n ' var semantics = ' +\n str +\n '(grammar);\\n' +\n ' return semantics;\\n' +\n '});\\n';\n }\n\n return str;\n }\n\n addOperationOrAttribute(type, signature, actionDict) {\n const typePlural = type + 's';\n\n const parsedNameAndFormalArgs = parseSignature(signature, type);\n const {name} = parsedNameAndFormalArgs;\n const {formals} = parsedNameAndFormalArgs;\n\n // TODO: check that there are no duplicate formal arguments\n\n this.assertNewName(name, type);\n\n // Create the action dictionary for this operation / attribute that contains a `_default` action\n // which defines the default behavior of iteration, terminal, and non-terminal nodes...\n const builtInDefault = newDefaultAction(type, name, doIt);\n const realActionDict = {_default: builtInDefault};\n // ... and add in the actions supplied by the programmer, which may override some or all of the\n // default ones.\n Object.keys(actionDict).forEach(name => {\n realActionDict[name] = actionDict[name];\n });\n\n const entry =\n type === 'operation' ?\n new Operation(name, formals, realActionDict, builtInDefault) :\n new Attribute(name, realActionDict, builtInDefault);\n\n // The following check is not strictly necessary (it will happen later anyway) but it's better\n // to catch errors early.\n entry.checkActionDict(this.grammar);\n\n this[typePlural][name] = entry;\n\n function doIt(...args) {\n // Dispatch to most specific version of this operation / attribute -- it may have been\n // overridden by a sub-semantics.\n const thisThing = this._semantics[typePlural][name];\n\n // Check that the caller passed the correct number of arguments.\n if (arguments.length !== thisThing.formals.length) {\n throw new Error(\n 'Invalid number of arguments passed to ' +\n name +\n ' ' +\n type +\n ' (expected ' +\n thisThing.formals.length +\n ', got ' +\n arguments.length +\n ')',\n );\n }\n\n // Create an \"arguments object\" from the arguments that were passed to this\n // operation / attribute.\n const argsObj = Object.create(null);\n for (const [idx, val] of Object.entries(args)) {\n const formal = thisThing.formals[idx];\n argsObj[formal] = val;\n }\n\n const oldArgs = this.args;\n this.args = argsObj;\n const ans = thisThing.execute(this._semantics, this);\n this.args = oldArgs;\n return ans;\n }\n\n if (type === 'operation') {\n this.Wrapper.prototype[name] = doIt;\n this.Wrapper.prototype[name].toString = function() {\n return '[' + name + ' operation]';\n };\n } else {\n Object.defineProperty(this.Wrapper.prototype, name, {\n get: doIt,\n configurable: true, // So the property can be deleted.\n });\n Object.defineProperty(this.attributeKeys, name, {\n value: uniqueId(name),\n });\n }\n }\n\n extendOperationOrAttribute(type, name, actionDict) {\n const typePlural = type + 's';\n\n // Make sure that `name` really is just a name, i.e., that it doesn't also contain formals.\n parseSignature(name, 'attribute');\n\n if (!(this.super && name in this.super[typePlural])) {\n throw new Error(\n 'Cannot extend ' +\n type +\n \" '\" +\n name +\n \"': did not inherit an \" +\n type +\n ' with that name',\n );\n }\n if (hasOwnProperty(this[typePlural], name)) {\n throw new Error('Cannot extend ' + type + \" '\" + name + \"' again\");\n }\n\n // Create a new operation / attribute whose actionDict delegates to the super operation /\n // attribute's actionDict, and which has all the keys from `inheritedActionDict`.\n const inheritedFormals = this[typePlural][name].formals;\n const inheritedActionDict = this[typePlural][name].actionDict;\n const newActionDict = Object.create(inheritedActionDict);\n Object.keys(actionDict).forEach(name => {\n newActionDict[name] = actionDict[name];\n });\n\n this[typePlural][name] =\n type === 'operation' ?\n new Operation(name, inheritedFormals, newActionDict) :\n new Attribute(name, newActionDict);\n\n // The following check is not strictly necessary (it will happen later anyway) but it's better\n // to catch errors early.\n this[typePlural][name].checkActionDict(this.grammar);\n }\n\n assertNewName(name, type) {\n if (hasOwnProperty(Wrapper.prototype, name)) {\n throw new Error('Cannot add ' + type + \" '\" + name + \"': that's a reserved name\");\n }\n if (name in this.operations) {\n throw new Error(\n 'Cannot add ' + type + \" '\" + name + \"': an operation with that name already exists\",\n );\n }\n if (name in this.attributes) {\n throw new Error(\n 'Cannot add ' + type + \" '\" + name + \"': an attribute with that name already exists\",\n );\n }\n }\n\n // Returns a wrapper for the given CST `node` in this semantics.\n // If `node` is already a wrapper, returns `node` itself. // TODO: why is this needed?\n wrap(node, source, optBaseInterval) {\n const baseInterval = optBaseInterval || source;\n return node instanceof this.Wrapper ? node : new this.Wrapper(node, source, baseInterval);\n }\n}\n\nfunction parseSignature(signature, type) {\n if (!Semantics.prototypeGrammar) {\n // The Operations and Attributes grammar won't be available while Ohm is loading,\n // but we can get away the following simplification b/c none of the operations\n // that are used while loading take arguments.\n assert(signature.indexOf('(') === -1);\n return {\n name: signature,\n formals: [],\n };\n }\n\n const r = Semantics.prototypeGrammar.match(\n signature,\n type === 'operation' ? 'OperationSignature' : 'AttributeSignature',\n );\n if (r.failed()) {\n throw new Error(r.message);\n }\n\n return Semantics.prototypeGrammarSemantics(r).parse();\n}\n\nfunction newDefaultAction(type, name, doIt) {\n return function(...children) {\n const thisThing = this._semantics.operations[name] || this._semantics.attributes[name];\n const args = thisThing.formals.map(formal => this.args[formal]);\n\n if (!this.isIteration() && children.length === 1) {\n // This CST node corresponds to a non-terminal in the grammar (e.g., AddExpr). The fact that\n // we got here means that this action dictionary doesn't have an action for this particular\n // non-terminal or a generic `_nonterminal` action.\n // As a convenience, if this node only has one child, we just return the result of applying\n // this operation / attribute to the child node.\n return doIt.apply(children[0], args);\n } else {\n // Otherwise, we throw an exception to let the programmer know that we don't know what\n // to do with this node.\n throw missingSemanticAction(this.ctorName, name, type, globalActionStack);\n }\n };\n}\n\n// Creates a new Semantics instance for `grammar`, inheriting operations and attributes from\n// `optSuperSemantics`, if it is specified. Returns a function that acts as a proxy for the new\n// Semantics instance. When that function is invoked with a CST node as an argument, it returns\n// a wrapper for that node which gives access to the operations and attributes provided by this\n// semantics.\nSemantics.createSemantics = function(grammar, optSuperSemantics) {\n const s = new Semantics(\n grammar,\n optSuperSemantics !== undefined ?\n optSuperSemantics :\n Semantics.BuiltInSemantics._getSemantics(),\n );\n\n // To enable clients to invoke a semantics like a function, return a function that acts as a proxy\n // for `s`, which is the real `Semantics` instance.\n const proxy = function ASemantics(matchResult) {\n if (!(matchResult instanceof MatchResult)) {\n throw new TypeError(\n 'Semantics expected a MatchResult, but got ' +\n unexpectedObjToString(matchResult),\n );\n }\n if (matchResult.failed()) {\n throw new TypeError('cannot apply Semantics to ' + matchResult.toString());\n }\n\n const cst = matchResult._cst;\n if (cst.grammar !== grammar) {\n throw new Error(\n \"Cannot use a MatchResult from grammar '\" +\n cst.grammar.name +\n \"' with a semantics for '\" +\n grammar.name +\n \"'\",\n );\n }\n const inputStream = new InputStream(matchResult.input);\n return s.wrap(cst, inputStream.interval(matchResult._cstOffset, matchResult.input.length));\n };\n\n // Forward public methods from the proxy to the semantics instance.\n proxy.addOperation = function(signature, actionDict) {\n s.addOperationOrAttribute('operation', signature, actionDict);\n return proxy;\n };\n proxy.extendOperation = function(name, actionDict) {\n s.extendOperationOrAttribute('operation', name, actionDict);\n return proxy;\n };\n proxy.addAttribute = function(name, actionDict) {\n s.addOperationOrAttribute('attribute', name, actionDict);\n return proxy;\n };\n proxy.extendAttribute = function(name, actionDict) {\n s.extendOperationOrAttribute('attribute', name, actionDict);\n return proxy;\n };\n proxy._getActionDict = function(operationOrAttributeName) {\n const action =\n s.operations[operationOrAttributeName] || s.attributes[operationOrAttributeName];\n if (!action) {\n throw new Error(\n '\"' +\n operationOrAttributeName +\n '\" is not a valid operation or attribute ' +\n 'name in this semantics for \"' +\n grammar.name +\n '\"',\n );\n }\n return action.actionDict;\n };\n proxy._remove = function(operationOrAttributeName) {\n let semantic;\n if (operationOrAttributeName in s.operations) {\n semantic = s.operations[operationOrAttributeName];\n delete s.operations[operationOrAttributeName];\n } else if (operationOrAttributeName in s.attributes) {\n semantic = s.attributes[operationOrAttributeName];\n delete s.attributes[operationOrAttributeName];\n }\n delete s.Wrapper.prototype[operationOrAttributeName];\n return semantic;\n };\n proxy.getOperationNames = function() {\n return Object.keys(s.operations);\n };\n proxy.getAttributeNames = function() {\n return Object.keys(s.attributes);\n };\n proxy.getGrammar = function() {\n return s.grammar;\n };\n proxy.toRecipe = function(semanticsOnly) {\n return s.toRecipe(semanticsOnly);\n };\n\n // Make the proxy's toString() work.\n proxy.toString = s.toString.bind(s);\n\n // Returns the semantics for the proxy.\n proxy._getSemantics = function() {\n return s;\n };\n\n return proxy;\n};\n\n// ----------------- Operation -----------------\n\n// An Operation represents a function to be applied to a concrete syntax tree (CST) -- it's very\n// similar to a Visitor (http://en.wikipedia.org/wiki/Visitor_pattern). An operation is executed by\n// recursively walking the CST, and at each node, invoking the matching semantic action from\n// `actionDict`. See `Operation.prototype.execute` for details of how a CST node's matching semantic\n// action is found.\nclass Operation {\n constructor(name, formals, actionDict, builtInDefault) {\n this.name = name;\n this.formals = formals;\n this.actionDict = actionDict;\n this.builtInDefault = builtInDefault;\n }\n\n checkActionDict(grammar) {\n grammar._checkTopDownActionDict(this.typeName, this.name, this.actionDict);\n }\n\n // Execute this operation on the CST node associated with `nodeWrapper` in the context of the\n // given Semantics instance.\n execute(semantics, nodeWrapper) {\n try {\n // Look for a semantic action whose name matches the node's constructor name, which is either\n // the name of a rule in the grammar, or '_terminal' (for a terminal node), or '_iter' (for an\n // iteration node).\n const {ctorName} = nodeWrapper._node;\n let actionFn = this.actionDict[ctorName];\n if (actionFn) {\n globalActionStack.push([this, ctorName]);\n return actionFn.apply(nodeWrapper, nodeWrapper._children());\n }\n\n // The action dictionary does not contain a semantic action for this specific type of node.\n // If this is a nonterminal node and the programmer has provided a `_nonterminal` semantic\n // action, we invoke it:\n if (nodeWrapper.isNonterminal()) {\n actionFn = this.actionDict._nonterminal;\n if (actionFn) {\n globalActionStack.push([this, '_nonterminal', ctorName]);\n return actionFn.apply(nodeWrapper, nodeWrapper._children());\n }\n }\n\n // Otherwise, we invoke the '_default' semantic action.\n globalActionStack.push([this, 'default action', ctorName]);\n return this.actionDict._default.apply(nodeWrapper, nodeWrapper._children());\n } finally {\n globalActionStack.pop();\n }\n }\n}\n\nOperation.prototype.typeName = 'operation';\n\n// ----------------- Attribute -----------------\n\n// Attributes are Operations whose results are memoized. This means that, for any given semantics,\n// the semantic action for a CST node will be invoked no more than once.\nclass Attribute extends Operation {\n constructor(name, actionDict, builtInDefault) {\n super(name, [], actionDict, builtInDefault);\n }\n\n execute(semantics, nodeWrapper) {\n const node = nodeWrapper._node;\n const key = semantics.attributeKeys[this.name];\n if (!hasOwnProperty(node, key)) {\n // The following is a super-send -- isn't JS beautiful? :/\n node[key] = Operation.prototype.execute.call(this, semantics, nodeWrapper);\n }\n return node[key];\n }\n}\n\nAttribute.prototype.typeName = 'attribute';\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nconst SPECIAL_ACTION_NAMES = ['_iter', '_terminal', '_nonterminal', '_default'];\n\nfunction getSortedRuleValues(grammar) {\n return Object.keys(grammar.rules)\n .sort()\n .map(name => grammar.rules[name]);\n}\n\n// Until ES2019, JSON was not a valid subset of JavaScript because U+2028 (line separator)\n// and U+2029 (paragraph separator) are allowed in JSON string literals, but not in JS.\n// This function properly encodes those two characters so that the resulting string is\n// represents both valid JSON, and valid JavaScript (for ES2018 and below).\n// See https://v8.dev/features/subsume-json for more details.\nconst jsonToJS = str => str.replace(/\\u2028/g, '\\\\u2028').replace(/\\u2029/g, '\\\\u2029');\n\nlet ohmGrammar$1;\nlet buildGrammar$1;\n\nclass Grammar {\n constructor(name, superGrammar, rules, optDefaultStartRule) {\n this.name = name;\n this.superGrammar = superGrammar;\n this.rules = rules;\n if (optDefaultStartRule) {\n if (!(optDefaultStartRule in rules)) {\n throw new Error(\n \"Invalid start rule: '\" +\n optDefaultStartRule +\n \"' is not a rule in grammar '\" +\n name +\n \"'\",\n );\n }\n this.defaultStartRule = optDefaultStartRule;\n }\n this._matchStateInitializer = undefined;\n this.supportsIncrementalParsing = true;\n }\n\n matcher() {\n return new Matcher(this);\n }\n\n // Return true if the grammar is a built-in grammar, otherwise false.\n // NOTE: This might give an unexpected result if called before BuiltInRules is defined!\n isBuiltIn() {\n return this === Grammar.ProtoBuiltInRules || this === Grammar.BuiltInRules;\n }\n\n equals(g) {\n if (this === g) {\n return true;\n }\n // Do the cheapest comparisons first.\n if (\n g == null ||\n this.name !== g.name ||\n this.defaultStartRule !== g.defaultStartRule ||\n !(this.superGrammar === g.superGrammar || this.superGrammar.equals(g.superGrammar))\n ) {\n return false;\n }\n const myRules = getSortedRuleValues(this);\n const otherRules = getSortedRuleValues(g);\n return (\n myRules.length === otherRules.length &&\n myRules.every((rule, i) => {\n return (\n rule.description === otherRules[i].description &&\n rule.formals.join(',') === otherRules[i].formals.join(',') &&\n rule.body.toString() === otherRules[i].body.toString()\n );\n })\n );\n }\n\n match(input, optStartApplication) {\n const m = this.matcher();\n m.replaceInputRange(0, 0, input);\n return m.match(optStartApplication);\n }\n\n trace(input, optStartApplication) {\n const m = this.matcher();\n m.replaceInputRange(0, 0, input);\n return m.trace(optStartApplication);\n }\n\n createSemantics() {\n return Semantics.createSemantics(this);\n }\n\n extendSemantics(superSemantics) {\n return Semantics.createSemantics(this, superSemantics._getSemantics());\n }\n\n // Check that every key in `actionDict` corresponds to a semantic action, and that it maps to\n // a function of the correct arity. If not, throw an exception.\n _checkTopDownActionDict(what, name, actionDict) {\n const problems = [];\n\n // eslint-disable-next-line guard-for-in\n for (const k in actionDict) {\n const v = actionDict[k];\n const isSpecialAction = SPECIAL_ACTION_NAMES.includes(k);\n\n if (!isSpecialAction && !(k in this.rules)) {\n problems.push(`'${k}' is not a valid semantic action for '${this.name}'`);\n continue;\n }\n if (typeof v !== 'function') {\n problems.push(`'${k}' must be a function in an action dictionary for '${this.name}'`);\n continue;\n }\n const actual = v.length;\n const expected = this._topDownActionArity(k);\n if (actual !== expected) {\n let details;\n if (k === '_iter' || k === '_nonterminal') {\n details =\n `it should use a rest parameter, e.g. \\`${k}(...children) {}\\`. ` +\n 'NOTE: this is new in Ohm v16 — see https://ohmjs.org/d/ati for details.';\n } else {\n details = `expected ${expected}, got ${actual}`;\n }\n problems.push(`Semantic action '${k}' has the wrong arity: ${details}`);\n }\n }\n if (problems.length > 0) {\n const prettyProblems = problems.map(problem => '- ' + problem);\n const error = new Error(\n [\n `Found errors in the action dictionary of the '${name}' ${what}:`,\n ...prettyProblems,\n ].join('\\n'),\n );\n error.problems = problems;\n throw error;\n }\n }\n\n // Return the expected arity for a semantic action named `actionName`, which\n // is either a rule name or a special action name like '_nonterminal'.\n _topDownActionArity(actionName) {\n // All special actions have an expected arity of 0, though all but _terminal\n // are expected to use the rest parameter syntax (e.g. `_iter(...children)`).\n // This is considered to have arity 0, i.e. `((...args) => {}).length` is 0.\n return SPECIAL_ACTION_NAMES.includes(actionName) ?\n 0 :\n this.rules[actionName].body.getArity();\n }\n\n _inheritsFrom(grammar) {\n let g = this.superGrammar;\n while (g) {\n if (g.equals(grammar, true)) {\n return true;\n }\n g = g.superGrammar;\n }\n return false;\n }\n\n toRecipe(superGrammarExpr = undefined) {\n const metaInfo = {};\n // Include the grammar source if it is available.\n if (this.source) {\n metaInfo.source = this.source.contents;\n }\n\n let startRule = null;\n if (this.defaultStartRule) {\n startRule = this.defaultStartRule;\n }\n\n const rules = {};\n Object.keys(this.rules).forEach(ruleName => {\n const ruleInfo = this.rules[ruleName];\n const {body} = ruleInfo;\n const isDefinition = !this.superGrammar || !this.superGrammar.rules[ruleName];\n\n let operation;\n if (isDefinition) {\n operation = 'define';\n } else {\n operation = body instanceof Extend ? 'extend' : 'override';\n }\n\n const metaInfo = {};\n if (ruleInfo.source && this.source) {\n const adjusted = ruleInfo.source.relativeTo(this.source);\n metaInfo.sourceInterval = [adjusted.startIdx, adjusted.endIdx];\n }\n\n const description = isDefinition ? ruleInfo.description : null;\n const bodyRecipe = body.outputRecipe(ruleInfo.formals, this.source);\n\n rules[ruleName] = [\n operation, // \"define\"/\"extend\"/\"override\"\n metaInfo,\n description,\n ruleInfo.formals,\n bodyRecipe,\n ];\n });\n\n // If the caller provided an expression to use for the supergrammar, use that.\n // Otherwise, if the supergrammar is a user grammar, use its recipe inline.\n let superGrammarOutput = 'null';\n if (superGrammarExpr) {\n superGrammarOutput = superGrammarExpr;\n } else if (this.superGrammar && !this.superGrammar.isBuiltIn()) {\n superGrammarOutput = this.superGrammar.toRecipe();\n }\n\n const recipeElements = [\n ...['grammar', metaInfo, this.name].map(JSON.stringify),\n superGrammarOutput,\n ...[startRule, rules].map(JSON.stringify),\n ];\n return jsonToJS(`[${recipeElements.join(',')}]`);\n }\n\n // TODO: Come up with better names for these methods.\n // TODO: Write the analog of these methods for inherited attributes.\n toOperationActionDictionaryTemplate() {\n return this._toOperationOrAttributeActionDictionaryTemplate();\n }\n toAttributeActionDictionaryTemplate() {\n return this._toOperationOrAttributeActionDictionaryTemplate();\n }\n\n _toOperationOrAttributeActionDictionaryTemplate() {\n // TODO: add the super-grammar's templates at the right place, e.g., a case for AddExpr_plus\n // should appear next to other cases of AddExpr.\n\n const sb = new StringBuffer();\n sb.append('{');\n\n let first = true;\n // eslint-disable-next-line guard-for-in\n for (const ruleName in this.rules) {\n const {body} = this.rules[ruleName];\n if (first) {\n first = false;\n } else {\n sb.append(',');\n }\n sb.append('\\n');\n sb.append(' ');\n this.addSemanticActionTemplate(ruleName, body, sb);\n }\n\n sb.append('\\n}');\n return sb.contents();\n }\n\n addSemanticActionTemplate(ruleName, body, sb) {\n sb.append(ruleName);\n sb.append(': function(');\n const arity = this._topDownActionArity(ruleName);\n sb.append(repeat('_', arity).join(', '));\n sb.append(') {\\n');\n sb.append(' }');\n }\n\n // Parse a string which expresses a rule application in this grammar, and return the\n // resulting Apply node.\n parseApplication(str) {\n let app;\n if (str.indexOf('<') === -1) {\n // simple application\n app = new Apply(str);\n } else {\n // parameterized application\n const cst = ohmGrammar$1.match(str, 'Base_application');\n app = buildGrammar$1(cst, {});\n }\n\n // Ensure that the application is valid.\n if (!(app.ruleName in this.rules)) {\n throw undeclaredRule(app.ruleName, this.name);\n }\n const {formals} = this.rules[app.ruleName];\n if (formals.length !== app.args.length) {\n const {source} = this.rules[app.ruleName];\n throw wrongNumberOfParameters(\n app.ruleName,\n formals.length,\n app.args.length,\n source,\n );\n }\n return app;\n }\n\n _setUpMatchState(state) {\n if (this._matchStateInitializer) {\n this._matchStateInitializer(state);\n }\n }\n}\n\n// The following grammar contains a few rules that couldn't be written in \"userland\".\n// At the bottom of src/main.js, we create a sub-grammar of this grammar that's called\n// `BuiltInRules`. That grammar contains several convenience rules, e.g., `letter` and\n// `digit`, and is implicitly the super-grammar of any grammar whose super-grammar\n// isn't specified.\nGrammar.ProtoBuiltInRules = new Grammar(\n 'ProtoBuiltInRules', // name\n undefined, // supergrammar\n {\n any: {\n body: any,\n formals: [],\n description: 'any character',\n primitive: true,\n },\n end: {\n body: end,\n formals: [],\n description: 'end of input',\n primitive: true,\n },\n\n caseInsensitive: {\n body: new CaseInsensitiveTerminal(new Param(0)),\n formals: ['str'],\n primitive: true,\n },\n lower: {\n body: new UnicodeChar('Ll'),\n formals: [],\n description: 'a lowercase letter',\n primitive: true,\n },\n upper: {\n body: new UnicodeChar('Lu'),\n formals: [],\n description: 'an uppercase letter',\n primitive: true,\n },\n // Union of Lt (titlecase), Lm (modifier), and Lo (other), i.e. any letter not in Ll or Lu.\n unicodeLtmo: {\n body: new UnicodeChar('Ltmo'),\n formals: [],\n description: 'a Unicode character in Lt, Lm, or Lo',\n primitive: true,\n },\n\n // These rules are not truly primitive (they could be written in userland) but are defined\n // here for bootstrapping purposes.\n spaces: {\n body: new Star(new Apply('space')),\n formals: [],\n },\n space: {\n body: new Range('\\x00', ' '),\n formals: [],\n description: 'a space',\n },\n },\n);\n\n// This method is called from main.js once Ohm has loaded.\nGrammar.initApplicationParser = function(grammar, builderFn) {\n ohmGrammar$1 = grammar;\n buildGrammar$1 = builderFn;\n};\n\n// --------------------------------------------------------------------\n// Private Stuff\n// --------------------------------------------------------------------\n\n// Constructors\n\nclass GrammarDecl {\n constructor(name) {\n this.name = name;\n }\n\n // Helpers\n\n sourceInterval(startIdx, endIdx) {\n return this.source.subInterval(startIdx, endIdx - startIdx);\n }\n\n ensureSuperGrammar() {\n if (!this.superGrammar) {\n this.withSuperGrammar(\n // TODO: The conditional expression below is an ugly hack. It's kind of ok because\n // I doubt anyone will ever try to declare a grammar called `BuiltInRules`. Still,\n // we should try to find a better way to do this.\n this.name === 'BuiltInRules' ? Grammar.ProtoBuiltInRules : Grammar.BuiltInRules,\n );\n }\n return this.superGrammar;\n }\n\n ensureSuperGrammarRuleForOverriding(name, source) {\n const ruleInfo = this.ensureSuperGrammar().rules[name];\n if (!ruleInfo) {\n throw cannotOverrideUndeclaredRule(name, this.superGrammar.name, source);\n }\n return ruleInfo;\n }\n\n installOverriddenOrExtendedRule(name, formals, body, source) {\n const duplicateParameterNames$1 = getDuplicates(formals);\n if (duplicateParameterNames$1.length > 0) {\n throw duplicateParameterNames(name, duplicateParameterNames$1, source);\n }\n const ruleInfo = this.ensureSuperGrammar().rules[name];\n const expectedFormals = ruleInfo.formals;\n const expectedNumFormals = expectedFormals ? expectedFormals.length : 0;\n if (formals.length !== expectedNumFormals) {\n throw wrongNumberOfParameters(name, expectedNumFormals, formals.length, source);\n }\n return this.install(name, formals, body, ruleInfo.description, source);\n }\n\n install(name, formals, body, description, source, primitive = false) {\n this.rules[name] = {\n body: body.introduceParams(formals),\n formals,\n description,\n source,\n primitive,\n };\n return this;\n }\n\n // Stuff that you should only do once\n\n withSuperGrammar(superGrammar) {\n if (this.superGrammar) {\n throw new Error('the super grammar of a GrammarDecl cannot be set more than once');\n }\n this.superGrammar = superGrammar;\n this.rules = Object.create(superGrammar.rules);\n\n // Grammars with an explicit supergrammar inherit a default start rule.\n if (!superGrammar.isBuiltIn()) {\n this.defaultStartRule = superGrammar.defaultStartRule;\n }\n return this;\n }\n\n withDefaultStartRule(ruleName) {\n this.defaultStartRule = ruleName;\n return this;\n }\n\n withSource(source) {\n this.source = new InputStream(source).interval(0, source.length);\n return this;\n }\n\n // Creates a Grammar instance, and if it passes the sanity checks, returns it.\n build() {\n const grammar = new Grammar(\n this.name,\n this.ensureSuperGrammar(),\n this.rules,\n this.defaultStartRule,\n );\n // Initialize internal props that are inherited from the super grammar.\n grammar._matchStateInitializer = grammar.superGrammar._matchStateInitializer;\n grammar.supportsIncrementalParsing = grammar.superGrammar.supportsIncrementalParsing;\n\n // TODO: change the pexpr.prototype.assert... methods to make them add\n // exceptions to an array that's provided as an arg. Then we'll be able to\n // show more than one error of the same type at a time.\n // TODO: include the offending pexpr in the errors, that way we can show\n // the part of the source that caused it.\n const grammarErrors = [];\n let grammarHasInvalidApplications = false;\n Object.keys(grammar.rules).forEach(ruleName => {\n const {body} = grammar.rules[ruleName];\n try {\n body.assertChoicesHaveUniformArity(ruleName);\n } catch (e) {\n grammarErrors.push(e);\n }\n try {\n body.assertAllApplicationsAreValid(ruleName, grammar);\n } catch (e) {\n grammarErrors.push(e);\n grammarHasInvalidApplications = true;\n }\n });\n if (!grammarHasInvalidApplications) {\n // The following check can only be done if the grammar has no invalid applications.\n Object.keys(grammar.rules).forEach(ruleName => {\n const {body} = grammar.rules[ruleName];\n try {\n body.assertIteratedExprsAreNotNullable(grammar, []);\n } catch (e) {\n grammarErrors.push(e);\n }\n });\n }\n if (grammarErrors.length > 0) {\n throwErrors(grammarErrors);\n }\n if (this.source) {\n grammar.source = this.source;\n }\n\n return grammar;\n }\n\n // Rule declarations\n\n define(name, formals, body, description, source, primitive) {\n this.ensureSuperGrammar();\n if (this.superGrammar.rules[name]) {\n throw duplicateRuleDeclaration(name, this.name, this.superGrammar.name, source);\n } else if (this.rules[name]) {\n throw duplicateRuleDeclaration(name, this.name, this.name, source);\n }\n const duplicateParameterNames$1 = getDuplicates(formals);\n if (duplicateParameterNames$1.length > 0) {\n throw duplicateParameterNames(name, duplicateParameterNames$1, source);\n }\n return this.install(name, formals, body, description, source, primitive);\n }\n\n override(name, formals, body, descIgnored, source) {\n this.ensureSuperGrammarRuleForOverriding(name, source);\n this.installOverriddenOrExtendedRule(name, formals, body, source);\n return this;\n }\n\n extend(name, formals, fragment, descIgnored, source) {\n const ruleInfo = this.ensureSuperGrammar().rules[name];\n if (!ruleInfo) {\n throw cannotExtendUndeclaredRule(name, this.superGrammar.name, source);\n }\n const body = new Extend(this.superGrammar, name, fragment);\n body.source = fragment.source;\n this.installOverriddenOrExtendedRule(name, formals, body, source);\n return this;\n }\n}\n\n// --------------------------------------------------------------------\n// Private stuff\n// --------------------------------------------------------------------\n\nclass Builder {\n constructor() {\n this.currentDecl = null;\n this.currentRuleName = null;\n }\n\n newGrammar(name) {\n return new GrammarDecl(name);\n }\n\n grammar(metaInfo, name, superGrammar, defaultStartRule, rules) {\n const gDecl = new GrammarDecl(name);\n if (superGrammar) {\n // `superGrammar` may be a recipe (i.e. an Array), or an actual grammar instance.\n gDecl.withSuperGrammar(\n superGrammar instanceof Grammar ? superGrammar : this.fromRecipe(superGrammar),\n );\n }\n if (defaultStartRule) {\n gDecl.withDefaultStartRule(defaultStartRule);\n }\n if (metaInfo && metaInfo.source) {\n gDecl.withSource(metaInfo.source);\n }\n\n this.currentDecl = gDecl;\n Object.keys(rules).forEach(ruleName => {\n this.currentRuleName = ruleName;\n const ruleRecipe = rules[ruleName];\n\n const action = ruleRecipe[0]; // define/extend/override\n const metaInfo = ruleRecipe[1];\n const description = ruleRecipe[2];\n const formals = ruleRecipe[3];\n const body = this.fromRecipe(ruleRecipe[4]);\n\n let source;\n if (gDecl.source && metaInfo && metaInfo.sourceInterval) {\n source = gDecl.source.subInterval(\n metaInfo.sourceInterval[0],\n metaInfo.sourceInterval[1] - metaInfo.sourceInterval[0],\n );\n }\n gDecl[action](ruleName, formals, body, description, source);\n });\n this.currentRuleName = this.currentDecl = null;\n return gDecl.build();\n }\n\n terminal(x) {\n return new Terminal(x);\n }\n\n range(from, to) {\n return new Range(from, to);\n }\n\n param(index) {\n return new Param(index);\n }\n\n alt(...termArgs) {\n let terms = [];\n for (let arg of termArgs) {\n if (!(arg instanceof PExpr)) {\n arg = this.fromRecipe(arg);\n }\n if (arg instanceof Alt) {\n terms = terms.concat(arg.terms);\n } else {\n terms.push(arg);\n }\n }\n return terms.length === 1 ? terms[0] : new Alt(terms);\n }\n\n seq(...factorArgs) {\n let factors = [];\n for (let arg of factorArgs) {\n if (!(arg instanceof PExpr)) {\n arg = this.fromRecipe(arg);\n }\n if (arg instanceof Seq) {\n factors = factors.concat(arg.factors);\n } else {\n factors.push(arg);\n }\n }\n return factors.length === 1 ? factors[0] : new Seq(factors);\n }\n\n star(expr) {\n if (!(expr instanceof PExpr)) {\n expr = this.fromRecipe(expr);\n }\n return new Star(expr);\n }\n\n plus(expr) {\n if (!(expr instanceof PExpr)) {\n expr = this.fromRecipe(expr);\n }\n return new Plus(expr);\n }\n\n opt(expr) {\n if (!(expr instanceof PExpr)) {\n expr = this.fromRecipe(expr);\n }\n return new Opt(expr);\n }\n\n not(expr) {\n if (!(expr instanceof PExpr)) {\n expr = this.fromRecipe(expr);\n }\n return new Not(expr);\n }\n\n lookahead(expr) {\n if (!(expr instanceof PExpr)) {\n expr = this.fromRecipe(expr);\n }\n return new Lookahead(expr);\n }\n\n lex(expr) {\n if (!(expr instanceof PExpr)) {\n expr = this.fromRecipe(expr);\n }\n return new Lex(expr);\n }\n\n app(ruleName, optParams) {\n if (optParams && optParams.length > 0) {\n optParams = optParams.map(function(param) {\n return param instanceof PExpr ? param : this.fromRecipe(param);\n }, this);\n }\n return new Apply(ruleName, optParams);\n }\n\n // Note that unlike other methods in this class, this method cannot be used as a\n // convenience constructor. It only works with recipes, because it relies on\n // `this.currentDecl` and `this.currentRuleName` being set.\n splice(beforeTerms, afterTerms) {\n return new Splice(\n this.currentDecl.superGrammar,\n this.currentRuleName,\n beforeTerms.map(term => this.fromRecipe(term)),\n afterTerms.map(term => this.fromRecipe(term)),\n );\n }\n\n fromRecipe(recipe) {\n // the meta-info of 'grammar' is processed in Builder.grammar\n const args = recipe[0] === 'grammar' ? recipe.slice(1) : recipe.slice(2);\n const result = this[recipe[0]](...args);\n\n const metaInfo = recipe[1];\n if (metaInfo) {\n if (metaInfo.sourceInterval && this.currentDecl) {\n result.withSource(this.currentDecl.sourceInterval(...metaInfo.sourceInterval));\n }\n }\n return result;\n }\n}\n\nfunction makeRecipe(recipe) {\n if (typeof recipe === 'function') {\n return recipe.call(new Builder());\n } else {\n if (typeof recipe === 'string') {\n // stringified JSON recipe\n recipe = JSON.parse(recipe);\n }\n return new Builder().fromRecipe(recipe);\n }\n}\n\nvar BuiltInRules = makeRecipe([\"grammar\",{\"source\":\"BuiltInRules {\\n\\n alnum (an alpha-numeric character)\\n = letter\\n | digit\\n\\n letter (a letter)\\n = lower\\n | upper\\n | unicodeLtmo\\n\\n digit (a digit)\\n = \\\"0\\\"..\\\"9\\\"\\n\\n hexDigit (a hexadecimal digit)\\n = digit\\n | \\\"a\\\"..\\\"f\\\"\\n | \\\"A\\\"..\\\"F\\\"\\n\\n ListOf\\n = NonemptyListOf\\n | EmptyListOf\\n\\n NonemptyListOf\\n = elem (sep elem)*\\n\\n EmptyListOf\\n = /* nothing */\\n\\n listOf\\n = nonemptyListOf\\n | emptyListOf\\n\\n nonemptyListOf\\n = elem (sep elem)*\\n\\n emptyListOf\\n = /* nothing */\\n\\n // Allows a syntactic rule application within a lexical context.\\n applySyntactic = app\\n}\"},\"BuiltInRules\",null,null,{\"alnum\":[\"define\",{\"sourceInterval\":[18,78]},\"an alpha-numeric character\",[],[\"alt\",{\"sourceInterval\":[60,78]},[\"app\",{\"sourceInterval\":[60,66]},\"letter\",[]],[\"app\",{\"sourceInterval\":[73,78]},\"digit\",[]]]],\"letter\":[\"define\",{\"sourceInterval\":[82,142]},\"a letter\",[],[\"alt\",{\"sourceInterval\":[107,142]},[\"app\",{\"sourceInterval\":[107,112]},\"lower\",[]],[\"app\",{\"sourceInterval\":[119,124]},\"upper\",[]],[\"app\",{\"sourceInterval\":[131,142]},\"unicodeLtmo\",[]]]],\"digit\":[\"define\",{\"sourceInterval\":[146,177]},\"a digit\",[],[\"range\",{\"sourceInterval\":[169,177]},\"0\",\"9\"]],\"hexDigit\":[\"define\",{\"sourceInterval\":[181,254]},\"a hexadecimal digit\",[],[\"alt\",{\"sourceInterval\":[219,254]},[\"app\",{\"sourceInterval\":[219,224]},\"digit\",[]],[\"range\",{\"sourceInterval\":[231,239]},\"a\",\"f\"],[\"range\",{\"sourceInterval\":[246,254]},\"A\",\"F\"]]],\"ListOf\":[\"define\",{\"sourceInterval\":[258,336]},null,[\"elem\",\"sep\"],[\"alt\",{\"sourceInterval\":[282,336]},[\"app\",{\"sourceInterval\":[282,307]},\"NonemptyListOf\",[[\"param\",{\"sourceInterval\":[297,301]},0],[\"param\",{\"sourceInterval\":[303,306]},1]]],[\"app\",{\"sourceInterval\":[314,336]},\"EmptyListOf\",[[\"param\",{\"sourceInterval\":[326,330]},0],[\"param\",{\"sourceInterval\":[332,335]},1]]]]],\"NonemptyListOf\":[\"define\",{\"sourceInterval\":[340,388]},null,[\"elem\",\"sep\"],[\"seq\",{\"sourceInterval\":[372,388]},[\"param\",{\"sourceInterval\":[372,376]},0],[\"star\",{\"sourceInterval\":[377,388]},[\"seq\",{\"sourceInterval\":[378,386]},[\"param\",{\"sourceInterval\":[378,381]},1],[\"param\",{\"sourceInterval\":[382,386]},0]]]]],\"EmptyListOf\":[\"define\",{\"sourceInterval\":[392,434]},null,[\"elem\",\"sep\"],[\"seq\",{\"sourceInterval\":[438,438]}]],\"listOf\":[\"define\",{\"sourceInterval\":[438,516]},null,[\"elem\",\"sep\"],[\"alt\",{\"sourceInterval\":[462,516]},[\"app\",{\"sourceInterval\":[462,487]},\"nonemptyListOf\",[[\"param\",{\"sourceInterval\":[477,481]},0],[\"param\",{\"sourceInterval\":[483,486]},1]]],[\"app\",{\"sourceInterval\":[494,516]},\"emptyListOf\",[[\"param\",{\"sourceInterval\":[506,510]},0],[\"param\",{\"sourceInterval\":[512,515]},1]]]]],\"nonemptyListOf\":[\"define\",{\"sourceInterval\":[520,568]},null,[\"elem\",\"sep\"],[\"seq\",{\"sourceInterval\":[552,568]},[\"param\",{\"sourceInterval\":[552,556]},0],[\"star\",{\"sourceInterval\":[557,568]},[\"seq\",{\"sourceInterval\":[558,566]},[\"param\",{\"sourceInterval\":[558,561]},1],[\"param\",{\"sourceInterval\":[562,566]},0]]]]],\"emptyListOf\":[\"define\",{\"sourceInterval\":[572,682]},null,[\"elem\",\"sep\"],[\"seq\",{\"sourceInterval\":[685,685]}]],\"applySyntactic\":[\"define\",{\"sourceInterval\":[685,710]},null,[\"app\"],[\"param\",{\"sourceInterval\":[707,710]},0]]}]);\n\nGrammar.BuiltInRules = BuiltInRules;\nannounceBuiltInRules(Grammar.BuiltInRules);\n\nvar ohmGrammar = makeRecipe([\"grammar\",{\"source\":\"Ohm {\\n\\n Grammars\\n = Grammar*\\n\\n Grammar\\n = ident SuperGrammar? \\\"{\\\" Rule* \\\"}\\\"\\n\\n SuperGrammar\\n = \\\"<:\\\" ident\\n\\n Rule\\n = ident Formals? ruleDescr? \\\"=\\\" RuleBody -- define\\n | ident Formals? \\\":=\\\" OverrideRuleBody -- override\\n | ident Formals? \\\"+=\\\" RuleBody -- extend\\n\\n RuleBody\\n = \\\"|\\\"? NonemptyListOf\\n\\n TopLevelTerm\\n = Seq caseName -- inline\\n | Seq\\n\\n OverrideRuleBody\\n = \\\"|\\\"? NonemptyListOf\\n\\n OverrideTopLevelTerm\\n = \\\"...\\\" -- superSplice\\n | TopLevelTerm\\n\\n Formals\\n = \\\"<\\\" ListOf \\\">\\\"\\n\\n Params\\n = \\\"<\\\" ListOf \\\">\\\"\\n\\n Alt\\n = NonemptyListOf\\n\\n Seq\\n = Iter*\\n\\n Iter\\n = Pred \\\"*\\\" -- star\\n | Pred \\\"+\\\" -- plus\\n | Pred \\\"?\\\" -- opt\\n | Pred\\n\\n Pred\\n = \\\"~\\\" Lex -- not\\n | \\\"&\\\" Lex -- lookahead\\n | Lex\\n\\n Lex\\n = \\\"#\\\" Base -- lex\\n | Base\\n\\n Base\\n = ident Params? ~(ruleDescr? \\\"=\\\" | \\\":=\\\" | \\\"+=\\\") -- application\\n | oneCharTerminal \\\"..\\\" oneCharTerminal -- range\\n | terminal -- terminal\\n | \\\"(\\\" Alt \\\")\\\" -- paren\\n\\n ruleDescr (a rule description)\\n = \\\"(\\\" ruleDescrText \\\")\\\"\\n\\n ruleDescrText\\n = (~\\\")\\\" any)*\\n\\n caseName\\n = \\\"--\\\" (~\\\"\\\\n\\\" space)* name (~\\\"\\\\n\\\" space)* (\\\"\\\\n\\\" | &\\\"}\\\")\\n\\n name (a name)\\n = nameFirst nameRest*\\n\\n nameFirst\\n = \\\"_\\\"\\n | letter\\n\\n nameRest\\n = \\\"_\\\"\\n | alnum\\n\\n ident (an identifier)\\n = name\\n\\n terminal\\n = \\\"\\\\\\\"\\\" terminalChar* \\\"\\\\\\\"\\\"\\n\\n oneCharTerminal\\n = \\\"\\\\\\\"\\\" terminalChar \\\"\\\\\\\"\\\"\\n\\n terminalChar\\n = escapeChar\\n | ~\\\"\\\\\\\\\\\" ~\\\"\\\\\\\"\\\" ~\\\"\\\\n\\\" \\\"\\\\u{0}\\\"..\\\"\\\\u{10FFFF}\\\"\\n\\n escapeChar (an escape sequence)\\n = \\\"\\\\\\\\\\\\\\\\\\\" -- backslash\\n | \\\"\\\\\\\\\\\\\\\"\\\" -- doubleQuote\\n | \\\"\\\\\\\\\\\\'\\\" -- singleQuote\\n | \\\"\\\\\\\\b\\\" -- backspace\\n | \\\"\\\\\\\\n\\\" -- lineFeed\\n | \\\"\\\\\\\\r\\\" -- carriageReturn\\n | \\\"\\\\\\\\t\\\" -- tab\\n | \\\"\\\\\\\\u{\\\" hexDigit hexDigit? hexDigit?\\n hexDigit? hexDigit? hexDigit? \\\"}\\\" -- unicodeCodePoint\\n | \\\"\\\\\\\\u\\\" hexDigit hexDigit hexDigit hexDigit -- unicodeEscape\\n | \\\"\\\\\\\\x\\\" hexDigit hexDigit -- hexEscape\\n\\n space\\n += comment\\n\\n comment\\n = \\\"//\\\" (~\\\"\\\\n\\\" any)* &(\\\"\\\\n\\\" | end) -- singleLine\\n | \\\"/*\\\" (~\\\"*/\\\" any)* \\\"*/\\\" -- multiLine\\n\\n tokens = token*\\n\\n token = caseName | comment | ident | operator | punctuation | terminal | any\\n\\n operator = \\\"<:\\\" | \\\"=\\\" | \\\":=\\\" | \\\"+=\\\" | \\\"*\\\" | \\\"+\\\" | \\\"?\\\" | \\\"~\\\" | \\\"&\\\"\\n\\n punctuation = \\\"<\\\" | \\\">\\\" | \\\",\\\" | \\\"--\\\"\\n}\"},\"Ohm\",null,\"Grammars\",{\"Grammars\":[\"define\",{\"sourceInterval\":[9,32]},null,[],[\"star\",{\"sourceInterval\":[24,32]},[\"app\",{\"sourceInterval\":[24,31]},\"Grammar\",[]]]],\"Grammar\":[\"define\",{\"sourceInterval\":[36,83]},null,[],[\"seq\",{\"sourceInterval\":[50,83]},[\"app\",{\"sourceInterval\":[50,55]},\"ident\",[]],[\"opt\",{\"sourceInterval\":[56,69]},[\"app\",{\"sourceInterval\":[56,68]},\"SuperGrammar\",[]]],[\"terminal\",{\"sourceInterval\":[70,73]},\"{\"],[\"star\",{\"sourceInterval\":[74,79]},[\"app\",{\"sourceInterval\":[74,78]},\"Rule\",[]]],[\"terminal\",{\"sourceInterval\":[80,83]},\"}\"]]],\"SuperGrammar\":[\"define\",{\"sourceInterval\":[87,116]},null,[],[\"seq\",{\"sourceInterval\":[106,116]},[\"terminal\",{\"sourceInterval\":[106,110]},\"<:\"],[\"app\",{\"sourceInterval\":[111,116]},\"ident\",[]]]],\"Rule_define\":[\"define\",{\"sourceInterval\":[131,181]},null,[],[\"seq\",{\"sourceInterval\":[131,170]},[\"app\",{\"sourceInterval\":[131,136]},\"ident\",[]],[\"opt\",{\"sourceInterval\":[137,145]},[\"app\",{\"sourceInterval\":[137,144]},\"Formals\",[]]],[\"opt\",{\"sourceInterval\":[146,156]},[\"app\",{\"sourceInterval\":[146,155]},\"ruleDescr\",[]]],[\"terminal\",{\"sourceInterval\":[157,160]},\"=\"],[\"app\",{\"sourceInterval\":[162,170]},\"RuleBody\",[]]]],\"Rule_override\":[\"define\",{\"sourceInterval\":[188,248]},null,[],[\"seq\",{\"sourceInterval\":[188,235]},[\"app\",{\"sourceInterval\":[188,193]},\"ident\",[]],[\"opt\",{\"sourceInterval\":[194,202]},[\"app\",{\"sourceInterval\":[194,201]},\"Formals\",[]]],[\"terminal\",{\"sourceInterval\":[214,218]},\":=\"],[\"app\",{\"sourceInterval\":[219,235]},\"OverrideRuleBody\",[]]]],\"Rule_extend\":[\"define\",{\"sourceInterval\":[255,305]},null,[],[\"seq\",{\"sourceInterval\":[255,294]},[\"app\",{\"sourceInterval\":[255,260]},\"ident\",[]],[\"opt\",{\"sourceInterval\":[261,269]},[\"app\",{\"sourceInterval\":[261,268]},\"Formals\",[]]],[\"terminal\",{\"sourceInterval\":[281,285]},\"+=\"],[\"app\",{\"sourceInterval\":[286,294]},\"RuleBody\",[]]]],\"Rule\":[\"define\",{\"sourceInterval\":[120,305]},null,[],[\"alt\",{\"sourceInterval\":[131,305]},[\"app\",{\"sourceInterval\":[131,170]},\"Rule_define\",[]],[\"app\",{\"sourceInterval\":[188,235]},\"Rule_override\",[]],[\"app\",{\"sourceInterval\":[255,294]},\"Rule_extend\",[]]]],\"RuleBody\":[\"define\",{\"sourceInterval\":[309,362]},null,[],[\"seq\",{\"sourceInterval\":[324,362]},[\"opt\",{\"sourceInterval\":[324,328]},[\"terminal\",{\"sourceInterval\":[324,327]},\"|\"]],[\"app\",{\"sourceInterval\":[329,362]},\"NonemptyListOf\",[[\"app\",{\"sourceInterval\":[344,356]},\"TopLevelTerm\",[]],[\"terminal\",{\"sourceInterval\":[358,361]},\"|\"]]]]],\"TopLevelTerm_inline\":[\"define\",{\"sourceInterval\":[385,408]},null,[],[\"seq\",{\"sourceInterval\":[385,397]},[\"app\",{\"sourceInterval\":[385,388]},\"Seq\",[]],[\"app\",{\"sourceInterval\":[389,397]},\"caseName\",[]]]],\"TopLevelTerm\":[\"define\",{\"sourceInterval\":[366,418]},null,[],[\"alt\",{\"sourceInterval\":[385,418]},[\"app\",{\"sourceInterval\":[385,397]},\"TopLevelTerm_inline\",[]],[\"app\",{\"sourceInterval\":[415,418]},\"Seq\",[]]]],\"OverrideRuleBody\":[\"define\",{\"sourceInterval\":[422,491]},null,[],[\"seq\",{\"sourceInterval\":[445,491]},[\"opt\",{\"sourceInterval\":[445,449]},[\"terminal\",{\"sourceInterval\":[445,448]},\"|\"]],[\"app\",{\"sourceInterval\":[450,491]},\"NonemptyListOf\",[[\"app\",{\"sourceInterval\":[465,485]},\"OverrideTopLevelTerm\",[]],[\"terminal\",{\"sourceInterval\":[487,490]},\"|\"]]]]],\"OverrideTopLevelTerm_superSplice\":[\"define\",{\"sourceInterval\":[522,543]},null,[],[\"terminal\",{\"sourceInterval\":[522,527]},\"...\"]],\"OverrideTopLevelTerm\":[\"define\",{\"sourceInterval\":[495,562]},null,[],[\"alt\",{\"sourceInterval\":[522,562]},[\"app\",{\"sourceInterval\":[522,527]},\"OverrideTopLevelTerm_superSplice\",[]],[\"app\",{\"sourceInterval\":[550,562]},\"TopLevelTerm\",[]]]],\"Formals\":[\"define\",{\"sourceInterval\":[566,606]},null,[],[\"seq\",{\"sourceInterval\":[580,606]},[\"terminal\",{\"sourceInterval\":[580,583]},\"<\"],[\"app\",{\"sourceInterval\":[584,602]},\"ListOf\",[[\"app\",{\"sourceInterval\":[591,596]},\"ident\",[]],[\"terminal\",{\"sourceInterval\":[598,601]},\",\"]]],[\"terminal\",{\"sourceInterval\":[603,606]},\">\"]]],\"Params\":[\"define\",{\"sourceInterval\":[610,647]},null,[],[\"seq\",{\"sourceInterval\":[623,647]},[\"terminal\",{\"sourceInterval\":[623,626]},\"<\"],[\"app\",{\"sourceInterval\":[627,643]},\"ListOf\",[[\"app\",{\"sourceInterval\":[634,637]},\"Seq\",[]],[\"terminal\",{\"sourceInterval\":[639,642]},\",\"]]],[\"terminal\",{\"sourceInterval\":[644,647]},\">\"]]],\"Alt\":[\"define\",{\"sourceInterval\":[651,685]},null,[],[\"app\",{\"sourceInterval\":[661,685]},\"NonemptyListOf\",[[\"app\",{\"sourceInterval\":[676,679]},\"Seq\",[]],[\"terminal\",{\"sourceInterval\":[681,684]},\"|\"]]]],\"Seq\":[\"define\",{\"sourceInterval\":[689,704]},null,[],[\"star\",{\"sourceInterval\":[699,704]},[\"app\",{\"sourceInterval\":[699,703]},\"Iter\",[]]]],\"Iter_star\":[\"define\",{\"sourceInterval\":[719,736]},null,[],[\"seq\",{\"sourceInterval\":[719,727]},[\"app\",{\"sourceInterval\":[719,723]},\"Pred\",[]],[\"terminal\",{\"sourceInterval\":[724,727]},\"*\"]]],\"Iter_plus\":[\"define\",{\"sourceInterval\":[743,760]},null,[],[\"seq\",{\"sourceInterval\":[743,751]},[\"app\",{\"sourceInterval\":[743,747]},\"Pred\",[]],[\"terminal\",{\"sourceInterval\":[748,751]},\"+\"]]],\"Iter_opt\":[\"define\",{\"sourceInterval\":[767,783]},null,[],[\"seq\",{\"sourceInterval\":[767,775]},[\"app\",{\"sourceInterval\":[767,771]},\"Pred\",[]],[\"terminal\",{\"sourceInterval\":[772,775]},\"?\"]]],\"Iter\":[\"define\",{\"sourceInterval\":[708,794]},null,[],[\"alt\",{\"sourceInterval\":[719,794]},[\"app\",{\"sourceInterval\":[719,727]},\"Iter_star\",[]],[\"app\",{\"sourceInterval\":[743,751]},\"Iter_plus\",[]],[\"app\",{\"sourceInterval\":[767,775]},\"Iter_opt\",[]],[\"app\",{\"sourceInterval\":[790,794]},\"Pred\",[]]]],\"Pred_not\":[\"define\",{\"sourceInterval\":[809,824]},null,[],[\"seq\",{\"sourceInterval\":[809,816]},[\"terminal\",{\"sourceInterval\":[809,812]},\"~\"],[\"app\",{\"sourceInterval\":[813,816]},\"Lex\",[]]]],\"Pred_lookahead\":[\"define\",{\"sourceInterval\":[831,852]},null,[],[\"seq\",{\"sourceInterval\":[831,838]},[\"terminal\",{\"sourceInterval\":[831,834]},\"&\"],[\"app\",{\"sourceInterval\":[835,838]},\"Lex\",[]]]],\"Pred\":[\"define\",{\"sourceInterval\":[798,862]},null,[],[\"alt\",{\"sourceInterval\":[809,862]},[\"app\",{\"sourceInterval\":[809,816]},\"Pred_not\",[]],[\"app\",{\"sourceInterval\":[831,838]},\"Pred_lookahead\",[]],[\"app\",{\"sourceInterval\":[859,862]},\"Lex\",[]]]],\"Lex_lex\":[\"define\",{\"sourceInterval\":[876,892]},null,[],[\"seq\",{\"sourceInterval\":[876,884]},[\"terminal\",{\"sourceInterval\":[876,879]},\"#\"],[\"app\",{\"sourceInterval\":[880,884]},\"Base\",[]]]],\"Lex\":[\"define\",{\"sourceInterval\":[866,903]},null,[],[\"alt\",{\"sourceInterval\":[876,903]},[\"app\",{\"sourceInterval\":[876,884]},\"Lex_lex\",[]],[\"app\",{\"sourceInterval\":[899,903]},\"Base\",[]]]],\"Base_application\":[\"define\",{\"sourceInterval\":[918,979]},null,[],[\"seq\",{\"sourceInterval\":[918,963]},[\"app\",{\"sourceInterval\":[918,923]},\"ident\",[]],[\"opt\",{\"sourceInterval\":[924,931]},[\"app\",{\"sourceInterval\":[924,930]},\"Params\",[]]],[\"not\",{\"sourceInterval\":[932,963]},[\"alt\",{\"sourceInterval\":[934,962]},[\"seq\",{\"sourceInterval\":[934,948]},[\"opt\",{\"sourceInterval\":[934,944]},[\"app\",{\"sourceInterval\":[934,943]},\"ruleDescr\",[]]],[\"terminal\",{\"sourceInterval\":[945,948]},\"=\"]],[\"terminal\",{\"sourceInterval\":[951,955]},\":=\"],[\"terminal\",{\"sourceInterval\":[958,962]},\"+=\"]]]]],\"Base_range\":[\"define\",{\"sourceInterval\":[986,1041]},null,[],[\"seq\",{\"sourceInterval\":[986,1022]},[\"app\",{\"sourceInterval\":[986,1001]},\"oneCharTerminal\",[]],[\"terminal\",{\"sourceInterval\":[1002,1006]},\"..\"],[\"app\",{\"sourceInterval\":[1007,1022]},\"oneCharTerminal\",[]]]],\"Base_terminal\":[\"define\",{\"sourceInterval\":[1048,1106]},null,[],[\"app\",{\"sourceInterval\":[1048,1056]},\"terminal\",[]]],\"Base_paren\":[\"define\",{\"sourceInterval\":[1113,1168]},null,[],[\"seq\",{\"sourceInterval\":[1113,1124]},[\"terminal\",{\"sourceInterval\":[1113,1116]},\"(\"],[\"app\",{\"sourceInterval\":[1117,1120]},\"Alt\",[]],[\"terminal\",{\"sourceInterval\":[1121,1124]},\")\"]]],\"Base\":[\"define\",{\"sourceInterval\":[907,1168]},null,[],[\"alt\",{\"sourceInterval\":[918,1168]},[\"app\",{\"sourceInterval\":[918,963]},\"Base_application\",[]],[\"app\",{\"sourceInterval\":[986,1022]},\"Base_range\",[]],[\"app\",{\"sourceInterval\":[1048,1056]},\"Base_terminal\",[]],[\"app\",{\"sourceInterval\":[1113,1124]},\"Base_paren\",[]]]],\"ruleDescr\":[\"define\",{\"sourceInterval\":[1172,1231]},\"a rule description\",[],[\"seq\",{\"sourceInterval\":[1210,1231]},[\"terminal\",{\"sourceInterval\":[1210,1213]},\"(\"],[\"app\",{\"sourceInterval\":[1214,1227]},\"ruleDescrText\",[]],[\"terminal\",{\"sourceInterval\":[1228,1231]},\")\"]]],\"ruleDescrText\":[\"define\",{\"sourceInterval\":[1235,1266]},null,[],[\"star\",{\"sourceInterval\":[1255,1266]},[\"seq\",{\"sourceInterval\":[1256,1264]},[\"not\",{\"sourceInterval\":[1256,1260]},[\"terminal\",{\"sourceInterval\":[1257,1260]},\")\"]],[\"app\",{\"sourceInterval\":[1261,1264]},\"any\",[]]]]],\"caseName\":[\"define\",{\"sourceInterval\":[1270,1338]},null,[],[\"seq\",{\"sourceInterval\":[1285,1338]},[\"terminal\",{\"sourceInterval\":[1285,1289]},\"--\"],[\"star\",{\"sourceInterval\":[1290,1304]},[\"seq\",{\"sourceInterval\":[1291,1302]},[\"not\",{\"sourceInterval\":[1291,1296]},[\"terminal\",{\"sourceInterval\":[1292,1296]},\"\\n\"]],[\"app\",{\"sourceInterval\":[1297,1302]},\"space\",[]]]],[\"app\",{\"sourceInterval\":[1305,1309]},\"name\",[]],[\"star\",{\"sourceInterval\":[1310,1324]},[\"seq\",{\"sourceInterval\":[1311,1322]},[\"not\",{\"sourceInterval\":[1311,1316]},[\"terminal\",{\"sourceInterval\":[1312,1316]},\"\\n\"]],[\"app\",{\"sourceInterval\":[1317,1322]},\"space\",[]]]],[\"alt\",{\"sourceInterval\":[1326,1337]},[\"terminal\",{\"sourceInterval\":[1326,1330]},\"\\n\"],[\"lookahead\",{\"sourceInterval\":[1333,1337]},[\"terminal\",{\"sourceInterval\":[1334,1337]},\"}\"]]]]],\"name\":[\"define\",{\"sourceInterval\":[1342,1382]},\"a name\",[],[\"seq\",{\"sourceInterval\":[1363,1382]},[\"app\",{\"sourceInterval\":[1363,1372]},\"nameFirst\",[]],[\"star\",{\"sourceInterval\":[1373,1382]},[\"app\",{\"sourceInterval\":[1373,1381]},\"nameRest\",[]]]]],\"nameFirst\":[\"define\",{\"sourceInterval\":[1386,1418]},null,[],[\"alt\",{\"sourceInterval\":[1402,1418]},[\"terminal\",{\"sourceInterval\":[1402,1405]},\"_\"],[\"app\",{\"sourceInterval\":[1412,1418]},\"letter\",[]]]],\"nameRest\":[\"define\",{\"sourceInterval\":[1422,1452]},null,[],[\"alt\",{\"sourceInterval\":[1437,1452]},[\"terminal\",{\"sourceInterval\":[1437,1440]},\"_\"],[\"app\",{\"sourceInterval\":[1447,1452]},\"alnum\",[]]]],\"ident\":[\"define\",{\"sourceInterval\":[1456,1489]},\"an identifier\",[],[\"app\",{\"sourceInterval\":[1485,1489]},\"name\",[]]],\"terminal\":[\"define\",{\"sourceInterval\":[1493,1531]},null,[],[\"seq\",{\"sourceInterval\":[1508,1531]},[\"terminal\",{\"sourceInterval\":[1508,1512]},\"\\\"\"],[\"star\",{\"sourceInterval\":[1513,1526]},[\"app\",{\"sourceInterval\":[1513,1525]},\"terminalChar\",[]]],[\"terminal\",{\"sourceInterval\":[1527,1531]},\"\\\"\"]]],\"oneCharTerminal\":[\"define\",{\"sourceInterval\":[1535,1579]},null,[],[\"seq\",{\"sourceInterval\":[1557,1579]},[\"terminal\",{\"sourceInterval\":[1557,1561]},\"\\\"\"],[\"app\",{\"sourceInterval\":[1562,1574]},\"terminalChar\",[]],[\"terminal\",{\"sourceInterval\":[1575,1579]},\"\\\"\"]]],\"terminalChar\":[\"define\",{\"sourceInterval\":[1583,1660]},null,[],[\"alt\",{\"sourceInterval\":[1602,1660]},[\"app\",{\"sourceInterval\":[1602,1612]},\"escapeChar\",[]],[\"seq\",{\"sourceInterval\":[1621,1660]},[\"not\",{\"sourceInterval\":[1621,1626]},[\"terminal\",{\"sourceInterval\":[1622,1626]},\"\\\\\"]],[\"not\",{\"sourceInterval\":[1627,1632]},[\"terminal\",{\"sourceInterval\":[1628,1632]},\"\\\"\"]],[\"not\",{\"sourceInterval\":[1633,1638]},[\"terminal\",{\"sourceInterval\":[1634,1638]},\"\\n\"]],[\"range\",{\"sourceInterval\":[1639,1660]},\"\\u0000\",\"􏿿\"]]]],\"escapeChar_backslash\":[\"define\",{\"sourceInterval\":[1703,1758]},null,[],[\"terminal\",{\"sourceInterval\":[1703,1709]},\"\\\\\\\\\"]],\"escapeChar_doubleQuote\":[\"define\",{\"sourceInterval\":[1765,1822]},null,[],[\"terminal\",{\"sourceInterval\":[1765,1771]},\"\\\\\\\"\"]],\"escapeChar_singleQuote\":[\"define\",{\"sourceInterval\":[1829,1886]},null,[],[\"terminal\",{\"sourceInterval\":[1829,1835]},\"\\\\'\"]],\"escapeChar_backspace\":[\"define\",{\"sourceInterval\":[1893,1948]},null,[],[\"terminal\",{\"sourceInterval\":[1893,1898]},\"\\\\b\"]],\"escapeChar_lineFeed\":[\"define\",{\"sourceInterval\":[1955,2009]},null,[],[\"terminal\",{\"sourceInterval\":[1955,1960]},\"\\\\n\"]],\"escapeChar_carriageReturn\":[\"define\",{\"sourceInterval\":[2016,2076]},null,[],[\"terminal\",{\"sourceInterval\":[2016,2021]},\"\\\\r\"]],\"escapeChar_tab\":[\"define\",{\"sourceInterval\":[2083,2132]},null,[],[\"terminal\",{\"sourceInterval\":[2083,2088]},\"\\\\t\"]],\"escapeChar_unicodeCodePoint\":[\"define\",{\"sourceInterval\":[2139,2243]},null,[],[\"seq\",{\"sourceInterval\":[2139,2221]},[\"terminal\",{\"sourceInterval\":[2139,2145]},\"\\\\u{\"],[\"app\",{\"sourceInterval\":[2146,2154]},\"hexDigit\",[]],[\"opt\",{\"sourceInterval\":[2155,2164]},[\"app\",{\"sourceInterval\":[2155,2163]},\"hexDigit\",[]]],[\"opt\",{\"sourceInterval\":[2165,2174]},[\"app\",{\"sourceInterval\":[2165,2173]},\"hexDigit\",[]]],[\"opt\",{\"sourceInterval\":[2188,2197]},[\"app\",{\"sourceInterval\":[2188,2196]},\"hexDigit\",[]]],[\"opt\",{\"sourceInterval\":[2198,2207]},[\"app\",{\"sourceInterval\":[2198,2206]},\"hexDigit\",[]]],[\"opt\",{\"sourceInterval\":[2208,2217]},[\"app\",{\"sourceInterval\":[2208,2216]},\"hexDigit\",[]]],[\"terminal\",{\"sourceInterval\":[2218,2221]},\"}\"]]],\"escapeChar_unicodeEscape\":[\"define\",{\"sourceInterval\":[2250,2309]},null,[],[\"seq\",{\"sourceInterval\":[2250,2291]},[\"terminal\",{\"sourceInterval\":[2250,2255]},\"\\\\u\"],[\"app\",{\"sourceInterval\":[2256,2264]},\"hexDigit\",[]],[\"app\",{\"sourceInterval\":[2265,2273]},\"hexDigit\",[]],[\"app\",{\"sourceInterval\":[2274,2282]},\"hexDigit\",[]],[\"app\",{\"sourceInterval\":[2283,2291]},\"hexDigit\",[]]]],\"escapeChar_hexEscape\":[\"define\",{\"sourceInterval\":[2316,2371]},null,[],[\"seq\",{\"sourceInterval\":[2316,2339]},[\"terminal\",{\"sourceInterval\":[2316,2321]},\"\\\\x\"],[\"app\",{\"sourceInterval\":[2322,2330]},\"hexDigit\",[]],[\"app\",{\"sourceInterval\":[2331,2339]},\"hexDigit\",[]]]],\"escapeChar\":[\"define\",{\"sourceInterval\":[1664,2371]},\"an escape sequence\",[],[\"alt\",{\"sourceInterval\":[1703,2371]},[\"app\",{\"sourceInterval\":[1703,1709]},\"escapeChar_backslash\",[]],[\"app\",{\"sourceInterval\":[1765,1771]},\"escapeChar_doubleQuote\",[]],[\"app\",{\"sourceInterval\":[1829,1835]},\"escapeChar_singleQuote\",[]],[\"app\",{\"sourceInterval\":[1893,1898]},\"escapeChar_backspace\",[]],[\"app\",{\"sourceInterval\":[1955,1960]},\"escapeChar_lineFeed\",[]],[\"app\",{\"sourceInterval\":[2016,2021]},\"escapeChar_carriageReturn\",[]],[\"app\",{\"sourceInterval\":[2083,2088]},\"escapeChar_tab\",[]],[\"app\",{\"sourceInterval\":[2139,2221]},\"escapeChar_unicodeCodePoint\",[]],[\"app\",{\"sourceInterval\":[2250,2291]},\"escapeChar_unicodeEscape\",[]],[\"app\",{\"sourceInterval\":[2316,2339]},\"escapeChar_hexEscape\",[]]]],\"space\":[\"extend\",{\"sourceInterval\":[2375,2394]},null,[],[\"app\",{\"sourceInterval\":[2387,2394]},\"comment\",[]]],\"comment_singleLine\":[\"define\",{\"sourceInterval\":[2412,2458]},null,[],[\"seq\",{\"sourceInterval\":[2412,2443]},[\"terminal\",{\"sourceInterval\":[2412,2416]},\"//\"],[\"star\",{\"sourceInterval\":[2417,2429]},[\"seq\",{\"sourceInterval\":[2418,2427]},[\"not\",{\"sourceInterval\":[2418,2423]},[\"terminal\",{\"sourceInterval\":[2419,2423]},\"\\n\"]],[\"app\",{\"sourceInterval\":[2424,2427]},\"any\",[]]]],[\"lookahead\",{\"sourceInterval\":[2430,2443]},[\"alt\",{\"sourceInterval\":[2432,2442]},[\"terminal\",{\"sourceInterval\":[2432,2436]},\"\\n\"],[\"app\",{\"sourceInterval\":[2439,2442]},\"end\",[]]]]]],\"comment_multiLine\":[\"define\",{\"sourceInterval\":[2465,2501]},null,[],[\"seq\",{\"sourceInterval\":[2465,2487]},[\"terminal\",{\"sourceInterval\":[2465,2469]},\"/*\"],[\"star\",{\"sourceInterval\":[2470,2482]},[\"seq\",{\"sourceInterval\":[2471,2480]},[\"not\",{\"sourceInterval\":[2471,2476]},[\"terminal\",{\"sourceInterval\":[2472,2476]},\"*/\"]],[\"app\",{\"sourceInterval\":[2477,2480]},\"any\",[]]]],[\"terminal\",{\"sourceInterval\":[2483,2487]},\"*/\"]]],\"comment\":[\"define\",{\"sourceInterval\":[2398,2501]},null,[],[\"alt\",{\"sourceInterval\":[2412,2501]},[\"app\",{\"sourceInterval\":[2412,2443]},\"comment_singleLine\",[]],[\"app\",{\"sourceInterval\":[2465,2487]},\"comment_multiLine\",[]]]],\"tokens\":[\"define\",{\"sourceInterval\":[2505,2520]},null,[],[\"star\",{\"sourceInterval\":[2514,2520]},[\"app\",{\"sourceInterval\":[2514,2519]},\"token\",[]]]],\"token\":[\"define\",{\"sourceInterval\":[2524,2600]},null,[],[\"alt\",{\"sourceInterval\":[2532,2600]},[\"app\",{\"sourceInterval\":[2532,2540]},\"caseName\",[]],[\"app\",{\"sourceInterval\":[2543,2550]},\"comment\",[]],[\"app\",{\"sourceInterval\":[2553,2558]},\"ident\",[]],[\"app\",{\"sourceInterval\":[2561,2569]},\"operator\",[]],[\"app\",{\"sourceInterval\":[2572,2583]},\"punctuation\",[]],[\"app\",{\"sourceInterval\":[2586,2594]},\"terminal\",[]],[\"app\",{\"sourceInterval\":[2597,2600]},\"any\",[]]]],\"operator\":[\"define\",{\"sourceInterval\":[2604,2669]},null,[],[\"alt\",{\"sourceInterval\":[2615,2669]},[\"terminal\",{\"sourceInterval\":[2615,2619]},\"<:\"],[\"terminal\",{\"sourceInterval\":[2622,2625]},\"=\"],[\"terminal\",{\"sourceInterval\":[2628,2632]},\":=\"],[\"terminal\",{\"sourceInterval\":[2635,2639]},\"+=\"],[\"terminal\",{\"sourceInterval\":[2642,2645]},\"*\"],[\"terminal\",{\"sourceInterval\":[2648,2651]},\"+\"],[\"terminal\",{\"sourceInterval\":[2654,2657]},\"?\"],[\"terminal\",{\"sourceInterval\":[2660,2663]},\"~\"],[\"terminal\",{\"sourceInterval\":[2666,2669]},\"&\"]]],\"punctuation\":[\"define\",{\"sourceInterval\":[2673,2709]},null,[],[\"alt\",{\"sourceInterval\":[2687,2709]},[\"terminal\",{\"sourceInterval\":[2687,2690]},\"<\"],[\"terminal\",{\"sourceInterval\":[2693,2696]},\">\"],[\"terminal\",{\"sourceInterval\":[2699,2702]},\",\"],[\"terminal\",{\"sourceInterval\":[2705,2709]},\"--\"]]]}]);\n\nconst superSplicePlaceholder = Object.create(PExpr.prototype);\n\nfunction namespaceHas(ns, name) {\n // Look for an enumerable property, anywhere in the prototype chain.\n for (const prop in ns) {\n if (prop === name) return true;\n }\n return false;\n}\n\n// Returns a Grammar instance (i.e., an object with a `match` method) for\n// `tree`, which is the concrete syntax tree of a user-written grammar.\n// The grammar will be assigned into `namespace` under the name of the grammar\n// as specified in the source.\nfunction buildGrammar(match, namespace, optOhmGrammarForTesting) {\n const builder = new Builder();\n let decl;\n let currentRuleName;\n let currentRuleFormals;\n let overriding = false;\n const metaGrammar = optOhmGrammarForTesting || ohmGrammar;\n\n // A visitor that produces a Grammar instance from the CST.\n const helpers = metaGrammar.createSemantics().addOperation('visit', {\n Grammars(grammarIter) {\n return grammarIter.children.map(c => c.visit());\n },\n Grammar(id, s, _open, rules, _close) {\n const grammarName = id.visit();\n decl = builder.newGrammar(grammarName);\n s.child(0) && s.child(0).visit();\n rules.children.map(c => c.visit());\n const g = decl.build();\n g.source = this.source.trimmed();\n if (namespaceHas(namespace, grammarName)) {\n throw duplicateGrammarDeclaration(g);\n }\n namespace[grammarName] = g;\n return g;\n },\n\n SuperGrammar(_, n) {\n const superGrammarName = n.visit();\n if (superGrammarName === 'null') {\n decl.withSuperGrammar(null);\n } else {\n if (!namespace || !namespaceHas(namespace, superGrammarName)) {\n throw undeclaredGrammar(superGrammarName, namespace, n.source);\n }\n decl.withSuperGrammar(namespace[superGrammarName]);\n }\n },\n\n Rule_define(n, fs, d, _, b) {\n currentRuleName = n.visit();\n currentRuleFormals = fs.children.map(c => c.visit())[0] || [];\n // If there is no default start rule yet, set it now. This must be done before visiting\n // the body, because it might contain an inline rule definition.\n if (!decl.defaultStartRule && decl.ensureSuperGrammar() !== Grammar.ProtoBuiltInRules) {\n decl.withDefaultStartRule(currentRuleName);\n }\n const body = b.visit();\n const description = d.children.map(c => c.visit())[0];\n const source = this.source.trimmed();\n return decl.define(currentRuleName, currentRuleFormals, body, description, source);\n },\n Rule_override(n, fs, _, b) {\n currentRuleName = n.visit();\n currentRuleFormals = fs.children.map(c => c.visit())[0] || [];\n\n const source = this.source.trimmed();\n decl.ensureSuperGrammarRuleForOverriding(currentRuleName, source);\n\n overriding = true;\n const body = b.visit();\n overriding = false;\n return decl.override(currentRuleName, currentRuleFormals, body, null, source);\n },\n Rule_extend(n, fs, _, b) {\n currentRuleName = n.visit();\n currentRuleFormals = fs.children.map(c => c.visit())[0] || [];\n const body = b.visit();\n const source = this.source.trimmed();\n return decl.extend(currentRuleName, currentRuleFormals, body, null, source);\n },\n RuleBody(_, terms) {\n return builder.alt(...terms.visit()).withSource(this.source);\n },\n OverrideRuleBody(_, terms) {\n const args = terms.visit();\n\n // Check if the super-splice operator (`...`) appears in the terms.\n const expansionPos = args.indexOf(superSplicePlaceholder);\n if (expansionPos >= 0) {\n const beforeTerms = args.slice(0, expansionPos);\n const afterTerms = args.slice(expansionPos + 1);\n\n // Ensure it appears no more than once.\n afterTerms.forEach(t => {\n if (t === superSplicePlaceholder) throw multipleSuperSplices(t);\n });\n\n return new Splice(\n decl.superGrammar,\n currentRuleName,\n beforeTerms,\n afterTerms,\n ).withSource(this.source);\n } else {\n return builder.alt(...args).withSource(this.source);\n }\n },\n Formals(opointy, fs, cpointy) {\n return fs.visit();\n },\n\n Params(opointy, ps, cpointy) {\n return ps.visit();\n },\n\n Alt(seqs) {\n return builder.alt(...seqs.visit()).withSource(this.source);\n },\n\n TopLevelTerm_inline(b, n) {\n const inlineRuleName = currentRuleName + '_' + n.visit();\n const body = b.visit();\n const source = this.source.trimmed();\n const isNewRuleDeclaration = !(\n decl.superGrammar && decl.superGrammar.rules[inlineRuleName]\n );\n if (overriding && !isNewRuleDeclaration) {\n decl.override(inlineRuleName, currentRuleFormals, body, null, source);\n } else {\n decl.define(inlineRuleName, currentRuleFormals, body, null, source);\n }\n const params = currentRuleFormals.map(formal => builder.app(formal));\n return builder.app(inlineRuleName, params).withSource(body.source);\n },\n OverrideTopLevelTerm_superSplice(_) {\n return superSplicePlaceholder;\n },\n\n Seq(expr) {\n return builder.seq(...expr.children.map(c => c.visit())).withSource(this.source);\n },\n\n Iter_star(x, _) {\n return builder.star(x.visit()).withSource(this.source);\n },\n Iter_plus(x, _) {\n return builder.plus(x.visit()).withSource(this.source);\n },\n Iter_opt(x, _) {\n return builder.opt(x.visit()).withSource(this.source);\n },\n\n Pred_not(_, x) {\n return builder.not(x.visit()).withSource(this.source);\n },\n Pred_lookahead(_, x) {\n return builder.lookahead(x.visit()).withSource(this.source);\n },\n\n Lex_lex(_, x) {\n return builder.lex(x.visit()).withSource(this.source);\n },\n\n Base_application(rule, ps) {\n const params = ps.children.map(c => c.visit())[0] || [];\n return builder.app(rule.visit(), params).withSource(this.source);\n },\n Base_range(from, _, to) {\n return builder.range(from.visit(), to.visit()).withSource(this.source);\n },\n Base_terminal(expr) {\n return builder.terminal(expr.visit()).withSource(this.source);\n },\n Base_paren(open, x, close) {\n return x.visit();\n },\n\n ruleDescr(open, t, close) {\n return t.visit();\n },\n ruleDescrText(_) {\n return this.sourceString.trim();\n },\n\n caseName(_, space1, n, space2, end) {\n return n.visit();\n },\n\n name(first, rest) {\n return this.sourceString;\n },\n nameFirst(expr) {},\n nameRest(expr) {},\n\n terminal(open, cs, close) {\n return cs.children.map(c => c.visit()).join('');\n },\n\n oneCharTerminal(open, c, close) {\n return c.visit();\n },\n\n escapeChar(c) {\n try {\n return unescapeCodePoint(this.sourceString);\n } catch (err) {\n if (err instanceof RangeError && err.message.startsWith('Invalid code point ')) {\n throw invalidCodePoint(c);\n }\n throw err; // Rethrow\n }\n },\n\n NonemptyListOf(x, _, xs) {\n return [x.visit()].concat(xs.children.map(c => c.visit()));\n },\n EmptyListOf() {\n return [];\n },\n\n _terminal() {\n return this.sourceString;\n },\n });\n return helpers(match).visit();\n}\n\nvar operationsAndAttributesGrammar = makeRecipe([\"grammar\",{\"source\":\"OperationsAndAttributes {\\n\\n AttributeSignature =\\n name\\n\\n OperationSignature =\\n name Formals?\\n\\n Formals\\n = \\\"(\\\" ListOf \\\")\\\"\\n\\n name (a name)\\n = nameFirst nameRest*\\n\\n nameFirst\\n = \\\"_\\\"\\n | letter\\n\\n nameRest\\n = \\\"_\\\"\\n | alnum\\n\\n}\"},\"OperationsAndAttributes\",null,\"AttributeSignature\",{\"AttributeSignature\":[\"define\",{\"sourceInterval\":[29,58]},null,[],[\"app\",{\"sourceInterval\":[54,58]},\"name\",[]]],\"OperationSignature\":[\"define\",{\"sourceInterval\":[62,100]},null,[],[\"seq\",{\"sourceInterval\":[87,100]},[\"app\",{\"sourceInterval\":[87,91]},\"name\",[]],[\"opt\",{\"sourceInterval\":[92,100]},[\"app\",{\"sourceInterval\":[92,99]},\"Formals\",[]]]]],\"Formals\":[\"define\",{\"sourceInterval\":[104,143]},null,[],[\"seq\",{\"sourceInterval\":[118,143]},[\"terminal\",{\"sourceInterval\":[118,121]},\"(\"],[\"app\",{\"sourceInterval\":[122,139]},\"ListOf\",[[\"app\",{\"sourceInterval\":[129,133]},\"name\",[]],[\"terminal\",{\"sourceInterval\":[135,138]},\",\"]]],[\"terminal\",{\"sourceInterval\":[140,143]},\")\"]]],\"name\":[\"define\",{\"sourceInterval\":[147,187]},\"a name\",[],[\"seq\",{\"sourceInterval\":[168,187]},[\"app\",{\"sourceInterval\":[168,177]},\"nameFirst\",[]],[\"star\",{\"sourceInterval\":[178,187]},[\"app\",{\"sourceInterval\":[178,186]},\"nameRest\",[]]]]],\"nameFirst\":[\"define\",{\"sourceInterval\":[191,223]},null,[],[\"alt\",{\"sourceInterval\":[207,223]},[\"terminal\",{\"sourceInterval\":[207,210]},\"_\"],[\"app\",{\"sourceInterval\":[217,223]},\"letter\",[]]]],\"nameRest\":[\"define\",{\"sourceInterval\":[227,257]},null,[],[\"alt\",{\"sourceInterval\":[242,257]},[\"terminal\",{\"sourceInterval\":[242,245]},\"_\"],[\"app\",{\"sourceInterval\":[252,257]},\"alnum\",[]]]]}]);\n\ninitBuiltInSemantics(Grammar.BuiltInRules);\ninitPrototypeParser(operationsAndAttributesGrammar); // requires BuiltInSemantics\n\nfunction initBuiltInSemantics(builtInRules) {\n const actions = {\n empty() {\n return this.iteration();\n },\n nonEmpty(first, _, rest) {\n return this.iteration([first].concat(rest.children));\n },\n };\n\n Semantics.BuiltInSemantics = Semantics.createSemantics(builtInRules, null).addOperation(\n 'asIteration',\n {\n emptyListOf: actions.empty,\n nonemptyListOf: actions.nonEmpty,\n EmptyListOf: actions.empty,\n NonemptyListOf: actions.nonEmpty,\n },\n );\n}\n\nfunction initPrototypeParser(grammar) {\n Semantics.prototypeGrammarSemantics = grammar.createSemantics().addOperation('parse', {\n AttributeSignature(name) {\n return {\n name: name.parse(),\n formals: [],\n };\n },\n OperationSignature(name, optFormals) {\n return {\n name: name.parse(),\n formals: optFormals.children.map(c => c.parse())[0] || [],\n };\n },\n Formals(oparen, fs, cparen) {\n return fs.asIteration().children.map(c => c.parse());\n },\n name(first, rest) {\n return this.sourceString;\n },\n });\n Semantics.prototypeGrammar = grammar;\n}\n\nfunction findIndentation(input) {\n let pos = 0;\n const stack = [0];\n const topOfStack = () => stack[stack.length - 1];\n\n const result = {};\n\n const regex = /( *).*(?:$|\\r?\\n|\\r)/g;\n let match;\n while ((match = regex.exec(input)) != null) {\n const [line, indent] = match;\n\n // The last match will always have length 0. In every other case, some\n // characters will be matched (possibly only the end of line chars).\n if (line.length === 0) break;\n\n const indentSize = indent.length;\n const prevSize = topOfStack();\n\n const indentPos = pos + indentSize;\n\n if (indentSize > prevSize) {\n // Indent -- always only 1.\n stack.push(indentSize);\n result[indentPos] = 1;\n } else if (indentSize < prevSize) {\n // Dedent -- can be multiple levels.\n const prevLength = stack.length;\n while (topOfStack() !== indentSize) {\n stack.pop();\n }\n result[indentPos] = -1 * (prevLength - stack.length);\n }\n pos += line.length;\n }\n // Ensure that there is a matching DEDENT for every remaining INDENT.\n if (stack.length > 1) {\n result[pos] = 1 - stack.length;\n }\n return result;\n}\n\nconst INDENT_DESCRIPTION = 'an indented block';\nconst DEDENT_DESCRIPTION = 'a dedent';\n\n// A sentinel value that is out of range for both charCodeAt() and codePointAt().\nconst INVALID_CODE_POINT = 0x10ffff + 1;\n\nclass InputStreamWithIndentation extends InputStream {\n constructor(state) {\n super(state.input);\n this.state = state;\n }\n\n _indentationAt(pos) {\n return this.state.userData[pos] || 0;\n }\n\n atEnd() {\n return super.atEnd() && this._indentationAt(this.pos) === 0;\n }\n\n next() {\n if (this._indentationAt(this.pos) !== 0) {\n this.examinedLength = Math.max(this.examinedLength, this.pos);\n return undefined;\n }\n return super.next();\n }\n\n nextCharCode() {\n if (this._indentationAt(this.pos) !== 0) {\n this.examinedLength = Math.max(this.examinedLength, this.pos);\n return INVALID_CODE_POINT;\n }\n return super.nextCharCode();\n }\n\n nextCodePoint() {\n if (this._indentationAt(this.pos) !== 0) {\n this.examinedLength = Math.max(this.examinedLength, this.pos);\n return INVALID_CODE_POINT;\n }\n return super.nextCodePoint();\n }\n}\n\nclass Indentation extends PExpr {\n constructor(isIndent = true) {\n super();\n this.isIndent = isIndent;\n }\n\n allowsSkippingPrecedingSpace() {\n return true;\n }\n\n eval(state) {\n const {inputStream} = state;\n const pseudoTokens = state.userData;\n state.doNotMemoize = true;\n\n const origPos = inputStream.pos;\n\n const sign = this.isIndent ? 1 : -1;\n const count = (pseudoTokens[origPos] || 0) * sign;\n if (count > 0) {\n // Update the count to consume the pseudotoken.\n state.userData = Object.create(pseudoTokens);\n state.userData[origPos] -= sign;\n\n state.pushBinding(new TerminalNode(0), origPos);\n return true;\n } else {\n state.processFailure(origPos, this);\n return false;\n }\n }\n\n getArity() {\n return 1;\n }\n\n _assertAllApplicationsAreValid(ruleName, grammar) {}\n\n _isNullable(grammar, memo) {\n return false;\n }\n\n assertChoicesHaveUniformArity(ruleName) {}\n\n assertIteratedExprsAreNotNullable(grammar) {}\n\n introduceParams(formals) {\n return this;\n }\n\n substituteParams(actuals) {\n return this;\n }\n\n toString() {\n return this.isIndent ? 'indent' : 'dedent';\n }\n\n toDisplayString() {\n return this.toString();\n }\n\n toFailure(grammar) {\n const description = this.isIndent ? INDENT_DESCRIPTION : DEDENT_DESCRIPTION;\n return new Failure(this, description, 'description');\n }\n}\n\n// Create a new definition for `any` that can consume indent & dedent.\nconst applyIndent = new Apply('indent');\nconst applyDedent = new Apply('dedent');\nconst newAnyBody = new Splice(BuiltInRules, 'any', [applyIndent, applyDedent], []);\n\nconst IndentationSensitive = new Builder()\n .newGrammar('IndentationSensitive')\n .withSuperGrammar(BuiltInRules)\n .define('indent', [], new Indentation(true), INDENT_DESCRIPTION, undefined, true)\n .define('dedent', [], new Indentation(false), DEDENT_DESCRIPTION, undefined, true)\n .extend('any', [], newAnyBody, 'any character', undefined)\n .build();\n\nObject.assign(IndentationSensitive, {\n _matchStateInitializer(state) {\n state.userData = findIndentation(state.input);\n state.inputStream = new InputStreamWithIndentation(state);\n },\n supportsIncrementalParsing: false,\n});\n\n// Generated by scripts/prebuild.js\nconst version = '17.1.0';\n\nGrammar.initApplicationParser(ohmGrammar, buildGrammar);\n\nconst isBuffer = obj =>\n !!obj.constructor &&\n typeof obj.constructor.isBuffer === 'function' &&\n obj.constructor.isBuffer(obj);\n\nfunction compileAndLoad(source, namespace) {\n const m = ohmGrammar.match(source, 'Grammars');\n if (m.failed()) {\n throw grammarSyntaxError(m);\n }\n return buildGrammar(m, namespace);\n}\n\nfunction grammar(source, optNamespace) {\n const ns = grammars(source, optNamespace);\n\n // Ensure that the source contained no more than one grammar definition.\n const grammarNames = Object.keys(ns);\n if (grammarNames.length === 0) {\n throw new Error('Missing grammar definition');\n } else if (grammarNames.length > 1) {\n const secondGrammar = ns[grammarNames[1]];\n const interval = secondGrammar.source;\n throw new Error(\n getLineAndColumnMessage(interval.sourceString, interval.startIdx) +\n 'Found more than one grammar definition -- use ohm.grammars() instead.',\n );\n }\n return ns[grammarNames[0]]; // Return the one and only grammar.\n}\n\nfunction grammars(source, optNamespace) {\n const ns = Object.create(optNamespace || {});\n if (typeof source !== 'string') {\n // For convenience, detect Node.js Buffer objects and automatically call toString().\n if (isBuffer(source)) {\n source = source.toString();\n } else {\n throw new TypeError(\n 'Expected string as first argument, got ' + unexpectedObjToString(source),\n );\n }\n }\n compileAndLoad(source, ns);\n return ns;\n}\n\nexports.ExperimentalIndentationSensitive = IndentationSensitive;\nexports._buildGrammar = buildGrammar;\nexports.grammar = grammar;\nexports.grammars = grammars;\nexports.makeRecipe = makeRecipe;\nexports.ohmGrammar = ohmGrammar;\nexports.pexprs = pexprs;\nexports.version = version;\n//# sourceMappingURL=ohm.cjs.map\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(341);\n"],"sourceRoot":""} \ No newline at end of file diff --git a/src/NDArray-class.ts b/src/NDArray-class.ts index 436b334..72cec37 100644 --- a/src/NDArray-class.ts +++ b/src/NDArray-class.ts @@ -13,17 +13,20 @@ class NDArray { modules: typeof import("./NDArray").modules; - any: (axis?: AxisArg, keepdims?: boolean) => NDArray | boolean; - all: (axis?: AxisArg, keepdims?: boolean) => NDArray | boolean; - sum: (axis?: AxisArg, keepdims?: boolean) => NDArray | number; - product: (axis?: AxisArg, keepdims?: boolean) => NDArray | number; - max: (axis?: AxisArg, keepdims?: boolean) => NDArray | number; - min: (axis?: AxisArg, keepdims?: boolean) => NDArray | number; - argmax: (axis?: AxisArg, keepdims?: boolean) => NDArray | number; - argmin: (axis?: AxisArg, keepdims?: boolean) => NDArray | number; - mean: (axis?: AxisArg, keepdims?: boolean) => NDArray | number; - var: (axis?: AxisArg, keepdims?: boolean) => NDArray | number; - std: (axis?: AxisArg, keepdims?: boolean) => NDArray | number; + any: ReduceSignatureBool; + all: ReduceSignatureBool; + sum: ReduceSignature; + product: ReduceSignature; + max: ReduceSignature; + min: ReduceSignature; + argmax: ReduceSignature; + argmin: ReduceSignature; + mean: ReduceSignature; + + var: ReduceSignature; + std: ReduceStdSignature; + norm: ReduceNormSignature; + add: SelfBinaryOperator; subtract: SelfBinaryOperator; multiply: SelfBinaryOperator; @@ -32,12 +35,13 @@ class NDArray { divide_int: SelfBinaryOperator; pow: SelfBinaryOperator; maximum: SelfBinaryOperator; + minimum: SelfBinaryOperator; bitwise_or: SelfBinaryOperator; bitwise_and: SelfBinaryOperator; bitwise_shift_right: SelfBinaryOperator; logical_xor: SelfBinaryOperator; logical_or: SelfBinaryOperator; - minimum: SelfBinaryOperator; + logical_and: SelfBinaryOperator; greater: SelfBinaryOperator; less: SelfBinaryOperator; @@ -47,6 +51,9 @@ class NDArray { not_equal: SelfBinaryOperator; isclose: (A: any, B: any, rtol?: number, atol?: number, equal_nan?: boolean) => number | boolean | NDArray; allclose: (A: any, B: any, rtol?: number, atol?: number, equal_nan?: boolean) => boolean; + + abs: SelfUnaryOperator; + assign: SelfAssignmentOperator; add_assign: SelfAssignmentOperator; subtract_assign: SelfAssignmentOperator; @@ -66,7 +73,7 @@ class NDArray { tolist: () => any; // fromJS: (A: any) => NDArray; - round: (decimals?: number) => NDArray; + round: RoundSignature; sort: (axis?: number) => NDArray; transpose: (axes?: number[]) => NDArray; op: (...args: any[]) => NDArray; @@ -131,8 +138,9 @@ import { GLOBALS } from './_globals'; GLOBALS.NDArray = NDArray; import { modules } from "./NDArray"; -import { SelfAssignmentOperator, SelfBinaryOperator } from './NDArray/operators'; -import { AxisArg } from './NDArray/reduce'; +import { SelfAssignmentOperator, SelfBinaryOperator, SelfUnaryOperator } from './NDArray/operators'; +// import { AxisArg, ReduceKwArgs } from './NDArray/reduce'; +import { AxisArg, KwParser, ReduceKwargs, ReduceNormSignature, ReduceSignature, ReduceSignatureBool, ReduceStdSignature, RoundKwargs, RoundParsedKwargs, RoundSignature } from './NDArray/kwargs'; NDArray.prototype.modules = modules; @@ -181,24 +189,39 @@ NDArray.prototype.toString = function () { // ============================== -function reduceDecorator(func) { - return function (axis: import("./NDArray/reduce").AxisArg = null, keepdims: boolean = false) { - ({ axis, keepdims } = Object.assign({ axis, keepdims }, this.__popKwArgs())); - return func(this, axis, keepdims); - } -} -NDArray.prototype.sum = reduceDecorator(modules.reduce.reducers.sum); -NDArray.prototype.product = reduceDecorator(modules.reduce.reducers.product); -NDArray.prototype.any = reduceDecorator(modules.reduce.reducers.any); -NDArray.prototype.all = reduceDecorator(modules.reduce.reducers.all); -NDArray.prototype.max = reduceDecorator(modules.reduce.reducers.max); -NDArray.prototype.min = reduceDecorator(modules.reduce.reducers.min); -NDArray.prototype.argmax = reduceDecorator(modules.reduce.reducers.argmax); -NDArray.prototype.argmin = reduceDecorator(modules.reduce.reducers.argmin); -NDArray.prototype.mean = reduceDecorator(modules.reduce.reducers.mean); -NDArray.prototype.var = reduceDecorator(modules.reduce.reducers.var); -NDArray.prototype.std = reduceDecorator(modules.reduce.reducers.std); +NDArray.prototype.any = modules.reduce.self_reducers.any; +NDArray.prototype.all = modules.reduce.self_reducers.all; + +NDArray.prototype.sum = modules.reduce.self_reducers.sum; +NDArray.prototype.product = modules.reduce.self_reducers.product; +NDArray.prototype.max = modules.reduce.self_reducers.max; +NDArray.prototype.min = modules.reduce.self_reducers.min; +NDArray.prototype.argmax = modules.reduce.self_reducers.argmax; +NDArray.prototype.argmin = modules.reduce.self_reducers.argmin; +NDArray.prototype.mean = modules.reduce.self_reducers.mean; + +NDArray.prototype.var = modules.reduce.self_reducers.var; +NDArray.prototype.std = modules.reduce.self_reducers.std; + + +// function reduceDecorator(func) { +// return function (axis: import("./NDArray/reduce").AxisArg = null, keepdims: boolean = false) { +// ({ axis, keepdims } = Object.assign({ axis, keepdims }, this.__popKwArgs())); +// return func(this, axis, keepdims); +// } +// } +// reducersExtra +// NDArray.prototype.var = reduceDecorator(modules.reduce.self_reducers.var); + +// NDArray.prototype.norm = function (axis: import("./NDArray/reduce").AxisArg = null, keepdims: boolean = false, ord = 2) { +// ({ axis, keepdims, ord } = Object.assign({ axis, keepdims, ord }, this.__popKwArgs())); +// return modules.reduce.reducers.norm(this, axis, keepdims, ord); +// } as any; +// NDArray.prototype.std = function (axis: import("./NDArray/reduce").AxisArg = null, keepdims: boolean = false, ddof = 0) { +// ({ axis, keepdims, ddof } = Object.assign({ axis, keepdims, ddof }, this.__popKwArgs())); +// return modules.reduce.reducers.std(this, axis, keepdims, ddof); +// } @@ -253,6 +276,8 @@ function unaryOpDecorator(func: import("./NDArray/operators").UnaryOperator): im // Unary operations: only boolean_not. Positive is useless and negative is almost useless NDArray.prototype.bitwise_or = unaryOpDecorator(modules.operators.op_unary["~"]); NDArray.prototype.logical_or = unaryOpDecorator(modules.operators.op_unary["not"]); +NDArray.prototype.abs = unaryOpDecorator(modules.operators.op_unary["abs"]); + NDArray.prototype.isclose = modules.operators.isclose; @@ -300,10 +325,7 @@ NDArray.prototype.tolist = function () { // elementwise methods // ============================== -NDArray.prototype.round = function (decimals = 0) { - ({ decimals } = Object.assign({ decimals }, this.__popKwArgs())); - return modules.elementwise.round(this, decimals); -}; +NDArray.prototype.round = modules.elementwise.round_kw.as_method; // ============================== // transform methods diff --git a/src/NDArray/elementwise.ts b/src/NDArray/elementwise.ts index 933dc9f..7328770 100644 --- a/src/NDArray/elementwise.ts +++ b/src/NDArray/elementwise.ts @@ -2,19 +2,20 @@ import { asarray, new_NDArray } from './basic'; import type NDArray from "../NDArray-class"; +import { KwParser, RoundParsedKwargs, RoundSignature } from './kwargs'; // Here, we declare only the core functions (those that are methods) -export function elementwise(A, func, dtype) { +export function elementwise(A: NDArray, func, dtype) { A = asarray(A); return new_NDArray(A.flat.map(func), A.shape, dtype); } - -export function round(A, decimals = 0) { +export function round(A: NDArray, decimals: number) { if (decimals == 0) elementwise(A, Math.round, Number); return elementwise(A, x => parseFloat(x.toFixed(decimals)), Number); }; +export const round_kw = new KwParser([["decimals", 0]]).decorators(round) export function bitwise_not(A: NDArray) { return elementwise(A, x => ~x, Number); diff --git a/src/NDArray/kwargs.ts b/src/NDArray/kwargs.ts new file mode 100644 index 0000000..be45c4e --- /dev/null +++ b/src/NDArray/kwargs.ts @@ -0,0 +1,61 @@ +import { NDArray } from "../NDArray-class"; + +export type AxisArg = null | number; + +export type ReduceKwargs = { axis?: number, keepdims?: boolean }; +export type ReduceSignature = (axis?: AxisArg | ReduceKwargs, keepdims?: boolean | ReduceKwargs) => NDArray | T; +export type ReduceSignatureBool = ReduceSignature; +export type ReduceParsedKwargs = [number, boolean]; + +export type ReduceStdKwargs = { axis?: number, keepdims?: boolean, ddof?: number }; +export type ReduceStdSignature = (axis?: AxisArg | ReduceStdKwargs, keepdims?: boolean | ReduceStdKwargs, ddof?: number | ReduceStdKwargs) => NDArray | number; +export type ReduceStdParsedKwargs = [number, boolean, number]; + +export type ReduceNormKwargs = { axis?: number, keepdims?: boolean, ord?: number }; +export type ReduceNormSignature = (axis?: AxisArg | ReduceNormKwargs, keepdims?: boolean | ReduceNormKwargs, ord?: number | ReduceNormKwargs) => NDArray | number; +export type ReduceNormParsedKwargs = [number, boolean, number]; + + +export type RoundKwargs = { decimals?: number }; +export type RoundSignature = (decimals?: number) => NDArray; +export type RoundParsedKwargs = [number]; + +type WithArray any> = (arr: NDArray, ...args: Parameters) => ReturnType; + +export class KwParser any, Parsed extends any[]> { + defaults: [string, any][]; + + constructor(defaults: [string, any][]) { + this.defaults = defaults; + } + + parse(...args: Parameters): Parsed { + let defaults = this.defaults; + let kwargs = Object.assign(Object.fromEntries(defaults)); + for (let i = 0; i < args.length; i++) { + let value = args[i]; + if (value instanceof Object) Object.assign(kwargs, value); + else if (value !== undefined) kwargs[defaults[i][0]] = value; + } + let sortedArgs = defaults.map(([key, _]) => kwargs[key]); + return sortedArgs as Parsed; + } + + decorator_func ReturnType>(func: F): WithArray { + return function (arr: NDArray, ...args: Parameters) { + const parsed = this.parse(...args); + return func(arr, ...parsed); + }; + } + + decorator_method ReturnType>(func: F): Signature { + let self = this; + return function (...args: Parameters) { + const parsed = self.parse(...args); + return func(this, ...parsed); + } as any; + } + decorators ReturnType>(func: F) { + return { as_function: this.decorator_func(func), as_method: this.decorator_method(func) }; + } +} diff --git a/src/NDArray/reduce.ts b/src/NDArray/reduce.ts index 7c06c80..dd19a58 100644 --- a/src/NDArray/reduce.ts +++ b/src/NDArray/reduce.ts @@ -1,27 +1,78 @@ //@ts-check import { asarray, new_NDArray, as_boolean, number_collapse, shape_shifts } from './basic'; -import { ArrayOrConstant, op_binary } from './operators'; -import type NDArray from "../NDArray-class"; +import { ArrayOrConstant, op_binary, op_unary } from './operators'; +import NDArray from "../NDArray-class"; +import { DType } from '../NDArray-class'; +import { ReduceStdParsedKwargs, ReduceStdSignature } from './kwargs'; + +const multiply = op_binary["*"]; +const subtract = op_binary["-"]; +const pow = op_binary["**"]; export type AxisArg = null | number; -// ============================== -// Reducing functions -// ============================== +export type ReduceKwArgs = { axis?: number, keepdims?: boolean }; +function _NDReducer_parse_args(arr: NDArray, axis: AxisArg | ReduceKwArgs = null, keepdims: boolean | ReduceKwArgs = false) { + if (keepdims instanceof Object) ({ axis, keepdims } = Object.assign({ axis, keepdims }, keepdims)); + if (axis instanceof Object) ({ axis, keepdims } = Object.assign({ axis, keepdims }, axis)); + ({ axis, keepdims } = Object.assign({ axis, keepdims }, arr.__popKwArgs())); + keepdims = as_boolean(keepdims) as boolean; + axis = axis as AxisArg; + return [axis, keepdims] as [AxisArg, boolean]; +} + +export class NDReducer{ + reducer: (arr: any[]) => T; + self_reduce: (axis?: AxisArg | ReduceKwArgs, keepdims?: boolean | ReduceKwArgs) => T | NDArray; + dtype: DType; + + constructor(reducer: (x: any[]) => T, dtype: any, _reduce = null) { + this.reducer = reducer; + this.dtype = dtype; + let _this = this; + this.self_reduce = function (axis = null, keepdims = false) { return _this.reduce(this, axis, keepdims); } + if (_reduce) this._reduce = _reduce; + } + + reduce(arr: NDArray, axis: AxisArg | ReduceKwArgs = null, keepdims: boolean | ReduceKwArgs = false): NDArray | T { + return this._reduce(arr, ..._NDReducer_parse_args(arr, axis, keepdims)); + } + + _reduce(arr: NDArray, axis: AxisArg, keepdims: boolean): NDArray | T { + if (axis == null) return this.reducer(arr.flat); + if (axis < 0) axis = arr.shape.length - 1; + let m = arr.shape[axis]; + let shift = shape_shifts(arr.shape)[axis]; + const groups = Array.from({ length: m }, (_) => [] as T[]); + arr.flat.forEach((value, i) => groups[(Math.floor(i / shift)) % m].push(value as any as T)); + // Transpose it: + let nCols = arr.size / m; + const groupsT = []; + for (let j = 0; j < nCols; j++) { + const newRow = []; + for (let i = 0; i < m; i++) newRow.push(groups[i][j]); + groupsT.push(newRow); + } + const flat: T[] = groupsT.map(this.reducer); + let shape = [...arr.shape]; + if (keepdims) shape[axis] = 1; + else shape = shape.filter((_, i) => i != axis); + const out = new_NDArray((flat as any[] as number[]), shape, this.dtype); + return out.size == 1 ? (out.flat[0] as any as T) : out; + }; +} + -export function reduce(arr, axis, keepdims, reducer, dtype = Number): ArrayOrConstant { - keepdims = as_boolean(keepdims); - // console.log({ arr }) - arr = asarray(arr); - if (axis == null) return reducer(arr.flat); +function apply_on_axis(func: (arr: any[]) => T, dtype, arr: NDArray, axis: AxisArg, keepdims: boolean): NDArray | T { + if (axis == null) return func(arr.flat); if (axis < 0) axis = arr.shape.length - 1; let m = arr.shape[axis]; let shift = shape_shifts(arr.shape)[axis]; - const groups = Array.from({ length: m }, (_) =>/**@type {number[]}*/([])); - arr.flat.forEach((value, i) => groups[(Math.floor(i / shift)) % m].push(value)); + const groups = Array.from({ length: m }, (_) => [] as T[]); + arr.flat.forEach((value, i) => groups[(Math.floor(i / shift)) % m].push(value as any as T)); // Transpose it: let nCols = arr.size / m; const groupsT = []; @@ -30,52 +81,171 @@ export function reduce(arr, axis, keepdims, reducer, dtype = Number): ArrayOrCon for (let i = 0; i < m; i++) newRow.push(groups[i][j]); groupsT.push(newRow); } - const flat: number[] = groupsT.map(reducer); + const flat: T[] = groupsT.map(func); let shape = [...arr.shape]; if (keepdims) shape[axis] = 1; else shape = shape.filter((_, i) => i != axis); - const out = new_NDArray(flat, shape, dtype) - return number_collapse(out); + const out = new_NDArray((flat as any[] as number[]), shape, dtype); + return out.size == 1 ? (out.flat[0] as any as T) : out; }; -type ReduceKwArgs = { axis?: number, keepdims?: boolean }; -function __make_reducer(dtype, reducer) { - return function (arr: NDArray, axis: AxisArg | ReduceKwArgs = null, keepdims: boolean | ReduceKwArgs = false) { - // Parse kwargs from right to left to overwrite (right has priority) - if (keepdims instanceof Object) ({ axis, keepdims } = Object.assign({ axis, keepdims }, keepdims)); - if (axis instanceof Object) ({ axis, keepdims } = Object.assign({ axis, keepdims }, axis)); - ({ axis, keepdims } = Object.assign({ axis, keepdims }, this)); - return reduce(arr, axis, keepdims, reducer, dtype); - }; +interface ABC_ReducerGeneric any> { + self_reduce: (...args: Parameters) => ReturnType; + reduce: (arr: NDArray, ...args: Parameters) => ReturnType; + kwParse: (arr: NDArray, ...args: Parameters) => Parsed; + _reduce: (arr: NDArray, ...args: Parsed) => ReturnType; } -export const reducers = { - sum: __make_reducer(Number, (arr) => arr.reduce((a, b) => a + b, 0)), - product: __make_reducer(Number, (arr) => arr.reduce((a, b) => a * b, 1)), - any: __make_reducer(Boolean, (arr) => { +class New_ReducerGeneric any, Parsed extends any[]> implements ABC_ReducerGeneric{ + + dtype: any = Number; + + defaults: [string, any][] = [ + ["axis", null], + ["keepdims", false], + ]; + + reduce: (arr: NDArray, ...args: Parameters) => ReturnType; + kwParse: (arr: NDArray, ...args: Parameters) => Parsed; + self_reduce: (...args: Parameters) => ReturnType; + constructor(flat_reduce: (flat: any[]) => any = null, extras: [string, any][] = []) { + let self = this; + // Define self_reduce (reduce with this as first argument) + this.self_reduce = function (...args: Parameters) { + if (!(this instanceof NDArray)) throw 'self_reduce must be called from an NDArray instance'; + return self._reduce(this, ...self.kwParse(this, ...args)); + }; + // Define _reduce (reduce implementation after parsing kwargs) + if (flat_reduce) { + const dtype = this.dtype; + this._reduce = function (arr: NDArray, ...args: Parsed) { + const [axis, keepdims] = args; + return apply_on_axis(flat_reduce, dtype, arr, axis, keepdims) as ReturnType; + } + } + this.reduce = function (arr: NDArray, ...args: Parameters): ReturnType { + const parsedKwargs = self.kwParse.bind(this)(arr, ...args); + return self._reduce(arr, ...parsedKwargs); + } + let defaults = [...this.defaults, ...extras]; + this.kwParse = function (arr: NDArray, ...args: Parameters): Parsed { + let kwargs = Object.assign(Object.fromEntries(defaults), arr.__popKwArgs(), this); + for (let i = 0; i < args.length; i++) { + let value = args[i]; + if (value instanceof Object) Object.assign(kwargs, value); + else if (value !== undefined) kwargs[defaults[i][0]] = value; + } + let out = defaults.map(([key, _]) => kwargs[key]); + return out as Parsed; + } + } + _reduce(arr: NDArray, ...args: Parsed): ReturnType { + throw 'Programming error: _reduce was not defined'; + } +} + +type KwargsBasic = { axis?: number, keepdims?: boolean }; +type SignatureNumeric = (axis?: AxisArg | KwargsBasic, keepdims?: boolean | KwargsBasic) => NDArray | number; +type ParsedNumeric = [number, boolean]; +class New_ReducerNumeric extends New_ReducerGeneric{ } + + +const sum = new New_ReducerNumeric((arr: any[]) => arr.reduce((a, b) => a + b, 0)); + +const variance = new class extends New_ReducerNumeric { + _reduce(arr: NDArray, ...args: ParsedNumeric) { + let [axis, keepdims] = args; + arr = subtract(arr, arr.mean({ axis, keepdims: true })); + arr = multiply(arr, arr); + return arr.mean({ axis, keepdims }); + } +}(); + + +type KwargsOrd = { axis?: number, keepdims?: boolean, ord?: number }; +type ParsedOrd = [number, boolean, number]; +type SignatureOrd = (arr: NDArray, axis?: AxisArg | KwargsOrd, keepdims?: boolean | KwargsOrd, ord?: number | KwargsOrd) => NDArray | number; +const norm = new class extends New_ReducerGeneric{ + _reduce(arr: NDArray, ...args: ParsedOrd) { + let [axis, keepdims, ord] = args; + if (ord % 2 != 0) arr = arr.abs(); + if (ord == Infinity) return arr.max(axis, keepdims); + if (ord == 1) return arr.sum(axis, keepdims); + return pow(pow(arr, ord).sum(axis, keepdims), 1 / ord); + } +}(null, [["ord", 2]]); + + +const standard_deviation = new class extends New_ReducerGeneric{ + _reduce(arr: NDArray, ...args: ReduceStdParsedKwargs) { + let [axis, keepdims, ddof] = args; + console.log('args', args); + console.log('arr', arr); + if (ddof == 0) return pow(arr.var(axis, keepdims), 0.5); + const _sum = _reducers.sum.reduce(op_binary["**"](arr, 2), { axis, keepdims }); + const _len = _reducers.len.reduce(arr, { axis, keepdims }); + return op_binary["**"](op_binary["/"](_sum, op_binary["-"](_len, ddof)), 0.5); + } +}(null, [["ddof", 0]]); + + +// ============================== +// Reducing functions +// ============================== + + +export const _reducers = { + sum, + // sum: new NDReducer((arr) => arr.reduce((a, b) => a + b, 0), Number), + product: new NDReducer((arr) => arr.reduce((a, b) => a * b, 1), Number), + mean: new NDReducer((arr) => arr.reduce((a, b) => a + b, 0) / arr.length, Number), + max: new New_ReducerNumeric((arr: any[]) => Math.max(...arr)), + // max: new NDReducer((arr) => Math.max(...arr), Number), + min: new NDReducer((arr) => Math.min(...arr), Number), + argmax: new NDReducer((arr) => arr.indexOf(Math.max(...arr)), Number), + argmin: new NDReducer((arr) => arr.indexOf(Math.min(...arr)), Number), + len: new NDReducer((arr) => arr.length, Number), + any: new NDReducer((arr) => { for (let x of arr) if (x) return true; return false; - }), - all: __make_reducer(Boolean, (arr) => { + }, Boolean), + all: new NDReducer((arr) => { for (let x of arr) if (!x) return false; return true; - }), - max: __make_reducer(Number, (arr) => Math.max(...arr)), - min: __make_reducer(Number, (arr) => Math.min(...arr)), - argmax: __make_reducer(Number, (arr) => arr.indexOf(Math.max(...arr))), - argmin: __make_reducer(Number, (arr) => arr.indexOf(Math.min(...arr))), - mean: __make_reducer(Number, (arr) => arr.reduce((a, b) => a + b, 0) / arr.length), - var: function (arr, axis = null, keepdims = false) { - ({ axis, keepdims } = Object.assign({ axis, keepdims }, this)); - const arrMean = reducers.mean.bind({ axis, keepdims: true })(arr); - arr = op_binary["-"](arr, arrMean); - arr = op_binary["*"](arr, arr); - return reducers.mean.bind({ axis, keepdims })(arr); - }, - std: function (arr, axis = null, keepdims = false) { - ({ axis, keepdims } = Object.assign({ axis, keepdims }, this)); - const variance = reducers.var.bind({ axis, keepdims })(arr); - return op_binary["**"](variance, 0.5); - }, + }, Boolean), + norm, + var: variance, + std: standard_deviation, }; + +export const self_reducers = { + sum: _reducers.sum.self_reduce, + product: _reducers.product.self_reduce, + mean: _reducers.mean.self_reduce, + max: _reducers.max.self_reduce, + min: _reducers.min.self_reduce, + argmax: _reducers.argmax.self_reduce, + argmin: _reducers.argmin.self_reduce, + len: _reducers.len.self_reduce, + any: _reducers.any.self_reduce, + all: _reducers.all.self_reduce, + norm: _reducers.norm.self_reduce, + std: standard_deviation.self_reduce, + var: _reducers.var.self_reduce, +} +export const reducers = { + sum: _reducers.sum.reduce, + product: _reducers.product.reduce, + mean: _reducers.mean.reduce, + max: _reducers.max.reduce, + min: _reducers.min.reduce, + argmax: _reducers.argmax.reduce, + argmin: _reducers.argmin.reduce, + len: _reducers.len.reduce, + any: _reducers.any.reduce, + all: _reducers.all.reduce, + norm: _reducers.norm.reduce, + std: _reducers.std.reduce, + var: _reducers.var.reduce, +} diff --git a/src/NDArray/transform.ts b/src/NDArray/transform.ts index 76c325e..a3a1117 100644 --- a/src/NDArray/transform.ts +++ b/src/NDArray/transform.ts @@ -42,6 +42,8 @@ export function apply_along_axis(arr: NDArray, axis: number, transform, dtype: D export function sort(A: NDArray, axis = -1) { ({ axis } = Object.assign({ axis }, this)); + //@ts-ignore + if (axis instanceof Object) ({ axis } = axis); return apply_along_axis(A, axis, (arr) => { const cpy = [...arr]; cpy.sort((a, b) => a - b); @@ -51,6 +53,9 @@ export function sort(A: NDArray, axis = -1) { export function transpose(arr: NDArray, axes: null | number[] = null) { ({ axes } = Object.assign({ axes }, this)); + //@ts-ignore + if (axes !== null && axes["axes"]) ({ axes } = axes); + let nDims = arr.shape.length; if (axes == null) return transpose(arr, Array.from({ length: nDims }, (_, i) => i).reverse()); if (axes.length !== nDims) throw new Error(`Axes must have length ${nDims}. Found ${axes.length}`); @@ -102,7 +107,9 @@ export function swapAxes(arr: NDArray, axisA: number, axisB: number) { export function concatenate(arrays: NDArray[], axis: number | null = null) { - ({ axis } = Object.assign({ axis }, this)); + // ({ axis } = Object.assign({ axis }, this)); + //@ts-ignore + if (axis instanceof Object) ({ axis } = axis); if (isarray(arrays)) arrays = [...arrays]; arrays = arrays.map(asarray); if (axis == null) { @@ -129,7 +136,9 @@ export function concatenate(arrays: NDArray[], axis: number | null = null) { export function stack(arrays: NDArray[], axis: number = 0) { - ({ axis } = Object.assign({ axis }, this)); + // ({ axis } = Object.assign({ axis }, this)); + //@ts-ignore + if (axis instanceof Object) ({ axis } = axis); if (isarray(arrays)) arrays = [...arrays]; if (!Array.isArray(arrays)) throw new Error(`Expected list of arrays. Found ${typeof arrays}`); arrays = arrays.map(asarray); diff --git a/src/index.ts b/src/index.ts index a5576c8..4336600 100644 --- a/src/index.ts +++ b/src/index.ts @@ -58,6 +58,7 @@ np.min = reduce.reducers.min; np.argmax = reduce.reducers.argmax; np.argmin = reduce.reducers.argmin; np.mean = reduce.reducers.mean; +np.norm = reduce.reducers.norm; np.var = reduce.reducers.var; np.std = reduce.reducers.std; @@ -125,7 +126,7 @@ np.tanh = ew.ops.tanh; np.acosh = ew.ops.acosh; np.asinh = ew.ops.asinh; np.atanh = ew.ops.atanh; -np.round = ew.ops.round; +np.round = ew.round_kw.as_function; // ============================== diff --git a/src/modules/constructors.ts b/src/modules/constructors.ts index 8b9a30b..3ff12a3 100644 --- a/src/modules/constructors.ts +++ b/src/modules/constructors.ts @@ -1,5 +1,6 @@ //@ts-check import NDArray from '../NDArray-class'; +import { KwParser } from '../NDArray/kwargs'; const { basic, elementwise } = NDArray.prototype.modules; diff --git a/src/modules/grammar.ts b/src/modules/grammar.ts index 4189a36..8ed5769 100644 --- a/src/modules/grammar.ts +++ b/src/modules/grammar.ts @@ -160,14 +160,16 @@ export const __makeSemantics = () => { const func = name.split('.').reduce((obj, name) => obj[name], np); if (func === undefined) throw new Error(`Unrecognized function ${name}`) const { args, kwArgs } = $callArgs.parse(); - return func.bind(kwArgs)(...args); + return Object.keys(kwArgs).length == 0 ? func(...args) : func(...args, kwArgs); + // return func.bind(kwArgs)(...args); // Old version }, Arr_method($arr, _dot, $name, $callArgs) { let arr = $arr.parse(); let name = $name.sourceString; const { args, kwArgs } = $callArgs.parse(); if (arr[name] === undefined) throw new Error(`Unrecognized method ${name}`); - return arr.withKwArgs(kwArgs)[name](...args); + // return arr.withKwArgs(kwArgs)[name](...args); // Old version + return Object.keys(kwArgs).length == 0 ? arr[name](...args) : arr[name](...args, kwArgs); }, Parenthesis(_, $arr, __) { return $arr.parse(); }, Arr_attribute($arr, _, $name) { return $arr.parse()[$name.sourceString]; }, diff --git a/tests/tests_october.ts b/tests/tests_october.ts index 5a96b03..55adc40 100644 --- a/tests/tests_october.ts +++ b/tests/tests_october.ts @@ -65,6 +65,8 @@ print(json.dumps(out, cls=NpEncoder), flush=True) // Unit tests: +npTest`np.arange(120)` +npTest`np.arange(120).std()`