解析这个语法从上到下树

时间:2014-02-08 13:54:47

标签: c++ parsing compiler-construction

请看下面的语法:

S=>AB
A=>aA | epsilon
B=>bB | b

此语法将生成 ab aaaab aaabbbbbbbb 等等......

我想为一个Recursive Descent解析器编写一个解析器,其中一个字符为lookahead。这是代码:

void ParseS()
{
    if(lookahead=="a")
    {
        GetNext();
        ParseA();

        if(lookahead=="b")
        {
            GetNext();  
            ParseB();
        }
        else
        {
            Error("expected 'b' at " + (index+1).ToString());
        }
    }
    else
    {
        Error("expected 'a' at " + (index + 1).ToString());
    }
}
void ParseA()
{
    if (lookahead == "a")
    {

        ParseA();
    }
    else {  }


}
void ParseB()
{
    if (lookahead == "b")
    {
        GetNext();
        ParseB();
    }
    else
    {
        Error("expected 'b' at " + (index + 1).ToString());
    }
}

错误在哪里?

从评论更新代码,效果很好:

    void ParseS()
    {
        if(lookahead=="a")
        {

            ParseA();

            if(lookahead=="b")
            {

                ParseB();
            }
            else
            {
                Error("expected 'b' at " + (index+1).ToString());
            }
        }
        else
        {
            Error("expected 'a' at " + (index + 1).ToString());
        }
    }
    void ParseA()
    {

        if (lookahead == "a")
        {
            GetNext();
            ParseA();
        }
        else {  }


    }
    void ParseB()
    {

        if (lookahead == "b")
        {
            GetNext();
            ParseB();
        }
        else if (lookahead != "$")
        {
            Error("expected 'b' at " + (index + 1).ToString());
        }
    }

0 个答案:

没有答案