请看下面的语法:
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());
}
}