How to encode FIRST & FOLLOW sets inside a compiler

安稳与你 提交于 2019-12-24 10:47:50

问题


I am writing a compiler for a compiler design course that I am taking and I am currently at the Syntax Analysis where I need to write a parser.

I need to have the FIRST and FOLLOW sets to handle any errors that may appear in the source text. I have precalculated the FIRST and FOLLOW sets for all of the non-terminals in my grammar but I am having trouble deciding where I should actually encode them inside of my program.

Should I place them in a map where the key is the name of the non-terminal?

Any advice would be helpful

This post may seem a little unclear, I can clarify any points if needed.


回答1:


If you want to keep them, you want to attach them to the nonterminals they represent. You probably also want an inversion, e.g., a map from set members back to the nonterminals of which they are the FIRST or FOLLOW.

Then you error recovery routine can use previous or more likely the "next" input token (that's the one which caused you report an error) to decide what you might insert into the input stream instead.

I don't actually store these. I use a GLR parser, whose parse tables are essentially LALR parse tables, and simply build a recursive algorithm to crawl over the tables to see what tokens might allow the parser to proceed. Indirectly, I'm taking advantage of FIRST and FOLLOW, since those were used to construct the parse tables.

If you are taking a compiler design course, I'm recommend focusing on the post-parsing issues. You can sink tons of time into trying to "patch up" the source in response to an error, and all you'll learn is that a) this is hard, and b) nobody will particularly like the choice you offer them. You can spend energy on syntax repair until you're blue in the face but I'd wait until somebody asked you to do it for a job. In the meantime, for a compiler class, I'd let my compiler simply say, "Syntax error on line N" and abort. Crummy but good enough to let you get on with the more interesting part.



来源:https://stackoverflow.com/questions/9753282/how-to-encode-first-follow-sets-inside-a-compiler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!