-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcli.js
executable file
·105 lines (99 loc) · 2.71 KB
/
cli.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env node
var os = require('os');
var fs = require('fs');
var util = require('util');
var argv = require('minimist')(process.argv.slice(2), {
default: {
'interactive-message': 'true'
}
});
var Aheui = require('./aheui.js');
if (argv['version']) {
const package = require('./package');
console.log(package.version);
process.exit(0);
}
var left = [];
var filename = argv._[0] + '';
var sourceCode;
try {
sourceCode = fs.readFileSync(filename, {
encoding: 'utf8'
});
}
catch (e) {
console.error('file not found: ' + e.path);
process.exit(1);
}
runCode(sourceCode);
function runCode(sourceCode) {
var machine = new Aheui.Machine(Aheui.codeSpace(sourceCode));
machine.input = interactiveInput;
machine.output = function (value) {
process.stdout.write(value + '');
};
machine.run(process.exit);
}
function interactiveInput(type) {
var limit = 255;
var platform = os.platform();
var input;
// print message
if (argv['interactive-message'] !== 'false') {
switch (type) {
case 'number':
process.stderr.write(' type the number and press enter: ');
break;
case 'character':
process.stderr.write(' type the character and press enter: ');
break;
}
}
if (left.length !== 0) input = left.shift();
// read user input
else {
switch (platform) {
case 'win32':
input = (function () {
var temp = fs.readSync(process.stdin.fd, limit, 0, 'utf8')[0];
return (left = temp.split(/\r?\n/g)).shift();
})();
break;
case 'linux': case 'darwin':
input = (function () {
var fd = fs.openSync('/dev/stdin', 'rs');
var buffer = Buffer.alloc(limit);
fs.readSync(fd, buffer, 0, buffer.length);
fs.closeSync(fd);
return (left = buffer.toString().split(/\r?\n/g)).shift();
})();
break;
default:
throw 'unexpected platform: ' + platform;
break;
}
left = left.filter(function (v) {return v !== ''});
}
// post-processing
var _input = input;
var _left = '';
switch (type) {
case 'number':
input = /^[-+]?\d+/.exec(_input);
if (input) {
_left = _input.substr(input[0].length);
input = input[0] | 0;
} else {
input = 0;
}
break;
case 'character':
input = _input.codePointAt();
_left = _input.substr(String.fromCodePoint(input).length);
break;
}
if (_left) {
left.unshift(_left);
}
return input;
}