Bison 如何解析到数据结构中以供以后执行?(柔性-野牛)
这是学校的作业。我只是在寻找一个正确的方向。也许当我看到答案时,我只是没有认出它(谷歌搜索) 我不想解析语法并立即执行{action},而是希望将所有内容都推送到数据结构中,以便以后执行。例如:如果cond stmt ELSE stmt,当正常解析时,两个stmt都会执行。我想如果我能把它放在某个地方,我就能控制发生的事情Bison 如何解析到数据结构中以供以后执行?(柔性-野牛),bison,flex-lexer,Bison,Flex Lexer,这是学校的作业。我只是在寻找一个正确的方向。也许当我看到答案时,我只是没有认出它(谷歌搜索) 我不想解析语法并立即执行{action},而是希望将所有内容都推送到数据结构中,以便以后执行。例如:如果cond stmt ELSE stmt,当正常解析时,两个stmt都会执行。我想如果我能把它放在某个地方,我就能控制发生的事情 我偏离基准了吗?完全正确 创建数据结构的常用方法是通过将$$(即产品的语义值)设置为根在该节点上的子树来构建它(作为一种树) 例如: %{ typedef struct
我偏离基准了吗?完全正确 创建数据结构的常用方法是通过将
$$
(即产品的语义值)设置为根在该节点上的子树来构建它(作为一种树)
例如:
%{
typedef
struct Operation {
short type;
short operator;
union {
struct {
struct Operation* left;
struct Operation* right;
};
Identifier* id;
// ... other possible value types
};
} Operation;
Operation* new_binary_node(int operator, Operation* left, Operation* right) {
Operation* subtree = malloc(sizeof *subtree);
subtree->type = BINOP;
subtree->operator = operator;
subtree->left = left;
subtree->right = right;
}
Operation* new_identifier_node(Identifier* id) {
Operation* subtree = malloc(sizeof *subtree);
subtree->type = IDENTIFIER;
subtree->id = id;
}
void free_node(Operation* subtree) {
if (subtree) {
switch (subtree->operator) {
case BINOP: free_node(subtree->left);
free_node(subtree->right);
break;
case IDENTIFIER:
free_identifier(subtree->id);
break;
// ...
}
free(subtree);
}
}
%}
%union {
Operator* op;
Identifier* id;
}
%type <op> expr
%token <id> IDENTIFIER
%left '+' '-'
%left '*' '/'
/* ... */
%%
expr: expr '+' expr { $$ = new_binary_node('+', $1, $3); }
| expr '-' expr { $$ = new_binary_node('-', $1, $3); }
| expr '*' expr { $$ = new_binary_node('*', $1, $3); }
| expr '/' expr { $$ = new_binary_node('/', $1, $3); }
| IDENTIFIER { $$ = new_identifier_node($1); }
| '(' expr ')' { $$ = $2; }
/* ... */
%{
类型定义
结构操作{
短型;
短算子;
联合{
结构{
结构操作*左;
结构操作*对;
};
标识符*id;
//…其他可能的值类型
};
}操作;
操作*新的二进制节点(整数运算符,操作*左,操作*右){
操作*子树=malloc(sizeof*子树);
子树->类型=BINOP;
子树->运算符=运算符;
子树->左=左;
子树->右=右;
}
操作*新的\u标识符\u节点(标识符*id){
操作*子树=malloc(sizeof*子树);
子树->类型=标识符;
子树->id=id;
}
void free_节点(操作*子树){
if(子树){
开关(子树->运算符){
case BINOP:自由节点(子树->左);
自由_节点(子树->右侧);
打破
案例标识符:
自由_标识符(子树->id);
打破
// ...
}
自由(子树);
}
}
%}
%联合{
操作员*op;
标识符*id;
}
%类型表达式
%令牌标识符
%左'+''-'
%左'*''/'
/* ... */
%%
expr:expr'+'expr{$$=new_binary_节点('+',$1,$3);}
|expr'-'expr{$$=new_binary_节点('-',$1,$3);}
|expr'*'expr{$$=new_binary_节点('*',$1,$3);}
|expr'/'expr{$$=new_binary_节点('/',$1,$3);}
|标识符{$$=new_IDENTIFIER_node($1);}
|“('expr')”{$$=$2;}
/* ... */
这可真是太多了!但它确实有意义(或者当它沉入其中时会有意义:)。非常感谢你。