Prerequisite – Parsing | Set 2 (Bottom Up or Shift Reduce Parsers)
Shift Reduce parser attempts for the construction of parse in a similar manner as done in bottom up parsing i.e. the parse tree is constructed from leaves(bottom) to the root(up). A more general form of shift reduce parser is LR parser.
This parser requires some data structures i.e.
- A input buffer for storing the input string.
- A stack for storing and accessing the production rules.
Basic Operations –
- Shift: This involves moving of symbols from input buffer onto the stack.
- Reduce: If the handle appears on top of the stack then, its reduction by using appropriate production rule is done i.e. RHS of production rule is popped out of stack and LHS of production rule is pushed onto the stack.
- Accept: If only start symbol is present in the stack and the input buffer is empty then, the parsing action is called accept. When accept action is obtained, it is means successful parsing is done.
- Error: This is the situation in which the parser can neither perform shift action nor reduce action and not even accept action.
Example 1 – Consider the grammar
S –> S + S
S –> S * S
S –> id
Perform Shift Reduce parsing for input string “id + id + id”.
Example 2 – Consider the grammar
E –> 2E2
E –> 3E3
E –> 4
Perform Shift Reduce parsing for input string “32423”.
Following is the implementation in C-
//Including Libraries #include<stdio.h> #include<stdlib.h> #include<string.h> //Global Variables int z = 0, i = 0, j = 0, c = 0; // Modify array size to increase // length of string to be parsed char a[16], ac[20], stk[15], act[10]; // This Function will check whether // the stack contain a production rule // which is to be Reduce. // Rules can be E->2E2 , E->3E3 , E->4 void check() { // Coping string to be printed as action strcpy (ac, "REDUCE TO E -> " ); // c=length of input string for (z = 0; z < c; z++) { //checking for producing rule E->4 if (stk[z] == '4' ) { printf ( "%s4" , ac); stk[z] = 'E' ; stk[z + 1] = ' |