Skip to content

Implement returned-view origin tracking (§21.1 Rule 6) with the §22.3 diagnostic contract #378

Closed

Description

@ehartford

Implement returned-view origin tracking (§21.1 Rule 6) with the §22.3 diagnostic contract

Summary

Rule 6 makes function boundaries participate in lifetime reasoning without annotations: when a function returns a view derived from parameters, the compiler records the possible-origin set in the function's effect summary, and at the call site ties the result to the intersection of those origins' lifetimes. Since the original survey, partial machinery shipped on main (commit 7caa03f4, "feat: implement closure summaries and view-origin checks"): origin masks, binding/expr view-deps, and return-point rejection now exist and err_view_two_origins.w passes. What remains is the call-site use-after-origin-death check (the actual normative example in §21.1 Rule 6) and upgrading every rejection to the §22.3 three-location-plus-remedy diagnostic contract. This is the load-bearing precision/diagnostics investment for the no-annotation model — users cannot annotate their way out, so rejection quality is the product.

Spec

§21.1 Rule 6 (docs/with-specification.md:10541-10560):

Returned-view origin tracking. When a function returns a reference or other view derived from one or more parameters, the compiler records the set of possible origin parameters in the function's effect summary. At the call site, the result is tied to the intersection of those origin lifetimes. If any possible origin dies before the view's last use, the program is rejected.

fn longest(a: &String, b: &String) -> &str: ...
let s1 = String.from("hello")
let view: &str
{
    let s2 = String.from("world")
    view = longest(s1, s2)
}
print(view) // ERROR: view may originate from s2

§22.3 Diagnostic Contract (docs/with-specification.md:10672-10691): every rejection produced by the §22.1 ephemeral rules and the §21.1 view-liveness rules must report, with source locations: (1) where the value was created (origin), (2) where it escapes or is invalidated (violation), (3) where it is later used when that is what makes the program unsafe — plus at least one idiomatic remedy (clone/copy out, collect into owned data, use a handle, restructure into a with scope, take &T). "A single-location 'value escapes' error does not satisfy this contract."

Also §3.4 (returning references), §21 preamble (function boundaries participate via inferred effect summaries).

Current state

Shipped (commit 7caa03f4, 2026-05-05) — verify-before-extending inventory:

  • Summary side (src/Sema.w): sig_param_view_origins: Vec[i32] (:268) — per-signature, per-param origin bitmask; binding_view_dep_* (:523-525) and expr_view_dep_* (:528-530) — concrete origin-symbol lists per binding/expression; closure_capture_summary_* (:515-517).
  • Recording (src/SemaCheck.w): function-body return masks recorded at :872-874 and stored into the signature at :920-922 (set_sig_param_view_origin); compute_expr_view_origin_mask (:4752) walks idents/calls/if-arms; record_call_view_origins (:4931) unions callee origin masks into call-site expr_view_deps, mapping origin params to concrete argument symbols (receiver handled via param_offset); binding deps populated at let via set_binding_view_deps (:4784); closure captures fold into expr_view_deps (:7744-7760).
  • Checking (src/SemaCheck.w): check_returned_view_origins (:4864) and check_yielded_view_origins (:4797) reject returning/yielding a view whose origin view_origin_is_stack_local (:4786); invoked at block tails (:4408), return values (:5002-5004), and fn-body roots (:874).
  • Passing fixtures: test/compile_errors/err_view_two_origins.w (two-origin longest-style leak through a call), err_view_dangling.w (local view via call returned), test/behavior/behav_escape_view_valid.w (param-origin return accepted), err_closure_capture_escape_summary.w. Earlier direct cases: err_return_local_ref_direct.w, err_return_local_ref_via_call.w, err_return_local_ref_binding.w.

Gaps vs the full Rule 6 + §22.3 contract:

  1. No call-site use-after-origin-death check. The dep data is consumed only at return/yield points and by raw-pointer validity notes (:2689-2697). The normative §21.1 Rule 6 example — view = longest(s1, s2) where s2 dies at inner-block end and view is used afterward without being returned — is accepted today. Origin death is only detected when the origin is a stack local leaking out of the whole function.
  2. Diagnostics violate §22.3. All five rejection sites emit single-location messages: "returned view may outlive its origin 'b'" (:4870, :4898, :4915, :4926) and "returned view may outlive its origin via local binding 'view'" (:4919). No origin label, no later-use label, no remedy. The precedent pattern to copy is the three-location view-liveness diagnostic at src/SemaCheck.w:11797-11809 (Diagnostic.err + add_label("view created here") + add_label("view used here")).
  3. Coverage gaps documented in src/BorrowCfg.w:22-29: branch-divergent uses, loop-iteration carry, and precise dataflow through calls are not handled by the AST-scan NLL substrate the origin checks ride on.
  4. Origin masks are i32 bitmasks shifted by param index (:4890, :4942) — functions with >31 params silently lose origin bits; needs a conservative all-origins fallback.

Implementation plan

  1. Origin-lifetime tying at call sites (src/SemaCheck.w). When a binding receives view deps (set_binding_view_deps, :4784), also record each dep's defining scope depth/decl node (the scope machinery already tracks decl nodes via binding_decl_nodes, :4507). On scope pop in check_block, for each dying local d, scan live ref-typed bindings of outer scopes whose dep list contains d; mark that binding poisoned-by-d (store the dying sym + its decl node + the dep-recording node). Use ordered Vec side tables keyed by binding sym — no unordered iteration (fixpoint determinism).
  2. Reject at the later use. In check_expr's ident path (and place-root uses), if the referenced binding is poisoned, emit the Rule 6 error at the use site. A poisoned binding that is never used after the origin dies is fine (NLL: "before the view's last use"). This mirrors how expire_dead_borrows_in_block (:4388) already scans forward for future uses — reuse expr_uses_symbol to decide whether any use follows the scope pop, attributing the first such use.
  3. §22.3 diagnostic shape (apply to the new check and retrofit the five existing single-location sites), following :11797-11809:
    • primary span: the later use (or the return for return-point rejections): `view` may originate from `s2`, which no longer lives here (§21.1 Rule 6)
    • label: possible origin bound here → the call/borrow site that recorded the dep (record_call_view_origins keeps call_node; store it alongside deps);
    • label: `s2` dropped at end of this block → origin decl/scope-end span;
    • help (pick by context): copy the data out before the block ends (e.g. .to_owned()), or declare 's2' in the outer scope.
      Keep the existing may outlive its origin substring stable where feasible — err_view_two_origins.w/err_view_dangling.w match on it.
  4. Mask-width hardening: in compute_expr_view_origin_mask/record_call_view_origins/sig recording, clamp param index ≥31 to a conservative "any param" sentinel bit so origins are never silently dropped.
  5. Precision debt, explicitly deferred (file follow-ups, do not block): branch-divergent liveness and loop back-edge carry require fleshing out src/BorrowCfg.w (its header says exactly this); conservative behavior in the meantime must be rejection, not acceptance, per §22 ("If the compiler cannot prove…, it rejects"), but only once the basic check exists — do not regress currently-accepted safe code without the CFG precision to keep false positives near zero.
  6. No rt//Link.w/seed surface is touched — sema-only; normal with build/:fixpoint discipline applies.

Test plan

test/compile_errors/:

  • err_view_origin_dies_before_use.w — the verbatim §21.1 Rule 6 longest example; //! expect-check-fail: may originate from (three-location diagnostic).
  • err_view_origin_dies_no_return.w — origin death + later use entirely inside one function (no return involved).
  • err_view_origin_single_param_inner_scope.w — single-origin case (id_view(&s2)) with use after s2's block.
  • Keep passing: err_view_two_origins.w, err_view_dangling.w, err_return_local_ref_*.w, err_closure_capture_escape_summary.w.

test/spec/:

  • spec_ss21_1_rule6_origin_tracking.w (//! expect-stdout: ok) — positive precision cases: (a) both origins outlive all uses; (b) view's last use occurs before the origin dies (NLL: accepted); (c) param-origin view returned and used by caller while args live.

Diagnostic contract: at least one negative test asserts the multi-label output (origin label + drop label + help: remedy) via //! expect-stderr fragments, per test/diagnostic_schema.md.

Acceptance criteria

  • The §21.1 Rule 6 spec example is rejected at the print(view) use with origin, invalidation, and use locations plus an idiomatic remedy.
  • Views whose last use precedes origin death are accepted (no false rejection of the NLL-safe pattern).
  • All five pre-existing single-location "may outlive its origin" sites emit §22.3-conformant diagnostics.
  • >31-param functions produce conservative (not silently-missing) origin facts.
  • Existing view-origin fixtures keep passing; verdicts deterministic across builds.
  • with build && with build :fixpoint && with build :test pass; with build :test-green recorded.

Dependencies

Traceability

Original issue context (preserved): Spec reference — §21.1 Rule 6 (returned-view origin tracking), §22.3 Diagnostic Contract (new in v7.0), §3.4. Survey (2026-06-09) recorded "not implemented — ephemeral checking is type-level only (src/SemaCheck.w:12830-12861) plus task-specific escape checks; src/BorrowCfg.w:22-29 documents NLL coverage gaps (branch-divergent uses, loop-iteration carry)"; that survey predates commit 7caa03f4, whose shipped machinery is inventoried under Current state. Note: single-location "value escapes" errors do not satisfy §22.3 — rejection quality is the product.

Activity

  1. ehartford commented on Jun 12, 2026

    @ehartford
    ContributorAuthor

    Implemented in 90171ad. Returned-view provenance now poisons surviving bindings when a possible stack origin leaves scope and rejects the first later use with the §21.1 Rule 6 / §22.3 diagnostic labels for origin recording, origin scope end, and later use. Added positive and negative coverage, including a >31-parameter conservative-origin regression. Verification passed: with build, with build :fixpoint, with build :test, and 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