Skip to content

String conversion APIs: CString, .to_cstring()/.as_cstr(), .as_view()/.to_owned() (§15.1–§15.3) #427

Closed

Description

@ehartford

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 str values and that non-str expressions 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/CString or 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-1258 registers a builtin CStr struct shape with ptr and len fields and a &CStr view type.
  • src/Sema.w:1285-1288 registers str, String, StrView, and CStr primitive names. String is currently an alias for owned str, and StrView is currently a reference/view type.
  • src/Codegen.w:488-489 interns str and CStr; src/Codegen.w:2625-2638 declares the LLVM shape for builtin CStr.
  • Searches for to_cstring, as_cstr, as_view, and to_owned show no coherent stdlib method surface for strings. The only CStr currently present is the builtin compiler/runtime representation, not a complete public API.
  • docs/completed/spec-impl-unalignment.md:113 flags the CString/CStr method surface as unverified.
  • docs/completed/mut.md:1071-1072 uses the intended path.to_cstring().ptr style 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

  1. Decide and encode the concrete type model:
    • String remains the public alias/name for owned str.
    • StrView is the public borrowed string view type, backed by the existing ty_str_view.
    • CStr is a borrowed NUL-terminated view with pointer and byte length excluding the terminator.
    • CString is a new owned, NUL-terminated buffer type with Drop.
  2. Add CString to sema/codegen builtin registration near src/Sema.w:1251-1288 and src/Codegen.w:2625-2638, or implement it as a stdlib type if the compiler no longer needs builtin knowledge beyond layout.
  3. Implement stdlib methods in the appropriate string/ffi module:
    • str.as_view() -> StrView and StrView.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.len that keep lifetime explicit.
  4. Implement Drop for CString so the allocation is visible in the type and cleaned deterministically.
  5. Route modeled retained C-string bindings to require CString/&CStr instead of using a call-scoped temporary.
  6. Ensure generated docs and diagnostics use the same names. If CString allocation can fail, expose the failure as Result, 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 a CString; c.as_cstr().len == s.len().
  • Compile-error test for to_cstring() on a proven interior-NUL string, or a behavior test expecting an Err if the API returns Result.
  • C interop smoke test where an API that retains the pointer accepts CString/&CStr but rejects a temporary str.
  • Regression test that CStr literals from test/spec/spec_ss15_3_c_string_literals.w still typecheck as borrowed C strings.

Acceptance criteria

  • Public String, StrView, CStr, and CString names have documented, tested behavior
  • .as_view(), .to_owned(), .to_cstring(), and .as_cstr() exist with the expected ownership/lifetime semantics
  • CString owns and frees its allocation through Drop
  • 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 str temporaries
  • with build && with build :fixpoint && with build :test pass

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

  1. ehartford commented on Jun 17, 2026

    @ehartford
    ContributorAuthor

    Blocked on #601. I implemented the full conversion surface in lib/std/string.w and verified the non-Result parts work:

    #601: dropping a Result[CString, E] (or any Result[DropType, E]) in the Err case runs Drop on the inactive Ok variant's garbage payload → panic: invalid free. This makes to_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 str temporaries for retained C-string params) additionally needs a param-retention contract mechanism that doesn't exist yet — likely its own follow-up.

  2. ehartford commented on Jun 17, 2026

    @ehartford
    ContributorAuthor

    Implemented in 6ee7119.

    Delivered (std.string): str.as_view() -> StrView, str.to_owned() -> str, CString (owned NUL-terminated buffer with Drop), 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions