// This is the parent stack node for a syntax stack in
// an LR parser. Children of this node will store
// semantic information.
class StackNode
{
public :
StackNode(int s){state = s;}
void setState(int s){state = s;}
int seeState(){return state;} // See the state at the top of the stack
private:
int state;
};
void ActionArray::Execute(ostream &out,const CodeArray &code,
const LookUpTable &l, String vals[],Array &sourceCode)
{
int state = 0;
IdTable ids;
ThreeAddressCode codeGen;
StateStack stack;
//Insert the 0 state into the stack.
stack.insert(new StackNode(0));
Lexical lex(sourceCode);
int sym = lex.getNextSymbol();
do
{
//Trace the parse
out<<" In state > "<<state<<endl;
out<<" Symbol "<<vals[sym].c_str()<<" Number "<<sym<<endl;
out<<" action "; act(state,sym)->print(out,code,vals,l)<<endl;
//Do the parse action
state = act(state,sym)->action(stack,*this,lex,ids,codeGen);
sym = lex.getSym();//check to see if symbol updated
}while (state >=0);
}
int ReduceAction::action(StateStack &s,const ActionArray &a,
Lexical &lex,IdTable &ids,ThreeAddressCode &code)const
{
Array<StackNode*> temps(5,1); // grab the stuff coming out
if (popNum >0)
for (int i = 0;i<popNum;i++)
temps[i] = s.remove(); //deleted as needed in generate
else
temps[0] = s.getTop();// must know conditional goto storage
// temps[0] always comes back with an appropriate type of StackNode *
int top = s.seeTop();
//This processes the goto part of the reduce. Get the state.
int newState = a.act(top,pushSym)->action(s,a,lex,ids,code);
temps[0]->setState(newState);// now we have the state - set it
s.insert(temps[0]);// push the new node
return newState;
}
1 S -> if E then S 2 S -> if E then S else S 3 S -> a 4 S -> b 5 E -> x 6 E -> y
0 Z -> S 1 S -> E = E 2 S -> i 3 E -> E + i 4 E -> i
0 Z -> S 1 S -> E = E 2 S -> i 3 E -> E + i 4 E -> i
Compute the First of expression "=E$", First(=E$) = { = } and first of "+i=", First(+i=)={I}
because [E->@E+i; { = } ] is in the state, add [E->@E+i; { + }][E -> @E+i;{+}] [E ->@i {+}] from [E->@E+i; {= }] and [E -> @i {= }]
merged to give[E -> @E+i; {=,+}], [E -> @i; {=,+}]}
Inputs |
||||||
|---|---|---|---|---|---|---|
| State | i | = | + | $ | S | E |
| 3 | r4 | r4 | r2 | |||