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.