创建Brainfuck解析器,解决循环运算符的最佳方法是什么?

Gar*_*hby 5 parsing loops brainfuck

我正在创建一个Brainfuck解析器(用BASIC方言)最终创建一个解释器,但我意识到它并不像我最初想的那样直截了当.我的问题是我需要一种方法来准确地解析Brainfuck程序中的匹配循环运算符.这是一个示例程序:

,>,>++++++++[<------<------>>-]
<<[>[>+>+<<-]>>[<<+>>-]<<<-]
>>>++++++[<++++++++>-],<.>.
Run Code Online (Sandbox Code Playgroud)

'['=循环开始

']'=循环结束

我需要记录每个匹配循环运算符的起点和终点,以便我可以根据需要跳转到源.有些循环是单独的,有些是嵌套的.

什么是解析这个的最佳方法?我想也许可以通过源文件创建一个2D数组(或类似的)来记录每个匹配运算符的开始和结束位置,但这看起来像是通过源的"来回".这是最好的方法吗?

更多信息:Brainfuck主页

编辑:非常感谢任何语言的示例代码.

Mik*_*scu 11

您是否考虑使用堆栈数据结构来记录"跳转点"(即指令指针的位置).

所以基本上,每次遇到"["时,你都会将指令指针的当前位置推到这个堆栈上.每当遇到"]"时,都会将指令指针重置为当前位于堆栈顶部的值.循环完成后,将其从堆栈中弹出.

这是一个带有100个内存单元的C++示例.代码递归地处理嵌套循环,虽然它没有被细化,但它应该说明概念.

char cells[100] = {0};   // define 100 memory cells
char* cell = cells;      // set memory pointer to first cell
char* ip = 0;            // define variable used as "instruction pointer"

void interpret(static char* program, int* stack, int sp)
{
    int tmp;
    if(ip == 0)              // if the instruction pointer hasn't been initialized
        ip = program;        //  now would be a good time

    while(*ip)               // this runs for as long as there is valid brainF**k 'code'
    {
        if(*ip == ',')
            *cell = getch();
        else if(*ip == '.')
            putch(*cell);
        else if(*ip == '>')
            cell++;
        else if(*ip == '<')
            cell--;
        else if(*ip == '+')
            *cell = *cell + 1;
        else if(*ip == '-')
            *cell = *cell - 1;
        else if(*ip == '[')
        {           
            stack[sp+1] = ip - program;
            *ip++;
            while(*cell != 0)
            {
                interpret(program, stack, sp + 1);
            }
            tmp = sp + 1;
            while((tmp >= (sp + 1)) || *ip != ']')
            {
                *ip++;
                if(*ip == '[')
                    stack[++tmp] = ip - program;
                else if(*ip == ']')
                    tmp--;
            }           
        }
        else if(*ip == ']')
        {
            ip = program + stack[sp] + 1;
            break;
        }
        *ip++;       // advance instruction
    }
}

int _tmain(int argc, _TCHAR* argv[])
{   
    int stack[100] = {0};  // use a stack of 100 levels, modeled using a simple array
    interpret(",>,>++++++++[<------<------>>-]<<[>[>+>+<<-]>>[<<+>>-]<<<-]>>>++++++[<++++++++>-],<.>.", stack, 0);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编辑 我刚刚重新编写代码,我意识到在while循环中有一个错误,如果指针的值为0,它将"跳过"解析的循环.这是我进行更改的地方:

while((tmp >= (sp + 1)) || *ip != ']')     // the bug was tmp > (sp + 1)
{
ip++;
if(*ip == '[')
    stack[++tmp] = ip - program;
else if(*ip == ']')
    tmp--;
}
Run Code Online (Sandbox Code Playgroud)

下面是相同解析器的实现,但不使用递归:

char cells[100] = {0};
void interpret(static char* program)
{
    int cnt;               // cnt is a counter that is going to be used
                           //     only when parsing 0-loops
    int stack[100] = {0};  // create a stack, 100 levels deep - modeled
                           //     using a simple array - and initialized to 0
    int sp = 0;            // sp is going to be used as a 'stack pointer'
    char* ip = program;    // ip is going to be used as instruction pointer
                           //    and it is initialized at the beginning or program
    char* cell = cells;    // cell is the pointer to the 'current' memory cell
                           //      and as such, it is initialized to the first
                           //      memory cell

    while(*ip)             // as long as ip point to 'valid code' keep going
    {
        if(*ip == ',')
            *cell = getch();
        else if(*ip == '.')
            putch(*cell);
        else if(*ip == '>')
            cell++;
        else if(*ip == '<')
            cell--;
        else if(*ip == '+')
            *cell = *cell + 1;
        else if(*ip == '-')
            *cell = *cell - 1;
        else if(*ip == '[')
        {           
            if(stack[sp] != ip - program)
                stack[++sp] = ip - program;

            *ip++;

            if(*cell != 0)
                continue;
            else
            {                   
                cnt = 1;
                while((cnt > 0) || *ip != ']')
                {
                    *ip++;
                    if(*ip == '[')
                    cnt++;
                    else if(*ip == ']')
                    cnt--;
                }
                sp--;
            }
        }else if(*ip == ']')
        {               
            ip = program + stack[sp];
            continue;
        }
        *ip++;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{   
    // define our program code here..
    char *prg = ",>++++++[<-------->-],[<+>-]<.";

    interpret(prg);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)