简体   繁体   中英

What is the scope of yacc/bison actions?

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?

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.

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);}
          ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM