如何解析数据结构以便以后执行? (Flex - Bison)

时间:2017-05-22 18:18:58

标签: bison flex-lexer

这是一项学校作业。我只是在朝着正确的方向寻找一个点。也许当我看到它时,我只是不认识答案(谷歌搜索)。

我不想解析语法并立即执行{action},而是希望将所有内容都推送到数据结构中以便以后执行。例如:IF-cond-stmt-ELSE-stmt,当正常解析时,两个stmt都被执行。我想如果我能把它放在某个地方,我就可以控制发生的事情。

我离开基地吗?

1 个答案:

答案 0 :(得分:0)

这是完全正确的。

创建数据结构的常用方法是通过将$$(即生产的语义值)设置为以该节点为根的子树来构建它(作为一种树)。

例如:

%{
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; }
/* ... */
相关问题