Repository navigation
Description
Summary
Implement the string conversion surface promised by §15.1-§15.3: owned strings, borrowed views, C string views, and owned C strings need explicit, ergonomic APIs. The compiler currently registers String, StrView, and CStr aliases/types, but the conversion methods named by the spec and migration docs are absent or untested. This is the user-facing half of making C interop humane without making users become the build system.
Spec
Relevant normative and design points:
- §15.4 states f-strings allocate owned
strvalues and that non-strexpressions must be formatted via f-strings, not by overloading output calls (docs/with-specification.md:7643-7650). - §16.3c says retained or unknown-lifetime C string pointers must use caller-managed storage such as
CStr/CStringor a generated wrapper; call-scoped temporaries are forbidden when the C callee may retain the pointer (docs/with-specification.md:8388-8391). - §16.3c also says no safe C-string conversion may silently truncate, hide caller-owned allocation, transcode, erase nullability, or use a call-scoped temporary for a retained pointer (
docs/with-specification.md:8432-8436).
The intended §15 conversion table from the campaign is:
let owned: String = "hello"
let view: StrView = owned.as_view()
let owned_again: String = view.to_owned()
let c_owned: CString = owned.to_cstring()? // checked interior-NUL conversion
let c_view: &CStr = c_owned.as_cstr()
Current state
src/Sema.w:1251-1258registers a builtinCStrstruct shape withptrandlenfields and a&CStrview type.src/Sema.w:1285-1288registersstr,String,StrView, andCStrprimitive names.Stringis currently an alias for ownedstr, andStrViewis currently a reference/view type.src/Codegen.w:488-489internsstrandCStr;src/Codegen.w:2625-2638declares the LLVM shape for builtinCStr.- Searches for
to_cstring,as_cstr,as_view, andto_ownedshow no coherent stdlib method surface for strings. The onlyCStrcurrently present is the builtin compiler/runtime representation, not a complete public API. docs/completed/spec-impl-unalignment.md:113flags the CString/CStr method surface as unverified.docs/completed/mut.md:1071-1072uses the intendedpath.to_cstring().ptrstyle in design text, which reinforces that this API is expected.- Bug: str→C-string conversion ignores interior NUL (§16.3c) #426 covers the required interior-NUL checks for
str-> C string conversion; this issue owns the stable API shape that uses those checks.
Implementation plan
- Decide and encode the concrete type model:
Stringremains the public alias/name for ownedstr.StrViewis the public borrowed string view type, backed by the existingty_str_view.CStris a borrowed NUL-terminated view with pointer and byte length excluding the terminator.CStringis a new owned, NUL-terminated buffer type withDrop.
- Add
CStringto sema/codegen builtin registration nearsrc/Sema.w:1251-1288andsrc/Codegen.w:2625-2638, or implement it as a stdlib type if the compiler no longer needs builtin knowledge beyond layout. - Implement stdlib methods in the appropriate string/ffi module:
str.as_view() -> StrViewandStrView.to_owned() -> str;str.to_cstring() -> Result[CString, CStringError]or the chosen error type, rejecting interior NUL;CString.as_cstr() -> &CStr;- accessors for
CStr.ptr/CStr.lenthat keep lifetime explicit.
- Implement
DropforCStringso the allocation is visible in the type and cleaned deterministically. - Route modeled retained C-string bindings to require
CString/&CStrinstead of using a call-scoped temporary. - Ensure generated docs and diagnostics use the same names. If
CStringallocation can fail, expose the failure asResult, not panic or silent null.
Test plan
test/spec/spec_ss15_2_string_conversion_apis.w:let s: String = "hi"compiles.let v: StrView = s.as_view()compiles and compares equal to"hi".let s2: String = v.to_owned()copies to owned storage.let c = s.to_cstring()?produces aCString;c.as_cstr().len == s.len().
- Compile-error test for
to_cstring()on a proven interior-NUL string, or a behavior test expecting anErrif the API returnsResult. - C interop smoke test where an API that retains the pointer accepts
CString/&CStrbut rejects a temporarystr. - Regression test that
CStrliterals fromtest/spec/spec_ss15_3_c_string_literals.wstill typecheck as borrowed C strings.
Acceptance criteria
- Public
String,StrView,CStr, andCStringnames have documented, tested behavior -
.as_view(),.to_owned(),.to_cstring(), and.as_cstr()exist with the expected ownership/lifetime semantics -
CStringowns and frees its allocation throughDrop - Interior NUL handling delegates to Bug: str→C-string conversion ignores interior NUL (§16.3c) #426's loud-failure rules
- Modeled retained C-string APIs no longer accept hidden call-scoped
strtemporaries -
with build && with build :fixpoint && with build :testpass
Dependencies
Depends on #426 for interior-NUL safety. Related to #434 only if the chosen CStringError participates in the generated Error trait surface.
Traceability
From the requirements campaign (docs/requirements.md, spec v7.1). Affected requirement IDs: 15.1.1.15, 15.2.1.1, 15.2.1.2, 15.2.1.5, 15.2.1.6, 15.3.1.17.
Activity
ehartford commentedon Jun 17, 2026
Blocked on #601. I implemented the full conversion surface in
lib/std/string.wand verified the non-Result parts work:str.as_view() -> StrView,str.to_owned() -> str✓pub type CString { ptr, len }withDrop(frees viawith_free) ✓ — a directly-boundCStringallocates and frees correctlyCString.as_cstr() -> &CStr(reinterpret;CString/CStrshare a{ptr,len}layout) ✓CStr.ptr()accessor (CStr.len()already existed) ✓enum CStringError: InteriorNulstr.to_cstring() -> Result[CString, CStringError]with an interior-NUL check returningErr(.InteriorNul)(delegates to Bug: str→C-string conversion ignores interior NUL (§16.3c) #426's loud-failure rules) — the Ok path works, but the Err path corrupts memory because of Enum/Result drop glue ignores discriminant — drops inactive Drop variant (memory corruption) #601.#601: dropping a
Result[CString, E](or anyResult[DropType, E]) in theErrcase runsDropon the inactiveOkvariant's garbage payload →panic: invalid free. This makesto_cstring()?unusable for the error path (and is a critical general bug). The clean repro is in #601.Reverted the WIP so main stays green; will re-land once #601's discriminant-aware enum drop glue is fixed.
Note: criterion 5 (reject hidden call-scoped
strtemporaries for retained C-string params) additionally needs a param-retention contract mechanism that doesn't exist yet — likely its own follow-up.Add String/StrView/CStr/CString conversion APIs (#427)
ehartford commentedon Jun 17, 2026
Implemented in 6ee7119.
Delivered (std.string):
str.as_view() -> StrView,str.to_owned() -> str,CString(owned NUL-terminated buffer withDrop),str.to_cstring() -> Result[CString, CStringError](interior NUL →Err(.InteriorNul), delegating to #426),CString.as_cstr() -> &CStr(layout reinterpret),CString.len(),CStr.ptr().This depended on #601 — the
Result[CString, _]Err-path drop corrupted the allocator until that match-arm-binding-scope bug was fixed.Acceptance criteria
Tests: spec_ss15_2_string_conversion_apis, behav_str_to_cstring_interior_nul_err.