-
Notifications
You must be signed in to change notification settings - Fork 65
/
index.js
92 lines (78 loc) · 2.61 KB
/
index.js
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
"use strict";
const generateBytecode = require("./passes/generate-bytecode");
const generateJS = require("./passes/generate-js");
const removeProxyRules = require("./passes/remove-proxy-rules");
const reportDuplicateLabels = require("./passes/report-duplicate-labels");
const reportDuplicateRules = require("./passes/report-duplicate-rules");
const reportInfiniteRecursion = require("./passes/report-infinite-recursion");
const reportInfiniteRepetition = require("./passes/report-infinite-repetition");
const reportUndefinedRules = require("./passes/report-undefined-rules");
const reportIncorrectPlucking = require("./passes/report-incorrect-plucking");
const visitor = require("./visitor");
function processOptions(options, defaults) {
const processedOptions = {};
Object.keys(options).forEach(name => {
processedOptions[name] = options[name];
});
Object.keys(defaults).forEach(name => {
if (!Object.prototype.hasOwnProperty.call(processedOptions, name)) {
processedOptions[name] = defaults[name];
}
});
return processedOptions;
}
const compiler = {
// AST node visitor builder. Useful mainly for plugins which manipulate the
// AST.
visitor,
// Compiler passes.
//
// Each pass is a function that is passed the AST. It can perform checks on it
// or modify it as needed. If the pass encounters a semantic error, it throws
// |peg.GrammarError|.
passes: {
check: {
reportUndefinedRules,
reportDuplicateRules,
reportDuplicateLabels,
reportInfiniteRecursion,
reportInfiniteRepetition,
reportIncorrectPlucking
},
transform: {
removeProxyRules
},
generate: {
generateBytecode,
generateJS
}
},
// Generates a parser from a specified grammar AST. Throws |peg.GrammarError|
// if the AST contains a semantic error. Note that not all errors are detected
// during the generation and some may protrude to the generated parser and
// cause its malfunction.
compile(ast, passes, options) {
options = options !== undefined ? options : {};
options = processOptions(options, {
allowedStartRules: [ast.rules[0].name],
cache: false,
dependencies: {},
exportVar: null,
format: "bare",
output: "parser",
trace: false
});
Object.keys(passes).forEach(stage => {
passes[stage].forEach(p => { p(ast, options); });
});
switch (options.output) {
case "parser":
return eval(ast.code);
case "source":
return ast.code;
default:
throw new Error("Invalid output format: " + options.output + ".");
}
}
};
module.exports = compiler;