Implementing Brainfuck loops in an interpreter

前端 未结 5 2274
隐瞒了意图╮
隐瞒了意图╮ 2021-02-20 07:53

I want to build a Brainfuck (Damn that name) interpreter in my freshly created programming language to prove it\'s turing-completeness.

Now, everything is clear so far (

5条回答
  •  既然无缘
    2021-02-20 08:17

    When you reach [, you test the data pointer.

    If it's false, you can scan for the next matched ] character, counting up how many [ you see and making sure you mark them off as you see each ].

    If it's true, you need to keep track of its position so you can jump back to it later. I suggest using a stack. Push the current program position onto the stack, then when you reach ], test the data pointer. If it's true, go to the topmost program position on the stack. If it's false, pop the position off the stack and continue.

    As you nest into inner loops, the stack will cleanly record the context of each loop.

    See stack (wikipedia). This is analogous to how assembly programs deal with function calls.

提交回复
热议问题