2
votes

I am learning about Context Free Grammars for a Compilers course I'm attending to. I was trying to define a Grammar for function's signatures. Examples would be:

int a
int b, int c
Object a, Object d
...

The closest I could achieve to something like that was:

Params -> Params, Param
       |  Param
       |  lambda

Param -> paramType paramName

Yet this isn't what I want. This grammar allows incorrect string as , int a. I've been here for a while and I can't think of a better way to get to a correct grammar.

Any help would be appreciated.

2

2 Answers

2
votes

Basically what we want is (Param,)* Param | lambda, so how do that in production rules? Well we can introduce another rule for (Param,)*, like this:

ParamCommas -> Param, ParamCommas
            |  lambda

Then we can use it in Params like this:

Params -> ParamCommas Param
       |  lambda

Note that we don't need an extra rule for a single Param as ParamCommas can already be lambda.

0
votes

What about doing this:

Param-> AB|lambda
A-> param
B->','paramB|lambda