Aer Interpreter Source
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
2.3 KiB

  1. class Brainfuck {
  2. private string $code;
  3. private int $code_pointer;
  4. private int[] $cells;
  5. private int $pointer;
  6. private string $input;
  7. private int $input_pointer;
  8. private int[] $buffer;
  9. private string $output;
  10. public void __construct(string $code, string $input = NULL) {
  11. $this->code = $code;
  12. $this->input = $input;
  13. }
  14. public void run() {
  15. while ($this->code_pointer < strlen($this->code)) {
  16. $this->interpret($this->code[$this->code_pointer]);
  17. $this->code_pointer++;
  18. }
  19. print($this->output);
  20. }
  21. private void interpret(string $command) {
  22. if(!array_key_exists($this->pointer, $this->cells)) {
  23. $this->cells[$this->pointer] = 0;
  24. }
  25. switch ($command) {
  26. case '>' :
  27. $this->pointer++;
  28. break;
  29. case '<' :
  30. $this->pointer--;
  31. break;
  32. case '+' :
  33. $this->cells[$this->pointer]++;
  34. if($this->cells[$this->pointer] > 255) {
  35. $this->cells[$this->pointer] = 0;
  36. }
  37. break;
  38. case '-' :
  39. $this->cells[$this->pointer]--;
  40. if($this->cells[$this->pointer] < 0) {
  41. $this->cells[$this->pointer] = 255;
  42. }
  43. break;
  44. case '.' :
  45. $this->output += chr($this->cells[$this->pointer]);
  46. break;
  47. case ',' :
  48. $this->cells[$this->pointer] = $this->input[$this->input_pointer] ? ord($this->input[$this->input_pointer]) : 0;
  49. $this->input_pointer++;
  50. break;
  51. case '[' :
  52. if($this->cells[$this->pointer] == 0) {
  53. int $delta = 1;
  54. while($delta && $this->code_pointer++ < strlen($this->code)) {
  55. switch ($this->code[$this->code_pointer]) {
  56. case '[' :
  57. $delta++;
  58. break;
  59. case ']' :
  60. $delta--;
  61. break;
  62. }
  63. }
  64. } else {
  65. $this->buffer[] = $this->code_pointer;
  66. }
  67. break;
  68. case ']' :
  69. $this->code_pointer = array_pop($this->buffer) - 1;
  70. }
  71. }
  72. }
  73. class Program {
  74. public void main() {
  75. object $bf;
  76. string $code;
  77. resource $dir;
  78. string $file;
  79. string[] $files;
  80. string $input;
  81. $dir = opendir('tests/data/brainfuck');
  82. while($file = readdir($dir)) {
  83. if($file == '.' || $file == '..') {
  84. continue;
  85. }
  86. $files[] = $file;
  87. }
  88. sort($files);
  89. unset($file);
  90. for(int $n = 0; $n < sizeof($files); $n++) {
  91. print('Executing "' + $files[$n] + '"' + "\n");
  92. $code = file_get_contents('tests/data/brainfuck/' + $files[$n]);
  93. $bf = new Brainfuck($code, $input);
  94. $bf->run();
  95. print("\n");
  96. }
  97. closedir($dir);
  98. }
  99. }