3

我是语法和解析领域的新手。

我正在尝试编写一个递归下降解析器来评估这样的字符串:

((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;
    }

正如我所说,我是这个领域的新手,所以我可能不了解一些非常基本的东西。

如果有人能引导我朝着正确的方向前进,我将不胜感激。

4

3 回答 3

1

对于表达式,手动编码的递归下降解析器是一件很容易编码的事情。

有关如何编写递归下降解析器的信息,请参阅我的SO 答案。

一旦你有了解析器的结构,就很容易在解析时评估表达式。

于 2012-07-09T23:23:05.887 回答
0

解析要遵循的基本约定是:

  1. 在规则开始时,当前标记应该是规则涵盖的第一个标记。

  2. 规则应该使用它涵盖的所有令牌。

于 2012-07-09T23:59:03.040 回答
0

我认为它非常微妙,但事实证明它非常简单:我的扫描仪没有捕捉到第二个(可能更高)右括号。哎哟。

感谢大家的帮助。

艾拉,我会接受你的回答,因为它提供了关于 RDP 的详细帮助。

于 2012-07-10T00:53:05.027 回答