-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (55 loc) Β· 2.32 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
// Requires for parsing
const escodegen = require("escodegen");
var parser = require("./emojilang");
module.exports = {
add(a,b) { return a+b }
}
// TODO: macro functions into emoji
var parse = exports.parse = function (source, verbose = false) { // Returns AST
var ast = null; // Abstract syntax tree representation of source code
try { // Parse source code to AST
ast = parser.parse(source);
} catch (exception) {
console.log("Parse Error: " + exception.message); // TODO: what do I return if there is an error?
}
if (verbose) {
console.log(ast); //TODO: find a better library for printing AST
}
return ast;
}
var generate = exports.generate = function (ast, verbose = false) {
// TODO: validate AST (and throw error if invalid?)
var code = escodegen.generate(ast); // Generate ECMAScript code from AST
// TODO: other processing functions
if (verbose) {
console.log(code);
}
return code
}
var exec = exports.exec = function (code, verbose = false) {
// TODO: check for code (and throw error if invalid?)
var timeStarted = process.hrtime.bigint();
try { // Try to run the generated code
eval(code); // Evaluage code from string
} catch (exception) {
console.log("Parse Error: " + exception.message); // TODO: what now?
}
var timeToExec = parseFloat(process.hrtime.bigint() - timeStarted); // Calculate time taken to execute
if (verbose) {
console.log("Executed emojilang script in: " + (timeToExec / 1000000).toFixed(3) + " ms"); // Logs time in ms to 3 decimal places
}
// TODO: add a return value (or a callback)
}
var run = exports.run = function (source, verbose = false) { // Parses, generates, and runs the code in one function
exec(generate(parse(source, verbose), verbose), verbose); // Parses the emojillang script, generates JS, executes it, passing the verbose param to each func
// TODO: add a return value (or a callback)
}
function test () { // Run if not called as a module
const fs = require("fs");
var example = fs.readFileSync("test.js", "utf8");
//var example = "π£πβππβππ\nβοΈπβοΈππconsoleπ¬logπ\"test\"πππ\n";
run(example, true);
}
if (require.main === module) { // Check if run directly from Node
test();
}