Files
AILang/runtime/str.c
T
Brummel 26fb3459d8 GREEN: io/print_str byte-faithful via @fputs(@stdout) — closes #29
The runtime print path now writes exactly the bytes of its
argument with no implicit trailing newline. `io/print_str` is
byte-faithful; authors who want a newline emit `(do io/print_str
"\n")` themselves.

## Codegen

`crates/ailang-codegen/src/lib.rs`:
- Module preamble: `@puts(ptr)` → `@fputs(ptr, ptr)` plus
  `@stdout = external global ptr` (libc's `FILE *stdout`).
- Effect-op lowering for `io/print_str`: emit
  `getelementptr +8` then `load ptr, ptr @stdout` then
  `call/tail call i32 @fputs(ptr bytes, ptr fp)`. Identical
  bytes-pointer GEP, distinct sink.
- The pinned IR-shape test renames from
  `print_str_calls_puts_with_bytes_pointer` to
  `print_str_calls_fputs_with_bytes_pointer_and_stdout` and now
  asserts: bytes-GEP present, stdout-load present, both module-
  preamble declarations present, and no `@puts(` call anywhere
  in the emitted IR.

## Why this shape, and not the alternatives

- *Rename `io/print_str` to `io/println_str` (issue #29 option 2)*
  — kept the auto-newline, just relabelled it. AILang's design
  bias is explicit-over-implicit (CLAUDE.md: implicit conversions
  cut). Auto-newline is a hidden runtime augmentation; the rename
  would have preserved it. Rejected.
- *Append `\n` inside the polymorphic `print` (Show-mediated)
  function in `examples/prelude.ail`* — would have been a one-line
  fix. Rejected: `print` is the Show-mediated formatter, not a
  newline emitter; baking a newline into it would have re-imposed
  the same implicit-augmentation problem one layer up, breaking
  callers that legitimately want pure-bytes output.

## Fixture / test sweep

30 `.ail` fixtures whose owning tests asserted line-separated
stdout now emit explicit `(do io/print_str "\n")` after each
print. Tests that asserted on multi-line stdout (`show_print_e2e`,
`floats_e2e`, `str_concat_e2e`, `eq_ord_e2e`, several `print_*`
smoke tests) had their fixtures sweetened the same way; assertions
themselves remain the canonical observable output. Fixtures that
never relied on the newline (no test ever read the absence of one)
were left untouched.

## Migrated metadata

- `crates/ailang-core/tests/hash_pin.rs`: the `ordering_match::main`
  canonical hash is refreshed (`b65a7f834703ffb4` →
  `8ed47b4062ce00f5`). The comment now names both successive
  corpus migrations honestly: the per-type-print-retirement (which
  moved `(do io/print_int x)` to `(app print x)`) AND this
  fputs swap (which wrapped that with `(seq ... (do io/print_str
  "\n"))`).
- `design/contracts/str-abi.md`: the consumer-ABI table now lists
  `@fputs` as the print sink. A prose paragraph documents the
  byte-faithful semantics and references this issue.
- `examples/ordering_match.prose.txt`: regenerated from the
  updated `ordering_match.ail`.
- `crates/ail/tests/snapshots/{hello,sum,max3,list,ws_main}.ll`:
  IR snapshots regenerated via `UPDATE_SNAPSHOTS=1`.
- Stale `@puts` comments in `runtime/str.c`,
  `crates/ail/tests/{e2e,show_print_e2e,print_no_leak_pin}.rs`
  replaced with `@fputs`.

## Verification

- `cargo test -p ail --test print_str_no_auto_newline_e2e` — both
  RED tests from commit c8ecfa3 now pass.
- `cargo test --workspace` — 90 test groups GREEN, 0 failures.
- `cargo build --workspace` — GREEN.
- No new clippy lints (24 warnings pre-existing in
  `crates/ailang-core/src/lib.rs:129`).
- Stats: `bench/orchestrator-stats/2026-05-21-iter-bugfix-print-
  str-fputs.json` — 1/1 tasks, 0 re-loops, 0 review loops.

## Empirical evidence cited

Caught in the 2026-05-21 Qwen3-Coder naming-A/B run
(`experiments/2026-05-21-naming-ab/runs/r1/`): every cohort wrote
`(do io/print_str "...\n")` with explicit `\n` and got doubled
newlines, failing the `t3_main_prints` stdout match across all
three cohorts. The empirical LLM-natural form already assumes the
new (post-this-commit) semantics — confirming the
feature-acceptance test in CLAUDE.md.

closes #29
2026-05-21 12:22:45 +02:00

245 lines
10 KiB
C

/* AILang Str runtime primitives.
*
* Provides ABI-stable string operations against the existing
* constant-Str layout (NUL-terminated byte buffer, passed as
* `ptr` in LLVM IR). Lives separately from runtime/rc.c so that
* a future heap-Str ABI milestone can swap the implementations
* without touching the RC runtime.
*
* Linked unconditionally by `ail build` (Gc, Bump, Rc) so that
* any program that monomorphises `eq__Str` (auto-loaded from
* the prelude) finds the symbol. Programs that never call
* `eq` on Str leave @ail_str_eq as a dead-stripped no-op at
* link time under clang -O2.
*/
#include <stdbool.h>
#include <string.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Defined in runtime/rc.c — exposed with default external linkage.
* Returns a zero-initialised payload whose `rc_header` sits at
* `payload - 8` and is initialised to refcount 1. str.c's heap-Str
* helpers call this regardless of the program's --alloc strategy,
* because heap-Str values are always refcounted (the global
* `--alloc` flag governs ADT allocation, not Str allocation).
*
* Declared `__attribute__((weak))` in hs.3 so the publicly-visible
* `ailang_int_to_str` / `ailang_float_to_str` symbols can link into
* binaries that do not pull in `runtime/rc.c` (i.e. `--alloc=bump`
* bench builds, where `rc.c` is not linked). Under
* such targets the reference resolves to NULL; the heap-Str helpers
* are not yet called from any IR site (hs.4 wires the lowering), so
* the NULL is never dereferenced at runtime. Under `--alloc=rc` the
* strong definition in `rc.c` wins as usual. Once hs.4 lands the
* unconditional `rc.c` link the `weak` attribute becomes a no-op
* (strong definitions always satisfy weak references); the attribute
* is intentionally retained so str.c remains link-safe in isolation.
*/
extern void *ailang_rc_alloc(size_t size) __attribute__((weak));
/* Byte-equality on NUL-terminated strings. Mirrors strcmp(...) == 0
* but exposed under a stable AILang-namespaced ABI so the codegen
* caller does not assume libc's strcmp shape. Heap-Str ABI milestone
* will replace the body with length-prefixed comparison without
* changing the signature. */
bool ail_str_eq(const char *a, const char *b) {
return strcmp(a, b) == 0;
}
/* Three-way comparison of NUL-terminated strings. Normalises libc
* strcmp's signed-int output to exactly -1 / 0 / +1 so the codegen
* caller can branch on `icmp slt i32 result, 0` and
* `icmp eq i32 result, 0` against constants directly without
* worrying about strcmp implementations that return values outside
* {-1, 0, +1}. Heap-Str ABI milestone will replace the body with
* length-prefixed comparison without changing the signature. */
int ail_str_compare(const char *a, const char *b) {
int r = strcmp(a, b);
if (r < 0) return -1;
if (r > 0) return 1;
return 0;
}
/* Heap-Str slab allocator. Lays out:
*
* [ rc_header (8B) | len (8B) | bytes... | NUL ]
* ^ ^
* payload-8 payload (returned)
*
* Calls `ailang_rc_alloc(8 + len + 1)`. The +8 is the len field;
* the +1 is the trailing NUL byte that keeps `@strcmp` and `@fputs`
* happy under the shared consumer ABI. Writes `len` into the first
* 8 bytes of the payload and returns the payload pointer; the
* caller is responsible for filling bytes [8 .. 8 + len) and the
* `NUL` byte at offset `8 + len`.
*
* Private (static linkage) — callers within this TU only.
*/
static char *str_alloc(uint64_t len) {
char *payload = (char *)ailang_rc_alloc(8 + len + 1);
*(uint64_t *)payload = len;
return payload;
}
/* Convert an i64 into a heap-allocated Str. Format `"%lld"`. The
* worst-case width is 20 chars (i64::MIN = "-9223372036854775808");
* a 64-byte stack buffer is comfortably oversized. `snprintf`'s
* return tells us how many bytes *would* have been written; if that
* exceeds the buffer we abort() defensively — this should be
* unreachable for any valid i64 input but survives format-string
* widening if a future change ever swaps `%lld` for something more
* verbose without re-sizing the buffer.
*
* Returns the payload pointer of a fresh heap-Str slab. Caller owns
* the refcount (init to 1 by `ailang_rc_alloc`); standard RC
* discipline (`ailang_rc_inc` / `ailang_rc_dec`) applies.
*/
char *ailang_int_to_str(int64_t n) {
char buf[64];
int written = snprintf(buf, sizeof(buf), "%lld", (long long)n);
if (written < 0 || (size_t)written >= sizeof(buf)) {
fprintf(stderr,
"ailang_int_to_str: snprintf truncation/error "
"(written=%d, buffer=%zu) — should be unreachable for any valid i64; aborting\n",
written, sizeof(buf));
abort();
}
uint64_t len = (uint64_t)written;
char *payload = str_alloc(len);
memcpy(payload + 8, buf, len);
payload[8 + len] = '\0';
return payload;
}
/* Convert a double into a heap-allocated Str. Format `"%g"` —
* the same libc rendering used throughout the runtime for Float
* text output (post-iter-rpe.1 polymorphic `print` for Float
* routes here via `Show Float.show`).
* NaN renders as libc-default (`nan`/`-nan`/etc.); ±Inf as `inf`
* /`-inf`. Worst-case width for `%g` on a `double` is bounded by
* the libc default precision (`%.6g` ⇒ at most ~13 chars including
* sign and exponent); the 64-byte stack buffer is comfortably
* oversized. Defensive `abort()` on truncation, same shape as
* `ailang_int_to_str`.
*
* `.0`-fallback (Gitea #7): if `x` is finite and `%g`'s output
* contains neither `.` nor `e`/`E`, append `.0` so a whole-valued
* Float renders with a Float-shaped suffix instead of Int-shaped
* text. Mirrors the surface printer's `write_float_lit` fallback
* at `crates/ailang-surface/src/print.rs` lines 624-637, keeping
* the surface/runtime round-trip-on-lex symmetry intact. The
* `isfinite(x)` fence skips the fallback for `nan`/`inf`/`-inf`,
* which would otherwise match the no-`.`-no-`e` predicate and
* render as `nan.0`/`inf.0`.
*
* Returns the payload pointer of a fresh heap-Str slab.
*/
char *ailang_float_to_str(double x) {
char buf[64];
int written = snprintf(buf, sizeof(buf), "%g", x);
if (written < 0 || (size_t)written >= sizeof(buf)) {
fprintf(stderr,
"ailang_float_to_str: snprintf truncation/error "
"(written=%d, buffer=%zu) — should be unreachable for any finite double; aborting\n",
written, sizeof(buf));
abort();
}
uint64_t len = (uint64_t)written;
/* `.0`-fallback — see block comment above and the surface
* counterpart at crates/ailang-surface/src/print.rs lines
* 624-637. `%g` output is ASCII, so plain `memchr` suffices. */
if (isfinite(x)
&& memchr(buf, '.', len) == NULL
&& memchr(buf, 'e', len) == NULL
&& memchr(buf, 'E', len) == NULL) {
if (len + 2 >= sizeof(buf)) {
fprintf(stderr,
"ailang_float_to_str: .0-fallback would overflow buffer "
"(len=%llu, buffer=%zu) — should be unreachable for any finite double; aborting\n",
(unsigned long long)len, sizeof(buf));
abort();
}
buf[len] = '.';
buf[len + 1] = '0';
len += 2;
}
char *payload = str_alloc(len);
memcpy(payload + 8, buf, len);
payload[8 + len] = '\0';
return payload;
}
/* Convert a bool into a heap-allocated Str — "true" (4 bytes) or
* "false" (5 bytes). Heap-allocates every call; the static-Str
* literal alternative (used by a hypothetical `\x -> if x then "true"
* else "false"` schema body) would require phi-of-static-Str
* through the drop-elision pipeline which is not load-bearing-
* ratified today (see parent spec §"Out of scope" / `bool_to_str` as
* schema-if).
*
* Returns the payload pointer of a fresh heap-Str slab.
*/
char *ailang_bool_to_str(bool b) {
const char *lit = b ? "true" : "false";
uint64_t len = b ? 4 : 5;
char *payload = str_alloc(len);
memcpy(payload + 8, lit, len);
payload[8 + len] = '\0';
return payload;
}
/* Clone a Str into a fresh heap-Str slab. Reads `len` from the
* first 8 bytes of the source payload, allocates a new slab of the
* same length via `str_alloc`, and memcpy's the payload bytes plus
* the trailing NUL. Works uniformly on static-Str and heap-Str
* inputs because the consumer ABI (i64 len at offset 0, bytes
* starting at offset 8, NUL at offset 8 + len) is identical
* between realisations (see design/contracts/str-abi.md); the rc_header at
* offset -8 — present only on heap-Str — is never consulted.
*
* Used by `show__Str` (parent spec milestone 24): converts a
* borrowed Str input into an Owned heap-Str output, preserving
* the uniform `show : forall a. Show a => (a borrow) -> Str Own`
* signature.
*
* Returns the payload pointer of a fresh heap-Str slab.
*/
char *ailang_str_clone(const char *src) {
uint64_t len = *(const uint64_t *)src;
char *payload = str_alloc(len);
memcpy(payload + 8, src + 8, len);
payload[8 + len] = '\0';
return payload;
}
/*
* `ailang_str_concat(a, b)` — heap-Str concatenation primitive
* shipped in iter str-concat (2026-05-13). Reads `len` headers from
* both source Str payloads (offset 0 of each), allocates a fresh
* heap-Str slab sized for the combined bytes via `str_alloc`,
* memcpys both payloads in order, NUL-terminates, returns the new
* payload pointer. Like `str_clone`, this works uniformly on static-
* Str and heap-Str inputs because the consumer ABI is identical
* between realisations (see design/contracts/str-abi.md).
*
* Used by Show bodies that want labelled output (e.g.
* `"Item " ++ int_to_str n`) and by any caller that needs to
* combine two existing Str values into a new owned Str.
*
* Returns the payload pointer of a fresh heap-Str slab. The rc
* header is initialised to 1 by `str_alloc`.
*/
char *ailang_str_concat(const char *a, const char *b) {
uint64_t la = *(const uint64_t *)a;
uint64_t lb = *(const uint64_t *)b;
char *payload = str_alloc(la + lb);
memcpy(payload + 8, a + 8, la);
memcpy(payload + 8 + la, b + 8, lb);
payload[8 + la + lb] = '\0';
return payload;
}