我是语法和解析领域的新手。
我正在尝试编写一个递归下降解析器来评估这样的字符串:
((3 == 5 AND 4 == 5) OR (6 == 6))
在我开始处理嵌套括号之前,一切对我来说都很好。本质上,我发现我过早地到达目标字符串的末尾。
我认为问题是由于当我遇到像“6”或倒数第二个括号这样的标记时,我评估它然后移动到下一个标记。我会删除前进到下一个令牌的代码,但是我不确定我如何前进。
我的语法,例如,看起来像这样(“=>”符号是我自己对规则“翻译”的符号):
测试:If CompoundSentence Then CompoundSentence | 复合句
CompoundSentence : ( CompoundSentence ) PCSopt |CompoundSentence 连词 |
句子 =>
CompoundSentence = (CompoundSentence) PCSopt | 句子 CSOpt
PCSOpt = Paren连词复合句 PCSOpt| 厄普西隆
CSOpt = 连词 CSOpt| 厄普西隆
Paren连词:And|Or
连词:和|或
句子:主语动词前缀
主题:主题中缀值 | 价值 =>
主题 = 值 SubjectOpt
SubjectOpt = 中缀值 SubjectOpt | 厄普西隆
动词:==|!=|>|<
谓词:谓词中缀值 | 价值 =>
谓词 = 值 PredicateOpt
PredicateOpt = 中缀值 PredicateOpt | 厄普西隆
中缀:+、-、*、/
我的复合句代码如下:
private string CompoundSentence(IEnumerator<Token> ts)
{
// CompoundSentence = ( CompoundSentence ) PCSopt | Sentence CSOpt
string sReturnValue = "";
switch(ts.Current.Category) {
case "OPENPAREN":
{
//Skip past the open parenthesis
ts.MoveNext();
string sCSValue = CompoundSentence(ts);
if(ts.Current.Category != "CLOSEPAREN") {
sReturnValue = "Missing parenthesis at " + ts.Current.OriginalString;
return sError;
}
else {
//Skip past the close parenthesis
ts.MoveNext();
}
sReturnValue = PCSOpt(sCSValue, ts);
break;
}
default:
{
string sSentenceVal = Sentence(ts);
//sSentenceVal is the truth value -- "TRUE" or "FALSE"
//of the initial Sentence component
//CSOpt will use that value, along with the particular conjunction
//and the value of the current token,
//to generate a new truth value.
sReturnValue = CSOpt(sSentenceVal, ts);
break;
}
}
return sReturnValue;
}
正如我所说,我是这个领域的新手,所以我可能不了解一些非常基本的东西。
如果有人能引导我朝着正确的方向前进,我将不胜感激。