-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtree_builder.js
More file actions
90 lines (68 loc) · 2.78 KB
/
tree_builder.js
File metadata and controls
90 lines (68 loc) · 2.78 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// The tree we get from the PEG parser describes the program but is more of a "meta-tree", where not everything is yet in order. This parses that output and produces a more traditional AST of the final program, which can then be turned easily into code.
const fs = require('fs');
const { registerTask } = require('grunt');
INPUT_FILE = './sample_code/99bottles.json';
// BUILDERS
// make sure functions and loops all have the same structure
const make_func = (name, params) => {
return {name: name, params: params, body: []};
}
const make_for_loop = (name, start, end, step) => {
return {name: name, start: start, end: end, step: step};
}
const make_while_loop = (name, condition) => {
return {name: name, condition: condition};
}
const func_list = {}; // holds all functions
func_list["main"] = (make_func("main", null, "")); // add main
const build_function = (inv) => {
let func = make_func(
inv.requests[0].id, // name
inv.requests[0].params.map(n => n.name) // params
);
// add commands to function
for(let i = 1; i < inv.requests.length; i++) { // skip first request
func.body.push(build_command(inv.requests[i])[0]); // get first request, the cmd itself
}
func_list[inv.requests[0].id] = func;
}
const build_command = (req, id = null) => {
if (req.id === "<prev id>" && id) {
req.id = id;
}
cmd = req;
// are we adding to a function or returning result?
if (req.loc) {
cmd = null; // we will not return if we're adding it to a particular place
}
return [cmd, id];
}
fs.readFile(INPUT_FILE, 'utf8', (err, data) => {
source = "";
function_list = [];
if (err) {
console.log(`Error reading file from disk: ${err}`);
} else {
// parse JSON string to JSON object
const c = JSON.parse(data);
c.invocations.forEach(inv => {
// top-level items; all following requests in this invocation will fall under this first request
if (['function','check'].includes(inv.requests[0].type)) {
func_list.push(build_function(inv));
} else { // the individual requests under an invocation
let id = null;
inv.requests.forEach(r => {
const [cmd, id] = build_command(r, id);
});
}
});
// // add all the functions to the source code
// let final_source = ""; // we're going to put the functions in first
// function_list.forEach(func => final_source += func.func + "}\n");
// final_source += source; // now add all the "main flow"
// console.log(source);
// fs.writeFile("sample_code/99bottles.js", final_source, function (err) {
// if (err) return console.log(err);
// });
}
});