Question

Is there a way to count arguments in the parser.y? I'm trying something that is recursive and I feel like that may not work due to the way yyparse() works. Here's what I'm trying in my parser.y:

arg_list:
     | arg ',' arg_list { 
          int func_arg_list_count(){ int argCount = 0; return argCount+1; } 

**

EDIT

**: Some updates, the above code is wrong as pointed out to me. Here is my union with some suggestions to update though I'm still having issues with the $1.

%union {
int val;
int count;
char *funcName;
}

%token <funcName> ID

%type <val> exp prop
%type <count> arg_list

Is it become my semantic value in lexer.l does not match up?

Oh here is there error code:

error: $1 of ‘arg_list’ has no declared type
 | arg ',' arg_list { $$ = $1 + 1; }
Était-ce utile?

La solution

What is written in the OP won't compile. In C, a function definition can only appear at the top-level, not inside braces, and bison actions are not at the top-level. (They are inside of a case statement, and in any event, the individual actions retain their braces.)

In bison, every non-terminal (and every terminal, for that matter) has a semantic value with a type specific to the non-terminal. So if you want the arg_list's semantic type to include the argument count, there is no problem. Just declare an appropriate type and add it to your %union. As a really simple example, here's an arg_list whose semantic type is precisely the count of arguments: (edited, @ChrisDodd pointed out the flaw in the original)

%union {
   int count;
   /* other types */
}

%type <count> arg_list non_empty_arg_list

%%

arg_list: /* EMPTY */        { $$ = 0; /* An empty list has no arguments */ }
        | non_empty_arg_list { $$ = $1; /* This is the default action. */ }

non_empty_arg_list:
          arg                        { $$ = 1; /* Starts with one argument */ }
        | non_empty_arg_list ',' arg { $$ = $1 + 1; /* Now it has one more argument */ }
        ;

Normally the semantic action of the arg_list would also build up a list of arguments in some fashion, so the semantic value would typically be more complicated. But that's a basic outline.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top