Reputation: 535
for example, I have this declaration in .ypp:
%{
#include <iostream>
#include <stdlib.h>
#include "structs.h"
#include "func.h"
#define YYSTYPE Types
%}
%union Types{
int Integer;
bool Boolean;
Expression Exp;
};
and in "structs.h" I have:
typedef union{
string str;
int integer;
bool boolean;
} Value;
struct Expression {
int lineNum;
Value val;
};
in "func.h" I have this func:
int binop(Types& a, Types& b); //assume all file needed included
can I pass inside the .ypp the $$ arg:
Exp : Exp Add Exp {$$.integer = binop($1, $2);}
Upvotes: 0
Views: 72
Reputation: 241791
You can certainly pass a semantic value by reference, but you can't assume that the reference will remain valid beyond the execution of the semantic action. So don't keep a persistent reference to a semantic value.
Semantic values are stored on the parser stack, and parser stack slots are reused at the parser's convenience (since it is really a stack). In particular, the $1...$n
slots are popped immediately after the semantic action is executed, while $$
is a temporary which is pushed (copied) onto the stack after $1...$n
are popped.
Even if the value were not popped right away -- as would be the case for a mid-rule semantic action -- the parser stack may be reallocated (thereby invalidating all references) in order to accommodate a push.
Upvotes: 2