UNPKG

2.56 kBJavaScriptView Raw
1/*
2** pegjs-otf -- On-The-Fly Compilation for PEG.js
3** Copyright (c) 2014-2017 Ralf S. Engelschall <rse@engelschall.com>
4**
5** Permission is hereby granted, free of charge, to any person obtaining
6** a copy of this software and associated documentation files (the
7** "Software"), to deal in the Software without restriction, including
8** without limitation the rights to use, copy, modify, merge, publish,
9** distribute, sublicense, and/or sell copies of the Software, and to
10** permit persons to whom the Software is furnished to do so, subject to
11** the following conditions:
12**
13** The above copyright notice and this permission notice shall be included
14** in all copies or substantial portions of the Software.
15**
16** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23*/
24
25/* global module: false */
26/* global require: false */
27
28/* built-in requirements */
29var fs = require("fs");
30var path = require("path");
31
32/* external requirements */
33var pegjs = require("pegjs");
34var sm = require("static-module");
35var through = require("through");
36
37/* Browserify transform */
38module.exports = function (file /*, options */) {
39 /* act on JavaScript files only */
40 if (path.extname(file) !== ".js")
41 return through();
42
43 /* act on all calls to method "generateFromFile" of module "pegjs-otf" */
44 return sm({
45 "pegjs-otf": {
46 "generateFromFile": function (filename, options) {
47 /* read the grammar definition */
48 var source = fs.readFileSync(filename, { encoding: "utf8" });
49
50 /* enfore source code output */
51 options.output = "source";
52
53 /* generate the parser with regular PEG.js API */
54 var parser = pegjs.generate(source, options);
55
56 /* replace the "generateFromFile(...)" call with the generated parser */
57 return "(" + parser + ")";
58 }
59 }
60 }, {
61 vars: {
62 /* allow "__dirname" to be used in "generateFromFile(...)" calls */
63 __dirname: path.dirname(file)
64 }
65 });
66};
67