pub fn runtime_header() -> &'static str {
r#"
// ============================================================================
// BuildLang Runtime Library
// Embedded in generated C output - do not edit
// ============================================================================
// --- I/O initialization ---
static void __build_init_io(void) {
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
}
// --- Numeric conversion helpers ---
// Saturating float-to-integer conversion matching Rust's `as` semantics: NaN
// maps to 0, out-of-range inputs clamp to the target's min/max, and in-range
// inputs truncate toward zero. A raw C cast is undefined behavior for NaN and
// for values outside the target range, so every float->int cast routes here.
// Thresholds are exact powers of two (hex float literals) so the boundary is
// decided with no rounding: any value that survives the guards truncates
// without overflow.
static int8_t bl_f2i_i8 (double v){ if (v!=v) return 0; if (v>= 0x1p7 ) return INT8_MAX; if (v<=-0x1p7 ) return INT8_MIN; return (int8_t)v; }
static uint8_t bl_f2i_u8 (double v){ if (v!=v) return 0; if (v<=0.0) return 0; if (v>= 0x1p8 ) return UINT8_MAX; return (uint8_t)v; }
static int16_t bl_f2i_i16(double v){ if (v!=v) return 0; if (v>= 0x1p15) return INT16_MAX; if (v<=-0x1p15) return INT16_MIN; return (int16_t)v; }
static uint16_t bl_f2i_u16(double v){ if (v!=v) return 0; if (v<=0.0) return 0; if (v>= 0x1p16) return UINT16_MAX; return (uint16_t)v; }
static int32_t bl_f2i_i32(double v){ if (v!=v) return 0; if (v>= 0x1p31) return INT32_MAX; if (v<=-0x1p31) return INT32_MIN; return (int32_t)v; }
static uint32_t bl_f2i_u32(double v){ if (v!=v) return 0; if (v<=0.0) return 0; if (v>= 0x1p32) return UINT32_MAX; return (uint32_t)v; }
static int64_t bl_f2i_i64(double v){ if (v!=v) return 0; if (v>= 0x1p63) return INT64_MAX; if (v<=-0x1p63) return INT64_MIN; return (int64_t)v; }
static uint64_t bl_f2i_u64(double v){ if (v!=v) return 0; if (v<=0.0) return 0; if (v>= 0x1p64) return UINT64_MAX; return (uint64_t)v; }
static __int128 bl_f2i_i128(double v){
if (v!=v) return 0;
__int128 imax = (__int128)(((unsigned __int128)1 << 127) - 1);
__int128 imin = -imax - 1;
if (v>= 0x1p127) return imax;
if (v<=-0x1p127) return imin;
return (__int128)v;
}
// --- Integer division and remainder traps ---
// Rust's `/` and `%` panic on a zero divisor and on the one signed overflow
// `MIN / -1`, in release as well as debug. C's raw `/` and `%` instead raise a
// hardware divide error for i32/i64 (a crash, or a hang under this toolchain for
// the MIN/-1 case), and, because a narrow operand promotes to `int`, silently
// return the wrong value for the narrow signed overflow ((int8_t)-128 / -1
// evaluates to 128 and truncates back to -128). Every integer `/` and `%` routes
// through these helpers so the result is a clean abort matching a Rust panic
// (exit 101). A float `/` stays IEEE (1.0/0.0 == inf) and a float `%` lowers to
// fmod, so neither reaches here. Unsigned division cannot overflow, so those
// helpers check only the zero divisor.
static void bl_arith_panic(const char* what) {
fprintf(stderr, "%s\n", what);
exit(101);
}
static void bl_match_fail(void) {
fprintf(stderr, "non-exhaustive match: no arm matched the scrutinee\n");
exit(101);
}
// --- Plain integer arithmetic traps ---
// BuildLang plain fixed-width integer +, -, *, and signed unary - are defined as
// checked operations. Route them through helpers so generated C never relies on
// C signed-overflow behavior or unsigned wrap for plain arithmetic. The helpers
// reuse the same fail-closed exit path as division/remainder traps.
static __int128 bl_i128_max(void) {
return (__int128)(((unsigned __int128)1 << 127) - 1);
}
static __int128 bl_i128_min(void) {
return -bl_i128_max() - 1;
}
#define BL_DEFINE_SIGNED_ARITH(SUFFIX, TYPE, MINV, MAXV) \
static TYPE bl_iadd_##SUFFIX(TYPE a, TYPE b){ \
if ((b > 0 && a > (TYPE)((MAXV) - b)) || (b < 0 && a < (TYPE)((MINV) - b))) bl_arith_panic("attempt to add with overflow"); \
return (TYPE)(a + b); \
} \
static TYPE bl_isub_##SUFFIX(TYPE a, TYPE b){ \
if ((b < 0 && a > (TYPE)((MAXV) + b)) || (b > 0 && a < (TYPE)((MINV) + b))) bl_arith_panic("attempt to subtract with overflow"); \
return (TYPE)(a - b); \
} \
static TYPE bl_imul_##SUFFIX(TYPE a, TYPE b){ \
if (a == 0 || b == 0) return 0; \
if (a == (TYPE)-1) { if (b == (MINV)) bl_arith_panic("attempt to multiply with overflow"); return (TYPE)-b; } \
if (b == (TYPE)-1) { if (a == (MINV)) bl_arith_panic("attempt to multiply with overflow"); return (TYPE)-a; } \
if (a > 0) { \
if (b > 0) { if (a > (TYPE)((MAXV) / b)) bl_arith_panic("attempt to multiply with overflow"); } \
else { if (b < (TYPE)((MINV) / a)) bl_arith_panic("attempt to multiply with overflow"); } \
} else { \
if (b > 0) { if (a < (TYPE)((MINV) / b)) bl_arith_panic("attempt to multiply with overflow"); } \
else { if (b < (TYPE)((MAXV) / a)) bl_arith_panic("attempt to multiply with overflow"); } \
} \
return (TYPE)(a * b); \
} \
static TYPE bl_ineg_##SUFFIX(TYPE a){ \
if (a == (MINV)) bl_arith_panic("attempt to negate with overflow"); \
return (TYPE)-a; \
}
#define BL_DEFINE_UNSIGNED_ARITH(SUFFIX, TYPE, MAXV) \
static TYPE bl_uadd_##SUFFIX(TYPE a, TYPE b){ if (a > (TYPE)((MAXV) - b)) bl_arith_panic("attempt to add with overflow"); return (TYPE)(a + b); } \
static TYPE bl_usub_##SUFFIX(TYPE a, TYPE b){ if (a < b) bl_arith_panic("attempt to subtract with overflow"); return (TYPE)(a - b); } \
static TYPE bl_umul_##SUFFIX(TYPE a, TYPE b){ if (b != 0 && a > (TYPE)((MAXV) / b)) bl_arith_panic("attempt to multiply with overflow"); return (TYPE)(a * b); }
BL_DEFINE_SIGNED_ARITH(i8, int8_t, INT8_MIN, INT8_MAX)
BL_DEFINE_SIGNED_ARITH(i16, int16_t, INT16_MIN, INT16_MAX)
BL_DEFINE_SIGNED_ARITH(i32, int32_t, INT32_MIN, INT32_MAX)
BL_DEFINE_SIGNED_ARITH(i64, int64_t, INT64_MIN, INT64_MAX)
BL_DEFINE_SIGNED_ARITH(i128, __int128, bl_i128_min(), bl_i128_max())
BL_DEFINE_SIGNED_ARITH(isize, intptr_t, INTPTR_MIN, INTPTR_MAX)
BL_DEFINE_UNSIGNED_ARITH(u8, uint8_t, UINT8_MAX)
BL_DEFINE_UNSIGNED_ARITH(u16, uint16_t, UINT16_MAX)
BL_DEFINE_UNSIGNED_ARITH(u32, uint32_t, UINT32_MAX)
BL_DEFINE_UNSIGNED_ARITH(u64, uint64_t, UINT64_MAX)
BL_DEFINE_UNSIGNED_ARITH(u128, unsigned __int128, ~((unsigned __int128)0))
BL_DEFINE_UNSIGNED_ARITH(usize, uintptr_t, UINTPTR_MAX)
#define BL_DEFINE_SIGNED_EXPLICIT_ARITH(SUFFIX, TYPE, UTYPE, WORKTYPE, MINV, MAXV, SIGNBIT, UMASK) \
static TYPE bl_iwrap_from_u_##SUFFIX(WORKTYPE bits){ \
UTYPE u = (UTYPE)(bits & (WORKTYPE)(UMASK)); \
if (u <= (UTYPE)(MAXV)) return (TYPE)u; \
if (u == (UTYPE)(SIGNBIT)) return (TYPE)(MINV); \
UTYPE mag = (UTYPE)((UTYPE)0 - u); \
return (TYPE)(-((TYPE)mag)); \
} \
static TYPE bl_iadd_wrapping_##SUFFIX(TYPE a, TYPE b){ return bl_iwrap_from_u_##SUFFIX((WORKTYPE)((WORKTYPE)(UTYPE)a + (WORKTYPE)(UTYPE)b)); } \
static TYPE bl_isub_wrapping_##SUFFIX(TYPE a, TYPE b){ return bl_iwrap_from_u_##SUFFIX((WORKTYPE)((WORKTYPE)(UTYPE)a - (WORKTYPE)(UTYPE)b)); } \
static TYPE bl_imul_wrapping_##SUFFIX(TYPE a, TYPE b){ return bl_iwrap_from_u_##SUFFIX((WORKTYPE)((WORKTYPE)(UTYPE)a * (WORKTYPE)(UTYPE)b)); } \
static TYPE bl_iadd_saturating_##SUFFIX(TYPE a, TYPE b){ \
if ((b > 0 && a > (TYPE)((MAXV) - b)) || (b < 0 && a < (TYPE)((MINV) - b))) return b > 0 ? (TYPE)(MAXV) : (TYPE)(MINV); \
return (TYPE)(a + b); \
} \
static TYPE bl_isub_saturating_##SUFFIX(TYPE a, TYPE b){ \
if ((b < 0 && a > (TYPE)((MAXV) + b)) || (b > 0 && a < (TYPE)((MINV) + b))) return b < 0 ? (TYPE)(MAXV) : (TYPE)(MINV); \
return (TYPE)(a - b); \
} \
static TYPE bl_imul_saturating_##SUFFIX(TYPE a, TYPE b){ \
if (a == 0 || b == 0) return 0; \
bool positive = (a < 0) == (b < 0); \
if (a == (TYPE)-1) { if (b == (MINV)) return (TYPE)(MAXV); return (TYPE)-b; } \
if (b == (TYPE)-1) { if (a == (MINV)) return (TYPE)(MAXV); return (TYPE)-a; } \
bool overflow = false; \
if (a > 0) { \
if (b > 0) { overflow = a > (TYPE)((MAXV) / b); } \
else { overflow = b < (TYPE)((MINV) / a); } \
} else { \
if (b > 0) { overflow = a < (TYPE)((MINV) / b); } \
else { overflow = b < (TYPE)((MAXV) / a); } \
} \
if (overflow) return positive ? (TYPE)(MAXV) : (TYPE)(MINV); \
return (TYPE)(a * b); \
}
#define BL_DEFINE_UNSIGNED_EXPLICIT_ARITH(SUFFIX, TYPE, WORKTYPE, MAXV) \
static TYPE bl_uadd_wrapping_##SUFFIX(TYPE a, TYPE b){ return (TYPE)((WORKTYPE)a + (WORKTYPE)b); } \
static TYPE bl_usub_wrapping_##SUFFIX(TYPE a, TYPE b){ return (TYPE)((WORKTYPE)a - (WORKTYPE)b); } \
static TYPE bl_umul_wrapping_##SUFFIX(TYPE a, TYPE b){ return (TYPE)((WORKTYPE)a * (WORKTYPE)b); } \
static TYPE bl_uadd_saturating_##SUFFIX(TYPE a, TYPE b){ if (a > (TYPE)((MAXV) - b)) return (TYPE)(MAXV); return (TYPE)(a + b); } \
static TYPE bl_usub_saturating_##SUFFIX(TYPE a, TYPE b){ if (a < b) return 0; return (TYPE)(a - b); } \
static TYPE bl_umul_saturating_##SUFFIX(TYPE a, TYPE b){ if (b != 0 && a > (TYPE)((MAXV) / b)) return (TYPE)(MAXV); return (TYPE)(a * b); }
BL_DEFINE_SIGNED_EXPLICIT_ARITH(i8, int8_t, uint8_t, uint32_t, INT8_MIN, INT8_MAX, ((uint8_t)1 << 7), UINT8_MAX)
BL_DEFINE_SIGNED_EXPLICIT_ARITH(i16, int16_t, uint16_t, uint32_t, INT16_MIN, INT16_MAX, ((uint16_t)1 << 15), UINT16_MAX)
BL_DEFINE_SIGNED_EXPLICIT_ARITH(i32, int32_t, uint32_t, uint64_t, INT32_MIN, INT32_MAX, ((uint32_t)1 << 31), UINT32_MAX)
BL_DEFINE_SIGNED_EXPLICIT_ARITH(i64, int64_t, uint64_t, unsigned __int128, INT64_MIN, INT64_MAX, ((uint64_t)1 << 63), UINT64_MAX)
BL_DEFINE_SIGNED_EXPLICIT_ARITH(i128, __int128, unsigned __int128, unsigned __int128, bl_i128_min(), bl_i128_max(), ((unsigned __int128)1 << 127), ~((unsigned __int128)0))
BL_DEFINE_SIGNED_EXPLICIT_ARITH(isize, intptr_t, uintptr_t, unsigned __int128, INTPTR_MIN, INTPTR_MAX, ((uintptr_t)1 << (sizeof(uintptr_t) * CHAR_BIT - 1)), UINTPTR_MAX)
BL_DEFINE_UNSIGNED_EXPLICIT_ARITH(u8, uint8_t, uint32_t, UINT8_MAX)
BL_DEFINE_UNSIGNED_EXPLICIT_ARITH(u16, uint16_t, uint32_t, UINT16_MAX)
BL_DEFINE_UNSIGNED_EXPLICIT_ARITH(u32, uint32_t, uint64_t, UINT32_MAX)
BL_DEFINE_UNSIGNED_EXPLICIT_ARITH(u64, uint64_t, unsigned __int128, UINT64_MAX)
BL_DEFINE_UNSIGNED_EXPLICIT_ARITH(u128, unsigned __int128, unsigned __int128, ~((unsigned __int128)0))
BL_DEFINE_UNSIGNED_EXPLICIT_ARITH(usize, uintptr_t, unsigned __int128, UINTPTR_MAX)
#undef BL_DEFINE_SIGNED_ARITH
#undef BL_DEFINE_UNSIGNED_ARITH
#undef BL_DEFINE_SIGNED_EXPLICIT_ARITH
#undef BL_DEFINE_UNSIGNED_EXPLICIT_ARITH
static int8_t bl_idiv_i8 (int8_t a, int8_t b){ if(b==0) bl_arith_panic("attempt to divide by zero"); if(a==INT8_MIN && b==-1) bl_arith_panic("attempt to divide with overflow"); return a/b; }
static int16_t bl_idiv_i16 (int16_t a, int16_t b){ if(b==0) bl_arith_panic("attempt to divide by zero"); if(a==INT16_MIN && b==-1) bl_arith_panic("attempt to divide with overflow"); return a/b; }
static int32_t bl_idiv_i32 (int32_t a, int32_t b){ if(b==0) bl_arith_panic("attempt to divide by zero"); if(a==INT32_MIN && b==-1) bl_arith_panic("attempt to divide with overflow"); return a/b; }
static int64_t bl_idiv_i64 (int64_t a, int64_t b){ if(b==0) bl_arith_panic("attempt to divide by zero"); if(a==INT64_MIN && b==-1) bl_arith_panic("attempt to divide with overflow"); return a/b; }
static __int128 bl_idiv_i128(__int128 a, __int128 b){ if(b==0) bl_arith_panic("attempt to divide by zero"); __int128 imin = -(__int128)(((unsigned __int128)1<<127)-1)-1; if(a==imin && b==-1) bl_arith_panic("attempt to divide with overflow"); return a/b; }
static int8_t bl_irem_i8 (int8_t a, int8_t b){ if(b==0) bl_arith_panic("attempt to calculate the remainder with a divisor of zero"); if(a==INT8_MIN && b==-1) bl_arith_panic("attempt to calculate the remainder with overflow"); return a%b; }
static int16_t bl_irem_i16 (int16_t a, int16_t b){ if(b==0) bl_arith_panic("attempt to calculate the remainder with a divisor of zero"); if(a==INT16_MIN && b==-1) bl_arith_panic("attempt to calculate the remainder with overflow"); return a%b; }
static int32_t bl_irem_i32 (int32_t a, int32_t b){ if(b==0) bl_arith_panic("attempt to calculate the remainder with a divisor of zero"); if(a==INT32_MIN && b==-1) bl_arith_panic("attempt to calculate the remainder with overflow"); return a%b; }
static int64_t bl_irem_i64 (int64_t a, int64_t b){ if(b==0) bl_arith_panic("attempt to calculate the remainder with a divisor of zero"); if(a==INT64_MIN && b==-1) bl_arith_panic("attempt to calculate the remainder with overflow"); return a%b; }
static __int128 bl_irem_i128(__int128 a, __int128 b){ if(b==0) bl_arith_panic("attempt to calculate the remainder with a divisor of zero"); __int128 imin = -(__int128)(((unsigned __int128)1<<127)-1)-1; if(a==imin && b==-1) bl_arith_panic("attempt to calculate the remainder with overflow"); return a%b; }
static uint8_t bl_udiv_u8 (uint8_t a, uint8_t b){ if(b==0) bl_arith_panic("attempt to divide by zero"); return a/b; }
static uint16_t bl_udiv_u16 (uint16_t a, uint16_t b){ if(b==0) bl_arith_panic("attempt to divide by zero"); return a/b; }
static uint32_t bl_udiv_u32 (uint32_t a, uint32_t b){ if(b==0) bl_arith_panic("attempt to divide by zero"); return a/b; }
static uint64_t bl_udiv_u64 (uint64_t a, uint64_t b){ if(b==0) bl_arith_panic("attempt to divide by zero"); return a/b; }
static unsigned __int128 bl_udiv_u128(unsigned __int128 a, unsigned __int128 b){ if(b==0) bl_arith_panic("attempt to divide by zero"); return a/b; }
static intptr_t bl_idiv_isize(intptr_t a, intptr_t b){ if(b==0) bl_arith_panic("attempt to divide by zero"); if(a==INTPTR_MIN && b==-1) bl_arith_panic("attempt to divide with overflow"); return a/b; }
static uintptr_t bl_udiv_usize(uintptr_t a, uintptr_t b){ if(b==0) bl_arith_panic("attempt to divide by zero"); return a/b; }
static uint8_t bl_urem_u8 (uint8_t a, uint8_t b){ if(b==0) bl_arith_panic("attempt to calculate the remainder with a divisor of zero"); return a%b; }
static uint16_t bl_urem_u16 (uint16_t a, uint16_t b){ if(b==0) bl_arith_panic("attempt to calculate the remainder with a divisor of zero"); return a%b; }
static uint32_t bl_urem_u32 (uint32_t a, uint32_t b){ if(b==0) bl_arith_panic("attempt to calculate the remainder with a divisor of zero"); return a%b; }
static uint64_t bl_urem_u64 (uint64_t a, uint64_t b){ if(b==0) bl_arith_panic("attempt to calculate the remainder with a divisor of zero"); return a%b; }
static unsigned __int128 bl_urem_u128(unsigned __int128 a, unsigned __int128 b){ if(b==0) bl_arith_panic("attempt to calculate the remainder with a divisor of zero"); return a%b; }
static intptr_t bl_irem_isize(intptr_t a, intptr_t b){ if(b==0) bl_arith_panic("attempt to calculate the remainder with a divisor of zero"); if(a==INTPTR_MIN && b==-1) bl_arith_panic("attempt to calculate the remainder with overflow"); return a%b; }
static uintptr_t bl_urem_usize(uintptr_t a, uintptr_t b){ if(b==0) bl_arith_panic("attempt to calculate the remainder with a divisor of zero"); return a%b; }
// Decimal formatting for 128-bit integers. printf has no standard format
// specifier for __int128. The `_into` helpers write into caller-owned
// storage so variadic calls can safely pass any number of i128/u128 arguments.
static void bl_fmt_u128_into(char* out, unsigned __int128 v) {
if (v == 0) { strcpy(out, "0"); return; }
char tmp[64];
int n = 0;
while (v != 0) {
tmp[n++] = (char)('0' + (int)(v % 10));
v /= 10;
}
for (int i = 0; i < n; ++i) out[i] = tmp[n - 1 - i];
out[n] = '\0';
}
static void bl_fmt_i128_into(char* out, __int128 v) {
unsigned __int128 mag;
int neg = v < 0;
if (neg) {
mag = (unsigned __int128)(-(v + 1)) + 1u;
} else {
mag = (unsigned __int128)v;
}
char tmp[64];
int n = 0;
if (mag == 0) {
tmp[n++] = '0';
} else {
while (mag != 0) {
tmp[n++] = (char)('0' + (int)(mag % 10));
mag /= 10;
}
}
int pos = 0;
if (neg) out[pos++] = '-';
for (int i = 0; i < n; ++i) out[pos++] = tmp[n - 1 - i];
out[pos] = '\0';
}
static char* bl_fmt_u128(unsigned __int128 v) {
static char pool[16][64];
static unsigned slot = 0;
char* out = pool[slot];
slot = (slot + 1u) & 15u;
bl_fmt_u128_into(out, v);
return out;
}
static char* bl_fmt_i128(__int128 v) {
static char pool[16][64];
static unsigned slot = 0;
char* out = pool[slot];
slot = (slot + 1u) & 15u;
bl_fmt_i128_into(out, v);
return out;
}
// Place a %e-formatted number ("[-]D[.DDD]e[+-]EE") as plain positional decimal
// with no exponent, the way Rust's float Display renders. Writes into `out`.
static void bl_sci_to_plain(const char* sci, char* out) {
const char* s = sci;
char* o = out;
if (*s == '-') { *o++ = '-'; s++; }
char digits[24]; int nd = 0;
digits[nd++] = *s++;
if (*s == '.') { s++; while (*s >= '0' && *s <= '9') digits[nd++] = *s++; }
int E = atoi(s + 1);
if (E >= 0) {
if (E + 1 >= nd) {
for (int i = 0; i < nd; ++i) *o++ = digits[i];
for (int i = 0; i < E + 1 - nd; ++i) *o++ = '0';
} else {
for (int i = 0; i < E + 1; ++i) *o++ = digits[i];
*o++ = '.';
for (int i = E + 1; i < nd; ++i) *o++ = digits[i];
}
} else {
*o++ = '0'; *o++ = '.';
for (int i = 0; i < -E - 1; ++i) *o++ = '0';
for (int i = 0; i < nd; ++i) *o++ = digits[i];
}
*o = '\0';
}
// Shortest round-tripping decimal for a double, rendered like Rust's Display:
// the fewest significant digits that parse back to the same value, in plain
// positional decimal, with "inf"/"-inf"/"NaN" for the non-finite cases and a
// signed zero. Returns a pointer into a small rotating pool of static buffers
// so several float arguments in one printf keep distinct text.
static char* bl_fmt_f64(double v) {
static char pool[16][512];
static unsigned slot = 0;
char* out = pool[slot];
slot = (slot + 1u) & 15u;
if (v != v) { strcpy(out, "NaN"); return out; }
double inf = 1.0 / 0.0;
if (v == inf) { strcpy(out, "inf"); return out; }
if (v == -inf) { strcpy(out, "-inf"); return out; }
if (v == 0.0) { strcpy(out, signbit(v) ? "-0" : "0"); return out; }
char sci[64];
int prec = 17;
for (int p = 1; p <= 17; ++p) {
snprintf(sci, sizeof sci, "%.*e", p - 1, v);
if (strtod(sci, NULL) == v) { prec = p; break; }
}
snprintf(sci, sizeof sci, "%.*e", prec - 1, v);
bl_sci_to_plain(sci, out);
return out;
}
// Shortest round-tripping decimal for a float, matching Rust's f32 Display:
// the round-trip is checked in f32 precision so 0.1_f32 prints "0.1".
static char* bl_fmt_f32(float x) {
static char pool[16][512];
static unsigned slot = 0;
char* out = pool[slot];
slot = (slot + 1u) & 15u;
if (x != x) { strcpy(out, "NaN"); return out; }
float inf = 1.0f / 0.0f;
if (x == inf) { strcpy(out, "inf"); return out; }
if (x == -inf) { strcpy(out, "-inf"); return out; }
if (x == 0.0f) { strcpy(out, signbit(x) ? "-0" : "0"); return out; }
char sci[64];
int prec = 9;
for (int p = 1; p <= 9; ++p) {
snprintf(sci, sizeof sci, "%.*e", p - 1, (double)x);
if (strtof(sci, NULL) == x) { prec = p; break; }
}
snprintf(sci, sizeof sci, "%.*e", prec - 1, (double)x);
bl_sci_to_plain(sci, out);
return out;
}
// --- String type ---
typedef struct {
const char* ptr;
size_t len;
size_t cap; // 0 for string literals (not heap-allocated)
} BuildString;
// --- Option type (generic, stores scalar payloads in a typed union) ---
typedef struct {
bool has_value;
union {
int64_t i;
uint64_t u;
__int128 i128;
unsigned __int128 u128;
double f;
void* p;
} value;
} Option;
// --- Result type (generic, stores Ok/Err as tagged union) ---
typedef struct {
bool is_ok;
union {
int64_t ok_i;
uint64_t ok_u;
__int128 ok_i128;
unsigned __int128 ok_u128;
double ok_f;
void* ok_p;
} ok;
union {
int64_t err_i;
uint64_t err_u;
__int128 err_i128;
unsigned __int128 err_u128;
double err_f;
void* err_p;
} err;
} Result;
#define BL_OPTION_NONE() ((Option){ .has_value = false })
#define BL_OPTION_SOME(SLOT, CAST, VALUE) ((Option){ .has_value = true, .value = { .SLOT = (CAST)(VALUE) } })
#define BL_DEFINE_SIGNED_CHECKED_ARITH(SUFFIX, TYPE, MINV, MAXV, SLOT, CAST) \
static Option bl_iadd_checked_##SUFFIX(TYPE a, TYPE b){ \
if ((b > 0 && a > (TYPE)((MAXV) - b)) || (b < 0 && a < (TYPE)((MINV) - b))) return BL_OPTION_NONE(); \
return BL_OPTION_SOME(SLOT, CAST, (TYPE)(a + b)); \
} \
static Option bl_isub_checked_##SUFFIX(TYPE a, TYPE b){ \
if ((b < 0 && a > (TYPE)((MAXV) + b)) || (b > 0 && a < (TYPE)((MINV) + b))) return BL_OPTION_NONE(); \
return BL_OPTION_SOME(SLOT, CAST, (TYPE)(a - b)); \
} \
static Option bl_imul_checked_##SUFFIX(TYPE a, TYPE b){ \
if (a == 0 || b == 0) return BL_OPTION_SOME(SLOT, CAST, 0); \
if (a == (TYPE)-1) { if (b == (MINV)) return BL_OPTION_NONE(); return BL_OPTION_SOME(SLOT, CAST, (TYPE)-b); } \
if (b == (TYPE)-1) { if (a == (MINV)) return BL_OPTION_NONE(); return BL_OPTION_SOME(SLOT, CAST, (TYPE)-a); } \
bool overflow = false; \
if (a > 0) { \
if (b > 0) { overflow = a > (TYPE)((MAXV) / b); } \
else { overflow = b < (TYPE)((MINV) / a); } \
} else { \
if (b > 0) { overflow = a < (TYPE)((MINV) / b); } \
else { overflow = b < (TYPE)((MAXV) / a); } \
} \
if (overflow) return BL_OPTION_NONE(); \
return BL_OPTION_SOME(SLOT, CAST, (TYPE)(a * b)); \
}
#define BL_DEFINE_UNSIGNED_CHECKED_ARITH(SUFFIX, TYPE, MAXV, SLOT, CAST) \
static Option bl_uadd_checked_##SUFFIX(TYPE a, TYPE b){ if (a > (TYPE)((MAXV) - b)) return BL_OPTION_NONE(); return BL_OPTION_SOME(SLOT, CAST, (TYPE)(a + b)); } \
static Option bl_usub_checked_##SUFFIX(TYPE a, TYPE b){ if (a < b) return BL_OPTION_NONE(); return BL_OPTION_SOME(SLOT, CAST, (TYPE)(a - b)); } \
static Option bl_umul_checked_##SUFFIX(TYPE a, TYPE b){ if (b != 0 && a > (TYPE)((MAXV) / b)) return BL_OPTION_NONE(); return BL_OPTION_SOME(SLOT, CAST, (TYPE)(a * b)); }
BL_DEFINE_SIGNED_CHECKED_ARITH(i8, int8_t, INT8_MIN, INT8_MAX, i, int64_t)
BL_DEFINE_SIGNED_CHECKED_ARITH(i16, int16_t, INT16_MIN, INT16_MAX, i, int64_t)
BL_DEFINE_SIGNED_CHECKED_ARITH(i32, int32_t, INT32_MIN, INT32_MAX, i, int64_t)
BL_DEFINE_SIGNED_CHECKED_ARITH(i64, int64_t, INT64_MIN, INT64_MAX, i, int64_t)
BL_DEFINE_SIGNED_CHECKED_ARITH(i128, __int128, bl_i128_min(), bl_i128_max(), i128, __int128)
BL_DEFINE_SIGNED_CHECKED_ARITH(isize, intptr_t, INTPTR_MIN, INTPTR_MAX, i, int64_t)
BL_DEFINE_UNSIGNED_CHECKED_ARITH(u8, uint8_t, UINT8_MAX, u, uint64_t)
BL_DEFINE_UNSIGNED_CHECKED_ARITH(u16, uint16_t, UINT16_MAX, u, uint64_t)
BL_DEFINE_UNSIGNED_CHECKED_ARITH(u32, uint32_t, UINT32_MAX, u, uint64_t)
BL_DEFINE_UNSIGNED_CHECKED_ARITH(u64, uint64_t, UINT64_MAX, u, uint64_t)
BL_DEFINE_UNSIGNED_CHECKED_ARITH(u128, unsigned __int128, ~((unsigned __int128)0), u128, unsigned __int128)
BL_DEFINE_UNSIGNED_CHECKED_ARITH(usize, uintptr_t, UINTPTR_MAX, u, uint64_t)
#undef BL_OPTION_NONE
#undef BL_OPTION_SOME
#undef BL_DEFINE_SIGNED_CHECKED_ARITH
#undef BL_DEFINE_UNSIGNED_CHECKED_ARITH
// --- Collection types (opaque handles) ---
typedef struct { void* data; size_t len; size_t cap; size_t front; } VecDeque;
typedef struct { void* buckets; size_t len; size_t cap; } HashSet;
// --- HashSet stubs (opaque, tracks membership via linear scan) ---
static HashSet build_hset_new(void) {
HashSet h = { NULL, 0, 0 };
return h;
}
static void build_hset_insert(HashSet h, BuildString val) {
(void)h; (void)val; // stub - full impl needs hash table
}
static bool build_hset_contains(HashSet h, BuildString val) {
(void)h; (void)val;
return false; // stub - full impl needs hash table
}
// --- VecDeque stub ---
static VecDeque build_vdeque_new(void) {
VecDeque d = { NULL, 0, 0, 0 };
return d;
}
// --- Type aliases ---
typedef BuildString string;
typedef uint64_t Time;
typedef uint64_t Duration;
typedef uint64_t Instant;
static BuildString build_string_new(const char* s) {
BuildString qs;
qs.ptr = s;
qs.len = strlen(s);
qs.cap = 0; // literal, not owned
return qs;
}
static BuildString build_string_concat(BuildString a, BuildString b) {
size_t new_len = a.len + b.len;
char* buf = (char*)malloc(new_len + 1);
memcpy(buf, a.ptr, a.len);
memcpy(buf + a.len, b.ptr, b.len);
buf[new_len] = '\0';
BuildString qs;
qs.ptr = buf;
qs.len = new_len;
qs.cap = new_len + 1;
return qs;
}
static size_t build_string_len(BuildString s) {
return s.len;
}
static bool build_string_eq(BuildString a, BuildString b) {
if (a.len != b.len) return false;
return memcmp(a.ptr, b.ptr, a.len) == 0;
}
/* Lexicographic byte comparison: negative, zero or positive, like strcmp,
for `<`, `<=`, `>` and `>=` on strings. A prefix sorts first. */
static int32_t build_string_cmp(BuildString a, BuildString b) {
size_t n = a.len < b.len ? a.len : b.len;
int c = n ? memcmp(a.ptr, b.ptr, n) : 0;
if (c != 0) return c < 0 ? -1 : 1;
if (a.len == b.len) return 0;
return a.len < b.len ? -1 : 1;
}
static void build_string_free(BuildString s) {
if (s.cap > 0) free((void*)s.ptr);
}
// Byte at index `i` of a string (as an int32), for `for c in s.chars()`.
static int32_t build_string_byte_at(BuildString s, size_t i) {
if (i >= s.len) return 0;
return (int32_t)(unsigned char)s.ptr[i];
}
// --- Bounds checking ---
// Rust checks every index against the length and panics on out-of-bounds, in
// release as well as debug. BuildLang follows that contract: an out-of-bounds
// index aborts with a diagnostic instead of reading or writing past the
// allocation. Exit code 101 matches a Rust panic. `bl_idx_chk` returns the
// validated index so a generated subscript reads `a[bl_idx_chk(i, n)]` and
// serves as both an rvalue and a store target; `bl_index_oob` is the shared
// abort the Vec runtime calls, where the index is already a size_t (a negative
// source index has wrapped, so it prints back through the signed cast).
static void bl_index_oob(long long index, size_t len) {
fprintf(stderr, "index out of bounds: the len is %llu but the index is %lld\n",
(unsigned long long)len, index);
exit(101);
}
static size_t bl_idx_chk(long long index, size_t len) {
if (index < 0 || (unsigned long long)index >= (unsigned long long)len) {
bl_index_oob(index, len);
}
return (size_t)index;
}
// --- Vec (dynamic array) type ---
typedef struct {
void* ptr;
size_t len;
size_t cap;
size_t elem_size;
} BuildVec;
static BuildVec build_vec_new(size_t elem_size) {
BuildVec v;
v.ptr = NULL;
v.len = 0;
v.cap = 0;
v.elem_size = elem_size;
return v;
}
static void build_vec_push(BuildVec* v, const void* elem) {
if (v->len >= v->cap) {
v->cap = v->cap == 0 ? 8 : v->cap * 2;
v->ptr = realloc(v->ptr, v->cap * v->elem_size);
}
memcpy((char*)v->ptr + v->len * v->elem_size, elem, v->elem_size);
v->len++;
}
static void* build_vec_get(BuildVec* v, size_t index) {
if (index >= v->len) bl_index_oob((long long)index, v->len);
return (char*)v->ptr + index * v->elem_size;
}
static void build_vec_free(BuildVec* v) {
free(v->ptr);
v->ptr = NULL;
v->len = 0;
v->cap = 0;
}
// --- Typed Vec helpers (wrapping BuildVec for specific element types) ---
static BuildVec build_vec_new_i32(void) { return build_vec_new(sizeof(int32_t)); }
static BuildVec build_vec_new_i64(void) { return build_vec_new(sizeof(int64_t)); }
static BuildVec build_vec_new_f64(void) { return build_vec_new(sizeof(double)); }
// Note: These wrappers use a global BuildVec pointer trick - the first
// argument is a BuildVec passed by value, but since BuildLang passes
// struct locals, the C compiler will place them on the stack where we
// can take their address. We use a thin wrapper to bridge the gap.
static BuildVec* __build_vec_ref = NULL;
static void build_vec_push_i32(BuildVec v, int32_t val) {
// Find the original local via the stored pointer (set by codegen)
// Fallback: push into a copy - but mutations won't be visible.
// The real solution: codegen passes &v. For now we use a global registry.
(void)v; (void)val;
}
// Simpler approach: heap-allocated vecs via a handle pattern
typedef struct { BuildVec* inner; } BuildVecHandle;
static BuildVecHandle build_hvec_new_i32(void) {
BuildVecHandle h;
h.inner = (BuildVec*)malloc(sizeof(BuildVec));
*h.inner = build_vec_new(sizeof(int32_t));
return h;
}
static void build_hvec_push_i32(BuildVecHandle h, int32_t val) { build_vec_push(h.inner, &val); }
static int32_t build_hvec_get_i32(BuildVecHandle h, size_t index) { return *(int32_t*)build_vec_get(h.inner, index); }
static size_t build_hvec_len(BuildVecHandle h) { return h.inner->len; }
static int32_t build_hvec_pop_i32(BuildVecHandle h) {
if (h.inner->len == 0) return 0;
h.inner->len--;
return *(int32_t*)((char*)h.inner->ptr + h.inner->len * h.inner->elem_size);
}
static void build_hvec_free(BuildVecHandle h) { build_vec_free(h.inner); free(h.inner); }
static int __build_cmp_i32(const void* a, const void* b) {
int32_t x = *(const int32_t*)a, y = *(const int32_t*)b;
return (x > y) - (x < y);
}
static int __build_cmp_i64(const void* a, const void* b) {
int64_t x = *(const int64_t*)a, y = *(const int64_t*)b;
return (x > y) - (x < y);
}
static int __build_cmp_f64(const void* a, const void* b) {
double x = *(const double*)a, y = *(const double*)b;
return (x > y) - (x < y);
}
static void build_hvec_sort_i32(BuildVecHandle h) {
if (h.inner->len > 1) qsort(h.inner->ptr, h.inner->len, sizeof(int32_t), __build_cmp_i32);
}
static void build_hvec_sort_i64(BuildVecHandle h) {
if (h.inner->len > 1) qsort(h.inner->ptr, h.inner->len, sizeof(int64_t), __build_cmp_i64);
}
static void build_hvec_sort_f64(BuildVecHandle h) {
if (h.inner->len > 1) qsort(h.inner->ptr, h.inner->len, sizeof(double), __build_cmp_f64);
}
// Storing out of bounds aborts through build_vec_get rather than silently
// dropping the write, matching Rust's `v[i] = x` panic.
static void build_hvec_set_i32(BuildVecHandle h, size_t i, int32_t val) {
*(int32_t*)build_vec_get(h.inner, i) = val;
}
static void build_hvec_set_i64(BuildVecHandle h, size_t i, int64_t val) {
*(int64_t*)build_vec_get(h.inner, i) = val;
}
static void build_hvec_set_f64(BuildVecHandle h, size_t i, double val) {
*(double*)build_vec_get(h.inner, i) = val;
}
static void build_hvec_set_str(BuildVecHandle h, size_t i, BuildString val) {
*(BuildString*)build_vec_get(h.inner, i) = val;
}
static bool build_hvec_contains_i32(BuildVecHandle h, int32_t val) {
for (size_t i = 0; i < h.inner->len; i++) {
if (*(int32_t*)build_vec_get(h.inner, i) == val) return true;
}
return false;
}
static bool build_hvec_contains_i64(BuildVecHandle h, int64_t val) {
for (size_t i = 0; i < h.inner->len; i++) {
if (*(int64_t*)build_vec_get(h.inner, i) == val) return true;
}
return false;
}
static bool build_hvec_contains_f64(BuildVecHandle h, double val) {
for (size_t i = 0; i < h.inner->len; i++) {
if (*(double*)build_vec_get(h.inner, i) == val) return true;
}
return false;
}
static bool build_hvec_contains_str(BuildVecHandle h, BuildString val) {
for (size_t i = 0; i < h.inner->len; i++) {
if (build_string_eq(*(BuildString*)build_vec_get(h.inner, i), val)) return true;
}
return false;
}
// f64 handle variants
static BuildVecHandle build_hvec_new_f64(void) {
BuildVecHandle h;
h.inner = (BuildVec*)malloc(sizeof(BuildVec));
*h.inner = build_vec_new(sizeof(double));
return h;
}
static void build_hvec_push_f64(BuildVecHandle h, double val) { build_vec_push(h.inner, &val); }
static double build_hvec_get_f64(BuildVecHandle h, size_t index) { return *(double*)build_vec_get(h.inner, index); }
static double build_hvec_pop_f64(BuildVecHandle h) {
if (h.inner->len == 0) return 0.0;
h.inner->len--;
return *(double*)((char*)h.inner->ptr + h.inner->len * h.inner->elem_size);
}
// i64 handle variants
static BuildVecHandle build_hvec_new_i64(void) {
BuildVecHandle h;
h.inner = (BuildVec*)malloc(sizeof(BuildVec));
*h.inner = build_vec_new(sizeof(int64_t));
return h;
}
static void build_hvec_push_i64(BuildVecHandle h, int64_t val) { build_vec_push(h.inner, &val); }
static int64_t build_hvec_get_i64(BuildVecHandle h, size_t index) { return *(int64_t*)build_vec_get(h.inner, index); }
static int64_t build_hvec_pop_i64(BuildVecHandle h) {
if (h.inner->len == 0) return 0;
h.inner->len--;
return *(int64_t*)((char*)h.inner->ptr + h.inner->len * h.inner->elem_size);
}
// --- Format string helpers (returns BuildString) ---
static BuildString build_format_i32(const char* fmt, int32_t v) {
char buf[64];
int n = snprintf(buf, sizeof(buf), fmt, v);
char* heap = (char*)malloc(n + 1);
memcpy(heap, buf, n + 1);
BuildString qs; qs.ptr = heap; qs.len = n; qs.cap = n + 1;
return qs;
}
static BuildString build_format_f64(const char* fmt, double v) {
char buf[128];
int n = snprintf(buf, sizeof(buf), fmt, v);
char* heap = (char*)malloc(n + 1);
memcpy(heap, buf, n + 1);
BuildString qs; qs.ptr = heap; qs.len = n; qs.cap = n + 1;
return qs;
}
static BuildString build_format_str(const char* fmt, const char* v) {
int n = snprintf(NULL, 0, fmt, v);
char* heap = (char*)malloc(n + 1);
snprintf(heap, n + 1, fmt, v);
BuildString qs; qs.ptr = heap; qs.len = n; qs.cap = n + 1;
return qs;
}
static BuildString build_i32_to_string(int32_t v) { return build_format_i32("%d", v); }
static BuildString build_i64_to_string(int64_t v) {
char buf[32];
int n = snprintf(buf, sizeof(buf), "%lld", (long long)v);
char* heap = (char*)malloc(n + 1);
memcpy(heap, buf, n + 1);
BuildString qs; qs.ptr = heap; qs.len = n; qs.cap = n + 1;
return qs;
}
static BuildString build_u64_to_string(uint64_t v) {
char buf[32];
int n = snprintf(buf, sizeof(buf), "%llu", (unsigned long long)v);
char* heap = (char*)malloc(n + 1);
memcpy(heap, buf, n + 1);
BuildString qs; qs.ptr = heap; qs.len = n; qs.cap = n + 1;
return qs;
}
static BuildString build_i128_to_string(__int128 v) {
char buf[64];
bl_fmt_i128_into(buf, v);
return build_format_str("%s", buf);
}
static BuildString build_u128_to_string(unsigned __int128 v) {
char buf[64];
bl_fmt_u128_into(buf, v);
return build_format_str("%s", buf);
}
static BuildString build_f64_to_string(double v) { return build_format_str("%s", bl_fmt_f64(v)); }
static BuildString build_f32_to_string(float v) { return build_format_str("%s", bl_fmt_f32(v)); }
// Variadic sprintf into a heap-owned BuildString. Backs the `format!` macro:
// the lowering builds a C printf-style format string and passes the same
// arguments it would to printf, but the result is captured as an owned string.
static BuildString build_sprintf(const char* fmt, ...) {
va_list args; va_start(args, fmt);
va_list args2; va_copy(args2, args);
int n = vsnprintf(NULL, 0, fmt, args);
va_end(args);
if (n < 0) { va_end(args2); return build_string_new(""); }
char* heap = (char*)malloc((size_t)n + 1);
vsnprintf(heap, (size_t)n + 1, fmt, args2);
va_end(args2);
BuildString qs; qs.ptr = heap; qs.len = (size_t)n; qs.cap = (size_t)n + 1;
return qs;
}
// --- Math constants ---
static const double BUILD_PI = 3.14159265358979323846;
static const double BUILD_E = 2.71828182845904523536;
static const double BUILD_TAU = 6.28318530717958647692;
// --- HashMap (i32 -> i32, open addressing with linear probing) ---
typedef struct {
int32_t* keys;
int32_t* values;
uint8_t* occupied;
size_t cap;
size_t len;
} BuildHashMap;
typedef struct { BuildHashMap* inner; } BuildMapHandle;
static BuildMapHandle build_map_new(void) {
BuildMapHandle h;
h.inner = (BuildHashMap*)malloc(sizeof(BuildHashMap));
h.inner->cap = 16;
h.inner->len = 0;
h.inner->keys = (int32_t*)calloc(16, sizeof(int32_t));
h.inner->values = (int32_t*)calloc(16, sizeof(int32_t));
h.inner->occupied = (uint8_t*)calloc(16, sizeof(uint8_t));
return h;
}
static void build_map_grow(BuildHashMap* m) {
size_t old_cap = m->cap;
int32_t* old_keys = m->keys;
int32_t* old_values = m->values;
uint8_t* old_occ = m->occupied;
m->cap *= 2;
m->len = 0;
m->keys = (int32_t*)calloc(m->cap, sizeof(int32_t));
m->values = (int32_t*)calloc(m->cap, sizeof(int32_t));
m->occupied = (uint8_t*)calloc(m->cap, sizeof(uint8_t));
for (size_t i = 0; i < old_cap; i++) {
if (old_occ[i]) {
uint32_t h = (uint32_t)old_keys[i] * 2654435761u;
size_t idx = h % m->cap;
while (m->occupied[idx]) idx = (idx + 1) % m->cap;
m->keys[idx] = old_keys[i];
m->values[idx] = old_values[i];
m->occupied[idx] = 1;
m->len++;
}
}
free(old_keys); free(old_values); free(old_occ);
}
static void build_map_insert(BuildMapHandle h, int32_t key, int32_t value) {
BuildHashMap* m = h.inner;
if (m->len * 4 >= m->cap * 3) build_map_grow(m);
uint32_t hash = (uint32_t)key * 2654435761u;
size_t idx = hash % m->cap;
while (m->occupied[idx]) {
if (m->keys[idx] == key) { m->values[idx] = value; return; }
idx = (idx + 1) % m->cap;
}
m->keys[idx] = key;
m->values[idx] = value;
m->occupied[idx] = 1;
m->len++;
}
static int32_t build_map_get(BuildMapHandle h, int32_t key, int32_t fallback) {
BuildHashMap* m = h.inner;
uint32_t hash = (uint32_t)key * 2654435761u;
size_t idx = hash % m->cap;
size_t start = idx;
while (m->occupied[idx]) {
if (m->keys[idx] == key) return m->values[idx];
idx = (idx + 1) % m->cap;
if (idx == start) break;
}
return fallback;
}
static bool build_map_contains(BuildMapHandle h, int32_t key) {
BuildHashMap* m = h.inner;
uint32_t hash = (uint32_t)key * 2654435761u;
size_t idx = hash % m->cap;
size_t start = idx;
while (m->occupied[idx]) {
if (m->keys[idx] == key) return true;
idx = (idx + 1) % m->cap;
if (idx == start) break;
}
return false;
}
static size_t build_map_len(BuildMapHandle h) { return h.inner->len; }
static bool build_map_remove(BuildMapHandle h, int32_t key) {
BuildHashMap* m = h.inner;
uint32_t hash = (uint32_t)key * 2654435761u;
size_t idx = hash % m->cap;
size_t start = idx;
while (m->occupied[idx]) {
if (m->keys[idx] == key) {
m->occupied[idx] = 0;
m->len--;
return true;
}
idx = (idx + 1) % m->cap;
if (idx == start) break;
}
return false;
}
// --- Typed HashMap: string key -> f64 value (open addressing, linear probing) ---
typedef struct {
char** keys; // heap-allocated copies of key strings
double* values;
uint8_t* occupied;
size_t cap;
size_t len;
} BuildStrF64Map;
typedef struct { BuildStrF64Map* inner; } BuildStrF64MapHandle;
typedef BuildStrF64MapHandle Map;
static uint32_t __build_hash_str(const char* s) {
uint32_t h = 2166136261u;
for (; *s; s++) { h ^= (uint8_t)*s; h *= 16777619u; }
return h;
}
static BuildStrF64MapHandle build_hmap_new_str_f64(void) {
BuildStrF64MapHandle h;
h.inner = (BuildStrF64Map*)malloc(sizeof(BuildStrF64Map));
h.inner->cap = 16;
h.inner->len = 0;
h.inner->keys = (char**)calloc(16, sizeof(char*));
h.inner->values = (double*)calloc(16, sizeof(double));
h.inner->occupied = (uint8_t*)calloc(16, sizeof(uint8_t));
return h;
}
// Collect a string-keyed map's keys into a Vec<String> handle, backing
// `m.keys()` (iteration order is bucket order, unspecified like Rust's).
static BuildVecHandle build_hmap_keys_str_f64(BuildStrF64MapHandle h) {
BuildVecHandle v;
v.inner = (BuildVec*)malloc(sizeof(BuildVec));
*v.inner = build_vec_new(sizeof(BuildString));
for (size_t __i = 0; __i < h.inner->cap; __i++) {
if (h.inner->occupied[__i]) {
BuildString __kbuf = build_string_new(h.inner->keys[__i]);
build_vec_push(v.inner, &__kbuf);
}
}
return v;
}
static void __build_hmap_grow_str_f64(BuildStrF64Map* m) {
size_t old_cap = m->cap;
char** old_keys = m->keys;
double* old_values = m->values;
uint8_t* old_occ = m->occupied;
m->cap *= 2;
m->len = 0;
m->keys = (char**)calloc(m->cap, sizeof(char*));
m->values = (double*)calloc(m->cap, sizeof(double));
m->occupied = (uint8_t*)calloc(m->cap, sizeof(uint8_t));
for (size_t i = 0; i < old_cap; i++) {
if (old_occ[i]) {
uint32_t hash = __build_hash_str(old_keys[i]);
size_t idx = hash % m->cap;
while (m->occupied[idx]) idx = (idx + 1) % m->cap;
m->keys[idx] = old_keys[i]; // transfer ownership
m->values[idx] = old_values[i];
m->occupied[idx] = 1;
m->len++;
}
}
free(old_keys); free(old_values); free(old_occ);
}
static void build_hmap_insert_str_f64(BuildStrF64MapHandle h, const char* key, double value) {
BuildStrF64Map* m = h.inner;
if (m->len * 4 >= m->cap * 3) __build_hmap_grow_str_f64(m);
uint32_t hash = __build_hash_str(key);
size_t idx = hash % m->cap;
while (m->occupied[idx]) {
if (strcmp(m->keys[idx], key) == 0) { m->values[idx] = value; return; }
idx = (idx + 1) % m->cap;
}
size_t klen = strlen(key);
m->keys[idx] = (char*)malloc(klen + 1);
memcpy(m->keys[idx], key, klen + 1);
m->values[idx] = value;
m->occupied[idx] = 1;
m->len++;
}
static double build_hmap_get_str_f64(BuildStrF64MapHandle h, const char* key) {
BuildStrF64Map* m = h.inner;
uint32_t hash = __build_hash_str(key);
size_t idx = hash % m->cap;
size_t start = idx;
while (m->occupied[idx]) {
if (strcmp(m->keys[idx], key) == 0) return m->values[idx];
idx = (idx + 1) % m->cap;
if (idx == start) break;
}
return 0.0;
}
static bool build_hmap_contains_str_f64(BuildStrF64MapHandle h, const char* key) {
BuildStrF64Map* m = h.inner;
uint32_t hash = __build_hash_str(key);
size_t idx = hash % m->cap;
size_t start = idx;
while (m->occupied[idx]) {
if (strcmp(m->keys[idx], key) == 0) return true;
idx = (idx + 1) % m->cap;
if (idx == start) break;
}
return false;
}
static bool build_hmap_remove_str_f64(BuildStrF64MapHandle h, const char* key) {
BuildStrF64Map* m = h.inner;
uint32_t hash = __build_hash_str(key);
size_t idx = hash % m->cap;
size_t start = idx;
while (m->occupied[idx]) {
if (strcmp(m->keys[idx], key) == 0) {
free(m->keys[idx]);
m->keys[idx] = NULL;
m->occupied[idx] = 0;
m->len--;
return true;
}
idx = (idx + 1) % m->cap;
if (idx == start) break;
}
return false;
}
static size_t build_hmap_len_str_f64(BuildStrF64MapHandle h) { return h.inner->len; }
// BuildString-accepting wrappers (used by method dispatch which
// passes BuildString values, not const char* pointers).
static void build_hmap_insert_qs(BuildStrF64MapHandle h, BuildString key, double value) {
build_hmap_insert_str_f64(h, key.ptr, value);
}
static double build_hmap_get_qs(BuildStrF64MapHandle h, BuildString key) {
return build_hmap_get_str_f64(h, key.ptr);
}
static bool build_hmap_contains_qs(BuildStrF64MapHandle h, BuildString key) {
return build_hmap_contains_str_f64(h, key.ptr);
}
static bool build_hmap_remove_qs(BuildStrF64MapHandle h, BuildString key) {
return build_hmap_remove_str_f64(h, key.ptr);
}
// --- Typed HashMap: str key -> str value (reuses StrF64Map, stores ptr in double bits) ---
static void build_hmap_insert_str_str(BuildStrF64MapHandle h, const char* key, BuildString value) {
// Store BuildString pointer bits in the double slot (safe on 64-bit)
double d;
memcpy(&d, &value, sizeof(d) > sizeof(value) ? sizeof(value) : sizeof(d));
build_hmap_insert_str_f64(h, key, d);
}
static BuildString build_hmap_get_str_str(BuildStrF64MapHandle h, const char* key) {
double d = build_hmap_get_str_f64(h, key);
BuildString s;
memset(&s, 0, sizeof(s));
memcpy(&s, &d, sizeof(d) > sizeof(s) ? sizeof(s) : sizeof(d));
return s;
}
// --- Typed HashMap: str key -> i64 value (stores i64 in double bits) ---
static void build_hmap_insert_str_i64(BuildStrF64MapHandle h, const char* key, int64_t value) {
double d;
memcpy(&d, &value, sizeof(d));
build_hmap_insert_str_f64(h, key, d);
}
static int64_t build_hmap_get_str_i64(BuildStrF64MapHandle h, const char* key) {
double d = build_hmap_get_str_f64(h, key);
int64_t v;
memcpy(&v, &d, sizeof(v));
return v;
}
// --- Typed HashMap: str key -> generic 8-byte value (for Vec/Struct values) ---
static void build_hmap_insert_str_gen(BuildStrF64MapHandle h, const char* key, void* value_ptr, size_t value_size) {
double d = 0;
memcpy(&d, value_ptr, value_size < sizeof(d) ? value_size : sizeof(d));
build_hmap_insert_str_f64(h, key, d);
}
static void build_hmap_get_str_gen(BuildStrF64MapHandle h, const char* key, void* out, size_t out_size) {
double d = build_hmap_get_str_f64(h, key);
memcpy(out, &d, out_size < sizeof(d) ? out_size : sizeof(d));
}
// --- Typed HashMap: i64 key -> f64 value ---
typedef struct {
int64_t* keys;
double* values;
uint8_t* occupied;
size_t cap;
size_t len;
} BuildI64F64Map;
typedef struct { BuildI64F64Map* inner; } BuildI64F64MapHandle;
static BuildI64F64MapHandle build_hmap_new_i64_f64(void) {
BuildI64F64MapHandle h;
h.inner = (BuildI64F64Map*)malloc(sizeof(BuildI64F64Map));
h.inner->cap = 16;
h.inner->len = 0;
h.inner->keys = (int64_t*)calloc(16, sizeof(int64_t));
h.inner->values = (double*)calloc(16, sizeof(double));
h.inner->occupied = (uint8_t*)calloc(16, sizeof(uint8_t));
return h;
}
static void __build_hmap_grow_i64_f64(BuildI64F64Map* m) {
size_t old_cap = m->cap;
int64_t* old_keys = m->keys;
double* old_values = m->values;
uint8_t* old_occ = m->occupied;
m->cap *= 2;
m->len = 0;
m->keys = (int64_t*)calloc(m->cap, sizeof(int64_t));
m->values = (double*)calloc(m->cap, sizeof(double));
m->occupied = (uint8_t*)calloc(m->cap, sizeof(uint8_t));
for (size_t i = 0; i < old_cap; i++) {
if (old_occ[i]) {
uint32_t hash = (uint32_t)((uint64_t)old_keys[i] * 2654435761u);
size_t idx = hash % m->cap;
while (m->occupied[idx]) idx = (idx + 1) % m->cap;
m->keys[idx] = old_keys[i];
m->values[idx] = old_values[i];
m->occupied[idx] = 1;
m->len++;
}
}
free(old_keys); free(old_values); free(old_occ);
}
static void build_hmap_insert_i64_f64(BuildI64F64MapHandle h, int64_t key, double value) {
BuildI64F64Map* m = h.inner;
if (m->len * 4 >= m->cap * 3) __build_hmap_grow_i64_f64(m);
uint32_t hash = (uint32_t)((uint64_t)key * 2654435761u);
size_t idx = hash % m->cap;
while (m->occupied[idx]) {
if (m->keys[idx] == key) { m->values[idx] = value; return; }
idx = (idx + 1) % m->cap;
}
m->keys[idx] = key;
m->values[idx] = value;
m->occupied[idx] = 1;
m->len++;
}
static double build_hmap_get_i64_f64(BuildI64F64MapHandle h, int64_t key) {
BuildI64F64Map* m = h.inner;
uint32_t hash = (uint32_t)((uint64_t)key * 2654435761u);
size_t idx = hash % m->cap;
size_t start = idx;
while (m->occupied[idx]) {
if (m->keys[idx] == key) return m->values[idx];
idx = (idx + 1) % m->cap;
if (idx == start) break;
}
return 0.0;
}
static bool build_hmap_contains_i64_f64(BuildI64F64MapHandle h, int64_t key) {
BuildI64F64Map* m = h.inner;
uint32_t hash = (uint32_t)((uint64_t)key * 2654435761u);
size_t idx = hash % m->cap;
size_t start = idx;
while (m->occupied[idx]) {
if (m->keys[idx] == key) return true;
idx = (idx + 1) % m->cap;
if (idx == start) break;
}
return false;
}
static bool build_hmap_remove_i64_f64(BuildI64F64MapHandle h, int64_t key) {
BuildI64F64Map* m = h.inner;
uint32_t hash = (uint32_t)((uint64_t)key * 2654435761u);
size_t idx = hash % m->cap;
size_t start = idx;
while (m->occupied[idx]) {
if (m->keys[idx] == key) {
m->occupied[idx] = 0;
m->len--;
return true;
}
idx = (idx + 1) % m->cap;
if (idx == start) break;
}
return false;
}
static size_t build_hmap_len_i64_f64(BuildI64F64MapHandle h) { return h.inner->len; }
// --- Print formatting helpers ---
// Use snprintf + __build_write for reliable output under MinTTY/git-bash.
static void build_print_i32(int32_t v) { printf("%d", v); }
static void build_print_i64(int64_t v) { printf("%lld", (long long)v); }
static void build_print_f32(float v) { printf("%s", bl_fmt_f32(v)); }
static void build_print_f64(double v) { printf("%s", bl_fmt_f64(v)); }
static void build_print_bool(bool v) { printf("%s", v ? "true" : "false"); }
static void build_print_str(const char* v) { printf("%s", v); }
static void build_print_string(BuildString v) { printf("%.*s", (int)v.len, v.ptr); }
static void build_print_char(char v) { printf("%c", v); }
// --- Math built-in helpers ---
static int32_t build_min_i32(int32_t a, int32_t b) { return a < b ? a : b; }
static int32_t build_max_i32(int32_t a, int32_t b) { return a > b ? a : b; }
static int64_t build_min_i64(int64_t a, int64_t b) { return a < b ? a : b; }
static int64_t build_max_i64(int64_t a, int64_t b) { return a > b ? a : b; }
static double build_min_f64(double a, double b) { return a < b ? a : b; }
static double build_max_f64(double a, double b) { return a > b ? a : b; }
static float build_min_f32(float a, float b) { return a < b ? a : b; }
static float build_max_f32(float a, float b) { return a > b ? a : b; }
// --- Vector Math Types ---
typedef struct { double x, y; } build_vec2;
typedef struct { double x, y, z; } build_vec3;
typedef struct { double x, y, z, w; } build_vec4;
typedef struct { double m[4][4]; } build_mat4;
// Constructors
static build_vec2 build_vec2_new(double x, double y) { return (build_vec2){x, y}; }
static build_vec3 build_vec3_new(double x, double y, double z) { return (build_vec3){x, y, z}; }
static build_vec4 build_vec4_new(double x, double y, double z, double w) { return (build_vec4){x, y, z, w}; }
// Vector dot product
static double build_dot2(build_vec2 a, build_vec2 b) { return a.x*b.x + a.y*b.y; }
static double build_dot3(build_vec3 a, build_vec3 b) { return a.x*b.x + a.y*b.y + a.z*b.z; }
static double build_dot4(build_vec4 a, build_vec4 b) { return a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w; }
// Vector length
static double build_length2(build_vec2 v) { return sqrt(build_dot2(v, v)); }
static double build_length3(build_vec3 v) { return sqrt(build_dot3(v, v)); }
static double build_length4(build_vec4 v) { return sqrt(build_dot4(v, v)); }
// Vector normalize
static build_vec2 build_normalize2(build_vec2 v) { double l = build_length2(v); return (build_vec2){v.x/l, v.y/l}; }
static build_vec3 build_normalize3(build_vec3 v) { double l = build_length3(v); return (build_vec3){v.x/l, v.y/l, v.z/l}; }
static build_vec4 build_normalize4(build_vec4 v) { double l = build_length4(v); return (build_vec4){v.x/l, v.y/l, v.z/l, v.w/l}; }
// Cross product (vec3 only)
static build_vec3 build_cross(build_vec3 a, build_vec3 b) {
return (build_vec3){a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x};
}
// Reflect
static build_vec3 build_reflect3(build_vec3 v, build_vec3 n) {
double d = build_dot3(v, n);
return (build_vec3){v.x - 2.0*d*n.x, v.y - 2.0*d*n.y, v.z - 2.0*d*n.z};
}
// Lerp
static build_vec2 build_lerp2(build_vec2 a, build_vec2 b, double t) {
return (build_vec2){a.x + (b.x-a.x)*t, a.y + (b.y-a.y)*t};
}
static build_vec3 build_lerp3(build_vec3 a, build_vec3 b, double t) {
return (build_vec3){a.x + (b.x-a.x)*t, a.y + (b.y-a.y)*t, a.z + (b.z-a.z)*t};
}
static build_vec4 build_lerp4(build_vec4 a, build_vec4 b, double t) {
return (build_vec4){a.x + (b.x-a.x)*t, a.y + (b.y-a.y)*t, a.z + (b.z-a.z)*t, a.w + (b.w-a.w)*t};
}
// Vec2 arithmetic
static build_vec2 build_vec2_add(build_vec2 a, build_vec2 b) { return (build_vec2){a.x+b.x, a.y+b.y}; }
static build_vec2 build_vec2_sub(build_vec2 a, build_vec2 b) { return (build_vec2){a.x-b.x, a.y-b.y}; }
static build_vec2 build_vec2_mul(build_vec2 a, build_vec2 b) { return (build_vec2){a.x*b.x, a.y*b.y}; }
static build_vec2 build_vec2_scale(build_vec2 v, double s) { return (build_vec2){v.x*s, v.y*s}; }
static build_vec2 build_vec2_neg(build_vec2 v) { return (build_vec2){-v.x, -v.y}; }
// Vec3 arithmetic
static build_vec3 build_vec3_add(build_vec3 a, build_vec3 b) { return (build_vec3){a.x+b.x, a.y+b.y, a.z+b.z}; }
static build_vec3 build_vec3_sub(build_vec3 a, build_vec3 b) { return (build_vec3){a.x-b.x, a.y-b.y, a.z-b.z}; }
static build_vec3 build_vec3_mul(build_vec3 a, build_vec3 b) { return (build_vec3){a.x*b.x, a.y*b.y, a.z*b.z}; }
static build_vec3 build_vec3_scale(build_vec3 v, double s) { return (build_vec3){v.x*s, v.y*s, v.z*s}; }
static build_vec3 build_vec3_neg(build_vec3 v) { return (build_vec3){-v.x, -v.y, -v.z}; }
// Vec4 arithmetic
static build_vec4 build_vec4_add(build_vec4 a, build_vec4 b) { return (build_vec4){a.x+b.x, a.y+b.y, a.z+b.z, a.w+b.w}; }
static build_vec4 build_vec4_sub(build_vec4 a, build_vec4 b) { return (build_vec4){a.x-b.x, a.y-b.y, a.z-b.z, a.w-b.w}; }
static build_vec4 build_vec4_mul(build_vec4 a, build_vec4 b) { return (build_vec4){a.x*b.x, a.y*b.y, a.z*b.z, a.w*b.w}; }
static build_vec4 build_vec4_scale(build_vec4 v, double s) { return (build_vec4){v.x*s, v.y*s, v.z*s, v.w*s}; }
static build_vec4 build_vec4_neg(build_vec4 v) { return (build_vec4){-v.x, -v.y, -v.z, -v.w}; }
// --- Mat4 operations ---
static build_mat4 build_mat4_identity(void) {
build_mat4 m = {{{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}}};
return m;
}
static build_mat4 build_mat4_mul(build_mat4 a, build_mat4 b) {
build_mat4 r = {{{0}}};
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
for (int k = 0; k < 4; k++)
r.m[i][j] += a.m[i][k] * b.m[k][j];
return r;
}
static build_vec4 build_mat4_mul_vec4(build_mat4 m, build_vec4 v) {
return (build_vec4){
m.m[0][0]*v.x + m.m[0][1]*v.y + m.m[0][2]*v.z + m.m[0][3]*v.w,
m.m[1][0]*v.x + m.m[1][1]*v.y + m.m[1][2]*v.z + m.m[1][3]*v.w,
m.m[2][0]*v.x + m.m[2][1]*v.y + m.m[2][2]*v.z + m.m[2][3]*v.w,
m.m[3][0]*v.x + m.m[3][1]*v.y + m.m[3][2]*v.z + m.m[3][3]*v.w
};
}
static build_mat4 build_mat4_translate(build_vec3 t) {
build_mat4 m = build_mat4_identity();
m.m[0][3] = t.x; m.m[1][3] = t.y; m.m[2][3] = t.z;
return m;
}
static build_mat4 build_mat4_scale(build_vec3 s) {
build_mat4 m = {{{s.x,0,0,0},{0,s.y,0,0},{0,0,s.z,0},{0,0,0,1}}};
return m;
}
static build_mat4 build_mat4_perspective(double fov, double aspect, double near_val, double far_val) {
double f = 1.0 / tan(fov * 0.5);
build_mat4 m = {{{0}}};
m.m[0][0] = f / aspect;
m.m[1][1] = f;
m.m[2][2] = (far_val + near_val) / (near_val - far_val);
m.m[2][3] = (2.0 * far_val * near_val) / (near_val - far_val);
m.m[3][2] = -1.0;
return m;
}
// --- Shader math functions ---
static double build_clampf(double x, double lo, double hi) { return x < lo ? lo : (x > hi ? hi : x); }
static build_vec3 build_clamp3(build_vec3 v, double lo, double hi) {
return (build_vec3){build_clampf(v.x, lo, hi), build_clampf(v.y, lo, hi), build_clampf(v.z, lo, hi)};
}
static double build_smoothstep(double edge0, double edge1, double x) {
double t = build_clampf((x - edge0) / (edge1 - edge0), 0.0, 1.0);
return t * t * (3.0 - 2.0 * t);
}
static double build_mix(double a, double b, double t) { return a + (b - a) * t; }
static double build_fract(double x) { return x - floor(x); }
static double build_step(double edge, double x) { return x < edge ? 0.0 : 1.0; }
static double build_saturate(double x) { return x < 0.0 ? 0.0 : (x > 1.0 ? 1.0 : x); }
// --- Effect handler runtime (setjmp/longjmp based) ---
#include <setjmp.h>
// Effect handler stack
typedef struct BuildHandler {
jmp_buf env;
int32_t effect_id;
void* handler_data;
struct BuildHandler* parent;
} BuildHandler;
// Global handler stack
static BuildHandler* __build_handler_stack = NULL;
// Push a handler onto the stack
static void build_push_handler(BuildHandler* h, int32_t effect_id) {
h->effect_id = effect_id;
h->handler_data = NULL;
h->parent = __build_handler_stack;
__build_handler_stack = h;
}
// Pop a handler from the stack
static void build_pop_handler(void) {
if (__build_handler_stack) {
__build_handler_stack = __build_handler_stack->parent;
}
}
// Perform an effect operation - jumps to the nearest handler
static void build_perform(int32_t effect_id, int32_t op_id, void* arg, void* result) {
BuildHandler* h = __build_handler_stack;
while (h) {
if (h->effect_id == effect_id) {
h->handler_data = arg;
longjmp(h->env, op_id + 1); // +1 because setjmp returns 0 on first call
}
h = h->parent;
}
// Unhandled effect - abort
fprintf(stderr, "Unhandled effect %d operation %d\n", effect_id, op_id);
abort();
}
// --- File I/O ---
static BuildString build_read_file(const char* path) {
FILE* f = fopen(path, "rb");
if (!f) return build_string_new("");
fseek(f, 0, SEEK_END);
long len = ftell(f);
fseek(f, 0, SEEK_SET);
char* buf = (char*)malloc(len + 1);
fread(buf, 1, len, f);
buf[len] = '\0';
fclose(f);
BuildString qs;
qs.ptr = buf;
qs.len = (size_t)len;
qs.cap = (size_t)(len + 1);
return qs;
}
static bool build_write_file(const char* path, const char* content) {
FILE* f = fopen(path, "wb");
if (!f) return false;
size_t len = strlen(content);
size_t written = fwrite(content, 1, len, f);
fclose(f);
return written == len;
}
static bool build_file_exists(const char* path) {
FILE* f = fopen(path, "rb");
if (f) { fclose(f); return true; }
return false;
}
// --- Binary file I/O ---
static bool build_write_bytes(const char* path, const char* data, int64_t len) {
FILE* f = fopen(path, "wb");
if (!f) return false;
fwrite(data, 1, (size_t)len, f);
fclose(f);
return true;
}
static BuildString build_read_bytes(const char* path) {
FILE* f = fopen(path, "rb");
if (!f) return build_string_new("");
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
char* buf = (char*)malloc(sz + 1);
fread(buf, 1, sz, f);
buf[sz] = 0;
fclose(f);
BuildString s;
s.ptr = buf;
s.len = (int64_t)sz;
s.cap = (int64_t)sz + 1;
return s;
}
static bool build_append_file(const char* path, const char* data) {
FILE* f = fopen(path, "ab");
if (!f) return false;
size_t len = strlen(data);
fwrite(data, 1, len, f);
fclose(f);
return true;
}
// --- Process / Environment ---
static int32_t build_exit(int32_t code) {
exit(code);
return code; // unreachable
}
// --- Graphics Stub (Vulkan helper) ---
// Minimal stub that prints what a real Vulkan backend would do.
// Used for testing the FFI integration pattern.
// When connected to a real Vulkan backend, these are replaced by
// linking against vulkan_helper.c / the Vulkan SDK.
typedef struct {
int32_t initialized;
int32_t width;
int32_t height;
int32_t frame_count;
int32_t should_close;
} BuildGfxContext;
static BuildGfxContext __build_gfx_ctx = {0, 0, 0, 0, 0};
static int32_t build_gfx_init(int32_t width, int32_t height, const char* title) {
printf("[GFX] Initializing %dx%d window: %s\n", width, height, title);
__build_gfx_ctx.initialized = 1;
__build_gfx_ctx.width = width;
__build_gfx_ctx.height = height;
__build_gfx_ctx.frame_count = 0;
__build_gfx_ctx.should_close = 0;
printf("[GFX] Vulkan instance created\n");
printf("[GFX] Physical device selected\n");
printf("[GFX] Logical device created\n");
printf("[GFX] Swapchain created (%dx%d)\n", width, height);
return 1;
}
static int32_t build_gfx_load_shader(const char* path, int32_t stage) {
printf("[GFX] Loading shader: %s (stage=%s)\n", path, stage == 0 ? "vertex" : "fragment");
return 1;
}
static int32_t build_gfx_create_pipeline(int32_t vertex_shader, int32_t fragment_shader) {
printf("[GFX] Creating graphics pipeline (vs=%d, fs=%d)\n", vertex_shader, fragment_shader);
return 1;
}
static void build_gfx_begin_frame(void) {
__build_gfx_ctx.frame_count++;
if (__build_gfx_ctx.frame_count <= 3) {
printf("[GFX] Begin frame %d\n", __build_gfx_ctx.frame_count);
}
}
static void build_gfx_clear(float r, float g, float b, float a) {
if (__build_gfx_ctx.frame_count <= 3) {
printf("[GFX] Clear (%.1f, %.1f, %.1f, %.1f)\n", r, g, b, a);
}
}
static void build_gfx_draw(int32_t vertex_count) {
if (__build_gfx_ctx.frame_count <= 3) {
printf("[GFX] Draw %d vertices\n", vertex_count);
}
}
static void build_gfx_end_frame(void) {
if (__build_gfx_ctx.frame_count <= 3) {
printf("[GFX] End frame %d\n", __build_gfx_ctx.frame_count);
}
if (__build_gfx_ctx.frame_count >= 3) {
__build_gfx_ctx.should_close = 1;
}
}
static int32_t build_gfx_should_close(void) {
return __build_gfx_ctx.should_close;
}
static void build_gfx_shutdown(void) {
printf("[GFX] Shutdown complete (%d frames rendered)\n", __build_gfx_ctx.frame_count);
__build_gfx_ctx.initialized = 0;
}
// --- String method helpers ---
static bool build_string_is_empty(BuildString s) {
return s.len == 0;
}
static bool build_string_starts_with(BuildString s, BuildString prefix) {
if (prefix.len > s.len) return false;
return memcmp(s.ptr, prefix.ptr, prefix.len) == 0;
}
static bool build_string_ends_with(BuildString s, BuildString suffix) {
if (suffix.len > s.len) return false;
return memcmp(s.ptr + s.len - suffix.len, suffix.ptr, suffix.len) == 0;
}
static bool build_string_contains(BuildString s, BuildString substr) {
if (substr.len == 0) return true;
if (substr.len > s.len) return false;
for (size_t i = 0; i <= s.len - substr.len; i++) {
if (memcmp(s.ptr + i, substr.ptr, substr.len) == 0) return true;
}
return false;
}
static BuildString build_string_to_upper(BuildString s) {
char* buf = (char*)malloc(s.len + 1);
for (size_t i = 0; i < s.len; i++) buf[i] = (char)toupper((unsigned char)s.ptr[i]);
buf[s.len] = '\0';
BuildString qs; qs.ptr = buf; qs.len = s.len; qs.cap = s.len + 1;
return qs;
}
static BuildString build_string_to_lower(BuildString s) {
char* buf = (char*)malloc(s.len + 1);
for (size_t i = 0; i < s.len; i++) buf[i] = (char)tolower((unsigned char)s.ptr[i]);
buf[s.len] = '\0';
BuildString qs; qs.ptr = buf; qs.len = s.len; qs.cap = s.len + 1;
return qs;
}
static BuildString build_string_trim(BuildString s) {
size_t start = 0;
while (start < s.len && isspace((unsigned char)s.ptr[start])) start++;
size_t end = s.len;
while (end > start && isspace((unsigned char)s.ptr[end - 1])) end--;
size_t new_len = end - start;
char* buf = (char*)malloc(new_len + 1);
memcpy(buf, s.ptr + start, new_len);
buf[new_len] = '\0';
BuildString qs; qs.ptr = buf; qs.len = new_len; qs.cap = new_len + 1;
return qs;
}
static BuildVec build_string_split(BuildString s, BuildString delim) {
BuildVec v = build_vec_new(sizeof(BuildString));
if (delim.len == 0) {
build_vec_push(&v, &s);
return v;
}
size_t start = 0;
/* `i + delim.len <= s.len`, not `i <= s.len - delim.len`: the size_t
subtraction wraps when the string is shorter than the delimiter
("".split(" ")), and the loop then reads far past the buffer. */
for (size_t i = 0; i + delim.len <= s.len; i++) {
if (memcmp(s.ptr + i, delim.ptr, delim.len) == 0) {
size_t part_len = i - start;
char* buf = (char*)malloc(part_len + 1);
memcpy(buf, s.ptr + start, part_len);
buf[part_len] = '\0';
BuildString part; part.ptr = buf; part.len = part_len; part.cap = part_len + 1;
build_vec_push(&v, &part);
start = i + delim.len;
i = start - 1; // loop will increment
}
}
// trailing part
size_t part_len = s.len - start;
char* buf = (char*)malloc(part_len + 1);
memcpy(buf, s.ptr + start, part_len);
buf[part_len] = '\0';
BuildString part; part.ptr = buf; part.len = part_len; part.cap = part_len + 1;
build_vec_push(&v, &part);
return v;
}
static BuildVec build_string_split_ws(BuildString s) {
BuildVec v = build_vec_new(sizeof(BuildString));
size_t i = 0;
while (i < s.len) {
while (i < s.len && isspace((unsigned char)s.ptr[i])) i++;
if (i >= s.len) break;
size_t start = i;
while (i < s.len && !isspace((unsigned char)s.ptr[i])) i++;
size_t part_len = i - start;
char* buf = (char*)malloc(part_len + 1);
memcpy(buf, s.ptr + start, part_len);
buf[part_len] = '\0';
BuildString part; part.ptr = buf; part.len = part_len; part.cap = part_len + 1;
build_vec_push(&v, &part);
}
return v;
}
static BuildVec build_string_lines(BuildString s) {
BuildString delim; delim.ptr = "\n"; delim.len = 1; delim.cap = 0;
return build_string_split(s, delim);
}
// Handle-returning split variants: box the BuildVec so the result is a proper
// Vec<String> (BuildVecHandle), integrating with build_hvec_len / build_hvec_get_str
// / for-loop iteration / indexing.
static BuildVecHandle build_string_split_h(BuildString s, BuildString delim) {
BuildVecHandle h; h.inner = (BuildVec*)malloc(sizeof(BuildVec));
*h.inner = build_string_split(s, delim); return h;
}
static BuildVecHandle build_string_split_ws_h(BuildString s) {
BuildVecHandle h; h.inner = (BuildVec*)malloc(sizeof(BuildVec));
*h.inner = build_string_split_ws(s); return h;
}
static BuildVecHandle build_string_lines_h(BuildString s) {
BuildVecHandle h; h.inner = (BuildVec*)malloc(sizeof(BuildVec));
*h.inner = build_string_lines(s); return h;
}
// --- Command-line arguments ---
#ifdef _WIN32
#include <io.h>
#define BUILD_ISATTY _isatty
#define BUILD_FILENO _fileno
#else
#include <unistd.h>
#define BUILD_ISATTY isatty
#define BUILD_FILENO fileno
#endif
static BuildVec BUILD_ARGS;
static int BUILD_ARGC = 0;
static BuildString build_string_from_cstr(const char* s) {
size_t len = strlen(s);
char* buf = (char*)malloc(len + 1);
memcpy(buf, s, len + 1);
BuildString qs; qs.ptr = buf; qs.len = len; qs.cap = len + 1;
return qs;
}
static void build_args_init(int argc, char** argv) {
BUILD_ARGC = argc;
BUILD_ARGS = build_vec_new(sizeof(BuildString));
for (int i = 0; i < argc; i++) {
BuildString s = build_string_from_cstr(argv[i]);
build_vec_push(&BUILD_ARGS, &s);
}
}
static int64_t build_args_count(void) {
return (int64_t)BUILD_ARGC;
}
static BuildString build_args_get(int64_t index) {
if (index < 0 || index >= BUILD_ARGC) {
return build_string_new("");
}
return *(BuildString*)build_vec_get(&BUILD_ARGS, (size_t)index);
}
// --- Stdin reading ---
static BuildString build_read_line(void) {
char buf[4096];
if (fgets(buf, sizeof(buf), stdin) == NULL) {
return build_string_new("");
}
return build_string_from_cstr(buf);
}
static BuildString build_read_all(void) {
size_t cap = 4096;
size_t len = 0;
char* buf = (char*)malloc(cap);
while (1) {
size_t n = fread(buf + len, 1, cap - len, stdin);
len += n;
if (n == 0) break;
if (len >= cap) {
cap *= 2;
buf = (char*)realloc(buf, cap);
}
}
buf[len] = '\0';
BuildString qs; qs.ptr = buf; qs.len = len; qs.cap = cap;
return qs;
}
static bool build_stdin_is_pipe(void) {
return !BUILD_ISATTY(BUILD_FILENO(stdin));
}
// --- Extended string operations ---
static int64_t build_string_parse_int(BuildString s) {
return (int64_t)atoll(s.ptr);
}
static double build_string_parse_float(BuildString s) {
return atof(s.ptr);
}
static BuildString build_string_char_at(BuildString s, int64_t idx) {
if (idx < 0 || (size_t)idx >= s.len) {
return build_string_new("");
}
char* buf = (char*)malloc(2);
buf[0] = s.ptr[idx];
buf[1] = '\0';
BuildString qs; qs.ptr = buf; qs.len = 1; qs.cap = 2;
return qs;
}
static BuildString build_string_substring(BuildString s, int64_t start, int64_t slen) {
if (start < 0) start = 0;
if ((size_t)start >= s.len || slen <= 0) {
return build_string_from_cstr("");
}
size_t actual = (size_t)slen;
if ((size_t)start + actual > s.len) actual = s.len - (size_t)start;
char* buf = (char*)malloc(actual + 1);
memcpy(buf, s.ptr + start, actual);
buf[actual] = '\0';
BuildString qs; qs.ptr = buf; qs.len = actual; qs.cap = actual + 1;
return qs;
}
static BuildString build_string_replace(BuildString s, BuildString old_s, BuildString new_s) {
if (old_s.len == 0) {
return build_string_from_cstr(s.ptr);
}
// Count occurrences
size_t count = 0;
const char* p = s.ptr;
while ((p = strstr(p, old_s.ptr)) != NULL) {
count++;
p += old_s.len;
}
if (count == 0) {
return build_string_from_cstr(s.ptr);
}
size_t new_len = s.len + count * (new_s.len - old_s.len);
char* buf = (char*)malloc(new_len + 1);
char* dst = buf;
const char* src = s.ptr;
while ((p = strstr(src, old_s.ptr)) != NULL) {
size_t chunk = (size_t)(p - src);
memcpy(dst, src, chunk);
dst += chunk;
memcpy(dst, new_s.ptr, new_s.len);
dst += new_s.len;
src = p + old_s.len;
}
// Copy remainder
size_t rem = s.len - (size_t)(src - s.ptr);
memcpy(dst, src, rem);
dst[rem] = '\0';
BuildString qs; qs.ptr = buf; qs.len = new_len; qs.cap = new_len + 1;
return qs;
}
static BuildString build_string_repeat(BuildString s, int64_t count) {
if (count <= 0 || s.len == 0) {
return build_string_from_cstr("");
}
size_t new_len = s.len * (size_t)count;
char* buf = (char*)malloc(new_len + 1);
for (int64_t i = 0; i < count; i++) {
memcpy(buf + i * s.len, s.ptr, s.len);
}
buf[new_len] = '\0';
BuildString qs; qs.ptr = buf; qs.len = new_len; qs.cap = new_len + 1;
return qs;
}
static int64_t build_string_index_of(BuildString s, BuildString substr) {
if (substr.len == 0) return 0;
if (substr.len > s.len) return -1;
const char* p = strstr(s.ptr, substr.ptr);
if (p == NULL) return -1;
return (int64_t)(p - s.ptr);
}
static int64_t build_string_compare(BuildString a, BuildString b) {
int c = strcmp(a.ptr, b.ptr);
return (int64_t)(c < 0 ? -1 : (c > 0 ? 1 : 0));
}
// --- Process exit ---
static void build_process_exit(int64_t code) {
exit((int)code);
}
// --- stderr output helper ---
static void build_eprint_str(const char* v) { fprintf(stderr, "%s", v); }
static void build_eprint_string(BuildString v) { fprintf(stderr, "%.*s", (int)v.len, v.ptr); }
// --- stdout initialization ---
// Disable output buffering so printf output is visible immediately,
// especially when running as a child process (e.g., buildc run).
#ifdef _MSC_VER
#pragma section(".CRT$XCU", read)
static void __build_init_stdio(void) { setvbuf(stdout, NULL, _IONBF, 0); }
__declspec(allocate(".CRT$XCU")) static void (*__build_init_ptr)(void) = __build_init_stdio;
#else
__attribute__((constructor)) static void __build_init_stdio(void) { setvbuf(stdout, NULL, _IONBF, 0); }
#endif
// --- String Vec handle variants ---
static BuildVecHandle build_hvec_new_str(void) {
BuildVecHandle h;
h.inner = (BuildVec*)malloc(sizeof(BuildVec));
*h.inner = build_vec_new(sizeof(BuildString));
return h;
}
static void build_hvec_push_str(BuildVecHandle h, BuildString val) { build_vec_push(h.inner, &val); }
static BuildString build_hvec_get_str(BuildVecHandle h, size_t index) { return *(BuildString*)build_vec_get(h.inner, index); }
// --- TCP socket support (includes must come before windows.h) ---
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#include <windows.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#define closesocket close
#endif
// --- Directory traversal ---
#ifdef _WIN32
// windows.h already included above
#else
#include <dirent.h>
#include <sys/stat.h>
#endif
static BuildVecHandle build_list_dir(const char* path) {
BuildVecHandle v = build_hvec_new_str();
#ifdef _WIN32
char search_path[1024];
snprintf(search_path, sizeof(search_path), "%s\\*", path);
WIN32_FIND_DATAA fd;
HANDLE h = FindFirstFileA(search_path, &fd);
if (h != INVALID_HANDLE_VALUE) {
do {
if (strcmp(fd.cFileName, ".") != 0 && strcmp(fd.cFileName, "..") != 0) {
build_hvec_push_str(v, build_string_from_cstr(fd.cFileName));
}
} while (FindNextFileA(h, &fd));
FindClose(h);
}
#else
DIR* d = opendir(path);
if (d) {
struct dirent* ent;
while ((ent = readdir(d)) != NULL) {
if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0) {
build_hvec_push_str(v, build_string_from_cstr(ent->d_name));
}
}
closedir(d);
}
#endif
return v;
}
static bool build_is_dir(const char* path) {
#ifdef _WIN32
DWORD attr = GetFileAttributesA(path);
return (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY));
#else
struct stat st;
return (stat(path, &st) == 0 && S_ISDIR(st.st_mode));
#endif
}
static int64_t build_file_size(const char* path) {
#ifdef _WIN32
WIN32_FILE_ATTRIBUTE_DATA fad;
if (GetFileAttributesExA(path, GetFileExInfoStandard, &fad)) {
return ((int64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow;
}
return -1;
#else
struct stat st;
return (stat(path, &st) == 0) ? st.st_size : -1;
#endif
}
// --- TCP socket functions ---
#ifdef _WIN32
static void build_net_init(void) {
static int initialized = 0;
if (!initialized) {
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
initialized = 1;
}
}
#else
static void build_net_init(void) {}
#endif
// Connect to host:port, returns socket fd (-1 on error)
static int64_t build_tcp_connect(const char* host, int64_t port) {
build_net_init();
struct addrinfo hints, *res;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
char port_str[16];
snprintf(port_str, sizeof(port_str), "%lld", (long long)port);
if (getaddrinfo(host, port_str, &hints, &res) != 0) return -1;
int64_t sock = (int64_t)socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sock < 0) { freeaddrinfo(res); return -1; }
if (connect((int)sock, res->ai_addr, (int)res->ai_addrlen) != 0) {
closesocket((int)sock);
freeaddrinfo(res);
return -1;
}
freeaddrinfo(res);
return sock;
}
// Send data on socket
static int64_t build_tcp_send(int64_t sock, const char* data) {
return send((int)sock, data, (int)strlen(data), 0);
}
// Receive data from socket (up to 64KB)
static BuildString build_tcp_recv(int64_t sock) {
char buf[65536];
int total = 0;
int n;
while (total < 65000) {
n = recv((int)sock, buf + total, sizeof(buf) - total - 1, 0);
if (n <= 0) break;
total += n;
}
buf[total] = '\0';
return build_string_from_cstr(buf);
}
// Close socket
static void build_tcp_close(int64_t sock) {
closesocket((int)sock);
}
// --- Environment variable access ---
static BuildString build_getenv(const char* name) {
const char* val = getenv(name);
if (val == NULL) return build_string_from_cstr("");
return build_string_from_cstr(val);
}
// --- Clock / time builtins ---
static int64_t build_clock_ms(void) {
#ifdef _WIN32
LARGE_INTEGER freq, count;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&count);
return (int64_t)(count.QuadPart * 1000 / freq.QuadPart);
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
#endif
}
static int64_t build_time_unix(void) {
return (int64_t)time(NULL);
}
// --- Seeded random builtin (Random capability) ---
//
// SplitMix64 over the top 53 bits: every operation is exact 64-bit integer
// arithmetic followed by an exact power-of-two scale, so the stream is
// bit-identical on every platform for a given seed. The seed arrives in
// BUILD_RANDOM_SEED, which `buildc run --seed N` sets for this process (and
// seals into the scientific receipt, so `receipt verify` re-runs the same
// stream). FAIL CLOSED: with no seed, or a malformed one, the first draw
// aborts rather than silently running an unseeded or fixed-default stream
// that would masquerade as sampling.
static uint64_t build_random_state;
static int build_random_seeded = 0;
static double build_random_f64(void) {
if (!build_random_seeded) {
const char* text = getenv("BUILD_RANDOM_SEED");
uint64_t seed = 0;
size_t i;
if (text == NULL || text[0] == '\0') {
fprintf(stderr, "random_f64: no seed provided; run under `buildc run <file> --seed N` (buildc sets BUILD_RANDOM_SEED for the program and seals the seed into the receipt)\n");
exit(101);
}
for (i = 0; text[i] != '\0'; i++) {
uint64_t digit;
if (text[i] < '0' || text[i] > '9') {
fprintf(stderr, "random_f64: BUILD_RANDOM_SEED `%s` is not a decimal u64\n", text);
exit(101);
}
digit = (uint64_t)(text[i] - '0');
if (seed > (UINT64_MAX - digit) / 10u) {
fprintf(stderr, "random_f64: BUILD_RANDOM_SEED `%s` overflows u64\n", text);
exit(101);
}
seed = seed * 10u + digit;
}
build_random_state = seed;
build_random_seeded = 1;
}
build_random_state += 0x9E3779B97F4A7C15ULL;
{
uint64_t z = build_random_state;
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
z = z ^ (z >> 31);
// Top 53 bits scaled by 2^-53: exact, uniform in [0, 1).
return (double)(z >> 11) * (1.0 / 9007199254740992.0);
}
}
// --- Model-call builtin (Model capability) ---
//
// A deliberately DUMB line protocol over TCP: connect to the host:port in
// BUILD_MODEL_ENDPOINT, send the prompt bytes plus a single '\n', read the
// reply with build_tcp_recv (which reads until the peer closes the
// connection or its 64KB buffer fills -- the harness-side shim is expected
// to write one line and close), and return it with one trailing newline
// (and a preceding carriage return) trimmed off. The model adapter (HTTP,
// tokenization, parameters) lives on the harness side of this seam, never
// in the compiler. FAIL CLOSED: no endpoint, a malformed endpoint, an
// embedded newline in the prompt, or a connection failure aborts rather
// than fabricating a completion.
static BuildString build_model_complete(const char* prompt) {
const char* endpoint = getenv("BUILD_MODEL_ENDPOINT");
char host[256];
const char* colon;
int64_t port;
int64_t sock;
size_t i;
BuildString reply;
if (endpoint == NULL || endpoint[0] == '\0') {
fprintf(stderr, "model_complete: no endpoint provided; set BUILD_MODEL_ENDPOINT to host:port (the harness-side shim speaks one prompt line out, one completion line back)\n");
exit(102);
}
colon = strrchr(endpoint, ':');
if (colon == NULL || colon == endpoint || colon[1] == '\0' || (size_t)(colon - endpoint) >= sizeof(host)) {
fprintf(stderr, "model_complete: BUILD_MODEL_ENDPOINT `%s` is not host:port\n", endpoint);
exit(102);
}
memcpy(host, endpoint, (size_t)(colon - endpoint));
host[colon - endpoint] = '\0';
port = 0;
for (i = 0; colon[1 + i] != '\0'; i++) {
if (colon[1 + i] < '0' || colon[1 + i] > '9' || port > 65535) {
fprintf(stderr, "model_complete: BUILD_MODEL_ENDPOINT port `%s` is not a valid port\n", colon + 1);
exit(102);
}
port = port * 10 + (colon[1 + i] - '0');
}
if (port == 0 || port > 65535) {
fprintf(stderr, "model_complete: BUILD_MODEL_ENDPOINT port out of range\n");
exit(102);
}
for (i = 0; prompt[i] != '\0'; i++) {
if (prompt[i] == '\n') {
fprintf(stderr, "model_complete: the prompt may not contain a newline (the line protocol uses it as the terminator)\n");
exit(102);
}
}
sock = build_tcp_connect(host, port);
if (sock < 0) {
fprintf(stderr, "model_complete: could not connect to %s\n", endpoint);
exit(102);
}
build_tcp_send(sock, prompt);
build_tcp_send(sock, "\n");
reply = build_tcp_recv(sock);
build_tcp_close(sock);
// Trim one trailing newline (and a carriage return before it). `len` is
// the logical length build_print_string and friends respect (BuildString
// is not required to be NUL-terminated at that offset), so shortening it
// is enough; the trimmed bytes are simply never read.
if (reply.len > 0 && reply.ptr[reply.len - 1] == '\n') {
reply.len -= 1;
}
if (reply.len > 0 && reply.ptr[reply.len - 1] == '\r') {
reply.len -= 1;
}
return reply;
}
// UTF-8 for `s.chars()` and for printing a char.
static uint32_t build_string_utf8_at(BuildString s, int64_t i) {
const unsigned char* p = (const unsigned char*)s.ptr + i;
size_t left = s.len - (size_t)i;
if (p[0] < 0x80 || left < 2) return p[0];
if ((p[0] & 0xE0) == 0xC0) return ((p[0] & 0x1F) << 6) | (p[1] & 0x3F);
if ((p[0] & 0xF0) == 0xE0 && left >= 3)
return ((p[0] & 0x0F) << 12) | ((p[1] & 0x3F) << 6) | (p[2] & 0x3F);
if ((p[0] & 0xF8) == 0xF0 && left >= 4)
return ((uint32_t)(p[0] & 0x07) << 18) | ((p[1] & 0x3F) << 12) | ((p[2] & 0x3F) << 6) | (p[3] & 0x3F);
return p[0];
}
static int64_t build_string_utf8_width(BuildString s, int64_t i) {
unsigned char b = (unsigned char)s.ptr[i];
int64_t w = b < 0x80 ? 1 : (b & 0xE0) == 0xC0 ? 2 : (b & 0xF0) == 0xE0 ? 3 : (b & 0xF8) == 0xF0 ? 4 : 1;
return (size_t)(i + w) <= s.len ? w : 1;
}
static BuildString build_char_to_string(uint32_t c) {
char buf[5] = {0};
if (c < 0x80) { buf[0] = (char)c; }
else if (c < 0x800) { buf[0] = (char)(0xC0 | (c >> 6)); buf[1] = (char)(0x80 | (c & 0x3F)); }
else if (c < 0x10000) { buf[0] = (char)(0xE0 | (c >> 12)); buf[1] = (char)(0x80 | ((c >> 6) & 0x3F)); buf[2] = (char)(0x80 | (c & 0x3F)); }
else { buf[0] = (char)(0xF0 | (c >> 18)); buf[1] = (char)(0x80 | ((c >> 12) & 0x3F)); buf[2] = (char)(0x80 | ((c >> 6) & 0x3F)); buf[3] = (char)(0x80 | (c & 0x3F)); }
return build_format_str("%s", buf);
}
// Debug (`{:?}`) text. A float prints its shortest round-trip form with `.0`
// added to a whole number, as Rust's Debug does. (Rust switches to exponent
// form at 1e16 and below 1e-4; that is not reproduced here.)
static BuildString build_f64_to_debug_string(double v) {
char* t = bl_fmt_f64(v);
int whole = 1;
for (char* p = t; *p; p++) {
if (*p == '.' || *p == 'e' || *p == 'E' || *p == 'n' || *p == 'N' || *p == 'i') { whole = 0; break; }
}
return whole ? build_format_str("%s.0", t) : build_format_str("%s", t);
}
static BuildString build_f32_to_debug_string(float v) {
return build_f64_to_debug_string((double)v);
}
// `{:?}` of a vector: `[a, b, c]`, strings quoted, as Rust prints a Vec.
static BuildString build_hvec_debug_open(void) { return build_string_new("["); }
static BuildString build_hvec_debug_close(BuildString acc) {
return build_string_concat(acc, build_string_new("]"));
}
static BuildString build_hvec_debug_sep(BuildString acc, size_t i) {
return i ? build_string_concat(acc, build_string_new(", ")) : acc;
}
static BuildString build_hvec_debug_i32(BuildVecHandle v) {
BuildString acc = build_hvec_debug_open();
size_t n = build_hvec_len(v);
for (size_t i = 0; i < n; i++) {
acc = build_hvec_debug_sep(acc, i);
acc = build_string_concat(acc, build_i64_to_string((int64_t)build_hvec_get_i32(v, i)));
}
return build_hvec_debug_close(acc);
}
static BuildString build_hvec_debug_i64(BuildVecHandle v) {
BuildString acc = build_hvec_debug_open();
size_t n = build_hvec_len(v);
for (size_t i = 0; i < n; i++) {
acc = build_hvec_debug_sep(acc, i);
acc = build_string_concat(acc, build_i64_to_string(build_hvec_get_i64(v, i)));
}
return build_hvec_debug_close(acc);
}
static BuildString build_hvec_debug_f64(BuildVecHandle v) {
BuildString acc = build_hvec_debug_open();
size_t n = build_hvec_len(v);
for (size_t i = 0; i < n; i++) {
acc = build_hvec_debug_sep(acc, i);
acc = build_string_concat(acc, build_f64_to_debug_string(build_hvec_get_f64(v, i)));
}
return build_hvec_debug_close(acc);
}
static BuildString build_hvec_debug_str(BuildVecHandle v) {
BuildString acc = build_hvec_debug_open();
size_t n = build_hvec_len(v);
for (size_t i = 0; i < n; i++) {
acc = build_hvec_debug_sep(acc, i);
acc = build_string_concat(acc, build_string_new("\""));
acc = build_string_concat(acc, build_hvec_get_str(v, i));
acc = build_string_concat(acc, build_string_new("\""));
}
return build_hvec_debug_close(acc);
}
// Vulkan host entry points, defined in runtime/vulkan_host.c and linked in by
// GPU host programs. Declared here so a call compiles against its real
// signature instead of an implicit declaration.
int build_vk_init(void);
const char* build_vk_device_name(void);
int build_vk_load_shader_file(const char* path);
int build_vk_run_compute(const char* spv_path);
int build_vk_create_graphics_pipeline(const char* vert_path, const char* frag_path);
void build_vk_set_push_constant_f32(int offset, float value);
int build_vk_draw_frame(void);
int build_vk_should_close(void);
void build_vk_request_close(void);
void build_vk_shutdown(void);
// ============================================================================
// End BuildLang Runtime
// ============================================================================
"#
}
pub fn portable_lf_stdio_support() -> &'static str {
r#"
// --- portable LF stdio mode ---
static void __build_stdio_mode_failed(const char* stream_name, const char* call_name) {
fprintf(stderr, "BuildLang stdio-mode portable-lf initialization failed: %s(%s)\n", call_name, stream_name);
exit(120);
}
static void __build_init_portable_lf_stdio(void) {
#ifdef _WIN32
int stdout_fd = _fileno(stdout);
if (stdout_fd == -1) {
__build_stdio_mode_failed("stdout", "_fileno");
}
if (_setmode(stdout_fd, _O_BINARY) == -1) {
__build_stdio_mode_failed("stdout", "_setmode");
}
int stderr_fd = _fileno(stderr);
if (stderr_fd == -1) {
__build_stdio_mode_failed("stderr", "_fileno");
}
if (_setmode(stderr_fd, _O_BINARY) == -1) {
__build_stdio_mode_failed("stderr", "_setmode");
}
#endif
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
}
"#
}
pub const MATH_BUILTINS: &[&str] = &[
"abs",
"sqrt",
"pow",
"sin",
"cos",
"tan",
"floor",
"ceil",
"round",
"min",
"max",
"read_file",
"write_file",
"file_exists",
"exit",
"read_bytes",
"write_bytes",
"append_file",
"dot",
"cross",
"normalize",
"length",
"reflect",
"lerp",
"mat4_identity",
"mat4_translate",
"mat4_scale",
"mat4_perspective",
"clamp",
"smoothstep",
"mix",
"fract",
"step",
"saturate",
"vec_new",
"vec_push",
"vec_get",
"vec_len",
"vec_pop",
"vec_new_f64",
"vec_push_f64",
"vec_get_f64",
"vec_pop_f64",
"vec_new_i64",
"vec_push_i64",
"vec_get_i64",
"vec_pop_i64",
"to_string_i32",
"to_string_f64",
"map_new",
"map_insert",
"map_get",
"map_contains",
"map_len",
"map_remove",
"map_new_i32",
"map_insert_i32",
"map_get_i32",
"map_contains_i32",
"map_len_i32",
"map_remove_i32",
"map_new_i64",
"map_insert_i64",
"map_get_i64",
"map_contains_i64",
"map_len_i64",
"map_remove_i64",
"build_vk_init",
"build_vk_load_shader_file",
"build_vk_run_compute",
"build_vk_shutdown",
"build_vk_create_graphics_pipeline",
"build_vk_set_push_constant_f32",
"build_vk_draw_frame",
"build_vk_should_close",
"build_vk_request_close",
"build_vk_device_name",
"args_count",
"args_get",
"read_line",
"read_all",
"stdin_is_pipe",
"process_exit",
"list_dir",
"is_dir",
"file_size",
"vec_new_str",
"vec_push_str",
"vec_get_str",
"tcp_connect",
"tcp_send",
"tcp_recv",
"tcp_close",
"getenv",
"clock_ms",
"time_unix",
"random_f64",
"model_complete",
];
pub fn math_builtin_to_c(name: &str) -> Option<&'static str> {
match name {
"abs" => Some("fabs"),
"sqrt" => Some("sqrt"),
"pow" => Some("pow"),
"sin" => Some("sin"),
"cos" => Some("cos"),
"tan" => Some("tan"),
"log" => Some("log"),
"log2" => Some("log2"),
"log10" => Some("log10"),
"exp" => Some("exp"),
"atan2" => Some("atan2"),
"floor" => Some("floor"),
"ceil" => Some("ceil"),
"round" => Some("round"),
"min" => Some("build_min_i32"),
"max" => Some("build_max_i32"),
"read_file" => Some("build_read_file"),
"write_file" => Some("build_write_file"),
"file_exists" => Some("build_file_exists"),
"exit" => Some("build_exit"),
"read_bytes" => Some("build_read_bytes"),
"write_bytes" => Some("build_write_bytes"),
"append_file" => Some("build_append_file"),
"vec_new" => Some("build_hvec_new_i32"),
"vec_push" => Some("build_hvec_push_i32"),
"vec_get" => Some("build_hvec_get_i32"),
"vec_len" => Some("build_hvec_len"),
"vec_pop" => Some("build_hvec_pop_i32"),
"vec_new_f64" => Some("build_hvec_new_f64"),
"vec_push_f64" => Some("build_hvec_push_f64"),
"vec_get_f64" => Some("build_hvec_get_f64"),
"vec_pop_f64" => Some("build_hvec_pop_f64"),
"vec_new_i64" => Some("build_hvec_new_i64"),
"vec_push_i64" => Some("build_hvec_push_i64"),
"vec_get_i64" => Some("build_hvec_get_i64"),
"vec_pop_i64" => Some("build_hvec_pop_i64"),
"to_string_i32" => Some("build_i32_to_string"),
"to_string_f64" => Some("build_f64_to_string"),
"map_new_i32" => Some("build_map_new"),
"map_insert_i32" => Some("build_map_insert"),
"map_get_i32" => Some("build_map_get"),
"map_contains_i32" => Some("build_map_contains"),
"map_len_i32" => Some("build_map_len"),
"map_remove_i32" => Some("build_map_remove"),
"map_new" => Some("build_hmap_new_str_f64"),
"map_insert" => Some("build_hmap_insert_str_f64"),
"map_get" => Some("build_hmap_get_str_f64"),
"map_contains" => Some("build_hmap_contains_str_f64"),
"map_len" => Some("build_hmap_len_str_f64"),
"map_remove" => Some("build_hmap_remove_str_f64"),
"map_new_i64" => Some("build_hmap_new_i64_f64"),
"map_insert_i64" => Some("build_hmap_insert_i64_f64"),
"map_get_i64" => Some("build_hmap_get_i64_f64"),
"map_contains_i64" => Some("build_hmap_contains_i64_f64"),
"map_len_i64" => Some("build_hmap_len_i64_f64"),
"map_remove_i64" => Some("build_hmap_remove_i64_f64"),
"build_vk_init" => Some("build_vk_init"),
"build_vk_load_shader_file" => Some("build_vk_load_shader_file"),
"build_vk_run_compute" => Some("build_vk_run_compute"),
"build_vk_shutdown" => Some("build_vk_shutdown"),
"build_vk_create_graphics_pipeline" => Some("build_vk_create_graphics_pipeline"),
"build_vk_set_push_constant_f32" => Some("build_vk_set_push_constant_f32"),
"build_vk_draw_frame" => Some("build_vk_draw_frame"),
"build_vk_should_close" => Some("build_vk_should_close"),
"build_vk_request_close" => Some("build_vk_request_close"),
"build_vk_device_name" => Some("build_vk_device_name"),
"dot" => Some("build_dot3"),
"cross" => Some("build_cross"),
"normalize" => Some("build_normalize3"),
"length" => Some("build_length3"),
"reflect" => Some("build_reflect3"),
"lerp" => Some("build_lerp3"),
"mat4_identity" => Some("build_mat4_identity"),
"mat4_translate" => Some("build_mat4_translate"),
"mat4_scale" => Some("build_mat4_scale"),
"mat4_perspective" => Some("build_mat4_perspective"),
"clamp" => Some("build_clampf"),
"saturate" => Some("build_saturate"),
"smoothstep" => Some("build_smoothstep"),
"mix" => Some("build_mix"),
"fract" => Some("build_fract"),
"step" => Some("build_step"),
"args_count" => Some("build_args_count"),
"args_get" => Some("build_args_get"),
"read_line" => Some("build_read_line"),
"read_all" => Some("build_read_all"),
"stdin_is_pipe" => Some("build_stdin_is_pipe"),
"process_exit" => Some("build_process_exit"),
"list_dir" => Some("build_list_dir"),
"is_dir" => Some("build_is_dir"),
"file_size" => Some("build_file_size"),
"vec_new_str" => Some("build_hvec_new_str"),
"vec_push_str" => Some("build_hvec_push_str"),
"vec_get_str" => Some("build_hvec_get_str"),
"tcp_connect" => Some("build_tcp_connect"),
"tcp_send" => Some("build_tcp_send"),
"tcp_recv" => Some("build_tcp_recv"),
"tcp_close" => Some("build_tcp_close"),
"getenv" => Some("build_getenv"),
"clock_ms" => Some("build_clock_ms"),
"time_unix" => Some("build_time_unix"),
"random_f64" => Some("build_random_f64"),
"model_complete" => Some("build_model_complete"),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_runtime_header_contains_string_type() {
let header = runtime_header();
assert!(header.contains("BuildString"));
assert!(header.contains("build_string_new"));
assert!(header.contains("build_string_concat"));
assert!(header.contains("build_string_len"));
assert!(header.contains("build_string_eq"));
assert!(header.contains("build_string_free"));
}
#[test]
fn test_runtime_header_contains_string_methods() {
let header = runtime_header();
assert!(header.contains("build_string_is_empty"));
assert!(header.contains("build_string_starts_with"));
assert!(header.contains("build_string_ends_with"));
assert!(header.contains("build_string_contains"));
assert!(header.contains("build_string_to_upper"));
assert!(header.contains("build_string_to_lower"));
assert!(header.contains("build_string_trim"));
assert!(header.contains("build_string_split"));
assert!(header.contains("build_string_split_ws"));
assert!(header.contains("build_string_lines"));
}
#[test]
fn test_runtime_header_contains_vec_type() {
let header = runtime_header();
assert!(header.contains("BuildVec"));
assert!(header.contains("build_vec_new"));
assert!(header.contains("build_vec_push"));
assert!(header.contains("build_vec_get"));
assert!(header.contains("build_vec_free"));
assert!(header.contains("build_hvec_new_f64"));
assert!(header.contains("build_hvec_push_f64"));
assert!(header.contains("build_hvec_get_f64"));
assert!(header.contains("build_hvec_new_i64"));
}
#[test]
fn test_runtime_header_contains_print_helpers() {
let header = runtime_header();
assert!(header.contains("build_print_i32"));
assert!(header.contains("build_print_i64"));
assert!(header.contains("build_print_f32"));
assert!(header.contains("build_print_f64"));
assert!(header.contains("build_print_bool"));
assert!(header.contains("build_print_str"));
assert!(header.contains("build_print_string"));
assert!(header.contains("build_print_char"));
}
#[test]
fn test_runtime_header_contains_math_helpers() {
let header = runtime_header();
assert!(header.contains("build_min_i32"));
assert!(header.contains("build_max_i32"));
assert!(header.contains("build_min_f64"));
assert!(header.contains("build_max_f64"));
}
#[test]
fn test_math_builtin_lookup() {
assert_eq!(math_builtin_to_c("abs"), Some("fabs"));
assert_eq!(math_builtin_to_c("sqrt"), Some("sqrt"));
assert_eq!(math_builtin_to_c("pow"), Some("pow"));
assert_eq!(math_builtin_to_c("sin"), Some("sin"));
assert_eq!(math_builtin_to_c("cos"), Some("cos"));
assert_eq!(math_builtin_to_c("tan"), Some("tan"));
assert_eq!(math_builtin_to_c("floor"), Some("floor"));
assert_eq!(math_builtin_to_c("ceil"), Some("ceil"));
assert_eq!(math_builtin_to_c("round"), Some("round"));
assert_eq!(math_builtin_to_c("min"), Some("build_min_i32"));
assert_eq!(math_builtin_to_c("max"), Some("build_max_i32"));
assert_eq!(math_builtin_to_c("unknown"), None);
}
#[test]
fn test_math_builtins_list() {
assert_eq!(MATH_BUILTINS.len(), 98);
assert!(MATH_BUILTINS.contains(&"abs"));
assert!(MATH_BUILTINS.contains(&"random_f64"));
assert!(MATH_BUILTINS.contains(&"model_complete"));
assert!(MATH_BUILTINS.contains(&"min"));
assert!(MATH_BUILTINS.contains(&"max"));
assert!(MATH_BUILTINS.contains(&"dot"));
assert!(MATH_BUILTINS.contains(&"cross"));
assert!(MATH_BUILTINS.contains(&"normalize"));
assert!(MATH_BUILTINS.contains(&"length"));
}
#[test]
fn test_runtime_header_contains_effect_handler() {
let header = runtime_header();
assert!(header.contains("BuildHandler"));
assert!(header.contains("build_push_handler"));
assert!(header.contains("build_pop_handler"));
assert!(header.contains("build_perform"));
assert!(header.contains("__build_handler_stack"));
assert!(header.contains("setjmp.h"));
}
#[test]
fn test_runtime_header_contains_file_io() {
let header = runtime_header();
assert!(header.contains("build_read_file"));
assert!(header.contains("build_write_file"));
assert!(header.contains("build_file_exists"));
assert!(header.contains("build_exit"));
assert!(header.contains("build_read_bytes"));
assert!(header.contains("build_write_bytes"));
assert!(header.contains("build_append_file"));
}
#[test]
fn test_runtime_header_contains_vector_types() {
let header = runtime_header();
assert!(header.contains("build_vec2"));
assert!(header.contains("build_vec3"));
assert!(header.contains("build_vec4"));
assert!(header.contains("build_mat4"));
assert!(header.contains("build_vec3_new"));
assert!(header.contains("build_dot3"));
assert!(header.contains("build_length3"));
assert!(header.contains("build_normalize3"));
assert!(header.contains("build_cross"));
assert!(header.contains("build_vec3_add"));
assert!(header.contains("build_vec3_sub"));
assert!(header.contains("build_vec3_mul"));
assert!(header.contains("build_vec3_scale"));
assert!(header.contains("build_vec3_neg"));
}
#[test]
fn test_vector_builtin_lookup() {
assert_eq!(math_builtin_to_c("dot"), Some("build_dot3"));
assert_eq!(math_builtin_to_c("cross"), Some("build_cross"));
assert_eq!(math_builtin_to_c("normalize"), Some("build_normalize3"));
assert_eq!(math_builtin_to_c("length"), Some("build_length3"));
assert_eq!(math_builtin_to_c("reflect"), Some("build_reflect3"));
assert_eq!(math_builtin_to_c("lerp"), Some("build_lerp3"));
}
#[test]
fn test_mat4_builtin_lookup() {
assert_eq!(
math_builtin_to_c("mat4_identity"),
Some("build_mat4_identity")
);
assert_eq!(
math_builtin_to_c("mat4_translate"),
Some("build_mat4_translate")
);
assert_eq!(math_builtin_to_c("mat4_scale"), Some("build_mat4_scale"));
assert_eq!(
math_builtin_to_c("mat4_perspective"),
Some("build_mat4_perspective")
);
}
#[test]
fn test_shader_math_builtin_lookup() {
assert_eq!(math_builtin_to_c("clamp"), Some("build_clampf"));
assert_eq!(math_builtin_to_c("smoothstep"), Some("build_smoothstep"));
assert_eq!(math_builtin_to_c("mix"), Some("build_mix"));
assert_eq!(math_builtin_to_c("fract"), Some("build_fract"));
assert_eq!(math_builtin_to_c("step"), Some("build_step"));
}
#[test]
fn test_runtime_header_contains_mat4_ops() {
let header = runtime_header();
assert!(header.contains("build_mat4_identity"));
assert!(header.contains("build_mat4_mul"));
assert!(header.contains("build_mat4_mul_vec4"));
assert!(header.contains("build_mat4_translate"));
assert!(header.contains("build_mat4_scale"));
assert!(header.contains("build_mat4_perspective"));
}
#[test]
fn test_runtime_header_contains_shader_math() {
let header = runtime_header();
assert!(header.contains("build_clampf"));
assert!(header.contains("build_clamp3"));
assert!(header.contains("build_smoothstep"));
assert!(header.contains("build_mix"));
assert!(header.contains("build_fract"));
assert!(header.contains("build_step"));
}
#[test]
fn test_io_builtin_lookup() {
assert_eq!(math_builtin_to_c("read_file"), Some("build_read_file"));
assert_eq!(math_builtin_to_c("write_file"), Some("build_write_file"));
assert_eq!(math_builtin_to_c("file_exists"), Some("build_file_exists"));
assert_eq!(math_builtin_to_c("exit"), Some("build_exit"));
assert_eq!(math_builtin_to_c("read_bytes"), Some("build_read_bytes"));
assert_eq!(math_builtin_to_c("write_bytes"), Some("build_write_bytes"));
assert_eq!(math_builtin_to_c("append_file"), Some("build_append_file"));
}
#[test]
fn test_runtime_header_contains_typed_hashmap() {
let header = runtime_header();
assert!(header.contains("BuildStrF64Map"));
assert!(header.contains("BuildStrF64MapHandle"));
assert!(header.contains("build_hmap_new_str_f64"));
assert!(header.contains("build_hmap_insert_str_f64"));
assert!(header.contains("build_hmap_get_str_f64"));
assert!(header.contains("build_hmap_contains_str_f64"));
assert!(header.contains("build_hmap_remove_str_f64"));
assert!(header.contains("build_hmap_len_str_f64"));
assert!(header.contains("BuildI64F64Map"));
assert!(header.contains("BuildI64F64MapHandle"));
assert!(header.contains("build_hmap_new_i64_f64"));
assert!(header.contains("build_hmap_insert_i64_f64"));
assert!(header.contains("build_hmap_get_i64_f64"));
assert!(header.contains("build_hmap_contains_i64_f64"));
assert!(header.contains("build_hmap_remove_i64_f64"));
assert!(header.contains("build_hmap_len_i64_f64"));
}
#[test]
fn test_hashmap_builtin_lookup() {
assert_eq!(math_builtin_to_c("map_new"), Some("build_hmap_new_str_f64"));
assert_eq!(
math_builtin_to_c("map_insert"),
Some("build_hmap_insert_str_f64")
);
assert_eq!(math_builtin_to_c("map_get"), Some("build_hmap_get_str_f64"));
assert_eq!(
math_builtin_to_c("map_contains"),
Some("build_hmap_contains_str_f64")
);
assert_eq!(
math_builtin_to_c("map_remove"),
Some("build_hmap_remove_str_f64")
);
assert_eq!(math_builtin_to_c("map_len"), Some("build_hmap_len_str_f64"));
assert_eq!(
math_builtin_to_c("map_new_i64"),
Some("build_hmap_new_i64_f64")
);
assert_eq!(
math_builtin_to_c("map_insert_i64"),
Some("build_hmap_insert_i64_f64")
);
assert_eq!(
math_builtin_to_c("map_get_i64"),
Some("build_hmap_get_i64_f64")
);
assert_eq!(math_builtin_to_c("map_new_i32"), Some("build_map_new"));
assert_eq!(
math_builtin_to_c("map_insert_i32"),
Some("build_map_insert")
);
}
#[test]
fn test_runtime_header_contains_graphics_stub() {
let header = runtime_header();
assert!(header.contains("BuildGfxContext"));
assert!(header.contains("build_gfx_init"));
assert!(header.contains("build_gfx_load_shader"));
assert!(header.contains("build_gfx_create_pipeline"));
assert!(header.contains("build_gfx_begin_frame"));
assert!(header.contains("build_gfx_clear"));
assert!(header.contains("build_gfx_draw"));
assert!(header.contains("build_gfx_end_frame"));
assert!(header.contains("build_gfx_should_close"));
assert!(header.contains("build_gfx_shutdown"));
}
#[test]
fn test_runtime_header_contains_cli_args() {
let header = runtime_header();
assert!(header.contains("BUILD_ARGS"));
assert!(header.contains("build_args_init"));
assert!(header.contains("build_args_count"));
assert!(header.contains("build_args_get"));
assert!(header.contains("build_string_from_cstr"));
}
#[test]
fn test_runtime_header_contains_stdin() {
let header = runtime_header();
assert!(header.contains("build_read_line"));
assert!(header.contains("build_read_all"));
assert!(header.contains("build_stdin_is_pipe"));
}
#[test]
fn test_runtime_header_contains_extended_string_ops() {
let header = runtime_header();
assert!(header.contains("build_string_parse_int"));
assert!(header.contains("build_string_parse_float"));
assert!(header.contains("build_string_char_at"));
assert!(header.contains("build_string_substring"));
assert!(header.contains("build_string_replace"));
assert!(header.contains("build_string_repeat"));
assert!(header.contains("build_string_index_of"));
assert!(header.contains("build_string_compare"));
}
#[test]
fn test_cli_builtin_lookup() {
assert_eq!(math_builtin_to_c("args_count"), Some("build_args_count"));
assert_eq!(math_builtin_to_c("args_get"), Some("build_args_get"));
assert_eq!(math_builtin_to_c("read_line"), Some("build_read_line"));
assert_eq!(math_builtin_to_c("read_all"), Some("build_read_all"));
assert_eq!(
math_builtin_to_c("stdin_is_pipe"),
Some("build_stdin_is_pipe")
);
assert_eq!(
math_builtin_to_c("process_exit"),
Some("build_process_exit")
);
}
#[test]
fn test_runtime_header_contains_dir_traversal() {
let header = runtime_header();
assert!(header.contains("build_list_dir"));
assert!(header.contains("build_is_dir"));
assert!(header.contains("build_file_size"));
assert!(header.contains("build_hvec_new_str"));
assert!(header.contains("build_hvec_push_str"));
assert!(header.contains("build_hvec_get_str"));
}
#[test]
fn test_clock_builtin_lookup() {
assert_eq!(math_builtin_to_c("clock_ms"), Some("build_clock_ms"));
assert_eq!(math_builtin_to_c("random_f64"), Some("build_random_f64"));
assert_eq!(math_builtin_to_c("time_unix"), Some("build_time_unix"));
}
#[test]
fn test_model_builtin_lookup() {
assert_eq!(
math_builtin_to_c("model_complete"),
Some("build_model_complete")
);
}
#[test]
fn test_runtime_header_contains_clock() {
let header = runtime_header();
assert!(header.contains("build_clock_ms"));
assert!(header.contains("build_time_unix"));
}
#[test]
fn test_runtime_header_contains_seeded_random() {
let header = runtime_header();
assert!(header.contains("build_random_f64"));
assert!(header.contains("BUILD_RANDOM_SEED"));
assert!(header.contains("no seed provided"));
}
#[test]
fn test_runtime_header_contains_model() {
let header = runtime_header();
assert!(header.contains("build_model_complete"));
assert!(header.contains("BUILD_MODEL_ENDPOINT"));
assert!(header.contains("no endpoint provided"));
}
#[test]
fn test_dir_builtin_lookup() {
assert_eq!(math_builtin_to_c("list_dir"), Some("build_list_dir"));
assert_eq!(math_builtin_to_c("is_dir"), Some("build_is_dir"));
assert_eq!(math_builtin_to_c("file_size"), Some("build_file_size"));
assert_eq!(math_builtin_to_c("vec_new_str"), Some("build_hvec_new_str"));
assert_eq!(
math_builtin_to_c("vec_push_str"),
Some("build_hvec_push_str")
);
assert_eq!(math_builtin_to_c("vec_get_str"), Some("build_hvec_get_str"));
}
}