0

This is for a school assignment. I'm just looking for a point in the right direction. Maybe I'm just not recognizing the answer when I see it (googling).

Instead of parsing the grammar and immediately performing the { action }, I would like to push everything into a data structure for later execution. For instance: IF-cond-stmt-ELSE-stmt, when parsed normally, both stmt's are executed. I think if I can put it somewhere, I would have control over what happens.

Am I off base?

1 Answers1

0

That's completely correct.

The usual way to create a data structure is to build it (as a kind of tree) by setting $$ (that is, the production's semantic value) to the subtree rooted at that node.

For example:

%{
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; }
/* ... */
rici
  • 234,347
  • 28
  • 237
  • 341