-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgenerate-railroad.js
More file actions
354 lines (298 loc) · 9.15 KB
/
generate-railroad.js
File metadata and controls
354 lines (298 loc) · 9.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/usr/bin/env node
const fs = require("node:fs");
const { spawnSync } = require("node:child_process");
const path = require("node:path");
// Customization section
const DEFAULT_INPUT_ABNF = "grammar/JSONC.abnf";
const DEFAULT_PROCESSED_ABNF = "grammar/jsonc-processed.abnf";
const DEFAULT_OUTPUT_HTML = "grammar/railroad-diagram.html";
const FORCED_HTML_HEADER = "JSONC GRAMMAR";
// Rules to inline from their %x... definitions as literal ABNF strings.
// Add more rule names here to apply the same transformation.
const INLINE_HEX_RULES = [
"multi-line-comment-start",
"multi-line-comment-end",
"asterisk",
"escape",
"single-line-comment-start",
"quotation-mark",
"decimal-point",
"minus",
"plus",
"zero",
];
// Inline selected rule references as quoted literals in specific target rules.
// Add more mappings here to reuse this transformation pattern.
const INLINE_LITERAL_REFS = [
{
targetRule: "value",
referencedRules: ["false", "true", "null"],
},
];
// Move selected rule definitions after another rule in the processed ABNF.
// Add more entries here to control rule ordering in generated output.
const REPOSITION_RULES_AFTER = [
{
ruleName: "begin-array",
afterRule: "array",
},
{
ruleName: "end-array",
afterRule: "begin-array",
},
{
ruleName: "begin-object",
afterRule: "object",
},
{
ruleName: "end-object",
afterRule: "begin-object",
},
{
ruleName: "name-separator",
afterRule: "member",
},
{
ruleName: "value-separator",
afterRule: "value",
},
{
ruleName: "digit",
afterRule: "unescaped",
},
{
ruleName: "digit1-9",
afterRule: "digit",
},
{
ruleName: "hexdigit",
afterRule: "digit1-9",
},
{
ruleName: "four-hexdigits",
afterRule: "hexdigit",
}
];
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function decodeAbnfHexSequence(value) {
const trimmed = value.trim();
if (!/^%x[0-9A-Fa-f]+(?:\.[0-9A-Fa-f]+)*$/.test(trimmed)) {
throw new Error(`Unsupported ABNF hex sequence: ${value}`);
}
const bytes = trimmed
.slice(2)
.split(".")
.map((part) => parseInt(part, 16));
return String.fromCodePoint(...bytes);
}
function getHexRuleSequence(source, ruleName) {
const escapedRuleName = escapeRegExp(ruleName);
const ruleRegex = new RegExp(
`^\\s*${escapedRuleName}\\s*=\\s*(%x[0-9A-Fa-f]+(?:\\.[0-9A-Fa-f]+)*)\\b.*$`,
"m",
);
const ruleMatch = source.match(ruleRegex);
if (!ruleMatch) {
throw new Error(`Rule ${ruleName} was not found.`);
}
return ruleMatch[1];
}
function getHexRuleLiteral(source, ruleName) {
return decodeAbnfHexSequence(getHexRuleSequence(source, ruleName));
}
function inlineHexRuleAsLiteral(source, ruleName) {
const escapedRuleName = escapeRegExp(ruleName);
const ruleRegex = new RegExp(
`^\\s*${escapedRuleName}\\s*=\\s*(%x[0-9A-Fa-f]+(?:\\.[0-9A-Fa-f]+)*)\\b.*$`,
"m",
);
const ruleMatch = source.match(ruleRegex);
if (!ruleMatch) {
throw new Error(`Rule ${ruleName} was not found.`);
}
const hexSequence = ruleMatch[1];
const literalChars = decodeAbnfHexSequence(hexSequence);
// Keep hex format for characters that cannot be represented safely
// as a single ABNF quoted string literal.
let replacement;
if (literalChars === "\\" || literalChars === '"') {
replacement = hexSequence;
} else {
// For other characters, escape only double quotes (not backslashes)
const escapedLiteralChars = literalChars.replace(/"/g, '\\"');
replacement = `"${escapedLiteralChars}"`;
}
const removeRuleRegex = new RegExp(`^\\s*${escapedRuleName}\\s*=.*(?:\\r?\\n|$)`, "m");
const withoutRule = source.replace(removeRuleRegex, "");
const useRuleRegex = new RegExp(
`(?<![A-Za-z0-9-])${escapedRuleName}(?![A-Za-z0-9-])`,
"g",
);
// Replace only grammar expressions: RHS after '=' or continuation lines.
return withoutRule
.split(/\r?\n/)
.map((line) => {
const eqIndex = line.indexOf("=");
if (eqIndex !== -1) {
const lhs = line.slice(0, eqIndex + 1);
const rhs = line.slice(eqIndex + 1).replace(useRuleRegex, replacement);
return `${lhs}${rhs}`;
}
if (/^\s/.test(line)) {
return line.replace(useRuleRegex, replacement);
}
return line;
})
.join("\n");
}
function inlineLiteralRefsInTargetRule(source, targetRule, referencedRules) {
const escapedTargetRule = escapeRegExp(targetRule);
const targetRuleRegex = new RegExp(`^(\\s*${escapedTargetRule}\\s*=\\s*)(.*)$`, "m");
const match = source.match(targetRuleRegex);
if (!match) {
throw new Error(`Rule ${targetRule} was not found.`);
}
const targetRulePrefix = match[1];
const targetRuleRhs = match[2];
let updatedRhs = targetRuleRhs;
for (const referencedRule of referencedRules) {
const replacementLiteral = getHexRuleSequence(source, referencedRule);
const referencedRuleRegex = new RegExp(
`(?<![A-Za-z0-9-])${escapeRegExp(referencedRule)}(?![A-Za-z0-9-])`,
"g",
);
updatedRhs = updatedRhs.replace(referencedRuleRegex, replacementLiteral);
}
return source.replace(targetRuleRegex, `${targetRulePrefix}${updatedRhs}`);
}
function removeRuleDefinitions(source, ruleNames) {
const removalSet = new Set(ruleNames);
return source
.split(/\r?\n/)
.filter((line) => {
const match = line.match(/^\s*([A-Za-z][A-Za-z0-9-]*)\s*=/);
if (!match) {
return true;
}
return !removalSet.has(match[1]);
})
.join("\n");
}
function findRuleBlock(lines, ruleName) {
const ruleStartRegex = new RegExp(`^\\s*${escapeRegExp(ruleName)}\\s*=`);
const startIndex = lines.findIndex((line) => ruleStartRegex.test(line));
if (startIndex === -1) {
throw new Error(`Rule ${ruleName} was not found.`);
}
let endIndex = startIndex + 1;
while (endIndex < lines.length && /^\s/.test(lines[endIndex])) {
endIndex += 1;
}
return {
startIndex,
endIndex,
blockLines: lines.slice(startIndex, endIndex),
};
}
function repositionRulesAfter(source, reorderings) {
let lines = source.split(/\r?\n/);
for (const { ruleName, afterRule } of reorderings) {
const ruleBlock = findRuleBlock(lines, ruleName);
lines.splice(ruleBlock.startIndex, ruleBlock.endIndex - ruleBlock.startIndex);
const afterRuleBlock = findRuleBlock(lines, afterRule);
lines.splice(afterRuleBlock.endIndex, 0, ...ruleBlock.blockLines);
}
return lines.join("\n");
}
function processAbnfSource(source) {
let processed = source;
for (const ruleName of INLINE_HEX_RULES) {
processed = inlineHexRuleAsLiteral(processed, ruleName);
}
for (const { targetRule, referencedRules } of INLINE_LITERAL_REFS) {
processed = inlineLiteralRefsInTargetRule(processed, targetRule, referencedRules);
processed = removeRuleDefinitions(processed, referencedRules);
}
processed = repositionRulesAfter(processed, REPOSITION_RULES_AFTER);
return processed;
}
function postProcessGeneratedHtml(htmlPath) {
const html = fs.readFileSync(htmlPath, "utf8");
const updated = html.replace(/<h1>[^<]*<\/h1>/, `<h1>${FORCED_HTML_HEADER}</h1>`);
if (updated !== html) {
fs.writeFileSync(htmlPath, updated, "utf8");
}
}
const args = process.argv.slice(2);
const titleIndex = args.indexOf("--title");
let title;
if (titleIndex !== -1) {
if (titleIndex + 1 >= args.length) {
console.error("Missing value for --title");
process.exit(1);
}
title = args[titleIndex + 1];
args.splice(titleIndex, 2);
}
const input = args[0] || DEFAULT_INPUT_ABNF;
const output = args[1] || DEFAULT_OUTPUT_HTML;
const processedAbnf = DEFAULT_PROCESSED_ABNF;
const inputPath = path.resolve(__dirname, input);
const outputPath = path.resolve(__dirname, output);
const processedPath = path.resolve(__dirname, processedAbnf);
let source;
try {
source = fs.readFileSync(inputPath, "utf8");
} catch (error) {
console.error(`Failed to read input ABNF: ${error.message}`);
process.exit(1);
}
let processed;
try {
processed = processAbnfSource(source);
} catch (error) {
console.error(`Failed to process ABNF source: ${error.message}`);
process.exit(1);
}
if (typeof processed !== "string") {
console.error("Failed to process ABNF source: processAbnfSource must return a string.");
process.exit(1);
}
try {
fs.mkdirSync(path.dirname(processedPath), { recursive: true });
fs.writeFileSync(processedPath, processed, "utf8");
} catch (error) {
console.error(`Failed to write processed ABNF: ${error.message}`);
process.exit(1);
}
const cliPath = path.join(
__dirname,
"node_modules",
"railroad-diagram-generator-js",
"bin",
"cli.js",
);
const cliArgs = [cliPath, "generate", processedPath, outputPath];
if (title) {
cliArgs.push("--title", title);
}
const result = spawnSync(process.execPath, cliArgs, {
cwd: __dirname,
stdio: "inherit",
});
if (result.error) {
console.error(`Failed to run railroad generator: ${result.error.message}`);
process.exit(1);
}
if (result.status !== 0) {
process.exit(result.status === null ? 1 : result.status);
}
try {
postProcessGeneratedHtml(outputPath);
} catch (error) {
console.error(`Failed to post-process generated HTML: ${error.message}`);
process.exit(1);
}
process.exit(0);