简体   繁体   English

yacc /野牛行动的范围是什么?

[英]What is the scope of yacc/bison actions?

I'm attempting to write a (relatively) simple config file parser in flex / bison . 我试图在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. 基本思想是我的bison语法使用一些C函数将解析的数据组织为一系列C结构。 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. 我遇到的问题涉及bison行动中的程序范围。 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? sec在以后的语法规则中不应该使用吗? I'm getting error: 'sec' undeclared when I try to call it as an argument again later on. 我收到error: 'sec' undeclared稍后我尝试再次将其作为参数时error: 'sec' undeclared 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). bison中的动作生成的所有代码都在其自己的范围内(IIRC,生成的代码将其包装在花括号中以强制执行此操作)。 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. 如果要使数据对其他操作全局可用,则需要在某处(也许在flexbison脚本的顶部?)显式声明一个全局变量,然后写入该变量。 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);}
          ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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