Skip to content

Instantly share code, notes, and snippets.

@PifyZ
Last active August 29, 2015 14:05
Show Gist options
  • Save PifyZ/a2503a93a13e88fe1f5a to your computer and use it in GitHub Desktop.
Save PifyZ/a2503a93a13e88fe1f5a to your computer and use it in GitHub Desktop.
Interpréteur Brainfuck en Haxe
package;
class Brainfuck {
public static function main() {
var args = Sys.args();
// On test si un fichier a été spécifié en argument
if (args.length != 1) {
Sys.println('Utilisation : ${Sys.executablePath()} file.bf');
Sys.exit(1);
}
var code = "";
// On essaye de lire ce fichier et affiche une erreur s'il y a un souci de lecture
try {
code = sys.io.File.getContent(args[0]);
} catch (e:String) {
Sys.println('Fichier "${args[0]}" inexistant.');
Sys.exit(2);
}
// Tous les calculs sympathiques
var sp = 0;
var ptr = 0;
var stack = [ for (i in 0 ... 1000) 0 ];
while (sp < code.length) {
switch (code.charAt(sp)) {
case ">": ptr++;
case "<": ptr--;
case "+": stack[ptr]++;
case "-": stack[ptr]--;
case ".": Sys.print(String.fromCharCode(stack[ptr]));
case ",": stack[ptr] = Sys.stdin().readByte();
case "[":
if (stack[ptr] == 0) {
var depth = 0;
var tmp_sp = sp + 1;
while (true) {
if (code.charAt(tmp_sp) == "[")
depth++;
if (code.charAt(tmp_sp) == "]") {
if (depth == 0) {
sp = tmp_sp;
break;
} else {
depth--;
}
}
tmp_sp++;
}
}
case "]":
if (stack[ptr] != 0) {
var depth = 0;
var tmp_sp = sp - 1;
while (true) {
if (code.charAt(tmp_sp) == "]")
depth++;
if (code.charAt(tmp_sp) == "[") {
if (depth == 0) {
sp = tmp_sp;
break;
} else {
depth--;
}
}
tmp_sp--;
}
}
}
sp++;
}
// En temps normal
// Sys.exit(0);
// Pour les tests
Sys.stdin().readLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment