diff --git a/.npmignore b/.npmignore index 1132e14..b571469 100644 --- a/.npmignore +++ b/.npmignore @@ -1,6 +1,6 @@ * !readme.md -!src/** +# !src/** !dist/** !LICENSE !package.json \ No newline at end of file diff --git a/dist/NDArray-class.d.ts b/dist/NDArray-class.d.ts new file mode 100644 index 0000000..fc90bef --- /dev/null +++ b/dist/NDArray-class.d.ts @@ -0,0 +1,86 @@ +export type DType = NumberConstructor | BooleanConstructor; +export type ArrayOrConstant = NDArray | number | boolean; +declare class NDArray { + _flat: number[]; + shape: number[]; + dtype: DType; + index: (...where: any[]) => any; + reshape: (shape: any, ...more_shape: any[]) => any; + modules: typeof import("./NDArray").modules; + 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: BinaryOperatorSignature; + subtract: BinaryOperatorSignature; + multiply: BinaryOperatorSignature; + divide: BinaryOperatorSignature; + mod: BinaryOperatorSignature; + divide_int: BinaryOperatorSignature; + pow: BinaryOperatorSignature; + maximum: BinaryOperatorSignature; + minimum: BinaryOperatorSignature; + bitwise_or: BinaryOperatorSignature; + bitwise_and: BinaryOperatorSignature; + bitwise_shift_right: BinaryOperatorSignature; + logical_xor: BinaryOperatorSignature; + logical_or: BinaryOperatorSignature; + logical_and: BinaryOperatorSignature; + greater: BinaryOperatorSignature; + less: BinaryOperatorSignature; + greater_equal: BinaryOperatorSignature; + less_equal: BinaryOperatorSignature; + equal: BinaryOperatorSignature; + not_equal: BinaryOperatorSignature; + 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: UnaryOperatorSignature; + negative: UnaryOperatorSignature; + logical_not: UnaryOperatorSignature; + bitwise_not: UnaryOperatorSignature; + assign: SelfAssignmentOperator; + add_assign: SelfAssignmentOperator; + subtract_assign: SelfAssignmentOperator; + multiply_assign: SelfAssignmentOperator; + divide_assign: SelfAssignmentOperator; + mod_assign: SelfAssignmentOperator; + pow_assign: SelfAssignmentOperator; + divide_int_assign: SelfAssignmentOperator; + maximum_assign: SelfAssignmentOperator; + minimum_assign: SelfAssignmentOperator; + bitwise_and_assign: SelfAssignmentOperator; + bitwise_or_assign: SelfAssignmentOperator; + logical_or_assign: SelfAssignmentOperator; + bitwise_shift_right_assign: SelfAssignmentOperator; + bitwise_shift_left_assign: SelfAssignmentOperator; + logical_and_assign: SelfAssignmentOperator; + tolist: () => any; + round: RoundSignature; + sort: (axis?: number) => NDArray; + transpose: (axes?: number[]) => NDArray; + op: (...args: any[]) => NDArray; + ravel: () => NDArray; + constructor(flat: number[], shape: number[], dtype?: any); + _simpleIndexes: import("./NDArray/indexes").AxesIndex | null; + get size(): number; + get flat(): number[]; + set flat(list: number[]); + get T(): NDArray; + [Symbol.iterator](): Generator; + get length(): number; + copy: () => NDArray; + item(): number; +} +import { SelfAssignmentOperator } from './NDArray/operators'; +import { BinaryOperatorSignature, ReduceNormSignature, ReduceSignature, ReduceSignatureBool, ReduceStdSignature, RoundSignature, UnaryOperatorSignature } from './NDArray/kwargs'; +export { NDArray }; +export default NDArray; +//# sourceMappingURL=NDArray-class.d.ts.map \ No newline at end of file diff --git a/dist/NDArray-class.d.ts.map b/dist/NDArray-class.d.ts.map new file mode 100644 index 0000000..1cc74de --- /dev/null +++ b/dist/NDArray-class.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"NDArray-class.d.ts","sourceRoot":"","sources":["../src/NDArray-class.ts"],"names":[],"mappings":"AACA,MAAM,MAAM,KAAK,GAAG,iBAAiB,GAAG,kBAAkB,CAAC;AAC3D,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,CAAC;AAGzD,cAAM,OAAO;IACX,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,KAAK,EAAE,KAAK,CAAC;IAEb,KAAK,EAAE,CAAC,GAAG,KAAK,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;IAChC,OAAO,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,UAAU,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;IAEnD,OAAO,EAAE,cAAc,WAAW,EAAE,OAAO,CAAC;IAE5C,GAAG,EAAE,mBAAmB,CAAC;IACzB,GAAG,EAAE,mBAAmB,CAAC;IACzB,GAAG,EAAE,eAAe,CAAC;IACrB,OAAO,EAAE,eAAe,CAAC;IACzB,GAAG,EAAE,eAAe,CAAC;IACrB,GAAG,EAAE,eAAe,CAAC;IACrB,MAAM,EAAE,eAAe,CAAC;IACxB,MAAM,EAAE,eAAe,CAAC;IACxB,IAAI,EAAE,eAAe,CAAC;IAEtB,GAAG,EAAE,eAAe,CAAC;IACrB,GAAG,EAAE,kBAAkB,CAAC;IACxB,IAAI,EAAE,mBAAmB,CAAC;IAE1B,GAAG,EAAE,uBAAuB,CAAC;IAC7B,QAAQ,EAAE,uBAAuB,CAAC;IAClC,QAAQ,EAAE,uBAAuB,CAAC;IAClC,MAAM,EAAE,uBAAuB,CAAC;IAChC,GAAG,EAAE,uBAAuB,CAAC;IAC7B,UAAU,EAAE,uBAAuB,CAAC;IACpC,GAAG,EAAE,uBAAuB,CAAC;IAC7B,OAAO,EAAE,uBAAuB,CAAC;IACjC,OAAO,EAAE,uBAAuB,CAAC;IACjC,UAAU,EAAE,uBAAuB,CAAC;IACpC,WAAW,EAAE,uBAAuB,CAAC;IACrC,mBAAmB,EAAE,uBAAuB,CAAC;IAE7C,WAAW,EAAE,uBAAuB,CAAC,OAAO,CAAC,CAAC;IAC9C,UAAU,EAAE,uBAAuB,CAAC,OAAO,CAAC,CAAC;IAC7C,WAAW,EAAE,uBAAuB,CAAC,OAAO,CAAC,CAAC;IAE9C,OAAO,EAAE,uBAAuB,CAAC;IACjC,IAAI,EAAE,uBAAuB,CAAC;IAC9B,aAAa,EAAE,uBAAuB,CAAC;IACvC,UAAU,EAAE,uBAAuB,CAAC;IACpC,KAAK,EAAE,uBAAuB,CAAC;IAC/B,SAAS,EAAE,uBAAuB,CAAC;IACnC,OAAO,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,OAAO,KAAK,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC;IAC3G,QAAQ,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,OAAO,KAAK,OAAO,CAAC;IAEzF,GAAG,EAAE,sBAAsB,CAAC;IAC5B,QAAQ,EAAE,sBAAsB,CAAC;IACjC,WAAW,EAAE,sBAAsB,CAAC;IACpC,WAAW,EAAE,sBAAsB,CAAC;IAEpC,MAAM,EAAE,sBAAsB,CAAC;IAC/B,UAAU,EAAE,sBAAsB,CAAC;IACnC,eAAe,EAAE,sBAAsB,CAAC;IACxC,eAAe,EAAE,sBAAsB,CAAC;IACxC,aAAa,EAAE,sBAAsB,CAAC;IACtC,UAAU,EAAE,sBAAsB,CAAC;IACnC,UAAU,EAAE,sBAAsB,CAAC;IACnC,iBAAiB,EAAE,sBAAsB,CAAC;IAC1C,cAAc,EAAE,sBAAsB,CAAC;IACvC,cAAc,EAAE,sBAAsB,CAAC;IACvC,kBAAkB,EAAE,sBAAsB,CAAC;IAC3C,iBAAiB,EAAE,sBAAsB,CAAC;IAC1C,iBAAiB,EAAE,sBAAsB,CAAC;IAC1C,0BAA0B,EAAE,sBAAsB,CAAC;IACnD,yBAAyB,EAAE,sBAAsB,CAAC;IAClD,kBAAkB,EAAE,sBAAsB,CAAC;IAE3C,MAAM,EAAE,MAAM,GAAG,CAAC;IAElB,KAAK,EAAE,cAAc,CAAC;IACtB,IAAI,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC;IACjC,SAAS,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,KAAK,OAAO,CAAC;IACxC,EAAE,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC;IAChC,KAAK,EAAE,MAAM,OAAO,CAAC;gBAET,IAAI,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,KAAK,GAAE,GAAY;IAOhE,cAAc,EAAE,OAAO,mBAAmB,EAAE,SAAS,GAAG,IAAI,CAAC;IAE7D,IAAI,IAAI,WAEP;IACD,IAAI,IAAI,aAIP;IACD,IAAI,IAAI,CAAC,IAAI,UAAA,EAUZ;IACD,IAAI,CAAC,YAEJ;IAYA,CAAC,MAAM,CAAC,QAAQ,CAAC;IAGlB,IAAI,MAAM,WAET;IACD,IAAI,EAAE,MAAM,OAAO,CAAC;IACpB,IAAI;CAIL;AAMD,OAAO,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAE7D,OAAO,EAAW,uBAAuB,EAA0B,mBAAmB,EAAE,eAAe,EAAE,mBAAmB,EAAE,kBAAkB,EAAkC,cAAc,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAuNnP,OAAO,EAAE,OAAO,EAAE,CAAC;AAEnB,eAAe,OAAO,CAAC"} \ No newline at end of file diff --git a/dist/NDArray/_globals.d.ts b/dist/NDArray/_globals.d.ts new file mode 100644 index 0000000..600000b --- /dev/null +++ b/dist/NDArray/_globals.d.ts @@ -0,0 +1,8 @@ +import type NDArray from "../NDArray-class"; +import { DType } from "../NDArray-class"; +export declare const _NDArray: typeof NDArray; +export declare function isarray(A: any): A is NDArray; +export declare const new_NDArray: (flat: number[], shape: number[], dtype: DType) => NDArray; +export declare function asarray(A: any): NDArray; +export declare function array(A: any): NDArray; +//# sourceMappingURL=_globals.d.ts.map \ No newline at end of file diff --git a/dist/NDArray/_globals.d.ts.map b/dist/NDArray/_globals.d.ts.map new file mode 100644 index 0000000..4163c0b --- /dev/null +++ b/dist/NDArray/_globals.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_globals.d.ts","sourceRoot":"","sources":["../../src/NDArray/_globals.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,OAAO,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAMzC,eAAO,MAAM,QAAQ,gBAAY,CAAC;AAGlC,wBAAgB,OAAO,CAAC,CAAC,EAAE,GAAG,GAAG,CAAC,IAAI,OAAO,CAE5C;AAED,eAAO,MAAM,WAAW,SAAU,MAAM,EAAE,SAAS,MAAM,EAAE,SAAS,KAAK,YAAqC,CAAC;AAE/G,wBAAgB,OAAO,CAAC,CAAC,KAAA,GAAG,OAAO,CAGlC;AAED,wBAAgB,KAAK,CAAC,CAAC,KAAA,WAMtB"} \ No newline at end of file diff --git a/dist/NDArray/basic.d.ts b/dist/NDArray/basic.d.ts new file mode 100644 index 0000000..9a6a650 --- /dev/null +++ b/dist/NDArray/basic.d.ts @@ -0,0 +1,22 @@ +import type NDArray from "../NDArray-class"; +import { DType } from "../NDArray-class"; +import { isarray, asarray, array, new_NDArray, _NDArray } from "./_globals"; +export { isarray, asarray, array, new_NDArray, _NDArray }; +/** + * If the array is 0D, it returns it's unique element (number or boolean). + * The signature is kept as NDArray for type consistency, even though the + * output is a number or a boolean. This is consistent with the facts that + * (1) all functions requiring arrays work with numbers as well because they call asarray, + * and (2) semantically, a constant is an array. + */ +export declare function number_collapse(arr: NDArray, expect?: boolean): NDArray | number; +export declare function as_boolean(obj: any): boolean; +export declare function as_number(obj: any): number; +export declare function shape_shifts(shape: any): number[]; +export declare function parse_shape(list: number | number[] | NDArray): number[]; +export declare function reshape(A: NDArray, shape_or_first: number | number[], ...more_shape: number[]): NDArray; +export declare function ravel(A: NDArray): NDArray; +export declare function new_from(shape: any, f?: any, dtype?: DType): NDArray; +export declare function empty(shape: any, dtype?: DType): NDArray; +export declare function copy(A: NDArray): NDArray; +//# sourceMappingURL=basic.d.ts.map \ No newline at end of file diff --git a/dist/NDArray/basic.d.ts.map b/dist/NDArray/basic.d.ts.map new file mode 100644 index 0000000..3ab386a --- /dev/null +++ b/dist/NDArray/basic.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"basic.d.ts","sourceRoot":"","sources":["../../src/NDArray/basic.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,OAAO,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE5E,OAAO,EACL,OAAO,EACP,OAAO,EACP,KAAK,EACL,WAAW,EACX,QAAQ,EACT,CAAA;AAID;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,UAAQ,GAAG,OAAO,GAAG,MAAM,CAI9E;AAED,wBAAgB,UAAU,CAAC,GAAG,KAAA,WAI7B;AACD,wBAAgB,SAAS,CAAC,GAAG,KAAA,UAI5B;AAOD,wBAAgB,YAAY,CAAC,KAAK,KAAA,YAMjC;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,YAU5D;AAGD,wBAAgB,OAAO,CAAC,CAAC,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,GAAG,UAAU,EAAE,MAAM,EAAE,WAgB7F;AACD,wBAAgB,KAAK,CAAC,CAAC,EAAE,OAAO,WAG/B;AAOD,wBAAgB,QAAQ,CAAC,KAAK,KAAA,EAAE,CAAC,GAAE,GAAe,EAAE,KAAK,GAAE,KAAc,WAKxE;AAED,wBAAgB,KAAK,CAAC,KAAK,KAAA,EAAE,KAAK,GAAE,KAAc,WAEjD;AAED,wBAAgB,IAAI,CAAC,CAAC,EAAE,OAAO,WAE9B"} \ No newline at end of file diff --git a/dist/NDArray/elementwise.d.ts b/dist/NDArray/elementwise.d.ts new file mode 100644 index 0000000..e1cf2bf --- /dev/null +++ b/dist/NDArray/elementwise.d.ts @@ -0,0 +1,59 @@ +import type NDArray from "../NDArray-class"; +export declare function elementwise(A: NDArray, func: any, dtype: any, out?: NDArray): NDArray; +export declare const funcs: { + sign: (A: NDArray, out?: NDArray) => NDArray; + sqrt: (A: NDArray, out?: NDArray) => NDArray; + square: (A: NDArray, out?: NDArray) => NDArray; + exp: (A: NDArray, out?: NDArray) => NDArray; + log: (A: NDArray, out?: NDArray) => NDArray; + log2: (A: NDArray, out?: NDArray) => NDArray; + log10: (A: NDArray, out?: NDArray) => NDArray; + log1p: (A: NDArray, out?: NDArray) => NDArray; + sin: (A: NDArray, out?: NDArray) => NDArray; + cos: (A: NDArray, out?: NDArray) => NDArray; + tan: (A: NDArray, out?: NDArray) => NDArray; + asin: (A: NDArray, out?: NDArray) => NDArray; + acos: (A: NDArray, out?: NDArray) => NDArray; + atan: (A: NDArray, out?: NDArray) => NDArray; + cosh: (A: NDArray, out?: NDArray) => NDArray; + sinh: (A: NDArray, out?: NDArray) => NDArray; + tanh: (A: NDArray, out?: NDArray) => NDArray; + acosh: (A: NDArray, out?: NDArray) => NDArray; + asinh: (A: NDArray, out?: NDArray) => NDArray; + atanh: (A: NDArray, out?: NDArray) => NDArray; +}; +export declare const ops: { + "~": (A: NDArray, out?: NDArray) => NDArray; + not: (A: NDArray, out?: NDArray) => NDArray; + "+": (A: NDArray, out?: NDArray) => NDArray; + "-": (A: NDArray, out?: NDArray) => NDArray; + round: (arr: NDArray, decimals: number, out?: NDArray) => NDArray; + negative: (A: NDArray, out?: NDArray) => NDArray; + bitwise_not: (A: NDArray, out?: NDArray) => NDArray; + logical_not: (A: NDArray, out?: NDArray) => NDArray; + valueOf: (A: NDArray, out?: NDArray) => NDArray; + abs: (A: NDArray, out?: NDArray) => NDArray; +}; +export declare const kw_ops: { + bitwise_not: { + as_function: (arr: number | boolean | NDArray, out?: NDArray) => NDArray; + as_method: (out?: NDArray) => NDArray; + }; + logical_not: { + as_function: (arr: number | boolean | NDArray, out?: NDArray) => NDArray; + as_method: (out?: NDArray) => NDArray; + }; + negative: { + as_function: (arr: number | boolean | NDArray, out?: NDArray) => NDArray; + as_method: (out?: NDArray) => NDArray; + }; + abs: { + as_function: (arr: number | boolean | NDArray, out?: NDArray) => NDArray; + as_method: (out?: NDArray) => NDArray; + }; + round: { + as_function: (arr: number | boolean | NDArray, decimals?: number) => NDArray; + as_method: (decimals?: number) => NDArray; + }; +}; +//# sourceMappingURL=elementwise.d.ts.map \ No newline at end of file diff --git a/dist/NDArray/elementwise.d.ts.map b/dist/NDArray/elementwise.d.ts.map new file mode 100644 index 0000000..549b81c --- /dev/null +++ b/dist/NDArray/elementwise.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elementwise.d.ts","sourceRoot":"","sources":["../../src/NDArray/elementwise.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,OAAO,MAAM,kBAAkB,CAAC;AAM5C,wBAAgB,WAAW,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,KAAA,EAAE,KAAK,KAAA,EAAE,GAAG,GAAE,OAAc,WAOvE;AAQD,eAAO,MAAM,KAAK;cALI,OAAO,QAAO,OAAO;cAArB,OAAO,QAAO,OAAO;gBAArB,OAAO,QAAO,OAAO;aAArB,OAAO,QAAO,OAAO;aAArB,OAAO,QAAO,OAAO;cAArB,OAAO,QAAO,OAAO;eAArB,OAAO,QAAO,OAAO;eAArB,OAAO,QAAO,OAAO;aAArB,OAAO,QAAO,OAAO;aAArB,OAAO,QAAO,OAAO;aAArB,OAAO,QAAO,OAAO;cAArB,OAAO,QAAO,OAAO;cAArB,OAAO,QAAO,OAAO;cAArB,OAAO,QAAO,OAAO;cAArB,OAAO,QAAO,OAAO;cAArB,OAAO,QAAO,OAAO;cAArB,OAAO,QAAO,OAAO;eAArB,OAAO,QAAO,OAAO;eAArB,OAAO,QAAO,OAAO;eAArB,OAAO,QAAO,OAAO;CA0B1C,CAAA;AAcD,eAAO,MAAM,GAAG;aAxCM,OAAO,QAAO,OAAO;aAArB,OAAO,QAAO,OAAO;aAArB,OAAO,QAAO,OAAO;aAArB,OAAO,QAAO,OAAO;iBA8Bd,OAAO,YAAY,MAAM,QAAO,OAAO;kBA9B9C,OAAO,QAAO,OAAO;qBAArB,OAAO,QAAO,OAAO;qBAArB,OAAO,QAAO,OAAO;iBAArB,OAAO,QAAO,OAAO;aAArB,OAAO,QAAO,OAAO;CA8C1C,CAAA;AAyBD,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;;CAGlB,CAAA"} \ No newline at end of file diff --git a/dist/NDArray/index.d.ts b/dist/NDArray/index.d.ts new file mode 100644 index 0000000..88380b8 --- /dev/null +++ b/dist/NDArray/index.d.ts @@ -0,0 +1,20 @@ +import './_globals'; +import * as basic from './basic'; +import * as indexes from './indexes'; +import * as jsInterface from './js-interface'; +import * as elementwise from './elementwise'; +import * as print from './print'; +import * as reduce from './reduce'; +import * as operators from './operators'; +import * as transform from './transform'; +export declare const modules: { + basic: typeof basic; + jsInterface: typeof jsInterface; + indexes: typeof indexes; + elementwise: typeof elementwise; + print: typeof print; + reduce: typeof reduce; + operators: typeof operators; + transform: typeof transform; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/NDArray/index.d.ts.map b/dist/NDArray/index.d.ts.map new file mode 100644 index 0000000..10bee62 --- /dev/null +++ b/dist/NDArray/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/NDArray/index.ts"],"names":[],"mappings":"AAGA,OAAO,YAAY,CAAC;AAEpB,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AACjC,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC;AACrC,OAAO,KAAK,WAAW,MAAM,gBAAgB,CAAC;AAC9C,OAAO,KAAK,WAAW,MAAM,eAAe,CAAC;AAC7C,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AACjC,OAAO,KAAK,MAAM,MAAM,UAAU,CAAC;AACnC,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AAEzC,eAAO,MAAM,OAAO;;;;;;;;;CASnB,CAAC"} \ No newline at end of file diff --git a/dist/NDArray/indexes.d.ts b/dist/NDArray/indexes.d.ts new file mode 100644 index 0000000..27d0efe --- /dev/null +++ b/dist/NDArray/indexes.d.ts @@ -0,0 +1,73 @@ +import type NDArray from "../NDArray-class"; +export type RangeSpec = string; +export type indexSpec = ':' | number | RangeSpec | NDArray | number[]; +export type GeneralIndexSpec = ':' | '...' | 'None' | null | indexSpec; +export type Where = null | GeneralIndexSpec[]; +export declare function index(arr: NDArray, where: Where): number | NDArray; +export declare class AxesIndex { + shape: any; + internalShape: any; + axisIndexes: AxisIndex[]; + private _indices; + private _size; + isSimple: boolean; + isConstant: boolean; + parse: (shape: number[], where: Where) => AxesIndex; + /** + * @param {AxisIndex[]} axisIndexes + */ + constructor(apparentShape: any, internalShape: any, axisIndexes: AxisIndex[]); + get indices(): number[]; + get __slices(): any[]; + get size(): number; +} +export declare function __parse_sliceRange(axis_size: any, { start, stop, step }: { + start: any; + stop: any; + step: any; +}): any[]; +export type AxisIndexSpec = { + type: ':'; + size: number; +} | { + type: 'number'; + index: number; +} | { + type: 'range'; + range: { + start: number; + step: number; + nSteps: number; + }; +} | { + type: 'array'; + indices: number[]; +}; +export declare class AxisIndex { + spec: AxisIndexSpec; + private _indices; + isSimple: boolean; + isConstant: boolean; + parse: (indexSpec: indexSpec | undefined, size: number) => { + axisIndex: AxisIndex; + span: number; + }; + parse_range: (size: number, start?: number, stop?: number, step?: number) => { + start: number; + step: number; + nSteps: number; + }; + parse_range_spec: (rangeString: string) => { + start: number; + stop: number; + step: number; + }; + /** + * Invariant: Immutable + * @param {AxisIndexSpec} spec + */ + constructor(spec: AxisIndexSpec); + get indices(): any; + get size(): number; +} +//# sourceMappingURL=indexes.d.ts.map \ No newline at end of file diff --git a/dist/NDArray/indexes.d.ts.map b/dist/NDArray/indexes.d.ts.map new file mode 100644 index 0000000..84dad5a --- /dev/null +++ b/dist/NDArray/indexes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"indexes.d.ts","sourceRoot":"","sources":["../../src/NDArray/indexes.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,OAAO,MAAM,kBAAkB,CAAC;AAG5C,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC;AAC/B,MAAM,MAAM,SAAS,GAAG,GAAG,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,GAAG,MAAM,EAAE,CAAC;AACtE,MAAM,MAAM,gBAAgB,GAAG,GAAG,GAAG,KAAK,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;AACvE,MAAM,MAAM,KAAK,GAAG,IAAI,GAAG,gBAAgB,EAAE,CAAC;AAI9C,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,oBAwB/C;AAMD,qBAAa,SAAS;IACpB,KAAK,EAAE,GAAG,CAAC;IACX,aAAa,EAAE,GAAG,CAAC;IACnB,WAAW,EAAE,SAAS,EAAE,CAAC;IACzB,OAAO,CAAC,QAAQ,CAAkB;IAClC,OAAO,CAAC,KAAK,CAAgB;IAC7B,QAAQ,EAAE,OAAO,CAAC;IAClB,UAAU,EAAE,OAAO,CAAC;IACpB,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,KAAK,KAAK,SAAS,CAAC;IACpD;;OAEG;gBACS,aAAa,KAAA,EAAE,aAAa,KAAA,EAAE,WAAW,EAAE,SAAS,EAAE;IASlE,IAAI,OAAO,aAIV;IACD,IAAI,QAAQ,UAEX;IACD,IAAI,IAAI,WAGP;CACF;AAwFD,wBAAgB,kBAAkB,CAAC,SAAS,KAAA,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE;;;;CAAA,SAmBlE;AAGD,MAAM,MAAM,aAAa,GAAG;IAAE,IAAI,EAAE,GAAG,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAE/M,qBAAa,SAAS;IACpB,IAAI,EAAE,aAAa,CAAC;IACpB,OAAO,CAAC,QAAQ,CAAO;IACvB,QAAQ,EAAE,OAAO,CAAC;IAClB,UAAU,EAAE,OAAO,CAAC;IACpB,KAAK,EAAE,CAAC,SAAS,EAAE,SAAS,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,KAAK;QAAE,SAAS,EAAE,SAAS,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;KAAE,CAAC;IACnG,WAAW,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,KAAK;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;KAAE,CAAC;IAC9H,gBAAgB,EAAE,CAAC,WAAW,EAAE,MAAM,KAAK;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;KAAE,CAAC;IAE1F;;;OAGG;gBACS,IAAI,EAAE,aAAa;IAM/B,IAAI,OAAO,QAWV;IACD,IAAI,IAAI,WAMP;CACF"} \ No newline at end of file diff --git a/dist/NDArray/js-interface.d.ts b/dist/NDArray/js-interface.d.ts new file mode 100644 index 0000000..300679e --- /dev/null +++ b/dist/NDArray/js-interface.d.ts @@ -0,0 +1,3 @@ +export declare function fromlist(arr: any, dtype?: any): import("../NDArray-class").NDArray; +export declare function tolist(arr: any): any; +//# sourceMappingURL=js-interface.d.ts.map \ No newline at end of file diff --git a/dist/NDArray/js-interface.d.ts.map b/dist/NDArray/js-interface.d.ts.map new file mode 100644 index 0000000..1144c20 --- /dev/null +++ b/dist/NDArray/js-interface.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"js-interface.d.ts","sourceRoot":"","sources":["../../src/NDArray/js-interface.ts"],"names":[],"mappings":"AAKA,wBAAgB,QAAQ,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,MAAO,sCAkC9C;AAED,wBAAgB,MAAM,CAAC,GAAG,KAAA,OAqCzB"} \ No newline at end of file diff --git a/dist/NDArray/kwargs.d.ts b/dist/NDArray/kwargs.d.ts new file mode 100644 index 0000000..e12d1ca --- /dev/null +++ b/dist/NDArray/kwargs.d.ts @@ -0,0 +1,65 @@ +import { NDArray } from "../NDArray-class"; +export type AxisArg = null | number; +export type ReduceKwargs = { + axis?: AxisArg; + keepdims?: boolean; +}; +export type ReduceSignature = (axis?: AxisArg | ReduceKwargs, keepdims?: boolean | ReduceKwargs) => NDArray | T; +export type ReduceSignatureBool = ReduceSignature; +export type ReduceParsedKwargs = [AxisArg, 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 = [AxisArg, 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 = [AxisArg, boolean, number]; +export type RoundKwargs = { + decimals?: number; +}; +export type RoundSignature = (decimals?: number) => NDArray; +export type RoundParsedKwargs = [number]; +export type BinaryOperatorSignature = (other: NDArray | T, out?: NDArray | null) => NDArray; +export type BinaryOperatorKwargs = { + other: NDArray; + out?: NDArray | null; +}; +export type BinaryOperatorParsedKwargs = [NDArray, NDArray | null]; +export type UnaryOperatorSignature = (out?: NDArray | null) => NDArray; +export type UnaryOperatorKwargs = { + out?: NDArray | null; +}; +export type UnaryOperatorParsedKwargs = [NDArray | null]; +type KwTuple = [string, any] | [string, any, (x: any) => any]; +export declare function kwDecorators any, Parsed extends any[]>({ defaults, func }: { + defaults: KwTuple[]; + func: (arr: NDArray, ...args: Parsed) => any; +}): { + as_function: (arr: number | boolean | NDArray, ...args: Parameters) => ReturnType; + as_method: (...args: Parameters) => ReturnType; +}; +export declare function kwDecorator any, Parsed extends any[]>({ defaults, func }: { + defaults: KwTuple[]; + func: (...args: Parsed) => any; +}): (...args: Parameters) => ReturnType; +export declare class KwParser any, Parsed extends any[]> { + defaults: KwTuple[]; + constructor(defaults: KwTuple[]); + parse(...args: Parameters): Parsed; + as_arr_function ReturnType>(func: F): (arr: NDArray | number | boolean, ...args: Parameters) => ReturnType; + as_arr_method ReturnType>(func: F): (...args: Parameters) => ReturnType; + decorators ReturnType>(func: F): { + as_function: (arr: number | boolean | NDArray, ...args: Parameters) => ReturnType; + as_method: (...args: Parameters) => ReturnType; + }; + as_function ReturnType>(func: F): (...args: Parameters) => ReturnType; +} +export {}; +//# sourceMappingURL=kwargs.d.ts.map \ No newline at end of file diff --git a/dist/NDArray/kwargs.d.ts.map b/dist/NDArray/kwargs.d.ts.map new file mode 100644 index 0000000..50e2d84 --- /dev/null +++ b/dist/NDArray/kwargs.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"kwargs.d.ts","sourceRoot":"","sources":["../../src/NDArray/kwargs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAG3C,MAAM,MAAM,OAAO,GAAG,IAAI,GAAG,MAAM,CAAC;AAEpC,MAAM,MAAM,YAAY,GAAG;IAAE,IAAI,CAAC,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC;AAClE,MAAM,MAAM,eAAe,CAAC,CAAC,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,EAAE,OAAO,GAAG,YAAY,EAAE,QAAQ,CAAC,EAAE,OAAO,GAAG,YAAY,KAAK,OAAO,GAAG,CAAC,CAAC;AAC5H,MAAM,MAAM,mBAAmB,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;AAC3D,MAAM,MAAM,kBAAkB,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAEpD,MAAM,MAAM,eAAe,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AACnF,MAAM,MAAM,kBAAkB,GAAG,CAAC,IAAI,CAAC,EAAE,OAAO,GAAG,eAAe,EAAE,QAAQ,CAAC,EAAE,OAAO,GAAG,eAAe,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,eAAe,KAAK,OAAO,GAAG,MAAM,CAAC;AAC/J,MAAM,MAAM,qBAAqB,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AAE/D,MAAM,MAAM,gBAAgB,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AACnF,MAAM,MAAM,mBAAmB,GAAG,CAAC,IAAI,CAAC,EAAE,OAAO,GAAG,gBAAgB,EAAE,QAAQ,CAAC,EAAE,OAAO,GAAG,gBAAgB,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,gBAAgB,KAAK,OAAO,GAAG,MAAM,CAAC;AAClK,MAAM,MAAM,sBAAsB,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AAGhE,MAAM,MAAM,WAAW,GAAG;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAChD,MAAM,MAAM,cAAc,GAAG,CAAC,QAAQ,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC;AAC5D,MAAM,MAAM,iBAAiB,GAAG,CAAC,MAAM,CAAC,CAAC;AAGzC,MAAM,MAAM,uBAAuB,CAAC,CAAC,GAAG,MAAM,IAAI,CAAC,KAAK,EAAE,OAAO,GAAG,CAAC,EAAE,GAAG,CAAC,EAAE,OAAO,GAAG,IAAI,KAAK,OAAO,CAAC;AACxG,MAAM,MAAM,oBAAoB,GAAG;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,GAAG,CAAC,EAAE,OAAO,GAAG,IAAI,CAAA;CAAE,CAAC;AAC5E,MAAM,MAAM,0BAA0B,GAAG,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC,CAAC;AAEnE,MAAM,MAAM,sBAAsB,GAAG,CAAC,GAAG,CAAC,EAAE,OAAO,GAAG,IAAI,KAAK,OAAO,CAAC;AACvE,MAAM,MAAM,mBAAmB,GAAG;IAAE,GAAG,CAAC,EAAE,OAAO,GAAG,IAAI,CAAA;CAAE,CAAC;AAC3D,MAAM,MAAM,yBAAyB,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,CAAC;AAGzD,KAAK,OAAO,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,GAAG,CAAC,CAAC;AAE9D,wBAAgB,YAAY,CAAC,SAAS,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EAAE,MAAM,SAAS,GAAG,EAAE,EAC1F,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE;IAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;IAAC,IAAI,EAAE,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,MAAM,KAAK,GAAG,CAAA;CAAE;;;EAE1F;AAED,wBAAgB,WAAW,CAAC,SAAS,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EAAE,MAAM,SAAS,GAAG,EAAE,EACzF,EAAE,QAAQ,EAAE,IAAI,EAAE,EAAE;IAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;IAAC,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,MAAM,KAAK,GAAG,CAAA;CAAE,6DAE5E;AAED,qBAAa,QAAQ,CAAC,SAAS,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EAAE,MAAM,SAAS,GAAG,EAAE;IACnF,QAAQ,EAAE,OAAO,EAAE,CAAC;gBAER,QAAQ,EAAE,OAAO,EAAE;IAI/B,KAAK,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,SAAS,CAAC,GAAG,MAAM;IAsB7C,eAAe,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,MAAM,KAAK,UAAU,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,GAAG,OAAO,EAAE,GAAG,IAAI,EAAE,UAAU,CAAC,SAAS,CAAC,KAAK,UAAU,CAAC,SAAS,CAAC;IAQxL,aAAa,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,MAAM,KAAK,UAAU,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,SAAS,CAAC,KAAK,UAAU,CAAC,SAAS,CAAC;IAQrJ,UAAU,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,IAAI,EAAE,MAAM,KAAK,UAAU,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,CAAC;;;;IAItF,WAAW,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,MAAM,KAAK,UAAU,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,SAAS,CAAC,KAAK,UAAU,CAAC,SAAS,CAAC;CAQtI"} \ No newline at end of file diff --git a/dist/NDArray/operators.d.ts b/dist/NDArray/operators.d.ts new file mode 100644 index 0000000..f451419 --- /dev/null +++ b/dist/NDArray/operators.d.ts @@ -0,0 +1,164 @@ +import * as indexes from './indexes'; +import type NDArray from "../NDArray-class"; +export type ArrayOrConstant = NDArray | number | boolean; +type Index = indexes.Where; +export declare function binary_operation(A: ArrayOrConstant, B: ArrayOrConstant, func: any, dtype: any, out?: NDArray | null): ArrayOrConstant; +export declare function _broadcast_shapes(shapeA: any, shapeB: any): any[]; +export type BinaryOperator = (A: ArrayOrConstant, B: ArrayOrConstant, out?: NDArray | null) => NDArray; +export type SelfBinaryOperator = (other: ArrayOrConstant, out?: NDArray | null) => NDArray; +export declare function __make_operator(dtype: any, func: any): BinaryOperator; +export declare function __make_operator_special(funcNum: any, funcBool: any): BinaryOperator; +export declare const op_binary: { + "+": BinaryOperator; + "-": BinaryOperator; + "*": BinaryOperator; + "/": BinaryOperator; + "%": BinaryOperator; + "//": BinaryOperator; + "**": BinaryOperator; + "<": BinaryOperator; + ">": BinaryOperator; + ">=": BinaryOperator; + "<=": BinaryOperator; + "==": BinaryOperator; + "!=": BinaryOperator; + "|": BinaryOperator; + "&": BinaryOperator; + "^": BinaryOperator; + "<<": BinaryOperator; + ">>": BinaryOperator; + or: BinaryOperator; + and: BinaryOperator; + xor: BinaryOperator; + max: BinaryOperator; + min: BinaryOperator; +}; +export declare function assign_operation(tgt: NDArray, src: ArrayOrConstant, where: Index, func: any, dtype: any): void; +export declare function _assign_operation_toJS(tgtJS: any[], src: any, where: Index, func: any, dtype: any): void; +export type AssignmentOperator = { + (tgt: NDArray, src: ArrayOrConstant): NDArray; + (tgt: NDArray, where: Index, src: ArrayOrConstant): NDArray; +}; +export type SelfAssignmentOperator = { + (other: ArrayOrConstant): NDArray; + (where: Index, other: ArrayOrConstant): NDArray; +}; +export declare function __make_assignment_operator(dtype: any, func: any): AssignmentOperator; +export declare const op_assign: { + "=": AssignmentOperator; + "+=": AssignmentOperator; + "-=": AssignmentOperator; + "*=": AssignmentOperator; + "/=": AssignmentOperator; + "%=": AssignmentOperator; + "//=": AssignmentOperator; + "**=": AssignmentOperator; + "|=": AssignmentOperator; + "&=": AssignmentOperator; + "^=": AssignmentOperator; + "<<=": AssignmentOperator; + ">>=": AssignmentOperator; + "max=": AssignmentOperator; + "min=": AssignmentOperator; + "or=": AssignmentOperator; + "and=": AssignmentOperator; +}; +export declare function isclose(A: any, B: any, rtol?: number, atol?: number, equal_nan?: boolean): ArrayOrConstant; +export declare function allclose(A: any, B: any, rtol?: number, atol?: number, equal_nan?: boolean): boolean; +export declare const kw_op_binary: { + "+": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "-": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "*": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "/": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "%": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "//": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "**": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "<": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + ">": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + ">=": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "<=": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "==": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "!=": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "|": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "&": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "^": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + "<<": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + ">>": { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + max: { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + min: { + as_function: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + as_method: (other: number | NDArray, out?: NDArray) => NDArray; + }; + or: { + as_function: (arr: number | boolean | NDArray, other: boolean | NDArray, out?: NDArray) => NDArray; + as_method: (other: boolean | NDArray, out?: NDArray) => NDArray; + }; + and: { + as_function: (arr: number | boolean | NDArray, other: boolean | NDArray, out?: NDArray) => NDArray; + as_method: (other: boolean | NDArray, out?: NDArray) => NDArray; + }; + xor: { + as_function: (arr: number | boolean | NDArray, other: boolean | NDArray, out?: NDArray) => NDArray; + as_method: (other: boolean | NDArray, out?: NDArray) => NDArray; + }; +}; +export declare const atan2: (y: NDArray, x: NDArray, out?: NDArray) => NDArray; +export {}; +//# sourceMappingURL=operators.d.ts.map \ No newline at end of file diff --git a/dist/NDArray/operators.d.ts.map b/dist/NDArray/operators.d.ts.map new file mode 100644 index 0000000..8013549 --- /dev/null +++ b/dist/NDArray/operators.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"operators.d.ts","sourceRoot":"","sources":["../../src/NDArray/operators.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC;AAKrC,OAAO,KAAK,OAAO,MAAM,kBAAkB,CAAC;AAG5C,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG,MAAM,GAAG,OAAO,CAAC;AACzD,KAAK,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;AAG3B,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,eAAe,EAAE,CAAC,EAAE,eAAe,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,GAAE,OAAO,GAAG,IAAW,GAAG,eAAe,CA0B3I;AAED,wBAAgB,iBAAiB,CAAC,MAAM,KAAA,EAAE,MAAM,KAAA,SAa/C;AAED,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,EAAE,eAAe,EAAE,CAAC,EAAE,eAAe,EAAE,GAAG,CAAC,EAAE,OAAO,GAAG,IAAI,KAAK,OAAO,CAAA;AACtG,MAAM,MAAM,kBAAkB,GAAG,CAAC,KAAK,EAAE,eAAe,EAAE,GAAG,CAAC,EAAE,OAAO,GAAG,IAAI,KAAK,OAAO,CAAA;AAE1F,wBAAgB,eAAe,CAAC,KAAK,KAAA,EAAE,IAAI,KAAA,GAAG,cAAc,CAM3D;AAED,wBAAgB,uBAAuB,CAAC,OAAO,KAAA,EAAE,QAAQ,KAAA,GAAG,cAAc,CAYzE;AAED,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;CA0BrB,CAAA;AAUD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,KAAA,EAAE,KAAK,KAAA,QAuB7F;AAID,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,QAWjG;AAGD,MAAM,MAAM,kBAAkB,GAAG;IAAE,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,eAAe,GAAG,OAAO,CAAC;IAAC,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,eAAe,GAAG,OAAO,CAAC;CAAE,CAAA;AAChJ,MAAM,MAAM,sBAAsB,GAAG;IAAE,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC;IAAC,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC;CAAE,CAAA;AAG5H,wBAAgB,0BAA0B,CAAC,KAAK,KAAA,EAAE,IAAI,KAAA,GAAG,kBAAkB,CAW1E;AAED,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;CAmBrB,CAAC;AASF,wBAAgB,OAAO,CAAC,CAAC,KAAA,EAAE,CAAC,KAAA,EAAE,IAAI,SAAQ,EAAE,IAAI,SAAQ,EAAE,SAAS,UAAQ,mBAO1E;AAED,wBAAgB,QAAQ,CAAC,CAAC,KAAA,EAAE,CAAC,KAAA,EAAE,IAAI,SAAQ,EAAE,IAAI,SAAQ,EAAE,SAAS,UAAQ,WAkB3E;AAYD,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0FxB,CAAA;AAED,eAAO,MAAM,KAAK,oDAGhB,CAAC"} \ No newline at end of file diff --git a/dist/NDArray/print.d.ts b/dist/NDArray/print.d.ts new file mode 100644 index 0000000..8930d84 --- /dev/null +++ b/dist/NDArray/print.d.ts @@ -0,0 +1,3 @@ +import type NDArray from "../NDArray-class"; +export declare function humanReadable(arr: NDArray): any; +//# sourceMappingURL=print.d.ts.map \ No newline at end of file diff --git a/dist/NDArray/print.d.ts.map b/dist/NDArray/print.d.ts.map new file mode 100644 index 0000000..80112a2 --- /dev/null +++ b/dist/NDArray/print.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"print.d.ts","sourceRoot":"","sources":["../../src/NDArray/print.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,OAAO,MAAM,kBAAkB,CAAC;AAI5C,wBAAgB,aAAa,CAAC,GAAG,EAAE,OAAO,OA+EzC"} \ No newline at end of file diff --git a/dist/NDArray/reduce.d.ts b/dist/NDArray/reduce.d.ts new file mode 100644 index 0000000..c107feb --- /dev/null +++ b/dist/NDArray/reduce.d.ts @@ -0,0 +1,72 @@ +import NDArray from "../NDArray-class"; +import { AxisArg } from './kwargs'; +export declare const reducers: { + sum: (arr: NDArray, axis: AxisArg | null, keepdims: boolean) => any; + product: (arr: NDArray, axis: AxisArg | null, keepdims: boolean) => any; + mean: (arr: NDArray, axis: AxisArg | null, keepdims: boolean) => number | NDArray; + max: (arr: NDArray, axis: AxisArg | null, keepdims: boolean) => number | NDArray; + min: (arr: NDArray, axis: AxisArg | null, keepdims: boolean) => number | NDArray; + argmax: (arr: NDArray, axis: AxisArg | null, keepdims: boolean) => number | NDArray; + argmin: (arr: NDArray, axis: AxisArg | null, keepdims: boolean) => number | NDArray; + len: (arr: NDArray, axis: AxisArg | null, keepdims: boolean) => number | NDArray; + any: (arr: NDArray, axis: AxisArg | null, keepdims: boolean) => boolean | NDArray; + all: (arr: NDArray, axis: AxisArg | null, keepdims: boolean) => boolean | NDArray; + norm: (arr: NDArray, axis: AxisArg, keepdims: boolean, ord: number) => any; + var: (arr: NDArray, axis: AxisArg, keepdims: boolean) => number | NDArray; + std: (arr: NDArray, axis: AxisArg, keepdims: boolean, ddof: number) => NDArray; +}; +export declare const kw_reducers: { + sum: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + }; + product: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + }; + mean: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + }; + max: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + }; + min: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + }; + argmax: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + }; + argmin: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + }; + len: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + }; + any: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => boolean | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => boolean | NDArray; + }; + all: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => boolean | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => boolean | NDArray; + }; + norm: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceNormKwargs, keepdims?: boolean | import("./kwargs").ReduceNormKwargs, ord?: number | import("./kwargs").ReduceNormKwargs) => number | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceNormKwargs, keepdims?: boolean | import("./kwargs").ReduceNormKwargs, ord?: number | import("./kwargs").ReduceNormKwargs) => number | NDArray; + }; + var: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceKwargs, keepdims?: boolean | import("./kwargs").ReduceKwargs) => number | NDArray; + }; + std: { + as_function: (arr: number | boolean | NDArray, axis?: number | import("./kwargs").ReduceStdKwargs, keepdims?: boolean | import("./kwargs").ReduceStdKwargs, ddof?: number | import("./kwargs").ReduceStdKwargs) => number | NDArray; + as_method: (axis?: number | import("./kwargs").ReduceStdKwargs, keepdims?: boolean | import("./kwargs").ReduceStdKwargs, ddof?: number | import("./kwargs").ReduceStdKwargs) => number | NDArray; + }; +}; +//# sourceMappingURL=reduce.d.ts.map \ No newline at end of file diff --git a/dist/NDArray/reduce.d.ts.map b/dist/NDArray/reduce.d.ts.map new file mode 100644 index 0000000..3663b20 --- /dev/null +++ b/dist/NDArray/reduce.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"reduce.d.ts","sourceRoot":"","sources":["../../src/NDArray/reduce.ts"],"names":[],"mappings":"AAGA,OAAO,OAAO,MAAM,kBAAkB,CAAC;AAEvC,OAAO,EAAE,OAAO,EAA6I,MAAM,UAAU,CAAC;AA4C9K,eAAO,MAAM,QAAQ;eALN,OAAO,QAAQ,OAAO,GAAG,IAAI,YAAY,OAAO;mBAAhD,OAAO,QAAQ,OAAO,GAAG,IAAI,YAAY,OAAO;gBAAhD,OAAO,QAAQ,OAAO,GAAG,IAAI,YAAY,OAAO;eAAhD,OAAO,QAAQ,OAAO,GAAG,IAAI,YAAY,OAAO;eAAhD,OAAO,QAAQ,OAAO,GAAG,IAAI,YAAY,OAAO;kBAAhD,OAAO,QAAQ,OAAO,GAAG,IAAI,YAAY,OAAO;kBAAhD,OAAO,QAAQ,OAAO,GAAG,IAAI,YAAY,OAAO;eAAhD,OAAO,QAAQ,OAAO,GAAG,IAAI,YAAY,OAAO;eAAhD,OAAO,QAAQ,OAAO,GAAG,IAAI,YAAY,OAAO;eAAhD,OAAO,QAAQ,OAAO,GAAG,IAAI,YAAY,OAAO;gBAsBjD,OAAO,QAAQ,OAAO,YAAY,OAAO,OAAO,MAAM;eAMvD,OAAO,QAAQ,OAAO,YAAY,OAAO;eAKzC,OAAO,QAAQ,OAAO,YAAY,OAAO,QAAQ,MAAM;CAMnE,CAAA;AAED,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqDvB,CAAC"} \ No newline at end of file diff --git a/dist/NDArray/transform.d.ts b/dist/NDArray/transform.d.ts new file mode 100644 index 0000000..def0277 --- /dev/null +++ b/dist/NDArray/transform.d.ts @@ -0,0 +1,10 @@ +import { DType } from '../NDArray-class'; +import type NDArray from "../NDArray-class"; +import { ArrayOrConstant } from './operators'; +export declare function apply_along_axis(arr: NDArray, axis: number, transform: any, dtype?: DType): ArrayOrConstant; +export declare function sort(A: NDArray, axis?: number): ArrayOrConstant; +export declare function transpose(arr: NDArray, axes?: null | number[]): NDArray; +export declare function swapAxes(arr: NDArray, axisA: number, axisB: number): NDArray; +export declare function concatenate(arrays: NDArray[], axis?: number | null): NDArray; +export declare function stack(arrays: NDArray[], axis?: number): NDArray; +//# sourceMappingURL=transform.d.ts.map \ No newline at end of file diff --git a/dist/NDArray/transform.d.ts.map b/dist/NDArray/transform.d.ts.map new file mode 100644 index 0000000..2b6e93f --- /dev/null +++ b/dist/NDArray/transform.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transform.d.ts","sourceRoot":"","sources":["../../src/NDArray/transform.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACzC,OAAO,KAAK,OAAO,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE9C,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,KAAA,EAAE,KAAK,GAAE,KAAc,GAAG,eAAe,CA8B9G;AAGD,wBAAgB,IAAI,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,SAAK,mBASzC;AAED,wBAAgB,SAAS,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,GAAE,IAAI,GAAG,MAAM,EAAS,WAwCnE;AAGD,wBAAgB,QAAQ,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,WASlE;AAGD,wBAAgB,WAAW,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,IAAI,GAAE,MAAM,GAAG,IAAW,WA0BxE;AAGD,wBAAgB,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,IAAI,GAAE,MAAU,WAiBxD"} \ No newline at end of file diff --git a/dist/_globals.d.ts b/dist/_globals.d.ts new file mode 100644 index 0000000..0734ab9 --- /dev/null +++ b/dist/_globals.d.ts @@ -0,0 +1,108 @@ +/** + * This file exists for the sole purpose splitting the class methods across multiple files + * while preserving all features of intellisense or JSDoc without errors. + * The main issue is that the implementation of the methods require NDArray very often. + * It resolves circular dependencies by using a global variable imported in each module. + * The main file must define `require('./core-globals').GLOBALS.NDArray = NDArray;` before + * importing any of the files that use it. + * + * A template header for files importing NDArray from this file is given below. + * DO NOT use `const NDArray = require("./core-globals").GLOBALS.NDArray;`. + * Use const {NDArray} = ... instead as indicated. (Intellisense stops working otherwise) + */ +export declare const GLOBALS: { + NDArray: typeof import("./NDArray-class").NDArray; + np: { + (template: number | boolean | any[] | TemplateStringsArray, ...variables: any[]): any; + NDArray: typeof import("./NDArray-class").NDArray; + tolist(template: number | boolean | any[] | TemplateStringsArray, ...variables: any[]): any; + fromlist: typeof import("./NDArray/js-interface").fromlist; + ravel: typeof import("./NDArray/basic").ravel; + reshape: typeof import("./NDArray/basic").reshape; + array: typeof import("./NDArray/_globals").array; + asarray: typeof import("./NDArray/_globals").asarray; + sum: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | import("./NDArray-class").NDArray; + product: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | import("./NDArray-class").NDArray; + prod: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | import("./NDArray-class").NDArray; + any: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => boolean | import("./NDArray-class").NDArray; + all: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => boolean | import("./NDArray-class").NDArray; + max: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | import("./NDArray-class").NDArray; + min: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | import("./NDArray-class").NDArray; + argmax: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | import("./NDArray-class").NDArray; + argmin: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | import("./NDArray-class").NDArray; + mean: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | import("./NDArray-class").NDArray; + norm: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceNormKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceNormKwargs, ord?: number | import("./NDArray/kwargs").ReduceNormKwargs) => number | import("./NDArray-class").NDArray; + var: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | import("./NDArray-class").NDArray; + std: (arr: number | boolean | import("./NDArray-class").NDArray, axis?: number | import("./NDArray/kwargs").ReduceStdKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceStdKwargs, ddof?: number | import("./NDArray/kwargs").ReduceStdKwargs) => number | import("./NDArray-class").NDArray; + transpose: typeof import("./NDArray/transform").transpose; + apply_along_axis: typeof import("./NDArray/transform").apply_along_axis; + sort: typeof import("./NDArray/transform").sort; + concatenate: typeof import("./NDArray/transform").concatenate; + stack: typeof import("./NDArray/transform").stack; + add: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + subtract: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + multiply: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + divide: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + mod: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + divide_int: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + pow: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + bitwise_or: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + bitwise_and: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + bitwise_xor: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + bitwise_shift_left: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + bitwise_shift_right: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + greater: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + less: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + greater_equal: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + less_equal: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + equal: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + not_equal: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + maximum: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + minimum: (arr: number | boolean | import("./NDArray-class").NDArray, other: number | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + logical_or: (arr: number | boolean | import("./NDArray-class").NDArray, other: boolean | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + logical_and: (arr: number | boolean | import("./NDArray-class").NDArray, other: boolean | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + atan2: (y: import("./NDArray-class").NDArray, x: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + allclose: typeof import("./NDArray/operators").allclose; + isclose: typeof import("./NDArray/operators").isclose; + sign: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + sqrt: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + square: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + exp: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + log: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + log2: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + log10: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + log1p: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + sin: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + cos: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + tan: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + asin: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + acos: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + atan: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + cosh: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + sinh: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + tanh: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + acosh: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + asinh: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + atanh: (A: import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + abs: (arr: number | boolean | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + bitwise_not: (arr: number | boolean | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + logical_not: (arr: number | boolean | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + negative: (arr: number | boolean | import("./NDArray-class").NDArray, out?: import("./NDArray-class").NDArray) => import("./NDArray-class").NDArray; + round: (arr: number | boolean | import("./NDArray-class").NDArray, decimals?: number) => import("./NDArray-class").NDArray; + modules: { + constructors: typeof import("./modules/constructors"); + grammar: typeof import("./modules/grammar"); + random: typeof import("./modules/random"); + }; + empty: typeof import("./modules/constructors").empty; + zeros: typeof import("./modules/constructors").zeros; + ones: typeof import("./modules/constructors").ones; + arange: typeof import("./modules/constructors").arange; + linspace: typeof import("./modules/constructors").linspace; + geomspace: typeof import("./modules/constructors").geomspace; + random: typeof import("./modules/random"); + pi: number; + e: number; + }; +}; +//# sourceMappingURL=_globals.d.ts.map \ No newline at end of file diff --git a/dist/_globals.d.ts.map b/dist/_globals.d.ts.map new file mode 100644 index 0000000..bb2fac1 --- /dev/null +++ b/dist/_globals.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_globals.d.ts","sourceRoot":"","sources":["../src/_globals.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;GAWG;AASH,eAAO,MAAM,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAGnB,CAAC"} \ No newline at end of file diff --git a/dist/caph1993-numpy-js.js b/dist/caph1993-numpy-js.js deleted file mode 100644 index 7ec90ed..0000000 --- a/dist/caph1993-numpy-js.js +++ /dev/null @@ -1,2 +0,0 @@ -!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]>"].as_method,s.prototype.logical_or=u.modules.operators.kw_op_binary.or.as_method,s.prototype.logical_and=u.modules.operators.kw_op_binary.and.as_method,s.prototype.logical_xor=u.modules.operators.kw_op_binary.xor.as_method,s.prototype.greater=u.modules.operators.kw_op_binary[">"].as_method,s.prototype.less=u.modules.operators.kw_op_binary["<"].as_method,s.prototype.greater_equal=u.modules.operators.kw_op_binary[">="].as_method,s.prototype.less_equal=u.modules.operators.kw_op_binary["<="].as_method,s.prototype.equal=u.modules.operators.kw_op_binary["=="].as_method,s.prototype.not_equal=u.modules.operators.kw_op_binary["!="].as_method,s.prototype.bitwise_not=u.modules.elementwise.kw_ops.bitwise_not.as_method,s.prototype.logical_not=u.modules.elementwise.kw_ops.logical_not.as_method,s.prototype.negative=u.modules.elementwise.kw_ops.negative.as_method,s.prototype.abs=u.modules.elementwise.kw_ops.abs.as_method,s.prototype.isclose=u.modules.operators.isclose,s.prototype.allclose=u.modules.operators.allclose,s.prototype.assign=c(u.modules.operators.op_assign["="]),s.prototype.add_assign=c(u.modules.operators.op_assign["+="]),s.prototype.subtract_assign=c(u.modules.operators.op_assign["-="]),s.prototype.multiply_assign=c(u.modules.operators.op_assign["*="]),s.prototype.divide_assign=c(u.modules.operators.op_assign["/="]),s.prototype.mod_assign=c(u.modules.operators.op_assign["%="]),s.prototype.divide_int_assign=c(u.modules.operators.op_assign["//="]),s.prototype.pow_assign=c(u.modules.operators.op_assign["**="]),s.prototype.maximum_assign=c(u.modules.operators.op_assign["↑="]),s.prototype.minimum_assign=c(u.modules.operators.op_assign["↓="]),s.prototype.bitwise_or_assign=c(u.modules.operators.op_assign["|="]),s.prototype.bitwise_and_assign=c(u.modules.operators.op_assign["&="]),s.prototype.bitwise_shift_left_assign=c(u.modules.operators.op_assign["<<="]),s.prototype.bitwise_shift_right_assign=c(u.modules.operators.op_assign[">>="]),s.prototype.logical_or_assign=c(u.modules.operators.op_assign["or="]),s.prototype.logical_and_assign=c(u.modules.operators.op_assign["and="]),s.prototype.tolist=function(){return u.modules.jsInterface.tolist(this)},s.prototype.round=u.modules.elementwise.kw_ops.round.as_method,s.prototype.transpose=function(e){return u.modules.transform.transpose(this,e=void 0===e?null:e)},s.prototype.sort=function(e){return u.modules.transform.sort(this,e=void 0===e?-1:e),null};s.prototype.op=function(){for(var e=[],t=0;t{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,f=(u-=m,1),d=0;d=e.length)throw new Error("Index spans over more dimensions than available in shape [".concat(e,"]: index(").concat(t,")"));f*=e[o],o+=i}n.axisIndexes.push(h),"number"!=h.spec.type&&n.apparentShape.push(h.size),n.internalShape.push(f)}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 d=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.atan2=t.kw_op_binary=t.allclose=t.isclose=t.op_assign=t.__make_assignment_operator=t._assign_operation_toJS=t.assign_operation=t.op_binary=t.__make_operator_special=t.__make_operator=t._broadcast_shapes=t.binary_operation=void 0,r(591)),w=r(870),o=r(545),r=r(380);function m(e,t,r,n,i){if(void 0===i&&(i=null),(0,w.isarray)(this))return r.bind(w._NDArray.prototype).apply(void 0,b([this],_(arguments),!1));e=(0,w.asarray)(e),t=(0,w.asarray)(t);var a=_(x(e.shape,t.shape),3),o=a[0],s=a[1],u=a[2];if(null==i)i=(0,w.new_from)(o,function(e){},n);else if(!(0,w.isarray)(i))throw new Error("Out must be of type ".concat(w._NDArray,". Got ").concat(typeof i));for(var l=[],c=(0,w.shape_shifts)(s),p=(0,w.shape_shifts)(u),h=e.flat,m=t.flat,f=0;f>="|"//="|"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 0==Object.keys(e).length?t.apply(void 0,u([],s(n),!1)):t.apply(void 0,u(u([],s(n),!1),[e],!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 0==Object.keys(n).length?e[r].apply(e,u([],s(i),!1)):e[r].apply(e,u(u([],s(i),!1),[n],!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.elementwise.ops;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 C(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:C,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:f,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 x(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 f,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 de="⋅",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,de).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 f;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=x.prototype.allowsSkippingPrecedingSpace=c.prototype.allowsSkippingPrecedingSpace=a.prototype.allowsSkippingPrecedingSpace=I.prototype.allowsSkippingPrecedingSpace=function(){return!0},s.prototype.allowsSkippingPrecedingSpace=d.prototype.allowsSkippingPrecedingSpace=w.prototype.allowsSkippingPrecedingSpace=b.prototype.allowsSkippingPrecedingSpace=_.prototype.allowsSkippingPrecedingSpace=o.prototype.allowsSkippingPrecedingSpace=h.prototype.allowsSkippingPrecedingSpace=function(){return!1};let O;ue(e=>{O=e});let we;n.prototype.assertAllApplicationsAreValid=function(e,t){we=0,this._assertAllApplicationsAreValid(e,t)},n.prototype._assertAllApplicationsAreValid=t("_assertAllApplicationsAreValid"),r._assertAllApplicationsAreValid=i._assertAllApplicationsAreValid=c.prototype._assertAllApplicationsAreValid=a.prototype._assertAllApplicationsAreValid=o.prototype._assertAllApplicationsAreValid=I.prototype._assertAllApplicationsAreValid=function(e,t){},w.prototype._assertAllApplicationsAreValid=function(e,t){we++,this.expr._assertAllApplicationsAreValid(e,t),we--},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=w.prototype.assertChoicesHaveUniformArity=I.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 xe{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])},w.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",k(this,r),e.map(e=>e.outputRecipe(t,r)),n.map(e=>e.outputRecipe(t,r))]},h.prototype.outputRecipe=function(t,r){return["seq",k(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=w.prototype.outputRecipe=function(e,t){return[this.constructor.name.toLowerCase(),k(this,t),this.expr.outputRecipe(e,t)]},x.prototype.outputRecipe=function(t,r){return["app",k(this,r),this.ruleName,this.args.map(e=>e.outputRecipe(t,r))]},I.prototype.outputRecipe=function(e,t){return["unicodeChar",k(this,t),this.category]},n.prototype.introduceParams=t("introduceParams"),r.introduceParams=i.introduceParams=c.prototype.introduceParams=a.prototype.introduceParams=o.prototype.introduceParams=I.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},d.prototype.introduceParams=_.prototype.introduceParams=b.prototype.introduceParams=w.prototype.introduceParams=function(e){return this.expr=this.expr.introduceParams(e),this},x.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=I.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},w.prototype._isNullable=function(e,t){return this.expr._isNullable(e,t)},x.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=I.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)))},d.prototype.substituteParams=_.prototype.substituteParams=b.prototype.substituteParams=w.prototype.substituteParams=function(e){return new this.constructor(this.expr.substituteParams(e))},x.prototype.substituteParams=function(t){var e;return 0===this.args.length?this:(e=this.args.map(e=>e.substituteParams(t)),new x(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},d.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=w.prototype.toArgumentNameList=function(e,t){return this.expr.toArgumentNameList(e,t)},x.prototype.toArgumentNameList=function(e,t){return[this.ruleName]},I.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=d.prototype.toDisplayString=_.prototype.toDisplayString=b.prototype.toDisplayString=w.prototype.toDisplayString=c.prototype.toDisplayString=a.prototype.toDisplayString=o.prototype.toDisplayString=function(){return this.toString()},x.prototype.toDisplayString=function(){var e;return 0e.toDisplayString()),this.ruleName+"<"+e.join(",")+">"):this.ruleName},I.prototype.toDisplayString=function(){return"Unicode ["+this.category+"] character"};class E{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 E(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 E(this,"any object","description")},i.toFailure=function(e){return new E(this,"end of input","description")},c.prototype.toFailure=function(e){return new E(this,this.obj,"string")},a.prototype.toFailure=function(e){return new E(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 E(this,e,"description")},b.prototype.toFailure=function(e){return this.expr.toFailure(e)},x.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 E(this,t,"description")},I.prototype.toFailure=function(e){return new E(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 E(this,e,"description")},h.prototype.toFailure=function(t){var e="("+this.factors.map(e=>e.toFailure(t)).join(" ")+")";return new E(this,e,"description")},d.prototype.toFailure=function(e){e="("+this.expr.toFailure(e)+this.operator+")";return new E(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},w.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(" ")+")"},d.prototype.toString=function(){return this.expr+this.operator},_.prototype.toString=function(){return"~"+this.expr},b.prototype.toString=function(){return"&"+this.expr},x.prototype.toString=function(){var e;return 0e.toString()),this.ruleName+"<"+e.join(",")+">"):this.ruleName},I.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 E(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:d,Star:y,Plus:g,Opt:v,Not:_,Lookahead:b,Lex:w,Apply:x,UnicodeChar:I});let ke;ue(e=>{ke=e.rules.applySyntactic.body});const Ee=new x("spaces");class Le{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(Ee),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==Ee?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 fe)}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 x){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 x&&(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===Ee,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===ke&&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 Re{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 De{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 R{constructor(e,t){const n=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(t?t.Wrapper:De){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!==R.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,L);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 je(u,e,l,r):new Ce(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(Fe(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 je(t,i,o):new Ce(t,o),this[n][t].checkActionDict(this.grammar)}assertNewName(e,t){if(Fe(De.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(!R.prototypeGrammar)return m(-1===e.indexOf("(")),{name:e,formals:[]};e=R.prototypeGrammar.match(e,"operation"===t?"OperationSignature":"AttributeSignature");if(e.failed())throw new Error(e.message);return R.prototypeGrammarSemantics(e).parse()}R.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 R(n,void 0!==e?e:R.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 je{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?(L.push([this,r]),e.apply(t,t._children())):(t.isNonterminal()&&(e=this.actionDict._nonterminal)?(L.push([this,"_nonterminal",r]),e):(L.push([this,"default action",r]),this.actionDict._default)).apply(t,t._children())}finally{L.pop()}}}je.prototype.typeName="operation";class Ce extends je{constructor(e,t,r){super(e,[],t,r)}execute(e,t){var r=t._node,n=e.attributeKeys[this.name];return Fe(r,n)||(r[n]=je.prototype.execute.call(this,e,t)),r[n]}}Ce.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 F{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 Re(this)}isBuiltIn(){return this===F.ProtoBuiltInRules||this===F.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 R.createSemantics(this)}extendSemantics(e){return R.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 f;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 x(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)}}F.ProtoBuiltInRules=new F("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 I("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new I("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new I("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new y(new x("space")),formals:[]},space:{body:new a("\0"," "),formals:[],description:"a space"}}),F.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?F.ProtoBuiltInRules:F.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 w(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=(F.BuiltInRules=$e,Ve=F.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()===F.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",[]]]]}]);M=F.BuiltInRules,D={empty(){return this.iteration()},nonEmpty(e,t,r){return this.iteration([e].concat(r.children))}},R.BuiltInSemantics=R.createSemantics(M,null).addOperation("asIteration",{emptyListOf:D.empty,nonemptyListOf:D.nonEmpty,EmptyListOf:D.empty,NonemptyListOf:D.nonEmpty}),M=Ze,R.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}}),R.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 E(this,t,"description")}}var D=new x("indent"),Ze=new x("dedent"),M=new p($e,"any",[D,Ze],[]),D=(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",[],M,"any character",void 0).build();Object.assign(D,{_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=D,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 // __popKwArgs() {\n // let out = this['__kwArgs'];\n // if (out === undefined) return {};\n // delete this['__kwArgs'];\n // return out;\n // }\n // /** @param {Object} kwArgs */\n // withKwArgs(kwArgs: { [s: string]: any; }) {\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// ==============================\nNDArray.prototype.any = NDArray_1.modules.reduce.kw_reducers.any.as_method;\nNDArray.prototype.all = NDArray_1.modules.reduce.kw_reducers.all.as_method;\nNDArray.prototype.sum = NDArray_1.modules.reduce.kw_reducers.sum.as_method;\nNDArray.prototype.product = NDArray_1.modules.reduce.kw_reducers.product.as_method;\nNDArray.prototype.max = NDArray_1.modules.reduce.kw_reducers.max.as_method;\nNDArray.prototype.min = NDArray_1.modules.reduce.kw_reducers.min.as_method;\nNDArray.prototype.argmax = NDArray_1.modules.reduce.kw_reducers.argmax.as_method;\nNDArray.prototype.argmin = NDArray_1.modules.reduce.kw_reducers.argmin.as_method;\nNDArray.prototype.mean = NDArray_1.modules.reduce.kw_reducers.mean.as_method;\nNDArray.prototype.var = NDArray_1.modules.reduce.kw_reducers.var.as_method;\nNDArray.prototype.std = NDArray_1.modules.reduce.kw_reducers.std.as_method;\nNDArray.prototype.norm = NDArray_1.modules.reduce.kw_reducers.norm.as_method;\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 return func(this, other, out);\n };\n}\nNDArray.prototype.add = NDArray_1.modules.operators.kw_op_binary[\"+\"].as_method;\nNDArray.prototype.subtract = NDArray_1.modules.operators.kw_op_binary[\"-\"].as_method;\nNDArray.prototype.multiply = NDArray_1.modules.operators.kw_op_binary[\"*\"].as_method;\nNDArray.prototype.divide = NDArray_1.modules.operators.kw_op_binary[\"/\"].as_method;\nNDArray.prototype.mod = NDArray_1.modules.operators.kw_op_binary[\"%\"].as_method;\nNDArray.prototype.divide_int = NDArray_1.modules.operators.kw_op_binary[\"//\"].as_method;\nNDArray.prototype.pow = NDArray_1.modules.operators.kw_op_binary[\"**\"].as_method;\nNDArray.prototype.maximum = NDArray_1.modules.operators.kw_op_binary[\"max\"].as_method;\nNDArray.prototype.minimum = NDArray_1.modules.operators.kw_op_binary[\"min\"].as_method;\nNDArray.prototype.bitwise_or = NDArray_1.modules.operators.kw_op_binary[\"|\"].as_method;\nNDArray.prototype.bitwise_and = NDArray_1.modules.operators.kw_op_binary[\"&\"].as_method;\nNDArray.prototype.bitwise_or = NDArray_1.modules.operators.kw_op_binary[\"^\"].as_method;\nNDArray.prototype.bitwise_shift_right = NDArray_1.modules.operators.kw_op_binary[\"<<\"].as_method;\nNDArray.prototype.bitwise_shift_right = NDArray_1.modules.operators.kw_op_binary[\">>\"].as_method;\nNDArray.prototype.logical_or = NDArray_1.modules.operators.kw_op_binary[\"or\"].as_method;\nNDArray.prototype.logical_and = NDArray_1.modules.operators.kw_op_binary[\"and\"].as_method;\nNDArray.prototype.logical_xor = NDArray_1.modules.operators.kw_op_binary[\"xor\"].as_method;\nNDArray.prototype.greater = NDArray_1.modules.operators.kw_op_binary[\">\"].as_method;\nNDArray.prototype.less = NDArray_1.modules.operators.kw_op_binary[\"<\"].as_method;\nNDArray.prototype.greater_equal = NDArray_1.modules.operators.kw_op_binary[\">=\"].as_method;\nNDArray.prototype.less_equal = NDArray_1.modules.operators.kw_op_binary[\"<=\"].as_method;\nNDArray.prototype.equal = NDArray_1.modules.operators.kw_op_binary[\"==\"].as_method;\nNDArray.prototype.not_equal = NDArray_1.modules.operators.kw_op_binary[\"!=\"].as_method;\n// Unary operations: only boolean_not. Positive is useless and negative is almost useless\nNDArray.prototype.bitwise_not = NDArray_1.modules.elementwise.kw_ops.bitwise_not.as_method;\nNDArray.prototype.logical_not = NDArray_1.modules.elementwise.kw_ops.logical_not.as_method;\nNDArray.prototype.negative = NDArray_1.modules.elementwise.kw_ops.negative.as_method;\nNDArray.prototype.abs = NDArray_1.modules.elementwise.kw_ops.abs.as_method;\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 = NDArray_1.modules.elementwise.kw_ops.round.as_method;\n// ==============================\n// transform methods\n// ==============================\n/** @param {null|number[]} axes */\nNDArray.prototype.transpose = function (axes) {\n if (axes === void 0) { axes = null; }\n return NDArray_1.modules.transform.transpose(this, axes);\n};\nNDArray.prototype.sort = function (axis) {\n if (axis === void 0) { axis = -1; }\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.elementwise.ops[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.elementwise.ops)), 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 assign operator \\\"\".concat(symbol, \"\\\". Options:\").concat(__spreadArray([], __read(Object.keys(NDArray_1.modules.operators.op_assign)), 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\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.kw_ops = exports.ops = exports.funcs = exports.elementwise = void 0;\nvar basic_1 = require(\"./basic\");\nvar kwargs_1 = require(\"./kwargs\");\n// Here, we declare only the core functions (those that are methods)\nfunction elementwise(A, func, dtype, out) {\n if (out === void 0) { out = null; }\n A = (0, basic_1.asarray)(A);\n if (out) {\n out.flat = A.flat.map(func);\n return out;\n }\n return (0, basic_1.new_NDArray)(A.flat.map(func), A.shape, dtype);\n}\nexports.elementwise = elementwise;\nfunction mk_elementwise(op, dtype) {\n return function (A, out) {\n if (out === void 0) { out = null; }\n return elementwise(A, op, dtype, out);\n };\n}\nexports.funcs = {\n sign: mk_elementwise(Math.sign, Number),\n sqrt: mk_elementwise(Math.sqrt, Number),\n square: mk_elementwise(function (a) { return a * a; }, Number),\n exp: mk_elementwise(Math.exp, Number),\n log: mk_elementwise(Math.log, Number),\n log2: mk_elementwise(Math.log2, Number),\n log10: mk_elementwise(Math.log10, Number),\n log1p: mk_elementwise(Math.log1p, Number),\n sin: mk_elementwise(Math.sin, Number),\n cos: mk_elementwise(Math.cos, Number),\n tan: mk_elementwise(Math.tan, Number),\n asin: mk_elementwise(Math.asin, Number),\n acos: mk_elementwise(Math.acos, Number),\n atan: mk_elementwise(Math.atan, Number),\n cosh: mk_elementwise(Math.cosh, Number),\n sinh: mk_elementwise(Math.sinh, Number),\n tanh: mk_elementwise(Math.tanh, Number),\n acosh: mk_elementwise(Math.acosh, Number),\n asinh: mk_elementwise(Math.asinh, Number),\n atanh: mk_elementwise(Math.atanh, Number),\n};\nvar _ops = {\n // Unary operators:\n round: function round(arr, decimals, out) {\n if (out === void 0) { out = null; }\n if (decimals == 0)\n elementwise(arr, Math.round, Number, out);\n return elementwise(arr, function (x) { return parseFloat(x.toFixed(decimals)); }, Number, out);\n },\n negative: mk_elementwise(function (x) { return -x; }, Number),\n bitwise_not: mk_elementwise(function (x) { return ~x; }, Number),\n logical_not: mk_elementwise(function (x) { return !x; }, Boolean),\n valueOf: mk_elementwise(function (x) { return +x; }, Number),\n abs: mk_elementwise(Math.abs, Number),\n};\nexports.ops = __assign(__assign({}, _ops), { \"~\": _ops.bitwise_not, \"not\": _ops.logical_not, \"+\": _ops.valueOf, \"-\": _ops.negative });\nvar _kw_ops = {\n bitwise_not: (0, kwargs_1.kwDecorators)({\n defaults: [[\"out\", null]],\n func: exports.ops.bitwise_not,\n }),\n logical_not: (0, kwargs_1.kwDecorators)({\n defaults: [[\"out\", null]],\n func: exports.ops.logical_not,\n }),\n negative: (0, kwargs_1.kwDecorators)({\n defaults: [[\"out\", null]],\n func: exports.ops.negative,\n }),\n abs: (0, kwargs_1.kwDecorators)({\n defaults: [[\"out\", null]],\n func: exports.ops.abs,\n }),\n round: (0, kwargs_1.kwDecorators)({\n defaults: [[\"decimals\", 0], [\"out\", null]],\n func: exports.ops.round,\n }),\n};\nexports.kw_ops = __assign({}, _kw_ops);\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 = false;\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};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KwParser = exports.kwDecorator = exports.kwDecorators = void 0;\nvar _globals_1 = require(\"./_globals\");\nfunction kwDecorators(_a) {\n var defaults = _a.defaults, func = _a.func;\n return new KwParser(defaults).decorators(func);\n}\nexports.kwDecorators = kwDecorators;\nfunction kwDecorator(_a) {\n var defaults = _a.defaults, func = _a.func;\n return new KwParser(defaults).as_function(func);\n}\nexports.kwDecorator = kwDecorator;\nvar KwParser = /** @class */ (function () {\n function KwParser(defaults) {\n this.defaults = defaults;\n }\n KwParser.prototype.parse = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var defaults = this.defaults;\n var kwargs = Object.assign(Object.fromEntries(defaults));\n for (var i = 0; i < args.length; i++) {\n var value = args[i];\n if (value instanceof Object && !(0, _globals_1.isarray)(value))\n Object.assign(kwargs, value);\n else if (value !== undefined)\n kwargs[defaults[i][0]] = value;\n }\n var sortedArgs = defaults.map(function (_, i) {\n var key = defaults[i][0];\n var value = kwargs[key];\n if (value === undefined) {\n throw new Error(\"Missing argument \".concat(key, \" in \").concat(args));\n }\n if (defaults[i].length === 3) {\n value = defaults[i][2](value);\n }\n return value;\n });\n return sortedArgs;\n };\n KwParser.prototype.as_arr_function = function (func) {\n var self = this;\n return function (arr) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n var parsed = self.parse.apply(self, __spreadArray([], __read(args), false));\n return func.apply(void 0, __spreadArray([(0, _globals_1.asarray)(arr)], __read(parsed), false));\n };\n };\n KwParser.prototype.as_arr_method = function (func) {\n var self = this;\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var parsed = self.parse.apply(self, __spreadArray([], __read(args), false));\n return func.apply(void 0, __spreadArray([this], __read(parsed), false));\n };\n };\n KwParser.prototype.decorators = function (func) {\n return { as_function: this.as_arr_function(func), as_method: this.as_arr_method(func) };\n };\n KwParser.prototype.as_function = function (func) {\n var self = this;\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var parsed = self.parse.apply(self, __spreadArray([], __read(args), false));\n return func.apply(void 0, __spreadArray([], __read(parsed), false));\n };\n };\n return KwParser;\n}());\nexports.KwParser = KwParser;\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.atan2 = exports.kw_op_binary = exports.allclose = exports.isclose = exports.op_assign = exports.__make_assignment_operator = exports._assign_operation_toJS = exports.assign_operation = 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 basic_1 = require(\"./basic\");\nvar js_interface_1 = require(\"./js-interface\");\nvar kwargs_1 = require(\"./kwargs\");\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 return binary_operation(A, B, func, dtype, out);\n }\n ;\n //@ts-ignore\n return operator;\n}\nexports.__make_operator = __make_operator;\nfunction __make_operator_special(funcNum, funcBool) {\n function operator(arr, other, out) {\n if (out === void 0) { out = null; }\n arr = (0, basic_1.asarray)(arr);\n other = (0, basic_1.asarray)(other);\n var dtype = arr.dtype, func;\n if (arr.dtype != other.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(arr, other, func, dtype, out);\n }\n ;\n //@ts-ignore\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\"];\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,\nfunction mk_kw_operator(op) {\n return (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: op,\n });\n}\nexports.kw_op_binary = {\n \"+\": mk_kw_operator(exports.op_binary[\"+\"]),\n \"-\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"-\"],\n }),\n \"*\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"*\"],\n }),\n \"/\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"/\"],\n }),\n \"%\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"%\"],\n }),\n \"//\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"//\"],\n }),\n \"**\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"**\"],\n }),\n \"<\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"<\"],\n }),\n \">\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\">\"],\n }),\n \">=\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\">=\"],\n }),\n \"<=\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"<=\"],\n }),\n \"==\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"==\"],\n }),\n \"!=\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"!=\"],\n }),\n \"|\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"|\"],\n }),\n \"&\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"&\"],\n }),\n \"^\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"^\"],\n }),\n \"<<\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"<<\"],\n }),\n \">>\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\">>\"],\n }),\n \"max\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"max\"],\n }),\n \"min\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"min\"],\n }),\n \"or\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"or\"],\n }),\n \"and\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"and\"],\n }),\n \"xor\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"xor\"],\n }),\n};\nexports.atan2 = (0, kwargs_1.kwDecorator)({\n defaults: [[\"y\", undefined, basic_1.asarray], [\"x\", undefined, basic_1.asarray], [\"out\", null]],\n func: __make_operator(Number, function (y, x) { return Math.atan2(y, x); }),\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.humanReadable = void 0;\nvar elementwise_1 = require(\"./elementwise\");\nvar js_interface_1 = require(\"./js-interface\");\nvar round = elementwise_1.ops.round;\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 = 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.kw_reducers = exports.reducers = void 0;\n//@ts-check\nvar basic_1 = require(\"./basic\");\nvar operators_1 = require(\"./operators\");\nvar kwargs_1 = require(\"./kwargs\");\nvar multiply = operators_1.op_binary[\"*\"];\nvar subtract = operators_1.op_binary[\"-\"];\nvar pow = operators_1.op_binary[\"**\"];\nfunction apply_on_axis(func, dtype, arr, axis, keepdims) {\n if (axis == null)\n return func(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 (_) { 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(func);\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 out.size == 1 ? out.flat[0] : out;\n}\n;\n// ==============================\n// Reducing functions\n// ==============================\nfunction mk_reducer(flat_reduce, dtype) {\n if (dtype === void 0) { dtype = Number; }\n return function (arr, axis, keepdims) {\n return apply_on_axis(flat_reduce, dtype, arr, axis, keepdims);\n };\n}\nexports.reducers = {\n sum: mk_reducer(function (arr) { return arr.reduce(function (a, b) { return a + b; }, 0); }),\n product: mk_reducer(function (arr) { return arr.reduce(function (a, b) { return a * b; }, 1); }),\n mean: mk_reducer(function (arr) { return arr.reduce(function (a, b) { return a + b; }, 0) / arr.length; }),\n max: mk_reducer(function (arr) { return Math.max.apply(Math, __spreadArray([], __read(arr), false)); }),\n min: mk_reducer(function (arr) { return Math.min.apply(Math, __spreadArray([], __read(arr), false)); }),\n argmax: mk_reducer(function (arr) { return arr.indexOf(Math.max.apply(Math, __spreadArray([], __read(arr), false))); }),\n argmin: mk_reducer(function (arr) { return arr.indexOf(Math.min.apply(Math, __spreadArray([], __read(arr), false))); }),\n len: mk_reducer(function (arr) { return arr.length; }),\n any: mk_reducer(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 }, Boolean),\n all: mk_reducer(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 }, Boolean),\n norm: function (arr, axis, keepdims, 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 return pow(exports.reducers.sum(pow(arr, ord), axis, keepdims), 1 / ord);\n },\n var: function (arr, axis, keepdims) {\n arr = subtract(arr, exports.reducers.mean(arr, axis, true));\n arr = multiply(arr, arr);\n return arr.mean({ axis: axis, keepdims: keepdims });\n },\n std: function (arr, axis, keepdims, ddof) {\n if (ddof == 0)\n return pow(arr.var(axis, keepdims), 0.5);\n var _sum = exports.reducers.sum(pow(arr, 2), axis, keepdims);\n var _len = exports.reducers.len(arr, axis, keepdims);\n return pow(operators_1.op_binary[\"/\"](_sum, operators_1.op_binary[\"-\"](_len, ddof)), 0.5);\n },\n};\nexports.kw_reducers = {\n sum: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.sum,\n }),\n product: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.product,\n }),\n mean: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.mean,\n }),\n max: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.max,\n }),\n min: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.min,\n }),\n argmax: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.argmax,\n }),\n argmin: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.argmin,\n }),\n len: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.len,\n }),\n any: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.any,\n }),\n all: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.all,\n }),\n norm: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false], [\"ord\", 2]],\n func: exports.reducers.norm,\n }),\n var: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.var,\n }),\n std: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false], [\"ddof\", 0]],\n func: exports.reducers.std,\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 var _a;\n if (axis === void 0) { axis = -1; }\n (axis = Object.assign({ axis: axis }, this).axis);\n //@ts-ignore\n if (axis instanceof Object)\n (_a = axis, axis = _a.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 var _a;\n if (axes === void 0) { axes = null; }\n (axes = Object.assign({ axes: axes }, this).axes);\n //@ts-ignore\n if (axes !== null && axes[\"axes\"])\n (_a = axes, axes = _a.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 _a, e_1, _b;\n if (axis === void 0) { axis = null; }\n // ({ axis } = Object.assign({ axis }, this));\n //@ts-ignore\n if (axis instanceof Object)\n (_a = axis, axis = _a.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 && (_b = arrays_1.return)) _b.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 _a, e_2, _b;\n if (axis === void 0) { axis = 0; }\n // ({ axis } = Object.assign({ axis }, this));\n //@ts-ignore\n if (axis instanceof Object)\n (_a = axis, axis = _a.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 && (_b = arrays_2.return)) _b.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.kw_reducers.sum.as_function;\nnp.product = reduce.kw_reducers.product.as_function;\nnp.prod = np.product;\nnp.any = reduce.kw_reducers.any.as_function;\nnp.all = reduce.kw_reducers.all.as_function;\nnp.max = reduce.kw_reducers.max.as_function;\nnp.min = reduce.kw_reducers.min.as_function;\nnp.argmax = reduce.kw_reducers.argmax.as_function;\nnp.argmin = reduce.kw_reducers.argmin.as_function;\nnp.mean = reduce.kw_reducers.mean.as_function;\nnp.norm = reduce.kw_reducers.norm.as_function;\nnp.var = reduce.kw_reducers.var.as_function;\nnp.std = reduce.kw_reducers.std.as_function;\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.kw_op_binary[\"+\"].as_function;\nnp.subtract = operators.kw_op_binary[\"-\"].as_function;\nnp.multiply = operators.kw_op_binary[\"*\"].as_function;\nnp.divide = operators.kw_op_binary[\"/\"].as_function;\nnp.mod = operators.kw_op_binary[\"%\"].as_function;\nnp.divide_int = operators.kw_op_binary[\"//\"].as_function;\nnp.pow = operators.kw_op_binary[\"**\"].as_function;\nnp.bitwise_or = operators.kw_op_binary[\"|\"].as_function;\nnp.bitwise_and = operators.kw_op_binary[\"&\"].as_function;\nnp.bitwise_xor = operators.kw_op_binary[\"^\"].as_function;\nnp.bitwise_shift_left = operators.kw_op_binary[\"<<\"].as_function;\nnp.bitwise_shift_right = operators.kw_op_binary[\">>\"].as_function;\nnp.greater = operators.kw_op_binary[\">\"].as_function;\nnp.less = operators.kw_op_binary[\"<\"].as_function;\nnp.greater_equal = operators.kw_op_binary[\">=\"].as_function;\nnp.less_equal = operators.kw_op_binary[\"<=\"].as_function;\nnp.equal = operators.kw_op_binary[\"==\"].as_function;\nnp.not_equal = operators.kw_op_binary[\"!=\"].as_function;\nnp.maximum = operators.kw_op_binary[\"max\"].as_function;\nnp.minimum = operators.kw_op_binary[\"min\"].as_function;\nnp.logical_or = operators.kw_op_binary[\"or\"].as_function;\nnp.logical_and = operators.kw_op_binary[\"and\"].as_function;\nnp.atan2 = operators.atan2;\nnp.allclose = operators.allclose;\nnp.isclose = operators.isclose;\nvar ew = NDArray_class_1.default.prototype.modules.elementwise;\nnp.sign = ew.funcs.sign;\nnp.sqrt = ew.funcs.sqrt;\nnp.square = ew.funcs.square;\nnp.exp = ew.funcs.exp;\nnp.log = ew.funcs.log;\nnp.log2 = ew.funcs.log2;\nnp.log10 = ew.funcs.log10;\nnp.log1p = ew.funcs.log1p;\nnp.sin = ew.funcs.sin;\nnp.cos = ew.funcs.cos;\nnp.tan = ew.funcs.tan;\nnp.asin = ew.funcs.asin;\nnp.acos = ew.funcs.acos;\nnp.atan = ew.funcs.atan;\nnp.cosh = ew.funcs.cosh;\nnp.sinh = ew.funcs.sinh;\nnp.tanh = ew.funcs.tanh;\nnp.acosh = ew.funcs.acosh;\nnp.asinh = ew.funcs.asinh;\nnp.atanh = ew.funcs.atanh;\nnp.abs = ew.kw_ops.abs.as_function;\nnp.bitwise_not = ew.kw_ops.bitwise_not.as_function;\nnp.logical_not = ew.kw_ops.logical_not.as_function;\nnp.abs = ew.kw_ops.abs.as_function;\nnp.negative = ew.kw_ops.negative.as_function;\nnp.round = ew.kw_ops.round.as_function;\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;\nnp.pi = Math.PI;\nnp.e = Math.E;\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.funcs.log(start);\n stop = elementwise.funcs.log(stop);\n return elementwise.funcs.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 Object.keys(kwArgs).length == 0 ? func.apply(void 0, __spreadArray([], __read(args), false)) : func.apply(void 0, __spreadArray(__spreadArray([], __read(args), false), [kwArgs], false));\n // return func.bind(kwArgs)(...args); // Old version\n },\n Arr_method: function ($arr, _dot, $name, $callArgs) {\n var arr = $arr.parse();\n var name = $name.sourceString;\n var _a = $callArgs.parse(), args = _a.args, kwArgs = _a.kwArgs;\n if (arr[name] === undefined)\n throw new Error(\"Unrecognized method \".concat(name));\n // return arr.withKwArgs(kwArgs)[name](...args); // Old version\n return Object.keys(kwArgs).length == 0 ? arr[name].apply(arr, __spreadArray([], __read(args), false)) : arr[name].apply(arr, __spreadArray(__spreadArray([], __read(args), false), [kwArgs], 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 ops = _globals_1.nd_modules.elementwise.ops;\n switch (symbol) {\n case \"+\": return ops[\"+\"](B);\n case \"-\": return ops[\"-\"](B);\n case \"~\": return ops[\"~\"](B);\n case \"!\": return ops[\"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/dist/index.d.ts b/dist/index.d.ts new file mode 100644 index 0000000..a77ccb5 --- /dev/null +++ b/dist/index.d.ts @@ -0,0 +1,95 @@ +declare const np: { + (template: TemplateStringsArray | any[] | number | boolean, ...variables: any[]): any; + NDArray: typeof NDArray; + tolist(template: TemplateStringsArray | any[] | number | boolean, ...variables: any[]): any; + fromlist: typeof import("./NDArray/js-interface").fromlist; + ravel: typeof import("./NDArray/basic").ravel; + reshape: typeof import("./NDArray/basic").reshape; + array: typeof import("./NDArray/_globals").array; + asarray: typeof import("./NDArray/_globals").asarray; + sum: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | NDArray; + product: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | NDArray; + prod: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | NDArray; + any: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => boolean | NDArray; + all: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => boolean | NDArray; + max: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | NDArray; + min: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | NDArray; + argmax: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | NDArray; + argmin: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | NDArray; + mean: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | NDArray; + norm: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceNormKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceNormKwargs, ord?: number | import("./NDArray/kwargs").ReduceNormKwargs) => number | NDArray; + var: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceKwargs) => number | NDArray; + std: (arr: number | boolean | NDArray, axis?: number | import("./NDArray/kwargs").ReduceStdKwargs, keepdims?: boolean | import("./NDArray/kwargs").ReduceStdKwargs, ddof?: number | import("./NDArray/kwargs").ReduceStdKwargs) => number | NDArray; + transpose: typeof import("./NDArray/transform").transpose; + apply_along_axis: typeof import("./NDArray/transform").apply_along_axis; + sort: typeof import("./NDArray/transform").sort; + concatenate: typeof import("./NDArray/transform").concatenate; + stack: typeof import("./NDArray/transform").stack; + add: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + subtract: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + multiply: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + divide: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + mod: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + divide_int: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + pow: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + bitwise_or: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + bitwise_and: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + bitwise_xor: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + bitwise_shift_left: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + bitwise_shift_right: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + greater: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + less: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + greater_equal: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + less_equal: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + equal: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + not_equal: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + maximum: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + minimum: (arr: number | boolean | NDArray, other: number | NDArray, out?: NDArray) => NDArray; + logical_or: (arr: number | boolean | NDArray, other: boolean | NDArray, out?: NDArray) => NDArray; + logical_and: (arr: number | boolean | NDArray, other: boolean | NDArray, out?: NDArray) => NDArray; + atan2: (y: NDArray, x: NDArray, out?: NDArray) => NDArray; + allclose: typeof import("./NDArray/operators").allclose; + isclose: typeof import("./NDArray/operators").isclose; + sign: (A: NDArray, out?: NDArray) => NDArray; + sqrt: (A: NDArray, out?: NDArray) => NDArray; + square: (A: NDArray, out?: NDArray) => NDArray; + exp: (A: NDArray, out?: NDArray) => NDArray; + log: (A: NDArray, out?: NDArray) => NDArray; + log2: (A: NDArray, out?: NDArray) => NDArray; + log10: (A: NDArray, out?: NDArray) => NDArray; + log1p: (A: NDArray, out?: NDArray) => NDArray; + sin: (A: NDArray, out?: NDArray) => NDArray; + cos: (A: NDArray, out?: NDArray) => NDArray; + tan: (A: NDArray, out?: NDArray) => NDArray; + asin: (A: NDArray, out?: NDArray) => NDArray; + acos: (A: NDArray, out?: NDArray) => NDArray; + atan: (A: NDArray, out?: NDArray) => NDArray; + cosh: (A: NDArray, out?: NDArray) => NDArray; + sinh: (A: NDArray, out?: NDArray) => NDArray; + tanh: (A: NDArray, out?: NDArray) => NDArray; + acosh: (A: NDArray, out?: NDArray) => NDArray; + asinh: (A: NDArray, out?: NDArray) => NDArray; + atanh: (A: NDArray, out?: NDArray) => NDArray; + abs: (arr: number | boolean | NDArray, out?: NDArray) => NDArray; + bitwise_not: (arr: number | boolean | NDArray, out?: NDArray) => NDArray; + logical_not: (arr: number | boolean | NDArray, out?: NDArray) => NDArray; + negative: (arr: number | boolean | NDArray, out?: NDArray) => NDArray; + round: (arr: number | boolean | NDArray, decimals?: number) => NDArray; + modules: { + constructors: typeof import("./modules/constructors"); + grammar: typeof import("./modules/grammar"); + random: typeof import("./modules/random"); + }; + empty: typeof import("./modules/constructors").empty; + zeros: typeof import("./modules/constructors").zeros; + ones: typeof import("./modules/constructors").ones; + arange: typeof import("./modules/constructors").arange; + linspace: typeof import("./modules/constructors").linspace; + geomspace: typeof import("./modules/constructors").geomspace; + random: typeof import("./modules/random"); + pi: number; + e: number; +}; +import NDArray from './NDArray-class'; +export { np }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/index.d.ts.map b/dist/index.d.ts.map new file mode 100644 index 0000000..85ea00f --- /dev/null +++ b/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,QAAA,MAAM,EAAE;eAAuB,oBAAoB,GAAG,GAAG,EAAE,GAAG,MAAM,GAAG,OAAO,gBAAgB,GAAG,EAAE;;qBAoC5E,oBAAoB,GAAG,GAAG,EAAE,GAAG,MAAM,GAAG,OAAO,gBAAgB,GAAG,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CApB1F,CAAA;AAYD,OAAO,OAAO,MAAM,iBAAiB,CAAC;AA6HtC,OAAO,EAAE,EAAE,EAAE,CAAC"} \ No newline at end of file diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..7eef027 --- /dev/null +++ b/dist/index.js @@ -0,0 +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={425: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]>"].as_method,s.prototype.logical_or=u.modules.operators.kw_op_binary.or.as_method,s.prototype.logical_and=u.modules.operators.kw_op_binary.and.as_method,s.prototype.logical_xor=u.modules.operators.kw_op_binary.xor.as_method,s.prototype.greater=u.modules.operators.kw_op_binary[">"].as_method,s.prototype.less=u.modules.operators.kw_op_binary["<"].as_method,s.prototype.greater_equal=u.modules.operators.kw_op_binary[">="].as_method,s.prototype.less_equal=u.modules.operators.kw_op_binary["<="].as_method,s.prototype.equal=u.modules.operators.kw_op_binary["=="].as_method,s.prototype.not_equal=u.modules.operators.kw_op_binary["!="].as_method,s.prototype.bitwise_not=u.modules.elementwise.kw_ops.bitwise_not.as_method,s.prototype.logical_not=u.modules.elementwise.kw_ops.logical_not.as_method,s.prototype.negative=u.modules.elementwise.kw_ops.negative.as_method,s.prototype.abs=u.modules.elementwise.kw_ops.abs.as_method,s.prototype.isclose=u.modules.operators.isclose,s.prototype.allclose=u.modules.operators.allclose,s.prototype.assign=c(u.modules.operators.op_assign["="]),s.prototype.add_assign=c(u.modules.operators.op_assign["+="]),s.prototype.subtract_assign=c(u.modules.operators.op_assign["-="]),s.prototype.multiply_assign=c(u.modules.operators.op_assign["*="]),s.prototype.divide_assign=c(u.modules.operators.op_assign["/="]),s.prototype.mod_assign=c(u.modules.operators.op_assign["%="]),s.prototype.divide_int_assign=c(u.modules.operators.op_assign["//="]),s.prototype.pow_assign=c(u.modules.operators.op_assign["**="]),s.prototype.maximum_assign=c(u.modules.operators.op_assign["↑="]),s.prototype.minimum_assign=c(u.modules.operators.op_assign["↓="]),s.prototype.bitwise_or_assign=c(u.modules.operators.op_assign["|="]),s.prototype.bitwise_and_assign=c(u.modules.operators.op_assign["&="]),s.prototype.bitwise_shift_left_assign=c(u.modules.operators.op_assign["<<="]),s.prototype.bitwise_shift_right_assign=c(u.modules.operators.op_assign[">>="]),s.prototype.logical_or_assign=c(u.modules.operators.op_assign["or="]),s.prototype.logical_and_assign=c(u.modules.operators.op_assign["and="]),s.prototype.tolist=function(){return u.modules.jsInterface.tolist(this)},s.prototype.round=u.modules.elementwise.kw_ops.round.as_method,s.prototype.transpose=function(e){return u.modules.transform.transpose(this,e=void 0===e?null:e)},s.prototype.sort=function(e){return u.modules.transform.sort(this,e=void 0===e?-1:e),null};s.prototype.op=function(){for(var e=[],t=0;t{Object.defineProperty(t,"__esModule",{value:!0}),t.modules=void 0,r(171);var n=r(147),i=r(82),a=r(160),o=r(584),s=r(339),u=r(587),l=r(185),r=r(394);t.modules={basic:n,jsInterface:a,indexes:i,elementwise:o,print:s,reduce:u,operators:l,transform:r}},82: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,f=(u-=m,1),d=0;d=e.length)throw new Error("Index spans over more dimensions than available in shape [".concat(e,"]: index(").concat(t,")"));f*=e[o],o+=i}n.axisIndexes.push(h),"number"!=h.spec.type&&n.apparentShape.push(h.size),n.internalShape.push(f)}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)}},160:function(e,t,r){var d=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.atan2=t.kw_op_binary=t.allclose=t.isclose=t.op_assign=t.__make_assignment_operator=t._assign_operation_toJS=t.assign_operation=t.op_binary=t.__make_operator_special=t.__make_operator=t._broadcast_shapes=t.binary_operation=void 0,r(82)),w=r(147),o=r(160),r=r(270);function m(e,t,r,n,i){if(void 0===i&&(i=null),(0,w.isarray)(this))return r.bind(w._NDArray.prototype).apply(void 0,b([this],_(arguments),!1));e=(0,w.asarray)(e),t=(0,w.asarray)(t);var a=_(x(e.shape,t.shape),3),o=a[0],s=a[1],u=a[2];if(null==i)i=(0,w.new_from)(o,function(e){},n);else if(!(0,w.isarray)(i))throw new Error("Out must be of type ".concat(w._NDArray,". Got ").concat(typeof i));for(var l=[],c=(0,w.shape_shifts)(s),p=(0,w.shape_shifts)(u),h=e.flat,m=t.flat,f=0;f>="|"//="|"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 0==Object.keys(e).length?t.apply(void 0,u([],s(n),!1)):t.apply(void 0,u(u([],s(n),!1),[e],!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 0==Object.keys(n).length?e[r].apply(e,u([],s(i),!1)):e[r].apply(e,u(u([],s(i),!1),[n],!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.elementwise.ops;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(392);var n=r(907),i=r(581),r=r(120);t.modules={constructors:n,grammar:i,random:r}},120: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 C(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:C,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:f,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 x(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 f,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 de="⋅",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,de).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 f;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=x.prototype.allowsSkippingPrecedingSpace=c.prototype.allowsSkippingPrecedingSpace=a.prototype.allowsSkippingPrecedingSpace=I.prototype.allowsSkippingPrecedingSpace=function(){return!0},s.prototype.allowsSkippingPrecedingSpace=d.prototype.allowsSkippingPrecedingSpace=w.prototype.allowsSkippingPrecedingSpace=b.prototype.allowsSkippingPrecedingSpace=_.prototype.allowsSkippingPrecedingSpace=o.prototype.allowsSkippingPrecedingSpace=h.prototype.allowsSkippingPrecedingSpace=function(){return!1};let O;ue(e=>{O=e});let we;n.prototype.assertAllApplicationsAreValid=function(e,t){we=0,this._assertAllApplicationsAreValid(e,t)},n.prototype._assertAllApplicationsAreValid=t("_assertAllApplicationsAreValid"),r._assertAllApplicationsAreValid=i._assertAllApplicationsAreValid=c.prototype._assertAllApplicationsAreValid=a.prototype._assertAllApplicationsAreValid=o.prototype._assertAllApplicationsAreValid=I.prototype._assertAllApplicationsAreValid=function(e,t){},w.prototype._assertAllApplicationsAreValid=function(e,t){we++,this.expr._assertAllApplicationsAreValid(e,t),we--},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=w.prototype.assertChoicesHaveUniformArity=I.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 xe{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])},w.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",k(this,r),e.map(e=>e.outputRecipe(t,r)),n.map(e=>e.outputRecipe(t,r))]},h.prototype.outputRecipe=function(t,r){return["seq",k(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=w.prototype.outputRecipe=function(e,t){return[this.constructor.name.toLowerCase(),k(this,t),this.expr.outputRecipe(e,t)]},x.prototype.outputRecipe=function(t,r){return["app",k(this,r),this.ruleName,this.args.map(e=>e.outputRecipe(t,r))]},I.prototype.outputRecipe=function(e,t){return["unicodeChar",k(this,t),this.category]},n.prototype.introduceParams=t("introduceParams"),r.introduceParams=i.introduceParams=c.prototype.introduceParams=a.prototype.introduceParams=o.prototype.introduceParams=I.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},d.prototype.introduceParams=_.prototype.introduceParams=b.prototype.introduceParams=w.prototype.introduceParams=function(e){return this.expr=this.expr.introduceParams(e),this},x.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=I.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},w.prototype._isNullable=function(e,t){return this.expr._isNullable(e,t)},x.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=I.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)))},d.prototype.substituteParams=_.prototype.substituteParams=b.prototype.substituteParams=w.prototype.substituteParams=function(e){return new this.constructor(this.expr.substituteParams(e))},x.prototype.substituteParams=function(t){var e;return 0===this.args.length?this:(e=this.args.map(e=>e.substituteParams(t)),new x(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},d.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=w.prototype.toArgumentNameList=function(e,t){return this.expr.toArgumentNameList(e,t)},x.prototype.toArgumentNameList=function(e,t){return[this.ruleName]},I.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=d.prototype.toDisplayString=_.prototype.toDisplayString=b.prototype.toDisplayString=w.prototype.toDisplayString=c.prototype.toDisplayString=a.prototype.toDisplayString=o.prototype.toDisplayString=function(){return this.toString()},x.prototype.toDisplayString=function(){var e;return 0e.toDisplayString()),this.ruleName+"<"+e.join(",")+">"):this.ruleName},I.prototype.toDisplayString=function(){return"Unicode ["+this.category+"] character"};class E{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 E(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 E(this,"any object","description")},i.toFailure=function(e){return new E(this,"end of input","description")},c.prototype.toFailure=function(e){return new E(this,this.obj,"string")},a.prototype.toFailure=function(e){return new E(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 E(this,e,"description")},b.prototype.toFailure=function(e){return this.expr.toFailure(e)},x.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 E(this,t,"description")},I.prototype.toFailure=function(e){return new E(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 E(this,e,"description")},h.prototype.toFailure=function(t){var e="("+this.factors.map(e=>e.toFailure(t)).join(" ")+")";return new E(this,e,"description")},d.prototype.toFailure=function(e){e="("+this.expr.toFailure(e)+this.operator+")";return new E(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},w.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(" ")+")"},d.prototype.toString=function(){return this.expr+this.operator},_.prototype.toString=function(){return"~"+this.expr},b.prototype.toString=function(){return"&"+this.expr},x.prototype.toString=function(){var e;return 0e.toString()),this.ruleName+"<"+e.join(",")+">"):this.ruleName},I.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 E(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:d,Star:y,Plus:g,Opt:v,Not:_,Lookahead:b,Lex:w,Apply:x,UnicodeChar:I});let ke;ue(e=>{ke=e.rules.applySyntactic.body});const Ee=new x("spaces");class Le{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(Ee),this.popBinding(),this.popFailuresInfo(),this.inputStream.pos}skipSpacesIfInSyntacticContext(){return this.inSyntacticContext()?this.skipSpaces():this.inputStream.pos}maybeSkipSpacesBefore(e){return e.allowsSkippingPrecedingSpace()&&e!==Ee?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 fe)}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 x){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 x&&(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===Ee,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===ke&&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 Re{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 De{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 R{constructor(e,t){const n=this;if(this.grammar=e,this.checkedActionDicts=!1,this.Wrapper=class extends(t?t.Wrapper:De){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!==R.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,L);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 je(u,e,l,r):new Ce(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(Fe(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 je(t,i,o):new Ce(t,o),this[n][t].checkActionDict(this.grammar)}assertNewName(e,t){if(Fe(De.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(!R.prototypeGrammar)return m(-1===e.indexOf("(")),{name:e,formals:[]};e=R.prototypeGrammar.match(e,"operation"===t?"OperationSignature":"AttributeSignature");if(e.failed())throw new Error(e.message);return R.prototypeGrammarSemantics(e).parse()}R.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 R(n,void 0!==e?e:R.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 je{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?(L.push([this,r]),e.apply(t,t._children())):(t.isNonterminal()&&(e=this.actionDict._nonterminal)?(L.push([this,"_nonterminal",r]),e):(L.push([this,"default action",r]),this.actionDict._default)).apply(t,t._children())}finally{L.pop()}}}je.prototype.typeName="operation";class Ce extends je{constructor(e,t,r){super(e,[],t,r)}execute(e,t){var r=t._node,n=e.attributeKeys[this.name];return Fe(r,n)||(r[n]=je.prototype.execute.call(this,e,t)),r[n]}}Ce.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 F{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 Re(this)}isBuiltIn(){return this===F.ProtoBuiltInRules||this===F.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 R.createSemantics(this)}extendSemantics(e){return R.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 f;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 x(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)}}F.ProtoBuiltInRules=new F("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 I("Ll"),formals:[],description:"a lowercase letter",primitive:!0},upper:{body:new I("Lu"),formals:[],description:"an uppercase letter",primitive:!0},unicodeLtmo:{body:new I("Ltmo"),formals:[],description:"a Unicode character in Lt, Lm, or Lo",primitive:!0},spaces:{body:new y(new x("space")),formals:[]},space:{body:new a("\0"," "),formals:[],description:"a space"}}),F.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?F.ProtoBuiltInRules:F.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 w(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=(F.BuiltInRules=$e,Ve=F.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()===F.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",[]]]]}]);M=F.BuiltInRules,D={empty(){return this.iteration()},nonEmpty(e,t,r){return this.iteration([e].concat(r.children))}},R.BuiltInSemantics=R.createSemantics(M,null).addOperation("asIteration",{emptyListOf:D.empty,nonemptyListOf:D.nonEmpty,EmptyListOf:D.empty,NonemptyListOf:D.nonEmpty}),M=Ze,R.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}}),R.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 E(this,t,"description")}}var D=new x("indent"),Ze=new x("dedent"),M=new p($e,"any",[D,Ze],[]),D=(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",[],M,"any character",void 0).build();Object.assign(D,{_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=D,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 // __popKwArgs() {\n // let out = this['__kwArgs'];\n // if (out === undefined) return {};\n // delete this['__kwArgs'];\n // return out;\n // }\n // /** @param {Object} kwArgs */\n // withKwArgs(kwArgs: { [s: string]: any; }) {\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// ==============================\nNDArray.prototype.any = NDArray_1.modules.reduce.kw_reducers.any.as_method;\nNDArray.prototype.all = NDArray_1.modules.reduce.kw_reducers.all.as_method;\nNDArray.prototype.sum = NDArray_1.modules.reduce.kw_reducers.sum.as_method;\nNDArray.prototype.product = NDArray_1.modules.reduce.kw_reducers.product.as_method;\nNDArray.prototype.max = NDArray_1.modules.reduce.kw_reducers.max.as_method;\nNDArray.prototype.min = NDArray_1.modules.reduce.kw_reducers.min.as_method;\nNDArray.prototype.argmax = NDArray_1.modules.reduce.kw_reducers.argmax.as_method;\nNDArray.prototype.argmin = NDArray_1.modules.reduce.kw_reducers.argmin.as_method;\nNDArray.prototype.mean = NDArray_1.modules.reduce.kw_reducers.mean.as_method;\nNDArray.prototype.var = NDArray_1.modules.reduce.kw_reducers.var.as_method;\nNDArray.prototype.std = NDArray_1.modules.reduce.kw_reducers.std.as_method;\nNDArray.prototype.norm = NDArray_1.modules.reduce.kw_reducers.norm.as_method;\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 return func(this, other, out);\n };\n}\nNDArray.prototype.add = NDArray_1.modules.operators.kw_op_binary[\"+\"].as_method;\nNDArray.prototype.subtract = NDArray_1.modules.operators.kw_op_binary[\"-\"].as_method;\nNDArray.prototype.multiply = NDArray_1.modules.operators.kw_op_binary[\"*\"].as_method;\nNDArray.prototype.divide = NDArray_1.modules.operators.kw_op_binary[\"/\"].as_method;\nNDArray.prototype.mod = NDArray_1.modules.operators.kw_op_binary[\"%\"].as_method;\nNDArray.prototype.divide_int = NDArray_1.modules.operators.kw_op_binary[\"//\"].as_method;\nNDArray.prototype.pow = NDArray_1.modules.operators.kw_op_binary[\"**\"].as_method;\nNDArray.prototype.maximum = NDArray_1.modules.operators.kw_op_binary[\"max\"].as_method;\nNDArray.prototype.minimum = NDArray_1.modules.operators.kw_op_binary[\"min\"].as_method;\nNDArray.prototype.bitwise_or = NDArray_1.modules.operators.kw_op_binary[\"|\"].as_method;\nNDArray.prototype.bitwise_and = NDArray_1.modules.operators.kw_op_binary[\"&\"].as_method;\nNDArray.prototype.bitwise_or = NDArray_1.modules.operators.kw_op_binary[\"^\"].as_method;\nNDArray.prototype.bitwise_shift_right = NDArray_1.modules.operators.kw_op_binary[\"<<\"].as_method;\nNDArray.prototype.bitwise_shift_right = NDArray_1.modules.operators.kw_op_binary[\">>\"].as_method;\nNDArray.prototype.logical_or = NDArray_1.modules.operators.kw_op_binary[\"or\"].as_method;\nNDArray.prototype.logical_and = NDArray_1.modules.operators.kw_op_binary[\"and\"].as_method;\nNDArray.prototype.logical_xor = NDArray_1.modules.operators.kw_op_binary[\"xor\"].as_method;\nNDArray.prototype.greater = NDArray_1.modules.operators.kw_op_binary[\">\"].as_method;\nNDArray.prototype.less = NDArray_1.modules.operators.kw_op_binary[\"<\"].as_method;\nNDArray.prototype.greater_equal = NDArray_1.modules.operators.kw_op_binary[\">=\"].as_method;\nNDArray.prototype.less_equal = NDArray_1.modules.operators.kw_op_binary[\"<=\"].as_method;\nNDArray.prototype.equal = NDArray_1.modules.operators.kw_op_binary[\"==\"].as_method;\nNDArray.prototype.not_equal = NDArray_1.modules.operators.kw_op_binary[\"!=\"].as_method;\n// Unary operations: only boolean_not. Positive is useless and negative is almost useless\nNDArray.prototype.bitwise_not = NDArray_1.modules.elementwise.kw_ops.bitwise_not.as_method;\nNDArray.prototype.logical_not = NDArray_1.modules.elementwise.kw_ops.logical_not.as_method;\nNDArray.prototype.negative = NDArray_1.modules.elementwise.kw_ops.negative.as_method;\nNDArray.prototype.abs = NDArray_1.modules.elementwise.kw_ops.abs.as_method;\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 = NDArray_1.modules.elementwise.kw_ops.round.as_method;\n// ==============================\n// transform methods\n// ==============================\n/** @param {null|number[]} axes */\nNDArray.prototype.transpose = function (axes) {\n if (axes === void 0) { axes = null; }\n return NDArray_1.modules.transform.transpose(this, axes);\n};\nNDArray.prototype.sort = function (axis) {\n if (axis === void 0) { axis = -1; }\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.elementwise.ops[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.elementwise.ops)), 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 assign operator \\\"\".concat(symbol, \"\\\". Options:\").concat(__spreadArray([], __read(Object.keys(NDArray_1.modules.operators.op_assign)), 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\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.kw_ops = exports.ops = exports.funcs = exports.elementwise = void 0;\nvar basic_1 = require(\"./basic\");\nvar kwargs_1 = require(\"./kwargs\");\n// Here, we declare only the core functions (those that are methods)\nfunction elementwise(A, func, dtype, out) {\n if (out === void 0) { out = null; }\n A = (0, basic_1.asarray)(A);\n if (out) {\n out.flat = A.flat.map(func);\n return out;\n }\n return (0, basic_1.new_NDArray)(A.flat.map(func), A.shape, dtype);\n}\nexports.elementwise = elementwise;\nfunction mk_elementwise(op, dtype) {\n return function (A, out) {\n if (out === void 0) { out = null; }\n return elementwise(A, op, dtype, out);\n };\n}\nexports.funcs = {\n sign: mk_elementwise(Math.sign, Number),\n sqrt: mk_elementwise(Math.sqrt, Number),\n square: mk_elementwise(function (a) { return a * a; }, Number),\n exp: mk_elementwise(Math.exp, Number),\n log: mk_elementwise(Math.log, Number),\n log2: mk_elementwise(Math.log2, Number),\n log10: mk_elementwise(Math.log10, Number),\n log1p: mk_elementwise(Math.log1p, Number),\n sin: mk_elementwise(Math.sin, Number),\n cos: mk_elementwise(Math.cos, Number),\n tan: mk_elementwise(Math.tan, Number),\n asin: mk_elementwise(Math.asin, Number),\n acos: mk_elementwise(Math.acos, Number),\n atan: mk_elementwise(Math.atan, Number),\n cosh: mk_elementwise(Math.cosh, Number),\n sinh: mk_elementwise(Math.sinh, Number),\n tanh: mk_elementwise(Math.tanh, Number),\n acosh: mk_elementwise(Math.acosh, Number),\n asinh: mk_elementwise(Math.asinh, Number),\n atanh: mk_elementwise(Math.atanh, Number),\n};\nvar _ops = {\n // Unary operators:\n round: function round(arr, decimals, out) {\n if (out === void 0) { out = null; }\n if (decimals == 0)\n elementwise(arr, Math.round, Number, out);\n return elementwise(arr, function (x) { return parseFloat(x.toFixed(decimals)); }, Number, out);\n },\n negative: mk_elementwise(function (x) { return -x; }, Number),\n bitwise_not: mk_elementwise(function (x) { return ~x; }, Number),\n logical_not: mk_elementwise(function (x) { return !x; }, Boolean),\n valueOf: mk_elementwise(function (x) { return +x; }, Number),\n abs: mk_elementwise(Math.abs, Number),\n};\nexports.ops = __assign(__assign({}, _ops), { \"~\": _ops.bitwise_not, \"not\": _ops.logical_not, \"+\": _ops.valueOf, \"-\": _ops.negative });\nvar _kw_ops = {\n bitwise_not: (0, kwargs_1.kwDecorators)({\n defaults: [[\"out\", null]],\n func: exports.ops.bitwise_not,\n }),\n logical_not: (0, kwargs_1.kwDecorators)({\n defaults: [[\"out\", null]],\n func: exports.ops.logical_not,\n }),\n negative: (0, kwargs_1.kwDecorators)({\n defaults: [[\"out\", null]],\n func: exports.ops.negative,\n }),\n abs: (0, kwargs_1.kwDecorators)({\n defaults: [[\"out\", null]],\n func: exports.ops.abs,\n }),\n round: (0, kwargs_1.kwDecorators)({\n defaults: [[\"decimals\", 0], [\"out\", null]],\n func: exports.ops.round,\n }),\n};\nexports.kw_ops = __assign({}, _kw_ops);\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 = false;\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};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.KwParser = exports.kwDecorator = exports.kwDecorators = void 0;\nvar _globals_1 = require(\"./_globals\");\nfunction kwDecorators(_a) {\n var defaults = _a.defaults, func = _a.func;\n return new KwParser(defaults).decorators(func);\n}\nexports.kwDecorators = kwDecorators;\nfunction kwDecorator(_a) {\n var defaults = _a.defaults, func = _a.func;\n return new KwParser(defaults).as_function(func);\n}\nexports.kwDecorator = kwDecorator;\nvar KwParser = /** @class */ (function () {\n function KwParser(defaults) {\n this.defaults = defaults;\n }\n KwParser.prototype.parse = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var defaults = this.defaults;\n var kwargs = Object.assign(Object.fromEntries(defaults));\n for (var i = 0; i < args.length; i++) {\n var value = args[i];\n if (value instanceof Object && !(0, _globals_1.isarray)(value))\n Object.assign(kwargs, value);\n else if (value !== undefined)\n kwargs[defaults[i][0]] = value;\n }\n var sortedArgs = defaults.map(function (_, i) {\n var key = defaults[i][0];\n var value = kwargs[key];\n if (value === undefined) {\n throw new Error(\"Missing argument \".concat(key, \" in \").concat(args));\n }\n if (defaults[i].length === 3) {\n value = defaults[i][2](value);\n }\n return value;\n });\n return sortedArgs;\n };\n KwParser.prototype.as_arr_function = function (func) {\n var self = this;\n return function (arr) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n var parsed = self.parse.apply(self, __spreadArray([], __read(args), false));\n return func.apply(void 0, __spreadArray([(0, _globals_1.asarray)(arr)], __read(parsed), false));\n };\n };\n KwParser.prototype.as_arr_method = function (func) {\n var self = this;\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var parsed = self.parse.apply(self, __spreadArray([], __read(args), false));\n return func.apply(void 0, __spreadArray([this], __read(parsed), false));\n };\n };\n KwParser.prototype.decorators = function (func) {\n return { as_function: this.as_arr_function(func), as_method: this.as_arr_method(func) };\n };\n KwParser.prototype.as_function = function (func) {\n var self = this;\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var parsed = self.parse.apply(self, __spreadArray([], __read(args), false));\n return func.apply(void 0, __spreadArray([], __read(parsed), false));\n };\n };\n return KwParser;\n}());\nexports.KwParser = KwParser;\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.atan2 = exports.kw_op_binary = exports.allclose = exports.isclose = exports.op_assign = exports.__make_assignment_operator = exports._assign_operation_toJS = exports.assign_operation = 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 basic_1 = require(\"./basic\");\nvar js_interface_1 = require(\"./js-interface\");\nvar kwargs_1 = require(\"./kwargs\");\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 return binary_operation(A, B, func, dtype, out);\n }\n ;\n //@ts-ignore\n return operator;\n}\nexports.__make_operator = __make_operator;\nfunction __make_operator_special(funcNum, funcBool) {\n function operator(arr, other, out) {\n if (out === void 0) { out = null; }\n arr = (0, basic_1.asarray)(arr);\n other = (0, basic_1.asarray)(other);\n var dtype = arr.dtype, func;\n if (arr.dtype != other.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(arr, other, func, dtype, out);\n }\n ;\n //@ts-ignore\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\"];\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,\nfunction mk_kw_operator(op) {\n return (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: op,\n });\n}\nexports.kw_op_binary = {\n \"+\": mk_kw_operator(exports.op_binary[\"+\"]),\n \"-\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"-\"],\n }),\n \"*\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"*\"],\n }),\n \"/\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"/\"],\n }),\n \"%\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"%\"],\n }),\n \"//\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"//\"],\n }),\n \"**\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"**\"],\n }),\n \"<\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"<\"],\n }),\n \">\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\">\"],\n }),\n \">=\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\">=\"],\n }),\n \"<=\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"<=\"],\n }),\n \"==\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"==\"],\n }),\n \"!=\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"!=\"],\n }),\n \"|\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"|\"],\n }),\n \"&\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"&\"],\n }),\n \"^\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"^\"],\n }),\n \"<<\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"<<\"],\n }),\n \">>\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\">>\"],\n }),\n \"max\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"max\"],\n }),\n \"min\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"min\"],\n }),\n \"or\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"or\"],\n }),\n \"and\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"and\"],\n }),\n \"xor\": (0, kwargs_1.kwDecorators)({\n defaults: [[\"other\", undefined, basic_1.asarray], [\"out\", null]],\n func: exports.op_binary[\"xor\"],\n }),\n};\nexports.atan2 = (0, kwargs_1.kwDecorator)({\n defaults: [[\"y\", undefined, basic_1.asarray], [\"x\", undefined, basic_1.asarray], [\"out\", null]],\n func: __make_operator(Number, function (y, x) { return Math.atan2(y, x); }),\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.humanReadable = void 0;\nvar elementwise_1 = require(\"./elementwise\");\nvar js_interface_1 = require(\"./js-interface\");\nvar round = elementwise_1.ops.round;\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 = 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.kw_reducers = exports.reducers = void 0;\n//@ts-check\nvar basic_1 = require(\"./basic\");\nvar operators_1 = require(\"./operators\");\nvar kwargs_1 = require(\"./kwargs\");\nvar multiply = operators_1.op_binary[\"*\"];\nvar subtract = operators_1.op_binary[\"-\"];\nvar pow = operators_1.op_binary[\"**\"];\nfunction apply_on_axis(func, dtype, arr, axis, keepdims) {\n if (axis == null)\n return func(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 (_) { 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(func);\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 out.size == 1 ? out.flat[0] : out;\n}\n;\n// ==============================\n// Reducing functions\n// ==============================\nfunction mk_reducer(flat_reduce, dtype) {\n if (dtype === void 0) { dtype = Number; }\n return function (arr, axis, keepdims) {\n return apply_on_axis(flat_reduce, dtype, arr, axis, keepdims);\n };\n}\nexports.reducers = {\n sum: mk_reducer(function (arr) { return arr.reduce(function (a, b) { return a + b; }, 0); }),\n product: mk_reducer(function (arr) { return arr.reduce(function (a, b) { return a * b; }, 1); }),\n mean: mk_reducer(function (arr) { return arr.reduce(function (a, b) { return a + b; }, 0) / arr.length; }),\n max: mk_reducer(function (arr) { return Math.max.apply(Math, __spreadArray([], __read(arr), false)); }),\n min: mk_reducer(function (arr) { return Math.min.apply(Math, __spreadArray([], __read(arr), false)); }),\n argmax: mk_reducer(function (arr) { return arr.indexOf(Math.max.apply(Math, __spreadArray([], __read(arr), false))); }),\n argmin: mk_reducer(function (arr) { return arr.indexOf(Math.min.apply(Math, __spreadArray([], __read(arr), false))); }),\n len: mk_reducer(function (arr) { return arr.length; }),\n any: mk_reducer(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 }, Boolean),\n all: mk_reducer(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 }, Boolean),\n norm: function (arr, axis, keepdims, 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 return pow(exports.reducers.sum(pow(arr, ord), axis, keepdims), 1 / ord);\n },\n var: function (arr, axis, keepdims) {\n arr = subtract(arr, exports.reducers.mean(arr, axis, true));\n arr = multiply(arr, arr);\n return arr.mean({ axis: axis, keepdims: keepdims });\n },\n std: function (arr, axis, keepdims, ddof) {\n if (ddof == 0)\n return pow(arr.var(axis, keepdims), 0.5);\n var _sum = exports.reducers.sum(pow(arr, 2), axis, keepdims);\n var _len = exports.reducers.len(arr, axis, keepdims);\n return pow(operators_1.op_binary[\"/\"](_sum, operators_1.op_binary[\"-\"](_len, ddof)), 0.5);\n },\n};\nexports.kw_reducers = {\n sum: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.sum,\n }),\n product: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.product,\n }),\n mean: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.mean,\n }),\n max: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.max,\n }),\n min: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.min,\n }),\n argmax: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.argmax,\n }),\n argmin: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.argmin,\n }),\n len: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.len,\n }),\n any: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.any,\n }),\n all: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.all,\n }),\n norm: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false], [\"ord\", 2]],\n func: exports.reducers.norm,\n }),\n var: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false]],\n func: exports.reducers.var,\n }),\n std: (0, kwargs_1.kwDecorators)({\n defaults: [[\"axis\", null], [\"keepdims\", false], [\"ddof\", 0]],\n func: exports.reducers.std,\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 var _a;\n if (axis === void 0) { axis = -1; }\n (axis = Object.assign({ axis: axis }, this).axis);\n //@ts-ignore\n if (axis instanceof Object)\n (_a = axis, axis = _a.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 var _a;\n if (axes === void 0) { axes = null; }\n (axes = Object.assign({ axes: axes }, this).axes);\n //@ts-ignore\n if (axes !== null && axes[\"axes\"])\n (_a = axes, axes = _a.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 _a, e_1, _b;\n if (axis === void 0) { axis = null; }\n // ({ axis } = Object.assign({ axis }, this));\n //@ts-ignore\n if (axis instanceof Object)\n (_a = axis, axis = _a.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 && (_b = arrays_1.return)) _b.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 _a, e_2, _b;\n if (axis === void 0) { axis = 0; }\n // ({ axis } = Object.assign({ axis }, this));\n //@ts-ignore\n if (axis instanceof Object)\n (_a = axis, axis = _a.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 && (_b = arrays_2.return)) _b.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.kw_reducers.sum.as_function;\nnp.product = reduce.kw_reducers.product.as_function;\nnp.prod = np.product;\nnp.any = reduce.kw_reducers.any.as_function;\nnp.all = reduce.kw_reducers.all.as_function;\nnp.max = reduce.kw_reducers.max.as_function;\nnp.min = reduce.kw_reducers.min.as_function;\nnp.argmax = reduce.kw_reducers.argmax.as_function;\nnp.argmin = reduce.kw_reducers.argmin.as_function;\nnp.mean = reduce.kw_reducers.mean.as_function;\nnp.norm = reduce.kw_reducers.norm.as_function;\nnp.var = reduce.kw_reducers.var.as_function;\nnp.std = reduce.kw_reducers.std.as_function;\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.kw_op_binary[\"+\"].as_function;\nnp.subtract = operators.kw_op_binary[\"-\"].as_function;\nnp.multiply = operators.kw_op_binary[\"*\"].as_function;\nnp.divide = operators.kw_op_binary[\"/\"].as_function;\nnp.mod = operators.kw_op_binary[\"%\"].as_function;\nnp.divide_int = operators.kw_op_binary[\"//\"].as_function;\nnp.pow = operators.kw_op_binary[\"**\"].as_function;\nnp.bitwise_or = operators.kw_op_binary[\"|\"].as_function;\nnp.bitwise_and = operators.kw_op_binary[\"&\"].as_function;\nnp.bitwise_xor = operators.kw_op_binary[\"^\"].as_function;\nnp.bitwise_shift_left = operators.kw_op_binary[\"<<\"].as_function;\nnp.bitwise_shift_right = operators.kw_op_binary[\">>\"].as_function;\nnp.greater = operators.kw_op_binary[\">\"].as_function;\nnp.less = operators.kw_op_binary[\"<\"].as_function;\nnp.greater_equal = operators.kw_op_binary[\">=\"].as_function;\nnp.less_equal = operators.kw_op_binary[\"<=\"].as_function;\nnp.equal = operators.kw_op_binary[\"==\"].as_function;\nnp.not_equal = operators.kw_op_binary[\"!=\"].as_function;\nnp.maximum = operators.kw_op_binary[\"max\"].as_function;\nnp.minimum = operators.kw_op_binary[\"min\"].as_function;\nnp.logical_or = operators.kw_op_binary[\"or\"].as_function;\nnp.logical_and = operators.kw_op_binary[\"and\"].as_function;\nnp.atan2 = operators.atan2;\nnp.allclose = operators.allclose;\nnp.isclose = operators.isclose;\nvar ew = NDArray_class_1.default.prototype.modules.elementwise;\nnp.sign = ew.funcs.sign;\nnp.sqrt = ew.funcs.sqrt;\nnp.square = ew.funcs.square;\nnp.exp = ew.funcs.exp;\nnp.log = ew.funcs.log;\nnp.log2 = ew.funcs.log2;\nnp.log10 = ew.funcs.log10;\nnp.log1p = ew.funcs.log1p;\nnp.sin = ew.funcs.sin;\nnp.cos = ew.funcs.cos;\nnp.tan = ew.funcs.tan;\nnp.asin = ew.funcs.asin;\nnp.acos = ew.funcs.acos;\nnp.atan = ew.funcs.atan;\nnp.cosh = ew.funcs.cosh;\nnp.sinh = ew.funcs.sinh;\nnp.tanh = ew.funcs.tanh;\nnp.acosh = ew.funcs.acosh;\nnp.asinh = ew.funcs.asinh;\nnp.atanh = ew.funcs.atanh;\nnp.abs = ew.kw_ops.abs.as_function;\nnp.bitwise_not = ew.kw_ops.bitwise_not.as_function;\nnp.logical_not = ew.kw_ops.logical_not.as_function;\nnp.abs = ew.kw_ops.abs.as_function;\nnp.negative = ew.kw_ops.negative.as_function;\nnp.round = ew.kw_ops.round.as_function;\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;\nnp.pi = Math.PI;\nnp.e = Math.E;\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.funcs.log(start);\n stop = elementwise.funcs.log(stop);\n return elementwise.funcs.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 Object.keys(kwArgs).length == 0 ? func.apply(void 0, __spreadArray([], __read(args), false)) : func.apply(void 0, __spreadArray(__spreadArray([], __read(args), false), [kwArgs], false));\n // return func.bind(kwArgs)(...args); // Old version\n },\n Arr_method: function ($arr, _dot, $name, $callArgs) {\n var arr = $arr.parse();\n var name = $name.sourceString;\n var _a = $callArgs.parse(), args = _a.args, kwArgs = _a.kwArgs;\n if (arr[name] === undefined)\n throw new Error(\"Unrecognized method \".concat(name));\n // return arr.withKwArgs(kwArgs)[name](...args); // Old version\n return Object.keys(kwArgs).length == 0 ? arr[name].apply(arr, __spreadArray([], __read(args), false)) : arr[name].apply(arr, __spreadArray(__spreadArray([], __read(args), false), [kwArgs], 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 ops = _globals_1.nd_modules.elementwise.ops;\n switch (symbol) {\n case \"+\": return ops[\"+\"](B);\n case \"-\": return ops[\"-\"](B);\n case \"~\": return ops[\"~\"](B);\n case \"!\": return ops[\"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__(800);\n"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/modules/_globals.d.ts b/dist/modules/_globals.d.ts new file mode 100644 index 0000000..1efedfe --- /dev/null +++ b/dist/modules/_globals.d.ts @@ -0,0 +1,104 @@ +declare const np: { + (template: number | boolean | any[] | TemplateStringsArray, ...variables: any[]): any; + NDArray: typeof import("../NDArray-class").NDArray; + tolist(template: number | boolean | any[] | TemplateStringsArray, ...variables: any[]): any; + fromlist: typeof import("../NDArray/js-interface").fromlist; + ravel: typeof import("../NDArray/basic").ravel; + reshape: typeof import("../NDArray/basic").reshape; + array: typeof import("../NDArray/_globals").array; + asarray: typeof import("../NDArray/_globals").asarray; + sum: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceKwargs) => number | import("../NDArray-class").NDArray; + product: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceKwargs) => number | import("../NDArray-class").NDArray; + prod: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceKwargs) => number | import("../NDArray-class").NDArray; + any: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceKwargs) => boolean | import("../NDArray-class").NDArray; + all: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceKwargs) => boolean | import("../NDArray-class").NDArray; + max: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceKwargs) => number | import("../NDArray-class").NDArray; + min: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceKwargs) => number | import("../NDArray-class").NDArray; + argmax: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceKwargs) => number | import("../NDArray-class").NDArray; + argmin: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceKwargs) => number | import("../NDArray-class").NDArray; + mean: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceKwargs) => number | import("../NDArray-class").NDArray; + norm: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceNormKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceNormKwargs, ord?: number | import("../NDArray/kwargs").ReduceNormKwargs) => number | import("../NDArray-class").NDArray; + var: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceKwargs) => number | import("../NDArray-class").NDArray; + std: (arr: number | boolean | import("../NDArray-class").NDArray, axis?: number | import("../NDArray/kwargs").ReduceStdKwargs, keepdims?: boolean | import("../NDArray/kwargs").ReduceStdKwargs, ddof?: number | import("../NDArray/kwargs").ReduceStdKwargs) => number | import("../NDArray-class").NDArray; + transpose: typeof import("../NDArray/transform").transpose; + apply_along_axis: typeof import("../NDArray/transform").apply_along_axis; + sort: typeof import("../NDArray/transform").sort; + concatenate: typeof import("../NDArray/transform").concatenate; + stack: typeof import("../NDArray/transform").stack; + add: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + subtract: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + multiply: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + divide: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + mod: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + divide_int: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + pow: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + bitwise_or: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + bitwise_and: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + bitwise_xor: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + bitwise_shift_left: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + bitwise_shift_right: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + greater: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + less: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + greater_equal: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + less_equal: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + equal: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + not_equal: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + maximum: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + minimum: (arr: number | boolean | import("../NDArray-class").NDArray, other: number | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + logical_or: (arr: number | boolean | import("../NDArray-class").NDArray, other: boolean | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + logical_and: (arr: number | boolean | import("../NDArray-class").NDArray, other: boolean | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + atan2: (y: import("../NDArray-class").NDArray, x: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + allclose: typeof import("../NDArray/operators").allclose; + isclose: typeof import("../NDArray/operators").isclose; + sign: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + sqrt: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + square: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + exp: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + log: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + log2: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + log10: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + log1p: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + sin: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + cos: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + tan: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + asin: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + acos: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + atan: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + cosh: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + sinh: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + tanh: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + acosh: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + asinh: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + atanh: (A: import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + abs: (arr: number | boolean | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + bitwise_not: (arr: number | boolean | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + logical_not: (arr: number | boolean | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + negative: (arr: number | boolean | import("../NDArray-class").NDArray, out?: import("../NDArray-class").NDArray) => import("../NDArray-class").NDArray; + round: (arr: number | boolean | import("../NDArray-class").NDArray, decimals?: number) => import("../NDArray-class").NDArray; + modules: { + constructors: typeof import("./constructors"); + grammar: typeof import("./grammar"); + random: typeof import("./random"); + }; + empty: typeof import("./constructors").empty; + zeros: typeof import("./constructors").zeros; + ones: typeof import("./constructors").ones; + arange: typeof import("./constructors").arange; + linspace: typeof import("./constructors").linspace; + geomspace: typeof import("./constructors").geomspace; + random: typeof import("./random"); + pi: number; + e: number; +}; +export { np }; +export declare const nd_modules: { + basic: typeof import("../NDArray/basic"); + jsInterface: typeof import("../NDArray/js-interface"); + indexes: typeof import("../NDArray/indexes"); + elementwise: typeof import("../NDArray/elementwise"); + print: typeof import("../NDArray/print"); + reduce: typeof import("../NDArray/reduce"); + operators: typeof import("../NDArray/operators"); + transform: typeof import("../NDArray/transform"); +}; +//# sourceMappingURL=_globals.d.ts.map \ No newline at end of file diff --git a/dist/modules/_globals.d.ts.map b/dist/modules/_globals.d.ts.map new file mode 100644 index 0000000..5510b6e --- /dev/null +++ b/dist/modules/_globals.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_globals.d.ts","sourceRoot":"","sources":["../../src/modules/_globals.ts"],"names":[],"mappings":"AAEA,QAAA,MAAQ,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAA+B,CAAC;AAG1C,OAAO,EAAE,EAAE,EAAE,CAAC;AACd,eAAO,MAAM,UAAU;;;;;;;;;CAA6B,CAAC"} \ No newline at end of file diff --git a/dist/modules/constructors.d.ts b/dist/modules/constructors.d.ts new file mode 100644 index 0000000..378756a --- /dev/null +++ b/dist/modules/constructors.d.ts @@ -0,0 +1,8 @@ +import NDArray from '../NDArray-class'; +export declare function empty(shape: any, dtype?: import('../NDArray-class').DType): NDArray; +export declare function zeros(shape: any, dtype?: import('../NDArray-class').DType): NDArray; +export declare function ones(shape: any, dtype?: import('../NDArray-class').DType): NDArray; +export declare function arange(arg0: any, arg1?: any): NDArray; +export declare function linspace(start: any, stop: any, num?: number, endpoint?: boolean): NDArray; +export declare function geomspace(start: any, stop: any, num?: number, endpoint?: boolean): NDArray; +//# sourceMappingURL=constructors.d.ts.map \ No newline at end of file diff --git a/dist/modules/constructors.d.ts.map b/dist/modules/constructors.d.ts.map new file mode 100644 index 0000000..fe30a45 --- /dev/null +++ b/dist/modules/constructors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"constructors.d.ts","sourceRoot":"","sources":["../../src/modules/constructors.ts"],"names":[],"mappings":"AACA,OAAO,OAAO,MAAM,kBAAkB,CAAC;AAKvC,wBAAgB,KAAK,CAAC,KAAK,KAAA,EAAE,KAAK,GAAE,OAAO,kBAAkB,EAAE,KAAc,WAE5E;AAED,wBAAgB,KAAK,CAAC,KAAK,KAAA,EAAE,KAAK,GAAE,OAAO,kBAAkB,EAAE,KAAc,WAG5E;AAED,wBAAgB,IAAI,CAAC,KAAK,KAAA,EAAE,KAAK,GAAE,OAAO,kBAAkB,EAAE,KAAc,WAG3E;AAED,wBAAgB,MAAM,CAAC,IAAI,KAAA,EAAE,IAAI,MAAO,WAKvC;AAED,wBAAgB,QAAQ,CAAC,KAAK,KAAA,EAAE,IAAI,KAAA,EAAE,GAAG,SAAK,EAAE,QAAQ,UAAO,WAO9D;AAED,wBAAgB,SAAS,CAAC,KAAK,KAAA,EAAE,IAAI,KAAA,EAAE,GAAG,SAAK,EAAE,QAAQ,UAAO,WAK/D"} \ No newline at end of file diff --git a/dist/modules/grammar.d.ts b/dist/modules/grammar.d.ts new file mode 100644 index 0000000..06fbd0c --- /dev/null +++ b/dist/modules/grammar.d.ts @@ -0,0 +1,93 @@ +import * as ohm from 'ohm-js'; +export declare const grammar: string; +export declare const ohmGrammar: ohm.Grammar; +export declare const __makeSemantics: () => { + parse: (template: any, ...variables: any[]) => any; + ohmSemantics: ohm.Semantics; + semantics: { + Instruction_sliceAssignment($tgt: any, _open: any, $where: any, _close: any, $symbol: any, $src: any): any; + Instruction_expression($arr: any): any; + Precedence11: ($A: any, $symbol: any, $B: any) => any; + Precedence10: ($A: any, $symbol: any, $B: any) => any; + Precedence09: ($A: any, $symbol: any, $B: any) => any; + Precedence08: ($A: any, $symbol: any, $B: any) => any; + Precedence07: ($A: any, $symbol: any, $B: any) => any; + Precedence06: ($A: any, $symbol: any, $B: any) => any; + Precedence05: ($A: any, $symbol: any, $B: any) => any; + Precedence04: (_: any, $symbol: any, $B: any) => any; + Precedence03: (_: any, $symbol: any, $B: any) => any; + Precedence02: ($A: any, $symbol: any, $B: any) => any; + number: (arg1: any, arg2: any, arg3: any, arg4: any, arg5: any, arg6: any, arg7: any) => number; + Arr_slice($arr: any, _open: any, $where: any, _close: any): any; + SliceTerm_constant($x: any): any; + Arr_call($name: any, $names: any, _: any, $callArgs: any): any; + Arr_method($arr: any, _dot: any, $name: any, $callArgs: any): any; + Parenthesis(_: any, $arr: any, __: any): any; + Arr_attribute($arr: any, _: any, $name: any): any; + Variable(_: any, $i: any, __: any): any; + int($sign: any, $value: any): number; + SliceRange($start: any, _: any, $stop: any, __: any, $step: any): any; + Constant($x: any): number | boolean; + String(_open: any, $str: any, _close: any): any; + CallArgs(_open: any, $args: any, _comma: any, $kwArgs: any, _trailing: any, _close: any): { + args: any; + kwArgs: { + [k: string]: any; + }; + }; + KwArg($key: any, _equals: any, $value: any): any[]; + NonemptyListOf(first: any, _: any, more: any): any[]; + JsArray(_open: any, $list: any, _trailing: any, _close: any): any; + _terminal(): any; + }; + semanticVariables: any[]; + busy: number; +}; +export declare const __parser_pool: { + parse: (template: any, ...variables: any[]) => any; + ohmSemantics: ohm.Semantics; + semantics: { + Instruction_sliceAssignment($tgt: any, _open: any, $where: any, _close: any, $symbol: any, $src: any): any; + Instruction_expression($arr: any): any; + Precedence11: ($A: any, $symbol: any, $B: any) => any; + Precedence10: ($A: any, $symbol: any, $B: any) => any; + Precedence09: ($A: any, $symbol: any, $B: any) => any; + Precedence08: ($A: any, $symbol: any, $B: any) => any; + Precedence07: ($A: any, $symbol: any, $B: any) => any; + Precedence06: ($A: any, $symbol: any, $B: any) => any; + Precedence05: ($A: any, $symbol: any, $B: any) => any; + Precedence04: (_: any, $symbol: any, $B: any) => any; + Precedence03: (_: any, $symbol: any, $B: any) => any; + Precedence02: ($A: any, $symbol: any, $B: any) => any; + number: (arg1: any, arg2: any, arg3: any, arg4: any, arg5: any, arg6: any, arg7: any) => number; + Arr_slice($arr: any, _open: any, $where: any, _close: any): any; + SliceTerm_constant($x: any): any; + Arr_call($name: any, $names: any, _: any, $callArgs: any): any; + Arr_method($arr: any, _dot: any, $name: any, $callArgs: any): any; + Parenthesis(_: any, $arr: any, __: any): any; + Arr_attribute($arr: any, _: any, $name: any): any; + Variable(_: any, $i: any, __: any): any; + int($sign: any, $value: any): number; + SliceRange($start: any, _: any, $stop: any, __: any, $step: any): any; + Constant($x: any): number | boolean; + String(_open: any, $str: any, _close: any): any; + CallArgs(_open: any, $args: any, _comma: any, $kwArgs: any, _trailing: any, _close: any): { + args: any; + kwArgs: { + [k: string]: any; + }; + }; + KwArg($key: any, _equals: any, $value: any): any[]; + NonemptyListOf(first: any, _: any, more: any): any[]; + JsArray(_open: any, $list: any, _trailing: any, _close: any): any; + _terminal(): any; + }; + semanticVariables: any[]; + busy: number; +}[]; +/** + * @param {TemplateStringsArray} template + * @param {any[]} variables + */ +export declare const parse: (template: any, ...variables: any[]) => any; +//# sourceMappingURL=grammar.d.ts.map \ No newline at end of file diff --git a/dist/modules/grammar.d.ts.map b/dist/modules/grammar.d.ts.map new file mode 100644 index 0000000..745e37a --- /dev/null +++ b/dist/modules/grammar.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"grammar.d.ts","sourceRoot":"","sources":["../../src/modules/grammar.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,GAAG,MAAM,QAAQ,CAAC;AAG9B,eAAO,MAAM,OAAO,QAiGnB,CAAC;AAEF,eAAO,MAAM,UAAU,aAAuB,CAAC;AAG/C,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqK3B,CAAA;AAGD,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAAsB,CAAC;AAEjD;;;GAGG;AACH,eAAO,MAAM,KAAK,6CAajB,CAAA"} \ No newline at end of file diff --git a/dist/modules/index.d.ts b/dist/modules/index.d.ts new file mode 100644 index 0000000..96db26a --- /dev/null +++ b/dist/modules/index.d.ts @@ -0,0 +1,10 @@ +import './_globals'; +import * as constructors from './constructors'; +import * as grammar from './grammar'; +import * as random from './random'; +export declare const modules: { + constructors: typeof constructors; + grammar: typeof grammar; + random: typeof random; +}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/modules/index.d.ts.map b/dist/modules/index.d.ts.map new file mode 100644 index 0000000..16bb8e4 --- /dev/null +++ b/dist/modules/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/modules/index.ts"],"names":[],"mappings":"AACA,OAAO,YAAY,CAAC;AAEpB,OAAO,KAAK,YAAY,MAAM,gBAAgB,CAAC;AAC/C,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC;AACrC,OAAO,KAAK,MAAM,MAAM,UAAU,CAAC;AAEnC,eAAO,MAAM,OAAO;;;;CAInB,CAAC"} \ No newline at end of file diff --git a/dist/modules/random.d.ts b/dist/modules/random.d.ts new file mode 100644 index 0000000..4a0d42d --- /dev/null +++ b/dist/modules/random.d.ts @@ -0,0 +1,18 @@ +export declare function random(shape: any): import("../NDArray-class").NDArray; +export declare function uniform(a: any, b: any, shape: any): import("../NDArray-class").NDArray; +export declare function exponential(mean: any, shape: any): import("../NDArray-class").NDArray; +/** @param {number} n */ +export declare function __normal(n: any): number[]; +export declare function randn(shape: any): import("../NDArray-class").NDArray; +export declare function normal(mean: any, std: any, shape: any): import("../NDArray-class").NDArray; +/** @param {any[]} list */ +export declare function _shuffle(list: any): void; +/** @param {any[]} list */ +export declare function _shuffled(list: any): any[]; +/** @param {NDArray} arr @returns {NDArray} */ +export declare function shuffled(arr: any): any; +/** + * @param {NDArray} arr + */ +export declare function shuffle(arr: any): void; +//# sourceMappingURL=random.d.ts.map \ No newline at end of file diff --git a/dist/modules/random.d.ts.map b/dist/modules/random.d.ts.map new file mode 100644 index 0000000..d137ccb --- /dev/null +++ b/dist/modules/random.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"random.d.ts","sourceRoot":"","sources":["../../src/modules/random.ts"],"names":[],"mappings":"AAIA,wBAAgB,MAAM,CAAC,KAAK,KAAA,sCAE3B;AACD,wBAAgB,OAAO,CAAC,CAAC,KAAA,EAAE,CAAC,KAAA,EAAE,KAAK,KAAA,sCAElC;AACD,wBAAgB,WAAW,CAAC,IAAI,KAAA,EAAE,KAAK,KAAA,sCAEtC;AAED,wBAAwB;AACxB,wBAAgB,QAAQ,CAAC,CAAC,KAAA,YAczB;AACD,wBAAgB,KAAK,CAAC,KAAK,KAAA,sCAG1B;AACD,wBAAgB,MAAM,CAAC,IAAI,KAAA,EAAE,GAAG,KAAA,EAAE,KAAK,KAAA,sCAEtC;AAGD,0BAA0B;AAC1B,wBAAgB,QAAQ,CAAC,IAAI,KAAA,QAO5B;AAED,0BAA0B;AAC1B,wBAAgB,SAAS,CAAC,IAAI,KAAA,SAI7B;AAED,+CAA+C;AAC/C,wBAAgB,QAAQ,CAAC,GAAG,KAAA,OAU3B;AAED;;GAEG;AACH,wBAAgB,OAAO,CAAC,GAAG,KAAA,QAE1B"} \ No newline at end of file diff --git a/dist/utils-js.d.ts b/dist/utils-js.d.ts new file mode 100644 index 0000000..02d4704 --- /dev/null +++ b/dist/utils-js.d.ts @@ -0,0 +1,5 @@ +export declare function binary_operation(A: any, B: any, func: any): boolean; +export declare function ravel(A: any): any[]; +export declare function allEq(A: any, B: any, nan_equal?: boolean): boolean; +export declare function allClose(A: any, B: any, rtol?: number, atol?: number, nan_equal?: boolean): boolean; +//# sourceMappingURL=utils-js.d.ts.map \ No newline at end of file diff --git a/dist/utils-js.d.ts.map b/dist/utils-js.d.ts.map new file mode 100644 index 0000000..df636da --- /dev/null +++ b/dist/utils-js.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils-js.d.ts","sourceRoot":"","sources":["../src/utils-js.ts"],"names":[],"mappings":"AAEA,wBAAgB,gBAAgB,CAAC,CAAC,KAAA,EAAE,CAAC,KAAA,EAAE,IAAI,KAAA,WAwB1C;AAED,wBAAgB,KAAK,CAAC,CAAC,KAAA,SAoBtB;AAED,wBAAgB,KAAK,CAAC,CAAC,KAAA,EAAE,CAAC,KAAA,EAAE,SAAS,UAAQ,WAY5C;AAED,wBAAgB,QAAQ,CAAC,CAAC,KAAA,EAAE,CAAC,KAAA,EAAE,IAAI,SAAQ,EAAE,IAAI,SAAQ,EAAE,SAAS,UAAQ,WAgB3E"} \ No newline at end of file diff --git a/docs-readme.md b/docs-readme.md index b343332..4d9d30f 100644 --- a/docs-readme.md +++ b/docs-readme.md @@ -1,6 +1,6 @@ -# Numpy-js documentation +# ndarray-js documentation -Numpy-js is a reimplementation of numpy for javascript that aims to make the coding experience as similar to numpy as possible. +ndarray-js is a reimplementation of numpy for javascript that aims to make the coding experience as similar to numpy as possible. diff --git a/package.json b/package.json index 8b99d59..525769b 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,8 @@ { - "name": "@caph1993/numpy-js", - "version": "4.0.1", + "name": "ndarray-js", + "version": "1.0.0", "description": "", - "main": "index.js", - "entrypoint":{ - "main": "dist/caph1993-numpy-js.js" - }, + "main": "src/index.ts", "scripts": { "build": "webpack --config webpack.config.js", "test": "cd tests && ts-node tests_october.ts", @@ -13,13 +10,14 @@ "lint": "eslint -f unix \"src/**/*.{ts,tsx}\"" }, "keywords": [ + "ndarray", "numpy", - "numpy-js", "math", - "ndarray", "array", + "numpy-js", + "typescript", "javascript", - "typescript" + "numjs" ], "author": "Carlos Pinzón", "license": "BSD 3", @@ -30,6 +28,7 @@ "@mxssfd/typedoc-theme": "^1.1.3", "@types/node": "^20.8.3", "d3": "^6.0.0", + "declaration-bundler-webpack-plugin": "^1.0.3", "eslint-plugin-tsdoc": "^0.2.17", "jsdom": "^22.1.0", "ts-loader": "^9.5.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9c8fb75..ed35048 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1,62 +1,85 @@ -lockfileVersion: 5.4 - -specifiers: - '@mxssfd/typedoc-theme': ^1.1.3 - '@types/node': ^20.8.3 - d3: ^6.0.0 - eslint-plugin-tsdoc: ^0.2.17 - jsdom: ^22.1.0 - ohm-js: ^17.1.0 - ts-loader: ^9.5.0 - ts-node: ^10.9.1 - typedoc: ^0.25.2 - typedoc-default-themes: ^0.12.10 - typedoc-neo-theme: ^1.1.1 - typedoc-plugin-merge-modules: ^5.1.0 - typedoc-theme-hierarchy: ^4.1.2 - typescript: ^5.2.2 - uglifyjs-webpack-plugin: ^2.2.0 - webpack: ^5.88.2 - webpack-cli: ^5.1.4 - webpack-license-plugin: ^4.3.0 +lockfileVersion: '6.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false dependencies: - ohm-js: 17.1.0 - typedoc-default-themes: 0.12.10 + ohm-js: + specifier: ^17.1.0 + version: 17.1.0 devDependencies: - '@mxssfd/typedoc-theme': 1.1.3_typedoc@0.25.2 - '@types/node': 20.8.3 - d3: 6.7.0 - eslint-plugin-tsdoc: 0.2.17 - jsdom: 22.1.0 - ts-loader: 9.5.0_dtthwp2bsqb7yvb7hoeealjg4i - ts-node: 10.9.1_sipn3hrabmvxbeu4xryuphsbsa - typedoc: 0.25.2_typescript@5.2.2 - typedoc-neo-theme: 1.1.1_typescript@5.2.2 - typedoc-plugin-merge-modules: 5.1.0_typedoc@0.25.2 - typedoc-theme-hierarchy: 4.1.2_typedoc@0.25.2 - typescript: 5.2.2 - uglifyjs-webpack-plugin: 2.2.0_webpack@5.88.2 - webpack: 5.88.2_webpack-cli@5.1.4 - webpack-cli: 5.1.4_webpack@5.88.2 - webpack-license-plugin: 4.3.0_webpack@5.88.2 + '@mxssfd/typedoc-theme': + specifier: ^1.1.3 + version: 1.1.3(typedoc@0.25.2) + '@types/node': + specifier: ^20.8.3 + version: 20.8.3 + d3: + specifier: ^6.0.0 + version: 6.7.0 + declaration-bundler-webpack-plugin: + specifier: ^1.0.3 + version: 1.0.3 + eslint-plugin-tsdoc: + specifier: ^0.2.17 + version: 0.2.17 + jsdom: + specifier: ^22.1.0 + version: 22.1.0 + ts-loader: + specifier: ^9.5.0 + version: 9.5.0(typescript@5.2.2)(webpack@5.88.2) + ts-node: + specifier: ^10.9.1 + version: 10.9.1(@types/node@20.8.3)(typescript@5.2.2) + typedoc: + specifier: ^0.25.2 + version: 0.25.2(typescript@5.2.2) + typedoc-default-themes: + specifier: ^0.12.10 + version: 0.12.10 + typedoc-neo-theme: + specifier: ^1.1.1 + version: 1.1.1(typescript@5.2.2) + typedoc-plugin-merge-modules: + specifier: ^5.1.0 + version: 5.1.0(typedoc@0.25.2) + typedoc-theme-hierarchy: + specifier: ^4.1.2 + version: 4.1.2(typedoc@0.25.2) + typescript: + specifier: ^5.2.2 + version: 5.2.2 + uglifyjs-webpack-plugin: + specifier: ^2.2.0 + version: 2.2.0(webpack@5.88.2) + webpack: + specifier: ^5.88.2 + version: 5.88.2(webpack-cli@5.1.4) + webpack-cli: + specifier: ^5.1.4 + version: 5.1.4(webpack@5.88.2) + webpack-license-plugin: + specifier: ^4.3.0 + version: 4.3.0(webpack@5.88.2) packages: - /@cspotcode/source-map-support/0.8.1: + /@cspotcode/source-map-support@0.8.1: resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} engines: {node: '>=12'} dependencies: '@jridgewell/trace-mapping': 0.3.9 dev: true - /@discoveryjs/json-ext/0.5.7: + /@discoveryjs/json-ext@0.5.7: resolution: {integrity: sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==} engines: {node: '>=10.0.0'} dev: true - /@jridgewell/gen-mapping/0.3.3: + /@jridgewell/gen-mapping@0.3.3: resolution: {integrity: sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==} engines: {node: '>=6.0.0'} dependencies: @@ -65,42 +88,42 @@ packages: '@jridgewell/trace-mapping': 0.3.19 dev: true - /@jridgewell/resolve-uri/3.1.1: + /@jridgewell/resolve-uri@3.1.1: resolution: {integrity: sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==} engines: {node: '>=6.0.0'} dev: true - /@jridgewell/set-array/1.1.2: + /@jridgewell/set-array@1.1.2: resolution: {integrity: sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==} engines: {node: '>=6.0.0'} dev: true - /@jridgewell/source-map/0.3.5: + /@jridgewell/source-map@0.3.5: resolution: {integrity: sha512-UTYAUj/wviwdsMfzoSJspJxbkH5o1snzwX0//0ENX1u/55kkZZkcTZP6u9bwKGkv+dkk9at4m1Cpt0uY80kcpQ==} dependencies: '@jridgewell/gen-mapping': 0.3.3 '@jridgewell/trace-mapping': 0.3.19 dev: true - /@jridgewell/sourcemap-codec/1.4.15: + /@jridgewell/sourcemap-codec@1.4.15: resolution: {integrity: sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==} dev: true - /@jridgewell/trace-mapping/0.3.19: + /@jridgewell/trace-mapping@0.3.19: resolution: {integrity: sha512-kf37QtfW+Hwx/buWGMPcR60iF9ziHa6r/CZJIHbmcm4+0qrXiVdxegAH0F6yddEVQ7zdkjcGCgCzUu+BcbhQxw==} dependencies: '@jridgewell/resolve-uri': 3.1.1 '@jridgewell/sourcemap-codec': 1.4.15 dev: true - /@jridgewell/trace-mapping/0.3.9: + /@jridgewell/trace-mapping@0.3.9: resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} dependencies: '@jridgewell/resolve-uri': 3.1.1 '@jridgewell/sourcemap-codec': 1.4.15 dev: true - /@microsoft/tsdoc-config/0.16.2: + /@microsoft/tsdoc-config@0.16.2: resolution: {integrity: sha512-OGiIzzoBLgWWR0UdRJX98oYO+XKGf7tiK4Zk6tQ/E4IJqGCe7dvkTvgDZV5cFJUzLGDOjeAXrnZoA6QkVySuxw==} dependencies: '@microsoft/tsdoc': 0.14.2 @@ -109,86 +132,86 @@ packages: resolve: 1.19.0 dev: true - /@microsoft/tsdoc/0.14.2: + /@microsoft/tsdoc@0.14.2: resolution: {integrity: sha512-9b8mPpKrfeGRuhFH5iO1iwCLeIIsV6+H1sRfxbkoGXIyQE2BTsPd9zqSqQJ+pv5sJ/hT5M1zvOFL02MnEezFug==} dev: true - /@mxssfd/typedoc-theme/1.1.3_typedoc@0.25.2: + /@mxssfd/typedoc-theme@1.1.3(typedoc@0.25.2): resolution: {integrity: sha512-/yP5rqhvibMpzXpmw0YLLRCpoj3uVWWlwyJseZXzGxTfiA6/fd1uubUqNoQAi2U19atMDonq8mQc+hlVctrX4g==} engines: {node: '>= 14'} peerDependencies: typedoc: ^0.25.1 dependencies: - typedoc: 0.25.2_typescript@5.2.2 + typedoc: 0.25.2(typescript@5.2.2) dev: true - /@tootallnate/once/2.0.0: + /@tootallnate/once@2.0.0: resolution: {integrity: sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==} engines: {node: '>= 10'} dev: true - /@tsconfig/node10/1.0.9: + /@tsconfig/node10@1.0.9: resolution: {integrity: sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==} dev: true - /@tsconfig/node12/1.0.11: + /@tsconfig/node12@1.0.11: resolution: {integrity: sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==} dev: true - /@tsconfig/node14/1.0.3: + /@tsconfig/node14@1.0.3: resolution: {integrity: sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==} dev: true - /@tsconfig/node16/1.0.4: + /@tsconfig/node16@1.0.4: resolution: {integrity: sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==} dev: true - /@types/eslint-scope/3.7.5: + /@types/eslint-scope@3.7.5: resolution: {integrity: sha512-JNvhIEyxVW6EoMIFIvj93ZOywYFatlpu9deeH6eSx6PE3WHYvHaQtmHmQeNw7aA81bYGBPPQqdtBm6b1SsQMmA==} dependencies: '@types/eslint': 8.44.3 '@types/estree': 1.0.2 dev: true - /@types/eslint/8.44.3: + /@types/eslint@8.44.3: resolution: {integrity: sha512-iM/WfkwAhwmPff3wZuPLYiHX18HI24jU8k1ZSH7P8FHwxTjZ2P6CoX2wnF43oprR+YXJM6UUxATkNvyv/JHd+g==} dependencies: '@types/estree': 1.0.2 '@types/json-schema': 7.0.13 dev: true - /@types/estree/1.0.2: + /@types/estree@1.0.2: resolution: {integrity: sha512-VeiPZ9MMwXjO32/Xu7+OwflfmeoRwkE/qzndw42gGtgJwZopBnzy2gD//NN1+go1mADzkDcqf/KnFRSjTJ8xJA==} dev: true - /@types/json-schema/7.0.13: + /@types/json-schema@7.0.13: resolution: {integrity: sha512-RbSSoHliUbnXj3ny0CNFOoxrIDV6SUGyStHsvDqosw6CkdPV8TtWGlfecuK4ToyMEAql6pzNxgCFKanovUzlgQ==} dev: true - /@types/node/20.8.3: + /@types/node@20.8.3: resolution: {integrity: sha512-jxiZQFpb+NlH5kjW49vXxvxTjeeqlbsnTAdBTKpzEdPs9itay7MscYXz3Fo9VYFEsfQ6LJFitHad3faerLAjCw==} dev: true - /@webassemblyjs/ast/1.11.6: + /@webassemblyjs/ast@1.11.6: resolution: {integrity: sha512-IN1xI7PwOvLPgjcf180gC1bqn3q/QaOCwYUahIOhbYUu8KA/3tw2RT/T0Gidi1l7Hhj5D/INhJxiICObqpMu4Q==} dependencies: '@webassemblyjs/helper-numbers': 1.11.6 '@webassemblyjs/helper-wasm-bytecode': 1.11.6 dev: true - /@webassemblyjs/floating-point-hex-parser/1.11.6: + /@webassemblyjs/floating-point-hex-parser@1.11.6: resolution: {integrity: sha512-ejAj9hfRJ2XMsNHk/v6Fu2dGS+i4UaXBXGemOfQ/JfQ6mdQg/WXtwleQRLLS4OvfDhv8rYnVwH27YJLMyYsxhw==} dev: true - /@webassemblyjs/helper-api-error/1.11.6: + /@webassemblyjs/helper-api-error@1.11.6: resolution: {integrity: sha512-o0YkoP4pVu4rN8aTJgAyj9hC2Sv5UlkzCHhxqWj8butaLvnpdc2jOwh4ewE6CX0txSfLn/UYaV/pheS2Txg//Q==} dev: true - /@webassemblyjs/helper-buffer/1.11.6: + /@webassemblyjs/helper-buffer@1.11.6: resolution: {integrity: sha512-z3nFzdcp1mb8nEOFFk8DrYLpHvhKC3grJD2ardfKOzmbmJvEf/tPIqCY+sNcwZIY8ZD7IkB2l7/pqhUhqm7hLA==} dev: true - /@webassemblyjs/helper-numbers/1.11.6: + /@webassemblyjs/helper-numbers@1.11.6: resolution: {integrity: sha512-vUIhZ8LZoIWHBohiEObxVm6hwP034jwmc9kuq5GdHZH0wiLVLIPcMCdpJzG4C11cHoQ25TFIQj9kaVADVX7N3g==} dependencies: '@webassemblyjs/floating-point-hex-parser': 1.11.6 @@ -196,11 +219,11 @@ packages: '@xtuc/long': 4.2.2 dev: true - /@webassemblyjs/helper-wasm-bytecode/1.11.6: + /@webassemblyjs/helper-wasm-bytecode@1.11.6: resolution: {integrity: sha512-sFFHKwcmBprO9e7Icf0+gddyWYDViL8bpPjJJl0WHxCdETktXdmtWLGVzoHbqUcY4Be1LkNfwTmXOJUFZYSJdA==} dev: true - /@webassemblyjs/helper-wasm-section/1.11.6: + /@webassemblyjs/helper-wasm-section@1.11.6: resolution: {integrity: sha512-LPpZbSOwTpEC2cgn4hTydySy1Ke+XEu+ETXuoyvuyezHO3Kjdu90KK95Sh9xTbmjrCsUwvWwCOQQNta37VrS9g==} dependencies: '@webassemblyjs/ast': 1.11.6 @@ -209,23 +232,23 @@ packages: '@webassemblyjs/wasm-gen': 1.11.6 dev: true - /@webassemblyjs/ieee754/1.11.6: + /@webassemblyjs/ieee754@1.11.6: resolution: {integrity: sha512-LM4p2csPNvbij6U1f19v6WR56QZ8JcHg3QIJTlSwzFcmx6WSORicYj6I63f9yU1kEUtrpG+kjkiIAkevHpDXrg==} dependencies: '@xtuc/ieee754': 1.2.0 dev: true - /@webassemblyjs/leb128/1.11.6: + /@webassemblyjs/leb128@1.11.6: resolution: {integrity: sha512-m7a0FhE67DQXgouf1tbN5XQcdWoNgaAuoULHIfGFIEVKA6tu/edls6XnIlkmS6FrXAquJRPni3ZZKjw6FSPjPQ==} dependencies: '@xtuc/long': 4.2.2 dev: true - /@webassemblyjs/utf8/1.11.6: + /@webassemblyjs/utf8@1.11.6: resolution: {integrity: sha512-vtXf2wTQ3+up9Zsg8sa2yWiQpzSsMyXj0qViVP6xKGCUT8p8YJ6HqI7l5eCnWx1T/FYdsv07HQs2wTFbbof/RA==} dev: true - /@webassemblyjs/wasm-edit/1.11.6: + /@webassemblyjs/wasm-edit@1.11.6: resolution: {integrity: sha512-Ybn2I6fnfIGuCR+Faaz7YcvtBKxvoLV3Lebn1tM4o/IAJzmi9AWYIPWpyBfU8cC+JxAO57bk4+zdsTjJR+VTOw==} dependencies: '@webassemblyjs/ast': 1.11.6 @@ -238,7 +261,7 @@ packages: '@webassemblyjs/wast-printer': 1.11.6 dev: true - /@webassemblyjs/wasm-gen/1.11.6: + /@webassemblyjs/wasm-gen@1.11.6: resolution: {integrity: sha512-3XOqkZP/y6B4F0PBAXvI1/bky7GryoogUtfwExeP/v7Nzwo1QLcq5oQmpKlftZLbT+ERUOAZVQjuNVak6UXjPA==} dependencies: '@webassemblyjs/ast': 1.11.6 @@ -248,7 +271,7 @@ packages: '@webassemblyjs/utf8': 1.11.6 dev: true - /@webassemblyjs/wasm-opt/1.11.6: + /@webassemblyjs/wasm-opt@1.11.6: resolution: {integrity: sha512-cOrKuLRE7PCe6AsOVl7WasYf3wbSo4CeOk6PkrjS7g57MFfVUF9u6ysQBBODX0LdgSvQqRiGz3CXvIDKcPNy4g==} dependencies: '@webassemblyjs/ast': 1.11.6 @@ -257,7 +280,7 @@ packages: '@webassemblyjs/wasm-parser': 1.11.6 dev: true - /@webassemblyjs/wasm-parser/1.11.6: + /@webassemblyjs/wasm-parser@1.11.6: resolution: {integrity: sha512-6ZwPeGzMJM3Dqp3hCsLgESxBGtT/OeCvCZ4TA1JUPYgmhAx38tTPR9JaKy0S5H3evQpO/h2uWs2j6Yc/fjkpTQ==} dependencies: '@webassemblyjs/ast': 1.11.6 @@ -268,36 +291,36 @@ packages: '@webassemblyjs/utf8': 1.11.6 dev: true - /@webassemblyjs/wast-printer/1.11.6: + /@webassemblyjs/wast-printer@1.11.6: resolution: {integrity: sha512-JM7AhRcE+yW2GWYaKeHL5vt4xqee5N2WcezptmgyhNS+ScggqcT1OtXykhAb13Sn5Yas0j2uv9tHgrjwvzAP4A==} dependencies: '@webassemblyjs/ast': 1.11.6 '@xtuc/long': 4.2.2 dev: true - /@webpack-cli/configtest/2.1.1_w46lltld4evug5kpkz4iei6qt4: + /@webpack-cli/configtest@2.1.1(webpack-cli@5.1.4)(webpack@5.88.2): resolution: {integrity: sha512-wy0mglZpDSiSS0XHrVR+BAdId2+yxPSoJW8fsna3ZpYSlufjvxnP4YbKTCBZnNIcGN4r6ZPXV55X4mYExOfLmw==} engines: {node: '>=14.15.0'} peerDependencies: webpack: 5.x.x webpack-cli: 5.x.x dependencies: - webpack: 5.88.2_webpack-cli@5.1.4 - webpack-cli: 5.1.4_webpack@5.88.2 + webpack: 5.88.2(webpack-cli@5.1.4) + webpack-cli: 5.1.4(webpack@5.88.2) dev: true - /@webpack-cli/info/2.0.2_w46lltld4evug5kpkz4iei6qt4: + /@webpack-cli/info@2.0.2(webpack-cli@5.1.4)(webpack@5.88.2): resolution: {integrity: sha512-zLHQdI/Qs1UyT5UBdWNqsARasIA+AaF8t+4u2aS2nEpBQh2mWIVb8qAklq0eUENnC5mOItrIB4LiS9xMtph18A==} engines: {node: '>=14.15.0'} peerDependencies: webpack: 5.x.x webpack-cli: 5.x.x dependencies: - webpack: 5.88.2_webpack-cli@5.1.4 - webpack-cli: 5.1.4_webpack@5.88.2 + webpack: 5.88.2(webpack-cli@5.1.4) + webpack-cli: 5.1.4(webpack@5.88.2) dev: true - /@webpack-cli/serve/2.0.5_w46lltld4evug5kpkz4iei6qt4: + /@webpack-cli/serve@2.0.5(webpack-cli@5.1.4)(webpack@5.88.2): resolution: {integrity: sha512-lqaoKnRYBdo1UgDX8uF24AfGMifWK19TxPmM5FHc2vAGxrJ/qtyUyFBWoY1tISZdelsQ5fBcOusifo5o5wSJxQ==} engines: {node: '>=14.15.0'} peerDependencies: @@ -308,23 +331,23 @@ packages: webpack-dev-server: optional: true dependencies: - webpack: 5.88.2_webpack-cli@5.1.4 - webpack-cli: 5.1.4_webpack@5.88.2 + webpack: 5.88.2(webpack-cli@5.1.4) + webpack-cli: 5.1.4(webpack@5.88.2) dev: true - /@xtuc/ieee754/1.2.0: + /@xtuc/ieee754@1.2.0: resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==} dev: true - /@xtuc/long/4.2.2: + /@xtuc/long@4.2.2: resolution: {integrity: sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==} dev: true - /abab/2.0.6: + /abab@2.0.6: resolution: {integrity: sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==} dev: true - /acorn-import-assertions/1.9.0_acorn@8.10.0: + /acorn-import-assertions@1.9.0(acorn@8.10.0): resolution: {integrity: sha512-cmMwop9x+8KFhxvKrKfPYmN6/pKTYYHBqLa0DfvVZcKMJWNyWLnaqND7dx/qn66R7ewM1UX5XMaDVP5wlVTaVA==} peerDependencies: acorn: ^8 @@ -332,18 +355,18 @@ packages: acorn: 8.10.0 dev: true - /acorn-walk/8.2.0: + /acorn-walk@8.2.0: resolution: {integrity: sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==} engines: {node: '>=0.4.0'} dev: true - /acorn/8.10.0: + /acorn@8.10.0: resolution: {integrity: sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==} engines: {node: '>=0.4.0'} hasBin: true dev: true - /agent-base/6.0.2: + /agent-base@6.0.2: resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} engines: {node: '>= 6.0.0'} dependencies: @@ -352,7 +375,7 @@ packages: - supports-color dev: true - /ajv-errors/1.0.1_ajv@6.12.6: + /ajv-errors@1.0.1(ajv@6.12.6): resolution: {integrity: sha512-DCRfO/4nQ+89p/RK43i8Ezd41EqdGIU4ld7nGF8OQ14oc/we5rEntLCUa7+jrn3nn83BosfwZA0wb4pon2o8iQ==} peerDependencies: ajv: '>=5.0.0' @@ -360,7 +383,7 @@ packages: ajv: 6.12.6 dev: true - /ajv-keywords/3.5.2_ajv@6.12.6: + /ajv-keywords@3.5.2(ajv@6.12.6): resolution: {integrity: sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==} peerDependencies: ajv: ^6.9.1 @@ -368,7 +391,7 @@ packages: ajv: 6.12.6 dev: true - /ajv/6.12.6: + /ajv@6.12.6: resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} dependencies: fast-deep-equal: 3.1.3 @@ -377,63 +400,63 @@ packages: uri-js: 4.4.1 dev: true - /ansi-sequence-parser/1.1.1: + /ansi-sequence-parser@1.1.1: resolution: {integrity: sha512-vJXt3yiaUL4UU546s3rPXlsry/RnM730G1+HkpKE012AN0sx1eOrxSu95oKDIonskeLTijMgqWZ3uDEe3NFvyg==} dev: true - /ansi-styles/4.3.0: + /ansi-styles@4.3.0: resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} engines: {node: '>=8'} dependencies: color-convert: 2.0.1 dev: true - /aproba/1.2.0: + /aproba@1.2.0: resolution: {integrity: sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==} dev: true - /arg/4.1.3: + /arg@4.1.3: resolution: {integrity: sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==} dev: true - /asynckit/0.4.0: + /asynckit@0.4.0: resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} dev: true - /at-least-node/1.0.0: + /at-least-node@1.0.0: resolution: {integrity: sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==} engines: {node: '>= 4.0.0'} dev: true - /balanced-match/1.0.2: + /balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} dev: true - /bluebird/3.7.2: + /bluebird@3.7.2: resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==} dev: true - /brace-expansion/1.1.11: + /brace-expansion@1.1.11: resolution: {integrity: sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==} dependencies: balanced-match: 1.0.2 concat-map: 0.0.1 dev: true - /brace-expansion/2.0.1: + /brace-expansion@2.0.1: resolution: {integrity: sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==} dependencies: balanced-match: 1.0.2 dev: true - /braces/3.0.2: + /braces@3.0.2: resolution: {integrity: sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==} engines: {node: '>=8'} dependencies: fill-range: 7.0.1 dev: true - /browserslist/4.22.1: + /browserslist@4.22.1: resolution: {integrity: sha512-FEVc202+2iuClEhZhrWy6ZiAcRLvNMyYcxZ8raemul1DYVOVdFsbqckWLdsixQZCpJlwe77Z3UTalE7jsjnKfQ==} engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true @@ -441,14 +464,14 @@ packages: caniuse-lite: 1.0.30001546 electron-to-chromium: 1.4.543 node-releases: 2.0.13 - update-browserslist-db: 1.0.13_browserslist@4.22.1 + update-browserslist-db: 1.0.13(browserslist@4.22.1) dev: true - /buffer-from/1.1.2: + /buffer-from@1.1.2: resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} dev: true - /cacache/12.0.4: + /cacache@12.0.4: resolution: {integrity: sha512-a0tMB40oefvuInr4Cwb3GerbL9xTj1D5yg0T5xrjGCGyfvbxseIXX7BAO/u/hIXdafzOI5JC3wDwHyf24buOAQ==} dependencies: bluebird: 3.7.2 @@ -461,18 +484,18 @@ packages: mississippi: 3.0.0 mkdirp: 0.5.6 move-concurrently: 1.0.1 - promise-inflight: 1.0.1_bluebird@3.7.2 + promise-inflight: 1.0.1(bluebird@3.7.2) rimraf: 2.7.1 ssri: 6.0.2 unique-filename: 1.1.1 y18n: 4.0.3 dev: true - /caniuse-lite/1.0.30001546: + /caniuse-lite@1.0.30001546: resolution: {integrity: sha512-zvtSJwuQFpewSyRrI3AsftF6rM0X80mZkChIt1spBGEvRglCrjTniXvinc8JKRoqTwXAgvqTImaN9igfSMtUBw==} dev: true - /chalk/4.1.2: + /chalk@4.1.2: resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} engines: {node: '>=10'} dependencies: @@ -480,21 +503,21 @@ packages: supports-color: 7.2.0 dev: true - /chalk/5.3.0: + /chalk@5.3.0: resolution: {integrity: sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==} engines: {node: ^12.17.0 || ^14.13 || >=16.0.0} dev: true - /chownr/1.1.4: + /chownr@1.1.4: resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==} dev: true - /chrome-trace-event/1.0.3: + /chrome-trace-event@1.0.3: resolution: {integrity: sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==} engines: {node: '>=6.0'} dev: true - /clone-deep/4.0.1: + /clone-deep@4.0.1: resolution: {integrity: sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==} engines: {node: '>=6'} dependencies: @@ -503,51 +526,51 @@ packages: shallow-clone: 3.0.1 dev: true - /color-convert/2.0.1: + /color-convert@2.0.1: resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} engines: {node: '>=7.0.0'} dependencies: color-name: 1.1.4 dev: true - /color-name/1.1.4: + /color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} dev: true - /colorette/2.0.20: + /colorette@2.0.20: resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==} dev: true - /colors/1.4.0: + /colors@1.4.0: resolution: {integrity: sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==} engines: {node: '>=0.1.90'} dev: true - /combined-stream/1.0.8: + /combined-stream@1.0.8: resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} engines: {node: '>= 0.8'} dependencies: delayed-stream: 1.0.0 dev: true - /commander/10.0.1: + /commander@10.0.1: resolution: {integrity: sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==} engines: {node: '>=14'} dev: true - /commander/2.20.3: + /commander@2.20.3: resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==} dev: true - /commondir/1.0.1: + /commondir@1.0.1: resolution: {integrity: sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==} dev: true - /concat-map/0.0.1: + /concat-map@0.0.1: resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} dev: true - /concat-stream/1.6.2: + /concat-stream@1.6.2: resolution: {integrity: sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==} engines: {'0': node >= 0.8} dependencies: @@ -557,7 +580,7 @@ packages: typedarray: 0.0.6 dev: true - /copy-concurrently/1.0.5: + /copy-concurrently@1.0.5: resolution: {integrity: sha512-f2domd9fsVDFtaFcbaRZuYXwtdmnzqbADSwhSWYxYB/Q8zsdUUFMXVRwXGDMWmbEzAn1kdRrtI1T/KTFOL4X2A==} dependencies: aproba: 1.2.0 @@ -568,15 +591,15 @@ packages: run-queue: 1.0.3 dev: true - /core-util-is/1.0.3: + /core-util-is@1.0.3: resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==} dev: true - /create-require/1.1.1: + /create-require@1.1.1: resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==} dev: true - /cross-spawn/7.0.3: + /cross-spawn@7.0.3: resolution: {integrity: sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==} engines: {node: '>= 8'} dependencies: @@ -585,71 +608,71 @@ packages: which: 2.0.2 dev: true - /cssstyle/3.0.0: + /cssstyle@3.0.0: resolution: {integrity: sha512-N4u2ABATi3Qplzf0hWbVCdjenim8F3ojEXpBDF5hBpjzW182MjNGLqfmQ0SkSPeQ+V86ZXgeH8aXj6kayd4jgg==} engines: {node: '>=14'} dependencies: rrweb-cssom: 0.6.0 dev: true - /cyclist/1.0.2: + /cyclist@1.0.2: resolution: {integrity: sha512-0sVXIohTfLqVIW3kb/0n6IiWF3Ifj5nm2XaSrLq2DI6fKIGa2fYAZdk917rUneaeLVpYfFcyXE2ft0fe3remsA==} dev: true - /d3-array/2.12.1: + /d3-array@2.12.1: resolution: {integrity: sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==} dependencies: internmap: 1.0.1 dev: true - /d3-axis/2.1.0: + /d3-axis@2.1.0: resolution: {integrity: sha512-z/G2TQMyuf0X3qP+Mh+2PimoJD41VOCjViJzT0BHeL/+JQAofkiWZbWxlwFGb1N8EN+Cl/CW+MUKbVzr1689Cw==} dev: true - /d3-brush/2.1.0: + /d3-brush@2.1.0: resolution: {integrity: sha512-cHLLAFatBATyIKqZOkk/mDHUbzne2B3ZwxkzMHvFTCZCmLaXDpZRihQSn8UNXTkGD/3lb/W2sQz0etAftmHMJQ==} dependencies: d3-dispatch: 2.0.0 d3-drag: 2.0.0 d3-interpolate: 2.0.1 d3-selection: 2.0.0 - d3-transition: 2.0.0_d3-selection@2.0.0 + d3-transition: 2.0.0(d3-selection@2.0.0) dev: true - /d3-chord/2.0.0: + /d3-chord@2.0.0: resolution: {integrity: sha512-D5PZb7EDsRNdGU4SsjQyKhja8Zgu+SHZfUSO5Ls8Wsn+jsAKUUGkcshLxMg9HDFxG3KqavGWaWkJ8EpU8ojuig==} dependencies: d3-path: 2.0.0 dev: true - /d3-color/2.0.0: + /d3-color@2.0.0: resolution: {integrity: sha512-SPXi0TSKPD4g9tw0NMZFnR95XVgUZiBH+uUTqQuDu1OsE2zomHU7ho0FISciaPvosimixwHFl3WHLGabv6dDgQ==} dev: true - /d3-contour/2.0.0: + /d3-contour@2.0.0: resolution: {integrity: sha512-9unAtvIaNk06UwqBmvsdHX7CZ+NPDZnn8TtNH1myW93pWJkhsV25JcgnYAu0Ck5Veb1DHiCv++Ic5uvJ+h50JA==} dependencies: d3-array: 2.12.1 dev: true - /d3-delaunay/5.3.0: + /d3-delaunay@5.3.0: resolution: {integrity: sha512-amALSrOllWVLaHTnDLHwMIiz0d1bBu9gZXd1FiLfXf8sHcX9jrcj81TVZOqD4UX7MgBZZ07c8GxzEgBpJqc74w==} dependencies: delaunator: 4.0.1 dev: true - /d3-dispatch/2.0.0: + /d3-dispatch@2.0.0: resolution: {integrity: sha512-S/m2VsXI7gAti2pBoLClFFTMOO1HTtT0j99AuXLoGFKO6deHDdnv6ZGTxSTTUTgO1zVcv82fCOtDjYK4EECmWA==} dev: true - /d3-drag/2.0.0: + /d3-drag@2.0.0: resolution: {integrity: sha512-g9y9WbMnF5uqB9qKqwIIa/921RYWzlUDv9Jl1/yONQwxbOfszAWTCm8u7HOTgJgRDXiRZN56cHT9pd24dmXs8w==} dependencies: d3-dispatch: 2.0.0 d3-selection: 2.0.0 dev: true - /d3-dsv/2.0.0: + /d3-dsv@2.0.0: resolution: {integrity: sha512-E+Pn8UJYx9mViuIUkoc93gJGGYut6mSDKy2+XaPwccwkRGlR+LO97L2VCCRjQivTwLHkSnAJG7yo00BWY6QM+w==} hasBin: true dependencies: @@ -658,17 +681,17 @@ packages: rw: 1.3.3 dev: true - /d3-ease/2.0.0: + /d3-ease@2.0.0: resolution: {integrity: sha512-68/n9JWarxXkOWMshcT5IcjbB+agblQUaIsbnXmrzejn2O82n3p2A9R2zEB9HIEFWKFwPAEDDN8gR0VdSAyyAQ==} dev: true - /d3-fetch/2.0.0: + /d3-fetch@2.0.0: resolution: {integrity: sha512-TkYv/hjXgCryBeNKiclrwqZH7Nb+GaOwo3Neg24ZVWA3MKB+Rd+BY84Nh6tmNEMcjUik1CSUWjXYndmeO6F7sw==} dependencies: d3-dsv: 2.0.0 dev: true - /d3-force/2.1.1: + /d3-force@2.1.1: resolution: {integrity: sha512-nAuHEzBqMvpFVMf9OX75d00OxvOXdxY+xECIXjW6Gv8BRrXu6gAWbv/9XKrvfJ5i5DCokDW7RYE50LRoK092ew==} dependencies: d3-dispatch: 2.0.0 @@ -676,50 +699,50 @@ packages: d3-timer: 2.0.0 dev: true - /d3-format/2.0.0: + /d3-format@2.0.0: resolution: {integrity: sha512-Ab3S6XuE/Q+flY96HXT0jOXcM4EAClYFnRGY5zsjRGNy6qCYrQsMffs7cV5Q9xejb35zxW5hf/guKw34kvIKsA==} dev: true - /d3-geo/2.0.2: + /d3-geo@2.0.2: resolution: {integrity: sha512-8pM1WGMLGFuhq9S+FpPURxic+gKzjluCD/CHTuUF3mXMeiCo0i6R0tO1s4+GArRFde96SLcW/kOFRjoAosPsFA==} dependencies: d3-array: 2.12.1 dev: true - /d3-hierarchy/2.0.0: + /d3-hierarchy@2.0.0: resolution: {integrity: sha512-SwIdqM3HxQX2214EG9GTjgmCc/mbSx4mQBn+DuEETubhOw6/U3fmnji4uCVrmzOydMHSO1nZle5gh6HB/wdOzw==} dev: true - /d3-interpolate/2.0.1: + /d3-interpolate@2.0.1: resolution: {integrity: sha512-c5UhwwTs/yybcmTpAVqwSFl6vrQ8JZJoT5F7xNFK9pymv5C0Ymcc9/LIJHtYIggg/yS9YHw8i8O8tgb9pupjeQ==} dependencies: d3-color: 2.0.0 dev: true - /d3-path/2.0.0: + /d3-path@2.0.0: resolution: {integrity: sha512-ZwZQxKhBnv9yHaiWd6ZU4x5BtCQ7pXszEV9CU6kRgwIQVQGLMv1oiL4M+MK/n79sYzsj+gcgpPQSctJUsLN7fA==} dev: true - /d3-polygon/2.0.0: + /d3-polygon@2.0.0: resolution: {integrity: sha512-MsexrCK38cTGermELs0cO1d79DcTsQRN7IWMJKczD/2kBjzNXxLUWP33qRF6VDpiLV/4EI4r6Gs0DAWQkE8pSQ==} dev: true - /d3-quadtree/2.0.0: + /d3-quadtree@2.0.0: resolution: {integrity: sha512-b0Ed2t1UUalJpc3qXzKi+cPGxeXRr4KU9YSlocN74aTzp6R/Ud43t79yLLqxHRWZfsvWXmbDWPpoENK1K539xw==} dev: true - /d3-random/2.2.2: + /d3-random@2.2.2: resolution: {integrity: sha512-0D9P8TRj6qDAtHhRQn6EfdOtHMfsUWanl3yb/84C4DqpZ+VsgfI5iTVRNRbELCfNvRfpMr8OrqqUTQ6ANGCijw==} dev: true - /d3-scale-chromatic/2.0.0: + /d3-scale-chromatic@2.0.0: resolution: {integrity: sha512-LLqy7dJSL8yDy7NRmf6xSlsFZ6zYvJ4BcWFE4zBrOPnQERv9zj24ohnXKRbyi9YHnYV+HN1oEO3iFK971/gkzA==} dependencies: d3-color: 2.0.0 d3-interpolate: 2.0.1 dev: true - /d3-scale/3.3.0: + /d3-scale@3.3.0: resolution: {integrity: sha512-1JGp44NQCt5d1g+Yy+GeOnZP7xHo0ii8zsQp6PGzd+C1/dl0KGsp9A7Mxwp+1D1o4unbTTxVdU/ZOIEBoeZPbQ==} dependencies: d3-array: 2.12.1 @@ -729,33 +752,33 @@ packages: d3-time-format: 3.0.0 dev: true - /d3-selection/2.0.0: + /d3-selection@2.0.0: resolution: {integrity: sha512-XoGGqhLUN/W14NmaqcO/bb1nqjDAw5WtSYb2X8wiuQWvSZUsUVYsOSkOybUrNvcBjaywBdYPy03eXHMXjk9nZA==} dev: true - /d3-shape/2.1.0: + /d3-shape@2.1.0: resolution: {integrity: sha512-PnjUqfM2PpskbSLTJvAzp2Wv4CZsnAgTfcVRTwW03QR3MkXF8Uo7B1y/lWkAsmbKwuecto++4NlsYcvYpXpTHA==} dependencies: d3-path: 2.0.0 dev: true - /d3-time-format/3.0.0: + /d3-time-format@3.0.0: resolution: {integrity: sha512-UXJh6EKsHBTjopVqZBhFysQcoXSv/5yLONZvkQ5Kk3qbwiUYkdX17Xa1PT6U1ZWXGGfB1ey5L8dKMlFq2DO0Ag==} dependencies: d3-time: 2.1.1 dev: true - /d3-time/2.1.1: + /d3-time@2.1.1: resolution: {integrity: sha512-/eIQe/eR4kCQwq7yxi7z4c6qEXf2IYGcjoWB5OOQy4Tq9Uv39/947qlDcN2TLkiTzQWzvnsuYPB9TrWaNfipKQ==} dependencies: d3-array: 2.12.1 dev: true - /d3-timer/2.0.0: + /d3-timer@2.0.0: resolution: {integrity: sha512-TO4VLh0/420Y/9dO3+f9abDEFYeCUr2WZRlxJvbp4HPTQcSylXNiL6yZa9FIUvV1yRiFufl1bszTCLDqv9PWNA==} dev: true - /d3-transition/2.0.0_d3-selection@2.0.0: + /d3-transition@2.0.0(d3-selection@2.0.0): resolution: {integrity: sha512-42ltAGgJesfQE3u9LuuBHNbGrI/AJjNL2OAUdclE70UE6Vy239GCBEYD38uBPoLeNsOhFStGpPI0BAOV+HMxog==} peerDependencies: d3-selection: '2' @@ -768,17 +791,17 @@ packages: d3-timer: 2.0.0 dev: true - /d3-zoom/2.0.0: + /d3-zoom@2.0.0: resolution: {integrity: sha512-fFg7aoaEm9/jf+qfstak0IYpnesZLiMX6GZvXtUSdv8RH2o4E2qeelgdU09eKS6wGuiGMfcnMI0nTIqWzRHGpw==} dependencies: d3-dispatch: 2.0.0 d3-drag: 2.0.0 d3-interpolate: 2.0.1 d3-selection: 2.0.0 - d3-transition: 2.0.0_d3-selection@2.0.0 + d3-transition: 2.0.0(d3-selection@2.0.0) dev: true - /d3/6.7.0: + /d3@6.7.0: resolution: {integrity: sha512-hNHRhe+yCDLUG6Q2LwvR/WdNFPOJQ5VWqsJcwIYVeI401+d2/rrCjxSXkiAdIlpx7/73eApFB4Olsmh3YN7a6g==} dependencies: d3-array: 2.12.1 @@ -809,11 +832,11 @@ packages: d3-time: 2.1.1 d3-time-format: 3.0.0 d3-timer: 2.0.0 - d3-transition: 2.0.0_d3-selection@2.0.0 + d3-transition: 2.0.0(d3-selection@2.0.0) d3-zoom: 2.0.0 dev: true - /data-urls/4.0.0: + /data-urls@4.0.0: resolution: {integrity: sha512-/mMTei/JXPqvFqQtfyTowxmJVwr2PVAeCcDxyFf6LhoOu/09TX2OX3kb2wzi4DMXcfj4OItwDOnhl5oziPnT6g==} engines: {node: '>=14'} dependencies: @@ -822,7 +845,7 @@ packages: whatwg-url: 12.0.1 dev: true - /debug/3.2.7: + /debug@3.2.7: resolution: {integrity: sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==} peerDependencies: supports-color: '*' @@ -833,7 +856,7 @@ packages: ms: 2.1.2 dev: true - /debug/4.3.4: + /debug@4.3.4: resolution: {integrity: sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==} engines: {node: '>=6.0'} peerDependencies: @@ -845,32 +868,36 @@ packages: ms: 2.1.2 dev: true - /decimal.js/10.4.3: + /decimal.js@10.4.3: resolution: {integrity: sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==} dev: true - /delaunator/4.0.1: + /declaration-bundler-webpack-plugin@1.0.3: + resolution: {integrity: sha512-bgeoSOZYTOOdiNUZd/U8K6Z+6IrM/X+DgUcm3/VI1l130lzOBeL+ObetjIkKksxcj0zUJbLaFRFumFGYDOQ9fg==} + dev: true + + /delaunator@4.0.1: resolution: {integrity: sha512-WNPWi1IRKZfCt/qIDMfERkDp93+iZEmOxN2yy4Jg+Xhv8SLk2UTqqbe1sfiipn0and9QrE914/ihdx82Y/Giag==} dev: true - /delayed-stream/1.0.0: + /delayed-stream@1.0.0: resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} engines: {node: '>=0.4.0'} dev: true - /diff/4.0.2: + /diff@4.0.2: resolution: {integrity: sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==} engines: {node: '>=0.3.1'} dev: true - /domexception/4.0.0: + /domexception@4.0.0: resolution: {integrity: sha512-A2is4PLG+eeSfoTMA95/s4pvAoSo2mKtiM5jlHkAVewmiO8ISFTFKZjH7UAM1Atli/OT/7JHOrJRJiMKUZKYBw==} engines: {node: '>=12'} dependencies: webidl-conversions: 7.0.0 dev: true - /duplexify/3.7.1: + /duplexify@3.7.1: resolution: {integrity: sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g==} dependencies: end-of-stream: 1.4.4 @@ -879,17 +906,17 @@ packages: stream-shift: 1.0.1 dev: true - /electron-to-chromium/1.4.543: + /electron-to-chromium@1.4.543: resolution: {integrity: sha512-t2ZP4AcGE0iKCCQCBx/K2426crYdxD3YU6l0uK2EO3FZH0pbC4pFz/sZm2ruZsND6hQBTcDWWlo/MLpiOdif5g==} dev: true - /end-of-stream/1.4.4: + /end-of-stream@1.4.4: resolution: {integrity: sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==} dependencies: once: 1.4.0 dev: true - /enhanced-resolve/5.15.0: + /enhanced-resolve@5.15.0: resolution: {integrity: sha512-LXYT42KJ7lpIKECr2mAXIaMldcNCh/7E0KBKOu4KSfkHmP+mZmSs+8V5gBAqisWBy0OO4W5Oyys0GO1Y8KtdKg==} engines: {node: '>=10.13.0'} dependencies: @@ -897,41 +924,41 @@ packages: tapable: 2.2.1 dev: true - /entities/4.5.0: + /entities@4.5.0: resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} engines: {node: '>=0.12'} dev: true - /envinfo/7.10.0: + /envinfo@7.10.0: resolution: {integrity: sha512-ZtUjZO6l5mwTHvc1L9+1q5p/R3wTopcfqMW8r5t8SJSKqeVI/LtajORwRFEKpEFuekjD0VBjwu1HMxL4UalIRw==} engines: {node: '>=4'} hasBin: true dev: true - /errno/0.1.8: + /errno@0.1.8: resolution: {integrity: sha512-dJ6oBr5SQ1VSd9qkk7ByRgb/1SH4JZjCHSW/mr63/QcXO9zLVxvJ6Oy13nio03rxpSnVDDjFor75SjVeZWPW/A==} hasBin: true dependencies: prr: 1.0.1 dev: true - /es-module-lexer/1.3.1: + /es-module-lexer@1.3.1: resolution: {integrity: sha512-JUFAyicQV9mXc3YRxPnDlrfBKpqt6hUYzz9/boprUJHs4e4KVr3XwOF70doO6gwXUor6EWZJAyWAfKki84t20Q==} dev: true - /escalade/3.1.1: + /escalade@3.1.1: resolution: {integrity: sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==} engines: {node: '>=6'} dev: true - /eslint-plugin-tsdoc/0.2.17: + /eslint-plugin-tsdoc@0.2.17: resolution: {integrity: sha512-xRmVi7Zx44lOBuYqG8vzTXuL6IdGOeF9nHX17bjJ8+VE6fsxpdGem0/SBTmAwgYMKYB1WBkqRJVQ+n8GK041pA==} dependencies: '@microsoft/tsdoc': 0.14.2 '@microsoft/tsdoc-config': 0.16.2 dev: true - /eslint-scope/5.1.1: + /eslint-scope@5.1.1: resolution: {integrity: sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==} engines: {node: '>=8.0.0'} dependencies: @@ -939,53 +966,53 @@ packages: estraverse: 4.3.0 dev: true - /esrecurse/4.3.0: + /esrecurse@4.3.0: resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} engines: {node: '>=4.0'} dependencies: estraverse: 5.3.0 dev: true - /estraverse/4.3.0: + /estraverse@4.3.0: resolution: {integrity: sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==} engines: {node: '>=4.0'} dev: true - /estraverse/5.3.0: + /estraverse@5.3.0: resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} engines: {node: '>=4.0'} dev: true - /events/3.3.0: + /events@3.3.0: resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==} engines: {node: '>=0.8.x'} dev: true - /fast-deep-equal/3.1.3: + /fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} dev: true - /fast-json-stable-stringify/2.1.0: + /fast-json-stable-stringify@2.1.0: resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} dev: true - /fastest-levenshtein/1.0.16: + /fastest-levenshtein@1.0.16: resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==} engines: {node: '>= 4.9.1'} dev: true - /figgy-pudding/3.5.2: + /figgy-pudding@3.5.2: resolution: {integrity: sha512-0btnI/H8f2pavGMN8w40mlSKOfTK2SVJmBfBeVIj3kNw0swwgzyRq0d5TJVOwodFmtvpPeWPN/MCcfuWF0Ezbw==} dev: true - /fill-range/7.0.1: + /fill-range@7.0.1: resolution: {integrity: sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==} engines: {node: '>=8'} dependencies: to-regex-range: 5.0.1 dev: true - /find-cache-dir/2.1.0: + /find-cache-dir@2.1.0: resolution: {integrity: sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ==} engines: {node: '>=6'} dependencies: @@ -994,14 +1021,14 @@ packages: pkg-dir: 3.0.0 dev: true - /find-up/3.0.0: + /find-up@3.0.0: resolution: {integrity: sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==} engines: {node: '>=6'} dependencies: locate-path: 3.0.0 dev: true - /find-up/4.1.0: + /find-up@4.1.0: resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==} engines: {node: '>=8'} dependencies: @@ -1009,14 +1036,14 @@ packages: path-exists: 4.0.0 dev: true - /flush-write-stream/1.1.1: + /flush-write-stream@1.1.1: resolution: {integrity: sha512-3Z4XhFZ3992uIq0XOqb9AreonueSYphE6oYbpt5+3u06JWklbsPkNv3ZKkP9Bz/r+1MWCaMoSQ28P85+1Yc77w==} dependencies: inherits: 2.0.4 readable-stream: 2.3.8 dev: true - /form-data/4.0.0: + /form-data@4.0.0: resolution: {integrity: sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==} engines: {node: '>= 6'} dependencies: @@ -1025,14 +1052,14 @@ packages: mime-types: 2.1.35 dev: true - /from2/2.3.0: + /from2@2.3.0: resolution: {integrity: sha512-OMcX/4IC/uqEPVgGeyfN22LJk6AZrMkRZHxcHBMBvHScDGgwTm2GT2Wkgtocyd3JfZffjj2kYUDXXII0Fk9W0g==} dependencies: inherits: 2.0.4 readable-stream: 2.3.8 dev: true - /fs-extra/11.1.1: + /fs-extra@11.1.1: resolution: {integrity: sha512-MGIE4HOvQCeUCzmlHs0vXpih4ysz4wg9qiSAu6cd42lVwPbTM1TjV7RusoyQqMmk/95gdQZX72u+YW+c3eEpFQ==} engines: {node: '>=14.14'} dependencies: @@ -1041,7 +1068,7 @@ packages: universalify: 2.0.0 dev: true - /fs-extra/9.1.0: + /fs-extra@9.1.0: resolution: {integrity: sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==} engines: {node: '>=10'} dependencies: @@ -1051,7 +1078,7 @@ packages: universalify: 2.0.0 dev: true - /fs-write-stream-atomic/1.0.10: + /fs-write-stream-atomic@1.0.10: resolution: {integrity: sha512-gehEzmPn2nAwr39eay+x3X34Ra+M2QlVUTLhkXPjWdeO8RF9kszk116avgBJM3ZyNHgHXBNx+VmPaFC36k0PzA==} dependencies: graceful-fs: 4.2.11 @@ -1060,20 +1087,20 @@ packages: readable-stream: 2.3.8 dev: true - /fs.realpath/1.0.0: + /fs.realpath@1.0.0: resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} dev: true - /get-npm-tarball-url/2.0.3: + /get-npm-tarball-url@2.0.3: resolution: {integrity: sha512-R/PW6RqyaBQNWYaSyfrh54/qtcnOp22FHCCiRhSSZj0FP3KQWCsxxt0DzIdVTbwTqe9CtQfvl/FPD4UIPt4pqw==} engines: {node: '>=12.17'} dev: true - /glob-to-regexp/0.4.1: + /glob-to-regexp@0.4.1: resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==} dev: true - /glob/7.2.3: + /glob@7.2.3: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} dependencies: fs.realpath: 1.0.0 @@ -1084,11 +1111,11 @@ packages: path-is-absolute: 1.0.1 dev: true - /graceful-fs/4.2.11: + /graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} dev: true - /handlebars/4.7.8: + /handlebars@4.7.8: resolution: {integrity: sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ==} engines: {node: '>=0.4.7'} hasBin: true @@ -1101,24 +1128,24 @@ packages: uglify-js: 3.17.4 dev: true - /has-flag/4.0.0: + /has-flag@4.0.0: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} dev: true - /has/1.0.4: + /has@1.0.4: resolution: {integrity: sha512-qdSAmqLF6209RFj4VVItywPMbm3vWylknmB3nvNiUIs72xAimcM8nVYxYr7ncvZq5qzk9MKIZR8ijqD/1QuYjQ==} engines: {node: '>= 0.4.0'} dev: true - /html-encoding-sniffer/3.0.0: + /html-encoding-sniffer@3.0.0: resolution: {integrity: sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==} engines: {node: '>=12'} dependencies: whatwg-encoding: 2.0.0 dev: true - /http-proxy-agent/5.0.0: + /http-proxy-agent@5.0.0: resolution: {integrity: sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==} engines: {node: '>= 6'} dependencies: @@ -1129,7 +1156,7 @@ packages: - supports-color dev: true - /https-proxy-agent/5.0.1: + /https-proxy-agent@5.0.1: resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==} engines: {node: '>= 6'} dependencies: @@ -1139,25 +1166,25 @@ packages: - supports-color dev: true - /iconv-lite/0.4.24: + /iconv-lite@0.4.24: resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==} engines: {node: '>=0.10.0'} dependencies: safer-buffer: 2.1.2 dev: true - /iconv-lite/0.6.3: + /iconv-lite@0.6.3: resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} engines: {node: '>=0.10.0'} dependencies: safer-buffer: 2.1.2 dev: true - /iferr/0.1.5: + /iferr@0.1.5: resolution: {integrity: sha512-DUNFN5j7Tln0D+TxzloUjKB+CtVu6myn0JEFak6dG18mNt9YkQ6lzGCdafwofISZ1lLF3xRHJ98VKy9ynkcFaA==} dev: true - /import-local/3.1.0: + /import-local@3.1.0: resolution: {integrity: sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==} engines: {node: '>=8'} hasBin: true @@ -1166,81 +1193,81 @@ packages: resolve-cwd: 3.0.0 dev: true - /imurmurhash/0.1.4: + /imurmurhash@0.1.4: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} engines: {node: '>=0.8.19'} dev: true - /infer-owner/1.0.4: + /infer-owner@1.0.4: resolution: {integrity: sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==} dev: true - /inflight/1.0.6: + /inflight@1.0.6: resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} dependencies: once: 1.4.0 wrappy: 1.0.2 dev: true - /inherits/2.0.4: + /inherits@2.0.4: resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} dev: true - /internmap/1.0.1: + /internmap@1.0.1: resolution: {integrity: sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==} dev: true - /interpret/1.4.0: + /interpret@1.4.0: resolution: {integrity: sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==} engines: {node: '>= 0.10'} dev: true - /interpret/3.1.1: + /interpret@3.1.1: resolution: {integrity: sha512-6xwYfHbajpoF0xLW+iwLkhwgvLoZDfjYfoFNu8ftMoXINzwuymNLd9u/KmwtdT2GbR+/Cz66otEGEVVUHX9QLQ==} engines: {node: '>=10.13.0'} dev: true - /is-core-module/2.13.0: + /is-core-module@2.13.0: resolution: {integrity: sha512-Z7dk6Qo8pOCp3l4tsX2C5ZVas4V+UxwQodwZhLopL91TX8UyyHEXafPcyoeeWuLrwzHcr3igO78wNLwHJHsMCQ==} dependencies: has: 1.0.4 dev: true - /is-number/7.0.0: + /is-number@7.0.0: resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} engines: {node: '>=0.12.0'} dev: true - /is-plain-object/2.0.4: + /is-plain-object@2.0.4: resolution: {integrity: sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==} engines: {node: '>=0.10.0'} dependencies: isobject: 3.0.1 dev: true - /is-potential-custom-element-name/1.0.1: + /is-potential-custom-element-name@1.0.1: resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} dev: true - /is-wsl/1.1.0: + /is-wsl@1.1.0: resolution: {integrity: sha512-gfygJYZ2gLTDlmbWMI0CE2MwnFzSN/2SZfkMlItC4K/JBlsWVDB0bO6XhqcY13YXE7iMcAJnzTCJjPiTeJJ0Mw==} engines: {node: '>=4'} dev: true - /isarray/1.0.0: + /isarray@1.0.0: resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==} dev: true - /isexe/2.0.0: + /isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} dev: true - /isobject/3.0.1: + /isobject@3.0.1: resolution: {integrity: sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==} engines: {node: '>=0.10.0'} dev: true - /jest-worker/27.5.1: + /jest-worker@27.5.1: resolution: {integrity: sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==} engines: {node: '>= 10.13.0'} dependencies: @@ -1249,11 +1276,11 @@ packages: supports-color: 8.1.1 dev: true - /jju/1.4.0: + /jju@1.4.0: resolution: {integrity: sha512-8wb9Yw966OSxApiCt0K3yNJL8pnNeIv+OEq2YMidz4FKP6nonSRoOXc80iXY4JaN2FC11B9qsNmDsm+ZOfMROA==} dev: true - /jsdom/22.1.0: + /jsdom@22.1.0: resolution: {integrity: sha512-/9AVW7xNbsBv6GfWho4TTNjEo9fe6Zhf9O7s0Fhhr3u+awPwAJMKwAMXnkk5vBxflqLW9hTHX/0cs+P3gW+cQw==} engines: {node: '>=16'} peerDependencies: @@ -1291,19 +1318,19 @@ packages: - utf-8-validate dev: true - /json-parse-even-better-errors/2.3.1: + /json-parse-even-better-errors@2.3.1: resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==} dev: true - /json-schema-traverse/0.4.1: + /json-schema-traverse@0.4.1: resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} dev: true - /jsonc-parser/3.2.0: + /jsonc-parser@3.2.0: resolution: {integrity: sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==} dev: true - /jsonfile/6.1.0: + /jsonfile@6.1.0: resolution: {integrity: sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==} dependencies: universalify: 2.0.0 @@ -1311,17 +1338,17 @@ packages: graceful-fs: 4.2.11 dev: true - /kind-of/6.0.3: + /kind-of@6.0.3: resolution: {integrity: sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==} engines: {node: '>=0.10.0'} dev: true - /loader-runner/4.3.0: + /loader-runner@4.3.0: resolution: {integrity: sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==} engines: {node: '>=6.11.5'} dev: true - /locate-path/3.0.0: + /locate-path@3.0.0: resolution: {integrity: sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==} engines: {node: '>=6'} dependencies: @@ -1329,35 +1356,35 @@ packages: path-exists: 3.0.0 dev: true - /locate-path/5.0.0: + /locate-path@5.0.0: resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==} engines: {node: '>=8'} dependencies: p-locate: 4.1.0 dev: true - /lodash/4.17.21: + /lodash@4.17.21: resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==} dev: true - /lru-cache/5.1.1: + /lru-cache@5.1.1: resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} dependencies: yallist: 3.1.1 dev: true - /lru-cache/6.0.0: + /lru-cache@6.0.0: resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} engines: {node: '>=10'} dependencies: yallist: 4.0.0 dev: true - /lunr/2.3.9: + /lunr@2.3.9: resolution: {integrity: sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==} dev: true - /make-dir/2.1.0: + /make-dir@2.1.0: resolution: {integrity: sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==} engines: {node: '>=6'} dependencies: @@ -1365,27 +1392,27 @@ packages: semver: 5.7.2 dev: true - /make-error/1.3.6: + /make-error@1.3.6: resolution: {integrity: sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==} dev: true - /marked/2.0.7: + /marked@2.0.7: resolution: {integrity: sha512-BJXxkuIfJchcXOJWTT2DOL+yFWifFv2yGYOUzvXg8Qz610QKw+sHCvTMYwA+qWGhlA2uivBezChZ/pBy1tWdkQ==} engines: {node: '>= 8.16.2'} hasBin: true dev: true - /marked/4.3.0: + /marked@4.3.0: resolution: {integrity: sha512-PRsaiG84bK+AMvxziE/lCFss8juXjNaWzVbN5tXAm4XjeaS9NAHhop+PjQxz2A9h8Q4M/xGmzP8vqNwy6JeK0A==} engines: {node: '>= 12'} hasBin: true dev: true - /merge-stream/2.0.0: + /merge-stream@2.0.0: resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} dev: true - /micromatch/4.0.5: + /micromatch@4.0.5: resolution: {integrity: sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==} engines: {node: '>=8.6'} dependencies: @@ -1393,36 +1420,36 @@ packages: picomatch: 2.3.1 dev: true - /mime-db/1.52.0: + /mime-db@1.52.0: resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} engines: {node: '>= 0.6'} dev: true - /mime-types/2.1.35: + /mime-types@2.1.35: resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} engines: {node: '>= 0.6'} dependencies: mime-db: 1.52.0 dev: true - /minimatch/3.1.2: + /minimatch@3.1.2: resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==} dependencies: brace-expansion: 1.1.11 dev: true - /minimatch/9.0.3: + /minimatch@9.0.3: resolution: {integrity: sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==} engines: {node: '>=16 || 14 >=14.17'} dependencies: brace-expansion: 2.0.1 dev: true - /minimist/1.2.8: + /minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} dev: true - /mississippi/3.0.0: + /mississippi@3.0.0: resolution: {integrity: sha512-x471SsVjUtBRtcvd4BzKE9kFC+/2TeWgKCgw0bZcw1b9l2X3QX5vCWgF+KaZaYm87Ss//rHnWryupDrgLvmSkA==} engines: {node: '>=4.0.0'} dependencies: @@ -1438,14 +1465,14 @@ packages: through2: 2.0.5 dev: true - /mkdirp/0.5.6: + /mkdirp@0.5.6: resolution: {integrity: sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==} hasBin: true dependencies: minimist: 1.2.8 dev: true - /move-concurrently/1.0.1: + /move-concurrently@1.0.1: resolution: {integrity: sha512-hdrFxZOycD/g6A6SoI2bB5NA/5NEqD0569+S47WZhPvm46sD50ZHdYaFmnua5lndde9rCHGjmfK7Z8BuCt/PcQ==} dependencies: aproba: 1.2.0 @@ -1456,11 +1483,11 @@ packages: run-queue: 1.0.3 dev: true - /ms/2.1.2: + /ms@2.1.2: resolution: {integrity: sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==} dev: true - /needle/3.2.0: + /needle@3.2.0: resolution: {integrity: sha512-oUvzXnyLiVyVGoianLijF9O/RecZUf7TkBfimjGrLM4eQhXyeJwM6GeAWccwfQ9aa4gMCZKqhAOuLaMIcQxajQ==} engines: {node: '>= 4.4.x'} hasBin: true @@ -1472,56 +1499,56 @@ packages: - supports-color dev: true - /neo-async/2.6.2: + /neo-async@2.6.2: resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==} dev: true - /node-releases/2.0.13: + /node-releases@2.0.13: resolution: {integrity: sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==} dev: true - /nwsapi/2.2.7: + /nwsapi@2.2.7: resolution: {integrity: sha512-ub5E4+FBPKwAZx0UwIQOjYWGHTEq5sPqHQNRN8Z9e4A7u3Tj1weLJsL59yH9vmvqEtBHaOmT6cYQKIZOxp35FQ==} dev: true - /ohm-js/17.1.0: + /ohm-js@17.1.0: resolution: {integrity: sha512-xc3B5dgAjTBQGHaH7B58M2Pmv6WvzrJ/3/7LeUzXNg0/sY3jQPdSd/S2SstppaleO77rifR1tyhdfFGNIwxf2Q==} engines: {node: '>=0.12.1'} dev: false - /once/1.4.0: + /once@1.4.0: resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} dependencies: wrappy: 1.0.2 dev: true - /p-limit/2.3.0: + /p-limit@2.3.0: resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==} engines: {node: '>=6'} dependencies: p-try: 2.2.0 dev: true - /p-locate/3.0.0: + /p-locate@3.0.0: resolution: {integrity: sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==} engines: {node: '>=6'} dependencies: p-limit: 2.3.0 dev: true - /p-locate/4.1.0: + /p-locate@4.1.0: resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==} engines: {node: '>=8'} dependencies: p-limit: 2.3.0 dev: true - /p-try/2.2.0: + /p-try@2.2.0: resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} engines: {node: '>=6'} dev: true - /parallel-transform/1.2.0: + /parallel-transform@1.2.0: resolution: {integrity: sha512-P2vSmIu38uIlvdcU7fDkyrxj33gTUy/ABO5ZUbGowxNCopBq/OoD42bP4UmMrJoPyk4Uqf0mu3mtWBhHCZD8yg==} dependencies: cyclist: 1.0.2 @@ -1529,74 +1556,74 @@ packages: readable-stream: 2.3.8 dev: true - /parse5/7.1.2: + /parse5@7.1.2: resolution: {integrity: sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==} dependencies: entities: 4.5.0 dev: true - /path-exists/3.0.0: + /path-exists@3.0.0: resolution: {integrity: sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ==} engines: {node: '>=4'} dev: true - /path-exists/4.0.0: + /path-exists@4.0.0: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} dev: true - /path-is-absolute/1.0.1: + /path-is-absolute@1.0.1: resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} engines: {node: '>=0.10.0'} dev: true - /path-key/3.1.1: + /path-key@3.1.1: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} dev: true - /path-parse/1.0.7: + /path-parse@1.0.7: resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} dev: true - /picocolors/1.0.0: + /picocolors@1.0.0: resolution: {integrity: sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==} dev: true - /picomatch/2.3.1: + /picomatch@2.3.1: resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==} engines: {node: '>=8.6'} dev: true - /pify/4.0.1: + /pify@4.0.1: resolution: {integrity: sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==} engines: {node: '>=6'} dev: true - /pkg-dir/3.0.0: + /pkg-dir@3.0.0: resolution: {integrity: sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==} engines: {node: '>=6'} dependencies: find-up: 3.0.0 dev: true - /pkg-dir/4.2.0: + /pkg-dir@4.2.0: resolution: {integrity: sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==} engines: {node: '>=8'} dependencies: find-up: 4.1.0 dev: true - /process-nextick-args/2.0.1: + /process-nextick-args@2.0.1: resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==} dev: true - /progress/2.0.3: + /progress@2.0.3: resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==} engines: {node: '>=0.4.0'} dev: true - /promise-inflight/1.0.1_bluebird@3.7.2: + /promise-inflight@1.0.1(bluebird@3.7.2): resolution: {integrity: sha512-6zWPyEOFaQBJYcGMHBKTKJ3u6TBsnMFOIZSa6ce1e/ZrrsOlnHRHbabMjLiBYKp+n44X9eUI6VUPaukCXHuG4g==} peerDependencies: bluebird: '*' @@ -1607,29 +1634,29 @@ packages: bluebird: 3.7.2 dev: true - /prr/1.0.1: + /prr@1.0.1: resolution: {integrity: sha512-yPw4Sng1gWghHQWj0B3ZggWUm4qVbPwPFcRG8KyxiU7J2OHFSoEHKS+EZ3fv5l1t9CyCiop6l/ZYeWbrgoQejw==} dev: true - /psl/1.9.0: + /psl@1.9.0: resolution: {integrity: sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==} dev: true - /pump/2.0.1: + /pump@2.0.1: resolution: {integrity: sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==} dependencies: end-of-stream: 1.4.4 once: 1.4.0 dev: true - /pump/3.0.0: + /pump@3.0.0: resolution: {integrity: sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==} dependencies: end-of-stream: 1.4.4 once: 1.4.0 dev: true - /pumpify/1.5.1: + /pumpify@1.5.1: resolution: {integrity: sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ==} dependencies: duplexify: 3.7.1 @@ -1637,22 +1664,22 @@ packages: pump: 2.0.1 dev: true - /punycode/2.3.0: + /punycode@2.3.0: resolution: {integrity: sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==} engines: {node: '>=6'} dev: true - /querystringify/2.2.0: + /querystringify@2.2.0: resolution: {integrity: sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==} dev: true - /randombytes/2.1.0: + /randombytes@2.1.0: resolution: {integrity: sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==} dependencies: safe-buffer: 5.2.1 dev: true - /readable-stream/2.3.8: + /readable-stream@2.3.8: resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==} dependencies: core-util-is: 1.0.3 @@ -1664,44 +1691,44 @@ packages: util-deprecate: 1.0.2 dev: true - /rechoir/0.6.2: + /rechoir@0.6.2: resolution: {integrity: sha512-HFM8rkZ+i3zrV+4LQjwQ0W+ez98pApMGM3HUrN04j3CqzPOzl9nmP15Y8YXNm8QHGv/eacOVEjqhmWpkRV0NAw==} engines: {node: '>= 0.10'} dependencies: resolve: 1.22.6 dev: true - /rechoir/0.8.0: + /rechoir@0.8.0: resolution: {integrity: sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==} engines: {node: '>= 10.13.0'} dependencies: resolve: 1.22.6 dev: true - /requires-port/1.0.0: + /requires-port@1.0.0: resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==} dev: true - /resolve-cwd/3.0.0: + /resolve-cwd@3.0.0: resolution: {integrity: sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==} engines: {node: '>=8'} dependencies: resolve-from: 5.0.0 dev: true - /resolve-from/5.0.0: + /resolve-from@5.0.0: resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} engines: {node: '>=8'} dev: true - /resolve/1.19.0: + /resolve@1.19.0: resolution: {integrity: sha512-rArEXAgsBG4UgRGcynxWIWKFvh/XZCcS8UJdHhwy91zwAvCZIbcs+vAbflgBnNjYMs/i/i+/Ux6IZhML1yPvxg==} dependencies: is-core-module: 2.13.0 path-parse: 1.0.7 dev: true - /resolve/1.22.6: + /resolve@1.22.6: resolution: {integrity: sha512-njhxM7mV12JfufShqGy3Rz8j11RPdLy4xi15UurGJeoHLfJpVXKdh3ueuOqbYUcDZnffr6X739JBo5LzyahEsw==} hasBin: true dependencies: @@ -1710,74 +1737,74 @@ packages: supports-preserve-symlinks-flag: 1.0.0 dev: true - /rimraf/2.7.1: + /rimraf@2.7.1: resolution: {integrity: sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==} hasBin: true dependencies: glob: 7.2.3 dev: true - /rrweb-cssom/0.6.0: + /rrweb-cssom@0.6.0: resolution: {integrity: sha512-APM0Gt1KoXBz0iIkkdB/kfvGOwC4UuJFeG/c+yV7wSc7q96cG/kJ0HiYCnzivD9SB53cLV1MlHFNfOuPaadYSw==} dev: true - /run-queue/1.0.3: + /run-queue@1.0.3: resolution: {integrity: sha512-ntymy489o0/QQplUDnpYAYUsO50K9SBrIVaKCWDOJzYJts0f9WH9RFJkyagebkw5+y1oi00R7ynNW/d12GBumg==} dependencies: aproba: 1.2.0 dev: true - /rw/1.3.3: + /rw@1.3.3: resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==} dev: true - /safe-buffer/5.1.2: + /safe-buffer@5.1.2: resolution: {integrity: sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==} dev: true - /safe-buffer/5.2.1: + /safe-buffer@5.2.1: resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} dev: true - /safer-buffer/2.1.2: + /safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} dev: true - /sax/1.3.0: + /sax@1.3.0: resolution: {integrity: sha512-0s+oAmw9zLl1V1cS9BtZN7JAd0cW5e0QH4W3LWEK6a4LaLEA2OTpGYWDY+6XasBLtz6wkm3u1xRw95mRuJ59WA==} dev: true - /saxes/6.0.0: + /saxes@6.0.0: resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} engines: {node: '>=v12.22.7'} dependencies: xmlchars: 2.2.0 dev: true - /schema-utils/1.0.0: + /schema-utils@1.0.0: resolution: {integrity: sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==} engines: {node: '>= 4'} dependencies: ajv: 6.12.6 - ajv-errors: 1.0.1_ajv@6.12.6 - ajv-keywords: 3.5.2_ajv@6.12.6 + ajv-errors: 1.0.1(ajv@6.12.6) + ajv-keywords: 3.5.2(ajv@6.12.6) dev: true - /schema-utils/3.3.0: + /schema-utils@3.3.0: resolution: {integrity: sha512-pN/yOAvcC+5rQ5nERGuwrjLlYvLTbCibnZ1I7B1LaiAz9BRBlE9GMgE/eqV30P7aJQUf7Ddimy/RsbYO/GrVGg==} engines: {node: '>= 10.13.0'} dependencies: '@types/json-schema': 7.0.13 ajv: 6.12.6 - ajv-keywords: 3.5.2_ajv@6.12.6 + ajv-keywords: 3.5.2(ajv@6.12.6) dev: true - /semver/5.7.2: + /semver@5.7.2: resolution: {integrity: sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==} hasBin: true dev: true - /semver/7.5.4: + /semver@7.5.4: resolution: {integrity: sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==} engines: {node: '>=10'} hasBin: true @@ -1785,36 +1812,36 @@ packages: lru-cache: 6.0.0 dev: true - /serialize-javascript/1.9.1: + /serialize-javascript@1.9.1: resolution: {integrity: sha512-0Vb/54WJ6k5v8sSWN09S0ora+Hnr+cX40r9F170nT+mSkaxltoE/7R3OrIdBSUv1OoiobH1QoWQbCnAO+e8J1A==} dev: true - /serialize-javascript/6.0.1: + /serialize-javascript@6.0.1: resolution: {integrity: sha512-owoXEFjWRllis8/M1Q+Cw5k8ZH40e3zhp/ovX+Xr/vi1qj6QesbyXXViFbpNvWvPNAD62SutwEXavefrLJWj7w==} dependencies: randombytes: 2.1.0 dev: true - /shallow-clone/3.0.1: + /shallow-clone@3.0.1: resolution: {integrity: sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==} engines: {node: '>=8'} dependencies: kind-of: 6.0.3 dev: true - /shebang-command/2.0.0: + /shebang-command@2.0.0: resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} engines: {node: '>=8'} dependencies: shebang-regex: 3.0.0 dev: true - /shebang-regex/3.0.0: + /shebang-regex@3.0.0: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} dev: true - /shelljs/0.8.5: + /shelljs@0.8.5: resolution: {integrity: sha512-TiwcRcrkhHvbrZbnRcFYMLl30Dfov3HKqzp5tO5b4pt6G/SezKcYhmDg15zXVBswHmctSAQKznqNW2LO5tTDow==} engines: {node: '>=4'} hasBin: true @@ -1824,7 +1851,7 @@ packages: rechoir: 0.6.2 dev: true - /shiki/0.14.4: + /shiki@0.14.4: resolution: {integrity: sha512-IXCRip2IQzKwxArNNq1S+On4KPML3Yyn8Zzs/xRgcgOWIr8ntIK3IKzjFPfjy/7kt9ZMjc+FItfqHRBg8b6tNQ==} dependencies: ansi-sequence-parser: 1.1.1 @@ -1833,7 +1860,7 @@ packages: vscode-textmate: 8.0.0 dev: true - /shiki/0.9.15: + /shiki@0.9.15: resolution: {integrity: sha512-/Y0z9IzhJ8nD9nbceORCqu6NgT9X6I8Fk8c3SICHI5NbZRLdZYFaB233gwct9sU0vvSypyaL/qaKvzyQGJBZSw==} dependencies: jsonc-parser: 3.2.0 @@ -1841,100 +1868,100 @@ packages: vscode-textmate: 5.2.0 dev: true - /source-list-map/2.0.1: + /source-list-map@2.0.1: resolution: {integrity: sha512-qnQ7gVMxGNxsiL4lEuJwe/To8UnK7fAnmbGEEH8RpLouuKbeEm0lhbQVFIrNSuB+G7tVrAlVsZgETT5nljf+Iw==} dev: true - /source-map-support/0.5.21: + /source-map-support@0.5.21: resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} dependencies: buffer-from: 1.1.2 source-map: 0.6.1 dev: true - /source-map/0.6.1: + /source-map@0.6.1: resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} engines: {node: '>=0.10.0'} dev: true - /source-map/0.7.4: + /source-map@0.7.4: resolution: {integrity: sha512-l3BikUxvPOcn5E74dZiq5BGsTb5yEwhaTSzccU6t4sDOH8NWJCstKO5QT2CvtFoK6F0saL7p9xHAqHOlCPJygA==} engines: {node: '>= 8'} dev: true - /spdx-exceptions/2.3.0: + /spdx-exceptions@2.3.0: resolution: {integrity: sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A==} dev: true - /spdx-expression-parse/3.0.1: + /spdx-expression-parse@3.0.1: resolution: {integrity: sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==} dependencies: spdx-exceptions: 2.3.0 spdx-license-ids: 3.0.16 dev: true - /spdx-expression-validate/2.0.0: + /spdx-expression-validate@2.0.0: resolution: {integrity: sha512-b3wydZLM+Tc6CFvaRDBOF9d76oGIHNCLYFeHbftFXUWjnfZWganmDmvtM5sm1cRwJc/VDBMLyGGrsLFd1vOxbg==} dependencies: spdx-expression-parse: 3.0.1 dev: true - /spdx-license-ids/3.0.16: + /spdx-license-ids@3.0.16: resolution: {integrity: sha512-eWN+LnM3GR6gPu35WxNgbGl8rmY1AEmoMDvL/QD6zYmPWgywxWqJWNdLGT+ke8dKNWrcYgYjPpG5gbTfghP8rw==} dev: true - /ssri/6.0.2: + /ssri@6.0.2: resolution: {integrity: sha512-cepbSq/neFK7xB6A50KHN0xHDotYzq58wWCa5LeWqnPrHG8GzfEjO/4O8kpmcGW+oaxkvhEJCWgbgNk4/ZV93Q==} dependencies: figgy-pudding: 3.5.2 dev: true - /stream-each/1.2.3: + /stream-each@1.2.3: resolution: {integrity: sha512-vlMC2f8I2u/bZGqkdfLQW/13Zihpej/7PmSiMQsbYddxuTsJp8vRe2x2FvVExZg7FaOds43ROAuFJwPR4MTZLw==} dependencies: end-of-stream: 1.4.4 stream-shift: 1.0.1 dev: true - /stream-shift/1.0.1: + /stream-shift@1.0.1: resolution: {integrity: sha512-AiisoFqQ0vbGcZgQPY1cdP2I76glaVA/RauYR4G4thNFgkTqr90yXTo4LYX60Jl+sIlPNHHdGSwo01AvbKUSVQ==} dev: true - /string_decoder/1.1.1: + /string_decoder@1.1.1: resolution: {integrity: sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==} dependencies: safe-buffer: 5.1.2 dev: true - /supports-color/7.2.0: + /supports-color@7.2.0: resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} engines: {node: '>=8'} dependencies: has-flag: 4.0.0 dev: true - /supports-color/8.1.1: + /supports-color@8.1.1: resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==} engines: {node: '>=10'} dependencies: has-flag: 4.0.0 dev: true - /supports-preserve-symlinks-flag/1.0.0: + /supports-preserve-symlinks-flag@1.0.0: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} dev: true - /symbol-tree/3.2.4: + /symbol-tree@3.2.4: resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} dev: true - /tapable/2.2.1: + /tapable@2.2.1: resolution: {integrity: sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==} engines: {node: '>=6'} dev: true - /terser-webpack-plugin/5.3.9_webpack@5.88.2: + /terser-webpack-plugin@5.3.9(webpack@5.88.2): resolution: {integrity: sha512-ZuXsqE07EcggTWQjXUj+Aot/OMcD0bMKGgF63f7UxYcu5/AJF53aIpK1YoP5xR9l6s/Hy2b+t1AM0bLNPRuhwA==} engines: {node: '>= 10.13.0'} peerDependencies: @@ -1955,10 +1982,10 @@ packages: schema-utils: 3.3.0 serialize-javascript: 6.0.1 terser: 5.21.0 - webpack: 5.88.2_webpack-cli@5.1.4 + webpack: 5.88.2(webpack-cli@5.1.4) dev: true - /terser/5.21.0: + /terser@5.21.0: resolution: {integrity: sha512-WtnFKrxu9kaoXuiZFSGrcAvvBqAdmKx0SFNmVNYdJamMu9yyN3I/QF0FbH4QcqJQ+y1CJnzxGIKH0cSj+FGYRw==} engines: {node: '>=10'} hasBin: true @@ -1969,21 +1996,21 @@ packages: source-map-support: 0.5.21 dev: true - /through2/2.0.5: + /through2@2.0.5: resolution: {integrity: sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==} dependencies: readable-stream: 2.3.8 xtend: 4.0.2 dev: true - /to-regex-range/5.0.1: + /to-regex-range@5.0.1: resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} engines: {node: '>=8.0'} dependencies: is-number: 7.0.0 dev: true - /tough-cookie/4.1.3: + /tough-cookie@4.1.3: resolution: {integrity: sha512-aX/y5pVRkfRnfmuX+OdbSdXvPe6ieKX/G2s7e98f4poJHnqH3281gDPm/metm6E/WRamfx7WC4HUqkWHfQHprw==} engines: {node: '>=6'} dependencies: @@ -1993,14 +2020,14 @@ packages: url-parse: 1.5.10 dev: true - /tr46/4.1.1: + /tr46@4.1.1: resolution: {integrity: sha512-2lv/66T7e5yNyhAAC4NaKe5nVavzuGJQVVtRYLyQ2OI8tsJ61PMLlelehb0wi2Hx6+hT/OJUWZcw8MjlSRnxvw==} engines: {node: '>=14'} dependencies: punycode: 2.3.0 dev: true - /ts-loader/9.5.0_dtthwp2bsqb7yvb7hoeealjg4i: + /ts-loader@9.5.0(typescript@5.2.2)(webpack@5.88.2): resolution: {integrity: sha512-LLlB/pkB4q9mW2yLdFMnK3dEHbrBjeZTYguaaIfusyojBgAGf5kF+O6KcWqiGzWqHk0LBsoolrp4VftEURhybg==} engines: {node: '>=12.0.0'} peerDependencies: @@ -2013,10 +2040,10 @@ packages: semver: 7.5.4 source-map: 0.7.4 typescript: 5.2.2 - webpack: 5.88.2_webpack-cli@5.1.4 + webpack: 5.88.2(webpack-cli@5.1.4) dev: true - /ts-node/10.9.1_sipn3hrabmvxbeu4xryuphsbsa: + /ts-node@10.9.1(@types/node@20.8.3)(typescript@5.2.2): resolution: {integrity: sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==} hasBin: true peerDependencies: @@ -2047,42 +2074,43 @@ packages: yn: 3.1.1 dev: true - /typedarray/0.0.6: + /typedarray@0.0.6: resolution: {integrity: sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==} dev: true - /typedoc-default-themes/0.12.10: + /typedoc-default-themes@0.12.10: resolution: {integrity: sha512-fIS001cAYHkyQPidWXmHuhs8usjP5XVJjWB8oZGqkTowZaz3v7g3KDZeeqE82FBrmkAnIBOY3jgy7lnPnqATbA==} engines: {node: '>= 8'} + dev: true - /typedoc-neo-theme/1.1.1_typescript@5.2.2: + /typedoc-neo-theme@1.1.1(typescript@5.2.2): resolution: {integrity: sha512-J20vYx72bGdhTDMFPK6vhtsisKwxm4B+O6H2MTCb3/gwXRLFWFUk+N7I78t5LhHKhUcM0nRDidZykQ5r/0AY6w==} engines: {node: '>=6'} dependencies: lunr: 2.3.9 - typedoc: 0.20.37_typescript@5.2.2 + typedoc: 0.20.37(typescript@5.2.2) transitivePeerDependencies: - typescript dev: true - /typedoc-plugin-merge-modules/5.1.0_typedoc@0.25.2: + /typedoc-plugin-merge-modules@5.1.0(typedoc@0.25.2): resolution: {integrity: sha512-jXH27L/wlxFjErgBXleh3opVgjVTXFEuBo68Yfl18S9Oh/IqxK6NV94jlEJ9hl4TXc9Zm2l7Rfk41CEkcCyvFQ==} peerDependencies: typedoc: 0.24.x || 0.25.x dependencies: - typedoc: 0.25.2_typescript@5.2.2 + typedoc: 0.25.2(typescript@5.2.2) dev: true - /typedoc-theme-hierarchy/4.1.2_typedoc@0.25.2: + /typedoc-theme-hierarchy@4.1.2(typedoc@0.25.2): resolution: {integrity: sha512-X3H+zaDkg7wLNoaPJoqXs3rnMfZ9BZjmlXRwplWDciaPfn2hojHxJJ+yVKdqqmojgiHJgg7MYWGDVpOfNlOJ5A==} peerDependencies: typedoc: ^0.24.0 || ^0.25.0 dependencies: fs-extra: 11.1.1 - typedoc: 0.25.2_typescript@5.2.2 + typedoc: 0.25.2(typescript@5.2.2) dev: true - /typedoc/0.20.37_typescript@5.2.2: + /typedoc@0.20.37(typescript@5.2.2): resolution: {integrity: sha512-9+qDhdc4X00qTNOtii6QX2z7ndAeWVOso7w3MPSoSJdXlVhpwPfm1yEp4ooKuWA9fiQILR8FKkyjmeqa13hBbw==} engines: {node: '>= 10.8.0'} hasBin: true @@ -2103,7 +2131,7 @@ packages: typescript: 5.2.2 dev: true - /typedoc/0.25.2_typescript@5.2.2: + /typedoc@0.25.2(typescript@5.2.2): resolution: {integrity: sha512-286F7BeATBiWe/qC4PCOCKlSTwfnsLbC/4cZ68oGBbvAqb9vV33quEOXx7q176OXotD+JdEerdQ1OZGJ818lnA==} engines: {node: '>= 16'} hasBin: true @@ -2117,19 +2145,19 @@ packages: typescript: 5.2.2 dev: true - /typescript/5.2.2: + /typescript@5.2.2: resolution: {integrity: sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==} engines: {node: '>=14.17'} hasBin: true dev: true - /uglify-js/3.17.4: + /uglify-js@3.17.4: resolution: {integrity: sha512-T9q82TJI9e/C1TAxYvfb16xO120tMVFZrGA3f9/P4424DNu6ypK103y0GPFVa17yotwSyZW5iYXgjYHkGrJW/g==} engines: {node: '>=0.8.0'} hasBin: true dev: true - /uglifyjs-webpack-plugin/2.2.0_webpack@5.88.2: + /uglifyjs-webpack-plugin@2.2.0(webpack@5.88.2): resolution: {integrity: sha512-mHSkufBmBuJ+KHQhv5H0MXijtsoA1lynJt1lXOaotja8/I0pR4L9oGaPIZw+bQBOFittXZg9OC1sXSGO9D9ZYg==} engines: {node: '>= 6.9.0'} peerDependencies: @@ -2142,34 +2170,34 @@ packages: serialize-javascript: 1.9.1 source-map: 0.6.1 uglify-js: 3.17.4 - webpack: 5.88.2_webpack-cli@5.1.4 + webpack: 5.88.2(webpack-cli@5.1.4) webpack-sources: 1.4.3 worker-farm: 1.7.0 dev: true - /unique-filename/1.1.1: + /unique-filename@1.1.1: resolution: {integrity: sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==} dependencies: unique-slug: 2.0.2 dev: true - /unique-slug/2.0.2: + /unique-slug@2.0.2: resolution: {integrity: sha512-zoWr9ObaxALD3DOPfjPSqxt4fnZiWblxHIgeWqW8x7UqDzEtHEQLzji2cuJYQFCU6KmoJikOYAZlrTHHebjx2w==} dependencies: imurmurhash: 0.1.4 dev: true - /universalify/0.2.0: + /universalify@0.2.0: resolution: {integrity: sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==} engines: {node: '>= 4.0.0'} dev: true - /universalify/2.0.0: + /universalify@2.0.0: resolution: {integrity: sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==} engines: {node: '>= 10.0.0'} dev: true - /update-browserslist-db/1.0.13_browserslist@4.22.1: + /update-browserslist-db@1.0.13(browserslist@4.22.1): resolution: {integrity: sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==} hasBin: true peerDependencies: @@ -2180,47 +2208,47 @@ packages: picocolors: 1.0.0 dev: true - /uri-js/4.4.1: + /uri-js@4.4.1: resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} dependencies: punycode: 2.3.0 dev: true - /url-parse/1.5.10: + /url-parse@1.5.10: resolution: {integrity: sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==} dependencies: querystringify: 2.2.0 requires-port: 1.0.0 dev: true - /util-deprecate/1.0.2: + /util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} dev: true - /v8-compile-cache-lib/3.0.1: + /v8-compile-cache-lib@3.0.1: resolution: {integrity: sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==} dev: true - /vscode-oniguruma/1.7.0: + /vscode-oniguruma@1.7.0: resolution: {integrity: sha512-L9WMGRfrjOhgHSdOYgCt/yRMsXzLDJSL7BPrOZt73gU0iWO4mpqzqQzOz5srxqTvMBaR0XZTSrVWo4j55Rc6cA==} dev: true - /vscode-textmate/5.2.0: + /vscode-textmate@5.2.0: resolution: {integrity: sha512-Uw5ooOQxRASHgu6C7GVvUxisKXfSgW4oFlO+aa+PAkgmH89O3CXxEEzNRNtHSqtXFTl0nAC1uYj0GMSH27uwtQ==} dev: true - /vscode-textmate/8.0.0: + /vscode-textmate@8.0.0: resolution: {integrity: sha512-AFbieoL7a5LMqcnOF04ji+rpXadgOXnZsxQr//r83kLPr7biP7am3g9zbaZIaBGwBRWeSvoMD4mgPdX3e4NWBg==} dev: true - /w3c-xmlserializer/4.0.0: + /w3c-xmlserializer@4.0.0: resolution: {integrity: sha512-d+BFHzbiCx6zGfz0HyQ6Rg69w9k19nviJspaj4yNscGjrHu94sVP+aRm75yEbCh+r2/yR+7q6hux9LVtbuTGBw==} engines: {node: '>=14'} dependencies: xml-name-validator: 4.0.0 dev: true - /watchpack/2.4.0: + /watchpack@2.4.0: resolution: {integrity: sha512-Lcvm7MGST/4fup+ifyKi2hjyIAwcdI4HRgtvTpIUxBRhB+RFtUh8XtDOxUfctVCnhVi+QQj49i91OyvzkJl6cg==} engines: {node: '>=10.13.0'} dependencies: @@ -2228,12 +2256,12 @@ packages: graceful-fs: 4.2.11 dev: true - /webidl-conversions/7.0.0: + /webidl-conversions@7.0.0: resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==} engines: {node: '>=12'} dev: true - /webpack-cli/5.1.4_webpack@5.88.2: + /webpack-cli@5.1.4(webpack@5.88.2): resolution: {integrity: sha512-pIDJHIEI9LR0yxHXQ+Qh95k2EvXpWzZ5l+d+jIo+RdSm9MiHfzazIxwwni/p7+x4eJZuvG1AJwgC4TNQ7NRgsg==} engines: {node: '>=14.15.0'} hasBin: true @@ -2251,9 +2279,9 @@ packages: optional: true dependencies: '@discoveryjs/json-ext': 0.5.7 - '@webpack-cli/configtest': 2.1.1_w46lltld4evug5kpkz4iei6qt4 - '@webpack-cli/info': 2.0.2_w46lltld4evug5kpkz4iei6qt4 - '@webpack-cli/serve': 2.0.5_w46lltld4evug5kpkz4iei6qt4 + '@webpack-cli/configtest': 2.1.1(webpack-cli@5.1.4)(webpack@5.88.2) + '@webpack-cli/info': 2.0.2(webpack-cli@5.1.4)(webpack@5.88.2) + '@webpack-cli/serve': 2.0.5(webpack-cli@5.1.4)(webpack@5.88.2) colorette: 2.0.20 commander: 10.0.1 cross-spawn: 7.0.3 @@ -2262,11 +2290,11 @@ packages: import-local: 3.1.0 interpret: 3.1.1 rechoir: 0.8.0 - webpack: 5.88.2_webpack-cli@5.1.4 + webpack: 5.88.2(webpack-cli@5.1.4) webpack-merge: 5.9.0 dev: true - /webpack-license-plugin/4.3.0_webpack@5.88.2: + /webpack-license-plugin@4.3.0(webpack@5.88.2): resolution: {integrity: sha512-zndSCSUoI66MkZNWYM04u3JrkYhZUmSoqx9E61GhusWoTxRcrPdiLx5aNIZH0j3jl7Im/CqTG7rOzBMjC8psqA==} engines: {node: '>=16.0.0'} peerDependencies: @@ -2277,13 +2305,13 @@ packages: lodash: 4.17.21 needle: 3.2.0 spdx-expression-validate: 2.0.0 - webpack: 5.88.2_webpack-cli@5.1.4 + webpack: 5.88.2(webpack-cli@5.1.4) webpack-sources: 3.2.3 transitivePeerDependencies: - supports-color dev: true - /webpack-merge/5.9.0: + /webpack-merge@5.9.0: resolution: {integrity: sha512-6NbRQw4+Sy50vYNTw7EyOn41OZItPiXB8GNv3INSoe3PSFaHJEz3SHTrYVaRm2LilNGnFUzh0FAwqPEmU/CwDg==} engines: {node: '>=10.0.0'} dependencies: @@ -2291,19 +2319,19 @@ packages: wildcard: 2.0.1 dev: true - /webpack-sources/1.4.3: + /webpack-sources@1.4.3: resolution: {integrity: sha512-lgTS3Xhv1lCOKo7SA5TjKXMjpSM4sBjNV5+q2bqesbSPs5FjGmU6jjtBSkX9b4qW87vDIsCIlUPOEhbZrMdjeQ==} dependencies: source-list-map: 2.0.1 source-map: 0.6.1 dev: true - /webpack-sources/3.2.3: + /webpack-sources@3.2.3: resolution: {integrity: sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==} engines: {node: '>=10.13.0'} dev: true - /webpack/5.88.2_webpack-cli@5.1.4: + /webpack@5.88.2(webpack-cli@5.1.4): resolution: {integrity: sha512-JmcgNZ1iKj+aiR0OvTYtWQqJwq37Pf683dY9bVORwVbUrDhLhdn/PlO2sHsFHPkj7sHNQF3JwaAkp49V+Sq1tQ==} engines: {node: '>=10.13.0'} hasBin: true @@ -2319,7 +2347,7 @@ packages: '@webassemblyjs/wasm-edit': 1.11.6 '@webassemblyjs/wasm-parser': 1.11.6 acorn: 8.10.0 - acorn-import-assertions: 1.9.0_acorn@8.10.0 + acorn-import-assertions: 1.9.0(acorn@8.10.0) browserslist: 4.22.1 chrome-trace-event: 1.0.3 enhanced-resolve: 5.15.0 @@ -2334,9 +2362,9 @@ packages: neo-async: 2.6.2 schema-utils: 3.3.0 tapable: 2.2.1 - terser-webpack-plugin: 5.3.9_webpack@5.88.2 + terser-webpack-plugin: 5.3.9(webpack@5.88.2) watchpack: 2.4.0 - webpack-cli: 5.1.4_webpack@5.88.2 + webpack-cli: 5.1.4(webpack@5.88.2) webpack-sources: 3.2.3 transitivePeerDependencies: - '@swc/core' @@ -2344,19 +2372,19 @@ packages: - uglify-js dev: true - /whatwg-encoding/2.0.0: + /whatwg-encoding@2.0.0: resolution: {integrity: sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==} engines: {node: '>=12'} dependencies: iconv-lite: 0.6.3 dev: true - /whatwg-mimetype/3.0.0: + /whatwg-mimetype@3.0.0: resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==} engines: {node: '>=12'} dev: true - /whatwg-url/12.0.1: + /whatwg-url@12.0.1: resolution: {integrity: sha512-Ed/LrqB8EPlGxjS+TrsXcpUond1mhccS3pchLhzSgPCnTimUCKj3IZE75pAs5m6heB2U2TMerKFUXheyHY+VDQ==} engines: {node: '>=14'} dependencies: @@ -2364,7 +2392,7 @@ packages: webidl-conversions: 7.0.0 dev: true - /which/2.0.2: + /which@2.0.2: resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} engines: {node: '>= 8'} hasBin: true @@ -2372,25 +2400,25 @@ packages: isexe: 2.0.0 dev: true - /wildcard/2.0.1: + /wildcard@2.0.1: resolution: {integrity: sha512-CC1bOL87PIWSBhDcTrdeLo6eGT7mCFtrg0uIJtqJUFyK+eJnzl8A1niH56uu7KMa5XFrtiV+AQuHO3n7DsHnLQ==} dev: true - /wordwrap/1.0.0: + /wordwrap@1.0.0: resolution: {integrity: sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==} dev: true - /worker-farm/1.7.0: + /worker-farm@1.7.0: resolution: {integrity: sha512-rvw3QTZc8lAxyVrqcSGVm5yP/IJ2UcB3U0graE3LCFoZ0Yn2x4EoVSqJKdB/T5M+FLcRPjz4TDacRf3OCfNUzw==} dependencies: errno: 0.1.8 dev: true - /wrappy/1.0.2: + /wrappy@1.0.2: resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} dev: true - /ws/8.14.2: + /ws@8.14.2: resolution: {integrity: sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==} engines: {node: '>=10.0.0'} peerDependencies: @@ -2403,33 +2431,33 @@ packages: optional: true dev: true - /xml-name-validator/4.0.0: + /xml-name-validator@4.0.0: resolution: {integrity: sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==} engines: {node: '>=12'} dev: true - /xmlchars/2.2.0: + /xmlchars@2.2.0: resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} dev: true - /xtend/4.0.2: + /xtend@4.0.2: resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} engines: {node: '>=0.4'} dev: true - /y18n/4.0.3: + /y18n@4.0.3: resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==} dev: true - /yallist/3.1.1: + /yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} dev: true - /yallist/4.0.0: + /yallist@4.0.0: resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} dev: true - /yn/3.1.1: + /yn@3.1.1: resolution: {integrity: sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==} engines: {node: '>=6'} dev: true diff --git a/readme.md b/readme.md index 948882f..e8bfd90 100644 --- a/readme.md +++ b/readme.md @@ -68,8 +68,8 @@ Find more details and usage patterns in the [documentation](https://caph1993.git Numpy-js can be used in: -- web applications: `