Skip to content

codegen: formatting an Option[&T] no longer crashes the compiler - #1216

Merged
ehartford merged 2 commits into
mainfrom
fix-fstring-option-ref
Sep 21, 2026
Merged

ehartford merged 2 commits into
mainfrom
fix-fstring-option-ref

Conversation

@ropoctl

@ropoctl ropoctl commented Sep 19, 2026

Copy link
Copy Markdown
Collaborator

What

print(f"{o}") with o: Option[&i32], Option[&str], or a HashMap.get result (display or debug mode) segfaulted the v0.15.2.x compiler with LLVMTypeOf on a null value. Found while building the wasm32 target (#1210); independent of it and fixed here on its own.

Root cause

Option[&T] is a nullable pointer (D22: the same niche representation as a map or slot lookup), not a tag + payload struct. gen_display_enum walked it as a struct: gen_enum_payload_field_value returns 0 for a non-struct value, and gen_display_enum_variant passed that null straight into coerce_typed_val_to_str, whose wl_type_of(0) is the crash.

Fix

  • gen_display_enum routes a pointer-shaped enum value to a new gen_display_nullable_option: null prints the None variant, otherwise the Some variant around the loaded pointee formatted as its own type (formatting observes; a str pointee reaches the concat as the borrowed value, which concat only reads).
  • gen_display_enum_variant now aborts with a BUG: message if a payload value is ever null again, instead of reaching LLVMTypeOf.

Verification

  • test/behavior/behav_fstring_option_ref.w (new): Option[&i32] Some and None, Option[&str], debug mode, HashMap.get hit and miss — passes.
  • The 51 existing fixtures matching fstring/fmt/format/option/display in test/behavior and test/spec pass on the rebuilt stage1.
  • Base: origin/main 3811221, pinned seed v0.15.2.0.

`print(f"{o}")` with `o: Option[&i32]` (or `Option[&str]`, or a
`HashMap.get` result, in display or debug mode) segfaulted the compiler:
LLVMTypeOf on a null value.

Root cause: Option[&T] is a nullable pointer (D22, the same niche
representation as a map or slot lookup), not a tag + payload struct.
gen_display_enum walked it as a struct; gen_enum_payload_field_value
returned 0 for the non-struct value and gen_display_enum_variant fed that
null straight into coerce_typed_val_to_str.

gen_display_enum now routes a pointer-shaped enum value to
gen_display_nullable_option: null prints the None variant, otherwise the
Some variant around the loaded pointee formatted as its own type
(formatting observes; a str pointee reaches the concat as the borrowed
value, which concat only reads). gen_display_enum_variant aborts with a
BUG message if a payload value is ever null again instead of reaching
LLVMTypeOf.

test/behavior/behav_fstring_option_ref.w covers Option[&i32] Some/None,
Option[&str], debug mode, and a HashMap.get hit and miss.
ehartford pushed a commit that referenced this pull request Sep 21, 2026
#1210)

* wasm32 target: With runtime over WASI preview1 plus an emitted JS host

`--target=wasm32` compiles a pure-With program to a WebAssembly module
whose only imports are WASI preview1 system calls, and emits `<prog>.js`,
an emscripten-style host that runs it under node (real filesystem, argv,
env, stdio) or in a browser (in-memory filesystem, console). No wasi-libc
and no emscripten musl: rt/wasm.w implements the rt_* platform contract
the Linux/Darwin/Windows backends implement over libc, directly on WASI,
and owns what a libc would (startup/exit, the page allocator behind
rt_mmap on memory.grow, malloc/free/memcmp, compiler-rt's __multi3).

Compiler: target kind 7 (wasm32; wasm64 reserved and refused), pointer
width as a target property read by TypeLayout, `@[import_module]` for the
WASI namespace, a `_start` entry wrapper, wasm-ld in the link stage with
--fatal-warnings, `with run`/`with test --target=wasm32` through node,
`:cross-rt-wasm` and `:wasm-tests` build targets, test/wasm fixtures,
docs/wasm-target.md and decision D45.

Two native "works by luck" ABI inconsistencies became hard failures on
wasm and are fixed for every target (ABI v5): an explicit `-> Unit`
lowered to an i32 result while an absent return type lowered to void, and
the HashMap/SlotMap runtime helpers were declared with placeholder
prototypes and called with the real arguments.

Not covered: async/fibers (no stack switching; refused at link), c_import
(refused), threads/processes/sockets (report failure), host-built corpus
bundles such as std.regex (refused at link). spec-inventory-check stays
red until `@[import_module]` and the wasm32 guard get spec wording.

* ci: wasm32 hello-world lane on linux; WebAssembly in the default SDK target set

.github/workflows/wasm32.yml runs on ubuntu-latest: it builds the static
LLVM SDK with tools/build-static-llvm.sh (cached on the script's hash, since
no published SDK carries the WebAssembly backend yet), bootstraps the pinned
linux seed, builds the compiler and the wasm32 runtime, compiles
test/wasm/wasm_hello.w for wasm32, runs it under node and asserts its
output, then runs the wasm32 fixtures (:wasm-tests).

WebAssembly joins AArch64 and X86 in the default LLVM_TARGETS_TO_BUILD of
tools/build-static-llvm.sh, tools/build-static-llvm.ps1 and build/sdk.w,
so the next published SDKs can drive this lane without building LLVM.

* build: link against LLVM SDKs without the WebAssembly backend

The compiler references LLVM's five LLVMInitializeWebAssembly* entry points,
so every published SDK (AArch64+X86 only) failed the compiler link with
undefined symbols. When the SDK lib dir has no libLLVMWebAssemblyCodeGen, the
link-metadata actions (native and the linux/windows cross variants) now
alias those entry points to rt/cimport_stubs.w's no-op
with_llvm_wasm_backend_missing, the same way with_clang_main is aliased on
SDKs that predate `with cc`. The generated EmbeddedClangResourceData bakes
embedded_llvm_wasm_backend_linked() from the same SDK fact, and every
command's --target parse refuses wasm32 on such a compiler with a message
naming the fix, before any codegen.

Verified locally both ways: a :dev build against the old SDK links and
refuses --target=wasm32; against the WebAssembly-enabled SDK the response
file carries no alias and the wasm hello world runs under node.

* docs(wasm): the Option[&T] formatting crash is fixed in #1216

* build: produce wasm-capable SDKs from source on all five hosts

Require WebAssembly target archives and wasm-ld at SDK install/package boundaries, include CMake runtime modules, and support Windows ARM64 packaging and wasm-ld.exe lookup.

Build and cache SDK artifacts in each native CI lane, unpack them for compiler verification, and run wasm fixtures. Use bounded-memory With archive I/O, USTAR prefixes for long module paths, and portable stdio without mixing UCRT descriptors with runtime handles.

Root-cause evidence: lldb stopped in sdk_str_compare at the u8 subtraction underflow and in tool_tar_build_header with an empty filename from the old 100-byte path rejection. Real source extraction exposed the whole-archive read limit; SDK packaging exceeded the memory gate before streaming. A cold HTTPS source fetch exposed the missing explicit bigint helper return type.

Validation: source-built LLVM 22.1.6 SDK; graph-owned Ninja/CMake source builds and LLVM source download/extraction; deterministic archive contract with binary data, empty file, permissions, symlink and long paths; native tar round trip and SHA256; packaged SDK LLVM configure; final compiler build and all six wasm fixtures; actionlint and diff checks. Other native hosts require CI.

---------

Co-authored-by: Eric Hartford <[email protected]>
Route nullable option payloads through the shared typed formatter. Follow reference layers by semantic type and handle Unit without loading LLVM void.

Debugger evidence: the old nested-reference repro passed an i32 address containing 0x41 to with_str_from_cstr and printed Some(A). Option[&Unit] trapped in LLVMBuildLoad2 called from gen_display_nullable_option; the same construction without formatting compiled. The fixed nested repro prints Some(65) and no longer links with_str_from_cstr.

Add regression coverage for double/triple references, strings, unsigned integers, None, Unit Some/None/debug/nested references, structs and nested options. Validation: dev compiler build, new and original regressions, all 53 matching formatting/option fixture files, and diff check passed. The broad analyze audit was stopped after prolonged ownership-state computation and is not claimed as passing.
@ehartford
ehartford merged commit 95cfaaa into main Sep 21, 2026
0 of 5 checks passed
@ehartford
ehartford deleted the fix-fstring-option-ref branch September 24, 2026 16:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants