Files
centvrion/centvrion/compiler/runtime/cent_runtime.c
2026-04-21 14:24:48 +02:00

597 lines
19 KiB
C

#include "cent_runtime.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/* ------------------------------------------------------------------ */
/* Global arena */
/* ------------------------------------------------------------------ */
CentArena *cent_arena;
int cent_magnvm = 0;
/* ------------------------------------------------------------------ */
/* Arena allocator */
/* ------------------------------------------------------------------ */
CentArena *cent_arena_new(size_t cap) {
CentArena *a = malloc(sizeof(CentArena));
if (!a) { fputs("cent: out of memory\n", stderr); exit(1); }
a->buf = malloc(cap);
if (!a->buf) { fputs("cent: out of memory\n", stderr); exit(1); }
a->used = 0;
a->cap = cap;
a->next = NULL;
return a;
}
static size_t align8(size_t n) { return (n + 7) & ~(size_t)7; }
void *cent_arena_alloc(CentArena *a, size_t n) {
n = align8(n);
CentArena *cur = a;
for (;;) {
if (cur->used + n <= cur->cap) {
void *p = cur->buf + cur->used;
cur->used += n;
return p;
}
if (!cur->next) {
size_t new_cap = cur->cap > n ? cur->cap : n;
cur->next = cent_arena_new(new_cap);
}
cur = cur->next;
}
}
/* ------------------------------------------------------------------ */
/* Error handling */
/* ------------------------------------------------------------------ */
void cent_type_error(const char *msg) {
fprintf(stderr, "CENTVRION type error: %s\n", msg);
exit(1);
}
void cent_runtime_error(const char *msg) {
fprintf(stderr, "CENTVRION error: %s\n", msg);
exit(1);
}
/* ------------------------------------------------------------------ */
/* Scope operations */
/* ------------------------------------------------------------------ */
CentValue cent_scope_get(CentScope *s, const char *name) {
for (int i = 0; i < s->len; i++) {
if (strcmp(s->names[i], name) == 0)
return s->vals[i];
}
fprintf(stderr, "CENTVRION error: undefined variable '%s'\n", name);
exit(1);
}
void cent_scope_set(CentScope *s, const char *name, CentValue v) {
for (int i = 0; i < s->len; i++) {
if (strcmp(s->names[i], name) == 0) {
s->vals[i] = v;
return;
}
}
if (s->len >= s->cap) {
int new_cap = s->cap ? s->cap * 2 : 8;
const char **new_names = cent_arena_alloc(cent_arena, new_cap * sizeof(char *));
CentValue *new_vals = cent_arena_alloc(cent_arena, new_cap * sizeof(CentValue));
if (s->len > 0) {
memcpy(new_names, s->names, s->len * sizeof(char *));
memcpy(new_vals, s->vals, s->len * sizeof(CentValue));
}
s->names = new_names;
s->vals = new_vals;
s->cap = new_cap;
}
s->names[s->len] = name;
s->vals[s->len] = v;
s->len++;
}
CentScope cent_scope_copy(CentScope *s) {
CentScope dst;
dst.len = s->len;
dst.cap = s->cap;
if (s->cap > 0) {
dst.names = cent_arena_alloc(cent_arena, s->cap * sizeof(char *));
dst.vals = cent_arena_alloc(cent_arena, s->cap * sizeof(CentValue));
if (s->len > 0) {
memcpy(dst.names, s->names, s->len * sizeof(char *));
memcpy(dst.vals, s->vals, s->len * sizeof(CentValue));
}
} else {
dst.names = NULL;
dst.vals = NULL;
}
return dst;
}
/* ------------------------------------------------------------------ */
/* Roman numeral conversion */
/* ------------------------------------------------------------------ */
/* Descending table used for both int→roman and roman→int */
static const struct { const char *str; long val; } ROMAN_TABLE[] = {
{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400},
{"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40},
{"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4},
{"I", 1}
};
#define ROMAN_TABLE_LEN 13
/* Transform a 1-3999 Roman string into its x1000 equivalent.
Each char: 'I' -> "M" (since I*1000 = M), others -> char + "_". */
static void transform_thousands(const char *src, char *dst, size_t dstsz) {
size_t pos = 0;
for (const char *p = src; *p; p++) {
if (*p == 'I') {
if (pos + 1 >= dstsz) cent_runtime_error("Roman numeral buffer overflow");
dst[pos++] = 'M';
} else {
if (pos + 2 >= dstsz) cent_runtime_error("Roman numeral buffer overflow");
dst[pos++] = *p;
dst[pos++] = '_';
}
}
dst[pos] = '\0';
}
void cent_int_to_roman(long n, char *buf, size_t bufsz) {
if (n <= 0 || (n > 3999 && !cent_magnvm))
cent_runtime_error("number out of range for Roman numerals (1-3999)");
size_t pos = 0;
if (n > 3999) {
char base[64];
cent_int_to_roman(n / 1000, base, sizeof(base));
char transformed[128];
transform_thousands(base, transformed, sizeof(transformed));
size_t tlen = strlen(transformed);
if (tlen >= bufsz) cent_runtime_error("Roman numeral buffer overflow");
memcpy(buf, transformed, tlen);
pos = tlen;
n = n % 1000;
if (n == 0) { buf[pos] = '\0'; return; }
}
for (int i = 0; i < ROMAN_TABLE_LEN && n > 0; i++) {
while (n >= ROMAN_TABLE[i].val) {
size_t slen = strlen(ROMAN_TABLE[i].str);
if (pos + slen >= bufsz)
cent_runtime_error("Roman numeral buffer overflow");
memcpy(buf + pos, ROMAN_TABLE[i].str, slen);
pos += slen;
n -= ROMAN_TABLE[i].val;
}
}
buf[pos] = '\0';
}
long cent_roman_to_int(const char *s) {
long result = 0;
int pos = 0;
int slen = (int)strlen(s);
if (slen == 0)
cent_runtime_error("empty Roman numeral");
while (pos < slen) {
int matched = 0;
for (int i = 0; i < ROMAN_TABLE_LEN; i++) {
int tlen = (int)strlen(ROMAN_TABLE[i].str);
if (strncmp(s + pos, ROMAN_TABLE[i].str, tlen) == 0) {
result += ROMAN_TABLE[i].val;
pos += tlen;
matched = 1;
break;
}
}
if (!matched) {
fprintf(stderr, "CENTVRION error: invalid Roman numeral: %s\n", s);
exit(1);
}
}
return result;
}
/* ------------------------------------------------------------------ */
/* Display */
/* ------------------------------------------------------------------ */
/* Write value as string into buf[0..bufsz-1]; return chars needed */
/* (not counting null). buf may be NULL (just count mode). */
static int write_val(CentValue v, char *buf, int bufsz) {
char tmp[64];
int n;
switch (v.type) {
case CENT_INT:
cent_int_to_roman(v.ival, tmp, sizeof(tmp));
n = (int)strlen(tmp);
if (buf && n < bufsz) { memcpy(buf, tmp, n); buf[n] = '\0'; }
return n;
case CENT_STR:
n = (int)strlen(v.sval);
if (buf && n < bufsz) { memcpy(buf, v.sval, n); buf[n] = '\0'; }
return n;
case CENT_BOOL:
if (v.bval) {
if (buf && bufsz > 7) { memcpy(buf, "VERITAS", 7); buf[7] = '\0'; }
return 7;
} else {
if (buf && bufsz > 8) { memcpy(buf, "FALSITAS", 8); buf[8] = '\0'; }
return 8;
}
case CENT_NULL:
if (buf && bufsz > 6) { memcpy(buf, "NVLLVS", 6); buf[6] = '\0'; }
return 6;
case CENT_FRAC: {
long num = v.fval.num, den = v.fval.den;
if (den < 0) { num = -num; den = -den; }
if (num < 0)
cent_runtime_error("cannot display negative numbers without SVBNVLLA");
long int_part = num / den;
long rem_num = num % den;
/* Integer part (omit leading zero for pure fractions) */
char int_buf[64] = {0};
int int_len = 0;
if (int_part > 0 || rem_num == 0) {
cent_int_to_roman(int_part, int_buf, sizeof(int_buf));
int_len = (int)strlen(int_buf);
}
/* Duodecimal fractional expansion — mirrors fraction_to_frac() */
char frac_buf[64] = {0};
int frac_pos = 0;
long cur_num = rem_num, cur_den = den;
for (int lvl = 0; lvl < 6 && cur_num != 0; lvl++) {
if (lvl > 0) frac_buf[frac_pos++] = '|';
long level_int = (cur_num * 12) / cur_den;
cur_num = (cur_num * 12) % cur_den;
for (int i = 0; i < (int)(level_int / 6); i++) frac_buf[frac_pos++] = 'S';
for (int i = 0; i < (int)((level_int % 6) / 2); i++) frac_buf[frac_pos++] = ':';
for (int i = 0; i < (int)((level_int % 6) % 2); i++) frac_buf[frac_pos++] = '.';
}
n = int_len + frac_pos;
if (buf && n < bufsz) {
memcpy(buf, int_buf, int_len);
memcpy(buf + int_len, frac_buf, frac_pos);
buf[n] = '\0';
}
return n;
}
case CENT_LIST: {
/* "[elem1 elem2 ...]" */
int total = 2; /* '[' + ']' */
for (int i = 0; i < v.lval.len; i++) {
if (i > 0) total++; /* space separator */
total += write_val(v.lval.items[i], NULL, 0);
}
if (!buf) return total;
int pos = 0;
buf[pos++] = '[';
for (int i = 0; i < v.lval.len; i++) {
if (i > 0) buf[pos++] = ' ';
int written = write_val(v.lval.items[i], buf + pos, bufsz - pos);
pos += written;
}
buf[pos++] = ']';
if (pos < bufsz) buf[pos] = '\0';
return total;
}
default:
cent_runtime_error("cannot display value");
return 0;
}
}
char *cent_make_string(CentValue v) {
int len = write_val(v, NULL, 0);
char *buf = cent_arena_alloc(cent_arena, len + 1);
write_val(v, buf, len + 1);
return buf;
}
/* ------------------------------------------------------------------ */
/* Arithmetic and comparison operators */
/* ------------------------------------------------------------------ */
static long gcd(long a, long b) {
a = a < 0 ? -a : a;
b = b < 0 ? -b : b;
while (b) { long t = b; b = a % b; a = t; }
return a ? a : 1;
}
static CentValue frac_reduce(long num, long den) {
if (den < 0) { num = -num; den = -den; }
long g = gcd(num < 0 ? -num : num, den);
return cent_frac(num / g, den / g);
}
static void to_frac(CentValue v, long *num, long *den) {
if (v.type == CENT_INT) { *num = v.ival; *den = 1; }
else if (v.type == CENT_NULL) { *num = 0; *den = 1; }
else { *num = v.fval.num; *den = v.fval.den; }
}
CentValue cent_add(CentValue a, CentValue b) {
if (a.type == CENT_INT && b.type == CENT_INT)
return cent_int(a.ival + b.ival);
if (a.type == CENT_NULL && b.type == CENT_NULL)
return cent_null();
if ((a.type == CENT_INT || a.type == CENT_FRAC || a.type == CENT_NULL) &&
(b.type == CENT_INT || b.type == CENT_FRAC || b.type == CENT_NULL)) {
long an, ad, bn, bd;
to_frac(a, &an, &ad); to_frac(b, &bn, &bd);
return frac_reduce(an * bd + bn * ad, ad * bd);
}
if (a.type == CENT_STR || b.type == CENT_STR)
cent_type_error("'+' cannot be used with strings; use '&' for concatenation");
else
cent_type_error("'+' requires two integers");
return cent_null();
}
CentValue cent_concat(CentValue a, CentValue b) {
const char *sa = (a.type == CENT_NULL) ? "" : cent_make_string(a);
const char *sb = (b.type == CENT_NULL) ? "" : cent_make_string(b);
int la = (int)strlen(sa), lb = (int)strlen(sb);
char *s = cent_arena_alloc(cent_arena, la + lb + 1);
memcpy(s, sa, la);
memcpy(s + la, sb, lb);
s[la + lb] = '\0';
return cent_str(s);
}
CentValue cent_sub(CentValue a, CentValue b) {
if (a.type == CENT_INT && b.type == CENT_INT)
return cent_int(a.ival - b.ival);
if ((a.type == CENT_INT || a.type == CENT_FRAC || a.type == CENT_NULL) &&
(b.type == CENT_INT || b.type == CENT_FRAC || b.type == CENT_NULL)) {
long an, ad, bn, bd;
to_frac(a, &an, &ad); to_frac(b, &bn, &bd);
return frac_reduce(an * bd - bn * ad, ad * bd);
}
cent_type_error("'-' requires two integers");
return cent_null();
}
CentValue cent_mul(CentValue a, CentValue b) {
if (a.type == CENT_INT && b.type == CENT_INT)
return cent_int(a.ival * b.ival);
if ((a.type == CENT_INT || a.type == CENT_FRAC || a.type == CENT_NULL) &&
(b.type == CENT_INT || b.type == CENT_FRAC || b.type == CENT_NULL)) {
long an, ad, bn, bd;
to_frac(a, &an, &ad); to_frac(b, &bn, &bd);
return frac_reduce(an * bn, ad * bd);
}
cent_type_error("'*' requires two integers");
return cent_null();
}
CentValue cent_div(CentValue a, CentValue b) {
if (a.type != CENT_INT || b.type != CENT_INT)
cent_type_error("'/' requires two integers");
if (b.ival == 0)
cent_runtime_error("division by zero");
return cent_int(a.ival / b.ival);
}
CentValue cent_div_frac(CentValue a, CentValue b) {
long an, ad, bn, bd;
to_frac(a, &an, &ad); to_frac(b, &bn, &bd);
if (bn == 0) cent_runtime_error("division by zero");
return frac_reduce(an * bd, ad * bn);
}
CentValue cent_mod(CentValue a, CentValue b) {
if (a.type != CENT_INT || b.type != CENT_INT)
cent_type_error("'RELIQVVM' requires two integers");
if (b.ival == 0)
cent_runtime_error("modulo by zero");
return cent_int(a.ival % b.ival);
}
CentValue cent_mod_frac(CentValue a, CentValue b) {
long an, ad, bn, bd;
to_frac(a, &an, &ad); to_frac(b, &bn, &bd);
if (bn == 0) cent_runtime_error("modulo by zero");
/* a/b mod c/d over a common denominator ad*bd:
num_a = an*bd, num_b = bn*ad
result = (num_a - floor(num_a/num_b) * num_b) / (ad*bd)
Use floored division so the result matches Python's Fraction.__mod__. */
long num_a = an * bd;
long num_b = bn * ad;
long q = num_a / num_b;
if ((num_a % num_b != 0) && ((num_a < 0) != (num_b < 0))) q -= 1;
long new_num = num_a - q * num_b;
return frac_reduce(new_num, ad * bd);
}
CentValue cent_eq(CentValue a, CentValue b) {
if ((a.type == CENT_INT || a.type == CENT_FRAC) &&
(b.type == CENT_INT || b.type == CENT_FRAC)) {
long an, ad, bn, bd;
to_frac(a, &an, &ad); to_frac(b, &bn, &bd);
return cent_bool(an * bd == bn * ad);
}
if (a.type != b.type) return cent_bool(0);
switch (a.type) {
case CENT_STR: return cent_bool(strcmp(a.sval, b.sval) == 0);
case CENT_BOOL: return cent_bool(a.bval == b.bval);
case CENT_NULL: return cent_bool(1);
default:
cent_type_error("'EST' not supported for this type");
return cent_null();
}
}
CentValue cent_neq(CentValue a, CentValue b) {
CentValue r = cent_eq(a, b);
return cent_bool(!r.bval);
}
CentValue cent_lt(CentValue a, CentValue b) {
if ((a.type == CENT_INT || a.type == CENT_FRAC || a.type == CENT_NULL) &&
(b.type == CENT_INT || b.type == CENT_FRAC || b.type == CENT_NULL)) {
long an, ad, bn, bd;
to_frac(a, &an, &ad); to_frac(b, &bn, &bd);
return cent_bool(an * bd < bn * ad);
}
cent_type_error("'MINVS' requires two integers");
return cent_null();
}
CentValue cent_gt(CentValue a, CentValue b) {
if ((a.type == CENT_INT || a.type == CENT_FRAC || a.type == CENT_NULL) &&
(b.type == CENT_INT || b.type == CENT_FRAC || b.type == CENT_NULL)) {
long an, ad, bn, bd;
to_frac(a, &an, &ad); to_frac(b, &bn, &bd);
return cent_bool(an * bd > bn * ad);
}
cent_type_error("'PLVS' requires two integers");
return cent_null();
}
CentValue cent_and(CentValue a, CentValue b) {
if (a.type != CENT_BOOL || b.type != CENT_BOOL)
cent_type_error("'ET' requires two booleans");
return cent_bool(a.bval && b.bval);
}
CentValue cent_or(CentValue a, CentValue b) {
if (a.type != CENT_BOOL || b.type != CENT_BOOL)
cent_type_error("'AVT' requires two booleans");
return cent_bool(a.bval || b.bval);
}
/* ------------------------------------------------------------------ */
/* Builtin functions */
/* ------------------------------------------------------------------ */
void cent_dice(CentValue v) {
char *s = cent_make_string(v);
fputs(s, stdout);
fputc('\n', stdout);
}
void cent_everro(void) {
fputs("\033[2J\033[H", stdout);
fflush(stdout);
}
CentValue cent_avdi(void) {
char *buf = cent_arena_alloc(cent_arena, 1024);
if (!fgets(buf, 1024, stdin)) {
buf[0] = '\0';
return cent_str(buf);
}
int len = (int)strlen(buf);
if (len > 0 && buf[len - 1] == '\n')
buf[len - 1] = '\0';
return cent_str(buf);
}
CentValue cent_avdi_numerus(void) {
CentValue s = cent_avdi();
return cent_int(cent_roman_to_int(s.sval));
}
CentValue cent_longitudo(CentValue v) {
if (v.type == CENT_LIST) return cent_int(v.lval.len);
if (v.type == CENT_STR) return cent_int((long)strlen(v.sval));
cent_type_error("'LONGITVDO' requires a list or string");
return cent_null(); /* unreachable; silences warning */
}
CentValue cent_fortis_numerus(CentValue lo, CentValue hi) {
if (lo.type != CENT_INT || hi.type != CENT_INT)
cent_type_error("'FORTIS_NVMERVS' requires two integers");
long range = hi.ival - lo.ival + 1;
if (range <= 0)
cent_runtime_error("'FORTIS_NVMERVS' requires lo <= hi");
return cent_int(lo.ival + rand() % range);
}
CentValue cent_fortis_electionis(CentValue lst) {
if (lst.type != CENT_LIST)
cent_type_error("'FORTIS_ELECTIONIS' requires a list");
if (lst.lval.len == 0)
cent_runtime_error("'FORTIS_ELECTIONIS' requires a non-empty list");
return lst.lval.items[rand() % lst.lval.len];
}
void cent_semen(CentValue seed) {
if (seed.type != CENT_INT)
cent_type_error("'SEMEN' requires an integer seed");
srand((unsigned)seed.ival);
}
/* ------------------------------------------------------------------ */
/* Array helpers */
/* ------------------------------------------------------------------ */
CentValue cent_list_new(int cap) {
CentValue *items = cent_arena_alloc(cent_arena, cap * sizeof(CentValue));
return cent_list(items, 0, cap);
}
void cent_list_push(CentValue *lst, CentValue v) {
if (lst->lval.len >= lst->lval.cap) {
int new_cap = lst->lval.cap ? lst->lval.cap * 2 : 8;
CentValue *new_items = cent_arena_alloc(cent_arena, new_cap * sizeof(CentValue));
if (lst->lval.len > 0)
memcpy(new_items, lst->lval.items, lst->lval.len * sizeof(CentValue));
lst->lval.items = new_items;
lst->lval.cap = new_cap;
}
lst->lval.items[lst->lval.len++] = v;
}
CentValue cent_list_index(CentValue lst, CentValue idx) {
if (lst.type != CENT_LIST)
cent_type_error("index requires a list");
long i;
if (idx.type == CENT_INT)
i = idx.ival;
else if (idx.type == CENT_FRAC && idx.fval.den == 1)
i = idx.fval.num;
else
cent_type_error("list index must be an integer");
if (i < 1 || i > lst.lval.len)
cent_runtime_error("list index out of range");
return lst.lval.items[i - 1];
}
void cent_list_index_set(CentValue *lst, CentValue idx, CentValue v) {
if (lst->type != CENT_LIST)
cent_type_error("index-assign requires a list");
if (idx.type != CENT_INT)
cent_type_error("list index must be an integer");
long i = idx.ival;
if (i < 1 || i > lst->lval.len)
cent_runtime_error("list index out of range");
lst->lval.items[i - 1] = v;
}
/* ------------------------------------------------------------------ */
/* Initialisation */
/* ------------------------------------------------------------------ */
void cent_init(void) {
cent_arena = cent_arena_new(1024 * 1024); /* 1 MiB initial arena */
srand((unsigned)time(NULL));
}