@traqula/core 0.0.18 → 0.0.20

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 (36) hide show
  1. package/lib/AstCoreFactory.js +1 -1
  2. package/lib/AstCoreFactory.js.map +1 -1
  3. package/lib/TransformerObject.d.ts +64 -0
  4. package/lib/TransformerObject.js +204 -0
  5. package/lib/TransformerObject.js.map +1 -0
  6. package/lib/TransformerSubTyped.d.ts +94 -0
  7. package/lib/TransformerSubTyped.js +116 -0
  8. package/lib/TransformerSubTyped.js.map +1 -0
  9. package/lib/TransformerTyped.d.ts +62 -0
  10. package/lib/TransformerTyped.js +95 -0
  11. package/lib/TransformerTyped.js.map +1 -0
  12. package/lib/generator-builder/dynamicGenerator.d.ts +13 -3
  13. package/lib/generator-builder/dynamicGenerator.js +90 -60
  14. package/lib/generator-builder/dynamicGenerator.js.map +1 -1
  15. package/lib/generator-builder/generatorBuilder.d.ts +5 -2
  16. package/lib/generator-builder/generatorBuilder.js +6 -3
  17. package/lib/generator-builder/generatorBuilder.js.map +1 -1
  18. package/lib/generator-builder/generatorTypes.d.ts +35 -21
  19. package/lib/generator-builder/generatorTypes.js.map +1 -1
  20. package/lib/index.cjs +346 -138
  21. package/lib/index.d.ts +3 -1
  22. package/lib/index.js +3 -1
  23. package/lib/index.js.map +1 -1
  24. package/lib/indirection-builder/IndirBuilder.d.ts +4 -1
  25. package/lib/indirection-builder/IndirBuilder.js +6 -3
  26. package/lib/indirection-builder/IndirBuilder.js.map +1 -1
  27. package/lib/parser-builder/parserBuilder.d.ts +12 -8
  28. package/lib/parser-builder/parserBuilder.js +6 -3
  29. package/lib/parser-builder/parserBuilder.js.map +1 -1
  30. package/lib/utils.d.ts +4 -0
  31. package/lib/utils.js +4 -0
  32. package/lib/utils.js.map +1 -1
  33. package/package.json +2 -2
  34. package/lib/Transformers.d.ts +0 -129
  35. package/lib/Transformers.js +0 -226
  36. package/lib/Transformers.js.map +0 -1
@@ -0,0 +1,62 @@
1
+ import type { Node } from './nodeTypings.js';
2
+ import type { SelectiveTraversalContext, TransformContext, VisitContext } from './TransformerObject.js';
3
+ import { TransformerObject } from './TransformerObject.js';
4
+ export type Safeness = 'safe' | 'unsafe';
5
+ export type SafeWrap<Safe extends Safeness, obj extends object> = Safe extends 'safe' ? {
6
+ [key in keyof obj]: unknown;
7
+ } : obj;
8
+ export type DefaultNodePreVisitor<Nodes extends Pick<Node, 'type'>> = {
9
+ [T in Nodes['type']]?: TransformContext;
10
+ };
11
+ export declare class TransformerTyped<Nodes extends Pick<Node, 'type'>> extends TransformerObject {
12
+ protected defaultNodePreVisitor: DefaultNodePreVisitor<Nodes>;
13
+ constructor(defaultContext?: TransformContext, defaultNodePreVisitor?: DefaultNodePreVisitor<Nodes>);
14
+ /**
15
+ * Transform a single node.
16
+ * The transformation calls the preVisitor from starting from the startObject.
17
+ * The preVisitor can dictate whether transformation should be stopped.
18
+ * Note that stopping the transformation also prevets further copying.
19
+ * The transformer itself transforms object starting with the deepest one that can be visited.
20
+ * The transformer callback is performed on a copy of the original.
21
+ * @param startObject
22
+ * @param nodeCallBacks
23
+ */
24
+ transformNode<Safe extends Safeness = 'safe', OutType = unknown>(startObject: object, nodeCallBacks: {
25
+ [T in Nodes['type']]?: {
26
+ transform?: (copy: SafeWrap<Safe, Extract<Nodes, {
27
+ type: T;
28
+ }>>, orig: Extract<Nodes, {
29
+ type: T;
30
+ }>) => unknown;
31
+ preVisitor?: (orig: Extract<Nodes, {
32
+ type: T;
33
+ }>) => TransformContext;
34
+ };
35
+ }): Safe extends 'unsafe' ? OutType : unknown;
36
+ /**
37
+ * Similar to {@link this.transformNode}, but without copying the startObject.
38
+ * The pre-visitor visits starting from the root, going deeper, while the actual visitor goes in reverse.
39
+ * @param startObject
40
+ * @param nodeCallBacks
41
+ */
42
+ visitNode(startObject: object, nodeCallBacks: {
43
+ [T in Nodes['type']]?: {
44
+ visitor?: (op: Extract<Nodes, {
45
+ type: T;
46
+ }>) => void;
47
+ preVisitor?: (op: Extract<Nodes, {
48
+ type: T;
49
+ }>) => VisitContext;
50
+ };
51
+ }): void;
52
+ /**
53
+ * Traverses only selected nodes as returned by the function.
54
+ * @param currentNode
55
+ * @param traverse
56
+ */
57
+ traverseNodes(currentNode: Nodes, traverse: {
58
+ [T in Nodes['type']]?: (op: Extract<Nodes, {
59
+ type: T;
60
+ }>) => SelectiveTraversalContext<Nodes>;
61
+ }): void;
62
+ }
@@ -0,0 +1,95 @@
1
+ import { TransformerObject } from './TransformerObject.js';
2
+ export class TransformerTyped extends TransformerObject {
3
+ defaultNodePreVisitor;
4
+ constructor(defaultContext = {}, defaultNodePreVisitor = {}) {
5
+ super(defaultContext);
6
+ this.defaultNodePreVisitor = defaultNodePreVisitor;
7
+ }
8
+ ;
9
+ /**
10
+ * Transform a single node.
11
+ * The transformation calls the preVisitor from starting from the startObject.
12
+ * The preVisitor can dictate whether transformation should be stopped.
13
+ * Note that stopping the transformation also prevets further copying.
14
+ * The transformer itself transforms object starting with the deepest one that can be visited.
15
+ * The transformer callback is performed on a copy of the original.
16
+ * @param startObject
17
+ * @param nodeCallBacks
18
+ */
19
+ transformNode(startObject, nodeCallBacks) {
20
+ const transformWrapper = (copy, orig) => {
21
+ let ogTransform;
22
+ const casted = copy;
23
+ if (casted.type) {
24
+ ogTransform = nodeCallBacks[casted.type]?.transform;
25
+ }
26
+ return ogTransform ? ogTransform(casted, orig) : copy;
27
+ };
28
+ const nodeDefaults = this.defaultNodePreVisitor;
29
+ const preVisitWrapper = (curObject) => {
30
+ let ogPreVisit;
31
+ let nodeContext = {};
32
+ const casted = curObject;
33
+ if (casted.type) {
34
+ ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;
35
+ nodeContext = nodeDefaults[casted.type] ?? nodeContext;
36
+ }
37
+ return ogPreVisit ? { ...nodeContext, ...ogPreVisit(casted) } : nodeContext;
38
+ };
39
+ return this.transformObject(startObject, transformWrapper, preVisitWrapper);
40
+ }
41
+ /**
42
+ * Similar to {@link this.transformNode}, but without copying the startObject.
43
+ * The pre-visitor visits starting from the root, going deeper, while the actual visitor goes in reverse.
44
+ * @param startObject
45
+ * @param nodeCallBacks
46
+ */
47
+ visitNode(startObject, nodeCallBacks) {
48
+ const visitorWrapper = (curObject) => {
49
+ const casted = curObject;
50
+ if (casted.type) {
51
+ const ogTransform = nodeCallBacks[casted.type]?.visitor;
52
+ if (ogTransform) {
53
+ ogTransform(casted);
54
+ }
55
+ }
56
+ };
57
+ const nodeDefaults = this.defaultNodePreVisitor;
58
+ const preVisitWrapper = (curObject) => {
59
+ let ogPreVisit;
60
+ let nodeContext = {};
61
+ const casted = curObject;
62
+ if (casted.type) {
63
+ ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;
64
+ nodeContext = nodeDefaults[casted.type] ?? nodeContext;
65
+ }
66
+ return ogPreVisit ? { ...nodeContext, ...ogPreVisit(casted) } : nodeContext;
67
+ };
68
+ return this.visitObject(startObject, visitorWrapper, preVisitWrapper);
69
+ }
70
+ /**
71
+ * Traverses only selected nodes as returned by the function.
72
+ * @param currentNode
73
+ * @param traverse
74
+ */
75
+ traverseNodes(currentNode, traverse) {
76
+ let didShortCut = false;
77
+ const recurse = (curNode) => {
78
+ const traverser = traverse[curNode.type];
79
+ if (traverser) {
80
+ const { next, shortcut } = traverser(curNode);
81
+ didShortCut = shortcut ?? false;
82
+ if (!didShortCut) {
83
+ for (const node of next ?? []) {
84
+ if (didShortCut) {
85
+ return;
86
+ }
87
+ recurse(node);
88
+ }
89
+ }
90
+ }
91
+ };
92
+ recurse(currentNode);
93
+ }
94
+ }
95
+ //# sourceMappingURL=TransformerTyped.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TransformerTyped.js","sourceRoot":"","sources":["TransformerTyped.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAQ3D,MAAM,OAAO,gBAAmD,SAAQ,iBAAiB;IAG3E;IAFZ,Y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EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,SAAS,CAAM,OAAO,CAAC,CAAC;gBACnD,WAAW,GAAG,QAAQ,IAAI,KAAK,CAAC;gBAChC,IAAI,CAAC,WAAW,EAAE,CAAC;oBACjB,KAAK,MAAM,IAAI,IAAI,IAAI,IAAI,EAAE,EAAE,CAAC;wBAC9B,IAAI,WAAW,EAAE,CAAC;4BAChB,OAAO;wBACT,CAAC;wBACD,OAAO,CAAC,IAAI,CAAC,CAAC;oBAChB,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC,CAAC;QAEF,OAAO,CAAC,WAAW,CAAC,CAAC;IACvB,CAAC;CACF","sourcesContent":["import type { Node } from './nodeTypings.js';\nimport type { SelectiveTraversalContext, TransformContext, VisitContext } from './TransformerObject.js';\nimport { TransformerObject } from './TransformerObject.js';\n\nexport type Safeness = 'safe' | 'unsafe';\nexport type SafeWrap<Safe extends Safeness, obj extends object> =\n Safe extends 'safe' ? {[key in keyof obj]: unknown } : obj;\n\nexport type DefaultNodePreVisitor<Nodes extends Pick<Node, 'type'>> = {[T in Nodes['type']]?: TransformContext };\n\nexport class TransformerTyped<Nodes extends Pick<Node, 'type'>> extends TransformerObject {\n public constructor(\n defaultContext: TransformContext = {},\n protected defaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ) {\n super(defaultContext);\n };\n\n /**\n * Transform a single node.\n * The transformation calls the preVisitor from starting from the startObject.\n * The preVisitor can dictate whether transformation should be stopped.\n * Note that stopping the transformation also prevets further copying.\n * The transformer itself transforms object starting with the deepest one that can be visited.\n * The transformer callback is performed on a copy of the original.\n * @param startObject\n * @param nodeCallBacks\n */\n public transformNode<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n transform?: (copy: SafeWrap<Safe, Extract<Nodes, { type: T }>>, orig: Extract<Nodes, { type: T }>) => unknown;\n preVisitor?: (orig: Extract<Nodes, { type: T }>) => TransformContext;\n }},\n ): Safe extends 'unsafe' ? OutType : unknown {\n const transformWrapper = (copy: object, orig: object): unknown => {\n let ogTransform: ((copy: any, orig: any) => unknown) | undefined;\n const casted = <{ type?: Nodes['type'] }>copy;\n if (casted.type) {\n ogTransform = nodeCallBacks[casted.type]?.transform;\n }\n return ogTransform ? ogTransform(casted, orig) : copy;\n };\n const nodeDefaults = this.defaultNodePreVisitor;\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => VisitContext) | undefined;\n let nodeContext: VisitContext = {};\n const casted = <{ type?: Nodes['type'] }>curObject;\n if (casted.type) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n nodeContext = nodeDefaults[casted.type] ?? nodeContext;\n }\n return ogPreVisit ? { ...nodeContext, ...ogPreVisit(casted) } : nodeContext;\n };\n return <any> this.transformObject(startObject, transformWrapper, preVisitWrapper);\n }\n\n /**\n * Similar to {@link this.transformNode}, but without copying the startObject.\n * The pre-visitor visits starting from the root, going deeper, while the actual visitor goes in reverse.\n * @param startObject\n * @param nodeCallBacks\n */\n public visitNode(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n visitor?: (op: Extract<Nodes, { type: T }>) => void;\n preVisitor?: (op: Extract<Nodes, { type: T }>) => VisitContext;\n }},\n ): void {\n const visitorWrapper = (curObject: object): void => {\n const casted = <{ type?: Nodes['type'] }>curObject;\n if (casted.type) {\n const ogTransform = nodeCallBacks[casted.type]?.visitor;\n if (ogTransform) {\n ogTransform(<any> casted);\n }\n }\n };\n const nodeDefaults = this.defaultNodePreVisitor;\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => VisitContext) | undefined;\n let nodeContext: VisitContext = {};\n const casted = <{ type?: Nodes['type'] }>curObject;\n if (casted.type) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n nodeContext = nodeDefaults[casted.type] ?? nodeContext;\n }\n return ogPreVisit ? { ...nodeContext, ...ogPreVisit(casted) } : nodeContext;\n };\n return this.visitObject(startObject, visitorWrapper, preVisitWrapper);\n }\n\n /**\n * Traverses only selected nodes as returned by the function.\n * @param currentNode\n * @param traverse\n */\n public traverseNodes(\n currentNode: Nodes,\n traverse: {[T in Nodes['type']]?: (op: Extract<Nodes, { type: T }>) => SelectiveTraversalContext<Nodes> },\n ): void {\n let didShortCut = false;\n\n const recurse = (curNode: Nodes): void => {\n const traverser = traverse[<Nodes['type']>curNode.type];\n if (traverser) {\n const { next, shortcut } = traverser(<any>curNode);\n didShortCut = shortcut ?? false;\n if (!didShortCut) {\n for (const node of next ?? []) {\n if (didShortCut) {\n return;\n }\n recurse(node);\n }\n }\n }\n };\n\n recurse(currentNode);\n }\n}\n"]}
@@ -8,19 +8,29 @@ export declare class DynamicGenerator<Context, Names extends string, RuleDefs ex
8
8
  protected __context: Context | undefined;
9
9
  protected origSource: string;
10
10
  protected generatedUntil: number;
11
- protected expectsSpace: boolean;
11
+ protected toEnsure: ((willPrint: string) => void)[];
12
+ /**
13
+ * Should not contain empty strings
14
+ * @protected
15
+ */
12
16
  protected readonly stringBuilder: string[];
13
17
  constructor(rules: RuleDefs);
14
18
  setContext(context: Context): void;
15
19
  protected getSafeContext(): Context & {
16
- [traqulaIndentation]?: unknown;
20
+ [traqulaIndentation]?: number;
17
21
  };
18
22
  protected readonly subrule: RuleDefArg['SUBRULE'];
19
23
  protected readonly handleLoc: RuleDefArg['HANDLE_LOC'];
20
24
  protected readonly catchup: RuleDefArg['CATCHUP'];
25
+ private handeEnsured;
21
26
  protected readonly print: RuleDefArg['PRINT'];
27
+ private doesEndWith;
28
+ protected readonly ensure: RuleDefArg['ENSURE'];
29
+ protected readonly ensureEither: RuleDefArg['ENSURE_EITHER'];
30
+ private pruneEndingBlanks;
31
+ protected readonly newLine: RuleDefArg['NEW_LINE'];
22
32
  private readonly printWord;
23
- private readonly printSpaceLeft;
24
33
  private readonly printWords;
25
34
  private readonly printOnEmpty;
35
+ private readonly printOnOwnLine;
26
36
  }
@@ -6,7 +6,11 @@ export class DynamicGenerator {
6
6
  __context = undefined;
7
7
  origSource = '';
8
8
  generatedUntil = 0;
9
- expectsSpace;
9
+ toEnsure = [];
10
+ /**
11
+ * Should not contain empty strings
12
+ * @protected
13
+ */
10
14
  stringBuilder = [];
11
15
  constructor(rules) {
12
16
  this.rules = rules;
@@ -15,7 +19,6 @@ export class DynamicGenerator {
15
19
  // Define function implementation
16
20
  this[rule.name] =
17
21
  ((input, context, args) => {
18
- this.expectsSpace = false;
19
22
  this.stringBuilder.length = 0;
20
23
  this.origSource = context.origSource;
21
24
  this.generatedUntil = context?.offset ?? 0;
@@ -40,12 +43,15 @@ export class DynamicGenerator {
40
43
  const generate = () => def.gImpl({
41
44
  SUBRULE: this.subrule,
42
45
  PRINT: this.print,
43
- PRINT_SPACE_LEFT: this.printSpaceLeft,
46
+ ENSURE: this.ensure,
47
+ ENSURE_EITHER: this.ensureEither,
48
+ NEW_LINE: this.newLine,
49
+ HANDLE_LOC: this.handleLoc,
50
+ CATCHUP: this.catchup,
44
51
  PRINT_WORD: this.printWord,
45
52
  PRINT_WORDS: this.printWords,
46
53
  PRINT_ON_EMPTY: this.printOnEmpty,
47
- CATCHUP: this.catchup,
48
- HANDLE_LOC: this.handleLoc,
54
+ PRINT_ON_OWN_LINE: this.printOnOwnLine,
49
55
  })(ast, this.getSafeContext(), ...arg);
50
56
  if (this.factory.isLocalized(ast)) {
51
57
  this.handleLoc(ast, generate);
@@ -85,45 +91,88 @@ export class DynamicGenerator {
85
91
  }
86
92
  this.generatedUntil = Math.max(this.generatedUntil, until);
87
93
  };
94
+ handeEnsured(toPrint) {
95
+ for (const callBack of this.toEnsure) {
96
+ callBack(toPrint);
97
+ }
98
+ this.toEnsure.length = 0;
99
+ }
88
100
  print = (...args) => {
89
- const pureArgs = args.filter(x => x.length > 0);
90
- if (pureArgs.length > 0) {
91
- const head = pureArgs[0];
92
- if (this.expectsSpace) {
93
- this.expectsSpace = false;
94
- const blanks = new Set(['\n', ' ', '\t']);
95
- if (this.stringBuilder.length > 0 &&
96
- !(blanks.has(head[0]) || blanks.has(this.stringBuilder.at(-1).at(-1)))) {
97
- this.stringBuilder.push(' ');
101
+ const joined = args.join('');
102
+ this.handeEnsured(joined);
103
+ this.stringBuilder.push(joined);
104
+ };
105
+ doesEndWith(subsStr) {
106
+ const len = subsStr.length;
107
+ let temp = '';
108
+ while (temp.length < len && this.stringBuilder.length > 0) {
109
+ temp = this.stringBuilder.pop() + temp;
110
+ }
111
+ this.stringBuilder.push(temp);
112
+ return temp.endsWith(subsStr);
113
+ }
114
+ ensure = (...args) => {
115
+ // Check whether already present
116
+ const toEnsure = args.join('');
117
+ if (!this.doesEndWith(toEnsure)) {
118
+ this.toEnsure.push((willPrint) => {
119
+ if (!willPrint.startsWith(toEnsure) && !this.doesEndWith(toEnsure)) {
120
+ this.stringBuilder.push(toEnsure);
98
121
  }
99
- }
100
- const context = this.getSafeContext();
101
- if (context[traqulaIndentation] && typeof context[traqulaIndentation] === 'number') {
102
- const indent = context[traqulaIndentation];
103
- for (const str of pureArgs) {
104
- const [noNl, ...postNl] = str.split('\n');
105
- this.stringBuilder.push(noNl);
106
- for (const subStr of postNl.map(line => line.trimStart())) {
107
- this.stringBuilder.push('\n', ' '.repeat(indent));
108
- if (subStr.length > 0) {
109
- this.stringBuilder.push(subStr);
110
- }
111
- }
122
+ });
123
+ }
124
+ };
125
+ ensureEither = (...args) => {
126
+ if (args.length === 1) {
127
+ this.ensure(...args);
128
+ }
129
+ else if (args.length > 1 &&
130
+ // Not already matched?
131
+ !args.some(subStr => this.doesEndWith(subStr))) {
132
+ this.toEnsure.push((willPrint) => {
133
+ if (!args.some(subStr => willPrint.startsWith(subStr)) && !args.some(subStr => this.doesEndWith(subStr))) {
134
+ this.stringBuilder.push(args[0]);
112
135
  }
136
+ });
137
+ }
138
+ };
139
+ pruneEndingBlanks() {
140
+ let temp = '';
141
+ while (/^[ \t]*$/u.test(temp) && this.stringBuilder.length > 0) {
142
+ temp = this.stringBuilder.pop() + temp;
143
+ }
144
+ this.print(temp.trimEnd());
145
+ }
146
+ newLine = (arg) => {
147
+ const indentation = this.getSafeContext()[traqulaIndentation] ?? 0;
148
+ if (indentation === -1) {
149
+ return;
150
+ }
151
+ const force = arg?.force ?? false;
152
+ this.pruneEndingBlanks();
153
+ if (force) {
154
+ this.print('\n', ' '.repeat(indentation));
155
+ }
156
+ else {
157
+ let temp = '';
158
+ while (!temp.includes('\n') && this.stringBuilder.length > 0) {
159
+ temp = this.stringBuilder.pop() + temp;
160
+ }
161
+ if (/\n[ \t]*$/u.test(temp)) {
162
+ // Pointer is on empty newline -> set correct indentation
163
+ temp = temp.replace(/\n[ \t]*$/u, `\n${' '.repeat(indentation)}`);
164
+ this.print(temp);
113
165
  }
114
166
  else {
115
- this.stringBuilder.push(...pureArgs);
167
+ // Pointer not on empty newline, print newline.
168
+ this.print(temp, '\n', ' '.repeat(indentation));
116
169
  }
117
170
  }
118
171
  };
119
172
  printWord = (...args) => {
120
- this.expectsSpace = true;
121
- this.print(...args);
122
- this.expectsSpace = true;
123
- };
124
- printSpaceLeft = (...args) => {
125
- this.expectsSpace = true;
173
+ this.ensureEither(' ', '\n');
126
174
  this.print(...args);
175
+ this.ensureEither(' ', '\n');
127
176
  };
128
177
  printWords = (...args) => {
129
178
  for (const arg of args) {
@@ -131,32 +180,13 @@ export class DynamicGenerator {
131
180
  }
132
181
  };
133
182
  printOnEmpty = (...args) => {
134
- // Check if pointer already on empty line
135
- let counter = this.stringBuilder.length - 1;
136
- let onEmpty = true;
137
- const isEmptyTest = /^[ \t\n]*$/u;
138
- while (counter >= 0 && onEmpty) {
139
- const cur = this.stringBuilder[counter];
140
- const indexOfNl = cur.lastIndexOf('\n');
141
- if (indexOfNl >= 0) {
142
- // This is the last newline that is printed
143
- onEmpty = isEmptyTest.test(cur.slice(indexOfNl));
144
- if (onEmpty) {
145
- // We still want to have the current indent printed
146
- const newVal = cur.slice(0, indexOfNl);
147
- if (newVal) {
148
- this.stringBuilder[counter] = cur.slice(0, indexOfNl);
149
- }
150
- else {
151
- this.stringBuilder.splice(counter, 1);
152
- }
153
- }
154
- break;
155
- }
156
- onEmpty = isEmptyTest.test(cur);
157
- counter--;
158
- }
159
- this.print('\n', ...args);
183
+ this.newLine();
184
+ this.print(...args);
185
+ };
186
+ printOnOwnLine = (...args) => {
187
+ this.newLine();
188
+ this.print(...args);
189
+ this.newLine();
160
190
  };
161
191
  }
162
192
  //# sourceMappingURL=dynamicGenerator.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dynamicGenerator.js","sourceRoot":"","sources":["dynamicGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAIjD,MAAM,OAAO,gBAAgB;IAQE;IAPV,OAAO,GAAG,IAAI,cAAc,EAAE,CAAC;IACxC,SAAS,GAAwB,SAAS,CAAC;IAC3C,UAAU,GAAG,EAAE,CAAC;IAChB,cAAc,GAAG,CAAC,CAAC;IACnB,YAAY,CAAU;IACb,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,KAAU,EAAE,OAA0D,EAAE,IAAS,EAAE,EAAE;oBAC3F,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;oBAC1B,IAAI,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,CAAC;oBAC9B,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;oBACrC,IAAI,CAAC,cAAc,GAAG,OAAO,EAAE,MAAM,IAAI,CAAC,CAAC;oBAC3C,IAAI,CAAC,U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OAAO,GAAG,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAChC,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,CAAC;IAC5B,CAAC,CAAC;CACH","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 expectsSpace: boolean;\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.expectsSpace = false;\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]?: unknown } {\n return <Context & { [traqulaIndentation]?: unknown }> 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 PRINT_SPACE_LEFT: this.printSpaceLeft,\n PRINT_WORD: this.printWord,\n PRINT_WORDS: this.printWords,\n PRINT_ON_EMPTY: this.printOnEmpty,\n CATCHUP: this.catchup,\n HANDLE_LOC: this.handleLoc,\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 protected readonly print: RuleDefArg['PRINT'] = (...args) => {\n const pureArgs = args.filter(x => x.length > 0);\n if (pureArgs.length > 0) {\n const head = pureArgs[0];\n if (this.expectsSpace) {\n this.expectsSpace = false;\n const blanks = new Set([ '\\n', ' ', '\\t' ]);\n if (this.stringBuilder.length > 0 &&\n !(blanks.has(head[0]) || blanks.has(this.stringBuilder.at(-1)!.at(-1)!))) {\n this.stringBuilder.push(' ');\n }\n }\n const context = this.getSafeContext();\n if (context[traqulaIndentation] && typeof context[traqulaIndentation] === 'number') {\n const indent = context[traqulaIndentation];\n for (const str of pureArgs) {\n const [ noNl, ...postNl ] = str.split('\\n');\n this.stringBuilder.push(noNl);\n for (const subStr of postNl.map(line => line.trimStart())) {\n this.stringBuilder.push('\\n', ' '.repeat(indent));\n if (subStr.length > 0) {\n this.stringBuilder.push(subStr);\n }\n }\n }\n } else {\n this.stringBuilder.push(...pureArgs);\n }\n }\n };\n\n private readonly printWord: RuleDefArg['PRINT_WORD'] = (...args) => {\n this.expectsSpace = true;\n this.print(...args);\n this.expectsSpace = true;\n };\n\n private readonly printSpaceLeft: RuleDefArg['PRINT_WORD'] = (...args) => {\n this.expectsSpace = true;\n this.print(...args);\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 // Check if pointer already on empty line\n let counter = this.stringBuilder.length - 1;\n let onEmpty = true;\n const isEmptyTest = /^[ \\t\\n]*$/u;\n while (counter >= 0 && onEmpty) {\n const cur = this.stringBuilder[counter];\n const indexOfNl = cur.lastIndexOf('\\n');\n if (indexOfNl >= 0) {\n // This is the last newline that is printed\n onEmpty = isEmptyTest.test(cur.slice(indexOfNl));\n if (onEmpty) {\n // We still want to have the current indent printed\n const newVal = cur.slice(0, indexOfNl);\n if (newVal) {\n this.stringBuilder[counter] = cur.slice(0, indexOfNl);\n } else {\n this.stringBuilder.splice(counter, 1);\n }\n }\n break;\n }\n onEmpty = isEmptyTest.test(cur);\n counter--;\n }\n this.print('\\n', ...args);\n };\n}\n"]}
1
+ {"version":3,"file":"dynamicGenerator.js","sourceRoot":"","sources":["dynamicGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAIjD,MAAM,OAAO,gBAAgB;IAYE;IAXV,OAAO,GAAG,IAAI,cAAc,EAAE,CAAC;IACxC,SAAS,GAAwB,SAAS,CAAC;IAC3C,UAAU,GAAG,EAAE,CAAC;IAChB,cAAc,GAAG,CAAC,CAAC;IACnB,QAAQ,GAAoC,EAAE,CAAC;IACzD;;;OAGG;IACgB,aAAa,GAAa,EAAE,CAAC;IAEhD,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E,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","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"]}
@@ -11,11 +11,13 @@ export declare class GeneratorBuilder<Context, Names extends string, RuleDefs ex
11
11
  static create<Rules extends readonly GeneratorRule[] = readonly GeneratorRule[], Context = Rules[0] extends GeneratorRule<infer context> ? context : never, Names extends string = ParseNamesFromList<Rules>, RuleDefs extends GenRuleMap<Names> = GenRulesToObject<Rules>>(rules: Rules): GeneratorBuilder<Context, Names, RuleDefs>;
12
12
  private rules;
13
13
  private constructor();
14
- widenContext<NewContext extends Context>(): GeneratorBuilder<NewContext, Names, RuleDefs>;
14
+ widenContext<NewContext extends Context>(): GeneratorBuilder<NewContext, Names, {
15
+ [Key in keyof RuleDefs]: Key extends Names ? (RuleDefs[Key] extends GeneratorRule<any, any, infer RT, infer PT> ? GeneratorRule<NewContext, Key, RT, PT> : never) : never;
16
+ }>;
15
17
  typePatch<Patch extends {
16
18
  [Key in Names]?: [any] | [any, any[]];
17
19
  }>(): GeneratorBuilder<Context, Names, {
18
- [Key in Names]: Key extends keyof Patch ? (Patch[Key] extends [any, any[]] ? GeneratorRule<Context, Key, Patch[Key][0], Patch[Key][1]> : (Patch[Key] extends GeneratorRule<Context, Key, any, infer args> ? GeneratorRule<Context, Key, Patch[Key][0], args> : never)) : never;
20
+ [Key in Names]: Key extends keyof Patch ? (Patch[Key] extends [any, any[]] ? GeneratorRule<Context, Key, Patch[Key][0], Patch[Key][1]> : (Patch[Key] extends [any] ? RuleDefs[Key] extends GeneratorRule<any, any, any, infer Par> ? GeneratorRule<Context, Key, Patch[Key][0], Par> : never : never)) : RuleDefs[Key] extends GeneratorRule<any, Key> ? RuleDefs[Key] : never;
19
21
  }>;
20
22
  /**
21
23
  * Change the implementation of an existing generator rule.
@@ -44,6 +46,7 @@ export declare class GeneratorBuilder<Context, Names extends string, RuleDefs ex
44
46
  deleteRule<U extends Names>(ruleName: U): GeneratorBuilder<Context, Exclude<Names, U>, {
45
47
  [K in Exclude<Names, U>]: RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never;
46
48
  }>;
49
+ getRule<U extends Names>(ruleName: U): RuleDefs[U] extends GeneratorRule<any, U, infer RT, infer PT> ? GeneratorRule<Context, U, RT, PT> : never;
47
50
  /**
48
51
  * Merge this grammar GeneratorBuilder with another.
49
52
  * It is best to merge the bigger grammar with the smaller one.
@@ -11,10 +11,10 @@ function listToRuleDefMap(rules) {
11
11
  }
12
12
  export class GeneratorBuilder {
13
13
  static create(start) {
14
- if (start instanceof GeneratorBuilder) {
15
- return new GeneratorBuilder({ ...start.rules });
14
+ if (Array.isArray(start)) {
15
+ return new GeneratorBuilder(listToRuleDefMap(start));
16
16
  }
17
- return new GeneratorBuilder(listToRuleDefMap(start));
17
+ return new GeneratorBuilder({ ...start.rules });
18
18
  }
19
19
  rules;
20
20
  constructor(startRules) {
@@ -63,6 +63,9 @@ export class GeneratorBuilder {
63
63
  delete this.rules[ruleName];
64
64
  return this;
65
65
  }
66
+ getRule(ruleName) {
67
+ return this.rules[ruleName];
68
+ }
66
69
  /**
67
70
  * Merge this grammar GeneratorBuilder with another.
68
71
  * It is best to merge the bigger grammar with the smaller one.
@@ -1 +1 @@
1
- {"version":3,"file":"generatorBuilder.js","sourceRoot":"","sources":["generatorBuilder.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAGzD;;GAEG;AACH,SAAS,gBAAgB,CAAqC,KAAQ;IACpE,MAAM,QAAQ,GAAkC,EAAE,CAAC;IACnD,K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;oBACnC,CAAC;yBAAM,CAAC;wBACN,MAAM,IAAI,KAAK,CAAC,mBAAmB,IAAI,CAAC,IAAI,mFAAmF,CAAC,CAAC;oBACnI,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QAED,IAAI,CAAC,KAAK,GAAmB,UAAU,CAAC;QACxC,OAAuB,IAAI,CAAC;IAC9B,CAAC;IAEM,KAAK;QACV,OAAsD,IAAI,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACzF,CAAC;CACF","sourcesContent":["import type { ParseNamesFromList } from '../parser-builder/builderTypes.js';\nimport type { CheckOverlap } from '../utils.js';\nimport type { GeneratorFromRules, GenRuleMap, GenRulesToObject } from './builderTypes.js';\nimport { DynamicGenerator } from './dynamicGenerator.js';\nimport type { GeneratorRule } from './generatorTypes.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 GeneratorRule[]>(rules: T): GenRulesToObject<T> {\n const newRules: Record<string, GeneratorRule> = {};\n for (const rule of rules) {\n newRules[rule.name] = rule;\n }\n return <GenRulesToObject<T>>newRules;\n}\n\nexport class GeneratorBuilder<Context, Names extends string, RuleDefs extends GenRuleMap<Names>> {\n /**\n * Create a GeneratorBuilder from some initial grammar rules or an existing GeneratorBuilder.\n * If a GeneratorBuilder is provided, a new copy will be created.\n */\n public static create<Context, Names extends string, RuleDefs extends GenRuleMap<Names>>(\n args: GeneratorBuilder<Context, Names, RuleDefs>\n ): GeneratorBuilder<Context, Names, RuleDefs>;\n public static create<\n Rules extends readonly GeneratorRule[] = readonly GeneratorRule[],\n Context = Rules[0] extends GeneratorRule<infer context> ? context : never,\n Names extends string = ParseNamesFromList<Rules>,\n RuleDefs extends GenRuleMap<Names> = GenRulesToObject<Rules>,\n >(rules: Rules): GeneratorBuilder<Context, Names, RuleDefs>;\n public static create<\n Rules extends readonly GeneratorRule[] = readonly GeneratorRule[],\n Context = Rules[0] extends GeneratorRule<infer context> ? context : never,\n Names extends string = ParseNamesFromList<Rules>,\n RuleDefs extends GenRuleMap<Names> = GenRulesToObject<Rules>,\n >(\n start: Rules | GeneratorBuilder<Context, Names, RuleDefs>,\n ): GeneratorBuilder<Context, Names, RuleDefs> {\n if (start instanceof GeneratorBuilder) {\n return new GeneratorBuilder({ ...start.rules });\n }\n return <GeneratorBuilder<Context, Names, RuleDefs>> <unknown> new GeneratorBuilder(listToRuleDefMap(start));\n }\n\n private rules: RuleDefs;\n\n private constructor(startRules: RuleDefs) {\n this.rules = startRules;\n }\n\n public widenContext<NewContext extends Context>(): GeneratorBuilder<NewContext, Names, RuleDefs> {\n return <GeneratorBuilder<NewContext, Names, RuleDefs>> <unknown> this;\n }\n\n public typePatch<Patch extends {[Key in Names]?: [any] | [any, any[]]}>():\n GeneratorBuilder<Context, Names, {[Key in Names]: Key extends keyof Patch ? (\n Patch[Key] extends [any, any[]] ? GeneratorRule<Context, Key, Patch[Key][0], Patch[Key][1]> : (\n // Only one - infer arg yourself\n Patch[Key] extends GeneratorRule<Context, Key, any, infer args> ?\n GeneratorRule<Context, Key, Patch[Key][0], args> : never\n )) : never\n }> {\n return <any> this;\n }\n\n /**\n * Change the implementation of an existing generator rule.\n */\n public patchRule<U extends Names, RET, ARGS extends any[]>(patch: GeneratorRule<Context, U, RET, ARGS>):\n GeneratorBuilder<Context, Names, {[Key in Names]: Key extends U ?\n GeneratorRule<Context, Key, RET, ARGS> :\n (RuleDefs[Key] extends GeneratorRule<Context, Key> ? RuleDefs[Key] : never)\n } > {\n const self = <GeneratorBuilder<Context, Names, {[Key in Names]: Key extends U ?\n GeneratorRule<Context, Key, RET, ARGS> :\n (RuleDefs[Key] extends GeneratorRule<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: GeneratorRule<Context, U, RET, ARGS>):\n GeneratorBuilder<Context, Names | U, {[K in Names | U]: K extends Names ?\n (RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never)\n : (K extends U ? GeneratorRule<Context, K, RET, ARGS> : never)\n }> {\n const self = <GeneratorBuilder<Context, Names | U, {[K in Names | U]: K extends Names ?\n (RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never)\n : (K extends U ? GeneratorRule<Context, K, RET, ARGS> : never) }>>\n <unknown> this;\n const rules = <Record<string, GeneratorRule<Context>>> self.rules;\n if (rules[rule.name] !== undefined && rules[rule.name] !== rule) {\n throw new Error(`Rule ${rule.name} already exists in the GeneratorBuilder`);\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, GeneratorRule<Context, U, RET, ARGS>>,\n ): GeneratorBuilder<Context, Names | U, {[K in Names | U]: K extends Names ?\n (RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never)\n : (K extends U ? GeneratorRule<Context, K, RET, ARGS> : never)\n }> {\n return this.addRuleRedundant(rule);\n }\n\n public addMany<U extends readonly GeneratorRule<Context>[]>(\n ...rules: CheckOverlap<ParseNamesFromList<U>, Names, U>\n ): GeneratorBuilder<\n Context,\n Names | ParseNamesFromList<U>,\n {[K in Names | ParseNamesFromList<U>]:\n K extends keyof GenRulesToObject<typeof rules> ? (\n GenRulesToObject<typeof rules>[K] extends GeneratorRule<Context, K> ? GenRulesToObject<typeof rules>[K] : never\n ) : (\n K extends Names ? (RuleDefs[K] extends GeneratorRule<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 GeneratorBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never }> {\n delete this.rules[ruleName];\n return <GeneratorBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never }>>\n <unknown> this;\n }\n\n /**\n * Merge this grammar GeneratorBuilder 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 GenRuleMap<OtherNames>,\n OW extends readonly GeneratorRule<Context>[],\n >(\n GeneratorBuilder: GeneratorBuilder<Context, OtherNames, OtherRules>,\n overridingRules: OW,\n ):\n GeneratorBuilder<\n Context,\n Names | OtherNames | ParseNamesFromList<OW>,\n {[K in Names | OtherNames | ParseNamesFromList<OW>]:\n K extends keyof GenRulesToObject<OW> ? (\n GenRulesToObject<OW>[K] extends GeneratorRule<Context, K> ? GenRulesToObject<OW>[K] : never\n )\n : (\n K extends Names ? (RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never)\n : K extends OtherNames ? (OtherRules[K] extends GeneratorRule<Context, K> ? OtherRules[K] : never)\n : 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, GeneratorRule<Context>> = { ...GeneratorBuilder.rules };\n const myRules: Record<string, GeneratorRule<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 GeneratorBuilder, 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 public build(): GeneratorFromRules<Context, Names, RuleDefs> {\n return <GeneratorFromRules<Context, Names, RuleDefs>> new DynamicGenerator(this.rules);\n }\n}\n"]}
1
+ {"version":3,"file":"generatorBuilder.js","sourceRoot":"","sources":["generatorBuilder.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAGzD;;GAEG;AACH,SAAS,gBAAgB,CAAqC,KAAQ;IACpE,MAAM,QAAQ,GAAkC,EAAE,CAAC;IACnD,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC7B,CAAC;IACD,OAA4B,QAAQ,CAAC;AACvC,CAAC;AAED,MAAM,OAAO,gBAAgB;IAcpB,MAAM,CAAC,MAAM,CAMlB,KAAyD;QAEzD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,OAA8D,IAAI,gBAAgB,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC9G,CAAC;QACD,OAAO,IAAI,gBAAgB,CAAC,EAAE,GAAqC,KAAM,CAAC,KAAK,EAAE,CAAC,CAAC;IACrF,CAAC;IAEO,KAAK,CAAW;IAExB,YAAoB,UAAoB;QACtC,IAAI,CAAC,KAAK,GAAG,UAAU,CAAC;IAC1B,CAAC;IAEM,YAAY;QAQjB,OAAa,IAAI,CAAC;IACpB,CAAC;IAEM,SAAS;QAUd,OAAa,IAAI,CAAC;IACpB,CAAC;IAED;;OAEG;IACI,SAAS,CAA2C,KAA2C;QAKpG,MAAM,IAAI,GAGE,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,GAAS,KAAK,CAAC;QACrC,OAAO,IA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,CAAC;YAC1C,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,SAAS,EAAE,CAAC;gBACxC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;YAC/B,CAAC;iBAAM,CAAC;gBACN,MAAM,YAAY,GAAG,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBAC3C,wCAAwC;gBACxC,IAAI,YAAY,KAAK,IAAI,EAAE,CAAC;oBAC1B,MAAM,QAAQ,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC;oBACjE,mFAAmF;oBACnF,IAAI,QAAQ,EAAE,CAAC;wBACb,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC;oBACnC,CAAC;yBAAM,CAAC;wBACN,MAAM,IAAI,KAAK,CAAC,mBAAmB,IAAI,CAAC,IAAI,mFAAmF,CAAC,CAAC;oBACnI,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;QAED,IAAI,CAAC,KAAK,GAAmB,UAAU,CAAC;QACxC,OAAuB,IAAI,CAAC;IAC9B,CAAC;IAEM,KAAK;QACV,OAAsD,IAAI,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACzF,CAAC;CACF","sourcesContent":["import type { ParseNamesFromList } from '../parser-builder/builderTypes.js';\nimport type { CheckOverlap } from '../utils.js';\nimport type { GeneratorFromRules, GenRuleMap, GenRulesToObject } from './builderTypes.js';\nimport { DynamicGenerator } from './dynamicGenerator.js';\nimport type { GeneratorRule } from './generatorTypes.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 GeneratorRule[]>(rules: T): GenRulesToObject<T> {\n const newRules: Record<string, GeneratorRule> = {};\n for (const rule of rules) {\n newRules[rule.name] = rule;\n }\n return <GenRulesToObject<T>>newRules;\n}\n\nexport class GeneratorBuilder<Context, Names extends string, RuleDefs extends GenRuleMap<Names>> {\n /**\n * Create a GeneratorBuilder from some initial grammar rules or an existing GeneratorBuilder.\n * If a GeneratorBuilder is provided, a new copy will be created.\n */\n public static create<Context, Names extends string, RuleDefs extends GenRuleMap<Names>>(\n args: GeneratorBuilder<Context, Names, RuleDefs>\n ): GeneratorBuilder<Context, Names, RuleDefs>;\n public static create<\n Rules extends readonly GeneratorRule[] = readonly GeneratorRule[],\n Context = Rules[0] extends GeneratorRule<infer context> ? context : never,\n Names extends string = ParseNamesFromList<Rules>,\n RuleDefs extends GenRuleMap<Names> = GenRulesToObject<Rules>,\n >(rules: Rules): GeneratorBuilder<Context, Names, RuleDefs>;\n public static create<\n Rules extends readonly GeneratorRule[] = readonly GeneratorRule[],\n Context = Rules[0] extends GeneratorRule<infer context> ? context : never,\n Names extends string = ParseNamesFromList<Rules>,\n RuleDefs extends GenRuleMap<Names> = GenRulesToObject<Rules>,\n >(\n start: Rules | GeneratorBuilder<Context, Names, RuleDefs>,\n ): GeneratorBuilder<Context, Names, RuleDefs> {\n if (Array.isArray(start)) {\n return <GeneratorBuilder<Context, Names, RuleDefs>> <unknown> new GeneratorBuilder(listToRuleDefMap(start));\n }\n return new GeneratorBuilder({ ...(<GeneratorBuilder<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>(): GeneratorBuilder<\n NewContext,\n Names,\n {[Key in keyof RuleDefs]: Key extends Names ?\n (RuleDefs[Key] extends GeneratorRule<any, any, infer RT, infer PT> ?\n GeneratorRule<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 GeneratorBuilder<Context, Names, {[Key in Names]: Key extends keyof Patch ? (\n Patch[Key] extends [any, any[]] ? GeneratorRule<Context, Key, Patch[Key][0], Patch[Key][1]> : (\n // Only one - infer arg yourself\n Patch[Key] extends [ any ] ?\n RuleDefs[Key] extends GeneratorRule<any, any, any, infer Par> ?\n GeneratorRule<Context, Key, Patch[Key][0], Par> : never\n : never\n )) : RuleDefs[Key] extends GeneratorRule<any, Key> ? RuleDefs[Key] : never\n }> {\n return <any> this;\n }\n\n /**\n * Change the implementation of an existing generator rule.\n */\n public patchRule<U extends Names, RET, ARGS extends any[]>(patch: GeneratorRule<Context, U, RET, ARGS>):\n GeneratorBuilder<Context, Names, {[Key in Names]: Key extends U ?\n GeneratorRule<Context, Key, RET, ARGS> :\n (RuleDefs[Key] extends GeneratorRule<Context, Key> ? RuleDefs[Key] : never)\n } > {\n const self = <GeneratorBuilder<Context, Names, {[Key in Names]: Key extends U ?\n GeneratorRule<Context, Key, RET, ARGS> :\n (RuleDefs[Key] extends GeneratorRule<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: GeneratorRule<Context, U, RET, ARGS>):\n GeneratorBuilder<Context, Names | U, {[K in Names | U]: K extends Names ?\n (RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never)\n : (K extends U ? GeneratorRule<Context, K, RET, ARGS> : never)\n }> {\n const self = <GeneratorBuilder<Context, Names | U, {[K in Names | U]: K extends Names ?\n (RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never)\n : (K extends U ? GeneratorRule<Context, K, RET, ARGS> : never) }>>\n <unknown> this;\n const rules = <Record<string, GeneratorRule<Context>>> self.rules;\n if (rules[rule.name] !== undefined && rules[rule.name] !== rule) {\n throw new Error(`Rule ${rule.name} already exists in the GeneratorBuilder`);\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, GeneratorRule<Context, U, RET, ARGS>>,\n ): GeneratorBuilder<Context, Names | U, {[K in Names | U]: K extends Names ?\n (RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never)\n : (K extends U ? GeneratorRule<Context, K, RET, ARGS> : never)\n }> {\n return this.addRuleRedundant(rule);\n }\n\n public addMany<U extends readonly GeneratorRule<Context>[]>(\n ...rules: CheckOverlap<ParseNamesFromList<U>, Names, U>\n ): GeneratorBuilder<\n Context,\n Names | ParseNamesFromList<U>,\n {[K in Names | ParseNamesFromList<U>]:\n K extends keyof GenRulesToObject<typeof rules> ? (\n GenRulesToObject<typeof rules>[K] extends GeneratorRule<Context, K> ? GenRulesToObject<typeof rules>[K] : never\n ) : (\n K extends Names ? (RuleDefs[K] extends GeneratorRule<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 GeneratorBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never }> {\n delete this.rules[ruleName];\n return <GeneratorBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never }>>\n <unknown> this;\n }\n\n public getRule<U extends Names>(ruleName: U): RuleDefs[U] extends GeneratorRule<any, U, infer RT, infer PT> ?\n GeneratorRule<Context, U, RT, PT> : never {\n return <any> this.rules[ruleName];\n }\n\n /**\n * Merge this grammar GeneratorBuilder 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 GenRuleMap<OtherNames>,\n OW extends readonly GeneratorRule<Context>[],\n >(\n GeneratorBuilder: GeneratorBuilder<Context, OtherNames, OtherRules>,\n overridingRules: OW,\n ):\n GeneratorBuilder<\n Context,\n Names | OtherNames | ParseNamesFromList<OW>,\n {[K in Names | OtherNames | ParseNamesFromList<OW>]:\n K extends keyof GenRulesToObject<OW> ? (\n GenRulesToObject<OW>[K] extends GeneratorRule<Context, K> ? GenRulesToObject<OW>[K] : never\n )\n : (\n K extends Names ? (RuleDefs[K] extends GeneratorRule<Context, K> ? RuleDefs[K] : never)\n : K extends OtherNames ? (OtherRules[K] extends GeneratorRule<Context, K> ? OtherRules[K] : never)\n : 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, GeneratorRule<Context>> = { ...GeneratorBuilder.rules };\n const myRules: Record<string, GeneratorRule<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 GeneratorBuilder, 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 public build(): GeneratorFromRules<Context, Names, RuleDefs> {\n return <GeneratorFromRules<Context, Names, RuleDefs>> new DynamicGenerator(this.rules);\n }\n}\n"]}