Repository navigation
Description
Summary
Ship the curated libc contract overlay the spec names as a standard toolchain deliverable. Since the safe/raw classification landed (commit 1373e45), every pointer-taking import is raw — even fopen(path, mode) and strlen(s), the spec's own §16.3c examples — so the §16.1 pitch ("modeled C functions just call") currently holds only for value-typed signatures. The overlay supplies contract evidence (NUL-termination, retention, nullability, buffer/length pairing, ownership) so high-traffic libc calls present modeled surfaces out of the box.
Spec
§16.3c Contract-Driven Coercion — Contract metadata sources (new in v7.0):
- "The facts that make a binding modeled come from, in priority order: explicit annotations in the importing project, curated contract overlays shipped with the toolchain, and package-supplied binding metadata (
with get c.*)." - "The toolchain maintains a curated libc overlay as a standard deliverable, so common calls such as
fopen,strlen, andwritepresent modeled surfaces out of the box; libraries without overlays import with raw surfaces until contracts are supplied." - "An overlay supplies evidence, never exemptions — it cannot weaken the rules below." (the str→
*const c_charfacts 1-3, byte-buffer ptr+len pairing, no hidden allocation, nullability asOption, etc.)
§16.1: modeled bindings are ordinary With calls; unmodeled contracts stay raw/explicit.
Current state
ci_function_requires_raw_abi(src/SemaDecl.w:478-496) marks any import raw when the signature is variadic or any param/return type tripsci_type_requires_raw_contract(src/SemaDecl.w:461-476: TY_PTR/TY_REF/TY_SLICE/TY_FN/TY_EXTERN_FN, recursing through generic args). Raw bindings requireunsafeto call (testerr_c_import_raw_call_requires_unsafe.w).- The only modeled coercion today is bool→int (
Sema.try_ci_coercion,src/SemaDiag.w:41-48); string-context "magic" was deliberately removed (req verdicts 16.3.4.28/.31/.43: no context reinterpretation, no strlen guessing). - There is no overlay format, no overlay lookup, and no per-parameter contract storage. Result:
unsafe { strlen(s) }is required andstrlen(s)with a Withstris a type error (testerr_c_import_str_to_c_char_requires_contract.w). - Evidence priority order has no implementation: explicit-annotation (CoreFoundation's reference-counted type family: model it as a D51 convention profile #357/Align @[effect] with §16.3d (declared effect contracts) #402) and package metadata (
with get c.*) sources are also absent.
Implementation plan
Phase A — overlay format and plumbing:
- Define the overlay schema as binding metadata keyed by
(header-ish domain, symbol name)with per-parameter and return facts, e.g.:- param facts:
cstr_in(read-only NUL-terminated input, no retention),buf_in(ptr=, len=)pairing,buf_out(ptr=, cap=),retains,consumes; - return facts:
nullable_ptr(→Option[*T]),owned(destructor=...)(feeds CoreFoundation's reference-counted type family: model it as a D51 convention profile #357),borrowed; - effects mapping onto
@[effect]bits where applicable (Align @[effect] with §16.3d (declared effect contracts) #402).
Encode as a With-source data table compiled into the compiler (e.g.src/CiOverlay.wwith a static table, or a.wovertext file embedded like the stdlib viasrc/compiler/EmbeddedStdlib.wmachinery). Determinism: iteration must be ordered (no unordered-map iteration — fixpoint rule).
- param facts:
- Add overlay lookup in c_import binding generation: when
ci_function_requires_raw_abiwould classify raw, first consult the overlay; if every pointer-bearing param/return has facts, generate the modeled binding instead:cstr_inparam: accept Withstr; emit the §16.3c bridge — pass directly when provably NUL-terminated static storage (string literals), else build a call-scoped NUL-terminated temporary, freed after the call; interior-NUL handling per Bug: str→C-string conversion ignores interior NUL (§16.3c) #426 (proven NUL = compile error; dynamic NUL = loud runtime per binding error model).buf_inpair: acceptstr/[]u8and expand to (ptr, len) at the call.nullable_ptrreturn: type asOption[*T](machinery exists:behav_c_import_nullable_ptr_none.w).- Anything without facts: stay raw (unchanged classification).
- Wire the priority order: project-local explicit annotations (when CoreFoundation's reference-counted type family: model it as a D51 convention profile #357/Align @[effect] with §16.3d (declared effect contracts) #402 land) override overlay entries; overlay overrides package metadata. Structure lookup as a chain so sources can land incrementally.
Phase B — curated libc content: - Ship overlay entries for the high-traffic surface: stdio (
fopen,fclose,fread,fwrite,fgets,printf-family stays raw/variadic), string (strlen,strcmp,strchrwith borrowed returns), stdlib (getenvnullable+borrowed,malloc/freestay raw — ownership belongs to CoreFoundation's reference-counted type family: model it as a D51 convention profile #357 wrappers), unistd (write,read,close). Each entry must cite the contract it asserts; entries are evidence, so wrong entries are bugs, not tuning. - Include the overlay version in the c_import cache key (
Zcu.c_import_cache_key_frontend,src/compiler/Frontend.w:352-374— add a#overlay:fingerprint line) so editing the overlay invalidates cached bindings.
Test plan
test/spec/spec_ss16_3c_libc_overlay.w:use c_import("stdio.h", ...)/string.h;strlen("abc") == 3callable withoutunsafe;fopen/fcloseround-trip on a temp file withoutunsafe;write(fd, data)with astrunder the modeled pair.//! expect-stdout: ok.test/compile_errors/err_c_import_unoverlaid_stays_raw.w: inline-header import of a customvoid f(char *p);(no overlay) — calling withoutunsafe→//! expect-error:(raw surface retained).- Interior NUL: proven interior NUL passed to a
cstr_inparam is a compile error (shared with Bug: str→C-string conversion ignores interior NUL (§16.3c) #426's tests). - Nullability: overlaid
getenv("NOPE")returnsOption;Noneobserved. - Cache: changing overlay fingerprint invalidates (internals test around the cache key; allow-list analogue already exists per Frontend.w:361-364).
- Negative guarantee: no overlay entry can make an unbounded
ptr-only buffer modeled (schema-level test or review gate).
Acceptance criteria
- Overlay format defined, documented, and embedded with the toolchain; lookup chain implements the §16.3c priority order.
-
fopen,strlen,write(documented contracts) callable withoutunsafe; semantics match §16.3c (no silent truncation, no hidden caller-owned allocation, nullability preserved). - Un-overlaid pointer functions remain raw — classification logic in SemaDecl.w unchanged for the no-evidence case.
- Overlay participates in the c_import cache key.
-
with build && with build :fixpoint && with build :testpass.
Dependencies
- Bug: str→C-string conversion ignores interior NUL (§16.3c) #426 (interior-NUL handling — the str→C-string bridge must implement it).
- String conversion APIs: CString, .to_cstring()/.as_cstr(), .as_view()/.to_owned() (§15.1–§15.3) #427 (CString/CStr APIs — caller-managed storage for retention cases).
- CoreFoundation's reference-counted type family: model it as a D51 convention profile #357 (ownership evidence → Drop wrappers;
owned(destructor=...)return facts feed it). - Align @[effect] with §16.3d (declared effect contracts) #402 (@[effect] — effect bits for overlay entries).
- Tests: c import coercion coverage (§16) #486 (coercion test coverage overlaps the negative cases).
Traceability
Spec reference: §16.3c Contract-Driven Coercion (Contract metadata sources — new in v7.0), §16.1.
Activity
ehartford commentedon Jun 18, 2026
Resolved design direction (maintainer decision)
The curated overlay replaces the blanket
const char*-as-cstring rule shipped in commit 1e53f8a — it does not merely supplement it. Rationale:Sema.ci_type_is_const_c_string_input/ci_param_type_requires_raw_contractinsrc/SemaDecl.w:472-488) assumes everyconst char*param is a NUL-terminated string input. That is exactly the "strlen guessing" / "context reinterpretation" the §16.3c req verdicts (16.3.4.28/.31/.43) forbid.const char*is also used for non-terminated byte buffers, single chars, and opaque data, so the blanket rule is unsound in the general case — a silent FFI memory-safety hazard.Implementation outline (for a dedicated session)
const char*exemption (ci_type_is_const_c_string_inputand its use inci_param_type_requires_raw_contract). With it gone, aconst char*-param extern reverts to raw/unsafe unless the overlay supplies acstr_infact.(domain, symbol)with per-param/return facts (cstr_in,buf_in(ptr,len),buf_out(ptr,cap),retains,consumes; returnsnullable_ptr→Option,owned(destructor)→feeds CoreFoundation's reference-counted type family: model it as a D51 convention profile #357,borrowed). Lookup inci_function_requires_raw_abi: modeled iff every pointer-bearing param/return has facts.strlen(and the others exercised bybehav_c_import_const_c_string_arg.w) move into the overlay so that test keeps passing through the evidenced path, not the blanket rule.Zcu.c_import_cache_key_frontend,src/compiler/Frontend.w).Note / caveat
This is a behavior change: generic
const char*externs not covered by the overlay revert to raw (requireunsafe). Acceptable per the spec-faithful reading; flagged here so the change is intentional, not a surprise. The migration is mechanical (add the contract to the project or the overlay). Deferred to a dedicated session because an overlay subsystem with a behavior change is high-risk to land at the tail of a long run.ehartford commentedon Jun 18, 2026
FINAL decision: Option 1 (overlay replaces blanket rule), take the breaking change
No external users → no migration, no deprecation cycle. The blanket
const char*→cstring rule (commit 1e53f8a) is removed;const char*params become modeled only when the overlay supplies acstr_infact. This is the cheapest this change will ever be — every added test/dependent makes ripping out the blanket rule harder later.Paper trail for future-me reading the removal in
git log: the blanket rule was unsound (const char*is also non-terminated buffers / single chars / opaque data) and was exactly the "strlen guessing" §16.3c forbids. It is replaced by evidence-driven overlay contracts, one coherent model.Day-one overlay coverage (REQUIRED — do not land the removal without this)
The removal must ship with enough real libc coverage that it is a net correctness improvement, not just purity. If the first overlay entry is only
strlen, the blanket rule has been rebuilt by hand for one symbol. Minimum tier-1 set, each citing the contract it asserts:cstr_in, value return (pure wins):strlen,strcmp,strncmp,strcasecmp,strncasecmp,atoi,atol,atofcstr_in, nullable borrowed ptr return →Option:strchr,strrchr,strstr,strpbrk,getenvbuf_in(ptr,len)pairs:memcmp,memchr(nullable Option return),writebehav_c_import_const_c_string_arg.w(strlen) must keep passing through the overlay, not the blanket rule — update the test's comment to say so; the assertions stay identical.Explicitly stays RAW day one (the blanket rule was wrong or unproven here)
strcpy,strncpy,strcat,sprintf,memcpy,memmove,memset(model asbuf_outlater when cap evidence is expressible).malloc,calloc,realloc,free,strdup,fopen/fclose. These getowned(destructor=…)facts once CoreFoundation's reference-counted type family: model it as a D51 convention profile #357 lands.Not tonight
Decision is made; implementation is a fresh-session job — overlay format + lookup + per-param contract storage + reverting the blanket rule + overlay cache-key fingerprint, with fixpoint kept green throughout. Threading a behavior change through sema is not tail-of-a-long-run work.
Replace blanket const char* modeling with curated overlay evidence (#379
ehartford commentedon Jun 18, 2026
Landed: cstr_in core + the breaking change (commit a88df01)
Option 1 is implemented for the
cstr_infact:ci_param_type_requires_raw_contract(the unconditionalconst char*exemption from 1e53f8a) is gone.ci_overlay_cstr_in_param_count(src/SemaDecl.w) is the curated table;ci_function_requires_raw_abimodels a pointer param only when the overlay vouches for it ascstr_in.try_ci_coercion(src/SemaDiag.w) gates the str→C-string coercion on the function being modeled (not inci_raw_syms) — raw functions get no string magic.frontend_cimport_compiler_fingerprint_line), so overlay edits invalidate cached bindings. No separate fingerprint needed.behav_c_import_const_c_string_arg(strlen via overlay),behav_c_import_overlay_strcmp,err_c_import_const_char_requires_overlay_evidence(non-curated const-char* now requires unsafe). Behavior 694 / compile-error 605 / spec 173, fixpoint holds.Behavior change is live: generic
const char*externs not in the overlay now requireunsafe.Remaining facts + an architectural finding
While prototyping
nullable_ptrI hit a design constraint worth recording:nullable_ptrborrowed returns (strchr/strrchr/strstr/strpbrk/getenv). Making these modeled (safe to call) is only half of it — to be spec-correct the return must be typedOption[*T]. Pointer returns becomeOption[*T]only when clang sees a_Nullableannotation (that is whymallocfromstdlib.hisOptionbut an unannotated inlinechar *strchr(...)is a plain*mut u8). So the overlay must rewrite the return toOption[*T]at binding generation (ci_emitflat-fn path,src/CImport.w:~1390), not merely exempt it from the raw check in sema. Shipping the exemption alone yields a plain nullable pointer — exactly the unsound shape Option 1 set out to remove.src/SemaDecl.w(whichusesSema);src/CImport.wdoes notuse Semaand adding it risks a dependency cycle. The clean fix is a dependency-freeCiOverlaymodule that bothCImport.w(for return rewriting) andSemaDecl.w(for raw classification)use. That refactor is the right first step for the remaining facts.buf_in(ptr,len)pairs (memcmp/memchr/write). Arity-changing: one With[]u8/strarg expands to two C args at the call. Needs call-lowering work.ownedreturns (fopen/strdup). Deferred to CoreFoundation's reference-counted type family: model it as a D51 convention profile #357's owning-wrapper mechanism.Next session: extract
CiOverlay, then addnullable_ptr(withOption[*T]return rewriting) andbuf_in.ehartford commentedon Jun 18, 2026
nullable_ptr attempt: validated approach + one focused codegen blocker (reverted, diagnosed)
Implemented the next fact (
nullable_ptrborrowed returns) end-to-end and reverted it after isolating a single MIR-typing bug. Recording the full diagnosis so the next session starts de-risked.What worked (architecture is sound):
src/CiOverlay.wleaf module holding the overlay tables. BothSemaDecl.w(raw classification) andCImport.w(binding generation)use CiOverlaywith no dependency cycle. Build + fixpoint green — the module auto-discovers (build globssrc/) and bare cross-module calls resolve.ci_overlay_return_is_borrowed_ptr(getenv/strchr/strrchr/strstr/strpbrk) and, inci_translate_function(src/CImport.w), wrapped such returns:if borrowed_ptr and ret starts "*" and not already Option: ret = "Option[" ++ ret ++ "]". Inci_function_requires_raw_abithe return is exempted from raw when the overlay vouches a borrowed ptr.strchr/getenvcompile and model correctly — callable without unsafe, typedOption[*T]. Sema is happy (it builds theNoneaggregate, proving it typed the result as Option).The blocker (codegen, not design):
Calling a modeled c_import function whose return I wrapped as
Option[*T]fails at codegen:src/CodegenDispatch.w:3303.dest_sema=14isty_void(14th base type). WithWITH_DEBUG_MIR_CODEGEN=1:[mir-call] callee=getenvthen[mir-agg] fn=main count=0 dest_ty_kind=0— theNoneaggregate's destination type is void, i.e. the modeled call'sOption[*T]return type is not propagated to the MIR call result.malloc(_Nullable→Option[*mut c_void], testbehav_c_import_nullable_ptr_none.w) works — but it is raw, called underunsafe. The modeled call path (which also applies the str→cstr arg coercion) is what drops the return type. This path was never exercised before because every previously-modeled c_import function had a scalar return.Fix direction for next session: make the modeled c_import call lowering (the coercion-applying path in
MirLower/SemaCheckcall handling) carry the callee's aggregate (Option[*T]) return type onto the MIR call result, the way the raw/_Nullablepath does. Then re-apply the (small, known-good)CiOverlayextraction +ci_translate_functionOption-wrap + the two tests (strchrSome/None/deref,getenvNone). Repro is instant:./out/release/bin/with build <test.w>(compile-time error, no full rebuild needed).Shipped state remains the cstr_in core (a88df01); this attempt is reverted.
ehartford commentedon Jun 18, 2026
The nullable_ptr codegen blocker is now tracked as #603 (modeled c_import Option[*T] returns mistype the aggregate destination as void). #603 blocks the nullable_ptr fact here; cstr_in core (a88df01) is unaffected. Fixing #603 unblocks re-applying nullable_ptr.
Model c_import borrowed nullable-pointer returns (#379)
Add negative test: uncurated pointer return stays raw (#379, #603)
ehartford commentedon Jun 18, 2026
Landed: nullable_ptr borrowed returns (490f61b, c9c1d6b) — #603 closed
strchr, strrchr, strstr, strpbrk, getenv are now modeled (callable without
unsafe), viaci_overlay_return_is_borrowed_ptrinsrc/SemaDecl.w.Corrected design note (supersedes the earlier "rewrite the return to
Option[*T]at binding-gen" plan): raw C pointers are natively nullable in With —== Noneand.unwrap()work directly on a plain*T(malloc returns a plain*mut c_voidand is used exactly this way). So a borrowed nullable-pointer return is left a plain raw pointer; the overlay fact only makes the call safe, and dereferencing the borrowed pointer staysunsafe. NoOptionbinding-text wrap, noCImportchange, no codegen change, noCiOverlaymodule / dependency-cycle concern. The earlier blocker (#603) was an artifact of the wrong wrap and is closed.Tests:
behav_c_import_overlay_strchr_borrowed,behav_c_import_overlay_getenv_none,err_c_import_uncurated_ptr_return_raw. Behavior 696, compile-error 606, fixpoint holds.Overlay coverage now
Remaining facts
buf_in(ptr,len)pairs (memcmp/memchr/write/read). Arity-changing: one With[]u8/strargument expands to two C arguments at the call site. This is the only remaining fact that needs new call-lowering machinery.ownedreturns (fopen/strdup). Deferred to CoreFoundation's reference-counted type family: model it as a D51 convention profile #357's owning-wrapper mechanism (owned(destructor=...)).ehartford commentedon Jun 18, 2026
buf_in: design-heavy, deferred with rationale
buf_in(collapse a(ptr, len)C pair into one With[]u8) needs new wrapper-generation infrastructure: emit the raw C function under a mangled extern name plus a safe With wrapper (fn f(buf: []u8) ...: unsafe { __raw_f(buf.ptr, buf.len) }). The wrapper is sound — the slice's length invariant makes the(ptr, len)call safe — and it is CImport-only (no cross-module/codegen concerns). The hard part is not the mechanism; it is that every clean libc target carries a semantic decision:write/read— the spec's headlinebuf_inexamples — are unavailable: c_importwritecollides with the With prelude and is omitted (seespec_ss16_ffi_and_c_import.w::test_c_import_system_prelude_collision_is_omitted).readisbuf_out(writes into the buffer), a mutable-slice variant — a different fact.memcmp(const void*, const void*, size_t)— two buffers share one length.nsemantics are a real choice (requirea.len == b.len? comparemin? compare common prefix?) — the spec does not specify, so picking one is a design decision, not a mechanical translation.memchr(const void*, int, size_t)—buf_inand a borrowed nullable-pointer return at once; the cleanest target but it composes two facts.So
buf_inis not a "one more overlay line" addition like cstr_in/nullable_ptr; it is a wrapper-gen feature whose every entry needs a contract decision (in vs out direction, two-buffer length relationship). It warrants a deliberate design pass (and abuf_outcompanion fact), not tail-end grinding.#379 status: substantially delivered
The two clean, high-traffic modeling facts are shipped and the unsound blanket rule is gone:
Remaining facts are tracked here but are each their own design effort:
buf_in/buf_out— wrapper-gen + per-entry contract decisions (above).ownedreturns (fopen/strdup) — belongs to CoreFoundation's reference-counted type family: model it as a D51 convention profile #357's owning-wrapper mechanism (owned(destructor=...)).Leaving #379 open for buf_in/owned, but the core overlay (evidence model + the high-traffic surface) is in.
Add @[link_name("symbol")] attribute for extern fns (toward #379)
Model c_import buf_in byte-buffer contracts (#379)
ehartford commentedon Jun 18, 2026
Landed: buf_in + @[link_name] (commits dba8b5e2, c1bd993)
@[link_name("symbol")]extern-fn attribute added (the primitive the wrapper needs to rename a raw binding while keeping C linkage).memchr,memcmpare modeled — a(ptr, len)C pair collapses into one With[]u8.ci_emit_buf_wrapper(src/CImport.w) generates a renamed raw extern (@[link_name], hidden) plus a safe slice-takingfnwrapper; the slice length invariant makes the call memory-safe.memcmprequires equal lengths (panics) per the agreed contract.ci_function_requires_raw_abiexempts any c_import fn with a slice param (C has no slices → it's a generated safe wrapper).behav_c_import_overlay_memchr,behav_c_import_overlay_memcmp. Behavior 701, fixpoint holds.Overlay coverage now
buf_out scoped to #604 (prerequisite — NOT deferred)
buf_out(memset/explicit_bzero) writes into the buffer, so it needs a[]mut u8argument. With currently cannot construct one (slice exprs yield[]T;split_at_mutyieldsVecRange; bare collections don't coerce) — shipping a buf_out wrapper now would be uncallable and would regress the rawmemsetsurface. The wrapper generator already handles the mutable case (is_mut→[]mut u8+&raw mut); only the[]mut Targument coercion (a missing, spec-promised coercion) and the overlay entries remain. Tracked with full root-cause analysis + design + size estimate in #604, which blocks buf_out here.Remaining for #379
ehartford commentedon Jun 19, 2026
Closing: curated libc overlay shipped (cstr_in + nullable_ptr + buf_in)
The overlay subsystem and its expressible high-traffic surface are delivered, and the unsound blanket rule is gone:
const char*→cstring assumption (1e53f8a); modeling is now evidence-driven via the curated overlay.[]u8): memchr, memcmp. Via generated safe wrappers over@[link_name]'d raw externs (new attribute, also generally useful).Downstream (tracked separately, NOT part of this overlay issue):
[]mut Tcross-function mutable-slice mechanism ([]mut T stages 2–3: local bindings, returns, and split_at_mut #604). Every current surface is worse than the raw fallback, so they stay raw (no regression). Falls out for free once[]mut Tlands.Closing #379 on the shipped overlay; the two remaining facts live with their actual prerequisites (#604, #357).
Add "Verify by Running, Not by Reasoning" to agent guidance
#357: generate proven-ownership owning wrappers for curated c_import …
ehartford commentedon Jul 2, 2026
buf_out is now shipped: #604 stage 1 landed parameter-position
[]mut Twith call-site coercion (4188d5e7), unblocking the mutable-buffer contract, and8274956ecurates memset/explicit_bzero as[]mut u8— callable with a plain array/Vec argument, nounsafein user code, slice length bounding the C write. (explicit_bzero's entry is inert on Darwin, active where libc declares it.) That completes the buf_in/buf_out pair from this issue's fact list.Implement []mut T stage 1: parameter-position mutable slices (#604)
Curate buf_out wrappers: memset/explicit_bzero as []mut u8 (#379)
release UAT: the raylib spiral on the raw surface, loud without a win…
A user program is a contract: the spiral as published, no `unsafe` in…
Modeled C stage 7: text views, owned foreign text, invalidation, fore…
libc facade: getenv, strerror, strchr, strrchr, strpbrk, strstr are p…
Modeled C stage 7: strings, buffers, domains (ruling §31-§43) (#1597)
c_import: a modeled wrapper beside another module's extern of its C f…
C backend and modeled-C fixes: map loops, generic structs, view compa…