Mudancas no parser.y
[toypasc.git] / ast.c
blob4ac9399feba47a4b77d4b15f59d41b9441cb880b
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "ast.h"
6 //static void _ast_node_print_graph(struct AstNode *node);
7 //static int graph_code;
9 struct AstNode *
10 ast_node_new(const char* name, int kind, int type,
11 int linenum, Symbol *symbol)
13 int i;
14 struct AstNode *node;
16 node = (struct AstNode *) malloc (sizeof(struct AstNode));
18 if (name != NULL){
19 node->name = strdup(name);
20 } else
21 node->name = NULL;
23 node->kind = kind;
24 node->type = type;
25 node->linenum = linenum;
26 node->symbol = symbol;
28 for (i = 0; i < AST_CHILDREN_NUM; i++)
29 node->children[i] = NULL;
30 node->next = NULL;
32 return node;
35 void
36 ast_node_destroy(struct AstNode *node)
38 int i;
40 if (node == NULL)
41 return;
43 for (i = 0; i < AST_CHILDREN_NUM; i++)
44 ast_node_destroy(node->children[i]);
45 ast_node_destroy(node->next);
47 free(node);
50 void
51 ast_node_print(struct AstNode *node)
53 int i;
54 bool go;
55 struct AstNode *temp;
57 if (node == NULL) {
58 printf("(AstNode) NULL\n");
59 return;
62 printf("(AstNode) %x : %s\n", node, node->name);
63 printf("kind: %d\n", node->kind);
64 printf("type: %d\n", node->type);
65 printf("value: ");
66 value_print(&node->value, node->type);
67 printf("\nlinenum: %d\n", node->linenum);
68 printf("symbol: %x\n", node->symbol);
70 if (node->next != NULL)
71 printf("Sibling: %x\n", node->next);
73 go = FALSE;
74 for (i = 0; i < AST_CHILDREN_NUM; i++)
75 go = go || (node->children[i] != NULL);
77 if (go) {
78 printf("Children\n");
79 for (i = 0; i < AST_CHILDREN_NUM; i++) {
80 temp = node->children[i];
81 printf("\t(AstNode) %x", temp);
82 if (temp != NULL) {
83 printf(" : %s", temp->name);
85 printf("\n");
89 printf("\n");
91 for (i = 0; i < AST_CHILDREN_NUM; i++) {
92 if (node->children[i] != NULL)
93 ast_node_print(node->children[i]);
95 if (node->next != NULL)
96 ast_node_print(node->next);
99 /* Draft...
100 void
101 ast_node_print_graph(struct AstNode *node)
103 graph_code = 0;
104 printf("/* toypasc AST graph. *\n");
105 printf("digraph {\n");
106 _ast_node_print_graph(node);
107 printf("}\n");
110 static void
111 _ast_node_print_graph(struct AstNode *node)
113 int i;
114 int code;
116 if (node == NULL)
117 return;
119 code = graph_code++;
121 printf("\t%s_%d [label=%s]\n", node->name, code, node->name);
122 for (i = 0; i < AST_CHILDREN_NUM; i++) {
123 if (node->children[i] != NULL)
124 printf("\t%s_%d -> %s_%d\n", node->name, code,
125 node->children[i]->name,
126 graph_code + 1);
127 _ast_node_print_graph(node->children[i]);
130 if (node->next != NULL)
131 printf("\t%s_%d -> %s_%d\n", node->next->name, code,
132 node->children[i]->name,
133 graph_code + 1);
134 _ast_node_print_graph(node->next);