0

I'm making my own compiler and I've gotten stuck with an error.
I have the grammar:

A -> + | -
B -> A C
C -> B

Now, following the rules I found here and here, the First and Follow Sets would be:

First(A) = {+, -}
First(B) = First(A) = {+, -}
First(C) = First(B) = First(A) = {+, -}

Follow(A) = First(C) = {+, -}
Follow(B) = Follow(C) = Follow(B) = ...
Follow(C) = Follow(B) = Follow(C) = ...

As you might notice, Follow(B) and Follow(C) loop back on themselves and cause me a StackOverflowError.
My question is: what to do when this happens, do we just say that Follow(B) = {} or do we do something else? Is this just bad grammar?

Filip
  • 68
  • 6

1 Answers1

0

B and C in that grammar are unproductive (or "useless") so it's not surprising that their FOLLOW sets are empty.

But your algorithm for computing follow sets is flawed if it falls into infinite recursion. You need to ensure that you don't visit the same non-terminal twice while recursing.

However, the usual algorithm, which you'll find in your textbook and in any number of class notes on the internet, does not use recursion. It's a simple least fixed-point algorithm, which can be considered as the simultaneous solution of a number of equations. See an example in this SO amswer.

rici
  • 234,347
  • 28
  • 237
  • 341