Files
AILang/docs/plans/0043-hs.1.md
T
Brummel 832375f2ac convention: counter-prefix file naming across docs/specs/, docs/plans/, design/contracts/, design/models/
All 176 files in the four accumulating directories now use a
zero-padded 4-digit counter prefix that reflects creation order
(`NNNN-slug.md`). The counter is assigned per directory in strict
git-log creation order; ties broken alphabetically by original name.
The old `YYYY-MM-DD-` prefix on docs/specs/ and docs/plans/ files is
dropped — the date is recoverable from git log and the counter
carries the ordering.

A file's counter is stable for the life of the file: never reassigned,
never reused, never compacted. Deleted files retire their counter;
subsequent files do not fill the gap. This is the property that lets
cross-references stay literal — refs use the full filename including
the counter (`design/contracts/0007-honesty-rule.md`) so they grep
cleanly and resolve directly without a glob step.

313 cross-references updated across .md/.rs/.toml/.c/.json files
(test pins, include_str! paths, design-INDEX entries, baseline notes,
runtime C comments, inter-contract markdown links incl. bare basename
and `../models/foo.md` forms).

CLAUDE.md gets a new "File-naming convention" section spelling out
the rule and rationale. skills/brainstorm/SKILL.md and
skills/planner/SKILL.md updated so new spec/plan creation produces
counter-prefixed names from the start.

The full test suite (cargo test --workspace) passes.
2026-05-28 13:31:31 +02:00

791 lines
28 KiB
Markdown

# hs.1 — Heap-Str ABI: Static-Str Layout Migration — Implementation Plan
> **Parent spec:** `docs/specs/0019-heap-str-abi.md`
>
> **For agentic workers:** REQUIRED SUB-SKILL: use `skills/implement`
> to run this plan. Steps use `- [ ]` checkboxes for tracking.
**Goal:** Migrate static-Str LLVM globals from the current raw
`[N+1 x i8]` byte-array shape to the unified packed-struct shape
`<{ i64, i64, [N+1 x i8] }>` carrying a `UINT64_MAX` sentinel
rc-header, an explicit `len` field, and the bytes + terminating
`NUL`. Switch the two `Literal::Str` codegen sites to materialise
an IR-Str pointer that lands on the `len`-field of the new global
(via constexpr `getelementptr`). Adjust the three codegen sites
that pass a Str pointer to a `NUL`-terminated-bytes C-API consumer
(`@puts`, `@ail_str_eq`, `@ail_str_compare`) to emit a `+8`
`getelementptr` immediately before the call to land on the bytes.
After this iter, the IR-Str-pointer convention is "the value
flowing through the IR as a `Str` points at the `len`-field of
the global"; every existing program produces byte-identical
stdout.
**Architecture:** Pure codegen-side refactor. No runtime changes,
no checker changes, no new builtins. The new global layout has the
sentinel-header slot that the next iter (`hs.2`) will exploit by
adding the `UINT64_MAX` short-circuit to `ailang_rc_inc` /
`ailang_rc_dec` in `runtime/rc.c`; in this iter the sentinel value
is hardcoded in the global initialiser and never observed by any
caller. The `+8` adjustments at C-API sites mean `@puts`,
`@ail_str_eq`, `@ail_str_compare` continue to receive a
`NUL`-terminated bytes pointer — they expect raw `char*`, unchanged
from today, only the offset machinery in the caller shifts. Format
strings (`%lld\n`, `%g\n`, `true\n`, `false\n`) keep the old raw
`[N x i8]` shape — they are runtime-internal scaffolding, never
flow as language `Str` values, and never reach the new ABI.
**Tech Stack:** Rust crate `ailang-codegen` (`crates/ailang-codegen/src/lib.rs`,
test module in the same file). Snapshot fixture in `crates/ail/tests/snapshots/hello.ll`.
---
## Files this plan creates or modifies
- **Modify:** `crates/ailang-codegen/src/lib.rs:534` — add a parallel
field `str_literals: BTreeMap<String, (String, usize)>` on the
`Emitter` struct next to the existing `strings` field. Same key
shape; the two tables coexist.
- **Modify:** `crates/ailang-codegen/src/lib.rs:753` — initialise
`str_literals: BTreeMap::new()` in the same constructor block
that initialises `strings`.
- **Modify:** `crates/ailang-codegen/src/lib.rs:2487-2498` — add a
new function `intern_str_literal` next to the existing
`intern_string`. Same dedup-by-content semantics but writes into
`self.str_literals` and reuses `self.str_counter` for monotonic
naming so the produced global names remain alphabetically
orderable alongside format-string globals.
- **Modify:** `crates/ailang-codegen/src/lib.rs:283-411` — add a
second aggregation `all_str_literals: BTreeMap<String,
Vec<(String, String)>>` alongside the existing `all_strings`,
populated from `emitter.str_literals` symmetrically to the
existing populate-from-`emitter.strings` block at line 403-410.
- **Modify:** `crates/ailang-codegen/src/lib.rs:438-450` — add a
parallel emission loop after the existing one. The new loop
emits each entry as
`@<name> = private unnamed_addr constant <{ i64, i64, [N+1 x i8] }> <{ i64 -1, i64 N, [N+1 x i8] c"<escaped>\00" }>, align 8`
where `N = c_byte_len(content)` (the bytes, excluding the
trailing `NUL`) and the `[N+1]` includes the `NUL`.
- **Modify:** `crates/ailang-codegen/src/lib.rs:890-893` — switch
the `Literal::Str` arm inside `emit_const_def`'s match block to
call `intern_str_literal` and return the constexpr-GEP form
instead of the bare `@{g}` name.
- **Modify:** `crates/ailang-codegen/src/lib.rs:1202-1207` — switch
the `Literal::Str` arm inside `lower_term`'s match block
symmetrically.
- **Modify:** `crates/ailang-codegen/src/lib.rs:2152-2170` — at
`io/print_str`, emit a `getelementptr i8, ptr <v>, i64 8` to land
on the bytes pointer immediately before the `@puts` call.
- **Modify:** `crates/ailang-codegen/src/lib.rs:2256-2268` — at
`eq__Str` intercept, emit `+8` GEPs on both `a_ssa` and `b_ssa`
before the `@ail_str_eq` call.
- **Modify:** `crates/ailang-codegen/src/lib.rs:2302-2321` — at
`compare__Str` intercept, emit `+8` GEPs on both `a_ssa` and
`b_ssa` before the `@ail_str_compare` call.
- **Modify:** `crates/ail/tests/snapshots/hello.ll` — regenerate
via `UPDATE_SNAPSHOTS=1 cargo test --workspace ir_snapshot_hello`
after Task 4 lands; the `@.str_hello_str_0` global and the
`@puts` callsite both change shape.
- **Test:** `crates/ailang-codegen/src/lib.rs` (test module starting
around `:3340`) — five new IR-shape tests pinning the new
conventions:
- `static_str_global_uses_packed_struct_with_sentinel_and_len`
- `static_str_callsite_pointer_is_payload_via_constexpr_gep`
- `print_str_calls_puts_with_bytes_pointer`
- `eq_str_calls_ail_str_eq_with_bytes_pointer`
- `compare_str_calls_ail_str_compare_with_bytes_pointer`
---
## Task 1: Migrate Str-literal globals to packed-struct layout
This task introduces the new emission machinery AND switches the
two language-`Str` codegen sites to use it. The two changes are
inseparable — `intern_str_literal` produces no observable output
without the callsite switch, and the callsite switch references a
function that doesn't exist without the new infrastructure.
**Files:**
- Modify: `crates/ailang-codegen/src/lib.rs:534, 753, 283-411, 438-450, 890-893, 1202-1207, 2487-2498`
- Test: `crates/ailang-codegen/src/lib.rs` (test module)
- [ ] **Step 1: Write the failing test `static_str_global_uses_packed_struct_with_sentinel_and_len`.**
Add this test to the `tests` module at the bottom of
`crates/ailang-codegen/src/lib.rs`, near the existing
`eq_str_mono_symbol_emits_ail_str_eq_call` test:
```rust
/// Iter hs.1: language `Str` literals emit as packed-struct
/// globals carrying a `UINT64_MAX` sentinel rc-header, an
/// explicit `len` field, and the bytes + trailing NUL. This
/// test pins the layout shape against a tiny single-Literal::Str
/// fixture.
#[test]
fn static_str_global_uses_packed_struct_with_sentinel_and_len() {
let m = Module {
schema: SCHEMA.into(),
name: "t".into(),
imports: vec![],
defs: vec![
Def::Const(ConstDef {
name: "greeting".into(),
ty: Type::str_(),
body: Term::Lit { lit: Literal::Str { value: "hello".into() } },
doc: None,
}),
Def::Fn(FnDef {
name: "main".into(),
ty: Type::Fn {
params: vec![],
ret: Box::new(Type::unit()),
effects: vec![],
param_modes: vec![],
ret_mode: ParamMode::Implicit,
},
params: vec![],
body: Term::Lit { lit: Literal::Unit },
suppress: vec![],
doc: None,
}),
],
};
let ir = emit_ir(&m).unwrap();
assert!(
ir.contains(r#"<{ i64, i64, [6 x i8] }> <{ i64 -1, i64 5, [6 x i8] c"hello\00" }>"#),
"expected packed-struct global with sentinel + len + bytes + NUL; ir was:\n{ir}"
);
}
```
- [ ] **Step 2: Run test to verify it fails.**
Run: `cargo test --workspace -p ailang-codegen static_str_global_uses_packed_struct_with_sentinel_and_len`
Expected: FAIL — the IR currently emits `[6 x i8] c"hello\00"`, not the packed-struct form.
- [ ] **Step 3: Add the `str_literals` field to `Emitter`.**
Modify `crates/ailang-codegen/src/lib.rs:534` to add the field next
to `strings`:
```rust
strings: BTreeMap<String, (String, usize)>,
str_literals: BTreeMap<String, (String, usize)>,
```
And initialise in the constructor at `:753`:
```rust
strings: BTreeMap::new(),
str_literals: BTreeMap::new(),
```
- [ ] **Step 4: Add the `intern_str_literal` function.**
Modify `crates/ailang-codegen/src/lib.rs:2487-2498` to add a
parallel function next to `intern_string`:
```rust
fn intern_str_literal(&mut self, hint: &str, content: &str) -> String {
if let Some((name, _)) = self.str_literals.get(content) {
return name.clone();
}
// Mangling per module: `.str_<module>_<hint>_<idx>`. Shares
// the same monotonic `str_counter` with `intern_string` so
// global names are stable-ordered across runs.
let name = format!(".str_{}_{}_{}", self.module_name, hint, self.str_counter);
self.str_counter += 1;
let len = c_byte_len(content);
self.str_literals
.insert(content.to_string(), (name.clone(), len));
name
}
```
- [ ] **Step 5: Add aggregation of `str_literals` in `lower_workspace`.**
Modify the workspace-aggregation block at `crates/ailang-codegen/src/lib.rs:283-411`.
Add a parallel `all_str_literals` declaration next to
`all_strings` at line 283:
```rust
let mut all_str_literals: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new();
```
And add a parallel population block immediately after the
existing `all_strings.insert(...)` at line 410:
```rust
let mut lit_entries: Vec<(String, String)> = Vec::new();
for (content, (name, _)) in &emitter.str_literals {
lit_entries.push((name.clone(), content.clone()));
}
lit_entries.sort_by(|a, b| a.0.cmp(&b.0));
all_str_literals.insert(mname.clone(), lit_entries);
```
- [ ] **Step 6: Emit the packed-struct globals.**
Modify the global-emission loop at
`crates/ailang-codegen/src/lib.rs:438-450`. Immediately after
the existing `for entries in all_strings.values() { ... }` block,
add the parallel emission for `all_str_literals`:
`c_byte_len(content)` (defined at
`crates/ailang-codegen/src/synth.rs:260` as `s.len() + 1`) returns
the byte length INCLUDING the trailing NUL. The array dim is
`[c_byte_len(content) x i8]`; the i64 `len`-field stores
`c_byte_len(content) - 1` (bytes excluding NUL).
```rust
for entries in all_str_literals.values() {
for (name, content) in entries {
let escaped = ll_string_literal(content);
let total = c_byte_len(content); // bytes + NUL
let bytes_len = total - 1; // bytes only
out.push_str(&format!(
"@{name} = private unnamed_addr constant <{{ i64, i64, [{total} x i8] }}> <{{ i64 -1, i64 {bytes_len}, [{total} x i8] c\"{escaped}\" }}>, align 8\n",
));
emitted_global = true;
}
}
```
- [ ] **Step 7: Switch the two `Literal::Str` arms to `intern_str_literal`.**
Modify `crates/ailang-codegen/src/lib.rs:890-893` from:
```rust
Literal::Str { value } => {
let g = self.intern_string("str", value);
("ptr".to_string(), format!("@{g}"))
}
```
to:
```rust
Literal::Str { value } => {
let g = self.intern_str_literal("str", value);
let total = c_byte_len(value); // bytes + NUL
(
"ptr".to_string(),
format!(
"getelementptr inbounds (<{{ i64, i64, [{total} x i8] }}>, ptr @{g}, i32 0, i32 1)",
),
)
}
```
And symmetrically at `crates/ailang-codegen/src/lib.rs:1202-1207`:
```rust
Literal::Str { value } => {
let g = self.intern_str_literal("str", value);
let total = c_byte_len(value); // bytes + NUL
(
format!(
"getelementptr inbounds (<{{ i64, i64, [{total} x i8] }}>, ptr @{g}, i32 0, i32 1)",
),
"ptr".into(),
)
}
```
- [ ] **Step 8: Run the test to verify it passes.**
Run: `cargo test --workspace -p ailang-codegen static_str_global_uses_packed_struct_with_sentinel_and_len`
Expected: PASS.
- [ ] **Step 9: Add the constexpr-GEP shape test.**
Append to the same test module:
```rust
/// Iter hs.1: a `Literal::Str` at a callsite materialises a
/// constexpr `getelementptr` landing on the `len`-field of the
/// packed-struct global, not the bare global name. This pins the
/// IR-Str-pointer convention used uniformly by all consumers.
#[test]
fn static_str_callsite_pointer_is_payload_via_constexpr_gep() {
let m = Module {
schema: SCHEMA.into(),
name: "t".into(),
imports: vec![],
defs: vec![Def::Fn(FnDef {
name: "main".into(),
ty: Type::Fn {
params: vec![],
ret: Box::new(Type::unit()),
effects: vec![],
param_modes: vec![],
ret_mode: ParamMode::Implicit,
},
params: vec![],
body: Term::App {
f: Box::new(Term::Var { name: "io/print_str".into() }),
args: vec![Term::Lit { lit: Literal::Str { value: "hi".into() } }],
},
suppress: vec![],
doc: None,
})],
};
let ir = emit_ir(&m).unwrap();
assert!(
ir.contains(r#"getelementptr inbounds (<{ i64, i64, [3 x i8] }>, ptr @.str_t_str_0, i32 0, i32 1)"#),
"expected constexpr-GEP-to-len-field at callsite; ir was:\n{ir}"
);
}
```
- [ ] **Step 10: Run test to verify it passes.**
Run: `cargo test --workspace -p ailang-codegen static_str_callsite_pointer_is_payload_via_constexpr_gep`
Expected: PASS.
---
## Task 2: `+8` GEP at `io/print_str` callsite
Between Task 1 completing and Task 2 completing, programs that
print a Str literal would pass the IR-Str pointer (now at
`len`-field) directly to `@puts`, which would print 8 bytes of
length-field junk before the actual bytes. This task makes the
print path consume the bytes pointer correctly.
**Files:**
- Modify: `crates/ailang-codegen/src/lib.rs:2152-2170`
- Test: `crates/ailang-codegen/src/lib.rs` (test module)
- [ ] **Step 1: Write the failing test `print_str_calls_puts_with_bytes_pointer`.**
```rust
/// Iter hs.1: after the layout migration, the `io/print_str`
/// path must `getelementptr i8` +8 onto the IR-Str pointer before
/// passing it to `@puts`, so `@puts` receives the bytes pointer
/// (skipping the `len` field) and produces correct output.
#[test]
fn print_str_calls_puts_with_bytes_pointer() {
let m = Module {
schema: SCHEMA.into(),
name: "t".into(),
imports: vec![],
defs: vec![Def::Fn(FnDef {
name: "main".into(),
ty: Type::Fn {
params: vec![],
ret: Box::new(Type::unit()),
effects: vec![],
param_modes: vec![],
ret_mode: ParamMode::Implicit,
},
params: vec![],
body: Term::App {
f: Box::new(Term::Var { name: "io/print_str".into() }),
args: vec![Term::Lit { lit: Literal::Str { value: "hi".into() } }],
},
suppress: vec![],
doc: None,
})],
};
let ir = emit_ir(&m).unwrap();
// Expect a +8 GEP immediately preceding the @puts call.
let body_idx = ir.find("define i8 @ail_t_main").expect("main body");
let body = &ir[body_idx..];
let puts_idx = body.find("@puts(").expect("@puts call present");
let before_puts = &body[..puts_idx];
assert!(
before_puts.contains("getelementptr inbounds i8, ptr ") && before_puts.contains(", i64 8"),
"expected `getelementptr inbounds i8, ptr <v>, i64 8` before @puts call; ir body was:\n{body}"
);
}
```
- [ ] **Step 2: Run test to verify it fails.**
Run: `cargo test --workspace -p ailang-codegen print_str_calls_puts_with_bytes_pointer`
Expected: FAIL — no GEP precedes `@puts` today; the IR-Str pointer
is passed directly.
- [ ] **Step 3: Add the `+8` GEP at the `io/print_str` callsite.**
Modify `crates/ailang-codegen/src/lib.rs:2152-2170` from:
```rust
"io/print_str" => {
if args.len() != 1 {
return Err(CodegenError::Internal(
"io/print_str arity".into(),
));
}
let (v, vty) = self.lower_term(&args[0])?;
if vty != "ptr" {
return Err(CodegenError::Internal(
"io/print_str needs ptr".into(),
));
}
self.body
.push_str(&format!(" {call_kw} i32 @puts(ptr {v})\n"));
if tail {
self.body.push_str(" ret i8 0\n");
self.block_terminated = true;
}
Ok(("0".into(), "i8".into()))
}
```
to:
```rust
"io/print_str" => {
if args.len() != 1 {
return Err(CodegenError::Internal(
"io/print_str arity".into(),
));
}
let (v, vty) = self.lower_term(&args[0])?;
if vty != "ptr" {
return Err(CodegenError::Internal(
"io/print_str needs ptr".into(),
));
}
// Iter hs.1: `Str` values now flow as a pointer to the
// `len`-field of the packed-struct slab; @puts needs the
// bytes pointer 8 bytes further on.
let bytes = self.fresh_ssa();
self.body.push_str(&format!(
" {bytes} = getelementptr inbounds i8, ptr {v}, i64 8\n"
));
self.body
.push_str(&format!(" {call_kw} i32 @puts(ptr {bytes})\n"));
if tail {
self.body.push_str(" ret i8 0\n");
self.block_terminated = true;
}
Ok(("0".into(), "i8".into()))
}
```
- [ ] **Step 4: Run test to verify it passes.**
Run: `cargo test --workspace -p ailang-codegen print_str_calls_puts_with_bytes_pointer`
Expected: PASS.
---
## Task 3: `+8` GEPs at `eq__Str` intercept
**Files:**
- Modify: `crates/ailang-codegen/src/lib.rs:2256-2268`
- Test: `crates/ailang-codegen/src/lib.rs` (test module)
- [ ] **Step 1: Write the failing test `eq_str_calls_ail_str_eq_with_bytes_pointer`.**
```rust
/// Iter hs.1: `eq__Str`'s body must `getelementptr i8` +8 on
/// both operand pointers before calling `@ail_str_eq`, since the
/// IR-Str pointer now lands on the `len`-field, not the bytes.
#[test]
fn eq_str_calls_ail_str_eq_with_bytes_pointer() {
let m = Module {
schema: SCHEMA.into(),
name: "prelude".into(),
imports: vec![],
defs: vec![
Def::Fn(FnDef {
name: "eq__Str".into(),
ty: Type::Fn {
params: vec![Type::str_(), Type::str_()],
ret: Box::new(Type::bool_()),
effects: vec![],
param_modes: vec![ParamMode::Borrow, ParamMode::Borrow],
ret_mode: ParamMode::Implicit,
},
params: vec!["x".into(), "y".into()],
body: Term::Lit { lit: Literal::Bool { value: false } },
suppress: vec![],
doc: None,
}),
Def::Fn(FnDef {
name: "main".into(),
ty: Type::Fn {
params: vec![],
ret: Box::new(Type::unit()),
effects: vec![],
param_modes: vec![],
ret_mode: ParamMode::Implicit,
},
params: vec![],
body: Term::Lit { lit: Literal::Unit },
suppress: vec![],
doc: None,
}),
],
};
let ir = emit_ir(&m).unwrap();
let body_idx = ir.find("define i1 @ail_prelude_eq__Str").expect("eq__Str body");
let body = &ir[body_idx..];
let eq_idx = body.find("@ail_str_eq(").expect("@ail_str_eq call present");
let before_eq = &body[..eq_idx];
// Two GEPs (one per operand) must precede the call.
let gep_count = before_eq.matches("getelementptr inbounds i8, ptr ").count();
assert_eq!(
gep_count, 2,
"expected 2 +8 GEPs before @ail_str_eq (one per operand); ir body was:\n{body}"
);
assert!(
before_eq.matches(", i64 8").count() >= 2,
"expected both GEPs to be `, i64 8`; ir body was:\n{body}"
);
}
```
- [ ] **Step 2: Run test to verify it fails.**
Run: `cargo test --workspace -p ailang-codegen eq_str_calls_ail_str_eq_with_bytes_pointer`
Expected: FAIL — current body passes `a_ssa` and `b_ssa` directly.
- [ ] **Step 3: Add the `+8` GEPs at the `eq__Str` intercept.**
Modify `crates/ailang-codegen/src/lib.rs:2256-2268` (the `eq__Str` arm
of `try_emit_primitive_instance_body`). Replace the body
construction:
```rust
let n = self.locals.len();
let a_ssa = self.locals[n - 2].1.clone();
let b_ssa = self.locals[n - 1].1.clone();
let dst = self.fresh_ssa();
self.body.push_str(&format!(
" {dst} = call zeroext i1 @ail_str_eq(ptr {a_ssa}, ptr {b_ssa})\n"
));
self.body.push_str(&format!(" ret i1 {dst}\n"));
self.body.push_str("}\n\n");
self.block_terminated = true;
Ok(true)
```
with:
```rust
let n = self.locals.len();
let a_ssa = self.locals[n - 2].1.clone();
let b_ssa = self.locals[n - 1].1.clone();
// Iter hs.1: IR-Str pointers now land on the `len`-field of the
// packed-struct slab; @ail_str_eq's strcmp-based body needs the
// bytes pointer 8 bytes further on.
let a_bytes = self.fresh_ssa();
let b_bytes = self.fresh_ssa();
self.body.push_str(&format!(
" {a_bytes} = getelementptr inbounds i8, ptr {a_ssa}, i64 8\n"
));
self.body.push_str(&format!(
" {b_bytes} = getelementptr inbounds i8, ptr {b_ssa}, i64 8\n"
));
let dst = self.fresh_ssa();
self.body.push_str(&format!(
" {dst} = call zeroext i1 @ail_str_eq(ptr {a_bytes}, ptr {b_bytes})\n"
));
self.body.push_str(&format!(" ret i1 {dst}\n"));
self.body.push_str("}\n\n");
self.block_terminated = true;
Ok(true)
```
- [ ] **Step 4: Run test to verify it passes.**
Run: `cargo test --workspace -p ailang-codegen eq_str_calls_ail_str_eq_with_bytes_pointer`
Expected: PASS.
---
## Task 4: `+8` GEPs at `compare__Str` intercept
**Files:**
- Modify: `crates/ailang-codegen/src/lib.rs:2302-2321`
- Test: `crates/ailang-codegen/src/lib.rs` (test module)
- [ ] **Step 1: Write the failing test `compare_str_calls_ail_str_compare_with_bytes_pointer`.**
```rust
/// Iter hs.1: `compare__Str`'s body must `getelementptr i8` +8
/// on both operand pointers before calling `@ail_str_compare`,
/// symmetric to the `eq__Str` change.
#[test]
fn compare_str_calls_ail_str_compare_with_bytes_pointer() {
// The synth_compare_module helper already exists in the test
// module for the other compare__T tests; use it.
let m = synth_compare_module("compare__Str", Type::str_());
let ir = emit_ir(&m).unwrap();
let body_idx = ir
.find("define ptr @ail_prelude_compare__Str")
.expect("compare__Str body");
let body = &ir[body_idx..];
let cmp_idx = body
.find("@ail_str_compare(")
.expect("@ail_str_compare call present");
let before_cmp = &body[..cmp_idx];
let gep_count = before_cmp.matches("getelementptr inbounds i8, ptr ").count();
assert_eq!(
gep_count, 2,
"expected 2 +8 GEPs before @ail_str_compare; ir body was:\n{body}"
);
assert!(
before_cmp.matches(", i64 8").count() >= 2,
"expected both GEPs to be `, i64 8`; ir body was:\n{body}"
);
}
```
(If `synth_compare_module` doesn't exist as a helper, look for the
existing `compare_str_mono_symbol_emits_ail_str_compare_call` test
at `crates/ailang-codegen/src/lib.rs:3626` and copy its fixture
construction inline.)
- [ ] **Step 2: Run test to verify it fails.**
Run: `cargo test --workspace -p ailang-codegen compare_str_calls_ail_str_compare_with_bytes_pointer`
Expected: FAIL.
- [ ] **Step 3: Add the `+8` GEPs at the `compare__Str` intercept.**
Modify `crates/ailang-codegen/src/lib.rs:2302-2321`. Replace:
```rust
let n = self.locals.len();
let a_ssa = self.locals[n - 2].1.clone();
let b_ssa = self.locals[n - 1].1.clone();
let cmp_res = self.fresh_ssa();
self.body.push_str(&format!(
" {cmp_res} = call i32 @ail_str_compare(ptr {a_ssa}, ptr {b_ssa})\n"
));
self.emit_compare_ladder(
&format!("icmp slt i32 {cmp_res}, 0"),
&format!("icmp eq i32 {cmp_res}, 0"),
)?;
Ok(true)
```
with:
```rust
let n = self.locals.len();
let a_ssa = self.locals[n - 2].1.clone();
let b_ssa = self.locals[n - 1].1.clone();
// Iter hs.1: IR-Str pointers now land on the `len`-field of the
// packed-struct slab; @ail_str_compare's strcmp-based body needs
// the bytes pointer 8 bytes further on.
let a_bytes = self.fresh_ssa();
let b_bytes = self.fresh_ssa();
self.body.push_str(&format!(
" {a_bytes} = getelementptr inbounds i8, ptr {a_ssa}, i64 8\n"
));
self.body.push_str(&format!(
" {b_bytes} = getelementptr inbounds i8, ptr {b_ssa}, i64 8\n"
));
let cmp_res = self.fresh_ssa();
self.body.push_str(&format!(
" {cmp_res} = call i32 @ail_str_compare(ptr {a_bytes}, ptr {b_bytes})\n"
));
self.emit_compare_ladder(
&format!("icmp slt i32 {cmp_res}, 0"),
&format!("icmp eq i32 {cmp_res}, 0"),
)?;
Ok(true)
```
- [ ] **Step 4: Run test to verify it passes.**
Run: `cargo test --workspace -p ailang-codegen compare_str_calls_ail_str_compare_with_bytes_pointer`
Expected: PASS.
---
## Task 5: Regenerate `hello.ll` snapshot and end-to-end regression
The IR snapshot of `hello.ail` (the only canonical example that
exercises a Str literal through @puts) now mismatches the actual
IR after Tasks 1+2 landed. Regenerate via the project's
`UPDATE_SNAPSHOTS=1` mechanism, then run the full regression
suite to confirm byte-identical program outputs.
**Files:**
- Modify: `crates/ail/tests/snapshots/hello.ll` (regenerated)
- [ ] **Step 1: Confirm the `ir_snapshot_hello` test fails before regenerating.**
Run: `cargo test --workspace -p ail ir_snapshot_hello`
Expected: FAIL — the snapshot mismatch should report a diff
showing the new packed-struct global and the `+8` GEP before `@puts`.
- [ ] **Step 2: Regenerate the snapshot.**
Run: `UPDATE_SNAPSHOTS=1 cargo test --workspace -p ail ir_snapshot_hello`
Expected: PASS, with stderr `updated snapshot: <path>`.
- [ ] **Step 3: Inspect the regenerated snapshot to confirm shape.**
Run: `head -25 crates/ail/tests/snapshots/hello.ll`
Expected: the `@.str_hello_str_0` global is now
`<{ i64, i64, [15 x i8] }> <{ i64 -1, i64 14, [15 x i8] c"Hello, AILang.\00" }>, align 8`
(exact `len` is 14 because "Hello, AILang." has 14 bytes; total
array is 15 with the trailing `NUL`). The `@puts` call line is
preceded by a `getelementptr inbounds i8, ptr <v>, i64 8` and the
call argument is the GEP result, not the bare global. Confirm
visually before continuing.
- [ ] **Step 4: Run `cargo test --workspace` end-to-end.**
Run: `cargo test --workspace`
Expected: PASS, all tests green.
- [ ] **Step 5: Run `bench/compile_check.py`.**
Run: `python3 bench/compile_check.py`
Expected: every `examples/` program compiles without error or
warning; the script exits 0.
- [ ] **Step 6: Run `bench/cross_lang.py`.**
Run: `python3 bench/cross_lang.py`
Expected: every fixture in `bench/reference/` produces
byte-identical stdout from its AILang and C implementations;
the script exits 0. This is the strongest regression gate —
it confirms that the layout migration left observable program
behaviour completely unchanged.
- [ ] **Step 7: Confirm no other snapshots changed.**
Run: `git status crates/ail/tests/snapshots/`
Expected: only `hello.ll` shows as modified. The other snapshots
(`sum.ll`, `list.ll`, `max3.ll`, `ws_main.ll`) contain only
format-string globals (`@.str_*_fmt_int_0` etc.), which kept the
raw `[N x i8]` shape — they should be byte-identical to before.
If any of them changed, investigate before continuing: it means
this iter inadvertently affected format-string emission.
---
## Notes for the implementer
- The IR-shape tests in Tasks 1-4 all use substring assertions —
insensitive to SSA-naming changes. They will survive future
refactors that rename intermediate variables but break if the
fundamental IR shape changes.
- Between Tasks 1 and 4 completing, programs that print or compare
Str literals would produce wrong output if executed end-to-end.
The per-task IR-shape tests do not catch this; Task 5's
regression suite does. If `cargo test --workspace` is invoked
mid-iter (between Tasks 1 and 4), it will report failures in
the e2e suite that are EXPECTED and will resolve once Task 4
lands. The implementer should not panic at intermediate
failures and should not commit before Task 5 reports green.
- No `runtime/` or `crates/ailang-check/` changes are required in
this iter. If the implementer finds themselves editing those
paths, they have strayed from scope.
- No `git commit` step. The Boss commits the working-tree diff at
iter end after audit-level inspection.