Skip to content
Permalink
Browse files

Refactor slightly so parser uses a flyweight pattern

  • Loading branch information...
ircmaxell committed Dec 23, 2012
1 parent 2739346 commit 7d0058bb968bd752b1f8818a08c27705127d8f2f
Showing with 18 additions and 28 deletions.
  1. +18 −28 lib/BrainFuck/Language.php
@@ -21,32 +21,24 @@ public function run($program, array $input = array()) {
}
protected function parse(array $program) {
// Use a flyweight here
$stdOps = array(
'+' => new Op\Plus,
'-' => new Op\Minus,
'.' => new Op\Output,
',' => new Op\Input,
'>' => new Op\MoveRight,
'<' => new Op\MoveLeft,
);
$ops = array();
$programPos = 0;
while(isset($program[$programPos])) {
switch ($program[$programPos]) {
case '+':
$ops[] = new Op\Plus;
break;
case '-':
$ops[] = new Op\Minus;
break;
case '.':
$ops[] = new Op\Output;
break;
case ',':
$ops[] = new Op\Input;
break;
case '>':
$ops[] = new Op\MoveRight;
break;
case '<':
$ops[] = new Op\MoveLeft;
break;
case '[':
$buffer = $this->parseLoop($program, $programPos);
$ops[] = new Op\Loop($this->parse($buffer));
break;
while (isset($program[$programPos])) {
$op = $program[$programPos];
if (isset($stdOps[$op])) {
$ops[] = $stdOps[$op];
} elseif ($op == '[') {
$buffer = $this->parseLoop($program, $programPos);
$ops[] = new Op\Loop($this->parse($buffer));
}
$programPos++;
}
@@ -57,17 +49,15 @@ protected function parseLoop(array $program, &$startPos) {
$openCount = 1;
$pos = $startPos;
while (isset($program[++$pos])) {
switch($program[$pos]) {
switch ($program[$pos]) {
case '[':
$openCount++;
break;
case ']':
$openCount--;
if ($openCount == 0) {
$buffer = array_slice(
$program,
$startPos + 1,
$pos - $startPos - 1
$program, $startPos + 1, $pos - $startPos - 1
);
$startPos = $pos;
return $buffer;

0 comments on commit 7d0058b

Please sign in to comment.
You can’t perform that action at this time.