Skip to content

Directed diagnostic: by-value parameter that is only read (or whose view escapes) should suggest &T #373

Closed

Description

@ehartford

Summary

Add the definition-site directed diagnostic that §3.8 (v7.1) requires for the classic call-mode authoring mistake: a plain T parameter consumes, so a function that returns a view derived from a by-value parameter produces a dangling reference, and a function that only reads a by-value parameter needlessly invalidates the caller's binding. Today the compiler accepts the dangling case entirely (verified — see Current state), so the strong form of this diagnostic is a soundness fix, not a lint. This is the constructive replacement for the move x/copy x gate removed by #372.

Spec

§3.8 Auto-Referencing (normative, final paragraph): "A function that only reads a by-value parameter, or returns a view derived from one, should take &T instead; when the compiler can see this mistake (for example, a view of a consumed parameter escaping through the return value), it emits a directed suggestion naming the parameter and the &T fix."

§21.1 Rule 6 (returned-view origin tracking): the origin set of a returned view is tied to argument lifetimes at the call site — which presupposes origins are borrowed, not consumed; a consumed origin dies inside the callee, so no call-site lifetime can ever satisfy it.

§22.3 Diagnostic Contract: rejections from origin/view rules must report (1) the origin, (2) the violation, (3) the later use when relevant, and name at least one idiomatic remedy ("take &T"). A single-location error does not satisfy the contract.

Expected diagnostics (from the original issue, aligned with §22.3):

  • Load-bearing (error): "longest consumes a but returns a view derived from it; take a: &String"
  • Lint-grade (warning): "f only reads x; consider x: &T so callers keep their binding"

Current state

Verified at 1c5258007a362fcd8c7a145b3e9c3be4c84ac47d:

  • The dangling program compiles and runs today. Probe: type Buf { data: i32 } (+ Drop impl), fn first_view(b: Buf) -> &i32: &b.data, let v = first_view(buf); print(v) — with-stage2 check reports ok. The by-value param is moved into the callee and dies at callee return; the returned &i32 dangles. Nothing in sema or the borrow checker rejects either the definition or the call.
  • All the inputs for the diagnostic already exist:
    • Per-param effect inference: EFF_ESCAPE_VIEW is recorded when a ref derived from a param escapes via return — explicit returns (src/SemaCheck.w:4994-4999), tail-expression bodies (:866-874, with note_param_view_origin + compute_expr_view_origin_mask), closures (:7029).
    • Effects are finalized into the signature at the end of function-body checking (src/SemaCheck.w:905-925): the loop over current_fn_param_effs writes set_sig_param_effect / set_sig_param_view_origin, and notably clamps &T/*T params to EFF_READ|EFF_ESCAPE_VIEW|EFF_RAW_PTR_VALIDITY — so a by-value param carrying EFF_ESCAPE_VIEW is precisely identifiable at this point.
    • View-origin plumbing: sig_param_view_origins (src/Sema.w:268, 2895, 2904), call-site recording record_call_view_origins (src/SemaCheck.w:4931, invoked at :8198 free calls, :10730/:10733 method calls), origin liveness check check_returned_view_origins (:874).
    • Param names for the message: current_fn_param_syms (used at :924).
  • Read-only inference for the lint form: a param whose accumulated effect is exactly EFF_READ is the "only reads" case. The spec-feedback ruling (docs/completed/spec-feedback.md §A.1, 2026-06-09 second pass) retracted silently rewriting such params as borrows because consume-then-dispose (RAII) bodies are textually identical — which is also why the lint must not fire for Drop-implementing types.
  • Nothing emits either diagnostic today; no test references them.

Implementation plan

  1. Error form (definition site) — src/SemaCheck.w, in the effect-finalization loop (~:905-925): after computing the final eff for param pi, if the param type is by-value (resolved kind not TY_REF/TY_PTR/slice) and (eff & EFF_ESCAPE_VIEW) != 0, emit an error on the function's param node:
    • text: '{fn_name}' consumes '{param_name}' but returns a view derived from it; take '{param_name}: &{TypeName}'
    • §22.3 compliance: attach a note pointing at the escaping return/tail expression (the node passed to note_place_effect — retain it alongside current_fn_param_origins as a parallel current_fn_param_view_nodes: Vec[i32] so the note has a real span).
    • Fire for Copy params too (a view of a by-value Copy param dangles just the same), with remedy text "return the value instead of a view" when the type is Copy.
  2. Sever the unsound acceptance path: record_call_view_origins/check_returned_view_origins currently tie returned views to argument origins regardless of parameter mode. Once step 1 makes the definition an error, add a defensive guard in record_call_view_origins (:4931): ignore origin params that are by-value (they cannot anchor a caller-side lifetime). This keeps the call-site analysis honest for signatures from modules compiled with errors suppressed (e.g. during migration) instead of silently extending a dead origin.
  3. Lint form (warning) — same finalization loop: if param is by-value, non-Copy, eff == EFF_READ (no write/consume/escape bits), and the param's type does not implement Drop directly or transitively (consume-to-dispose is a legitimate signature; Sema.has_drop_method src/Sema.w:3370 plus a transitive needs-drop helper — coordinate with the predicate Tests: drop semantics coverage (§2) #496's split bug introduces), emit a warning:
    • text: '{fn_name}' only reads '{param_name}'; consider '{param_name}: &{TypeName}' so callers keep their binding
    • Use emit_warning (existing infra, e.g. SemaCheck.w:2547). Skip main, test fns, @[c_export]/extern boundaries, and trait-impl methods whose signature is fixed by the trait declaration (changing the param mode there is not the author's local choice).
  4. Effect-inference dependency: the error form is only as good as EFF_ESCAPE_VIEW inference. The known gap — consume via plain let x = param not recording EFF_CONSUME (Remove the move x/copy x acknowledgment requirement for consuming arguments #372 step 2) — does not affect EFF_ESCAPE_VIEW, but verify the field-projection case (&param.field through nested fields) populates compute_expr_view_origin_mask correctly; add tests either way.
  5. No rt/Link/seed changes; sema-only. Run the lint over the compiler's own sources expecting findings; fix the flagged signatures (they are real wins) rather than suppressing — but if volume is large, land the warning behind the existing diagnostics plumbing first and clean src/ in a follow-up commit (one logical change per commit).

Test plan

  • test/compile_errors/err_byvalue_view_escape.w (//! expect-check-fail: consumes 'a' but returns a view derived from it): the longest-shaped repro — two by-value params, returns &str/&i32 derived from one; assert the message names the parameter and the &T remedy.
  • test/compile_errors/err_byvalue_view_escape_tail.w: tail-expression body (fn f(b: Buf) -> &i32: &b.data) — covers the :866 inference path (this is the exact probe that compiles today).
  • test/compile_errors/err_byvalue_view_escape_field.w: nested field projection &b.inner.data.
  • Negative (no diagnostic): same body with b: &Buf — compiles clean; view-origin call-site rule (§21.1 R6) still applies. Extend test/spec/spec_ss03_4_returning_references.w.
  • Lint form, via //! expect-stderr: warning assertions: by-value non-Copy read-only param warns; same param type with a Drop impl does not warn; &T param does not warn; param that is consumed (let x = v) does not warn (needs Remove the move x/copy x acknowledgment requirement for consuming arguments #372 step 2's inference fix to be reliable — until then write the consumed-param case with explicit move).
  • Regression: spec_ss03_8_auto_referencing.w, err_eff_escape_* successors from Remove the move x/copy x acknowledgment requirement for consuming arguments #372.

Acceptance criteria

  • The probe program (by-value param, returned & view, call + use) is rejected at the definition with a message naming the function, the parameter, and the &T fix, plus a note at the escaping expression (§22.3).
  • Read-only by-value non-Copy params produce the lint warning; Drop-implementing types and trait-fixed signatures are exempt.
  • No false error on &T params or on by-value params whose returned value is owned (EFF_ESCAPE_VALUE only).
  • Compiler sources (src/, lib/std/) build clean under the new error; lint findings in our own code are fixed, not suppressed.
  • with build && with build :fixpoint && with build :test pass.

Dependencies

Traceability

Spec reference: §3.8 (parameter modes), §21.1 Rule 6 (returned-view origin) — spec v7.0/v7.1. Original Expected/Notes preserved: both diagnostic forms, auto-ref keeps call sites unchanged either way, dependency on view-origin analysis (#378).

Activity

  1. ehartford commented on Jun 13, 2026

    @ehartford
    ContributorAuthor

    Implemented in bf9a7ac1.

    Summary:

    • Rejects by-value parameters whose returned view is derived from the consumed parameter, with a diagnostic naming the function, parameter, by-value origin, escaping expression, and &T remedy.
    • Records ordinary read effects and normalizes read away when stronger effects are present, preserving existing @[effect] contracts while enabling the read-only by-value warning.
    • Stops call-site returned-view origin tracking from treating by-value parameters as valid borrow anchors.
    • Adds compile-error coverage for explicit-return, tail-expression, and nested-field dangling views; borrowed-parameter positive spec coverage; and CLI edge coverage for the read-only warning plus &T/Drop exemptions.

    Verification passed after rebasing onto origin/main:

    • WITH=$PWD/out/bin/with ./out/release/bin/with check src/main.w
    • WITH=$PWD/out/bin/with ./out/release/bin/with build
    • WITH=$PWD/out/bin/with ./out/release/bin/with build :fixpoint
    • WITH=$PWD/out/bin/with ./out/release/bin/with build :test
    • WITH=$PWD/out/bin/with ./out/release/bin/with build :test-green
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