3

我的 C 语法中的函数定义有问题,可以在这里找到http://www.archive-host.com/files/1959635/24fe084677d7655eb57ba66e1864081450017dd9/cAST.txt,它没有正确定义,我不能乘它通过一些东西。我想输入的代码是这个:

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

函数定义是这样的:

function_definition
    : declaration_specifiers declarator compound_statement
    | declarator compound_statement
    ;

declaration_specifiers 应该链接到 int 和 declarator 到 factorielle(int n),为此我替换了这个:

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

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

但这并没有太大帮助。

至于乘法,我不知道该怎么做才不会带来冲突。请问有没有办法解决这个问题?

4

2 回答 2

1

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).

于 2013-03-09T08:59:01.557 回答
0

我可能通过替换找到了问题第一部分的解决方案

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

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

并将其添加到 direct_declarator:

| ID '(' parameter_type_list ')'

但不知道会不会带来一些冲突。

于 2013-03-09T07:11:35.863 回答