2

I have the following Brainfuck interpreter that is passing a minimal test suite. Except a sizeable problem like printing fibonacci sequence seems to fail (the last test in the suite). The brainfuck fibonacci code that my interpreted fails to execute is from http://esoteric.sange.fi/brainfuck/bf-source/prog/fibonacci.txt. What is wrong with my interpreted? Here is a fiddle: https://jsfiddle.net/rt017kpz/

function brainLuck(code, input) {
  // "Infinite" heap of memory initialized as 0 for bf to store program values
  let data = new Proxy([], {get: (arr, i) => arr[i] ? arr[i] : 0 })
  let ptr = 0;
  let inputPtr = 0;
  let codePtr = 0;
  let output = '';
  let loopStack = []

  const op = {
    '+' : () => {
      if (data[ptr] === 255) { data[ptr] = 0; }
      else { data[ptr]++; }
      codePtr++;
    },
    '-' : () => {
      if (data[ptr] === 0) { data[ptr] = 255; }
      else { data[ptr]--; }
      codePtr++;
    },
    '.' : () => { 
      output += String.fromCharCode(data[ptr]); 
      codePtr++;
    },
    ',' : () => {
      data[ptr] = input.charCodeAt(inputPtr++); 
      codePtr++;
    },
    '>' : () => { 
      ptr++; codePtr++; 
    },
    '<' : () => {
      if (ptr > 0) { ptr--; }
      codePtr++; 
    },
    '[' : () => {
      if (data[ptr] === 0) {
        while(code[codePtr] !== ']') codePtr++;
      } else { 
        loopStack.unshift(codePtr);
      }
      codePtr++ 
    },
    ']' : () => {
      if (data[ptr] === 0) { loopStack.shift(); }
      else { codePtr = loopStack[0] }
      codePtr++
    }
  }

  while(codePtr < code.length) {
    if(op[code[codePtr]]) op[code[codePtr]]()
    else codePtr++
  }
  return output;
}



////////// TESTS //////////////

it('handles `+` and `.` operants', () => {
  expect(
    brainLuck('+++.')
  ).to.equal(
    String.fromCharCode(3)
  )
})

it('handles `-` operant and underflows from 0 to 255', () => {
  expect(
    brainLuck('+++----.')
  ).to.equal(
    String.fromCharCode(255)
  )
})

it('handles `,` the input operand', () => {
  expect(
    brainLuck(',.', 'A')
  ).to.equal(
    'A'
  )
})

it('handles input in conjuction with arithmetic', () => {
  expect(
    brainLuck(',+.', 'A')
  ).to.equal(
    'B'
  )
})

it('handles looping (`[`, `]`) and shift (`<`, `>`) operants', () => {
  expect(
    brainLuck(',>+++[<.>-]', 'A')
  ).to.equal(
    'AAA'
  )
})

it('only parses known symbols', () => {
  expect(
    brainLuck(',nothing>++else+[<.>matters!-]', 'A')
  ).to.equal(
    'AAA'
  )
})

it('handles nested loops', () => {
  expect(
    brainLuck(',>+++[->+++[<<.>>-]<]', 'A')
  ).to.equal(
    'AAAAAAAAA'
  )
})

it('can multiply two numbers', () => {
  expect(
    brainLuck(',>,<[>[->+>+<<]>>[-<<+>>]<<<-]>>.', String.fromCharCode(8,9))
  ).to.equal(
    String.fromCharCode(72)
  )
})

it('can print the fibonacci sequence', () => {
  expect(
    brainLuck('++++>+>>>>++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++<<<<<<[>[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<[>++++++++++[-<-[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<[>>>+<<<-]>>[-]]<<]>>>[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<+>>[-]]<<<<<<<]>>>>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]++++++++++<[->-<]>++++++++++++++++++++++++++++++++++++++++++++++++.[-]<<<<<<<<<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<-[>>.>.<<<[-]]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+>-]>[<+>-]<<<-]')
  ).to.equal(
    '1, 1, 2, 3'
  )
})


mocha.run();
<html>
<head>
  <meta charset="utf-8">
  <title>Mocha Tests</title>
  <link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" />
</head>
<body>
  <div id="mocha"></div>
  <script src="https://cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js"></script>
  <script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
  <script>mocha.setup('bdd')</script>
</body>
</html>
Red Mercury
  • 3,971
  • 1
  • 26
  • 32
  • Have you tried stepping through the code in a debugger to find out what it could be? And *how* does the test fail? Does it "crash"? Give unexpected results? Something else? – Some programmer dude Aug 19 '17 at 18:03
  • Thanks for responding, if you run my code snippet you can see `Error: expected ':, ' to equal '1, 1, 2, 3'`. As for stepping though with a debugger, I have tried but bf code is so heavily obfuscated. I've had no luck so far. Fibonacci bf code is so large. Unfortunately it's the only one I know which fails to execute correctly. – Red Mercury Aug 19 '17 at 18:04
  • Is your `]` implementation correct? I would expect to see something like `if (data[ptr] !== 0) { while(code[codePtr] !== '[') codePtr--;` (I think probably it is ok. You are using an array as a stack.) – Dave Cousineau Aug 19 '17 at 18:14
  • 1
    What about the `<` implementation. Is it correct that you can't go left past zero? Maybe you should be able to go "infinitely" in both directions? – Dave Cousineau Aug 19 '17 at 18:18
  • Thanks for both suggestions @Sahuagin! Yeah I think using an array as a stack is fine. I tried swapping out for loop, same outcome. But curiously, if i remove the non-negative ptr check, I run into an infinite loop. I'm actually not sure if negative data registers are allowed in bf. I assumed not. – Red Mercury Aug 19 '17 at 18:25
  • @Sahuagin The `loopStack` is needed. Consider `[[]]`. Repeating outer loop would loop back to shot: until the inner loops `[` – Red Mercury Aug 19 '17 at 18:41
  • Ok, yes, I think that's the problem then. Your implementation of `[` looks for the first `]` symbol, but the matching one is actually the second one. You need to keep track of other `[` and `]` symbols as you scan, and only match when you're at the same level as the one you started with. – Dave Cousineau Aug 19 '17 at 18:45
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/152346/discussion-between-red-mercury-and-sahuagin). – Red Mercury Aug 19 '17 at 18:48

1 Answers1

3

Your implementation of [ searches for the first ] rather than the matching ], which might be the second, third, fourth, etc. ] symbol. You need to count them as you scan. The following snippet has an implementation of [ that does this, and the fib test now works:

function brainLuck(code, input) {
  // "Infinite" heap of memory initialized as 0 for bf to store program values
  let data = new Proxy([], {get: (arr, i) => arr[i] ? arr[i] : 0 })
  let ptr = 0;
  let inputPtr = 0;
  let codePtr = 0;
  let output = '';
  let loopStack = []

  const op = {
    '+' : () => {
      if (data[ptr] === 255) { data[ptr] = 0; }
      else { data[ptr]++; }
      codePtr++;
    },
    '-' : () => {
      if (data[ptr] === 0) { data[ptr] = 255; }
      else { data[ptr]--; }
      codePtr++;
    },
    '.' : () => { 
      output += String.fromCharCode(data[ptr]); 
      codePtr++;
    },
    ',' : () => {
      data[ptr] = input.charCodeAt(inputPtr++); 
      codePtr++;
    },
    '>' : () => { 
      ptr++; codePtr++; 
    },
    '<' : () => {
      if (ptr > 0) { ptr--; }
      codePtr++; 
    },
    '[' : () => {
      if (data[ptr] === 0) {
        let level = 0;
        while(code[codePtr] !== ']' || level > 1) {
           if (code[codePtr] === '[')
              level += 1;
           if (code[codePtr] === ']')
              level -= 1;
           codePtr++;
        }
      } else { 
        loopStack.unshift(codePtr);
      }
      codePtr++ 
    },
    ']' : () => {
      if (data[ptr] === 0) { loopStack.shift(); }
      else { codePtr = loopStack[0] }
      codePtr++
    }
  }

  while(codePtr < code.length) {
    if(op[code[codePtr]]) op[code[codePtr]]()
    else codePtr++
  }
  return output;
}



////////// TESTS //////////////

it('handles `+` and `.` operants', () => {
  expect(
    brainLuck('+++.')
  ).to.equal(
    String.fromCharCode(3)
  )
})

it('handles `-` operant and underflows from 0 to 255', () => {
  expect(
    brainLuck('+++----.')
  ).to.equal(
    String.fromCharCode(255)
  )
})

it('handles `,` the input operand', () => {
  expect(
    brainLuck(',.', 'A')
  ).to.equal(
    'A'
  )
})

it('handles input in conjuction with arithmetic', () => {
  expect(
    brainLuck(',+.', 'A')
  ).to.equal(
    'B'
  )
})

it('handles looping (`[`, `]`) and shift (`<`, `>`) operants', () => {
  expect(
    brainLuck(',>+++[<.>-]', 'A')
  ).to.equal(
    'AAA'
  )
})

it('only parses known symbols', () => {
  expect(
    brainLuck(',nothing>++else+[<.>matters!-]', 'A')
  ).to.equal(
    'AAA'
  )
})

it('handles nested loops', () => {
  expect(
    brainLuck(',>+++[->+++[<<.>>-]<]', 'A')
  ).to.equal(
    'AAAAAAAAA'
  )
})

it('can multiply two numbers', () => {
  expect(
    brainLuck(',>,<[>[->+>+<<]>>[-<<+>>]<<<-]>>.', String.fromCharCode(8,9))
  ).to.equal(
    String.fromCharCode(72)
  )
})

it('can print the fibonacci sequence', () => {
  expect(
    brainLuck('++++>+>>>>++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++<<<<<<[>[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<[>++++++++++[-<-[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<[>>>+<<<-]>>[-]]<<]>>>[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<+>>[-]]<<<<<<<]>>>>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]++++++++++<[->-<]>++++++++++++++++++++++++++++++++++++++++++++++++.[-]<<<<<<<<<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<-[>>.>.<<<[-]]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+>-]>[<+>-]<<<-]')
  ).to.equal(
    '1, 1, 2, 3'
  )
})


mocha.run();
<html>
<head>
  <meta charset="utf-8">
  <title>Mocha Tests</title>
  <link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" />
</head>
<body>
  <div id="mocha"></div>
  <script src="https://cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js"></script>
  <script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
  <script>mocha.setup('bdd')</script>
</body>
</html>
Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80