@traqula/core 0.0.1-alpha.10
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.
- package/LICENSE.txt +22 -0
- package/README.md +137 -0
- package/lib/CoreFactory.d.ts +39 -0
- package/lib/CoreFactory.js +135 -0
- package/lib/CoreFactory.js.map +1 -0
- package/lib/Transformer.d.ts +26 -0
- package/lib/Transformer.js +57 -0
- package/lib/Transformer.js.map +1 -0
- package/lib/generator-builder/builderTypes.d.ts +20 -0
- package/lib/generator-builder/builderTypes.js +2 -0
- package/lib/generator-builder/builderTypes.js.map +1 -0
- package/lib/generator-builder/dynamicGenerator.d.ts +22 -0
- package/lib/generator-builder/dynamicGenerator.js +115 -0
- package/lib/generator-builder/dynamicGenerator.js.map +1 -0
- package/lib/generator-builder/generatorBuilder.d.ts +60 -0
- package/lib/generator-builder/generatorBuilder.js +104 -0
- package/lib/generator-builder/generatorBuilder.js.map +1 -0
- package/lib/generator-builder/generatorTypes.d.ts +36 -0
- package/lib/generator-builder/generatorTypes.js +2 -0
- package/lib/generator-builder/generatorTypes.js.map +1 -0
- package/lib/index.cjs +10121 -0
- package/lib/index.d.ts +13 -0
- package/lib/index.js +19 -0
- package/lib/index.js.map +1 -0
- package/lib/indirection-builder/IndirBuilder.d.ts +43 -0
- package/lib/indirection-builder/IndirBuilder.js +60 -0
- package/lib/indirection-builder/IndirBuilder.js.map +1 -0
- package/lib/indirection-builder/dynamicIndirected.d.ts +9 -0
- package/lib/indirection-builder/dynamicIndirected.js +28 -0
- package/lib/indirection-builder/dynamicIndirected.js.map +1 -0
- package/lib/indirection-builder/helpers.d.ts +24 -0
- package/lib/indirection-builder/helpers.js +11 -0
- package/lib/indirection-builder/helpers.js.map +1 -0
- package/lib/lexer-builder/LexerBuilder.d.ts +23 -0
- package/lib/lexer-builder/LexerBuilder.js +96 -0
- package/lib/lexer-builder/LexerBuilder.js.map +1 -0
- package/lib/nodeTypings.d.ts +53 -0
- package/lib/nodeTypings.js +2 -0
- package/lib/nodeTypings.js.map +1 -0
- package/lib/parser-builder/builderTypes.d.ts +26 -0
- package/lib/parser-builder/builderTypes.js +2 -0
- package/lib/parser-builder/builderTypes.js.map +1 -0
- package/lib/parser-builder/dynamicParser.d.ts +9 -0
- package/lib/parser-builder/dynamicParser.js +113 -0
- package/lib/parser-builder/dynamicParser.js.map +1 -0
- package/lib/parser-builder/parserBuilder.d.ts +74 -0
- package/lib/parser-builder/parserBuilder.js +171 -0
- package/lib/parser-builder/parserBuilder.js.map +1 -0
- package/lib/parser-builder/ruleDefTypes.d.ts +347 -0
- package/lib/parser-builder/ruleDefTypes.js +2 -0
- package/lib/parser-builder/ruleDefTypes.js.map +1 -0
- package/lib/utils.d.ts +17 -0
- package/lib/utils.js +8 -0
- package/lib/utils.js.map +1 -0
- package/package.json +47 -0
package/LICENSE.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright © 2024–now Jitse De Smet
|
|
4
|
+
Comunica Association and Ghent University – imec, Belgium
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in
|
|
14
|
+
all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
22
|
+
THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# Traqula core package
|
|
2
|
+
|
|
3
|
+
**WARNING:** V2 will come shortly and will have lots of breaking changes.
|
|
4
|
+
|
|
5
|
+
Traqula core contains core components of Traqula.
|
|
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
|
+
This library heavily relies on the amazing [Chevrotain package](https://chevrotain.io/docs/).
|
|
8
|
+
Knowing the basics of that package will allow you to quickly generate your own grammars.
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install @traqula/core
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
or
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
yarn add @traqula/core
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
23
|
+
|
|
24
|
+
Each parser contains two steps:
|
|
25
|
+
1. a lexer
|
|
26
|
+
2. a grammar + abstract syntax tree generation step.
|
|
27
|
+
|
|
28
|
+
Sometimes grammar definitions and abstract syntax tree generation is split into separate steps.
|
|
29
|
+
In this library, we choose to keep the two together when building a parser.
|
|
30
|
+
|
|
31
|
+
### Lexer Builder
|
|
32
|
+
|
|
33
|
+
To tackle the first step, a lexer should be created.
|
|
34
|
+
This is a system that separates different groups of characters into annotated groups.
|
|
35
|
+
In human language for example the sentence 'I eat apples' is lexed into different groups called **tokens** namely `words` and `spaces`:
|
|
36
|
+
`I`, ` `, `eat`, ` `, `apples`.
|
|
37
|
+
|
|
38
|
+
To create a token definition, you use the provided function `createToken` like:
|
|
39
|
+
```typescript
|
|
40
|
+
const select = createToken({ name: 'Select', pattern: /select/i, label: 'SELECT' });
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Lexer definitions are then put in a list and when a lexer is build, the lexer will match a string to the [**first token in the list**](https://chevrotain.io/docs/tutorial/step1_lexing.html#creating-the-lexer) that matches.
|
|
44
|
+
Note that the order of definitions in the list is thus essential.
|
|
45
|
+
|
|
46
|
+
We therefore use a [lexer builder](./lib/lexer-builder/LexerBuilder.ts) which allows you to easily:
|
|
47
|
+
1. change the order of lexer rules,
|
|
48
|
+
2. and create a new lexer staring from an existing one.
|
|
49
|
+
|
|
50
|
+
Creating a builder is as easy as:
|
|
51
|
+
|
|
52
|
+
```typescript
|
|
53
|
+
const sparql11Tokens = LexerBuilder.create(<const> [select, describe]);
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
A new lexer can be created from an existing one by calling:
|
|
57
|
+
```typescript
|
|
58
|
+
const sparql11AdjustTokens = sparql11Tokens.addBefore(select, BuiltInAdjust);
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Parser Builder
|
|
62
|
+
|
|
63
|
+
The grammar builder is used to link together grammar rules such that they can be converted into a parser.
|
|
64
|
+
Grammar rule definitions come in the form of [ParserRule](./lib/parser-builder/ruleDefTypes.ts) objects.
|
|
65
|
+
Each `ParserRule` object contains its name and its returnType.
|
|
66
|
+
Optionally, it can also contain arguments that should be provided to the SUBRULE calls.
|
|
67
|
+
A simple example of a grammar rule is the rule bellow that allows you to parse booleanLiterals.
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
/**
|
|
71
|
+
* Parses a boolean literal.
|
|
72
|
+
* [[134]](https://www.w3.org/TR/sparql11-query/#rBooleanLiteral)
|
|
73
|
+
*/
|
|
74
|
+
export const booleanLiteral: ParserRule<'booleanLiteral', LiteralTerm> = <const> {
|
|
75
|
+
name: 'booleanLiteral',
|
|
76
|
+
impl: ({ CONSUME, OR, context }) => () => OR([
|
|
77
|
+
{ ALT: () => context.dataFactory.literal(
|
|
78
|
+
CONSUME(l.true_).image.toLowerCase(),
|
|
79
|
+
context.dataFactory.namedNode(CommonIRIs.BOOLEAN),
|
|
80
|
+
) },
|
|
81
|
+
{ ALT: () => context.dataFactory.literal(
|
|
82
|
+
CONSUME(l.false_).image.toLowerCase(),
|
|
83
|
+
context.dataFactory.namedNode(CommonIRIs.BOOLEAN),
|
|
84
|
+
) },
|
|
85
|
+
]),
|
|
86
|
+
};
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The `impl` member of `ParserRule` is a function that receives:
|
|
90
|
+
1. essential functions to create a grammar rule (capitalized members),
|
|
91
|
+
2. a context object that can be used by the rules,
|
|
92
|
+
3. a cache object ([WeakMap](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap)) that can be used to cache the creation of long lists in the parser, [increasing parser performance](https://chevrotain.io/docs/guide/performance.html#caching-arrays-of-alternatives).
|
|
93
|
+
|
|
94
|
+
You cannot unpack the context entry in the function definition itself because the parser uses a [recording phase](https://chevrotain.io/docs/guide/internals.html#grammar-recording) to optimize itself. During this phase, the context entry will be undefined, as such, it can only be accessed within the `ACTION` function.
|
|
95
|
+
|
|
96
|
+
The result of an `impl` call is a function called a `rule`.
|
|
97
|
+
Rules can be [parameterized](https://chevrotain.io/docs/features/parameterized_rules.html), although I have not found a scenario where that is usefully.
|
|
98
|
+
Personally I create a function that can be used to create multiple `ParserRule` objects.
|
|
99
|
+
The result of a rule should match the type provided in the `ParserRule` definition, and is the result of a call of `SUBRULE` with that rule.
|
|
100
|
+
|
|
101
|
+
#### Patching rules
|
|
102
|
+
|
|
103
|
+
When a rule definition calls to a subrule using `SUBRULE(mySub)`, the implementation itself is not necessarily called.
|
|
104
|
+
That is because the SUBRULE function will call the function with the same name as `mySub` that is present in the current grammarBuilder.
|
|
105
|
+
|
|
106
|
+
A builder is thus free to override definitions as it pleases. Doing so does however **break the types** and should thus only be done with care.
|
|
107
|
+
An example patch is:
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
const myBuilder = Builder
|
|
111
|
+
.createBuilder(<const> [selectOrDescribe, selectRule, describeRule])
|
|
112
|
+
.patchRule(selectRuleAlternative);
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
When `selectOrDescribe` calls what it thinks to be `selectRule`,
|
|
116
|
+
it will instead call `selectRuleAlternative` since it overwrote the function `selectRule` with the same name.
|
|
117
|
+
|
|
118
|
+
### Generator Builder
|
|
119
|
+
|
|
120
|
+
The generator builder function in much the same as the [parser builder](#parser-builder).
|
|
121
|
+
Your builder expects objects of type [GeneratorRule](lib/generator-builder/generatorTypes.ts),
|
|
122
|
+
containing the implementation of the generator in the `gImpl` member.
|
|
123
|
+
The `gImpl` function gets essential functions to create a generator rule (capitalized members),
|
|
124
|
+
returning a function that will get the AST and context, returning a string.
|
|
125
|
+
For generator rules, you can unpack the context since no recording phase is present in this case.
|
|
126
|
+
The idea is that GeneratorRules and ParserRules can be tied together in the same object, as such, similar behaviour is grouped together.
|
|
127
|
+
|
|
128
|
+
```typescript
|
|
129
|
+
/**
|
|
130
|
+
* Parses a named node, either as an IRI or as a prefixed name.
|
|
131
|
+
* [[136]](https://www.w3.org/TR/sparql11-query/#riri)
|
|
132
|
+
*/
|
|
133
|
+
export const iri: GeneratorRule<'iri', IriTerm> = <const> {
|
|
134
|
+
name: 'iri',
|
|
135
|
+
gImpl: () => ast => ast.value,
|
|
136
|
+
};
|
|
137
|
+
```
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { IToken } from 'chevrotain';
|
|
2
|
+
import type { SourceLocation, SourceLocationNodeAutoGenerate, SourceLocationNodeReplace, SourceLocationNoMaterialize, SourceLocationSource, SourceLocationStringReplace, Node, Localized, Wrap } from './nodeTypings';
|
|
3
|
+
export type Typed<Type extends PropertyKey> = {
|
|
4
|
+
type: Type;
|
|
5
|
+
};
|
|
6
|
+
export type SubTyped<Type extends PropertyKey, Subtype extends PropertyKey> = {
|
|
7
|
+
type: Type;
|
|
8
|
+
subType: Subtype;
|
|
9
|
+
};
|
|
10
|
+
export declare class CoreFactory {
|
|
11
|
+
wrap<T>(val: T, loc: SourceLocation): Wrap<T>;
|
|
12
|
+
isLocalized(obj: unknown): obj is Localized;
|
|
13
|
+
sourceLocation(...elements: (undefined | IToken | Localized)[]): SourceLocation;
|
|
14
|
+
sourceLocationNoMaterialize(): SourceLocationNoMaterialize;
|
|
15
|
+
/**
|
|
16
|
+
* Returns a copy of the argument that is not materialized
|
|
17
|
+
*/
|
|
18
|
+
dematerialized<T extends Node>(arg: T): T & {
|
|
19
|
+
loc: SourceLocationNoMaterialize;
|
|
20
|
+
};
|
|
21
|
+
safeObjectTransform(value: unknown, mapper: (some: object) => any): any;
|
|
22
|
+
forcedAutoGenTree<T extends object>(obj: T): T;
|
|
23
|
+
forceMaterialized<T extends Node>(arg: T): T;
|
|
24
|
+
isSourceLocation(loc: object): loc is SourceLocation;
|
|
25
|
+
sourceLocationSource(start: number, end: number): SourceLocationSource;
|
|
26
|
+
gen(): SourceLocationNodeAutoGenerate;
|
|
27
|
+
isSourceLocationSource(loc: object): loc is SourceLocationSource;
|
|
28
|
+
isSourceLocationStringReplace(loc: object): loc is SourceLocationStringReplace;
|
|
29
|
+
sourceLocationNodeReplaceUnsafe(loc: SourceLocation): SourceLocationNodeReplace;
|
|
30
|
+
sourceLocationNodeReplace(location: SourceLocationSource): SourceLocationNodeReplace;
|
|
31
|
+
sourceLocationNodeReplace(start: number, end: number): SourceLocationNodeReplace;
|
|
32
|
+
isSourceLocationNodeReplace(loc: object): loc is SourceLocationNodeReplace;
|
|
33
|
+
isSourceLocationNodeAutoGenerate(loc: object): loc is SourceLocationNodeAutoGenerate;
|
|
34
|
+
nodeShouldPrint(node: Localized): boolean;
|
|
35
|
+
printFilter(node: Localized, callback: () => void): void;
|
|
36
|
+
isSourceLocationNoMaterialize(loc: object): loc is SourceLocationNoMaterialize;
|
|
37
|
+
isOfType<Type extends string>(obj: object, type: Type): obj is Typed<Type>;
|
|
38
|
+
isOfSubType<Type extends string, SubType extends string>(obj: object, type: Type, subType: SubType): obj is SubTyped<Type, SubType>;
|
|
39
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
export class CoreFactory {
|
|
2
|
+
wrap(val, loc) {
|
|
3
|
+
return { val, loc };
|
|
4
|
+
}
|
|
5
|
+
isLocalized(obj) {
|
|
6
|
+
return typeof obj === 'object' && obj !== null && 'loc' in obj &&
|
|
7
|
+
typeof obj.loc === 'object' && obj.loc !== null && 'sourceLocationType' in obj.loc;
|
|
8
|
+
}
|
|
9
|
+
sourceLocation(...elements) {
|
|
10
|
+
const pureElements = elements.filter(x => x !== undefined);
|
|
11
|
+
if (pureElements.length === 0) {
|
|
12
|
+
return this.sourceLocationNoMaterialize();
|
|
13
|
+
}
|
|
14
|
+
const filtered = pureElements.filter(element => !this.isLocalized(element) || this.isSourceLocationSource(element.loc) ||
|
|
15
|
+
this.isSourceLocationStringReplace(element.loc) || this.isSourceLocationNodeReplace(element.loc));
|
|
16
|
+
if (filtered.length === 0) {
|
|
17
|
+
return this.gen();
|
|
18
|
+
}
|
|
19
|
+
const first = filtered[0];
|
|
20
|
+
const last = filtered.at(-1);
|
|
21
|
+
return {
|
|
22
|
+
sourceLocationType: 'source',
|
|
23
|
+
start: this.isLocalized(first) ?
|
|
24
|
+
first.loc.start :
|
|
25
|
+
first.startOffset,
|
|
26
|
+
end: this.isLocalized(last) ?
|
|
27
|
+
last.loc.end :
|
|
28
|
+
(last.endOffset + 1),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
sourceLocationNoMaterialize() {
|
|
32
|
+
return { sourceLocationType: 'noMaterialize' };
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Returns a copy of the argument that is not materialized
|
|
36
|
+
*/
|
|
37
|
+
dematerialized(arg) {
|
|
38
|
+
return { ...arg, loc: this.sourceLocationNoMaterialize() };
|
|
39
|
+
}
|
|
40
|
+
safeObjectTransform(value, mapper) {
|
|
41
|
+
if (value && typeof value === 'object') {
|
|
42
|
+
// If you wonder why this is all so hard, this is the reason. We cannot lose the methods of our Array objects
|
|
43
|
+
if (Array.isArray(value)) {
|
|
44
|
+
return value.map(x => this.safeObjectTransform(x, mapper));
|
|
45
|
+
}
|
|
46
|
+
return mapper(value);
|
|
47
|
+
}
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
forcedAutoGenTree(obj) {
|
|
51
|
+
const copy = { ...obj };
|
|
52
|
+
for (const [key, value] of Object.entries(copy)) {
|
|
53
|
+
copy[key] = this.safeObjectTransform(value, obj => this.forcedAutoGenTree(obj));
|
|
54
|
+
}
|
|
55
|
+
if (this.isLocalized(copy)) {
|
|
56
|
+
copy.loc = this.gen();
|
|
57
|
+
}
|
|
58
|
+
return copy;
|
|
59
|
+
}
|
|
60
|
+
forceMaterialized(arg) {
|
|
61
|
+
if (this.isSourceLocationNoMaterialize(arg.loc)) {
|
|
62
|
+
return this.forcedAutoGenTree(arg);
|
|
63
|
+
}
|
|
64
|
+
return { ...arg };
|
|
65
|
+
}
|
|
66
|
+
isSourceLocation(loc) {
|
|
67
|
+
return 'sourceLocationType' in loc;
|
|
68
|
+
}
|
|
69
|
+
sourceLocationSource(start, end) {
|
|
70
|
+
return {
|
|
71
|
+
sourceLocationType: 'source',
|
|
72
|
+
start,
|
|
73
|
+
end,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
gen() {
|
|
77
|
+
return { sourceLocationType: 'autoGenerate' };
|
|
78
|
+
}
|
|
79
|
+
isSourceLocationSource(loc) {
|
|
80
|
+
return this.isSourceLocation(loc) && loc.sourceLocationType === 'source';
|
|
81
|
+
}
|
|
82
|
+
isSourceLocationStringReplace(loc) {
|
|
83
|
+
return this.isSourceLocation(loc) && loc.sourceLocationType === 'stringReplace';
|
|
84
|
+
}
|
|
85
|
+
sourceLocationNodeReplaceUnsafe(loc) {
|
|
86
|
+
if (this.isSourceLocationSource(loc)) {
|
|
87
|
+
return this.sourceLocationNodeReplace(loc);
|
|
88
|
+
}
|
|
89
|
+
throw new Error('not possible');
|
|
90
|
+
}
|
|
91
|
+
sourceLocationNodeReplace(startOrLoc, end) {
|
|
92
|
+
let starting;
|
|
93
|
+
let ending;
|
|
94
|
+
if (typeof startOrLoc === 'number') {
|
|
95
|
+
starting = startOrLoc;
|
|
96
|
+
ending = end;
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
starting = startOrLoc.start;
|
|
100
|
+
ending = startOrLoc.end;
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
sourceLocationType: 'nodeReplace',
|
|
104
|
+
start: starting,
|
|
105
|
+
end: ending,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
isSourceLocationNodeReplace(loc) {
|
|
109
|
+
return this.isSourceLocation(loc) && loc.sourceLocationType === 'nodeReplace';
|
|
110
|
+
}
|
|
111
|
+
isSourceLocationNodeAutoGenerate(loc) {
|
|
112
|
+
return this.isSourceLocation(loc) && loc.sourceLocationType === 'autoGenerate';
|
|
113
|
+
}
|
|
114
|
+
nodeShouldPrint(node) {
|
|
115
|
+
return this.isSourceLocationNodeReplace(node.loc) ||
|
|
116
|
+
this.isSourceLocationNodeAutoGenerate(node.loc);
|
|
117
|
+
}
|
|
118
|
+
printFilter(node, callback) {
|
|
119
|
+
if (this.nodeShouldPrint(node)) {
|
|
120
|
+
callback();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
isSourceLocationNoMaterialize(loc) {
|
|
124
|
+
return this.isSourceLocation(loc) && loc.sourceLocationType === 'noMaterialize';
|
|
125
|
+
}
|
|
126
|
+
isOfType(obj, type) {
|
|
127
|
+
const casted = obj;
|
|
128
|
+
return casted.type === type;
|
|
129
|
+
}
|
|
130
|
+
isOfSubType(obj, type, subType) {
|
|
131
|
+
const temp = obj;
|
|
132
|
+
return temp.type === type && temp.subType === subType;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
//# sourceMappingURL=CoreFactory.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"CoreFactory.js","sourceRoot":"","sources":["CoreFactory.ts"],"names":[],"mappings":"AAiBA,MAAM,OAAO,WAAW;IACf,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,MAAM,YAAY,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;QAC3D,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC9B,OAAO,IAAI,CAAC,2BAA2B,EAAE,CAAC;QAC5C,CAAC;QACD,MAAM,QAAQ,GAAG,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAC7C,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,IAAI,CAAC,sBAAsB,CAAC,OAAO,CAAC,GAAG,CAAC;YACtE,IAAI,CAAC,6BAA6B,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,2BAA2B,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;QACpG,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC1B,OAAO,IAAI,CAAC,GAAG,EAA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AC,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","sourcesContent":["import type { IToken } from 'chevrotain';\n\nimport type {\n SourceLocation,\n SourceLocationNodeAutoGenerate,\n SourceLocationNodeReplace,\n SourceLocationNoMaterialize,\n SourceLocationSource,\n SourceLocationStringReplace,\n Node,\n Localized,\n Wrap,\n} from './nodeTypings';\n\nexport type Typed<Type extends PropertyKey> = { type: Type };\nexport type SubTyped<Type extends PropertyKey, Subtype extends PropertyKey> = { type: Type; subType: Subtype };\n\nexport class CoreFactory {\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[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"]}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { SubTyped } from './CoreFactory';
|
|
2
|
+
import type { Node } from './nodeTypings';
|
|
3
|
+
type MapNodeTypeToImpls<Nodes extends Node> = {
|
|
4
|
+
[Node in Nodes as Node['type']]: Node;
|
|
5
|
+
};
|
|
6
|
+
type MapNodeSubTypeToImpls<Nodes extends Node & {
|
|
7
|
+
subType: string;
|
|
8
|
+
}> = {
|
|
9
|
+
[Node in Nodes as Node['subType']]: Node;
|
|
10
|
+
};
|
|
11
|
+
export type AlterNodeOutput<RecursiveObject extends object, Input, Out> = {
|
|
12
|
+
[Key in keyof RecursiveObject]: RecursiveObject[Key] extends object ? (AlterNodeOutput<RecursiveObject[Key], Input, Out> extends Input ? Out : AlterNodeOutput<RecursiveObject[Key], Input, Out>) : RecursiveObject[Key];
|
|
13
|
+
};
|
|
14
|
+
export declare class Transformer<Nodes extends Node, NodeMapping extends MapNodeTypeToImpls<Nodes> & Record<string, unknown> = MapNodeTypeToImpls<Nodes>> {
|
|
15
|
+
transformNode<Input extends object, TypeFilter extends keyof NodeMapping, Out>(curObject: Input, searchType: TypeFilter, patch: (current: NodeMapping[TypeFilter]) => Out): AlterNodeOutput<Input, NodeMapping[TypeFilter], Out>;
|
|
16
|
+
transformNodeSpecific<Input extends object, TypeFilter extends keyof NodeMapping, SpecificType extends keyof SpecificNodes, Out, SpecificNodes = NodeMapping[TypeFilter] extends Node & {
|
|
17
|
+
subType: string;
|
|
18
|
+
} ? MapNodeSubTypeToImpls<NodeMapping[TypeFilter]> : never>(curObject: Input, searchType: TypeFilter, searchSubType: SpecificType, patch: (current: SpecificNodes[SpecificType]) => Out): AlterNodeOutput<Input, SubTyped<TypeFilter, SpecificType>, Out>;
|
|
19
|
+
visitObjects(curObject: object, visitor: (current: object) => void): void;
|
|
20
|
+
visitNode<Input extends object, TypeFilter extends keyof NodeMapping>(curObject: Input, searchType: TypeFilter, visitor: (current: Readonly<NodeMapping[TypeFilter]>) => void): void;
|
|
21
|
+
visitNodeSpecific<Input extends object, TypeFilter extends keyof NodeMapping, SpecificType extends keyof SpecificNodes, SpecificNodes = NodeMapping[TypeFilter] extends Node & {
|
|
22
|
+
subType: string;
|
|
23
|
+
} ? MapNodeSubTypeToImpls<NodeMapping[TypeFilter]> : never>(curObject: Input, searchType: TypeFilter, searchSubType: SpecificType, visitor: (current: Readonly<SpecificNodes[SpecificType]>) => void): void;
|
|
24
|
+
private safeObjectVisit;
|
|
25
|
+
}
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export class Transformer {
|
|
2
|
+
transformNode(curObject, searchType, patch) {
|
|
3
|
+
const copy = { ...curObject };
|
|
4
|
+
for (const [key, value] of Object.entries(copy)) {
|
|
5
|
+
copy[key] =
|
|
6
|
+
this.safeObjectVisit(value, obj => this.transformNode(obj, searchType, patch));
|
|
7
|
+
}
|
|
8
|
+
if (copy.type === searchType) {
|
|
9
|
+
return patch(copy);
|
|
10
|
+
}
|
|
11
|
+
return copy;
|
|
12
|
+
}
|
|
13
|
+
transformNodeSpecific(curObject, searchType, searchSubType, patch) {
|
|
14
|
+
const copy = { ...curObject };
|
|
15
|
+
for (const [key, value] of Object.entries(copy)) {
|
|
16
|
+
copy[key] =
|
|
17
|
+
this.safeObjectVisit(value, obj => this.transformNodeSpecific(obj, searchType, searchSubType, patch));
|
|
18
|
+
}
|
|
19
|
+
if (copy.type === searchType && copy.subType === searchSubType) {
|
|
20
|
+
return patch(copy);
|
|
21
|
+
}
|
|
22
|
+
return copy;
|
|
23
|
+
}
|
|
24
|
+
visitObjects(curObject, visitor) {
|
|
25
|
+
for (const value of Object.values(curObject)) {
|
|
26
|
+
this.safeObjectVisit(value, obj => this.visitObjects(obj, visitor));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
visitNode(curObject, searchType, visitor) {
|
|
30
|
+
for (const value of Object.values(curObject)) {
|
|
31
|
+
this.safeObjectVisit(value, obj => this.visitNode(obj, searchType, visitor));
|
|
32
|
+
}
|
|
33
|
+
if (curObject.type === searchType) {
|
|
34
|
+
visitor(curObject);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
visitNodeSpecific(curObject, searchType, searchSubType, visitor) {
|
|
38
|
+
for (const value of Object.values(curObject)) {
|
|
39
|
+
this.safeObjectVisit(value, obj => this.visitNodeSpecific(obj, searchType, searchSubType, visitor));
|
|
40
|
+
}
|
|
41
|
+
const cast = curObject;
|
|
42
|
+
if (cast.type === searchType && cast.subType === searchSubType) {
|
|
43
|
+
visitor(curObject);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
safeObjectVisit(value, mapper) {
|
|
47
|
+
if (value && typeof value === 'object') {
|
|
48
|
+
// If you wonder why this is all so hard, this is the reason. We cannot lose the methods of our Array objects
|
|
49
|
+
if (Array.isArray(value)) {
|
|
50
|
+
return value.map(x => this.safeObjectVisit(x, mapper));
|
|
51
|
+
}
|
|
52
|
+
return mapper(value);
|
|
53
|
+
}
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=Transformer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Transformer.js","sourceRoot":"","sources":["Transformer.ts"],"names":[],"mappings":"AAcA,MAAM,OAAO,WAAW;IAIf,aAAa,CAClB,SAAgB,EAChB,UAAsB,EACtB,KAAgD;QAEhD,MAAM,IAAI,GAAuB,EAAE,GAAG,SAAS,EAAE,CAAC;QAClD,KAAK,MAAM,CAAE,GAAG,EAAE,KAAK,CAAE,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;YACvB,IAAK,CAAC,GAAG,CAAC;gBACnC,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC,CAAC;QACnF,CAAC;QACD,IAAI,IAAI,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YAC7B,OAAa,KAAK,CAA2B,IAAI,CAAC,CAAC;QACrD,CAAC;QACD,OAAa,IAAI,CAAC;IACpB,CAAC;IAEM,qBAAqB,CAQ1B,SAAgB,EAChB,UAAsB,EACtB,aA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iB,CAOtB,SAAgB,EAChB,UAAsB,EACtB,aAA2B,EAC3B,OAAiE;QAEjE,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,EAAE,CAAC;YAC7C,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,iBAAiB,CAAC,GAAG,EAAE,UAAU,EAAE,aAAa,EAAE,OAAO,CAAC,CAAC,CAAC;QACtG,CAAC;QACD,MAAM,IAAI,GAA0C,SAAS,CAAC;QAC9D,IAAI,IAAI,CAAC,IAAI,KAAK,UAAU,IAAI,IAAI,CAAC,OAAO,KAAK,aAAa,EAAE,CAAC;YAC/D,OAAO,CAA+B,SAAS,CAAC,CAAC;QACnD,CAAC;IACH,CAAC;IAEO,eAAe,CAAC,KAAc,EAAE,MAA6B;QACnE,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YACvC,6GAA6G;YAC7G,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;gBACzB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;YACzD,CAAC;YACD,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["import type { SubTyped } from './CoreFactory';\nimport type { Node } from './nodeTypings';\n\ntype MapNodeTypeToImpls<Nodes extends Node> = {[Node in Nodes as Node['type']]: Node };\ntype MapNodeSubTypeToImpls<Nodes extends Node & { subType: string }> = {[Node in Nodes as Node['subType']]: Node };\n\nexport type AlterNodeOutput<RecursiveObject extends object, Input, Out>\n = {\n [Key in keyof RecursiveObject]: RecursiveObject[Key] extends object ?\n (AlterNodeOutput<RecursiveObject[Key], Input, Out> extends Input ?\n Out : AlterNodeOutput<RecursiveObject[Key], Input, Out>) :\n RecursiveObject[Key]\n };\n\nexport class Transformer<\n Nodes extends Node,\nNodeMapping extends MapNodeTypeToImpls<Nodes> & Record<string, unknown> = MapNodeTypeToImpls<Nodes>,\n> {\n public transformNode<Input extends object, TypeFilter extends keyof NodeMapping, Out>(\n curObject: Input,\n searchType: TypeFilter,\n patch: (current: NodeMapping[TypeFilter]) => Out,\n ): AlterNodeOutput<Input, NodeMapping[TypeFilter], Out> {\n const copy: { type?: unknown } = { ...curObject };\n for (const [ key, value ] of Object.entries(copy)) {\n (<Record<string, unknown>> copy)[key] =\n this.safeObjectVisit(value, obj => this.transformNode(obj, searchType, patch));\n }\n if (copy.type === searchType) {\n return <any> patch(<NodeMapping[TypeFilter]> copy);\n }\n return <any> copy;\n }\n\n public transformNodeSpecific<\n Input extends object,\nTypeFilter extends keyof NodeMapping,\nSpecificType extends keyof SpecificNodes,\nOut,\nSpecificNodes = NodeMapping[TypeFilter] extends Node & { subType: string } ?\n MapNodeSubTypeToImpls<NodeMapping[TypeFilter]> : never,\n>(\n curObject: Input,\n searchType: TypeFilter,\n searchSubType: SpecificType,\n patch: (current: SpecificNodes[SpecificType]) => Out,\n ): AlterNodeOutput<Input, SubTyped<TypeFilter, SpecificType>, Out> {\n const copy: { type?: unknown; subType?: unknown } = { ...curObject };\n for (const [ key, value ] of Object.entries(copy)) {\n (<Record<string, unknown>> copy)[key] =\n this.safeObjectVisit(value, obj => this.transformNodeSpecific(obj, searchType, searchSubType, patch));\n }\n if (copy.type === searchType && copy.subType === searchSubType) {\n return <any> patch(<SpecificNodes[SpecificType]> copy);\n }\n return <any> copy;\n }\n\n public visitObjects(curObject: object, visitor: (current: object) => void): void {\n for (const value of Object.values(curObject)) {\n this.safeObjectVisit(value, obj => this.visitObjects(obj, visitor));\n }\n }\n\n public visitNode<Input extends object, TypeFilter extends keyof NodeMapping>(\n curObject: Input,\n searchType: TypeFilter,\n visitor: (current: Readonly<NodeMapping[TypeFilter]>) => void,\n ): void {\n for (const value of Object.values(curObject)) {\n this.safeObjectVisit(value, obj => this.visitNode(obj, searchType, visitor));\n }\n if ((<{ type?: unknown }>curObject).type === searchType) {\n visitor(<NodeMapping[TypeFilter]> curObject);\n }\n }\n\n public visitNodeSpecific<\n Input extends object,\nTypeFilter extends keyof NodeMapping,\nSpecificType extends keyof SpecificNodes,\nSpecificNodes = NodeMapping[TypeFilter] extends Node & { subType: string } ?\n MapNodeSubTypeToImpls<NodeMapping[TypeFilter]> : never,\n >(\n curObject: Input,\n searchType: TypeFilter,\n searchSubType: SpecificType,\n visitor: (current: Readonly<SpecificNodes[SpecificType]>) => void,\n ): void {\n for (const value of Object.values(curObject)) {\n this.safeObjectVisit(value, obj => this.visitNodeSpecific(obj, searchType, searchSubType, visitor));\n }\n const cast = <{ type?: unknown; subType?: unknown }>curObject;\n if (cast.type === searchType && cast.subType === searchSubType) {\n visitor(<SpecificNodes[SpecificType]> curObject);\n }\n }\n\n private safeObjectVisit(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.safeObjectVisit(x, mapper));\n }\n return mapper(value);\n }\n return value;\n }\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ParseNamesFromList } from '../parser-builder/builderTypes';
|
|
2
|
+
import type { GeneratorRule } from './generatorTypes';
|
|
3
|
+
/**
|
|
4
|
+
* Convert a list of ruledefs to a record that maps each rule name to its definition.
|
|
5
|
+
*/
|
|
6
|
+
export type GenRuleMap<RuleNames extends string> = {
|
|
7
|
+
[Key in RuleNames]: GeneratorRule<any, Key>;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Convert a list of RuleDefs to a Record with the name of the RuleDef as the key, matching the RuleDefMap type.
|
|
11
|
+
*/
|
|
12
|
+
export type GenRulesToObject<T extends readonly GeneratorRule[], Names extends string = ParseNamesFromList<T>, Agg extends Record<string, GeneratorRule> = Record<never, never>> = T extends readonly [infer First, ...infer Rest] ? (First extends GeneratorRule ? (Rest extends readonly GeneratorRule[] ? (GenRulesToObject<Rest, Names, {
|
|
13
|
+
[K in keyof Agg | First['name']]: K extends First['name'] ? First : Agg[K];
|
|
14
|
+
}>) : never) : never) : GenRuleMap<Names> & Agg;
|
|
15
|
+
export type GeneratorFromRules<Context, Names extends string, RuleDefs extends GenRuleMap<Names>> = {
|
|
16
|
+
[K in Names]: RuleDefs[K] extends GeneratorRule<Context, K, infer RET, infer ARGS> ? (input: RET, context: Context & {
|
|
17
|
+
origSource: string;
|
|
18
|
+
offset?: number;
|
|
19
|
+
}, args: ARGS) => string : never;
|
|
20
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"builderTypes.js","sourceRoot":"","sources":["builderTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ParseNamesFromList } from '../parser-builder/builderTypes';\nimport type { GeneratorRule } from './generatorTypes';\n\n/**\n * Convert a list of ruledefs to a record that maps each rule name to its definition.\n */\nexport type GenRuleMap<RuleNames extends string> = {[Key in RuleNames]: GeneratorRule<any, Key> };\n\n/**\n * Convert a list of RuleDefs to a Record with the name of the RuleDef as the key, matching the RuleDefMap type.\n */\nexport type GenRulesToObject<\n T extends readonly GeneratorRule[],\n Names extends string = ParseNamesFromList<T>,\n Agg extends Record<string, GeneratorRule> = Record<never, never>,\n> = T extends readonly [infer First, ...infer Rest] ? (\n First extends GeneratorRule ? (\n Rest extends readonly GeneratorRule[] ? (\n GenRulesToObject<Rest, Names, {[K in keyof Agg | First['name']]: K extends First['name'] ? First : Agg[K] }>\n ) : never\n ) : never\n) : GenRuleMap<Names> & Agg;\n\nexport type GeneratorFromRules<Context, Names extends string, RuleDefs extends GenRuleMap<Names>> = {\n [K in Names]: RuleDefs[K] extends GeneratorRule<Context, K, infer RET, infer ARGS> ?\n (input: RET, context: Context & { origSource: string; offset?: number }, args: ARGS) => string : never\n};\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { CoreFactory } from '../CoreFactory';
|
|
2
|
+
import type { GenRuleMap } from './builderTypes';
|
|
3
|
+
import type { RuleDefArg } from './generatorTypes';
|
|
4
|
+
export declare class DynamicGenerator<Context, Names extends string, RuleDefs extends GenRuleMap<Names>> {
|
|
5
|
+
protected rules: RuleDefs;
|
|
6
|
+
protected readonly factory: CoreFactory;
|
|
7
|
+
protected __context: Context | undefined;
|
|
8
|
+
protected origSource: string;
|
|
9
|
+
protected generatedUntil: number;
|
|
10
|
+
protected expectsSpace: boolean;
|
|
11
|
+
protected readonly stringBuilder: string[];
|
|
12
|
+
constructor(rules: RuleDefs);
|
|
13
|
+
setContext(context: Context): void;
|
|
14
|
+
protected getSafeContext(): Context;
|
|
15
|
+
protected readonly subrule: RuleDefArg['SUBRULE'];
|
|
16
|
+
protected readonly handleLoc: RuleDefArg['HANDLE_LOC'];
|
|
17
|
+
protected readonly catchup: RuleDefArg['CATCHUP'];
|
|
18
|
+
protected readonly print: RuleDefArg['PRINT'];
|
|
19
|
+
private readonly printWord;
|
|
20
|
+
private readonly printSpaceLeft;
|
|
21
|
+
private readonly printWords;
|
|
22
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { CoreFactory } from '../CoreFactory';
|
|
2
|
+
export class DynamicGenerator {
|
|
3
|
+
constructor(rules) {
|
|
4
|
+
this.rules = rules;
|
|
5
|
+
this.factory = new CoreFactory();
|
|
6
|
+
this.__context = undefined;
|
|
7
|
+
this.origSource = '';
|
|
8
|
+
this.generatedUntil = 0;
|
|
9
|
+
this.stringBuilder = [];
|
|
10
|
+
this.subrule = (cstDef, ast, arg) => {
|
|
11
|
+
const def = this.rules[cstDef.name];
|
|
12
|
+
if (!def) {
|
|
13
|
+
throw new Error(`Rule ${cstDef.name} not found`);
|
|
14
|
+
}
|
|
15
|
+
const generate = () => def.gImpl({
|
|
16
|
+
SUBRULE: this.subrule,
|
|
17
|
+
PRINT: this.print,
|
|
18
|
+
PRINT_SPACE_LEFT: this.printSpaceLeft,
|
|
19
|
+
PRINT_WORD: this.printWord,
|
|
20
|
+
PRINT_WORDS: this.printWords,
|
|
21
|
+
CATCHUP: this.catchup,
|
|
22
|
+
HANDLE_LOC: this.handleLoc,
|
|
23
|
+
})(ast, this.getSafeContext(), arg);
|
|
24
|
+
if (this.factory.isLocalized(ast)) {
|
|
25
|
+
this.handleLoc(ast, generate);
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
generate();
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
this.handleLoc = (localized, handle) => {
|
|
32
|
+
if (this.factory.isSourceLocationNoMaterialize(localized.loc)) {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
if (this.factory.isSourceLocationStringReplace(localized.loc)) {
|
|
36
|
+
this.catchup(localized.loc.start);
|
|
37
|
+
this.print(localized.loc.newSource);
|
|
38
|
+
this.generatedUntil = localized.loc.end;
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (this.factory.isSourceLocationNodeReplace(localized.loc)) {
|
|
42
|
+
this.catchup(localized.loc.start);
|
|
43
|
+
this.generatedUntil = localized.loc.end;
|
|
44
|
+
}
|
|
45
|
+
if (this.factory.isSourceLocationSource(localized.loc)) {
|
|
46
|
+
this.catchup(localized.loc.start);
|
|
47
|
+
}
|
|
48
|
+
// If autoGenerate - do nothing
|
|
49
|
+
const ret = handle();
|
|
50
|
+
if (this.factory.isSourceLocationSource(localized.loc)) {
|
|
51
|
+
this.catchup(localized.loc.end);
|
|
52
|
+
}
|
|
53
|
+
return ret;
|
|
54
|
+
};
|
|
55
|
+
this.catchup = (until) => {
|
|
56
|
+
const start = this.generatedUntil;
|
|
57
|
+
if (start < until) {
|
|
58
|
+
this.print(this.origSource.slice(start, until));
|
|
59
|
+
}
|
|
60
|
+
this.generatedUntil = Math.max(this.generatedUntil, until);
|
|
61
|
+
};
|
|
62
|
+
this.print = (...args) => {
|
|
63
|
+
const pureArgs = args.filter(x => x.length > 0);
|
|
64
|
+
if (pureArgs.length > 0) {
|
|
65
|
+
const [head, ...tail] = pureArgs;
|
|
66
|
+
if (this.expectsSpace) {
|
|
67
|
+
this.expectsSpace = false;
|
|
68
|
+
const blanks = new Set(['\n', ' ', '\t']);
|
|
69
|
+
if (this.stringBuilder.length > 0 &&
|
|
70
|
+
!(blanks.has(head[0]) || blanks.has(this.stringBuilder.at(-1).at(-1)))) {
|
|
71
|
+
this.stringBuilder.push(' ');
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
this.stringBuilder.push(head);
|
|
75
|
+
this.stringBuilder.push(...tail);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
this.printWord = (...args) => {
|
|
79
|
+
this.expectsSpace = true;
|
|
80
|
+
this.print(...args);
|
|
81
|
+
this.expectsSpace = true;
|
|
82
|
+
};
|
|
83
|
+
this.printSpaceLeft = (...args) => {
|
|
84
|
+
this.expectsSpace = true;
|
|
85
|
+
this.print(...args);
|
|
86
|
+
};
|
|
87
|
+
this.printWords = (...args) => {
|
|
88
|
+
for (const arg of args) {
|
|
89
|
+
this.printWord(arg);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
// eslint-disable-next-line ts/no-unnecessary-type-assertion
|
|
93
|
+
for (const rule of Object.values(rules)) {
|
|
94
|
+
// Define function implementation
|
|
95
|
+
this[rule.name] =
|
|
96
|
+
((input, context, args) => {
|
|
97
|
+
this.expectsSpace = false;
|
|
98
|
+
this.stringBuilder.length = 0;
|
|
99
|
+
this.origSource = context.origSource;
|
|
100
|
+
this.generatedUntil = context?.offset ?? 0;
|
|
101
|
+
this.setContext(context);
|
|
102
|
+
this.subrule(rule, input, args);
|
|
103
|
+
this.catchup(this.origSource.length);
|
|
104
|
+
return this.stringBuilder.join('');
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
setContext(context) {
|
|
109
|
+
this.__context = context;
|
|
110
|
+
}
|
|
111
|
+
getSafeContext() {
|
|
112
|
+
return this.__context;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
//# sourceMappingURL=dynamicGenerator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dynamicGenerator.js","sourceRoot":"","sources":["dynamicGenerator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAI7C,MAAM,OAAO,gBAAgB;IAQ3B,YAA6B,KAAe;QAAf,UAAK,GAAL,KAAK,CAAU;QAPzB,YAAO,GAAG,IAAI,WAAW,EAAE,CAAC;QACrC,cAAS,GAAwB,SAAS,CAAC;QAC3C,eAAU,GAAG,EAAE,CAAC;QAChB,mBAAc,GAAG,CAAC,CAAC;QAEV,kBAAa,GAAa,EAAE,CAAC;QA+B7B,YAAO,GAA0B,CAAC,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE;YACvE,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAS,MAAM,CAAC,IAAI,CAAC,CAAC;YAC5C,IAAI,CAAC,GAAG,EAAE,CAAC;gBACT,MAAM,IAAI,KAAK,CAAC,QAAQ,MAAM,CAAC,IAAI,YAAY,CAAC,CAAC;YACnD,CAAC;YAED,MAAM,QAAQ,GAAG,GAAS,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC;gBACrC,OAAO,EAAE,IAAI,CAAC,OAAO;gBACrB,KAAK,EAAE,IAAI,CAAC,KAAK;gBACjB,gBAAgB,EAAE,IAAI,CAAC,cAAc;gBACrC,UAAU,EAAE,IAAI,CAAC,SAAS;gBAC1B,WAAW,EAAE,IAAI,CAAC,UAAU;gBAC5B,OAAO,EAAE,IAAI,CAAC,OAAO;gBACrB,UAAU,EAAE,IAAI,CAAC,SAAS;aAC3B,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,cAAc,EAAE,EAAE,GAAG,CAAC,CAAC;YAEpC,IAAI,IAAI,CAAC,OAAO,CAAC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CAAC,CAAC;oBAC3C,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;oBAEzB,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;oBAEhC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;oBAErC,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBACrC,CAAC,CAAC,CAAC;QACP,CAAC;IACH,CAAC;IAEM,UAAU,CAAC,OAAgB;QAChC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC;IAC3B,CAAC;IAES,cAAc;QACtB,OAAiB,IAAI,CAAC,SAAS,CAAC;IAClC,CAAC;CA6FF","sourcesContent":["import { CoreFactory } from '../CoreFactory';\nimport type { GenRuleMap } from './builderTypes';\nimport type { GeneratorRule, RuleDefArg } from './generatorTypes';\n\nexport class DynamicGenerator<Context, Names extends string, RuleDefs extends GenRuleMap<Names>> {\n protected readonly factory = new CoreFactory();\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 {\n return <Context> 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 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, ...tail ] = pureArgs;\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 this.stringBuilder.push(head);\n this.stringBuilder.push(...tail);\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"]}
|