-
Notifications
You must be signed in to change notification settings - Fork 0
/
repl
executable file
·91 lines (78 loc) · 1.81 KB
/
repl
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
#!/usr/bin/env node
const readline = require('readline');
const chalk = require('chalk');
const toAST = require('./src/to-ast');
const interpret = require('./src/interpret');
const natives = require('./src/natives');
const _ = require('./src/util');
const package = require('./package.json');
const scope = natives;
let stack = [];
const opening = chalk.blue('(');
const closing = chalk.blue(')');
function title() {
console.log(`r${chalk.magenta('\u2630')}stack REPL`);
console.log(`Version ${package.version}\n`);
}
function color(a) {
if(typeof a == 'number') {
return chalk.yellow(a);
}
if(typeof a == 'string') {
return chalk.green(`"${a}"`);
}
if(typeof a == 'boolean') {
return chalk.red(`${a}`);
}
if(typeof a == 'object') {
if(a.type == 'block') {
return block(a);
}
if(a.type == 'symbol') {
return chalk.blue(a.name);
}
return color(a.value);
}
}
function block(block) {
const terms = block.expression.terms;
return [
chalk.white('('),
terms.map(color).join(' '),
chalk.white(')')
].join(' ');
}
function prompt(reader, carry='') {
function onRead(input) {
const code = carry + input;
try {
const ast = toAST(code);
try {
stack = interpret(ast, stack, scope);
console.log(
opening,
stack.map(color).join(' '),
closing
);
} catch(ex) {
console.error(ex);
} finally {
prompt(reader, '');
}
} catch(ex) {
console.log(ex);
return prompt(reader, code);
}
}
if(carry.length == 0) {
reader.question(chalk.magenta('\u2630 '), onRead);
} else {
reader.question(chalk.magenta('.. '), onRead);
}
}
const reader = readline.createInterface({
input: process.stdin,
output: process.stdout
});
title();
prompt(reader);