-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtype.c
108 lines (95 loc) · 2.53 KB
/
type.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "takuya.h"
Type *int_type() {
Type *ty = calloc(1, sizeof(Type));
ty->kind = TY_INT;
return ty;
}
Type *pointer_to(Type *base) {
Type *ty = calloc(1, sizeof(Type));
ty->kind = TY_PTR;
ty->base = base;
return ty;
}
Type *array_of(Type *base, int size) {
Type *ty = calloc(1, sizeof(Type));
ty->kind = TY_ARRAY;
ty->base = base;
ty->array_size = size;
return ty;
}
int size_of(Type *ty) {
if (ty->kind == TY_INT || ty->kind == TY_PTR)
return 8;
assert(ty->kind == TY_ARRAY);
return size_of(ty->base) * ty->array_size;
}
void visit(Node *node) {
if (!node)
return;
visit(node->lhs);
visit(node->rhs);
visit(node->cond);
visit(node->then);
visit(node->els);
visit(node->init);
visit(node->inc);
for (Node *n = node->body; n; n = n->next)
visit(n);
for (Node *n = node->args; n; n = n->next)
visit(n);
switch (node->kind) {
case ND_MUL:
case ND_DIV:
case ND_EQ:
case ND_NE:
case ND_LT:
case ND_LE:
case ND_FUNCALL:
case ND_NUM:
node->ty = int_type();
return;
case ND_VAR:
node->ty = node->var->ty;
return;
case ND_ADD:
if (node->rhs->ty->base) {//int_typeはenumの0だからfalse 左にポインタ型が来るように調整。ex pがポインタ型の時は 1+p じゃなくてp+1とする
Node *tmp = node->lhs;
node->lhs = node->rhs;
node->rhs = tmp;
}
if (node->rhs->ty->base)
error_at("", "invalid pointer arithmetic operands");
node->ty = node->lhs->ty;
return;
case ND_SUB:
if (node->rhs->ty->base)
error_at("", "invalid pointer arithmetic operands");
node->ty = node->lhs->ty;
return;
case ND_ASSIGN:
node->ty = node->lhs->ty;
return;
case ND_ADDR:
if (node->lhs->ty->kind == TY_ARRAY)
node->ty = pointer_to(node->lhs->ty->base);
else
node->ty = pointer_to(node->lhs->ty);
return;
case ND_DEREF:
if (!node->lhs->ty->base)//x=3; y=&x;*yとかだと*yという値は3を表すからint型。**yみたいなやつは*yというポインタ型を表すからポインタ型
error_at("", "invalid pointer dereference");
node->ty = node->lhs->ty->base;
return;
case ND_SIZEOF://sizeofは関数ではなく実際は単項演算子
node->kind = ND_NUM;
node->ty = int_type();
node->val = size_of(node->lhs->ty);
node->lhs = NULL;
return;
}
}
void add_type(Program *prog) {
for (Function *fn = prog->fns; fn; fn = fn->next)
for (Node *node = fn->node; node; node = node->next)
visit(node);
}