-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
105 lines (78 loc) · 2.53 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
93
94
95
96
97
98
99
100
101
102
103
104
105
'use strict';
var fs = require('fs'),
path = require('path'),
peg = require('pegjs'),
importPlugin = require('./lib/compiler-plugin'),
parseImports = require('./lib/parse-imports');
var parsers = {},
importStack = [];
function buildParser(filename, options) {
// if we've already imported this file, don't touch it again
if (parsers[filename]) {
return parsers[filename];
}
var absoluteFilename = path.resolve(filename),
grammar = parseImports(absoluteFilename);
if (importStack.indexOf(absoluteFilename) !== -1) {
throw new peg.GrammarError('Circular dependency on ' + absoluteFilename);
} else {
importStack.push(absoluteFilename);
}
// recursively build the files we discovered
grammar.dependencies.forEach(function(dependency) {
// convert path to absolute
if (dependency.path.charAt(0) === '.') {
var prospectivePath = path.resolve(
path.dirname(filename),
dependency.path);
if (fs.existsSync(path.join(prospectivePath, 'index.peg'))) {
dependency.path = path.join(prospectivePath, 'index.peg');
} else if (fs.existsSync(prospectivePath + '.peg')) {
dependency.path = prospectivePath + '.peg';
} else if (fs.existsSync(prospectivePath)) {
dependency.path = prospectivePath;
}
} else {
dependency.path = require.resolve(dependency.path);
}
var parser;
try {
parser = buildParser(dependency.path, options);
} catch(e) {
if (e instanceof peg.GrammarError) {
throw new peg.GrammarError(dependency.path + ': ' + e.message + '\n');
} else {
throw e;
}
}
});
// call out to PEG and build the parser
var combinedOptions = {};
for (var option in options) {
if (options.hasOwnProperty(option)) {
combinedOptions[option] = options[option];
}
}
if (combinedOptions.plugins) {
combinedOptions.plugins = combinedOptions.plugins.concat(importPlugin);
} else {
combinedOptions.plugins = [importPlugin];
}
combinedOptions.filename = absoluteFilename;
combinedOptions.dependencies = grammar.dependencies;
var newParser;
try {
newParser = peg.buildParser(grammar.text, combinedOptions);
} catch(e) {
if (e instanceof peg.GrammarError) {
throw new peg.GrammarError(absoluteFilename + ': ' + e.message + '\n');
} else {
throw e;
}
}
// pop ourselves off the import stack
importStack.pop();
parsers[absoluteFilename] = newParser;
return newParser;
};
module.exports = { buildParser: buildParser };