work on type inference some more
[ccc.git] / sem / hm / gamma.c
1 #include <stdlib.h>
2 #include <string.h>
3
4 #include "../hm.h"
5
6 struct gamma *gamma_init()
7 {
8 struct gamma *gamma = safe_malloc(sizeof(struct gamma));
9 gamma->fresh = 0;
10 gamma->nschemes = 0;
11 gamma->vars = NULL;
12 gamma->schemes = NULL;
13 return gamma;
14 }
15
16 void gamma_insert(struct gamma *gamma, char *ident, struct scheme *scheme)
17 {
18 gamma->nschemes++;
19 gamma->vars = realloc(gamma->vars, gamma->nschemes*sizeof(char *));
20 gamma->schemes = realloc(gamma->schemes,
21 gamma->nschemes*sizeof(struct scheme *));
22 gamma->vars[gamma->nschemes-1] = safe_strdup(ident);
23 gamma->schemes[gamma->nschemes-1] = scheme;
24 }
25
26 struct scheme *gamma_lookup(struct gamma *gamma, char *ident)
27 {
28 for (int i = 0; i<gamma->nschemes; i++)
29 if (strcmp(ident, gamma->vars[i]) == 0)
30 return gamma->schemes[i];
31 return NULL;
32 }
33
34 struct type *gamma_fresh(struct gamma *gamma)
35 {
36 char buf[10] = {0};
37 sprintf(buf, "%d", gamma->fresh++);
38 return type_var(safe_strdup(buf));
39 }
40
41 void gamma_print(struct gamma *gamma, FILE *out)
42 {
43 fprintf(out, "{");
44 for (int i = 0; i<gamma->nschemes; i++) {
45 fprintf(out, "%s=", gamma->vars[i]);
46 scheme_print(gamma->schemes[i], out);
47 if (i + 1 < gamma->nschemes)
48 fprintf(out, ", ");
49 }
50 fprintf(out, "}");
51 }
52
53 void gamma_free(struct gamma *gamma)
54 {
55 for (int i = 0; i<gamma->nschemes; i++) {
56 free(gamma->vars[i]);
57 scheme_free(gamma->schemes[i]);
58 }
59 free(gamma->vars);
60 free(gamma->schemes);
61 free(gamma);
62 }