简体   繁体   English

自上而下的解析与递归语法

[英]Top-Down Parsing with recursive grammar

I have an assignment in school which tells us to create a Top-Down Parser in Java which follows this grammar: 我在学校里有一个作业,告诉我们按照以下语法在Java中创建一个自上而下的解析器:

    assign = id , '=' , expr , ';' ;
    expr = term , [ ( ’+’ | ’-’ ) , expr ] ;
    term = factor , [ ( ’*’ | ’/’) , term] ;
    factor = int | ’(’ , expr , ’)’ ;

I think I have understood the basics concepts of parsing, such as "if we have an id, check if the next token is a '=' and the next is an expr, and if the next after that is a ';'". 我想我已经理解了解析的基本概念,例如“如果我们有一个id,请检查下一个标记是否为'=',下一个标记是否为expr,以及之后的下一个标记是否为';'”。 Correct? 正确?

Now, if I want to check if the incoming input is an expression: 现在,如果我想检查输入的输入是否为表达式:

I check the tokens to see if a term is there, then if a "+ token" OR "- token" is there, and finally if an "expr" is there. 我检查标记以查看是否有术语,然后是否有“ +标记”或“-标记”,最后是否有“ expr”。 But, if I check if there's an "expr" there, it's going to loop, and eventually check again if there's an "expr", and again, and again. 但是,如果我检查是否存在“ expr”,它将循环播放,并最终一次又一次地检查是否存在“ expr”。

I don't see how I can get that too work? 我看不出我该怎么做? Can someone help me? 有人能帮我吗?

Kind regards, 亲切的问候,

OP seems worried that if his code for the expr rule calls the parsing rule for expr, it will get caught in an infinite loop. OP似乎担心,如果他的expr规则代码调用expr的解析规则,它将陷入无限循环。

He need not worry! 他不用担心!

It takes a bit of thought, but what actually happens when that call C1 is made, is that the called expr rules tests for a term . 这需要一些思考,但是当调用C1时实际发生的是,被调用的expr规则测试一个term If that is the last term in the set of summands that comprise the expr, there will be no following plus/minus and the C1 call will terminate and return to the parent parsing routine, which will then be complete. 如果那是组成expr的求和集合中的最后一项,则将没有跟随的正/负,并且C1调用将终止并返回到父解析例程,然后该例程将完成。 No loop. 没有循环。

If it is not the last term, the term will get parsed, plus/minus will be seen, and the C1 instance will make another call C2 back to expr. 如果不是最后一项,则将对该词项进行解析,将看到加号/减号,并且C1实例将再次调用C2返回expr。 This recursion acts like one loop iteration, and gets treated as we have described. 这种递归的行为就像一个循环的迭代,并按照我们的描述进行处理。

Should work just fine. 应该工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM