-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBF2.js
More file actions
297 lines (257 loc) · 11.6 KB
/
Copy pathBF2.js
File metadata and controls
297 lines (257 loc) · 11.6 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
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
class BF2Interpreter {
constructor(calculateTapeLength = false) {
this.code = ""; // BF2 code
this.tape = new Uint8Array(10); // Memory tape, using Uint8Array for better performance
this.pointer = 0; // Points to the current memory cell
this.input = []; // Input to the Brainfuck code
this.inputIndex = 0; // Input index
this.instructionPointer = 0; // To traverse the BF2 code
this.bracketMap = new Map(); // Precomputed loop positions
this.defaultTapeLength = 10; // Default tape length if not provided
this.lengthWarning = false; // To track if length was not defined
this.calculateTapeLength = calculateTapeLength; // To calculate tape length from %...%
this.stopped = false; // Flag to stop the interpreter
this.maxOperations = 1000000000; // Limit to avoid infinite loops
this.operationCount = 0; // Track number of operations
this.maxOutputLength = 10000;
this.lenCounter = 0;
// Output buffer
this.output = "";
this.outputBuffer = new Uint8Array(this.maxOutputLength);
this.outputIndex = 0;
this.bufferTapeOutput = []; // Buffer to store tape output lines
this.isTapeRecorded = false; // Marks whether the tape is to be recorded or not
}
// Function to extract and calculate tape length from %...%
parseTapeLength() {
const firstPercent = this.code.indexOf('%');
const secondPercent = this.code.indexOf('%', firstPercent + 1);
// If no %...% is found or only one %, use default length and set warning
if (firstPercent === -1 || secondPercent === -1) {
this.tape = new Uint8Array(this.defaultTapeLength);
this.lengthWarning = true;
return;
}
// Extract the code between the first and second %
const lengthCode = this.code.slice(firstPercent + 1, secondPercent);
if (!lengthCode.trim()) {
this.tape = new Uint8Array(this.defaultTapeLength);
this.lengthWarning = true;
return;
}
// Run a "mini" interpreter to calculate the tape length
const miniInterpreter = new BF2Interpreter(true);
miniInterpreter.run(lengthCode);
const tapeLength = miniInterpreter.tape[0];
this.tape = new Uint8Array(tapeLength > 0 ? tapeLength : this.defaultTapeLength);
this.lengthWarning = tapeLength <= 0;
// Remove the tape length definition part (only between the first two %) from the main code
this.code = this.code.slice(0, firstPercent) + this.code.slice(secondPercent + 1);
}
// Function to precompute the loop matching for faster execution
preprocessLoops() {
const stack = [];
for (let i = 0; i < this.code.length; i++) {
const command = this.code[i];
if (command === '[') {
stack.push(i);
} else if (command === ']') {
if (stack.length === 0) {
return `Mismatched ']' at position ${i}`;
}
const start = stack.pop();
this.bracketMap.set(start, i); // Map the start and end of the loop
this.bracketMap.set(i, start); // Map the end to the start
}
}
if (stack.length > 0) {
return `Mismatched '[' at position ${stack.pop()}`;
}
}
// Efficient tape output to minimize redundant operations
printTape(operation) {
if (!this.calculateTapeLength) {
const lineNumber = this.bufferTapeOutput.length + 1;
const paddedLineNumber = lineNumber.toString().padStart(3, ' ');
const spaceSeparatedTape = Array.from(this.tape)
.map((value, index) => (index === this.pointer ? `\u0332${value}` : `${value}`)) // Underline the pointer value
.join(', ');
// If the operation is ',', add the input value instead of a comma
let operationValue = operation;
if (operation === ',' && this.input.length > 0) {
const inputValue = this.input[this.inputIndex % this.input.length];
operationValue = `${inputValue}`;
// Adjust the spaces after operationValue based on the length of the input value
const extraSpacesToRemove = Math.min(operationValue.length - 1, 2); // Max 2 spaces to remove
const baseSpacing = ' '; // Default 5 spaces between the operation and the tape
const adjustedSpacing = baseSpacing.slice(0, baseSpacing.length - extraSpacesToRemove);
this.bufferTapeOutput.push(
` ${paddedLineNumber}-> ${operationValue}${adjustedSpacing}[${spaceSeparatedTape}]`
);
} else {
// Add "=> (output)" if the operation is '.'
const outputSuffix =
operation === '.' ? ` => ${this.getReadableOutput(this.tape[this.pointer])}` : '';
this.bufferTapeOutput.push(
` ${paddedLineNumber}-> ${operation} [${spaceSeparatedTape}]${outputSuffix}`
);
}
}
}
// Helper function to convert output into readable string with escape sequences
getReadableOutput(charCode) {
const char = String.fromCharCode(charCode);
switch (char) {
case '\n': return '\\n';
case '\t': return '\\t';
case '\r': return '\\r';
case '\b': return '\\b';
case '\f': return '\\f';
default:
return /[ -~]/.test(char) ? char : `\\x${charCode.toString(16).padStart(2, '0')}`;
}
}
// Function to stop execution
stopCode() {
this.stopped = true;
this.output += "\nExecution stopped by user.\n";
this.output += String.fromCharCode.apply(null, this.outputBuffer.subarray(0, this.outputIndex));
this.lenCounter > 0 && (this.output += `...(${this.lenCounter} more characters)`);
this.operationCount > this.maxOperations && (this.output += `\n\nExecution stopped: Max operations limit reached (${this.maxOperations}).\n`);
return { result: this.output, operationCount: this.operationCount, tape: this.bufferTapeOutput};
}
// Function to run the Brainfuck code asynchronously
async run(incomingCode, recordTape) {
this.isTapeRecorded = recordTape;
recordTape && (this.maxOperations = 100000);
this.bufferTapeOutput = []; // Reset buffer
const match = incomingCode.match(/\((.*?)\)$/);
if (match) {
const inputStrings = match[1].split(' ');
this.input = [];
for (let val of inputStrings) {
const num = Number(val);
if (isNaN(num)) {
this.output += `Error: Invalid input '${val}'. Only numeric inputs are allowed.\n`;
return { result: this.output, operationCount: this.operationCount, tape: this.bufferTapeOutput };
}
this.input.push(num);
}
// Remove the input part (including the parentheses) from the code
incomingCode = incomingCode.slice(0, match.index).trim();
} else {
this.input = []; // No input provided
}
if (this.code.includes(',') && this.input.length === 0) {
this.output += "Error: Input expected, but none provided.\n";
return { result: this.output, operationCount: this.operationCount, tape: this.bufferTapeOutput };
}
this.code = incomingCode.replace(/[\s\n]+/g, ''); // Remove whitespaces and newlines
// Parse tape length before running the main code
if (!this.calculateTapeLength) {
this.parseTapeLength();
} else {
this.tape = new Uint8Array(this.defaultTapeLength); // Fall back to default if invalid
}
// If tape length is not defined, throw warning
this.lengthWarning && (this.output += "Warning: Tape length not defined. Using default length of 10.\n\n");
this.output += "--- Output: \n";
const loopError = this.preprocessLoops(); // Precompute loop positions
if (loopError) {
this.output += loopError;
return { result: this.output, operationCount: this.operationCount, tape: this.bufferTapeOutput};
}
while (this.instructionPointer < this.code.length && !this.stopped && this.operationCount <= this.maxOperations) {
this.operationCount++;
this.isTapeRecorded && this.printTape(this.instructionPointer === 0 ? ' ' : this.code[this.instructionPointer - 1]);
const error = this.executeCommand(this.code.charCodeAt(this.instructionPointer));
if (error) {
this.output += error;
break;
}
this.instructionPointer++;
}
// Convert output buffer to string
this.isTapeRecorded && this.printTape(this.code[this.instructionPointer - 1]);
this.output += String.fromCharCode.apply(null, this.outputBuffer.subarray(0, this.outputIndex));
this.lenCounter > 0 && (this.output += `...(${this.lenCounter} more characters)`);
this.operationCount > this.maxOperations && (this.output += `\n\nExecution stopped: Max operations limit reached (${this.maxOperations}).\n`);
// Return the output and operation count
return {
result: this.output,
operationCount: this.operationCount,
tape: this.bufferTapeOutput
};
}
// Function to execute the commands based on ASCII values
executeCommand(commandCode) {
switch (commandCode) {
case 62: // >
case 60: // <
case 43: // +
case 45: // -
if (!this.isTapeRecorded) {
// Consecutive operations handling with loop unrolling
let consecutiveCount = 1;
while (this.code.charCodeAt(this.instructionPointer + consecutiveCount) === commandCode) { // Count consecutive operations
consecutiveCount++;
this.operationCount++;
}
switch (commandCode) { // Perform the operation
case 62: // >
this.pointer += consecutiveCount;
if (this.pointer >= this.tape.length) return `Pointer moved out of bounds (right) at command ${this.instructionPointer}.\n`;
break;
case 60: // <
this.pointer -= consecutiveCount;
if (this.pointer < 0) return `Pointer moved out of bounds (left) at command ${this.instructionPointer}.\n`;
break;
case 43: // +
this.tape[this.pointer] = (this.tape[this.pointer] + consecutiveCount) & 255;
break;
case 45: // -
this.tape[this.pointer] = (this.tape[this.pointer] - consecutiveCount) & 255;
break;
}
this.instructionPointer += consecutiveCount - 1;
} else {
// diabled loop unrolling for when tape is recorded
switch (commandCode) {
case 62: // >
if (++this.pointer >= this.tape.length) return `Pointer moved out of bounds (right) at command ${this.instructionPointer}.\n`;
break;
case 60: // <
if (--this.pointer < 0) return `Pointer moved out of bounds (left) at command ${this.instructionPointer}.\n`;
break;
case 43: // +
this.tape[this.pointer] = (this.tape[this.pointer] + 1) & 255;
break;
case 45: // -
this.tape[this.pointer] = (this.tape[this.pointer] - 1) & 255;
break;
}
}
break;
case 46: // .
if (this.outputIndex < this.maxOutputLength) {
this.outputBuffer[this.outputIndex++] = this.tape[this.pointer];
} else {
this.lenCounter++;
}
break;
case 44: // ,
if (this.input.length > 0) {
const inputValue = this.input[this.inputIndex % this.input.length];
this.tape[this.pointer] = (this.tape[this.pointer] + inputValue) & 255;
this.inputIndex++;
}
break;
case 91: // [
if (this.tape[this.pointer] === 0) this.instructionPointer = this.bracketMap.get(this.instructionPointer);
break;
case 93: // ]
if (this.tape[this.pointer] !== 0) this.instructionPointer = this.bracketMap.get(this.instructionPointer) - 1;
break;
}
}
}