You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.3 KiB
JavaScript

7 years ago
'use strict';
const path = require("path");
function fixDependencyPaths(dependencies) {
/* When generating a parser on runtime, the parser source will be evaluated
* from within the PEG.js source code, which means that relative dependency
* paths will not work. This function patches all relative paths, by
* resolving them to absolute paths relative from this file. */
return Object.keys(dependencies).reduce((obj, key) => {
obj[key] = path.join(__dirname, dependencies[key]);
return obj;
}, {});
}
module.exports = function(body, options = {}) {
let expressionParser, parserOptions;
7 years ago
if (options.tracer != null) {
const pegjs = require("pegjs");
const fs = require("fs");
const path = require("path");
let grammar = fs.readFileSync(path.join(__dirname, "../src/expression.pegjs"), {encoding: "utf8"});
let pegOptions = require("../pegjs-options.js");
if (pegOptions.dependencies != null) {
pegOptions.dependencies = fixDependencyPaths(pegOptions.dependencies);
}
expressionParser = pegjs.generate(grammar, Object.assign({
trace: true,
format: "commonjs"
}, pegOptions));
parserOptions = {
tracer: options.tracer
};
} else {
expressionParser = require("./expression");
parserOptions = {};
}
return expressionParser.parse(body, parserOptions);
}