Reputation: 692
I'm attempting to write a (relatively) simple config file parser in flex
/bison
. The basic idea is that my bison
grammar uses some C functions to organize the parsed data into a series of C structs. I'd be happy to post my code if anyone thinks it is necessary to answer the question, just comment.
The issue I'm running into involves the scope of procedures within bison
actions. For example, if I have something like:
set
: NTOK name {
section *sec
init_s(sec, $2);
add_s(cf, sec);
}
Shouldn't sec
be available in a later rule of the grammar for use? I'm getting error: 'sec' undeclared
when I try to call it as an argument again later on. Can anyone enlighten me?
Upvotes: 0
Views: 1628
Reputation: 19950
This problem is typically solved by assigning types to the tokens and rules. You can also append own parameters to the parser function.
%union {
char* name;
section* sec;
}
%parse-param {whatever_type cf}
%token <name> name
%type <sec> set
%%
set : NTOK name {
init_s(&$$, $2);
add_s(cf, $$);
}
;
other_rule: set name {do_something_other($1 $2);}
;
Upvotes: 0
Reputation: 373462
All code generated for actions in bison
is in its own scope (IIRC, the generated code wraps it in curly-braces to enforce this). If you want to make data globally available to other actions, you'll need to explicitly declare a global variable somewhere (perhaps at the top of the flex
or bison
script?), then write to that variable. The rationale behind this is that if every variable in an action were implicitly global, or at least readable by other actions, then it would be very easy to accidentally recycle garbage data when you meant to be creating new data.
Upvotes: 4