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.
#if defined(__GNUC__) || defined(__clang__)
__attribute__((noreturn, cold))
#endif
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;
}
// With gcc or clang the checks use the overflow builtins: the same result and
// the same trap (the exact result does not fit TYPE), without the division the
// portable multiply check needs. Other compilers take the portable helpers.
#if defined(__GNUC__) || defined(__clang__)
#define BL_DEFINE_SIGNED_ARITH(SUFFIX, TYPE, MINV, MAXV) \
static inline TYPE bl_iadd_##SUFFIX(TYPE a, TYPE b){ \
TYPE r; if (__builtin_expect(__builtin_add_overflow(a, b, &r), 0)) bl_arith_panic("attempt to add with overflow"); \
return r; \
} \
static inline TYPE bl_isub_##SUFFIX(TYPE a, TYPE b){ \
TYPE r; if (__builtin_expect(__builtin_sub_overflow(a, b, &r), 0)) bl_arith_panic("attempt to subtract with overflow"); \
return r; \
} \
static inline TYPE bl_imul_##SUFFIX(TYPE a, TYPE b){ \
TYPE r; if (__builtin_expect(__builtin_mul_overflow(a, b, &r), 0)) bl_arith_panic("attempt to multiply with overflow"); \
return r; \
} \
static inline 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 inline TYPE bl_uadd_##SUFFIX(TYPE a, TYPE b){ \
TYPE r; if (__builtin_expect(__builtin_add_overflow(a, b, &r), 0)) bl_arith_panic("attempt to add with overflow"); \
return r; \
} \
static inline TYPE bl_usub_##SUFFIX(TYPE a, TYPE b){ \
TYPE r; if (__builtin_expect(__builtin_sub_overflow(a, b, &r), 0)) bl_arith_panic("attempt to subtract with overflow"); \
return r; \
} \
static inline TYPE bl_umul_##SUFFIX(TYPE a, TYPE b){ \
TYPE r; if (__builtin_expect(__builtin_mul_overflow(a, b, &r), 0)) bl_arith_panic("attempt to multiply with overflow"); \
return r; \
}
#else
#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); }
#endif
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; }
// Per-thread storage for the formatters' rotating buffers: a par_for /
// par_map body may format numbers on several threads at once (M5).
#if defined(_MSC_VER) && !defined(__clang__)
#define BL_TLS __declspec(thread)
#else
#define BL_TLS __thread
#endif
// 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 BL_TLS char pool[16][64];
static BL_TLS 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 BL_TLS char pool[16][64];
static BL_TLS 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 BL_TLS char pool[16][512];
static BL_TLS 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 BL_TLS char pool[16][512];
static BL_TLS 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).
#if defined(__GNUC__) || defined(__clang__)
__attribute__((noreturn, cold))
#endif
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++;
}
// The check stays on every access; it is marked unlikely so the compiler
// lays the abort out of the hot path.
#if defined(__GNUC__) || defined(__clang__)
#define BL_UNLIKELY(c) __builtin_expect(!!(c), 0)
#else
#define BL_UNLIKELY(c) (c)
#endif
static void* build_vec_get(BuildVec* v, size_t index) {
if (BL_UNLIKELY(index >= v->len)) bl_index_oob((long long)index, v->len);
return (char*)v->ptr + index * v->elem_size;
}
#if defined(__GNUC__) || defined(__clang__)
__attribute__((noreturn, cold))
#endif
static void bl_vec_layout_fail(size_t got, size_t want) {
fprintf(stderr, "internal error: a vector holds %zu-byte elements where its type needs %zu bytes\n", got, want);
exit(101);
}
// A vector element at a hoisted buffer (see the C backend's vec_hoist). The
// hoisted length is 0 when the vector's element size is not `es`, so every
// access then fails here and `bl_vat_fail` names the layout fault; otherwise
// the abort and its message are the ones `build_vec_get` and the
// element-sized setters print.
#if defined(__GNUC__) || defined(__clang__)
__attribute__((noreturn, cold))
#endif
static void bl_vat_fail(const BuildVec* v, size_t es, size_t i, int set_msg) {
if (v->elem_size != es) bl_vec_layout_fail(v->elem_size, es);
if (set_msg) {
fprintf(stderr, "Vec index out of bounds: %zu >= %zu\n", i, v->len);
exit(101);
}
bl_index_oob((long long)i, v->len);
}
static inline char* bl_vat(const BuildVec* v, char* p, size_t n, size_t es, size_t i) {
if (BL_UNLIKELY(i >= n)) bl_vat_fail(v, es, i, 0);
return p + i * es;
}
static inline char* bl_vat_set(const BuildVec* v, char* p, size_t n, size_t es, size_t i) {
if (BL_UNLIKELY(i >= n)) bl_vat_fail(v, es, i, 1);
return p + i * es;
}
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; }
// The element buffer of a vector, for a `&[T]` view of a `&Vec<T>` argument.
// `es` is the size of `T`; a vector that stores another width is refused.
static void* build_hvec_data(BuildVecHandle h, size_t es) {
if (h.inner->elem_size != es) bl_vec_layout_fail(h.inner->elem_size, es);
return h.inner->ptr;
}
// The element buffer from `start`, for a `&v[start..end]` view. As in Rust the
// range must satisfy start <= end <= len, or the program stops with 101.
static void* build_hvec_range(BuildVecHandle h, size_t es, int64_t start, int64_t end) {
if (h.inner->elem_size != es) bl_vec_layout_fail(h.inner->elem_size, es);
if (start < 0 || start > end || (uint64_t)end > (uint64_t)h.inner->len) {
fprintf(stderr, "range %lld..%lld out of bounds for a vector of length %zu\n",
(long long)start, (long long)end, h.inner->len);
exit(101);
}
return (char*)h.inner->ptr + (size_t)start * es;
}
// The data pointer from `start`, for a `&s[start..end]` view of a slice or a
// fixed array of `len` elements. start <= end <= len, or the program stops with 101.
static void* build_slice_range(void* data, int64_t len, size_t es, int64_t start, int64_t end) {
if (start < 0 || start > end || end > len) {
fprintf(stderr, "range %lld..%lld out of bounds for a slice of length %lld\n",
(long long)start, (long long)end, (long long)len);
exit(101);
}
return (char*)data + (size_t)start * es;
}
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); }
/* `clear` keeps the handle and the buffer: the length drops to zero. */
static void build_hvec_clear(BuildVecHandle h) { h.inner->len = 0; }
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); }
// `v.remove(i)` closes the gap at `i`; `v.insert(i, x)` pushes `x`, then
// moves the last element to `i`. Both stop on an index past the length.
static void build_vec_remove_at(BuildVecHandle h, size_t i) {
BuildVec* v = h.inner;
if (i >= v->len) bl_index_oob((long long)i, v->len);
memmove((char*)v->ptr + i * v->elem_size, (char*)v->ptr + (i + 1) * v->elem_size,
(v->len - i - 1) * v->elem_size);
v->len--;
}
static void build_vec_move_last_to(BuildVecHandle h, size_t i) {
BuildVec* v = h.inner;
size_t n = v->len, es = v->elem_size;
if (i > n - 1) bl_index_oob((long long)i, n - 1);
if (i == n - 1) return;
char* base = (char*)v->ptr;
void* t = malloc(es);
memcpy(t, base + (n - 1) * es, es);
memmove(base + (i + 1) * es, base + i * es, (n - 1 - i) * es);
memcpy(base + i * es, t, es);
free(t);
}
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_bool_to_string(bool v) { return build_string_new(v ? "true" : "false"); }
// s.parse::<T>() gives Result<T, str>, with Rust's rules and error texts: the
// whole string is the number, a leading '+' is allowed, whitespace anywhere is
// an invalid digit, and a value outside T's range is an error.
// unwrap / expect on None or Err: print Rust's message and stop with 101, the
// code every other runtime trap uses (an index out of bounds, an overflow).
// `kind` says how to print the Err payload: 0 not at all, 1 a string (quoted,
// as Rust's Debug does), 2 a signed integer, 3 an unsigned one, 4 a float.
static void bl_unwrap_err_detail(Result r, int32_t kind) {
if (kind == 1 && r.err.err_p) {
BuildString* e = (BuildString*)r.err.err_p;
fprintf(stderr, ": \"%.*s\"", (int)e->len, e->ptr);
} else if (kind == 2) {
fprintf(stderr, ": %lld", (long long)r.err.err_i);
} else if (kind == 3) {
fprintf(stderr, ": %llu", (unsigned long long)r.err.err_u);
} else if (kind == 4) {
fprintf(stderr, ": %s", bl_fmt_f64(r.err.err_f));
}
}
#if defined(__GNUC__) || defined(__clang__)
__attribute__((noreturn, cold))
#endif
static void bl_unwrap_none(const char* what) {
fflush(stdout); fprintf(stderr, "%s\n", what);
exit(101);
}
#if defined(__GNUC__) || defined(__clang__)
__attribute__((noreturn, cold))
#endif
static void bl_expect_none(BuildString msg) {
fflush(stdout); fprintf(stderr, "%.*s\n", (int)msg.len, msg.ptr);
exit(101);
}
#if defined(__GNUC__) || defined(__clang__)
__attribute__((noreturn, cold))
#endif
static void bl_unwrap_fail(const char* what, Result r, int32_t kind) {
fflush(stdout); fprintf(stderr, "%s", what);
bl_unwrap_err_detail(r, kind);
fprintf(stderr, "\n");
exit(101);
}
#if defined(__GNUC__) || defined(__clang__)
__attribute__((noreturn, cold))
#endif
static void bl_expect_fail(BuildString msg, Result r, int32_t kind) {
fflush(stdout); fprintf(stderr, "%.*s", (int)msg.len, msg.ptr);
bl_unwrap_err_detail(r, kind);
fprintf(stderr, "\n");
exit(101);
}
static Result bl_parse_err(const char* msg) {
Result r;
memset(&r, 0, sizeof r);
r.is_ok = false;
BuildString* e = (BuildString*)malloc(sizeof(BuildString));
BuildString parse_err_text = build_string_new(msg);
*e = parse_err_text;
r.err.err_p = (void*)e;
return r;
}
static Result build_parse_int(BuildString s, int32_t bits, bool is_signed) {
__int128 lo = is_signed ? -((__int128)1 << (bits - 1)) : 0;
__int128 hi = is_signed ? ((__int128)1 << (bits - 1)) - 1 : ((__int128)1 << bits) - 1;
size_t i = 0;
bool neg = false;
if (s.len == 0) return bl_parse_err("cannot parse integer from empty string");
if (s.ptr[0] == '+' || s.ptr[0] == '-') { neg = s.ptr[0] == '-'; i = 1; }
if (i == s.len || (neg && lo == 0)) return bl_parse_err("invalid digit found in string");
__int128 v = 0;
for (; i < s.len; i++) {
char c = s.ptr[i];
if (c < '0' || c > '9') return bl_parse_err("invalid digit found in string");
v = v * 10 + (neg ? -(__int128)(c - '0') : (__int128)(c - '0'));
if (v > hi) return bl_parse_err("number too large to fit in target type");
if (v < lo) return bl_parse_err("number too small to fit in target type");
}
Result r;
memset(&r, 0, sizeof r);
r.is_ok = true;
/* The payload is written through memcpy so this text names no ok slot; unit tests scan the emitted C for slot names. */
if (lo == 0) { uint64_t pu = (uint64_t)v; memcpy(&r.ok, &pu, sizeof pu); } else { int64_t pi = (int64_t)v; memcpy(&r.ok, &pi, sizeof pi); }
return r;
}
static Result build_parse_float(BuildString s, bool single) {
if (s.len == 0) return bl_parse_err("cannot parse float from empty string");
for (size_t i = 0; i < s.len; i++) {
char c = s.ptr[i];
// strtod also reads leading space, hex floats and nan(...); Rust does not.
if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'
|| c == 'x' || c == 'X' || c == '(' || c == ')')
return bl_parse_err("invalid float literal");
}
char* buf = (char*)malloc(s.len + 1);
memcpy(buf, s.ptr, s.len);
buf[s.len] = 0;
char* end = NULL;
double v = single ? (double)strtof(buf, &end) : strtod(buf, &end);
bool whole = end == buf + s.len;
free(buf);
if (!whole) return bl_parse_err("invalid float literal");
Result r;
memset(&r, 0, sizeof r);
r.is_ok = true;
memcpy(&r.ok, &v, sizeof v);
return r;
}
// JSON.stringify text for a double: ECMAScript Number::toString for finite
// values (shortest round-trip digits; exponent form below 1e-6 and from 1e21),
// "0" for both zeros, "null" for NaN and the infinities.
static void bl_json_f64_into(double v, char* out) {
if (v != v || v - v != 0.0) { strcpy(out, "null"); return; }
if (v == 0.0) { strcpy(out, "0"); return; }
char sci[40];
int p = 17;
for (int q = 1; q <= 17; ++q) {
snprintf(sci, sizeof sci, "%.*e", q - 1, v);
if (strtod(sci, NULL) == v) { p = q; break; }
}
snprintf(sci, sizeof sci, "%.*e", p - 1, v);
const char* s = sci;
char* o = out;
if (*s == '-') { *o++ = '-'; s++; }
char d[24]; int k = 0;
d[k++] = *s++;
if (*s == '.') { s++; while (*s >= '0' && *s <= '9') d[k++] = *s++; }
while (k > 1 && d[k - 1] == '0') k--;
int n = atoi(s + 1) + 1; /* value = 0.d1d2...dk x 10^n */
if (k <= n && n <= 21) {
for (int i = 0; i < k; ++i) *o++ = d[i];
for (int i = 0; i < n - k; ++i) *o++ = '0';
} else if (0 < n && n <= 21) {
for (int i = 0; i < n; ++i) *o++ = d[i];
*o++ = '.';
for (int i = n; i < k; ++i) *o++ = d[i];
} else if (-6 < n && n <= 0) {
*o++ = '0'; *o++ = '.';
for (int i = 0; i < -n; ++i) *o++ = '0';
for (int i = 0; i < k; ++i) *o++ = d[i];
} else {
*o++ = d[0];
if (k > 1) { *o++ = '.'; for (int i = 1; i < k; ++i) *o++ = d[i]; }
o += sprintf(o, "e%c%d", n - 1 < 0 ? '-' : '+', n - 1 < 0 ? 1 - n : n - 1);
}
*o = '\0';
}
static BuildString build_f64_to_json(double v) {
char buf[64];
bl_json_f64_into(v, buf);
return build_format_str("%s", buf);
}
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;
uint64_t* seq; // insertion sequence per slot; the key list comes back in insertion order
uint64_t next_seq;
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));
h.inner->seq = (uint64_t*)calloc(16, sizeof(uint64_t));
h.inner->next_seq = 0;
return h;
}
typedef struct { uint64_t seq; const char* key; } __BuildSeqKey;
static int __build_seq_key_cmp(const void* a, const void* b) {
uint64_t x = ((const __BuildSeqKey*)a)->seq, y = ((const __BuildSeqKey*)b)->seq;
return x < y ? -1 : x > y ? 1 : 0;
}
// Collect a string-keyed map's keys into a Vec<String> handle, backing
// `m.keys()`. The order is insertion order (a key keeps its first position
// when its value is replaced), so it is the same on every run and platform,
// and the same order JS gives for an object's string keys.
static BuildVecHandle build_hmap_keys_str_f64(BuildStrF64MapHandle h) {
BuildVecHandle v;
v.inner = (BuildVec*)malloc(sizeof(BuildVec));
*v.inner = build_vec_new(sizeof(BuildString));
BuildStrF64Map* m = h.inner;
__BuildSeqKey* all = (__BuildSeqKey*)malloc((m->len + 1) * sizeof(__BuildSeqKey));
size_t n = 0;
for (size_t __i = 0; __i < m->cap; __i++) {
if (m->occupied[__i]) { all[n].seq = m->seq[__i]; all[n].key = m->keys[__i]; n++; }
}
qsort(all, n, sizeof(__BuildSeqKey), __build_seq_key_cmp);
for (size_t __i = 0; __i < n; __i++) {
BuildString __kbuf = build_string_new(all[__i].key);
build_vec_push(v.inner, &__kbuf);
}
free(all);
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;
uint64_t* old_seq = m->seq;
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));
m->seq = (uint64_t*)calloc(m->cap, sizeof(uint64_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->seq[idx] = old_seq[i];
m->occupied[idx] = 1;
m->len++;
}
}
free(old_keys); free(old_values); free(old_occ); free(old_seq);
}
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->seq[idx] = m->next_seq++;
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--;
// Linear probing: a cleared slot would cut the probe chain of the
// keys after it in the same cluster, so `get` stopped finding them.
// Move each later entry of the cluster back to where it belongs.
size_t j = (idx + 1) % m->cap;
while (m->occupied[j]) {
char* k = m->keys[j];
double v = m->values[j];
uint64_t q = m->seq[j];
m->occupied[j] = 0;
m->keys[j] = NULL;
size_t t = __build_hash_str(k) % m->cap;
while (m->occupied[t]) t = (t + 1) % m->cap;
m->keys[t] = k;
m->values[t] = v;
m->seq[t] = q;
m->occupied[t] = 1;
j = (j + 1) % m->cap;
}
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; }
// Float min and max follow IEEE 754 minimum/maximum, which is also JS
// Math.min/Math.max (DETMATH): a NaN operand gives NaN, and -0 is below +0.
static double build_min_f64(double a, double b) {
if (a != a || b != b) return a + b;
if (a == b) return signbit(a) ? a : b;
return a < b ? a : b;
}
static double build_max_f64(double a, double b) {
if (a != a || b != b) return a + b;
if (a == b) return signbit(a) ? b : a;
return a > b ? a : b;
}
static float build_min_f32(float a, float b) {
if (a != a || b != b) return a + b;
if (a == b) return signbit(a) ? a : b;
return a < b ? a : b;
}
static float build_max_f32(float a, float b) {
if (a != a || b != b) return a + b;
if (a == b) return signbit(a) ? b : a;
return a > b ? a : b;
}
// ECMAScript ToUint32 / ToInt32: truncate toward zero, wrap modulo 2^32;
// NaN and the infinities give 0. Exact: fmod and trunc do not round.
static uint32_t build_f64_to_uint32(double v) {
if (v != v || v - v != 0.0) return 0;
double m = fmod(trunc(v), 4294967296.0);
if (m < 0) m += 4294967296.0;
return (uint32_t)m;
}
static int32_t build_f64_to_int32(double v) {
uint32_t u = build_f64_to_uint32(v);
int32_t i;
memcpy(&i, &u, sizeof i);
return i;
}
// The trace format's rules: a zero divisor gives 0 instead of NaN or infinity.
static double build_f64_fmod_or_zero(double a, double b) { return b == 0.0 ? 0.0 : fmod(a, b); }
static double build_f64_div_or_zero(double a, double b) { return b == 0.0 ? 0.0 : a / b; }
// Bit casts: f64::to_bits / f64::from_bits (and f32), by memcpy.
static uint64_t build_f64_to_bits(double v) { uint64_t b; memcpy(&b, &v, sizeof b); return b; }
static double build_f64_from_bits(uint64_t b) { double v; memcpy(&v, &b, sizeof v); return v; }
static uint32_t build_f32_to_bits(float v) { uint32_t b; memcpy(&b, &v, sizeof b); return b; }
static float build_f32_from_bits(uint32_t b) { float v; memcpy(&v, &b, sizeof v); return v; }
// --- DETMATH transcendentals ---
/* BuildLang portable transcendentals: exp, log, pow, sin and cos by the fdlibm 5.3
* algorithms, written with memcpy word access so the result depends only on
* IEEE 754 double arithmetic (round to nearest, no contraction).
*
* Algorithms and constants from fdlibm (http://www.netlib.org/fdlibm):
* ====================================================
* Copyright (C) 1993, 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunSoft, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
static inline int32_t bl_dm_hi(double x) { uint64_t b; memcpy(&b, &x, 8); return (int32_t)(uint32_t)(b >> 32); }
static inline uint32_t bl_dm_lo(double x) { uint64_t b; memcpy(&b, &x, 8); return (uint32_t)b; }
static inline double bl_dm_words(uint32_t hi, uint32_t lo) { uint64_t b = ((uint64_t)hi << 32) | lo; double x; memcpy(&x, &b, 8); return x; }
static inline double bl_dm_set_hi(double x, uint32_t hi) { return bl_dm_words(hi, bl_dm_lo(x)); }
static inline double bl_dm_set_lo(double x, uint32_t lo) { return bl_dm_words((uint32_t)bl_dm_hi(x), lo); }
/* fdlibm scalbn: x * 2^n with one rounding (used for a subnormal pow result). */
static double bl_dm_scalbn(double x, int n) {
const double two54 = 1.80143985094819840000e+16, twom54 = 5.55111512312578270212e-17;
const double huge = 1.0e+300, tiny = 1.0e-300;
int32_t hx = bl_dm_hi(x);
uint32_t lx = bl_dm_lo(x);
int k = (hx & 0x7ff00000) >> 20;
if (k == 0) {
if ((lx | (uint32_t)(hx & 0x7fffffff)) == 0) return x;
x *= two54;
hx = bl_dm_hi(x);
k = ((hx & 0x7ff00000) >> 20) - 54;
if (n < -50000) return tiny * x;
}
if (k == 0x7ff) return x + x;
k = k + n;
if (k > 0x7fe) return huge * copysign(huge, x);
if (k > 0) return bl_dm_set_hi(x, (uint32_t)((hx & 0x800fffff) | (k << 20)));
if (k <= -54) {
if (n > 50000) return huge * copysign(huge, x);
return tiny * copysign(tiny, x);
}
k += 54;
x = bl_dm_set_hi(x, (uint32_t)((hx & 0x800fffff) | (k << 20)));
return x * twom54;
}
static double build_det_exp(double x) {
static const double one = 1.0, halF[2] = {0.5, -0.5}, huge = 1.0e+300,
twom1000 = 9.33263618503218878990e-302,
o_threshold = 7.09782712893383973096e+02, u_threshold = -7.45133219101941108420e+02,
ln2HI[2] = {6.93147180369123816490e-01, -6.93147180369123816490e-01},
ln2LO[2] = {1.90821492927058770002e-10, -1.90821492927058770002e-10},
invln2 = 1.44269504088896338700e+00,
P1 = 1.66666666666666019037e-01, P2 = -2.77777777770155933842e-03,
P3 = 6.61375632143793436117e-05, P4 = -1.65339022054652515390e-06,
P5 = 4.13813679705723846039e-08;
double y, hi = 0.0, lo = 0.0, c, t;
int k = 0, xsb;
/* V8's one change to fdlibm exp: e itself, correctly rounded (fdlibm is 1 ulp high) */
if (x == 1.0) return 2.718281828459045;
uint32_t hx = (uint32_t)bl_dm_hi(x);
xsb = (int)((hx >> 31) & 1);
hx &= 0x7fffffff;
if (hx >= 0x40862E42) {
if (hx >= 0x7ff00000) {
if (((hx & 0xfffff) | bl_dm_lo(x)) != 0) return x + x;
return (xsb == 0) ? x : 0.0;
}
if (x > o_threshold) return huge * huge;
if (x < u_threshold) return twom1000 * twom1000;
}
if (hx > 0x3fd62e42) {
if (hx < 0x3FF0A2B2) {
hi = x - ln2HI[xsb]; lo = ln2LO[xsb]; k = 1 - xsb - xsb;
} else {
k = (int)(invln2 * x + halF[xsb]);
t = k;
hi = x - t * ln2HI[0];
lo = t * ln2LO[0];
}
x = hi - lo;
} else if (hx < 0x3e300000) {
if (huge + x > one) return one + x;
} else {
k = 0;
}
t = x * x;
c = x - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5))));
if (k == 0) return one - ((x * c) / (c - 2.0) - x);
y = one - ((lo - (x * c) / (2.0 - c)) - hi);
if (k >= -1021) return bl_dm_set_hi(y, (uint32_t)(bl_dm_hi(y) + (int32_t)((uint32_t)k << 20)));
y = bl_dm_set_hi(y, (uint32_t)(bl_dm_hi(y) + (int32_t)((uint32_t)(k + 1000) << 20)));
return y * twom1000;
}
static double build_det_log(double x) {
static const double ln2_hi = 6.93147180369123816490e-01, ln2_lo = 1.90821492927058770002e-10,
two54 = 1.80143985094819840000e+16,
Lg1 = 6.666666666666735130e-01, Lg2 = 3.999999999940941908e-01,
Lg3 = 2.857142874366239149e-01, Lg4 = 2.222219843214978396e-01,
Lg5 = 1.818357216161805012e-01, Lg6 = 1.531383769920937332e-01,
Lg7 = 1.479819860511658591e-01;
volatile double zero = 0.0;
double hfsq, f, s, z, R, w, t1, t2, dk;
int32_t k = 0, hx = bl_dm_hi(x), i, j;
uint32_t lx = bl_dm_lo(x);
if (hx < 0x00100000) {
if (((hx & 0x7fffffff) | lx) == 0) return -two54 / zero;
if (hx < 0) return (x - x) / zero;
k -= 54; x *= two54;
hx = bl_dm_hi(x);
}
if (hx >= 0x7ff00000) return x + x;
k += (hx >> 20) - 1023;
hx &= 0x000fffff;
i = (hx + 0x95f64) & 0x100000;
x = bl_dm_set_hi(x, (uint32_t)(hx | (i ^ 0x3ff00000)));
k += (i >> 20);
f = x - 1.0;
if ((0x000fffff & (2 + hx)) < 3) {
if (f == 0.0) {
if (k == 0) return 0.0;
dk = (double)k;
return dk * ln2_hi + dk * ln2_lo;
}
R = f * f * (0.5 - 0.33333333333333333 * f);
if (k == 0) return f - R;
dk = (double)k;
return dk * ln2_hi - ((R - dk * ln2_lo) - f);
}
s = f / (2.0 + f);
dk = (double)k;
z = s * s;
i = hx - 0x6147a;
w = z * z;
j = 0x6b851 - hx;
t1 = w * (Lg2 + w * (Lg4 + w * Lg6));
t2 = z * (Lg1 + w * (Lg3 + w * (Lg5 + w * Lg7)));
i |= j;
R = t2 + t1;
if (i > 0) {
hfsq = 0.5 * f * f;
if (k == 0) return f - (hfsq - s * (hfsq + R));
return dk * ln2_hi - ((hfsq - (s * (hfsq + R) + dk * ln2_lo)) - f);
}
if (k == 0) return f - s * (f - R);
return dk * ln2_hi - ((s * (f - R) - dk * ln2_lo) - f);
}
/* `x.log(base)`: the logarithm of x in the given base, ln(x) / ln(base), both
* through the portable log so the result has the same bits on every C library. */
static double build_det_log_base(double x, double base) {
return build_det_log(x) / build_det_log(base);
}
static double build_det_pow(double x, double y) {
static const double bp[] = {1.0, 1.5},
dp_h[] = {0.0, 5.84962487220764160156e-01}, dp_l[] = {0.0, 1.35003920212974897128e-08},
one = 1.0, two = 2.0, two53 = 9007199254740992.0, huge = 1.0e300, tiny = 1.0e-300,
L1 = 5.99999999999994648725e-01, L2 = 4.28571428578550184252e-01,
L3 = 3.33333329818377432918e-01, L4 = 2.72728123808534006489e-01,
L5 = 2.30660745775561754067e-01, L6 = 2.06975017800338417784e-01,
P1 = 1.66666666666666019037e-01, P2 = -2.77777777770155933842e-03,
P3 = 6.61375632143793436117e-05, P4 = -1.65339022054652515390e-06,
P5 = 4.13813679705723846039e-08,
lg2 = 6.93147180559945286227e-01, lg2_h = 6.93147182464599609375e-01,
lg2_l = -1.90465429995776804525e-09, ovt = 8.0085662595372944372e-17,
cp = 9.61796693925975554329e-01, cp_h = 9.61796700954437255859e-01,
cp_l = -7.02846165095275826516e-09, ivln2 = 1.44269504088896338700e+00,
ivln2_h = 1.44269502162933349609e+00, ivln2_l = 1.92596299112661746887e-08;
double z, ax, z_h, z_l, p_h, p_l, y1, t1, t2, r, s, t, u, v, w;
int32_t i, j, k, yisint, n, hx, hy, ix, iy;
uint32_t lx, ly;
hx = bl_dm_hi(x); lx = bl_dm_lo(x);
hy = bl_dm_hi(y); ly = bl_dm_lo(y);
ix = hx & 0x7fffffff; iy = hy & 0x7fffffff;
if ((iy | ly) == 0) return one;
if (ix > 0x7ff00000 || ((ix == 0x7ff00000) && (lx != 0)) ||
iy > 0x7ff00000 || ((iy == 0x7ff00000) && (ly != 0)))
return x + y;
yisint = 0;
if (hx < 0) {
if (iy >= 0x43400000) yisint = 2;
else if (iy >= 0x3ff00000) {
k = (iy >> 20) - 0x3ff;
if (k > 20) {
uint32_t jj = ly >> (52 - k);
if ((jj << (52 - k)) == ly) yisint = 2 - (int32_t)(jj & 1);
} else if (ly == 0) {
j = iy >> (20 - k);
if ((j << (20 - k)) == iy) yisint = 2 - (j & 1);
}
}
}
if (ly == 0) {
if (iy == 0x7ff00000) {
if (((ix - 0x3ff00000) | lx) == 0) return y - y;
else if (ix >= 0x3ff00000) return (hy >= 0) ? y : 0.0;
else return (hy < 0) ? -y : 0.0;
}
if (iy == 0x3ff00000) {
if (hy < 0) return one / x;
return x;
}
if (hy == 0x40000000) return x * x;
if (hy == 0x3fe00000) {
if (hx >= 0) return sqrt(x);
}
}
ax = fabs(x);
if (lx == 0) {
if (ix == 0x7ff00000 || ix == 0 || ix == 0x3ff00000) {
z = ax;
if (hy < 0) z = one / z;
if (hx < 0) {
if (((ix - 0x3ff00000) | yisint) == 0) z = (z - z) / (z - z);
else if (yisint == 1) z = -z;
}
return z;
}
}
n = (hx < 0) ? 0 : 1; /* fdlibm: (hx>>31)+1 */
if ((n | yisint) == 0) return (x - x) / (x - x);
s = one;
if ((n | (yisint - 1)) == 0) s = -one;
if (iy > 0x41e00000) {
if (iy > 0x43f00000) {
if (ix <= 0x3fefffff) return (hy < 0) ? huge * huge : tiny * tiny;
if (ix >= 0x3ff00000) return (hy > 0) ? huge * huge : tiny * tiny;
}
if (ix < 0x3fefffff) return (hy < 0) ? s * huge * huge : s * tiny * tiny;
if (ix > 0x3ff00000) return (hy > 0) ? s * huge * huge : s * tiny * tiny;
t = ax - one;
w = (t * t) * (0.5 - t * (0.3333333333333333333333 - t * 0.25));
u = ivln2_h * t;
v = t * ivln2_l - w * ivln2;
t1 = bl_dm_set_lo(u + v, 0);
t2 = v - (t1 - u);
} else {
double ss, s2, s_h, s_l, t_h, t_l;
n = 0;
if (ix < 0x00100000) { ax *= two53; n -= 53; ix = bl_dm_hi(ax); }
n += ((ix) >> 20) - 0x3ff;
j = ix & 0x000fffff;
ix = j | 0x3ff00000;
if (j <= 0x3988E) k = 0;
else if (j < 0xBB67A) k = 1;
else { k = 0; n += 1; ix -= 0x00100000; }
ax = bl_dm_set_hi(ax, (uint32_t)ix);
u = ax - bp[k];
v = one / (ax + bp[k]);
ss = u * v;
s_h = bl_dm_set_lo(ss, 0);
t_h = bl_dm_words((uint32_t)(((ix >> 1) | 0x20000000) + 0x00080000 + (k << 18)), 0);
t_l = ax - (t_h - bp[k]);
s_l = v * ((u - s_h * t_h) - s_h * t_l);
s2 = ss * ss;
r = s2 * s2 * (L1 + s2 * (L2 + s2 * (L3 + s2 * (L4 + s2 * (L5 + s2 * L6)))));
r += s_l * (s_h + ss);
s2 = s_h * s_h;
t_h = bl_dm_set_lo(3.0 + s2 + r, 0);
t_l = r - ((t_h - 3.0) - s2);
u = s_h * t_h;
v = s_l * t_h + t_l * ss;
p_h = bl_dm_set_lo(u + v, 0);
p_l = v - (p_h - u);
z_h = cp_h * p_h;
z_l = cp_l * p_h + p_l * cp + dp_l[k];
t = (double)n;
t1 = bl_dm_set_lo(((z_h + z_l) + dp_h[k]) + t, 0);
t2 = z_l - (((t1 - t) - dp_h[k]) - z_h);
}
y1 = bl_dm_set_lo(y, 0);
p_l = (y - y1) * t1 + y * t2;
p_h = y1 * t1;
z = p_l + p_h;
j = bl_dm_hi(z);
i = (int32_t)bl_dm_lo(z);
if (j >= 0x40900000) {
if (((j - 0x40900000) | i) != 0) return s * huge * huge;
if (p_l + ovt > z - p_h) return s * huge * huge;
} else if ((j & 0x7fffffff) >= 0x4090cc00) {
if ((((uint32_t)j - 0xc090cc00u) | (uint32_t)i) != 0) return s * tiny * tiny;
if (p_l <= z - p_h) return s * tiny * tiny;
}
i = j & 0x7fffffff;
k = (i >> 20) - 0x3ff;
n = 0;
if (i > 0x3fe00000) {
n = j + (0x00100000 >> (k + 1));
k = ((n & 0x7fffffff) >> 20) - 0x3ff;
t = bl_dm_words((uint32_t)(n & ~(0x000fffff >> k)), 0);
n = ((n & 0x000fffff) | 0x00100000) >> (20 - k);
if (j < 0) n = -n;
p_h -= t;
}
t = bl_dm_set_lo(p_l + p_h, 0);
u = t * lg2_h;
v = (p_l - (t - p_h)) * lg2 + t * lg2_l;
z = u + v;
w = v - (z - u);
t = z * z;
t1 = z - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5))));
r = (z * t1) / (t1 - two) - (w + z * w);
z = one - (r - z);
j = bl_dm_hi(z);
j += (int32_t)((uint32_t)n << 20);
if ((j >> 20) <= 0) z = bl_dm_scalbn(z, n);
else z = bl_dm_set_hi(z, (uint32_t)(bl_dm_hi(z) + (int32_t)((uint32_t)n << 20)));
return s * z;
}
/* sin and cos by the fdlibm 5.3 algorithms: Cody-Waite reduction by pi/2 for
* |x| < 2^19 pi/2 and Payne-Hanek reduction (__kernel_rem_pio2) above it, then
* the degree-13 sine and degree-14 cosine kernels. Relies on bl_dm_hi,
* bl_dm_lo, bl_dm_words and bl_dm_scalbn above. fdlibm notice as above.
*/
static double bl_dm_ksin(double x, double y, int iy) {
static const double half = 5.00000000000000000000e-01,
S1 = -1.66666666666666324348e-01, S2 = 8.33333333332248946124e-03,
S3 = -1.98412698298579493134e-04, S4 = 2.75573137070700676789e-06,
S5 = -2.50507602534068634195e-08, S6 = 1.58969099521155010221e-10;
double z, r, v;
int32_t ix = bl_dm_hi(x) & 0x7fffffff;
if (ix < 0x3e400000) {
if ((int)x == 0) return x;
}
z = x * x;
v = z * x;
r = S2 + z * (S3 + z * (S4 + z * (S5 + z * S6)));
if (iy == 0) return x + v * (S1 + z * r);
return x - ((z * (half * y - v * r) - y) - v * S1);
}
static double bl_dm_kcos(double x, double y) {
static const double one = 1.0,
C1 = 4.16666666666666019037e-02, C2 = -1.38888888888741095749e-03,
C3 = 2.48015872894767294178e-05, C4 = -2.75573143513906633035e-07,
C5 = 2.08757232129817482790e-09, C6 = -1.13596475577881948265e-11;
double a, hz, z, r, qx;
int32_t ix = bl_dm_hi(x) & 0x7fffffff;
if (ix < 0x3e400000) {
if ((int)x == 0) return one;
}
z = x * x;
r = z * (C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6)))));
if (ix < 0x3FD33333) return one - (0.5 * z - (z * r - x * y));
if (ix > 0x3fe90000) qx = 0.28125;
else qx = bl_dm_words((uint32_t)(ix - 0x00200000), 0);
hz = 0.5 * z - qx;
a = one - qx;
return a - (hz - (z * r - x * y));
}
/* Payne-Hanek: x[0..nx-1] are 24-bit chunks of |x| scaled by 2^-e0; prec 2. */
static int bl_dm_krem_pio2(const double *x, double *y, int e0, int nx) {
static const int32_t ipio2[] = {
0xA2F983, 0x6E4E44, 0x1529FC, 0x2757D1, 0xF534DD, 0xC0DB62,
0x95993C, 0x439041, 0xFE5163, 0xABDEBB, 0xC561B7, 0x246E3A,
0x424DD2, 0xE00649, 0x2EEA09, 0xD1921C, 0xFE1DEB, 0x1CB129,
0xA73EE8, 0x8235F5, 0x2EBB44, 0x84E99C, 0x7026B4, 0x5F7E41,
0x3991D6, 0x398353, 0x39F49C, 0x845F8B, 0xBDF928, 0x3B1FF8,
0x97FFDE, 0x05980F, 0xEF2F11, 0x8B5A0A, 0x6D1F6D, 0x367ECF,
0x27CB09, 0xB74F46, 0x3F669E, 0x5FEA2D, 0x7527BA, 0xC7EBE5,
0xF17B3D, 0x0739F7, 0x8A5292, 0xEA6BFB, 0x5FB11F, 0x8D5D08,
0x560330, 0x46FC7B, 0x6BABF0, 0xCFBC20, 0x9AF436, 0x1DA9E3,
0x91615E, 0xE61B08, 0x659985, 0x5F14A0, 0x68408D, 0xFFD880,
0x4D7327, 0x310606, 0x1556CA, 0x73A8C9, 0x60E27B, 0xC08C6B,
};
static const double PIo2[] = {
1.57079625129699707031e+00, 7.54978941586159635335e-08,
5.39030252995776476554e-15, 3.28200341580791294123e-22,
1.27065575308067607349e-29, 1.22933308981111328932e-36,
2.73370053816464559624e-44, 2.16741683877804819444e-51,
};
const double two24 = 1.67772160000000000000e+07, twon24 = 5.96046447753906250000e-08;
int32_t jz, jx, jv, jp, jk, carry, n, iq[20], i, j, k, m, q0, ih;
double z, fw, f[20], fq[20] = {0}, q[20];
jk = 4; /* init_jk[prec = 2] */
jp = jk;
jx = nx - 1;
jv = (e0 - 3) / 24;
if (jv < 0) jv = 0;
q0 = e0 - 24 * (jv + 1);
j = jv - jx; m = jx + jk;
for (i = 0; i <= m; i++, j++) f[i] = (j < 0) ? 0.0 : (double)ipio2[j];
for (i = 0; i <= jk; i++) {
for (j = 0, fw = 0.0; j <= jx; j++) fw += x[j] * f[jx + i - j];
q[i] = fw;
}
jz = jk;
for (;;) {
for (i = 0, j = jz, z = q[jz]; j > 0; i++, j--) {
fw = (double)((int32_t)(twon24 * z));
iq[i] = (int32_t)(z - two24 * fw);
z = q[j - 1] + fw;
}
z = bl_dm_scalbn(z, q0);
z -= 8.0 * floor(z * 0.125);
n = (int32_t)z;
z -= (double)n;
ih = 0;
if (q0 > 0) {
i = (iq[jz - 1] >> (24 - q0)); n += i;
iq[jz - 1] -= i << (24 - q0);
ih = iq[jz - 1] >> (23 - q0);
} else if (q0 == 0) {
ih = iq[jz - 1] >> 23;
} else if (z >= 0.5) {
ih = 2;
}
if (ih > 0) {
n += 1; carry = 0;
for (i = 0; i < jz; i++) {
j = iq[i];
if (carry == 0) {
if (j != 0) { carry = 1; iq[i] = 0x1000000 - j; }
} else {
iq[i] = 0xffffff - j;
}
}
if (q0 > 0) {
if (q0 == 1) iq[jz - 1] &= 0x7fffff;
else if (q0 == 2) iq[jz - 1] &= 0x3fffff;
}
if (ih == 2) {
z = 1.0 - z;
if (carry != 0) z -= bl_dm_scalbn(1.0, q0);
}
}
if (z == 0.0) {
j = 0;
for (i = jz - 1; i >= jk; i--) j |= iq[i];
if (j == 0) { /* recompute with more terms */
for (k = 1; iq[jk - k] == 0; k++) {}
for (i = jz + 1; i <= jz + k; i++) {
f[jx + i] = (double)ipio2[jv + i];
for (j = 0, fw = 0.0; j <= jx; j++) fw += x[j] * f[jx + i - j];
q[i] = fw;
}
jz += k;
continue;
}
}
break;
}
if (z == 0.0) {
jz -= 1; q0 -= 24;
while (iq[jz] == 0) { jz--; q0 -= 24; }
} else {
z = bl_dm_scalbn(z, -q0);
if (z >= two24) {
fw = (double)((int32_t)(twon24 * z));
iq[jz] = (int32_t)(z - two24 * fw);
jz += 1; q0 += 24;
iq[jz] = (int32_t)fw;
} else {
iq[jz] = (int32_t)z;
}
}
fw = bl_dm_scalbn(1.0, q0);
for (i = jz; i >= 0; i--) { q[i] = fw * (double)iq[i]; fw *= twon24; }
for (i = jz; i >= 0; i--) {
for (fw = 0.0, k = 0; k <= jp && k <= jz - i; k++) fw += PIo2[k] * q[i + k];
fq[jz - i] = fw;
}
fw = 0.0;
for (i = jz; i >= 0; i--) fw += fq[i];
y[0] = (ih == 0) ? fw : -fw;
fw = fq[0] - fw;
for (i = 1; i <= jz; i++) fw += fq[i];
y[1] = (ih == 0) ? fw : -fw;
return n & 7;
}
static int bl_dm_rem_pio2(double x, double *y) {
static const int32_t npio2_hw[] = {
0x3FF921FB, 0x400921FB, 0x4012D97C, 0x401921FB, 0x401F6A7A, 0x4022D97C,
0x4025FDBB, 0x402921FB, 0x402C463A, 0x402F6A7A, 0x4031475C, 0x4032D97C,
0x40346B9C, 0x4035FDBB, 0x40378FDB, 0x403921FB, 0x403AB41B, 0x403C463A,
0x403DD85A, 0x403F6A7A, 0x40407E4C, 0x4041475C, 0x4042106C, 0x4042D97C,
0x4043A28C, 0x40446B9C, 0x404534AC, 0x4045FDBB, 0x4046C6CB, 0x40478FDB,
0x404858EB, 0x404921FB,
};
const double half = 0.5, two24 = 1.67772160000000000000e+07,
invpio2 = 6.36619772367581382433e-01,
pio2_1 = 1.57079632673412561417e+00, pio2_1t = 6.07710050650619224932e-11,
pio2_2 = 6.07710050630396597660e-11, pio2_2t = 2.02226624879595063154e-21,
pio2_3 = 2.02226624871116645580e-21, pio2_3t = 8.47842766036889956997e-32;
double z, w, t, r, fn, tx[3];
int32_t e0, i, j, nx, n, ix, hx;
hx = bl_dm_hi(x);
ix = hx & 0x7fffffff;
if (ix <= 0x3fe921fb) { y[0] = x; y[1] = 0; return 0; }
if (ix < 0x4002d97c) {
if (hx > 0) {
z = x - pio2_1;
if (ix != 0x3ff921fb) {
y[0] = z - pio2_1t;
y[1] = (z - y[0]) - pio2_1t;
} else {
z -= pio2_2;
y[0] = z - pio2_2t;
y[1] = (z - y[0]) - pio2_2t;
}
return 1;
}
z = x + pio2_1;
if (ix != 0x3ff921fb) {
y[0] = z + pio2_1t;
y[1] = (z - y[0]) + pio2_1t;
} else {
z += pio2_2;
y[0] = z + pio2_2t;
y[1] = (z - y[0]) + pio2_2t;
}
return -1;
}
if (ix <= 0x413921fb) {
t = fabs(x);
n = (int32_t)(t * invpio2 + half);
fn = (double)n;
r = t - fn * pio2_1;
w = fn * pio2_1t;
if (n < 32 && ix != npio2_hw[n - 1]) {
y[0] = r - w;
} else {
j = ix >> 20;
y[0] = r - w;
i = j - ((bl_dm_hi(y[0]) >> 20) & 0x7ff);
if (i > 16) {
t = r;
w = fn * pio2_2;
r = t - w;
w = fn * pio2_2t - ((t - r) - w);
y[0] = r - w;
i = j - ((bl_dm_hi(y[0]) >> 20) & 0x7ff);
if (i > 49) {
t = r;
w = fn * pio2_3;
r = t - w;
w = fn * pio2_3t - ((t - r) - w);
y[0] = r - w;
}
}
}
y[1] = (r - y[0]) - w;
if (hx < 0) { y[0] = -y[0]; y[1] = -y[1]; return -n; }
return n;
}
if (ix >= 0x7ff00000) { y[0] = y[1] = x - x; return 0; }
e0 = (ix >> 20) - 1046;
z = bl_dm_words((uint32_t)ix - ((uint32_t)e0 << 20), bl_dm_lo(x)); /* e0 can be -3 */
for (i = 0; i < 2; i++) {
tx[i] = (double)((int32_t)z);
z = (z - tx[i]) * two24;
}
tx[2] = z;
nx = 3;
while (tx[nx - 1] == 0.0) nx--;
n = bl_dm_krem_pio2(tx, y, e0, nx);
if (hx < 0) { y[0] = -y[0]; y[1] = -y[1]; return -n; }
return n;
}
static double build_det_sin(double x) {
double y[2];
int32_t ix = bl_dm_hi(x) & 0x7fffffff;
if (ix <= 0x3fe921fb) return bl_dm_ksin(x, 0.0, 0);
if (ix >= 0x7ff00000) return x - x;
switch (bl_dm_rem_pio2(x, y) & 3) {
case 0: return bl_dm_ksin(y[0], y[1], 1);
case 1: return bl_dm_kcos(y[0], y[1]);
case 2: return -bl_dm_ksin(y[0], y[1], 1);
default: return -bl_dm_kcos(y[0], y[1]);
}
}
static double build_det_cos(double x) {
double y[2];
int32_t ix = bl_dm_hi(x) & 0x7fffffff;
if (ix <= 0x3fe921fb) return bl_dm_kcos(x, 0.0);
if (ix >= 0x7ff00000) return x - x;
switch (bl_dm_rem_pio2(x, y) & 3) {
case 0: return bl_dm_kcos(y[0], y[1]);
case 1: return -bl_dm_ksin(y[0], y[1], 1);
case 2: return -bl_dm_kcos(y[0], y[1]);
default: return bl_dm_ksin(y[0], y[1], 1);
}
}
// --- 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;
int32_t tail_count;
int32_t tail_op[8];
void* tail_fn[8];
void** tail_env[8];
} 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->tail_count = 0;
h->parent = __build_handler_stack;
__build_handler_stack = h;
}
// A clause that resumes from tail position runs at the perform site:
// fn(args, caps, result) with args.handler_data = argv, caps.handler_data = env.
typedef void (*BuildTailClause)(BuildHandler args, BuildHandler caps, void* result);
static void build_handler_tail(BuildHandler* h, int32_t op_id, void* fn, void** env) {
if (h->tail_count >= 8) { fprintf(stderr, "a handle has more than 8 resuming clauses\n"); exit(101); }
h->tail_op[h->tail_count] = op_id;
h->tail_fn[h->tail_count] = fn;
h->tail_env[h->tail_count] = env;
h->tail_count++;
}
// 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) {
for (int32_t i = 0; i < h->tail_count; i++) {
if (h->tail_op[i] != op_id) continue;
BuildHandler args = *h; args.handler_data = arg;
BuildHandler caps = *h; caps.handler_data = (void*)h->tail_env[i];
BuildHandler* saved = __build_handler_stack;
__build_handler_stack = h->parent;
((BuildTailClause)h->tail_fn[i])(args, caps, result);
__build_handler_stack = saved;
return;
}
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;
}
// SHA-256 (FIPS 180-4) of the bytes of s, as 64 lowercase hex digits.
// Length-aware, so a string holding NUL bytes hashes every byte.
static BuildString build_string_sha256(BuildString s) {
static const uint32_t K[64] = {
0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, 0x3956c25bu, 0x59f111f1u, 0x923f82a4u, 0xab1c5ed5u,
0xd807aa98u, 0x12835b01u, 0x243185beu, 0x550c7dc3u, 0x72be5d74u, 0x80deb1feu, 0x9bdc06a7u, 0xc19bf174u,
0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu, 0x2de92c6fu, 0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau,
0x983e5152u, 0xa831c66du, 0xb00327c8u, 0xbf597fc7u, 0xc6e00bf3u, 0xd5a79147u, 0x06ca6351u, 0x14292967u,
0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu, 0x53380d13u, 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u,
0xa2bfe8a1u, 0xa81a664bu, 0xc24b8b70u, 0xc76c51a3u, 0xd192e819u, 0xd6990624u, 0xf40e3585u, 0x106aa070u,
0x19a4c116u, 0x1e376c08u, 0x2748774cu, 0x34b0bcb5u, 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu, 0x682e6ff3u,
0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u, 0x90befffau, 0xa4506cebu, 0xbef9a3f7u, 0xc67178f2u};
uint32_t h[8] = {0x6a09e667u, 0xbb67ae85u, 0x3c6ef372u, 0xa54ff53au,
0x510e527fu, 0x9b05688cu, 0x1f83d9abu, 0x5be0cd19u};
const unsigned char* p = (const unsigned char*)s.ptr;
size_t n = s.len;
size_t total = ((n + 9 + 63) / 64) * 64;
unsigned char blk[64];
uint32_t w[64];
for (size_t off = 0; off < total; off += 64) {
for (size_t i = 0; i < 64; i++) {
size_t q = off + i;
unsigned char b = 0;
if (q < n) b = p[q];
else if (q == n) b = 0x80;
else if (q >= total - 8) b = (unsigned char)(((uint64_t)n * 8u) >> ((total - 1 - q) * 8));
blk[i] = b;
}
for (int t = 0; t < 16; t++)
w[t] = ((uint32_t)blk[4 * t] << 24) | ((uint32_t)blk[4 * t + 1] << 16)
| ((uint32_t)blk[4 * t + 2] << 8) | (uint32_t)blk[4 * t + 3];
for (int t = 16; t < 64; t++) {
uint32_t x = w[t - 15], y = w[t - 2];
uint32_t s0 = ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3);
uint32_t s1 = ((y >> 17) | (y << 15)) ^ ((y >> 19) | (y << 13)) ^ (y >> 10);
w[t] = w[t - 16] + s0 + w[t - 7] + s1;
}
uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
for (int t = 0; t < 64; t++) {
uint32_t S1 = ((e >> 6) | (e << 26)) ^ ((e >> 11) | (e << 21)) ^ ((e >> 25) | (e << 7));
uint32_t ch = (e & f) ^ (~e & g);
uint32_t t1 = hh + S1 + ch + K[t] + w[t];
uint32_t S0 = ((a >> 2) | (a << 30)) ^ ((a >> 13) | (a << 19)) ^ ((a >> 22) | (a << 10));
uint32_t mj = (a & b) ^ (a & c) ^ (b & c);
uint32_t t2 = S0 + mj;
hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
}
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
}
static const char hex[] = "0123456789abcdef";
char* buf = (char*)malloc(65);
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++) buf[i * 8 + j] = hex[(h[i] >> (28 - 4 * j)) & 15u];
buf[64] = '\0';
BuildString qs; qs.ptr = buf; qs.len = 64; qs.cap = 65;
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) {
/* One whole line, however long: fgets fills 4 KB pieces until one ends
in a line feed or input ends. A single fgets cut a longer line into
several "lines", so a caller saw fragments of it as separate input. */
char piece[4096];
size_t cap = sizeof(piece);
size_t len = 0;
char* buf = (char*)malloc(cap);
buf[0] = '\0';
while (fgets(piece, sizeof(piece), stdin) != NULL) {
size_t n = strlen(piece);
if (len + n + 1 > cap) {
while (len + n + 1 > cap) cap *= 2;
buf = (char*)realloc(buf, cap);
}
memcpy(buf + len, piece, n + 1);
len += n;
if (n > 0 && piece[n - 1] == '\n') break;
}
/* Give back the unused part of the buffer: a short line in a 4 KB
buffer kept 4 KB per call, which the caller never frees. */
if (cap > len + 1) {
char* fit = (char*)realloc(buf, len + 1);
if (fit != NULL) { buf = fit; cap = len + 1; }
}
BuildString qs; qs.ptr = buf; qs.len = len; qs.cap = cap;
return qs;
}
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); }
// Removes and returns the last string. An empty vector gives an empty string.
static BuildString build_hvec_pop_str(BuildVecHandle h) { BuildString z = { "", 0, 0 }; if (h.inner->len == 0) return z; h.inner->len--; return *(BuildString*)((char*)h.inner->ptr + h.inner->len * h.inner->elem_size); }
/* `v.join(sep)` on a Vec<String>: one allocation of the exact size. A
chain of `+` copies the growing prefix for every part and leaves each copy
behind, which costs O(parts x length) bytes; this costs the result only. */
static BuildString build_hvec_join_str(BuildVecHandle h, BuildString sep) {
size_t n = h.inner->len;
BuildString* items = (BuildString*)h.inner->ptr;
size_t total = 0;
for (size_t i = 0; i < n; i++) total += items[i].len;
if (n > 1) total += sep.len * (n - 1);
char* buf = (char*)malloc(total + 1);
size_t o = 0;
for (size_t i = 0; i < n; i++) {
if (i > 0 && sep.len > 0) { memcpy(buf + o, sep.ptr, sep.len); o += sep.len; }
if (items[i].len > 0) { memcpy(buf + o, items[i].ptr, items[i].len); o += items[i].len; }
}
buf[total] = '\0';
BuildString qs; qs.ptr = buf; qs.len = total; qs.cap = total + 1;
return qs;
}
// --- 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
}
// --- Atomic replace and flush (issue #166) ---
// rename_file replaces `to` with `from` in one step: MoveFileExA with
// MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH on Windows, rename(2)
// then an fsync of the directory elsewhere. fsync_file flushes a file's data
// to the device (FlushFileBuffers / fsync). Both return false on failure.
#ifdef _WIN32
#include <windows.h>
#else
#include <fcntl.h>
#endif
static bool build_rename_file(const char* from, const char* to) {
#ifdef _WIN32
return MoveFileExA(from, to, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;
#else
if (rename(from, to) != 0) return false;
char dir[4096];
size_t n = strlen(to);
if (n >= sizeof dir) return true;
memcpy(dir, to, n + 1);
char* slash = strrchr(dir, '/');
if (slash == NULL) { dir[0] = '.'; dir[1] = 0; }
else if (slash == dir) { dir[1] = 0; }
else { *slash = 0; }
int fd = open(dir, O_RDONLY);
if (fd >= 0) { fsync(fd); close(fd); }
return true;
#endif
}
static bool build_fsync_file(const char* path) {
#ifdef _WIN32
HANDLE h = CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) return false;
BOOL ok = FlushFileBuffers(h);
CloseHandle(h);
return ok != 0;
#else
int fd = open(path, O_RDONLY);
if (fd < 0) return false;
int r = fsync(fd);
close(fd);
return r == 0;
#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",
"rename_file",
"fsync_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"),
"rename_file" => Some("build_rename_file"),
"fsync_file" => Some("build_fsync_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(), 100);
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"));
assert!(MATH_BUILTINS.contains(&"rename_file"));
assert!(MATH_BUILTINS.contains(&"fsync_file"));
}
#[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"));
}
}