types.c (970B)
1 #include <string.h> 2 #include <stdlib.h> 3 #include <stdio.h> 4 #include <stdbool.h> 5 6 #include "ast.h" 7 8 #define SAME(s1, s2) (strcmp(s1, s2) == 0) 9 10 void 11 type_error(const char *expected, const char *got) { 12 fprintf(stderr, "type error: expected %s, but got %s\n", expected, got); 13 exit(1); 14 } 15 16 bool 17 same_type(struct ast_type *t1, struct ast_type *t2) { 18 if (t1->t != t2->t) 19 return false; 20 switch (t1->t) { 21 case BASIC_T: 22 return (strcmp(t1->type, t2->type) == 0); 23 case FUNCTION_T: 24 return same_type(t1->ret, t2); 25 } 26 return false; 27 } 28 29 struct ast_type * 30 typeof_expr(struct ast_expr *expr) { 31 switch (expr->op) { 32 case VALUE: 33 case ADD: 34 case SUB: 35 case DIV: 36 case MUL: 37 case NESTED: 38 case FUNCTION: 39 case VAR: 40 default: 41 return NULL; 42 } 43 } 44 45 void 46 typecheck_dec(struct ast_dec *dec) { 47 if (same_type(dec->type, typeof_expr(dec->value))) 48 type_error("ah", "ah"); 49 } 50 51 void 52 typecheck(struct ast_decs *body) { 53 while (body) { 54 typecheck_dec(body->dec); 55 body = body->decs; 56 } 57 }