-
Notifications
You must be signed in to change notification settings - Fork 152
/
util.c
116 lines (98 loc) · 2.34 KB
/
util.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
109
110
111
112
113
114
115
116
#include "9cc.h"
noreturn void error(char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
exit(1);
}
char *format(char *fmt, ...) {
char buf[2048];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
return strdup(buf);
}
Vector *new_vec() {
Vector *v = malloc(sizeof(Vector));
v->data = malloc(sizeof(void *) * 16);
v->capacity = 16;
v->len = 0;
return v;
}
void vec_push(Vector *v, void *elem) {
if (v->len == v->capacity) {
v->capacity *= 2;
v->data = realloc(v->data, sizeof(void *) * v->capacity);
}
v->data[v->len++] = elem;
}
Map *new_map(void) {
Map *map = malloc(sizeof(Map));
map->keys = new_vec();
map->vals = new_vec();
return map;
}
void map_put(Map *map, char *key, void *val) {
vec_push(map->keys, key);
vec_push(map->vals, val);
}
void *map_get(Map *map, char *key) {
for (int i = map->keys->len - 1; i >= 0; i--)
if (!strcmp(map->keys->data[i], key))
return map->vals->data[i];
return NULL;
}
bool map_exists(Map *map, char *key) {
for (int i = 0; i < map->keys->len; i++)
if (!strcmp(map->keys->data[i], key))
return true;
return false;
}
StringBuilder *new_sb(void) {
StringBuilder *sb = malloc(sizeof(StringBuilder));
sb->data = malloc(8);
sb->capacity = 8;
sb->len = 0;
return sb;
}
static void sb_grow(StringBuilder *sb, int len) {
if (sb->len + len <= sb->capacity)
return;
while (sb->len + len > sb->capacity)
sb->capacity *= 2;
sb->data = realloc(sb->data, sb->capacity);
}
void sb_add(StringBuilder *sb, char s) {
sb_grow(sb, 1);
sb->data[sb->len++] = s;
}
void sb_append(StringBuilder *sb, char *s) { sb_append_n(sb, s, strlen(s)); }
void sb_append_n(StringBuilder *sb, char *s, int len) {
sb_grow(sb, len);
memcpy(sb->data + sb->len, s, len);
sb->len += len;
}
char *sb_get(StringBuilder *sb) {
sb_add(sb, '\0');
return sb->data;
}
int roundup(int x, int align) { return (x + align - 1) & ~(align - 1); }
Type *ptr_to(Type *base) {
Type *ty = calloc(1, sizeof(Type));
ty->ty = PTR;
ty->size = 8;
ty->align = 8;
ty->ptr_to = base;
return ty;
}
Type *ary_of(Type *base, int len) {
Type *ty = calloc(1, sizeof(Type));
ty->ty = ARY;
ty->size = base->size * len;
ty->align = base->align;
ty->ary_of = base;
ty->len = len;
return ty;
}