A shift-reduce parser uses a parse stack which
(conceptually) contains grammar symbols. During the operation of the parser,
symbols from the input are shifted
onto the stack. If a prefix of the symbols on top of the
stack matches the RHS of a grammar rule which is
the correct rule to use within the current context,
then the parser reduces
the RHS of the rule to its LHS, replacing the RHS symbols on
top of the stack with the nonterminal occurring on the LHS of the rule. This
shift-reduce process continues until the parser terminates, reporting either
success or failure. It terminates with success when the input is legal and is accepted by
the parser. It terminates with failure if an error is detected in the input.
The parser is nothing but a stack automaton which may be in
one of several discrete states.
A state is usually represented simply as an integer. In reality, the parse
stack contains states, rather than grammar symbols. However, since each state
corresponds to a unique grammar symbol, the state stack can be mapped onto the
grammar symbol stack.
Goto
Table
The
goto
table is a table with rows indexed by states and columns indexed
by nonterminal
symbols. When the parser is in state s
immediately after reducing
by rule N, then
the next state to enter is given by goto[s][N].
The
current state of a shift-reduce parser is the state on top of the state stack.
The detailed operation of such a parser is as follows:
1. Initialize the parse stack to contain a
single state s0,
where s0 is
the distinguished initial state of
the parser.
2. Use the state s on
top of the parse stack and the current lookahead t to
consult the action table
entry action[s][t]:
· If the action table entry is shift s' then
push state s'
onto the stack and advance the input so that the lookahead
is set to the next token.
· If the action table entry is reduce r and
rule r has
m symbols
in its RHS, then pop m
symbols off the parse stack. Let s' be
the state now revealed on top of the parse stack and N be
the LHS nonterminal for rule r.
Then consult the goto table and push the state given by goto[s'][N] onto the stack. The lookahead token is
not changed
by this step.
· If the action table entry is accept,
then terminate the parse with success.
· If the action table entry is error,
then signal an error.
3. Repeat step (2) until the parser terminates.
No comments:
Post a Comment