【问题标题】:Recursive Descent Parser and Nested Parentheses递归下降解析器和嵌套括号
【发布时间】:2012-07-09 23:04:31
【问题描述】:

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

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

((3 == 5 AND 4 == 5) OR (6 == 6))

在我开始处理嵌套括号之前,一切对我来说都很好。从本质上讲,我发现我过早地到达目标字符串的末尾。

我认为问题在于当我遇到像“6”或倒数第二个括号这样的标记时,我对其进行评估,然后移至下一个标记。我会删除前进到下一个令牌的代码,但是我不确定我如何前进。

我的语法看起来是这样的(“=>”符号是我自己对规则“翻译”的符号):

测试:如果 CompoundSentence Then CompoundSentence |复合句

CompoundSentence : ( CompoundSentence ) PCSopt |CompoundSentence 连词 |

句子 =>

CompoundSentence = (CompoundSentence) PCSopt |句子 CSOpt

PCSOpt = ParenConjunction CompoundSentence PCSOpt|厄普西隆

CSOpt = 连词 CSOpt|厄普西隆

ParenConjunction: And|Or

连词:与|或

句子:主语动词前缀

主题:主题中缀值 |价值 =>

主题 = 价值主题选择

SubjectOpt = 中缀值 SubjectOpt |厄普西隆

动词:==|!=|>|

谓词:谓词中缀值 |价值 =>

Predicate= 值 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;
    }

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

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

【问题讨论】:

    标签: parsing grammar recursive-descent


    【解决方案1】:

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

    见我的SO answer for how to write recursive descent parsers.

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

    【讨论】:

      【解决方案2】:

      解析的基本约定是:

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

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

      【讨论】:

        【解决方案3】:

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

        感谢大家的帮助。

        Ira,我会接受您对 RDP 提供的详细帮助的回答。

        【讨论】:

          猜你喜欢
          • 2015-08-07
          • 1970-01-01
          • 2012-05-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多