Project restructuring to support the new direction

This commit is contained in:
2025-08-28 13:02:37 -05:00
parent d109b6f374
commit 330aca002f
11 changed files with 89 additions and 99 deletions

3
example/c/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
*.o
scheme
scheme.exe

5
example/c/Makefile Normal file
View File

@@ -0,0 +1,5 @@
CFLAGS=-g
all: scheme
scheme: gc.o runtime.o

27
example/c/common.h Normal file
View File

@@ -0,0 +1,27 @@
#ifndef _COMMON_H_
#define _COMMON_H_
#define SIZE 1024
#define BROKEN_HEART 1
#define CONS 2
#define INTEGER 3
#define SYMBOL 4
#define BYE 5
typedef struct box_t {
char type;
union {
int integer;
char* symbol;
struct cons_t* cons;
};
} box_t;
typedef struct cons_t {
box_t car;
box_t cdr;
} cons_t;
extern cons_t *the_empty_list;
#endif // _COMMON_H_

64
example/c/gc.c Normal file
View File

@@ -0,0 +1,64 @@
// Cheney style stop and copy garbage collector
#include "gc.h"
cons_t *the_empty_list = NULL;
static cons_t *old, *new, *scanptr, *freeptr, *eom, *root;
size_t tos;
void gc_init() {
old = calloc(sizeof(cons_t), SIZE);
freeptr = old;
eom = old + (SIZE / 2);
new = eom + 1;
root = alloc();
}
cons_t *alloc() {
if (freeptr < eom) {
cons_t *retval = freeptr;
freeptr++;
return retval;
} else {
gc_run();
return alloc();
}
}
void gc_run() {
freeptr = new;
scanptr = new;
// Relocate root
relocate(root);
// Enter the main GC loop
gc_loop();
// Flip old and new;
cons_t *temp = old;
old = new;
new = temp;
}
void gc_loop() {
while (scanptr < freeptr) {
relocate(scanptr);
scanptr++;
}
}
void move(box_t box) {
if (box.type == CONS && box.cons != the_empty_list) {
if (box.cons->car.type == BROKEN_HEART) {
box.cons = box.cons->cdr.cons;
} else {
memcpy(freeptr, box.cons, sizeof(cons_t));
box.cons->car.type = BROKEN_HEART;
box.cons->cdr.cons = freeptr;
freeptr++;
}
}
}
void relocate(cons_t* cons) {
move(cons->car);
move(cons->cdr);
}

16
example/c/gc.h Normal file
View File

@@ -0,0 +1,16 @@
#ifndef _GC_H_
#define _GC_H_
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "common.h"
void gc_init();
cons_t *alloc();
void gc_run();
void gc_loop();
void relocate(cons_t*);
#endif // _GC_H_