Need to remove indirect left recursion from CFG
You should focus on trying to only modify productions that aren't "good". A production is "good" if it :


Starts with a terminal,
Is an epsilon production, or
Is in the form A-&gt;B (followed by a series of terminals and non-terminals) and we can partially order the non-terminals so that A&lt;B. We'd also have to do some extra checks if B being nullable. That is, if B is nullable, we'd have to consider all productions in which B occurs and is nulled. For example, suppose we have the grammar:

A -&gt; BAa
B -&gt; b | esp


At first glance, the rule A-&gt;BAa might appear good (because we can assert that A&lt;B), but if B is nulled, we end up with the production A-&gt;Aa which is bad. This is usually not a big problem, but you've got to make sure you cover all your cases. Note that this doesn't apply to your example, but I'd figure I'd be thorough.


For your grammar:


A-&gt;Ba is good since we can assert that A&lt;B.
b is good because this is a terminal.
For similar reasons, all the productions of B and C are also "good", so we shouldn't change them.
For D, there are several problems. Obviously, we cannot assert that D&lt;D, and we also can't assert that D&lt;A or D&lt;C (since we assumed that A&lt;B&lt;C&lt;D in our previous step). However, the productions for A, B, and C are all "good", so we can substitute those in and expose the hidden left recursion (as you've done in your work).


In short, you should only worry about modifying "bad" productions and leaving any "good" ones as they are. It's not always possible to do this, but in general, it'll save you work.