-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.js
56 lines (55 loc) · 1.71 KB
/
test.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
const parser = require('./parser')
const ast = { type: 'Program', body: '', sourceType: 'script' }
let consoleInput = []
let jsOut = []
const escodegen = require('escodegen')
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
// repl
rl.on('line', (input) => {
if (input === 'exit') rl.close()
if (input !== 'exit') {
consoleInput += input + '\n'
} else {
var solution = parser(consoleInput.trim())
ast.body = solution
try {
var js = escodegen.generate(ast)
} catch (e) {
console.log(`You probably put some brackets in the wrong places, or..
This program doesn't have the particular functionality`)
}
js = js.replace(/\n/g, '').replace(/;/g, '\n').trim()
js = js.split('\n')
while (js.length > 0) {
if (js[0].charAt(0) === ' ') {
jsOut[jsOut.length - 1] += js.shift()
continue
}
jsOut.push(js.shift())
}
writeStream(jsOut.join('\n'), ast)
}
})
// writes input into out.js file adding appropriate lines
// writes ast into ast.txt
function writeStream (input, ast) {
var fs = require('fs')
fs.writeFile('ast.txt', JSON.stringify(ast, null, 2), function (err) {
if (err) return console.log(`Error in Execution\n `, err)
})
var stream = fs.createWriteStream('out.js')
stream.once('open', function (fd) {
input = input.toString().split('\n')
for (let statement in input) {
let firstWord = input[statement].split(' ')
firstWord = firstWord[0]
if (firstWord === 'const' || firstWord.length === 0) stream.write(input[statement] + '\n')
else stream.write('console.log(' + input[statement] + ')' + '\n')
}
stream.end()
})
}