@traqula/core 0.0.24 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +4 -1
  2. package/dist/cjs/lib/AstCoreFactory.js +50 -5
  3. package/dist/cjs/lib/AstCoreFactory.js.map +1 -1
  4. package/dist/cjs/lib/generator-builder/dynamicGenerator.js +20 -0
  5. package/dist/cjs/lib/generator-builder/dynamicGenerator.js.map +1 -1
  6. package/dist/cjs/lib/parser-builder/dynamicParser.js +1 -0
  7. package/dist/cjs/lib/parser-builder/dynamicParser.js.map +1 -1
  8. package/dist/cjs/lib/parser-builder/parserBuilder.js +2 -2
  9. package/dist/cjs/lib/parser-builder/parserBuilder.js.map +1 -1
  10. package/dist/cjs/lib/transformers/TransformerObject.js.map +1 -1
  11. package/dist/cjs/lib/transformers/TransformerSubTyped.js +30 -40
  12. package/dist/cjs/lib/transformers/TransformerSubTyped.js.map +1 -1
  13. package/dist/cjs/lib/transformers/TransformerTyped.js +23 -35
  14. package/dist/cjs/lib/transformers/TransformerTyped.js.map +1 -1
  15. package/dist/cjs/lib/types.js.map +1 -1
  16. package/dist/cjs/lib/utils.js +7 -0
  17. package/dist/cjs/lib/utils.js.map +1 -1
  18. package/dist/esm/lib/AstCoreFactory.d.ts +19 -7
  19. package/dist/esm/lib/AstCoreFactory.js +50 -5
  20. package/dist/esm/lib/AstCoreFactory.js.map +1 -1
  21. package/dist/esm/lib/generator-builder/dynamicGenerator.d.ts +5 -0
  22. package/dist/esm/lib/generator-builder/dynamicGenerator.js +20 -0
  23. package/dist/esm/lib/generator-builder/dynamicGenerator.js.map +1 -1
  24. package/dist/esm/lib/parser-builder/dynamicParser.js +1 -0
  25. package/dist/esm/lib/parser-builder/dynamicParser.js.map +1 -1
  26. package/dist/esm/lib/parser-builder/parserBuilder.js +2 -2
  27. package/dist/esm/lib/parser-builder/parserBuilder.js.map +1 -1
  28. package/dist/esm/lib/transformers/TransformerObject.d.ts +1 -1
  29. package/dist/esm/lib/transformers/TransformerObject.js.map +1 -1
  30. package/dist/esm/lib/transformers/TransformerSubTyped.d.ts +31 -22
  31. package/dist/esm/lib/transformers/TransformerSubTyped.js +30 -40
  32. package/dist/esm/lib/transformers/TransformerSubTyped.js.map +1 -1
  33. package/dist/esm/lib/transformers/TransformerTyped.d.ts +24 -20
  34. package/dist/esm/lib/transformers/TransformerTyped.js +23 -35
  35. package/dist/esm/lib/transformers/TransformerTyped.js.map +1 -1
  36. package/dist/esm/lib/types.d.ts +68 -6
  37. package/dist/esm/lib/types.js.map +1 -1
  38. package/dist/esm/lib/utils.d.ts +10 -0
  39. package/dist/esm/lib/utils.js +7 -0
  40. package/dist/esm/lib/utils.js.map +1 -1
  41. package/package.json +3 -3
package/README.md CHANGED
@@ -1,7 +1,10 @@
1
1
  # Traqula core package
2
2
 
3
+ [![npm version](https://badge.fury.io/js/@traqula%2Fcore.svg)](https://www.npmjs.com/package/@traqula/core)
4
+
3
5
  Traqula core contains core components of Traqula.
4
- Most importantly, its [lexer builder](./lib/lexer-builder/LexerBuilder.ts), [parser builder](./lib/parser-builder/parserBuilder.ts), and [generator builder](./lib/generator-builder/generatorBuilder.ts).
6
+ Most importantly, its [lexer builder](./lib/lexer-builder/LexerBuilder.ts), [parser builder](./lib/parser-builder/parserBuilder.ts), and [generator builder](./lib/generator-builder/generatorBuilder.ts);
7
+ as well as providing generic DAG transformers/ visitors.
5
8
  This library heavily relies on the amazing [Chevrotain package](https://chevrotain.io/docs/).
6
9
  Knowing the basics of that package will allow you to quickly generate your own grammars.
7
10
 
@@ -2,6 +2,10 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AstCoreFactory = void 0;
4
4
  class AstCoreFactory {
5
+ tracksSourceLocation;
6
+ constructor(args = {}) {
7
+ this.tracksSourceLocation = args.tracksSourceLocation ?? true;
8
+ }
5
9
  wrap(val, loc) {
6
10
  return { val, loc };
7
11
  }
@@ -10,6 +14,9 @@ class AstCoreFactory {
10
14
  typeof obj.loc === 'object' && obj.loc !== null && 'sourceLocationType' in obj.loc;
11
15
  }
12
16
  sourceLocation(...elements) {
17
+ if (!this.tracksSourceLocation) {
18
+ return this.gen();
19
+ }
13
20
  const pureElements = elements.filter(x => x !== undefined);
14
21
  if (pureElements.length === 0) {
15
22
  return this.sourceLocationNoMaterialize();
@@ -32,6 +39,9 @@ class AstCoreFactory {
32
39
  };
33
40
  }
34
41
  sourceLocationNoMaterialize() {
42
+ if (!this.tracksSourceLocation) {
43
+ return this.gen();
44
+ }
35
45
  return { sourceLocationType: 'noMaterialize' };
36
46
  }
37
47
  /**
@@ -76,12 +86,43 @@ class AstCoreFactory {
76
86
  end,
77
87
  };
78
88
  }
89
+ /**
90
+ * {@inheritDoc SourceLocationInlinedSource}
91
+ */
92
+ sourceLocationInlinedSource(newSource, subLoc, start, end, startOnNew = 0, endOnNew = newSource.length) {
93
+ if (!this.tracksSourceLocation) {
94
+ return this.gen();
95
+ }
96
+ if (this.isSourceLocationSource(subLoc)) {
97
+ startOnNew = subLoc.start;
98
+ endOnNew = subLoc.end;
99
+ }
100
+ return {
101
+ sourceLocationType: 'inlinedSource',
102
+ newSource,
103
+ start,
104
+ end,
105
+ loc: subLoc,
106
+ startOnNew,
107
+ endOnNew,
108
+ };
109
+ }
110
+ ;
111
+ isSourceLocationInlinedSource(loc) {
112
+ return this.isSourceLocation(loc) && loc.sourceLocationType === 'inlinedSource';
113
+ }
79
114
  gen() {
80
115
  return { sourceLocationType: 'autoGenerate' };
81
116
  }
82
117
  isSourceLocationSource(loc) {
83
118
  return this.isSourceLocation(loc) && loc.sourceLocationType === 'source';
84
119
  }
120
+ sourceLocationStringReplace(newSource, start, end) {
121
+ if (!this.tracksSourceLocation) {
122
+ return this.gen();
123
+ }
124
+ return { sourceLocationType: 'stringReplace', newSource, start, end };
125
+ }
85
126
  isSourceLocationStringReplace(loc) {
86
127
  return this.isSourceLocation(loc) && loc.sourceLocationType === 'stringReplace';
87
128
  }
@@ -89,7 +130,10 @@ class AstCoreFactory {
89
130
  if (this.isSourceLocationSource(loc)) {
90
131
  return this.sourceLocationNodeReplace(loc);
91
132
  }
92
- throw new Error('not possible');
133
+ if (this.isSourceLocationInlinedSource(loc)) {
134
+ return this.sourceLocationNodeReplaceUnsafe(loc.loc);
135
+ }
136
+ throw new Error(`Cannot convert SourceLocation of type ${loc.sourceLocationType} to SourceLocationNodeReplace`);
93
137
  }
94
138
  sourceLocationNodeReplace(startOrLoc, end) {
95
139
  let starting;
@@ -114,12 +158,13 @@ class AstCoreFactory {
114
158
  isSourceLocationNodeAutoGenerate(loc) {
115
159
  return this.isSourceLocation(loc) && loc.sourceLocationType === 'autoGenerate';
116
160
  }
117
- nodeShouldPrint(node) {
118
- return this.isSourceLocationNodeReplace(node.loc) ||
119
- this.isSourceLocationNodeAutoGenerate(node.loc);
161
+ isPrintingLoc(loc) {
162
+ return this.isSourceLocationNodeReplace(loc) ||
163
+ this.isSourceLocationNodeAutoGenerate(loc) ||
164
+ (this.isSourceLocationInlinedSource(loc) && this.isPrintingLoc(loc.loc));
120
165
  }
121
166
  printFilter(node, callback) {
122
- if (this.nodeShouldPrint(node)) {
167
+ if (this.isPrintingLoc(node.loc)) {
123
168
  callback();
124
169
  }
125
170
  }
@@ -1 +1 @@
1
- {"version":3,"file":"AstCoreFactory.js","sourceRoot":"","sources":["../../../lib/AstCoreFactory.ts"],"names":[],"mappings":";;;AAgBA,MAAa,cAAc;IAClB,IAAI,CAAI,GAAM,EAAE,GAAmB;QACxC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;IACtB,CAAC;IAEM,WAAW,CAAC,GAAY;QAC7B,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,IAAI,KAAK,IAAI,GAAG;YAC5D,OAAO,GAAG,CAAC,GAAG,KAAK,QAAQ,IAAI,GAAG,CAAC,GAAG,KAAK,IAAI,IAAI,oBAAoB,IAAI,GAAG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,QAAQ;YACf,GAAG,EAAE,MAAM;SACZ,CAAC;IACJ,CAAC;IAEM,2BAA2B,CAAC,GAAW;QAC5C,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,kBAAkB,KAAK,aAAa,CAAC;IAChF,CAAC;IAEM,gCAAgC,CAAC,GAAW;QACjD,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,kBAAkB,KAAK,cAAc,CAAC;IACjF,CAAC;IAEM,eAAe,CAAC,IAAe;QACpC,OAAO,IAAI,CAAC,2BAA2B,CAAC,IAAI,CAAC,GAAG,CAAC;YAC/C,IAAI,CAAC,gCAAgC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACpD,CAAC;IAEM,WAAW,CAAC,IAAe,EAAE,QAAoB;QACtD,IAAI,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC;YAC/B,QAAQ,EAAE,CAAC;QACb,CAAC;IACH,CAAC;IAEM,6BAA6B,CAAC,GAAW;QAC9C,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,kBAAkB,KAAK,eAAe,CAAC;IAClF,CAAC;IAEM,QAAQ,CAAsB,GAAW,EAAE,IAAU;QAC1D,MAAM,MAAM,GAAmB,GAAG,CAAC;QACnC,OAAO,MAAM,CAAC,IAAI,KAAK,IAAI,CAAC;IAC9B,CAAC;IAEM,WAAW,CAA8C,GAAW,EAAE,IAAU,EAAE,OAAgB;QAEvG,MAAM,IAAI,GAA0C,GAAG,CAAC;QACxD,OAAO,IAAI,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,OAAO,KAAK,OAAO,CAAC;IACxD,CAAC;CACF;AA7JD,wCA6JC","sourcesContent":["import type { IToken } from '@traqula/chevrotain';\n\nimport type {\n SourceLocation,\n SourceLocationNodeAutoGenerate,\n SourceLocationNodeReplace,\n SourceLocationNoMaterialize,\n SourceLocationSource,\n SourceLocationStringReplace,\n Node,\n Localized,\n Wrap,\n Typed,\n SubTyped,\n} from './types.js';\n\nexport class AstCoreFactory {\n public wrap<T>(val: T, loc: SourceLocation): Wrap<T> {\n return { val, loc };\n }\n\n public isLocalized(obj: unknown): obj is Localized {\n return typeof obj === 'object' && obj !== null && 'loc' in obj &&\n typeof obj.loc === 'object' && obj.loc !== null && 'sourceLocationType' in obj.loc;\n }\n\n public sourceLocation(...elements: (undefined | IToken | Localized)[]): SourceLocation {\n const pureElements = elements.filter(x => x !== undefined);\n if (pureElements.length === 0) {\n return this.sourceLocationNoMaterialize();\n }\n const filtered = pureElements.filter(element =>\n !this.isLocalized(element) || this.isSourceLocationSource(element.loc) ||\n this.isSourceLocationStringReplace(element.loc) || this.isSourceLocationNodeReplace(element.loc));\n if (filtered.length === 0) {\n return this.gen();\n }\n const first = filtered.at(0)!;\n const last = filtered.at(-1)!;\n return {\n sourceLocationType: 'source',\n start: this.isLocalized(first) ?\n (<SourceLocationSource | SourceLocationStringReplace> first.loc).start :\n first.startOffset,\n end: this.isLocalized(last) ?\n (<SourceLocationSource | SourceLocationStringReplace> last.loc).end :\n (last.endOffset! + 1),\n };\n }\n\n public sourceLocationNoMaterialize(): SourceLocationNoMaterialize {\n return { sourceLocationType: 'noMaterialize' };\n }\n\n /**\n * Returns a copy of the argument that is not materialized\n */\n public dematerialized<T extends Node>(arg: T): T & { loc: SourceLocationNoMaterialize } {\n return { ...arg, loc: this.sourceLocationNoMaterialize() };\n }\n\n public safeObjectTransform(value: unknown, mapper: (some: object) => any): any {\n if (value && typeof value === 'object') {\n // If you wonder why this is all so hard, this is the reason. We cannot lose the methods of our Array objects\n if (Array.isArray(value)) {\n return value.map(x => this.safeObjectTransform(x, mapper));\n }\n return mapper(value);\n }\n return value;\n }\n\n public forcedAutoGenTree<T extends object>(obj: T): T {\n const copy = { ...obj };\n for (const [ key, value ] of Object.entries(copy)) {\n (<Record<string, object>> copy)[key] = this.safeObjectTransform(value, obj => this.forcedAutoGenTree(obj));\n }\n if (this.isLocalized(copy)) {\n copy.loc = this.gen();\n }\n return copy;\n }\n\n public forceMaterialized<T extends Node>(arg: T): T {\n if (this.isSourceLocationNoMaterialize(arg.loc)) {\n return this.forcedAutoGenTree(arg);\n }\n return { ...arg };\n }\n\n public isSourceLocation(loc: object): loc is SourceLocation {\n return 'sourceLocationType' in loc;\n }\n\n public sourceLocationSource(start: number, end: number): SourceLocationSource {\n return {\n sourceLocationType: 'source',\n start,\n end,\n };\n }\n\n public gen(): SourceLocationNodeAutoGenerate {\n return { sourceLocationType: 'autoGenerate' };\n }\n\n public isSourceLocationSource(loc: object): loc is SourceLocationSource {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'source';\n }\n\n public isSourceLocationStringReplace(loc: object): loc is SourceLocationStringReplace {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'stringReplace';\n }\n\n public sourceLocationNodeReplaceUnsafe(loc: SourceLocation): SourceLocationNodeReplace {\n if (this.isSourceLocationSource(loc)) {\n return this.sourceLocationNodeReplace(loc);\n }\n throw new Error('not possible');\n }\n\n public sourceLocationNodeReplace(location: SourceLocationSource): SourceLocationNodeReplace;\n public sourceLocationNodeReplace(start: number, end: number): SourceLocationNodeReplace;\n public sourceLocationNodeReplace(startOrLoc: number | SourceLocationSource, end?: number): SourceLocationNodeReplace {\n let starting;\n let ending;\n if (typeof startOrLoc === 'number') {\n starting = startOrLoc;\n ending = end!;\n } else {\n starting = startOrLoc.start;\n ending = startOrLoc.end;\n }\n return {\n sourceLocationType: 'nodeReplace',\n start: starting,\n end: ending,\n };\n }\n\n public isSourceLocationNodeReplace(loc: object): loc is SourceLocationNodeReplace {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'nodeReplace';\n }\n\n public isSourceLocationNodeAutoGenerate(loc: object): loc is SourceLocationNodeAutoGenerate {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'autoGenerate';\n }\n\n public nodeShouldPrint(node: Localized): boolean {\n return this.isSourceLocationNodeReplace(node.loc) ||\n this.isSourceLocationNodeAutoGenerate(node.loc);\n }\n\n public printFilter(node: Localized, callback: () => void): void {\n if (this.nodeShouldPrint(node)) {\n callback();\n }\n }\n\n public isSourceLocationNoMaterialize(loc: object): loc is SourceLocationNoMaterialize {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'noMaterialize';\n }\n\n public isOfType<Type extends string>(obj: object, type: Type): obj is Typed<Type> {\n const casted: { type?: any } = obj;\n return casted.type === type;\n }\n\n public isOfSubType<Type extends string, SubType extends string>(obj: object, type: Type, subType: SubType):\n obj is SubTyped<Type, SubType> {\n const temp: { type?: unknown; subType?: unknown } = obj;\n return temp.type === type && temp.subType === subType;\n }\n}\n"]}
1
+ {"version":3,"file":"AstCoreFactory.js","sourceRoot":"","sources":["../../../lib/AstCoreFactory.ts"],"names":[],"mappings":";;;AAwBA,MAAa,cAAc;IAClB,oBAAoB,CAAU;IACrC,YAAmB,OAAoC,EAAE;QACvD,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC,oBAAoB,IAAI,IAAI,CAAC;IAChE,CAAC;IAEM,IAAI,CAAI,GAAM,EAAE,GAAmB;QACxC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;IACtB,CAAC;IAEM,WAAW,CAAC,GAAY;QAC7B,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,IAAI,KAAK,IAAI,GAAG;YAC5D,OAAO,GAAG,CAAC,GAAG,KAAK,QAAQ,IAAI,GAAG,CAAC,GAAG,KAAK,IAAI,IAAI,oBAAoB,IAAI,GAAG,CAAC,GAAG,CAAC;IACvF,CAAC;IAEM,cAAc,CAAC,GAAG,QAA4C;QACnE,IAAI,CAAC,IAAI,CAAC,oBAAoB,EAAE,CAAC;YAC/B,OAAO,IAAI,CAAC,GAAG,EAAE,CAAC;QACpB,CAAC;QAED,MAAM,YAAY,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE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AAG,CAAC,kBAAkB,KAAK,aAAa,CAAC;IAChF,CAAC;IAEM,gCAAgC,CAAC,GAAW;QACjD,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,kBAAkB,KAAK,cAAc,CAAC;IACjF,CAAC;IAEM,aAAa,CAAC,GAAmB;QACtC,OAAO,IAAI,CAAC,2BAA2B,CAAC,GAAG,CAAC;YAC1C,IAAI,CAAC,gCAAgC,CAAC,GAAG,CAAC;YAC1C,CAAC,IAAI,CAAC,6BAA6B,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;IAC7E,CAAC;IAEM,WAAW,CAAC,IAAe,EAAE,QAAoB;QACtD,IAAI,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;YACjC,QAAQ,EAAE,CAAC;QACb,CAAC;IACH,CAAC;IAEM,6BAA6B,CAAC,GAAW;QAC9C,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,kBAAkB,KAAK,eAAe,CAAC;IAClF,CAAC;IAEM,QAAQ,CAAsB,GAAW,EAAE,IAAU;QAC1D,MAAM,MAAM,GAAmB,GAAG,CAAC;QACnC,OAAO,MAAM,CAAC,IAAI,KAAK,IAAI,CAAC;IAC9B,CAAC;IAEM,WAAW,CAA8C,GAAW,EAAE,IAAU,EAAE,OAAgB;QAEvG,MAAM,IAAI,GAA0C,GAAG,CAAC;QACxD,OAAO,IAAI,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,OAAO,KAAK,OAAO,CAAC;IACxD,CAAC;CACF;AAtND,wCAsNC","sourcesContent":["import type { IToken } from '@traqula/chevrotain';\n\nimport type {\n SourceLocation,\n SourceLocationNodeAutoGenerate,\n SourceLocationNodeReplace,\n SourceLocationNoMaterialize,\n SourceLocationSource,\n SourceLocationStringReplace,\n Node,\n Localized,\n Wrap,\n Typed,\n SubTyped,\n SourceLocationInlinedSource,\n} from './types.js';\n\nexport interface AstCoreFactoryArgs {\n /**\n * Whether the AstFactory can track sources, if not, the sourceLocation function returns autoGen. Default true\n */\n tracksSourceLocation: boolean;\n}\n\nexport class AstCoreFactory implements AstCoreFactoryArgs {\n public tracksSourceLocation: boolean;\n public constructor(args: Partial<AstCoreFactoryArgs> = {}) {\n this.tracksSourceLocation = args.tracksSourceLocation ?? true;\n }\n\n public wrap<T>(val: T, loc: SourceLocation): Wrap<T> {\n return { val, loc };\n }\n\n public isLocalized(obj: unknown): obj is Localized {\n return typeof obj === 'object' && obj !== null && 'loc' in obj &&\n typeof obj.loc === 'object' && obj.loc !== null && 'sourceLocationType' in obj.loc;\n }\n\n public sourceLocation(...elements: (undefined | IToken | Localized)[]): SourceLocation {\n if (!this.tracksSourceLocation) {\n return this.gen();\n }\n\n const pureElements = elements.filter(x => x !== undefined);\n if (pureElements.length === 0) {\n return this.sourceLocationNoMaterialize();\n }\n\n const filtered = pureElements.filter(element =>\n !this.isLocalized(element) || this.isSourceLocationSource(element.loc) ||\n this.isSourceLocationStringReplace(element.loc) || this.isSourceLocationNodeReplace(element.loc));\n if (filtered.length === 0) {\n return this.gen();\n }\n const first = filtered.at(0)!;\n const last = filtered.at(-1)!;\n return {\n sourceLocationType: 'source',\n start: this.isLocalized(first) ?\n (<SourceLocationSource | SourceLocationStringReplace> first.loc).start :\n first.startOffset,\n end: this.isLocalized(last) ?\n (<SourceLocationSource | SourceLocationStringReplace> last.loc).end :\n (last.endOffset! + 1),\n };\n }\n\n public sourceLocationNoMaterialize(): SourceLocation {\n if (!this.tracksSourceLocation) {\n return this.gen();\n }\n return { sourceLocationType: 'noMaterialize' };\n }\n\n /**\n * Returns a copy of the argument that is not materialized\n */\n public dematerialized<T extends Node>(arg: T): T {\n return { ...arg, loc: this.sourceLocationNoMaterialize() };\n }\n\n public safeObjectTransform(value: unknown, mapper: (some: object) => any): any {\n if (value && typeof value === 'object') {\n // If you wonder why this is all so hard, this is the reason. We cannot lose the methods of our Array objects\n if (Array.isArray(value)) {\n return value.map(x => this.safeObjectTransform(x, mapper));\n }\n return mapper(value);\n }\n return value;\n }\n\n public forcedAutoGenTree<T extends object>(obj: T): T {\n const copy = { ...obj };\n for (const [ key, value ] of Object.entries(copy)) {\n (<Record<string, object>> copy)[key] = this.safeObjectTransform(value, obj => this.forcedAutoGenTree(obj));\n }\n if (this.isLocalized(copy)) {\n copy.loc = this.gen();\n }\n return copy;\n }\n\n public forceMaterialized<T extends Node>(arg: T): T {\n if (this.isSourceLocationNoMaterialize(arg.loc)) {\n return this.forcedAutoGenTree(arg);\n }\n return { ...arg };\n }\n\n public isSourceLocation(loc: object): loc is SourceLocation {\n return 'sourceLocationType' in loc;\n }\n\n public sourceLocationSource(start: number, end: number): SourceLocationSource {\n return {\n sourceLocationType: 'source',\n start,\n end,\n };\n }\n\n /**\n * {@inheritDoc SourceLocationInlinedSource}\n */\n public sourceLocationInlinedSource(\n newSource: string,\n subLoc: SourceLocation,\n start: number,\n end: number,\n startOnNew = 0,\n endOnNew: number = newSource.length,\n ): SourceLocation {\n if (!this.tracksSourceLocation) {\n return this.gen();\n }\n if (this.isSourceLocationSource(subLoc)) {\n startOnNew = subLoc.start;\n endOnNew = subLoc.end;\n }\n return {\n sourceLocationType: 'inlinedSource',\n newSource,\n start,\n end,\n loc: subLoc,\n startOnNew,\n endOnNew,\n }satisfies SourceLocationInlinedSource;\n };\n\n public isSourceLocationInlinedSource(loc: object): loc is SourceLocationInlinedSource {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'inlinedSource';\n }\n\n public gen(): SourceLocationNodeAutoGenerate {\n return { sourceLocationType: 'autoGenerate' };\n }\n\n public isSourceLocationSource(loc: object): loc is SourceLocationSource {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'source';\n }\n\n public sourceLocationStringReplace(newSource: string, start: number, end: number): SourceLocation {\n if (!this.tracksSourceLocation) {\n return this.gen();\n }\n return { sourceLocationType: 'stringReplace', newSource, start, end } satisfies SourceLocationStringReplace;\n }\n\n public isSourceLocationStringReplace(loc: object): loc is SourceLocationStringReplace {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'stringReplace';\n }\n\n public sourceLocationNodeReplaceUnsafe(loc: SourceLocation): SourceLocationNodeReplace {\n if (this.isSourceLocationSource(loc)) {\n return this.sourceLocationNodeReplace(loc);\n }\n if (this.isSourceLocationInlinedSource(loc)) {\n return this.sourceLocationNodeReplaceUnsafe(loc.loc);\n }\n throw new Error(`Cannot convert SourceLocation of type ${loc.sourceLocationType} to SourceLocationNodeReplace`);\n }\n\n public sourceLocationNodeReplace(location: SourceLocationSource): SourceLocationNodeReplace;\n public sourceLocationNodeReplace(start: number, end: number): SourceLocationNodeReplace;\n public sourceLocationNodeReplace(startOrLoc: number | SourceLocationSource, end?: number): SourceLocationNodeReplace {\n let starting;\n let ending;\n if (typeof startOrLoc === 'number') {\n starting = startOrLoc;\n ending = end!;\n } else {\n starting = startOrLoc.start;\n ending = startOrLoc.end;\n }\n return {\n sourceLocationType: 'nodeReplace',\n start: starting,\n end: ending,\n };\n }\n\n public isSourceLocationNodeReplace(loc: object): loc is SourceLocationNodeReplace {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'nodeReplace';\n }\n\n public isSourceLocationNodeAutoGenerate(loc: object): loc is SourceLocationNodeAutoGenerate {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'autoGenerate';\n }\n\n public isPrintingLoc(loc: SourceLocation): boolean {\n return this.isSourceLocationNodeReplace(loc) ||\n this.isSourceLocationNodeAutoGenerate(loc) ||\n (this.isSourceLocationInlinedSource(loc) && this.isPrintingLoc(loc.loc));\n }\n\n public printFilter(node: Localized, callback: () => void): void {\n if (this.isPrintingLoc(node.loc)) {\n callback();\n }\n }\n\n public isSourceLocationNoMaterialize(loc: object): loc is SourceLocationNoMaterialize {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'noMaterialize';\n }\n\n public isOfType<Type extends string>(obj: object, type: Type): obj is Typed<Type> {\n const casted: { type?: any } = obj;\n return casted.type === type;\n }\n\n public isOfSubType<Type extends string, SubType extends string>(obj: object, type: Type, subType: SubType):\n obj is SubTyped<Type, SubType> {\n const temp: { type?: unknown; subType?: unknown } = obj;\n return temp.type === type && temp.subType === subType;\n }\n}\n"]}
@@ -8,6 +8,7 @@ class DynamicGenerator {
8
8
  factory = new AstCoreFactory_js_1.AstCoreFactory();
9
9
  __context = undefined;
10
10
  origSource = '';
11
+ handledInlineSource;
11
12
  generatedUntil = 0;
12
13
  toEnsure = [];
13
14
  /**
@@ -80,6 +81,22 @@ class DynamicGenerator {
80
81
  if (this.factory.isSourceLocationSource(localized.loc)) {
81
82
  this.catchup(localized.loc.start);
82
83
  }
84
+ if (this.factory.isSourceLocationInlinedSource(localized.loc) && this.handledInlineSource !== localized.loc) {
85
+ // Calling handleLoc on the same AST multiple times should be the same as doing it once.
86
+ this.handledInlineSource = localized.loc;
87
+ this.catchup(localized.loc.start);
88
+ const origSource = this.origSource;
89
+ const origPointer = this.generatedUntil;
90
+ this.origSource = localized.loc.newSource;
91
+ this.generatedUntil = 0;
92
+ this.catchup(localized.loc.startOnNew);
93
+ this.handleLoc(localized.loc, handle);
94
+ this.generatedUntil = localized.loc.endOnNew;
95
+ this.catchup(this.origSource.length);
96
+ this.origSource = origSource;
97
+ this.generatedUntil = Math.max(origPointer, localized.loc.end);
98
+ return;
99
+ }
83
100
  // If autoGenerate - do nothing
84
101
  const ret = handle();
85
102
  if (this.factory.isSourceLocationSource(localized.loc)) {
@@ -87,6 +104,9 @@ class DynamicGenerator {
87
104
  }
88
105
  return ret;
89
106
  };
107
+ /**
108
+ * Catchup until, excluding
109
+ */
90
110
  catchup = (until) => {
91
111
  const start = this.generatedUntil;
92
112
  if (start < until) {
@@ -1 +1 @@
1
- {"version":3,"file":"dynamicGenerator.js","sourceRoot":"","sources":["../../../../lib/generator-builder/dynamicGenerator.ts"],"names":[],"mappings":";;;AAAA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CAAC,YAAY,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAC7B,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;QACpB,IAAI,CAAC,YAAY,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC,CAAC;IAEe,UAAU,GAA6B,CAAC,GAAG,IAAI,EAAE,EAAE;QAClE,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QACtB,CAAC;IACH,CAAC,CAAC;IAEe,YAAY,GAAiC,CAAC,GAAG,IAAI,EAAE,EAAE;QACxE,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;IACtB,CAAC,CAAC;IAEe,cAAc,GAAoC,CAAC,GAAG,IAAI,EAAE,EAAE;QAC7E,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC,CAAC;CACH;AA/MD,4CA+MC","sourcesContent":["import { AstCoreFactory } from '../AstCoreFactory.js';\nimport { traqulaIndentation } from '../utils.js';\nimport type { GenRuleMap } from './builderTypes.js';\nimport type { GeneratorRule, RuleDefArg } from './generatorTypes.js';\n\nexport class DynamicGenerator<Context, Names extends string, RuleDefs extends GenRuleMap<Names>> {\n protected readonly factory = new AstCoreFactory();\n protected __context: Context | undefined = undefined;\n protected origSource = '';\n protected generatedUntil = 0;\n protected toEnsure: ((willPrint: string) => void)[] = [];\n /**\n * Should not contain empty strings\n * @protected\n */\n protected readonly stringBuilder: string[] = [];\n\n public constructor(protected rules: RuleDefs) {\n // eslint-disable-next-line ts/no-unnecessary-type-assertion\n for (const rule of <GeneratorRule[]> Object.values(rules)) {\n // Define function implementation\n this[<keyof (typeof this)> rule.name] =\n <any> ((input: any, context: Context & { origSource: string; offset?: number }, args: any) => {\n this.stringBuilder.length = 0;\n this.origSource = context.origSource;\n this.generatedUntil = context?.offset ?? 0;\n this.setContext(context);\n\n this.subrule(rule, input, args);\n\n this.catchup(this.origSource.length);\n\n return this.stringBuilder.join('');\n });\n }\n }\n\n public setContext(context: Context): void {\n this.__context = context;\n }\n\n protected getSafeContext(): Context & { [traqulaIndentation]?: number } {\n return <Context & { [traqulaIndentation]?: number }> this.__context;\n }\n\n protected readonly subrule: RuleDefArg['SUBRULE'] = (cstDef, ast, ...arg) => {\n const def = this.rules[<Names> cstDef.name];\n if (!def) {\n throw new Error(`Rule ${cstDef.name} not found`);\n }\n\n const generate = (): void => def.gImpl({\n SUBRULE: this.subrule,\n PRINT: this.print,\n ENSURE: this.ensure,\n ENSURE_EITHER: this.ensureEither,\n NEW_LINE: this.newLine,\n HANDLE_LOC: this.handleLoc,\n CATCHUP: this.catchup,\n\n PRINT_WORD: this.printWord,\n PRINT_WORDS: this.printWords,\n PRINT_ON_EMPTY: this.printOnEmpty,\n PRINT_ON_OWN_LINE: this.printOnOwnLine,\n })(ast, this.getSafeContext(), ...arg);\n\n if (this.factory.isLocalized(ast)) {\n this.handleLoc(ast, generate);\n } else {\n generate();\n }\n };\n\n protected readonly handleLoc: RuleDefArg['HANDLE_LOC'] = (localized, handle) => {\n if (this.factory.isSourceLocationNoMaterialize(localized.loc)) {\n return;\n }\n if (this.factory.isSourceLocationStringReplace(localized.loc)) {\n this.catchup(localized.loc.start);\n this.print(localized.loc.newSource);\n this.generatedUntil = localized.loc.end;\n return;\n }\n if (this.factory.isSourceLocationNodeReplace(localized.loc)) {\n this.catchup(localized.loc.start);\n this.generatedUntil = localized.loc.end;\n }\n if (this.factory.isSourceLocationSource(localized.loc)) {\n this.catchup(localized.loc.start);\n }\n // If autoGenerate - do nothing\n\n const ret = handle();\n\n if (this.factory.isSourceLocationSource(localized.loc)) {\n this.catchup(localized.loc.end);\n }\n return ret;\n };\n\n protected readonly catchup: RuleDefArg['CATCHUP'] = (until) => {\n const start = this.generatedUntil;\n if (start < until) {\n this.print(this.origSource.slice(start, until));\n }\n this.generatedUntil = Math.max(this.generatedUntil, until);\n };\n\n private handeEnsured(toPrint: string): void {\n for (const callBack of this.toEnsure) {\n callBack(toPrint);\n }\n this.toEnsure.length = 0;\n }\n\n protected readonly print: RuleDefArg['PRINT'] = (...args) => {\n const joined = args.join('');\n this.handeEnsured(joined);\n this.stringBuilder.push(joined);\n };\n\n private doesEndWith(subsStr: string): boolean {\n const len = subsStr.length;\n let temp = '';\n while (temp.length < len && this.stringBuilder.length > 0) {\n temp = this.stringBuilder.pop() + temp;\n }\n this.stringBuilder.push(temp);\n return temp.endsWith(subsStr);\n }\n\n protected readonly ensure: RuleDefArg['ENSURE'] = (...args) => {\n // Check whether already present\n const toEnsure = args.join('');\n if (!this.doesEndWith(toEnsure)) {\n this.toEnsure.push((willPrint) => {\n if (!willPrint.startsWith(toEnsure) && !this.doesEndWith(toEnsure)) {\n this.stringBuilder.push(toEnsure);\n }\n });\n }\n };\n\n protected readonly ensureEither: RuleDefArg['ENSURE_EITHER'] = (...args) => {\n if (args.length === 1) {\n this.ensure(...args);\n } else if (args.length > 1 &&\n // Not already matched?\n !args.some(subStr => this.doesEndWith(subStr))) {\n this.toEnsure.push((willPrint) => {\n if (!args.some(subStr => willPrint.startsWith(subStr)) && !args.some(subStr => this.doesEndWith(subStr))) {\n this.stringBuilder.push(args[0]);\n }\n });\n }\n };\n\n private pruneEndingBlanks(): void {\n let temp = '';\n while (/^[ \\t]*$/u.test(temp) && this.stringBuilder.length > 0) {\n temp = this.stringBuilder.pop() + temp;\n }\n this.print(temp.trimEnd());\n }\n\n protected readonly newLine: RuleDefArg['NEW_LINE'] = (arg) => {\n const indentation = this.getSafeContext()[traqulaIndentation] ?? 0;\n if (indentation === -1) {\n return;\n }\n const force = arg?.force ?? false;\n this.pruneEndingBlanks();\n if (force) {\n this.print('\\n', ' '.repeat(indentation));\n } else {\n let temp = '';\n while (!temp.includes('\\n') && this.stringBuilder.length > 0) {\n temp = this.stringBuilder.pop() + temp;\n }\n if (/\\n[ \\t]*$/u.test(temp)) {\n // Pointer is on empty newline -> set correct indentation\n temp = temp.replace(/\\n[ \\t]*$/u, `\\n${' '.repeat(indentation)}`);\n this.print(temp);\n } else {\n // Pointer not on empty newline, print newline.\n this.print(temp, '\\n', ' '.repeat(indentation));\n }\n }\n };\n\n private readonly printWord: RuleDefArg['PRINT_WORD'] = (...args) => {\n this.ensureEither(' ', '\\n');\n this.print(...args);\n this.ensureEither(' ', '\\n');\n };\n\n private readonly printWords: RuleDefArg['PRINT_WORD'] = (...args) => {\n for (const arg of args) {\n this.printWord(arg);\n }\n };\n\n private readonly printOnEmpty: RuleDefArg['PRINT_ON_EMPTY'] = (...args) => {\n this.newLine();\n this.print(...args);\n };\n\n private readonly printOnOwnLine: RuleDefArg['PRINT_ON_OWN_LINE'] = (...args) => {\n this.newLine();\n this.print(...args);\n this.newLine();\n };\n}\n"]}
1
+ {"version":3,"file":"dynamicGenerator.js","sourceRoot":"","sources":["../../../../lib/generator-builder/dynamicGenerator.ts"],"names":[],"mappings":";;;AAAA,4DAAsD;AAEtD,0CAAiD;AAIjD,MAAa,gBAAgB;IAaE;IAZV,OAAO,GAAG,IAAI,kCAAc,EAAE,CAAC;IACxC,SAAS,GAAwB,SAAS,CAAC;IAC3C,UAAU,GAAG,EAAE,CAAC;IAChB,mBAAmB,CAA0C;IAC7D,cAAc,GAAG,CAAC,CAAC;IACnB,QAAQ,GAAoC,EAAE,CAAC;IACzD;;;OAGG;IACgB,aAAa,GAAa,EAAE,CAAC;IAEhD,YAA6B,KAAe;QAAf,UAAK,GAAL,KAAK,CAAU;QAC1C,4DAA4D;QAC5D,KAAK,MAAM,IAAI,IAAsB,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1D,iCAAiC;YACjC,IAAI,CAAuB,IAAI,CAAC,IAAI,CAAC;gBAC7B,CAAC,CAAC,KAA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';\nimport type { SourceLocationInlinedSource } from '../types.js';\nimport { traqulaIndentation } from '../utils.js';\nimport type { GenRuleMap } from './builderTypes.js';\nimport type { GeneratorRule, RuleDefArg } from './generatorTypes.js';\n\nexport class DynamicGenerator<Context, Names extends string, RuleDefs extends GenRuleMap<Names>> {\n protected readonly factory = new AstCoreFactory();\n protected __context: Context | undefined = undefined;\n protected origSource = '';\n protected handledInlineSource: SourceLocationInlinedSource | undefined;\n protected generatedUntil = 0;\n protected toEnsure: ((willPrint: string) => void)[] = [];\n /**\n * Should not contain empty strings\n * @protected\n */\n protected readonly stringBuilder: string[] = [];\n\n public constructor(protected rules: RuleDefs) {\n // eslint-disable-next-line ts/no-unnecessary-type-assertion\n for (const rule of <GeneratorRule[]> Object.values(rules)) {\n // Define function implementation\n this[<keyof (typeof this)> rule.name] =\n <any> ((input: any, context: Context & { origSource: string; offset?: number }, args: any) => {\n this.stringBuilder.length = 0;\n this.origSource = context.origSource;\n this.generatedUntil = context?.offset ?? 0;\n this.setContext(context);\n\n this.subrule(rule, input, args);\n\n this.catchup(this.origSource.length);\n\n return this.stringBuilder.join('');\n });\n }\n }\n\n public setContext(context: Context): void {\n this.__context = context;\n }\n\n protected getSafeContext(): Context & { [traqulaIndentation]?: number } {\n return <Context & { [traqulaIndentation]?: number }> this.__context;\n }\n\n protected readonly subrule: RuleDefArg['SUBRULE'] = (cstDef, ast, ...arg) => {\n const def = this.rules[<Names> cstDef.name];\n if (!def) {\n throw new Error(`Rule ${cstDef.name} not found`);\n }\n\n const generate = (): void => def.gImpl({\n SUBRULE: this.subrule,\n PRINT: this.print,\n ENSURE: this.ensure,\n ENSURE_EITHER: this.ensureEither,\n NEW_LINE: this.newLine,\n HANDLE_LOC: this.handleLoc,\n CATCHUP: this.catchup,\n\n PRINT_WORD: this.printWord,\n PRINT_WORDS: this.printWords,\n PRINT_ON_EMPTY: this.printOnEmpty,\n PRINT_ON_OWN_LINE: this.printOnOwnLine,\n })(ast, this.getSafeContext(), ...arg);\n\n if (this.factory.isLocalized(ast)) {\n this.handleLoc(ast, generate);\n } else {\n generate();\n }\n };\n\n protected readonly handleLoc: RuleDefArg['HANDLE_LOC'] = (localized, handle) => {\n if (this.factory.isSourceLocationNoMaterialize(localized.loc)) {\n return;\n }\n if (this.factory.isSourceLocationStringReplace(localized.loc)) {\n this.catchup(localized.loc.start);\n this.print(localized.loc.newSource);\n this.generatedUntil = localized.loc.end;\n return;\n }\n if (this.factory.isSourceLocationNodeReplace(localized.loc)) {\n this.catchup(localized.loc.start);\n this.generatedUntil = localized.loc.end;\n }\n if (this.factory.isSourceLocationSource(localized.loc)) {\n this.catchup(localized.loc.start);\n }\n if (this.factory.isSourceLocationInlinedSource(localized.loc) && this.handledInlineSource !== localized.loc) {\n // Calling handleLoc on the same AST multiple times should be the same as doing it once.\n this.handledInlineSource = localized.loc;\n this.catchup(localized.loc.start);\n const origSource = this.origSource;\n const origPointer = this.generatedUntil;\n this.origSource = localized.loc.newSource;\n this.generatedUntil = 0;\n this.catchup(localized.loc.startOnNew);\n\n this.handleLoc(localized.loc, handle);\n\n this.generatedUntil = localized.loc.endOnNew;\n this.catchup(this.origSource.length);\n this.origSource = origSource;\n this.generatedUntil = Math.max(origPointer, localized.loc.end);\n return;\n }\n // If autoGenerate - do nothing\n\n const ret = handle();\n\n if (this.factory.isSourceLocationSource(localized.loc)) {\n this.catchup(localized.loc.end);\n }\n return ret;\n };\n\n /**\n * Catchup until, excluding\n */\n protected readonly catchup: RuleDefArg['CATCHUP'] = (until) => {\n const start = this.generatedUntil;\n if (start < until) {\n this.print(this.origSource.slice(start, until));\n }\n this.generatedUntil = Math.max(this.generatedUntil, until);\n };\n\n private handeEnsured(toPrint: string): void {\n for (const callBack of this.toEnsure) {\n callBack(toPrint);\n }\n this.toEnsure.length = 0;\n }\n\n protected readonly print: RuleDefArg['PRINT'] = (...args) => {\n const joined = args.join('');\n this.handeEnsured(joined);\n this.stringBuilder.push(joined);\n };\n\n private doesEndWith(subsStr: string): boolean {\n const len = subsStr.length;\n let temp = '';\n while (temp.length < len && this.stringBuilder.length > 0) {\n temp = this.stringBuilder.pop() + temp;\n }\n this.stringBuilder.push(temp);\n return temp.endsWith(subsStr);\n }\n\n protected readonly ensure: RuleDefArg['ENSURE'] = (...args) => {\n // Check whether already present\n const toEnsure = args.join('');\n if (!this.doesEndWith(toEnsure)) {\n this.toEnsure.push((willPrint) => {\n if (!willPrint.startsWith(toEnsure) && !this.doesEndWith(toEnsure)) {\n this.stringBuilder.push(toEnsure);\n }\n });\n }\n };\n\n protected readonly ensureEither: RuleDefArg['ENSURE_EITHER'] = (...args) => {\n if (args.length === 1) {\n this.ensure(...args);\n } else if (args.length > 1 &&\n // Not already matched?\n !args.some(subStr => this.doesEndWith(subStr))) {\n this.toEnsure.push((willPrint) => {\n if (!args.some(subStr => willPrint.startsWith(subStr)) && !args.some(subStr => this.doesEndWith(subStr))) {\n this.stringBuilder.push(args[0]);\n }\n });\n }\n };\n\n private pruneEndingBlanks(): void {\n let temp = '';\n while (/^[ \\t]*$/u.test(temp) && this.stringBuilder.length > 0) {\n temp = this.stringBuilder.pop() + temp;\n }\n this.print(temp.trimEnd());\n }\n\n protected readonly newLine: RuleDefArg['NEW_LINE'] = (arg) => {\n const indentation = this.getSafeContext()[traqulaIndentation] ?? 0;\n if (indentation === -1) {\n return;\n }\n const force = arg?.force ?? false;\n this.pruneEndingBlanks();\n if (force) {\n this.print('\\n', ' '.repeat(indentation));\n } else {\n let temp = '';\n while (!temp.includes('\\n') && this.stringBuilder.length > 0) {\n temp = this.stringBuilder.pop() + temp;\n }\n if (/\\n[ \\t]*$/u.test(temp)) {\n // Pointer is on empty newline -> set correct indentation\n temp = temp.replace(/\\n[ \\t]*$/u, `\\n${' '.repeat(indentation)}`);\n this.print(temp);\n } else {\n // Pointer not on empty newline, print newline.\n this.print(temp, '\\n', ' '.repeat(indentation));\n }\n }\n };\n\n private readonly printWord: RuleDefArg['PRINT_WORD'] = (...args) => {\n this.ensureEither(' ', '\\n');\n this.print(...args);\n this.ensureEither(' ', '\\n');\n };\n\n private readonly printWords: RuleDefArg['PRINT_WORD'] = (...args) => {\n for (const arg of args) {\n this.printWord(arg);\n }\n };\n\n private readonly printOnEmpty: RuleDefArg['PRINT_ON_EMPTY'] = (...args) => {\n this.newLine();\n this.print(...args);\n };\n\n private readonly printOnOwnLine: RuleDefArg['PRINT_ON_OWN_LINE'] = (...args) => {\n this.newLine();\n this.print(...args);\n this.newLine();\n };\n}\n"]}
@@ -12,6 +12,7 @@ class DynamicParser extends chevrotain_1.EmbeddedActionsParser {
12
12
  // RecoveryEnabled: true,
13
13
  maxLookahead: 1,
14
14
  skipValidations: true,
15
+ dynamicTokensEnabled: false,
15
16
  ...config,
16
17
  });
17
18
  this.context = undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"dynamicParser.js","sourceRoot":"","sources":["../../../../lib/parser-builder/dynamicParser.ts"],"names":[],"mappings":";;;AAAA,oDAA4D;AAK5D,MAAa,aACX,SAAQ,kCAAqB;IACrB,OAAO,CAAsB;IAE9B,UAAU,CAAC,OAAgB;QAChC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,YAAmB,KAAe,EAAE,eAAgC,EAAE,SAAwB,EAAE;QAC9F,KAAK,CAAC,eAAe,EAAE;YACrB,yBAAyB;YACzB,YAAY,EAAE,CAAC;YACf,eAAe,EAAE,IAAI;YACrB,GAAG,MAAM;SACV,CAAC,CAAC;QACH,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;QACzB,MAAM,OAAO,GAAG,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACxC,MAAM,QAAQ,GAAa;YACzB,GAAG,OAAO;YACV,KAAK,EAAE,IAAI,OAAO,EAAE;SACrB,CAAC;QAEF,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,MAAM,CAAsC,KAAK,CAAC,EAAE,CAAC;YAC7E,wEAAwE;YACxE,IAAI,CAAsB,IAAI,CAAC,IAAI,CAAC,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WAAW,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAChE,QAAQ,EAAE,WAAW,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAChE,QAAQ,EAAE,WAAW,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAChE,QAAQ,EAAE,WAAW,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAChE,QAAQ,EAAE,WAAW,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;SACjE,CAAC;IACJ,CAAC;CACF;AAxHD,sCAwHC","sourcesContent":["import { EmbeddedActionsParser } from '@traqula/chevrotain';\nimport type { IParserConfig, TokenVocabulary } from '@traqula/chevrotain';\nimport type { ParseRuleMap } from './builderTypes.js';\nimport type { CstDef, ImplArgs, ParserRule } from './ruleDefTypes.js';\n\nexport class DynamicParser<Context, Names extends string, RuleDefs extends ParseRuleMap<Names>>\n extends EmbeddedActionsParser {\n private context: Context | undefined;\n\n public setContext(context: Context): void {\n this.context = context;\n }\n\n public constructor(rules: RuleDefs, tokenVocabulary: TokenVocabulary, config: IParserConfig = {}) {\n super(tokenVocabulary, {\n // RecoveryEnabled: true,\n maxLookahead: 1,\n skipValidations: true,\n ...config,\n });\n this.context = undefined;\n const selfRef = this.constructSelfRef();\n const implArgs: ImplArgs = {\n ...selfRef,\n cache: new WeakMap(),\n };\n\n for (const rule of Object.values(<Record<string, ParserRule<Context>>>rules)) {\n // Function implementation itself - this function is called AFTER lexing\n this[<keyof (typeof this)>rule.name] = <any> this.RULE(rule.name, rule.impl(implArgs));\n }\n this.performSelfAnalysis();\n }\n\n private constructSelfRef(): CstDef {\n const subRuleImpl = (chevrotainSubrule: typeof this.SUBRULE): CstDef['SUBRULE'] =>\n ((cstDef, ...arg) =>\n chevrotainSubrule(<any> this[<keyof (typeof this)>cstDef.name], <any>{ ARGS: [ this.context, ...arg ]})\n ) satisfies CstDef['SUBRULE'];\n return {\n CONSUME: (tokenType, option) => this.CONSUME(tokenType, option),\n CONSUME1: (tokenType, option) => this.CONSUME1(tokenType, option),\n CONSUME2: (tokenType, option) => this.CONSUME2(tokenType, option),\n CONSUME3: (tokenType, option) => this.CONSUME3(tokenType, option),\n CONSUME4: (tokenType, option) => this.CONSUME4(tokenType, option),\n CONSUME5: (tokenType, option) => this.CONSUME5(tokenType, option),\n CONSUME6: (tokenType, option) => this.CONSUME6(tokenType, option),\n CONSUME7: (tokenType, option) => this.CONSUME7(tokenType, option),\n CONSUME8: (tokenType, option) => this.CONSUME8(tokenType, option),\n CONSUME9: (tokenType, option) => this.CONSUME9(tokenType, option),\n OPTION: actionORMethodDef => this.OPTION(actionORMethodDef),\n OPTION1: actionORMethodDef => this.OPTION1(actionORMethodDef),\n OPTION2: actionORMethodDef => this.OPTION2(actionORMethodDef),\n OPTION3: actionORMethodDef => this.OPTION3(actionORMethodDef),\n OPTION4: actionORMethodDef => this.OPTION4(actionORMethodDef),\n OPTION5: actionORMethodDef => this.OPTION5(actionORMethodDef),\n OPTION6: actionORMethodDef => this.OPTION6(actionORMethodDef),\n OPTION7: actionORMethodDef => this.OPTION7(actionORMethodDef),\n OPTION8: actionORMethodDef => this.OPTION8(actionORMethodDef),\n OPTION9: actionORMethodDef => this.OPTION9(actionORMethodDef),\n OR: altsOrOpts => this.OR(altsOrOpts),\n OR1: altsOrOpts => this.OR1(altsOrOpts),\n OR2: altsOrOpts => this.OR2(altsOrOpts),\n OR3: altsOrOpts => this.OR3(altsOrOpts),\n OR4: altsOrOpts => this.OR4(altsOrOpts),\n OR5: altsOrOpts => this.OR5(altsOrOpts),\n OR6: altsOrOpts => this.OR6(altsOrOpts),\n OR7: altsOrOpts => this.OR7(altsOrOpts),\n OR8: altsOrOpts => this.OR8(altsOrOpts),\n OR9: altsOrOpts => this.OR9(altsOrOpts),\n MANY: actionORMethodDef => this.MANY(actionORMethodDef),\n MANY1: actionORMethodDef => this.MANY1(actionORMethodDef),\n MANY2: actionORMethodDef => this.MANY2(actionORMethodDef),\n MANY3: actionORMethodDef => this.MANY3(actionORMethodDef),\n MANY4: actionORMethodDef => this.MANY4(actionORMethodDef),\n MANY5: actionORMethodDef => this.MANY5(actionORMethodDef),\n MANY6: actionORMethodDef => this.MANY6(actionORMethodDef),\n MANY7: actionORMethodDef => this.MANY7(actionORMethodDef),\n MANY8: actionORMethodDef => this.MANY8(actionORMethodDef),\n MANY9: actionORMethodDef => this.MANY9(actionORMethodDef),\n MANY_SEP: options => this.MANY_SEP(options),\n MANY_SEP1: options => this.MANY_SEP1(options),\n MANY_SEP2: options => this.MANY_SEP2(options),\n MANY_SEP3: options => this.MANY_SEP3(options),\n MANY_SEP4: options => this.MANY_SEP4(options),\n MANY_SEP5: options => this.MANY_SEP5(options),\n MANY_SEP6: options => this.MANY_SEP6(options),\n MANY_SEP7: options => this.MANY_SEP7(options),\n MANY_SEP8: options => this.MANY_SEP8(options),\n MANY_SEP9: options => this.MANY_SEP9(options),\n AT_LEAST_ONE: actionORMethodDef => this.AT_LEAST_ONE(actionORMethodDef),\n AT_LEAST_ONE1: actionORMethodDef => this.AT_LEAST_ONE1(actionORMethodDef),\n AT_LEAST_ONE2: actionORMethodDef => this.AT_LEAST_ONE2(actionORMethodDef),\n AT_LEAST_ONE3: actionORMethodDef => this.AT_LEAST_ONE3(actionORMethodDef),\n AT_LEAST_ONE4: actionORMethodDef => this.AT_LEAST_ONE4(actionORMethodDef),\n AT_LEAST_ONE5: actionORMethodDef => this.AT_LEAST_ONE5(actionORMethodDef),\n AT_LEAST_ONE6: actionORMethodDef => this.AT_LEAST_ONE6(actionORMethodDef),\n AT_LEAST_ONE7: actionORMethodDef => this.AT_LEAST_ONE7(actionORMethodDef),\n AT_LEAST_ONE8: actionORMethodDef => this.AT_LEAST_ONE8(actionORMethodDef),\n AT_LEAST_ONE9: actionORMethodDef => this.AT_LEAST_ONE9(actionORMethodDef),\n AT_LEAST_ONE_SEP: options => this.AT_LEAST_ONE_SEP(options),\n AT_LEAST_ONE_SEP1: options => this.AT_LEAST_ONE_SEP1(options),\n AT_LEAST_ONE_SEP2: options => this.AT_LEAST_ONE_SEP2(options),\n AT_LEAST_ONE_SEP3: options => this.AT_LEAST_ONE_SEP3(options),\n AT_LEAST_ONE_SEP4: options => this.AT_LEAST_ONE_SEP4(options),\n AT_LEAST_ONE_SEP5: options => this.AT_LEAST_ONE_SEP5(options),\n AT_LEAST_ONE_SEP6: options => this.AT_LEAST_ONE_SEP6(options),\n AT_LEAST_ONE_SEP7: options => this.AT_LEAST_ONE_SEP7(options),\n AT_LEAST_ONE_SEP8: options => this.AT_LEAST_ONE_SEP8(options),\n AT_LEAST_ONE_SEP9: options => this.AT_LEAST_ONE_SEP9(options),\n ACTION: func => this.ACTION(func),\n BACKTRACK: (cstDef, ...args) =>\n this.BACKTRACK(<any> this[<keyof (typeof this)>cstDef.name], <any>{ ARGS: args }),\n SUBRULE: subRuleImpl((rule, args) => this.SUBRULE(rule, args)),\n SUBRULE1: subRuleImpl((rule, args) => this.SUBRULE1(rule, args)),\n SUBRULE2: subRuleImpl((rule, args) => this.SUBRULE2(rule, args)),\n SUBRULE3: subRuleImpl((rule, args) => this.SUBRULE3(rule, args)),\n SUBRULE4: subRuleImpl((rule, args) => this.SUBRULE4(rule, args)),\n SUBRULE5: subRuleImpl((rule, args) => this.SUBRULE5(rule, args)),\n SUBRULE6: subRuleImpl((rule, args) => this.SUBRULE6(rule, args)),\n SUBRULE7: subRuleImpl((rule, args) => this.SUBRULE7(rule, args)),\n SUBRULE8: subRuleImpl((rule, args) => this.SUBRULE8(rule, args)),\n SUBRULE9: subRuleImpl((rule, args) => this.SUBRULE9(rule, args)),\n };\n }\n}\n"]}
1
+ {"version":3,"file":"dynamicParser.js","sourceRoot":"","sources":["../../../../lib/parser-builder/dynamicParser.ts"],"names":[],"mappings":";;;AAAA,oDAA4D;AAK5D,MAAa,aACX,SAAQ,kCAAqB;IACrB,OAAO,CAAsB;IAE9B,UAAU,CAAC,OAAgB;QAChC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,YAAmB,KAAe,EAAE,eAAgC,EAAE,SAAwB,EAAE;QAC9F,KAAK,CAAC,eAAe,EAAE;YACrB,yBAAyB;YACzB,YAAY,EAAE,CAAC;YACf,eAAe,EAAE,IAAI;YACrB,oBAAoB,EAAE,KAAK;YAC3B,GAAG,MAAM;SACV,CAAC,CAAC;QACH,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;QACzB,MAAM,OAAO,GAAG,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACxC,MAAM,QAAQ,GAAa;YACzB,GAAG,OAAO;YACV,KAAK,EAAE,IAAI,OAAO,EAAE;SACrB,CAAC;QAEF,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,MAAM,CAAsC,KAAK,CAAC,EAAE,CAAC;YAC7E,wEAAwE;YACxE,IAAI,CAAsB,IAAI,CAAC,IAAI,CAAC,GAAS,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;QACzF,CAAC;QACD,IAAI,CAAC,mBAAmB,EAAE,CAAC;IAC7B,CAAC;IAEO,gBAAgB;QACtB,MAAM,WAAW,GAAG,CAAC,iBAAsC,EAAqB,EAAE,CAChF,CAAC,CAAC,MAAM,EAAE,GAAG,GAAG,EAAE,EAAE,CAClB,iBAAiB,CAAO,IAAI,CAAsB,MAAM,CAAC,IAAI,CAAC,EAAO,EAAE,I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AC,CAAC;YAChE,QAAQ,EAAE,WAAW,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAChE,QAAQ,EAAE,WAAW,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;SACjE,CAAC;IACJ,CAAC;CACF;AAzHD,sCAyHC","sourcesContent":["import { EmbeddedActionsParser } from '@traqula/chevrotain';\nimport type { IParserConfig, TokenVocabulary } from '@traqula/chevrotain';\nimport type { ParseRuleMap } from './builderTypes.js';\nimport type { CstDef, ImplArgs, ParserRule } from './ruleDefTypes.js';\n\nexport class DynamicParser<Context, Names extends string, RuleDefs extends ParseRuleMap<Names>>\n extends EmbeddedActionsParser {\n private context: Context | undefined;\n\n public setContext(context: Context): void {\n this.context = context;\n }\n\n public constructor(rules: RuleDefs, tokenVocabulary: TokenVocabulary, config: IParserConfig = {}) {\n super(tokenVocabulary, {\n // RecoveryEnabled: true,\n maxLookahead: 1,\n skipValidations: true,\n dynamicTokensEnabled: false,\n ...config,\n });\n this.context = undefined;\n const selfRef = this.constructSelfRef();\n const implArgs: ImplArgs = {\n ...selfRef,\n cache: new WeakMap(),\n };\n\n for (const rule of Object.values(<Record<string, ParserRule<Context>>>rules)) {\n // Function implementation itself - this function is called AFTER lexing\n this[<keyof (typeof this)>rule.name] = <any> this.RULE(rule.name, rule.impl(implArgs));\n }\n this.performSelfAnalysis();\n }\n\n private constructSelfRef(): CstDef {\n const subRuleImpl = (chevrotainSubrule: typeof this.SUBRULE): CstDef['SUBRULE'] =>\n ((cstDef, ...arg) =>\n chevrotainSubrule(<any> this[<keyof (typeof this)>cstDef.name], <any>{ ARGS: [ this.context, ...arg ]})\n ) satisfies CstDef['SUBRULE'];\n return {\n CONSUME: (tokenType, option) => this.CONSUME(tokenType, option),\n CONSUME1: (tokenType, option) => this.CONSUME1(tokenType, option),\n CONSUME2: (tokenType, option) => this.CONSUME2(tokenType, option),\n CONSUME3: (tokenType, option) => this.CONSUME3(tokenType, option),\n CONSUME4: (tokenType, option) => this.CONSUME4(tokenType, option),\n CONSUME5: (tokenType, option) => this.CONSUME5(tokenType, option),\n CONSUME6: (tokenType, option) => this.CONSUME6(tokenType, option),\n CONSUME7: (tokenType, option) => this.CONSUME7(tokenType, option),\n CONSUME8: (tokenType, option) => this.CONSUME8(tokenType, option),\n CONSUME9: (tokenType, option) => this.CONSUME9(tokenType, option),\n OPTION: actionORMethodDef => this.OPTION(actionORMethodDef),\n OPTION1: actionORMethodDef => this.OPTION1(actionORMethodDef),\n OPTION2: actionORMethodDef => this.OPTION2(actionORMethodDef),\n OPTION3: actionORMethodDef => this.OPTION3(actionORMethodDef),\n OPTION4: actionORMethodDef => this.OPTION4(actionORMethodDef),\n OPTION5: actionORMethodDef => this.OPTION5(actionORMethodDef),\n OPTION6: actionORMethodDef => this.OPTION6(actionORMethodDef),\n OPTION7: actionORMethodDef => this.OPTION7(actionORMethodDef),\n OPTION8: actionORMethodDef => this.OPTION8(actionORMethodDef),\n OPTION9: actionORMethodDef => this.OPTION9(actionORMethodDef),\n OR: altsOrOpts => this.OR(altsOrOpts),\n OR1: altsOrOpts => this.OR1(altsOrOpts),\n OR2: altsOrOpts => this.OR2(altsOrOpts),\n OR3: altsOrOpts => this.OR3(altsOrOpts),\n OR4: altsOrOpts => this.OR4(altsOrOpts),\n OR5: altsOrOpts => this.OR5(altsOrOpts),\n OR6: altsOrOpts => this.OR6(altsOrOpts),\n OR7: altsOrOpts => this.OR7(altsOrOpts),\n OR8: altsOrOpts => this.OR8(altsOrOpts),\n OR9: altsOrOpts => this.OR9(altsOrOpts),\n MANY: actionORMethodDef => this.MANY(actionORMethodDef),\n MANY1: actionORMethodDef => this.MANY1(actionORMethodDef),\n MANY2: actionORMethodDef => this.MANY2(actionORMethodDef),\n MANY3: actionORMethodDef => this.MANY3(actionORMethodDef),\n MANY4: actionORMethodDef => this.MANY4(actionORMethodDef),\n MANY5: actionORMethodDef => this.MANY5(actionORMethodDef),\n MANY6: actionORMethodDef => this.MANY6(actionORMethodDef),\n MANY7: actionORMethodDef => this.MANY7(actionORMethodDef),\n MANY8: actionORMethodDef => this.MANY8(actionORMethodDef),\n MANY9: actionORMethodDef => this.MANY9(actionORMethodDef),\n MANY_SEP: options => this.MANY_SEP(options),\n MANY_SEP1: options => this.MANY_SEP1(options),\n MANY_SEP2: options => this.MANY_SEP2(options),\n MANY_SEP3: options => this.MANY_SEP3(options),\n MANY_SEP4: options => this.MANY_SEP4(options),\n MANY_SEP5: options => this.MANY_SEP5(options),\n MANY_SEP6: options => this.MANY_SEP6(options),\n MANY_SEP7: options => this.MANY_SEP7(options),\n MANY_SEP8: options => this.MANY_SEP8(options),\n MANY_SEP9: options => this.MANY_SEP9(options),\n AT_LEAST_ONE: actionORMethodDef => this.AT_LEAST_ONE(actionORMethodDef),\n AT_LEAST_ONE1: actionORMethodDef => this.AT_LEAST_ONE1(actionORMethodDef),\n AT_LEAST_ONE2: actionORMethodDef => this.AT_LEAST_ONE2(actionORMethodDef),\n AT_LEAST_ONE3: actionORMethodDef => this.AT_LEAST_ONE3(actionORMethodDef),\n AT_LEAST_ONE4: actionORMethodDef => this.AT_LEAST_ONE4(actionORMethodDef),\n AT_LEAST_ONE5: actionORMethodDef => this.AT_LEAST_ONE5(actionORMethodDef),\n AT_LEAST_ONE6: actionORMethodDef => this.AT_LEAST_ONE6(actionORMethodDef),\n AT_LEAST_ONE7: actionORMethodDef => this.AT_LEAST_ONE7(actionORMethodDef),\n AT_LEAST_ONE8: actionORMethodDef => this.AT_LEAST_ONE8(actionORMethodDef),\n AT_LEAST_ONE9: actionORMethodDef => this.AT_LEAST_ONE9(actionORMethodDef),\n AT_LEAST_ONE_SEP: options => this.AT_LEAST_ONE_SEP(options),\n AT_LEAST_ONE_SEP1: options => this.AT_LEAST_ONE_SEP1(options),\n AT_LEAST_ONE_SEP2: options => this.AT_LEAST_ONE_SEP2(options),\n AT_LEAST_ONE_SEP3: options => this.AT_LEAST_ONE_SEP3(options),\n AT_LEAST_ONE_SEP4: options => this.AT_LEAST_ONE_SEP4(options),\n AT_LEAST_ONE_SEP5: options => this.AT_LEAST_ONE_SEP5(options),\n AT_LEAST_ONE_SEP6: options => this.AT_LEAST_ONE_SEP6(options),\n AT_LEAST_ONE_SEP7: options => this.AT_LEAST_ONE_SEP7(options),\n AT_LEAST_ONE_SEP8: options => this.AT_LEAST_ONE_SEP8(options),\n AT_LEAST_ONE_SEP9: options => this.AT_LEAST_ONE_SEP9(options),\n ACTION: func => this.ACTION(func),\n BACKTRACK: (cstDef, ...args) =>\n this.BACKTRACK(<any> this[<keyof (typeof this)>cstDef.name], <any>{ ARGS: args }),\n SUBRULE: subRuleImpl((rule, args) => this.SUBRULE(rule, args)),\n SUBRULE1: subRuleImpl((rule, args) => this.SUBRULE1(rule, args)),\n SUBRULE2: subRuleImpl((rule, args) => this.SUBRULE2(rule, args)),\n SUBRULE3: subRuleImpl((rule, args) => this.SUBRULE3(rule, args)),\n SUBRULE4: subRuleImpl((rule, args) => this.SUBRULE4(rule, args)),\n SUBRULE5: subRuleImpl((rule, args) => this.SUBRULE5(rule, args)),\n SUBRULE6: subRuleImpl((rule, args) => this.SUBRULE6(rule, args)),\n SUBRULE7: subRuleImpl((rule, args) => this.SUBRULE7(rule, args)),\n SUBRULE8: subRuleImpl((rule, args) => this.SUBRULE8(rule, args)),\n SUBRULE9: subRuleImpl((rule, args) => this.SUBRULE9(rule, args)),\n };\n }\n}\n"]}
@@ -134,7 +134,7 @@ ${errorLine}`);
134
134
  }
135
135
  build({ tokenVocabulary, parserConfig = {}, lexerConfig = {}, queryPreProcessor = s => s, errorHandler, }) {
136
136
  const lexer = LexerBuilder_js_1.LexerBuilder.create().add(...tokenVocabulary).build({
137
- positionTracking: 'full',
137
+ positionTracking: 'onlyOffset',
138
138
  recoveryEnabled: false,
139
139
  ensureOptimizations: true,
140
140
  safeMode: false,
@@ -159,7 +159,7 @@ ${errorLine}`);
159
159
  parser.setContext(context);
160
160
  const result = parser[rule.name](context, ...args);
161
161
  if (parser.errors.length > 0) {
162
- // Console.log(lexResult);
162
+ // Console.log(JSON.stringify(lexResult, null, 2));
163
163
  if (errorHandler) {
164
164
  errorHandler(parser.errors);
165
165
  }
@@ -1 +1 @@
1
- {"version":3,"file":"parserBuilder.js","sourceRoot":"","sources":["../../../../lib/parser-builder/parserBuilder.ts"],"names":[],"mappings":";;;AAQA,sEAAgE;AAShE,yDAAmD;AAGnD;;GAEG;AACH,SAAS,gBAAgB,CAAkC,KAAQ;IACjE,MAAM,QAAQ,GAA+B,EAAE,CAAC;IAChD,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC7B,CAAC;IACD,OAA8B,QAAQ,CAAC;AACzC,CAAC;AAUD;;;;;GAKG;AACH,iDAAiD;AACjD,MAAa,aAAa;IACxB;;;OAGG;IACI,MAAM,CAAC,MAAM,CAMlB,KAAsD;QAEtD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,OAA2D,IAAI,aAAa,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAC;QACxG,CAAC;QACD,OAAO,IAAI,aAAa,CAAC,EAAE,GAAkC,KAAM,CAAC,KAAK,EAAE,CAAC,CAAC;IAC/E,CAAC;IAEO,KAAK,CAAW;IAExB,YAAoB,UAAoB;QACtC,IAAI,CAAC,KAAK,GAAG,UAAU,CAAC;IAC1B,CAAC;IAEM,YAAY;QAOjB,OAAa,IAAI,CAAC;IACpB,CAAC;IAEM,SAAS;QAUd,OAAa,IAAI,CAAC;IACpB,CAAC;IAED;;OAEG;IACI,SAAS,CAA2C,KAAwC;QAKjG,MAAM,IAAI,GAEE,IAAI,CAAC;QACjB,IAAI,CAAC,K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,CAAC,KAAa,EAAE,OAAgB,EAAE,GAAG,IAAe,EAAE,EAAE;gBAC/F,MAAM,cAAc,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC;gBAChD,MAAM,SAAS,GAAG,KAAK,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;gBAEjD,8BAA8B;gBAC9B,MAAM,CAAC,KAAK,GAAG,SAAS,CAAC,MAAM,CAAC;gBAChC,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;gBAC3B,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC;gBACnD,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBAC7B,0BAA0B;oBAC1B,IAAI,YAAY,EAAE,CAAC;wBACjB,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;oBAC9B,CAAC;yBAAM,CAAC;wBACN,IAAI,CAAC,mBAAmB,CAAC,cAAc,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;oBAC1D,CAAC;gBACH,CAAC;gBACD,OAAO,MAAM,CAAC;YAChB,CAAC,CAAC,CAAC;QACL,CAAC;QACD,OAAmD,oBAAoB,CAAC;IAC1E,CAAC;IAEO,OAAO,CAAC,EAAE,eAAe,EAAE,MAAM,GAAG,EAAE,EAG7C;QAEC,OACuD,IAAI,gCAAa,CAAC,IAAI,CAAC,KAAK,EAAE,eAAe,EAAE,MAAM,CAAC,CAAC;IAChH,CAAC;CACF;AAhQD,sCAgQC","sourcesContent":["import type {\n ILexerConfig,\n IParserConfig,\n IRecognitionException,\n TokenType,\n TokenVocabulary,\n EmbeddedActionsParser,\n} from '@traqula/chevrotain';\nimport { LexerBuilder } from '../lexer-builder/LexerBuilder.js';\nimport type { CheckOverlap } from '../utils.js';\nimport type {\n ParseMethodsFromRules,\n ParserFromRules,\n ParseRuleMap,\n ParseRulesToObject,\n ParseNamesFromList,\n} from './builderTypes.js';\nimport { DynamicParser } from './dynamicParser.js';\nimport type { ParserRule } from './ruleDefTypes.js';\n\n/**\n * Converts a list of ruledefs to a record mapping a name to the corresponding ruledef.\n */\nfunction listToRuleDefMap<T extends readonly ParserRule[]>(rules: T): ParseRulesToObject<T> {\n const newRules: Record<string, ParserRule> = {};\n for (const rule of rules) {\n newRules[rule.name] = rule;\n }\n return <ParseRulesToObject<T>>newRules;\n}\n\nexport interface ParserBuildArgs {\n tokenVocabulary: readonly TokenType[];\n parserConfig?: IParserConfig;\n lexerConfig?: ILexerConfig;\n queryPreProcessor?: (input: string) => string;\n errorHandler?: (errors: IRecognitionException[]) => void;\n}\n\n/**\n * The grammar builder. This is the core of traqula (besides using the amazing chevrotain framework).\n * Using the builder you can create a grammar + AST creator.\n * At any point in time, a parser can be constructed from the added rules.\n * Constructing a parser will cause a validation which will validate the correctness of the grammar.\n */\n// This code is wild so other code can be simple.\nexport class ParserBuilder<Context, Names extends string, RuleDefs extends ParseRuleMap<Names>> {\n /**\n * Create a builder from some initial grammar rules or an existing builder.\n * If a builder is provided, a new copy will be created.\n */\n public static create<\n Rules extends readonly ParserRule[] = readonly ParserRule[],\n Context = Rules[0] extends ParserRule<infer context> ? context : never,\n Names extends string = ParseNamesFromList<Rules>,\n RuleDefs extends ParseRuleMap<Names> = ParseRulesToObject<Rules>,\n >(\n start: Rules | ParserBuilder<Context, Names, RuleDefs>,\n ): ParserBuilder<Context, Names, RuleDefs> {\n if (Array.isArray(start)) {\n return <ParserBuilder<Context, Names, RuleDefs>> <unknown> new ParserBuilder(listToRuleDefMap(start));\n }\n return new ParserBuilder({ ...(<ParserBuilder<any, any, any>>start).rules });\n }\n\n private rules: RuleDefs;\n\n private constructor(startRules: RuleDefs) {\n this.rules = startRules;\n }\n\n public widenContext<NewContext extends Context>(): ParserBuilder<\n NewContext,\nNames,\n{[Key in keyof RuleDefs]: Key extends Names ?\n (RuleDefs[Key] extends ParserRule<any, any, infer RT, infer PT> ? ParserRule<NewContext, Key, RT, PT> : never)\n : never }\n> {\n return <any> this;\n }\n\n public typePatch<Patch extends {[Key in Names]?: [any] | [any, any[]]}>():\n ParserBuilder<Context, Names, {[Key in Names]: Key extends keyof Patch ? (\n Patch[Key] extends [any, any[]] ? ParserRule<Context, Key, Patch[Key][0], Patch[Key][1]> : (\n // Only one - infer yourself\n Patch[Key] extends [any] ? (\n RuleDefs[Key] extends ParserRule<any, any, any, infer Par> ?\n ParserRule<Context, Key, Patch[Key][0], Par> : never\n ) : never\n )\n ) : (RuleDefs[Key] extends ParserRule<Context, Key> ? RuleDefs[Key] : never) }> {\n return <any> this;\n }\n\n /**\n * Change the implementation of an existing grammar rule.\n */\n public patchRule<U extends Names, RET, ARGS extends any[]>(patch: ParserRule<Context, U, RET, ARGS>):\n ParserBuilder<Context, Names, {[Key in Names]: Key extends U ?\n ParserRule<Context, Key, RET, ARGS> :\n (RuleDefs[Key] extends ParserRule<Context, Key> ? RuleDefs[Key] : never)\n } > {\n const self = <ParserBuilder<Context, Names, {[Key in Names]: Key extends U ?\n ParserRule<Context, Key, RET, ARGS> : (RuleDefs[Key] extends ParserRule<Context, Key> ? RuleDefs[Key] : never) }>>\n <unknown> this;\n self.rules[patch.name] = <any> patch;\n return self;\n }\n\n /**\n * Add a rule to the grammar. If the rule already exists, but the implementation differs, an error will be thrown.\n */\n public addRuleRedundant<U extends string, RET, ARGS extends any[]>(rule: ParserRule<Context, U, RET, ARGS>):\n ParserBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n ParserRule<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never)\n }> {\n const self = <ParserBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n ParserRule<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never) }>>\n <unknown> this;\n const rules = <Record<string, ParserRule<Context>>> self.rules;\n if (rules[rule.name] !== undefined && rules[rule.name] !== rule) {\n throw new Error(`Rule ${rule.name} already exists in the builder`);\n }\n rules[rule.name] = rule;\n return self;\n }\n\n /**\n * Add a rule to the grammar. Will raise a typescript error if the rule already exists in the grammar.\n */\n public addRule<U extends string, RET, ARGS extends any[]>(\n rule: CheckOverlap<U, Names, ParserRule<Context, U, RET, ARGS>>,\n ): ParserBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n ParserRule<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never) }> {\n return this.addRuleRedundant(rule);\n }\n\n public addMany<U extends readonly ParserRule<Context>[]>(\n ...rules: CheckOverlap<ParseNamesFromList<U>, Names, U>\n ): ParserBuilder<\n Context,\n Names | ParseNamesFromList<U>,\n {[K in Names | ParseNamesFromList<U>]:\n K extends keyof ParseRulesToObject<typeof rules> ? (\n ParseRulesToObject<typeof rules>[K] extends ParserRule<Context, K> ? ParseRulesToObject<typeof rules>[K] : never\n ) : (\n K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never\n )\n }\n > {\n this.rules = { ...this.rules, ...listToRuleDefMap(rules) };\n return <any> <unknown> this;\n }\n\n /**\n * Delete a grammar rule by its name.\n */\n public deleteRule<U extends Names>(ruleName: U):\n ParserBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never }> {\n delete this.rules[ruleName];\n return <ParserBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never }>>\n <unknown> this;\n }\n\n public getRule<U extends Names>(ruleName: U): RuleDefs[U] extends ParserRule<any, U, infer RT, infer PT> ?\n ParserRule<Context, U, RT, PT> : never {\n return <any> this.rules[ruleName];\n }\n\n /**\n * Merge this grammar builder with another.\n * It is best to merge the bigger grammar with the smaller one.\n * If the two builders both have a grammar rule with the same name,\n * no error will be thrown case they map to the same ruledef object.\n * If they map to a different object, an error will be thrown.\n * To fix this problem, the overridingRules array should contain a rule with the same conflicting name,\n * this rule implementation will be used.\n */\n public merge<\n OtherNames extends string,\n OtherRules extends ParseRuleMap<OtherNames>,\n OW extends readonly ParserRule<Context>[],\n >(\n builder: ParserBuilder<Context, OtherNames, OtherRules>,\n overridingRules: OW,\n ):\n ParserBuilder<\n Context,\n Names | OtherNames | ParseNamesFromList<OW>,\n {[K in Names | OtherNames | ParseNamesFromList<OW>]:\n K extends keyof ParseRulesToObject<OW> ? (\n ParseRulesToObject<OW>[K] extends ParserRule<Context, K> ? ParseRulesToObject<OW>[K] : never\n )\n : (\n K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never)\n : K extends OtherNames ? (OtherRules[K] extends ParserRule<Context, K> ? OtherRules[K] : never) : never\n ) }\n > {\n // Assume the other grammar is bigger than yours. So start from that one and add this one\n const otherRules: Record<string, ParserRule<Context>> = { ...builder.rules };\n const myRules: Record<string, ParserRule<Context>> = this.rules;\n\n for (const rule of Object.values(myRules)) {\n if (otherRules[rule.name] === undefined) {\n otherRules[rule.name] = rule;\n } else {\n const existingRule = otherRules[rule.name];\n // If same rule, no issue, move on. Else\n if (existingRule !== rule) {\n const override = overridingRules.find(x => x.name === rule.name);\n // If override specified, take override, else, inform user that there is a conflict\n if (override) {\n otherRules[rule.name] = override;\n } else {\n throw new Error(`Rule with name \"${rule.name}\" already exists in the builder, specify an override to resolve conflict`);\n }\n }\n }\n }\n\n this.rules = <any> <unknown> otherRules;\n return <any> <unknown> this;\n }\n\n private defaultErrorHandler(input: string, errors: IRecognitionException[]): void {\n const firstError = errors[0];\n const messageBuilder: string[] = [ 'Parse error' ];\n const lineIdx = firstError.token.startLine;\n if (lineIdx !== undefined && !Number.isNaN(lineIdx)) {\n const errorLine = input.split('\\n')[lineIdx - 1];\n messageBuilder.push(` on line ${lineIdx}\n${errorLine}`);\n const columnIdx = firstError.token.startColumn;\n if (columnIdx !== undefined) {\n messageBuilder.push(`\\n${'-'.repeat(columnIdx - 1)}^`);\n }\n }\n messageBuilder.push(`\\n${firstError.message}`);\n throw new Error(messageBuilder.join(''));\n }\n\n public build({\n tokenVocabulary,\n parserConfig = {},\n lexerConfig = {},\n queryPreProcessor = s => s,\n errorHandler,\n }: ParserBuildArgs): ParserFromRules<Context, Names, RuleDefs> {\n const lexer = LexerBuilder.create().add(...tokenVocabulary).build({\n positionTracking: 'full',\n recoveryEnabled: false,\n ensureOptimizations: true,\n safeMode: false,\n skipValidations: true,\n ...lexerConfig,\n });\n // Get the chevrotain parser\n const parser = this.consume({\n tokenVocabulary: <TokenType[]> tokenVocabulary,\n config: parserConfig,\n });\n // Start building a parser that does not pass input using a state, but instead gets it as a function argument.\n const selfSufficientParser: Partial<ParserFromRules<Context, Names, RuleDefs>> = {};\n\n // To do that, we need to create a wrapper for each parser rule.\n // eslint-disable-next-line ts/no-unnecessary-type-assertion\n for (const rule of <ParserRule<Context, Names>[]> Object.values(this.rules)) {\n selfSufficientParser[rule.name] = <any> ((input: string, context: Context, ...args: unknown[]) => {\n const processedInput = queryPreProcessor(input);\n const lexResult = lexer.tokenize(processedInput);\n\n // This also resets the parser\n parser.input = lexResult.tokens;\n parser.setContext(context);\n const result = parser[rule.name](context, ...args);\n if (parser.errors.length > 0) {\n // Console.log(lexResult);\n if (errorHandler) {\n errorHandler(parser.errors);\n } else {\n this.defaultErrorHandler(processedInput, parser.errors);\n }\n }\n return result;\n });\n }\n return <ParserFromRules<Context, Names, RuleDefs>> selfSufficientParser;\n }\n\n private consume({ tokenVocabulary, config = {}}: {\n tokenVocabulary: TokenVocabulary;\n config?: IParserConfig;\n }): EmbeddedActionsParser & ParseMethodsFromRules<Context, Names, RuleDefs> &\n { setContext: (context: Context) => void } {\n return <EmbeddedActionsParser & ParseMethodsFromRules<Context, Names, RuleDefs> &\n { setContext: (context: Context) => void }><unknown> new DynamicParser(this.rules, tokenVocabulary, config);\n }\n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CAAC,MAAM,CAAC;gBAChC,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;gBAC3B,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC;gBACnD,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBAC7B,mDAAmD;oBACnD,IAAI,YAAY,EAAE,CAAC;wBACjB,YAAY,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;oBAC9B,CAAC;yBAAM,CAAC;wBACN,IAAI,CAAC,mBAAmB,CAAC,cAAc,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;oBAC1D,CAAC;gBACH,CAAC;gBACD,OAAO,MAAM,CAAC;YAChB,CAAC,CAAC,CAAC;QACL,CAAC;QACD,OAAmD,oBAAoB,CAAC;IAC1E,CAAC;IAEO,OAAO,CAAC,EAAE,eAAe,EAAE,MAAM,GAAG,EAAE,EAG7C;QAEC,OACuD,IAAI,gCAAa,CAAC,IAAI,CAAC,KAAK,EAAE,eAAe,EAAE,MAAM,CAAC,CAAC;IAChH,CAAC;CACF;AAhQD,sCAgQC","sourcesContent":["import type {\n ILexerConfig,\n IParserConfig,\n IRecognitionException,\n TokenType,\n TokenVocabulary,\n EmbeddedActionsParser,\n} from '@traqula/chevrotain';\nimport { LexerBuilder } from '../lexer-builder/LexerBuilder.js';\nimport type { CheckOverlap } from '../utils.js';\nimport type {\n ParseMethodsFromRules,\n ParserFromRules,\n ParseRuleMap,\n ParseRulesToObject,\n ParseNamesFromList,\n} from './builderTypes.js';\nimport { DynamicParser } from './dynamicParser.js';\nimport type { ParserRule } from './ruleDefTypes.js';\n\n/**\n * Converts a list of ruledefs to a record mapping a name to the corresponding ruledef.\n */\nfunction listToRuleDefMap<T extends readonly ParserRule[]>(rules: T): ParseRulesToObject<T> {\n const newRules: Record<string, ParserRule> = {};\n for (const rule of rules) {\n newRules[rule.name] = rule;\n }\n return <ParseRulesToObject<T>>newRules;\n}\n\nexport interface ParserBuildArgs {\n tokenVocabulary: readonly TokenType[];\n parserConfig?: IParserConfig;\n lexerConfig?: ILexerConfig;\n queryPreProcessor?: (input: string) => string;\n errorHandler?: (errors: IRecognitionException[]) => void;\n}\n\n/**\n * The grammar builder. This is the core of traqula (besides using the amazing chevrotain framework).\n * Using the builder you can create a grammar + AST creator.\n * At any point in time, a parser can be constructed from the added rules.\n * Constructing a parser will cause a validation which will validate the correctness of the grammar.\n */\n// This code is wild so other code can be simple.\nexport class ParserBuilder<Context, Names extends string, RuleDefs extends ParseRuleMap<Names>> {\n /**\n * Create a builder from some initial grammar rules or an existing builder.\n * If a builder is provided, a new copy will be created.\n */\n public static create<\n Rules extends readonly ParserRule[] = readonly ParserRule[],\n Context = Rules[0] extends ParserRule<infer context> ? context : never,\n Names extends string = ParseNamesFromList<Rules>,\n RuleDefs extends ParseRuleMap<Names> = ParseRulesToObject<Rules>,\n >(\n start: Rules | ParserBuilder<Context, Names, RuleDefs>,\n ): ParserBuilder<Context, Names, RuleDefs> {\n if (Array.isArray(start)) {\n return <ParserBuilder<Context, Names, RuleDefs>> <unknown> new ParserBuilder(listToRuleDefMap(start));\n }\n return new ParserBuilder({ ...(<ParserBuilder<any, any, any>>start).rules });\n }\n\n private rules: RuleDefs;\n\n private constructor(startRules: RuleDefs) {\n this.rules = startRules;\n }\n\n public widenContext<NewContext extends Context>(): ParserBuilder<\n NewContext,\nNames,\n{[Key in keyof RuleDefs]: Key extends Names ?\n (RuleDefs[Key] extends ParserRule<any, any, infer RT, infer PT> ? ParserRule<NewContext, Key, RT, PT> : never)\n : never }\n> {\n return <any> this;\n }\n\n public typePatch<Patch extends {[Key in Names]?: [any] | [any, any[]]}>():\n ParserBuilder<Context, Names, {[Key in Names]: Key extends keyof Patch ? (\n Patch[Key] extends [any, any[]] ? ParserRule<Context, Key, Patch[Key][0], Patch[Key][1]> : (\n // Only one - infer yourself\n Patch[Key] extends [any] ? (\n RuleDefs[Key] extends ParserRule<any, any, any, infer Par> ?\n ParserRule<Context, Key, Patch[Key][0], Par> : never\n ) : never\n )\n ) : (RuleDefs[Key] extends ParserRule<Context, Key> ? RuleDefs[Key] : never) }> {\n return <any> this;\n }\n\n /**\n * Change the implementation of an existing grammar rule.\n */\n public patchRule<U extends Names, RET, ARGS extends any[]>(patch: ParserRule<Context, U, RET, ARGS>):\n ParserBuilder<Context, Names, {[Key in Names]: Key extends U ?\n ParserRule<Context, Key, RET, ARGS> :\n (RuleDefs[Key] extends ParserRule<Context, Key> ? RuleDefs[Key] : never)\n } > {\n const self = <ParserBuilder<Context, Names, {[Key in Names]: Key extends U ?\n ParserRule<Context, Key, RET, ARGS> : (RuleDefs[Key] extends ParserRule<Context, Key> ? RuleDefs[Key] : never) }>>\n <unknown> this;\n self.rules[patch.name] = <any> patch;\n return self;\n }\n\n /**\n * Add a rule to the grammar. If the rule already exists, but the implementation differs, an error will be thrown.\n */\n public addRuleRedundant<U extends string, RET, ARGS extends any[]>(rule: ParserRule<Context, U, RET, ARGS>):\n ParserBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n ParserRule<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never)\n }> {\n const self = <ParserBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n ParserRule<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never) }>>\n <unknown> this;\n const rules = <Record<string, ParserRule<Context>>> self.rules;\n if (rules[rule.name] !== undefined && rules[rule.name] !== rule) {\n throw new Error(`Rule ${rule.name} already exists in the builder`);\n }\n rules[rule.name] = rule;\n return self;\n }\n\n /**\n * Add a rule to the grammar. Will raise a typescript error if the rule already exists in the grammar.\n */\n public addRule<U extends string, RET, ARGS extends any[]>(\n rule: CheckOverlap<U, Names, ParserRule<Context, U, RET, ARGS>>,\n ): ParserBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n ParserRule<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never) }> {\n return this.addRuleRedundant(rule);\n }\n\n public addMany<U extends readonly ParserRule<Context>[]>(\n ...rules: CheckOverlap<ParseNamesFromList<U>, Names, U>\n ): ParserBuilder<\n Context,\n Names | ParseNamesFromList<U>,\n {[K in Names | ParseNamesFromList<U>]:\n K extends keyof ParseRulesToObject<typeof rules> ? (\n ParseRulesToObject<typeof rules>[K] extends ParserRule<Context, K> ? ParseRulesToObject<typeof rules>[K] : never\n ) : (\n K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never\n )\n }\n > {\n this.rules = { ...this.rules, ...listToRuleDefMap(rules) };\n return <any> <unknown> this;\n }\n\n /**\n * Delete a grammar rule by its name.\n */\n public deleteRule<U extends Names>(ruleName: U):\n ParserBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never }> {\n delete this.rules[ruleName];\n return <ParserBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never }>>\n <unknown> this;\n }\n\n public getRule<U extends Names>(ruleName: U): RuleDefs[U] extends ParserRule<any, U, infer RT, infer PT> ?\n ParserRule<Context, U, RT, PT> : never {\n return <any> this.rules[ruleName];\n }\n\n /**\n * Merge this grammar builder with another.\n * It is best to merge the bigger grammar with the smaller one.\n * If the two builders both have a grammar rule with the same name,\n * no error will be thrown case they map to the same ruledef object.\n * If they map to a different object, an error will be thrown.\n * To fix this problem, the overridingRules array should contain a rule with the same conflicting name,\n * this rule implementation will be used.\n */\n public merge<\n OtherNames extends string,\n OtherRules extends ParseRuleMap<OtherNames>,\n OW extends readonly ParserRule<Context>[],\n >(\n builder: ParserBuilder<Context, OtherNames, OtherRules>,\n overridingRules: OW,\n ):\n ParserBuilder<\n Context,\n Names | OtherNames | ParseNamesFromList<OW>,\n {[K in Names | OtherNames | ParseNamesFromList<OW>]:\n K extends keyof ParseRulesToObject<OW> ? (\n ParseRulesToObject<OW>[K] extends ParserRule<Context, K> ? ParseRulesToObject<OW>[K] : never\n )\n : (\n K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never)\n : K extends OtherNames ? (OtherRules[K] extends ParserRule<Context, K> ? OtherRules[K] : never) : never\n ) }\n > {\n // Assume the other grammar is bigger than yours. So start from that one and add this one\n const otherRules: Record<string, ParserRule<Context>> = { ...builder.rules };\n const myRules: Record<string, ParserRule<Context>> = this.rules;\n\n for (const rule of Object.values(myRules)) {\n if (otherRules[rule.name] === undefined) {\n otherRules[rule.name] = rule;\n } else {\n const existingRule = otherRules[rule.name];\n // If same rule, no issue, move on. Else\n if (existingRule !== rule) {\n const override = overridingRules.find(x => x.name === rule.name);\n // If override specified, take override, else, inform user that there is a conflict\n if (override) {\n otherRules[rule.name] = override;\n } else {\n throw new Error(`Rule with name \"${rule.name}\" already exists in the builder, specify an override to resolve conflict`);\n }\n }\n }\n }\n\n this.rules = <any> <unknown> otherRules;\n return <any> <unknown> this;\n }\n\n private defaultErrorHandler(input: string, errors: IRecognitionException[]): void {\n const firstError = errors[0];\n const messageBuilder: string[] = [ 'Parse error' ];\n const lineIdx = firstError.token.startLine;\n if (lineIdx !== undefined && !Number.isNaN(lineIdx)) {\n const errorLine = input.split('\\n')[lineIdx - 1];\n messageBuilder.push(` on line ${lineIdx}\n${errorLine}`);\n const columnIdx = firstError.token.startColumn;\n if (columnIdx !== undefined) {\n messageBuilder.push(`\\n${'-'.repeat(columnIdx - 1)}^`);\n }\n }\n messageBuilder.push(`\\n${firstError.message}`);\n throw new Error(messageBuilder.join(''));\n }\n\n public build({\n tokenVocabulary,\n parserConfig = {},\n lexerConfig = {},\n queryPreProcessor = s => s,\n errorHandler,\n }: ParserBuildArgs): ParserFromRules<Context, Names, RuleDefs> {\n const lexer = LexerBuilder.create().add(...tokenVocabulary).build({\n positionTracking: 'onlyOffset',\n recoveryEnabled: false,\n ensureOptimizations: true,\n safeMode: false,\n skipValidations: true,\n ...lexerConfig,\n });\n // Get the chevrotain parser\n const parser = this.consume({\n tokenVocabulary: <TokenType[]> tokenVocabulary,\n config: parserConfig,\n });\n // Start building a parser that does not pass input using a state, but instead gets it as a function argument.\n const selfSufficientParser: Partial<ParserFromRules<Context, Names, RuleDefs>> = {};\n\n // To do that, we need to create a wrapper for each parser rule.\n // eslint-disable-next-line ts/no-unnecessary-type-assertion\n for (const rule of <ParserRule<Context, Names>[]> Object.values(this.rules)) {\n selfSufficientParser[rule.name] = <any> ((input: string, context: Context, ...args: unknown[]) => {\n const processedInput = queryPreProcessor(input);\n const lexResult = lexer.tokenize(processedInput);\n\n // This also resets the parser\n parser.input = lexResult.tokens;\n parser.setContext(context);\n const result = parser[rule.name](context, ...args);\n if (parser.errors.length > 0) {\n // Console.log(JSON.stringify(lexResult, null, 2));\n if (errorHandler) {\n errorHandler(parser.errors);\n } else {\n this.defaultErrorHandler(processedInput, parser.errors);\n }\n }\n return result;\n });\n }\n return <ParserFromRules<Context, Names, RuleDefs>> selfSufficientParser;\n }\n\n private consume({ tokenVocabulary, config = {}}: {\n tokenVocabulary: TokenVocabulary;\n config?: IParserConfig;\n }): EmbeddedActionsParser & ParseMethodsFromRules<Context, Names, RuleDefs> &\n { setContext: (context: Context) => void } {\n return <EmbeddedActionsParser & ParseMethodsFromRules<Context, Names, RuleDefs> &\n { setContext: (context: Context) => void }><unknown> new DynamicParser(this.rules, tokenVocabulary, config);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"TransformerObject.js","sourceRoot":"","sources":["../../../../lib/transformers/TransformerObject.ts"],"names":[],"mappings":";;;AAsCA,MAAa,iBAAiB;IAMU;IAL5B,YAAY,GAAG,SAAS,CAAC;IACnC;;;OAGG;IACH,YAAsC,iBAAmC,EAAE;QAArC,mBAAc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G,CAAC,CAAC;wBAClB,CAAC;oBACH,CAAC;gBACH,CAAC;YACH,CAAC;YACD,aAAa,EAAE,CAAC;QAClB,CAAC;QACD,IAAI,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;QACvD,CAAC;QACD,aAAa,EAAE,CAAC;IAClB,CAAC;CACF;AA9OD,8CA8OC","sourcesContent":["export interface VisitContext {\n /**\n * Whether you should stop iterating after this object. Default false.\n */\n shortcut?: boolean;\n /**\n * Whether you should continue iterating deeper with this object. Default true.\n */\n continue?: boolean;\n /**\n * Object keys that can be ignored, meaning they do not get visited.\n */\n ignoreKeys?: Set<string>;\n}\n\nexport interface TransformContext extends VisitContext {\n /**\n * Object keys that will be shallowly copied but not traversed.\n * When the same key is included here and in ignoreKeys, the copy will still be made.\n */\n shallowKeys?: Set<string>;\n /**\n * Whether the visited object should be shallowly copied or not. Defaults to true.\n */\n copy?: boolean;\n}\n\nexport interface SelectiveTraversalContext<Nodes> {\n /**\n * Nodes you should visit next. Defaults to empty list\n */\n next?: Nodes[];\n /**\n * Whether you should stop visiting after visiting this object. Default false.\n */\n shortcut?: boolean;\n}\n\nexport class TransformerObject {\n protected maxStackSize = 1_000_000;\n /**\n * Creates stateless transformer.\n * @param defaultContext\n */\n public constructor(protected readonly defaultContext: TransformContext = {}) {}\n\n public clone(newDefaultContext: TransformContext = {}): TransformerObject {\n return new TransformerObject({ ...this.defaultContext, ...newDefaultContext });\n }\n\n /**\n * Function to shallow clone any type.\n * @param obj\n * @protected\n */\n protected cloneObj<T>(obj: T): T {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n const proto = Object.getPrototypeOf(obj);\n\n // Fast path: plain object\n if (proto === Object.prototype || proto === null) {\n // Spread or assign preserves fast properties\n return { ...obj };\n }\n\n // Otherwise, preserve prototype for custom objects\n return Object.assign(Object.create(proto), obj);\n }\n\n /**\n * Recursively transforms all objects that are not arrays. Mapper is called on deeper objects first.\n * @param startObject object to start iterating from\n * @param mapper mapper to transform the various objects - argument is a copy of the original\n * @param preVisitor callback that is evaluated before iterating deeper.\n * If continues is false, we do not iterate deeper, current object is still mapped. - default: true\n * If shortcut is true, we do not iterate deeper, nor do we branch out, this mapper will be the last one called.\n * - Default false\n */\n public transformObject(\n startObject: object,\n mapper: (copy: object, orig: object) => unknown,\n preVisitor: (orig: object) => TransformContext = () => ({}),\n ): unknown {\n const defaults = this.defaultContext;\n const defaultCopyFlag = defaults.copy ?? true;\n const defaultContinues = defaults.continue ?? true;\n const defaultIgnoreKeys = defaults.ignoreKeys;\n const defaultShallowKeys = defaults.shallowKeys;\n const defaultDidShortCut = defaults.shortcut ?? false;\n\n // Code handles own stack instead of using recursion - this optimizes it for deep operations.\n let didShortCut = false;\n const resultWrap = { res: startObject };\n\n // Grows with stack\n const stack = [ startObject ];\n const stackParent: object[] = [ resultWrap ];\n const stackParentKey: string[] = [ 'res' ];\n\n // Grows with reverse stack - when popping down the stack, you realise you still want to map something.\n // Counter of stack size when we started adding the children of this object, going beyond this means a new parent\n const handleMapperOnLen: number[] = [];\n const mapperCopyStack: object[] = [];\n const mapperOrigStack: object[] = [];\n const mapperParent: object[] = [];\n const mapperParentKey: string[] = [];\n\n function handleMapper(): void {\n while (stack.length === handleMapperOnLen.at(-1)) {\n handleMapperOnLen.pop();\n const copyToMap = mapperCopyStack.pop()!;\n const origToMap = mapperOrigStack.pop()!;\n const parent = <Record<string, unknown>> mapperParent.pop()!;\n const parentKey = mapperParentKey.pop()!;\n parent[parentKey] = mapper(copyToMap, origToMap);\n }\n }\n\n while (stack.length > 0 && stack.length < this.maxStackSize) {\n const curObject = stack.pop()!;\n const curParent = stackParent.pop()!;\n const curKey = stackParentKey.pop()!;\n\n // Only add to the stack when you did not shortcut\n if (!didShortCut) {\n if (Array.isArray(curObject)) {\n const newArr = [ ...curObject ];\n handleMapperOnLen.push(stack.length);\n mapperCopyStack.push(newArr);\n mapperOrigStack.push(curObject);\n mapperParent.push(curParent);\n mapperParentKey.push(curKey);\n\n for (let index = curObject.length - 1; index >= 0; index--) {\n const val = curObject[index];\n if (val !== null && typeof val === 'object') {\n stack.push(val);\n stackParent.push(newArr);\n stackParentKey.push(index.toString());\n }\n }\n handleMapper();\n continue;\n }\n\n // Perform pre visit before expanding the stack\n const context = preVisitor(<any>curObject);\n const copyFlag = context.copy ?? defaultCopyFlag;\n const continues = context.continue ?? defaultContinues;\n const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;\n const shallowKeys = context.shallowKeys ?? defaultShallowKeys;\n didShortCut = context.shortcut ?? defaultDidShortCut;\n\n const copy = copyFlag ? this.cloneObj(curObject) : curObject;\n\n // Register that you want to be visited\n handleMapperOnLen.push(stack.length);\n mapperCopyStack.push(copy);\n mapperOrigStack.push(curObject);\n mapperParent.push(curParent);\n mapperParentKey.push(curKey);\n\n // Extend stack if needed. When shortcutted, should still unwind the stack, but no longer add to it.\n if (continues && !didShortCut) {\n for (const key in copy) {\n if (!Object.hasOwn(copy, key)) {\n continue;\n }\n const val = (<Record<string, unknown>> copy)[key];\n\n // If shallow copy required, do\n const onlyShallow = shallowKeys && shallowKeys?.has(key);\n if (onlyShallow) {\n // Do not add stack entry - assign straight away\n (<Record<string, unknown>> copy)[key] = this.cloneObj(val);\n }\n if (ignoreKeys && ignoreKeys.has(key)) {\n // Do not add stack entry\n continue;\n }\n if (!onlyShallow && val !== null && typeof val === 'object') {\n // Do add stack entry.\n stack.push(val);\n stackParentKey.push(key);\n stackParent.push(copy);\n }\n }\n }\n }\n handleMapper();\n }\n if (stack.length >= this.maxStackSize) {\n throw new Error('Transform object stack overflowed');\n }\n handleMapper();\n\n return <any> resultWrap.res;\n }\n\n /**\n * Visitor that visits all objects. Visits deeper objects first.\n */\n public visitObject(\n startObject: object,\n visitor: (orig: object) => void,\n preVisitor: (orig: object) => VisitContext = () => ({}),\n ): void {\n const defaults = this.defaultContext;\n const defaultContinues = defaults.continue ?? true;\n const defaultIgnoreKeys = defaults.ignoreKeys;\n const defaultShortcut = defaults.shortcut ?? false;\n\n let didShortCut = false;\n\n // Stack of things to preVisit\n const stack = [ startObject ];\n // When the stack is done preVisiting things above this lengths, visit the bellow\n const handleVisitorOnLen: number[] = [];\n const visitorStack: object[] = [];\n\n function handleVisitor(): void {\n while (stack.length === handleVisitorOnLen.at(-1)) {\n handleVisitorOnLen.pop();\n const toVisit = visitorStack.pop()!;\n visitor(toVisit);\n }\n }\n\n while (stack.length > 0 && stack.length < this.maxStackSize) {\n const curObject = stack.pop()!;\n\n if (!didShortCut) {\n if (Array.isArray(curObject)) {\n for (let i = curObject.length - 1; i >= 0; i--) {\n stack.push(curObject[i]);\n }\n handleVisitor();\n continue;\n }\n\n // Perform pre visit before expanding the stack\n const context = preVisitor(curObject);\n didShortCut = context.shortcut ?? defaultShortcut;\n const continues = context.continue ?? defaultContinues;\n const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;\n\n // Register that you want to be visited\n handleVisitorOnLen.push(stack.length);\n visitorStack.push(curObject);\n\n // Extend stack if needed. When shortcutted, should still unwind the stack, but no longer add to it.\n if (continues && !didShortCut) {\n for (const key in curObject) {\n if (!Object.hasOwn(curObject, key)) {\n continue;\n }\n if (ignoreKeys && ignoreKeys.has(key)) {\n continue;\n }\n const val = (<Record<string, unknown>> curObject)[key];\n if (val && typeof val === 'object') {\n stack.push(val);\n }\n }\n }\n }\n handleVisitor();\n }\n if (stack.length >= this.maxStackSize) {\n throw new Error('Transform object stack overflowed');\n }\n handleVisitor();\n }\n}\n"]}
1
+ {"version":3,"file":"TransformerObject.js","sourceRoot":"","sources":["../../../../lib/transformers/TransformerObject.ts"],"names":[],"mappings":";;;AAsCA,MAAa,iBAAiB;IAMU;IAL5B,YAAY,GAAG,SAAS,CAAC;IACnC;;;OAGG;IACH,YAAsC,iBAAmC,EAAE;QAArC,mBAAc,GAAd,cAAc,CAAuB;IAAG,CAAC;IAExE,KAAK,CAA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C;YACH,CAAC;YACD,aAAa,EAAE,CAAC;QAClB,CAAC;QACD,IAAI,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtC,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;QACvD,CAAC;QACD,aAAa,EAAE,CAAC;IAClB,CAAC;CACF;AA9OD,8CA8OC","sourcesContent":["export interface VisitContext {\n /**\n * Whether you should stop iterating after this object. Default false.\n */\n shortcut?: boolean;\n /**\n * Whether you should continue iterating deeper with this object. Default true.\n */\n continue?: boolean;\n /**\n * Object keys that can be ignored, meaning they do not get visited.\n */\n ignoreKeys?: Set<string>;\n}\n\nexport interface TransformContext extends VisitContext {\n /**\n * Object keys that will be shallowly copied but not traversed.\n * When the same key is included here and in ignoreKeys, the copy will still be made.\n */\n shallowKeys?: Set<string>;\n /**\n * Whether the visited object should be shallowly copied or not. Defaults to true.\n */\n copy?: boolean;\n}\n\nexport interface SelectiveTraversalContext<Nodes> {\n /**\n * Nodes you should visit next. Defaults to empty list\n */\n next?: Nodes[];\n /**\n * Whether you should stop visiting after visiting this object. Default false.\n */\n shortcut?: boolean;\n}\n\nexport class TransformerObject {\n protected maxStackSize = 1_000_000;\n /**\n * Creates stateless transformer.\n * @param defaultContext\n */\n public constructor(protected readonly defaultContext: TransformContext = {}) {}\n\n public clone(newDefaultContext: TransformContext = {}): TransformerObject {\n return new TransformerObject({ ...this.defaultContext, ...newDefaultContext });\n }\n\n /**\n * Function to shallow clone any type.\n * @param obj\n * @protected\n */\n public cloneObj<T>(obj: T): T {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n const proto = Object.getPrototypeOf(obj);\n\n // Fast path: plain object\n if (proto === Object.prototype || proto === null) {\n // Spread or assign preserves fast properties\n return { ...obj };\n }\n\n // Otherwise, preserve prototype for custom objects\n return Object.assign(Object.create(proto), obj);\n }\n\n /**\n * Recursively transforms all objects that are not arrays. Mapper is called on deeper objects first.\n * @param startObject object to start iterating from\n * @param mapper mapper to transform the various objects - argument is a copy of the original\n * @param preVisitor callback that is evaluated before iterating deeper.\n * If continues is false, we do not iterate deeper, current object is still mapped. - default: true\n * If shortcut is true, we do not iterate deeper, nor do we branch out, this mapper will be the last one called.\n * - Default false\n */\n public transformObject(\n startObject: object,\n mapper: (copy: object, orig: object) => unknown,\n preVisitor: (orig: object) => TransformContext = () => ({}),\n ): unknown {\n const defaults = this.defaultContext;\n const defaultCopyFlag = defaults.copy ?? true;\n const defaultContinues = defaults.continue ?? true;\n const defaultIgnoreKeys = defaults.ignoreKeys;\n const defaultShallowKeys = defaults.shallowKeys;\n const defaultDidShortCut = defaults.shortcut ?? false;\n\n // Code handles own stack instead of using recursion - this optimizes it for deep operations.\n let didShortCut = false;\n const resultWrap = { res: startObject };\n\n // Grows with stack\n const stack = [ startObject ];\n const stackParent: object[] = [ resultWrap ];\n const stackParentKey: string[] = [ 'res' ];\n\n // Grows with reverse stack - when popping down the stack, you realise you still want to map something.\n // Counter of stack size when we started adding the children of this object, going beyond this means a new parent\n const handleMapperOnLen: number[] = [];\n const mapperCopyStack: object[] = [];\n const mapperOrigStack: object[] = [];\n const mapperParent: object[] = [];\n const mapperParentKey: string[] = [];\n\n function handleMapper(): void {\n while (stack.length === handleMapperOnLen.at(-1)) {\n handleMapperOnLen.pop();\n const copyToMap = mapperCopyStack.pop()!;\n const origToMap = mapperOrigStack.pop()!;\n const parent = <Record<string, unknown>> mapperParent.pop()!;\n const parentKey = mapperParentKey.pop()!;\n parent[parentKey] = mapper(copyToMap, origToMap);\n }\n }\n\n while (stack.length > 0 && stack.length < this.maxStackSize) {\n const curObject = stack.pop()!;\n const curParent = stackParent.pop()!;\n const curKey = stackParentKey.pop()!;\n\n // Only add to the stack when you did not shortcut\n if (!didShortCut) {\n if (Array.isArray(curObject)) {\n const newArr = [ ...curObject ];\n handleMapperOnLen.push(stack.length);\n mapperCopyStack.push(newArr);\n mapperOrigStack.push(curObject);\n mapperParent.push(curParent);\n mapperParentKey.push(curKey);\n\n for (let index = curObject.length - 1; index >= 0; index--) {\n const val = curObject[index];\n if (val !== null && typeof val === 'object') {\n stack.push(val);\n stackParent.push(newArr);\n stackParentKey.push(index.toString());\n }\n }\n handleMapper();\n continue;\n }\n\n // Perform pre visit before expanding the stack\n const context = preVisitor(<any>curObject);\n const copyFlag = context.copy ?? defaultCopyFlag;\n const continues = context.continue ?? defaultContinues;\n const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;\n const shallowKeys = context.shallowKeys ?? defaultShallowKeys;\n didShortCut = context.shortcut ?? defaultDidShortCut;\n\n const copy = copyFlag ? this.cloneObj(curObject) : curObject;\n\n // Register that you want to be visited\n handleMapperOnLen.push(stack.length);\n mapperCopyStack.push(copy);\n mapperOrigStack.push(curObject);\n mapperParent.push(curParent);\n mapperParentKey.push(curKey);\n\n // Extend stack if needed. When shortcutted, should still unwind the stack, but no longer add to it.\n if (continues && !didShortCut) {\n for (const key in copy) {\n if (!Object.hasOwn(copy, key)) {\n continue;\n }\n const val = (<Record<string, unknown>> copy)[key];\n\n // If shallow copy required, do\n const onlyShallow = shallowKeys && shallowKeys?.has(key);\n if (onlyShallow) {\n // Do not add stack entry - assign straight away\n (<Record<string, unknown>> copy)[key] = this.cloneObj(val);\n }\n if (ignoreKeys && ignoreKeys.has(key)) {\n // Do not add stack entry\n continue;\n }\n if (!onlyShallow && val !== null && typeof val === 'object') {\n // Do add stack entry.\n stack.push(val);\n stackParentKey.push(key);\n stackParent.push(copy);\n }\n }\n }\n }\n handleMapper();\n }\n if (stack.length >= this.maxStackSize) {\n throw new Error('Transform object stack overflowed');\n }\n handleMapper();\n\n return <any> resultWrap.res;\n }\n\n /**\n * Visitor that visits all objects. Visits deeper objects first.\n */\n public visitObject(\n startObject: object,\n visitor: (orig: object) => void,\n preVisitor: (orig: object) => VisitContext = () => ({}),\n ): void {\n const defaults = this.defaultContext;\n const defaultContinues = defaults.continue ?? true;\n const defaultIgnoreKeys = defaults.ignoreKeys;\n const defaultShortcut = defaults.shortcut ?? false;\n\n let didShortCut = false;\n\n // Stack of things to preVisit\n const stack = [ startObject ];\n // When the stack is done preVisiting things above this lengths, visit the bellow\n const handleVisitorOnLen: number[] = [];\n const visitorStack: object[] = [];\n\n function handleVisitor(): void {\n while (stack.length === handleVisitorOnLen.at(-1)) {\n handleVisitorOnLen.pop();\n const toVisit = visitorStack.pop()!;\n visitor(toVisit);\n }\n }\n\n while (stack.length > 0 && stack.length < this.maxStackSize) {\n const curObject = stack.pop()!;\n\n if (!didShortCut) {\n if (Array.isArray(curObject)) {\n for (let i = curObject.length - 1; i >= 0; i--) {\n stack.push(curObject[i]);\n }\n handleVisitor();\n continue;\n }\n\n // Perform pre visit before expanding the stack\n const context = preVisitor(curObject);\n didShortCut = context.shortcut ?? defaultShortcut;\n const continues = context.continue ?? defaultContinues;\n const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;\n\n // Register that you want to be visited\n handleVisitorOnLen.push(stack.length);\n visitorStack.push(curObject);\n\n // Extend stack if needed. When shortcutted, should still unwind the stack, but no longer add to it.\n if (continues && !didShortCut) {\n for (const key in curObject) {\n if (!Object.hasOwn(curObject, key)) {\n continue;\n }\n if (ignoreKeys && ignoreKeys.has(key)) {\n continue;\n }\n const val = (<Record<string, unknown>> curObject)[key];\n if (val && typeof val === 'object') {\n stack.push(val);\n }\n }\n }\n }\n handleVisitor();\n }\n if (stack.length >= this.maxStackSize) {\n throw new Error('Transform object stack overflowed');\n }\n handleVisitor();\n }\n}\n"]}