Repository navigation
Description
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): "
longestconsumesabut returns a view derived from it; takea: &String" - Lint-grade (warning): "
fonly readsx; considerx: &Tso 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 checkreports ok. The by-value param is moved into the callee and dies at callee return; the returned&i32dangles. 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_VIEWis recorded when a ref derived from a param escapes via return — explicit returns (src/SemaCheck.w:4994-4999), tail-expression bodies (:866-874, withnote_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 overcurrent_fn_param_effswritesset_sig_param_effect/set_sig_param_view_origin, and notably clamps&T/*Tparams toEFF_READ|EFF_ESCAPE_VIEW|EFF_RAW_PTR_VALIDITY— so a by-value param carryingEFF_ESCAPE_VIEWis precisely identifiable at this point. - View-origin plumbing:
sig_param_view_origins(src/Sema.w:268, 2895, 2904), call-site recordingrecord_call_view_origins(src/SemaCheck.w:4931, invoked at:8198free calls,:10730/:10733method calls), origin liveness checkcheck_returned_view_origins(:874). - Param names for the message:
current_fn_param_syms(used at:924).
- Per-param effect inference:
- Read-only inference for the lint form: a param whose accumulated effect is exactly
EFF_READis 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
- Error form (definition site) —
src/SemaCheck.w, in the effect-finalization loop (~:905-925): after computing the finalefffor parampi, if the param type is by-value (resolved kind notTY_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 alongsidecurrent_fn_param_originsas a parallelcurrent_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.
- text:
- Sever the unsound acceptance path:
record_call_view_origins/check_returned_view_originscurrently tie returned views to argument origins regardless of parameter mode. Once step 1 makes the definition an error, add a defensive guard inrecord_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. - 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_methodsrc/Sema.w:3370plus 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). Skipmain, 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).
- text:
- Effect-inference dependency: the error form is only as good as
EFF_ESCAPE_VIEWinference. The known gap — consume via plainlet x = paramnot recordingEFF_CONSUME(Remove the move x/copy x acknowledgment requirement for consuming arguments #372 step 2) — does not affectEFF_ESCAPE_VIEW, but verify the field-projection case (¶m.fieldthrough nested fields) populatescompute_expr_view_origin_maskcorrectly; add tests either way. - 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): thelongest-shaped repro — two by-value params, returns&str/&i32derived from one; assert the message names the parameter and the&Tremedy.test/compile_errors/err_byvalue_view_escape_tail.w: tail-expression body (fn f(b: Buf) -> &i32: &b.data) — covers the:866inference 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. Extendtest/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;&Tparam 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 explicitmove). - 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&Tfix, 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
&Tparams 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 :testpass.
Dependencies
- Remove the move x/copy x acknowledgment requirement for consuming arguments #372 (remove move/copy ack) — this diagnostic is its replacement; also Remove the move x/copy x acknowledgment requirement for consuming arguments #372 step 2 fixes the consume-inference gap the lint's "not consumed" condition relies on.
- Implement returned-view origin tracking (§21.1 Rule 6) with the §22.3 diagnostic contract #378 (returned-view origin tracking with §22.3 contract) — owns the call-site half of Rule 6; this issue owns the definition-site mode check. Step 2's guard overlaps; coordinate.
- Tests: drop semantics coverage (§2) #496 split bug — shares the transitive needs-drop predicate used by the lint exemption.
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
ehartford commentedon Jun 13, 2026
Implemented in
bf9a7ac1.Summary:
&Tremedy.readaway when stronger effects are present, preserving existing@[effect]contracts while enabling the read-only by-value warning.&T/Drop exemptions.Verification passed after rebasing onto
origin/main:WITH=$PWD/out/bin/with ./out/release/bin/with check src/main.wWITH=$PWD/out/bin/with ./out/release/bin/with buildWITH=$PWD/out/bin/with ./out/release/bin/with build :fixpointWITH=$PWD/out/bin/with ./out/release/bin/with build :testWITH=$PWD/out/bin/with ./out/release/bin/with build :test-green