What is Operator Precedence Parsing Algorithm in compiler design?

Compiler DesignProgramming LanguagesComputer Programming

Any string of Grammar can be parsed by using stack implementation, as in shift Reduce parsing. But in operator precedence parsing shifting and reducing is done based on Precedence Relation between symbol at the top of stack & current input symbol of the input string to be parsed.

The operator precedence parsing algorithm is as follows −

Input − The precedence relations from some operator precedence grammar and an input string of terminals from that grammar.

Output − There is no output but it can construct a skeletal parse tree as we parse, with one non-terminal labeling all interior nodes and the use of single productions not shown. Alternatively, the sequence of shift-reduce steps can be considered the output.

Method − Let the input string be a1a2 … … . an.$Initially, the stack contains $.

  • Repeat forever
  • If only $ is on the stack and only $ is on the input then accept and break else
  • begin
  • let a be the topmost terminal symbol on the stack and let b be the current input symbols.
  • If a <. b or a =. b then shift b onto the stack /*Shift*/
  • else if a . >b then /*reduce*/
  • repeat pop the stack
  • until the top stack terminal is related by <. to the terminal most recently popped.
  • else call the error-correcting routine end.

Example1 − Construct the Precedence Relation table for the Grammar.

E → E + E|E − E|E ∗ E|E⁄E|E ↑ E|(E)| − E|id

Using Assumptions

OperatorsPrecedenceAssociation
HighestRight Associative
* and /Next HighestLeft Associative
+ and −LowestLeft Associative

Solution

Operator Precedence Relations


+*/id()$
+.>.><.<.<.<.<..>.>
.>.><.<.<.<.<..>.>
*.>.>.>.><.<.<..>.>
/.>.>.>.><.<.<..>.>
.>.>.>.><.<.<..>.>
id.>.>.>.>.>

.>.>
(<.<.<.<.<.<.<.=
).>.>.>.>.>

.>.>
$<.<.<.<.<.<.<.

Example2 − Find out all precedence relations between various operators & symbols in the following Grammar & show them using the precedence table.

E → E + T|T

T → T ∗ F|F

F → (E)|id

Solution


+*()id$
+.>.<<..><..>
*.>.><..><..>
(<.<.<.=.<.
).>.>
.>
.>
id.>.>
.>
.>
$<.<.<.
<.
raja
Updated on 29-Oct-2021 13:07:17

Advertisements