-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathast_printer.c
78 lines (76 loc) · 1.67 KB
/
ast_printer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "include/ast_printer.h"
#include <stdio.h>
void print_ast_expr(AST_EXPR *root)
{
if (!root->children)
{
printf("%s ", root->op->lexeme);
return;
}
else
{
printf("(");
for (int i = 0; i < root->children->size; i++)
{
print_ast_expr(root->children->elements[i]);
}
}
printf("%s) ", root->op->lexeme);
}
void print_ast_stmt(AST_STMT *root, int depth)
{
if (root->type == EXPRESSION_STATEMENT)
{
print_ast_expr(list_get(root->values, 0));
printf("\n");
}
if (root->type == BLOCK)
{
printf("BLOCK START %d\n", depth);
LIST *values = root->values;
for (int i = 0; i < values->size; i++)
{
print_ast_stmt(list_get(values, i), depth + 1);
}
printf("BLOCK END %d\n", depth);
}
if (root->type == ASSIGNMENT)
{
printf("%s := ", root->id->lexeme);
AST_STMT *assignee = list_get(root->values, 0);
print_ast_stmt(assignee, depth);
}
if (root->type == DECLARATION)
{
TOKEN *type = list_get(root->values, 0);
printf("declare %s of type %s\n", root->id->lexeme,
type->lexeme);
}
if (root->type == PRINT_STATEMENT)
{
printf("print ");
print_ast_expr(list_get(root->values, 0));
printf("\n");
}
if (root->type == CONDITION)
{
TOKEN *type = list_get(root->values, 0);
printf("\nif ");
print_ast_stmt(list_get(root->values, 0), depth);
print_ast_stmt(list_get(root->values, 1), depth);
if (root->values->size == 3)
{
printf("\nelse ");
print_ast_stmt(list_get(root->values, 2), depth);
}
printf("\n");
}
if (root->type == LOOP)
{
TOKEN *type = list_get(root->values, 0);
printf("\nwhile ");
print_ast_stmt(list_get(root->values, 0), depth);
print_ast_stmt(list_get(root->values, 1), depth);
printf("\n");
}
}