그건 완전히 맞습니다.
데이터 구조를 만드는 일반적인 방법은 해당 노드를 루트로하는 서브 트리에 $$
(즉, 프로덕션의 의미 적 값)을 설정하여 트리 구조로 빌드하는 것입니다. 예를 들어
:에 걸릴 수있는 많은입니다
%{
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; }
/* ... */
! 그러나 그것이 의미가 있습니다 (또는 그것이 안으로 가라 앉을 때). 정말 고맙습니다. –