What is Top-Down Parsing with Backtracking in compiler design?

Compiler DesignProgramming LanguagesComputer Programming

In Top-Down Parsing with Backtracking, Parser will attempt multiple rules or production to identify the match for input string by backtracking at every step of derivation. So, if the applied production does not give the input string as needed, or it does not match with the needed string, then it can undo that shift.

Example1 − Consider the Grammar

S → a A d

A → b c | b

Make parse tree for the string a bd. Also, show parse Tree when Backtracking is required when the wrong alternative is chosen.

Solution

The derivation for the string abd will be −

S ⇒ a A d ⇒ abd (Required String)

If bc is substituted in place of non-terminal A then the string obtained will be abcd.

S ⇒ a A d ⇒ abcd (Wrong Alternative)

Figure (a) represents S → aAd

Figure (b) represents an expansion of tree with production A → bc which gives string abcd which does not match with string abd. So, it backtracks & chooses another alternative, i.e., A → b in figure (c) which matches with abd.

Algorithm for Backtracking

Example2 − Write an Algorithm for Top-Down Parsing with Backtracking for the following Grammar.

S → a A d

A → bc| b

Solution

In the following Algorithm, there is a procedure for each Non-terminal S & A. Terminal symbols a, b, c, d in Grammar are input symbols or Look ahead symbols to be read by Parser.

advance( ) − It is a function used to move the input pointer to the next input symbol.

Limitations of Top-Down Parsing with Backtracking

Following are some problems, which occur in Top-Down Parsing with Backtracking.

  • Backtracking − Backtracking looks very simple and easy to implement but choosing a different alternative causes lot of problems which are given below −

    • Undoing semantic actions requires a lot of overhead.

    • Entries made in the symbol table during parsing have to be removed while backtracking.

Due to these reasons, backtracking is not used for practical compilers.

Left Recursion − A grammar is left recursive if it has the production of form.

A → Aα|β

Which causes the parser to enter into an infinite loop.

  • Choosing Right Production − The order in which alternatives are tested can change the language accepted.

  • Difficult to locate error − When failure occurs, it is difficult to know where the error occurred.

raja
Updated on 30-Oct-2021 12:45:01

Advertisements