简体   繁体   中英

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:

    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 ';'". 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. 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.

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.

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 . 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. 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. This recursion acts like one loop iteration, and gets treated as we have described.

Should work just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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