grammar-well 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/.eslintrc.cjs +14 -0
  2. package/README.md +288 -0
  3. package/bootstrap.ts +35 -0
  4. package/build/compiler/compiler.d.ts +48 -0
  5. package/build/compiler/compiler.js +227 -0
  6. package/build/compiler/compiler.js.map +1 -0
  7. package/build/compiler/generator.d.ts +23 -0
  8. package/build/compiler/generator.js +213 -0
  9. package/build/compiler/generator.js.map +1 -0
  10. package/build/compiler/import-resolver.d.ts +15 -0
  11. package/build/compiler/import-resolver.js +37 -0
  12. package/build/compiler/import-resolver.js.map +1 -0
  13. package/build/compiler/outputs/javascript.d.ts +3 -0
  14. package/build/compiler/outputs/javascript.js +29 -0
  15. package/build/compiler/outputs/javascript.js.map +1 -0
  16. package/build/compiler/outputs/json.d.ts +2 -0
  17. package/build/compiler/outputs/json.js +8 -0
  18. package/build/compiler/outputs/json.js.map +1 -0
  19. package/build/compiler/outputs/typescript.d.ts +2 -0
  20. package/build/compiler/outputs/typescript.js +108 -0
  21. package/build/compiler/outputs/typescript.js.map +1 -0
  22. package/build/grammars/gwell.d.ts +997 -0
  23. package/build/grammars/gwell.js +537 -0
  24. package/build/grammars/gwell.js.map +1 -0
  25. package/build/grammars/json.d.ts +151 -0
  26. package/build/grammars/json.js +112 -0
  27. package/build/grammars/json.js.map +1 -0
  28. package/build/grammars/number.d.ts +239 -0
  29. package/build/grammars/number.js +115 -0
  30. package/build/grammars/number.js.map +1 -0
  31. package/build/grammars/number.json +1 -0
  32. package/build/grammars/string.d.ts +116 -0
  33. package/build/grammars/string.js +50 -0
  34. package/build/grammars/string.js.map +1 -0
  35. package/build/grammars/string.json +1 -0
  36. package/build/grammars/whitespace.d.ts +51 -0
  37. package/build/grammars/whitespace.js +30 -0
  38. package/build/grammars/whitespace.js.map +1 -0
  39. package/build/grammars/whitespace.json +1 -0
  40. package/build/index.d.ts +4 -0
  41. package/build/index.js +21 -0
  42. package/build/index.js.map +1 -0
  43. package/build/lexers/character-lexer.d.ts +27 -0
  44. package/build/lexers/character-lexer.js +71 -0
  45. package/build/lexers/character-lexer.js.map +1 -0
  46. package/build/lexers/stateful-lexer.d.ts +48 -0
  47. package/build/lexers/stateful-lexer.js +309 -0
  48. package/build/lexers/stateful-lexer.js.map +1 -0
  49. package/build/lexers/token-buffer.d.ts +32 -0
  50. package/build/lexers/token-buffer.js +92 -0
  51. package/build/lexers/token-buffer.js.map +1 -0
  52. package/build/parser/algorithms/cyk.d.ts +16 -0
  53. package/build/parser/algorithms/cyk.js +58 -0
  54. package/build/parser/algorithms/cyk.js.map +1 -0
  55. package/build/parser/algorithms/earley.d.ts +48 -0
  56. package/build/parser/algorithms/earley.js +158 -0
  57. package/build/parser/algorithms/earley.js.map +1 -0
  58. package/build/parser/algorithms/lr.d.ts +10 -0
  59. package/build/parser/algorithms/lr.js +34 -0
  60. package/build/parser/algorithms/lr.js.map +1 -0
  61. package/build/parser/parser.d.ts +26 -0
  62. package/build/parser/parser.js +74 -0
  63. package/build/parser/parser.js.map +1 -0
  64. package/build/typings.d.ts +198 -0
  65. package/build/typings.js +3 -0
  66. package/build/typings.js.map +1 -0
  67. package/build/utility/general.d.ts +46 -0
  68. package/build/utility/general.js +112 -0
  69. package/build/utility/general.js.map +1 -0
  70. package/build/utility/lint.d.ts +2 -0
  71. package/build/utility/lint.js +28 -0
  72. package/build/utility/lint.js.map +1 -0
  73. package/build/utility/lr.d.ts +56 -0
  74. package/build/utility/lr.js +131 -0
  75. package/build/utility/lr.js.map +1 -0
  76. package/build/utility/text-format.d.ts +11 -0
  77. package/build/utility/text-format.js +84 -0
  78. package/build/utility/text-format.js.map +1 -0
  79. package/licenses/LICENSE.txt +165 -0
  80. package/licenses/moo.license +29 -0
  81. package/licenses/nearley.license +21 -0
  82. package/package.json +52 -0
  83. package/src/compiler/compiler.ts +239 -0
  84. package/src/compiler/generator.ts +229 -0
  85. package/src/compiler/import-resolver.ts +36 -0
  86. package/src/compiler/outputs/javascript.ts +27 -0
  87. package/src/compiler/outputs/json.ts +5 -0
  88. package/src/compiler/outputs/typescript.ts +105 -0
  89. package/src/grammars/gwell.gwell +278 -0
  90. package/src/grammars/gwell.js +539 -0
  91. package/src/grammars/gwell.json +1 -0
  92. package/src/grammars/json.gwell +75 -0
  93. package/src/grammars/json.js +121 -0
  94. package/src/grammars/json.json +1 -0
  95. package/src/grammars/number.gwell +20 -0
  96. package/src/grammars/number.js +117 -0
  97. package/src/grammars/number.json +1 -0
  98. package/src/grammars/string.gwell +15 -0
  99. package/src/grammars/string.js +52 -0
  100. package/src/grammars/string.json +1 -0
  101. package/src/grammars/whitespace.gwell +6 -0
  102. package/src/grammars/whitespace.js +32 -0
  103. package/src/grammars/whitespace.json +1 -0
  104. package/src/index.ts +4 -0
  105. package/src/lexers/character-lexer.ts +73 -0
  106. package/src/lexers/stateful-lexer.ts +335 -0
  107. package/src/lexers/token-buffer.ts +102 -0
  108. package/src/parser/algorithms/cyk.ts +74 -0
  109. package/src/parser/algorithms/earley.ts +193 -0
  110. package/src/parser/algorithms/lr.ts +37 -0
  111. package/src/parser/parser.ts +77 -0
  112. package/src/typings.ts +221 -0
  113. package/src/utility/general.ts +120 -0
  114. package/src/utility/lint.ts +26 -0
  115. package/src/utility/lr.ts +153 -0
  116. package/src/utility/text-format.ts +84 -0
  117. package/testing.ts +18 -0
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2014, 2015, 2016, 2017, 2018, 2019 Kartik Chandra, Tim Radvan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "grammar-well",
3
+ "version": "1.1.0",
4
+ "description": "Cross-platform Parser written in TypeScript",
5
+ "main": "build/index.js",
6
+ "scripts": {
7
+ "prebuild": "tsc --build --clean",
8
+ "build": "tsc --build",
9
+ "bootstrap": "ts-node bootstrap.ts",
10
+ "testing": "ts-node testing.ts",
11
+ "benchmark": "node tests/performance/benchmark.js",
12
+ "test": "nyc mocha tests/**/*.spec.ts",
13
+ "profile": "node tests/performance/profile.js"
14
+ },
15
+ "author": "0x6563",
16
+ "license": "LGPL-3.0",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/0x6563/grammar-well.git"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/0x6563/grammar-well/issues"
23
+ },
24
+ "homepage": "https://github.com/0x6563/grammar-well#readme",
25
+ "devDependencies": {
26
+ "@types/chai": "^4.3.4",
27
+ "@types/mocha": "^10.0.1",
28
+ "@types/node": "^18.11.18",
29
+ "@typescript-eslint/eslint-plugin": "^5.49.0",
30
+ "@typescript-eslint/parser": "^5.49.0",
31
+ "babel-cli": "^6.26.0",
32
+ "babel-preset-env": "^1.7.0",
33
+ "benny": "^3.7.1",
34
+ "chai": "^4.3.7",
35
+ "eslint": "^8.33.0",
36
+ "expect": "^29.4.1",
37
+ "mocha": "^10.2.0",
38
+ "nyc": "^15.1.0",
39
+ "ts-node": "^10.9.1",
40
+ "typescript": "^4.9.4",
41
+ "yaml": "^2.2.1"
42
+ },
43
+ "keywords": [
44
+ "parser",
45
+ "parse",
46
+ "generator",
47
+ "compiler",
48
+ "compile",
49
+ "grammar",
50
+ "language"
51
+ ]
52
+ }
@@ -0,0 +1,239 @@
1
+ import { CompileOptions, GrammarBuilderContext, OutputFormat, LanguageDirective, ConfigDirective, GrammarBuilderSymbolRepeat, GrammarBuilderExpression, GeneratorGrammarRule, GrammarDirective, ImportDirective, LexerDirective, GrammarBuilderSymbolSubexpression, GrammarTypeLiteral, GeneratorGrammarSymbol, GrammarBuilderSymbol, GrammarBuilderRule } from "../typings";
2
+
3
+ import { Parser } from "../parser/parser";
4
+ import { FileSystemResolver } from "./import-resolver";
5
+ import Language from '../grammars/gwell';
6
+
7
+ import { ESMOutput, JavascriptOutput } from "./outputs/javascript";
8
+ import { TypescriptFormat } from "./outputs/typescript";
9
+ import { JSONFormatter } from "./outputs/json";
10
+
11
+ import * as number from '../grammars/number.json';
12
+ import * as string from '../grammars/string.json';
13
+ import * as whitespace from '../grammars/whitespace.json';
14
+ import { Generator } from "./generator";
15
+
16
+ const BuiltInRegistry = {
17
+ number,
18
+ string,
19
+ whitespace,
20
+ }
21
+ const OutputFormats = {
22
+ _default: JavascriptOutput,
23
+ object: (grammar, exportName) => ({ grammar, exportName }),
24
+ json: JSONFormatter,
25
+ js: JavascriptOutput,
26
+ javascript: JavascriptOutput,
27
+ module: ESMOutput,
28
+ esmodule: ESMOutput,
29
+ ts: TypescriptFormat,
30
+ typescript: TypescriptFormat
31
+ }
32
+
33
+ export async function Compile(rules: string | LanguageDirective | (LanguageDirective[]), config: CompileOptions = {}) {
34
+ const builder = new GrammarBuilder(config);
35
+ await builder.import(rules as any);
36
+ return builder.export(config.format);
37
+ }
38
+
39
+ export class GrammarBuilder {
40
+ private parser = new Parser(Language());
41
+ private context: GrammarBuilderContext;
42
+
43
+ generator = new Generator();
44
+
45
+ constructor(private config: CompileOptions = {}, context?: GrammarBuilderContext) {
46
+ this.context = context || {
47
+ alreadyCompiled: new Set(),
48
+ resolver: config.resolverInstance ? config.resolverInstance : config.resolver ? new config.resolver(config.basedir) : new FileSystemResolver(config.basedir),
49
+ uuids: {}
50
+ }
51
+ this.generator.state.grammar.uuids = this.context.uuids;
52
+ }
53
+
54
+ export<T extends OutputFormat = '_default'>(format: T, name: string = 'GWLanguage'): ReturnType<typeof OutputFormats[T]> {
55
+ const grammar = this.generator.state;
56
+ const output = format || grammar.config.preprocessor || '_default';
57
+ if (OutputFormats[output]) {
58
+ return OutputFormats[output](this.generator, name);
59
+ }
60
+ throw new Error("No such preprocessor: " + output)
61
+ }
62
+
63
+ async import(source: string): Promise<void>
64
+ async import(directive: LanguageDirective): Promise<void>
65
+ async import(directives: LanguageDirective[]): Promise<void>
66
+ async import(directives: string | LanguageDirective | (LanguageDirective[])): Promise<void> {
67
+ if (typeof directives == 'string') {
68
+ await this.mergeLanguageDefinitionString(directives);
69
+ return;
70
+ }
71
+ directives = Array.isArray(directives) ? directives : [directives];
72
+ for (const directive of directives) {
73
+ if ("head" in directive) {
74
+ this.generator.state.head.push(directive.head.js);
75
+ } else if ("body" in directive) {
76
+ this.generator.state.body.push(directive.body.js);
77
+ } else if ("import" in directive) {
78
+ await this.processImportDirective(directive);
79
+ } else if ("config" in directive) {
80
+ this.processConfigDirective(directive);
81
+ } else if ("grammar" in directive) {
82
+ this.processGrammarDirective(directive);
83
+ } else if ("lexer" in directive) {
84
+ this.processLexerDirective(directive);
85
+ }
86
+ }
87
+ }
88
+
89
+ private async processImportDirective(directive: ImportDirective) {
90
+ if (directive.path) {
91
+ await this.importGrammar(directive.import);
92
+ } else {
93
+ this.importBuiltIn(directive.import);
94
+ }
95
+ }
96
+
97
+ private processConfigDirective(directive: ConfigDirective) {
98
+ Object.assign(this.generator.state.config, directive.config);
99
+ }
100
+
101
+ private processGrammarDirective(directive: GrammarDirective) {
102
+ if (directive.grammar.config) {
103
+ this.generator.state.grammar.start = directive.grammar.config.start || this.generator.state.grammar.start;
104
+ }
105
+
106
+ for (const rule of directive.grammar.rules) {
107
+ this.buildRules(rule.name, rule.expressions, rule);
108
+ this.generator.state.grammar.start = this.generator.state.grammar.start || rule.name;
109
+ }
110
+ }
111
+
112
+ private processLexerDirective(directive: LexerDirective) {
113
+ if (!this.generator.state.lexer) {
114
+ this.generator.state.lexer = {
115
+ start: '',
116
+ states: {}
117
+ };
118
+ }
119
+ this.generator.state.lexer.start = directive.lexer.start || this.generator.state.lexer.start || (directive.lexer.states.length ? directive.lexer.states[0].name : '');
120
+ for (const state of directive.lexer.states) {
121
+ this.generator.addLexerState(state);
122
+ }
123
+ }
124
+
125
+ private importBuiltIn(name: string) {
126
+ name = name.toLowerCase();
127
+ if (!this.context.alreadyCompiled.has(name)) {
128
+ this.context.alreadyCompiled.add(name);
129
+ if (!BuiltInRegistry[name])
130
+ return;
131
+ this.generator.merge(BuiltInRegistry[name].state);
132
+ }
133
+ }
134
+
135
+ private async importGrammar(name) {
136
+ const resolver = this.context.resolver;
137
+ const path = resolver.path(name);
138
+ if (!this.context.alreadyCompiled.has(path)) {
139
+ this.context.alreadyCompiled.add(path);
140
+ await this.mergeLanguageDefinitionString(await resolver.body(path))
141
+ }
142
+ }
143
+
144
+ private async mergeLanguageDefinitionString(body: string) {
145
+ const builder = new GrammarBuilder(this.config, this.context);
146
+ await builder.import(this.parser.run(body).results[0]);
147
+ this.generator.merge(builder.generator.state);
148
+ return;
149
+ }
150
+
151
+ private buildRules(name: string, expressions: GrammarBuilderExpression[], rule?: GrammarBuilderRule) {
152
+ for (const expression of expressions) {
153
+ this.generator.addGrammarRule(this.buildRule(name, expression, rule));
154
+ }
155
+ }
156
+
157
+ private buildRule(name: string, expression: GrammarBuilderExpression, rule?: GrammarBuilderRule): GeneratorGrammarRule {
158
+ const symbols: GeneratorGrammarSymbol[] = [];
159
+ for (let i = 0; i < expression.symbols.length; i++) {
160
+ const symbol = this.buildSymbol(name, expression.symbols[i]);
161
+ if (symbol)
162
+ symbols.push(symbol);
163
+ }
164
+ return { name, symbols, postprocess: expression.postprocess || rule?.postprocess };
165
+ }
166
+
167
+ private buildSymbol(name: string, symbol: GrammarBuilderSymbol): GeneratorGrammarSymbol {
168
+ if ('repeat' in symbol) {
169
+ return this.buildRepeatRules(name, symbol);
170
+ }
171
+ if ('rule' in symbol) {
172
+ return symbol;
173
+ }
174
+ if ('regex' in symbol) {
175
+ return symbol;
176
+ }
177
+ if ('token' in symbol) {
178
+ return symbol;
179
+ }
180
+ if ('literal' in symbol) {
181
+ if (!symbol.literal.length) {
182
+ return null;
183
+ }
184
+ if (symbol.literal.length === 1 || this.generator.state.lexer) {
185
+ return symbol;
186
+ }
187
+ return this.buildCharacterRules(name, symbol);
188
+ }
189
+ if ('subexpression' in symbol) {
190
+ return this.buildSubExpressionRules(name, symbol);
191
+ }
192
+ }
193
+
194
+ private buildCharacterRules(name: string, symbol: GrammarTypeLiteral) {
195
+ const id = this.generator.grammarUUID(name + "$STR");
196
+ this.buildRules(id, [
197
+ {
198
+ symbols: symbol.literal
199
+ .split("")
200
+ .map((literal) => {
201
+ if (symbol.insensitive && literal.toLowerCase() != literal.toUpperCase())
202
+ return { regex: literal, flags: 'i' }
203
+ return { literal }
204
+ }),
205
+ postprocess: { builtin: "join" }
206
+ }
207
+ ]);
208
+ return { rule: id };
209
+ }
210
+
211
+ private buildSubExpressionRules(name: string, symbol: GrammarBuilderSymbolSubexpression) {
212
+ const id = this.generator.grammarUUID(name + "$SUB");
213
+ this.buildRules(id, symbol.subexpression);
214
+ return { rule: id };
215
+ }
216
+
217
+ private buildRepeatRules(name: string, symbol: GrammarBuilderSymbolRepeat) {
218
+ let id: string;
219
+ const expr1: GrammarBuilderExpression = { symbols: [] };
220
+ const expr2: GrammarBuilderExpression = { symbols: [] };
221
+ if (symbol.repeat == '+') {
222
+ id = this.generator.grammarUUID(name + "$RPT1N");
223
+ expr1.symbols = [symbol.expression];
224
+ expr2.symbols = [{ rule: id }, symbol.expression];
225
+ expr2.postprocess = { builtin: "concat" };
226
+ } else if (symbol.repeat == '*') {
227
+ id = this.generator.grammarUUID(name + "$RPT0N");
228
+ expr2.symbols = [{ rule: id }, symbol.expression];
229
+ expr2.postprocess = { builtin: "concat" };
230
+ } else if (symbol.repeat == '?') {
231
+ id = this.generator.grammarUUID(name + "$RPT01");
232
+ expr1.symbols = [symbol.expression];
233
+ expr1.postprocess = { builtin: "first" };
234
+ expr2.postprocess = { builtin: "null" };
235
+ }
236
+ this.buildRules(id, [expr1, expr2]);
237
+ return { rule: id };
238
+ }
239
+ }
@@ -0,0 +1,229 @@
1
+ import { Dictionary, GeneratorState, GeneratorGrammarRule, GeneratorGrammarSymbol, LexerConfig, LexerStateDefinition } from "../typings";
2
+
3
+ const PostProcessors = {
4
+ "join": "({data}) => data.join('')",
5
+ "concat": "({data}) => data[0].concat([data[1]])",
6
+ "null": "() => null",
7
+ "first": "({data}) => data[0]"
8
+ };
9
+
10
+ export class Generator {
11
+
12
+ state: GeneratorState = {
13
+ grammar: {
14
+ start: '',
15
+ rules: {},
16
+ uuids: {}
17
+ },
18
+ lexer: null,
19
+ head: [],
20
+ body: [],
21
+ config: {},
22
+ version: 'unknown',
23
+ }
24
+
25
+ serializeHead() {
26
+ if (this.state.config.noscript)
27
+ return '';
28
+ return this.state.head.join('\n');
29
+ }
30
+
31
+ serializeBody() {
32
+ if (this.state.config.noscript)
33
+ return '';
34
+ return this.state.body.join('\n');
35
+ }
36
+
37
+ serializeLanguage(depth: number = 0) {
38
+ return this.pretty({
39
+ grammar: this.serializeGrammar(depth + 1),
40
+ lexer: this.serializeLexerConfig(depth + 1)
41
+ }, depth);
42
+ }
43
+
44
+ merge(state: GeneratorState) {
45
+ // TODO: Resolve Conflicting Rules and UUIDS
46
+ Object.assign(this.state.grammar.rules, state.grammar.rules);
47
+ this.state.grammar.start = state.grammar.start || this.state.grammar.start;
48
+
49
+ if (state.lexer) {
50
+ if (this.state.lexer) {
51
+ Object.assign(this.state.lexer.states, state.lexer.states);
52
+ } else {
53
+ this.state.lexer = state.lexer;
54
+ }
55
+ this.state.lexer.start = state.lexer.start || this.state.lexer.start;
56
+ }
57
+ this.state.head.push(...state.head);
58
+ this.state.body.push(...state.body);
59
+ Object.assign(this.state.config, state.config);
60
+ }
61
+
62
+ grammarUUID(name: string) {
63
+ this.state.grammar.uuids[name] = (this.state.grammar.uuids[name] || 0) + 1;
64
+ return name + 'x' + this.state.grammar.uuids[name];
65
+ }
66
+
67
+ addGrammarRule(rule: GeneratorGrammarRule) {
68
+ this.state.grammar.rules[rule.name] = this.state.grammar.rules[rule.name] || [];
69
+ this.state.grammar.rules[rule.name].push(rule);
70
+ }
71
+
72
+ addLexerState(state: LexerStateDefinition) {
73
+ this.state.lexer.states[state.name] = this.state.lexer.states[state.name] || { name: state.name, rules: [] }
74
+ const target = this.state.lexer.states[state.name];
75
+ target.default = typeof state.default == 'string' ? state.default : target.default;
76
+ target.unmatched = typeof state.unmatched == 'string' ? state.unmatched : target.unmatched;
77
+ target.rules.push(...state.rules);
78
+ }
79
+
80
+ private serializeGrammar(depth: number = 0) {
81
+ if (!this.state.grammar) {
82
+ return null;
83
+ }
84
+ return this.pretty({
85
+ start: JSON.stringify(this.state.grammar.start),
86
+ rules: this.serializeGrammarRules(depth + 1)
87
+ }, depth);
88
+ }
89
+
90
+ private serializeGrammarRules(depth: number = 0) {
91
+ const map = {};
92
+ for (const rule in this.state.grammar.rules) {
93
+ map[rule] = this.state.grammar.rules[rule].map(v => this.serializeGrammarRule(v))
94
+ }
95
+ return this.pretty(map, depth);
96
+ }
97
+
98
+ private serializeSymbol(s: GeneratorGrammarSymbol) {
99
+ if (typeof s === 'string') {
100
+ return JSON.stringify(s);
101
+ } else if ('rule' in s) {
102
+ return JSON.stringify(s.rule);
103
+ } else if ('regex' in s) {
104
+ return `/${s.regex}/${s.flags || ''}`;
105
+ } else if ('token' in s) {
106
+ return `{ token: ${JSON.stringify(s.token)} }`;
107
+ } else if ('literal' in s) {
108
+ return `{ literal: ${JSON.stringify(s.literal)} }`;
109
+ } else if ('js' in s) {
110
+ return s.js;
111
+ } else {
112
+ return JSON.stringify(s);
113
+ }
114
+ }
115
+
116
+ private serializeGrammarRule(rule: GeneratorGrammarRule) {
117
+ const symbols = [];
118
+ const alias = {};
119
+ for (let i = 0; i < rule.symbols.length; i++) {
120
+ symbols.push(this.serializeSymbol(rule.symbols[i]));
121
+ if (rule.symbols[i].alias) {
122
+ alias[rule.symbols[i].alias] = i;
123
+ }
124
+ }
125
+ return this.pretty({
126
+ name: JSON.stringify(rule.name),
127
+ symbols: this.pretty(symbols, -1),
128
+ postprocess: this.serializePostProcess(rule.postprocess, alias)
129
+ }, -1);
130
+ }
131
+
132
+ private serializePostProcess(postprocess: GeneratorGrammarRule['postprocess'], alias: Dictionary<number>) {
133
+ if (!postprocess)
134
+ return null;
135
+ if ('builtin' in postprocess)
136
+ return PostProcessors[postprocess.builtin];
137
+ if (this.state.config.noscript)
138
+ return;
139
+ if (typeof postprocess == 'string')
140
+ return postprocess;
141
+ if ('js' in postprocess)
142
+ return postprocess.js;
143
+ if ('template' in postprocess)
144
+ return this.templatePostProcess(postprocess.template, alias);
145
+ }
146
+
147
+ private templatePostProcess(templateBody: string, alias: { [key: string]: number }) {
148
+ for (const key in alias) {
149
+ templateBody = templateBody.replace(new RegExp('(?:\\$)' + key + '(?![a-zA-Z\\d\\$_])'), `data[${alias[key]}]`);
150
+ }
151
+ return "({data}) => { return " + templateBody.replace(/\$(\d+)/g, "data[$1]") + "; }";
152
+ }
153
+
154
+ private serializeLexerConfig(depth: number = 0) {
155
+ if (!this.state.lexer)
156
+ return null;
157
+
158
+ if (typeof this.state.lexer === 'string')
159
+ return this.state.lexer;
160
+
161
+ return this.pretty({
162
+ start: JSON.stringify(this.state.lexer.start),
163
+ states: this.serializeLexerConfigStates(depth + 1)
164
+ }, depth);
165
+ }
166
+
167
+ private serializeLexerConfigStates(depth: number) {
168
+ const map = {};
169
+ for (const key in this.state.lexer.states) {
170
+ const state = this.state.lexer.states[key];
171
+ map[state.name] = this.pretty({
172
+ name: JSON.stringify(state.name),
173
+ default: state.default ? JSON.stringify(state.default) : null,
174
+ unmatched: state.unmatched ? JSON.stringify(state.unmatched) : null,
175
+ rules: this.serializeLexerConfigStateRules(state.rules, depth + 2)
176
+ }, depth + 1);
177
+ }
178
+ return this.pretty(map, depth);
179
+ }
180
+
181
+ private serializeLexerConfigStateRules(rules: LexerConfig['states'][0]['rules'], depth: number) {
182
+ const ary = rules.map(rule => {
183
+ if ('import' in rule)
184
+ return this.pretty({ import: JSON.stringify(rule.import) }, -1)
185
+ return this.pretty({
186
+ when: this.serializeSymbol(rule.when as any),
187
+ type: JSON.stringify(rule.type),
188
+ tag: JSON.stringify(rule.tag),
189
+ pop: JSON.stringify(rule.pop),
190
+ set: JSON.stringify(rule.set),
191
+ inset: JSON.stringify(rule.inset),
192
+ goto: JSON.stringify(rule.goto),
193
+ }, -1);
194
+ });
195
+ return this.pretty(ary, depth);
196
+ }
197
+
198
+ private newLine(depth: number) {
199
+ return '\n' + ' '.repeat(depth * 4);
200
+ }
201
+
202
+ private pretty(obj: string[] | { [key: string]: string | (string[]) }, depth = 0) {
203
+ if (Array.isArray(obj)) {
204
+ let r = `[`;
205
+ for (let i = 0; i < obj.length; i++) {
206
+ const value = obj[i];
207
+ r += `${depth >= 0 ? this.newLine(depth + 1) : ' '}${value}${(this.isVal(obj[i + 1]) ? ',' : '')}`;
208
+ }
209
+ r += `${depth >= 0 ? this.newLine(depth) : ' '}]`;
210
+ return r;
211
+ }
212
+
213
+ let r = `{`;
214
+ const keys = Object.keys(obj).filter(v => this.isVal(obj[v]));
215
+ const prefix = depth >= 0 ? this.newLine(depth + 1) : ' ';
216
+ for (let i = 0; i < keys.length; i++) {
217
+ const key = /[a-z_][a-z\d_$]*/i.test(keys[i]) ? keys[i] : keys[i];
218
+ const value = Array.isArray(obj[keys[i]]) ? this.pretty(obj[keys[i]] as string[], depth >= 0 ? depth + 1 : -1) : obj[keys[i]];
219
+ const suffix = (this.isVal(obj[keys[i + 1]]) ? ',' : '');
220
+ r += `${prefix}${key}: ${value}${suffix}`;
221
+ }
222
+ r += `${depth >= 0 ? this.newLine(depth) : ' '}}`;
223
+ return r;
224
+ }
225
+
226
+ private isVal(value) {
227
+ return typeof value !== 'undefined' && value !== null;
228
+ }
229
+ }
@@ -0,0 +1,36 @@
1
+ /// <reference types="typescript/lib/lib.webworker" />
2
+ import { ImportResolver } from "../typings";
3
+ export class FileSystemResolver implements ImportResolver {
4
+ private baseDir: string;
5
+ private readFile: (path: string, type: string) => Promise<string>;
6
+ private resolve: (path: string, ...paths: string[]) => string;
7
+
8
+ constructor(baseDir: string) {
9
+ const { readFile } = require('fs');
10
+ const { resolve, dirname } = require('path');
11
+ const { promisify } = require('util');
12
+ this.readFile = promisify(readFile);
13
+ this.resolve = resolve;
14
+ this.baseDir = baseDir ? dirname(baseDir) : process?.cwd();
15
+ }
16
+
17
+ path(path: string) {
18
+ return this.resolve(this.baseDir, path);
19
+ }
20
+
21
+ body(path: string) {
22
+ return this.readFile(path, 'utf-8');
23
+ }
24
+ }
25
+
26
+ export class BrowserImportResolver implements ImportResolver {
27
+ constructor(private baseURL: string) { }
28
+
29
+ path(path: string) {
30
+ return (new URL(path, this.baseURL)).href;
31
+ }
32
+
33
+ async body(path: string) {
34
+ return (await fetch(path)).text();
35
+ }
36
+ }
@@ -0,0 +1,27 @@
1
+ import { Generator } from "../generator";
2
+
3
+ export function JavascriptOutput(generator: Generator, exportName: string) {
4
+ return `${Generate(generator, exportName)}
5
+
6
+ if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
7
+ module.exports = ${exportName};
8
+ } else {
9
+ window.${exportName} = ${exportName};
10
+ }`;
11
+ }
12
+
13
+ export function ESMOutput(generator: Generator, exportName: string) {
14
+ return `${Generate(generator, exportName)}
15
+
16
+ export default ${exportName};`;
17
+ }
18
+
19
+ function Generate(generator: Generator, exportName: string) {
20
+ return `// Generated automatically by Grammar-Well, version ${generator.state.version}
21
+ // https://github.com/0x6563/grammar-well
22
+ ${generator.serializeHead()}
23
+ function ${exportName}(){
24
+ ${generator.serializeBody()}
25
+ return ${generator.serializeLanguage(1)}
26
+ }`;
27
+ }
@@ -0,0 +1,5 @@
1
+ import { Generator } from "../generator";
2
+
3
+ export function JSONFormatter(generator: Generator, exportName) {
4
+ return JSON.stringify({ state: generator.state, exportName });
5
+ }