Skip to content

Implement implicit parameters and with name(expr): contexts (§7.3a, §9.1a) #398

Closed

Description

@ehartford

Implement implicit parameters and with name(expr): contexts (§7.3a, §9.1a)

Summary

Implicit parameters let cross-cutting values (device/stream/allocator handles, std.context.Context) flow to callees from an enclosing with name(expr): scope without positional plumbing. The core landed in commit a0a54f6 ("F6 — Automatic implicit parameter resolution") and is exercised by test/behavior/behav_implicit_params.w. This issue now tracks the verified remainder: the implicit+default declaration error, closure capture of contexts (currently a silent miscompile), implicit fill on method calls (currently an LLVM verify error), plus tests locking in the already-working duplicate-implicit-type error and auto-ref lookup.

Spec

§7.3a Form 3a: Implicit Context (docs/with-specification.md:2558-2607), §9.1a (docs/with-specification.md:3063-3105), std.context (lib/std/context.w).

fn sin(x: &Array, ctx: implicit &Context) -> Array: ...

with context(default_device()):
    let y = sin(x)                // ctx resolved implicitly
    let w = sin(x, ctx: other)    // explicit argument overrides implicit

Normative rules (§7.3a, §9.1a):

  • Resolution order: positional → named → implicit → defaults.
  • Implicit resolution is lexical and type-based; innermost with name(expr): wins; the identifier in with name(expr): is descriptive only.
  • Auto-ref applies during implicit lookup (Context and &Context compose).
  • A function may not declare two implicit parameters of the same type.
  • An implicit parameter may not also have a default value.
  • Closures capture the implicit contexts visible at their definition site, like ordinary lexical bindings.

Current state

Landed and verified working (commit a0a54f6):

  • Parser: implicit is a soft keyword on parameter types (src/Parser.w:6905-6906), recorded as FN_PARAM_FLAG_IMPLICIT (src/Ast.w:232, accessor fn_param_is_implicit :268).
  • with name(expr): parses as NK_WITH_IMPLICIT; Sema.check_with_implicit (src/SemaCheck.w:7434) pushes onto the implicit_binding_types/implicit_binding_syms stacks (src/Sema.w:460-461) and pops at scope exit — giving innermost-shadowing lexical scoping.
  • check_call fills unfilled implicit params from the stack, innermost-first, by types_compatible match, encoding the resolution as a negative marker 0 - bind_sym in the resolved-args table (named-arg path src/SemaCheck.w:7897-7917; plain-call path :7933-7990). Defaults are filled after implicits — resolution order matches the spec.
  • MIR: lower_call decodes the marker and pushes lower_var(impl_sym, 0, 0) (src/MirLower.w:5554-5561).
  • Missing-context diagnostic exists: "implicit parameter not provided; add a 'with' binding of the matching type" (src/SemaCheck.w:8145).
  • Duplicate-implicit-type error already exists: "function has multiple implicit parameters of the same type" (src/SemaDecl.w:1166-1173) — verified firing. Needs only a compile-error test.
  • Auto-ref during lookup works for plain calls — verified end-to-end: fn f(x: i32, ctx: implicit &Ctx) resolves from with c(Ctx {...}): and runs correctly. Needs tests, not implementation.
  • behav_implicit_params.w covers automatic resolution, explicit named override, and nested shadowing.

Verified gaps (the remainder):

  1. implicit+default not rejected. fn f(x: i32, ctx: implicit Ctx = Ctx { m: 1 }) passes check today (verified). §9.1a says this must be an error.
  2. Closure capture of contexts is a silent miscompile. Verified: with c(Ctx { m: 3 }): let cl = v => f(v); apply(cl) compiles and runs but produces a wrong value (the implicit arg reads garbage). Root cause: sema resolves the marker 0 - bind_sym against the lexically-live stack, but the closure's capture analysis only sees AST idents — the context binding never enters the closure's capture set (set_closure_capture_summary, src/Sema.w:2774), so lower_var(impl_sym, ...) inside the closure body resolves to a nonexistent local.
  3. Method calls with implicit params break codegen. Verified: fn S.scale(self: &S, ctx: implicit Ctx) + s.scale() under a context binding passes sema but fails with "LLVM verify error: Incorrect number of arguments passed to called function!" — the implicit-fill passes live only in check_call's function path; the method-call lowering never receives resolved args.

Implementation plan

  1. implicit+default declaration error — src/SemaDecl.w, in the same param loop that detects duplicate implicit types (:1157-1173): if fn_param_is_implicit(p_flags) != 0 and self.ast.get_fn_param_default(param_start, pi) != 0, emit error "implicit parameter may not have a default value" on the param node. (Overlap: Named-args rule gaps: implicit+default rejection, placeholder+named rejection (§9.1a, §9.4) #456 lists "implicit+default rejection" too — implement once, here, and note it in Named-args rule gaps: implicit+default rejection, placeholder+named rejection (§9.1a, §9.4) #456.)
  2. Method-call implicit fill — extend the implicit third-pass to the method-call check path (the call sites that compute sig_idx/param_offset for receiver calls; check_call's param_offset plumbing already models receivers, so the fix is to run the same fill + store_resolved_call_args for method calls, and to make the method-call MIR lowering honor has_resolved_call_args the way lower_call does at src/MirLower.w:5554). Until then sema accepts what codegen can't lower — a correctness hole that must not survive this issue.
  3. Closure capture of contexts — two coordinated changes:
    a. Sema: when a call inside a closure body resolves an implicit param to bind_sym, record bind_sym as a captured symbol of the enclosing closure (feed it into the same machinery that builds closure_capture_summary_*, src/Sema.w:515-517/2774), so escape checks and capture layout include it. Capture is by value at definition site (§7.3a: "just like ordinary lexical bindings"); since check_with_implicit pops the binding at scope exit, the captured copy is what survives.
    b. MirLower: when lowering the negative marker inside a closure, lower_var must find the binding through the closure environment (it will, once (a) puts the symbol in the capture set — verify lower_var's capture lookup path handles it).
    Edge cases: nested closures (capture propagates outward through each level); a closure defined outside any context that calls an implicit-param function must still get the "implicit parameter not provided" error at the closure's definition site, not garbage.
  4. Ephemeral interaction: std.context.Context is ephemeral (lib/std/context.w:31). A closure capturing an ephemeral context must obey the existing escaping-closure-captures-ephemeral rejection (err_escaping_bound_closure_captures_ref.w family). Add this to the capture summary's effect bits so an escaping closure capturing a Context is rejected, while a non-escaping one works.
  5. Tests (below), including locking in already-working behavior.

No rt/Link/seed surface is touched; normal with build + fixpoint applies.

Test plan

  • test/compile_errors/err_implicit_param_default.w — //! expect-check-fail: implicit parameter may not have a default value; fn with ctx: implicit Ctx = ....
  • test/compile_errors/err_implicit_param_duplicate_type.w — //! expect-check-fail: function has multiple implicit parameters of the same type; two implicit Ctx params (locks in existing SemaDecl.w:1172 behavior).
  • test/compile_errors/err_implicit_param_missing_context.w — call with no enclosing with name(expr): → "implicit parameter not provided; add a 'with' binding of the matching type".
  • test/behavior/behav_implicit_autoref.w — //! expect-stdout: ok: ctx: implicit &Ctx resolved from a by-value context binding; also a ctx: implicit Ctx param with field reads, both directions through one call chain.
  • test/behavior/behav_implicit_closure_capture.w — //! expect-stdout: ok: closure defined inside with c(Ctx { m: 3 }): calling an implicit-param fn; invoked (a) inside the scope, (b) passed to a function and invoked there; nested with-scopes shadowing across closure definition sites (definition-site capture, not call-site).
  • test/behavior/behav_implicit_method_call.w — //! expect-stdout: ok: fn S.scale(self: &S, ctx: implicit Ctx) called as s.scale() under a context binding (currently an LLVM verify error — this test is the regression gate for step 2).
  • test/spec/spec_ss07_3a_implicit_context.w — port the §7.3a examples: trace_id(ctx: implicit Context) with with active(default_context()): from lib/std/context.w; explicit-override; innermost-shadowing (extends behav_implicit_params.w with the std.context shape).
  • Negative: closure capturing ephemeral Context escaping its scope → reuse the escaping-closure diagnostic (file under test/compile_errors/).

Acceptance criteria

  • implicit + default value is a compile error with the exact message above.
  • Duplicate implicit types remain a compile error (test exists).
  • Method calls with implicit params work end-to-end (no LLVM verify error).
  • Closures capture visible contexts at definition site and produce correct values; no silent miscompile path remains.
  • Auto-ref lookup covered by passing tests in both Ctx/&Ctx directions.
  • Resolution order positional → named → implicit → defaults covered by a test mixing all four.
  • with build && with build :fixpoint && with build :test pass (and with build :test-green recorded).

Dependencies

Activity

  1. ehartford commented on Jun 10, 2026

    @ehartford
    ContributorAuthor

    Scope correction from the requirements campaign (2026-06-10): implicit parameters + with name(expr): resolution are substantially IMPLEMENTED (landed a0a54f6; behav_implicit_params.w, behav_std_context.w cover resolution order, shadowing, named override, type-driven lookup). Remaining under this issue: duplicate-implicit-type error, implicit+default error, auto-ref during lookup, closure-capture verification.

  2. ehartford commented on Jun 14, 2026

    @ehartford
    ContributorAuthor

    Implemented in 56d6fce. Completed implicit context resolution: implicit+default declarations now diagnose with the spec wording, method calls fill implicit/default args through the resolved-arg path, and closure environments include sema-resolved implicit captures so definition-site context capture no longer silently miscompiles. Added positive and negative coverage for duplicate implicit types, missing contexts, auto-ref lookup, closure capture, method calls, std.context §7.3a behavior, and escaping ephemeral Context capture. Verification passed: build, fixpoint, full :test, and explicit :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