How can an LR(0) parser ever leave state 0?

跟風遠走 提交于 2019-12-11 01:42:17

问题


I've read Wikipedia's explanation at least a dozen times, but I'm still confused at how an LR(0) parser ever leaves state 0.

Wikipedia's example, with its explanation, says:

The parser starts out with the stack containing just the initial state ('0'): [0]
The first symbol from the input string that the parser sees is '1'.

... but this doesn't make sense to me, because seeing the input symbol would be performing a lookahead, but an LR(0) parser, by definition, can't perform a lookahead.

When the parser is at state 0, it hasn't shifted yet, so it doesn't have any symbols on its stack.
Given that it's an LR(0) parser, it can't perform a lookahead either.

So how does it use the table to figure out which state to shift or reduce into, from state 0?


回答1:


The symbol shifted is not a lookahead. It's consumed.

LR(0) grammars have to decide to reduce without consulting the next symbol. Once they've decided not to reduce, they've implicitly decided to shift. [1]

The shift action involves reading a symbol, pushing it onto the stack, and consulting the action table to decide which state to transition to.

That's different from LR(k>0) grammars in that an LR(k>0) grammar can use the lookahead symbol to decide between shifting and reducing, while an LR(0) grammar cannot. But both of them get to decide which state to goto after they read the shifted symbol.


[Note 1] ...or to accept, if the shifted symbol is the end-of-input marker, but that's just a special case of a state.



来源:https://stackoverflow.com/questions/13084829/how-can-an-lr0-parser-ever-leave-state-0

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