简体   繁体   English

如何从野牛语法中初始化变量?

[英]How to initiate a variable from the Grammar in Bison?

let's imagine we have this grammar 假设我们有这种语法

start: 
expressions;
expressions:
           expressions expression 
           | expression 
           ;
expression:
          expression NAME value { float $2 = $3;}
          | NAME value  { float $1 = $2;}
          ;
value:
      INT '.' INT
      ;

and for this grammar we apply this input 对于这个语法,我们应用此输入

a 2.0 b 3.0 a 2.0 b 3.0

this should be interpreted by our grammar like this ( float a = 2.0 ; float b = 3.0; ) 这应该由我们的语法解释如下(float a = 2.0; float b = 3.0;)

my aim is really to declare some variable with a name and with a constructor do some thing like myClass NAME(value); 我的目的实际上是声明一个具有名称的变量,并使用构造函数来执行诸如myClass NAME(value)之类的操作; and value is a float. 价值是浮点数。

the problems are I don't know how to get the whole value of a grammatical bloc like value in my exemple and how to make a declaration of variable name that will change in each line with in input file and wont have some generic float a = $1; 问题是我不知道如何在示例中获得像语法值之类的语法块的全部值,以及如何进行变量名声明,该变量名将在输入文件的每一行中更改,并且不会具有一些通用浮点数= $ 1;

I already have my flex tokeniser working which will give me NAME and VALUE 我已经有我的flex tokeniser工作了,它将给我NAME和VALUE

You can't use strings in place of variable names in C++. 在C ++中,不能使用字符串代替变量名。 What you should do instead is to define a map from strings to floats and then do something like the_map[$2] = $3; 您应该做的是定义一个从字符串到浮点的映射,然后执行诸如the_map[$2] = $3; instead of float $2 = $3; 而不是float $2 = $3; .

On an unrelated note, you need to add an action to value that makes it produce a float value (or make your lexer generate a single token for floats and use that). 无关紧要的是,您需要在value上添加一个操作,使其生成浮点值(或让您的词法分析器为float生成单个标记并使用该标记)。 Otherwise $3 doesn't have a proper value when you use it in expression 's action. 否则,在expression的action中使用$3它没有适当的值。

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

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