3
votes

I have an issue with the function definition in my C grammar wich can be found here http://www.archive-host.com/files/1959635/24fe084677d7655eb57ba66e1864081450017dd9/cAST.txt, it does not define correctly and I can't multiply it by something. The code I am tring to input is this one :

int factorielle(int n)
  { int x;
   if ( n == 0)
  return 1;
   else return n*factorielle(n-1);
  }

The function definition is this one :

function_definition
    : declaration_specifiers declarator compound_statement
    | declarator compound_statement
    ;

declaration_specifiers should be linked to int and declarator to factorielle(int n), to do this I replaced this :

direct_declarator
: ID ((direct_declarator '[' ']') | (direct_declarator '(' parameter_type_list ')') | (direct_declarator '(' identifier_list ')') | (direct_declarator '(' ')') )*

with

direct_declarator
: ID ((direct_declarator '[' ']') | (direct_declarator '(' parameter_type_list ')') | (direct_declarator '(' identifier_list ')') | (direct_declarator '(' ')')  | '(' parameter_type_list ')' )*

But it does not help much.

As for the multiplication I don't know how to do without bringing conflict. is there a way to fix this please ?

2

2 Answers

1
votes

You're likely to have an difficult time parsing real C code using a pure grammar with pure ANTLR.

The reason is that certain declarations look like legitimate executable statements. (While the referenced answer seems to be about LR(1) parsers, it is really about parsers that cannot handle ambiguity; ANTLR cannot).

The only way to tell them apart is to use context information available from earlier symbol declarations. So you will have to collect symbol types as you parse, and inspect that information in the grammar rule reductions to decide whether such instances are statements or declarations. (I don't know how one implements this in ANTLR, although I believe it to be possible).

0
votes

I may have found a solution to the first part of the issue by remplacing

compound_statement
  : '{' '}'
  | '{' statement_list '}'
  ;

with

compound_statement
  : '{' '}'
  | '{' statement_list '}'
  | '{' external_declaration+ '}'
  ;

and adding this to direct_declarator:

| ID '(' parameter_type_list ')'

But I don't know if it will bring some conflicts.