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

2019-07-19 01:58发布

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条回答
仙女界的扛把子
2楼-- · 2019-07-19 02:43

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.

查看更多
登录 后发表回答