我的brainfuck解析器代码有什么问题?

时间:2012-10-08 04:57:52

标签: java parsing brainfuck esoteric-languages

我正在尝试用Java编写一个可以读取,编译和运行brainfuck源文件(.bf)的程序。我已经让它与维基百科的Hello World示例一起工作得很好,但它打破了ROT13示例(声称它在实际匹配时达到了无与伦比的]

实际的解析器代码全部写在一个.JAVA文件中,但它的核心(实际的brainfuck解析器和运行代码)在下面的方法doNow(char)中。以下是变量:cells是要运行的字符数组(char[]); pointer是Java解决方法,指向数组中的地址(short); PC是程序计数器(int),loopStack是一堆地址,对应[ s(基本上是short[])。这些不是问题,因为它们在Hello World测试中工作得很好。接受输入的方法会自动过滤掉多余的字符,我确认它可以从调试检查中完美地工作。

为什么这个解析器不能运行ROT 13代码?

代码


我的解析器,用Java编写

  /** The array of data */
  private byte[] cells = new byte[Short.MAX_VALUE];
  /** The pointer that is manipulated by the user or program */
  private short pointer = 0;
  /** The program counter, to run compiled programs */
  private int PC = 0;
  /** The compiled commands */
  private ArrayPP<Character> commandBuffer = new ArrayPP<>();
  /** The stack of locations of loop brackets ({@code [}) in the command buffer */
  private ArrayPP<Short> loopStack = new ArrayPP<>();//ArrayPP is my proprietary augmented array object, which also functions as a perfectly working stack.

  public int doNow(char command) throws IOException
  {
    PC++;
    switch (command)
    {
      case '>':
        return ++pointer;
      case '<':
        return --pointer;
      case '+':
        return ++cells[pointer];
      case '-':
        return --cells[pointer];
      case '.':
        System.out.print((char)cells[pointer]);
        return 0;
      case ',':
        return cells[pointer] = (byte)System.in.read();
      case '[':
        if (cells[pointer] == 0)//If we're ready to skip this conditional
        {
          int oldPC = PC;
          try
          {
            while (getCompiledCommand(PC) != ']')//Find the matching ]
              PC++;
            PC++;//Now that we're at the ], skip over it to the next command
          }
          catch (ArrayIndexOutOfBoundsException e)
          {
            throw new NullPointerException("Unmatched '[' at " + oldPC);//If we try to reference a command outside the buffer
          }
        }
        else//if we want to enter this conditional
          loopStack.push(PC - 1);//Add the location of this conditional to the list of conditionals which we are in
        return PC;
      case ']':
        try
        {
          return PC = loopStack.pop();//Move us to the matching [ and remove it from the list of conditionals we're in
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
          throw new NullPointerException("Unmatched ] at " + PC);//If the loop stack is empty
        }
      default:
        throw new AssertionError(command + " is not a valid command.");
    }
  }
  public char getCompiledCommand(int commandIndex)
  {
    return commandBuffer.get(commandIndex);//Look into the buffer of precompiled commands and fetch the one at the given index
  }

Hello World示例(效果很好)

+++++ +++++             initialize counter (cell #0) to 10
[                       use loop to set the next four cells to 70/100/30/10
    > +++++ ++              add  7 to cell #1
    > +++++ +++++           add 10 to cell #2 
    > +++                   add  3 to cell #3
    > +                     add  1 to cell #4
    <<<< -                  decrement counter (cell #0)
]                   
> ++ .                  print 'H'
> + .                   print 'e'
+++++ ++ .              print 'l'
.                       print 'l'
+++ .                   print 'o'
> ++ .                  print ' '
<< +++++ +++++ +++++ .  print 'W'
> .                     print 'o'
+++ .                   print 'r'
----- - .               print 'l'
----- --- .             print 'd'
> + .                   print '!'
> .                     print '\n'

ROT 13示例(我的测试控制台输入为M。在几次循环迭代后中断命令54)

-,+[                         Read first character and start outer character reading loop
    -[                       Skip forward if character is 0
        >>++++[>++++++++<-]  Set up divisor (32) for division loop
                               (MEMORY LAYOUT: dividend copy remainder divisor quotient zero zero)
        <+<-[                Set up dividend (x minus 1) and enter division loop
            >+>+>-[>>>]      Increase copy and remainder / reduce divisor / Normal case: skip forward
            <[[>+<-]>>+>]    Special case: move remainder back to divisor and increase quotient
            <<<<<-           Decrement dividend
        ]                    End division loop
    ]>>>[-]+                 End skip loop; zero former divisor and reuse space for a flag
    >--[-[<->+++[-]]]<[         Zero that flag unless quotient was 2 or 3; zero quotient; check flag
        ++++++++++++<[       If flag then set up divisor (13) for second division loop
                               (MEMORY LAYOUT: zero copy dividend divisor remainder quotient zero zero)
            >-[>+>>]         Reduce divisor; Normal case: increase remainder
            >[+[<+>-]>+>>]   Special case: increase remainder / move it back to divisor / increase quotient
            <<<<<-           Decrease dividend
        ]                    End division loop
        >>[<+>-]             Add remainder back to divisor to get a useful 13
        >[                   Skip forward if quotient was 0
            -[               Decrement quotient and skip forward if quotient was 1
                -<<[-]>>     Zero quotient and divisor if quotient was 2
            ]<<[<<->>-]>>    Zero divisor and subtract 13 from copy if quotient was 1
        ]<<[<<+>>-]          Zero divisor and add 13 to copy if quotient was 0
    ]                        End outer skip loop (jump to here if ((character minus 1)/32) was not 2 or 3)
    <[-]                     Clear remainder from first division if second division was skipped
    <.[-]                    Output ROT13ed character from copy and clear it
    <-,+                     Read next character
]                            End character reading loop

说清楚,这是它破裂的地方:

            >[+[<+>-]>+>>]   Special case: increase remainder / move it back to divisor / increase quotient
                         ^

2 个答案:

答案 0 :(得分:5)

你应该在'['case分支中跟踪'[]'嵌套:现在,[+++[----]+]中第一个'['的匹配是第一个']',这是不好的。< / p>

答案 1 :(得分:4)

问题


问题似乎在于这一行:

            while (getCompiledCommand(PC) != ']')//Find the matching ]

这在Hello World程序中工作正常,因为它没有嵌套循环。但是,对于嵌套循环,我们遇到的问题是它遇到第一个遇到的],这并不总是匹配的]

修复


一种可能的解决方法是在while循环之前引入变量,比如loopCount,并在每次遇到[时递增它,然后在遇到]时递减它。 loopCount大于0.例如:

        int loopCount = 0;
        while ((command = getCompiledCommand(PC)) != ']' && loopCount == 0)//Find the matching ]. We can save the return in command because we're done using it.
        {
          if (command == '[')//If we run into a nested loop
            loopCount++;
          else if (command == ']')//If we run into the end of a nested loop
            loopCount--;

          PC++;
        }