waforth/src/tools/preprocess.js

65 lines
1.4 KiB
JavaScript
Raw Normal View History

2019-11-08 16:55:34 +01:00
#!/usr/bin/env node
const process = require("process");
const fs = require("fs");
2019-11-09 19:49:34 +01:00
const _ = require("lodash");
2019-11-09 20:04:11 +01:00
const program = require("commander");
let file;
program
.arguments("<file>")
.option(
"--enable-bulk-memory",
"use bulk memory operations instead of own implementation"
)
.action(f => {
file = f;
});
program.parse(process.argv);
2019-11-08 16:55:34 +01:00
const lines = fs
.readFileSync(file)
.toString()
.split("\n");
const definitions = {};
2019-11-09 20:04:11 +01:00
let skipLevel = 0;
let skippingDefinition = false;
2019-11-08 16:55:34 +01:00
lines.forEach(line => {
2019-11-09 19:49:34 +01:00
// Constants
2019-11-08 16:55:34 +01:00
Object.keys(definitions).forEach(k => {
line = line.replace(
2019-11-09 19:49:34 +01:00
new RegExp("(\\s)" + _.escapeRegExp(k) + "(\\s|\\))", "g"),
2019-11-08 22:22:52 +01:00
"$1" + definitions[k] + " (; = " + k + " ;)$2"
2019-11-08 16:55:34 +01:00
);
});
2019-11-08 21:53:56 +01:00
const m = line.match(/^;;\s+([!a-zA-Z0-9_]+)\s*:=\s*([^\s]+)/);
2019-11-08 16:55:34 +01:00
if (m) {
definitions[m[1]] = m[2];
}
2019-11-09 19:49:34 +01:00
2019-11-09 20:04:11 +01:00
// Bulk memory operations
if (program.enableBulkMemory) {
line = line
.replace(/\(call \$memcopy/g, "(memory.copy")
.replace(/\(call \$memset/g, "(memory.fill");
if (line.match(/\(func (\$memset|\$memcopy)/)) {
skippingDefinition = true;
skipLevel = 0;
}
}
if (skippingDefinition) {
skipLevel += (line.match(/\(/g) || []).length;
skipLevel -= (line.match(/\)/g) || []).length;
}
// Output line
if (!skippingDefinition) {
console.log(line);
}
if (skippingDefinition && skipLevel <= 0) {
skippingDefinition = false;
}
2019-11-08 16:55:34 +01:00
});