This repository was archived by the owner on Oct 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuild.js
69 lines (60 loc) · 1.87 KB
/
build.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
const esbuild = require("esbuild");
const PurescriptPlugin = require("esbuild-plugin-purescript");
const path = require("path");
const fs = require("fs");
const util = require("util");
const nearley = require("nearley");
const compile = require("nearley/lib/compile");
const generate = require("nearley/lib/generate");
const nearleyGrammar = require("nearley/lib/nearley-language-bootstrapped");
const readFile = (fileName) => util.promisify(fs.readFile)(fileName, "utf8");
function compileGrammar(sourceCode) {
// Parse the grammar source into an AST
const grammarParser = new nearley.Parser(nearleyGrammar);
grammarParser.feed(sourceCode);
const grammarAst = grammarParser.results[0]; // TODO check for errors
// Compile the AST into a set of rules
const grammarInfoObject = compile(grammarAst, {});
// Generate JavaScript code from the rules
const grammarJs = generate(grammarInfoObject, "grammar");
return grammarJs;
}
const NearleyPlugin = () => ({
name: "nearley",
setup(build) {
const namespace = "nearley";
const fileFilter = /\.ne$/;
build.onResolve({ filter: fileFilter }, (args) => ({
path: path.join(args.resolveDir, args.path),
namespace,
pluginData: { resolveDir: args.resolveDir },
}));
build.onLoad({ filter: /.*/, namespace }, async (args) => {
try {
return {
contents: compileGrammar(await readFile(args.path)),
resolveDir: args.pluginData.resolveDir,
};
} catch (e) {
console.log(e.token);
return {
errors: [
{
text: e.message,
},
],
};
}
});
},
});
esbuild
.build({
entryPoints: ["src/index.js"],
bundle: true,
outdir: "dist",
plugins: [PurescriptPlugin(), NearleyPlugin()],
sourcemap: "inline",
platform: "node",
})
.catch((_e) => process.exit(1));