11 #define GC_INITIAL_CAPACITY 256
22 static long int value_of_expr(struct Expr expr)
24 if (expr.type == EXPR_CONS) {
25 return (long int) expr.cons;
26 } else if (expr.type == EXPR_ATOM) {
27 return (long int) expr.atom;
33 static int compare_exprs(const void *a, const void *b)
38 const long int ptr_a = value_of_expr(*(const struct Expr *)a);
39 const long int ptr_b = value_of_expr(*(const struct Expr *)b);
40 const long int d = ptr_b - ptr_a;
58 Gc *gc = PUSH_LT(lt, malloc(sizeof(Gc)), free);
64 gc->exprs = PUSH_LT(lt, malloc(sizeof(struct Expr) * GC_INITIAL_CAPACITY), free);
65 if (gc->exprs == NULL) {
69 gc->visited = PUSH_LT(lt, malloc(sizeof(int) * GC_INITIAL_CAPACITY), free);
70 if (gc->visited == NULL) {
75 gc->capacity = GC_INITIAL_CAPACITY;
80 void destroy_gc(Gc *gc)
84 for (size_t i = 0; i < gc->size; ++i) {
85 destroy_expr(gc->exprs[i]);
91 int gc_add_expr(Gc *gc, struct Expr expr)
95 if (gc->size >= gc->capacity) {
96 const size_t new_capacity = gc->capacity * 2;
97 struct Expr *const new_exprs = realloc(
99 sizeof(struct Expr) * new_capacity);
101 if (new_exprs == NULL) {
105 gc->capacity = new_capacity;
106 gc->exprs = REPLACE_LT(gc->lt, gc->exprs, new_exprs);
109 gc->exprs[gc->size++] = expr;
114 static long int gc_find_expr(Gc *gc, struct Expr expr)
119 struct Expr *result =
120 (struct Expr *) bsearch(&expr, gc->exprs, gc->size,
121 sizeof(struct Expr), compare_exprs);
123 if (result == NULL) {
127 return (long int) (result - gc->exprs);
130 static void gc_traverse_expr(Gc *gc, struct Expr root)
133 const long int root_index = gc_find_expr(gc, root);
134 assert(root_index >= 0);
136 if (gc->visited[root_index]) {
141 gc_traverse_expr(gc, root.cons->car);
142 gc_traverse_expr(gc, root.cons->cdr);
145 gc->visited[root_index] = 1;
148 void gc_collect(Gc *gc, struct Expr root)
153 /* Sort gc->exprs O(nlogn) */
154 qsort(gc->exprs, gc->size, sizeof(struct Expr), compare_exprs);
156 /* Defragment O(n) */
157 while(gc->size > 0 && gc->exprs[gc->size - 1].type == EXPR_VOID) {
161 /* Initialize visited array O(n) */
162 memset(gc->visited, 0, sizeof(int) * gc->size);
164 /* Traverse root O(nlogn) */
165 gc_traverse_expr(gc, root);
167 /* Dealloc unvisted O(n) */
168 for (size_t i = 0; i < gc->size; ++i) {
169 if (!gc->visited[i]) {
170 destroy_expr(gc->exprs[i]);
171 gc->exprs[i] = void_expr();
176 void gc_inspect(const Gc *gc)
178 for (size_t i = 0; i < gc->size; ++i) {
179 if (gc->exprs[i].type == EXPR_VOID) {