Backtracking in a Recursive-Descent Parser for Grammar (S \rightarrow cAd), (A \rightarrow ab \mid ac \mid a) on Input cad
Backtracking in a Recursive-Descent Parser for Grammar (S \rightarrow cAd), (A \rightarrow ab \mid ac \mid a) on Input cad
Recursive-descent attempt order for nonterminal A
- 1Step 1
Using (S \rightarrow cAd), the parser matches terminal
c. The remaining input isadand it must parse (A) starting at the leadinga. - 2Step 2
Parser attempts
ab. It matchesa, then expectsbbut the next input symbol isd(since remaining isad). This alternative fails, so the parser backtracks. - 3Step 3
Parser rewinds to retry the second alternative
ac. It matchesa, then expectscbut the next input symbol is stilld. This fails again, so the parser backtracks. - 4Step 4
Parser rewinds and tries
a. It matchesasuccessfully. Now the parser returns to (S \rightarrow cAd) and matches terminald. - 5Step 5
"All symbols are matched with no further backtracking."
Counting backtracks
- Backtrack after failing
A → ab: 1 - Backtrack after failing
A → ac: 2 A → asucceeds, so no further backtracking inside (A).
✅ Total backtracks on
cad= 2 → choice (i).
Why backtracking happens exactly twice
Because (A) has three alternatives and the input beginning at the (A) position is
afollowed byd, the first two alternatives require a second symbol (bforab,cforac) but encounterd, producing failure and forcing backtracking each time.2
Correct answer (MCQ)
Footnotes
-
Recursive Descent Parser - GeeksforGeeks - Provides an algorithmic description: if a mismatch occurs, backtrack and try another possibility. ↩
-
Recursive descent, LL and predictive parsers - Eli Bendersky - Discusses predictive parsing (no backtracking) via lookahead and why ambiguity causes need for more power/backtracking. ↩
- Backtrack after failing
Choose the correct answer
Pro Tip
When the question asks for number of backtracks, assume the parser tests alternatives in order and counts each failed alternative attempt that triggers a rewind.
Common pitfall
"Do not count terminal mismatches inside a successful alternative as separate backtracks—only count the times the parser actually rewinds and switches to the next production alternative."
Visual summary (alternatives attempted for A)
Backtracking attempts while parsing A on 'ad'
Only alternatives of A are considered after matching 'c' in S → cAd.
Recursive Descent Parsing (backtracking concept)
Knowledge Check
For the grammar (S \rightarrow cAd), (A \rightarrow ab \mid ac \mid a), and input cad, what is the number of backtracks in a backtracking recursive-descent parser?