The grammar is like below:
bexpr -> bexpr or bterm | bterm
bterm -> bterm and bfactor | bfactor
bfactor -> not bfactor | ( bexpr ) | true | false
and I have already removed left recursion
bexpr -> bterm bexpr'
bexpr' -> or bterm bexpr' | ε
bterm -> bfactor bterm'
bterm' -> and bfactor bterm' | ε
bfactor -> not bfactor | (bexpr) | true | false
I've calculated the first sets
first(bexpr) = first(bterm) = first(bfactor) = [not, (, true, false]
first(bexpr') = [or, ε]
first(bterm') = [and, ε]
I thought the follow sets of bterm and bfactor are
follow(bterm)=first(bexpr')\epsilon+follow(bexpr)=[or]+[$,)]=[or,$,)]
follow(bfactor)=first(bterm')\epsilon+follow(bterm)=[and]+[or,$,)]=[and, or, $, )]
but the reference answer says
follow(bterm) = [or, $]
follow(bfactor) = [and, $]
Why am I wrong?
I believe the reference answer is incorrect. For example, consider the derivation:
bexpr
-> bterm bexpr'
-> bterm
-> bfactor bterm'
-> bfactor
-> ( bexpr )
-> ( bterm bexpr' )
-> ( bterm )
-> ( bfactor bterm' )
-> ( bfactor )
This shows that you can derive sentential forms in which both bterm
and bfactor
are immediately followed by )
. Thus, according to the definition of FOLLOW
, )
must be in both FOLLOW(bterm)
and FOLLOW(bfactor)
(which is true in your answer but not the reference answer).
The only other discrepancy is that your answer has or
in FOLLOW(bfactor)
and the reference answer doesn't. You can show it should be there by finding a derivation in which bfactor
is immediately followed by or
, which shouldn't be too hard.
More simply, observe just the derivation
bterm
-> bfactor bterm'
-> bfactor
Thus, in sentential forms, a bfactor
can appear anywhere that a bterm
appears, and so the follow-set for bfactor
must include all the symbols in the follow-set for bterm
. This is the case in your answer but not in the reference answer.