7 static const char *basictype_str
[] = {
8 [btbool
] = "Bool", [btchar
] = "Char", [btint
] = "Int",
12 struct type
*type_arrow(struct type
*l
, struct type
*r
)
14 struct type
*res
= safe_malloc(sizeof(struct type
));
16 res
->data
.tarrow
.l
= l
;
17 res
->data
.tarrow
.r
= r
;
22 struct type
*type_basic(enum basictype type
)
24 struct type
*res
= safe_malloc(sizeof(struct type
));
26 res
->data
.tbasic
= type
;
30 struct type
*type_list(struct type
*type
)
32 struct type
*res
= safe_malloc(sizeof(struct type
));
34 res
->data
.tlist
= type
;
38 struct type
*type_tuple(struct type
*l
, struct type
*r
)
40 struct type
*res
= safe_malloc(sizeof(struct type
));
42 res
->data
.ttuple
.l
= l
;
43 res
->data
.ttuple
.r
= r
;
47 struct type
*type_var(char *ident
)
49 struct type
*res
= safe_malloc(sizeof(struct type
));
50 if (strcmp(ident
, "Int") == 0) {
52 res
->data
.tbasic
= btint
;
54 } else if (strcmp(ident
, "Char") == 0) {
56 res
->data
.tbasic
= btchar
;
58 } else if (strcmp(ident
, "Bool") == 0) {
60 res
->data
.tbasic
= btbool
;
62 } else if (strcmp(ident
, "Void") == 0) {
64 res
->data
.tbasic
= btvoid
;
68 res
->data
.tvar
= ident
;
73 void type_print(struct type
*type
, FILE *out
)
79 safe_fprintf(out
, "(");
80 type_print(type
->data
.tarrow
.l
, out
);
81 safe_fprintf(out
, "->");
82 type_print(type
->data
.tarrow
.r
, out
);
83 safe_fprintf(out
, ")");
86 safe_fprintf(out
, "%s", basictype_str
[type
->data
.tbasic
]);
89 safe_fprintf(out
, "[");
90 type_print(type
->data
.tlist
, out
);
91 safe_fprintf(out
, "]");
94 safe_fprintf(out
, "(");
95 type_print(type
->data
.ttuple
.l
, out
);
96 safe_fprintf(out
, ",");
97 type_print(type
->data
.ttuple
.r
, out
);
98 safe_fprintf(out
, ")");
101 safe_fprintf(out
, "%s", type
->data
.tvar
);
104 die("Unsupported type node\n");
108 void type_free(struct type
*type
)
112 switch (type
->type
) {
114 type_free(type
->data
.tarrow
.l
);
115 type_free(type
->data
.tarrow
.r
);
120 type_free(type
->data
.tlist
);
123 type_free(type
->data
.ttuple
.l
);
124 type_free(type
->data
.ttuple
.r
);
127 free(type
->data
.tvar
);
130 die("Unsupported type node\n");
135 struct type
*type_dup(struct type
*r
)
137 struct type
*res
= safe_malloc(sizeof(struct type
));
141 res
->data
.tarrow
.l
= type_dup(r
->data
.tarrow
.l
);
142 res
->data
.tarrow
.r
= type_dup(r
->data
.tarrow
.r
);
147 res
->data
.tlist
= type_dup(r
->data
.tlist
);
150 res
->data
.ttuple
.l
= type_dup(r
->data
.ttuple
.l
);
151 res
->data
.ttuple
.r
= type_dup(r
->data
.ttuple
.r
);
154 res
->data
.tvar
= safe_strdup(r
->data
.tvar
);
160 void type_ftv(struct type
*r
, int *nftv
, char ***ftv
)
164 type_ftv(r
->data
.ttuple
.l
, nftv
, ftv
);
165 type_ftv(r
->data
.ttuple
.r
, nftv
, ftv
);
170 type_ftv(r
->data
.tlist
, nftv
, ftv
);
173 type_ftv(r
->data
.ttuple
.l
, nftv
, ftv
);
174 type_ftv(r
->data
.ttuple
.r
, nftv
, ftv
);
177 *ftv
= realloc(*ftv
, (*nftv
+1)*sizeof(char *));
180 (*ftv
)[(*nftv
)++] = r
->data
.tvar
;