forked from gkucmierz/brainfuck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrainfuck.js
181 lines (163 loc) · 5.2 KB
/
brainfuck.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
let orders = ',.[]<>+-'.split('');
let regex = {
clean: new RegExp('[^' + escapeRegExp(orders.join('')) + ']', 'g'),
value: /[\+\-]+/g,
pointer: /[\<\>]+/g,
instruction: /[0-9]*./g,
zero: /\[(\-|\+)\]/g
};
let config = {
memorySize: 30000,
bits: 8, // 8, 16, 32
maxInstructions: 0, // limit execution to number of instructions, omit if 0
allowSpecialChars: false, //Allow the use of special character codes for decimal, hex, octal, and binary
};
function getInstruction(count, orderLess, orderMore) {
return ({
'1': (count > 1) ? count + orderMore : orderMore,
'0': '',
'-1': (count < -1) ? (-count) + orderLess : orderLess
})[Math.sign(count)];
}
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function cloneObj(obj) {
return Object.keys(obj).reduce((res, key) => (res[key] = obj[key], res), {});
}
function extendObj(obj, ext) {
return Object.keys(ext || {}).reduce((res, key) => (res[key] = ext[key], res), obj);
}
module.exports.config = (userConfig) => {
if (typeof userConfig === 'undefined') {
return cloneObj(config);
}
extendObj(config, userConfig);
};
module.exports.compile = (bfSource, userConfig) => {
let actualConfig = extendObj(cloneObj(config), userConfig);
let cleanedSource = (bfSource + '').replace(regex.clean, '');
let optimized = cleanedSource
// optimze cell manipulating instructions
// for example: '+++--' => '+'
// '+++++' => '5+'
.replace(regex.value, (m) => {
let map = { '+': 1, '-': -1 };
let n = m.split('').reduce((acc, b) => acc + map[b], 0);
return getInstruction(n, '-', '+');
})
// optimze pointer manipulating instructions
// for example: '>>><<' => '>'
// '>>>>>' => '5>'
.replace(regex.pointer, (m) => {
let map = { '>': 1, '<': -1 };
let n = m.split('').reduce((acc, b) => acc + map[b], 0);
return getInstruction(n, '<', '>');
})
// add (z)ero instruction => it makes reseting cell much faster
.replace(regex.zero, 'z');
let ordersMap = { // m,p,o,i,l
',': () => 'm[p]=i();',
'.': () => 'o(m[p]);',
'[': () => 'while(m[p]){',
']': () => '}',
'<': (count) => 'p-=' + count + ';while(p<0)p+=l;',
'>': (count) => 'p+=' + count + ';while(p>=l)p-=l;',
'+': (count) => 'm[p]+=' + count + ';',
'-': (count) => 'm[p]-=' + count + ';',
// optimizations:
'z': () => 'm[p]=0;' // [-] => quick reset memory cell
};
let createOrder = (order, count) => {
// if there is a instruction limit, add prefix check-instruction to every instruction
let prefix = actualConfig.maxInstructions > 0 ? 'if(!--c)return;' : '';
return [prefix, ordersMap[order](count)].join('');
};
let definitions = {
// count
c: (config) => config.maxInstructions > 0 ? 'let c=' + config.maxInstructions + ';' : '',
// length
l: (config) => ['let l=', config.memorySize, ';'].join(''),
// memory
m: (config) => {
const constr = { '8': 'Uint8Array', '16': 'Uint16Array', '32': 'Uint32Array' };
return ['let m=new ', constr[config.bits] || constr[8], '(l);'].join('');
},
// pointer
p: () => 'let p=0;',
// out
o: () => 'let o=output||(()=>0);',
// in
i: () => 'let i=input||(()=>0);'
};
let bases = [
{
match: /^((x[\da-fA-F]*)|(u[\da-fA-F]{4}))/,
parse: /[\da-fA-F]*$/,
base: 16,
// \x7e == \x7E == \u007e == 126
},
{
match: /^o[0-7]*/,
parse: /[0-7]*$/,
base: 8,
// \o176 == 126
},
{
match: /^b[01]*/,
parse: /[01]*$/,
base: 2,
// \b1111110 == 126
},
{
match: /^\d*/,
parse: /\d*$/,
base: 10,
// \126 == 126
},
]
// create variables definitions
let code = Object.keys(definitions).map(key => definitions[key](actualConfig));
// create rest code
(optimized.match(regex.instruction) || []).map((instruction) => {
let count = +instruction.slice(0, -1) || 1;
let order = instruction.slice(-1);
code.push(createOrder(order, count));
});
let compiled = new Function(['input', 'output'], code.join(''));
return {
run: (input, output) => {
let inp, out;
let res = [];
if (typeof input === 'string') {
input = input.split('');
inp = () => {
let ch = input.shift();
if (actualConfig.allowSpecialChars && ch === `\\`) {
const joined_input = input.join('');
const res =
bases.find(({ match }) => match.test(joined_input))
if (!res) return `\\`.charCodeAt(0);
const match = joined_input.match(res.match)[0];
const value = parseInt(match.match(res.parse)[0], res.base);
input.splice(0, match.length);
return value;
} else return ch ? ch.charCodeAt(0) : 0;
};
} else if (typeof input === 'function') {
inp = input;
}
if (typeof output !== 'function') {
output = () => 0;
}
out = (num) => {
let ch = String.fromCharCode(num);
output(num, ch);
res.push(ch);
};
compiled(inp, out);
return res.join('');
},
toString: () => compiled.toString()
};
};