From 8c1071fc6f7a08f6bb4257d8b80882c22a71e396 Mon Sep 17 00:00:00 2001 From: microproofs Date: Sat, 10 Oct 2026 11:41:55 +0700 Subject: [PATCH 01/24] fix(examples): move test-only imports into tests blocks nash build strips tests blocks before canonicalization, so module-level imports used only by tests were reported as unused. Signed-off-by: microproofs --- examples/order/src/Order.nash | 3 +-- examples/vesting/app/src/VestingTests.nash | 6 ++++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/examples/order/src/Order.nash b/examples/order/src/Order.nash index 2fc2d70d..0624b52c 100644 --- a/examples/order/src/Order.nash +++ b/examples/order/src/Order.nash @@ -1,8 +1,6 @@ module Order exposing (compare, invert, sort) import Prelude exposing (..) -import Literal -import Logic exposing (not) import Ord exposing (Ord) import Ordering exposing (type ordering(..)) @@ -29,6 +27,7 @@ insert x xs = tests import Prop exposing (int) import Test exposing (label) + import Logic exposing (not) test "lt is strict" = do assert (not (lt 1 1)) diff --git a/examples/vesting/app/src/VestingTests.nash b/examples/vesting/app/src/VestingTests.nash index 7ccb2301..57d518f0 100644 --- a/examples/vesting/app/src/VestingTests.nash +++ b/examples/vesting/app/src/VestingTests.nash @@ -2,8 +2,6 @@ module VestingTests exposing ( context ) import Builtin exposing (..) -import Vesting -import VestingParam constr : ( int, list Data ) -> Data @@ -61,6 +59,10 @@ context action time signers = tests + import Vesting + + import VestingParam + test "claim after deadline succeeds" = do Vesting.main (context 0 11 []) From da4a4d3a3e4466fcc6af3ab0e2e2fb34e5334b46 Mon Sep 17 00:00:00 2001 From: microproofs Date: Sat, 10 Oct 2026 15:02:22 +0700 Subject: [PATCH 02/24] fix(solve): unify type applications with transparent aliases by their bodies Signed-off-by: microproofs --- .../transparent-alias-application.md | 5 +++ ...fies_through_a_transparent_alias_body.snap | 29 +++++++++++++++++ crates/nash-codegen/src/build/tests.rs | 23 ++++++++++++++ crates/nash-solve/src/unify.rs | 31 ++++++++++++++++--- 4 files changed, 84 insertions(+), 4 deletions(-) create mode 100644 .sampo/changesets/transparent-alias-application.md create mode 100644 crates/nash-codegen/src/build/snapshots/nash_codegen__build__tests__higher_kinded_application_unifies_through_a_transparent_alias_body.snap diff --git a/.sampo/changesets/transparent-alias-application.md b/.sampo/changesets/transparent-alias-application.md new file mode 100644 index 00000000..2f0a59e7 --- /dev/null +++ b/.sampo/changesets/transparent-alias-application.md @@ -0,0 +1,5 @@ +--- +cargo/nash-solve: patch +--- + +Unify a type-variable application such as `'f 'a` with a transparent alias through the alias body when the alias's own parameters cannot supply the applied arguments. `type alias Xs = List Int` now works with `List.length`; record aliases remain nominal. diff --git a/crates/nash-codegen/src/build/snapshots/nash_codegen__build__tests__higher_kinded_application_unifies_through_a_transparent_alias_body.snap b/crates/nash-codegen/src/build/snapshots/nash_codegen__build__tests__higher_kinded_application_unifies_through_a_transparent_alias_body.snap new file mode 100644 index 00000000..96d9a6ac --- /dev/null +++ b/crates/nash-codegen/src/build/snapshots/nash_codegen__build__tests__higher_kinded_application_unifies_through_a_transparent_alias_body.snap @@ -0,0 +1,29 @@ +--- +source: crates/nash-codegen/src/build/tests.rs +description: "module Main exposing (..)\nimport Primitive exposing (..)\nimport Builtin exposing (..)\ntype alias ints = list int\ntrait Pass 'f where\n pass : 'f 'a -> 'f 'a\nimpl Pass list where\n pass x = x\nvalues : ints\nvalues = [1, 2]\nmain = pass values\n" +--- +--- unoptimized Core +let pass#2 : list 'erased -> list 'erased = \x#4 : list 'erased -> x#4 in +let fromInt#5 : int -> int = \value#6 : int -> value#6 in +let values#3 : list int = mkCons (fromInt#5 1) (mkCons (fromInt#5 2) (con (list integer) [])) in +let main#1 : list int = pass#2 values#3 in +main#1 +--- unoptimized UPLC +(program 1.1.0 + [(lam pass_2 + [(lam fromInt_5 + [(lam values_3 [(lam main_1 main_1) [pass_2 values_3]]) + [[(force (builtin mkCons)) [fromInt_5 (con integer 1)]] + [[(force (builtin mkCons)) [fromInt_5 (con integer 2)]] (con (list integer) [])]]]) + (lam value_6 value_6)]) + (lam x_4 x_4)]) +--- optimized Core +(con (list integer) [1, 2]) +--- optimized UPLC +(program 1.1.0 (con (list integer) [1, 2])) +--- result +(con (list integer) [1, 2]) +--- logs +[] +--- budget +cpu: 656824, memory: 3364 diff --git a/crates/nash-codegen/src/build/tests.rs b/crates/nash-codegen/src/build/tests.rs index ba18a36e..2c38a217 100644 --- a/crates/nash-codegen/src/build/tests.rs +++ b/crates/nash-codegen/src/build/tests.rs @@ -989,6 +989,29 @@ fn higher_kinded_default_method_accepts_a_nominal_record_alias() { assert!(!result.result.starts_with("error:"), "{}", result.result); } +#[test] +fn higher_kinded_application_unifies_through_a_transparent_alias_body() { + let result = core_eval( + "higher_kinded_application_unifies_through_a_transparent_alias_body", + indoc::indoc!( + r#" + module Main exposing (..) + import Primitive exposing (..) + import Builtin exposing (..) + type alias ints = list int + trait Pass 'f where + pass : 'f 'a -> 'f 'a + impl Pass list where + pass x = x + values : ints + values = [1, 2] + main = pass values + "# + ), + ); + assert!(!result.result.starts_with("error:"), "{}", result.result); +} + #[test] fn source_data_encoding_preserves_nominal_constructors() { let result = core_eval( diff --git a/crates/nash-solve/src/unify.rs b/crates/nash-solve/src/unify.rs index f637e6a1..6a52b50e 100644 --- a/crates/nash-solve/src/unify.rs +++ b/crates/nash-solve/src/unify.rs @@ -355,12 +355,21 @@ fn unify_partial_alias<'a>( unify_alias_args(uf, vars, args, other_args)?; merge(uf, context, other) } - Content::Structure(flat) => unify_application_alias(uf, vars, context, flat, alias), + Content::Structure(flat) => { + unify_application_alias(uf, vars, context, flat, alias, Side::First) + } Content::Error => merge(uf, context, Content::Error), _ => Err(()), } } +/// Which side of the unification context holds the alias. +#[derive(Clone, Copy)] +enum Side { + First, + Second, +} + /// Decompose the supplied suffix while keeping the original closed alias body. fn unify_application_alias<'a>( uf: &mut UnionFind<'a>, @@ -368,6 +377,7 @@ fn unify_application_alias<'a>( context: &Context<'a>, flat: FlatType<'a>, alias: Content<'a>, + side: Side, ) -> UResult { let FlatType::AppV1(head, applied) = type_::normalize_application(uf, flat) else { return Err(()); @@ -390,7 +400,19 @@ fn unify_application_alias<'a>( _ => unreachable!(), }; if applied.is_empty() || applied.len() > args.len() { - return Err(()); + // The application cannot split the alias's own parameters. A transparent + // alias still unifies through its body; record aliases stay nominal. + return match &alias { + Content::Alias { real, body, .. } + if !matches!(body.value, nash_ast::Type::Record { .. }) => + { + match side { + Side::First => sub_unify(uf, vars, *real, context.second), + Side::Second => sub_unify(uf, vars, context.first, *real), + } + } + _ => Err(()), + }; } let split = args.len() - applied.len(); let partial = fresh( @@ -486,6 +508,7 @@ fn unify_alias<'a>( body, real: real_var, }, + Side::First, ), Content::Structure(_) if nominal => Err(()), Content::Structure(_) => sub_unify(uf, vars, real_var, context.second), @@ -528,11 +551,11 @@ fn unify_structure<'a>( Content::RigidVar(_) => Err(()), alias @ Content::PartialAlias { .. } => { - unify_application_alias(uf, vars, context, flat_type, alias) + unify_application_alias(uf, vars, context, flat_type, alias, Side::Second) } alias @ Content::Alias { .. } => { if matches!(flat_type, FlatType::AppV1(..)) { - unify_application_alias(uf, vars, context, flat_type, alias) + unify_application_alias(uf, vars, context, flat_type, alias, Side::Second) } else { let Content::Alias { real, body, .. } = alias else { unreachable!() From cc95d39997bc0021aa2796d324ba70b9706b0e32 Mon Sep 17 00:00:00 2001 From: microproofs Date: Sat, 10 Oct 2026 16:30:41 +0700 Subject: [PATCH 03/24] fix(solve): keep a failed annotated body's annotation for its callers Signed-off-by: microproofs --- .sampo/changesets/annotated-body-recovery.md | 5 ++ crates/nash-solve/src/solve/infer.rs | 16 +++- crates/nash-solve/tests/inference.rs | 82 +++++++++++++++++++ ...lure_reports_caller_argument_mismatch.snap | 29 +++++++ ...aller_constraints_from_the_annotation.snap | 18 ++++ ...lure_reports_caller_argument_mismatch.snap | 29 +++++++ ...y_failure_reports_caller_missing_impl.snap | 34 ++++++++ ...lure_reports_caller_argument_mismatch.snap | 29 +++++++ 8 files changed, 238 insertions(+), 4 deletions(-) create mode 100644 .sampo/changesets/annotated-body-recovery.md create mode 100644 crates/nash-solve/tests/snapshots/inference__recovery_annotated_body_failure_reports_caller_argument_mismatch.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__recovery_annotated_body_failure_resolves_caller_constraints_from_the_annotation.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__recovery_annotated_group_body_failure_reports_caller_argument_mismatch.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__recovery_constrained_annotated_body_failure_reports_caller_missing_impl.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__recovery_local_annotated_body_failure_reports_caller_argument_mismatch.snap diff --git a/.sampo/changesets/annotated-body-recovery.md b/.sampo/changesets/annotated-body-recovery.md new file mode 100644 index 00000000..f9f60655 --- /dev/null +++ b/.sampo/changesets/annotated-body-recovery.md @@ -0,0 +1,5 @@ +--- +cargo/nash-solve: patch +--- + +Keep checking callers of an annotated definition against its annotation when its body has a type error. Callers now report their own mismatches and no longer receive spurious ambiguity errors. An annotation whose type variables escape still blocks its uses. diff --git a/crates/nash-solve/src/solve/infer.rs b/crates/nash-solve/src/solve/infer.rs index 8499b15c..3fc6277a 100644 --- a/crates/nash-solve/src/solve/infer.rs +++ b/crates/nash-solve/src/solve/infer.rs @@ -482,6 +482,7 @@ impl<'a> Solver<'a, '_> { ) -> ScopeResult<'a> { let young = rank + 1; state = self.generalize_scope(uf, young, state); + let escapes_before = state.errors.len(); for rigid in rigids { if uf.get(*rigid).rank != NO_RANK && !crate::recovery::is_poisoned(uf, [*rigid]) { let owner = binder @@ -494,6 +495,10 @@ impl<'a> Solver<'a, '_> { }); } } + // A body error leaves a valid annotation usable by callers, as in Elm. + // Only an annotation that lets its own variables escape blocks its uses. + let annotated = !definitions.is_empty() && definitions.iter().all(|d| d.context.is_some()); + let annotation_failed = state.errors.len() > escapes_before; if let Some(binder) = binder { let depth = self.enter_givens(uf, rank, given, Some(binder)); loop { @@ -528,9 +533,12 @@ impl<'a> Solver<'a, '_> { } else { &[] }; - if state.errors.len() > errors_before - && let Some(binder) = binder - { + let failed = if annotated { + annotation_failed + } else { + state.errors.len() > errors_before + }; + if failed && let Some(binder) = binder { self.fail_definition(uf, binder.node()); } self.record_definitions(uf, rank, definitions, declared, context, binder); @@ -608,7 +616,7 @@ impl<'a> Solver<'a, '_> { binder, definition.context.is_some(), ); - if state.errors.len() > errors_before { + if state.errors.len() > errors_before && definition.context.is_none() { self.fail_definition(uf, definition.site.node()); } self.givens.truncate(depth); diff --git a/crates/nash-solve/tests/inference.rs b/crates/nash-solve/tests/inference.rs index eba0931f..c0622b91 100644 --- a/crates/nash-solve/tests/inference.rs +++ b/crates/nash-solve/tests/inference.rs @@ -135,6 +135,88 @@ fn recovery_reports_an_independent_escaping_annotation_and_blocks_its_uses() { .expect_err("the local annotation is invalid independently of mismatch"); } +#[test] +fn recovery_annotated_body_failure_resolves_caller_constraints_from_the_annotation() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + trait Round 'a where + create : () -> 'a + impl Round () where + create x = x + helper : () -> () + helper x = \y -> y + caller : () + caller = helper (create ()) + "# + ); +} + +#[test] +fn recovery_annotated_body_failure_reports_caller_argument_mismatch() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (..) + helper : () -> () + helper x = \y -> y + caller : () + caller = helper Primitive.True + "# + ); +} + +#[test] +fn recovery_local_annotated_body_failure_reports_caller_argument_mismatch() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (..) + caller : () + caller = + let + inner : () -> () + inner x = \y -> y + in + inner Primitive.True + "# + ); +} + +#[test] +fn recovery_annotated_group_body_failure_reports_caller_argument_mismatch() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (..) + isEven : () -> () + isEven x = isOdd x + isOdd : () -> () + isOdd x = if Primitive.True then \y -> y else isEven x + caller : () + caller = isEven Primitive.True + "# + ); +} + +#[test] +fn recovery_constrained_annotated_body_failure_reports_caller_missing_impl() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (..) + trait Same 'a where + same : 'a -> 'a -> () + impl Same () where + same x y = x + check : Same 'a => 'a -> () + check x = \y -> y + caller : () + caller = check Primitive.True + "# + ); +} + #[test] fn recovery_blocks_repeated_and_recursive_uses_but_keeps_sibling_errors() { for broken in [ diff --git a/crates/nash-solve/tests/snapshots/inference__recovery_annotated_body_failure_reports_caller_argument_mismatch.snap b/crates/nash-solve/tests/snapshots/inference__recovery_annotated_body_failure_reports_caller_argument_mismatch.snap new file mode 100644 index 00000000..7b9a6a4b --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__recovery_annotated_body_failure_reports_caller_argument_mismatch.snap @@ -0,0 +1,29 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (..)\nhelper : () -> ()\nhelper x = \\y -> y\ncaller : ()\ncaller = helper Primitive.True\n" +info: diagnostic +--- +nash::type::mismatch + + × Type mismatch: expected `unit`, found `bool`. + ╭─[Main.nash:6:17] + 5 │ caller : () + 6 │ caller = helper Primitive.True + · ───────┬────── + · ╰── argument 1 of `helper` + ╰──── + + +nash::type::mismatch + + × Type mismatch: expected `unit`, found `'a -> 'a`. + ╭─[Main.nash:4:12] + 2 │ import Primitive exposing (..) + 3 │ helper : () -> () + · ────┬─── + · ╰── declared type + 4 │ helper x = \y -> y + · ───┬─── + · ╰── body of `helper` + 5 │ caller : () + ╰──── diff --git a/crates/nash-solve/tests/snapshots/inference__recovery_annotated_body_failure_resolves_caller_constraints_from_the_annotation.snap b/crates/nash-solve/tests/snapshots/inference__recovery_annotated_body_failure_resolves_caller_constraints_from_the_annotation.snap new file mode 100644 index 00000000..c08133d6 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__recovery_annotated_body_failure_resolves_caller_constraints_from_the_annotation.snap @@ -0,0 +1,18 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\ntrait Round 'a where\n create : () -> 'a\nimpl Round () where\n create x = x\nhelper : () -> ()\nhelper x = \\y -> y\ncaller : ()\ncaller = helper (create ())\n" +info: diagnostic +--- +nash::type::mismatch + + × Type mismatch: expected `unit`, found `'a -> 'a`. + ╭─[Main.nash:7:12] + 5 │ create x = x + 6 │ helper : () -> () + · ────┬─── + · ╰── declared type + 7 │ helper x = \y -> y + · ───┬─── + · ╰── body of `helper` + 8 │ caller : () + ╰──── diff --git a/crates/nash-solve/tests/snapshots/inference__recovery_annotated_group_body_failure_reports_caller_argument_mismatch.snap b/crates/nash-solve/tests/snapshots/inference__recovery_annotated_group_body_failure_reports_caller_argument_mismatch.snap new file mode 100644 index 00000000..9990c3ea --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__recovery_annotated_group_body_failure_reports_caller_argument_mismatch.snap @@ -0,0 +1,29 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (..)\nisEven : () -> ()\nisEven x = isOdd x\nisOdd : () -> ()\nisOdd x = if Primitive.True then \\y -> y else isEven x\ncaller : ()\ncaller = isEven Primitive.True\n" +info: diagnostic +--- +nash::type::mismatch + + × Type mismatch: expected `unit`, found `bool`. + ╭─[Main.nash:8:17] + 7 │ caller : () + 8 │ caller = isEven Primitive.True + · ───────┬────── + · ╰── argument 1 of `isEven` + ╰──── + + +nash::type::mismatch + + × Type mismatch: expected `unit`, found `'a -> 'a`. + ╭─[Main.nash:6:34] + 4 │ isEven x = isOdd x + 5 │ isOdd : () -> () + · ────┬─── + · ╰── declared type + 6 │ isOdd x = if Primitive.True then \y -> y else isEven x + · ───┬─── + · ╰── if branch 1 + 7 │ caller : () + ╰──── diff --git a/crates/nash-solve/tests/snapshots/inference__recovery_constrained_annotated_body_failure_reports_caller_missing_impl.snap b/crates/nash-solve/tests/snapshots/inference__recovery_constrained_annotated_body_failure_reports_caller_missing_impl.snap new file mode 100644 index 00000000..29b9efb5 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__recovery_constrained_annotated_body_failure_reports_caller_missing_impl.snap @@ -0,0 +1,34 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (..)\ntrait Same 'a where\n same : 'a -> 'a -> ()\nimpl Same () where\n same x y = x\ncheck : Same 'a => 'a -> ()\ncheck x = \\y -> y\ncaller : ()\ncaller = check Primitive.True\n" +info: diagnostic +--- +nash::type::missing_impl + + × No impl for `Same bool`. + ╭─[Main.nash:10:10] + 9 │ caller : () + 10 │ caller = check Primitive.True + · ──┬── + · ╰── required by `check` + ╰──── + help: Available impl heads: + + unit + + Import or define an impl for `Same bool`. + + +nash::type::mismatch + + × Type mismatch: expected `unit`, found `'a -> 'a`. + ╭─[Main.nash:8:11] + 6 │ same x y = x + 7 │ check : Same 'a => 'a -> () + · ────┬─── + · ╰── declared type + 8 │ check x = \y -> y + · ───┬─── + · ╰── body of `check` + 9 │ caller : () + ╰──── diff --git a/crates/nash-solve/tests/snapshots/inference__recovery_local_annotated_body_failure_reports_caller_argument_mismatch.snap b/crates/nash-solve/tests/snapshots/inference__recovery_local_annotated_body_failure_reports_caller_argument_mismatch.snap new file mode 100644 index 00000000..02886aec --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__recovery_local_annotated_body_failure_reports_caller_argument_mismatch.snap @@ -0,0 +1,29 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (..)\ncaller : ()\ncaller =\n let\n inner : () -> ()\n inner x = \\y -> y\n in\n inner Primitive.True\n" +info: diagnostic +--- +nash::type::mismatch + + × Type mismatch: expected `unit`, found `bool`. + ╭─[Main.nash:9:11] + 8 │ in + 9 │ inner Primitive.True + · ───────┬────── + · ╰── argument 1 of `inner` + ╰──── + + +nash::type::mismatch + + × Type mismatch: expected `unit`, found `'a -> 'a`. + ╭─[Main.nash:7:19] + 5 │ let + 6 │ inner : () -> () + · ────┬─── + · ╰── declared type + 7 │ inner x = \y -> y + · ───┬─── + · ╰── body of `inner` + 8 │ in + ╰──── From aae9116859153e0339029c7169e7dd1f7a6b4443 Mon Sep 17 00:00:00 2001 From: microproofs Date: Sat, 10 Oct 2026 17:22:30 +0700 Subject: [PATCH 04/24] fix(solve): do not report types stranded by a failed call as ambiguous Signed-off-by: microproofs --- .../changesets/stranded-call-constraints.md | 5 ++ crates/nash-solve/src/recovery.rs | 21 ++++++ crates/nash-solve/src/solve.rs | 18 ++++- crates/nash-solve/tests/inference.rs | 75 +++++++++++++++++++ ...ake_its_argument_constraint_ambiguous.snap | 18 +++++ ...d_call_keeps_an_independent_ambiguity.snap | 32 ++++++++ ...call_leaves_a_shared_argument_unknown.snap | 18 +++++ 7 files changed, 186 insertions(+), 1 deletion(-) create mode 100644 .sampo/changesets/stranded-call-constraints.md create mode 100644 crates/nash-solve/tests/snapshots/inference__recovery_failed_call_does_not_make_its_argument_constraint_ambiguous.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__recovery_failed_call_keeps_an_independent_ambiguity.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__recovery_failed_call_leaves_a_shared_argument_unknown.snap diff --git a/.sampo/changesets/stranded-call-constraints.md b/.sampo/changesets/stranded-call-constraints.md new file mode 100644 index 00000000..8c69eb80 --- /dev/null +++ b/.sampo/changesets/stranded-call-constraints.md @@ -0,0 +1,5 @@ +--- +cargo/nash-solve: patch +--- + +Stop reporting ambiguous or unresolved trait constraints on values passed to a definition whose body failed to type check. Their types are unknown because of that failure; the body error is still reported, and fixing it reveals any remaining ambiguity. diff --git a/crates/nash-solve/src/recovery.rs b/crates/nash-solve/src/recovery.rs index 3d88da3d..7da93585 100644 --- a/crates/nash-solve/src/recovery.rs +++ b/crates/nash-solve/src/recovery.rs @@ -12,6 +12,10 @@ pub(crate) struct Dependencies { edges: BTreeSet<(Variable, Variable)>, computations: BTreeSet<(Variable, Variable)>, field_receivers: BTreeSet<(Variable, Variable)>, + /// Variables whose only type information came from a structure that merged + /// into an existing `Error`, such as the argument of a call to a failed + /// definition. They are unknown because of that failure, not ambiguous. + stranded: BTreeSet, } impl Dependencies { @@ -71,6 +75,23 @@ impl Dependencies { self.field_receivers.insert((output, receiver)); } + /// Remember variables the roots contained before they merged into `Error`. + pub(crate) fn strand( + &mut self, + uf: &mut UnionFind<'_>, + roots: impl IntoIterator, + ) { + let lost = self.detached(uf, roots); + self.stranded.extend(lost); + } + + pub(crate) fn is_stranded(&self, uf: &mut UnionFind<'_>, variable: Variable) -> bool { + let variable = uf.find(variable); + self.stranded + .iter() + .any(|stranded| uf.find(*stranded) == variable) + } + pub(crate) fn invalidate( &self, uf: &mut UnionFind<'_>, diff --git a/crates/nash-solve/src/solve.rs b/crates/nash-solve/src/solve.rs index f2bc5c96..4aa4f3ca 100644 --- a/crates/nash-solve/src/solve.rs +++ b/crates/nash-solve/src/solve.rs @@ -220,6 +220,10 @@ impl<'a> Solver<'a, '_> { self.has_poison = true; crate::recovery::poison_roots(uf, detached); self.propagate_poison(uf); + } else if matches!(uf.get(actual).content, Content::Error) { + // A successful merge into an existing Error drops the other side's + // structure, leaving its children without any type information. + self.dependencies.strand(uf, [actual, expected]); } answer } @@ -725,6 +729,7 @@ impl<'a> Solver<'a, '_> { | crate::preds::Solution::Apply { subs }, ) => pending.extend(subs), Some(_) => {} + None if self.predicate_stranded(uf, id) => {} None => { let args = self.bump.alloc_slice_fill_iter( pred.body @@ -754,6 +759,14 @@ impl<'a> Solver<'a, '_> { errors } + /// A constraint whose open variables lost their type information to a + /// failed call is unknown because of that failure, not unresolved. + fn predicate_stranded(&self, uf: &mut UnionFind<'a>, id: type_::PredId) -> bool { + Self::type_variables(uf, self.predicates.get(id).body.roots().collect()) + .into_iter() + .any(|variable| self.dependencies.is_stranded(uf, variable)) + } + fn finish( &mut self, uf: &mut UnionFind<'a>, @@ -2203,7 +2216,10 @@ impl<'a> Solver<'a, '_> { let variables = Self::type_variables(uf, self.predicates.get(*id).body.roots().collect()); for var in variables { - if uf.get(var).rank == NO_RANK && !reachable.contains(&var) { + if uf.get(var).rank == NO_RANK + && !reachable.contains(&var) + && !self.dependencies.is_stranded(uf, var) + { ambiguous.entry(var).or_default().push(*id); } } diff --git a/crates/nash-solve/tests/inference.rs b/crates/nash-solve/tests/inference.rs index c0622b91..4c372d6a 100644 --- a/crates/nash-solve/tests/inference.rs +++ b/crates/nash-solve/tests/inference.rs @@ -217,6 +217,81 @@ fn recovery_constrained_annotated_body_failure_reports_caller_missing_impl() { ); } +#[test] +fn recovery_failed_call_does_not_make_its_argument_constraint_ambiguous() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (..) + trait Round 'a where + create : () -> 'a + broken x = + let + bad : () + bad = \y -> y + in + x + caller : () + caller = broken (create ()) + "# + ); +} + +#[test] +fn recovery_failed_call_keeps_an_independent_ambiguity() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (..) + trait Round 'a where + create : () -> 'a + discard : 'a -> () + broken x = + let + bad : () + bad = \y -> y + in + x + caller : () + caller = + let + ignored : () + ignored = broken () + in + discard (create ()) + "# + ); +} + +#[test] +fn recovery_failed_call_leaves_a_shared_argument_unknown() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (..) + trait Round 'a where + create : () -> 'a + discard : 'a -> () + broken x = + let + bad : () + bad = \y -> y + in + x + caller : () + caller = + (\shared -> + let + ignored : () + ignored = broken shared + in + discard shared + ) + (create ()) + "# + ); +} + #[test] fn recovery_blocks_repeated_and_recursive_uses_but_keeps_sibling_errors() { for broken in [ diff --git a/crates/nash-solve/tests/snapshots/inference__recovery_failed_call_does_not_make_its_argument_constraint_ambiguous.snap b/crates/nash-solve/tests/snapshots/inference__recovery_failed_call_does_not_make_its_argument_constraint_ambiguous.snap new file mode 100644 index 00000000..7f255646 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__recovery_failed_call_does_not_make_its_argument_constraint_ambiguous.snap @@ -0,0 +1,18 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (..)\ntrait Round 'a where\n create : () -> 'a\nbroken x =\n let\n bad : ()\n bad = \\y -> y\n in\n x\ncaller : ()\ncaller = broken (create ())\n" +info: diagnostic +--- +nash::type::mismatch + + × Type mismatch: expected `unit`, found `'a -> 'a`. + ╭─[Main.nash:8:15] + 6 │ let + 7 │ bad : () + · ─┬ + · ╰── declared type + 8 │ bad = \y -> y + · ───┬─── + · ╰── body of `bad` + 9 │ in + ╰──── diff --git a/crates/nash-solve/tests/snapshots/inference__recovery_failed_call_keeps_an_independent_ambiguity.snap b/crates/nash-solve/tests/snapshots/inference__recovery_failed_call_keeps_an_independent_ambiguity.snap new file mode 100644 index 00000000..482bcbf7 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__recovery_failed_call_keeps_an_independent_ambiguity.snap @@ -0,0 +1,32 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (..)\ntrait Round 'a where\n create : () -> 'a\n discard : 'a -> ()\nbroken x =\n let\n bad : ()\n bad = \\y -> y\n in\n x\ncaller : ()\ncaller =\n let\n ignored : ()\n ignored = broken ()\n in\n discard (create ())\n" +info: diagnostic +--- +nash::type::ambiguous_type + + × Cannot determine type `'a` in `caller`. + ╭─[Main.nash:13:1] + 12 │ caller : () + 13 │ caller = + · ────── + 14 │ let + ╰──── + help: Required constraints: Round 'a + + Add a type annotation that determines this variable. + + +nash::type::mismatch + + × Type mismatch: expected `unit`, found `'a -> 'a`. + ╭─[Main.nash:9:15] + 7 │ let + 8 │ bad : () + · ─┬ + · ╰── declared type + 9 │ bad = \y -> y + · ───┬─── + · ╰── body of `bad` + 10 │ in + ╰──── diff --git a/crates/nash-solve/tests/snapshots/inference__recovery_failed_call_leaves_a_shared_argument_unknown.snap b/crates/nash-solve/tests/snapshots/inference__recovery_failed_call_leaves_a_shared_argument_unknown.snap new file mode 100644 index 00000000..8221e7c6 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__recovery_failed_call_leaves_a_shared_argument_unknown.snap @@ -0,0 +1,18 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (..)\ntrait Round 'a where\n create : () -> 'a\n discard : 'a -> ()\nbroken x =\n let\n bad : ()\n bad = \\y -> y\n in\n x\ncaller : ()\ncaller =\n (\\shared ->\n let\n ignored : ()\n ignored = broken shared\n in\n discard shared\n )\n (create ())\n" +info: diagnostic +--- +nash::type::mismatch + + × Type mismatch: expected `unit`, found `'a -> 'a`. + ╭─[Main.nash:9:15] + 7 │ let + 8 │ bad : () + · ─┬ + · ╰── declared type + 9 │ bad = \y -> y + · ───┬─── + · ╰── body of `bad` + 10 │ in + ╰──── From a73ee39bb350cb95049e2665734a8f592a6ecf9a Mon Sep 17 00:00:00 2001 From: microproofs Date: Fri, 9 Oct 2026 00:50:06 +0700 Subject: [PATCH 05/24] build: optimize the compiler crates in the dev profile Signed-off-by: microproofs --- Cargo.toml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 74c3e2e3..4508896e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,9 +39,19 @@ xz2 = "0.1" # Keep zip 2 defaults except unused Bzip2 support. zip = { version = "2", default-features = false, features = ["aes-crypto", "deflate64", "deflate", "lzma", "time", "zstd", "xz"] } -# Optimize insta/similar in dev for faster diffs +# Optimize the compiler crates and insta/similar in dev for faster tests and diffs [profile.dev.package] +bumpalo.opt-level = 3 insta.opt-level = 3 +nash-ast.opt-level = 3 +nash-can.opt-level = 3 +nash-codegen.opt-level = 3 +nash-constrain.opt-level = 3 +nash-ir.opt-level = 3 +nash-nitpick.opt-level = 3 +nash-parse.opt-level = 3 +nash-plutus.opt-level = 3 +nash-solve.opt-level = 3 similar.opt-level = 3 # The profile that 'dist' will build with From 438d5070993867b6b47643b2a45b2d557aecd91c Mon Sep 17 00:00:00 2001 From: microproofs Date: Fri, 9 Oct 2026 16:36:57 +0700 Subject: [PATCH 06/24] refactor(traits): keep the trait search limits in one place Signed-off-by: microproofs --- .sampo/changesets/shared-trait-search-limits.md | 5 +++++ crates/nash-ast/src/head.rs | 4 ++++ crates/nash-can/src/entailment.rs | 5 +---- crates/nash-can/src/impls.rs | 5 +++-- crates/nash-can/tests/impls.rs | 13 +++++++------ crates/nash-codegen/src/evidence.rs | 12 +++++------- crates/nash-solve/src/evidence.rs | 5 +++-- crates/nash-solve/src/resolve.rs | 9 ++++++--- crates/nash-solve/src/solve.rs | 5 +++-- 9 files changed, 37 insertions(+), 26 deletions(-) create mode 100644 .sampo/changesets/shared-trait-search-limits.md diff --git a/.sampo/changesets/shared-trait-search-limits.md b/.sampo/changesets/shared-trait-search-limits.md new file mode 100644 index 00000000..eee57c09 --- /dev/null +++ b/.sampo/changesets/shared-trait-search-limits.md @@ -0,0 +1,5 @@ +--- +cargo/nash-ast: minor +--- + +Add `nash_ast::head::WORK_LIMIT` and `nash_ast::head::DEPTH_LIMIT`, the one definition of the trait search limits. Canonicalization, inference and code generation now use them. diff --git a/crates/nash-ast/src/head.rs b/crates/nash-ast/src/head.rs index fff34dc6..a6feeccd 100644 --- a/crates/nash-ast/src/head.rs +++ b/crates/nash-ast/src/head.rs @@ -9,6 +9,10 @@ use nash_region::Located; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Limit; +// Impl contexts need not decrease, so every trait search has a budget. +pub const WORK_LIMIT: usize = 16_384; +pub const DEPTH_LIMIT: usize = 128; + pub enum Match { Yes(T), No, diff --git a/crates/nash-can/src/entailment.rs b/crates/nash-can/src/entailment.rs index 0eb1a414..ad107d97 100644 --- a/crates/nash-can/src/entailment.rs +++ b/crates/nash-can/src/entailment.rs @@ -2,16 +2,13 @@ use std::collections::BTreeMap; use bumpalo::Bump; +use nash_ast::head::{DEPTH_LIMIT, WORK_LIMIT}; use nash_ast::{Pred, QualifiedName, Type}; use nash_region::Located; use crate::Error; use crate::environment::{ImplInfo, Tables}; -// Flexible contexts need not decrease. Bound both resolution and structural work. -const WORK_LIMIT: usize = 16_384; -const DEPTH_LIMIT: usize = 128; - #[derive(Clone, Copy, Debug)] pub enum Failure { Missing, diff --git a/crates/nash-can/src/impls.rs b/crates/nash-can/src/impls.rs index 212a626c..f1a3bd28 100644 --- a/crates/nash-can/src/impls.rs +++ b/crates/nash-can/src/impls.rs @@ -2,6 +2,7 @@ use crate::environment::{Env, TraitInfo, dups}; use crate::error::BadHead; use crate::{Error, kinds, module, types, warning::Warning}; use bumpalo::Bump; +use nash_ast::head::WORK_LIMIT; use nash_ast::{Annotation, Head, Impl, ImplKey, Pred, QualifiedName, Type}; use nash_region::Located; use nash_source::Type as SourceType; @@ -111,7 +112,7 @@ fn insert_impl<'a>( trait_: impl_.trait_, heads: bump.alloc_slice_fill_iter(impl_.heads.iter().map(|h| h.value)), }; - let mut remaining = 16_384; + let mut remaining = WORK_LIMIT; for (candidate, first) in table .iter() .filter(|(candidate, _)| candidate.trait_ == key.trait_) @@ -287,7 +288,7 @@ pub(crate) fn canonicalize<'a>( &[left.value], &[right.value], &|head| head_repr(kind_env, head), - &mut 16_384, + &mut { WORK_LIMIT }, ) .map_err(|_| { vec![Error::ImplPatternLimit { diff --git a/crates/nash-can/tests/impls.rs b/crates/nash-can/tests/impls.rs index be4aa1ab..c8fffd7c 100644 --- a/crates/nash-can/tests/impls.rs +++ b/crates/nash-can/tests/impls.rs @@ -3,6 +3,7 @@ use snapshot_support::SnapshotInputs; use bumpalo::Bump; use indoc::indoc; +use nash_ast::head::WORK_LIMIT; #[test] fn inline_impl_bounds_are_retained_for_superclasses() { @@ -48,18 +49,18 @@ fn recursive_overlap_ignores_representation_contexts() { nash_ast::head::overlaps(keys[a].heads, keys[b].heads, &|_| None, budget) }; assert!( - overlap(0, 1, &mut 16_384).unwrap(), + overlap(0, 1, &mut { WORK_LIMIT }).unwrap(), "representation contexts do not make equal heads disjoint" ); - assert!(overlap(0, 2, &mut 16_384).unwrap()); - assert!(overlap(1, 2, &mut 16_384).unwrap()); + assert!(overlap(0, 2, &mut { WORK_LIMIT }).unwrap()); + assert!(overlap(1, 2, &mut { WORK_LIMIT }).unwrap()); assert!( - overlap(0, 0, &mut 16_384).unwrap(), + overlap(0, 0, &mut { WORK_LIMIT }).unwrap(), "fresh binders preserve overlap" ); - let mut budget = 16_384; + let mut budget = WORK_LIMIT; assert!(overlap(0, 0, &mut budget).unwrap()); - let mut exact_budget = 16_384 - budget; + let mut exact_budget = WORK_LIMIT - budget; assert!(exact_budget > 0); assert!(overlap(0, 0, &mut exact_budget).unwrap()); assert_eq!(exact_budget, 0); diff --git a/crates/nash-codegen/src/evidence.rs b/crates/nash-codegen/src/evidence.rs index bc8c4500..60582d65 100644 --- a/crates/nash-codegen/src/evidence.rs +++ b/crates/nash-codegen/src/evidence.rs @@ -5,6 +5,7 @@ //! demands are a separate part of specialization identity. use std::collections::HashMap; +use nash_ast::head::{DEPTH_LIMIT, WORK_LIMIT}; use nash_ast::{AliasType, Evidence, Head, ImplRef, NodeId, Pred, QualifiedName, Type, primitives}; use nash_can::environment::Tables; use nash_plutus::arena::Arena; @@ -12,9 +13,6 @@ use nash_region::Located; use crate::ty_of::Substitution; -const MAX_DEPTH: usize = 128; -const MAX_WORK: usize = 16_384; - #[derive(Debug, PartialEq, Eq, thiserror::Error)] pub enum Error<'a> { #[error("no evidence supplied for binder {0:?}")] @@ -66,7 +64,7 @@ pub fn ground<'a>( Grounder { arena, tables, - remaining: MAX_WORK, + remaining: WORK_LIMIT, } .one(evidence, subst, givens, 0) } @@ -81,7 +79,7 @@ pub fn ground_arguments<'a>( Grounder { arena, tables, - remaining: MAX_WORK, + remaining: WORK_LIMIT, } .arguments(evidence, subst, givens, 0) } @@ -119,12 +117,12 @@ pub fn executable_identity<'a>( } }) } - let mut remaining = MAX_WORK; + let mut remaining = WORK_LIMIT; visit(evidence, &mut remaining, 0) } fn step<'a>(remaining: &mut usize, depth: usize) -> Result<(), Error<'a>> { - if depth > MAX_DEPTH || *remaining == 0 { + if depth > DEPTH_LIMIT || *remaining == 0 { return Err(Error::Limit); } *remaining -= 1; diff --git a/crates/nash-solve/src/evidence.rs b/crates/nash-solve/src/evidence.rs index 57834519..308036a9 100644 --- a/crates/nash-solve/src/evidence.rs +++ b/crates/nash-solve/src/evidence.rs @@ -1,5 +1,6 @@ //! Impl evidence for ground canonical predicates, outside the inference loop. use bumpalo::Bump; +use nash_ast::head::{DEPTH_LIMIT, WORK_LIMIT}; use nash_ast::{Evidence, ImplRef, Pred, QualifiedName, Type}; use nash_can::environment::Tables; use nash_region::Located; @@ -29,7 +30,7 @@ pub fn resolve<'a>( Resolver { bump, tables, - remaining: 16_384, + remaining: WORK_LIMIT, } .resolve(pred, 0) } @@ -127,7 +128,7 @@ impl<'a> Resolver<'_, 'a> { } fn step(&mut self, depth: usize) -> Result<(), Failure> { - if depth >= 128 || self.remaining == 0 { + if depth >= DEPTH_LIMIT || self.remaining == 0 { return Err(Failure::Limit); } self.remaining -= 1; diff --git a/crates/nash-solve/src/resolve.rs b/crates/nash-solve/src/resolve.rs index 8233775a..60677041 100644 --- a/crates/nash-solve/src/resolve.rs +++ b/crates/nash-solve/src/resolve.rs @@ -1,5 +1,6 @@ //! Coherent selection from known heads and read-only probes for relational //! equalities. The solver commits only a unique candidate's equalities. +use nash_ast::head::WORK_LIMIT; use nash_ast::{HeadCon, ImplKey, QualifiedName}; use nash_can::environment::{ImplInfo, Tables}; use nash_constrain::{Content, FlatType, UnionFind, Variable}; @@ -279,7 +280,9 @@ pub(crate) fn select<'a>( ) -> Selection<'a> { use nash_ast::head::{Match, matches}; if args.len() >= 2 { - match given_candidates(tables, uf, trait_, args, givens, allocated, &mut 16_384) { + match given_candidates(tables, uf, trait_, args, givens, allocated, &mut { + WORK_LIMIT + }) { None => return Selection::Limit, Some(candidates) if !candidates.is_empty() => return Selection::Deferred, Some(_) => {} @@ -297,7 +300,7 @@ pub(crate) fn select<'a>( View::Flexible | View::Rigid(_) | View::Application | View::Error ) }); - let mut remaining = 16_384; + let mut remaining = WORK_LIMIT; let mut selected = None; let mut deferred = false; for (key, info) in tables.impls_for(trait_) { @@ -543,7 +546,7 @@ pub(crate) fn improvement<'a>( if args.len() < 2 { return None; } - let mut remaining = 16_384; + let mut remaining = WORK_LIMIT; let mut candidates = given_candidates(tables, uf, trait_, args, givens, allocated, &mut remaining)?; if !candidates.is_empty() { diff --git a/crates/nash-solve/src/solve.rs b/crates/nash-solve/src/solve.rs index 4aa4f3ca..74b0c866 100644 --- a/crates/nash-solve/src/solve.rs +++ b/crates/nash-solve/src/solve.rs @@ -5,6 +5,7 @@ use std::collections::{BTreeMap, BTreeSet, VecDeque}; use bumpalo::Bump; use nash_ast::Type as CanType; +use nash_ast::head::{DEPTH_LIMIT, WORK_LIMIT}; use nash_can::Annotations; use nash_constrain::error::{Category, Error, Expected, PExpected}; use nash_constrain::type_::{ @@ -1492,7 +1493,7 @@ impl<'a> Solver<'a, '_> { .entry(self.predicates.root(id)) .or_default(); *work += 1; - if *work > 16_384 || resolution_depth >= 128 { + if *work > WORK_LIMIT || resolution_depth >= DEPTH_LIMIT { state.errors.push(Error::ImplResolutionLimit { region: site.region, name: site.name, @@ -3186,7 +3187,7 @@ mod copy_tests { solver.wanted.push((OUTERMOST_RANK, id)); ids.push(id); } - solver.resolution_work.insert(ids[0], 16_384); + solver.resolution_work.insert(ids[0], WORK_LIMIT); let result = solver.resolve_wanted( &mut uf, OUTERMOST_RANK, From e58587b64f25a5a990735aa40924a580e7fccc5c Mon Sep 17 00:00:00 2001 From: microproofs Date: Fri, 9 Oct 2026 21:32:47 +0700 Subject: [PATCH 07/24] feat: raise the trait search and specialization depth limits to 256 Signed-off-by: microproofs --- .sampo/changesets/depth-limits-256.md | 6 ++++++ crates/nash-ast/src/head.rs | 2 +- crates/nash-codegen/src/build.rs | 2 +- docs/traits.md | 6 +++--- 4 files changed, 11 insertions(+), 5 deletions(-) create mode 100644 .sampo/changesets/depth-limits-256.md diff --git a/.sampo/changesets/depth-limits-256.md b/.sampo/changesets/depth-limits-256.md new file mode 100644 index 00000000..6ae90a8d --- /dev/null +++ b/.sampo/changesets/depth-limits-256.md @@ -0,0 +1,6 @@ +--- +cargo/nash-ast: patch +cargo/nash-codegen: patch +--- + +Raise the trait search depth limit (`nash_ast::head::DEPTH_LIMIT`) and the specialization type depth limit from 128 to 256. diff --git a/crates/nash-ast/src/head.rs b/crates/nash-ast/src/head.rs index a6feeccd..4ab3e130 100644 --- a/crates/nash-ast/src/head.rs +++ b/crates/nash-ast/src/head.rs @@ -11,7 +11,7 @@ pub struct Limit; // Impl contexts need not decrease, so every trait search has a budget. pub const WORK_LIMIT: usize = 16_384; -pub const DEPTH_LIMIT: usize = 128; +pub const DEPTH_LIMIT: usize = 256; pub enum Match { Yes(T), diff --git a/crates/nash-codegen/src/build.rs b/crates/nash-codegen/src/build.rs index afa3c40d..5c87b312 100644 --- a/crates/nash-codegen/src/build.rs +++ b/crates/nash-codegen/src/build.rs @@ -24,7 +24,7 @@ use emission::hoist_strings; pub(crate) use emission::names; const MAX_SPECIALIZATIONS: usize = 1024; -const MAX_TYPE_DEPTH: usize = 128; +const MAX_TYPE_DEPTH: usize = 256; #[derive(Clone, Copy)] pub struct Input<'a, 's> { diff --git a/docs/traits.md b/docs/traits.md index ded26cff..e938b7d9 100644 --- a/docs/traits.md +++ b/docs/traits.md @@ -273,7 +273,7 @@ does not assume that different head variable names make impls disjoint. Superclass checking during canonicalization performs a bounded search. A predicate already active in the instance-resolution chain is a cycle, not a proof. Expanding flexible contexts are bounded too: each impl check -allows 16,384 work steps and fewer than 128 nested resolution or type +allows 16,384 work steps and fewer than 256 nested resolution or type conversion calls. Predicate comparisons count toward the work limit. Failure reports the instantiated superclass requirement and distinguishes a missing proof, a cycle, and the search limit. The given superclass @@ -381,7 +381,7 @@ context is the given set. Impl selection waits for the surrounding definition's type equalities. Captured outer variables must also be fixed before rejecting an enclosing given in favor of an impl. Impl contexts may expand indefinitely; resolution -is bounded to 128 levels and 16,384 attempts per definition boundary. Exceeding +is bounded to 256 levels and 16,384 attempts per definition boundary. Exceeding either bound reports `ImplResolutionLimit` at the originating call. An exhausted search never counts as evidence that a constraint was satisfied. @@ -553,7 +553,7 @@ arguments with an already-proven Big representation; it does not choose a representation. Failures distinguish `MissingImpl`, `NonGround`, and `Limit`, retaining the failed predicate. Resolution and type traversal share a 16,384-step work -budget, with a depth limit of 128. Context substitution is charged before +budget, with a depth limit of 256. Context substitution is charged before allocation. Callers supply well-kinded canonical types and complete tables. Codegen specializes executable trait evidence at compile time. It walks a From 95afd58c42d4c4f2da0f5b0166ab8dd3a0f9c587 Mon Sep 17 00:00:00 2001 From: microproofs Date: Sat, 10 Oct 2026 01:29:44 +0700 Subject: [PATCH 08/24] test(codegen): build the deep type from the depth limit Signed-off-by: microproofs --- crates/nash-codegen/src/evidence/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/nash-codegen/src/evidence/tests.rs b/crates/nash-codegen/src/evidence/tests.rs index 2899dba7..85258cda 100644 --- a/crates/nash-codegen/src/evidence/tests.rs +++ b/crates/nash-codegen/src/evidence/tests.rs @@ -313,7 +313,7 @@ fn cycles_and_deep_types_stop_before_recursive_allocation() { Err(Error::Limit) )); let mut typ = named(&arena, "int", &[]); - for _ in 0..150 { + for _ in 0..=DEPTH_LIMIT { typ = named(&arena, "list", arena.alloc_slice_copy(&[typ])); } assert!(matches!( From 532e437ad0cdad996feb55548fba7cc3e8703256 Mon Sep 17 00:00:00 2001 From: microproofs Date: Sun, 11 Oct 2026 18:50:20 +0700 Subject: [PATCH 09/24] perf(solve): index kind contracts, recovery edges, and scheme records Kind checks, recovery closure, stranded lookups, scheme lookups, and the per-scope grouping in finish scanned every earlier record. Each is now an index that follows union-find merges through the new UnionFind::merges log. Debug builds keep an ORACLE that recomputes the old scan and asserts the same result on every call; step 13 removes them after the constraint tree and coverage changes land. Signed-off-by: microproofs --- .../changesets/solver-indexed-bookkeeping.md | 6 + crates/nash-constrain/src/union_find.rs | 14 +- crates/nash-solve/src/kind_check.rs | 209 ++++++++++++-- crates/nash-solve/src/recovery.rs | 182 +++++++++++-- crates/nash-solve/src/solve.rs | 255 +++++++++++------- 5 files changed, 520 insertions(+), 146 deletions(-) create mode 100644 .sampo/changesets/solver-indexed-bookkeeping.md diff --git a/.sampo/changesets/solver-indexed-bookkeeping.md b/.sampo/changesets/solver-indexed-bookkeeping.md new file mode 100644 index 00000000..f411c0b8 --- /dev/null +++ b/.sampo/changesets/solver-indexed-bookkeeping.md @@ -0,0 +1,6 @@ +--- +cargo/nash-constrain: patch +cargo/nash-solve: patch +--- + +Index kind contracts, recovery dependencies, stranded variables, and scheme records so that type checking does not scan every earlier declaration again. diff --git a/crates/nash-constrain/src/union_find.rs b/crates/nash-constrain/src/union_find.rs index ac13be73..11841ec4 100644 --- a/crates/nash-constrain/src/union_find.rs +++ b/crates/nash-constrain/src/union_find.rs @@ -26,11 +26,17 @@ enum PointInfo<'a> { #[derive(Debug, Default)] pub struct UnionFind<'a> { points: Vec>, + // DEVIATION from Elm: `(loser, winner)` of every union, so an index keyed + // by representative can follow merges without a scan. + merges: Vec<(Variable, Variable)>, } impl<'a> UnionFind<'a> { pub fn new() -> Self { - UnionFind { points: Vec::new() } + UnionFind { + points: Vec::new(), + merges: Vec::new(), + } } pub fn fresh(&mut self, desc: Descriptor<'a>) -> Variable { @@ -109,6 +115,7 @@ impl<'a> UnionFind<'a> { }; self.points[loser.index()] = PointInfo::Link(winner); + self.merges.push((loser, winner)); match &mut self.points[winner.index()] { PointInfo::Info { weight, desc } => { *weight = new_weight; @@ -127,6 +134,11 @@ impl<'a> UnionFind<'a> { self.repr(point) } + /// Every union so far as `(loser, winner)`, oldest first. + pub fn merges(&self) -> &[(Variable, Variable)] { + &self.merges + } + /// True when this point has been unioned into another representative. pub fn redundant(&self, point: Variable) -> bool { matches!(self.points[point.index()], PointInfo::Link(_)) diff --git a/crates/nash-solve/src/kind_check.rs b/crates/nash-solve/src/kind_check.rs index 13cdf799..135859a2 100644 --- a/crates/nash-solve/src/kind_check.rs +++ b/crates/nash-solve/src/kind_check.rs @@ -2,7 +2,7 @@ //! //! Keep every expression root: discarded intermediate types must also have //! kind Type. Predicate-only variables are checked through the predicate store. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; use bumpalo::Bump; use nash_can::kinds::{Infer, K, KindEnv, Mismatch}; @@ -21,6 +21,99 @@ pub(crate) struct Contract<'a> { pub region: Region, } +/// Recorded contracts with an index by the class of their variable. +#[derive(Default)] +pub(crate) struct Contracts<'a> { + all: Vec>, + /// Positions in `all`, ascending, so a class keeps contract order. + by_class: HashMap>, + /// Number of union-find merges already applied to `by_class`. + merged: usize, +} + +/// Contracts whose index agrees with the current union-find classes. +#[derive(Clone, Copy)] +struct Indexed<'c, 'a>(&'c Contracts<'a>); + +impl<'a> Contracts<'a> { + fn indexed(&mut self, uf: &UnionFind<'a>) -> Indexed<'_, 'a> { + for &(loser, winner) in &uf.merges()[self.merged..] { + if let Some(moved) = self.by_class.remove(&loser) { + let kept = self.by_class.entry(winner).or_default(); + kept.extend(moved); + kept.sort_unstable(); + } + } + self.merged = uf.merges().len(); + Indexed(self) + } + + pub(crate) fn len(&self) -> usize { + self.all.len() + } + + pub(crate) fn push(&mut self, uf: &mut UnionFind<'a>, contract: Contract<'a>) { + self.indexed(uf); + self.by_class + .entry(uf.find(contract.variable)) + .or_default() + .push(self.all.len()); + self.all.push(contract); + } + + /// Contracts among the first `recorded` on the class of `variable`, oldest first. + pub(crate) fn on_class( + &mut self, + uf: &mut UnionFind<'a>, + variable: Variable, + recorded: usize, + ) -> Vec> { + let class = uf.find(variable); + self.indexed(uf) + .on(class) + .take_while(|(position, _)| *position < recorded) + .map(|(_, contract)| *contract) + .collect() + } +} + +impl<'c, 'a> Indexed<'c, 'a> { + fn on(self, class: Variable) -> impl Iterator)> { + self.0 + .by_class + .get(&class) + .into_iter() + .flatten() + .map(move |&position| (position, &self.0.all[position])) + } + + /// ORACLE: the per-check scan of every contract that the index replaces. + #[cfg(any(test, debug_assertions))] + fn assert_scan_agrees(self, uf: &mut UnionFind<'a>) { + let mut scan = BTreeMap::<_, Vec<_>>::new(); + for contract in &self.0.all { + if crate::recovery::is_poisoned(uf, [contract.owner]) { + continue; + } + scan.entry(uf.find(contract.variable)) + .or_default() + .push(std::ptr::from_ref(contract.kind)); + } + let mut index = BTreeMap::<_, Vec<_>>::new(); + for &class in self.0.by_class.keys() { + let kinds: Vec<_> = self + .on(class) + .filter(|(_, contract)| !crate::recovery::is_poisoned(uf, [contract.owner])) + .map(|(_, contract)| std::ptr::from_ref(contract.kind)) + .collect(); + if !kinds.is_empty() { + index.insert(class, kinds); + } + } + assert_eq!(scan, index); + } +} + pub(crate) struct Failure<'a> { pub error: Error<'a>, pub variable: Variable, @@ -30,32 +123,17 @@ struct Check<'a, 'env> { infer: Infer<'a>, env: &'env KindEnv<'a>, variables: BTreeMap>, - contracts: BTreeMap>>, + contracts: Indexed<'env, 'a>, failed: Option, } impl<'a, 'env> Check<'a, 'env> { - fn new( - bump: &'a Bump, - uf: &mut UnionFind<'a>, - env: &'env KindEnv<'a>, - contracts: &[Contract<'a>], - ) -> Self { - let mut requirements = BTreeMap::<_, Vec<_>>::new(); - for contract in contracts { - if crate::recovery::is_poisoned(uf, [contract.owner]) { - continue; - } - requirements - .entry(uf.find(contract.variable)) - .or_default() - .push(contract.kind); - } + fn new(bump: &'a Bump, env: &'env KindEnv<'a>, contracts: Indexed<'env, 'a>) -> Self { Self { infer: Infer::new(bump), env, variables: BTreeMap::new(), - contracts: requirements, + contracts, failed: None, } } @@ -83,9 +161,11 @@ impl<'a, 'env> Check<'a, 'env> { } let kind = self.infer.fresh(); self.variables.insert(variable, kind); - if let Some(requirements) = self.contracts.get(&variable) { - for requirement in requirements { - self.infer.unify(self.infer.from_kind(requirement), kind)?; + // Poison does not change inside one check. + for (_, contract) in self.contracts.on(variable) { + if !crate::recovery::is_poisoned(uf, [contract.owner]) { + self.infer + .unify(self.infer.from_kind(contract.kind), kind)?; } } let actual = match uf.get(variable).content.clone() { @@ -227,17 +307,20 @@ pub(crate) fn check<'a>( env: &KindEnv<'a>, roots: &[(Variable, Region)], predicates: &Store<'a>, - contracts: &[Contract<'a>], - dependencies: &crate::recovery::Dependencies, + contracts: &mut Contracts<'a>, + dependencies: &mut crate::recovery::Dependencies, ) -> Vec> { // Restart after each failure: kind assignments made by a failed check must // not affect another diagnostic. Poison the failing nested type, then let // directed containment skip its parents while retaining sibling roots. let mut errors = Vec::new(); + let contracts = contracts.indexed(uf); loop { - let mut check = Check::new(bump, uf, env, contracts); + #[cfg(debug_assertions)] + contracts.assert_scan_agrees(uf); + let mut check = Check::new(bump, env, contracts); let result = (|| { - for contract in contracts { + for contract in &contracts.0.all { if !crate::recovery::is_poisoned(uf, [contract.owner, contract.variable]) { check .variable(uf, contract.variable) @@ -287,10 +370,13 @@ pub(crate) fn freeze<'a>( root: nash_region::Located, predicates: &[Body<'a>], quantified: &[Variable], - contracts: &[Contract<'a>], + contracts: &mut Contracts<'a>, ) -> Result>, Box>> { let region = root.region; - let mut check = Check::new(bump, uf, env, contracts); + let contracts = contracts.indexed(uf); + #[cfg(debug_assertions)] + contracts.assert_scan_agrees(uf); + let mut check = Check::new(bump, env, contracts); let result = (|| { check.values(uf, [root.value])?; for body in predicates { @@ -317,3 +403,70 @@ pub(crate) fn freeze<'a>( }) }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::recovery::tests::Lcg; + use nash_constrain::type_::{make_descriptor, mk_flex_var}; + + #[test] + fn contract_index_agrees_with_the_contract_scan() { + let bump = Bump::new(); + let mut compared = 0; + for seed in 0..300 { + let mut random = Lcg(seed); + let mut uf = UnionFind::new(); + let mut contracts = Contracts::default(); + let mut variables: Vec<_> = (0..4).map(|_| mk_flex_var(&mut uf)).collect(); + for _ in 0..150 { + match random.below(7) { + 0 => variables.push(mk_flex_var(&mut uf)), + 1 => { + let children = (random.pick(&variables), random.pick(&variables)); + variables.push(uf.fresh(make_descriptor(Content::Structure( + FlatType::Fun1(children.0, children.1), + )))); + } + 2 | 3 => { + let contract = Contract { + variable: random.pick(&variables), + owner: random.pick(&variables), + // A fresh allocation gives every contract its own identity. + kind: bump.alloc(nash_ast::Kind::Type), + region: Region::zero(), + }; + contracts.push(&mut uf, contract); + } + 4 => { + let (first, second) = (random.pick(&variables), random.pick(&variables)); + let content = uf.get(first).content.clone(); + uf.union(first, second, make_descriptor(content)); + } + 5 => { + let variable = random.pick(&variables); + uf.modify(variable, |desc| desc.content = Content::Error); + } + _ => { + contracts.indexed(&uf).assert_scan_agrees(&mut uf); + let variable = random.pick(&variables); + let recorded = random.below(contracts.len() + 1); + let scan: Vec<_> = contracts.all[..recorded] + .iter() + .filter(|contract| uf.equivalent(variable, contract.variable)) + .map(|contract| std::ptr::from_ref(contract.kind)) + .collect(); + let index: Vec<_> = contracts + .on_class(&mut uf, variable, recorded) + .iter() + .map(|contract| std::ptr::from_ref(contract.kind)) + .collect(); + assert_eq!(index, scan); + compared += 1; + } + } + } + } + assert!(compared > 5_000); + } +} diff --git a/crates/nash-solve/src/recovery.rs b/crates/nash-solve/src/recovery.rs index 7da93585..764df9a9 100644 --- a/crates/nash-solve/src/recovery.rs +++ b/crates/nash-solve/src/recovery.rs @@ -3,19 +3,28 @@ //! Failed comparisons invalidate changed shared variables. Containment carries //! that failure to parents without invalidating independent siblings. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use nash_constrain::{Content, FlatType, UnionFind, Variable}; #[derive(Default)] pub(crate) struct Dependencies { - edges: BTreeSet<(Variable, Variable)>, + /// Recorded containment: parent handle to child handles. + edges: BTreeMap>, + /// Recorded parent handles by their current representative. + parents: HashMap>, computations: BTreeSet<(Variable, Variable)>, field_receivers: BTreeSet<(Variable, Variable)>, - /// Variables whose only type information came from a structure that merged - /// into an existing `Error`, such as the argument of a call to a failed - /// definition. They are unknown because of that failure, not ambiguous. - stranded: BTreeSet, + /// Representatives of variables whose only type information came from a + /// structure that merged into an existing `Error`, such as the argument of + /// a call to a failed definition. They are unknown because of that + /// failure, not ambiguous. + stranded: HashSet, + /// ORACLE input: stranded variables as recorded, before later merges. + #[cfg(any(test, debug_assertions))] + stranded_handles: BTreeSet, + /// Number of union-find merges already applied to `parents` and `stranded`. + merged: usize, } impl Dependencies { @@ -26,6 +35,7 @@ impl Dependencies { uf: &mut UnionFind<'_>, roots: impl IntoIterator, ) { + self.sync(uf); let mut pending: Vec<_> = roots.into_iter().collect(); let mut seen = BTreeSet::new(); while let Some(variable) = pending.pop() { @@ -35,15 +45,37 @@ impl Dependencies { } for child in children(&uf.get(variable).content) { let child = uf.find(child); - self.edges.insert((variable, child)); + let recorded = self.edges.entry(variable).or_default(); + if recorded.is_empty() { + self.parents.entry(variable).or_default().push(variable); + } + recorded.insert(child); pending.push(child); } } } + /// Move the indexes keyed by representative along the merges made since + /// the last call. + pub(crate) fn sync(&mut self, uf: &UnionFind<'_>) { + for &(loser, winner) in &uf.merges()[self.merged..] { + if let Some(moved) = self.parents.remove(&loser) { + self.parents.entry(winner).or_default().extend(moved); + } + if self.stranded.remove(&loser) { + self.stranded.insert(winner); + } + } + self.merged = uf.merges().len(); + } + pub(crate) fn propagate(&self, uf: &mut UnionFind<'_>) -> bool { let mut changed = false; - for &(parent, child) in self.edges.iter().chain(&self.computations) { + let edges = self + .edges + .iter() + .flat_map(|(parent, children)| children.iter().map(move |child| (*parent, *child))); + for (parent, child) in edges.chain(self.computations.iter().copied()) { // Retain an aggregate whose current shape already contains the // error: unification can still check its unaffected children. // A lost historical edge or a separate computation result needs @@ -82,18 +114,35 @@ impl Dependencies { roots: impl IntoIterator, ) { let lost = self.detached(uf, roots); + #[cfg(any(test, debug_assertions))] + self.stranded_handles.extend(&lost); self.stranded.extend(lost); } + /// Call `sync` after the last merge before a lookup. pub(crate) fn is_stranded(&self, uf: &mut UnionFind<'_>, variable: Variable) -> bool { + debug_assert_eq!( + self.merged, + uf.merges().len(), + "stranded lookup after an unsynced merge" + ); + let found = self.stranded.contains(&uf.find(variable)); + #[cfg(debug_assertions)] + assert_eq!(found, self.stranded_scan(uf, variable)); + found + } + + /// ORACLE: the scan of every stranded variable that the lookup replaces. + #[cfg(any(test, debug_assertions))] + fn stranded_scan(&self, uf: &mut UnionFind<'_>, variable: Variable) -> bool { let variable = uf.find(variable); - self.stranded + self.stranded_handles .iter() .any(|stranded| uf.find(*stranded) == variable) } pub(crate) fn invalidate( - &self, + &mut self, uf: &mut UnionFind<'_>, roots: impl IntoIterator, ) { @@ -103,7 +152,7 @@ impl Dependencies { /// Nodes removed by normalization still belong to the original computation. pub(crate) fn detached( - &self, + &mut self, uf: &mut UnionFind<'_>, roots: impl IntoIterator, ) -> BTreeSet { @@ -115,17 +164,42 @@ impl Dependencies { .collect() } + /// Everything reachable through current structure or recorded containment. fn historical( - &self, + &mut self, uf: &mut UnionFind<'_>, roots: impl IntoIterator, ) -> BTreeSet { + self.sync(uf); + let roots: Vec<_> = roots.into_iter().collect(); + let mut pending = roots.clone(); + let mut variables = BTreeSet::new(); + while let Some(variable) = pending.pop() { + let variable = uf.find(variable); + if !variables.insert(variable) { + continue; + } + pending.extend(children(&uf.get(variable).content)); + for parent in self.parents.get(&variable).into_iter().flatten() { + pending.extend(self.edges[parent].iter().copied()); + } + } + #[cfg(debug_assertions)] + assert_eq!(variables, self.historical_scan(uf, roots)); + variables + } + + /// ORACLE: the fixed-point scan that `historical` replaces. + #[cfg(any(test, debug_assertions))] + fn historical_scan(&self, uf: &mut UnionFind<'_>, roots: Vec) -> BTreeSet { let mut variables = reachable(uf, roots); loop { let before = variables.len(); - for &(parent, child) in &self.edges { - if variables.contains(&uf.find(parent)) { - variables.extend(reachable(uf, [child])); + for (parent, recorded) in &self.edges { + if variables.contains(&uf.find(*parent)) { + for child in recorded { + variables.extend(reachable(uf, [*child])); + } } } if variables.len() == before { @@ -200,3 +274,81 @@ pub(crate) fn poison_roots( } changed } + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use nash_constrain::type_::{make_descriptor, mk_flex_var}; + + /// Fixed-seed generator, so the randomized tests need no dependency. + pub(crate) struct Lcg(pub u64); + + impl Lcg { + pub(crate) fn below(&mut self, bound: usize) -> usize { + self.0 = self + .0 + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (self.0 >> 33) as usize % bound + } + + pub(crate) fn pick(&mut self, variables: &[Variable]) -> Variable { + variables[self.below(variables.len())] + } + } + + #[test] + fn historical_closure_and_stranded_lookup_agree_with_the_scans() { + let (mut closures, mut stranded, mut unstranded) = (0, 0, 0); + for seed in 0..300 { + let mut random = Lcg(seed); + let mut uf = UnionFind::new(); + let mut dependencies = Dependencies::default(); + let mut variables: Vec<_> = (0..4).map(|_| mk_flex_var(&mut uf)).collect(); + for _ in 0..200 { + match random.below(9) { + 0 => variables.push(mk_flex_var(&mut uf)), + 1 | 2 => { + let children = (random.pick(&variables), random.pick(&variables)); + variables.push(uf.fresh(make_descriptor(Content::Structure( + FlatType::Fun1(children.0, children.1), + )))); + } + 3 => dependencies.remember(&mut uf, [random.pick(&variables)]), + 4 => { + // Unification keeps the content of one side. + let (first, second) = (random.pick(&variables), random.pick(&variables)); + let kept = if random.below(2) == 0 { first } else { second }; + let content = uf.get(kept).content.clone(); + uf.union(first, second, make_descriptor(content)); + } + 5 => { + // Normalization removes the visible children of a node. + let variable = random.pick(&variables); + uf.modify(variable, |desc| desc.content = Content::FlexVar(None)); + } + 6 => dependencies.strand(&mut uf, [random.pick(&variables)]), + 7 => { + dependencies.sync(&uf); + let variable = random.pick(&variables); + let scan = dependencies.stranded_scan(&mut uf, variable); + assert_eq!(dependencies.is_stranded(&mut uf, variable), scan); + if scan { + stranded += 1; + } else { + unstranded += 1; + } + } + _ => { + let roots = vec![random.pick(&variables), random.pick(&variables)]; + let scan = dependencies.historical_scan(&mut uf, roots.clone()); + assert_eq!(dependencies.historical(&mut uf, roots), scan); + closures += 1; + } + } + } + } + assert!(closures > 5_000); + assert!(stranded > 500 && unstranded > 500); + } +} diff --git a/crates/nash-solve/src/solve.rs b/crates/nash-solve/src/solve.rs index 74b0c866..c95326be 100644 --- a/crates/nash-solve/src/solve.rs +++ b/crates/nash-solve/src/solve.rs @@ -80,6 +80,41 @@ enum UseSource { }, } +/// Recorded schemes with a lookup by defining node. +#[derive(Default)] +struct Schemes<'a> { + records: Vec>, + /// First record of each site node. + by_site: std::collections::HashMap, +} + +impl<'a> Schemes<'a> { + fn push(&mut self, record: SchemeRecord<'a>) { + self.by_site + .entry(record.site.node()) + .or_insert(self.records.len()); + self.records.push(record); + } + + fn at(&self, site: nash_ast::NodeId) -> Option<&SchemeRecord<'a>> { + let found = self.by_site.get(&site).map(|index| &self.records[*index]); + // ORACLE: the scan of every scheme that the lookup replaces. + #[cfg(debug_assertions)] + assert_eq!( + found.map(std::ptr::from_ref), + self.records + .iter() + .find(|scheme| scheme.site.node() == site) + .map(std::ptr::from_ref) + ); + found + } + + fn iter(&self) -> std::slice::Iter<'_, SchemeRecord<'a>> { + self.records.iter() + } +} + struct NodeTypeRecord { node: nash_ast::NodeId, variable: Variable, @@ -125,7 +160,7 @@ struct Solver<'a, 'tables> { predicates: Store<'a>, wanted: Vec<(usize, type_::PredId)>, givens: Vec>, - schemes: Vec>, + schemes: Schemes<'a>, recursive_uses: Vec, uses: Vec>, expr_types: Vec, @@ -138,7 +173,7 @@ struct Solver<'a, 'tables> { failed_predicates: BTreeSet, failed_definitions: std::collections::HashSet, value_roots: Vec<(Variable, nash_region::Region)>, - kind_contracts: Vec>, + kind_contracts: crate::kind_check::Contracts<'a>, kind_errors: Vec>, fields: Vec>, } @@ -165,7 +200,7 @@ impl<'a, 'tables> Solver<'a, 'tables> { predicates: Store::default(), wanted: Vec::new(), givens: Vec::new(), - schemes: Vec::new(), + schemes: Schemes::default(), recursive_uses: Vec::new(), uses: Vec::new(), expr_types: Vec::new(), @@ -178,7 +213,7 @@ impl<'a, 'tables> Solver<'a, 'tables> { failed_predicates: BTreeSet::new(), failed_definitions: std::collections::HashSet::new(), value_roots: Vec::new(), - kind_contracts: Vec::new(), + kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), test_scope: false, @@ -266,7 +301,7 @@ impl<'a> Solver<'a, '_> { self.failed_definitions.insert(definition); loop { let before = self.failed_definitions.len(); - for scheme in &self.schemes { + for scheme in self.schemes.iter() { if self.failed_definitions.contains(&scheme.site.node()) || self.failed_definitions.contains(&scheme.binder) { @@ -564,8 +599,7 @@ impl<'a> Solver<'a, '_> { loop { let scheme = self .schemes - .iter() - .find(|scheme| scheme.site.node() == owner) + .at(owner) .expect("body owner has a recorded scheme"); match scheme.parent { Some(parent) => { @@ -687,13 +721,15 @@ impl<'a> Solver<'a, '_> { &self.tables.kinds, &self.value_roots, &self.predicates, - &self.kind_contracts, - &self.dependencies, + &mut self.kind_contracts, + &mut self.dependencies, ); if !errors.is_empty() { self.has_poison = true; self.propagate_poison(uf); } + // Unknown constraints below look up stranded variables. + self.dependencies.sync(uf); let growing = self.growing_evidence(); for use_ in &self.uses { if crate::recovery::is_poisoned(uf, [use_.variable]) { @@ -782,21 +818,70 @@ impl<'a> Solver<'a, '_> { let mut solved = SolvedTypes::default(); let mut orders = HashMap::new(); let mut rendered_uses = HashMap::new(); + // Group every record by scope once, scopes in first-seen order. let mut scopes = Vec::new(); - for scheme in &self.schemes { + let mut scope_index = HashMap::new(); + let mut members: Vec>> = Vec::new(); + for scheme in self.schemes.iter() { let root = self.scope(scheme.site.node()).0; - if !scopes.contains(&root) { + let index = *scope_index.entry(root).or_insert(members.len()); + if index == members.len() { scopes.push(root); + members.push(Vec::new()); + } + members[index].push(scheme); + } + let scope_of = |owner: nash_ast::NodeId| scope_index[&self.scope(owner).0]; + let mut uses: Vec>> = vec![Vec::new(); scopes.len()]; + for use_ in &self.uses { + uses[scope_of(use_.owner.expect("use belongs to a definition"))].push(use_); + } + let mut exprs: Vec> = vec![Vec::new(); scopes.len()]; + for record in &self.expr_types { + if let Some(owner) = record.owner { + exprs[scope_of(owner)].push(record); + } + } + let mut patterns: Vec> = vec![Vec::new(); scopes.len()]; + for record in &self.pattern_types { + if let Some(owner) = record.owner { + patterns[scope_of(owner)].push(record); } } // Quantifier order must be frozen with its rendered scheme, before // another body can assign names to its own instantiations. - for scope in &scopes { - let mut members: Vec<_> = self - .schemes - .iter() - .filter(|scheme| self.scope(scheme.site.node()).0 == *scope) - .collect(); + for (index, mut members) in members.into_iter().enumerate() { + let (uses, exprs, patterns) = (&uses[index], &exprs[index], &patterns[index]); + // ORACLE: the per-scope filters over every record that the grouping replaces. + #[cfg(debug_assertions)] + { + let scope = scopes[index]; + let same = |owner: nash_ast::NodeId| self.scope(owner).0 == scope; + assert!( + members.iter().copied().map(std::ptr::from_ref).eq(self + .schemes + .iter() + .filter(|scheme| same(scheme.site.node())) + .map(std::ptr::from_ref)) + ); + assert!( + uses.iter().copied().map(std::ptr::from_ref).eq(self + .uses + .iter() + .filter(|use_| same(use_.owner.expect("use belongs to a definition"))) + .map(std::ptr::from_ref)) + ); + for (grouped, records) in + [(exprs, &self.expr_types), (patterns, &self.pattern_types)] + { + assert!( + grouped.iter().copied().map(std::ptr::from_ref).eq(records + .iter() + .filter(|record| record.owner.is_some_and(same)) + .map(std::ptr::from_ref)) + ); + } + } members.sort_by_key(|scheme| self.scope(scheme.site.node()).1); let mut roots = Vec::new(); for scheme in &members { @@ -805,22 +890,11 @@ impl<'a> Solver<'a, '_> { roots.extend(self.predicates.get(*id).body.roots()); } } - for use_ in &self.uses { - if self - .scope(use_.owner.expect("use belongs to a definition")) - .0 - != *scope - { - continue; - } + for use_ in uses { let quantified = match use_.source { - UseSource::Local { definition, .. } => self - .schemes - .iter() - .find(|scheme| scheme.site.node() == definition) - .unwrap() - .quantified - .as_slice(), + UseSource::Local { definition, .. } => { + self.schemes.at(definition).unwrap().quantified.as_slice() + } UseSource::Foreign { .. } => &[], }; roots.extend(self.use_variables(uf, use_, quantified)); @@ -846,13 +920,7 @@ impl<'a> Solver<'a, '_> { // Node types must use the same variable names as their owner's // schemes and instances. Add them last so existing quantifier // ordering remains stable when a body introduces private types. - let node_types = self.expr_types.iter().chain(&self.pattern_types); - roots.extend(node_types.filter_map(|record| { - record - .owner - .filter(|owner| self.scope(*owner).0 == *scope) - .map(|_| record.variable) - })); + roots.extend(exprs.iter().chain(patterns).map(|record| record.variable)); crate::annotation::prepare_scope(self.bump, uf, &roots); for scheme in members { let id = scheme.site.node(); @@ -882,22 +950,11 @@ impl<'a> Solver<'a, '_> { }, ); } - for use_ in &self.uses { - if self - .scope(use_.owner.expect("use belongs to a definition")) - .0 - != *scope - { - continue; - } + for use_ in uses { let keys = match &use_.source { - UseSource::Local { definition, .. } => self - .schemes - .iter() - .find(|scheme| scheme.site.node() == *definition) - .unwrap() - .quantified - .clone(), + UseSource::Local { definition, .. } => { + self.schemes.at(*definition).unwrap().quantified.clone() + } UseSource::Foreign { variables } => variables.clone(), }; let variables = self.use_variables(uf, use_, &keys); @@ -914,21 +971,14 @@ impl<'a> Solver<'a, '_> { "one instance per original use node" ); } - for (records, output) in [ - (&self.expr_types, &mut solved.exprs), - (&self.pattern_types, &mut solved.patterns), - ] { + for (records, output) in [(exprs, &mut solved.exprs), (patterns, &mut solved.patterns)] + { for record in records { - if record - .owner - .is_some_and(|owner| self.scope(owner).0 == *scope) - { - let typ = crate::annotation::to_solved_type(self.bump, uf, record.variable); - assert!( - output.insert(record.node, typ).is_none(), - "one type per original node" - ); - } + let typ = crate::annotation::to_solved_type(self.bump, uf, record.variable); + assert!( + output.insert(record.node, typ).is_none(), + "one type per original node" + ); } } } @@ -1892,9 +1942,13 @@ impl<'a> Solver<'a, '_> { Located::at(region, root), &bodies, quantified, - &self.kind_contracts, + &mut self.kind_contracts, ) { - Ok(contracts) => self.kind_contracts.extend(contracts), + Ok(contracts) => { + for contract in contracts { + self.kind_contracts.push(uf, contract); + } + } Err(failure) => { self.kind_errors.push(failure.error); self.has_poison = true; @@ -1963,11 +2017,7 @@ impl<'a> Solver<'a, '_> { let UseSource::Local { definition, .. } = use_.source else { unreachable!("recursive local use") }; - let Some(scheme) = self - .schemes - .iter() - .find(|scheme| scheme.site.node() == definition) - else { + let Some(scheme) = self.schemes.at(definition) else { self.recursive_uses.push(use_index); continue; }; @@ -2061,10 +2111,9 @@ impl<'a> Solver<'a, '_> { return self.register(uf, rank, Content::Error); } let mut roots = vec![binding.variable]; - if let Some(scheme) = self - .schemes - .iter() - .find(|scheme| Some(scheme.site.node()) == binding.definition) + if let Some(scheme) = binding + .definition + .and_then(|definition| self.schemes.at(definition)) { // A destructured name instantiates its whole aggregate scheme, // including quantifiers absent from this selected component. @@ -2209,6 +2258,7 @@ impl<'a> Solver<'a, '_> { } } } + self.dependencies.sync(uf); let mut ambiguous: BTreeMap<_, Vec<_>> = BTreeMap::new(); for (_, id) in &self.wanted[start..] { if self.predicate_blocked(uf, *id) { @@ -2507,16 +2557,17 @@ impl<'a> Solver<'a, '_> { .map(|root| self.make_copy_help(uf, rank, *root, quantified)) .collect(); let copied = std::mem::take(&mut self.copied); - let contracts = self.kind_contracts.clone(); + let recorded = self.kind_contracts.len(); for (original, copy) in &copied { - for contract in &contracts { - if uf.equivalent(*original, contract.variable) { - self.kind_contracts.push(crate::kind_check::Contract { + for contract in self.kind_contracts.on_class(uf, *original, recorded) { + self.kind_contracts.push( + uf, + crate::kind_check::Contract { variable: *copy, owner: roots[0], - ..*contract - }); - } + ..contract + }, + ); } uf.modify(*original, |desc| { desc.copy = None; @@ -3131,7 +3182,7 @@ mod copy_tests { predicates: Store::default(), wanted: Vec::new(), givens: Vec::new(), - schemes: Vec::new(), + schemes: Schemes::default(), recursive_uses: Vec::new(), uses: Vec::new(), expr_types: Vec::new(), @@ -3144,7 +3195,7 @@ mod copy_tests { failed_predicates: BTreeSet::new(), failed_definitions: std::collections::HashSet::new(), value_roots: Vec::new(), - kind_contracts: Vec::new(), + kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), test_scope: false, @@ -3224,7 +3275,7 @@ mod copy_tests { predicates: Store::default(), wanted: Vec::new(), givens: Vec::new(), - schemes: Vec::new(), + schemes: Schemes::default(), recursive_uses: Vec::new(), uses: Vec::new(), expr_types: Vec::new(), @@ -3237,7 +3288,7 @@ mod copy_tests { failed_predicates: BTreeSet::new(), failed_definitions: std::collections::HashSet::new(), value_roots: Vec::new(), - kind_contracts: Vec::new(), + kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), test_scope: false, @@ -3296,7 +3347,7 @@ mod copy_tests { predicates: Store::default(), wanted: Vec::new(), givens: Vec::new(), - schemes: Vec::new(), + schemes: Schemes::default(), recursive_uses: Vec::new(), uses: Vec::new(), expr_types: Vec::new(), @@ -3309,7 +3360,7 @@ mod copy_tests { failed_predicates: BTreeSet::new(), failed_definitions: std::collections::HashSet::new(), value_roots: Vec::new(), - kind_contracts: Vec::new(), + kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), test_scope: false, @@ -3370,7 +3421,7 @@ mod copy_tests { predicates: Store::default(), wanted: Vec::new(), givens: Vec::new(), - schemes: Vec::new(), + schemes: Schemes::default(), recursive_uses: Vec::new(), uses: Vec::new(), expr_types: Vec::new(), @@ -3383,7 +3434,7 @@ mod copy_tests { failed_predicates: BTreeSet::new(), failed_definitions: std::collections::HashSet::new(), value_roots: Vec::new(), - kind_contracts: Vec::new(), + kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), test_scope: false, @@ -3457,7 +3508,7 @@ mod copy_tests { predicates: Store::default(), wanted: Vec::new(), givens: Vec::new(), - schemes: Vec::new(), + schemes: Schemes::default(), recursive_uses: Vec::new(), uses: Vec::new(), expr_types: Vec::new(), @@ -3470,7 +3521,7 @@ mod copy_tests { failed_predicates: BTreeSet::new(), failed_definitions: std::collections::HashSet::new(), value_roots: Vec::new(), - kind_contracts: Vec::new(), + kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), test_scope: false, @@ -3594,7 +3645,7 @@ mod copy_tests { predicates: Store::default(), wanted: Vec::new(), givens: Vec::new(), - schemes: Vec::new(), + schemes: Schemes::default(), recursive_uses: Vec::new(), uses: Vec::new(), expr_types: Vec::new(), @@ -3607,7 +3658,7 @@ mod copy_tests { failed_predicates: BTreeSet::new(), failed_definitions: std::collections::HashSet::new(), value_roots: Vec::new(), - kind_contracts: Vec::new(), + kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), test_scope: false, @@ -3765,7 +3816,7 @@ mod copy_tests { predicates: Store::default(), wanted: Vec::new(), givens: Vec::new(), - schemes: Vec::new(), + schemes: Schemes::default(), recursive_uses: Vec::new(), uses: Vec::new(), expr_types: Vec::new(), @@ -3778,7 +3829,7 @@ mod copy_tests { failed_predicates: BTreeSet::new(), failed_definitions: std::collections::HashSet::new(), value_roots: Vec::new(), - kind_contracts: Vec::new(), + kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), test_scope: false, @@ -3852,7 +3903,7 @@ mod copy_tests { predicates: Store::default(), wanted: Vec::new(), givens: Vec::new(), - schemes: Vec::new(), + schemes: Schemes::default(), recursive_uses: Vec::new(), uses: Vec::new(), expr_types: Vec::new(), @@ -3865,7 +3916,7 @@ mod copy_tests { failed_predicates: BTreeSet::new(), failed_definitions: std::collections::HashSet::new(), value_roots: Vec::new(), - kind_contracts: Vec::new(), + kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), test_scope: false, From de1b709752b35099baf2503ece7f6e2c86efce6e Mon Sep 17 00:00:00 2001 From: microproofs Date: Mon, 12 Oct 2026 11:39:16 +0700 Subject: [PATCH 10/24] refactor(traits): share impl selection between inference, entailment, and evidence Inference, superclass entailment, and evidence each had their own impl selection loop. They now call nash_ast::head::select_impl with a SelectPolicy: Defer (inference) lets any undecided candidate defer the selection; Exact (rigid or ground arguments) treats it as not proven. Every candidate is matched under both policies. A second match panics as an impl coherence violation instead of keeping the first or the last: canonicalization already rejects overlapping impls. Signed-off-by: microproofs --- .sampo/changesets/shared-impl-selection.md | 5 + Cargo.lock | 1 + crates/nash-ast/Cargo.toml | 3 + crates/nash-ast/src/head.rs | 193 ++++++++++++++++++ ...t_tests__selection_outcomes_by_policy.snap | 25 +++ crates/nash-can/src/entailment.rs | 38 ++-- crates/nash-solve/src/evidence.rs | 51 ++--- crates/nash-solve/src/resolve.rs | 51 +++-- crates/nash-solve/tests/inference.rs | 23 +++ ..._do_not_select_both_disjoint_blankets.snap | 16 ++ 10 files changed, 335 insertions(+), 71 deletions(-) create mode 100644 .sampo/changesets/shared-impl-selection.md create mode 100644 crates/nash-ast/src/snapshots/nash_ast__head__select_tests__selection_outcomes_by_policy.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__contradictory_inferred_classes_do_not_select_both_disjoint_blankets.snap diff --git a/.sampo/changesets/shared-impl-selection.md b/.sampo/changesets/shared-impl-selection.md new file mode 100644 index 00000000..ff057b50 --- /dev/null +++ b/.sampo/changesets/shared-impl-selection.md @@ -0,0 +1,5 @@ +--- +cargo/nash-ast: minor +--- + +Add `select_impl` with `SelectPolicy` and `ImplSelection`, the one impl selection used by inference, superclass entailment, and evidence. Every candidate is matched, and a second match stops the compiler as a coherence bug instead of picking one. diff --git a/Cargo.lock b/Cargo.lock index a5d0d716..1f37c8b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1725,6 +1725,7 @@ name = "nash-ast" version = "0.12.0" dependencies = [ "bumpalo", + "insta", "nash-region", "nash-source", ] diff --git a/crates/nash-ast/Cargo.toml b/crates/nash-ast/Cargo.toml index 2a594fb7..88c18dd8 100644 --- a/crates/nash-ast/Cargo.toml +++ b/crates/nash-ast/Cargo.toml @@ -11,3 +11,6 @@ license.workspace = true bumpalo.workspace = true nash-region = { path = "../nash-region", version = "0.3.0" } nash-source = { path = "../nash-source", version = "0.10.0" } + +[dev-dependencies] +insta.workspace = true diff --git a/crates/nash-ast/src/head.rs b/crates/nash-ast/src/head.rs index 4ab3e130..36239ab5 100644 --- a/crates/nash-ast/src/head.rs +++ b/crates/nash-ast/src/head.rs @@ -192,6 +192,60 @@ pub fn matches<'a, T: Types<'a>>( )) } +/// How an undecided candidate affects impl selection. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SelectPolicy { + /// Inference: any undecided candidate defers the whole selection. + Defer, + /// Rigid or ground arguments: an undecided candidate is not proven. + Exact, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum ImplSelection { + Selected { info: I, arguments: Vec }, + Deferred, + Missing, +} + +/// Select the impl whose heads match `arguments`. Every candidate is matched, +/// so a second match always stops the compiler: canonicalization rejects +/// overlapping impls, and two matches here mean that check has a bug. +pub fn select_impl<'h, 'a: 'h, T: Types<'a>, I>( + types: &mut T, + candidates: impl IntoIterator], usize, I)>, + arguments: &[T::Node], + remaining: &mut usize, + policy: SelectPolicy, +) -> Result, Limit> { + let mut first: Option<&'h [Head<'a>]> = None; + let mut selected = None; + let mut deferred = false; + for (heads, variable_count, info) in candidates { + match matches(types, heads, arguments, variable_count, remaining)? { + Match::No => {} + Match::Deferred => deferred = true, + Match::Yes(bound) => { + if let Some(first) = first { + panic!( + "impl coherence violated: heads {first:?} and {heads:?} both match the same arguments" + ); + } + first = Some(heads); + selected = Some(ImplSelection::Selected { + info, + arguments: bound, + }); + } + } + } + Ok(match selected { + _ if deferred && policy == SelectPolicy::Defer => ImplSelection::Deferred, + Some(selected) => selected, + None => ImplSelection::Missing, + }) +} + #[derive(Clone, Copy)] struct Term<'p, 'a> { pattern: &'p Head<'a>, @@ -331,3 +385,142 @@ fn unifiable( } Ok(true) } + +#[cfg(test)] +mod select_tests { + use super::*; + use crate::primitives::Repr; + + /// Each candidate head is a variable restricted to one representation; + /// the outcome of its class test is the scripted answer for that class. + struct Scripted(Vec<(ReprSet, Outcome)>); + + #[derive(Clone, Copy)] + enum Outcome { + Yes, + No, + Deferred, + } + + impl<'a> Types<'a> for Scripted { + type Node = (); + fn in_class(&mut self, _: (), class: ReprSet) -> Match<()> { + match self.0.iter().find(|(candidate, _)| *candidate == class) { + Some((_, Outcome::Yes)) => Match::Yes(()), + Some((_, Outcome::Deferred)) => Match::Deferred, + Some((_, Outcome::No)) | None => Match::No, + } + } + fn constructor(&mut self, _: (), _: HeadCon<'a>) -> Match> { + unreachable!("candidates are variable heads") + } + fn equal(&mut self, _: (), _: (), _: &mut usize) -> Result, Limit> { + unreachable!("each candidate has one variable") + } + } + + const CLASSES: [Repr; 3] = [Repr::Big, Repr::Const, Repr::Term]; + + /// Candidate `i` answers `outcomes[i]`; the selection names the winning index. + fn select( + outcomes: &[Outcome], + policy: SelectPolicy, + budget: usize, + ) -> Result, Limit> { + let heads: Vec<_> = CLASSES + .iter() + .map(|repr| { + [Head::Var { + index: 0, + repr: ReprSet::only(*repr), + }] + }) + .collect(); + let mut types = Scripted( + CLASSES + .iter() + .zip(outcomes) + .map(|(repr, outcome)| (ReprSet::only(*repr), *outcome)) + .collect(), + ); + let candidates = heads + .iter() + .take(outcomes.len()) + .enumerate() + .map(|(index, heads)| (heads.as_slice(), 1, index)); + select_impl(&mut types, candidates, &[()], &mut { budget }, policy) + } + + use Outcome::{Deferred, No, Yes}; + use SelectPolicy::{Defer, Exact}; + + fn render(result: Result, Limit>) -> String { + match result { + Ok(ImplSelection::Selected { info, .. }) => format!("selects impl {}", info + 1), + Ok(ImplSelection::Deferred) => "waits".to_owned(), + Ok(ImplSelection::Missing) => "no impl".to_owned(), + Err(Limit) => "work limit".to_owned(), + } + } + + fn describe(outcomes: &[Outcome]) -> String { + if outcomes.is_empty() { + return "no impls".to_owned(); + } + let words: Vec<_> = outcomes + .iter() + .map(|outcome| match outcome { + Yes => "matches", + No => "does not match", + Deferred => "undecided", + }) + .collect(); + words.join(", ") + } + + #[test] + fn selection_outcomes_by_policy() { + let scenarios: &[(&[Outcome], usize)] = &[ + (&[], 100), + (&[No, No], 100), + (&[No, Yes, No], 100), + (&[Yes, Deferred], 100), + (&[Deferred, Yes], 100), + (&[Deferred, No], 100), + (&[No, Yes], 1), + ]; + let mut output = String::new(); + for (outcomes, budget) in scenarios { + let budget_note = if *budget == 1 { + " (budget for one step)" + } else { + "" + }; + output.push_str(&format!( + "{}{budget_note}\n inference: {}\n closed types: {}\n", + describe(outcomes), + render(select(outcomes, Defer, *budget)), + render(select(outcomes, Exact, *budget)), + )); + } + insta::with_settings!({ + description => "Impls in declaration order and how each one matches the arguments. \ + Inference uses SelectPolicy::Defer; entailment and evidence use SelectPolicy::Exact.", + omit_expression => true, + }, { + insta::assert_snapshot!(output); + }); + } + + #[test] + #[should_panic(expected = "impl coherence violated")] + fn exact_stops_the_compiler_on_a_second_match() { + let _ = select(&[Yes, No, Yes], Exact, 100); + } + + #[test] + #[should_panic(expected = "impl coherence violated")] + fn defer_stops_the_compiler_on_a_second_match() { + let _ = select(&[Yes, Deferred, Yes], Defer, 100); + } +} diff --git a/crates/nash-ast/src/snapshots/nash_ast__head__select_tests__selection_outcomes_by_policy.snap b/crates/nash-ast/src/snapshots/nash_ast__head__select_tests__selection_outcomes_by_policy.snap new file mode 100644 index 00000000..e093b735 --- /dev/null +++ b/crates/nash-ast/src/snapshots/nash_ast__head__select_tests__selection_outcomes_by_policy.snap @@ -0,0 +1,25 @@ +--- +source: crates/nash-ast/src/head.rs +description: "Impls in declaration order and how each one matches the arguments. Inference uses SelectPolicy::Defer; entailment and evidence use SelectPolicy::Exact." +--- +no impls + inference: no impl + closed types: no impl +does not match, does not match + inference: no impl + closed types: no impl +does not match, matches, does not match + inference: selects impl 2 + closed types: selects impl 2 +matches, undecided + inference: waits + closed types: selects impl 1 +undecided, matches + inference: waits + closed types: selects impl 2 +undecided, does not match + inference: waits + closed types: no impl +does not match, matches (budget for one step) + inference: work limit + closed types: work limit diff --git a/crates/nash-can/src/entailment.rs b/crates/nash-can/src/entailment.rs index ad107d97..20c49cb6 100644 --- a/crates/nash-can/src/entailment.rs +++ b/crates/nash-can/src/entailment.rs @@ -359,27 +359,27 @@ impl<'a> Resolver<'_, 'a> { .iter() .map(|arg| self.canonical(arg, 0)) .collect::>()?; - let mut selected = None; - for (key, info) in self + let candidates = self .tables .impls_for(wanted.trait_.ok_or(Failure::Missing)?) - { - if let nash_ast::head::Match::Yes(arguments) = nash_ast::head::matches( - &mut nash_ast::head::Canonical(&|typ, class| { - crate::kinds::in_class(self.bump, &self.tables.kinds, typ, class, &class_givens) - }), - key.heads, - &canonical_args, - info.variables.len(), - &mut self.remaining, - ) - .map_err(|_| Failure::Limit)? - { - selected = Some((*info, arguments)); - break; - } - } - let (impl_, arguments) = selected.ok_or(Failure::Missing)?; + .map(|(key, info)| (key.heads, info.variables.len(), *info)); + let selection = nash_ast::head::select_impl( + &mut nash_ast::head::Canonical(&|typ, class| { + crate::kinds::in_class(self.bump, &self.tables.kinds, typ, class, &class_givens) + }), + candidates, + &canonical_args, + &mut self.remaining, + nash_ast::head::SelectPolicy::Exact, + ) + .map_err(|_| Failure::Limit)?; + let nash_ast::head::ImplSelection::Selected { + info: impl_, + arguments, + } = selection + else { + return Err(Failure::Missing); + }; let mut subst = BTreeMap::new(); for (name, argument) in impl_.variables.iter().zip(arguments) { subst.insert(*name, self.term(argument, &BTreeMap::new(), 0)?); diff --git a/crates/nash-solve/src/evidence.rs b/crates/nash-solve/src/evidence.rs index 308036a9..066cce5e 100644 --- a/crates/nash-solve/src/evidence.rs +++ b/crates/nash-solve/src/evidence.rs @@ -301,30 +301,33 @@ impl<'a> Resolver<'_, 'a> { typ: args[0], })); } - let mut selected = None; - for (key, info) in self.tables.impls_for(trait_) { - if let nash_ast::head::Match::Yes(arguments) = nash_ast::head::matches( - &mut nash_ast::head::Canonical(&|typ, class| match nash_can::kinds::repr_of( - self.bump, - &self.tables.kinds, - typ, - ) { - Some(actual) if class.contains(actual) => nash_ast::head::Match::Yes(()), - Some(_) => nash_ast::head::Match::No, - None => nash_ast::head::Match::Deferred, - }), - key.heads, - args, - info.variables.len(), - &mut self.remaining, - ) - .map_err(|_| error(Failure::Limit))? - { - selected = Some((*key, *info, arguments)); - break; - } - } - let (key, info, type_args) = selected.ok_or_else(|| error(Failure::MissingImpl))?; + let candidates = self + .tables + .impls_for(trait_) + .map(|(key, info)| (key.heads, info.variables.len(), (*key, *info))); + let selection = nash_ast::head::select_impl( + &mut nash_ast::head::Canonical(&|typ, class| match nash_can::kinds::repr_of( + self.bump, + &self.tables.kinds, + typ, + ) { + Some(actual) if class.contains(actual) => nash_ast::head::Match::Yes(()), + Some(_) => nash_ast::head::Match::No, + None => nash_ast::head::Match::Deferred, + }), + candidates, + args, + &mut self.remaining, + nash_ast::head::SelectPolicy::Exact, + ) + .map_err(|_| error(Failure::Limit))?; + let nash_ast::head::ImplSelection::Selected { + info: (key, info), + arguments: type_args, + } = selection + else { + return Err(error(Failure::MissingImpl)); + }; let substitution = info .variables .iter() diff --git a/crates/nash-solve/src/resolve.rs b/crates/nash-solve/src/resolve.rs index 60677041..0e4f36ec 100644 --- a/crates/nash-solve/src/resolve.rs +++ b/crates/nash-solve/src/resolve.rs @@ -278,7 +278,7 @@ pub(crate) fn select<'a>( givens: &[crate::preds::Body<'a>], allocated: &mut Vec, ) -> Selection<'a> { - use nash_ast::head::{Match, matches}; + use nash_ast::head::{ImplSelection, SelectPolicy, select_impl}; if args.len() >= 2 { match given_candidates(tables, uf, trait_, args, givens, allocated, &mut { WORK_LIMIT @@ -300,33 +300,28 @@ pub(crate) fn select<'a>( View::Flexible | View::Rigid(_) | View::Application | View::Error ) }); - let mut remaining = WORK_LIMIT; - let mut selected = None; - let mut deferred = false; - for (key, info) in tables.impls_for(trait_) { - match matches( - &mut types, - key.heads, - args, - info.variables.len(), - &mut remaining, - ) { - Err(_) => return Selection::Limit, - Ok(Match::No) => {} - Ok(Match::Deferred) => deferred = true, - Ok(Match::Yes(arguments)) => { - selected = Some(Selection::Impl { - info, - key: *key, - substitution: info.variables.iter().copied().zip(arguments).collect(), - }); - } - } - } - if deferred || (selected.is_none() && unknown_outer) { - Selection::Deferred - } else { - selected.unwrap_or(Selection::Missing) + let candidates = tables + .impls_for(trait_) + .map(|(key, info)| (key.heads, info.variables.len(), (key, *info))); + match select_impl( + &mut types, + candidates, + args, + &mut { WORK_LIMIT }, + SelectPolicy::Defer, + ) { + Err(_) => Selection::Limit, + Ok(ImplSelection::Deferred) => Selection::Deferred, + Ok(ImplSelection::Selected { + info: (key, info), + arguments, + }) => Selection::Impl { + info, + key: *key, + substitution: info.variables.iter().copied().zip(arguments).collect(), + }, + Ok(ImplSelection::Missing) if unknown_outer => Selection::Deferred, + Ok(ImplSelection::Missing) => Selection::Missing, } } diff --git a/crates/nash-solve/tests/inference.rs b/crates/nash-solve/tests/inference.rs index 4c372d6a..29be5f61 100644 --- a/crates/nash-solve/tests/inference.rs +++ b/crates/nash-solve/tests/inference.rs @@ -5266,6 +5266,29 @@ fn representation_classes_select_disjoint_blankets() { ); } +/// A use that requires both disjoint blankets' classes must be reported as a +/// representation contradiction, never reach the selector as two matches. +#[test] +fn contradictory_inferred_classes_do_not_select_both_disjoint_blankets() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Const, Storable, Little) + trait Keep 'a where + keep : 'a -> 'a + impl Keep ('a : Big) where + keep x = x + impl Keep ('a : Little) where + keep x = x + big : Big 'a => 'a -> 'a + big x = x + little : Little 'a => 'a -> 'a + little x = x + bad x = keep (big (little x)) + "# + ); +} + #[test] fn representation_classes_intersect_givens_and_expand_aliases() { assert_inference_snapshot!( diff --git a/crates/nash-solve/tests/snapshots/inference__contradictory_inferred_classes_do_not_select_both_disjoint_blankets.snap b/crates/nash-solve/tests/snapshots/inference__contradictory_inferred_classes_do_not_select_both_disjoint_blankets.snap new file mode 100644 index 00000000..ec836218 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__contradictory_inferred_classes_do_not_select_both_disjoint_blankets.snap @@ -0,0 +1,16 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (Big, Const, Storable, Little)\ntrait Keep 'a where\n keep : 'a -> 'a\nimpl Keep ('a : Big) where\n keep x = x\nimpl Keep ('a : Little) where\n keep x = x\nbig : Big 'a => 'a -> 'a\nbig x = x\nlittle : Little 'a => 'a -> 'a\nlittle x = x\nbad x = keep (big (little x))\n" +info: diagnostic +--- +nash::type::contradictory_representation + + × `bad` requires incompatible representations for `'a`. + ╭─[Main.nash:13:1] + 12 │ little x = x + 13 │ bad x = keep (big (little x)) + · ─── + ╰──── + help: Required: Big, Little. + + Use a consistent representation or convert the value explicitly. From f205096a25e5f4e1aedd2ec2ddd5da3d44b48eeb Mon Sep 17 00:00:00 2001 From: microproofs Date: Mon, 12 Oct 2026 13:45:12 +0700 Subject: [PATCH 11/24] fix(traits): reject contradictory representation contexts on type applications check_representation_consistency only grouped predicates on plain type variables, so a context such as (Big ('f 'a), Little ('f 'a)) passed canonicalization. In inference, the givens then proved an empty representation set, which in_class read as proof of every class: both disjoint blanket impls matched and select_impl stopped the compiler. Group predicates by location-free type identity (nash_ast::same_type) and report the existing contradictory-representation error with the subject type. in_class now asserts the proven set is non-empty. Signed-off-by: microproofs --- .../contradictory-application-contexts.md | 8 +++++ crates/nash-ast/src/evidence.rs | 3 +- crates/nash-ast/src/lib.rs | 1 + crates/nash-can/src/error.rs | 3 +- crates/nash-can/src/kinds.rs | 33 +++++++++++++------ crates/nash-can/tests/kind_predicates.rs | 20 +++++++++++ ...cation_annotation_context_is_rejected.snap | 14 ++++++++ ..._application_impl_context_is_rejected.snap | 14 ++++++++ crates/nash-report/src/canonicalize.rs | 20 ++++++++--- crates/nash-solve/src/resolve.rs | 6 ++++ 10 files changed, 106 insertions(+), 16 deletions(-) create mode 100644 .sampo/changesets/contradictory-application-contexts.md create mode 100644 crates/nash-can/tests/snapshots/kind_predicates__contradictory_application_annotation_context_is_rejected.snap create mode 100644 crates/nash-can/tests/snapshots/kind_predicates__contradictory_application_impl_context_is_rejected.snap diff --git a/.sampo/changesets/contradictory-application-contexts.md b/.sampo/changesets/contradictory-application-contexts.md new file mode 100644 index 00000000..a4f717e4 --- /dev/null +++ b/.sampo/changesets/contradictory-application-contexts.md @@ -0,0 +1,8 @@ +--- +cargo/nash-ast: minor +cargo/nash-can: patch +cargo/nash-report: patch +cargo/nash-solve: patch +--- + +Reject contradictory representation contexts on type applications, such as `(Big ('f 'a), Little ('f 'a))`, with the existing contradictory-representation error. They used to reach impl selection, where an empty proven set matched every disjoint impl. Export `nash_ast::same_type` for location-free type comparison. diff --git a/crates/nash-ast/src/evidence.rs b/crates/nash-ast/src/evidence.rs index 8e812480..83d918ab 100644 --- a/crates/nash-ast/src/evidence.rs +++ b/crates/nash-ast/src/evidence.rs @@ -9,7 +9,8 @@ fn same_types(a: &[&Located>], b: &[&Located>]) -> bool { a.len() == b.len() && a.iter().zip(b).all(|(a, b)| same_type(&a.value, &b.value)) } -fn same_type(a: &Type<'_>, b: &Type<'_>) -> bool { +/// Structural type equality that ignores source locations. +pub fn same_type(a: &Type<'_>, b: &Type<'_>) -> bool { match (a, b) { (Type::Var(a), Type::Var(b)) => a == b, diff --git a/crates/nash-ast/src/lib.rs b/crates/nash-ast/src/lib.rs index 123fd909..975fa4a0 100644 --- a/crates/nash-ast/src/lib.rs +++ b/crates/nash-ast/src/lib.rs @@ -1,4 +1,5 @@ mod evidence; +pub use evidence::same_type; pub mod head; pub mod primitives; diff --git a/crates/nash-can/src/error.rs b/crates/nash-can/src/error.rs index 03075ecc..e46ecc7b 100644 --- a/crates/nash-can/src/error.rs +++ b/crates/nash-can/src/error.rs @@ -191,7 +191,8 @@ pub enum Error<'a> { }, ContradictoryRepresentation { region: Region, - variable: &'a str, + /// A type variable or a type application such as `'f 'a`. + subject: &'a Located>, }, ImplOfBuiltinTrait { region: Region, diff --git a/crates/nash-can/src/kinds.rs b/crates/nash-can/src/kinds.rs index 7c758bcd..c5001b95 100644 --- a/crates/nash-can/src/kinds.rs +++ b/crates/nash-can/src/kinds.rs @@ -1715,24 +1715,37 @@ pub(crate) fn infer_declarations<'a>( } } +/// Every subject of representation predicates, variable or application, +/// must admit at least one representation. fn check_representation_consistency<'a>( predicates: &[Pred<'a>], ) -> Result<(), Vec>> { - let mut admitted = BTreeMap::new(); + let mut admitted: Vec<( + &'a nash_region::Located>, + primitives::ReprSet, + )> = Vec::new(); for pred in predicates { let Some(trait_) = pred.trait_ref().and_then(ReprTrait::of) else { continue; }; - let arg = pred.args()[0]; - if let Type::Var(name) = arg.value { - let previous = admitted.entry(name).or_insert(primitives::ReprSet::ALL); - *previous = previous.intersect(trait_.admits()); - if previous.is_empty() { - return Err(vec![crate::Error::ContradictoryRepresentation { - region: arg.region, - variable: name, - }]); + let subject = pred.args()[0]; + let index = match admitted + .iter() + .position(|(other, _)| nash_ast::same_type(&other.value, &subject.value)) + { + Some(index) => index, + None => { + admitted.push((subject, primitives::ReprSet::ALL)); + admitted.len() - 1 } + }; + let set = &mut admitted[index].1; + *set = set.intersect(trait_.admits()); + if set.is_empty() { + return Err(vec![crate::Error::ContradictoryRepresentation { + region: subject.region, + subject, + }]); } } Ok(()) diff --git a/crates/nash-can/tests/kind_predicates.rs b/crates/nash-can/tests/kind_predicates.rs index 41f2a815..9a423e30 100644 --- a/crates/nash-can/tests/kind_predicates.rs +++ b/crates/nash-can/tests/kind_predicates.rs @@ -143,6 +143,26 @@ fn explicit_representation_contradictions_are_rejected() { check_snapshot!(&bump, "f : (Big 'a, Little 'a) => 'a -> 'a\nf x = x").unwrap_err(); } +#[test] +fn contradictory_application_annotation_context_is_rejected() { + let bump = Bump::new(); + check_snapshot!( + &bump, + "f : (Big ('f 'a), Little ('f 'a)) => 'f 'a -> 'f 'a\nf x = x" + ) + .unwrap_err(); +} + +#[test] +fn contradictory_application_impl_context_is_rejected() { + let bump = Bump::new(); + check_snapshot!( + &bump, + "type box 'f = Box ('f int)\ntrait Keep 'a where\n keep : 'a -> 'a\nimpl (Big ('f int), Little ('f int)) => Keep (box 'f) where\n keep x = x" + ) + .unwrap_err(); +} + #[test] fn trait_parameter_kinds_come_from_method_uses() { let bump = Bump::new(); diff --git a/crates/nash-can/tests/snapshots/kind_predicates__contradictory_application_annotation_context_is_rejected.snap b/crates/nash-can/tests/snapshots/kind_predicates__contradictory_application_annotation_context_is_rejected.snap new file mode 100644 index 00000000..b92159a6 --- /dev/null +++ b/crates/nash-can/tests/snapshots/kind_predicates__contradictory_application_annotation_context_is_rejected.snap @@ -0,0 +1,14 @@ +--- +source: crates/nash-can/tests/kind_predicates.rs +description: "module Main exposing (..)\n\nimport Primitive exposing (..)\nimport Builtin exposing (..)\n\nf : (Big ('f 'a), Little ('f 'a)) => 'f 'a -> 'f 'a\nf x = x\n" +--- +nash::names::contradictory_representation + + × The representation requirements on 'f 'a are incompatible: + ╭─[src/Main.nash:6:27] + 5 │ + 6 │ f : (Big ('f 'a), Little ('f 'a)) => 'f 'a -> 'f 'a + · ───── + 7 │ f x = x + ╰──── + help: Change the incompatible constraints or uses of this type. diff --git a/crates/nash-can/tests/snapshots/kind_predicates__contradictory_application_impl_context_is_rejected.snap b/crates/nash-can/tests/snapshots/kind_predicates__contradictory_application_impl_context_is_rejected.snap new file mode 100644 index 00000000..53513a94 --- /dev/null +++ b/crates/nash-can/tests/snapshots/kind_predicates__contradictory_application_impl_context_is_rejected.snap @@ -0,0 +1,14 @@ +--- +source: crates/nash-can/tests/kind_predicates.rs +description: "module Main exposing (..)\n\nimport Primitive exposing (..)\nimport Builtin exposing (..)\n\ntype box 'f = Box ('f int)\ntrait Keep 'a where\n keep : 'a -> 'a\nimpl (Big ('f int), Little ('f int)) => Keep (box 'f) where\n keep x = x\n" +--- +nash::names::contradictory_representation + + × The representation requirements on 'f Primitive.int are incompatible: + ╭─[src/Main.nash:9:29] + 8 │ keep : 'a -> 'a + 9 │ impl (Big ('f int), Little ('f int)) => Keep (box 'f) where + · ────── + 10 │ keep x = x + ╰──── + help: Change the incompatible constraints or uses of this type. diff --git a/crates/nash-report/src/canonicalize.rs b/crates/nash-report/src/canonicalize.rs index fddddce2..8906b28e 100644 --- a/crates/nash-report/src/canonicalize.rs +++ b/crates/nash-report/src/canonicalize.rs @@ -616,11 +616,23 @@ pub fn to_report_with_name(source: &Source<'_>, error: &Error<'_>, expected_name admitted(*required) ), ), - Error::ContradictoryRepresentation { region, variable } => simple( + Error::ContradictoryRepresentation { region, subject } => simple( "CONTRADICTORY REPRESENTATION", *region, - &format!("The representation requirements on '{variable} are incompatible:"), - "Change the incompatible constraints or uses of this variable.", + &format!( + "The representation requirements on {} are incompatible:", + crate::render_type::can_to_doc( + &crate::localizer::Localizer::default(), + crate::render_type::Ctx::None, + &subject.value, + ) + .render(80, false) + ), + if matches!(subject.value, nash_ast::Type::Var(_)) { + "Change the incompatible constraints or uses of this variable." + } else { + "Change the incompatible constraints or uses of this type." + }, ), Error::IrregularRecursion { region, @@ -1939,7 +1951,7 @@ mod coverage { r2, Error::ContradictoryRepresentation { region: r(), - variable: "a", + subject: &nash_region::Located::at_zero(nash_ast::Type::Var("a")), }, ); } diff --git a/crates/nash-solve/src/resolve.rs b/crates/nash-solve/src/resolve.rs index 0e4f36ec..1c92e5e2 100644 --- a/crates/nash-solve/src/resolve.rs +++ b/crates/nash-solve/src/resolve.rs @@ -242,6 +242,12 @@ impl<'a> nash_ast::head::Types<'a> for ClassedTypes<'_, 'a> { } } } + // Canonicalization rejects contradictory contexts; an empty set would + // otherwise prove every class and select every disjoint impl. + assert!( + !proven.is_empty(), + "contradictory representation givens reached impl selection" + ); if !proven.is_all() && proven.intersect(class) == proven { return Match::Yes(()); } From ba4576789b6b8e589e55a74a9fd51b8f6d78337a Mon Sep 17 00:00:00 2001 From: microproofs Date: Mon, 12 Oct 2026 19:56:23 +0700 Subject: [PATCH 12/24] refactor(types): restore the Elm constraint tree nash-constrain again turns the canonical AST into Elm's constraint tree and nash-solve walks it, in place of direct inference. The generator and walker are the pre-removal files (recursive, Elm order) plus the features added since: SaveType node metadata, module tests (TestScope), overloaded Bool and Unit literals, assert/fail/todo/trace/comptime, native pair patterns, diagnostic regions, alias identity of annotated functions, fix A, gap B, and the step 03/04 machinery. Let branches without definitions record no schemes (decision N4). Types convert once per constraint, as in Elm. Definition types convert on their own, so an annotated definition publishes its declared type: a call with more arguments in the same module no longer replaces an alias in its annotation, and importers find the impls of that alias. Direct inference lost the alias there (regression test added). No existing snapshot changes. Signed-off-by: microproofs --- .sampo/changesets/restore-constraint-tree.md | 6 + SPEC.md | 8 +- crates/nash-constrain/Cargo.toml | 5 +- crates/nash-constrain/src/expression.rs | 1794 +++++++++++++++++ crates/nash-constrain/src/instantiate.rs | 124 +- crates/nash-constrain/src/lib.rs | 13 +- crates/nash-constrain/src/module.rs | 74 +- crates/nash-constrain/src/pattern.rs | 346 ++++ crates/nash-constrain/src/type_.rs | 186 +- crates/nash-driver/src/compile.rs | 2 +- crates/nash-solve/src/lib.rs | 9 +- crates/nash-solve/src/solve.rs | 881 +++++++- crates/nash-solve/src/solve/expressions.rs | 905 --------- crates/nash-solve/src/solve/infer.rs | 1309 ------------ crates/nash-solve/src/solve/patterns.rs | 372 ---- crates/nash-solve/tests/inference.rs | 72 + ...impl_for_importers_after_a_wider_call.snap | 9 + docs/frontend-hardening-verification.md | 17 +- docs/overview.md | 4 +- docs/research/compiler-stack-audit.md | 2 +- .../type-representation-and-evidence.md | 11 +- docs/traits.md | 8 +- plans/07-codegen.md | 5 +- 23 files changed, 3493 insertions(+), 2669 deletions(-) create mode 100644 .sampo/changesets/restore-constraint-tree.md create mode 100644 crates/nash-constrain/src/expression.rs create mode 100644 crates/nash-constrain/src/pattern.rs delete mode 100644 crates/nash-solve/src/solve/expressions.rs delete mode 100644 crates/nash-solve/src/solve/infer.rs delete mode 100644 crates/nash-solve/src/solve/patterns.rs create mode 100644 crates/nash-solve/tests/snapshots/inference__annotated_alias_result_keeps_its_impl_for_importers_after_a_wider_call.snap diff --git a/.sampo/changesets/restore-constraint-tree.md b/.sampo/changesets/restore-constraint-tree.md new file mode 100644 index 00000000..3160b270 --- /dev/null +++ b/.sampo/changesets/restore-constraint-tree.md @@ -0,0 +1,6 @@ +--- +cargo/nash-constrain: minor +cargo/nash-solve: patch +--- + +Restore Elm's constraint tree: `nash-constrain` generates it from the canonical AST and `nash-solve` walks it, in place of direct inference. An annotated definition now publishes its declared type: a call with more arguments in the same module no longer replaces an alias in its annotation, so importers find the impls of that alias. diff --git a/SPEC.md b/SPEC.md index 44ae0619..ece3110b 100644 --- a/SPEC.md +++ b/SPEC.md @@ -8,7 +8,7 @@ component specs in [`docs/`](docs/); chunked implementation plans in ## Pipeline ``` -parse -> canonicalize -> kinds -> direct inference (+ traits) -> nitpick +parse -> canonicalize -> kinds -> constrain + solve (+ traits) -> nitpick -> macro expansion (loop) -> Core IR -> optimize -> UPLC ``` @@ -24,8 +24,8 @@ produce UPLC programs; all dependencies inline into each program. | `nash-parse` | parser + Elm error hierarchy | extend ([plans/01](plans/01-syntax.md)) | | `nash-ast` | canonical AST | extend | | `nash-can` | canonicalization, interfaces | extend | -| `nash-constrain` | union-find types, canonical instantiation, type errors | done | -| `nash-solve` | direct AST inference, traits, defaulting | extend | +| `nash-constrain` | constraint generation, union-find types, canonical instantiation, type errors | done | +| `nash-solve` | constraint solver, traits, defaulting | extend | | `nash-nitpick` | exhaustiveness and redundancy | done ([plans/05](plans/05-nitpick.md)) | | `nash-report` | concise diagnostics (terminal, JSON, LSP) | done ([plans/06](plans/06-diagnostics.md)) | | `nash-ir` | Core IR + passes | new ([plans/07](plans/07-codegen.md), [08](plans/08-optimizer.md)) | @@ -46,7 +46,7 @@ Done: - [x] Parser (Elm `Parse/*` port, full syntax error hierarchy) - [x] Canonicalization (Elm `Canonicalize/*` port, SCC, interfaces) -- [x] Type inference (direct AST inference, rank-based solver, records, aliases) +- [x] Type inference (constraint generation, rank-based solver, records, aliases) - [x] Frontend hardening and direct-inference parity ([verification](docs/frontend-hardening-verification.md)) - [x] Project config, driver, dependency-ordered builds, interface cache - [x] `nash check` diff --git a/crates/nash-constrain/Cargo.toml b/crates/nash-constrain/Cargo.toml index 7129c123..a7c454e3 100644 --- a/crates/nash-constrain/Cargo.toml +++ b/crates/nash-constrain/Cargo.toml @@ -3,8 +3,9 @@ name = "nash-constrain" version = "0.9.0" edition.workspace = true description = """ -Shared union-find types, canonical type instantiation, and diagnostics \ -for direct type inference. +Responsible for building the set of constraints that are used \ +during type inference of a program, and for gathering context \ +needed for pleasant error messages when a type error occurs. """ homepage.workspace = true repository.workspace = true diff --git a/crates/nash-constrain/src/expression.rs b/crates/nash-constrain/src/expression.rs new file mode 100644 index 00000000..57d7282d --- /dev/null +++ b/crates/nash-constrain/src/expression.rs @@ -0,0 +1,1794 @@ +//! Port of Elm's `Type.Constrain.Expression`: turn canonical expressions +//! into constraints. +//! +//! Deviations from Elm: +//! - No `Float`/`Chr` literals, `Negate`, `Shader`, `VarKernel`, `VarDebug`. +//! - Literals are overloaded: a `Foreign` use of a `From*` scheme. +//! - Records are nominal and closed: `Field`/`Record` constraints replace +//! extensible record types. +//! - `Let` carries trait givens and scheme identities. +//! - Every expression constraint is wrapped in `SaveType`. +//! - Recursive definitions keep all header variables in the group's `Let`. + +use bumpalo::Bump; +use nash_ast::{ + CaseBranch, Def as CanDef, Expr as CanExpr, FieldUpdate, FieldValue, IfBranch, NodeId, + TypedPattern, +}; +use nash_region::{Located, Region}; + +use crate::error::{Category, Context, Expected, MaybeName, PContext, PExpected, SubContext}; +use crate::instantiate; +use crate::pattern; +use crate::type_::{self, Constraint, Definition, Type, exists, mk_flex_var, name_to_rigid}; +use crate::union_find::{UnionFind, Variable}; + +/// Elm's `RTV`: rigid type variables introduced by enclosing type +/// annotations, shared with nested annotations. +pub type Rtv<'a> = instantiate::FreeVars<'a>; + +type Exp<'a> = Expected<'a, &'a Type<'a>>; + +pub fn constrain<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + expr: &Located>, + expected: Exp<'a>, +) -> Constraint<'a> { + let region = expr.region; + let node = NodeId::expr(expr); + let typ = expectation_type(expected); + let constraint = match &expr.value { + CanExpr::VarLocal(name) => Constraint::Local(region, node, name, expected), + + CanExpr::VarTopLevel(reference) => { + Constraint::Local(region, node, reference.name, expected) + } + + CanExpr::VarForeign { + reference, + annotation, + } => Constraint::Foreign(region, node, reference.name, annotation, expected), + + CanExpr::VarMethod { + method, annotation, .. + } => Constraint::Foreign(region, node, method, annotation, expected), + + CanExpr::VarConstructor { + reference, + annotation, + .. + } => Constraint::Foreign(region, node, reference.name, annotation, expected), + + CanExpr::VarOperator { + symbol, annotation, .. + } => Constraint::Foreign(region, node, symbol, annotation, expected), + + CanExpr::Str(_) + | CanExpr::Bytes(_) + | CanExpr::Int(_) + | CanExpr::Bool(_) + | CanExpr::Unit => { + let (name, trait_) = match &expr.value { + CanExpr::Str(_) => ("fromString", "FromString"), + CanExpr::Bytes(_) => ("fromBytes", "FromBytes"), + CanExpr::Bool(_) => ("fromBool", "FromBool"), + CanExpr::Unit => ("fromUnit", "FromUnit"), + _ => ("fromInt", "FromInt"), + }; + Constraint::Foreign( + region, + node, + name, + type_::literal_annotation(bump, &[type_::literal_trait(trait_)]), + expected, + ) + } + + CanExpr::List(elements) => constrain_list(bump, uf, rtv, region, elements, expected), + + CanExpr::Binop { + symbol, + annotation, + left, + right, + .. + } => constrain_binop( + bump, uf, rtv, region, node, symbol, annotation, left, right, expected, + ), + + CanExpr::Lambda { parameters, body } => { + constrain_lambda(bump, uf, rtv, region, parameters, body, expected) + } + + CanExpr::Call { + function, + arguments, + } => constrain_call(bump, uf, rtv, region, function, arguments, expected), + + CanExpr::If { + branches, + final_else, + } => constrain_if(bump, uf, rtv, region, branches, final_else, expected), + + CanExpr::Case { + scrutinee, + branches, + } => constrain_case(bump, uf, rtv, region, scrutinee, branches, expected), + + CanExpr::Let { definition, body } => { + let body_con = constrain(bump, uf, rtv, body, expected); + constrain_def(bump, uf, rtv, definition, body_con) + } + + CanExpr::LetRec { definitions, body } => { + let body_con = constrain(bump, uf, rtv, body, expected); + constrain_recursive_defs(bump, uf, rtv, definitions, body_con) + } + + CanExpr::LetDestruct { + pattern, + value, + body, + } => { + let body_con = constrain(bump, uf, rtv, body, expected); + constrain_destruct(bump, uf, rtv, region, pattern, value, body_con) + } + + CanExpr::Accessor(field) => { + let record_var = mk_flex_var(uf); + let field_var = mk_flex_var(uf); + let record_type: &'a Type<'a> = bump.alloc(Type::VarN(record_var)); + let field_type: &'a Type<'a> = bump.alloc(Type::VarN(field_var)); + exists( + bump, + bump.alloc_slice_copy(&[record_var, field_var]), + c_and( + bump, + vec![ + Constraint::Field { + region, + context: type_::FieldContext::Accessor, + record: record_type, + field, + field_type, + }, + Constraint::Equal( + region, + Category::Accessor(field), + bump.alloc(Type::FunN(record_type, field_type)), + expected, + ), + ], + ), + ) + } + + CanExpr::Access { record, field } => { + let record_var = mk_flex_var(uf); + let field_var = mk_flex_var(uf); + let record_type: &'a Type<'a> = bump.alloc(Type::VarN(record_var)); + let field_type: &'a Type<'a> = bump.alloc(Type::VarN(field_var)); + let record_con = constrain(bump, uf, rtv, record, Expected::NoExpectation(record_type)); + exists( + bump, + bump.alloc_slice_copy(&[record_var, field_var]), + c_and( + bump, + vec![ + record_con, + Constraint::Field { + region, + context: type_::FieldContext::Access { + record_region: record.region, + maybe_name: get_access_name(record), + }, + record: record_type, + field: field.value, + field_type, + }, + Constraint::Equal( + region, + Category::Access(field.value), + field_type, + expected, + ), + ], + ), + ) + } + + CanExpr::Update { + record, + base, + fields, + } => constrain_update(bump, uf, rtv, region, record, base, fields, expected), + + CanExpr::Record { + alias, + annotation, + fields, + } => constrain_record( + bump, uf, rtv, region, node, *alias, annotation, fields, expected, + ), + + CanExpr::Assert(condition) => c_and( + bump, + vec![ + constrain( + bump, + uf, + rtv, + condition, + Expected::NoExpectation(bump.alloc(type_::bool())), + ), + Constraint::Equal(region, Category::Unit, bump.alloc(type_::unit()), expected), + ], + ), + + CanExpr::Fail(message) | CanExpr::Todo(message) => { + message.map_or(Constraint::True, |msg| { + constrain( + bump, + uf, + rtv, + msg, + Expected::NoExpectation(bump.alloc(Type::AppN { + home: nash_ast::primitives::primitive_home(), + name: "string", + args: &[], + })), + ) + }) + } + + CanExpr::Trace { message, body } => c_and( + bump, + vec![ + constrain( + bump, + uf, + rtv, + message, + Expected::NoExpectation(bump.alloc(Type::AppN { + home: nash_ast::primitives::primitive_home(), + name: "string", + args: &[], + })), + ), + constrain(bump, uf, rtv, body, expected), + ], + ), + + CanExpr::Comptime(inner) => constrain(bump, uf, rtv, inner, expected), + + CanExpr::Tuple { + first, + second, + rest, + } => constrain_tuple(bump, uf, rtv, region, first, second, rest, expected), + }; + Constraint::SaveType { + node, + kind: type_::NodeKind::Expression, + typ, + constraint: bump.alloc(constraint), + } +} + +// HELPERS + +fn c_and<'a>(bump: &'a Bump, cons: Vec>) -> Constraint<'a> { + Constraint::And(bump.alloc_slice_fill_iter(cons)) +} + +fn expectation_type<'a>(expected: Exp<'a>) -> &'a Type<'a> { + match expected { + Expected::NoExpectation(typ) + | Expected::FromContext(_, _, typ) + | Expected::FromAnnotation(_, _, _, _, typ) => typ, + } +} + +fn singleton_header<'a>( + bump: &'a Bump, + name: &'a str, + region: Region, + tipe: &'a Type<'a>, +) -> &'a [(&'a str, Located<&'a Type<'a>>)] { + bump.alloc_slice_copy(&[(name, Located::at(region, tipe))]) +} + +fn header_slice<'a>( + bump: &'a Bump, + headers: pattern::Header<'a>, +) -> &'a [(&'a str, Located<&'a Type<'a>>)] { + bump.alloc_slice_fill_iter(headers) +} + +fn reversed_and<'a>(bump: &'a Bump, mut rev_cons: Vec>) -> Constraint<'a> { + rev_cons.reverse(); + c_and(bump, rev_cons) +} + +// CONSTRAIN LAMBDA + +fn constrain_lambda<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + region: Region, + args: &[&Located>], + body: &Located>, + expected: Exp<'a>, +) -> Constraint<'a> { + let Args { + vars, + tipe, + result_type, + state, + } = constrain_args(bump, uf, args); + + let body_con = constrain(bump, uf, rtv, body, Expected::NoExpectation(result_type)); + + exists( + bump, + bump.alloc_slice_fill_iter(vars), + c_and( + bump, + vec![ + Constraint::Let { + declarations: &[], + given: &[], + binder: None, + definitions: &[], + rigid_vars: &[], + flex_vars: bump.alloc_slice_fill_iter(state.vars), + header: header_slice(bump, state.headers), + header_con: bump.alloc(reversed_and(bump, state.rev_cons)), + body_con: bump.alloc(body_con), + }, + Constraint::Equal(region, Category::Lambda, tipe, expected), + ], + ), + ) +} + +// CONSTRAIN CALL + +fn constrain_call<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + region: Region, + func: &Located>, + args: &[&Located>], + expected: Exp<'a>, +) -> Constraint<'a> { + let maybe_name = get_name(func); + let func_region = func.region; + + let func_var = mk_flex_var(uf); + let result_var = mk_flex_var(uf); + let func_type: &'a Type<'a> = bump.alloc(Type::VarN(func_var)); + let result_type: &'a Type<'a> = bump.alloc(Type::VarN(result_var)); + + let func_con = constrain(bump, uf, rtv, func, Expected::NoExpectation(func_type)); + + let mut arg_vars = Vec::with_capacity(args.len()); + let mut arg_types = Vec::with_capacity(args.len()); + let mut arg_cons = Vec::with_capacity(args.len()); + for (index, arg) in args.iter().enumerate() { + let arg_var = mk_flex_var(uf); + let arg_type: &'a Type<'a> = bump.alloc(Type::VarN(arg_var)); + let arg_con = constrain( + bump, + uf, + rtv, + arg, + Expected::FromContext(region, Context::CallArg(maybe_name, index), arg_type), + ); + arg_vars.push(arg_var); + arg_types.push(arg_type); + arg_cons.push(arg_con); + } + + let arity_type = arg_types.iter().rev().fold(result_type, |acc, arg_type| { + bump.alloc(Type::FunN(arg_type, acc)) + }); + let category = Category::CallResult(maybe_name); + + let mut vars = vec![func_var, result_var]; + vars.extend(arg_vars); + + exists( + bump, + bump.alloc_slice_fill_iter(vars), + c_and( + bump, + vec![ + func_con, + Constraint::Equal( + func_region, + category, + func_type, + Expected::FromContext( + region, + Context::CallArity(maybe_name, args.len()), + arity_type, + ), + ), + c_and(bump, arg_cons), + Constraint::Equal(region, category, result_type, expected), + ], + ), + ) +} + +fn get_name<'a>(func: &Located>) -> MaybeName<'a> { + match &func.value { + CanExpr::VarMethod { method, .. } => MaybeName::FuncName(method), + CanExpr::VarLocal(name) => MaybeName::FuncName(name), + CanExpr::VarTopLevel(reference) => MaybeName::FuncName(reference.name), + CanExpr::VarForeign { reference, .. } => MaybeName::FuncName(reference.name), + CanExpr::VarConstructor { reference, .. } => MaybeName::CtorName(reference.name), + CanExpr::VarOperator { symbol, .. } => MaybeName::OpName(symbol), + _ => MaybeName::NoName, + } +} + +fn get_access_name<'a>(record: &Located>) -> Option<&'a str> { + match &record.value { + CanExpr::VarLocal(name) => Some(name), + CanExpr::VarTopLevel(reference) => Some(reference.name), + CanExpr::VarForeign { reference, .. } => Some(reference.name), + _ => None, + } +} + +// CONSTRAIN BINOP + +#[allow(clippy::too_many_arguments)] +fn constrain_binop<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + region: Region, + node: NodeId, + op: &'a str, + annotation: &'a nash_ast::Annotation<'a>, + left_expr: &Located>, + right_expr: &Located>, + expected: Exp<'a>, +) -> Constraint<'a> { + let left_var = mk_flex_var(uf); + let right_var = mk_flex_var(uf); + let answer_var = mk_flex_var(uf); + let left_type: &'a Type<'a> = bump.alloc(Type::VarN(left_var)); + let right_type: &'a Type<'a> = bump.alloc(Type::VarN(right_var)); + let answer_type: &'a Type<'a> = bump.alloc(Type::VarN(answer_var)); + let binop_type: &'a Type<'a> = bump.alloc(Type::FunN( + left_type, + bump.alloc(Type::FunN(right_type, answer_type)), + )); + + let op_con = Constraint::Foreign( + region, + node, + op, + annotation, + Expected::NoExpectation(binop_type), + ); + + let left_con = constrain( + bump, + uf, + rtv, + left_expr, + Expected::FromContext(region, Context::OpLeft(op), left_type), + ); + let right_con = constrain( + bump, + uf, + rtv, + right_expr, + Expected::FromContext(region, Context::OpRight(op), right_type), + ); + + exists( + bump, + bump.alloc_slice_copy(&[left_var, right_var, answer_var]), + c_and( + bump, + vec![ + op_con, + left_con, + right_con, + Constraint::Equal( + region, + Category::CallResult(MaybeName::OpName(op)), + answer_type, + expected, + ), + ], + ), + ) +} + +// CONSTRAIN LISTS + +fn constrain_list<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + region: Region, + entries: &[&Located>], + expected: Exp<'a>, +) -> Constraint<'a> { + let entry_var = mk_flex_var(uf); + let entry_type: &'a Type<'a> = bump.alloc(Type::VarN(entry_var)); + let list_type: &'a Type<'a> = bump.alloc(type_::list(bump, entry_type)); + + let entry_cons = entries + .iter() + .enumerate() + .map(|(index, entry)| { + constrain( + bump, + uf, + rtv, + entry, + Expected::FromContext( + region, + Context::ListEntry(index, index.checked_sub(1).map(|i| entries[i].region)), + entry_type, + ), + ) + }) + .collect(); + + exists( + bump, + bump.alloc_slice_copy(&[entry_var]), + c_and( + bump, + vec![ + c_and(bump, entry_cons), + Constraint::Equal(region, Category::List, list_type, expected), + ], + ), + ) +} + +// CONSTRAIN IF EXPRESSIONS + +fn constrain_if<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + region: Region, + branches: &[IfBranch<'a>], + final_else: &Located>, + expected: Exp<'a>, +) -> Constraint<'a> { + let bool_type: &'a Type<'a> = bump.alloc(type_::bool()); + let cond_cons: Vec> = branches + .iter() + .map(|branch| { + constrain( + bump, + uf, + rtv, + branch.condition, + Expected::FromContext(region, Context::IfCondition, bool_type), + ) + }) + .collect(); + + let exprs: Vec<&Located>> = branches + .iter() + .map(|branch| branch.then_branch) + .chain(std::iter::once(final_else)) + .collect(); + + match expected { + Expected::FromAnnotation(name, annotation_region, arity, _, tipe) => { + let branch_cons = exprs + .iter() + .enumerate() + .map(|(index, branch_expr)| { + constrain( + bump, + uf, + rtv, + branch_expr, + Expected::FromAnnotation( + name, + annotation_region, + arity, + SubContext::TypedIfBranch(index), + tipe, + ), + ) + }) + .collect(); + c_and(bump, vec![c_and(bump, cond_cons), c_and(bump, branch_cons)]) + } + + _ => { + let branch_var = mk_flex_var(uf); + let branch_type: &'a Type<'a> = bump.alloc(Type::VarN(branch_var)); + + let branch_cons = exprs + .iter() + .enumerate() + .map(|(index, branch_expr)| { + constrain( + bump, + uf, + rtv, + branch_expr, + Expected::FromContext( + region, + Context::IfBranch(index, index.checked_sub(1).map(|i| exprs[i].region)), + branch_type, + ), + ) + }) + .collect(); + + exists( + bump, + bump.alloc_slice_copy(&[branch_var]), + c_and( + bump, + vec![ + c_and(bump, cond_cons), + c_and(bump, branch_cons), + Constraint::Equal(region, Category::If, branch_type, expected), + ], + ), + ) + } + } +} + +// CONSTRAIN CASE EXPRESSIONS + +fn constrain_case<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + region: Region, + expr: &Located>, + branches: &[CaseBranch<'a>], + expected: Exp<'a>, +) -> Constraint<'a> { + let ptrn_var = mk_flex_var(uf); + let ptrn_type: &'a Type<'a> = bump.alloc(Type::VarN(ptrn_var)); + let expr_con = constrain(bump, uf, rtv, expr, Expected::NoExpectation(ptrn_type)); + + match expected { + Expected::FromAnnotation(name, annotation_region, arity, _, tipe) => { + let mut cons = vec![expr_con]; + for (index, branch) in branches.iter().enumerate() { + cons.push(constrain_case_branch( + bump, + uf, + rtv, + branch, + PExpected::FromContext(region, PContext::CaseMatch(index), ptrn_type), + Expected::FromAnnotation( + name, + annotation_region, + arity, + SubContext::TypedCaseBranch(index), + tipe, + ), + )); + } + exists(bump, bump.alloc_slice_copy(&[ptrn_var]), c_and(bump, cons)) + } + + _ => { + let branch_var = mk_flex_var(uf); + let branch_type: &'a Type<'a> = bump.alloc(Type::VarN(branch_var)); + + let mut branch_cons = Vec::with_capacity(branches.len()); + for (index, branch) in branches.iter().enumerate() { + branch_cons.push(constrain_case_branch( + bump, + uf, + rtv, + branch, + PExpected::FromContext(region, PContext::CaseMatch(index), ptrn_type), + Expected::FromContext( + region, + Context::CaseBranch( + index, + index.checked_sub(1).map(|i| branches[i].body.region), + ), + branch_type, + ), + )); + } + + exists( + bump, + bump.alloc_slice_copy(&[ptrn_var, branch_var]), + c_and( + bump, + vec![ + expr_con, + c_and(bump, branch_cons), + Constraint::Equal(region, Category::Case, branch_type, expected), + ], + ), + ) + } + } +} + +fn constrain_case_branch<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + branch: &CaseBranch<'a>, + p_expect: PExpected<'a, &'a Type<'a>>, + b_expect: Exp<'a>, +) -> Constraint<'a> { + let state = pattern::add(bump, uf, branch.pattern, p_expect, pattern::empty_state()); + + let body_con = constrain(bump, uf, rtv, branch.body, b_expect); + + Constraint::Let { + declarations: &[], + given: &[], + binder: None, + definitions: &[], + rigid_vars: &[], + flex_vars: bump.alloc_slice_fill_iter(state.vars), + header: header_slice(bump, state.headers), + header_con: bump.alloc(reversed_and(bump, state.rev_cons)), + body_con: bump.alloc(body_con), + } +} + +// CONSTRAIN RECORD + +#[allow(clippy::too_many_arguments)] +fn constrain_record<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + region: Region, + node: NodeId, + alias: nash_ast::QualifiedName<'a>, + annotation: &'a nash_ast::Annotation<'a>, + fields: &[FieldValue<'a>], + expected: Exp<'a>, +) -> Constraint<'a> { + let mut vars = Vec::with_capacity(fields.len() + 1); + let mut cons = Vec::with_capacity(fields.len() + 2); + let mut args = Vec::with_capacity(fields.len()); + for field in fields { + let var = mk_flex_var(uf); + let typ: &'a Type<'a> = bump.alloc(Type::VarN(var)); + vars.push(var); + args.push(typ); + cons.push(constrain( + bump, + uf, + rtv, + field.value, + Expected::FromContext( + region, + Context::RecordField(alias.name, field.field.value), + typ, + ), + )); + } + let result = mk_flex_var(uf); + vars.push(result); + let result_type: &'a Type<'a> = bump.alloc(Type::VarN(result)); + let ctor_type = args.into_iter().rev().fold(result_type, |result, arg| { + &*bump.alloc(Type::FunN(arg, result)) + }); + cons.push(Constraint::Foreign( + region, + node, + alias.name, + annotation, + Expected::NoExpectation(ctor_type), + )); + cons.push(Constraint::Equal( + region, + Category::Record, + result_type, + expected, + )); + exists(bump, bump.alloc_slice_fill_iter(vars), c_and(bump, cons)) +} + +// CONSTRAIN RECORD UPDATE + +#[allow(clippy::too_many_arguments)] +fn constrain_update<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + region: Region, + name: &'a str, + expr: &Located>, + fields: &'a [FieldUpdate<'a>], + expected: Exp<'a>, +) -> Constraint<'a> { + let record_var = mk_flex_var(uf); + let record_type: &'a Type<'a> = bump.alloc(Type::VarN(record_var)); + let mut vars = vec![record_var]; + let mut cons = vec![constrain( + bump, + uf, + rtv, + expr, + Expected::FromContext(region, Context::RecordUpdateKeys(name, fields), record_type), + )]; + if fields.is_empty() { + cons.push(Constraint::Record { + region, + context: type_::FieldContext::Update { record: name }, + record: record_type, + }); + } + for field in fields { + let var = mk_flex_var(uf); + vars.push(var); + let field_type: &'a Type<'a> = bump.alloc(Type::VarN(var)); + cons.push(constrain( + bump, + uf, + rtv, + field.value, + Expected::FromContext( + region, + Context::RecordUpdateValue(field.field.value), + field_type, + ), + )); + cons.push(Constraint::Field { + region: field.field.region, + context: type_::FieldContext::Update { record: name }, + record: record_type, + field: field.field.value, + field_type, + }); + } + cons.push(Constraint::Equal( + region, + Category::Record, + record_type, + expected, + )); + exists(bump, bump.alloc_slice_fill_iter(vars), c_and(bump, cons)) +} + +// CONSTRAIN TUPLE + +#[allow(clippy::too_many_arguments)] +fn constrain_tuple<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + region: Region, + a: &Located>, + b: &Located>, + rest: &[&Located>], + expected: Exp<'a>, +) -> Constraint<'a> { + let a_var = mk_flex_var(uf); + let b_var = mk_flex_var(uf); + let a_type: &'a Type<'a> = bump.alloc(Type::VarN(a_var)); + let b_type: &'a Type<'a> = bump.alloc(Type::VarN(b_var)); + + let a_con = constrain(bump, uf, rtv, a, Expected::NoExpectation(a_type)); + let b_con = constrain(bump, uf, rtv, b, Expected::NoExpectation(b_type)); + + let mut vars = vec![a_var, b_var]; + let mut cons = vec![a_con, b_con]; + let mut types = Vec::with_capacity(rest.len()); + for item in rest { + let var = mk_flex_var(uf); + let tipe: &'a Type<'a> = bump.alloc(Type::VarN(var)); + vars.push(var); + types.push(tipe); + cons.push(constrain( + bump, + uf, + rtv, + item, + Expected::NoExpectation(tipe), + )); + } + let tuple_type = bump.alloc(Type::TupleN(a_type, b_type, bump.alloc_slice_copy(&types))); + cons.push(Constraint::Equal( + region, + Category::Tuple, + tuple_type, + expected, + )); + exists(bump, bump.alloc_slice_copy(&vars), c_and(bump, cons)) +} + +// CONSTRAIN DESTRUCTURES + +fn constrain_destruct<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + region: Region, + pattern_ast: &Located>, + expr: &Located>, + body_con: Constraint<'a>, +) -> Constraint<'a> { + let pattern_var = mk_flex_var(uf); + let pattern_type: &'a Type<'a> = bump.alloc(Type::VarN(pattern_var)); + + let mut state = pattern::add( + bump, + uf, + pattern_ast, + PExpected::NoExpectation(pattern_type), + pattern::empty_state(), + ); + + let expr_con = constrain( + bump, + uf, + rtv, + expr, + Expected::FromContext(region, Context::Destructure, pattern_type), + ); + + let mut flex_vars = vec![pattern_var]; + flex_vars.append(&mut state.vars); + + // Elm: `CAnd (reverse (exprCon:revCons))` — exprCon runs last. + let mut cons = state.rev_cons; + cons.reverse(); + cons.push(expr_con); + + let binder = type_::Binder::Pattern { + node: NodeId::pattern(pattern_ast), + name: bump.alloc(Located::at(region, "")), + }; + Constraint::Let { + declarations: &[], + given: &[], + binder: Some(binder), + definitions: bump.alloc_slice_copy(&[Definition { + site: binder, + typ: pattern_type, + context: None, + }]), + rigid_vars: &[], + flex_vars: bump.alloc_slice_fill_iter(flex_vars), + header: header_slice(bump, state.headers), + header_con: bump.alloc(c_and(bump, cons)), + body_con: bump.alloc(body_con), + } +} + +// CONSTRAIN DEF + +pub fn constrain_def<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + def: &CanDef<'a>, + body_con: Constraint<'a>, +) -> Constraint<'a> { + constrain_definition(bump, uf, rtv, def, body_con, true) +} + +/// Check a method body in the module environment without introducing its +/// name as a top-level value. Its annotation is already specialized for +/// the enclosing trait or impl by canonicalization. +pub fn constrain_method<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + def: &CanDef<'a>, +) -> Constraint<'a> { + assert!(matches!(def, CanDef::TypedDef { .. })); + constrain_definition(bump, uf, &Rtv::new(), def, Constraint::True, false) +} + +/// Nash-only module test scope. Elm has no source-level test declarations. +pub fn constrain_test<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + test: &'a nash_ast::Test<'a>, +) -> Constraint<'a> { + let unit = bump.alloc(type_::unit()); + let binder = type_::Binder::Named(test.name); + let mut flex_vars = Vec::new(); + let mut prefix = Vec::new(); + let mut state = pattern::empty_state(); + + for via in test.binders { + let element_var = mk_flex_var(uf); + flex_vars.push(element_var); + let element = bump.alloc(Type::VarN(element_var)); + let prng = bump.alloc(Type::AppN { + home: nash_ast::ModuleName { + package: Some(nash_ast::primitives::BASE), + name: "Prop", + }, + name: "prng", + args: &[], + }); + let pair = bump.alloc(Type::TupleN(element, prng, &[])); + let result = bump.alloc(Type::AppN { + home: nash_ast::ModuleName { + package: Some(nash_ast::primitives::BASE), + name: "Option", + }, + name: "option", + args: bump.alloc_slice_copy(&[&*pair]), + }); + let generator = bump.alloc(Type::FunN(prng, result)); + prefix.push(constrain( + bump, + uf, + &Rtv::new(), + via.generator, + Expected::FromContext(via.generator.region, Context::TestGenerator, generator), + )); + state = pattern::add( + bump, + uf, + via.pattern, + PExpected::NoExpectation(element), + state, + ); + } + + let body = constrain( + bump, + uf, + &Rtv::new(), + test.body, + Expected::FromContext(test.region, Context::TestBody, unit), + ); + prefix.push(Constraint::Let { + declarations: &[], + given: &[], + binder: None, + definitions: &[], + rigid_vars: &[], + flex_vars: bump.alloc_slice_fill_iter(state.vars), + header: header_slice(bump, state.headers), + header_con: bump.alloc(reversed_and(bump, state.rev_cons)), + body_con: bump.alloc(body), + }); + Constraint::TestScope(bump.alloc(Constraint::Let { + declarations: &[], + given: &[], + binder: Some(binder), + definitions: bump.alloc_slice_copy(&[Definition { + site: binder, + typ: unit, + context: None, + }]), + rigid_vars: &[], + flex_vars: bump.alloc_slice_fill_iter(flex_vars), + header: &[], + header_con: bump.alloc(c_and(bump, prefix)), + body_con: bump.alloc(Constraint::True), + })) +} + +fn constrain_definition<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + def: &CanDef<'a>, + body_con: Constraint<'a>, + bind_name: bool, +) -> Constraint<'a> { + match def { + CanDef::Def { name, args, body } => { + let Args { + vars, + tipe, + result_type, + state, + } = constrain_args(bump, uf, args); + + let expr_con = constrain(bump, uf, rtv, body, Expected::NoExpectation(result_type)); + + Constraint::Let { + declarations: &[], + given: &[], + binder: Some(type_::Binder::Named(name)), + definitions: bump.alloc_slice_copy(&[Definition { + site: type_::Binder::Named(name), + typ: tipe, + context: None, + }]), + rigid_vars: &[], + flex_vars: bump.alloc_slice_fill_iter(vars), + header: if bind_name { + singleton_header(bump, name.value, name.region, tipe) + } else { + &[] + }, + header_con: bump.alloc(Constraint::Let { + declarations: &[], + given: &[], + binder: None, + definitions: &[], + rigid_vars: &[], + flex_vars: bump.alloc_slice_fill_iter(state.vars), + header: header_slice(bump, state.headers), + header_con: bump.alloc(reversed_and(bump, state.rev_cons)), + body_con: bump.alloc(expr_con), + }), + body_con: bump.alloc(body_con), + } + } + + CanDef::TypedDef { + name, + free_vars, + context, + args, + body, + typ: src_result_type, + annotation, + .. + } => { + let (new_rigids, new_rtv) = make_rigids(bump, uf, rtv, free_vars); + + let TypedArgs { + tipe, + result_type, + state, + } = constrain_typed_args( + bump, + uf, + &new_rtv, + name.value, + args, + src_result_type, + annotation, + ); + + let expected = Expected::FromAnnotation( + name.value, + annotation.region, + args.len(), + SubContext::TypedBody, + result_type, + ); + let expr_con = constrain(bump, uf, &new_rtv, body, expected); + let given = instantiate::from_src_context(bump, &new_rtv, context); + + Constraint::Let { + declarations: &[], + given, + binder: Some(type_::Binder::Named(name)), + definitions: bump.alloc_slice_copy(&[Definition { + site: type_::Binder::Named(name), + typ: tipe, + context: Some(given), + }]), + rigid_vars: bump.alloc_slice_fill_iter(new_rigids.iter().map(|(_, var)| *var)), + flex_vars: &[], + header: if bind_name { + singleton_header(bump, name.value, name.region, tipe) + } else { + &[] + }, + header_con: bump.alloc(Constraint::Let { + declarations: &[], + given: &[], + binder: None, + definitions: &[], + rigid_vars: &[], + flex_vars: bump.alloc_slice_fill_iter(state.vars), + header: header_slice(bump, state.headers), + header_con: bump.alloc(reversed_and(bump, state.rev_cons)), + body_con: bump.alloc(expr_con), + }), + body_con: bump.alloc(body_con), + } + } + } +} + +/// Elm: `newNames = Map.difference freeVars rtv` then `nameToRigid` per +/// name in `Map` (name-sorted) order. +fn make_rigids<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + free_vars: &[&'a str], +) -> (Vec<(&'a str, Variable)>, Rtv<'a>) { + let mut new_names: Vec<&'a str> = free_vars + .iter() + .filter(|name| !rtv.contains_key(*name)) + .copied() + .collect(); + new_names.sort_unstable(); + + let new_rigids: Vec<(&'a str, Variable)> = new_names + .into_iter() + .map(|name| (name, name_to_rigid(uf, name))) + .collect(); + + let mut new_rtv = rtv.clone(); + for (name, var) in &new_rigids { + new_rtv.insert(name, bump.alloc(Type::VarN(*var))); + } + + (new_rigids, new_rtv) +} + +// CONSTRAIN RECURSIVE DEFS + +struct Info<'a> { + definitions: Vec>, + vars: Vec, + cons: Vec>, + headers: pattern::Header<'a>, +} + +impl<'a> Info<'a> { + fn empty() -> Info<'a> { + Info { + definitions: Vec::new(), + vars: Vec::new(), + cons: Vec::new(), + headers: pattern::Header::new(), + } + } +} + +pub fn constrain_recursive_defs<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + defs: &[&CanDef<'a>], + body_con: Constraint<'a>, +) -> Constraint<'a> { + let mut rigid_info = Info::empty(); + let mut flex_info = Info::empty(); + + for def in defs { + match def { + CanDef::Def { name, args, body } => { + let Args { + vars: new_flex_vars, + tipe, + result_type, + state, + } = constrain_args(bump, uf, args); + + let expr_con = constrain(bump, uf, rtv, body, Expected::NoExpectation(result_type)); + + let def_con = Constraint::Let { + declarations: &[], + given: &[], + binder: None, + definitions: &[], + rigid_vars: &[], + flex_vars: bump.alloc_slice_fill_iter(state.vars), + header: header_slice(bump, state.headers), + header_con: bump.alloc(reversed_and(bump, state.rev_cons)), + body_con: bump.alloc(expr_con), + }; + + // All recursive headers share one rank until every body has + // been checked. Introducing an earlier header's variables in a + // later definition's pattern scope can generalize them early. + flex_info.vars.extend(new_flex_vars); + flex_info.cons.push(def_con); + flex_info.definitions.push(Definition { + site: type_::Binder::Named(name), + typ: tipe, + context: None, + }); + flex_info + .headers + .insert(name.value, Located::at(name.region, tipe)); + } + + CanDef::TypedDef { + name, + free_vars, + context, + args, + body, + typ: src_result_type, + annotation, + .. + } => { + let (new_rigids, new_rtv) = make_rigids(bump, uf, rtv, free_vars); + + let TypedArgs { + tipe, + result_type, + state, + } = constrain_typed_args( + bump, + uf, + &new_rtv, + name.value, + args, + src_result_type, + annotation, + ); + + let expr_con = constrain( + bump, + uf, + &new_rtv, + body, + Expected::FromAnnotation( + name.value, + annotation.region, + args.len(), + SubContext::TypedBody, + result_type, + ), + ); + + let def_con = Constraint::Let { + declarations: &[], + given: &[], + binder: None, + definitions: &[], + rigid_vars: &[], + flex_vars: bump.alloc_slice_fill_iter(state.vars), + header: header_slice(bump, state.headers), + header_con: bump.alloc(reversed_and(bump, state.rev_cons)), + body_con: bump.alloc(expr_con), + }; + + let given = instantiate::from_src_context(bump, &new_rtv, context); + + // Elm prepends each def's rigids: latest def first, names + // sorted within a def. + let mut vars: Vec = new_rigids.iter().map(|(_, var)| *var).collect(); + vars.append(&mut rigid_info.vars); + rigid_info.vars = vars; + rigid_info.definitions.push(Definition { + site: type_::Binder::Named(name), + typ: tipe, + context: Some(given), + }); + rigid_info.cons.push(Constraint::Let { + declarations: &[], + given, + binder: Some(type_::Binder::Named(name)), + definitions: bump.alloc_slice_copy(&[Definition { + site: type_::Binder::Named(name), + typ: tipe, + context: Some(given), + }]), + rigid_vars: bump.alloc_slice_fill_iter(new_rigids.iter().map(|(_, var)| *var)), + flex_vars: &[], + header: &[], + header_con: bump.alloc(def_con), + body_con: bump.alloc(Constraint::True), + }); + rigid_info + .headers + .insert(name.value, Located::at(name.region, tipe)); + } + } + } + + // Elm builds the cons lists by prepending, so they end up latest-first. + rigid_info.cons.reverse(); + flex_info.cons.reverse(); + + let flex_headers = header_slice(bump, flex_info.headers); + let flex_definitions = bump.alloc_slice_fill_iter(flex_info.definitions); + Constraint::Let { + declarations: bump.alloc_slice_fill_iter(rigid_info.definitions), + given: &[], + binder: None, + definitions: &[], + rigid_vars: bump.alloc_slice_fill_iter(rigid_info.vars), + flex_vars: &[], + header: header_slice(bump, rigid_info.headers), + header_con: bump.alloc(Constraint::True), + body_con: bump.alloc(Constraint::Let { + declarations: &[], + given: &[], + binder: flex_definitions.first().map(|def| def.site), + definitions: flex_definitions, + rigid_vars: &[], + flex_vars: bump.alloc_slice_fill_iter(flex_info.vars), + header: flex_headers, + header_con: bump.alloc(Constraint::Let { + declarations: flex_definitions, + given: &[], + binder: None, + definitions: &[], + rigid_vars: &[], + flex_vars: &[], + header: flex_headers, + header_con: bump.alloc(Constraint::True), + body_con: bump.alloc(c_and(bump, flex_info.cons)), + }), + body_con: bump.alloc(c_and(bump, vec![c_and(bump, rigid_info.cons), body_con])), + }), + } +} + +// CONSTRAIN ARGS + +struct Args<'a> { + vars: Vec, + tipe: &'a Type<'a>, + result_type: &'a Type<'a>, + state: pattern::State<'a>, +} + +fn constrain_args<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + args: &[&Located>], +) -> Args<'a> { + args_help(bump, uf, args, pattern::empty_state()) +} + +fn args_help<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + args: &[&Located>], + state: pattern::State<'a>, +) -> Args<'a> { + let mut arg_vars = Vec::with_capacity(args.len()); + let mut arg_types: Vec<&'a Type<'a>> = Vec::with_capacity(args.len()); + + let mut state = state; + for arg_pattern in args { + let arg_var = mk_flex_var(uf); + let arg_type: &'a Type<'a> = bump.alloc(Type::VarN(arg_var)); + state = pattern::add( + bump, + uf, + arg_pattern, + PExpected::NoExpectation(arg_type), + state, + ); + arg_vars.push(arg_var); + arg_types.push(arg_type); + } + + let result_var = mk_flex_var(uf); + let result_type: &'a Type<'a> = bump.alloc(Type::VarN(result_var)); + + let tipe = arg_types.iter().rev().fold(result_type, |acc, arg_type| { + bump.alloc(Type::FunN(arg_type, acc)) + }); + + let mut vars = arg_vars; + vars.push(result_var); + + Args { + vars, + tipe, + result_type, + state, + } +} + +// CONSTRAIN TYPED ARGS + +struct TypedArgs<'a> { + tipe: &'a Type<'a>, + result_type: &'a Type<'a>, + state: pattern::State<'a>, +} + +fn constrain_typed_args<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + rtv: &Rtv<'a>, + name: &'a str, + args: &[TypedPattern<'a>], + src_result_type: &Located>, + annotation: &Located>, +) -> TypedArgs<'a> { + let mut state = pattern::empty_state(); + + for (index, arg) in args.iter().enumerate() { + let arg_type = instantiate::from_src_type(bump, rtv, arg.typ); + let expected = PExpected::FromContext( + arg.pattern.region, + PContext::TypedArg(name, index, annotation.region), + arg_type, + ); + state = pattern::add(bump, uf, arg.pattern, expected, state); + } + + let result_type = instantiate::from_src_type(bump, rtv, src_result_type); + + // Nash-only: retain an annotated alias around the whole function. Splitting + // arguments can otherwise expand an alias that has trait implementations. + let tipe = instantiate::from_src_type(bump, rtv, annotation); + + TypedArgs { + tipe, + result_type, + state, + } +} + +#[cfg(test)] +mod node_tests { + use super::*; + use nash_ast::{Annotation, ModuleName, QualifiedName}; + + #[test] + fn prepared_rigids_preserve_order_captures_and_predicate_substitution() { + let bump = Bump::new(); + let mut uf = UnionFind::new(); + let captured = name_to_rigid(&mut uf, "captured"); + let rtv = Rtv::from([("captured", &*bump.alloc(Type::VarN(captured)))]); + let var = |name| &*bump.alloc(Located::at_zero(nash_ast::Type::Var(name))); + let (z, cap, a) = (var("z"), var("captured"), var("a")); + let result = &*bump.alloc(Located::at_zero(nash_ast::Type::App { + head: z, + args: bump.alloc_slice_copy(&[cap, a]), + })); + let definition = CanDef::TypedDef { + name: bump.alloc(Located::at_zero("test")), + free_vars: &["z", "captured", "a"], + context: bump.alloc_slice_copy(&[nash_ast::Pred::Apply { + head: z, + args: bump.alloc_slice_copy(&[cap, a]), + }]), + annotation: result, + args: &[], + body: bump.alloc(Located::at_zero(CanExpr::Unit)), + typ: result, + }; + let variable = |typ: &Type<'_>| { + let Type::VarN(variable) = typ else { + panic!("type variable") + }; + *variable + }; + let mut prepare = || { + let Constraint::Let { + given, + definitions, + rigid_vars, + .. + } = constrain_def(&bump, &mut uf, &rtv, &definition, Constraint::True) + else { + panic!("definition scope") + }; + let [type_::Pred::Apply { head, args }] = given else { + panic!("Apply context") + }; + let Type::AppVarN(type_head, type_args) = definitions[0].typ else { + panic!("signature application") + }; + assert_eq!(variable(type_head), variable(head)); + assert_eq!( + type_args + .iter() + .map(|arg| variable(arg)) + .collect::>(), + args.iter().map(|arg| variable(arg)).collect::>() + ); + let [ + type_::Pred::Apply { + head: declared_head, + args: declared_args, + }, + ] = definitions[0].context.expect("declared context") + else { + panic!("declared Apply context") + }; + assert_eq!(variable(declared_head), variable(head)); + assert_eq!( + declared_args + .iter() + .map(|arg| variable(arg)) + .collect::>(), + args.iter().map(|arg| variable(arg)).collect::>() + ); + ( + rigid_vars, + variable(head), + args.iter().map(|arg| variable(arg)).collect::>(), + ) + }; + let (rigids, head, args) = prepare(); + let (other_rigids, other_head, other_args) = prepare(); + assert_eq!(rigids.len(), 2); + assert!(matches!( + uf.get(rigids[0]).content, + type_::Content::RigidVar("a") + )); + assert!(matches!( + uf.get(rigids[1]).content, + type_::Content::RigidVar("z") + )); + assert_eq!(head, rigids[1]); + assert_eq!(args, [captured, rigids[0]]); + assert_eq!(other_args[0], captured); + assert_ne!(other_args[1], args[1]); + assert_ne!(other_head, head); + assert_eq!(other_rigids, [other_args[1], other_head]); + } + + #[test] + fn literals_and_patterns_keep_original_nodes_and_ordered_predicates() { + let bump = Bump::new(); + for (expr, pattern, trait_name) in [ + (CanExpr::Int(7), nash_ast::Pattern::Int(7), "FromInt"), + ( + CanExpr::Bytes(&[0, 255]), + nash_ast::Pattern::Bytes(&[0, 255]), + "FromBytes", + ), + ( + CanExpr::Str("nash"), + nash_ast::Pattern::Str("nash"), + "FromString", + ), + ] { + let expr = bump.alloc(Located::at_zero(expr)); + let pattern = bump.alloc(Located::at_zero(pattern)); + let mut uf = UnionFind::new(); + let expected = bump.alloc(Type::VarN(mk_flex_var(&mut uf))); + let constraint = constrain( + &bump, + &mut uf, + &Rtv::new(), + expr, + Expected::NoExpectation(expected), + ); + let Constraint::SaveType { constraint, .. } = constraint else { + panic!("saved literal type") + }; + let Constraint::Foreign(_, node, _, annotation, _) = constraint else { + panic!("literal scheme") + }; + assert_eq!(*node, NodeId::expr(expr)); + assert_eq!(annotation.context.len(), 1); + assert_eq!(annotation.context[0].trait_ref().unwrap().name, trait_name); + assert_eq!( + annotation.context[0].trait_ref().unwrap().home.package, + Some(nash_ast::primitives::BASE) + ); + let state = pattern::add( + &bump, + &mut uf, + pattern, + PExpected::NoExpectation(expected), + pattern::empty_state(), + ); + let annotations: Vec<_> = state + .rev_cons + .iter() + .filter_map(|c| match c { + Constraint::Foreign(_, node, _, annotation, _) => { + assert_eq!(*node, NodeId::pattern(pattern)); + Some(annotation) + } + _ => None, + }) + .collect(); + assert_eq!(annotations.len(), 1, "one evidence instance per pattern"); + assert_eq!( + annotations[0] + .context + .iter() + .map(|p| p.trait_ref().unwrap().name) + .collect::>(), + [trait_name, "Eq"] + ); + // The solver instantiates scheme variables by name, so both + // predicates use one substitution when they name one variable. + let annotation = annotations[0]; + let [variable] = annotation.free_vars else { + panic!("one literal variable") + }; + for pred in annotation.context { + assert!(matches!( + pred.args(), + [arg] if matches!(arg.value, nash_ast::Type::Var(name) if name == *variable) + )); + } + } + } + + fn uses(constraint: &Constraint<'_>, nodes: &mut Vec) { + match constraint { + Constraint::Local(_, node, ..) | Constraint::Foreign(_, node, ..) => nodes.push(*node), + Constraint::And(constraints) => { + for constraint in *constraints { + uses(constraint, nodes); + } + } + Constraint::Let { + header_con, + body_con, + .. + } => { + uses(header_con, nodes); + uses(body_con, nodes); + } + Constraint::SaveType { constraint, .. } | Constraint::TestScope(constraint) => { + uses(constraint, nodes) + } + _ => {} + } + } + + #[test] + fn operator_and_method_uses_keep_distinct_node_identity_at_the_same_region() { + let bump = Bump::new(); + let region = Region::zero(); + let reference = QualifiedName { + home: ModuleName { + package: None, + name: "Main", + }, + name: "Combine", + }; + let annotation = bump.alloc(Annotation { + context: &[], + free_vars: &[], + typ: bump.alloc(Located::at(region, nash_ast::Type::unit())), + }); + let local = bump.alloc(Located::at(region, CanExpr::VarLocal("x"))); + let method = bump.alloc(Located::at( + region, + CanExpr::VarMethod { + trait_: reference, + method: "combine", + annotation, + }, + )); + let operator = bump.alloc(Located::at( + region, + CanExpr::Binop { + symbol: "+", + operator_home: reference.home, + reference, + annotation, + left: local, + right: method, + }, + )); + let mut uf = UnionFind::new(); + let constraint = constrain( + &bump, + &mut uf, + &Rtv::new(), + operator, + Expected::NoExpectation(bump.alloc(crate::type_::unit())), + ); + let mut nodes = Vec::new(); + uses(&constraint, &mut nodes); + assert_eq!( + nodes, + [ + NodeId::expr(operator), + NodeId::expr(local), + NodeId::expr(method) + ] + ); + } +} diff --git a/crates/nash-constrain/src/instantiate.rs b/crates/nash-constrain/src/instantiate.rs index ac9ddaa8..2fefc99d 100644 --- a/crates/nash-constrain/src/instantiate.rs +++ b/crates/nash-constrain/src/instantiate.rs @@ -1,14 +1,132 @@ -//! Instantiate canonical types directly into union-find variables. +//! Instantiate canonical types into the constraint language or directly into +//! union-find variables. use std::collections::BTreeMap; -#[cfg(test)] use bumpalo::Bump; -use nash_ast::Type as CanType; +use nash_ast::{AliasType as CanAliasType, Type as CanType}; use nash_region::Located; +use crate::type_::Type; use crate::{Content, FlatType, UnionFind, Variable}; +pub type FreeVars<'a> = BTreeMap<&'a str, &'a Type<'a>>; + +pub fn from_src_context<'a>( + bump: &'a Bump, + rtv: &FreeVars<'a>, + context: &[nash_ast::Pred<'a>], +) -> &'a [crate::type_::Pred<'a>] { + bump.alloc_slice_fill_iter(context.iter().map(|pred| { + let args = + bump.alloc_slice_fill_iter(pred.args().iter().map(|arg| from_src_type(bump, rtv, arg))); + match *pred { + nash_ast::Pred::Trait { trait_, .. } => crate::type_::Pred::Trait { + trait_, + args, + hidden: false, + }, + nash_ast::Pred::Implied { trait_, .. } => crate::type_::Pred::Trait { + trait_, + args, + hidden: true, + }, + nash_ast::Pred::Apply { head, .. } => crate::type_::Pred::Apply { + head: from_src_type(bump, rtv, head), + args, + }, + } + })) +} + +pub fn from_src_type<'a>( + bump: &'a Bump, + free_vars: &FreeVars<'a>, + src_type: &Located>, +) -> &'a Type<'a> { + match &src_type.value { + CanType::App { head, args } => bump.alloc(Type::AppVarN( + from_src_type(bump, free_vars, head), + bump.alloc_slice_fill_iter(args.iter().map(|arg| from_src_type(bump, free_vars, arg))), + )), + CanType::Lambda { from, to } => bump.alloc(Type::FunN( + from_src_type(bump, free_vars, from), + from_src_type(bump, free_vars, to), + )), + CanType::Var(name) => free_vars + .get(name) + .expect("canonical types only mention their free variables"), + CanType::Named { reference, args } => bump.alloc(Type::AppN { + home: reference.home, + name: reference.name, + args: bump + .alloc_slice_fill_iter(args.iter().map(|arg| from_src_type(bump, free_vars, arg))), + }), + CanType::Alias { + reference, + arguments, + remaining, + target, + } => { + let targs = bump.alloc_slice_fill_iter( + arguments + .iter() + .map(|arg| (arg.name, from_src_type(bump, free_vars, arg.typ))), + ); + let body = match target { + CanAliasType::Open(body) | CanAliasType::Filled { body, .. } => *body, + }; + if !remaining.is_empty() { + assert!( + matches!(target, CanAliasType::Open(_)), + "partial alias body must be closed" + ); + return bump.alloc(Type::PartialAliasN { + home: reference.home, + name: reference.name, + args: targs, + remaining, + body, + }); + } + let real = match target { + CanAliasType::Filled { typ: real_type, .. } => { + from_src_type(bump, free_vars, real_type) + } + CanAliasType::Open(real_type) => { + let arg_vars: FreeVars<'a> = targs.iter().copied().collect(); + from_src_type(bump, &arg_vars, real_type) + } + }; + bump.alloc(Type::AliasN { + home: reference.home, + name: reference.name, + args: targs, + real, + body, + }) + } + CanType::Tuple { + first, + second, + rest, + } => bump.alloc(Type::TupleN( + from_src_type(bump, free_vars, first), + from_src_type(bump, free_vars, second), + bump.alloc_slice_fill_iter( + rest.iter().map(|item| from_src_type(bump, free_vars, item)), + ), + )), + CanType::Record { fields } => bump.alloc(Type::RecordN { + fields: bump.alloc_slice_fill_iter( + fields + .iter() + .map(|field| (field.field, from_src_type(bump, free_vars, field.typ))), + ), + }), + } +} + /// A nominal alias application inspected without allocating inference variables. pub struct AliasApplication<'a> { pub home: nash_ast::ModuleName<'a>, diff --git a/crates/nash-constrain/src/lib.rs b/crates/nash-constrain/src/lib.rs index e90c98fe..721f09d1 100644 --- a/crates/nash-constrain/src/lib.rs +++ b/crates/nash-constrain/src/lib.rs @@ -1,16 +1,25 @@ -//! Shared union-find types, canonical instantiation, and inference diagnostics. +//! Constraint generation for Nash type inference: a port of Elm's +//! `Type.Constrain.*` plus the shared vocabulary from `Type.Type`, +//! `Type.UnionFind`, `Type.Error`, and `Reporting.Error.Type`. +//! +//! Where Elm creates unification variables in ambient `IO`, Nash threads an +//! explicit [`UnionFind`] store: [`constrain`] fills it with fresh variables +//! and `nash-solve` mutates it while it walks the returned [`Constraint`]. pub mod error; pub mod error_type; pub mod instantiate; pub mod module; +pub mod pattern; pub mod type_; +mod expression; mod union_find; pub use crate::error::{ Category, Context, Error, Expected, MaybeName, PCategory, PContext, PExpected, SubContext, }; pub use crate::error_type::ErrorType; -pub use crate::type_::{Content, Descriptor, FlatType, Mark}; +pub use crate::module::constrain; +pub use crate::type_::{Constraint, Content, Descriptor, FlatType, Mark, Type}; pub use crate::union_find::{UnionFind, Variable}; diff --git a/crates/nash-constrain/src/module.rs b/crates/nash-constrain/src/module.rs index 07de94aa..65f78a6d 100644 --- a/crates/nash-constrain/src/module.rs +++ b/crates/nash-constrain/src/module.rs @@ -1,13 +1,83 @@ -//! Post-solve validator entry-point checks. These do not instantiate or default types. +//! Constraint generation for a module, plus post-solve validator entry-point checks. use crate::Error; use bumpalo::Bump; use nash_ast::{ - AliasType, Annotation, Module, ModuleKind, Pred, Type, + AliasType, Annotation, Decls, Module, ModuleKind, Pred, Type, primitives::{Repr, ReprSet, ReprTrait}, }; use nash_can::kinds::{KindEnv, TypeInfo}; use nash_region::Located; +use crate::UnionFind; +use crate::expression; +use crate::type_::Constraint; + +/// Elm's `Type.Constrain.Module`, extended with Nash trait methods and tests. +pub fn constrain<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + module: &Module<'a>, +) -> Constraint<'a> { + let definitions = module + .traits + .iter() + .flat_map(|trait_| { + trait_ + .value + .methods + .iter() + .filter_map(|method| method.default) + }) + .chain( + module + .impls + .iter() + .flat_map(|impl_| impl_.value.methods.iter().copied()), + ); + let mut tail: Vec<_> = definitions + .map(|definition| expression::constrain_method(bump, uf, definition)) + .collect(); + tail.extend( + module + .tests + .iter() + .map(|test| expression::constrain_test(bump, uf, test)), + ); + tail.push(Constraint::SaveTheEnvironment); + constrain_decls( + bump, + uf, + module.decls, + Constraint::And(bump.alloc_slice_fill_iter(tail)), + ) +} + +fn constrain_decls<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + decls: &Decls<'a>, + final_constraint: Constraint<'a>, +) -> Constraint<'a> { + match decls { + Decls::Declare { definition, next } => { + let next_con = constrain_decls(bump, uf, next, final_constraint); + expression::constrain_def(bump, uf, &expression::Rtv::new(), definition, next_con) + } + Decls::DeclareRec { + definition, + following, + next, + } => { + let next_con = constrain_decls(bump, uf, next, final_constraint); + let mut defs = Vec::with_capacity(1 + following.len()); + defs.push(*definition); + defs.extend(following.iter().copied()); + expression::constrain_recursive_defs(bump, uf, &expression::Rtv::new(), &defs, next_con) + } + Decls::Empty => final_constraint, + } +} + /// Check the solved lambda spine of a validator's main before code generation. /// An unconstrained variable remains polymorphic here; validator code generation /// chooses its boundary instantiation. Normal module roots are never defaulted. diff --git a/crates/nash-constrain/src/pattern.rs b/crates/nash-constrain/src/pattern.rs new file mode 100644 index 00000000..202c1ec7 --- /dev/null +++ b/crates/nash-constrain/src/pattern.rs @@ -0,0 +1,346 @@ +//! Port of Elm's `Type.Constrain.Pattern`: turn a canonical pattern into +//! binding headers plus the constraints its structure implies. + +use std::collections::BTreeMap; + +use bumpalo::Bump; +use nash_ast::{Pattern as CanPattern, PatternCtor}; +use nash_region::{Located, Region}; + +use crate::error::{Expected, PCategory, PContext, PExpected}; +use crate::instantiate; +use crate::type_::{self, Constraint, Type, mk_flex_var, name_to_flex}; +use crate::union_find::{UnionFind, Variable}; + +/// Elm's `Pattern.State`. Constraints are stored in reverse order so that +/// adding one is O(1); callers reverse when building the final `CLet`. +pub struct State<'a> { + pub headers: Header<'a>, + pub vars: Vec, + pub rev_cons: Vec>, +} + +pub type Header<'a> = BTreeMap<&'a str, Located<&'a Type<'a>>>; + +pub fn empty_state<'a>() -> State<'a> { + State { + headers: BTreeMap::new(), + vars: Vec::new(), + rev_cons: Vec::new(), + } +} + +pub fn add<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + pattern: &Located>, + expectation: PExpected<'a, &'a Type<'a>>, + state: State<'a>, +) -> State<'a> { + let region = pattern.region; + let typ = get_type(expectation); + let mut state = state; + state.rev_cons.push(Constraint::SaveType { + node: nash_ast::NodeId::pattern(pattern), + kind: type_::NodeKind::Pattern, + typ, + constraint: bump.alloc(Constraint::True), + }); + match &pattern.value { + CanPattern::Anything => state, + + CanPattern::Var(name) => add_to_headers(region, name, expectation, state), + + CanPattern::Alias { + pattern: real_pattern, + name, + } => { + let state = add_to_headers(region, name, expectation, state); + add(bump, uf, real_pattern, expectation, state) + } + + CanPattern::Unit => { + let mut state = state; + let unit_con = Constraint::Pattern( + region, + PCategory::Unit, + bump.alloc(crate::type_::unit()), + expectation, + ); + state.rev_cons.push(unit_con); + state + } + + // Nash-only: Elm has tuples but no native pair pattern. + CanPattern::Pair { first, second } => { + let first_var = mk_flex_var(uf); + let second_var = mk_flex_var(uf); + let first_type = bump.alloc(Type::VarN(first_var)); + let second_type = bump.alloc(Type::VarN(second_var)); + let pair_type = bump.alloc(Type::AppN { + home: nash_ast::primitives::primitive_home(), + name: "pair", + args: bump.alloc_slice_copy(&[&*first_type, &*second_type]), + }); + let state = add(bump, uf, first, PExpected::NoExpectation(first_type), state); + let mut state = add( + bump, + uf, + second, + PExpected::NoExpectation(second_type), + state, + ); + state.vars.extend([first_var, second_var]); + state.rev_cons.push(Constraint::Pattern( + region, + PCategory::Pair, + pair_type, + expectation, + )); + state + } + + CanPattern::Tuple { + first, + second, + rest, + } => add_tuple(bump, uf, region, first, second, rest, expectation, state), + + CanPattern::Constructor(ctor) => add_ctor(bump, uf, region, ctor, expectation, state), + + CanPattern::List(patterns) => { + let entry_var = mk_flex_var(uf); + let entry_type: &'a Type<'a> = bump.alloc(Type::VarN(entry_var)); + let list_type: &'a Type<'a> = bump.alloc(type_::list(bump, entry_type)); + + let mut state = + patterns + .iter() + .enumerate() + .fold(state, |state, (index, entry_pattern)| { + let expectation = + PExpected::FromContext(region, PContext::ListEntry(index), entry_type); + add(bump, uf, entry_pattern, expectation, state) + }); + + let list_con = Constraint::Pattern(region, PCategory::List, list_type, expectation); + state.vars.push(entry_var); + state.rev_cons.push(list_con); + state + } + + CanPattern::Cons { head, tail } => { + let entry_var = mk_flex_var(uf); + let entry_type: &'a Type<'a> = bump.alloc(Type::VarN(entry_var)); + let list_type: &'a Type<'a> = bump.alloc(type_::list(bump, entry_type)); + + let head_expectation = PExpected::NoExpectation(entry_type); + let tail_expectation = PExpected::FromContext(region, PContext::Tail, list_type); + + let state = add(bump, uf, tail, tail_expectation, state); + let mut state = add(bump, uf, head, head_expectation, state); + + let list_con = Constraint::Pattern(region, PCategory::List, list_type, expectation); + state.vars.push(entry_var); + state.rev_cons.push(list_con); + state + } + + CanPattern::Record(fields) => { + let mut state = state; + let record_var = mk_flex_var(uf); + let record_type: &'a Type<'a> = bump.alloc(Type::VarN(record_var)); + state.vars.push(record_var); + state.rev_cons.push(Constraint::Pattern( + region, + PCategory::Record, + record_type, + expectation, + )); + if fields.is_empty() { + state.rev_cons.push(Constraint::Record { + region, + context: type_::FieldContext::Pattern, + record: record_type, + }); + } + for field in *fields { + let var = mk_flex_var(uf); + let field_type: &'a Type<'a> = bump.alloc(Type::VarN(var)); + state.vars.push(var); + state + .headers + .entry(*field) + .or_insert_with(|| Located::at(region, field_type)); + state.rev_cons.push(Constraint::Field { + region, + context: type_::FieldContext::Pattern, + record: record_type, + field, + field_type, + }); + } + state + } + + CanPattern::Int(_) | CanPattern::Str(_) | CanPattern::Bytes(_) => { + let (trait_name, category) = match pattern.value { + CanPattern::Int(_) => ("FromInt", PCategory::Int), + CanPattern::Bytes(_) => ("FromBytes", PCategory::Bytes), + _ => ("FromString", PCategory::Str), + }; + let mut state = state; + let var = mk_flex_var(uf); + let typ: &'a Type<'a> = bump.alloc(Type::VarN(var)); + state.vars.push(var); + state + .rev_cons + .push(Constraint::Pattern(region, category, typ, expectation)); + state.rev_cons.push(Constraint::Foreign( + region, + nash_ast::NodeId::pattern(pattern), + "literal", + type_::literal_annotation( + bump, + &[type_::literal_trait(trait_name), type_::eq_trait()], + ), + Expected::NoExpectation(typ), + )); + state + } + + CanPattern::Bool { .. } => { + let mut state = state; + let bool_con = Constraint::Pattern( + region, + PCategory::Bool, + bump.alloc(type_::bool()), + expectation, + ); + state.rev_cons.push(bool_con); + state + } + } +} + +// STATE HELPERS + +fn add_to_headers<'a>( + region: Region, + name: &'a str, + expectation: PExpected<'a, &'a Type<'a>>, + mut state: State<'a>, +) -> State<'a> { + let tipe = get_type(expectation); + state.headers.insert(name, Located::at(region, tipe)); + state +} + +fn get_type<'a>(expectation: PExpected<'a, &'a Type<'a>>) -> &'a Type<'a> { + match expectation { + PExpected::NoExpectation(tipe) => tipe, + PExpected::FromContext(_, _, tipe) => tipe, + } +} + +// CONSTRAIN TUPLE + +#[allow(clippy::too_many_arguments)] +fn add_tuple<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + region: Region, + a: &Located>, + b: &Located>, + rest: &[&Located>], + expectation: PExpected<'a, &'a Type<'a>>, + state: State<'a>, +) -> State<'a> { + let a_var = mk_flex_var(uf); + let b_var = mk_flex_var(uf); + let a_type: &'a Type<'a> = bump.alloc(Type::VarN(a_var)); + let b_type: &'a Type<'a> = bump.alloc(Type::VarN(b_var)); + + let state = simple_add(bump, uf, a, a_type, state); + let mut state = simple_add(bump, uf, b, b_type, state); + state.vars.extend([a_var, b_var]); + let mut types = Vec::with_capacity(rest.len()); + for item in rest { + let var = mk_flex_var(uf); + let tipe: &'a Type<'a> = bump.alloc(Type::VarN(var)); + state = simple_add(bump, uf, item, tipe, state); + state.vars.push(var); + types.push(tipe); + } + state.rev_cons.push(Constraint::Pattern( + region, + PCategory::Tuple, + bump.alloc(Type::TupleN(a_type, b_type, bump.alloc_slice_copy(&types))), + expectation, + )); + state +} + +fn simple_add<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + pattern: &Located>, + pattern_type: &'a Type<'a>, + state: State<'a>, +) -> State<'a> { + add( + bump, + uf, + pattern, + PExpected::NoExpectation(pattern_type), + state, + ) +} + +// CONSTRAIN CONSTRUCTORS + +fn add_ctor<'a>( + bump: &'a Bump, + uf: &mut UnionFind<'a>, + region: Region, + ctor: &PatternCtor<'a>, + expectation: PExpected<'a, &'a Type<'a>>, + state: State<'a>, +) -> State<'a> { + let home = ctor.reference.home; + let type_name = ctor.reference.union; + let ctor_name = ctor.reference.name; + + let var_pairs: Vec<(&'a str, Variable)> = ctor + .union + .parameters + .iter() + .map(|var| (*var, name_to_flex(uf, var))) + .collect(); + let type_pairs: Vec<(&'a str, &'a Type<'a>)> = var_pairs + .iter() + .map(|(name, var)| (*name, &*bump.alloc(Type::VarN(*var)))) + .collect(); + let free_var_dict: instantiate::FreeVars<'a> = type_pairs.iter().copied().collect(); + + let mut state = ctor.arguments.iter().fold(state, |state, arg| { + let tipe = instantiate::from_src_type(bump, &free_var_dict, arg.typ); + let arg_expectation = PExpected::FromContext( + region, + PContext::CtorArg(ctor_name, arg.index as usize), + tipe, + ); + add(bump, uf, arg.pattern, arg_expectation, state) + }); + + let ctor_type: &'a Type<'a> = bump.alloc(Type::AppN { + home, + name: type_name, + args: bump.alloc_slice_fill_iter(type_pairs.iter().map(|(_, typ)| *typ)), + }); + let ctor_con = Constraint::Pattern(region, PCategory::Ctor(ctor_name), ctor_type, expectation); + + state.vars.extend(var_pairs.iter().map(|(_, var)| *var)); + state.rev_cons.push(ctor_con); + state +} diff --git a/crates/nash-constrain/src/type_.rs b/crates/nash-constrain/src/type_.rs index 948c157b..9962a475 100644 --- a/crates/nash-constrain/src/type_.rs +++ b/crates/nash-constrain/src/type_.rs @@ -1,4 +1,5 @@ -//! Union-find type descriptors, scheme identities, and literal annotations. +//! Port of the data half of Elm's `Type.Type`: constraints, the inference +//! `Type` language, and unification variable descriptors. //! //! `toAnnotation` and `toErrorType` live in `nash-solve` (they are only //! called by the solver and need `nash-can`'s canonical-type utilities). @@ -8,10 +9,25 @@ use std::collections::BTreeMap; use nash_ast::{Annotation, ModuleName, NodeId, QualifiedName}; use nash_region::{Located, Region}; +use crate::error::{Category, Expected, PCategory, PExpected}; use crate::union_find::{UnionFind, Variable}; // CONSTRAINTS +/// An annotation predicate instantiated over the definition's rigid variables. +#[derive(Clone, Copy, Debug)] +pub enum Pred<'a> { + Trait { + trait_: QualifiedName<'a>, + args: &'a [&'a Type<'a>], + hidden: bool, + }, + Apply { + head: &'a Type<'a>, + args: &'a [&'a Type<'a>], + }, +} + /// Scheme identity is an original definition name or a destructuring pattern. #[derive(Clone, Copy, Debug)] pub enum Binder<'a> { @@ -37,6 +53,108 @@ impl<'a> Binder<'a> { } } +/// Preserve the original scheme identity and full type independently of lexical scope. +#[derive(Clone, Copy, Debug)] +pub struct Definition<'a> { + pub site: Binder<'a>, + pub typ: &'a Type<'a>, + /// `Some`, including an empty slice, distinguishes a declared scheme. + pub context: Option<&'a [Pred<'a>]>, +} + +/// Elm's `Type.Constraint`. Allocated in a bump arena, so collections are +/// slices, not owned containers. +#[derive(Debug)] +pub enum Constraint<'a> { + Record { + region: Region, + context: FieldContext<'a>, + record: &'a Type<'a>, + }, + Field { + region: Region, + context: FieldContext<'a>, + record: &'a Type<'a>, + field: &'a str, + field_type: &'a Type<'a>, + }, + True, + SaveTheEnvironment, + Equal( + Region, + Category<'a>, + &'a Type<'a>, + Expected<'a, &'a Type<'a>>, + ), + Local(Region, NodeId, &'a str, Expected<'a, &'a Type<'a>>), + Foreign( + Region, + NodeId, + &'a str, + &'a Annotation<'a>, + Expected<'a, &'a Type<'a>>, + ), + Pattern( + Region, + PCategory<'a>, + &'a Type<'a>, + PExpected<'a, &'a Type<'a>>, + ), + And(&'a [Constraint<'a>]), + Let { + /// Recursive binding identities published before checking group bodies. + /// Annotated declarations also supply their final contexts immediately. + declarations: &'a [Definition<'a>], + /// Assumed while checking the definition body, over its rigid variables. + given: &'a [Pred<'a>], + /// Evidence owner; the first untyped member for a recursive group. + binder: Option>, + /// All definitions generalized here, even when no lexical name is bound. + definitions: &'a [Definition<'a>], + rigid_vars: &'a [Variable], + flex_vars: &'a [Variable], + /// Name-sorted, mirroring Elm's `Map.Map Name (A.Located Type)`. + header: &'a [(&'a str, Located<&'a Type<'a>>)], + header_con: &'a Constraint<'a>, + body_con: &'a Constraint<'a>, + }, + /// Nash only: record the solved type of an expression or pattern node for + /// `SolvedTypes`. Elm does not keep the type of each node. + SaveType { + node: NodeId, + kind: NodeKind, + typ: &'a Type<'a>, + constraint: &'a Constraint<'a>, + }, + /// Nash only: module tests see test-only fields. + TestScope(&'a Constraint<'a>), +} + +#[derive(Clone, Copy, Debug)] +pub enum NodeKind { + Expression, + Pattern, +} + +/// Elm's `exists`: a `CLet` binding only flex variables. +pub fn exists<'a>( + bump: &'a bumpalo::Bump, + flex_vars: &'a [Variable], + constraint: Constraint<'a>, +) -> Constraint<'a> { + Constraint::Let { + declarations: &[], + given: &[], + binder: None, + definitions: &[], + rigid_vars: &[], + flex_vars, + header: &[], + header_con: bump.alloc(constraint), + body_con: bump.alloc(Constraint::True), + } +} + // TYPE PRIMITIVES #[derive(Clone, Copy, Debug)] @@ -63,6 +181,40 @@ pub enum FlatType<'a> { Tuple1(Variable, Variable, Vec), } +/// Elm's `Type.Type`: the language the constraint generator writes types in. +#[derive(Clone, Copy, Debug)] +pub enum Type<'a> { + PartialAliasN { + home: ModuleName<'a>, + name: &'a str, + args: &'a [(&'a str, &'a Type<'a>)], + remaining: &'a [&'a str], + body: &'a Located>, + }, + /// Nash only: the application of a type variable. + AppVarN(&'a Type<'a>, &'a [&'a Type<'a>]), + AliasN { + home: ModuleName<'a>, + name: &'a str, + args: &'a [(&'a str, &'a Type<'a>)], + real: &'a Type<'a>, + body: &'a Located>, + }, + VarN(Variable), + AppN { + home: ModuleName<'a>, + name: &'a str, + args: &'a [&'a Type<'a>], + }, + FunN(&'a Type<'a>, &'a Type<'a>), + /// Name-sorted, mirroring Elm's `Map.Map Name Type`. Records are closed, so + /// there is no extension variable. + RecordN { + fields: &'a [(&'a str, &'a Type<'a>)], + }, + TupleN(&'a Type<'a>, &'a Type<'a>, &'a [&'a Type<'a>]), +} + /// Flatten application spines whose heads inference has already determined. /// This does not bind unknown heads or expand aliases. pub fn normalize_application<'a>(uf: &mut UnionFind<'a>, term: FlatType<'a>) -> FlatType<'a> { @@ -210,6 +362,30 @@ pub fn literal_default(trait_: nash_ast::QualifiedName<'_>) -> Option(bump: &'a bumpalo::Bump, element: &'a Type<'a>) -> Type<'a> { + Type::AppN { + home: nash_ast::primitives::primitive_home(), + name: "list", + args: bump.alloc_slice_copy(&[element]), + } +} + +pub const fn unit<'a>() -> Type<'a> { + Type::AppN { + home: nash_ast::primitives::primitive_home(), + name: "unit", + args: &[], + } +} + +pub const fn bool<'a>() -> Type<'a> { + Type::AppN { + home: nash_ast::primitives::primitive_home(), + name: "bool", + args: &[], + } +} + // MAKE FLEX VARIABLES pub fn mk_flex_var<'a>(uf: &mut UnionFind<'a>) -> Variable { @@ -219,3 +395,11 @@ pub fn mk_flex_var<'a>(uf: &mut UnionFind<'a>) -> Variable { pub const fn unnamed_flex_var<'a>() -> Content<'a> { Content::FlexVar(None) } + +pub fn name_to_flex<'a>(uf: &mut UnionFind<'a>, name: &'a str) -> Variable { + uf.fresh(make_descriptor(Content::FlexVar(Some(name)))) +} + +pub fn name_to_rigid<'a>(uf: &mut UnionFind<'a>, name: &'a str) -> Variable { + uf.fresh(make_descriptor(Content::RigidVar(name))) +} diff --git a/crates/nash-driver/src/compile.rs b/crates/nash-driver/src/compile.rs index dc0741a0..e14cc792 100644 --- a/crates/nash-driver/src/compile.rs +++ b/crates/nash-driver/src/compile.rs @@ -1,7 +1,7 @@ //! Module compilation orchestration. //! //! Each module runs Elm's full pipeline: parse -> canonicalize -> -//! direct inference -> nitpick -> `Interface::from_module` with the solver's +//! constraint generation and solving -> nitpick -> `Interface::from_module` with the solver's //! annotations. Modules compile in dependency order, and each solved //! module and solved evidence remain in the build scope. Canonical nodes //! live in a shared arena, so interfaces borrow them without moving the diff --git a/crates/nash-solve/src/lib.rs b/crates/nash-solve/src/lib.rs index 2c6d3d5e..f8283dfa 100644 --- a/crates/nash-solve/src/lib.rs +++ b/crates/nash-solve/src/lib.rs @@ -2,10 +2,11 @@ //! `Type.Unify`, and `Type.Occurs`, plus the `toAnnotation`/`toErrorType` //! half of `Type.Type`. //! -//! The driver passes the canonical module to [`run`], which infers directly -//! into the existing union-find and predicate stores. Success returns the -//! annotations used by `nash_can::from_module` -//! together with definition schemes and use-site instances in [`SolvedTypes`]. +//! The driver passes the canonical module to [`run`], which runs +//! `nash_constrain::constrain` to build a constraint tree (filling a +//! `UnionFind` store with fresh variables) and then walks it. Success returns +//! the annotations used by `nash_can::from_module` together with definition +//! schemes and use-site instances in [`SolvedTypes`]. mod annotation; pub mod evidence; diff --git a/crates/nash-solve/src/solve.rs b/crates/nash-solve/src/solve.rs index c95326be..2f7d694a 100644 --- a/crates/nash-solve/src/solve.rs +++ b/crates/nash-solve/src/solve.rs @@ -1,5 +1,6 @@ -//! Direct canonical AST inference with Elm's rank-based generalization, -//! producing annotations, definition schemes, and use-site evidence. +//! Elm's constraint solver: walks the constraint tree that `nash-constrain` +//! generates, with rank-based generalization. It produces annotations, +//! definition schemes, and use-site evidence. use std::collections::{BTreeMap, BTreeSet, VecDeque}; @@ -9,16 +10,11 @@ use nash_ast::head::{DEPTH_LIMIT, WORK_LIMIT}; use nash_can::Annotations; use nash_constrain::error::{Category, Error, Expected, PExpected}; use nash_constrain::type_::{ - self, Content, Descriptor, FlatType, Mark, NO_MARK, NO_RANK, OUTERMOST_RANK, + self, Constraint, Content, Descriptor, FlatType, Mark, NO_MARK, NO_RANK, OUTERMOST_RANK, Type, }; use nash_constrain::{UnionFind, Variable}; use nash_region::{Located, Region}; -mod expressions; -mod infer; -mod patterns; -use infer::Definition; - use crate::annotation::to_error_type; use crate::occurs; use crate::preds::{Body, Origin, Predicate, Store, UseSite}; @@ -32,16 +28,19 @@ pub fn run<'a>( module: &nash_ast::Module<'a>, tables: &nash_can::environment::Tables<'a>, ) -> Result<(Annotations<'a>, crate::SolvedTypes<'a>), Vec>> { + let constraint = nash_constrain::constrain(bump, uf, module); let mut solver = Solver::new(bump, tables); - let state = solver.infer_module( + let state = solver.solve( uf, - module, + &Env::new(), + OUTERMOST_RANK, State { env: Env::new(), mark: NO_MARK.next(), errors: Vec::new(), }, + &constraint, ); solver.finish_state(uf, state) @@ -178,6 +177,15 @@ struct Solver<'a, 'tables> { fields: Vec>, } +/// A `Let` definition with its type and context converted to variables, for +/// the Nash-only declared contexts, scheme records, and ambiguity check. +#[derive(Clone, Copy)] +struct Definition<'a> { + site: type_::Binder<'a>, + typ: Variable, + context: Option<&'a [Body<'a>]>, +} + struct GivenFrame<'a> { binder: nash_ast::NodeId, predicates: Vec>, @@ -240,6 +248,694 @@ impl<'a, 'tables> Solver<'a, 'tables> { } } +// SOLVE + +impl<'a> Solver<'a, '_> { + fn solve( + &mut self, + uf: &mut UnionFind<'a>, + env: &Env<'a>, + rank: usize, + state: State<'a>, + constraint: &Constraint<'a>, + ) -> State<'a> { + match constraint { + Constraint::Record { + region, + context, + record, + } => { + let record = self.type_to_variable(uf, rank, record); + self.fields.push(DeferredField { + test_scope: self.test_scope, + region: *region, + context: *context, + record, + field: None, + }); + let mut state = state; + self.retry_fields(uf, rank, &mut state.errors); + state + } + + Constraint::Field { + region, + context, + record, + field, + field_type, + } => { + let record = self.type_to_variable(uf, rank, record); + let field_type = self.type_to_variable(uf, rank, field_type); + self.dependencies.field(field_type, record); + self.fields.push(DeferredField { + test_scope: self.test_scope, + region: *region, + context: *context, + record, + field: Some((field, field_type)), + }); + let mut state = state; + self.retry_fields(uf, rank, &mut state.errors); + state + } + + Constraint::True => state, + + Constraint::SaveTheEnvironment => State { + env: env.clone(), + ..state + }, + + Constraint::Equal(region, category, tipe, expectation) => { + let actual = self.type_to_variable(uf, rank, tipe); + self.equal(uf, rank, state, *region, *category, actual, expectation) + } + + Constraint::Local(region, node, name, expectation) => { + let binding = *env + .get(name) + .expect("constraint generator only references bound locals"); + let actual = self.instantiate_binding( + uf, + rank, + binding, + UseSite { + node: *node, + region: *region, + name, + }, + ); + self.equal( + uf, + rank, + state, + *region, + Category::Local(name), + actual, + expectation, + ) + } + + Constraint::Foreign(region, node, name, annotation, expectation) => { + let actual = self.src_type_to_variable( + uf, + rank, + UseSite { + node: *node, + region: *region, + name, + }, + annotation, + ); + self.equal( + uf, + rank, + state, + *region, + Category::Foreign(name), + actual, + expectation, + ) + } + + Constraint::Pattern(region, category, tipe, expectation) => { + let actual = self.type_to_variable(uf, rank, tipe); + let expected = self.pattern_expectation_to_variable(uf, rank, expectation); + self.formed_at(uf, rank, &[actual, expected], *region); + match self.unify(uf, actual, expected) { + unify::Answer::Ok(vars) => { + self.introduce(uf, rank, &vars); + state + } + unify::Answer::Err(vars, actual_type, expected_type) => { + self.introduce(uf, rank, &vars); + add_error( + state, + Error::BadPattern( + *region, + *category, + actual_type, + expectation.type_replace(expected_type), + ), + ) + } + } + } + + Constraint::And(constraints) => constraints + .iter() + .fold(state, |state, sub| self.solve(uf, env, rank, state, sub)), + + Constraint::SaveType { + node, + kind, + typ, + constraint, + } => match kind { + type_::NodeKind::Expression => { + let variable = self.type_to_variable(uf, rank, typ); + self.expr_types.push(NodeTypeRecord { + node: *node, + variable, + owner: self.owners.last().copied(), + }); + self.solve(uf, env, rank, state, constraint) + } + type_::NodeKind::Pattern => { + let variable = self.type_to_variable(uf, rank, typ); + self.pattern_types.push(NodeTypeRecord { + node: *node, + variable, + owner: self.owners.last().copied(), + }); + self.solve(uf, env, rank, state, constraint) + } + }, + + Constraint::TestScope(constraint) => { + let previous = self.test_scope; + self.test_scope = true; + let state = self.solve(uf, env, rank, state, constraint); + self.test_scope = previous; + state + } + + Constraint::Let { + declarations, + given, + binder, + definitions, + rigid_vars, + flex_vars, + header, + header_con, + body_con, + } => { + let errors_before = state.errors.len(); + let wanted_start = self.wanted.len(); + let annotated = definitions.iter().any(|def| def.context.is_some()); + if definitions.is_empty() + && rigid_vars.is_empty() + && matches!(body_con, Constraint::True) + { + self.introduce(uf, rank, flex_vars); + let given = self.convert_givens(uf, rank, given); + self.solve_header(uf, env, rank, state, header_con, given, *binder, annotated) + } else if definitions.is_empty() && rigid_vars.is_empty() && flex_vars.is_empty() { + let decls = self.convert_definitions(uf, rank, declarations); + let declared = self.declared_contexts(uf, rank, &[], &decls); + let given = self.convert_givens(uf, rank, given); + let state1 = self + .solve_header(uf, env, rank, state, header_con, given, *binder, annotated); + let locals: Vec<(&'a str, Located)> = header + .iter() + .map(|(name, loc_type)| { + let var = self.type_to_variable(uf, rank, loc_type.value); + (*name, Located::at(loc_type.region, var)) + }) + .collect(); + let mut new_env = env.clone(); + for (name, loc) in &locals { + new_env.entry(name).or_insert(Binding { + declared_quantifiers: &[], + variable: loc.value, + context: declared.get(name).copied().unwrap_or(&[]), + context_is_final: !declarations + .iter() + .any(|def| def.site.name().value == *name && def.context.is_none()), + definition: definitions + .iter() + .chain(declarations.iter()) + .find(|def| def.site.name().value == *name) + .map(|def| def.site.node()) + .or_else(|| { + binder + .filter(|b| matches!(b, type_::Binder::Pattern { .. })) + .map(type_::Binder::node) + }), + }); + } + let state2 = self.solve(uf, &new_env, rank, state1, body_con); + locals.into_iter().fold(state2, |state, (name, loc)| { + self.check_occurs(uf, state, name, loc) + }) + } else { + // work in the next pool to localize header + let next_rank = rank + 1; + if next_rank >= self.pools.len() { + let pools_length = self.pools.len(); + self.pools.resize(pools_length * 2, Vec::new()); + } + + // introduce variables + let vars: Vec = + rigid_vars.iter().chain(flex_vars.iter()).copied().collect(); + for var in &vars { + uf.modify(*var, |desc| desc.rank = next_rank); + } + self.pools[next_rank] = vars; + + // run solver in next pool + let locals: Vec<(&'a str, Located)> = header + .iter() + .map(|(name, loc_type)| { + let var = self.type_to_variable(uf, next_rank, loc_type.value); + (*name, Located::at(loc_type.region, var)) + }) + .collect(); + let given_bodies = self.convert_givens(uf, next_rank, given); + let defs = self.convert_definitions(uf, next_rank, definitions); + let decls = self.convert_definitions(uf, next_rank, declarations); + let declared = self.declared_contexts(uf, next_rank, &defs, &decls); + let mut state1 = self.solve_header( + uf, + env, + next_rank, + state, + header_con, + given_bodies, + *binder, + annotated, + ); + + let young_mark = state1.mark; + let visit_mark = young_mark.next(); + let final_mark = visit_mark.next(); + + self.retry_fields(uf, next_rank, &mut state1.errors); + self.finish_fields(uf, next_rank, &mut state1.errors); + + // pop pool + self.generalize(uf, young_mark, visit_mark, next_rank); + self.pools[next_rank] = Vec::new(); + + // An unrelated error must not suppress an escaping annotation. + let escapes_before = state1.errors.len(); + for rigid in rigid_vars.iter() { + if uf.get(*rigid).rank != NO_RANK + && !crate::recovery::is_poisoned(uf, [*rigid]) + { + let owner = binder + .map(|name| (name.name().region, name.name().value)) + .or_else(|| header.first().map(|(name, typ)| (typ.region, *name))); + state1.errors.push(Error::AnnotationVariableEscapes { + region: owner + .map_or_else(nash_region::Region::zero, |(region, _)| region), + name: owner.map(|(_, name)| name), + variable: to_error_type(self.bump, uf, *rigid), + }); + } + } + // A body error leaves a valid annotation usable by callers, as in Elm. + // Only an annotation that lets its own variables escape blocks its uses. + let all_annotated = !definitions.is_empty() + && definitions.iter().all(|def| def.context.is_some()); + let annotation_failed = state1.errors.len() > escapes_before; + + if let Some(binder) = *binder { + let depth = self.enter_givens(uf, rank, given_bodies, Some(binder)); + loop { + let (errors, defaulted) = + self.check_ambiguity(uf, rank, wanted_start, &defs, binder.name()); + state1.errors.extend(errors); + if !defaulted { + break; + } + state1 = self.resolve_wanted( + uf, + next_rank, + state1, + wanted_start, + Some(binder), + annotated, + ); + } + self.givens.truncate(depth); + } + let context = if !definitions.is_empty() + && definitions.iter().all(|def| def.context.is_none()) + { + self.retain_wanted( + uf, + rank, + wanted_start, + binder.expect("inferred definition binder").node(), + ) + } else { + &[] + }; + + let mut new_env = env.clone(); + let failed = if all_annotated { + annotation_failed + } else { + state1.errors.len() > errors_before + }; + if failed && let Some(binder) = *binder { + self.fail_definition(uf, binder.node()); + } + self.record_definitions(uf, rank, &defs, &declared, context, *binder); + for (name, loc) in &locals { + new_env.entry(name).or_insert(Binding { + declared_quantifiers: if declarations + .iter() + .any(|def| def.site.name().value == *name && def.context.is_some()) + { + rigid_vars + } else { + &[] + }, + variable: loc.value, + context: declared.get(name).copied().unwrap_or(context), + context_is_final: true, + definition: definitions + .iter() + .chain(declarations.iter()) + .find(|def| def.site.name().value == *name) + .map(|def| def.site.node()) + .or_else(|| { + binder + .filter(|b| matches!(b, type_::Binder::Pattern { .. })) + .map(type_::Binder::node) + }), + }); + } + let temp_state = State { + env: state1.env, + mark: final_mark, + errors: state1.errors, + }; + let new_state = self.solve(uf, &new_env, rank, temp_state, body_con); + + locals.into_iter().fold(new_state, |state, (name, loc)| { + self.check_occurs(uf, state, name, loc) + }) + } + } + } + } + + /// Solve a header constraint in the scope of its givens and its evidence + /// owner, then retry fields and resolve the predicates wanted in this scope. + #[allow(clippy::too_many_arguments)] + fn solve_header( + &mut self, + uf: &mut UnionFind<'a>, + env: &Env<'a>, + rank: usize, + state: State<'a>, + constraint: &Constraint<'a>, + given: &[Body<'a>], + binder: Option>, + annotated: bool, + ) -> State<'a> { + // Attribute new failures to their owning binding. This count does not + // gate any independent constraint or reset the collected diagnostics. + let errors_before = state.errors.len(); + let depth = self.enter_givens(uf, rank, given, binder); + let start = self.wanted.len(); + let owner_depth = self.owners.len(); + if let Some(binder) = binder { + self.owners.push(binder.node()); + } + let mut state = self.solve(uf, env, rank, state, constraint); + self.retry_fields(uf, rank, &mut state.errors); + state = self.resolve_wanted(uf, rank, state, start, binder, annotated); + // An annotated body keeps its annotation for callers; its failure is + // decided after generalization. + if state.errors.len() > errors_before + && !annotated + && let Some(binder) = binder + { + self.fail_definition(uf, binder.node()); + } + self.givens.truncate(depth); + self.owners.truncate(owner_depth); + state + } + + /// Unify an actual variable with an expectation, as Elm's `CEqual` does. + #[allow(clippy::too_many_arguments)] + fn equal( + &mut self, + uf: &mut UnionFind<'a>, + rank: usize, + state: State<'a>, + region: Region, + category: Category<'a>, + actual: Variable, + expectation: &Expected<'a, &'a Type<'a>>, + ) -> State<'a> { + let expected = self.expected_to_variable(uf, rank, expectation); + if let Expected::FromContext(_, nash_constrain::error::Context::CallArity(_, arity), _) = + expectation + { + let mut result = expected; + let mut inputs = vec![actual]; + for _ in 0..*arity { + let Content::Structure(FlatType::Fun1(argument, output)) = uf.get(result).content + else { + break; + }; + inputs.push(argument); + result = output; + } + self.dependencies.computation(result, inputs); + } + self.formed_at(uf, rank, &[actual, expected], region); + match self.unify(uf, actual, expected) { + unify::Answer::Ok(vars) => { + self.introduce(uf, rank, &vars); + state + } + unify::Answer::Err(vars, actual_type, expected_type) => { + self.introduce(uf, rank, &vars); + add_error( + state, + Error::BadExpr( + region, + category, + actual_type, + expectation.type_replace(expected_type), + ), + ) + } + } + } + + // EXPECTATIONS TO VARIABLE + + fn expected_to_variable( + &mut self, + uf: &mut UnionFind<'a>, + rank: usize, + expectation: &Expected<'a, &'a Type<'a>>, + ) -> Variable { + let tipe = match expectation { + Expected::NoExpectation(tipe) => tipe, + Expected::FromContext(_, _, tipe) => tipe, + Expected::FromAnnotation(_, _, _, _, tipe) => tipe, + }; + self.type_to_variable(uf, rank, tipe) + } + + fn pattern_expectation_to_variable( + &mut self, + uf: &mut UnionFind<'a>, + rank: usize, + expectation: &PExpected<'a, &'a Type<'a>>, + ) -> Variable { + let tipe = match expectation { + PExpected::NoExpectation(tipe) => tipe, + PExpected::FromContext(_, _, tipe) => tipe, + }; + self.type_to_variable(uf, rank, tipe) + } + + fn convert_givens( + &mut self, + uf: &mut UnionFind<'a>, + rank: usize, + given: &[type_::Pred<'a>], + ) -> &'a [Body<'a>] { + let bump = self.bump; + bump.alloc_slice_fill_iter( + given + .iter() + .map(|pred| self.constraint_predicate(uf, rank, *pred)), + ) + } + + /// Convert each definition type on its own, as Elm converts each type in + /// each constraint. Its scheme is then the declared type: unification of + /// the header variable at a later use cannot remove an alias name, which + /// selects impls in Nash. + fn convert_definitions( + &mut self, + uf: &mut UnionFind<'a>, + rank: usize, + definitions: &[type_::Definition<'a>], + ) -> Vec> { + definitions + .iter() + .map(|definition| Definition { + site: definition.site, + typ: self.type_to_variable(uf, rank, definition.typ), + context: definition + .context + .map(|context| self.convert_givens(uf, rank, context)), + }) + .collect() + } + + // TYPE TO VARIABLE + + fn type_to_variable( + &mut self, + uf: &mut UnionFind<'a>, + rank: usize, + tipe: &Type<'a>, + ) -> Variable { + match tipe { + Type::PartialAliasN { + home, + name, + args, + remaining, + body, + } => { + let args = args + .iter() + .map(|(name, typ)| (*name, self.type_to_variable(uf, rank, typ))) + .collect(); + self.register( + uf, + rank, + Content::PartialAlias { + home: *home, + name, + args, + remaining: remaining.to_vec(), + body, + }, + ) + } + Type::VarN(var) => *var, + + Type::AppVarN(head, args) => { + let head = self.type_to_variable(uf, rank, head); + let args = args + .iter() + .map(|arg| self.type_to_variable(uf, rank, arg)) + .collect(); + self.register(uf, rank, Content::Structure(FlatType::AppV1(head, args))) + } + + Type::AppN { home, name, args } => { + let arg_vars: Vec = args + .iter() + .map(|arg| self.type_to_variable(uf, rank, arg)) + .collect(); + self.register( + uf, + rank, + Content::Structure(FlatType::App1(*home, name, arg_vars)), + ) + } + + Type::FunN(a, b) => { + let a_var = self.type_to_variable(uf, rank, a); + let b_var = self.type_to_variable(uf, rank, b); + self.register(uf, rank, Content::Structure(FlatType::Fun1(a_var, b_var))) + } + + Type::AliasN { + home, + name, + args, + real, + body, + } => { + let arg_vars: Vec<(&'a str, Variable)> = args + .iter() + .map(|(arg_name, arg_type)| { + (*arg_name, self.type_to_variable(uf, rank, arg_type)) + }) + .collect(); + let alias_var = self.type_to_variable(uf, rank, real); + self.register( + uf, + rank, + Content::Alias { + home: *home, + name, + args: arg_vars, + real: alias_var, + body, + }, + ) + } + + Type::RecordN { fields } => { + let field_vars: BTreeMap<&'a str, Variable> = fields + .iter() + .map(|(name, field_type)| (*name, self.type_to_variable(uf, rank, field_type))) + .collect(); + self.register(uf, rank, Content::Structure(FlatType::Record1(field_vars))) + } + + Type::TupleN(a, b, rest) => { + let a_var = self.type_to_variable(uf, rank, a); + let b_var = self.type_to_variable(uf, rank, b); + let c_var = rest + .iter() + .map(|c| self.type_to_variable(uf, rank, c)) + .collect(); + self.register( + uf, + rank, + Content::Structure(FlatType::Tuple1(a_var, b_var, c_var)), + ) + } + } + } + + fn constraint_predicate( + &mut self, + uf: &mut UnionFind<'a>, + rank: usize, + predicate: type_::Pred<'a>, + ) -> Body<'a> { + match predicate { + type_::Pred::Trait { + trait_, + args, + hidden, + } => Body::Trait { + trait_, + hidden, + args: args + .iter() + .map(|arg| self.type_to_variable(uf, rank, arg)) + .collect(), + }, + type_::Pred::Apply { head, args } => Body::Apply { + head: self.type_to_variable(uf, rank, head), + args: args + .iter() + .map(|arg| self.type_to_variable(uf, rank, arg)) + .collect(), + }, + } + } + + fn structure(&mut self, uf: &mut UnionFind<'a>, rank: usize, typ: FlatType<'a>) -> Variable { + let typ = type_::normalize_application(uf, typ); + self.register(uf, rank, Content::Structure(typ)) + } +} + impl<'a> Solver<'a, '_> { fn unify( &mut self, @@ -2857,7 +3553,7 @@ fn adjust_rank_content<'a>( #[cfg(test)] mod copy_tests { use super::*; - // Insert in solve.rs tests module; use Solver::new and finish_state. + fn primitive_state<'a>() -> State<'a> { State { env: Env::new(), @@ -2866,6 +3562,30 @@ mod copy_tests { } } + fn fresh<'a>(solver: &mut Solver<'a, '_>, uf: &mut UnionFind<'a>, rank: usize) -> Variable { + solver.register(uf, rank, Content::FlexVar(None)) + } + + /// Solve one `Equal` constraint between two existing variables. + fn equal<'a>( + solver: &mut Solver<'a, '_>, + uf: &mut UnionFind<'a>, + state: State<'a>, + region: Region, + category: Category<'a>, + actual: Variable, + expected: Variable, + ) -> State<'a> { + let bump = solver.bump; + let constraint = Constraint::Equal( + region, + category, + bump.alloc(Type::VarN(actual)), + Expected::NoExpectation(bump.alloc(Type::VarN(expected))), + ); + solver.solve(uf, &Env::new(), OUTERMOST_RANK, state, &constraint) + } + fn primitive_nullary<'a>( solver: &mut Solver<'a, '_>, uf: &mut UnionFind<'a>, @@ -2897,14 +3617,14 @@ mod copy_tests { let mut uf = UnionFind::new(); let actual = primitive_nullary(&mut solver, &mut uf, "list"); let expected = primitive_nullary(&mut solver, &mut uf, "list"); - let state = solver.equal( + let state = equal( + &mut solver, &mut uf, - OUTERMOST_RANK, primitive_state(), nash_region::Region::zero(), Category::List, actual, - Expected::NoExpectation(expected), + expected, ); let errors = solver.finish_state(&mut uf, state).unwrap_err(); assert!( @@ -2927,28 +3647,28 @@ mod copy_tests { }; let function = primitive_unit_function(&mut solver, &mut uf); let unit = primitive_nullary(&mut solver, &mut uf, "unit"); - let mut state = solver.equal( + let mut state = equal( + &mut solver, &mut uf, - OUTERMOST_RANK, primitive_state(), at(1), Category::Lambda, function, - Expected::NoExpectation(unit), + unit, ); for line in [2, 3] { // Four separate list nodes across these two equalities: sharing the // source description never meant sharing its materialized UF graph. let actual = primitive_nullary(&mut solver, &mut uf, "list"); let expected = primitive_nullary(&mut solver, &mut uf, "list"); - state = solver.equal( + state = equal( + &mut solver, &mut uf, - OUTERMOST_RANK, state, at(line), Category::List, actual, - Expected::NoExpectation(expected), + expected, ); } let errors = solver.finish_state(&mut uf, state).unwrap_err(); @@ -2977,20 +3697,20 @@ mod copy_tests { let mut solver = Solver::new(&bump, &tables); let mut uf = UnionFind::new(); let rank = OUTERMOST_RANK; - let head = solver.fresh(&mut uf, rank); - let result = solver.fresh(&mut uf, rank); + let head = fresh(&mut solver, &mut uf, rank); + let result = fresh(&mut solver, &mut uf, rank); let region = nash_region::Region::zero(); let argument = primitive_nullary(&mut solver, &mut uf, "unit"); let applied = solver.structure(&mut uf, rank, FlatType::AppV1(head, vec![argument])); - let mut state = solver.equal( + let mut state = equal( + &mut solver, &mut uf, - rank, primitive_state(), region, Category::List, result, - Expected::NoExpectation(applied), + applied, ); let argument = primitive_nullary(&mut solver, &mut uf, "unit"); @@ -3003,38 +3723,38 @@ mod copy_tests { vec![argument], ), ); - state = solver.equal( + state = equal( + &mut solver, &mut uf, - rank, state, region, Category::List, result, - Expected::NoExpectation(list), + list, ); let function = primitive_unit_function(&mut solver, &mut uf); - state = solver.equal( + state = equal( + &mut solver, &mut uf, - rank, state, region, Category::List, result, - Expected::NoExpectation(function), + function, ); // Rebuild this entire function graph after the previous failing equality. // Only the explicit head/result variables are shared between operations. let function = primitive_unit_function(&mut solver, &mut uf); - state = solver.equal( + state = equal( + &mut solver, &mut uf, - rank, state, region, Category::List, head, - Expected::NoExpectation(function), + function, ); let errors = solver.finish_state(&mut uf, state).unwrap_err(); assert_eq!( @@ -3045,6 +3765,64 @@ mod copy_tests { assert!(matches!(errors[0], Error::BadExpr(..)), "{errors:#?}"); } + #[test] + fn apply_head_and_arguments_share_the_signature_substitution() { + use nash_ast::Pred; + + let bump = Bump::new(); + let tables = nash_can::environment::Tables::default(); + let mut solver = Solver::new(&bump, &tables); + let mut uf = UnionFind::new(); + let f = fresh(&mut solver, &mut uf, 2); + let a = fresh(&mut solver, &mut uf, 2); + let scope = BTreeMap::from([("f", f), ("a", a)]); + let head = &*bump.alloc(Located::at_zero(CanType::Var("f"))); + let arg = &*bump.alloc(Located::at_zero(CanType::Var("a"))); + let args = bump.alloc_slice_copy(&[arg]); + let application = + solver.canonical_predicate(&mut uf, 2, &scope, Pred::Apply { head, args }); + let Body::Apply { + head: actual_head, + args: actual_args, + } = application + else { + panic!("Apply preserved") + }; + assert_eq!(actual_head, f); + assert_eq!(actual_args, [a]); + let representation = solver.canonical_predicate( + &mut uf, + 2, + &scope, + Pred::Implied { + trait_: nash_ast::primitives::ReprTrait::Big.qualified(), + args, + }, + ); + let Body::Trait { + hidden, + args, + trait_, + } = representation + else { + panic!("representation predicate preserved") + }; + assert!(hidden); + assert_eq!(trait_, nash_ast::primitives::ReprTrait::Big.qualified()); + assert_eq!(args, [a]); + let signature = Located::at_zero(CanType::App { + head, + args: bump.alloc_slice_copy(&[arg]), + }); + let signature = solver.src_type_to_var(&mut uf, 2, &scope, &signature); + let Content::Structure(FlatType::AppV1(type_head, type_args)) = &uf.get(signature).content + else { + panic!("type application preserved") + }; + assert_eq!(*type_head, actual_head); + assert_eq!(type_args, &actual_args); + } + use nash_constrain::type_::{PredId, make_descriptor}; fn evidence_name(name: nash_ast::QualifiedName<'_>) -> String { @@ -3267,6 +4045,7 @@ mod copy_tests { let canonical = nash_can::canonicalize(&bump, nash_can::Context::default(), &parsed).unwrap(); let mut uf = UnionFind::new(); + let constraint = nash_constrain::constrain(&bump, &mut uf, &canonical.module); let mut solver = Solver { bump: &bump, tables: &canonical.tables, @@ -3293,14 +4072,16 @@ mod copy_tests { fields: Vec::new(), test_scope: false, }; - let result = solver.infer_module( + let result = solver.solve( &mut uf, - &canonical.module, + &Env::new(), + OUTERMOST_RANK, State { env: Env::new(), mark: NO_MARK.next(), errors: Vec::new(), }, + &constraint, ); assert!(result.errors.is_empty()); assert!( @@ -3339,6 +4120,7 @@ mod copy_tests { let canonical = nash_can::canonicalize(&bump, nash_can::Context::default(), &parsed).unwrap(); let mut uf = UnionFind::new(); + let constraint = nash_constrain::constrain(&bump, &mut uf, &canonical.module); let mut solver = Solver { bump: &bump, tables: &canonical.tables, @@ -3365,14 +4147,16 @@ mod copy_tests { fields: Vec::new(), test_scope: false, }; - let result = solver.infer_module( + let result = solver.solve( &mut uf, - &canonical.module, + &Env::new(), + OUTERMOST_RANK, State { env: Env::new(), mark: NO_MARK.next(), errors: Vec::new(), }, + &constraint, ); let localizer = nash_report::localizer::Localizer::from_module(&parsed, &[]); insta::with_settings!({description => source, omit_expression => true, info => &"diagnostic"}, { @@ -3413,6 +4197,7 @@ mod copy_tests { let canonical = nash_can::canonicalize(&bump, nash_can::Context::default(), &parsed).unwrap(); let mut uf = UnionFind::new(); + let constraint = nash_constrain::constrain(&bump, &mut uf, &canonical.module); let mut solver = Solver { bump: &bump, tables: &canonical.tables, @@ -3439,14 +4224,16 @@ mod copy_tests { fields: Vec::new(), test_scope: false, }; - let result = solver.infer_module( + let result = solver.solve( &mut uf, - &canonical.module, + &Env::new(), + OUTERMOST_RANK, State { env: Env::new(), mark: NO_MARK.next(), errors: Vec::new(), }, + &constraint, ); assert!(result.errors.is_empty()); let local = solver @@ -3500,6 +4287,7 @@ mod copy_tests { let canonical = nash_can::canonicalize(&bump, nash_can::Context::default(), &parsed).unwrap(); let mut uf = UnionFind::new(); + let constraint = nash_constrain::constrain(&bump, &mut uf, &canonical.module); let mut solver = Solver { bump: &bump, tables: &canonical.tables, @@ -3526,14 +4314,16 @@ mod copy_tests { fields: Vec::new(), test_scope: false, }; - let result = solver.infer_module( + let result = solver.solve( &mut uf, - &canonical.module, + &Env::new(), + OUTERMOST_RANK, State { env: Env::new(), mark: NO_MARK.next(), errors: Vec::new(), }, + &constraint, ); assert!(result.errors.is_empty(), "{:?}", result.errors); assert!(result.env["value"].context.is_empty()); @@ -3637,6 +4427,7 @@ mod copy_tests { let group_binder = group_binder.unwrap(); let h_binder = h_binder.unwrap(); let mut uf = UnionFind::new(); + let constraint = nash_constrain::constrain(&bump, &mut uf, &canonical.module); let mut solver = Solver { bump: &bump, tables: &canonical.tables, @@ -3663,14 +4454,16 @@ mod copy_tests { fields: Vec::new(), test_scope: false, }; - let result = solver.infer_module( + let result = solver.solve( &mut uf, - &canonical.module, + &Env::new(), + OUTERMOST_RANK, State { env: Env::new(), mark: NO_MARK.next(), errors: Vec::new(), }, + &constraint, ); assert!(result.errors.is_empty(), "{:?}", result.errors); assert!(solver.wanted.is_empty()); diff --git a/crates/nash-solve/src/solve/expressions.rs b/crates/nash-solve/src/solve/expressions.rs deleted file mode 100644 index fc1259c5..00000000 --- a/crates/nash-solve/src/solve/expressions.rs +++ /dev/null @@ -1,905 +0,0 @@ -use super::*; -use nash_ast::{Expr as CanExpr, NodeId}; -use nash_constrain::error::{Context, MaybeName, PContext, SubContext}; - -impl<'a> Solver<'a, '_> { - #[allow(clippy::too_many_arguments)] - pub(super) fn infer_expr( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - state: State<'a>, - rtv: &BTreeMap<&'a str, Variable>, - expr: &Located>, - expected: Expected<'a, Variable>, - ) -> State<'a> { - let variable = match expected { - Expected::NoExpectation(var) - | Expected::FromContext(_, _, var) - | Expected::FromAnnotation(_, _, _, _, var) => var, - }; - self.expr_types.push(NodeTypeRecord { - node: NodeId::expr(expr), - variable, - owner: self.owners.last().copied(), - }); - // These are exactly the old `exists` boundaries. Their wanted flush - // must remain even though variables are now introduced eagerly. - let existential = matches!( - &expr.value, - CanExpr::List(_) - | CanExpr::Binop { .. } - | CanExpr::Lambda { .. } - | CanExpr::Call { .. } - | CanExpr::Case { .. } - | CanExpr::Accessor(_) - | CanExpr::Access { .. } - | CanExpr::Update { .. } - | CanExpr::Record { .. } - | CanExpr::Tuple { .. } - | CanExpr::If { .. } - ); - let wanted_start = self.wanted.len(); - let mut state = self.infer_expr_inner(uf, env, rank, state, rtv, expr, expected); - if existential { - self.retry_fields(uf, rank, &mut state.errors); - state = self.resolve_wanted(uf, rank, state, wanted_start, None, false); - } - state - } - - #[allow(clippy::too_many_arguments)] - fn infer_expr_inner( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - mut state: State<'a>, - rtv: &BTreeMap<&'a str, Variable>, - expr: &Located>, - expected: Expected<'a, Variable>, - ) -> State<'a> { - let region = expr.region; - let node = NodeId::expr(expr); - match &expr.value { - CanExpr::VarLocal(name) => { - self.local(uf, env, rank, state, region, node, name, expected) - } - CanExpr::VarTopLevel(reference) => { - self.local(uf, env, rank, state, region, node, reference.name, expected) - } - CanExpr::VarForeign { - reference, - annotation, - } => self.foreign( - uf, - rank, - state, - region, - node, - reference.name, - annotation, - expected, - ), - CanExpr::VarConstructor { - reference, - annotation, - .. - } => self.foreign( - uf, - rank, - state, - region, - node, - reference.name, - annotation, - expected, - ), - CanExpr::VarMethod { - method, annotation, .. - } => self.foreign(uf, rank, state, region, node, method, annotation, expected), - CanExpr::VarOperator { - symbol, annotation, .. - } => self.foreign(uf, rank, state, region, node, symbol, annotation, expected), - CanExpr::Str(_) - | CanExpr::Bytes(_) - | CanExpr::Int(_) - | CanExpr::Bool(_) - | CanExpr::Unit => { - let (name, trait_) = match &expr.value { - CanExpr::Str(_) => ("fromString", "FromString"), - CanExpr::Bytes(_) => ("fromBytes", "FromBytes"), - CanExpr::Bool(_) => ("fromBool", "FromBool"), - CanExpr::Unit => ("fromUnit", "FromUnit"), - _ => ("fromInt", "FromInt"), - }; - let annotation = - type_::literal_annotation(self.bump, &[type_::literal_trait(trait_)]); - self.foreign(uf, rank, state, region, node, name, annotation, expected) - } - CanExpr::List(entries) => { - let element = self.fresh(uf, rank); - for (index, entry) in entries.iter().enumerate() { - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - entry, - Expected::FromContext( - region, - Context::ListEntry( - index, - index.checked_sub(1).map(|i| entries[i].region), - ), - element, - ), - ); - } - let list = self.structure( - uf, - rank, - FlatType::App1( - nash_ast::primitives::primitive_home(), - "list", - vec![element], - ), - ); - self.equal(uf, rank, state, region, Category::List, list, expected) - } - CanExpr::Binop { - symbol, - annotation, - left, - right, - .. - } => { - let left_var = self.fresh(uf, rank); - let right_var = self.fresh(uf, rank); - let result = self.fresh(uf, rank); - let tail = self.structure(uf, rank, FlatType::Fun1(right_var, result)); - let function = self.structure(uf, rank, FlatType::Fun1(left_var, tail)); - state = self.foreign( - uf, - rank, - state, - region, - node, - symbol, - annotation, - Expected::NoExpectation(function), - ); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - left, - Expected::FromContext(region, Context::OpLeft(symbol), left_var), - ); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - right, - Expected::FromContext(region, Context::OpRight(symbol), right_var), - ); - self.equal( - uf, - rank, - state, - region, - Category::CallResult(MaybeName::OpName(symbol)), - result, - expected, - ) - } - CanExpr::Lambda { parameters, body } => { - let args: Vec<_> = parameters.iter().map(|_| self.fresh(uf, rank)).collect(); - let result = self.fresh(uf, rank); - let patterns: Vec<_> = parameters - .iter() - .zip(&args) - .map(|(pattern, var)| (*pattern, PExpected::NoExpectation(*var))) - .collect(); - let scope = self.infer_patterns(uf, env, rank, state, &patterns); - state = self.infer_expr( - uf, - &scope.env, - rank, - scope.state, - rtv, - body, - Expected::NoExpectation(result), - ); - state = self.close_locals(uf, state, scope.locals); - let function = args.into_iter().rev().fold(result, |tail, arg| { - self.structure(uf, rank, FlatType::Fun1(arg, tail)) - }); - self.equal( - uf, - rank, - state, - region, - Category::Lambda, - function, - expected, - ) - } - CanExpr::Call { - function, - arguments, - } => { - let name = direct_get_name(function); - let function_var = self.fresh(uf, rank); - let result = self.fresh(uf, rank); - let args: Vec<_> = arguments.iter().map(|_| self.fresh(uf, rank)).collect(); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - function, - Expected::NoExpectation(function_var), - ); - let arity_type = args.iter().rev().fold(result, |tail, arg| { - self.structure(uf, rank, FlatType::Fun1(*arg, tail)) - }); - state = self.equal( - uf, - rank, - state, - function.region, - Category::CallResult(name), - function_var, - Expected::FromContext( - region, - Context::CallArity(name, arguments.len()), - arity_type, - ), - ); - for (index, (arg, var)) in arguments.iter().zip(args).enumerate() { - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - arg, - Expected::FromContext(region, Context::CallArg(name, index), var), - ); - } - self.equal( - uf, - rank, - state, - region, - Category::CallResult(name), - result, - expected, - ) - } - CanExpr::If { - branches, - final_else, - } => { - // All conditions precede all branch bodies, including else-if. - let branch_var = self.fresh(uf, rank); - for branch in *branches { - let boolean = self.structure( - uf, - rank, - FlatType::App1(nash_ast::primitives::primitive_home(), "bool", vec![]), - ); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - branch.condition, - Expected::FromContext(region, Context::IfCondition, boolean), - ); - } - let mut previous_branch = None; - for (index, branch) in branches - .iter() - .map(|branch| branch.then_branch) - .chain(std::iter::once(*final_else)) - .enumerate() - { - let branch_expected = Expected::FromContext( - region, - Context::IfBranch(index, previous_branch), - branch_var, - ); - state = self.infer_expr(uf, env, rank, state, rtv, branch, branch_expected); - previous_branch = Some(branch.region); - } - self.equal(uf, rank, state, region, Category::If, branch_var, expected) - } - CanExpr::Case { - scrutinee, - branches, - } => { - let matched = self.fresh(uf, rank); - let branch_var = self.fresh(uf, rank); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - scrutinee, - Expected::NoExpectation(matched), - ); - for (index, branch) in branches.iter().enumerate() { - let scope = self.infer_patterns( - uf, - env, - rank, - state, - &[( - branch.pattern, - PExpected::FromContext(region, PContext::CaseMatch(index), matched), - )], - ); - let branch_expected = Expected::FromContext( - region, - Context::CaseBranch( - index, - index.checked_sub(1).map(|i| branches[i].body.region), - ), - branch_var, - ); - state = self.infer_expr( - uf, - &scope.env, - rank, - scope.state, - rtv, - branch.body, - branch_expected, - ); - state = self.close_locals(uf, state, scope.locals); - } - self.equal( - uf, - rank, - state, - region, - Category::Case, - branch_var, - expected, - ) - } - CanExpr::Let { definition, body } => { - let scope = self.infer_definition(uf, env, rank, state, rtv, definition, true); - state = self.infer_expr(uf, &scope.env, rank, scope.state, rtv, body, expected); - self.close_locals(uf, state, scope.locals) - } - CanExpr::LetRec { definitions, body } => { - let scope = self.infer_group(uf, env, rank, state, rtv, definitions); - state = self.infer_expr(uf, &scope.env, rank, scope.state, rtv, body, expected); - self.close_locals(uf, state, scope.locals) - } - CanExpr::LetDestruct { - pattern, - value, - body, - } => { - let scope = self.infer_destruct(uf, env, rank, state, rtv, region, pattern, value); - state = self.infer_expr(uf, &scope.env, rank, scope.state, rtv, body, expected); - self.close_locals(uf, state, scope.locals) - } - CanExpr::Accessor(field) => { - let record = self.fresh(uf, rank); - let value = self.fresh(uf, rank); - state = self.field( - uf, - rank, - state, - DeferredField { - test_scope: self.test_scope, - region, - context: type_::FieldContext::Accessor, - record, - field: Some((field, value)), - }, - ); - let function = self.structure(uf, rank, FlatType::Fun1(record, value)); - self.equal( - uf, - rank, - state, - region, - Category::Accessor(field), - function, - expected, - ) - } - CanExpr::Access { record, field } => { - let record_var = self.fresh(uf, rank); - let value = self.fresh(uf, rank); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - record, - Expected::NoExpectation(record_var), - ); - state = self.field( - uf, - rank, - state, - DeferredField { - test_scope: self.test_scope, - region, - context: type_::FieldContext::Access { - record_region: record.region, - maybe_name: direct_get_access_name(record), - }, - record: record_var, - field: Some((field.value, value)), - }, - ); - self.equal( - uf, - rank, - state, - region, - Category::Access(field.value), - value, - expected, - ) - } - CanExpr::Update { - record, - base, - fields, - } => { - let record_var = self.fresh(uf, rank); - let values: Vec<_> = fields.iter().map(|_| self.fresh(uf, rank)).collect(); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - base, - Expected::FromContext( - region, - Context::RecordUpdateKeys(record, fields), - record_var, - ), - ); - if fields.is_empty() { - state = self.field( - uf, - rank, - state, - DeferredField { - test_scope: self.test_scope, - region, - context: type_::FieldContext::Update { record }, - record: record_var, - field: None, - }, - ); - } - for (field, var) in fields.iter().zip(values) { - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - field.value, - Expected::FromContext( - region, - Context::RecordUpdateValue(field.field.value), - var, - ), - ); - state = self.field( - uf, - rank, - state, - DeferredField { - test_scope: self.test_scope, - region: field.field.region, - context: type_::FieldContext::Update { record }, - record: record_var, - field: Some((field.field.value, var)), - }, - ); - } - self.equal( - uf, - rank, - state, - region, - Category::Record, - record_var, - expected, - ) - } - CanExpr::Record { - alias, - annotation, - fields, - } => { - let args: Vec<_> = fields.iter().map(|_| self.fresh(uf, rank)).collect(); - let result = self.fresh(uf, rank); - for (field, var) in fields.iter().zip(&args) { - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - field.value, - Expected::FromContext( - region, - Context::RecordField(alias.name, field.field.value), - *var, - ), - ); - } - let constructor = args.into_iter().rev().fold(result, |tail, arg| { - self.structure(uf, rank, FlatType::Fun1(arg, tail)) - }); - state = self.foreign( - uf, - rank, - state, - region, - node, - alias.name, - annotation, - Expected::NoExpectation(constructor), - ); - self.equal(uf, rank, state, region, Category::Record, result, expected) - } - CanExpr::Assert(condition) => { - let boolean = self.structure( - uf, - rank, - FlatType::App1(nash_ast::primitives::primitive_home(), "bool", vec![]), - ); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - condition, - Expected::NoExpectation(boolean), - ); - let unit = self.structure( - uf, - rank, - FlatType::App1(nash_ast::primitives::primitive_home(), "unit", vec![]), - ); - self.equal(uf, rank, state, region, Category::Unit, unit, expected) - } - CanExpr::Fail(message) | CanExpr::Todo(message) => { - if let Some(message) = message { - let string = self.structure( - uf, - rank, - FlatType::App1(nash_ast::primitives::primitive_home(), "string", vec![]), - ); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - message, - Expected::NoExpectation(string), - ); - } - state - } - CanExpr::Trace { message, body } => { - let string = self.structure( - uf, - rank, - FlatType::App1(nash_ast::primitives::primitive_home(), "string", vec![]), - ); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - message, - Expected::NoExpectation(string), - ); - self.infer_expr(uf, env, rank, state, rtv, body, expected) - } - CanExpr::Comptime(inner) => self.infer_expr(uf, env, rank, state, rtv, inner, expected), - CanExpr::Tuple { - first, - second, - rest, - } => { - let first_var = self.fresh(uf, rank); - let second_var = self.fresh(uf, rank); - let tail: Vec<_> = rest.iter().map(|_| self.fresh(uf, rank)).collect(); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - first, - Expected::NoExpectation(first_var), - ); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - second, - Expected::NoExpectation(second_var), - ); - for (item, var) in rest.iter().zip(&tail) { - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - item, - Expected::NoExpectation(*var), - ); - } - let tuple = self.structure(uf, rank, FlatType::Tuple1(first_var, second_var, tail)); - self.equal(uf, rank, state, region, Category::Tuple, tuple, expected) - } - } - } -} - -fn direct_get_name<'a>(expr: &Located>) -> MaybeName<'a> { - match &expr.value { - CanExpr::VarMethod { method, .. } => MaybeName::FuncName(method), - CanExpr::VarLocal(name) => MaybeName::FuncName(name), - CanExpr::VarTopLevel(reference) | CanExpr::VarForeign { reference, .. } => { - MaybeName::FuncName(reference.name) - } - CanExpr::VarConstructor { reference, .. } => MaybeName::CtorName(reference.name), - CanExpr::VarOperator { symbol, .. } => MaybeName::OpName(symbol), - _ => MaybeName::NoName, - } -} - -fn direct_get_access_name<'a>(expr: &Located>) -> Option<&'a str> { - match &expr.value { - CanExpr::VarLocal(name) => Some(name), - CanExpr::VarTopLevel(reference) | CanExpr::VarForeign { reference, .. } => { - Some(reference.name) - } - _ => None, - } -} - -impl<'a> Solver<'a, '_> { - /// An annotation is canonical syntax, not a shared unification structure. - /// Reinstantiate it at each branch equation so one failed branch cannot - /// poison another branch's structural expectation. Its rigid variables - /// still come from the same lexical substitution. - #[allow(clippy::too_many_arguments)] - pub(super) fn infer_annotated_expr( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - mut state: State<'a>, - rtv: &BTreeMap<&'a str, Variable>, - expr: &Located>, - expected: Expected<'a, &'a Located>>, - ) -> State<'a> { - let Expected::FromAnnotation(name, annotation_region, arity, _, typ) = expected else { - unreachable!("annotated expression has its canonical expectation") - }; - // These forms recurse directly through canonical expectations instead - // of entering infer_expr. Retain their original arena node identities. - if matches!( - expr.value, - CanExpr::If { .. } - | CanExpr::Case { .. } - | CanExpr::Let { .. } - | CanExpr::LetRec { .. } - | CanExpr::LetDestruct { .. } - | CanExpr::Trace { .. } - | CanExpr::Comptime(_) - ) { - let variable = self.src_type_to_var(uf, rank, rtv, typ); - self.expr_types.push(NodeTypeRecord { - node: NodeId::expr(expr), - variable, - owner: self.owners.last().copied(), - }); - } - let region = expr.region; - match &expr.value { - CanExpr::Trace { message, body } => { - let string = self.structure( - uf, - rank, - FlatType::App1(nash_ast::primitives::primitive_home(), "string", vec![]), - ); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - message, - Expected::NoExpectation(string), - ); - self.infer_annotated_expr(uf, env, rank, state, rtv, body, expected) - } - CanExpr::Comptime(inner) => { - self.infer_annotated_expr(uf, env, rank, state, rtv, inner, expected) - } - CanExpr::If { - branches, - final_else, - } => { - for branch in *branches { - let boolean = self.structure( - uf, - rank, - FlatType::App1(nash_ast::primitives::primitive_home(), "bool", Vec::new()), - ); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - branch.condition, - Expected::FromContext(region, Context::IfCondition, boolean), - ); - } - for (index, branch) in branches - .iter() - .map(|branch| branch.then_branch) - .chain(std::iter::once(*final_else)) - .enumerate() - { - state = self.infer_annotated_expr( - uf, - env, - rank, - state, - rtv, - branch, - Expected::FromAnnotation( - name, - annotation_region, - arity, - SubContext::TypedIfBranch(index), - typ, - ), - ); - } - state - } - CanExpr::Case { - scrutinee, - branches, - } => { - let start = self.wanted.len(); - let matched = self.fresh(uf, rank); - state = self.infer_expr( - uf, - env, - rank, - state, - rtv, - scrutinee, - Expected::NoExpectation(matched), - ); - for (index, branch) in branches.iter().enumerate() { - let scope = self.infer_patterns( - uf, - env, - rank, - state, - &[( - branch.pattern, - PExpected::FromContext(region, PContext::CaseMatch(index), matched), - )], - ); - state = self.infer_annotated_expr( - uf, - &scope.env, - rank, - scope.state, - rtv, - branch.body, - Expected::FromAnnotation( - name, - annotation_region, - arity, - SubContext::TypedCaseBranch(index), - typ, - ), - ); - state = self.close_locals(uf, state, scope.locals); - } - self.retry_fields(uf, rank, &mut state.errors); - self.resolve_wanted(uf, rank, state, start, None, false) - } - CanExpr::Let { definition, body } => { - let scope = self.infer_definition(uf, env, rank, state, rtv, definition, true); - state = self.infer_annotated_expr( - uf, - &scope.env, - rank, - scope.state, - rtv, - body, - expected, - ); - self.close_locals(uf, state, scope.locals) - } - CanExpr::LetRec { definitions, body } => { - let scope = self.infer_group(uf, env, rank, state, rtv, definitions); - state = self.infer_annotated_expr( - uf, - &scope.env, - rank, - scope.state, - rtv, - body, - expected, - ); - self.close_locals(uf, state, scope.locals) - } - CanExpr::LetDestruct { - pattern, - value, - body, - } => { - let scope = self.infer_destruct(uf, env, rank, state, rtv, region, pattern, value); - state = self.infer_annotated_expr( - uf, - &scope.env, - rank, - scope.state, - rtv, - body, - expected, - ); - self.close_locals(uf, state, scope.locals) - } - _ => { - let variable = self.src_type_to_var(uf, rank, rtv, typ); - self.infer_expr( - uf, - env, - rank, - state, - rtv, - expr, - expected.type_replace(variable), - ) - } - } - } -} diff --git a/crates/nash-solve/src/solve/infer.rs b/crates/nash-solve/src/solve/infer.rs deleted file mode 100644 index 3fc6277a..00000000 --- a/crates/nash-solve/src/solve/infer.rs +++ /dev/null @@ -1,1309 +0,0 @@ -//! Infer directly from canonical definitions. Only union-find variables cross scopes. -use super::*; -use nash_ast::{Decls, Def, Expr, Module, Pattern}; -use nash_constrain::error::{Context, PCategory, PContext, SubContext}; -use type_::Binder; - -type Rtv<'a> = BTreeMap<&'a str, Variable>; -type Locals<'a> = Vec<(&'a str, Located)>; -type Arguments<'a> = Vec<(&'a Located>, PExpected<'a, Variable>)>; - -#[derive(Clone, Copy)] -pub(super) struct Definition<'a> { - pub site: Binder<'a>, - pub typ: Variable, - pub context: Option<&'a [Body<'a>]>, -} - -pub(super) struct ScopeResult<'a> { - pub env: Env<'a>, - pub state: State<'a>, - pub locals: Locals<'a>, -} - -struct PreparedDefinition<'a> { - definition: Definition<'a>, - arguments: Arguments<'a>, - source: &'a Def<'a>, - expected: Expected<'a, Variable>, - rtv: Rtv<'a>, - rigids: &'a [Variable], -} - -impl<'a> Solver<'a, '_> { - pub(super) fn fresh(&mut self, uf: &mut UnionFind<'a>, rank: usize) -> Variable { - self.register(uf, rank, Content::FlexVar(None)) - } - - pub(super) fn structure( - &mut self, - uf: &mut UnionFind<'a>, - rank: usize, - typ: FlatType<'a>, - ) -> Variable { - let typ = type_::normalize_application(uf, typ); - self.register(uf, rank, Content::Structure(typ)) - } - - pub(super) fn field( - &mut self, - uf: &mut UnionFind<'a>, - rank: usize, - mut state: State<'a>, - field: DeferredField<'a>, - ) -> State<'a> { - if let Some((_, typ)) = field.field { - self.dependencies.field(typ, field.record); - } - self.fields.push(field); - self.retry_fields(uf, rank, &mut state.errors); - state - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn equal( - &mut self, - uf: &mut UnionFind<'a>, - rank: usize, - state: State<'a>, - region: Region, - category: Category<'a>, - actual: Variable, - expectation: Expected<'a, Variable>, - ) -> State<'a> { - let expected = expectation_type(expectation); - if let Expected::FromContext(_, Context::CallArity(_, arity), _) = expectation { - let mut result = expected; - let mut inputs = vec![actual]; - for _ in 0..arity { - let Content::Structure(FlatType::Fun1(argument, output)) = uf.get(result).content - else { - break; - }; - inputs.push(argument); - result = output; - } - self.dependencies.computation(result, inputs); - } - self.formed_at(uf, rank, &[actual, expected], region); - match self.unify(uf, actual, expected) { - unify::Answer::Ok(vars) => { - self.introduce(uf, rank, &vars); - state - } - unify::Answer::Err(vars, actual, expected) => { - self.introduce(uf, rank, &vars); - add_error( - state, - Error::BadExpr(region, category, actual, expectation.type_replace(expected)), - ) - } - } - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn pattern_equal( - &mut self, - uf: &mut UnionFind<'a>, - rank: usize, - state: State<'a>, - region: Region, - category: PCategory<'a>, - actual: Variable, - expectation: PExpected<'a, Variable>, - ) -> State<'a> { - let expected = match expectation { - PExpected::NoExpectation(t) | PExpected::FromContext(_, _, t) => t, - }; - self.formed_at(uf, rank, &[actual, expected], region); - match self.unify(uf, actual, expected) { - unify::Answer::Ok(vars) => { - self.introduce(uf, rank, &vars); - state - } - unify::Answer::Err(vars, actual, expected) => { - self.introduce(uf, rank, &vars); - add_error( - state, - Error::BadPattern(region, category, actual, expectation.type_replace(expected)), - ) - } - } - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn local( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - state: State<'a>, - region: Region, - node: nash_ast::NodeId, - name: &'a str, - expected: Expected<'a, Variable>, - ) -> State<'a> { - let binding = *env.get(name).expect("canonical local is bound"); - let actual = self.instantiate_binding(uf, rank, binding, UseSite { node, region, name }); - self.equal( - uf, - rank, - state, - region, - Category::Local(name), - actual, - expected, - ) - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn foreign( - &mut self, - uf: &mut UnionFind<'a>, - rank: usize, - state: State<'a>, - region: Region, - node: nash_ast::NodeId, - name: &'a str, - annotation: &'a nash_ast::Annotation<'a>, - expected: Expected<'a, Variable>, - ) -> State<'a> { - let actual = - self.src_type_to_variable(uf, rank, UseSite { node, region, name }, annotation); - self.equal( - uf, - rank, - state, - region, - Category::Foreign(name), - actual, - expected, - ) - } - - fn young_pool(&mut self, rank: usize) -> usize { - let young = rank + 1; - if young >= self.pools.len() { - self.pools.resize(self.pools.len() * 2, Vec::new()); - } - assert!( - self.pools[young].is_empty(), - "young pool belongs to one active scope" - ); - young - } - - fn generalize_scope( - &mut self, - uf: &mut UnionFind<'a>, - rank: usize, - mut state: State<'a>, - ) -> State<'a> { - self.retry_fields(uf, rank, &mut state.errors); - self.finish_fields(uf, rank, &mut state.errors); - self.generalize(uf, state.mark, state.mark.next(), rank); - self.pools[rank].clear(); - state.mark = state.mark.next().next(); - state - } - - pub(super) fn close_locals( - &mut self, - uf: &mut UnionFind<'a>, - state: State<'a>, - locals: Locals<'a>, - ) -> State<'a> { - locals.into_iter().fold(state, |state, (name, loc)| { - self.check_occurs(uf, state, name, loc) - }) - } - - pub(super) fn infer_patterns( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - mut state: State<'a>, - args: &[(&Located>, PExpected<'a, Variable>)], - ) -> ScopeResult<'a> { - let owns = args - .iter() - .any(|(pattern, _)| super::patterns::pattern_owns_vars(pattern)); - let pattern_rank = if owns { self.young_pool(rank) } else { rank }; - let start = self.wanted.len(); - let mut headers = BTreeMap::new(); - for (pattern, expected) in args.iter().rev() { - state = self.infer_pattern(uf, pattern_rank, state, pattern, *expected, &mut headers); - } - self.finish_pattern_scope(uf, env, rank, pattern_rank, state, start, headers) - } - - #[allow(clippy::too_many_arguments)] - fn finish_pattern_scope( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - pattern_rank: usize, - mut state: State<'a>, - start: usize, - headers: BTreeMap<&'a str, Located>, - ) -> ScopeResult<'a> { - self.retry_fields(uf, pattern_rank, &mut state.errors); - state = self.resolve_wanted(uf, pattern_rank, state, start, None, false); - if pattern_rank != rank { - state = self.generalize_scope(uf, pattern_rank, state); - } - let locals: Locals<'a> = headers.into_iter().collect(); - let mut env = env.clone(); - for (name, loc) in &locals { - env.entry(name).or_insert(Binding { - variable: loc.value, - context: &[], - definition: None, - context_is_final: true, - declared_quantifiers: &[], - }); - } - ScopeResult { env, state, locals } - } - - fn prepare_definition( - &mut self, - uf: &mut UnionFind<'a>, - rank: usize, - rtv: &Rtv<'a>, - def: &'a Def<'a>, - ) -> PreparedDefinition<'a> { - let mut rtv = rtv.clone(); - let mut rigids = Vec::new(); - let (name, arguments, result, context, annotation_region) = match def { - Def::Def { name, args, .. } => { - let arguments: Arguments<'a> = args - .iter() - .map(|pattern| (*pattern, PExpected::NoExpectation(self.fresh(uf, rank)))) - .collect(); - (*name, arguments, self.fresh(uf, rank), None, None) - } - Def::TypedDef { - name, - free_vars, - context, - args, - typ, - annotation, - .. - } => { - let mut names: Vec<_> = free_vars - .iter() - .copied() - .filter(|name| !rtv.contains_key(name)) - .collect(); - names.sort_unstable(); - for name in names { - let var = self.register(uf, rank, Content::RigidVar(name)); - rigids.push(var); - rtv.insert(name, var); - } - let arguments: Arguments<'a> = args - .iter() - .enumerate() - .map(|(index, arg)| { - let typ = self.src_type_to_var(uf, rank, &rtv, arg.typ); - ( - arg.pattern, - PExpected::FromContext( - arg.pattern.region, - PContext::TypedArg(name.value, index, annotation.region), - typ, - ), - ) - }) - .collect(); - let result = self.src_type_to_var(uf, rank, &rtv, typ); - let context: Vec<_> = context - .iter() - .map(|pred| self.canonical_predicate(uf, rank, &rtv, *pred)) - .collect(); - ( - *name, - arguments, - result, - Some(&*self.bump.alloc_slice_fill_iter(context)), - Some(annotation.region), - ) - } - }; - // Splitting arguments can expand a function alias; retain its declared identity. - let typ = if let Def::TypedDef { annotation, .. } = def { - self.src_type_to_var(uf, rank, &rtv, annotation) - } else { - arguments - .iter() - .rev() - .fold(result, |result, (_, expected)| { - let arg = match expected { - PExpected::NoExpectation(t) | PExpected::FromContext(_, _, t) => *t, - }; - self.structure(uf, rank, FlatType::Fun1(arg, result)) - }) - }; - let expected = if let Some(annotation_region) = annotation_region { - Expected::FromAnnotation( - name.value, - annotation_region, - arguments.len(), - SubContext::TypedBody, - result, - ) - } else { - Expected::NoExpectation(result) - }; - PreparedDefinition { - definition: Definition { - site: Binder::Named(name), - typ, - context, - }, - arguments, - source: def, - expected, - rtv, - rigids: self.bump.alloc_slice_copy(&rigids), - } - } - - fn infer_prepared_body( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - state: State<'a>, - prepared: &PreparedDefinition<'a>, - ) -> State<'a> { - match prepared.source { - Def::Def { body, .. } => { - let scope = self.infer_patterns(uf, env, rank, state, &prepared.arguments); - let state = self.infer_expr( - uf, - &scope.env, - rank, - scope.state, - &prepared.rtv, - body, - prepared.expected, - ); - self.close_locals(uf, state, scope.locals) - } - Def::TypedDef { - name, - args, - body, - typ, - annotation, - .. - } => { - let scope = self.infer_typed_patterns( - uf, - env, - rank, - state, - name.value, - annotation.region, - args, - &prepared.rtv, - ); - let state = self.infer_annotated_expr( - uf, - &scope.env, - rank, - scope.state, - &prepared.rtv, - body, - prepared.expected.type_replace(*typ), - ); - self.close_locals(uf, state, scope.locals) - } - } - } - - #[allow(clippy::too_many_arguments)] - fn infer_typed_patterns( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - mut state: State<'a>, - name: &'a str, - annotation_region: Region, - args: &[nash_ast::TypedPattern<'a>], - rtv: &Rtv<'a>, - ) -> ScopeResult<'a> { - let owns = args - .iter() - .any(|arg| super::patterns::pattern_owns_vars(arg.pattern)); - let pattern_rank = if owns { self.young_pool(rank) } else { rank }; - let start = self.wanted.len(); - let mut headers = BTreeMap::new(); - for (index, arg) in args.iter().enumerate().rev() { - state = self.infer_canonical_pattern( - uf, - pattern_rank, - state, - arg.pattern, - PExpected::FromContext( - arg.pattern.region, - PContext::TypedArg(name, index, annotation_region), - arg.typ, - ), - rtv, - &mut headers, - ); - } - self.finish_pattern_scope(uf, env, rank, pattern_rank, state, start, headers) - } - - #[allow(clippy::too_many_arguments)] - fn finish_bindings( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - mut state: State<'a>, - definitions: &[Definition<'a>], - declarations: &[Definition<'a>], - rigids: &'a [Variable], - locals: Locals<'a>, - declared: &BTreeMap<&'a str, &'a [type_::PredId]>, - binder: Option>, - given: &[Body<'a>], - wanted_start: usize, - errors_before: usize, - ) -> ScopeResult<'a> { - let young = rank + 1; - state = self.generalize_scope(uf, young, state); - let escapes_before = state.errors.len(); - for rigid in rigids { - if uf.get(*rigid).rank != NO_RANK && !crate::recovery::is_poisoned(uf, [*rigid]) { - let owner = binder - .map(|b| (b.name().region, b.name().value)) - .or_else(|| locals.first().map(|(name, loc)| (loc.region, *name))); - state.errors.push(Error::AnnotationVariableEscapes { - region: owner.map_or_else(Region::zero, |(r, _)| r), - name: owner.map(|(_, n)| n), - variable: to_error_type(self.bump, uf, *rigid), - }); - } - } - // A body error leaves a valid annotation usable by callers, as in Elm. - // Only an annotation that lets its own variables escape blocks its uses. - let annotated = !definitions.is_empty() && definitions.iter().all(|d| d.context.is_some()); - let annotation_failed = state.errors.len() > escapes_before; - if let Some(binder) = binder { - let depth = self.enter_givens(uf, rank, given, Some(binder)); - loop { - let (errors, defaulted) = - self.check_ambiguity(uf, rank, wanted_start, definitions, binder.name()); - state.errors.extend(errors); - if !defaulted { - break; - } - // The young scope is already generalized. Defaulting can make - // representation queries allocate alias substitutions; those - // belong to the enclosing live scope. - state = self.resolve_wanted( - uf, - rank, - state, - wanted_start, - Some(binder), - definitions.iter().any(|d| d.context.is_some()), - ); - } - self.givens.truncate(depth); - } - let context = if !definitions.is_empty() && definitions.iter().all(|d| d.context.is_none()) - { - self.retain_wanted( - uf, - rank, - wanted_start, - binder.expect("inferred binding owner").node(), - ) - } else { - &[] - }; - let failed = if annotated { - annotation_failed - } else { - state.errors.len() > errors_before - }; - if failed && let Some(binder) = binder { - self.fail_definition(uf, binder.node()); - } - self.record_definitions(uf, rank, definitions, declared, context, binder); - let mut env = env.clone(); - for (name, loc) in &locals { - env.entry(name).or_insert(Binding { - variable: loc.value, - context: declared.get(name).copied().unwrap_or(context), - definition: definitions - .iter() - .chain(declarations) - .find(|d| d.site.name().value == *name) - .map(|d| d.site.node()) - .or_else(|| { - binder - .filter(|b| matches!(b, Binder::Pattern { .. })) - .map(Binder::node) - }), - context_is_final: true, - declared_quantifiers: if declarations - .iter() - .any(|d| d.site.name().value == *name && d.context.is_some()) - { - rigids - } else { - &[] - }, - }); - } - ScopeResult { env, state, locals } - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn infer_definition( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - state: State<'a>, - rtv: &Rtv<'a>, - def: &'a Def<'a>, - bind_name: bool, - ) -> ScopeResult<'a> { - let young = self.young_pool(rank); - let prepared = self.prepare_definition(uf, young, rtv, def); - self.check_prepared(uf, env, rank, state, prepared, bind_name) - } - - fn check_prepared( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - state: State<'a>, - prepared: PreparedDefinition<'a>, - bind_name: bool, - ) -> ScopeResult<'a> { - let young = rank + 1; - let errors_before = state.errors.len(); - let start = self.wanted.len(); - let definition = prepared.definition; - let binder = Some(definition.site); - let declared = self.declared_contexts(uf, young, &[definition], &[]); - let given = definition.context.unwrap_or(&[]); - let depth = self.enter_givens(uf, young, given, binder); - let owners = self.owners.len(); - self.owners.push(definition.site.node()); - let mut state = self.infer_prepared_body(uf, env, young, state, &prepared); - self.retry_fields(uf, young, &mut state.errors); - state = self.resolve_wanted( - uf, - young, - state, - start, - binder, - definition.context.is_some(), - ); - if state.errors.len() > errors_before && definition.context.is_none() { - self.fail_definition(uf, definition.site.node()); - } - self.givens.truncate(depth); - self.owners.truncate(owners); - let name = definition.site.name(); - let locals = if bind_name { - vec![(name.value, Located::at(name.region, definition.typ))] - } else { - Vec::new() - }; - self.finish_bindings( - uf, - env, - rank, - state, - &[definition], - &[], - prepared.rigids, - locals, - &declared, - binder, - given, - start, - errors_before, - ) - } - - pub(super) fn infer_module( - &mut self, - uf: &mut UnionFind<'a>, - module: &Module<'a>, - state: State<'a>, - ) -> State<'a> { - self.infer_decls(uf, &Env::new(), OUTERMOST_RANK, state, module.decls, module) - } - - fn infer_decls( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - state: State<'a>, - decls: &Decls<'a>, - module: &Module<'a>, - ) -> State<'a> { - let (scope, next) = match decls { - Decls::Declare { definition, next } => ( - self.infer_definition(uf, env, rank, state, &Rtv::new(), definition, true), - *next, - ), - Decls::DeclareRec { - definition, - following, - next, - } => { - let mut defs = vec![*definition]; - defs.extend_from_slice(following); - ( - self.infer_group(uf, env, rank, state, &Rtv::new(), &defs), - *next, - ) - } - Decls::Empty => { - let mut state = state; - for definition in module - .traits - .iter() - .flat_map(|t| t.value.methods.iter().filter_map(|m| m.default)) - .chain( - module - .impls - .iter() - .flat_map(|i| i.value.methods.iter().copied()), - ) - { - let scope = - self.infer_definition(uf, env, rank, state, &Rtv::new(), definition, false); - state = self.close_locals(uf, scope.state, scope.locals); - } - for test in module.tests { - self.test_scope = true; - let young = self.young_pool(rank); - let start = self.wanted.len(); - let errors_before = state.errors.len(); - let binder = Binder::Named(test.name); - let unit = self.structure( - uf, - young, - FlatType::App1(nash_ast::primitives::primitive_home(), "unit", vec![]), - ); - let definition = Definition { - site: binder, - typ: unit, - context: None, - }; - let owners = self.owners.len(); - self.owners.push(binder.node()); - let mut patterns = Vec::new(); - for binder in test.binders { - let element = self.fresh(uf, young); - let base = Some(nash_ast::primitives::BASE); - let prng = self.structure( - uf, - young, - FlatType::App1( - nash_ast::ModuleName { - package: base, - name: "Prop", - }, - "prng", - vec![], - ), - ); - let pair = - self.structure(uf, young, FlatType::Tuple1(element, prng, vec![])); - let result = self.structure( - uf, - young, - FlatType::App1( - nash_ast::ModuleName { - package: base, - name: "Option", - }, - "option", - vec![pair], - ), - ); - let generator = self.structure(uf, young, FlatType::Fun1(prng, result)); - state = self.infer_expr( - uf, - env, - young, - state, - &Rtv::new(), - binder.generator, - Expected::FromContext( - binder.generator.region, - Context::TestGenerator, - generator, - ), - ); - patterns.push((binder.pattern, PExpected::NoExpectation(element))); - } - let scope = self.infer_patterns(uf, env, young, state, &patterns); - state = self.infer_expr( - uf, - &scope.env, - young, - scope.state, - &Rtv::new(), - test.body, - Expected::FromContext(test.region, Context::TestBody, unit), - ); - self.retry_fields(uf, young, &mut state.errors); - state = self.resolve_wanted(uf, young, state, start, Some(binder), false); - state = self.close_locals(uf, state, scope.locals); - self.owners.truncate(owners); - // Tests own solved metadata and evidence without entering the value environment. - state = self - .finish_bindings( - uf, - env, - rank, - state, - &[definition], - &[], - &[], - Vec::new(), - &BTreeMap::new(), - Some(binder), - &[], - start, - errors_before, - ) - .state; - } - self.test_scope = false; - state.env = env.clone(); - return state; - } - }; - let state = self.infer_decls(uf, &scope.env, rank, scope.state, next, module); - self.close_locals(uf, state, scope.locals) - } -} - -pub(super) fn expectation_type(expected: Expected<'_, Variable>) -> Variable { - match expected { - Expected::NoExpectation(t) - | Expected::FromContext(_, _, t) - | Expected::FromAnnotation(_, _, _, _, t) => t, - } -} - -impl<'a> Solver<'a, '_> { - pub(super) fn infer_group( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - mut state: State<'a>, - rtv: &Rtv<'a>, - defs: &[&'a Def<'a>], - ) -> ScopeResult<'a> { - let owns_rigids = defs.iter().any(|def| match def { - Def::TypedDef { free_vars, .. } => free_vars.iter().any(|name| !rtv.contains_key(name)), - _ => false, - }); - let declared_rank = if owns_rigids { - self.young_pool(rank) - } else { - rank - }; - let mut typed = Vec::new(); - for def in defs - .iter() - .filter(|def| matches!(def, Def::TypedDef { .. })) - { - typed.push((*def, self.prepare_definition(uf, declared_rank, rtv, def))); - } - let declarations: Vec<_> = typed.iter().map(|(_, p)| p.definition).collect(); - let rigid_vars: Vec<_> = typed - .iter() - .rev() - .flat_map(|(_, p)| p.rigids.iter().copied()) - .collect(); - let rigid_vars = &*self.bump.alloc_slice_copy(&rigid_vars); - let declared = self.declared_contexts(uf, declared_rank, &[], &declarations); - if owns_rigids { - state = self.generalize_scope(uf, declared_rank, state); - } - let mut declared_env = env.clone(); - let mut locals = BTreeMap::new(); - for declaration in &declarations { - let name = declaration.site.name(); - locals.insert(name.value, Located::at(name.region, declaration.typ)); - declared_env.entry(name.value).or_insert(Binding { - variable: declaration.typ, - context: declared.get(name.value).copied().unwrap_or(&[]), - definition: Some(declaration.site.node()), - context_is_final: true, - declared_quantifiers: rigid_vars, - }); - } - let inferred_defs: Vec<_> = defs - .iter() - .filter(|def| matches!(def, Def::Def { .. })) - .copied() - .collect(); - let mut result = if inferred_defs.is_empty() { - ScopeResult { - env: declared_env, - state, - locals: Vec::new(), - } - } else { - let young = self.young_pool(rank); - let prepared: Vec<_> = inferred_defs - .iter() - .map(|def| self.prepare_definition(uf, young, rtv, def)) - .collect(); - let definitions: Vec<_> = prepared.iter().map(|p| p.definition).collect(); - let binder = Some(definitions[0].site); - let mut recursive_env = declared_env.clone(); - let mut inferred_locals = BTreeMap::new(); - for definition in &definitions { - let name = definition.site.name(); - inferred_locals.insert(name.value, Located::at(name.region, definition.typ)); - recursive_env.entry(name.value).or_insert(Binding { - variable: definition.typ, - context: &[], - definition: Some(definition.site.node()), - context_is_final: false, - declared_quantifiers: &[], - }); - } - let errors_before = state.errors.len(); - let start = self.wanted.len(); - let owners = self.owners.len(); - self.owners.push(definitions[0].site.node()); - for prepared in prepared.iter().rev() { - state = self.infer_prepared_body(uf, &recursive_env, young, state, prepared); - } - // The recursive headers are checked inside the group before its - // generalization, as well as after the group's continuation. - state = self.close_locals( - uf, - state, - inferred_locals - .iter() - .map(|(name, loc)| (*name, *loc)) - .collect(), - ); - self.retry_fields(uf, young, &mut state.errors); - state = self.resolve_wanted(uf, young, state, start, binder, false); - self.owners.truncate(owners); - self.finish_bindings( - uf, - &declared_env, - rank, - state, - &definitions, - &[], - &[], - inferred_locals.into_iter().collect(), - &BTreeMap::new(), - binder, - &[], - start, - errors_before, - ) - }; - for (def, prepared) in typed.into_iter().rev() { - let young = self.young_pool(rank); - self.introduce(uf, young, prepared.rigids); - let mut body = self.prepare_definition(uf, young, &prepared.rtv, def); - body.rigids = prepared.rigids; - let checked = self.check_prepared(uf, &result.env, rank, result.state, body, false); - result.state = self.close_locals(uf, checked.state, checked.locals); - } - locals.extend(result.locals); - result.locals = locals.into_iter().collect(); - result - } - - #[allow(clippy::too_many_arguments)] - pub(super) fn infer_destruct( - &mut self, - uf: &mut UnionFind<'a>, - env: &Env<'a>, - rank: usize, - state: State<'a>, - rtv: &Rtv<'a>, - region: Region, - pattern: &'a Located>, - expr: &'a Located>, - ) -> ScopeResult<'a> { - let young = self.young_pool(rank); - let typ = self.fresh(uf, young); - let binder = Binder::Pattern { - node: nash_ast::NodeId::pattern(pattern), - name: self.bump.alloc(Located::at(region, "")), - }; - let definition = Definition { - site: binder, - typ, - context: None, - }; - let mut headers = BTreeMap::new(); - let errors_before = state.errors.len(); - let start = self.wanted.len(); - let owners = self.owners.len(); - self.owners.push(binder.node()); - let state = self.infer_pattern( - uf, - young, - state, - pattern, - PExpected::NoExpectation(typ), - &mut headers, - ); - let mut state = self.infer_expr( - uf, - env, - young, - state, - rtv, - expr, - Expected::FromContext(region, Context::Destructure, typ), - ); - self.retry_fields(uf, young, &mut state.errors); - state = self.resolve_wanted(uf, young, state, start, Some(binder), false); - self.owners.truncate(owners); - self.finish_bindings( - uf, - env, - rank, - state, - &[definition], - &[], - &[], - headers.into_iter().collect(), - &BTreeMap::new(), - Some(binder), - &[], - start, - errors_before, - ) - } -} - -#[cfg(test)] -mod preparation_tests { - use super::*; - use nash_ast::{Annotation, ModuleName, NodeId, Pred, QualifiedName, Type as CanType}; - - #[test] - fn apply_head_and_arguments_share_the_signature_substitution() { - let bump = Bump::new(); - let tables = nash_can::environment::Tables::default(); - let mut solver = Solver::new(&bump, &tables); - let mut uf = UnionFind::new(); - let f = solver.fresh(&mut uf, 2); - let a = solver.fresh(&mut uf, 2); - let scope = BTreeMap::from([("f", f), ("a", a)]); - let head = &*bump.alloc(Located::at_zero(CanType::Var("f"))); - let arg = &*bump.alloc(Located::at_zero(CanType::Var("a"))); - let args = bump.alloc_slice_copy(&[arg]); - let application = - solver.canonical_predicate(&mut uf, 2, &scope, Pred::Apply { head, args }); - let Body::Apply { - head: actual_head, - args: actual_args, - } = application - else { - panic!("Apply preserved") - }; - assert_eq!(actual_head, f); - assert_eq!(actual_args, [a]); - let representation = solver.canonical_predicate( - &mut uf, - 2, - &scope, - Pred::Implied { - trait_: nash_ast::primitives::ReprTrait::Big.qualified(), - args, - }, - ); - let Body::Trait { - hidden, - args, - trait_, - } = representation - else { - panic!("representation predicate preserved") - }; - assert!(hidden); - assert_eq!(trait_, nash_ast::primitives::ReprTrait::Big.qualified()); - assert_eq!(args, [a]); - let signature = Located::at_zero(CanType::App { - head, - args: bump.alloc_slice_copy(&[arg]), - }); - let signature = solver.src_type_to_var(&mut uf, 2, &scope, &signature); - let Content::Structure(FlatType::AppV1(type_head, type_args)) = &uf.get(signature).content - else { - panic!("type application preserved") - }; - assert_eq!(*type_head, actual_head); - assert_eq!(type_args, &actual_args); - } - - #[test] - fn prepared_rigids_preserve_order_captures_and_predicate_substitution() { - let bump = Bump::new(); - let tables = nash_can::environment::Tables::default(); - let mut solver = Solver::new(&bump, &tables); - let mut uf = UnionFind::new(); - let captured = solver.register(&mut uf, 1, Content::RigidVar("captured")); - let scope = BTreeMap::from([("captured", captured)]); - let z = &*bump.alloc(Located::at_zero(CanType::Var("z"))); - let cap = &*bump.alloc(Located::at_zero(CanType::Var("captured"))); - let a = &*bump.alloc(Located::at_zero(CanType::Var("a"))); - let result = &*bump.alloc(Located::at_zero(CanType::App { - head: z, - args: bump.alloc_slice_copy(&[cap, a]), - })); - let definition = bump.alloc(Def::TypedDef { - name: bump.alloc(Located::at_zero("test")), - free_vars: &["z", "captured", "a"], - context: bump.alloc_slice_copy(&[Pred::Apply { - head: z, - args: bump.alloc_slice_copy(&[cap, a]), - }]), - annotation: result, - args: &[], - body: bump.alloc(Located::at_zero(Expr::Unit)), - typ: result, - }); - let prepared = solver.prepare_definition(&mut uf, 2, &scope, definition); - assert_eq!(prepared.rigids.len(), 2); - assert!(matches!( - uf.get(prepared.rigids[0]).content, - Content::RigidVar("a") - )); - assert!(matches!( - uf.get(prepared.rigids[1]).content, - Content::RigidVar("z") - )); - assert_eq!(prepared.rtv["captured"], captured); - assert_eq!(uf.get(captured).rank, 1); - assert!(prepared.rigids.iter().all(|var| uf.get(*var).rank == 2)); - let [Body::Apply { head, args }] = prepared.definition.context.unwrap() else { - panic!("Apply context") - }; - assert_eq!(*head, prepared.rigids[1]); - assert_eq!(args, &[captured, prepared.rigids[0]]); - let Content::Structure(FlatType::AppV1(type_head, type_args)) = - &uf.get(prepared.definition.typ).content - else { - panic!("signature application") - }; - assert_eq!(type_head, head); - assert_eq!(type_args, args); - let other = solver.prepare_definition(&mut uf, 2, &scope, definition); - assert_eq!(other.rtv["captured"], captured); - assert_ne!(other.rtv["a"], prepared.rtv["a"]); - assert_ne!(other.rtv["z"], prepared.rtv["z"]); - } - - #[test] - fn literals_and_patterns_keep_original_nodes_and_ordered_predicates() { - let bump = Bump::new(); - let mut tables = nash_can::environment::Tables::default(); - for trait_ in [ - type_::literal_trait("FromInt"), - type_::literal_trait("FromString"), - type_::literal_trait("FromBytes"), - type_::eq_trait(), - ] { - tables.kinds.traits.insert(trait_, &[&nash_ast::Kind::Type]); - } - for (expression, pattern, trait_name) in [ - (Expr::Int(7), Pattern::Int(7), "FromInt"), - ( - Expr::Bytes(&[0, 255]), - Pattern::Bytes(&[0, 255]), - "FromBytes", - ), - (Expr::Str("nash"), Pattern::Str("nash"), "FromString"), - ] { - let expression = bump.alloc(Located::at_zero(expression)); - let pattern = bump.alloc(Located::at_zero(pattern)); - let mut solver = Solver::new(&bump, &tables); - let mut uf = UnionFind::new(); - let value = solver.fresh(&mut uf, 2); - let state = State { - env: Env::new(), - mark: NO_MARK.next(), - errors: Vec::new(), - }; - let state = solver.infer_expr( - &mut uf, - &Env::new(), - 2, - state, - &Rtv::new(), - expression, - Expected::NoExpectation(value), - ); - assert!(state.errors.is_empty()); - assert_eq!(solver.uses.len(), 1); - let use_ = &solver.uses[0]; - assert_eq!(use_.site.node, NodeId::expr(expression)); - assert_eq!(use_.predicates.len(), 1); - let expression_predicate = &solver.predicates.get(use_.predicates[0]).body; - let trait_ = expression_predicate.trait_ref().unwrap(); - assert_eq!(trait_.name, trait_name); - assert_eq!(trait_.home.package, Some(nash_ast::primitives::BASE)); - let value = solver.fresh(&mut uf, 2); - let mut headers = BTreeMap::new(); - let state = solver.infer_pattern( - &mut uf, - 2, - state, - pattern, - PExpected::NoExpectation(value), - &mut headers, - ); - assert!(state.errors.is_empty()); - assert_eq!( - solver.uses.len(), - 2, - "one evidence use per literal expression/pattern" - ); - let use_ = &solver.uses[1]; - assert_eq!(use_.site.node, NodeId::pattern(pattern)); - let predicates: Vec<_> = use_ - .predicates - .iter() - .map(|id| &solver.predicates.get(*id).body) - .collect(); - assert_eq!( - predicates - .iter() - .map(|pred| pred.trait_ref().unwrap().name) - .collect::>(), - [trait_name, "Eq"] - ); - assert_eq!( - predicates[0].args(), - predicates[1].args(), - "literal and Eq use one substitution" - ); - assert_eq!(predicates[0].args().len(), 1); - } - } - - #[test] - fn operator_and_method_uses_keep_distinct_node_identity_at_the_same_region() { - let bump = Bump::new(); - let tables = nash_can::environment::Tables::default(); - let mut solver = Solver::new(&bump, &tables); - let mut uf = UnionFind::new(); - let unit = &*bump.alloc(Located::at_zero(CanType::unit())); - let method_annotation = bump.alloc(Annotation { - free_vars: &[], - context: &[], - typ: unit, - }); - let tail = bump.alloc(Located::at_zero(CanType::Lambda { - from: unit, - to: unit, - })); - let op_annotation = bump.alloc(Annotation { - free_vars: &[], - context: &[], - typ: bump.alloc(Located::at_zero(CanType::Lambda { - from: unit, - to: tail, - })), - }); - let reference = QualifiedName { - home: ModuleName { - package: None, - name: "Main", - }, - name: "Combine", - }; - let local = &*bump.alloc(Located::at_zero(Expr::VarLocal("x"))); - let method = &*bump.alloc(Located::at_zero(Expr::VarMethod { - trait_: reference, - method: "combine", - annotation: method_annotation, - })); - let operator = &*bump.alloc(Located::at_zero(Expr::Binop { - symbol: "+", - operator_home: reference.home, - reference, - annotation: op_annotation, - left: local, - right: method, - })); - let name = bump.alloc(Located::at_zero("x")); - let variable = solver.src_type_to_var(&mut uf, 2, &Rtv::new(), unit); - let env = Env::from([( - "x", - Binding { - variable, - context: &[], - definition: Some(NodeId::def(name)), - context_is_final: true, - declared_quantifiers: &[], - }, - )]); - let state = State { - env: Env::new(), - mark: NO_MARK.next(), - errors: Vec::new(), - }; - let state = solver.infer_expr( - &mut uf, - &env, - 2, - state, - &Rtv::new(), - operator, - Expected::NoExpectation(variable), - ); - assert!(state.errors.is_empty()); - let nodes: Vec<_> = solver.uses.iter().map(|use_| use_.site.node).collect(); - assert_eq!( - nodes, - [ - NodeId::expr(operator), - NodeId::expr(local), - NodeId::expr(method) - ] - ); - assert_ne!(nodes[0], nodes[1]); - assert_ne!(nodes[0], nodes[2]); - assert_ne!(nodes[1], nodes[2]); - assert!( - solver - .uses - .iter() - .all(|use_| use_.site.region == Region::zero()) - ); - } -} diff --git a/crates/nash-solve/src/solve/patterns.rs b/crates/nash-solve/src/solve/patterns.rs deleted file mode 100644 index b15baf9a..00000000 --- a/crates/nash-solve/src/solve/patterns.rs +++ /dev/null @@ -1,372 +0,0 @@ -use super::*; -use nash_constrain::error::{PCategory, PContext}; - -/// Match whether the former pattern state would own any fresh variables. -/// The caller must select the pattern's rank before inference begins. -pub(super) fn pattern_owns_vars(pattern: &Located>) -> bool { - use nash_ast::Pattern; - match &pattern.value { - Pattern::Anything | Pattern::Var(_) | Pattern::Unit | Pattern::Bool { .. } => false, - Pattern::Alias { pattern, .. } => pattern_owns_vars(pattern), - Pattern::Constructor(ctor) => { - !ctor.union.parameters.is_empty() - || ctor - .arguments - .iter() - .any(|arg| pattern_owns_vars(arg.pattern)) - } - Pattern::Pair { .. } - | Pattern::Tuple { .. } - | Pattern::List(_) - | Pattern::Cons { .. } - | Pattern::Record(_) - | Pattern::Int(_) - | Pattern::Str(_) - | Pattern::Bytes(_) => true, - } -} - -impl<'a> Solver<'a, '_> { - #[allow(clippy::too_many_arguments)] - pub(super) fn infer_pattern( - &mut self, - uf: &mut UnionFind<'a>, - rank: usize, - mut state: State<'a>, - pattern: &Located>, - expected: PExpected<'a, Variable>, - headers: &mut BTreeMap<&'a str, Located>, - ) -> State<'a> { - use nash_ast::Pattern; - let region = pattern.region; - let expected_var = match expected { - PExpected::NoExpectation(var) | PExpected::FromContext(_, _, var) => var, - }; - self.pattern_types.push(NodeTypeRecord { - node: nash_ast::NodeId::pattern(pattern), - variable: expected_var, - owner: self.owners.last().copied(), - }); - match &pattern.value { - Pattern::Anything => state, - Pattern::Var(name) => { - headers.insert(name, Located::at(region, expected_var)); - state - } - Pattern::Alias { - pattern: inner, - name, - } => { - headers.insert(name, Located::at(region, expected_var)); - self.infer_pattern(uf, rank, state, inner, expected, headers) - } - Pattern::Unit | Pattern::Bool { .. } => { - let (name, category) = if matches!(pattern.value, Pattern::Unit) { - ("unit", PCategory::Unit) - } else { - ("bool", PCategory::Bool) - }; - let actual = self.register( - uf, - rank, - Content::Structure(FlatType::App1( - nash_ast::primitives::primitive_home(), - name, - Vec::new(), - )), - ); - self.pattern_equal(uf, rank, state, region, category, actual, expected) - } - Pattern::Pair { first, second } => { - let first_var = self.register(uf, rank, Content::FlexVar(None)); - let second_var = self.register(uf, rank, Content::FlexVar(None)); - let actual = self.register( - uf, - rank, - Content::Structure(FlatType::App1( - nash_ast::primitives::primitive_home(), - "pair", - vec![first_var, second_var], - )), - ); - state = - self.pattern_equal(uf, rank, state, region, PCategory::Pair, actual, expected); - state = self.infer_pattern( - uf, - rank, - state, - second, - PExpected::NoExpectation(second_var), - headers, - ); - self.infer_pattern( - uf, - rank, - state, - first, - PExpected::NoExpectation(first_var), - headers, - ) - } - Pattern::Tuple { - first, - second, - rest, - } => { - let first_var = self.register(uf, rank, Content::FlexVar(None)); - let second_var = self.register(uf, rank, Content::FlexVar(None)); - let rest_vars: Vec<_> = rest - .iter() - .map(|_| self.register(uf, rank, Content::FlexVar(None))) - .collect(); - let actual = self.register( - uf, - rank, - Content::Structure(FlatType::Tuple1(first_var, second_var, rest_vars.clone())), - ); - state = - self.pattern_equal(uf, rank, state, region, PCategory::Tuple, actual, expected); - for (item, var) in rest.iter().zip(rest_vars).rev() { - state = self.infer_pattern( - uf, - rank, - state, - item, - PExpected::NoExpectation(var), - headers, - ); - } - state = self.infer_pattern( - uf, - rank, - state, - second, - PExpected::NoExpectation(second_var), - headers, - ); - self.infer_pattern( - uf, - rank, - state, - first, - PExpected::NoExpectation(first_var), - headers, - ) - } - Pattern::Constructor(ctor) => { - let pairs: Vec<_> = ctor - .union - .parameters - .iter() - .map(|name| (*name, self.register(uf, rank, Content::FlexVar(Some(name))))) - .collect(); - let variables: BTreeMap<_, _> = pairs.iter().copied().collect(); - let actual = self.register( - uf, - rank, - Content::Structure(FlatType::App1( - ctor.reference.home, - ctor.reference.union, - pairs.iter().map(|(_, var)| *var).collect(), - )), - ); - state = self.pattern_equal( - uf, - rank, - state, - region, - PCategory::Ctor(ctor.reference.name), - actual, - expected, - ); - for arg in ctor.arguments.iter().rev() { - state = self.infer_canonical_pattern( - uf, - rank, - state, - arg.pattern, - PExpected::FromContext( - region, - PContext::CtorArg(ctor.reference.name, arg.index as usize), - arg.typ, - ), - &variables, - headers, - ); - } - state - } - Pattern::List(items) => { - let entry = self.register(uf, rank, Content::FlexVar(None)); - let list = self.register( - uf, - rank, - Content::Structure(FlatType::App1( - nash_ast::primitives::primitive_home(), - "list", - vec![entry], - )), - ); - state = - self.pattern_equal(uf, rank, state, region, PCategory::List, list, expected); - for (index, item) in items.iter().enumerate().rev() { - state = self.infer_pattern( - uf, - rank, - state, - item, - PExpected::FromContext(region, PContext::ListEntry(index), entry), - headers, - ); - } - state - } - Pattern::Cons { head, tail } => { - let entry = self.register(uf, rank, Content::FlexVar(None)); - let list = self.register( - uf, - rank, - Content::Structure(FlatType::App1( - nash_ast::primitives::primitive_home(), - "list", - vec![entry], - )), - ); - state = - self.pattern_equal(uf, rank, state, region, PCategory::List, list, expected); - state = self.infer_pattern( - uf, - rank, - state, - head, - PExpected::NoExpectation(entry), - headers, - ); - // The tail has its own structural expectation; a failed outer - // comparison must not poison this independent equation. - let list = self.structure( - uf, - rank, - FlatType::App1(nash_ast::primitives::primitive_home(), "list", vec![entry]), - ); - self.infer_pattern( - uf, - rank, - state, - tail, - PExpected::FromContext(region, PContext::Tail, list), - headers, - ) - } - Pattern::Record(fields) => { - let record = self.register(uf, rank, Content::FlexVar(None)); - // Allocate in source order, then execute field checks in the - // reverse order used by the former rev_cons list. - let fields_with_vars: Vec<_> = fields - .iter() - .map(|field| { - let var = self.register(uf, rank, Content::FlexVar(None)); - headers - .entry(*field) - .or_insert_with(|| Located::at(region, var)); - (*field, var) - }) - .collect(); - if fields.is_empty() { - state = self.field( - uf, - rank, - state, - DeferredField { - test_scope: self.test_scope, - region, - context: type_::FieldContext::Pattern, - record, - field: None, - }, - ); - } - for field in fields_with_vars.into_iter().rev() { - state = self.field( - uf, - rank, - state, - DeferredField { - test_scope: self.test_scope, - region, - context: type_::FieldContext::Pattern, - record, - field: Some(field), - }, - ); - } - self.pattern_equal(uf, rank, state, region, PCategory::Record, record, expected) - } - Pattern::Int(_) | Pattern::Str(_) | Pattern::Bytes(_) => { - let (trait_name, category) = match pattern.value { - Pattern::Int(_) => ("FromInt", PCategory::Int), - Pattern::Bytes(_) => ("FromBytes", PCategory::Bytes), - _ => ("FromString", PCategory::Str), - }; - let actual = self.register(uf, rank, Content::FlexVar(None)); - let annotation = type_::literal_annotation( - self.bump, - &[type_::literal_trait(trait_name), type_::eq_trait()], - ); - state = self.foreign( - uf, - rank, - state, - region, - nash_ast::NodeId::pattern(pattern), - "literal", - annotation, - Expected::NoExpectation(actual), - ); - self.pattern_equal(uf, rank, state, region, category, actual, expected) - } - } - } -} - -impl<'a> Solver<'a, '_> { - /// Canonical structures are materialized separately for alias bindings and - /// pattern equations. Canonical variables still resolve through the same - /// substitution, even when inference has already learned their structure. - #[allow(clippy::too_many_arguments)] - pub(super) fn infer_canonical_pattern( - &mut self, - uf: &mut UnionFind<'a>, - rank: usize, - state: State<'a>, - pattern: &Located>, - expected: PExpected<'a, &'a Located>>, - variables: &BTreeMap<&'a str, Variable>, - headers: &mut BTreeMap<&'a str, Located>, - ) -> State<'a> { - let (PExpected::NoExpectation(typ) | PExpected::FromContext(_, _, typ)) = expected; - let var = self.src_type_to_var(uf, rank, variables, typ); - match &pattern.value { - nash_ast::Pattern::Alias { - pattern: inner, - name, - } => { - self.pattern_types.push(NodeTypeRecord { - node: nash_ast::NodeId::pattern(pattern), - variable: var, - owner: self.owners.last().copied(), - }); - headers.insert(name, Located::at(pattern.region, var)); - self.infer_canonical_pattern(uf, rank, state, inner, expected, variables, headers) - } - _ => self.infer_pattern( - uf, - rank, - state, - pattern, - expected.type_replace(var), - headers, - ), - } - } -} diff --git a/crates/nash-solve/tests/inference.rs b/crates/nash-solve/tests/inference.rs index 29be5f61..80632847 100644 --- a/crates/nash-solve/tests/inference.rs +++ b/crates/nash-solve/tests/inference.rs @@ -2462,6 +2462,78 @@ fn typed_alias_function() { ); } +/// An annotated definition publishes its declared type. A call with more +/// arguments in the same module must not replace the alias in the published +/// annotation: an importer resolves the impl of the alias by its name. +#[test] +fn annotated_alias_result_keeps_its_impl_for_importers_after_a_wider_call() { + let snapshot_inputs = SnapshotInputs::default(); + let bump = Bump::new(); + let mut interfaces = literal_interfaces(&bump); + let mut output = Vec::new(); + for (module_name, source) in [ + ( + "Gen", + indoc!( + r#" + module Gen exposing (..) + type alias gen 'a = int -> ('a, int) + trait Name 'a where + name : 'a -> () + impl Name (gen int) where + name _ = () + start : int -> gen int + start n = \seed -> (n, seed) + run : int -> (int, int) + run seed = start 4 seed + "# + ), + ), + ( + "Main", + indoc!( + r#" + module Main exposing (..) + import Gen exposing (..) + label = name (start 1) + "# + ), + ), + ] { + let source = bump.alloc_str(source); + let parsed = nash_parse::Parser::new(&bump, snapshot_inputs.record(source)) + .module() + .unwrap(); + let canonical = nash_can::canonicalize( + &bump, + Context { + package: None, + interfaces: Some(&interfaces), + }, + &parsed, + ) + .unwrap(); + let (annotations, _) = nash_solve::run( + &bump, + &mut UnionFind::new(), + &canonical.module, + &canonical.tables, + ) + .unwrap_or_else(|errors| panic!("{}", render_errors(source, &errors))); + output.push(format!( + "{module_name}:\n{}", + render_annotations(&annotations) + )); + interfaces.insert( + module_name, + nash_can::from_module(&bump, &canonical.module, &annotations), + ); + } + insta::with_settings!({description => snapshot_inputs.description(), omit_expression => true}, { + insta::assert_snapshot!(output.join("\n")); + }); +} + // RECURSION #[test] diff --git a/crates/nash-solve/tests/snapshots/inference__annotated_alias_result_keeps_its_impl_for_importers_after_a_wider_call.snap b/crates/nash-solve/tests/snapshots/inference__annotated_alias_result_keeps_its_impl_for_importers_after_a_wider_call.snap new file mode 100644 index 00000000..6656c79e --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__annotated_alias_result_keeps_its_impl_for_importers_after_a_wider_call.snap @@ -0,0 +1,9 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Gen exposing (..)\ntype alias gen 'a = int -> ('a, int)\ntrait Name 'a where\n name : 'a -> ()\nimpl Name (gen int) where\n name _ = ()\nstart : int -> gen int\nstart n = \\seed -> (n, seed)\nrun : int -> (int, int)\nrun seed = start 4 seed\n\n\nmodule Main exposing (..)\nimport Gen exposing (..)\nlabel = name (start 1)\n" +--- +Gen: +run : int -> ( int, int ) +start : int -> gen int +Main: +label : unit diff --git a/docs/frontend-hardening-verification.md b/docs/frontend-hardening-verification.md index b6a1bd41..9d909859 100644 --- a/docs/frontend-hardening-verification.md +++ b/docs/frontend-hardening-verification.md @@ -1,9 +1,11 @@ # Frontend hardening verification -The six frontend cleanup changes and direct AST inference are complete. The -replacement preserves the union-find and predicate engines, removes the -allocated Constraint tree and intermediate inference Type, and passes all -adoption gates. Plan 07 and code generation are outside this change. +The six frontend cleanup changes are complete. A seventh change, direct AST +inference, replaced the constraint tree and passed all adoption gates. It was +later reverted: `nash-constrain` again generates the Elm constraint tree and +`nash-solve` walks it. The union-find and predicate engines are the same in +both designs. The inference sections below describe the direct engine as it was +measured at that time. Plan 07 and code generation are outside this change. ## Commit sequence @@ -19,7 +21,7 @@ rebases; use `jj log -r ` for the current commit hash. | `otpvxozr` | Remove inactive interface-cache machinery | | `ovwmkvpo` | Borrow canonical local scopes | | `npksuwvn` | Bound trait candidate traversal | -| `lssnqtpu` | Infer directly from the canonical AST | +| `lssnqtpu` | Infer directly from the canonical AST (replaced later by the restored constraint tree) | An external rebase placed these changes on release commit `046cb63c`. Its changes from the saved baseline are release metadata and changelogs; no Rust @@ -126,5 +128,6 @@ The retained local audit root is - `occurs-review/`: targeted fixtures and complete original/candidate outputs. The seven recovery snapshots are committed with the inference tests. External -audit copies contain the original engine only for verification; the production -tree has one direct inference path. +audit copies contain the original engine only for verification. The production +tree builds the constraint tree and walks it again (see the note at the top of +this file); the direct inference path no longer exists. diff --git a/docs/overview.md b/docs/overview.md index 040a08e0..e534c01a 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -44,7 +44,7 @@ Done (ported from the Elm compiler, Haskell -> Rust): - `nash-parse` — recursive-descent parser with Elm's full error hierarchy - `nash-can` — canonicalization (name resolution, SCC ordering, interfaces) -- `nash-constrain` + `nash-solve` — direct AST inference with Elm's rank-based solver +- `nash-constrain` + `nash-solve` — constraint generation and Elm's rank-based solver - `nash-driver` / `nash-config` / `nash-cli` — build graph, `nash.jsonc`, `nash check` - `nash-plutus` — complete UPLC: terms, flat codec, CEK machine, cost models @@ -229,7 +229,7 @@ crates/ nash-ast canonical AST (extend: kinds, traits, evidence slots) nash-can canonicalization + Haskell 98 kinds + datatype contexts nash-constrain union-find types + canonical instantiation + type errors - nash-solve direct AST inference + traits + kind contracts + evidence + nash-solve constraint solver + traits + kind contracts + evidence nash-nitpick exhaustiveness (new) nash-report diagnostics: source labels -> terminal / JSON / LSP nash-ir Core IR + Core->Core passes (new) diff --git a/docs/research/compiler-stack-audit.md b/docs/research/compiler-stack-audit.md index c941e31e..b61e3066 100644 --- a/docs/research/compiler-stack-audit.md +++ b/docs/research/compiler-stack-audit.md @@ -54,7 +54,7 @@ still covered by the nested-type/constant follow-ups below. | Area | Recursive path | Why the parser limit does not settle it | | --- | --- | --- | -| Flat source chains | `nash-can/src/expression.rs` field access and `build_tree_rec`; `nash-solve/src/solve/expressions.rs` | Parser nesting limit 64 does not limit flat operator/access chains. Equal-precedence operator construction also repeatedly scans the remaining chain. | +| Flat source chains | `nash-can/src/expression.rs` field access and `build_tree_rec`; `nash-constrain/src/expression.rs` | Parser nesting limit 64 does not limit flat operator/access chains. Equal-precedence operator construction also repeatedly scans the remaining chain. | | IR type metadata | Derived type equality and `Builder::plutus_type` | Deeply nested types are independent of term-tree depth. | | Nested constants | Flat `encode_type` / `type_from_tags`, constant equality and pretty printing | Iterative Flat term traversal does not cover nested constant types or data. | | Module graph | `nash-driver/src/graph.rs` cycle reporting | Import graph depth is independent of source expression nesting. | diff --git a/docs/research/type-representation-and-evidence.md b/docs/research/type-representation-and-evidence.md index 60a7ada9..248f25f4 100644 --- a/docs/research/type-representation-and-evidence.md +++ b/docs/research/type-representation-and-evidence.md @@ -15,10 +15,11 @@ correctness machinery around generalization, predicates, and error recovery. ### What the two implementations actually do -Nash already infers directly from the canonical AST. Its former intermediate -constraint-tree architecture is gone. Switching representations would therefore -not remove that layer a second time. See -[`solve/infer.rs`](../../crates/nash-solve/src/solve/infer.rs) and +Nash infers in two stages, as Elm does. `nash-constrain` turns the canonical +AST into an arena-owned constraint tree, and `nash-solve` walks that tree with +the union-find store. Switching representations would not remove the +constraint layer. See +[`nash-constrain/lib.rs`](../../crates/nash-constrain/src/lib.rs) and [`nash-solve/lib.rs`](../../crates/nash-solve/src/lib.rs). Nash stores a graph: a small `Variable` indexes a descriptor, whose children are @@ -267,7 +268,7 @@ For example, `use : (forall a. a -> a) -> (unit, Color)` uses mathematical AST keeps quantification on `Annotation.free_vars`; nested `Type` nodes do not contain quantified schemes, and function parameters get monomorphic variables. See [`Annotation` and `Type`](../../crates/nash-ast/src/lib.rs) and -[lambda inference](../../crates/nash-solve/src/solve/expressions.rs). The solver's +[lambda constraints](../../crates/nash-constrain/src/expression.rs). The solver's internal variable ranks track generalization levels; they do not mean rank-N source types. diff --git a/docs/traits.md b/docs/traits.md index e938b7d9..6282d877 100644 --- a/docs/traits.md +++ b/docs/traits.md @@ -297,9 +297,11 @@ Context reduction: a retained context never contains both `Ord 'a` and ## Inference Nash keeps Elm's rank-based solver (`nash-solve`). Predicates ride along -with unification variables. Inference walks the canonical AST directly; -there is no allocated constraint tree or intermediate inference type. -Canonical types instantiate directly into union-find variables. +with unification variables. `nash-constrain` turns the canonical AST into an +arena-owned constraint tree, and the solver walks it in Elm's order. Types +in the tree are the inference `Type` language; the solver turns them into +union-find variables. Canonical annotations instantiate directly into +union-find variables. Each definition owns its young rank, wanted predicates, and evidence binder. Pattern scopes introduce a younger rank only when they own fresh variables. diff --git a/plans/07-codegen.md b/plans/07-codegen.md index 9079a49b..4124c5b2 100644 --- a/plans/07-codegen.md +++ b/plans/07-codegen.md @@ -24,8 +24,9 @@ carry complete substitutions separately. Preserve trait-free polymorphic recursion through opaque values. Bound specialization work and report resource limits when demanded layouts keep growing. Core permits `Ty::Erased` where no representation inspection is needed. -Implementation follows the current source APIs; old constraint-tree solver -signatures in the sketches are historical. Record each concrete correction here +Implementation follows the current source APIs; the constraint-tree solver +signatures in the sketches may differ from the restored `nash-constrain` and +`nash-solve` code. Record each concrete correction here as its chunk lands. The Core type model includes `Erased` pass-through values and `Constructor` metadata for higher-kinded arguments. Type conversion records ADT layouts lazily, one level at a time. UPLC printing uses lexical scope for From 37ea48736d9dfba9ceeb185f531e26385fa7aedc Mon Sep 17 00:00:00 2001 From: microproofs Date: Tue, 13 Oct 2026 17:49:43 +0700 Subject: [PATCH 13/24] fix(solve): reject representation givens that contradict an enclosing annotation A local annotation shares the enclosing annotation's type variables, as Elm's rtv does (Constrain/Expression.hs constrainDef). Canonicalization checks each context alone, so 'Little 'a' inside 'Big 'a => ...' passed, and the joined given frames reached impl selection with an empty proven set, where an assert stopped the compiler. enter_givens now groups the representation givens of all active frames and the new frame by subject, as in_class compares them, and reports a contradiction with the existing contradictory-representation error at the local definition. The subject is poisoned, so obligations on it are dropped and the frame's second entry (ambiguity loop) does not report again. check_ambiguity shares the grouping. A requirement implied by another one (Storable next to Big) is left out of the report. The in_class assert stays: contradictory givens reaching impl selection are a compiler bug. Its comment now names both checks. Signed-off-by: microproofs --- .../nested-representation-contexts.md | 5 + crates/nash-solve/src/resolve.rs | 6 +- crates/nash-solve/src/solve.rs | 143 +++++++++++++----- crates/nash-solve/tests/inference.rs | 69 +++++++++ ...cting_the_trait_parameter_is_rejected.snap | 17 +++ ..._enclosing_representation_is_rejected.snap | 17 +++ ...ion_is_rejected_before_impl_selection.snap | 17 +++ 7 files changed, 231 insertions(+), 43 deletions(-) create mode 100644 .sampo/changesets/nested-representation-contexts.md create mode 100644 crates/nash-solve/tests/snapshots/inference__default_method_local_annotation_contradicting_the_trait_parameter_is_rejected.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__local_annotation_contradicting_the_enclosing_representation_is_rejected.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__local_annotation_contradiction_is_rejected_before_impl_selection.snap diff --git a/.sampo/changesets/nested-representation-contexts.md b/.sampo/changesets/nested-representation-contexts.md new file mode 100644 index 00000000..43917fdd --- /dev/null +++ b/.sampo/changesets/nested-representation-contexts.md @@ -0,0 +1,5 @@ +--- +cargo/nash-solve: patch +--- + +Report a local annotation whose representation constraints contradict an enclosing annotation, such as `Little 'a` inside `Big 'a => ...`, as a contradictory-representation error. The two annotations share `'a`, and their combined constraints used to reach impl selection and crash the compiler. The error no longer lists a requirement that another listed requirement implies, such as `Storable` next to `Big`. diff --git a/crates/nash-solve/src/resolve.rs b/crates/nash-solve/src/resolve.rs index 1c92e5e2..98afeebb 100644 --- a/crates/nash-solve/src/resolve.rs +++ b/crates/nash-solve/src/resolve.rs @@ -242,8 +242,10 @@ impl<'a> nash_ast::head::Types<'a> for ClassedTypes<'_, 'a> { } } } - // Canonicalization rejects contradictory contexts; an empty set would - // otherwise prove every class and select every disjoint impl. + // Canonicalization rejects a contradictory context, and the solver + // rejects contradictory nested contexts on entry and poisons their + // subject. An empty set would prove every class and select every + // disjoint impl. assert!( !proven.is_empty(), "contradictory representation givens reached impl selection" diff --git a/crates/nash-solve/src/solve.rs b/crates/nash-solve/src/solve.rs index 2f7d694a..05b6eeeb 100644 --- a/crates/nash-solve/src/solve.rs +++ b/crates/nash-solve/src/solve.rs @@ -141,6 +141,17 @@ fn add_error<'a>(mut state: State<'a>, error: Error<'a>) -> State<'a> { state } +/// The subject and class of a representation predicate such as `Big 'a`. +fn representation_requirement<'a>( + body: &Body<'a>, +) -> Option<(Variable, nash_ast::primitives::ReprTrait)> { + let Body::Trait { trait_, args, .. } = body else { + return None; + }; + let required = nash_ast::primitives::ReprTrait::of(*trait_)?; + Some((args[0], required)) +} + #[derive(Clone, Copy)] struct DeferredField<'a> { test_scope: bool, @@ -554,7 +565,13 @@ impl<'a> Solver<'a, '_> { let annotation_failed = state1.errors.len() > escapes_before; if let Some(binder) = *binder { - let depth = self.enter_givens(uf, rank, given_bodies, Some(binder)); + let depth = self.enter_givens( + uf, + rank, + given_bodies, + Some(binder), + &mut state1.errors, + ); loop { let (errors, defaulted) = self.check_ambiguity(uf, rank, wanted_start, &defs, binder.name()); @@ -644,7 +661,7 @@ impl<'a> Solver<'a, '_> { uf: &mut UnionFind<'a>, env: &Env<'a>, rank: usize, - state: State<'a>, + mut state: State<'a>, constraint: &Constraint<'a>, given: &[Body<'a>], binder: Option>, @@ -653,7 +670,7 @@ impl<'a> Solver<'a, '_> { // Attribute new failures to their owning binding. This count does not // gate any independent constraint or reset the collected diagnostics. let errors_before = state.errors.len(); - let depth = self.enter_givens(uf, rank, given, binder); + let depth = self.enter_givens(uf, rank, given, binder, &mut state.errors); let start = self.wanted.len(); let owner_depth = self.owners.len(); if let Some(binder) = binder { @@ -1868,6 +1885,7 @@ impl<'a> Solver<'a, '_> { rank: usize, given: &[Body<'a>], binder: Option>, + errors: &mut Vec>, ) -> usize { let depth = self.givens.len(); if let Some(binder) = binder.filter(|_| !given.is_empty()) { @@ -1883,6 +1901,23 @@ impl<'a> Solver<'a, '_> { }) .collect(); self.expand_givens(uf, rank, &mut predicates); + // Canonicalization checks each context alone. A local annotation + // shares the enclosing annotation's type variables, as Elm's `rtv` + // does, so its representation givens must also agree with every + // enclosing frame. A frame entered again finds its subject poisoned. + let requirements = self + .givens + .iter() + .flat_map(|frame| frame.predicates.iter()) + .chain(&predicates) + .filter_map(|given| representation_requirement(&given.body)) + .collect(); + errors.extend(self.contradictory_representations( + uf, + rank, + requirements, + binder.name(), + )); self.givens.push(GivenFrame { binder: binder.node(), predicates, @@ -2858,63 +2893,89 @@ impl<'a> Solver<'a, '_> { copies[0] } - fn check_ambiguity( + /// Group representation requirements by subject, as `in_class` compares + /// them, and report each subject that no representation admits. The + /// subject is poisoned, so obligations on it are dropped instead of + /// reaching impl selection. A requirement that another one implies is left + /// out of the report. + fn contradictory_representations( &mut self, uf: &mut UnionFind<'a>, rank: usize, - start: usize, - definitions: &[Definition<'a>], + requirements: Vec<(Variable, nash_ast::primitives::ReprTrait)>, binder: &'a Located<&'a str>, - ) -> (Vec>, bool) { - use nash_ast::primitives::ReprTrait; - // Check the conjunction before defaulting or generalizing. An - // impossible representation context cannot be exported as a scheme, - // even when its variable is reachable from the inferred result. - let mut representations: Vec<(Variable, Vec)> = Vec::new(); + ) -> Vec> { + use nash_ast::primitives::{ReprSet, ReprTrait}; + let mut subjects: Vec<(Variable, Vec)> = Vec::new(); let mut allocated = Vec::new(); - for (_, id) in &self.wanted[start..] { - if self.predicate_blocked(uf, *id) { + for (argument, required) in requirements { + let subject = + crate::representation::subject(uf, &self.tables.kinds, argument, &mut allocated); + if crate::recovery::is_poisoned(uf, [subject]) { continue; } - let Body::Trait { trait_, args, .. } = &self.predicates.get(*id).body else { - continue; - }; - let Some(required) = ReprTrait::of(*trait_) else { - continue; - }; - let subject = - crate::representation::subject(uf, &self.tables.kinds, args[0], &mut allocated); - if let Some((_, requirements)) = representations + if let Some((_, found)) = subjects .iter_mut() .find(|(other, _)| crate::preds::same_args(uf, &[*other], &[subject])) { - if !requirements.contains(&required) { - requirements.push(required); + if !found.contains(&required) { + found.push(required); } } else { - representations.push((subject, vec![required])); + subjects.push((subject, vec![required])); } } self.introduce(uf, rank, &allocated); let mut errors = Vec::new(); - for (subject, requirements) in representations { - let admitted = requirements - .iter() - .fold(nash_ast::primitives::ReprSet::ALL, |set, requirement| { - set.intersect(requirement.admits()) - }); - if admitted.is_empty() { - errors.push(Error::ContradictoryRepresentation { - region: binder.region, - name: binder.value, - typ: to_error_type(self.bump, uf, subject), - requirements: self.bump.alloc_slice_fill_iter(requirements), - }); - self.has_poison = true; - crate::recovery::poison(uf, [subject]); + for (subject, requirements) in subjects { + let admitted = requirements.iter().fold(ReprSet::ALL, |set, requirement| { + set.intersect(requirement.admits()) + }); + if !admitted.is_empty() { + continue; } + let shown: Vec<_> = requirements + .iter() + .copied() + .filter(|requirement| { + !requirements.iter().any(|other| { + other.admits() != requirement.admits() + && other.admits().intersect(requirement.admits()) == other.admits() + }) + }) + .collect(); + errors.push(Error::ContradictoryRepresentation { + region: binder.region, + name: binder.value, + typ: to_error_type(self.bump, uf, subject), + requirements: self.bump.alloc_slice_copy(&shown), + }); + self.has_poison = true; + crate::recovery::poison(uf, [subject]); } self.propagate_poison(uf); + errors + } + + fn check_ambiguity( + &mut self, + uf: &mut UnionFind<'a>, + rank: usize, + start: usize, + definitions: &[Definition<'a>], + binder: &'a Located<&'a str>, + ) -> (Vec>, bool) { + // Check the conjunction before defaulting or generalizing. An + // impossible representation context cannot be exported as a scheme, + // even when its variable is reachable from the inferred result. + let mut requirements = Vec::new(); + for (_, id) in &self.wanted[start..] { + if self.predicate_blocked(uf, *id) { + continue; + } + requirements.extend(representation_requirement(&self.predicates.get(*id).body)); + } + let mut errors = self.contradictory_representations(uf, rank, requirements, binder); let roots: Vec<_> = definitions.iter().map(|def| def.typ).collect(); let mut reachable = Self::type_variables(uf, roots); if definitions diff --git a/crates/nash-solve/tests/inference.rs b/crates/nash-solve/tests/inference.rs index 80632847..0465fb51 100644 --- a/crates/nash-solve/tests/inference.rs +++ b/crates/nash-solve/tests/inference.rs @@ -5361,6 +5361,75 @@ fn contradictory_inferred_classes_do_not_select_both_disjoint_blankets() { ); } +/// A local annotation shares the enclosing annotation's type variables, as +/// in Elm. Each context is consistent alone, but together they admit no +/// representation for `'a`. +#[test] +fn local_annotation_contradicting_the_enclosing_representation_is_rejected() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Const, Little) + constOnly : Const 'b => 'b -> 'b + constOnly x = x + outer : Big 'a => 'a -> 'a + outer x = + let + inner : Little 'a => 'a -> 'a + inner y = constOnly y + in + x + "# + ); +} + +/// The contradiction must be reported before impl selection: with no +/// representation left, both disjoint blankets would match `'a`. +#[test] +fn local_annotation_contradiction_is_rejected_before_impl_selection() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Little) + trait Keep 'a where + keep : 'a -> 'a + impl Keep ('a : Big) where + keep x = x + impl Keep ('a : Little) where + keep x = x + outer : Big 'a => 'a -> 'a + outer x = + let + inner : Little 'a => 'a -> 'a + inner y = keep y + in + x + "# + ); +} + +/// A trait parameter's representation reaches a default method's local +/// annotation through the method's own trait constraint. +#[test] +fn default_method_local_annotation_contradicting_the_trait_parameter_is_rejected() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Const, Little) + constOnly : Const 'b => 'b -> 'b + constOnly x = x + trait Foo ('a : Big) where + foo : 'a -> 'a + foo x = + let + inner : Little 'a => 'a -> 'a + inner y = constOnly y + in + x + "# + ); +} + #[test] fn representation_classes_intersect_givens_and_expand_aliases() { assert_inference_snapshot!( diff --git a/crates/nash-solve/tests/snapshots/inference__default_method_local_annotation_contradicting_the_trait_parameter_is_rejected.snap b/crates/nash-solve/tests/snapshots/inference__default_method_local_annotation_contradicting_the_trait_parameter_is_rejected.snap new file mode 100644 index 00000000..23bddb18 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__default_method_local_annotation_contradicting_the_trait_parameter_is_rejected.snap @@ -0,0 +1,17 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (Big, Const, Little)\nconstOnly : Const 'b => 'b -> 'b\nconstOnly x = x\ntrait Foo ('a : Big) where\n foo : 'a -> 'a\n foo x =\n let\n inner : Little 'a => 'a -> 'a\n inner y = constOnly y\n in\n x\n" +info: diagnostic +--- +nash::type::contradictory_representation + + × `inner` requires incompatible representations for `'a`. + ╭─[Main.nash:10:13] + 9 │ inner : Little 'a => 'a -> 'a + 10 │ inner y = constOnly y + · ───── + 11 │ in + ╰──── + help: Required: Big, Little. + + Use a consistent representation or convert the value explicitly. diff --git a/crates/nash-solve/tests/snapshots/inference__local_annotation_contradicting_the_enclosing_representation_is_rejected.snap b/crates/nash-solve/tests/snapshots/inference__local_annotation_contradicting_the_enclosing_representation_is_rejected.snap new file mode 100644 index 00000000..cfa33c2e --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__local_annotation_contradicting_the_enclosing_representation_is_rejected.snap @@ -0,0 +1,17 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (Big, Const, Little)\nconstOnly : Const 'b => 'b -> 'b\nconstOnly x = x\nouter : Big 'a => 'a -> 'a\nouter x =\n let\n inner : Little 'a => 'a -> 'a\n inner y = constOnly y\n in\n x\n" +info: diagnostic +--- +nash::type::contradictory_representation + + × `inner` requires incompatible representations for `'a`. + ╭─[Main.nash:9:9] + 8 │ inner : Little 'a => 'a -> 'a + 9 │ inner y = constOnly y + · ───── + 10 │ in + ╰──── + help: Required: Big, Little. + + Use a consistent representation or convert the value explicitly. diff --git a/crates/nash-solve/tests/snapshots/inference__local_annotation_contradiction_is_rejected_before_impl_selection.snap b/crates/nash-solve/tests/snapshots/inference__local_annotation_contradiction_is_rejected_before_impl_selection.snap new file mode 100644 index 00000000..9a2c7e7d --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__local_annotation_contradiction_is_rejected_before_impl_selection.snap @@ -0,0 +1,17 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (Big, Little)\ntrait Keep 'a where\n keep : 'a -> 'a\nimpl Keep ('a : Big) where\n keep x = x\nimpl Keep ('a : Little) where\n keep x = x\nouter : Big 'a => 'a -> 'a\nouter x =\n let\n inner : Little 'a => 'a -> 'a\n inner y = keep y\n in\n x\n" +info: diagnostic +--- +nash::type::contradictory_representation + + × `inner` requires incompatible representations for `'a`. + ╭─[Main.nash:13:9] + 12 │ inner : Little 'a => 'a -> 'a + 13 │ inner y = keep y + · ───── + 14 │ in + ╰──── + help: Required: Big, Little. + + Use a consistent representation or convert the value explicitly. From 115db1d2d1dd6c5516a14029428c1d2a0447e64f Mon Sep 17 00:00:00 2001 From: microproofs Date: Tue, 13 Oct 2026 23:13:34 +0700 Subject: [PATCH 14/24] fix(traits): check every impl context through its superclasses check_annotation rejects a context that admits no representation once its superclasses are added (Foo 'a with trait Foo ('a : Big) next to Little 'a). check_impl ran only the formation check; the superclass check reached an impl only through the annotation of each method it defines. An impl that defines no method skipped it, and superclass entailment then saw an empty proven set, so both disjoint blankets matched and select_impl stopped the compiler. check_impl now runs the same superclass check (check_superclass_consistency, moved out of check_annotation), so such an impl gets the existing contradictory-representation error at its context. kinds::in_class asserts a non-empty proven set instead of silently proving every class, as the solver's in_class does. Signed-off-by: microproofs --- .../impl-context-superclass-consistency.md | 5 ++ crates/nash-can/src/kinds.rs | 85 ++++++++++++------- crates/nash-can/tests/kind_predicates.rs | 22 +++++ ...ds_rejects_a_superclass_contradiction.snap | 13 +++ ...pl_rejects_a_superclass_contradiction.snap | 13 +++ 5 files changed, 108 insertions(+), 30 deletions(-) create mode 100644 .sampo/changesets/impl-context-superclass-consistency.md create mode 100644 crates/nash-can/tests/snapshots/kind_predicates__impl_using_only_default_methods_rejects_a_superclass_contradiction.snap create mode 100644 crates/nash-can/tests/snapshots/kind_predicates__marker_impl_rejects_a_superclass_contradiction.snap diff --git a/.sampo/changesets/impl-context-superclass-consistency.md b/.sampo/changesets/impl-context-superclass-consistency.md new file mode 100644 index 00000000..d4e8cd17 --- /dev/null +++ b/.sampo/changesets/impl-context-superclass-consistency.md @@ -0,0 +1,5 @@ +--- +cargo/nash-can: patch +--- + +Check every impl context together with its superclasses for contradictory representations. An impl that defines no method, such as `impl (Foo 'a, Little 'a) => Sub 'a` where `Foo` requires `Big`, skipped this check and crashed the superclass entailment check; it now gets the contradictory-representation error. diff --git a/crates/nash-can/src/kinds.rs b/crates/nash-can/src/kinds.rs index c5001b95..5ac95b69 100644 --- a/crates/nash-can/src/kinds.rs +++ b/crates/nash-can/src/kinds.rs @@ -1751,6 +1751,45 @@ fn check_representation_consistency<'a>( Ok(()) } +/// A class premise also promises its superclasses. Reject a context such as +/// BigOnly int when BigOnly has Big as a superclass, even if unused. +fn check_superclass_consistency<'a>( + bump: &'a Bump, + env: &KindEnv<'a>, + predicates: &[Pred<'a>], + context: &'a crate::error::KindContext<'a>, +) -> Result<(), Vec>> { + let group = Default::default(); + let mut validation = Formation::new(bump, env, &group); + let mut pending = predicates.to_vec(); + let mut seen = std::collections::HashSet::new(); + while let Some(pred) = pending.pop() { + if !seen.insert(pred.key()) { + continue; + } + validation + .reduce(pred) + .map_err(|failure| vec![representation_error(failure, context)])?; + if let Some(info) = pred + .trait_ref() + .and_then(|name| env.superclasses.get(&name)) + { + let substitution = info + .parameters + .iter() + .copied() + .zip(pred.args().iter().copied()) + .collect(); + pending.extend( + info.supers + .iter() + .map(|sup| substitute_predicate(bump, &substitution, *sup)), + ); + } + } + check_representation_consistency(&validation.predicates) +} + pub fn check_annotation<'a>( bump: &'a Bump, env: &KindEnv<'a>, @@ -1785,36 +1824,7 @@ pub fn check_annotation<'a>( .typ(annotation.typ) .map_err(|failure| vec![representation_error(failure, context)])?; check_representation_consistency(&formation.predicates)?; - // A class premise also promises its superclasses. Reject a context such - // as BigOnly int when BigOnly has Big as a superclass, even if unused. - let mut validation = Formation::new(bump, env, &group); - let mut pending = formation.predicates.clone(); - let mut seen = std::collections::HashSet::new(); - while let Some(pred) = pending.pop() { - if !seen.insert(pred.key()) { - continue; - } - validation - .reduce(pred) - .map_err(|failure| vec![representation_error(failure, context)])?; - if let Some(info) = pred - .trait_ref() - .and_then(|name| env.superclasses.get(&name)) - { - let substitution = info - .parameters - .iter() - .copied() - .zip(pred.args().iter().copied()) - .collect(); - pending.extend( - info.supers - .iter() - .map(|sup| substitute_predicate(bump, &substitution, *sup)), - ); - } - } - check_representation_consistency(&validation.predicates)?; + check_superclass_consistency(bump, env, &formation.predicates, context)?; Ok(bump.alloc(nash_ast::Annotation { typ: annotation.typ, free_vars: annotation.free_vars, @@ -2004,6 +2014,14 @@ pub(crate) fn check_impl<'a>( })?; } check_representation_consistency(&formation.predicates)?; + // An impl that defines no method gets no method annotation check, so its + // context is checked through its superclasses here. + check_superclass_consistency( + bump, + env, + &formation.predicates, + &crate::error::KindContext::TypeAnnotation, + )?; Ok(bump.alloc_slice_fill_iter(formation.predicates)) } @@ -2129,6 +2147,13 @@ pub fn in_class<'a>( proven = proven.intersect(required.admits()); } } + // `check_annotation` and `check_impl` reject a context that admits no + // representation, superclasses included. An empty set would prove every + // class and select every disjoint impl. + assert!( + !proven.is_empty(), + "contradictory representation givens reached impl selection" + ); if !proven.is_all() && proven.intersect(class) == proven { nash_ast::head::Match::Yes(()) } else { diff --git a/crates/nash-can/tests/kind_predicates.rs b/crates/nash-can/tests/kind_predicates.rs index 9a423e30..9eecc031 100644 --- a/crates/nash-can/tests/kind_predicates.rs +++ b/crates/nash-can/tests/kind_predicates.rs @@ -163,6 +163,28 @@ fn contradictory_application_impl_context_is_rejected() { .unwrap_err(); } +/// `Foo` promises `Big`, so this context admits no representation. The impl +/// defines no method, so no method annotation repeats the context check. +#[test] +fn impl_using_only_default_methods_rejects_a_superclass_contradiction() { + let bump = Bump::new(); + check_snapshot!( + &bump, + "trait Foo ('a : Big) where\n\ntrait Keep 'a where\n keep : 'a -> 'a\nimpl Keep ('a : Big) where\n keep x = x\nimpl Keep ('a : Little) where\n keep x = x\ntrait Keep 'a => Sub 'a where\n sub : 'a -> 'a\n sub x = x\nimpl (Foo 'a, Little 'a) => Sub 'a where" + ) + .unwrap_err(); +} + +#[test] +fn marker_impl_rejects_a_superclass_contradiction() { + let bump = Bump::new(); + check_snapshot!( + &bump, + "trait Foo ('a : Big) where\n\ntrait Keep 'a where\n keep : 'a -> 'a\nimpl Keep ('a : Big) where\n keep x = x\nimpl Keep ('a : Little) where\n keep x = x\ntrait Keep 'a => Sub 'a where\n\nimpl (Foo 'a, Little 'a) => Sub 'a where" + ) + .unwrap_err(); +} + #[test] fn trait_parameter_kinds_come_from_method_uses() { let bump = Bump::new(); diff --git a/crates/nash-can/tests/snapshots/kind_predicates__impl_using_only_default_methods_rejects_a_superclass_contradiction.snap b/crates/nash-can/tests/snapshots/kind_predicates__impl_using_only_default_methods_rejects_a_superclass_contradiction.snap new file mode 100644 index 00000000..aff52b67 --- /dev/null +++ b/crates/nash-can/tests/snapshots/kind_predicates__impl_using_only_default_methods_rejects_a_superclass_contradiction.snap @@ -0,0 +1,13 @@ +--- +source: crates/nash-can/tests/kind_predicates.rs +description: "module Main exposing (..)\n\nimport Primitive exposing (..)\nimport Builtin exposing (..)\n\ntrait Foo ('a : Big) where\n\ntrait Keep 'a where\n keep : 'a -> 'a\nimpl Keep ('a : Big) where\n keep x = x\nimpl Keep ('a : Little) where\n keep x = x\ntrait Keep 'a => Sub 'a where\n sub : 'a -> 'a\n sub x = x\nimpl (Foo 'a, Little 'a) => Sub 'a where\n" +--- +nash::names::contradictory_representation + + × The representation requirements on 'a are incompatible: + ╭─[src/Main.nash:17:11] + 16 │ sub x = x + 17 │ impl (Foo 'a, Little 'a) => Sub 'a where + · ── + ╰──── + help: Change the incompatible constraints or uses of this variable. diff --git a/crates/nash-can/tests/snapshots/kind_predicates__marker_impl_rejects_a_superclass_contradiction.snap b/crates/nash-can/tests/snapshots/kind_predicates__marker_impl_rejects_a_superclass_contradiction.snap new file mode 100644 index 00000000..3164851d --- /dev/null +++ b/crates/nash-can/tests/snapshots/kind_predicates__marker_impl_rejects_a_superclass_contradiction.snap @@ -0,0 +1,13 @@ +--- +source: crates/nash-can/tests/kind_predicates.rs +description: "module Main exposing (..)\n\nimport Primitive exposing (..)\nimport Builtin exposing (..)\n\ntrait Foo ('a : Big) where\n\ntrait Keep 'a where\n keep : 'a -> 'a\nimpl Keep ('a : Big) where\n keep x = x\nimpl Keep ('a : Little) where\n keep x = x\ntrait Keep 'a => Sub 'a where\n\nimpl (Foo 'a, Little 'a) => Sub 'a where\n" +--- +nash::names::contradictory_representation + + × The representation requirements on 'a are incompatible: + ╭─[src/Main.nash:16:11] + 15 │ + 16 │ impl (Foo 'a, Little 'a) => Sub 'a where + · ── + ╰──── + help: Change the incompatible constraints or uses of this variable. From b7cb3a1231f89e87faf7b36534a5b1e3176c4141 Mon Sep 17 00:00:00 2001 From: microproofs Date: Tue, 13 Oct 2026 23:27:54 +0700 Subject: [PATCH 15/24] fix(solve): do not select impls for infinite types Impls are disjoint only over finite types. A let-bound definition's wanted predicates are resolved when it is generalized, before the occurs check of the enclosing binding, so a cyclic argument reached impl selection. Two impls that are disjoint on finite types both matched it (('a, 'a) and ('a, 'a -> 'b) for f f), and select_impl stopped the compiler; an impl that matches at every depth repeated its own context until the work limit and gave a false impl-resolution-limit error. resolve_wanted now defers a wanted whose arguments reach a cycle, before impl selection and relational improvement. The binding's occurs check reports the infinite type and poisons it, as Elm's CLet occurs fold does, which drops the wanted. The cycle check (occurs::reaches_cycle) follows the edges of Elm's occurs but visits each variable once, so types with shared parts stay linear. The select_impl doc comment now states the real invariant. Signed-off-by: microproofs --- .../infinite-type-impl-selection.md | 5 ++ crates/nash-ast/src/head.rs | 8 ++- crates/nash-solve/src/occurs.rs | 51 ++++++++++++++ crates/nash-solve/src/solve.rs | 9 +++ crates/nash-solve/tests/inference.rs | 67 +++++++++++++++++++ ...etween_impls_disjoint_on_finite_types.snap | 15 +++++ ...g_impl_reports_only_the_infinite_type.snap | 15 +++++ ...meter_trait_wait_for_the_occurs_check.snap | 15 +++++ 8 files changed, 183 insertions(+), 2 deletions(-) create mode 100644 .sampo/changesets/infinite-type-impl-selection.md create mode 100644 crates/nash-solve/tests/snapshots/inference__infinite_argument_does_not_select_between_impls_disjoint_on_finite_types.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__infinite_argument_with_one_matching_impl_reports_only_the_infinite_type.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__infinite_arguments_of_a_two_parameter_trait_wait_for_the_occurs_check.snap diff --git a/.sampo/changesets/infinite-type-impl-selection.md b/.sampo/changesets/infinite-type-impl-selection.md new file mode 100644 index 00000000..63dc0857 --- /dev/null +++ b/.sampo/changesets/infinite-type-impl-selection.md @@ -0,0 +1,5 @@ +--- +cargo/nash-solve: patch +--- + +Do not select an impl for a trait constraint whose argument is an infinite type; the occurs check of the binding reports the type, as in Elm. Two impls that are disjoint on finite types can both match an infinite type, which crashed the compiler, and an impl that matches it at every depth gave a false impl-resolution-limit error. diff --git a/crates/nash-ast/src/head.rs b/crates/nash-ast/src/head.rs index 36239ab5..69718c44 100644 --- a/crates/nash-ast/src/head.rs +++ b/crates/nash-ast/src/head.rs @@ -209,8 +209,12 @@ pub enum ImplSelection { } /// Select the impl whose heads match `arguments`. Every candidate is matched, -/// so a second match always stops the compiler: canonicalization rejects -/// overlapping impls, and two matches here mean that check has a bug. +/// and a second match stops the compiler. Two impls can match one argument +/// list only if they overlap on finite types, which canonicalization rejects; +/// if the representation givens contradict each other, which canonicalization +/// rejects in one context and the solver across nested contexts; or if an +/// argument is an infinite type, which inference does not select for (the +/// occurs check of its binding reports it). A second match is a compiler bug. pub fn select_impl<'h, 'a: 'h, T: Types<'a>, I>( types: &mut T, candidates: impl IntoIterator], usize, I)>, diff --git a/crates/nash-solve/src/occurs.rs b/crates/nash-solve/src/occurs.rs index fbee968c..fed09ad4 100644 --- a/crates/nash-solve/src/occurs.rs +++ b/crates/nash-solve/src/occurs.rs @@ -1,5 +1,7 @@ //! Port of Elm's `Type.Occurs`: does a variable occur in its own structure? +use std::collections::BTreeMap; + use nash_constrain::{Content, FlatType, UnionFind, Variable}; pub fn occurs(uf: &mut UnionFind<'_>, var: Variable) -> bool { @@ -64,3 +66,52 @@ fn occurs_help( } } } + +#[derive(Clone, Copy)] +enum Visit { + Active, + Done, +} + +/// Does a cycle occur in a type reachable from `roots`? This follows the +/// edges of `occurs`, but visits each variable once, so a type that repeats a +/// shared part stays linear. `occurs` keeps Elm's path-only check for the +/// occurs check of a binding. +pub fn reaches_cycle(uf: &mut UnionFind<'_>, roots: &[Variable]) -> bool { + let mut visits = BTreeMap::new(); + roots + .iter() + .any(|root| reaches_cycle_help(uf, &mut visits, *root)) +} + +fn reaches_cycle_help( + uf: &mut UnionFind<'_>, + visits: &mut BTreeMap, + var: Variable, +) -> bool { + let var = uf.find(var); + match visits.get(&var) { + Some(Visit::Active) => return true, + Some(Visit::Done) => return false, + None => {} + } + visits.insert(var, Visit::Active); + let children = match uf.get(var).content.clone() { + Content::FlexVar(_) | Content::RigidVar(_) | Content::Error => Vec::new(), + Content::Structure(FlatType::AppV1(head, args)) => [head].into_iter().chain(args).collect(), + Content::Structure(FlatType::App1(_, _, args)) => args, + Content::Structure(FlatType::Fun1(a, b)) => vec![a, b], + Content::Structure(FlatType::Record1(fields)) => fields.into_values().collect(), + Content::Structure(FlatType::Tuple1(a, b, rest)) => { + [a, b].into_iter().chain(rest).collect() + } + Content::Alias { args, .. } | Content::PartialAlias { args, .. } => { + args.into_iter().map(|(_, arg)| arg).collect() + } + }; + let found = children + .into_iter() + .any(|child| reaches_cycle_help(uf, visits, child)); + visits.insert(var, Visit::Done); + found +} diff --git a/crates/nash-solve/src/solve.rs b/crates/nash-solve/src/solve.rs index 05b6eeeb..17166eac 100644 --- a/crates/nash-solve/src/solve.rs +++ b/crates/nash-solve/src/solve.rs @@ -2203,6 +2203,15 @@ impl<'a> Solver<'a, '_> { self.predicates.solve(uf, id, solution); continue; } + // Impls are disjoint only over finite types, and an impl that + // matches an infinite type matches it again at every depth. Elm + // reports an infinite type at the occurs check after its `CLet` + // (`Type/Solve.hs` `occurs`); the binding's check here does the + // same and poisons the type, which drops this wanted. + if occurs::reaches_cycle(uf, &args) { + self.wanted.push((wanted_rank, id)); + continue; + } // A blanket impl can match a rigid argument without narrowing it; // its prerequisites are checked against the enclosing givens below. let givens: Vec<_> = self diff --git a/crates/nash-solve/tests/inference.rs b/crates/nash-solve/tests/inference.rs index 0465fb51..a9baf3cc 100644 --- a/crates/nash-solve/tests/inference.rs +++ b/crates/nash-solve/tests/inference.rs @@ -2622,6 +2622,73 @@ fn infinite_type() { ); } +/// Impls are disjoint only over finite types: the infinite type of `f` +/// matches both heads. The occurs check of the binding must report it. +#[test] +fn infinite_argument_does_not_select_between_impls_disjoint_on_finite_types() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + trait Same 'a where + same : 'a -> () + impl Same ('a, 'a) where + same _ = () + impl Same ('a, 'a -> 'b) where + same _ = () + bad f = + let + g = ( f f, same ( f, f ) ) + in + g + "# + ); +} + +/// Two arguments also reach the relational improvement probes. +#[test] +fn infinite_arguments_of_a_two_parameter_trait_wait_for_the_occurs_check() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + trait Pair 'a 'b where + pair : 'a -> 'b -> () + impl Pair 'a 'a where + pair _ _ = () + impl Pair 'a (list 'a) where + pair _ _ = () + same : 'a -> 'a -> 'a + same a _ = a + bad x = + let + g = ( same x [ x ], pair x x ) + in + g + "# + ); +} + +/// One impl matches the infinite type at every depth, so selecting it would +/// repeat its own context until the work limit. +#[test] +fn infinite_argument_with_one_matching_impl_reports_only_the_infinite_type() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + trait Show2 'a where + show2 : 'a -> () + impl Show2 'a => Show2 (list 'a) where + show2 _ = () + same : 'a -> 'a -> 'a + same a _ = a + bad x = + let + g = ( same x [ x ], show2 x ) + in + g + "# + ); +} + #[test] fn string_literal_requires_an_impl_for_the_result_type() { assert_inference_error_snapshot!( diff --git a/crates/nash-solve/tests/snapshots/inference__infinite_argument_does_not_select_between_impls_disjoint_on_finite_types.snap b/crates/nash-solve/tests/snapshots/inference__infinite_argument_does_not_select_between_impls_disjoint_on_finite_types.snap new file mode 100644 index 00000000..12a5a679 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__infinite_argument_does_not_select_between_impls_disjoint_on_finite_types.snap @@ -0,0 +1,15 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\ntrait Same 'a where\n same : 'a -> ()\nimpl Same ('a, 'a) where\n same _ = ()\nimpl Same ('a, 'a -> 'b) where\n same _ = ()\nbad f =\n let\n g = ( f f, same ( f, f ) )\n in\n g\n" +info: diagnostic +--- +nash::type::infinite_type + + × `f` has a self-referential type: ∞ -> 'a + ╭─[Main.nash:8:5] + 7 │ same _ = () + 8 │ bad f = + · ─ + 9 │ let + ╰──── + help: Break the type cycle; ∞ marks a repeated part of the type. diff --git a/crates/nash-solve/tests/snapshots/inference__infinite_argument_with_one_matching_impl_reports_only_the_infinite_type.snap b/crates/nash-solve/tests/snapshots/inference__infinite_argument_with_one_matching_impl_reports_only_the_infinite_type.snap new file mode 100644 index 00000000..2113548d --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__infinite_argument_with_one_matching_impl_reports_only_the_infinite_type.snap @@ -0,0 +1,15 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\ntrait Show2 'a where\n show2 : 'a -> ()\nimpl Show2 'a => Show2 (list 'a) where\n show2 _ = ()\nsame : 'a -> 'a -> 'a\nsame a _ = a\nbad x =\n let\n g = ( same x [ x ], show2 x )\n in\n g\n" +info: diagnostic +--- +nash::type::infinite_type + + × `g` has a self-referential type: ( list ∞, unit ) + ╭─[Main.nash:10:9] + 9 │ let + 10 │ g = ( same x [ x ], show2 x ) + · ─ + 11 │ in + ╰──── + help: Break the type cycle; ∞ marks a repeated part of the type. diff --git a/crates/nash-solve/tests/snapshots/inference__infinite_arguments_of_a_two_parameter_trait_wait_for_the_occurs_check.snap b/crates/nash-solve/tests/snapshots/inference__infinite_arguments_of_a_two_parameter_trait_wait_for_the_occurs_check.snap new file mode 100644 index 00000000..3094118c --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__infinite_arguments_of_a_two_parameter_trait_wait_for_the_occurs_check.snap @@ -0,0 +1,15 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\ntrait Pair 'a 'b where\n pair : 'a -> 'b -> ()\nimpl Pair 'a 'a where\n pair _ _ = ()\nimpl Pair 'a (list 'a) where\n pair _ _ = ()\nsame : 'a -> 'a -> 'a\nsame a _ = a\nbad x =\n let\n g = ( same x [ x ], pair x x )\n in\n g\n" +info: diagnostic +--- +nash::type::infinite_type + + × `g` has a self-referential type: ( list ∞, unit ) + ╭─[Main.nash:12:9] + 11 │ let + 12 │ g = ( same x [ x ], pair x x ) + · ─ + 13 │ in + ╰──── + help: Break the type cycle; ∞ marks a repeated part of the type. From baadec9e5b89b384d1433a68849bd85a237b6aea Mon Sep 17 00:00:00 2001 From: microproofs Date: Wed, 14 Oct 2026 00:39:16 +0700 Subject: [PATCH 16/24] feat(traits): select representation-split impls by coverage A rigid type variable at an impl-head position that tests a representation class kept impl selection from deciding: same : Eq 'a => list 'a -> list 'a -> bool was rejected with "No impl for Eq (list 'a)", although Base has an Eq list impl for every element representation. Inference now proves such a predicate by coverage (audit item 08, owner decisions D2, N2, N3): - nash-ast head::cover_impls finds the rigid subjects, checks the limit first (the given closure holds the wanted trait at each subject), then selects an impl for every admitted Big/Const/Term cell. One work budget pays for all of it. - nash-solve runs it in resolve_wanted when selection defers or misses, and proves each covered impl's context under its cell with a non-deferring prover (givens, representations, impls, coverage again). The proofs are recorded as Solution::Specialize subs, so the growing evidence check rejects polymorphic recursion through coverage. A missing element trait or branch context is a missing-constraint error; an uncovered cell keeps today's missing-impl text. - The evidence is Evidence::Specialize { trait_, args }. Code generation selects the impl for each use (method B): the demand analysis gives each template the type variables that coverage selects with, propagated through calls, and the specialization key holds their types. Superclass proofs in nash-can do not use the rule (N3). nash-can is not changed. Signed-off-by: microproofs --- .sampo/changesets/representation-coverage.md | 7 + crates/nash-ast/src/evidence.rs | 14 + crates/nash-ast/src/head.rs | 362 +++++++++++++- crates/nash-ast/src/lib.rs | 7 + crates/nash-ast/src/primitives.rs | 8 + ..._coverage_tests__cover_impls_outcomes.snap | 20 + crates/nash-can/tests/impls.rs | 19 + ...oof_needs_the_split_requirement_named.snap | 17 + crates/nash-codegen/src/build.rs | 29 +- crates/nash-codegen/src/demand.rs | 142 +++++- crates/nash-codegen/src/evidence.rs | 30 +- crates/nash-driver/tests/base_traits.rs | 4 + .../tests/fixtures/base-traits/Coverage.nash | 71 +++ .../base_traits__representation_coverage.snap | 11 + crates/nash-solve/src/preds.rs | 6 + crates/nash-solve/src/resolve.rs | 204 ++++++-- crates/nash-solve/src/solve.rs | 454 ++++++++++++++++-- crates/nash-solve/tests/evidence.rs | 2 +- crates/nash-solve/tests/inference.rs | 195 ++++++++ ...__coverage_counts_as_growing_evidence.snap | 16 + ..._context_of_an_unannotated_definition.snap | 5 + ...age_names_the_element_without_a_given.snap | 16 + ...anch_context_under_its_representation.snap | 5 + ...rage_reports_a_missing_branch_context.snap | 16 + ..._reports_the_uncovered_representation.snap | 20 + ...age_requires_the_trait_at_the_element.snap | 16 + ...verage_search_stops_at_the_work_limit.snap | 16 + ...lects_split_impls_for_a_rigid_element.snap | 5 + docs/codegen.md | 10 + docs/traits.md | 31 +- 30 files changed, 1651 insertions(+), 107 deletions(-) create mode 100644 .sampo/changesets/representation-coverage.md create mode 100644 crates/nash-ast/src/snapshots/nash_ast__head__coverage_tests__cover_impls_outcomes.snap create mode 100644 crates/nash-can/tests/snapshots/impls__superclass_proof_needs_the_split_requirement_named.snap create mode 100644 crates/nash-driver/tests/fixtures/base-traits/Coverage.nash create mode 100644 crates/nash-driver/tests/snapshots/base_traits__representation_coverage.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__coverage_counts_as_growing_evidence.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__coverage_keeps_the_inferred_context_of_an_unannotated_definition.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__coverage_names_the_element_without_a_given.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__coverage_proves_a_branch_context_under_its_representation.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__coverage_reports_a_missing_branch_context.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__coverage_reports_the_uncovered_representation.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__coverage_requires_the_trait_at_the_element.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__coverage_search_stops_at_the_work_limit.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__coverage_selects_split_impls_for_a_rigid_element.snap diff --git a/.sampo/changesets/representation-coverage.md b/.sampo/changesets/representation-coverage.md new file mode 100644 index 00000000..2c34cda2 --- /dev/null +++ b/.sampo/changesets/representation-coverage.md @@ -0,0 +1,7 @@ +--- +cargo/nash-ast: minor +cargo/nash-solve: minor +cargo/nash-codegen: minor +--- + +Add the representation coverage rule. When a rigid type variable keeps impl selection from deciding, because the impls are split by its representation class (for example `Eq (list ('a : Big))` and `Eq 'a => Eq (list ('a : Little))`), inference accepts the predicate if the annotation states the trait at that variable and every admitted representation selects an impl whose context holds. `same : Eq 'a => list 'a -> list 'a -> bool` now compiles. The evidence is the new `Evidence::Specialize`; code generation selects the impl for each use and keeps the selecting types in the specialization key. A missing element constraint is now reported as a missing constraint, such as `Eq 'a`, instead of a missing impl for the container. Superclass proofs do not use the rule: an impl names a split requirement in its context. nash-ast also gains `head::cover_impls` and `ReprTrait::exactly`. diff --git a/crates/nash-ast/src/evidence.rs b/crates/nash-ast/src/evidence.rs index 83d918ab..3c2ffae4 100644 --- a/crates/nash-ast/src/evidence.rs +++ b/crates/nash-ast/src/evidence.rs @@ -173,6 +173,16 @@ impl PartialEq for Evidence<'_> { (Self::Super { of: ao, index: ai }, Self::Super { of: bo, index: bi }) => { ao == bo && ai == bi } + ( + Self::Specialize { + trait_: a, + args: aa, + }, + Self::Specialize { + trait_: b, + args: ba, + }, + ) => a == b && same_types(aa, ba), _ => false, } } @@ -208,6 +218,10 @@ impl Hash for Evidence<'_> { of.hash(state); index.hash(state); } + Self::Specialize { trait_, args } => { + trait_.hash(state); + hash_types(args, state); + } } } } diff --git a/crates/nash-ast/src/head.rs b/crates/nash-ast/src/head.rs index 69718c44..f4978884 100644 --- a/crates/nash-ast/src/head.rs +++ b/crates/nash-ast/src/head.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use crate::Type; use crate::primitives::{Repr, ReprSet}; -use crate::{Head, HeadCon}; +use crate::{Head, HeadCon, QualifiedName}; use nash_region::Located; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -250,6 +250,139 @@ pub fn select_impl<'h, 'a: 'h, T: Types<'a>, I>( }) } +/// What a representation-tested head position learns about its argument. +pub enum CoverageSubject { + /// The class test is decided; ordinary selection handles it. + Decided, + /// The argument can still change; coverage cannot apply yet. + Deferred, + /// A rigid argument whose class is open within `admitted`. + Rigid { subject: S, admitted: ReprSet }, +} + +/// Type and given view for the finite search over representation cells. +pub trait CoverageTypes<'a>: Types<'a> { + type Subject: Copy + Ord; + fn coverage_subject( + &mut self, + node: Self::Node, + tested: ReprSet, + ) -> CoverageSubject; + /// True when a given holds `trait_` with this subject as a direct argument. + fn given_at(&mut self, trait_: QualifiedName<'a>, subject: Self::Subject) -> bool; + /// Class tests of later selections see these representations. + fn set_coverage_assumptions(&mut self, assumptions: &[(Self::Subject, Repr)]); +} + +pub enum Coverage { + /// No rigid subject decides the selection, or an argument can still change. + NotApplicable, + /// No given holds the wanted trait at this subject. + Unstated(S), + /// This cell selects no impl. + Missing(Vec<(S, Repr)>), + Complete(Vec>), +} + +pub struct CoveredImpl { + pub assumptions: Vec<(S, Repr)>, + pub info: I, + pub arguments: Vec, +} + +/// Select an impl for every admitted representation cell of the rigid +/// variables at representation-tested head positions. Only such positions +/// create dimensions. The limit comes first: every subject needs a given of +/// `trait_` at it, so a signature never hides the trait that selects. One +/// budget pays for the discovery, the cells and every selection. +pub fn cover_impls<'h, 'a: 'h, T: CoverageTypes<'a>, I: Copy>( + types: &mut T, + trait_: QualifiedName<'a>, + candidates: &[(&'h [Head<'a>], usize, I)], + arguments: &[T::Node], + remaining: &mut usize, +) -> Result, Limit> { + let mut subjects = BTreeMap::new(); + let mut deferred = false; + for (heads, _, _) in candidates { + let mut pending: Vec<_> = heads.iter().zip(arguments.iter().copied()).collect(); + while let Some((head, argument)) = pending.pop() { + step(remaining)?; + match head { + Head::Var { repr, .. } if repr.is_all() => {} + Head::Var { repr, .. } => match types.coverage_subject(argument, *repr) { + CoverageSubject::Decided => {} + CoverageSubject::Deferred => deferred = true, + CoverageSubject::Rigid { subject, admitted } => { + subjects + .entry(subject) + .and_modify(|old: &mut ReprSet| *old = old.intersect(admitted)) + .or_insert(admitted); + } + }, + _ => match types.constructor(argument, head.con().expect("constructor pattern")) { + Match::Yes(nodes) => { + let patterns = children(head); + if patterns.len() == nodes.len() { + pending.extend(patterns.into_iter().zip(nodes)); + } + } + Match::Deferred => deferred = true, + Match::No => {} + }, + } + } + } + if deferred || subjects.is_empty() { + return Ok(Coverage::NotApplicable); + } + if let Some(subject) = subjects + .keys() + .copied() + .find(|subject| !types.given_at(trait_, *subject)) + { + return Ok(Coverage::Unstated(subject)); + } + let mut cells = vec![Vec::new()]; + for (subject, admitted) in subjects { + let mut next = Vec::new(); + for cell in cells { + for repr in [Repr::Big, Repr::Const, Repr::Term] { + if admitted.contains(repr) { + step(remaining)?; + let mut cell: Vec<_> = cell.clone(); + cell.push((subject, repr)); + next.push(cell); + } + } + } + cells = next; + } + let mut covered = Vec::new(); + for assumptions in cells { + types.set_coverage_assumptions(&assumptions); + let selected = select_impl( + types, + candidates.iter().copied(), + arguments, + remaining, + SelectPolicy::Defer, + ); + types.set_coverage_assumptions(&[]); + match selected? { + ImplSelection::Selected { info, arguments } => covered.push(CoveredImpl { + assumptions, + info, + arguments, + }), + ImplSelection::Missing | ImplSelection::Deferred => { + return Ok(Coverage::Missing(assumptions)); + } + } + } + Ok(Coverage::Complete(covered)) +} + #[derive(Clone, Copy)] struct Term<'p, 'a> { pattern: &'p Head<'a>, @@ -528,3 +661,230 @@ mod select_tests { let _ = select(&[Yes, Deferred, Yes], Defer, 100); } } + +#[cfg(test)] +mod coverage_tests { + use super::*; + + /// Arguments are rigid subjects, or a pair of them for tuple heads. A + /// subject belongs to a class only through the current cell. + #[derive(Clone, Copy)] + enum Arg { + Subject(u8), + Pair(u8, u8), + } + + struct Rigid { + given: Vec, + deferred: bool, + assumptions: Vec<(u8, Repr)>, + } + + impl<'a> Types<'a> for Rigid { + type Node = Arg; + fn in_class(&mut self, node: Arg, class: ReprSet) -> Match<()> { + let Arg::Subject(subject) = node else { + return Match::No; + }; + match self.assumptions.iter().find(|(other, _)| *other == subject) { + Some((_, repr)) if class.contains(*repr) => Match::Yes(()), + _ => Match::No, + } + } + fn constructor(&mut self, node: Arg, expected: HeadCon<'a>) -> Match> { + match (node, expected) { + (Arg::Pair(a, b), HeadCon::Tuple(2)) => { + Match::Yes(vec![Arg::Subject(a), Arg::Subject(b)]) + } + _ => Match::No, + } + } + fn equal(&mut self, _: Arg, _: Arg, _: &mut usize) -> Result, Limit> { + unreachable!("no head repeats a variable") + } + } + + impl<'a> CoverageTypes<'a> for Rigid { + type Subject = u8; + fn coverage_subject(&mut self, node: Arg, _: ReprSet) -> CoverageSubject { + match node { + _ if self.deferred => CoverageSubject::Deferred, + Arg::Subject(subject) => CoverageSubject::Rigid { + subject, + admitted: ReprSet::ALL, + }, + Arg::Pair(..) => unreachable!("tuple heads are constructors"), + } + } + fn given_at(&mut self, _: QualifiedName<'a>, subject: u8) -> bool { + self.given.contains(&subject) + } + fn set_coverage_assumptions(&mut self, assumptions: &[(u8, Repr)]) { + self.assumptions = assumptions.to_vec(); + } + } + + const BIG: ReprSet = ReprSet::only(Repr::Big); + const LITTLE: ReprSet = crate::primitives::ReprTrait::Little.admits(); + const fn var(index: u16, repr: ReprSet) -> Head<'static> { + Head::Var { index, repr } + } + const BIG_HEAD: [Head<'static>; 1] = [var(0, BIG)]; + const LITTLE_HEAD: [Head<'static>; 1] = [var(0, LITTLE)]; + const PAIR_BIG: [Head<'static>; 1] = [Head::Tuple(&[var(0, BIG), var(1, ReprSet::ALL)])]; + const PAIR_LITTLE_BIG: [Head<'static>; 1] = [Head::Tuple(&[var(0, LITTLE), var(1, BIG)])]; + const PAIR_LITTLE_LITTLE: [Head<'static>; 1] = [Head::Tuple(&[var(0, LITTLE), var(1, LITTLE)])]; + + fn search( + impls: &[(&'static str, &[Head<'static>])], + argument: Arg, + given: &[u8], + deferred: bool, + budget: usize, + ) -> (Result, Limit>, usize) { + let trait_ = QualifiedName { + home: crate::ModuleName { + package: None, + name: "Main", + }, + name: "Probe", + }; + let candidates: Vec<_> = impls + .iter() + .map(|(name, heads)| { + let variables = match heads { + [Head::Tuple(_)] => 2, + _ => 1, + }; + (*heads, variables, *name) + }) + .collect(); + let mut types = Rigid { + given: given.to_vec(), + deferred, + assumptions: Vec::new(), + }; + let mut remaining = budget; + let result = cover_impls(&mut types, trait_, &candidates, &[argument], &mut remaining); + (result, budget - remaining) + } + + fn cell(assumptions: &[(u8, Repr)]) -> String { + assumptions + .iter() + .map(|(subject, repr)| format!("'{} {repr:?}", char::from(b'a' + subject))) + .collect::>() + .join(", ") + } + + fn render(result: Result, Limit>) -> String { + match result { + Ok(Coverage::NotApplicable) => "not applicable".to_owned(), + Ok(Coverage::Unstated(subject)) => { + format!("needs the trait at '{}", char::from(b'a' + subject)) + } + Ok(Coverage::Missing(assumptions)) => { + format!("no impl for the cell {}", cell(&assumptions)) + } + Ok(Coverage::Complete(covered)) => covered + .iter() + .map(|covered| format!("{} selects {}", cell(&covered.assumptions), covered.info)) + .collect::>() + .join("; "), + Err(Limit) => "work limit".to_owned(), + } + } + + #[test] + fn cover_impls_outcomes() { + let split: &[(&str, &[Head])] = &[("big", &BIG_HEAD), ("little", &LITTLE_HEAD)]; + let only_big: &[(&str, &[Head])] = &[("big", &BIG_HEAD)]; + let pairs: &[(&str, &[Head])] = &[ + ("first big", &PAIR_BIG), + ("first little, second big", &PAIR_LITTLE_BIG), + ("both little", &PAIR_LITTLE_LITTLE), + ]; + let element = Arg::Subject(0); + let both = Arg::Pair(0, 1); + let (_, pairs_cost) = search(pairs, both, &[0, 1], false, WORK_LIMIT); + let scenarios = [ + ( + "Big and Little impls, given at 'a", + split, + element, + &[0][..], + false, + WORK_LIMIT, + ), + ( + "only a Big impl, given at 'a", + only_big, + element, + &[0], + false, + WORK_LIMIT, + ), + ( + "Big and Little impls, no given", + split, + element, + &[], + false, + WORK_LIMIT, + ), + ( + "only a Big impl, no given (the limit comes first)", + only_big, + element, + &[], + false, + WORK_LIMIT, + ), + ( + "Big and Little impls, the argument can still change", + split, + element, + &[0], + true, + WORK_LIMIT, + ), + ( + "pair impls, given at 'a and 'b", + pairs, + both, + &[0, 1], + false, + WORK_LIMIT, + ), + ( + "pair impls, given at 'a only", + pairs, + both, + &[0], + false, + WORK_LIMIT, + ), + ( + "pair impls, one step less than the whole search", + pairs, + both, + &[0, 1], + false, + pairs_cost - 1, + ), + ]; + let mut output = String::new(); + for (name, impls, argument, given, deferred, budget) in scenarios { + let (result, _) = search(impls, argument, given, deferred, budget); + output.push_str(&format!("{name}\n {}\n", render(result))); + } + insta::with_settings!({ + description => "Coverage of a wanted predicate whose arguments are rigid variables. \ + Big covers Big; Little covers Const and Term. One budget pays for subject \ + discovery, the cells, and every selection.", + omit_expression => true, + }, { + insta::assert_snapshot!(output); + }); + } +} diff --git a/crates/nash-ast/src/lib.rs b/crates/nash-ast/src/lib.rs index 975fa4a0..a7c92af3 100644 --- a/crates/nash-ast/src/lib.rs +++ b/crates/nash-ast/src/lib.rs @@ -649,6 +649,13 @@ pub enum Evidence<'a> { Given { binder: NodeId, index: u16 }, /// The `index`-th superclass of `of`'s trait. Super { of: &'a Evidence<'a>, index: u16 }, + /// Representation coverage: the impl depends on the representation of a + /// rigid variable in `args`. Code generation selects it for each use, when + /// the arguments are known. + Specialize { + trait_: QualifiedName<'a>, + args: &'a [&'a Located>], + }, } impl<'a> Head<'a> { diff --git a/crates/nash-ast/src/primitives.rs b/crates/nash-ast/src/primitives.rs index db3743f3..a9ad9902 100644 --- a/crates/nash-ast/src/primitives.rs +++ b/crates/nash-ast/src/primitives.rs @@ -133,6 +133,14 @@ impl ReprTrait { Self::Little => 6, }) } + /// The representation trait that admits exactly `repr`. + pub const fn exactly(repr: Repr) -> Self { + match repr { + Repr::Big => Self::Big, + Repr::Const => Self::Const, + Repr::Term => Self::Term, + } + } pub const fn supers(self) -> &'static [Self] { match self { Self::Big => &[Self::Storable], diff --git a/crates/nash-ast/src/snapshots/nash_ast__head__coverage_tests__cover_impls_outcomes.snap b/crates/nash-ast/src/snapshots/nash_ast__head__coverage_tests__cover_impls_outcomes.snap new file mode 100644 index 00000000..b4e38f00 --- /dev/null +++ b/crates/nash-ast/src/snapshots/nash_ast__head__coverage_tests__cover_impls_outcomes.snap @@ -0,0 +1,20 @@ +--- +source: crates/nash-ast/src/head.rs +description: "Coverage of a wanted predicate whose arguments are rigid variables. Big covers Big; Little covers Const and Term. One budget pays for subject discovery, the cells, and every selection." +--- +Big and Little impls, given at 'a + 'a Big selects big; 'a Const selects little; 'a Term selects little +only a Big impl, given at 'a + no impl for the cell 'a Const +Big and Little impls, no given + needs the trait at 'a +only a Big impl, no given (the limit comes first) + needs the trait at 'a +Big and Little impls, the argument can still change + not applicable +pair impls, given at 'a and 'b + 'a Big, 'b Big selects first big; 'a Big, 'b Const selects first big; 'a Big, 'b Term selects first big; 'a Const, 'b Big selects first little, second big; 'a Const, 'b Const selects both little; 'a Const, 'b Term selects both little; 'a Term, 'b Big selects first little, second big; 'a Term, 'b Const selects both little; 'a Term, 'b Term selects both little +pair impls, given at 'a only + needs the trait at 'b +pair impls, one step less than the whole search + work limit diff --git a/crates/nash-can/tests/impls.rs b/crates/nash-can/tests/impls.rs index c8fffd7c..d20b8141 100644 --- a/crates/nash-can/tests/impls.rs +++ b/crates/nash-can/tests/impls.rs @@ -1142,3 +1142,22 @@ fn classed_superclass_selection_normalizes_alias_application_givens() { insta::assert_debug_snapshot!(result.module.impls); }); } + +/// A superclass proof never uses representation coverage (owner decision N3): +/// an impl names the split requirement in its context. Only the element +/// requirement is not enough, although inference would cover it in a body. +#[test] +fn superclass_proof_needs_the_split_requirement_named() { + let snapshot_inputs = SnapshotInputs::default(); + let bump = Bump::new(); + let mut results = Vec::new(); + for context in ["Kind (list 'a)", "Kind 'a"] { + let source = format!( + "module Main exposing (..)\nimport Primitive exposing (Big, Little)\ntrait Kind 'a where\n kind : 'a -> 'a\nimpl Kind (list ('a : Big)) where\n kind x = x\nimpl Kind 'a => Kind (list ('a : Little)) where\n kind x = x\ntrait Kind 'a => Child 'a where\n child : 'a -> 'a\nimpl {context} => Child (list 'a) where\n child x = x\n" + ); + results.push(canonicalize(&bump, snapshot_inputs.record(&source)).map(|_| ())); + } + insta::with_settings!({description => snapshot_inputs.description(), omit_expression => true}, { + insta::assert_snapshot!(snapshot_inputs.results(&results)); + }); +} diff --git a/crates/nash-can/tests/snapshots/impls__superclass_proof_needs_the_split_requirement_named.snap b/crates/nash-can/tests/snapshots/impls__superclass_proof_needs_the_split_requirement_named.snap new file mode 100644 index 00000000..68e323d8 --- /dev/null +++ b/crates/nash-can/tests/snapshots/impls__superclass_proof_needs_the_split_requirement_named.snap @@ -0,0 +1,17 @@ +--- +source: crates/nash-can/tests/impls.rs +description: "module Main exposing (..)\nimport Primitive exposing (Big, Little)\ntrait Kind 'a where\n kind : 'a -> 'a\nimpl Kind (list ('a : Big)) where\n kind x = x\nimpl Kind 'a => Kind (list ('a : Little)) where\n kind x = x\ntrait Kind 'a => Child 'a where\n child : 'a -> 'a\nimpl Kind (list 'a) => Child (list 'a) where\n child x = x\n\n\nmodule Main exposing (..)\nimport Primitive exposing (Big, Little)\ntrait Kind 'a where\n kind : 'a -> 'a\nimpl Kind (list ('a : Big)) where\n kind x = x\nimpl Kind 'a => Kind (list ('a : Little)) where\n kind x = x\ntrait Kind 'a => Child 'a where\n child : 'a -> 'a\nimpl Kind 'a => Child (list 'a) where\n child x = x\n" +--- +Case 1: accepted +nash::names::missing_superclass + + × The `Main.Child` impl for (Primitive.list ('a0 : Storable)) does not establish + │ superclass 1: + ╭─[src/Main.nash:11:1] + 10 │ child : 'a -> 'a + 11 │ ╭─▶ impl Kind 'a => Child (list 'a) where + 12 │ ╰─▶ child x = x + ╰──── + help: It must also satisfy `Main.Kind (Primitive.list 'a)`. I cannot find an impl or + context constraint that provides it. Add the required impl or include the + necessary constraint in this impl's context. diff --git a/crates/nash-codegen/src/build.rs b/crates/nash-codegen/src/build.rs index 5c87b312..10246bfb 100644 --- a/crates/nash-codegen/src/build.rs +++ b/crates/nash-codegen/src/build.rs @@ -293,6 +293,8 @@ struct Key<'a> { template: usize, evidence: Vec>, layouts: Vec>, + /// Types that representation coverage selects an impl with. + coverage: Vec>, } struct InstanceBody<'a> { template: usize, @@ -500,13 +502,13 @@ impl<'a, 'b, 's> Engine<'a, 'b, 's> { } pub fn eager_template(&self, template: usize) -> Result> { let annotation = self.scheme(template)?.annotation; + let id = self.templates[template].id(); + let demanded = + |names: &crate::demand::Names<'a>| names.get(&id).is_some_and(|d| !d.is_empty()); Ok(annotation.free_vars.is_empty() || (annotation.context.iter().all(|p| p.trait_ref().is_none()) - && self - .build - .demands - .get(&self.templates[template].id()) - .is_none_or(|d| d.is_empty()))) + && !demanded(&self.build.demands.layouts) + && !demanded(&self.build.demands.coverage))) } pub fn can_type( &self, @@ -615,7 +617,7 @@ impl<'a, 'b, 's> Engine<'a, 'b, 's> { ) -> Result, Error<'a>> { let t = &self.templates[template]; let mut layouts = Vec::new(); - if let Some(demands) = self.build.demands.get(&t.id()) { + if let Some(demands) = self.build.demands.layouts.get(&t.id()) { for name in demands { let Some(typ) = subst.get(name) else { return Err(Error::RuntimeLayout(Ty::Erased)); @@ -625,6 +627,18 @@ impl<'a, 'b, 's> Engine<'a, 'b, 's> { layouts.push(native(self.ir.arena, ty)?); } } + let mut coverage = Vec::new(); + if let Some(names) = self.build.demands.coverage.get(&t.id()) { + for name in names { + let typ = *subst.get(name).ok_or(Error::RuntimeLayout(Ty::Erased))?; + check_type(typ, &Substitution::new())?; + let ty = self.types.ty(typ, &Substitution::new())?; + if ty == Ty::Erased { + return Err(Error::RuntimeLayout(ty)); + } + coverage.push(ty); + } + } let evidence_key = evidence .iter() .map(evidence::executable_identity) @@ -636,6 +650,7 @@ impl<'a, 'b, 's> Engine<'a, 'b, 's> { template, layouts, evidence: evidence_key, + coverage, }; if let Some(old) = self.specs.iter().find(|old| old.key == key) { return Ok(old.binder); @@ -648,7 +663,7 @@ impl<'a, 'b, 's> Engine<'a, 'b, 's> { for name in scheme.annotation.free_vars { runtime_subst.remove(name); } - if let Some(demands) = self.build.demands.get(&t.id()) { + if let Some(demands) = self.build.demands.layouts.get(&t.id()) { for name in demands { let typ = *subst.get(name).ok_or(Error::RuntimeLayout(Ty::Erased))?; let layout = self.types.ty(typ, &Substitution::new())?; diff --git a/crates/nash-codegen/src/demand.rs b/crates/nash-codegen/src/demand.rs index 69f79e05..a7e67662 100644 --- a/crates/nash-codegen/src/demand.rs +++ b/crates/nash-codegen/src/demand.rs @@ -1,12 +1,21 @@ -//! Fixed-point analysis of the type variables inspected by generated code. +//! Fixed-point analysis of the type variables whose concrete types belong in a +//! specialization key. use nash_ast::{primitives, *}; use nash_region::Located; use nash_solve::SolvedTypes; use std::collections::{BTreeSet, HashMap}; -pub type Demands<'a> = HashMap>; +pub(crate) type Names<'a> = HashMap>; type Scope<'a> = HashMap<&'a str, Option>; +/// Type variables of each definition, in its solved scheme's names. +pub struct Demands<'a> { + /// Variables whose runtime layout generated code inspects. + pub layouts: Names<'a>, + /// Variables whose types select an impl by representation coverage. + pub coverage: Names<'a>, +} + #[cfg(test)] mod tests { use super::*; @@ -52,7 +61,8 @@ struct MethodCall<'a> { args: &'a [&'a Located>], } struct Analysis<'a> { - demands: Demands<'a>, + demands: Names<'a>, + coverage: Names<'a>, owners: HashMap>, top: HashMap, NodeId>, methods: HashMap<(QualifiedName<'a>, &'a str), Vec>, @@ -65,6 +75,7 @@ struct Analysis<'a> { pub fn analyze<'a>(modules: &[(&Module<'a>, &SolvedTypes<'a>)]) -> Demands<'a> { let mut a = Analysis { demands: HashMap::new(), + coverage: HashMap::new(), owners: HashMap::new(), top: HashMap::new(), methods: HashMap::new(), @@ -144,6 +155,7 @@ pub fn analyze<'a>(modules: &[(&Module<'a>, &SolvedTypes<'a>)]) -> Demands<'a> { } loop { let previous = a.demands.clone(); + let previous_coverage = a.coverage.clone(); for call in &a.calls { let Some(owner) = a.owners.get(&call.target) else { continue; @@ -155,20 +167,34 @@ pub fn analyze<'a>(modules: &[(&Module<'a>, &SolvedTypes<'a>)]) -> Demands<'a> { variables(typ, a.demands.entry(call.caller).or_default()); } } + // A coverage type anywhere in an argument selects the callee's impl. + for &name in &previous_coverage[&call.target] { + if let Some(index) = owner.free.iter().position(|v| *v == name) + && let Some(typ) = call.args.get(index) + { + all_variables(typ, a.coverage.entry(call.caller).or_default()); + } + } } for call in &a.method_calls { // A Given can select any applicable implementation at specialization. // Demand arguments only when a real method body inspects a layout. - if a.methods - .get(&(call.trait_, call.method)) - .into_iter() - .flatten() - .any(|id| !previous[id].is_empty()) - { + let bodies = || { + a.methods + .get(&(call.trait_, call.method)) + .into_iter() + .flatten() + }; + if bodies().any(|id| !previous[id].is_empty()) { for typ in call.args { variables(typ, a.demands.entry(call.caller).or_default()); } } + if bodies().any(|id| !previous_coverage[id].is_empty()) { + for typ in call.args { + all_variables(typ, a.coverage.entry(call.caller).or_default()); + } + } } for (id, owner) in &a.owners { if let Some(parent) = owner.parent { @@ -177,10 +203,18 @@ pub fn analyze<'a>(modules: &[(&Module<'a>, &SolvedTypes<'a>)]) -> Demands<'a> { a.demands.entry(parent).or_default().insert(name); } } + for &name in &previous_coverage[id] { + if !owner.free.contains(&name) { + a.coverage.entry(parent).or_default().insert(name); + } + } } } - if previous == a.demands { - return a.demands; + if previous == a.demands && previous_coverage == a.coverage { + return Demands { + layouts: a.demands, + coverage: a.coverage, + }; } } } @@ -251,6 +285,70 @@ fn variables<'a>(typ: &'a Located>, out: &mut BTreeSet<&'a str>) { _ => {} } } +/// Every type variable of a type, in any position. +fn all_variables<'a>(typ: &'a Located>, out: &mut BTreeSet<&'a str>) { + match &typ.value { + Type::Var(name) => { + out.insert(name); + } + Type::Named { args, .. } => { + for t in *args { + all_variables(t, out); + } + } + Type::App { head, args } => { + all_variables(head, out); + for t in *args { + all_variables(t, out); + } + } + Type::Lambda { from, to } => { + all_variables(from, out); + all_variables(to, out); + } + Type::Tuple { + first, + second, + rest, + } => { + all_variables(first, out); + all_variables(second, out); + for t in *rest { + all_variables(t, out); + } + } + Type::Record { fields } => { + for field in *fields { + all_variables(field.typ, out); + } + } + Type::Alias { arguments, .. } => { + for arg in *arguments { + all_variables(arg.typ, out); + } + } + } +} +/// The variables of every coverage selection in this evidence. +fn specialized_variables<'a>(evidence: &Evidence<'a>, out: &mut BTreeSet<&'a str>) { + match evidence { + Evidence::Specialize { args, .. } => { + for arg in *args { + all_variables(arg, out); + } + } + Evidence::Impl { args, .. } => { + for arg in *args { + specialized_variables(arg, out); + } + } + Evidence::Super { of, .. } => specialized_variables(of, out), + Evidence::Repr { .. } + | Evidence::ReflexiveLift { .. } + | Evidence::StructuralEq { .. } + | Evidence::Given { .. } => {} + } +} fn bind<'a>(p: &'a Located>, target: Option, env: &mut Scope<'a>) { match &p.value { Pattern::Var(name) => { @@ -310,6 +408,7 @@ impl<'a> Analysis<'a> { }, ); self.demands.entry(id).or_default(); + self.coverage.entry(id).or_default(); } fn def( &mut self, @@ -359,12 +458,22 @@ impl<'a> Analysis<'a> { } } fn call(&mut self, target: NodeId, node: NodeId, caller: NodeId, solved: &SolvedTypes<'a>) { + self.specialized(node, caller, solved); self.calls.push(Call { caller, target, args: solved.instances.get(&node).map_or(&[], |i| i.type_args), }); } + /// The caller's key holds the types that coverage selects with. + fn specialized(&mut self, node: NodeId, caller: NodeId, solved: &SolvedTypes<'a>) { + if let Some(instance) = solved.instances.get(&node) { + let names = self.coverage.entry(caller).or_default(); + for evidence in instance.evidence { + specialized_variables(evidence, names); + } + } + } fn method( &mut self, trait_: QualifiedName<'a>, @@ -373,6 +482,7 @@ impl<'a> Analysis<'a> { caller: NodeId, solved: &SolvedTypes<'a>, ) { + self.specialized(node, caller, solved); self.method_calls.push(MethodCall { caller, trait_, @@ -652,7 +762,7 @@ mod graph_tests { instance(&b, &mut s, call, option); let d = def(&b, &mut s, "plain", &["a"], call); let m = module(&b, &[d]); - assert!(analyze(&[(&m, &s)])[&NodeId::def(definition(d).0)].is_empty()); + assert!(analyze(&[(&m, &s)]).layouts[&NodeId::def(definition(d).0)].is_empty()); } #[test] fn nil_demand_propagates_across_helpers_with_scoped_names() { @@ -681,7 +791,7 @@ mod graph_tests { ); let outer = def(&b, &mut s, "outer", &["opaque"], opaque); let m = module(&b, &[helper, caller, outer]); - let demands = analyze(&[(&m, &s)]); + let demands = analyze(&[(&m, &s)]).layouts; assert_eq!( demands[&NodeId::def(definition(helper).0)], BTreeSet::from(["element"]) @@ -707,7 +817,7 @@ mod graph_tests { ); let outer = def(&b, &mut s, "outer", &["captured"], body); let m = module(&b, &[outer]); - let demands = analyze(&[(&m, &s)]); + let demands = analyze(&[(&m, &s)]).layouts; assert_eq!( demands[&NodeId::def(definition(outer).0)], BTreeSet::from(["captured"]) @@ -737,7 +847,7 @@ mod graph_tests { ); let d = def(&b, &mut s, "plain", &["a"], call); let m = module(&b, &[d]); - assert!(analyze(&[(&m, &s)])[&NodeId::def(definition(d).0)].is_empty()); + assert!(analyze(&[(&m, &s)]).layouts[&NodeId::def(definition(d).0)].is_empty()); } #[test] @@ -762,7 +872,7 @@ mod graph_tests { })); m.impls = b.alloc_slice_copy(&[&*impl_]); assert_eq!( - analyze(&[(&m, &s)])[&NodeId::def(definition(d).0)], + analyze(&[(&m, &s)]).layouts[&NodeId::def(definition(d).0)], BTreeSet::from(["a"]) ); } diff --git a/crates/nash-codegen/src/evidence.rs b/crates/nash-codegen/src/evidence.rs index 60582d65..485f82f2 100644 --- a/crates/nash-codegen/src/evidence.rs +++ b/crates/nash-codegen/src/evidence.rs @@ -112,7 +112,7 @@ pub fn executable_identity<'a>( } ExecutableEvidence::Impl(*impl_, children) } - Evidence::Given { .. } | Evidence::Super { .. } => { + Evidence::Given { .. } | Evidence::Super { .. } | Evidence::Specialize { .. } => { return Err(Error::UnresolvedEvidence); } }) @@ -222,6 +222,29 @@ impl<'a> Grounder<'a, '_> { .ok_or(Error::NoEvidence)?; return self.one(&resolved, &Substitution::new(), &HashMap::new(), depth + 1); } + Evidence::Specialize { trait_, args } => { + // Method B: the specialization key holds these types, so each + // use selects its impl here, with the types substituted. + let types = args + .iter() + .map(|typ| self.typ(typ, subst)) + .collect::, _>>()?; + let predicate = Pred::Trait { + trait_: *trait_, + args: self.arena.alloc_slice_copy(&types), + }; + let resolved = + nash_solve::evidence::resolve(self.arena.as_bump(), self.tables, &predicate) + .map_err(|error| { + if error.reason == nash_solve::evidence::Failure::Limit { + Error::Limit + } else { + Error::Resolution(error.reason) + } + })? + .ok_or(Error::NoEvidence)?; + return self.one(&resolved, &Substitution::new(), &HashMap::new(), depth + 1); + } Evidence::Repr { trait_, typ } => Evidence::Repr { trait_: *trait_, typ: self.typ(typ, subst)?, @@ -388,7 +411,10 @@ impl<'a> Grounder<'a, '_> { } // `one` has resolved givens/projections and handled representation // superclasses directly before calling this private helper. - Evidence::Repr { .. } | Evidence::Given { .. } | Evidence::Super { .. } => { + Evidence::Repr { .. } + | Evidence::Given { .. } + | Evidence::Super { .. } + | Evidence::Specialize { .. } => { unreachable!("superclass predicate requires resolved non-representation evidence") } }; diff --git a/crates/nash-driver/tests/base_traits.rs b/crates/nash-driver/tests/base_traits.rs index c4573b20..938dd5ea 100644 --- a/crates/nash-driver/tests/base_traits.rs +++ b/crates/nash-driver/tests/base_traits.rs @@ -125,6 +125,10 @@ base_snapshot!( ); base_snapshot!(map_helpers, "fixtures/base-traits/Maps.nash"); base_snapshot!(representation_classes, "fixtures/base-traits/Classed.nash"); +base_snapshot!( + representation_coverage, + "fixtures/base-traits/Coverage.nash" +); base_snapshot!(prop_helpers, "fixtures/base-traits/PropHelpers.nash"); base_snapshot!(cardano_value, "fixtures/base-traits/CardanoValue.nash"); diff --git a/crates/nash-driver/tests/fixtures/base-traits/Coverage.nash b/crates/nash-driver/tests/fixtures/base-traits/Coverage.nash new file mode 100644 index 00000000..22506097 --- /dev/null +++ b/crates/nash-driver/tests/fixtures/base-traits/Coverage.nash @@ -0,0 +1,71 @@ +module Main exposing (..) + +trait Kind 'a where + kind : 'a -> string + +impl Kind ('a : Storable) where + kind _ = "storable" + +type box 'a = Box 'a + +impl Kind (box ('a : Big)) where + kind _ = "big box" + +impl Kind 'a => Kind (box ('a : Little)) where + kind _ = "little box" + +trait Kind 'a => Child 'a where + child : 'a -> string + +impl Kind (box 'a) => Child (box 'a) where + child x = kind x + +viaBox : Kind 'a => 'a -> string +viaBox x = kind (Box x) + +fromSuper : Child 't => 't -> string +fromSuper x = kind x + +viaElement : Kind 'a => 'a -> string +viaElement x = fromSuper (Box x) + +viaCaller : Kind 'a => 'a -> string +viaCaller x = viaBox x + +same : Eq 'a => list 'a -> list 'a -> bool +same xs ys = xs == ys + +bigValue : Int +bigValue = 42 +littleValue : int +littleValue = 42 + +tests + test "a split impl is selected for each use, big element first" = do + assert (viaBox bigValue == "big box") + assert (viaBox littleValue == "little box") + + test "a split impl is selected for each use, little element first" = do + assert (viaBox littleValue == "little box") + assert (viaBox bigValue == "big box") + + test "a superclass of a delayed context, big element first" = do + assert (viaElement bigValue == "big box") + assert (viaElement littleValue == "little box") + + test "a superclass of a delayed context, little element first" = do + assert (viaElement littleValue == "little box") + assert (viaElement bigValue == "big box") + + test "a generic caller passes the selecting type on, big element first" = do + assert (viaCaller bigValue == "big box") + assert (viaCaller littleValue == "little box") + + test "a generic caller passes the selecting type on, little element first" = do + assert (viaCaller littleValue == "little box") + assert (viaCaller bigValue == "big box") + + test "list equality under an element constraint" = do + assert (same [bigValue] [bigValue]) + assert (same [littleValue] [littleValue]) + assert (not (same [littleValue] [littleValue, littleValue])) diff --git a/crates/nash-driver/tests/snapshots/base_traits__representation_coverage.snap b/crates/nash-driver/tests/snapshots/base_traits__representation_coverage.snap new file mode 100644 index 00000000..5410ba1c --- /dev/null +++ b/crates/nash-driver/tests/snapshots/base_traits__representation_coverage.snap @@ -0,0 +1,11 @@ +--- +source: crates/nash-driver/tests/base_traits.rs +description: "module Main exposing (..)\n\ntrait Kind 'a where\n kind : 'a -> string\n\nimpl Kind ('a : Storable) where\n kind _ = \"storable\"\n\ntype box 'a = Box 'a\n\nimpl Kind (box ('a : Big)) where\n kind _ = \"big box\"\n\nimpl Kind 'a => Kind (box ('a : Little)) where\n kind _ = \"little box\"\n\ntrait Kind 'a => Child 'a where\n child : 'a -> string\n\nimpl Kind (box 'a) => Child (box 'a) where\n child x = kind x\n\nviaBox : Kind 'a => 'a -> string\nviaBox x = kind (Box x)\n\nfromSuper : Child 't => 't -> string\nfromSuper x = kind x\n\nviaElement : Kind 'a => 'a -> string\nviaElement x = fromSuper (Box x)\n\nviaCaller : Kind 'a => 'a -> string\nviaCaller x = viaBox x\n\nsame : Eq 'a => list 'a -> list 'a -> bool\nsame xs ys = xs == ys\n\nbigValue : Int\nbigValue = 42\nlittleValue : int\nlittleValue = 42\n\ntests\n test \"a split impl is selected for each use, big element first\" = do\n assert (viaBox bigValue == \"big box\")\n assert (viaBox littleValue == \"little box\")\n\n test \"a split impl is selected for each use, little element first\" = do\n assert (viaBox littleValue == \"little box\")\n assert (viaBox bigValue == \"big box\")\n\n test \"a superclass of a delayed context, big element first\" = do\n assert (viaElement bigValue == \"big box\")\n assert (viaElement littleValue == \"little box\")\n\n test \"a superclass of a delayed context, little element first\" = do\n assert (viaElement littleValue == \"little box\")\n assert (viaElement bigValue == \"big box\")\n\n test \"a generic caller passes the selecting type on, big element first\" = do\n assert (viaCaller bigValue == \"big box\")\n assert (viaCaller littleValue == \"little box\")\n\n test \"a generic caller passes the selecting type on, little element first\" = do\n assert (viaCaller littleValue == \"little box\")\n assert (viaCaller bigValue == \"big box\")\n\n test \"list equality under an element constraint\" = do\n assert (same [bigValue] [bigValue])\n assert (same [littleValue] [littleValue])\n assert (not (same [littleValue] [littleValue, littleValue]))\n" +--- +a split impl is selected for each use, big element first: Pass; traces: [] +a split impl is selected for each use, little element first: Pass; traces: [] +a superclass of a delayed context, big element first: Pass; traces: [] +a superclass of a delayed context, little element first: Pass; traces: [] +a generic caller passes the selecting type on, big element first: Pass; traces: [] +a generic caller passes the selecting type on, little element first: Pass; traces: [] +list equality under an element constraint: Pass; traces: [] diff --git a/crates/nash-solve/src/preds.rs b/crates/nash-solve/src/preds.rs index bdc70380..0981aa10 100644 --- a/crates/nash-solve/src/preds.rs +++ b/crates/nash-solve/src/preds.rs @@ -186,6 +186,12 @@ pub enum Solution<'a> { index: usize, path: Vec, }, + /// Representation coverage: every admitted representation of the rigid + /// subjects selects an impl. `subs` are the impl contexts proved for each + /// cell; code generation selects the impl again for each use. + Specialize { + subs: Vec, + }, } #[derive(Default)] diff --git a/crates/nash-solve/src/resolve.rs b/crates/nash-solve/src/resolve.rs index 98afeebb..735f2d03 100644 --- a/crates/nash-solve/src/resolve.rs +++ b/crates/nash-solve/src/resolve.rs @@ -192,7 +192,52 @@ struct ClassedTypes<'u, 'a> { tables: &'u Tables<'a>, givens: &'u [crate::preds::Body<'a>], allocated: &'u mut Vec, + /// The representation cell that coverage is selecting for. + assumptions: Vec<(Variable, nash_ast::primitives::Repr)>, } + +impl<'u, 'a> ClassedTypes<'u, 'a> { + fn new( + uf: &'u mut UnionFind<'a>, + tables: &'u Tables<'a>, + givens: &'u [crate::preds::Body<'a>], + allocated: &'u mut Vec, + ) -> Self { + ClassedTypes { + types: InferenceTypes(uf), + tables, + givens, + allocated, + assumptions: Vec::new(), + } + } + + /// The representations that the representation givens and the current + /// coverage cell admit for a normalized subject. + fn admitted(&mut self, subject: Variable) -> nash_ast::primitives::ReprSet { + use nash_ast::primitives::{ReprSet, ReprTrait}; + let uf = &mut *self.types.0; + let mut proven = ReprSet::ALL; + for given in self.givens { + if let crate::preds::Body::Trait { trait_, args, .. } = given + && let Some(required) = ReprTrait::of(*trait_) + { + let arg = + crate::representation::subject(uf, &self.tables.kinds, args[0], self.allocated); + if crate::preds::same_args(uf, &[arg], &[subject]) { + proven = proven.intersect(required.admits()); + } + } + } + for (other, repr) in &self.assumptions { + if crate::preds::same_args(uf, &[*other], &[subject]) { + proven = proven.intersect(ReprSet::only(*repr)); + } + } + proven + } +} + impl<'a> nash_ast::head::Types<'a> for ClassedTypes<'_, 'a> { type Node = Variable; fn constructor( @@ -215,10 +260,7 @@ impl<'a> nash_ast::head::Types<'a> for ClassedTypes<'_, 'a> { node: Variable, class: nash_ast::primitives::ReprSet, ) -> nash_ast::head::Match<()> { - use nash_ast::{ - head::Match, - primitives::{ReprSet, ReprTrait}, - }; + use nash_ast::head::Match; let uf = &mut *self.types.0; let subject = crate::representation::subject(uf, &self.tables.kinds, node, self.allocated); if let Some(actual) = @@ -230,22 +272,11 @@ impl<'a> nash_ast::head::Types<'a> for ClassedTypes<'_, 'a> { Match::No }; } - let mut proven = ReprSet::ALL; - for given in self.givens { - if let crate::preds::Body::Trait { trait_, args, .. } = given - && let Some(required) = ReprTrait::of(*trait_) - { - let arg = - crate::representation::subject(uf, &self.tables.kinds, args[0], self.allocated); - if crate::preds::same_args(uf, &[arg], &[subject]) { - proven = proven.intersect(required.admits()); - } - } - } + let proven = self.admitted(subject); // Canonicalization rejects a contradictory context, and the solver // rejects contradictory nested contexts on entry and poisons their - // subject. An empty set would prove every class and select every - // disjoint impl. + // subject. A coverage cell only takes an admitted representation. An + // empty set would prove every class and select every disjoint impl. assert!( !proven.is_empty(), "contradictory representation givens reached impl selection" @@ -260,6 +291,48 @@ impl<'a> nash_ast::head::Types<'a> for ClassedTypes<'_, 'a> { } } +impl<'a> nash_ast::head::CoverageTypes<'a> for ClassedTypes<'_, 'a> { + type Subject = Variable; + fn coverage_subject( + &mut self, + node: Variable, + tested: nash_ast::primitives::ReprSet, + ) -> nash_ast::head::CoverageSubject { + use nash_ast::head::CoverageSubject; + let uf = &mut *self.types.0; + let subject = crate::representation::subject(uf, &self.tables.kinds, node, self.allocated); + if crate::representation::known(uf, &self.tables.kinds, subject, self.allocated).is_some() { + return CoverageSubject::Decided; + } + match self.types.view(subject).0 { + View::Rigid(root) => { + let admitted = self.admitted(subject); + let both = admitted.intersect(tested); + if both == admitted || both.is_empty() { + CoverageSubject::Decided + } else { + CoverageSubject::Rigid { + subject: root, + admitted, + } + } + } + View::Flexible | View::Application | View::Error => CoverageSubject::Deferred, + _ => CoverageSubject::Decided, + } + } + fn given_at(&mut self, trait_: QualifiedName<'a>, subject: Variable) -> bool { + let uf = &mut *self.types.0; + self.givens.iter().any(|given| { + matches!(given, crate::preds::Body::Trait { trait_: name, args, .. } + if *name == trait_ && args.iter().any(|arg| uf.find(*arg) == subject)) + }) + } + fn set_coverage_assumptions(&mut self, assumptions: &[(Variable, nash_ast::primitives::Repr)]) { + self.assumptions = assumptions.to_vec(); + } +} + pub(crate) fn in_class<'a>( tables: &Tables<'a>, uf: &mut UnionFind<'a>, @@ -269,13 +342,7 @@ pub(crate) fn in_class<'a>( allocated: &mut Vec, ) -> nash_ast::head::Match<()> { use nash_ast::head::Types; - ClassedTypes { - types: InferenceTypes(uf), - tables, - givens, - allocated, - } - .in_class(node, class) + ClassedTypes::new(uf, tables, givens, allocated).in_class(node, class) } pub(crate) fn select<'a>( @@ -296,12 +363,7 @@ pub(crate) fn select<'a>( Some(_) => {} } } - let mut types = ClassedTypes { - types: InferenceTypes(uf), - tables, - givens, - allocated, - }; + let mut types = ClassedTypes::new(uf, tables, givens, allocated); let unknown_outer = args.iter().any(|arg| { matches!( types.types.view(*arg).0, @@ -333,6 +395,65 @@ pub(crate) fn select<'a>( } } +pub(crate) enum Coverage<'a> { + NotApplicable, + Limit, + /// No given holds the wanted trait at this rigid subject. + Unstated(Variable), + /// A representation cell selects no impl. + Uncovered, + Complete(Vec>), +} + +pub(crate) struct CoveredImpl<'a> { + pub info: &'a ImplInfo<'a>, + pub substitution: Vec<(&'a str, Variable)>, + pub assumptions: Vec<(Variable, nash_ast::primitives::Repr)>, +} + +/// Select an impl for every admitted representation of the rigid variables +/// that keep `select` from deciding (inference only). The cells are not +/// committed to inference: each covered impl's context is proved under its +/// cell by the caller, and code generation selects again for each use. +pub(crate) fn coverage<'a>( + tables: &Tables<'a>, + uf: &mut UnionFind<'a>, + trait_: QualifiedName<'a>, + args: &[Variable], + givens: &[crate::preds::Body<'a>], + allocated: &mut Vec, + remaining: &mut usize, +) -> Coverage<'a> { + use nash_ast::head::Coverage as Cells; + let candidates: Vec<_> = tables + .impls_for(trait_) + .map(|(key, info)| (key.heads, info.variables.len(), *info)) + .collect(); + let mut types = ClassedTypes::new(uf, tables, givens, allocated); + match nash_ast::head::cover_impls(&mut types, trait_, &candidates, args, remaining) { + Err(_) => Coverage::Limit, + Ok(Cells::NotApplicable) => Coverage::NotApplicable, + Ok(Cells::Unstated(subject)) => Coverage::Unstated(subject), + Ok(Cells::Missing(_)) => Coverage::Uncovered, + Ok(Cells::Complete(covered)) => Coverage::Complete( + covered + .into_iter() + .map(|covered| CoveredImpl { + info: covered.info, + substitution: covered + .info + .variables + .iter() + .copied() + .zip(covered.arguments) + .collect(), + assumptions: covered.assumptions, + }) + .collect(), + ), + } +} + /// Probe equalities without changing the inference graph. A candidate may relate /// existing variables, but cannot manufacture a missing constructor application. struct Probe<'u, 'a> { @@ -505,12 +626,7 @@ fn given_candidates<'a>( seen.push(given); let mut probe = Probe { nominal: false, - types: ClassedTypes { - types: InferenceTypes(uf), - tables, - givens, - allocated, - }, + types: ClassedTypes::new(uf, tables, givens, allocated), substitutions: Default::default(), equations: Vec::new(), classes: Vec::new(), @@ -562,12 +678,7 @@ pub(crate) fn improvement<'a>( for (key, info) in tables.impls_for(trait_) { let mut probe = Probe { nominal: false, - types: ClassedTypes { - types: InferenceTypes(uf), - tables, - givens, - allocated, - }, + types: ClassedTypes::new(uf, tables, givens, allocated), substitutions: Default::default(), equations: Vec::new(), classes: Vec::new(), @@ -596,12 +707,7 @@ pub(crate) fn improvement<'a>( { let mut probe = Probe { nominal: true, - types: ClassedTypes { - types: InferenceTypes(uf), - tables, - givens, - allocated, - }, + types: ClassedTypes::new(uf, tables, givens, allocated), substitutions: Default::default(), equations: Vec::new(), classes: Vec::new(), diff --git a/crates/nash-solve/src/solve.rs b/crates/nash-solve/src/solve.rs index 17166eac..4f8678ae 100644 --- a/crates/nash-solve/src/solve.rs +++ b/crates/nash-solve/src/solve.rs @@ -152,6 +152,16 @@ fn representation_requirement<'a>( Some((args[0], required)) } +/// Why representation coverage could not prove a wanted predicate. +enum CoverageProblem<'a> { + Limit, + /// Some cell cannot prove this predicate: a context of a covered impl, + /// or, at the limit, the wanted trait at a rigid subject. + MissingContext(Body<'a>), + /// Some representation cell selects no impl. + Uncovered, +} + #[derive(Clone, Copy)] struct DeferredField<'a> { test_scope: bool, @@ -1383,11 +1393,15 @@ impl<'a> Solver<'a, '_> { continue; } match &self.predicates.get(id).solution { - Some(Solution::Impl { subs, .. }) => pending.extend( - subs.iter() - .filter(|id| self.predicates.get(**id).body.trait_ref().is_some()) - .map(|id| (*id, true)), - ), + Some(Solution::Impl { subs, .. } | Solution::Specialize { subs }) => { + pending.extend( + subs.iter() + .filter(|id| { + self.predicates.get(**id).body.trait_ref().is_some() + }) + .map(|id| (*id, true)), + ) + } Some( Solution::Given { binder, index } | Solution::Super { binder, index, .. }, @@ -1476,7 +1490,8 @@ impl<'a> Solver<'a, '_> { match &pred.solution { Some( crate::preds::Solution::Impl { subs, .. } - | crate::preds::Solution::Apply { subs }, + | crate::preds::Solution::Apply { subs } + | crate::preds::Solution::Specialize { subs }, ) => pending.extend(subs), Some(_) => {} None if self.predicate_stranded(uf, id) => {} @@ -1626,6 +1641,10 @@ impl<'a> Solver<'a, '_> { | crate::preds::Solution::Repr { typ, .. }, ) => roots.push(*typ), Some(crate::preds::Solution::Apply { subs }) => pending.extend(subs), + // Code generation selects again from these types. + Some(crate::preds::Solution::Specialize { .. }) => { + roots.extend(self.predicates.get(id).body.roots()) + } _ => {} } } @@ -1804,6 +1823,18 @@ impl<'a> Solver<'a, '_> { ), args: self.evidence_arguments(uf, subs), }, + Solution::Specialize { .. } => { + let Body::Trait { trait_, args, .. } = &self.predicates.get(id).body else { + unreachable!("coverage proves trait predicates") + }; + Evidence::Specialize { + trait_: *trait_, + args: self.bump.alloc_slice_fill_iter( + args.iter() + .map(|var| crate::annotation::to_solved_type(self.bump, uf, *var)), + ), + } + } } } @@ -2053,27 +2084,7 @@ impl<'a> Solver<'a, '_> { continue; } let body = self.predicates.get(id).body.clone(); - let mut allocated = Vec::new(); - let solution = self.givens.iter().rev().find_map(|frame| { - frame.predicates.iter().find_map(|given| { - crate::representation::same_predicate( - uf, - &self.tables.kinds, - &given.body, - &body, - &mut allocated, - ) - .then_some((frame.binder, given.index, given.path.clone())) - }) - }); - self.introduce(uf, rank, &allocated); - if let Some((binder, index, path)) = solution { - if let Some(index) = index { - self.predicates.solve_given(uf, id, binder, index, path); - } else { - self.predicates - .solve(uf, id, Solution::Apply { subs: Vec::new() }); - } + if self.solve_from_givens(uf, rank, id, &body) { continue; } let roots: Vec<_> = body.roots().collect(); @@ -2254,6 +2265,80 @@ impl<'a> Solver<'a, '_> { continue; } } + // Representation coverage: a rigid variable at a representation- + // tested head position keeps ordinary selection from deciding. + if matches!( + selection, + crate::resolve::Selection::Deferred | crate::resolve::Selection::Missing + ) && let Some(binder) = binder + { + let mut remaining = WORK_LIMIT; + match self.cover(uf, rank, id, trait_, &args, &[], &mut remaining, 0) { + Ok(None) => {} + Ok(Some(subs)) => { + self.predicates.solve(uf, id, Solution::Specialize { subs }); + continue; + } + Err(problem) => { + let Some(site) = site else { + self.wanted.push((wanted_rank, id)); + continue; + }; + match problem { + CoverageProblem::Limit => { + state.errors.push(Error::ImplResolutionLimit { + region: site.region, + name: site.name, + trait_, + }); + self.failed_lineages.insert(self.predicates.root(id)); + } + _ if !report_missing => self.wanted.push((wanted_rank, id)), + CoverageProblem::MissingContext(Body::Trait { + trait_: missing, + args: missing_args, + .. + }) => { + let missing_args = self.bump.alloc_slice_fill_iter( + missing_args + .iter() + .map(|arg| to_error_type(self.bump, uf, *arg)), + ); + self.failed_predicates.insert(id); + state.errors.push(Error::MissingConstraint { + region: site.region, + name: site.name, + trait_: missing, + args: missing_args, + binder: binder.name(), + }); + } + CoverageProblem::MissingContext(Body::Apply { .. }) + | CoverageProblem::Uncovered => { + let args: Vec<_> = args + .iter() + .map(|arg| to_error_type(self.bump, uf, *arg)) + .collect(); + let available: Vec<_> = self + .tables + .impls_for(trait_) + .map(|(key, _)| key.heads) + .collect(); + self.failed_predicates.insert(id); + state.errors.push(Error::MissingImpl { + region: site.region, + name: site.name, + trait_, + args: self.bump.alloc_slice_copy(&args), + available: self.bump.alloc_slice_copy(&available), + because: self.requirement_chain(uf, id), + }); + } + } + continue; + } + } + } if report_missing && !matches!(selection, crate::resolve::Selection::Impl { .. }) && let Some(binder) = binder @@ -2364,6 +2449,313 @@ impl<'a> Solver<'a, '_> { state } + /// Whether the givens, with any coverage cell, prove `class` for `node`. + fn proves_class( + &mut self, + uf: &mut UnionFind<'a>, + rank: usize, + node: Variable, + class: nash_ast::primitives::ReprTrait, + givens: &[Body<'a>], + ) -> bool { + let mut allocated = Vec::new(); + let result = crate::resolve::in_class( + self.tables, + uf, + node, + class.admits(), + givens, + &mut allocated, + ); + self.introduce(uf, rank, &allocated); + matches!(result, nash_ast::head::Match::Yes(())) + } + + /// Solve `id` from a given of an active frame, nearest frame first. + fn solve_from_givens( + &mut self, + uf: &mut UnionFind<'a>, + rank: usize, + id: type_::PredId, + body: &Body<'a>, + ) -> bool { + let mut allocated = Vec::new(); + let solution = self.givens.iter().rev().find_map(|frame| { + frame.predicates.iter().find_map(|given| { + crate::representation::same_predicate( + uf, + &self.tables.kinds, + &given.body, + body, + &mut allocated, + ) + .then_some((frame.binder, given.index, given.path.clone())) + }) + }); + self.introduce(uf, rank, &allocated); + let Some((binder, index, path)) = solution else { + return false; + }; + if let Some(index) = index { + self.predicates.solve_given(uf, id, binder, index, path); + } else { + self.predicates + .solve(uf, id, crate::preds::Solution::Apply { subs: Vec::new() }); + } + true + } + + /// The givens of every active frame, then the coverage cell assumptions. + fn given_bodies(&self, assumptions: &[Body<'a>]) -> Vec> { + self.givens + .iter() + .flat_map(|frame| frame.predicates.iter().map(|given| given.body.clone())) + .chain(assumptions.iter().cloned()) + .collect() + } + + /// Prove `trait_ args` by representation coverage (inference only). + /// `Ok(None)`: coverage does not apply. `Ok(Some(subs))`: every admitted + /// cell selects an impl, and `subs` prove each impl's context under its + /// cell. The cells are never committed to inference. + #[allow(clippy::too_many_arguments)] + fn cover( + &mut self, + uf: &mut UnionFind<'a>, + rank: usize, + parent: type_::PredId, + trait_: nash_ast::QualifiedName<'a>, + args: &[Variable], + assumptions: &[Body<'a>], + remaining: &mut usize, + depth: usize, + ) -> Result>, CoverageProblem<'a>> { + if depth >= DEPTH_LIMIT { + return Err(CoverageProblem::Limit); + } + let givens = self.given_bodies(assumptions); + let mut allocated = Vec::new(); + let coverage = crate::resolve::coverage( + self.tables, + uf, + trait_, + args, + &givens, + &mut allocated, + remaining, + ); + self.introduce(uf, rank, &allocated); + let covered = match coverage { + crate::resolve::Coverage::NotApplicable => return Ok(None), + crate::resolve::Coverage::Limit => return Err(CoverageProblem::Limit), + crate::resolve::Coverage::Unstated(subject) => { + return Err(CoverageProblem::MissingContext(Body::Trait { + trait_, + args: if args.len() == 1 { + vec![subject] + } else { + args.to_vec() + }, + hidden: false, + })); + } + crate::resolve::Coverage::Uncovered => return Err(CoverageProblem::Uncovered), + crate::resolve::Coverage::Complete(covered) => covered, + }; + let mut subs = Vec::new(); + for covered in covered { + let mut cell = assumptions.to_vec(); + cell.extend( + covered + .assumptions + .iter() + .map(|(subject, repr)| Body::Trait { + trait_: nash_ast::primitives::ReprTrait::exactly(*repr).qualified(), + args: vec![*subject], + hidden: true, + }), + ); + let vars: BTreeMap<_, _> = covered.substitution.into_iter().collect(); + for (index, context) in covered.info.context.iter().enumerate() { + let body = self.canonical_predicate(uf, rank, &vars, *context); + let sub = self.predicates.push( + uf, + Predicate { + body: body.clone(), + origin: Origin::Sub { parent, index }, + solution: None, + }, + ); + if let Err(problem) = self.prove(uf, rank, sub, &cell, remaining, depth + 1) { + self.predicates.detach(uf, sub); + return Err(match problem { + CoverageProblem::Limit => CoverageProblem::Limit, + _ => CoverageProblem::MissingContext(body), + }); + } + subs.push(sub); + } + } + Ok(Some(subs)) + } + + /// Prove one predicate of a coverage cell now, without deferral: from a + /// given, a representation, a selected impl, or coverage again. + fn prove( + &mut self, + uf: &mut UnionFind<'a>, + rank: usize, + id: type_::PredId, + assumptions: &[Body<'a>], + remaining: &mut usize, + depth: usize, + ) -> Result<(), CoverageProblem<'a>> { + use crate::preds::Solution; + use nash_ast::primitives::{Repr, ReprTrait}; + nash_ast::head::step(remaining).map_err(|_| CoverageProblem::Limit)?; + if depth >= DEPTH_LIMIT { + return Err(CoverageProblem::Limit); + } + let body = self.predicates.get(id).body.clone(); + if self.solve_from_givens(uf, rank, id, &body) { + return Ok(()); + } + let givens = self.given_bodies(assumptions); + let (trait_, args) = match body { + Body::Apply { head, args } => { + let children = self + .application_context(uf, rank, head, &args) + .ok_or(CoverageProblem::Uncovered)?; + let mut subs = Vec::new(); + for (index, child) in children.into_iter().enumerate() { + let sub = self.predicates.push( + uf, + Predicate { + body: child, + origin: Origin::Sub { parent: id, index }, + solution: None, + }, + ); + if let Err(problem) = + self.prove(uf, rank, sub, assumptions, remaining, depth + 1) + { + self.predicates.detach(uf, sub); + return Err(problem); + } + subs.push(sub); + } + self.predicates.solve(uf, id, Solution::Apply { subs }); + return Ok(()); + } + Body::Trait { trait_, args, .. } => (trait_, args), + }; + if let Some(required) = ReprTrait::of(trait_) { + let proven = match self.representation(uf, rank, args[0]) { + Some(actual) => required.admits().contains(actual), + None => self.proves_class(uf, rank, args[0], required, &givens), + }; + if !proven { + return Err(CoverageProblem::Uncovered); + } + self.predicates.solve( + uf, + id, + Solution::Repr { + trait_: required, + typ: args[0], + }, + ); + return Ok(()); + } + if trait_ == nash_ast::primitives::lift_trait() + && self.tables.has_reflexive_lift() + && args.len() == 2 + && crate::preds::same_args(uf, &args[..1], &args[1..]) + { + self.predicates + .solve(uf, id, Solution::ReflexiveLift { typ: args[0] }); + return Ok(()); + } + if trait_ == nash_ast::primitives::eq_trait() + && self.tables.has_structural_eq() + && args.len() == 1 + && (self.representation(uf, rank, args[0]) == Some(Repr::Big) + || self.proves_class(uf, rank, args[0], ReprTrait::Big, &givens)) + { + self.predicates + .solve(uf, id, Solution::StructuralEq { typ: args[0] }); + return Ok(()); + } + if occurs::reaches_cycle(uf, &args) { + return Err(CoverageProblem::Uncovered); + } + let mut allocated = Vec::new(); + let selection = + crate::resolve::select(self.tables, uf, trait_, &args, &givens, &mut allocated); + self.introduce(uf, rank, &allocated); + match selection { + crate::resolve::Selection::Impl { + info, + key, + substitution, + } => { + let type_vars = substitution.iter().map(|(_, var)| *var).collect(); + let vars: BTreeMap<_, _> = substitution.into_iter().collect(); + let mut subs = Vec::new(); + for (index, context) in info.context.iter().enumerate() { + let body = self.canonical_predicate(uf, rank, &vars, *context); + let sub = self.predicates.push( + uf, + Predicate { + body, + origin: Origin::Sub { parent: id, index }, + solution: None, + }, + ); + if let Err(problem) = + self.prove(uf, rank, sub, assumptions, remaining, depth + 1) + { + self.predicates.detach(uf, sub); + return Err(problem); + } + subs.push(sub); + } + self.predicates.solve( + uf, + id, + Solution::Impl { + impl_: nash_ast::ImplRef { + home: info.home, + key, + }, + type_vars, + subs, + }, + ); + Ok(()) + } + crate::resolve::Selection::Limit => Err(CoverageProblem::Limit), + crate::resolve::Selection::Deferred | crate::resolve::Selection::Missing => { + match self.cover( + uf, + rank, + id, + trait_, + &args, + assumptions, + remaining, + depth + 1, + )? { + Some(subs) => { + self.predicates.solve(uf, id, Solution::Specialize { subs }); + Ok(()) + } + None => Err(CoverageProblem::Uncovered), + } + } + } + } + fn formed_at( &mut self, uf: &mut UnionFind<'a>, @@ -3942,6 +4334,14 @@ mod copy_tests { } Evidence::StructuralEq { typ } => format!("StructuralEq {}", evidence_type(typ)), Evidence::ReflexiveLift { typ } => format!("ReflexiveLift {}", evidence_type(typ)), + Evidence::Specialize { trait_, args } => format!( + "Specialize {} [{}]", + evidence_name(*trait_), + args.iter() + .map(|typ| evidence_type(typ)) + .collect::>() + .join(", ") + ), Evidence::Impl { impl_, type_args, diff --git a/crates/nash-solve/tests/evidence.rs b/crates/nash-solve/tests/evidence.rs index e608ce2d..0c6a08da 100644 --- a/crates/nash-solve/tests/evidence.rs +++ b/crates/nash-solve/tests/evidence.rs @@ -55,7 +55,7 @@ fn dictionaries<'a>( }), Evidence::StructuralEq { typ } => Some(Evidence::StructuralEq { typ }), Evidence::ReflexiveLift { typ } => Some(Evidence::ReflexiveLift { typ }), - Evidence::Given { .. } | Evidence::Super { .. } => { + Evidence::Given { .. } | Evidence::Super { .. } | Evidence::Specialize { .. } => { panic!("ground evidence must be closed") } }) diff --git a/crates/nash-solve/tests/inference.rs b/crates/nash-solve/tests/inference.rs index a9baf3cc..8d3a0e82 100644 --- a/crates/nash-solve/tests/inference.rs +++ b/crates/nash-solve/tests/inference.rs @@ -5534,6 +5534,201 @@ fn representation_class_requires_a_given_for_rigid_types() { ); } +// REPRESENTATION COVERAGE + +/// `Probe (list 'a)` has one impl for each representation class of `'a`. +/// With `Probe 'a` given, every class of the rigid `'a` selects an impl. +#[test] +fn coverage_selects_split_impls_for_a_rigid_element() { + assert_inference_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Little) + trait Probe 'a where + probe : 'a -> () + impl Probe (list ('a : Big)) where + probe _ = () + impl Probe 'a => Probe (list ('a : Little)) where + probe _ = () + check : Probe 'a => list 'a -> () + check xs = probe xs + "# + ); +} + +/// The limit is checked first: a signature never hides the trait at an +/// element that selects the impl. +#[test] +fn coverage_requires_the_trait_at_the_element() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Little) + trait Probe 'a where + probe : 'a -> () + impl Probe (list ('a : Big)) where + probe _ = () + impl Probe 'a => Probe (list ('a : Little)) where + probe _ = () + check : list 'a -> () + check xs = probe xs + "# + ); +} + +#[test] +fn coverage_names_the_element_without_a_given() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Little) + trait Probe 'a where + probe : 'a -> () + impl Probe (map ('k : Big) ('v : Big)) where + probe _ = () + impl ( Probe 'k, Probe 'v ) => Probe (map ('k : Little) 'v) where + probe _ = () + impl Probe 'v => Probe (map ('k : Big) ('v : Little)) where + probe _ = () + check : Probe 'k => map 'k 'v -> () + check m = probe m + "# + ); +} + +/// The Big impl needs `Wrap 'a`, which only the Big blanket provides: the +/// branch context is proved under the representation of its cell. +#[test] +fn coverage_proves_a_branch_context_under_its_representation() { + assert_inference_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Little) + trait Wrap 'a where + wrap : 'a -> () + impl Wrap ('a : Big) where + wrap _ = () + trait Probe 'a where + probe : 'a -> () + impl Wrap 'a => Probe (list ('a : Big)) where + probe _ = () + impl Probe 'a => Probe (list ('a : Little)) where + probe _ = () + check : Probe 'a => list 'a -> () + check xs = probe xs + "# + ); +} + +#[test] +fn coverage_reports_a_missing_branch_context() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Little) + trait Label 'a where + label : 'a -> () + trait Probe 'a where + probe : 'a -> () + impl Probe (list ('a : Big)) where + probe _ = () + impl ( Probe 'a, Label 'a ) => Probe (list ('a : Little)) where + probe _ = () + check : Probe 'a => list 'a -> () + check xs = probe xs + "# + ); +} + +/// No impl covers a Term element, so coverage cannot replace selection. +#[test] +fn coverage_reports_the_uncovered_representation() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Const) + type box 'a = Box 'a + trait Probe 'a where + probe : 'a -> () + impl Probe (box ('a : Big)) where + probe _ = () + impl Probe 'a => Probe (box ('a : Const)) where + probe _ = () + check : Probe 'a => box 'a -> () + check x = probe x + "# + ); +} + +/// Six subjects give 729 cells, more than one work budget can select. +#[test] +fn coverage_search_stops_at_the_work_limit() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Little) + type six 'a 'b 'c 'd 'e 'f = Six 'a 'b 'c 'd 'e 'f + trait Kind 'a where + kind : 'a -> () + impl Kind (six ('a : Big) 'b 'c 'd 'e 'f) where + kind _ = () + impl Kind (six ('a : Little) ('b : Big) 'c 'd 'e 'f) where + kind _ = () + impl Kind (six ('a : Little) ('b : Little) ('c : Big) 'd 'e 'f) where + kind _ = () + impl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Big) 'e 'f) where + kind _ = () + impl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Little) ('e : Big) 'f) where + kind _ = () + impl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Little) ('e : Little) ('f : Big)) where + kind _ = () + impl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Little) ('e : Little) ('f : Little)) where + kind _ = () + check : ( Kind 'a, Kind 'b, Kind 'c, Kind 'd, Kind 'e, Kind 'f ) => six 'a 'b 'c 'd 'e 'f -> () + check x = kind x + "# + ); +} + +/// Coverage applies to rigid variables only: an unannotated definition keeps +/// the constraint on the container in its inferred context. +#[test] +fn coverage_keeps_the_inferred_context_of_an_unannotated_definition() { + assert_inference_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Little) + trait Probe 'a where + probe : 'a -> () + impl Probe (list ('a : Big)) where + probe _ = () + impl Probe 'a => Probe (list ('a : Little)) where + probe _ = () + check x = probe [ x ] + "# + ); +} + +/// A covered recursive call wraps the caller's own given in an impl at each +/// level, so code generation would need one copy for every depth. +#[test] +fn coverage_counts_as_growing_evidence() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Little, Storable) + trait Probe 'a where + probe : 'a -> () + impl Probe (list ('a : Big)) where + probe _ = () + impl Probe 'a => Probe (list ('a : Little)) where + probe _ = () + nest : ( Probe 'a, Storable 'a ) => 'a -> () + nest x = nest [ x ] + "# + ); +} + #[test] fn relational_constraints_infer_hidden_components() { assert_inference_snapshot!( diff --git a/crates/nash-solve/tests/snapshots/inference__coverage_counts_as_growing_evidence.snap b/crates/nash-solve/tests/snapshots/inference__coverage_counts_as_growing_evidence.snap new file mode 100644 index 00000000..2d596ec4 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__coverage_counts_as_growing_evidence.snap @@ -0,0 +1,16 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (Big, Little, Storable)\ntrait Probe 'a where\n probe : 'a -> ()\nimpl Probe (list ('a : Big)) where\n probe _ = ()\nimpl Probe 'a => Probe (list ('a : Little)) where\n probe _ = ()\nnest : ( Probe 'a, Storable 'a ) => 'a -> ()\nnest x = nest [ x ]\n" +info: diagnostic +--- +nash::type::polymorphic_recursion + + × Recursive call to `nest` grows its trait requirement. + ╭─[Main.nash:10:10] + 9 │ nest : ( Probe 'a, Storable 'a ) => 'a -> () + 10 │ nest x = nest [ x ] + · ──── + ╰──── + help: Probe (list 'a) + + Keep trait arguments stable across recursive calls, or split the recursion. diff --git a/crates/nash-solve/tests/snapshots/inference__coverage_keeps_the_inferred_context_of_an_unannotated_definition.snap b/crates/nash-solve/tests/snapshots/inference__coverage_keeps_the_inferred_context_of_an_unannotated_definition.snap new file mode 100644 index 00000000..24b2e7ab --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__coverage_keeps_the_inferred_context_of_an_unannotated_definition.snap @@ -0,0 +1,5 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "Code:\n\nmodule Main exposing (..)\nimport Primitive exposing (Big, Little)\ntrait Probe 'a where\n probe : 'a -> ()\nimpl Probe (list ('a : Big)) where\n probe _ = ()\nimpl Probe 'a => Probe (list ('a : Little)) where\n probe _ = ()\ncheck x = probe [ x ]\n" +--- +check : forall a. (Probe (list a), Storable a) => a -> unit diff --git a/crates/nash-solve/tests/snapshots/inference__coverage_names_the_element_without_a_given.snap b/crates/nash-solve/tests/snapshots/inference__coverage_names_the_element_without_a_given.snap new file mode 100644 index 00000000..286f3106 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__coverage_names_the_element_without_a_given.snap @@ -0,0 +1,16 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (Big, Little)\ntrait Probe 'a where\n probe : 'a -> ()\nimpl Probe (map ('k : Big) ('v : Big)) where\n probe _ = ()\nimpl ( Probe 'k, Probe 'v ) => Probe (map ('k : Little) 'v) where\n probe _ = ()\nimpl Probe 'v => Probe (map ('k : Big) ('v : Little)) where\n probe _ = ()\ncheck : Probe 'k => map 'k 'v -> ()\ncheck m = probe m\n" +info: diagnostic +--- +nash::type::missing_constraint + + × `probe` requires undeclared constraint `Probe 'v`. + ╭─[Main.nash:12:11] + 11 │ check : Probe 'k => map 'k 'v -> () + 12 │ check m = probe m + · ──┬── ──┬── + · │ ╰── constraint required here + · ╰── annotation for `check` + ╰──── + help: Add `Probe 'v` to the annotation for `check`. diff --git a/crates/nash-solve/tests/snapshots/inference__coverage_proves_a_branch_context_under_its_representation.snap b/crates/nash-solve/tests/snapshots/inference__coverage_proves_a_branch_context_under_its_representation.snap new file mode 100644 index 00000000..16e4fb09 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__coverage_proves_a_branch_context_under_its_representation.snap @@ -0,0 +1,5 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "Code:\n\nmodule Main exposing (..)\nimport Primitive exposing (Big, Little)\ntrait Wrap 'a where\n wrap : 'a -> ()\nimpl Wrap ('a : Big) where\n wrap _ = ()\ntrait Probe 'a where\n probe : 'a -> ()\nimpl Wrap 'a => Probe (list ('a : Big)) where\n probe _ = ()\nimpl Probe 'a => Probe (list ('a : Little)) where\n probe _ = ()\ncheck : Probe 'a => list 'a -> ()\ncheck xs = probe xs\n" +--- +check : forall a. (Probe a, Storable a) => list a -> unit diff --git a/crates/nash-solve/tests/snapshots/inference__coverage_reports_a_missing_branch_context.snap b/crates/nash-solve/tests/snapshots/inference__coverage_reports_a_missing_branch_context.snap new file mode 100644 index 00000000..af84ee57 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__coverage_reports_a_missing_branch_context.snap @@ -0,0 +1,16 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (Big, Little)\ntrait Label 'a where\n label : 'a -> ()\ntrait Probe 'a where\n probe : 'a -> ()\nimpl Probe (list ('a : Big)) where\n probe _ = ()\nimpl ( Probe 'a, Label 'a ) => Probe (list ('a : Little)) where\n probe _ = ()\ncheck : Probe 'a => list 'a -> ()\ncheck xs = probe xs\n" +info: diagnostic +--- +nash::type::missing_constraint + + × `probe` requires undeclared constraint `Label 'a`. + ╭─[Main.nash:12:12] + 11 │ check : Probe 'a => list 'a -> () + 12 │ check xs = probe xs + · ──┬── ──┬── + · │ ╰── constraint required here + · ╰── annotation for `check` + ╰──── + help: Add `Label 'a` to the annotation for `check`. diff --git a/crates/nash-solve/tests/snapshots/inference__coverage_reports_the_uncovered_representation.snap b/crates/nash-solve/tests/snapshots/inference__coverage_reports_the_uncovered_representation.snap new file mode 100644 index 00000000..bb3d7359 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__coverage_reports_the_uncovered_representation.snap @@ -0,0 +1,20 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (Big, Const)\ntype box 'a = Box 'a\ntrait Probe 'a where\n probe : 'a -> ()\nimpl Probe (box ('a : Big)) where\n probe _ = ()\nimpl Probe 'a => Probe (box ('a : Const)) where\n probe _ = ()\ncheck : Probe 'a => box 'a -> ()\ncheck x = probe x\n" +info: diagnostic +--- +nash::type::missing_impl + + × No impl for `Probe (box 'a)`. + ╭─[Main.nash:11:11] + 10 │ check : Probe 'a => box 'a -> () + 11 │ check x = probe x + · ──┬── + · ╰── required by `probe` + ╰──── + help: Available impl heads: + + (box ('a0 : Big)) + (box ('a0 : Const)) + + Import or define an impl for `Probe (box 'a)`. diff --git a/crates/nash-solve/tests/snapshots/inference__coverage_requires_the_trait_at_the_element.snap b/crates/nash-solve/tests/snapshots/inference__coverage_requires_the_trait_at_the_element.snap new file mode 100644 index 00000000..35b9140c --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__coverage_requires_the_trait_at_the_element.snap @@ -0,0 +1,16 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (Big, Little)\ntrait Probe 'a where\n probe : 'a -> ()\nimpl Probe (list ('a : Big)) where\n probe _ = ()\nimpl Probe 'a => Probe (list ('a : Little)) where\n probe _ = ()\ncheck : list 'a -> ()\ncheck xs = probe xs\n" +info: diagnostic +--- +nash::type::missing_constraint + + × `probe` requires undeclared constraint `Probe 'a`. + ╭─[Main.nash:10:12] + 9 │ check : list 'a -> () + 10 │ check xs = probe xs + · ──┬── ──┬── + · │ ╰── constraint required here + · ╰── annotation for `check` + ╰──── + help: Add `Probe 'a` to the annotation for `check`. diff --git a/crates/nash-solve/tests/snapshots/inference__coverage_search_stops_at_the_work_limit.snap b/crates/nash-solve/tests/snapshots/inference__coverage_search_stops_at_the_work_limit.snap new file mode 100644 index 00000000..42cae8e0 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__coverage_search_stops_at_the_work_limit.snap @@ -0,0 +1,16 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (Big, Little)\ntype six 'a 'b 'c 'd 'e 'f = Six 'a 'b 'c 'd 'e 'f\ntrait Kind 'a where\n kind : 'a -> ()\nimpl Kind (six ('a : Big) 'b 'c 'd 'e 'f) where\n kind _ = ()\nimpl Kind (six ('a : Little) ('b : Big) 'c 'd 'e 'f) where\n kind _ = ()\nimpl Kind (six ('a : Little) ('b : Little) ('c : Big) 'd 'e 'f) where\n kind _ = ()\nimpl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Big) 'e 'f) where\n kind _ = ()\nimpl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Little) ('e : Big) 'f) where\n kind _ = ()\nimpl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Little) ('e : Little) ('f : Big)) where\n kind _ = ()\nimpl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Little) ('e : Little) ('f : Little)) where\n kind _ = ()\ncheck : ( Kind 'a, Kind 'b, Kind 'c, Kind 'd, Kind 'e, Kind 'f ) => six 'a 'b 'c 'd 'e 'f -> ()\ncheck x = kind x\n" +info: diagnostic +--- +nash::type::impl_resolution_limit + + × Impl resolution for `Kind` in `kind` exceeded the work limit. + ╭─[Main.nash:21:11] + 20 │ check : ( Kind 'a, Kind 'b, Kind 'c, Kind 'd, Kind 'e, Kind 'f ) => six 'a 'b 'c 'd 'e 'f -> () + 21 │ check x = kind x + · ──── + ╰──── + help: This requirement remains unchecked; other reported errors still apply. + + Simplify cyclic or growing impl constraints. diff --git a/crates/nash-solve/tests/snapshots/inference__coverage_selects_split_impls_for_a_rigid_element.snap b/crates/nash-solve/tests/snapshots/inference__coverage_selects_split_impls_for_a_rigid_element.snap new file mode 100644 index 00000000..8d6d5fa4 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__coverage_selects_split_impls_for_a_rigid_element.snap @@ -0,0 +1,5 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "Code:\n\nmodule Main exposing (..)\nimport Primitive exposing (Big, Little)\ntrait Probe 'a where\n probe : 'a -> ()\nimpl Probe (list ('a : Big)) where\n probe _ = ()\nimpl Probe 'a => Probe (list ('a : Little)) where\n probe _ = ()\ncheck : Probe 'a => list 'a -> ()\ncheck xs = probe xs\n" +--- +check : forall a. (Probe a, Storable a) => list a -> unit diff --git a/docs/codegen.md b/docs/codegen.md index 6065d8e1..b7abaed6 100644 --- a/docs/codegen.md +++ b/docs/codegen.md @@ -201,6 +201,16 @@ The worklist identifies a specialization by: 3. The runtime layout descriptors demanded by that body and its callees. Complete source type arguments remain available as substitution metadata, but do not all participate in key equality or hashing. +4. The types of the variables that representation coverage selects with + (`Evidence::Specialize`, see [traits.md](traits.md) Entailment). The impl + is selected for each use from these types, so two uses with the same + given evidence, for example one `impl Kind ('a : Storable)` for a Big and a + Const element, still get separate copies when `Kind (box 'a)` selects + different impls for them. + +Coverage demand propagates like layout demand: a caller that passes such a +variable to a callee with a coverage demand holds every type variable of that +argument in its own key. Layout demand propagates through calls to a fixed point. It includes native constant construction and representation-dependent builtins. In particular an diff --git a/docs/traits.md b/docs/traits.md index 6282d877..25dbf8e6 100644 --- a/docs/traits.md +++ b/docs/traits.md @@ -188,9 +188,10 @@ retains the compared type for codegen. Builtin-list Eq has disjoint implementations by element representation: Big elements compare `listData` results through structural Big Eq; Little elements use elementwise Eq with short-circuiting. This is ordinary library code, not a -compiler optimization. Generic callers with unknown element representation must -request `Eq (list 'a)` directly; `Eq 'a` alone does not select one of the two -representation-constrained impls. Known Big elements need no element Eq context; +compiler optimization. A generic caller with unknown element representation can +request `Eq 'a`: inference covers both representation-constrained impls (see +`by_coverage` under Entailment) and code generation selects one for each use. +Requesting `Eq (list 'a)` directly also works. Known Big elements need no element Eq context; known Little elements still require element Eq. Builtin pair elements are Little, so native map-shaped lists retain elementwise pair equality. Big `Map` equality is already covered by structural Big Eq. @@ -201,7 +202,8 @@ no runtime wrapper. Its ordinary library Eq implementations are disjoint: Big/Big compares `mapData` results structurally; Little keys with any values and Big keys with Little values compare entries using the selected element Eq. The alias itself requires neither Big nor Eq. A generic caller whose key/value -representations are unknown requests `Eq (map 'k 'v)` directly. Alias identity selects the map +representations are unknown requests `Eq 'k` and `Eq 'v`, which coverage turns into the +map impl of each use, or `Eq (map 'k 'v)` directly. Alias identity selects the map impl; raw pair lists still select list Eq. `unMapData` returns the alias, and Map operations retain it in native map results. `Map.toList` explicitly returns the underlying list. Entry order and duplicate entries remain significant. @@ -259,6 +261,26 @@ when it needs one that is missing. - `by_instance`: every argument of `P` has a head constructor, an impl with `P`'s key exists, and `Given ⊢ Q` for every `Q` in the impl's context instantiated at `P`'s arguments. +- `by_coverage` (inference only: wanted predicates of function and method + bodies): ordinary selection cannot decide `P = T t1 .. tn` because a rigid + variable sits at an impl-head position that tests a representation class + (a *subject* of `P`). The limit comes first: the given closure must hold a + predicate of `T` with each subject itself as an argument (for one parameter, + exactly `T 'x`), so a signature never hides the trait that selects. Then + every *cell*, one representation per subject (Big, Const or Term, as the + representation and formation givens admit), must select an impl, and the + context of each selected impl must hold in its cell. The evidence is + `Specialize P`; code generation selects the impl for each use. One work + budget (16,384 steps) pays for finding the subjects, the cells and every + selection; more is an impl-resolution-limit error. Rigid variables come only + from annotations: an unannotated definition keeps `T (list 'a)` in its + inferred context. + +Superclass proofs (declaration checking) use `by_given` and `by_instance` +only, never `by_coverage`. An impl names a split requirement in its context, +as Base does: `impl ( Ord 'a, Eq (list 'a) ) => Ord (list 'a)` is accepted, +`impl Ord 'a => Ord (list 'a)` gets a missing-superclass error. This is what +Haskell does when instance selection depends on a rigid variable. After checking givens, resolution recognizes the compiler-owned reflexive rule only for package `nash/base`, module `Lift`, trait `Lift`. Both arguments @@ -286,6 +308,7 @@ Evidence = Impl { impl_: ImplRef, type_args: [Type], args: [Evidence] } -- by_i | ReflexiveLift { typ: Type } -- compiler rule for equal Big types | Given { binder: NodeId, index: u16 } -- i-th predicate of the scheme of definition `binder` | Super { of: Evidence, index: u16 } -- i-th superclass of an evidence's trait + | Specialize { trait_: TraitName, args: [Type] } -- by_coverage; codegen selects for each use ``` `NodeId` is the identity of an AST node (its arena address), the key From 4c4e5155128aba697fcb2181ded80f0de5e03070 Mon Sep 17 00:00:00 2001 From: microproofs Date: Thu, 15 Oct 2026 00:48:08 +0700 Subject: [PATCH 17/24] fix(solve): resolve superclass evidence for open phantom types wrapper : tag 'p -> bool; wrapper t = same t t, with same : Ord 'a => 'a -> 'a -> bool, type-checked, but nash test stopped with "superclass resolution requires a ground type, found p". No use fixes the phantom 'p, so it stays open in code generation, and the superclass step of Grounder::one rejected every type variable before resolution. nash_solve::evidence::resolve now keeps open type variables. An open variable equals only itself, so impl heads bind it and reflexive Lift proves Lift 'a 'a. Resolution reports NonGround only when a decision needs the variable: impl selection (the new nash_ast::head::Open under SelectPolicy::Defer), a representation test, a reflexive Lift that the variable could decide, or a requirement that formation of a type leaves. A predicate whose open variable no decision tests, such as Keep ('a -> int) without a function impl, reports MissingImpl. In nash-codegen, the Super arm keeps only the arity check: inspect_type loses its require_ground mode, and Error::NonGround is removed. A rigid variable that would select a superclass impl is already a missing-constraint error in type checking (new solver test). Signed-off-by: microproofs --- .sampo/changesets/open-superclass-types.md | 7 ++ crates/nash-ast/src/head.rs | 84 ++++++++++--- crates/nash-codegen/src/evidence.rs | 22 ++-- crates/nash-codegen/src/evidence/tests.rs | 2 +- crates/nash-driver/tests/base_traits.rs | 4 + .../tests/fixtures/base-traits/Phantom.nash | 19 +++ ...ts__phantom_type_through_a_superclass.snap | 5 + crates/nash-solve/src/evidence.rs | 111 ++++++++++++++---- crates/nash-solve/tests/evidence.rs | 83 +++++++++++-- crates/nash-solve/tests/inference.rs | 28 +++++ ...cts_a_superclass_impl_is_a_type_error.snap | 16 +++ docs/codegen.md | 6 +- docs/traits.md | 33 ++++-- 13 files changed, 343 insertions(+), 77 deletions(-) create mode 100644 .sampo/changesets/open-superclass-types.md create mode 100644 crates/nash-driver/tests/fixtures/base-traits/Phantom.nash create mode 100644 crates/nash-driver/tests/snapshots/base_traits__phantom_type_through_a_superclass.snap create mode 100644 crates/nash-solve/tests/snapshots/inference__open_type_that_selects_a_superclass_impl_is_a_type_error.snap diff --git a/.sampo/changesets/open-superclass-types.md b/.sampo/changesets/open-superclass-types.md new file mode 100644 index 00000000..84b5b7b6 --- /dev/null +++ b/.sampo/changesets/open-superclass-types.md @@ -0,0 +1,7 @@ +--- +cargo/nash-ast: minor +cargo/nash-solve: minor +cargo/nash-codegen: minor +--- + +Resolve superclass evidence when a type variable stays open. A phantom parameter that no use fixes, as in `wrapper : tag 'p -> bool; wrapper t = same t t` with `same : Ord 'a => 'a -> 'a -> bool`, passed type checking but stopped `nash test` with "superclass resolution requires a ground type". `nash_solve::evidence::resolve` now keeps open type variables. An open variable equals only itself, and resolution reports `NonGround` only when impl selection, a representation test, or the requirements of a type need the variable. The new `nash_ast::head::Open` matches impl heads against open types. `nash_codegen::evidence::Error::NonGround` is removed. diff --git a/crates/nash-ast/src/head.rs b/crates/nash-ast/src/head.rs index f4978884..66804afa 100644 --- a/crates/nash-ast/src/head.rs +++ b/crates/nash-ast/src/head.rs @@ -31,8 +31,17 @@ pub trait Types<'a> { ) -> Result, Limit>; } +/// Canonical types whose variables are rigid: a variable equals only itself +/// and matches no constructor. pub struct Canonical<'r, 'a>(pub &'r dyn Fn(&'a Located>, ReprSet) -> Match<()>); +/// Canonical types whose variables stay open: nothing will bind them, as in +/// code generation when no use fixes a phantom parameter. An open variable +/// equals only itself. A constructor test or a comparison that only an open +/// variable could decide is undecided, so under `SelectPolicy::Defer` a +/// selection that needs an open variable is `Deferred`. +pub struct Open<'r, 'a>(pub &'r dyn Fn(&'a Located>, ReprSet) -> Match<()>); + #[derive(PartialEq, Eq)] enum CanonicalCon<'a> { Known(HeadCon<'a>), @@ -93,12 +102,7 @@ impl<'a> Types<'a> for Canonical<'_, 'a> { (self.0)(node, class) } fn constructor(&mut self, node: Self::Node, expected: HeadCon<'a>) -> Match> { - let (con, args) = canonical_view(node); - if con == CanonicalCon::Known(expected) { - Match::Yes(args) - } else { - Match::No - } + constructor_view(node, expected, false) } fn equal( &mut self, @@ -106,18 +110,68 @@ impl<'a> Types<'a> for Canonical<'_, 'a> { second: Self::Node, remaining: &mut usize, ) -> Result, Limit> { - let mut pending = vec![(first, second)]; - while let Some((first, second)) = pending.pop() { - step(remaining)?; - let (a, aa) = canonical_view(first); - let (b, ba) = canonical_view(second); - if a != b || aa.len() != ba.len() { - return Ok(Match::No); - } + equal_views(first, second, remaining, false) + } +} + +impl<'a> Types<'a> for Open<'_, 'a> { + type Node = &'a Located>; + fn in_class(&mut self, node: Self::Node, class: ReprSet) -> Match<()> { + (self.0)(node, class) + } + fn constructor(&mut self, node: Self::Node, expected: HeadCon<'a>) -> Match> { + constructor_view(node, expected, true) + } + fn equal( + &mut self, + first: Self::Node, + second: Self::Node, + remaining: &mut usize, + ) -> Result, Limit> { + equal_views(first, second, remaining, true) + } +} + +// With `open`, a type variable is undecided instead of matching nothing. +fn constructor_view<'a>( + node: &'a Located>, + expected: HeadCon<'a>, + open: bool, +) -> Match>>> { + match canonical_view(node) { + (CanonicalCon::Known(con), args) if con == expected => Match::Yes(args), + (CanonicalCon::Var(_), _) if open => Match::Deferred, + _ => Match::No, + } +} + +// With `open`, a mismatch at a type variable is undecided instead of false. +// A definite mismatch elsewhere still decides. +fn equal_views<'a>( + first: &'a Located>, + second: &'a Located>, + remaining: &mut usize, + open: bool, +) -> Result, Limit> { + let mut pending = vec![(first, second)]; + let mut deferred = false; + while let Some((first, second)) = pending.pop() { + step(remaining)?; + let (a, aa) = canonical_view(first); + let (b, ba) = canonical_view(second); + if a == b && aa.len() == ba.len() { pending.extend(aa.into_iter().zip(ba)); + } else if open && (matches!(a, CanonicalCon::Var(_)) || matches!(b, CanonicalCon::Var(_))) { + deferred = true; + } else { + return Ok(Match::No); } - Ok(Match::Yes(())) } + Ok(if deferred { + Match::Deferred + } else { + Match::Yes(()) + }) } pub fn step(remaining: &mut usize) -> Result<(), Limit> { diff --git a/crates/nash-codegen/src/evidence.rs b/crates/nash-codegen/src/evidence.rs index 485f82f2..861143c8 100644 --- a/crates/nash-codegen/src/evidence.rs +++ b/crates/nash-codegen/src/evidence.rs @@ -1,8 +1,9 @@ //! Close compile-time evidence references without introducing runtime dictionaries. //! //! Type substitution is simultaneous. Payloads may remain open when code erases -//! them; only instance superclass resolution requires a concrete predicate. Runtime layout -//! demands are a separate part of specialization identity. +//! them, as a phantom parameter does when no use fixes it. Superclass +//! resolution accepts open types; it fails only where an open type would select +//! the impl. Runtime layout demands are a separate part of specialization identity. use std::collections::HashMap; use nash_ast::head::{DEPTH_LIMIT, WORK_LIMIT}; @@ -34,8 +35,6 @@ pub enum Error<'a> { MalformedPredicate, #[error("superclass does not have an evidence slot")] NoEvidence, - #[error("superclass resolution requires a ground type, found {0}")] - NonGround(&'a str), #[error("evidence still contains a given or superclass projection")] UnresolvedEvidence, #[error("evidence normalization exceeded its work or depth limit")] @@ -314,7 +313,7 @@ impl<'a> Grounder<'a, '_> { ) -> Result<&'a Located>, Error<'a>> { // substitute_type is recursive, so bound its input and replacements // before calling it. Replacement types are not substituted again. - self.inspect_type(typ, Some(subst), false)?; + self.inspect_type(typ, subst)?; Ok(nash_can::types::substitute_type( self.arena.as_bump(), subst, @@ -325,8 +324,7 @@ impl<'a> Grounder<'a, '_> { fn inspect_type( &mut self, typ: &'a Located>, - subst: Option<&Substitution<'a>>, - require_ground: bool, + subst: &Substitution<'a>, ) -> Result<(), Error<'a>> { let mut pending = vec![(typ, 0, true)]; while let Some((typ, depth, replace)) = pending.pop() { @@ -334,11 +332,8 @@ impl<'a> Grounder<'a, '_> { let mut push = |child| pending.push((child, depth + 1, replace)); match &typ.value { Type::Var(name) => { - if let Some(value) = subst.filter(|_| replace).and_then(|subst| subst.get(name)) - { + if replace && let Some(value) = subst.get(name) { pending.push((*value, depth + 1, false)); - } else if require_ground { - return Err(Error::NonGround(name)); } } Type::App { head, args } => { @@ -493,7 +488,7 @@ impl<'a> Grounder<'a, '_> { Ok(self.arena.alloc(Located::at_zero(typ))) } - fn validate_predicate(&mut self, predicate: Pred<'a>) -> Result<(), Error<'a>> { + fn validate_predicate(&self, predicate: Pred<'a>) -> Result<(), Error<'a>> { if let Some(trait_) = predicate.trait_ref() { let arity = if primitives::ReprTrait::of(trait_).is_some() { 1 @@ -509,9 +504,6 @@ impl<'a> Grounder<'a, '_> { return Err(Error::MalformedPredicate); } } - for typ in predicate.types() { - self.inspect_type(typ, None, true)?; - } Ok(()) } } diff --git a/crates/nash-codegen/src/evidence/tests.rs b/crates/nash-codegen/src/evidence/tests.rs index 85258cda..653a7a83 100644 --- a/crates/nash-codegen/src/evidence/tests.rs +++ b/crates/nash-codegen/src/evidence/tests.rs @@ -285,7 +285,7 @@ fn malformed_slots_and_open_types_return_errors() { &Substitution::new(), &HashMap::new() ), - Err(Error::NonGround("a")) + Err(Error::Resolution(nash_solve::evidence::Failure::NonGround)) )); assert!(matches!( executable_identity(&given), diff --git a/crates/nash-driver/tests/base_traits.rs b/crates/nash-driver/tests/base_traits.rs index 938dd5ea..c3b84e11 100644 --- a/crates/nash-driver/tests/base_traits.rs +++ b/crates/nash-driver/tests/base_traits.rs @@ -129,6 +129,10 @@ base_snapshot!( representation_coverage, "fixtures/base-traits/Coverage.nash" ); +base_snapshot!( + phantom_type_through_a_superclass, + "fixtures/base-traits/Phantom.nash" +); base_snapshot!(prop_helpers, "fixtures/base-traits/PropHelpers.nash"); base_snapshot!(cardano_value, "fixtures/base-traits/CardanoValue.nash"); diff --git a/crates/nash-driver/tests/fixtures/base-traits/Phantom.nash b/crates/nash-driver/tests/fixtures/base-traits/Phantom.nash new file mode 100644 index 00000000..f695aa75 --- /dev/null +++ b/crates/nash-driver/tests/fixtures/base-traits/Phantom.nash @@ -0,0 +1,19 @@ +module Main exposing (..) + +type tag 'p = Tag + +impl Eq (tag 'p) where + eq _ _ = True + +impl Ord (tag 'p) where + compare _ _ = EQ + +same : Ord 'a => 'a -> 'a -> bool +same a b = a == b + +wrapper : tag 'p -> bool +wrapper t = same t t + +tests + test "an open phantom type reaches Eq through Ord" = do + assert (wrapper Tag) diff --git a/crates/nash-driver/tests/snapshots/base_traits__phantom_type_through_a_superclass.snap b/crates/nash-driver/tests/snapshots/base_traits__phantom_type_through_a_superclass.snap new file mode 100644 index 00000000..14da799f --- /dev/null +++ b/crates/nash-driver/tests/snapshots/base_traits__phantom_type_through_a_superclass.snap @@ -0,0 +1,5 @@ +--- +source: crates/nash-driver/tests/base_traits.rs +description: "module Main exposing (..)\n\ntype tag 'p = Tag\n\nimpl Eq (tag 'p) where\n eq _ _ = True\n\nimpl Ord (tag 'p) where\n compare _ _ = EQ\n\nsame : Ord 'a => 'a -> 'a -> bool\nsame a b = a == b\n\nwrapper : tag 'p -> bool\nwrapper t = same t t\n\ntests\n test \"an open phantom type reaches Eq through Ord\" = do\n assert (wrapper Tag)\n" +--- +an open phantom type reaches Eq through Ord: Pass; traces: [] diff --git a/crates/nash-solve/src/evidence.rs b/crates/nash-solve/src/evidence.rs index 066cce5e..65c462b8 100644 --- a/crates/nash-solve/src/evidence.rs +++ b/crates/nash-solve/src/evidence.rs @@ -1,4 +1,5 @@ -//! Impl evidence for ground canonical predicates, outside the inference loop. +//! Impl evidence for canonical predicates after inference. A type variable +//! that reaches resolution is open: nothing will bind it. use bumpalo::Bump; use nash_ast::head::{DEPTH_LIMIT, WORK_LIMIT}; use nash_ast::{Evidence, ImplRef, Pred, QualifiedName, Type}; @@ -8,6 +9,8 @@ use nash_region::Located; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Failure { MissingImpl, + /// A decision needs an open type variable: impl selection, a + /// representation test, or the requirements of a type. NonGround, Limit, } @@ -19,9 +22,10 @@ pub struct Error<'a> { } /// Resolve a well-kinded canonical predicate using the complete impl table. -/// Nominal aliases retain their identity. Open types are rejected; resolution -/// never chooses a type or kind to make an impl match. Recursive contexts and -/// structural traversal share a bounded work budget. +/// Nominal aliases retain their identity. An open type variable equals only +/// itself; resolution never chooses a type or kind to make an impl match, so +/// a decision that needs an open variable fails with `NonGround`. Recursive +/// contexts and structural traversal share a bounded work budget. pub fn resolve<'a>( bump: &'a Bump, tables: &Tables<'a>, @@ -41,10 +45,12 @@ enum Constructor<'a> { Tuple(usize), Function, Record(Vec<&'a str>), + Var(&'a str), } // A region-independent, nominal view for reflexive equality. Alias bodies and -// unsupplied bound parameters are not part of a nominal application. +// unsupplied bound parameters are not part of a nominal application. An open +// variable equals only itself. #[derive(PartialEq, Eq)] struct Term<'a> { con: Constructor<'a>, @@ -138,10 +144,10 @@ impl<'a> Resolver<'_, 'a> { fn term(&mut self, typ: &Type<'a>, depth: usize) -> Result, Failure> { self.step(depth)?; let (con, args) = match typ { - Type::Var(_) => return Err(Failure::NonGround), + Type::Var(name) => (Constructor::Var(name), Vec::new()), Type::App { head, args } => { let mut head = self.term(&head.value, depth + 1)?; - if !matches!(head.con, Constructor::Named(_)) { + if !matches!(head.con, Constructor::Named(_) | Constructor::Var(_)) { return Err(Failure::MissingImpl); } for arg in *args { @@ -254,8 +260,9 @@ impl<'a> Resolver<'_, 'a> { .typ(typ) .map_err(|_| error(Failure::MissingImpl))?; } - // Every input is ground. Formation must fully discharge its internal - // requirements before a ground evidence marker can be issued. + // Formation leaves a requirement that it cannot decide, such as a + // representation class that a type declaration demands of an open + // variable. Evidence cannot discharge it. if !formation.predicates.is_empty() { return Err(error(Failure::NonGround)); } @@ -277,6 +284,7 @@ impl<'a> Resolver<'_, 'a> { typ: args[0], })) } + None if mentions_open(&args[0].value) => Err(error(Failure::NonGround)), _ => Err(error(Failure::MissingImpl)), }; } @@ -295,38 +303,46 @@ impl<'a> Resolver<'_, 'a> { } if trait_ == nash_ast::primitives::lift_trait() && self.tables.has_reflexive_lift() - && matches!(terms.as_slice(), [first, second] if first == second) + && let [first, second] = terms.as_slice() { - return Ok(Resolution::Complete(Evidence::ReflexiveLift { - typ: args[0], - })); + match agree(first, second) { + nash_ast::head::Match::Yes(()) => { + return Ok(Resolution::Complete(Evidence::ReflexiveLift { + typ: args[0], + })); + } + nash_ast::head::Match::Deferred => return Err(error(Failure::NonGround)), + nash_ast::head::Match::No => {} + } } let candidates = self .tables .impls_for(trait_) .map(|(key, info)| (key.heads, info.variables.len(), (*key, *info))); let selection = nash_ast::head::select_impl( - &mut nash_ast::head::Canonical(&|typ, class| match nash_can::kinds::repr_of( + &mut nash_ast::head::Open(&|typ, class| match nash_can::kinds::repr_of( self.bump, &self.tables.kinds, typ, ) { Some(actual) if class.contains(actual) => nash_ast::head::Match::Yes(()), Some(_) => nash_ast::head::Match::No, - None => nash_ast::head::Match::Deferred, + None if mentions_open(&typ.value) => nash_ast::head::Match::Deferred, + None => nash_ast::head::Match::No, }), candidates, args, &mut self.remaining, - nash_ast::head::SelectPolicy::Exact, + nash_ast::head::SelectPolicy::Defer, ) .map_err(|_| error(Failure::Limit))?; - let nash_ast::head::ImplSelection::Selected { - info: (key, info), - arguments: type_args, - } = selection - else { - return Err(error(Failure::MissingImpl)); + let (key, info, type_args) = match selection { + nash_ast::head::ImplSelection::Selected { + info: (key, info), + arguments, + } => (key, info, arguments), + nash_ast::head::ImplSelection::Deferred => return Err(error(Failure::NonGround)), + nash_ast::head::ImplSelection::Missing => return Err(error(Failure::MissingImpl)), }; let substitution = info .variables @@ -356,6 +372,57 @@ impl<'a> Resolver<'_, 'a> { } } +// Reflexive Lift compares nominal terms. Terms that differ only where an open +// variable stands could become equal, so the rule cannot decide them. +fn agree(first: &Term<'_>, second: &Term<'_>) -> nash_ast::head::Match<()> { + let mut pending = vec![(first, second)]; + let mut deferred = false; + while let Some((first, second)) = pending.pop() { + if first.con == second.con && first.args.len() == second.args.len() { + pending.extend(first.args.iter().zip(&second.args)); + } else if matches!(first.con, Constructor::Var(_)) + || matches!(second.con, Constructor::Var(_)) + { + deferred = true; + } else { + return nash_ast::head::Match::No; + } + } + if deferred { + nash_ast::head::Match::Deferred + } else { + nash_ast::head::Match::Yes(()) + } +} + +fn mentions_open(typ: &Type<'_>) -> bool { + let mut pending = vec![typ]; + while let Some(typ) = pending.pop() { + match typ { + Type::Var(_) => return true, + Type::App { head, args } => { + pending.push(&head.value); + pending.extend(args.iter().map(|arg| &arg.value)); + } + Type::Named { args, .. } => pending.extend(args.iter().map(|arg| &arg.value)), + Type::Alias { arguments, .. } => { + pending.extend(arguments.iter().map(|arg| &arg.typ.value)); + } + Type::Lambda { from, to } => pending.extend([&from.value, &to.value]), + Type::Tuple { + first, + second, + rest, + } => { + pending.extend([&first.value, &second.value]); + pending.extend(rest.iter().map(|arg| &arg.value)); + } + Type::Record { fields } => pending.extend(fields.iter().map(|field| &field.typ.value)), + } + } + false +} + #[cfg(test)] mod predicate_tests { use super::*; diff --git a/crates/nash-solve/tests/evidence.rs b/crates/nash-solve/tests/evidence.rs index 0c6a08da..06d599ce 100644 --- a/crates/nash-solve/tests/evidence.rs +++ b/crates/nash-solve/tests/evidence.rs @@ -532,20 +532,29 @@ fn ground_resolution_reports_missing_open_and_expanding_requirements() { cycle x = x function : (int -> int) -> (int -> int) function x = x + openFunction : ('a -> int) -> ('a -> int) + openFunction x = x " ), ); let trait_ = *tables.traits.keys().find(|key| key.name == "Keep").unwrap(); - let results: Vec<_> = ["missing", "open", "growing", "cycle", "function"] - .into_iter() - .map(|name| { - let pred = Pred::Trait { - trait_, - args: bump.alloc_slice_copy(&[input(&annotations, name)]), - }; - (name, resolve(&bump, &tables, &pred).unwrap_err().reason) - }) - .collect(); + let results: Vec<_> = [ + "missing", + "open", + "growing", + "cycle", + "function", + "openFunction", + ] + .into_iter() + .map(|name| { + let pred = Pred::Trait { + trait_, + args: bump.alloc_slice_copy(&[input(&annotations, name)]), + }; + (name, resolve(&bump, &tables, &pred).unwrap_err().reason) + }) + .collect(); assert_eq!( results, vec![ @@ -554,6 +563,7 @@ fn ground_resolution_reports_missing_open_and_expanding_requirements() { ("growing", Failure::Limit), ("cycle", Failure::Limit), ("function", Failure::MissingImpl), + ("openFunction", Failure::MissingImpl), ] ); let mut deep = input(&annotations, "missing"); @@ -580,3 +590,56 @@ fn ground_resolution_reports_missing_open_and_expanding_requirements() { Failure::Limit ); } + +#[test] +fn open_types_resolve_when_no_decision_needs_them() { + let bump = Bump::new(); + let (tables, annotations) = fixture( + &bump, + indoc::indoc!( + " + module Lift exposing (..) + trait Lift 'small 'big where + lift : 'small -> 'big + lower : 'big -> 'small + trait Keep 'a where + keep : 'a -> 'a + type tag 'p = Tag + impl Keep (tag 'p) where + keep x = x + phantom : tag 'p -> tag 'p + phantom x = x + first : 'a -> 'a + first x = x + second : 'b -> 'b + second x = x + " + ), + ); + let keep = *tables.traits.keys().find(|key| key.name == "Keep").unwrap(); + assert!(matches!( + resolve( + &bump, + &tables, + &Pred::Trait { + trait_: keep, + args: bump.alloc_slice_copy(&[input(&annotations, "phantom")]), + } + ), + Ok(Some(Evidence::Impl { .. })) + )); + let lift = |first, second| Pred::Trait { + trait_: nash_ast::primitives::lift_trait(), + args: bump.alloc_slice_copy(&[input(&annotations, first), input(&annotations, second)]), + }; + assert!(matches!( + resolve(&bump, &tables, &lift("first", "first")), + Ok(Some(Evidence::ReflexiveLift { .. })) + )); + assert_eq!( + resolve(&bump, &tables, &lift("first", "second")) + .unwrap_err() + .reason, + Failure::NonGround + ); +} diff --git a/crates/nash-solve/tests/inference.rs b/crates/nash-solve/tests/inference.rs index 8d3a0e82..ad892191 100644 --- a/crates/nash-solve/tests/inference.rs +++ b/crates/nash-solve/tests/inference.rs @@ -5729,6 +5729,34 @@ fn coverage_counts_as_growing_evidence() { ); } +/// Code generation resolves a superclass at the types of each use, where a +/// phantom parameter can stay open. When the parameter would select the +/// superclass impl, type checking reports the missing constraint first. +#[test] +fn open_type_that_selects_a_superclass_impl_is_a_type_error() { + assert_inference_error_snapshot!( + r#" + module Main exposing (..) + import Primitive exposing (Big, Little) + type box 'a = Box 'a + trait Kind 'a where + kind : 'a -> string + impl Kind (box ('a : Big)) where + kind _ = "big box" + impl Kind 'a => Kind (box ('a : Little)) where + kind _ = "little box" + trait Kind 'a => Child 'a where + child : 'a -> string + impl Kind (box 'a) => Child (box 'a) where + child x = kind x + fromSuper : Child 't => 't -> string + fromSuper x = kind x + wrapper : box 'p -> string + wrapper b = fromSuper b + "# + ); +} + #[test] fn relational_constraints_infer_hidden_components() { assert_inference_snapshot!( diff --git a/crates/nash-solve/tests/snapshots/inference__open_type_that_selects_a_superclass_impl_is_a_type_error.snap b/crates/nash-solve/tests/snapshots/inference__open_type_that_selects_a_superclass_impl_is_a_type_error.snap new file mode 100644 index 00000000..f6b7f54c --- /dev/null +++ b/crates/nash-solve/tests/snapshots/inference__open_type_that_selects_a_superclass_impl_is_a_type_error.snap @@ -0,0 +1,16 @@ +--- +source: crates/nash-solve/tests/inference.rs +description: "module Main exposing (..)\nimport Primitive exposing (Big, Little)\ntype box 'a = Box 'a\ntrait Kind 'a where\n kind : 'a -> string\nimpl Kind (box ('a : Big)) where\n kind _ = \"big box\"\nimpl Kind 'a => Kind (box ('a : Little)) where\n kind _ = \"little box\"\ntrait Kind 'a => Child 'a where\n child : 'a -> string\nimpl Kind (box 'a) => Child (box 'a) where\n child x = kind x\nfromSuper : Child 't => 't -> string\nfromSuper x = kind x\nwrapper : box 'p -> string\nwrapper b = fromSuper b\n" +info: diagnostic +--- +nash::type::missing_constraint + + × `fromSuper` requires undeclared constraint `Kind 'p`. + ╭─[Main.nash:17:13] + 16 │ wrapper : box 'p -> string + 17 │ wrapper b = fromSuper b + · ───┬─── ────┬──── + · │ ╰── constraint required here + · ╰── annotation for `wrapper` + ╰──── + help: Add `Kind 'p` to the annotation for `wrapper`. diff --git a/docs/codegen.md b/docs/codegen.md index b7abaed6..2f372369 100644 --- a/docs/codegen.md +++ b/docs/codegen.md @@ -251,8 +251,10 @@ instantiated at `type_args` (or the trait's default method body with the impl's evidence substituted). `args` supplies the evidence for the impl's own context (`impl Eq 'a => Eq (list ('a : Little))`), and a `Super` node (`lt` using `Eq` through `Ord`'s superclass) resolves to the superclass impl through -the impl table. After this phase there are no dictionaries and no trait -names in `Core`. +the impl table. The superclass predicate can mention a type variable that no +use fixes, such as a phantom parameter. Resolution keeps that variable open +and fails only where it would select the impl. After this phase there are no +dictionaries and no trait names in `Core`. ### 3. Pattern matching diff --git a/docs/traits.md b/docs/traits.md index 25dbf8e6..0dc825a7 100644 --- a/docs/traits.md +++ b/docs/traits.md @@ -555,27 +555,34 @@ preserves polymorphic destructuring without losing qualified constraints. ### Resolving outside the solver -Power-assert ([testing.md](testing.md)) needs `Show` at whatever ground -type a subexpression has, and `@derive` ([macros.md](macros.md)) needs to -know whether a field type already has an impl. Both run after solving, on -fully ground canonical types, so the resolver is also exposed as a plain -function: +Power-assert ([testing.md](testing.md)) needs `Show` at whatever type a +subexpression has, and `@derive` ([macros.md](macros.md)) needs to know +whether a field type already has an impl. Both run after solving, so the +resolver is also exposed as a plain function. Code generation also calls it +for superclasses, method contexts, and `Specialize` evidence: ```rust pub fn resolve<'a>( bump: &'a Bump, tables: &Tables<'a>, - pred: &Pred<'a>, // args are ground `Located`s: no `Type::Var` + pred: &Pred<'a>, // a `Type::Var` in the args is open ) -> Result, nash_solve::evidence::Error<'a>> ``` It is the same `by_instance` walk without unification variables: match each argument's head constructor against the impl table, instantiate the -impl's context at the argument's type arguments, recurse. A ground -predicate never needs `Given`, so the result is a closed tree of `Impl` and -exact-core `ReflexiveLift` evidence. Reflexive Lift requires nominally equal -arguments with an already-proven Big representation; it does not choose -a representation. +impl's context at the argument's type arguments, recurse. A type variable +that reaches the resolver is open: no use fixed it, as with a phantom +parameter, and nothing will bind it. An open variable equals only itself and +binds impl head variables like any other type. A decision that needs an open +variable fails with `NonGround`: impl selection (`head::Open` under +`SelectPolicy::Defer`), a representation test, or a requirement that +formation of a type leaves. In a checked program, a rigid variable that +selects an impl needs a stated constraint, so type checking reports that case +first. The predicate never needs `Given`, so the result is a closed tree of +`Impl` and exact-core `ReflexiveLift` evidence. Reflexive Lift requires +nominally equal arguments with an already-proven Big representation; it does +not choose a representation. Failures distinguish `MissingImpl`, `NonGround`, and `Limit`, retaining the failed predicate. Resolution and type traversal share a 16,384-step work budget, with a depth limit of 256. Context substitution is charged before @@ -595,7 +602,9 @@ for the authoritative specialization identity and recursive-layout check. `Super { of, index }` after substitution is an `Impl`, and the superclass impl is found by key: the `index`-th superclass of the impl's trait, at the -impl's heads. The impl check guarantees it exists. +impl's heads. The impl check guarantees it exists. The heads can still hold +open types after substitution; resolution fails only where an open type would +select the superclass impl. ## `do` notation From b2fd17f24ff8025a9684cbbcb9f2b94db9f8a9ad Mon Sep 17 00:00:00 2001 From: microproofs Date: Thu, 15 Oct 2026 01:34:57 +0700 Subject: [PATCH 18/24] refactor(solve): remove the step 03 scan oracles Step 03 replaced linear scans with indexes for kind contracts, recovery closure, stranded lookups, scheme lookups and the per-scope grouping in finish. Debug builds kept each old scan as an ORACLE and asserted on every call that it agreed with the index, so debug runs still paid the quadratic cost. The constraint tree (05) and coverage (08) changes have landed, so the oracles go: the debug-build call sites, the scan helpers, the stranded_handles field that fed one of them, and the two randomized tests that compared the indexes with the scans (contract_index_agrees_with_the_contract_scan and historical_closure_and_stranded_lookup_agree_with_the_scans). Signed-off-by: microproofs --- crates/nash-solve/src/kind_check.rs | 97 ---------------------- crates/nash-solve/src/recovery.rs | 122 +--------------------------- crates/nash-solve/src/solve.rs | 42 +--------- 3 files changed, 3 insertions(+), 258 deletions(-) diff --git a/crates/nash-solve/src/kind_check.rs b/crates/nash-solve/src/kind_check.rs index 135859a2..dd53b4f0 100644 --- a/crates/nash-solve/src/kind_check.rs +++ b/crates/nash-solve/src/kind_check.rs @@ -86,32 +86,6 @@ impl<'c, 'a> Indexed<'c, 'a> { .flatten() .map(move |&position| (position, &self.0.all[position])) } - - /// ORACLE: the per-check scan of every contract that the index replaces. - #[cfg(any(test, debug_assertions))] - fn assert_scan_agrees(self, uf: &mut UnionFind<'a>) { - let mut scan = BTreeMap::<_, Vec<_>>::new(); - for contract in &self.0.all { - if crate::recovery::is_poisoned(uf, [contract.owner]) { - continue; - } - scan.entry(uf.find(contract.variable)) - .or_default() - .push(std::ptr::from_ref(contract.kind)); - } - let mut index = BTreeMap::<_, Vec<_>>::new(); - for &class in self.0.by_class.keys() { - let kinds: Vec<_> = self - .on(class) - .filter(|(_, contract)| !crate::recovery::is_poisoned(uf, [contract.owner])) - .map(|(_, contract)| std::ptr::from_ref(contract.kind)) - .collect(); - if !kinds.is_empty() { - index.insert(class, kinds); - } - } - assert_eq!(scan, index); - } } pub(crate) struct Failure<'a> { @@ -316,8 +290,6 @@ pub(crate) fn check<'a>( let mut errors = Vec::new(); let contracts = contracts.indexed(uf); loop { - #[cfg(debug_assertions)] - contracts.assert_scan_agrees(uf); let mut check = Check::new(bump, env, contracts); let result = (|| { for contract in &contracts.0.all { @@ -374,8 +346,6 @@ pub(crate) fn freeze<'a>( ) -> Result>, Box>> { let region = root.region; let contracts = contracts.indexed(uf); - #[cfg(debug_assertions)] - contracts.assert_scan_agrees(uf); let mut check = Check::new(bump, env, contracts); let result = (|| { check.values(uf, [root.value])?; @@ -403,70 +373,3 @@ pub(crate) fn freeze<'a>( }) }) } - -#[cfg(test)] -mod tests { - use super::*; - use crate::recovery::tests::Lcg; - use nash_constrain::type_::{make_descriptor, mk_flex_var}; - - #[test] - fn contract_index_agrees_with_the_contract_scan() { - let bump = Bump::new(); - let mut compared = 0; - for seed in 0..300 { - let mut random = Lcg(seed); - let mut uf = UnionFind::new(); - let mut contracts = Contracts::default(); - let mut variables: Vec<_> = (0..4).map(|_| mk_flex_var(&mut uf)).collect(); - for _ in 0..150 { - match random.below(7) { - 0 => variables.push(mk_flex_var(&mut uf)), - 1 => { - let children = (random.pick(&variables), random.pick(&variables)); - variables.push(uf.fresh(make_descriptor(Content::Structure( - FlatType::Fun1(children.0, children.1), - )))); - } - 2 | 3 => { - let contract = Contract { - variable: random.pick(&variables), - owner: random.pick(&variables), - // A fresh allocation gives every contract its own identity. - kind: bump.alloc(nash_ast::Kind::Type), - region: Region::zero(), - }; - contracts.push(&mut uf, contract); - } - 4 => { - let (first, second) = (random.pick(&variables), random.pick(&variables)); - let content = uf.get(first).content.clone(); - uf.union(first, second, make_descriptor(content)); - } - 5 => { - let variable = random.pick(&variables); - uf.modify(variable, |desc| desc.content = Content::Error); - } - _ => { - contracts.indexed(&uf).assert_scan_agrees(&mut uf); - let variable = random.pick(&variables); - let recorded = random.below(contracts.len() + 1); - let scan: Vec<_> = contracts.all[..recorded] - .iter() - .filter(|contract| uf.equivalent(variable, contract.variable)) - .map(|contract| std::ptr::from_ref(contract.kind)) - .collect(); - let index: Vec<_> = contracts - .on_class(&mut uf, variable, recorded) - .iter() - .map(|contract| std::ptr::from_ref(contract.kind)) - .collect(); - assert_eq!(index, scan); - compared += 1; - } - } - } - } - assert!(compared > 5_000); - } -} diff --git a/crates/nash-solve/src/recovery.rs b/crates/nash-solve/src/recovery.rs index 764df9a9..a9632178 100644 --- a/crates/nash-solve/src/recovery.rs +++ b/crates/nash-solve/src/recovery.rs @@ -20,9 +20,6 @@ pub(crate) struct Dependencies { /// a call to a failed definition. They are unknown because of that /// failure, not ambiguous. stranded: HashSet, - /// ORACLE input: stranded variables as recorded, before later merges. - #[cfg(any(test, debug_assertions))] - stranded_handles: BTreeSet, /// Number of union-find merges already applied to `parents` and `stranded`. merged: usize, } @@ -114,8 +111,6 @@ impl Dependencies { roots: impl IntoIterator, ) { let lost = self.detached(uf, roots); - #[cfg(any(test, debug_assertions))] - self.stranded_handles.extend(&lost); self.stranded.extend(lost); } @@ -126,19 +121,7 @@ impl Dependencies { uf.merges().len(), "stranded lookup after an unsynced merge" ); - let found = self.stranded.contains(&uf.find(variable)); - #[cfg(debug_assertions)] - assert_eq!(found, self.stranded_scan(uf, variable)); - found - } - - /// ORACLE: the scan of every stranded variable that the lookup replaces. - #[cfg(any(test, debug_assertions))] - fn stranded_scan(&self, uf: &mut UnionFind<'_>, variable: Variable) -> bool { - let variable = uf.find(variable); - self.stranded_handles - .iter() - .any(|stranded| uf.find(*stranded) == variable) + self.stranded.contains(&uf.find(variable)) } pub(crate) fn invalidate( @@ -171,8 +154,7 @@ impl Dependencies { roots: impl IntoIterator, ) -> BTreeSet { self.sync(uf); - let roots: Vec<_> = roots.into_iter().collect(); - let mut pending = roots.clone(); + let mut pending: Vec<_> = roots.into_iter().collect(); let mut variables = BTreeSet::new(); while let Some(variable) = pending.pop() { let variable = uf.find(variable); @@ -184,28 +166,6 @@ impl Dependencies { pending.extend(self.edges[parent].iter().copied()); } } - #[cfg(debug_assertions)] - assert_eq!(variables, self.historical_scan(uf, roots)); - variables - } - - /// ORACLE: the fixed-point scan that `historical` replaces. - #[cfg(any(test, debug_assertions))] - fn historical_scan(&self, uf: &mut UnionFind<'_>, roots: Vec) -> BTreeSet { - let mut variables = reachable(uf, roots); - loop { - let before = variables.len(); - for (parent, recorded) in &self.edges { - if variables.contains(&uf.find(*parent)) { - for child in recorded { - variables.extend(reachable(uf, [*child])); - } - } - } - if variables.len() == before { - break; - } - } variables } } @@ -274,81 +234,3 @@ pub(crate) fn poison_roots( } changed } - -#[cfg(test)] -pub(crate) mod tests { - use super::*; - use nash_constrain::type_::{make_descriptor, mk_flex_var}; - - /// Fixed-seed generator, so the randomized tests need no dependency. - pub(crate) struct Lcg(pub u64); - - impl Lcg { - pub(crate) fn below(&mut self, bound: usize) -> usize { - self.0 = self - .0 - .wrapping_mul(6364136223846793005) - .wrapping_add(1442695040888963407); - (self.0 >> 33) as usize % bound - } - - pub(crate) fn pick(&mut self, variables: &[Variable]) -> Variable { - variables[self.below(variables.len())] - } - } - - #[test] - fn historical_closure_and_stranded_lookup_agree_with_the_scans() { - let (mut closures, mut stranded, mut unstranded) = (0, 0, 0); - for seed in 0..300 { - let mut random = Lcg(seed); - let mut uf = UnionFind::new(); - let mut dependencies = Dependencies::default(); - let mut variables: Vec<_> = (0..4).map(|_| mk_flex_var(&mut uf)).collect(); - for _ in 0..200 { - match random.below(9) { - 0 => variables.push(mk_flex_var(&mut uf)), - 1 | 2 => { - let children = (random.pick(&variables), random.pick(&variables)); - variables.push(uf.fresh(make_descriptor(Content::Structure( - FlatType::Fun1(children.0, children.1), - )))); - } - 3 => dependencies.remember(&mut uf, [random.pick(&variables)]), - 4 => { - // Unification keeps the content of one side. - let (first, second) = (random.pick(&variables), random.pick(&variables)); - let kept = if random.below(2) == 0 { first } else { second }; - let content = uf.get(kept).content.clone(); - uf.union(first, second, make_descriptor(content)); - } - 5 => { - // Normalization removes the visible children of a node. - let variable = random.pick(&variables); - uf.modify(variable, |desc| desc.content = Content::FlexVar(None)); - } - 6 => dependencies.strand(&mut uf, [random.pick(&variables)]), - 7 => { - dependencies.sync(&uf); - let variable = random.pick(&variables); - let scan = dependencies.stranded_scan(&mut uf, variable); - assert_eq!(dependencies.is_stranded(&mut uf, variable), scan); - if scan { - stranded += 1; - } else { - unstranded += 1; - } - } - _ => { - let roots = vec![random.pick(&variables), random.pick(&variables)]; - let scan = dependencies.historical_scan(&mut uf, roots.clone()); - assert_eq!(dependencies.historical(&mut uf, roots), scan); - closures += 1; - } - } - } - } - assert!(closures > 5_000); - assert!(stranded > 500 && unstranded > 500); - } -} diff --git a/crates/nash-solve/src/solve.rs b/crates/nash-solve/src/solve.rs index 4f8678ae..1be1e6e6 100644 --- a/crates/nash-solve/src/solve.rs +++ b/crates/nash-solve/src/solve.rs @@ -96,17 +96,7 @@ impl<'a> Schemes<'a> { } fn at(&self, site: nash_ast::NodeId) -> Option<&SchemeRecord<'a>> { - let found = self.by_site.get(&site).map(|index| &self.records[*index]); - // ORACLE: the scan of every scheme that the lookup replaces. - #[cfg(debug_assertions)] - assert_eq!( - found.map(std::ptr::from_ref), - self.records - .iter() - .find(|scheme| scheme.site.node() == site) - .map(std::ptr::from_ref) - ); - found + self.by_site.get(&site).map(|index| &self.records[*index]) } fn iter(&self) -> std::slice::Iter<'_, SchemeRecord<'a>> { @@ -1580,36 +1570,6 @@ impl<'a> Solver<'a, '_> { // another body can assign names to its own instantiations. for (index, mut members) in members.into_iter().enumerate() { let (uses, exprs, patterns) = (&uses[index], &exprs[index], &patterns[index]); - // ORACLE: the per-scope filters over every record that the grouping replaces. - #[cfg(debug_assertions)] - { - let scope = scopes[index]; - let same = |owner: nash_ast::NodeId| self.scope(owner).0 == scope; - assert!( - members.iter().copied().map(std::ptr::from_ref).eq(self - .schemes - .iter() - .filter(|scheme| same(scheme.site.node())) - .map(std::ptr::from_ref)) - ); - assert!( - uses.iter().copied().map(std::ptr::from_ref).eq(self - .uses - .iter() - .filter(|use_| same(use_.owner.expect("use belongs to a definition"))) - .map(std::ptr::from_ref)) - ); - for (grouped, records) in - [(exprs, &self.expr_types), (patterns, &self.pattern_types)] - { - assert!( - grouped.iter().copied().map(std::ptr::from_ref).eq(records - .iter() - .filter(|record| record.owner.is_some_and(same)) - .map(std::ptr::from_ref)) - ); - } - } members.sort_by_key(|scheme| self.scope(scheme.site.node()).1); let mut roots = Vec::new(); for scheme in &members { From 3a13ea502bd41258f762943f00eb5b3e32aeec87 Mon Sep 17 00:00:00 2001 From: microproofs Date: Thu, 15 Oct 2026 13:58:00 +0700 Subject: [PATCH 19/24] fix(solve): let a selected impl prove an open type that another impl cannot decide 09 made open-type evidence select under SelectPolicy::Defer, where any undecided candidate defers the whole selection. With impl Label (twins 'a 'a) and impl Label (twins int bool), the open twins p p matches the first impl for every p, but the second cannot decide p, so resolution failed with NonGround. A reflexive Lift that p could decide also returned NonGround before impl search, although impl Lift (twins 'a 'a) (twins int bool) proves the pair. Type checking treats p as rigid and selects those impls, so both programs passed nash check and then stopped nash test with "cannot resolve superclass: NonGround" (driver test phantom_pair_through_a_superclass). The resolver uses SelectPolicy::Exact again, so a selected impl wins over an undecided candidate. Under Exact, select_impl now returns Deferred when nothing is selected and a candidate is undecided, so the resolver still reports NonGround there. Entailment never sees Deferred: its rigid types decide every test. An undecided reflexive Lift falls through to impl selection and reports NonGround only when no impl is selected. docs/traits.md no longer says that reflexive Lift needs a Big representation. It needs nominally equal arguments only: Lift int int and Lift () () resolve, and canonicalization accepts it for Big and Const types. Signed-off-by: microproofs --- .sampo/changesets/open-superclass-types.md | 2 +- crates/nash-ast/src/head.rs | 22 ++++--- ...t_tests__selection_outcomes_by_policy.snap | 14 ++--- crates/nash-driver/tests/base_traits.rs | 4 ++ .../fixtures/base-traits/PhantomPair.nash | 49 ++++++++++++++++ ...ts__phantom_pair_through_a_superclass.snap | 6 ++ crates/nash-solve/src/evidence.rs | 9 ++- crates/nash-solve/tests/evidence.rs | 57 +++++++++++++++++++ docs/traits.md | 13 +++-- 9 files changed, 152 insertions(+), 24 deletions(-) create mode 100644 crates/nash-driver/tests/fixtures/base-traits/PhantomPair.nash create mode 100644 crates/nash-driver/tests/snapshots/base_traits__phantom_pair_through_a_superclass.snap diff --git a/.sampo/changesets/open-superclass-types.md b/.sampo/changesets/open-superclass-types.md index 84b5b7b6..8c980bf4 100644 --- a/.sampo/changesets/open-superclass-types.md +++ b/.sampo/changesets/open-superclass-types.md @@ -4,4 +4,4 @@ cargo/nash-solve: minor cargo/nash-codegen: minor --- -Resolve superclass evidence when a type variable stays open. A phantom parameter that no use fixes, as in `wrapper : tag 'p -> bool; wrapper t = same t t` with `same : Ord 'a => 'a -> 'a -> bool`, passed type checking but stopped `nash test` with "superclass resolution requires a ground type". `nash_solve::evidence::resolve` now keeps open type variables. An open variable equals only itself, and resolution reports `NonGround` only when impl selection, a representation test, or the requirements of a type need the variable. The new `nash_ast::head::Open` matches impl heads against open types. `nash_codegen::evidence::Error::NonGround` is removed. +Resolve superclass evidence when a type variable stays open. A phantom parameter that no use fixes, as in `wrapper : tag 'p -> bool; wrapper t = same t t` with `same : Ord 'a => 'a -> 'a -> bool`, passed type checking but stopped `nash test` with "superclass resolution requires a ground type". `nash_solve::evidence::resolve` now keeps open type variables. An open variable equals only itself. An impl that matches whatever the variable is proves the predicate, and resolution reports `NonGround` only when no impl does and impl selection, a representation test, or the requirements of a type need the variable. The new `nash_ast::head::Open` matches impl heads against open types. Under `SelectPolicy::Exact`, `select_impl` now returns `Deferred` when no impl is selected and a candidate is undecided. `nash_codegen::evidence::Error::NonGround` is removed. diff --git a/crates/nash-ast/src/head.rs b/crates/nash-ast/src/head.rs index 66804afa..a4c7aca3 100644 --- a/crates/nash-ast/src/head.rs +++ b/crates/nash-ast/src/head.rs @@ -38,8 +38,9 @@ pub struct Canonical<'r, 'a>(pub &'r dyn Fn(&'a Located>, ReprSet) -> M /// Canonical types whose variables stay open: nothing will bind them, as in /// code generation when no use fixes a phantom parameter. An open variable /// equals only itself. A constructor test or a comparison that only an open -/// variable could decide is undecided, so under `SelectPolicy::Defer` a -/// selection that needs an open variable is `Deferred`. +/// variable could decide is undecided, so under `SelectPolicy::Exact` a +/// selection that needs an open variable is `Deferred` unless another +/// candidate is selected. pub struct Open<'r, 'a>(pub &'r dyn Fn(&'a Located>, ReprSet) -> Match<()>); #[derive(PartialEq, Eq)] @@ -251,7 +252,9 @@ pub fn matches<'a, T: Types<'a>>( pub enum SelectPolicy { /// Inference: any undecided candidate defers the whole selection. Defer, - /// Rigid or ground arguments: an undecided candidate is not proven. + /// Entailment and evidence: an undecided candidate is not proven, so a + /// selected candidate wins over it. With no selection, an undecided + /// candidate makes the result `Deferred`. Exact, } @@ -300,6 +303,7 @@ pub fn select_impl<'h, 'a: 'h, T: Types<'a>, I>( Ok(match selected { _ if deferred && policy == SelectPolicy::Defer => ImplSelection::Deferred, Some(selected) => selected, + None if deferred => ImplSelection::Deferred, None => ImplSelection::Missing, }) } @@ -645,10 +649,12 @@ mod select_tests { use Outcome::{Deferred, No, Yes}; use SelectPolicy::{Defer, Exact}; - fn render(result: Result, Limit>) -> String { + fn render(policy: SelectPolicy, result: Result, Limit>) -> String { match result { Ok(ImplSelection::Selected { info, .. }) => format!("selects impl {}", info + 1), - Ok(ImplSelection::Deferred) => "waits".to_owned(), + // Inference waits for its variables; nothing binds an open type. + Ok(ImplSelection::Deferred) if policy == Defer => "waits".to_owned(), + Ok(ImplSelection::Deferred) => "undecided".to_owned(), Ok(ImplSelection::Missing) => "no impl".to_owned(), Err(Limit) => "work limit".to_owned(), } @@ -688,10 +694,10 @@ mod select_tests { "" }; output.push_str(&format!( - "{}{budget_note}\n inference: {}\n closed types: {}\n", + "{}{budget_note}\n inference: {}\n entailment and evidence: {}\n", describe(outcomes), - render(select(outcomes, Defer, *budget)), - render(select(outcomes, Exact, *budget)), + render(Defer, select(outcomes, Defer, *budget)), + render(Exact, select(outcomes, Exact, *budget)), )); } insta::with_settings!({ diff --git a/crates/nash-ast/src/snapshots/nash_ast__head__select_tests__selection_outcomes_by_policy.snap b/crates/nash-ast/src/snapshots/nash_ast__head__select_tests__selection_outcomes_by_policy.snap index e093b735..57bf12db 100644 --- a/crates/nash-ast/src/snapshots/nash_ast__head__select_tests__selection_outcomes_by_policy.snap +++ b/crates/nash-ast/src/snapshots/nash_ast__head__select_tests__selection_outcomes_by_policy.snap @@ -4,22 +4,22 @@ description: "Impls in declaration order and how each one matches the arguments. --- no impls inference: no impl - closed types: no impl + entailment and evidence: no impl does not match, does not match inference: no impl - closed types: no impl + entailment and evidence: no impl does not match, matches, does not match inference: selects impl 2 - closed types: selects impl 2 + entailment and evidence: selects impl 2 matches, undecided inference: waits - closed types: selects impl 1 + entailment and evidence: selects impl 1 undecided, matches inference: waits - closed types: selects impl 2 + entailment and evidence: selects impl 2 undecided, does not match inference: waits - closed types: no impl + entailment and evidence: undecided does not match, matches (budget for one step) inference: work limit - closed types: work limit + entailment and evidence: work limit diff --git a/crates/nash-driver/tests/base_traits.rs b/crates/nash-driver/tests/base_traits.rs index c3b84e11..0a9bab41 100644 --- a/crates/nash-driver/tests/base_traits.rs +++ b/crates/nash-driver/tests/base_traits.rs @@ -133,6 +133,10 @@ base_snapshot!( phantom_type_through_a_superclass, "fixtures/base-traits/Phantom.nash" ); +base_snapshot!( + phantom_pair_through_a_superclass, + "fixtures/base-traits/PhantomPair.nash" +); base_snapshot!(prop_helpers, "fixtures/base-traits/PropHelpers.nash"); base_snapshot!(cardano_value, "fixtures/base-traits/CardanoValue.nash"); diff --git a/crates/nash-driver/tests/fixtures/base-traits/PhantomPair.nash b/crates/nash-driver/tests/fixtures/base-traits/PhantomPair.nash new file mode 100644 index 00000000..02f16d61 --- /dev/null +++ b/crates/nash-driver/tests/fixtures/base-traits/PhantomPair.nash @@ -0,0 +1,49 @@ +module Main exposing (..) + +import Lift exposing (Lift) + +type twins 'a 'b = Twins + +trait Label 'a where + label : 'a -> string + +impl Label (twins 'a 'a) where + label _ = "same" + +impl Label (twins int bool) where + label _ = "mixed" + +trait Label 'a => Named 'a where + name : 'a -> string + +impl Named (twins 'a 'a) where + name _ = "named" + +viaSuper : Named 't => 't -> string +viaSuper x = label x + +pairLabel : twins 'p 'p -> string +pairLabel t = viaSuper t + +impl Lift (twins 'a 'a) (twins int bool) where + lift _ = Twins + lower _ = Twins + +trait Lift 'small 'big => Convert 'small 'big where + convert : 'small -> 'big + +impl Convert (twins 'a 'a) (twins int bool) where + convert t = lift t + +viaLift : Convert 'small 'big => 'small -> 'big +viaLift x = lift x + +pairToMixed : twins 'p 'p -> twins int bool +pairToMixed t = viaLift t + +tests + test "an open pair selects the impl that matches every pair" = do + assert (pairLabel Twins == "same") + + test "an open pair lifts through an impl that reflexivity cannot decide" = do + assert (label (pairToMixed Twins) == "mixed") diff --git a/crates/nash-driver/tests/snapshots/base_traits__phantom_pair_through_a_superclass.snap b/crates/nash-driver/tests/snapshots/base_traits__phantom_pair_through_a_superclass.snap new file mode 100644 index 00000000..1c01b94f --- /dev/null +++ b/crates/nash-driver/tests/snapshots/base_traits__phantom_pair_through_a_superclass.snap @@ -0,0 +1,6 @@ +--- +source: crates/nash-driver/tests/base_traits.rs +description: "module Main exposing (..)\n\nimport Lift exposing (Lift)\n\ntype twins 'a 'b = Twins\n\ntrait Label 'a where\n label : 'a -> string\n\nimpl Label (twins 'a 'a) where\n label _ = \"same\"\n\nimpl Label (twins int bool) where\n label _ = \"mixed\"\n\ntrait Label 'a => Named 'a where\n name : 'a -> string\n\nimpl Named (twins 'a 'a) where\n name _ = \"named\"\n\nviaSuper : Named 't => 't -> string\nviaSuper x = label x\n\npairLabel : twins 'p 'p -> string\npairLabel t = viaSuper t\n\nimpl Lift (twins 'a 'a) (twins int bool) where\n lift _ = Twins\n lower _ = Twins\n\ntrait Lift 'small 'big => Convert 'small 'big where\n convert : 'small -> 'big\n\nimpl Convert (twins 'a 'a) (twins int bool) where\n convert t = lift t\n\nviaLift : Convert 'small 'big => 'small -> 'big\nviaLift x = lift x\n\npairToMixed : twins 'p 'p -> twins int bool\npairToMixed t = viaLift t\n\ntests\n test \"an open pair selects the impl that matches every pair\" = do\n assert (pairLabel Twins == \"same\")\n\n test \"an open pair lifts through an impl that reflexivity cannot decide\" = do\n assert (label (pairToMixed Twins) == \"mixed\")\n" +--- +an open pair selects the impl that matches every pair: Pass; traces: [] +an open pair lifts through an impl that reflexivity cannot decide: Pass; traces: [] diff --git a/crates/nash-solve/src/evidence.rs b/crates/nash-solve/src/evidence.rs index 65c462b8..e94c908f 100644 --- a/crates/nash-solve/src/evidence.rs +++ b/crates/nash-solve/src/evidence.rs @@ -301,6 +301,8 @@ impl<'a> Resolver<'_, 'a> { typ: args[0], })); } + // An impl can still prove a pair that reflexivity cannot decide. + let mut undecided = false; if trait_ == nash_ast::primitives::lift_trait() && self.tables.has_reflexive_lift() && let [first, second] = terms.as_slice() @@ -311,7 +313,7 @@ impl<'a> Resolver<'_, 'a> { typ: args[0], })); } - nash_ast::head::Match::Deferred => return Err(error(Failure::NonGround)), + nash_ast::head::Match::Deferred => undecided = true, nash_ast::head::Match::No => {} } } @@ -333,7 +335,7 @@ impl<'a> Resolver<'_, 'a> { candidates, args, &mut self.remaining, - nash_ast::head::SelectPolicy::Defer, + nash_ast::head::SelectPolicy::Exact, ) .map_err(|_| error(Failure::Limit))?; let (key, info, type_args) = match selection { @@ -342,6 +344,9 @@ impl<'a> Resolver<'_, 'a> { arguments, } => (key, info, arguments), nash_ast::head::ImplSelection::Deferred => return Err(error(Failure::NonGround)), + nash_ast::head::ImplSelection::Missing if undecided => { + return Err(error(Failure::NonGround)); + } nash_ast::head::ImplSelection::Missing => return Err(error(Failure::MissingImpl)), }; let substitution = info diff --git a/crates/nash-solve/tests/evidence.rs b/crates/nash-solve/tests/evidence.rs index 06d599ce..706701b3 100644 --- a/crates/nash-solve/tests/evidence.rs +++ b/crates/nash-solve/tests/evidence.rs @@ -643,3 +643,60 @@ fn open_types_resolve_when_no_decision_needs_them() { Failure::NonGround ); } + +/// `twins 'a 'a` proves the open `twins p p` for every `p`. The disjoint +/// `twins int bool` and reflexive Lift cannot decide it, and must not block +/// that proof. +#[test] +fn selected_impl_proves_an_open_type_that_another_rule_cannot_decide() { + let bump = Bump::new(); + let (tables, annotations) = fixture( + &bump, + indoc::indoc!( + " + module Lift exposing (..) + trait Lift 'small 'big where + lift : 'small -> 'big + lower : 'big -> 'small + trait Keep 'a where + keep : 'a -> 'a + type twins 'a 'b = Twins + impl Keep (twins 'a 'a) where + keep x = x + impl Keep (twins int bool) where + keep x = x + impl Lift (twins 'a 'a) (twins int bool) where + lift _ = Twins + lower _ = Twins + same : twins 'p 'p -> twins 'p 'p + same x = x + mixed : twins int bool -> twins int bool + mixed x = x + " + ), + ); + let keep = *tables.traits.keys().find(|key| key.name == "Keep").unwrap(); + assert!(matches!( + resolve( + &bump, + &tables, + &Pred::Trait { + trait_: keep, + args: bump.alloc_slice_copy(&[input(&annotations, "same")]), + } + ), + Ok(Some(Evidence::Impl { .. })) + )); + assert!(matches!( + resolve( + &bump, + &tables, + &Pred::Trait { + trait_: nash_ast::primitives::lift_trait(), + args: bump + .alloc_slice_copy(&[input(&annotations, "same"), input(&annotations, "mixed")]), + } + ), + Ok(Some(Evidence::Impl { .. })) + )); +} diff --git a/docs/traits.md b/docs/traits.md index 0dc825a7..e8bbf633 100644 --- a/docs/traits.md +++ b/docs/traits.md @@ -305,7 +305,7 @@ Evidence is the derivation: ``` Evidence = Impl { impl_: ImplRef, type_args: [Type], args: [Evidence] } -- by_instance; type_args = head vars - | ReflexiveLift { typ: Type } -- compiler rule for equal Big types + | ReflexiveLift { typ: Type } -- compiler rule for nominally equal types | Given { binder: NodeId, index: u16 } -- i-th predicate of the scheme of definition `binder` | Super { of: Evidence, index: u16 } -- i-th superclass of an evidence's trait | Specialize { trait_: TraitName, args: [Type] } -- by_coverage; codegen selects for each use @@ -574,15 +574,16 @@ each argument's head constructor against the impl table, instantiate the impl's context at the argument's type arguments, recurse. A type variable that reaches the resolver is open: no use fixed it, as with a phantom parameter, and nothing will bind it. An open variable equals only itself and -binds impl head variables like any other type. A decision that needs an open -variable fails with `NonGround`: impl selection (`head::Open` under -`SelectPolicy::Defer`), a representation test, or a requirement that +binds impl head variables like any other type. An impl that matches whatever +the variable is proves the predicate, even when another candidate or +reflexive Lift depends on the variable. Otherwise a decision that needs an +open variable fails with `NonGround`: impl selection (`head::Open` under +`SelectPolicy::Exact`), a representation test, or a requirement that formation of a type leaves. In a checked program, a rigid variable that selects an impl needs a stated constraint, so type checking reports that case first. The predicate never needs `Given`, so the result is a closed tree of `Impl` and exact-core `ReflexiveLift` evidence. Reflexive Lift requires -nominally equal arguments with an already-proven Big representation; it does -not choose a representation. +nominally equal arguments and does not choose a representation. Failures distinguish `MissingImpl`, `NonGround`, and `Limit`, retaining the failed predicate. Resolution and type traversal share a 16,384-step work budget, with a depth limit of 256. Context substitution is charged before From 4dcd4e986ad5cb4b15baefdbf159b140fa4e36a8 Mon Sep 17 00:00:00 2001 From: microproofs Date: Thu, 15 Oct 2026 18:22:45 +0700 Subject: [PATCH 20/24] fix(report): break tuple and record entries as Elm's D.cat does render_type::tuple and record joined their entries with Doc::cat, which is Elm's <> and has no break point. Elm's Render/Type.hs joins them with D.cat, wl-pprint's cat: the entries stay on one line when they fit and go one per line otherwise. A tuple wider than the page therefore broke only inside its last entries and drifted to the right. Doc::pcat is D.cat (a group of entries separated by LineBreak). tuple and the record fields use it. No existing snapshot changes. The new source_pipeline_tuple_wider_than_the_page shows the layout for a type mismatch. Signed-off-by: microproofs --- .../changesets/report-tuple-record-entries.md | 5 +++++ crates/nash-report/src/doc.rs | 5 +++++ crates/nash-report/src/render_type.rs | 6 +++--- ...ce_pipeline_tuple_wider_than_the_page.snap | 20 +++++++++++++++++++ crates/nash-report/src/type_/tests.rs | 8 ++++++++ 5 files changed, 41 insertions(+), 3 deletions(-) create mode 100644 .sampo/changesets/report-tuple-record-entries.md create mode 100644 crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_tuple_wider_than_the_page.snap diff --git a/.sampo/changesets/report-tuple-record-entries.md b/.sampo/changesets/report-tuple-record-entries.md new file mode 100644 index 00000000..6e81e4c8 --- /dev/null +++ b/.sampo/changesets/report-tuple-record-entries.md @@ -0,0 +1,5 @@ +--- +cargo/nash-report: minor +--- + +Break a tuple or record type that does not fit the line with one entry per line, as Elm does. The entries were joined without break points, so only the last entries broke and the type drifted to the right. Add `Doc::pcat`, Elm's `D.cat`. diff --git a/crates/nash-report/src/doc.rs b/crates/nash-report/src/doc.rs index 0ba57656..b114d404 100644 --- a/crates/nash-report/src/doc.rs +++ b/crates/nash-report/src/doc.rs @@ -67,6 +67,11 @@ impl Doc { pub fn hcat(docs: impl IntoIterator) -> Doc { Doc::cat(docs) } + /// Elm `D.cat` (wl-pprint `cat`): one line when the docs fit, otherwise + /// one per line. `Doc::cat` is `<>`. + pub fn pcat(docs: impl IntoIterator) -> Doc { + Doc::Group(Box::new(intersperse(docs, Doc::LineBreak))) + } /// `P.vcat`. pub fn vcat(docs: impl IntoIterator) -> Doc { intersperse(docs, Doc::HardLine) diff --git a/crates/nash-report/src/render_type.rs b/crates/nash-report/src/render_type.rs index a0f67529..de3573fe 100644 --- a/crates/nash-report/src/render_type.rs +++ b/crates/nash-report/src/render_type.rs @@ -37,7 +37,7 @@ pub fn tuple(a: Doc, b: Doc, rest: Vec) -> Doc { .chain(rest) .enumerate() .map(|(i, d)| Doc::hsep([Doc::text(if i == 0 { "(" } else { "," }), d])); - Doc::align(Doc::sep([Doc::cat(entries), Doc::text(")")])) + Doc::align(Doc::sep([Doc::pcat(entries), Doc::text(")")])) } fn entry((name, typ): (Doc, Doc)) -> Doc { Doc::hang(4, Doc::sep([Doc::hsep([name, Doc::text(":")]), typ])) @@ -64,12 +64,12 @@ fn record_docs(entries: Vec<(Doc, Doc)>, ext: Option, vertical: bool) -> Do let body = if let Some(ext) = ext { Doc::hang( 4, - Doc::sep([Doc::hsep([Doc::text("{"), ext]), Doc::cat(fields)]), + Doc::sep([Doc::hsep([Doc::text("{"), ext]), Doc::pcat(fields)]), ) } else if vertical { Doc::vcat(fields) } else { - Doc::cat(fields) + Doc::pcat(fields) }; if vertical { Doc::vcat([body, Doc::text("}")]) diff --git a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_tuple_wider_than_the_page.snap b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_tuple_wider_than_the_page.snap new file mode 100644 index 00000000..7c10be6d --- /dev/null +++ b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_tuple_wider_than_the_page.snap @@ -0,0 +1,20 @@ +--- +source: crates/nash-report/src/type_/tests.rs +description: "module Main exposing (..)\ntype wrapper 'a = Wrapper 'a\ntype pair 'a 'b = Pair 'a 'b\nf : ( wrapper (pair Primitive.int Primitive.bytes), wrapper (pair Primitive.string Primitive.bool), wrapper (pair Primitive.int Primitive.int) ) -> Primitive.int\nf x = x\n" +--- +nash::type::mismatch + + × Type mismatch: expected `int`, + │ found `( wrapper (pair int bytes) + │ , wrapper (pair string bool) + │ , wrapper (pair int int) + │ )`. + ╭─[Main.nash:5:7] + 3 │ type pair 'a 'b = Pair 'a 'b + 4 │ f : ( wrapper (pair Primitive.int Primitive.bytes), wrapper (pair Primitive.string Primitive.bool), wrapper (pair Primitive.int Primitive.int) ) -> Primitive.int + · ──────────────────────────────────────────────────────────────────────────────┬────────────────────────────────────────────────────────────────────────────── + · ╰── declared type + 5 │ f x = x + · ┬ + · ╰── body of `f` + ╰──── diff --git a/crates/nash-report/src/type_/tests.rs b/crates/nash-report/src/type_/tests.rs index 7ff5378f..41126036 100644 --- a/crates/nash-report/src/type_/tests.rs +++ b/crates/nash-report/src/type_/tests.rs @@ -1256,6 +1256,14 @@ fn source_pipeline_infinite_type() { let _guard = settings.bind_to_scope(); insta::assert_snapshot!(type_error_reports(source)); } +/// A tuple wider than the page puts one entry on each line. +#[test] +fn source_pipeline_tuple_wider_than_the_page() { + let source = "module Main exposing (..)\ntype wrapper 'a = Wrapper 'a\ntype pair 'a 'b = Pair 'a 'b\nf : ( wrapper (pair Primitive.int Primitive.bytes), wrapper (pair Primitive.string Primitive.bool), wrapper (pair Primitive.int Primitive.int) ) -> Primitive.int\nf x = x\n"; + let settings = source_settings(source); + let _guard = settings.bind_to_scope(); + insta::assert_snapshot!(type_error_reports(source)); +} #[test] fn source_pipeline_missing_impl() { let source = "module Main exposing (..)\ntype A = A\ntrait Eq 'a where\n eq : 'a -> 'a -> Primitive.bool\nf : A -> Primitive.bool\nf a = eq a a\n"; From b613c93b077b2c22d13af47904d6e6fffb00d002 Mon Sep 17 00:00:00 2001 From: microproofs Date: Thu, 15 Oct 2026 18:18:22 +0700 Subject: [PATCH 21/24] fix(report): build long trait help lines from document parts missing_constraint and missing_impl rendered the wanted predicate to a string at width 80 and spliced it into Doc::text. A predicate wider than 80 columns rendered with a line break, so Doc::text's assertion stopped nash check with "Doc::text must not contain newlines". Both help lines are now built from document parts, as the messages already were. with_predicate wraps each message and help sentence of the two producers in hang 4 (sep [lead, predicate]): a sentence that does not fit puts the predicate on its own line indented by 4, and a sentence that fits renders exactly as before. Three existing snapshots change: two help lines of 88 and 97 columns (via_requires_generator, map_lift_rejects_inferred_native_pair_components) and an 81-column representation message (missing_storable_constraint_for_list_element) now break before the predicate. Doc::text and its assertion are unchanged. Signed-off-by: microproofs --- .sampo/changesets/long-trait-help-lines.md | 5 ++ ...jects_inferred_native_pair_components.snap | 3 +- ..._storable_constraint_for_list_element.snap | 4 +- ...issing_constraint_wider_than_the_page.snap | 23 +++++++++ ...line_missing_impl_wider_than_the_page.snap | 22 ++++++++ crates/nash-report/src/type_/tests.rs | 16 ++++++ crates/nash-report/src/type_/traits.rs | 51 +++++++++++-------- .../testing__via_requires_generator.snap | 3 +- 8 files changed, 101 insertions(+), 26 deletions(-) create mode 100644 .sampo/changesets/long-trait-help-lines.md create mode 100644 crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_missing_constraint_wider_than_the_page.snap create mode 100644 crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_missing_impl_wider_than_the_page.snap diff --git a/.sampo/changesets/long-trait-help-lines.md b/.sampo/changesets/long-trait-help-lines.md new file mode 100644 index 00000000..96487efc --- /dev/null +++ b/.sampo/changesets/long-trait-help-lines.md @@ -0,0 +1,5 @@ +--- +cargo/nash-report: patch +--- + +Stop `nash check` from crashing with "Doc::text must not contain newlines" when a missing-constraint or missing-impl predicate is wider than 80 columns. The help line is now part of the report layout instead of pre-rendered text. When a sentence with a predicate does not fit the line, the predicate moves to its own line, indented by 4. Sentences that fit render as before. diff --git a/crates/nash-driver/tests/snapshots/bundled_base__map_lift_rejects_inferred_native_pair_components.snap b/crates/nash-driver/tests/snapshots/bundled_base__map_lift_rejects_inferred_native_pair_components.snap index 75b7aee8..6703c412 100644 --- a/crates/nash-driver/tests/snapshots/bundled_base__map_lift_rejects_inferred_native_pair_components.snap +++ b/crates/nash-driver/tests/snapshots/bundled_base__map_lift_rejects_inferred_native_pair_components.snap @@ -21,4 +21,5 @@ nash::type::missing_impl … - Import or define an impl for `Lift (list (pair int (list Data))) (Map Int (List Data))`. + Import or define an impl for + `Lift (list (pair int (list Data))) (Map Int (List Data))`. diff --git a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__missing_storable_constraint_for_list_element.snap b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__missing_storable_constraint_for_list_element.snap index fade9249..c93936e3 100644 --- a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__missing_storable_constraint_for_list_element.snap +++ b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__missing_storable_constraint_for_list_element.snap @@ -4,8 +4,8 @@ description: "module Main exposing (..)\nvalues = [\\x -> x + 1]\n" --- nash::type::missing_impl - × Unsatisfied representation constraint `Primitive.Storable (Primitive.int - │ -> Primitive.int)`. + × Unsatisfied representation constraint + │ `Primitive.Storable (Primitive.int -> Primitive.int)`. ╭─[Main.nash:2:10] 1 │ module Main exposing (..) 2 │ values = [\x -> x + 1] diff --git a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_missing_constraint_wider_than_the_page.snap b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_missing_constraint_wider_than_the_page.snap new file mode 100644 index 00000000..efbdc227 --- /dev/null +++ b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_missing_constraint_wider_than_the_page.snap @@ -0,0 +1,23 @@ +--- +source: crates/nash-report/src/type_/tests.rs +description: "module Main exposing (..)\ntype wrapper 'a = Wrapper 'a\ntype pair 'a 'b = Pair 'a 'b\ntrait Relate 'a 'b where\n relate : 'a -> 'b -> Primitive.bool\nf : 'element -> ( wrapper (pair Primitive.int Primitive.bytes), wrapper (pair Primitive.string Primitive.bool), wrapper (pair Primitive.int Primitive.int) ) -> Primitive.bool\nf x y = relate x y\n" +--- +nash::type::missing_constraint + + × `relate` requires undeclared constraint + │ `Relate 'element ( wrapper (pair int bytes) + │ , wrapper (pair string bool) + │ , wrapper (pair int int) + │ )`. + ╭─[Main.nash:7:9] + 6 │ f : 'element -> ( wrapper (pair Primitive.int Primitive.bytes), wrapper (pair Primitive.string Primitive.bool), wrapper (pair Primitive.int Primitive.int) ) -> Primitive.bool + 7 │ f x y = relate x y + · ┬ ───┬── + · │ ╰── constraint required here + · ╰── annotation for `f` + ╰──── + help: Add + `Relate 'element ( wrapper (pair int bytes) + , wrapper (pair string bool) + , wrapper (pair int int) + )` to the annotation for `f`. diff --git a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_missing_impl_wider_than_the_page.snap b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_missing_impl_wider_than_the_page.snap new file mode 100644 index 00000000..deb4972c --- /dev/null +++ b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_missing_impl_wider_than_the_page.snap @@ -0,0 +1,22 @@ +--- +source: crates/nash-report/src/type_/tests.rs +description: "module Main exposing (..)\ntype wrapper 'a = Wrapper 'a\ntype pair 'a 'b = Pair 'a 'b\ntrait Probe 'a where\n probe : 'a -> 'a\nf : ( wrapper (pair Primitive.int Primitive.bytes), wrapper (pair Primitive.string Primitive.bool), wrapper (pair Primitive.int Primitive.int) ) -> ( wrapper (pair Primitive.int Primitive.bytes), wrapper (pair Primitive.string Primitive.bool), wrapper (pair Primitive.int Primitive.int) )\nf x = probe x\n" +--- +nash::type::missing_impl + + × No impl for + │ `Probe ( wrapper (pair int bytes) + │ , wrapper (pair string bool) + │ , wrapper (pair int int) + │ )`. + ╭─[Main.nash:7:7] + 6 │ f : ( wrapper (pair Primitive.int Primitive.bytes), wrapper (pair Primitive.string Primitive.bool), wrapper (pair Primitive.int Primitive.int) ) -> ( wrapper (pair Primitive.int Primitive.bytes), wrapper (pair Primitive.string Primitive.bool), wrapper (pair Primitive.int Primitive.int) ) + 7 │ f x = probe x + · ──┬── + · ╰── required by `probe` + ╰──── + help: Import or define an impl for + `Probe ( wrapper (pair int bytes) + , wrapper (pair string bool) + , wrapper (pair int int) + )`. diff --git a/crates/nash-report/src/type_/tests.rs b/crates/nash-report/src/type_/tests.rs index 41126036..2147ab85 100644 --- a/crates/nash-report/src/type_/tests.rs +++ b/crates/nash-report/src/type_/tests.rs @@ -1278,6 +1278,22 @@ fn source_pipeline_missing_constraint() { let _guard = settings.bind_to_scope(); insta::assert_snapshot!(type_error_reports(source)); } +/// The wanted predicate is wider than 80 columns, so the help line wraps. +#[test] +fn source_pipeline_missing_impl_wider_than_the_page() { + let source = "module Main exposing (..)\ntype wrapper 'a = Wrapper 'a\ntype pair 'a 'b = Pair 'a 'b\ntrait Probe 'a where\n probe : 'a -> 'a\nf : ( wrapper (pair Primitive.int Primitive.bytes), wrapper (pair Primitive.string Primitive.bool), wrapper (pair Primitive.int Primitive.int) ) -> ( wrapper (pair Primitive.int Primitive.bytes), wrapper (pair Primitive.string Primitive.bool), wrapper (pair Primitive.int Primitive.int) )\nf x = probe x\n"; + let settings = source_settings(source); + let _guard = settings.bind_to_scope(); + insta::assert_snapshot!(type_error_reports(source)); +} +/// The wanted predicate is wider than 80 columns, so the help line wraps. +#[test] +fn source_pipeline_missing_constraint_wider_than_the_page() { + let source = "module Main exposing (..)\ntype wrapper 'a = Wrapper 'a\ntype pair 'a 'b = Pair 'a 'b\ntrait Relate 'a 'b where\n relate : 'a -> 'b -> Primitive.bool\nf : 'element -> ( wrapper (pair Primitive.int Primitive.bytes), wrapper (pair Primitive.string Primitive.bool), wrapper (pair Primitive.int Primitive.int) ) -> Primitive.bool\nf x y = relate x y\n"; + let settings = source_settings(source); + let _guard = settings.bind_to_scope(); + insta::assert_snapshot!(type_error_reports(source)); +} #[test] fn example_one_big_little_annotation() { diff --git a/crates/nash-report/src/type_/traits.rs b/crates/nash-report/src/type_/traits.rs index daa57678..8562dcaf 100644 --- a/crates/nash-report/src/type_/traits.rs +++ b/crates/nash-report/src/type_/traits.rs @@ -13,6 +13,17 @@ fn predicate(l: &Localizer, trait_: QualifiedName<'_>, args: &[&ErrorType<'_>]) .chain(args.iter().map(|ty| type_diff::to_doc(l, Ctx::App, ty))), ) } +// `lead `predicate`tail`. When the sentence does not fit, the predicate moves +// to its own line, indented 4; a sentence that fits renders unchanged. +fn with_predicate(lead: String, predicate: Doc, tail: String) -> Doc { + Doc::hang( + 4, + Doc::sep([ + Doc::text(lead), + Doc::cat([Doc::text("`"), predicate, Doc::text(format!("`{tail}"))]), + ]), + ) +} fn report( title: &str, region: Region, @@ -226,16 +237,16 @@ pub(super) fn missing_constraint( let mut report = report( "MISSING CONSTRAINT", region, - Doc::cat([ - Doc::text(format!("`{name}` requires undeclared constraint `")), + with_predicate( + format!("`{name}` requires undeclared constraint"), wanted.clone(), - Doc::text("`."), - ]), - [Doc::text(format!( - "Add `{}` to the annotation for `{}`.", - wanted.render(80, false), - binder.value - ))], + ".".into(), + ), + [with_predicate( + "Add".into(), + wanted, + format!(" to the annotation for `{}`.", binder.value), + )], ); report.primary_label = Some("constraint required here".into()); report.with_label(crate::Label { @@ -346,23 +357,19 @@ pub(super) fn missing_impl( ReprTrait::Little => "Const or Term", }; ( - Doc::cat([ - Doc::text("Unsatisfied representation constraint `"), + with_predicate( + "Unsatisfied representation constraint".into(), wanted, - Doc::text("`."), - ]), - format!( - "Use a type with {admitted} representation; an impl cannot change representation." + ".".into(), ), + Doc::text(format!( + "Use a type with {admitted} representation; an impl cannot change representation." + )), ) } else { - let hint = format!( - "Import or define an impl for `{}`.", - wanted.render(80, false) - ); ( - Doc::cat([Doc::text("No impl for `"), wanted, Doc::text("`.")]), - hint, + with_predicate("No impl for".into(), wanted.clone(), ".".into()), + with_predicate("Import or define an impl for".into(), wanted, ".".into()), ) }; let mut details = Vec::new(); @@ -388,7 +395,7 @@ pub(super) fn missing_impl( Doc::vcat(because.iter().map(|reason| requirement(l, reason))), )); } - details.push(Doc::text(hint)); + details.push(hint); let mut report = report("MISSING IMPL", region, message, details); report.primary_label = Some(if name.is_empty() { "required here".into() diff --git a/crates/nash-solve/tests/snapshots/testing__via_requires_generator.snap b/crates/nash-solve/tests/snapshots/testing__via_requires_generator.snap index 77092e8a..a0514950 100644 --- a/crates/nash-solve/tests/snapshots/testing__via_requires_generator.snap +++ b/crates/nash-solve/tests/snapshots/testing__via_requires_generator.snap @@ -17,4 +17,5 @@ nash::type::missing_impl unit - Import or define an impl for `Literal.FromUnit (Prop.prng -> Option.option ( unit, Prop.prng ))`. + Import or define an impl for + `Literal.FromUnit (Prop.prng -> Option.option ( unit, Prop.prng ))`. From 3d86f0971cba9df677d02296c21c25ed7889b52c Mon Sep 17 00:00:00 2001 From: microproofs Date: Fri, 16 Oct 2026 12:10:51 +0700 Subject: [PATCH 22/24] fix(report): align the record after Available fields under its brace The missing-field hint concatenated "Available fields: " with a vertical record, so the record's later lines started at the left margin instead of under its opening brace. Doc::align keeps them under the brace. Six snapshots change, each only in that indentation. Signed-off-by: microproofs --- .sampo/changesets/available-fields-alignment.md | 5 +++++ crates/nash-report/src/type_/records.rs | 2 +- .../nash_report__type___tests__missing_field_alias.snap | 2 +- ...port__type___tests__record_access_missing_field_typo.snap | 4 ++-- ...sh_report__type___tests__record_update_unknown_field.snap | 2 +- ..._report__type___tests__source_pipeline_record_access.snap | 2 +- .../inference__nominal_record_missing_field_errors.snap | 2 +- ...block_dependent_traits_and_keep_independent_traits-2.snap | 2 +- 8 files changed, 13 insertions(+), 8 deletions(-) create mode 100644 .sampo/changesets/available-fields-alignment.md diff --git a/.sampo/changesets/available-fields-alignment.md b/.sampo/changesets/available-fields-alignment.md new file mode 100644 index 00000000..78e38a44 --- /dev/null +++ b/.sampo/changesets/available-fields-alignment.md @@ -0,0 +1,5 @@ +--- +cargo/nash-report: patch +--- + +Align the record after "Available fields:" under its opening brace. Its later lines started at the left margin. diff --git a/crates/nash-report/src/type_/records.rs b/crates/nash-report/src/type_/records.rs index 89f14f61..744b7a48 100644 --- a/crates/nash-report/src/type_/records.rs +++ b/crates/nash-report/src/type_/records.rs @@ -110,7 +110,7 @@ fn nearby(l: &Localizer, field: &str, fields: &[(&str, &ErrorType<'_>)]) -> (Doc ( Doc::stack([ Doc::text(format!("Did you mean `{}`?", first.0)), - Doc::cat([Doc::text("Available fields: "), fields_doc]), + Doc::cat([Doc::text("Available fields: "), Doc::align(fields_doc)]), ]), sorted .iter() diff --git a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__missing_field_alias.snap b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__missing_field_alias.snap index 7bca9ffc..bf59353c 100644 --- a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__missing_field_alias.snap +++ b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__missing_field_alias.snap @@ -14,4 +14,4 @@ nash::type::missing_field help: Did you mean `age`? Available fields: { age : Primitive.int - } + } diff --git a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__record_access_missing_field_typo.snap b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__record_access_missing_field_typo.snap index c3e56f31..52a110e0 100644 --- a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__record_access_missing_field_typo.snap +++ b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__record_access_missing_field_typo.snap @@ -14,5 +14,5 @@ nash::type::mismatch help: Did you mean `name`? Available fields: { name : Primitive.string - , age : Primitive.int - } + , age : Primitive.int + } diff --git a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__record_update_unknown_field.snap b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__record_update_unknown_field.snap index 15832b61..990566f0 100644 --- a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__record_update_unknown_field.snap +++ b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__record_update_unknown_field.snap @@ -13,4 +13,4 @@ nash::type::mismatch help: Did you mean `name`? Available fields: { name : Primitive.string - } + } diff --git a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_record_access.snap b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_record_access.snap index 5fa7f3b6..54ea0396 100644 --- a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_record_access.snap +++ b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__source_pipeline_record_access.snap @@ -14,4 +14,4 @@ nash::type::missing_field help: Did you mean `age`? Available fields: { age : A - } + } diff --git a/crates/nash-solve/tests/snapshots/inference__nominal_record_missing_field_errors.snap b/crates/nash-solve/tests/snapshots/inference__nominal_record_missing_field_errors.snap index cde1cc80..6fc525eb 100644 --- a/crates/nash-solve/tests/snapshots/inference__nominal_record_missing_field_errors.snap +++ b/crates/nash-solve/tests/snapshots/inference__nominal_record_missing_field_errors.snap @@ -15,4 +15,4 @@ nash::type::missing_field help: Did you mean `x`? Available fields: { x : int - } + } diff --git a/crates/nash-solve/tests/snapshots/inference__recovery_field_failures_block_dependent_traits_and_keep_independent_traits-2.snap b/crates/nash-solve/tests/snapshots/inference__recovery_field_failures_block_dependent_traits_and_keep_independent_traits-2.snap index 0029769e..a5ccbd2e 100644 --- a/crates/nash-solve/tests/snapshots/inference__recovery_field_failures_block_dependent_traits_and_keep_independent_traits-2.snap +++ b/crates/nash-solve/tests/snapshots/inference__recovery_field_failures_block_dependent_traits_and_keep_independent_traits-2.snap @@ -16,7 +16,7 @@ nash::type::missing_field help: Did you mean `a`? Available fields: { a : unit - } + } nash::type::missing_impl From 5655782b2686abb979fda1157722dd10c4728b19 Mon Sep 17 00:00:00 2001 From: microproofs Date: Fri, 16 Oct 2026 15:12:41 +0700 Subject: [PATCH 23/24] refactor(constrain): carry the tests scope on record field constraints Constraint::TestScope wrapped each module test so that the walker set a test_scope flag while it solved the test, and DeferredField copied the flag to choose between tables.test_fields and tables.fields. The scope is a lexical fact the generator already knows, so the walker no longer keeps state for it. Rtv, the generator's lexical environment, becomes a struct with the rigid variables and a tests flag, and constrain_test starts from Rtv::tests(). Constraint::Record and Constraint::Field carry tests, set from Rtv at the accessor, access and update sites, and from pattern::State (empty_state(tests)) at record patterns. The solver reads the flag from the constraint. TestScope and Solver::test_scope are removed, so the constraint language is Elm's plus SaveType. Field visibility is unchanged and no snapshot changes. The new test_imports_grant_field_visibility_to_every_field_form_in_tests covers the accessor, update and pattern forms in both scopes; its snapshot was recorded before this change. Signed-off-by: microproofs --- .../changesets/field-constraint-test-scope.md | 6 ++ crates/nash-constrain/src/expression.rs | 85 +++++++++++++------ crates/nash-constrain/src/pattern.rs | 7 +- crates/nash-constrain/src/type_.rs | 7 +- crates/nash-solve/src/solve.rs | 28 ++---- ...sibility_to_every_field_form_in_tests.snap | 37 ++++++++ crates/nash-solve/tests/testing.rs | 83 +++++++++++------- 7 files changed, 169 insertions(+), 84 deletions(-) create mode 100644 .sampo/changesets/field-constraint-test-scope.md create mode 100644 crates/nash-solve/tests/snapshots/testing__imports_grant_field_visibility_to_every_field_form_in_tests.snap diff --git a/.sampo/changesets/field-constraint-test-scope.md b/.sampo/changesets/field-constraint-test-scope.md new file mode 100644 index 00000000..bee584b3 --- /dev/null +++ b/.sampo/changesets/field-constraint-test-scope.md @@ -0,0 +1,6 @@ +--- +cargo/nash-constrain: minor +cargo/nash-solve: patch +--- + +Record on each record-field constraint whether it comes from a module test, in place of the `Constraint::TestScope` wrapper. `Constraint::Record` and `Constraint::Field` gain a `tests` field, `TestScope` is removed, and `pattern::State` and `pattern::empty_state` take the flag. Field visibility is unchanged: fields that only a tests-block import makes visible are visible in tests and nowhere else. diff --git a/crates/nash-constrain/src/expression.rs b/crates/nash-constrain/src/expression.rs index 57d7282d..66f829ec 100644 --- a/crates/nash-constrain/src/expression.rs +++ b/crates/nash-constrain/src/expression.rs @@ -24,8 +24,27 @@ use crate::type_::{self, Constraint, Definition, Type, exists, mk_flex_var, name use crate::union_find::{UnionFind, Variable}; /// Elm's `RTV`: rigid type variables introduced by enclosing type -/// annotations, shared with nested annotations. -pub type Rtv<'a> = instantiate::FreeVars<'a>; +/// annotations, shared with nested annotations. Nash also records whether +/// the expression is in a module test, where tests-block imports make more +/// labeled constructors visible. +#[derive(Clone, Default)] +pub struct Rtv<'a> { + vars: instantiate::FreeVars<'a>, + tests: bool, +} + +impl Rtv<'_> { + pub fn new() -> Self { + Self::default() + } + + fn tests() -> Self { + Self { + tests: true, + ..Self::default() + } + } +} type Exp<'a> = Expected<'a, &'a Type<'a>>; @@ -153,6 +172,7 @@ pub fn constrain<'a>( record: record_type, field, field_type, + tests: rtv.tests, }, Constraint::Equal( region, @@ -187,6 +207,7 @@ pub fn constrain<'a>( record: record_type, field: field.value, field_type, + tests: rtv.tests, }, Constraint::Equal( region, @@ -328,7 +349,7 @@ fn constrain_lambda<'a>( tipe, result_type, state, - } = constrain_args(bump, uf, args); + } = constrain_args(bump, uf, args, rtv.tests); let body_con = constrain(bump, uf, rtv, body, Expected::NoExpectation(result_type)); @@ -738,7 +759,13 @@ fn constrain_case_branch<'a>( p_expect: PExpected<'a, &'a Type<'a>>, b_expect: Exp<'a>, ) -> Constraint<'a> { - let state = pattern::add(bump, uf, branch.pattern, p_expect, pattern::empty_state()); + let state = pattern::add( + bump, + uf, + branch.pattern, + p_expect, + pattern::empty_state(rtv.tests), + ); let body_con = constrain(bump, uf, rtv, branch.body, b_expect); @@ -839,6 +866,7 @@ fn constrain_update<'a>( region, context: type_::FieldContext::Update { record: name }, record: record_type, + tests: rtv.tests, }); } for field in fields { @@ -862,6 +890,7 @@ fn constrain_update<'a>( record: record_type, field: field.field.value, field_type, + tests: rtv.tests, }); } cons.push(Constraint::Equal( @@ -939,7 +968,7 @@ fn constrain_destruct<'a>( uf, pattern_ast, PExpected::NoExpectation(pattern_type), - pattern::empty_state(), + pattern::empty_state(rtv.tests), ); let expr_con = constrain( @@ -1003,7 +1032,7 @@ pub fn constrain_method<'a>( constrain_definition(bump, uf, &Rtv::new(), def, Constraint::True, false) } -/// Nash-only module test scope. Elm has no source-level test declarations. +/// Nash-only: a module test. Elm has no source-level test declarations. pub fn constrain_test<'a>( bump: &'a Bump, uf: &mut UnionFind<'a>, @@ -1013,7 +1042,7 @@ pub fn constrain_test<'a>( let binder = type_::Binder::Named(test.name); let mut flex_vars = Vec::new(); let mut prefix = Vec::new(); - let mut state = pattern::empty_state(); + let mut state = pattern::empty_state(true); for via in test.binders { let element_var = mk_flex_var(uf); @@ -1040,7 +1069,7 @@ pub fn constrain_test<'a>( prefix.push(constrain( bump, uf, - &Rtv::new(), + &Rtv::tests(), via.generator, Expected::FromContext(via.generator.region, Context::TestGenerator, generator), )); @@ -1056,7 +1085,7 @@ pub fn constrain_test<'a>( let body = constrain( bump, uf, - &Rtv::new(), + &Rtv::tests(), test.body, Expected::FromContext(test.region, Context::TestBody, unit), ); @@ -1071,7 +1100,7 @@ pub fn constrain_test<'a>( header_con: bump.alloc(reversed_and(bump, state.rev_cons)), body_con: bump.alloc(body), }); - Constraint::TestScope(bump.alloc(Constraint::Let { + Constraint::Let { declarations: &[], given: &[], binder: Some(binder), @@ -1085,7 +1114,7 @@ pub fn constrain_test<'a>( header: &[], header_con: bump.alloc(c_and(bump, prefix)), body_con: bump.alloc(Constraint::True), - })) + } } fn constrain_definition<'a>( @@ -1103,7 +1132,7 @@ fn constrain_definition<'a>( tipe, result_type, state, - } = constrain_args(bump, uf, args); + } = constrain_args(bump, uf, args, rtv.tests); let expr_con = constrain(bump, uf, rtv, body, Expected::NoExpectation(result_type)); @@ -1172,7 +1201,7 @@ fn constrain_definition<'a>( result_type, ); let expr_con = constrain(bump, uf, &new_rtv, body, expected); - let given = instantiate::from_src_context(bump, &new_rtv, context); + let given = instantiate::from_src_context(bump, &new_rtv.vars, context); Constraint::Let { declarations: &[], @@ -1217,7 +1246,7 @@ fn make_rigids<'a>( ) -> (Vec<(&'a str, Variable)>, Rtv<'a>) { let mut new_names: Vec<&'a str> = free_vars .iter() - .filter(|name| !rtv.contains_key(*name)) + .filter(|name| !rtv.vars.contains_key(*name)) .copied() .collect(); new_names.sort_unstable(); @@ -1229,7 +1258,7 @@ fn make_rigids<'a>( let mut new_rtv = rtv.clone(); for (name, var) in &new_rigids { - new_rtv.insert(name, bump.alloc(Type::VarN(*var))); + new_rtv.vars.insert(name, bump.alloc(Type::VarN(*var))); } (new_rigids, new_rtv) @@ -1273,7 +1302,7 @@ pub fn constrain_recursive_defs<'a>( tipe, result_type, state, - } = constrain_args(bump, uf, args); + } = constrain_args(bump, uf, args, rtv.tests); let expr_con = constrain(bump, uf, rtv, body, Expected::NoExpectation(result_type)); @@ -1356,7 +1385,7 @@ pub fn constrain_recursive_defs<'a>( body_con: bump.alloc(expr_con), }; - let given = instantiate::from_src_context(bump, &new_rtv, context); + let given = instantiate::from_src_context(bump, &new_rtv.vars, context); // Elm prepends each def's rigids: latest def first, names // sorted within a def. @@ -1442,8 +1471,9 @@ fn constrain_args<'a>( bump: &'a Bump, uf: &mut UnionFind<'a>, args: &[&Located>], + tests: bool, ) -> Args<'a> { - args_help(bump, uf, args, pattern::empty_state()) + args_help(bump, uf, args, pattern::empty_state(tests)) } fn args_help<'a>( @@ -1505,10 +1535,10 @@ fn constrain_typed_args<'a>( src_result_type: &Located>, annotation: &Located>, ) -> TypedArgs<'a> { - let mut state = pattern::empty_state(); + let mut state = pattern::empty_state(rtv.tests); for (index, arg) in args.iter().enumerate() { - let arg_type = instantiate::from_src_type(bump, rtv, arg.typ); + let arg_type = instantiate::from_src_type(bump, &rtv.vars, arg.typ); let expected = PExpected::FromContext( arg.pattern.region, PContext::TypedArg(name, index, annotation.region), @@ -1517,11 +1547,11 @@ fn constrain_typed_args<'a>( state = pattern::add(bump, uf, arg.pattern, expected, state); } - let result_type = instantiate::from_src_type(bump, rtv, src_result_type); + let result_type = instantiate::from_src_type(bump, &rtv.vars, src_result_type); // Nash-only: retain an annotated alias around the whole function. Splitting // arguments can otherwise expand an alias that has trait implementations. - let tipe = instantiate::from_src_type(bump, rtv, annotation); + let tipe = instantiate::from_src_type(bump, &rtv.vars, annotation); TypedArgs { tipe, @@ -1540,7 +1570,10 @@ mod node_tests { let bump = Bump::new(); let mut uf = UnionFind::new(); let captured = name_to_rigid(&mut uf, "captured"); - let rtv = Rtv::from([("captured", &*bump.alloc(Type::VarN(captured)))]); + let rtv = Rtv { + vars: instantiate::FreeVars::from([("captured", &*bump.alloc(Type::VarN(captured)))]), + tests: false, + }; let var = |name| &*bump.alloc(Located::at_zero(nash_ast::Type::Var(name))); let (z, cap, a) = (var("z"), var("captured"), var("a")); let result = &*bump.alloc(Located::at_zero(nash_ast::Type::App { @@ -1676,7 +1709,7 @@ mod node_tests { &mut uf, pattern, PExpected::NoExpectation(expected), - pattern::empty_state(), + pattern::empty_state(false), ); let annotations: Vec<_> = state .rev_cons @@ -1729,9 +1762,7 @@ mod node_tests { uses(header_con, nodes); uses(body_con, nodes); } - Constraint::SaveType { constraint, .. } | Constraint::TestScope(constraint) => { - uses(constraint, nodes) - } + Constraint::SaveType { constraint, .. } => uses(constraint, nodes), _ => {} } } diff --git a/crates/nash-constrain/src/pattern.rs b/crates/nash-constrain/src/pattern.rs index 202c1ec7..f1850b09 100644 --- a/crates/nash-constrain/src/pattern.rs +++ b/crates/nash-constrain/src/pattern.rs @@ -14,19 +14,22 @@ use crate::union_find::{UnionFind, Variable}; /// Elm's `Pattern.State`. Constraints are stored in reverse order so that /// adding one is O(1); callers reverse when building the final `CLet`. +/// `tests` marks a pattern in a module test (see `Constraint::Field`). pub struct State<'a> { pub headers: Header<'a>, pub vars: Vec, pub rev_cons: Vec>, + pub tests: bool, } pub type Header<'a> = BTreeMap<&'a str, Located<&'a Type<'a>>>; -pub fn empty_state<'a>() -> State<'a> { +pub fn empty_state<'a>(tests: bool) -> State<'a> { State { headers: BTreeMap::new(), vars: Vec::new(), rev_cons: Vec::new(), + tests, } } @@ -162,6 +165,7 @@ pub fn add<'a>( region, context: type_::FieldContext::Pattern, record: record_type, + tests: state.tests, }); } for field in *fields { @@ -178,6 +182,7 @@ pub fn add<'a>( record: record_type, field, field_type, + tests: state.tests, }); } state diff --git a/crates/nash-constrain/src/type_.rs b/crates/nash-constrain/src/type_.rs index 9962a475..5d3679a3 100644 --- a/crates/nash-constrain/src/type_.rs +++ b/crates/nash-constrain/src/type_.rs @@ -66,17 +66,22 @@ pub struct Definition<'a> { /// slices, not owned containers. #[derive(Debug)] pub enum Constraint<'a> { + /// `tests`: the use is in a module test, where tests-block imports make + /// more labeled constructors visible. Record { region: Region, context: FieldContext<'a>, record: &'a Type<'a>, + tests: bool, }, + /// `tests`: as for `Record`. Field { region: Region, context: FieldContext<'a>, record: &'a Type<'a>, field: &'a str, field_type: &'a Type<'a>, + tests: bool, }, True, SaveTheEnvironment, @@ -126,8 +131,6 @@ pub enum Constraint<'a> { typ: &'a Type<'a>, constraint: &'a Constraint<'a>, }, - /// Nash only: module tests see test-only fields. - TestScope(&'a Constraint<'a>), } #[derive(Clone, Copy, Debug)] diff --git a/crates/nash-solve/src/solve.rs b/crates/nash-solve/src/solve.rs index 1be1e6e6..b475dc08 100644 --- a/crates/nash-solve/src/solve.rs +++ b/crates/nash-solve/src/solve.rs @@ -154,7 +154,7 @@ enum CoverageProblem<'a> { #[derive(Clone, Copy)] struct DeferredField<'a> { - test_scope: bool, + tests: bool, region: nash_region::Region, context: type_::FieldContext<'a>, record: Variable, @@ -164,7 +164,6 @@ struct DeferredField<'a> { struct Solver<'a, 'tables> { bump: &'a Bump, tables: &'tables nash_can::environment::Tables<'a>, - test_scope: bool, pools: Vec>, copied: Vec<(Variable, Variable)>, predicates: Store<'a>, @@ -235,7 +234,6 @@ impl<'a, 'tables> Solver<'a, 'tables> { kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), - test_scope: false, } } @@ -275,10 +273,11 @@ impl<'a> Solver<'a, '_> { region, context, record, + tests, } => { let record = self.type_to_variable(uf, rank, record); self.fields.push(DeferredField { - test_scope: self.test_scope, + tests: *tests, region: *region, context: *context, record, @@ -295,12 +294,13 @@ impl<'a> Solver<'a, '_> { record, field, field_type, + tests, } => { let record = self.type_to_variable(uf, rank, record); let field_type = self.type_to_variable(uf, rank, field_type); self.dependencies.field(field_type, record); self.fields.push(DeferredField { - test_scope: self.test_scope, + tests: *tests, region: *region, context: *context, record, @@ -424,14 +424,6 @@ impl<'a> Solver<'a, '_> { } }, - Constraint::TestScope(constraint) => { - let previous = self.test_scope; - self.test_scope = true; - let state = self.solve(uf, env, rank, state, constraint); - self.test_scope = previous; - state - } - Constraint::Let { declarations, given, @@ -1208,7 +1200,7 @@ impl<'a> Solver<'a, '_> { } return true; } - let visible = if field.test_scope { + let visible = if field.tests { &self.tables.test_fields } else { &self.tables.fields @@ -4406,7 +4398,6 @@ mod copy_tests { kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), - test_scope: false, }; let mut uf = UnionFind::new(); let name = bump.alloc(Located::at_zero("value")); @@ -4500,7 +4491,6 @@ mod copy_tests { kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), - test_scope: false, }; let result = solver.solve( &mut uf, @@ -4575,7 +4565,6 @@ mod copy_tests { kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), - test_scope: false, }; let result = solver.solve( &mut uf, @@ -4652,7 +4641,6 @@ mod copy_tests { kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), - test_scope: false, }; let result = solver.solve( &mut uf, @@ -4742,7 +4730,6 @@ mod copy_tests { kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), - test_scope: false, }; let result = solver.solve( &mut uf, @@ -4882,7 +4869,6 @@ mod copy_tests { kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), - test_scope: false, }; let result = solver.solve( &mut uf, @@ -5055,7 +5041,6 @@ mod copy_tests { kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), - test_scope: false, }; let mut uf = UnionFind::new(); let a = bump.alloc(Located::at_zero(CanType::Var("a"))); @@ -5142,7 +5127,6 @@ mod copy_tests { kind_contracts: Default::default(), kind_errors: Vec::new(), fields: Vec::new(), - test_scope: false, }; let mut uf = UnionFind::new(); let result = uf.fresh(make_descriptor(Content::RigidVar("a"))); diff --git a/crates/nash-solve/tests/snapshots/testing__imports_grant_field_visibility_to_every_field_form_in_tests.snap b/crates/nash-solve/tests/snapshots/testing__imports_grant_field_visibility_to_every_field_form_in_tests.snap new file mode 100644 index 00000000..4e1ed006 --- /dev/null +++ b/crates/nash-solve/tests/snapshots/testing__imports_grant_field_visibility_to_every_field_form_in_tests.snap @@ -0,0 +1,37 @@ +--- +source: crates/nash-solve/tests/testing.rs +description: "module Aux exposing (..)\ntype box = Box { value : () }\nboxed = Box { value = () }\n\nmodule Bridge exposing (boxed)\nimport Aux\nboxed = Aux.boxed\n\nmodule Main exposing (..)\nimport Bridge\ntests\n import Aux\n test \"accessor\" = do\n .value Bridge.boxed\n test \"update\" = do\n let b = Bridge.boxed in let _ = { b | value = () } in ()\n test \"pattern\" = do\n let { value } = Bridge.boxed in value\n\nmodule Main exposing (..)\nimport Bridge\nleakAccessor = .value Bridge.boxed\nleakUpdate = let b = Bridge.boxed in { b | value = () }\nleakPattern = let { value } = Bridge.boxed in value\ntests\n import Aux\n test \"visible\" = do\n Bridge.boxed.value\n" +info: diagnostic +--- +nash::type::not_a_record + + × Expected a record, found `Aux.box`. + ╭─[Main.nash:3:16] + 2 │ import Bridge + 3 │ leakAccessor = .value Bridge.boxed + · ───┬── + · ╰── field `value` accessor + 4 │ leakUpdate = let b = Bridge.boxed in { b | value = () } + ╰──── + +nash::type::not_a_record + + × Expected a record, found `Aux.box`. + ╭─[Main.nash:5:19] + 4 │ leakUpdate = let b = Bridge.boxed in { b | value = () } + 5 │ leakPattern = let { value } = Bridge.boxed in value + · ────┬──── + · ╰── field `value` pattern + 6 │ tests + ╰──── + +nash::type::not_a_record + + × Expected a record, found `Aux.box`. + ╭─[Main.nash:4:44] + 3 │ leakAccessor = .value Bridge.boxed + 4 │ leakUpdate = let b = Bridge.boxed in { b | value = () } + · ──┬── + · ╰── field `value` update of `b` + 5 │ leakPattern = let { value } = Bridge.boxed in value + ╰──── diff --git a/crates/nash-solve/tests/testing.rs b/crates/nash-solve/tests/testing.rs index 6cc3b279..f18e5a6e 100644 --- a/crates/nash-solve/tests/testing.rs +++ b/crates/nash-solve/tests/testing.rs @@ -127,16 +127,16 @@ type_error!( "module Main exposing (public)\npublic = ()\ntests\n prop \"type\" =\n let x via () in\n do\n x\n" ); -#[test] -fn test_imports_do_not_grant_field_visibility_to_module_values() { - let aux = - "module Aux exposing (..)\ntype box = Box { value : () }\nboxed = Box { value = () }\n"; - let bridge = "module Bridge exposing (boxed)\nimport Aux\nboxed = Aux.boxed\n"; - let good = "module Main exposing (..)\nimport Bridge\ntests\n import Aux\n test \"visible\" = do\n Bridge.boxed.value\n"; - let bad = "module Main exposing (..)\nimport Bridge\nleak = Bridge.boxed.value\ntests\n import Aux\n test \"visible\" = do\n Bridge.boxed.value\n"; +const FIELD_AUX: &str = + "module Aux exposing (..)\ntype box = Box { value : () }\nboxed = Box { value = () }\n"; +const FIELD_BRIDGE: &str = "module Bridge exposing (boxed)\nimport Aux\nboxed = Aux.boxed\n"; + +/// Solves `good` and `bad` against Aux and Bridge; `good` must type-check. +/// Returns the rendered errors of `bad`. Both import Aux only in tests. +fn test_field_visibility(good: &str, bad: &str) -> String { let bump = Bump::new(); let mut interfaces = literals::literal_interfaces(&bump); - for (name, source) in [("Aux", aux), ("Bridge", bridge)] { + for (name, source) in [("Aux", FIELD_AUX), ("Bridge", FIELD_BRIDGE)] { let parsed = nash_parse::Parser::new(&bump, source).module().unwrap(); let can = nash_can::canonicalize( &bump, @@ -154,7 +154,7 @@ fn test_imports_do_not_grant_field_visibility_to_module_values() { nash_can::from_module(&bump, &can.module, &annotations), ); } - for source in [good, bad] { + let solve = |source: &str| -> Result<(), String> { let parsed = nash_parse::Parser::new(&bump, source).module().unwrap(); let can = nash_can::canonicalize( &bump, @@ -165,27 +165,46 @@ fn test_imports_do_not_grant_field_visibility_to_module_values() { &parsed, ) .unwrap(); - let result = nash_solve::run(&bump, &mut UnionFind::new(), &can.module, &can.tables); - if source == good { - result.unwrap(); - } else { - let errors = result.unwrap_err(); - let localizer = nash_report::localizer::Localizer::from_module(&parsed, &[]); - let text = nash_report::Source::new(source); - let rendered = errors - .iter() - .map(|e| { - nash_report::render_plain( - &nash_report::type_::to_report(&localizer, e), - &text, - "Main.nash", - ) - }) - .collect::>() - .join("\n"); - insta::with_settings!({description => format!("{aux}\n{bridge}\n{good}\n{bad}"), omit_expression => true, info => &"diagnostic"}, { - insta::assert_snapshot!(rendered); - }); - } - } + let Err(errors) = nash_solve::run(&bump, &mut UnionFind::new(), &can.module, &can.tables) + else { + return Ok(()); + }; + let localizer = nash_report::localizer::Localizer::from_module(&parsed, &[]); + let text = nash_report::Source::new(source); + Err(errors + .iter() + .map(|e| { + nash_report::render_plain( + &nash_report::type_::to_report(&localizer, e), + &text, + "Main.nash", + ) + }) + .collect::>() + .join("\n")) + }; + solve(good).unwrap(); + solve(bad).unwrap_err() +} + +#[test] +fn test_imports_do_not_grant_field_visibility_to_module_values() { + let good = "module Main exposing (..)\nimport Bridge\ntests\n import Aux\n test \"visible\" = do\n Bridge.boxed.value\n"; + let bad = "module Main exposing (..)\nimport Bridge\nleak = Bridge.boxed.value\ntests\n import Aux\n test \"visible\" = do\n Bridge.boxed.value\n"; + let rendered = test_field_visibility(good, bad); + insta::with_settings!({description => format!("{FIELD_AUX}\n{FIELD_BRIDGE}\n{good}\n{bad}"), omit_expression => true, info => &"diagnostic"}, { + insta::assert_snapshot!(rendered); + }); +} + +/// The accessor, update, and record pattern forms see the same test-only +/// fields as `.value` access, and stay hidden from module values. +#[test] +fn test_imports_grant_field_visibility_to_every_field_form_in_tests() { + let good = "module Main exposing (..)\nimport Bridge\ntests\n import Aux\n test \"accessor\" = do\n .value Bridge.boxed\n test \"update\" = do\n let b = Bridge.boxed in let _ = { b | value = () } in ()\n test \"pattern\" = do\n let { value } = Bridge.boxed in value\n"; + let bad = "module Main exposing (..)\nimport Bridge\nleakAccessor = .value Bridge.boxed\nleakUpdate = let b = Bridge.boxed in { b | value = () }\nleakPattern = let { value } = Bridge.boxed in value\ntests\n import Aux\n test \"visible\" = do\n Bridge.boxed.value\n"; + let rendered = test_field_visibility(good, bad); + insta::with_settings!({description => format!("{FIELD_AUX}\n{FIELD_BRIDGE}\n{good}\n{bad}"), omit_expression => true, info => &"diagnostic"}, { + insta::assert_snapshot!(rendered); + }); } From d47d27754abacb94275313da7e8f032c65275307 Mon Sep 17 00:00:00 2001 From: microproofs Date: Sat, 24 Oct 2026 14:06:19 +0700 Subject: [PATCH 24/24] refactor: replace search budgets with one compile fuel counter Trait search, overlap checks, superclass entailment, evidence and code generation each had their own work or depth budget. They counted work differently, so a program could pass `nash check` and then fail `nash build` with no location (depth 178 to 255 of a nested `impl C 'a => C (wrap 'a)`). Replace them with one step counter, `nash_ast::fuel`, that the driver installs around each module compile. The command line runs with unlimited fuel. The language server runs with 10,000,000 steps per module, so a looping program reports `nash::type::out_of_fuel` instead of freezing the editor. Cycle detection and the polymorphic recursion error stay. Signed-off-by: microproofs --- .sampo/changesets/compile-fuel.md | 16 ++ .sampo/changesets/depth-limits-256.md | 6 - .../infinite-type-impl-selection.md | 2 +- .../changesets/shared-trait-search-limits.md | 5 - crates/nash-ast/src/fuel.rs | 96 ++++++++++ crates/nash-ast/src/head.rs | 168 ++++++++---------- crates/nash-ast/src/lib.rs | 1 + ..._coverage_tests__cover_impls_outcomes.snap | 4 +- ...t_tests__selection_outcomes_by_policy.snap | 6 +- crates/nash-can/src/entailment.rs | 122 +++++++------ crates/nash-can/src/error.rs | 3 +- crates/nash-can/src/impls.rs | 31 ++-- crates/nash-can/tests/impls.rs | 68 ++++--- ...ports_running_out_of_fuel_at_the_impl.snap | 14 ++ ...ng_out_of_fuel_on_expanding_contexts.snap} | 9 +- crates/nash-cli/src/cmd/build.rs | 4 +- crates/nash-cli/src/cmd/check.rs | 7 +- crates/nash-cli/src/cmd/test.rs | 4 +- crates/nash-codegen/src/build.rs | 38 ++-- crates/nash-codegen/src/build/emission.rs | 40 ++--- crates/nash-codegen/src/build/tests.rs | 10 +- crates/nash-codegen/src/evidence.rs | 147 ++++++--------- crates/nash-codegen/src/evidence/tests.rs | 17 +- crates/nash-constrain/src/error.rs | 3 +- crates/nash-docs/src/project.rs | 4 +- crates/nash-docs/src/tests.rs | 6 +- crates/nash-driver/src/compile.rs | 53 ++++-- .../src/compile/collection_tests.rs | 3 +- crates/nash-driver/src/lib.rs | 5 +- crates/nash-driver/src/project.rs | 4 +- crates/nash-driver/tests/base_traits.rs | 8 +- crates/nash-driver/tests/build.rs | 17 +- crates/nash-driver/tests/bundled_base.rs | 10 +- crates/nash-driver/tests/nested_trace.rs | 4 +- crates/nash-driver/tests/production.rs | 38 ++-- crates/nash-driver/tests/stack.rs | 4 +- crates/nash-driver/tests/support/mod.rs | 4 +- crates/nash-driver/tests/vesting.rs | 4 +- crates/nash-language-server/src/workspace.rs | 35 +++- crates/nash-report/src/canonicalize.rs | 77 ++++---- ...onicalize__branches__superclass_limit.snap | 15 -- ..._coverage__variant_impl_pattern_limit.snap | 14 -- ...calize__coverage__variant_out_of_fuel.snap | 14 ++ crates/nash-report/src/type_.rs | 6 +- ...sh_report__type___tests__out_of_fuel.snap} | 6 +- crates/nash-report/src/type_/tests.rs | 4 +- crates/nash-report/src/type_/traits.rs | 10 +- crates/nash-solve/src/evidence.rs | 101 ++++------- crates/nash-solve/src/occurs.rs | 6 +- crates/nash-solve/src/preds.rs | 9 - crates/nash-solve/src/recovery.rs | 1 + crates/nash-solve/src/resolve.rs | 94 +++------- crates/nash-solve/src/solve.rs | 138 +++++--------- crates/nash-solve/tests/evidence.rs | 32 +--- crates/nash-solve/tests/inference.rs | 56 ++---- ...verage_search_stops_at_the_work_limit.snap | 16 -- ..._impl_context_stops_with_a_diagnostic.snap | 6 +- ..._of_fuel_keeps_unrelated_obligations.snap} | 6 +- docs/diagnostics.md | 4 +- docs/traits.md | 53 ++++-- plans/02-kind-rewrite-audit.md | 6 +- plans/03-traits.md | 17 +- plans/04-representation.md | 2 +- plans/06-diagnostics.md | 4 +- plans/07-codegen.md | 8 +- 65 files changed, 830 insertions(+), 895 deletions(-) create mode 100644 .sampo/changesets/compile-fuel.md delete mode 100644 .sampo/changesets/depth-limits-256.md delete mode 100644 .sampo/changesets/shared-trait-search-limits.md create mode 100644 crates/nash-ast/src/fuel.rs create mode 100644 crates/nash-can/tests/snapshots/impls__overlap_check_reports_running_out_of_fuel_at_the_impl.snap rename crates/nash-can/tests/snapshots/{impls__superclass_resolution_bounds_expanding_contexts.snap => impls__superclass_resolution_reports_running_out_of_fuel_on_expanding_contexts.snap} (55%) delete mode 100644 crates/nash-report/src/snapshots/nash_report__canonicalize__branches__superclass_limit.snap delete mode 100644 crates/nash-report/src/snapshots/nash_report__canonicalize__coverage__variant_impl_pattern_limit.snap create mode 100644 crates/nash-report/src/snapshots/nash_report__canonicalize__coverage__variant_out_of_fuel.snap rename crates/nash-report/src/type_/snapshots/{nash_report__type___tests__impl_resolution_limit.snap => nash_report__type___tests__out_of_fuel.snap} (70%) delete mode 100644 crates/nash-solve/tests/snapshots/inference__coverage_search_stops_at_the_work_limit.snap rename crates/nash-solve/tests/snapshots/{inference__recovery_resolution_limit_keeps_unrelated_obligations.snap => inference__recovery_out_of_fuel_keeps_unrelated_obligations.snap} (88%) diff --git a/.sampo/changesets/compile-fuel.md b/.sampo/changesets/compile-fuel.md new file mode 100644 index 00000000..83635b8f --- /dev/null +++ b/.sampo/changesets/compile-fuel.md @@ -0,0 +1,16 @@ +--- +cargo/nash-ast: minor +cargo/nash-can: minor +cargo/nash-cli: minor +cargo/nash-codegen: minor +cargo/nash-constrain: minor +cargo/nash-docs: patch +cargo/nash-driver: minor +cargo/nash-language-server: minor +cargo/nash-report: minor +cargo/nash-solve: minor +--- + +Replace every separate search budget with one compile fuel counter, `nash_ast::fuel`. Trait resolution, impl overlap checks, superclass entailment, evidence resolution and code generation share it: each search step takes a `tick`, and the driver installs a fresh `Fuel` for each module's compile. `nash check`, `build`, `test` and `docs` run with unlimited fuel, so programs that the old fixed limits rejected now compile, such as an impl context that rewraps its argument used at 200 nested types. The language server runs with 10 million steps per module, so an editor gives up on a looping program after a second or two instead of freezing. + +Running out of fuel is one error kind, `COMPILATION STEP LIMIT` (`nash::type::out_of_fuel`), replacing `ImplResolutionLimit` (`nash::type::impl_resolution_limit`), `ImplPatternLimit` (`nash::names::impl_pattern_limit`), the superclass search limit, and the code generation specialization, evidence and recursion normalization limits. The solver reports it at the use that needed the search, canonicalization at the impl being checked, and code generation as a plain error. `nash_driver::build`, `build_with` and `test_with` take a `Fuel` argument, re-exported as `nash_driver::Fuel`. diff --git a/.sampo/changesets/depth-limits-256.md b/.sampo/changesets/depth-limits-256.md deleted file mode 100644 index 6ae90a8d..00000000 --- a/.sampo/changesets/depth-limits-256.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -cargo/nash-ast: patch -cargo/nash-codegen: patch ---- - -Raise the trait search depth limit (`nash_ast::head::DEPTH_LIMIT`) and the specialization type depth limit from 128 to 256. diff --git a/.sampo/changesets/infinite-type-impl-selection.md b/.sampo/changesets/infinite-type-impl-selection.md index 63dc0857..0424e7cc 100644 --- a/.sampo/changesets/infinite-type-impl-selection.md +++ b/.sampo/changesets/infinite-type-impl-selection.md @@ -2,4 +2,4 @@ cargo/nash-solve: patch --- -Do not select an impl for a trait constraint whose argument is an infinite type; the occurs check of the binding reports the type, as in Elm. Two impls that are disjoint on finite types can both match an infinite type, which crashed the compiler, and an impl that matches it at every depth gave a false impl-resolution-limit error. +Do not select an impl for a trait constraint whose argument is an infinite type; the occurs check of the binding reports the type, as in Elm. Two impls that are disjoint on finite types can both match an infinite type, which crashed the compiler, and an impl that matches it at every depth gave a false step-limit error. diff --git a/.sampo/changesets/shared-trait-search-limits.md b/.sampo/changesets/shared-trait-search-limits.md deleted file mode 100644 index eee57c09..00000000 --- a/.sampo/changesets/shared-trait-search-limits.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -cargo/nash-ast: minor ---- - -Add `nash_ast::head::WORK_LIMIT` and `nash_ast::head::DEPTH_LIMIT`, the one definition of the trait search limits. Canonicalization, inference and code generation now use them. diff --git a/crates/nash-ast/src/fuel.rs b/crates/nash-ast/src/fuel.rs new file mode 100644 index 00000000..171a8c41 --- /dev/null +++ b/crates/nash-ast/src/fuel.rs @@ -0,0 +1,96 @@ +//! The one step counter every compiler search draws from. +//! +//! Impl contexts need not shrink, so trait resolution, overlap checks and code +//! generation can loop on a program that is accepted syntactically. Instead of +//! a budget per search, the driver installs one `Fuel` around each module's +//! compile, and every search loop calls [`tick`]. A pass over an existing type +//! that cannot run away on its own pays with [`charge`], so the steps track +//! time even when the types grow. The command-line tools run `Unlimited`; the +//! language server runs `Limited` so an editor never freezes on a looping +//! program. +//! +//! The counter is thread-local so no signature carries it. That is sound only +//! while the installed section runs on one thread and never awaits; the driver +//! installs it inside its dedicated compiler thread. With nothing installed the +//! fuel is `Unlimited`. +use std::cell::Cell; + +/// How many steps a compile may take. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Fuel { + Unlimited, + Limited(u64), +} + +/// The installed fuel ran out. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OutOfFuel; + +thread_local! { + static REMAINING: Cell = const { Cell::new(Fuel::Unlimited) }; +} + +/// Spend one step. +#[inline] +pub fn tick() -> Result<(), OutOfFuel> { + REMAINING.with(|remaining| match remaining.get() { + Fuel::Unlimited => Ok(()), + Fuel::Limited(0) => Err(OutOfFuel), + Fuel::Limited(steps) => { + remaining.set(Fuel::Limited(steps - 1)); + Ok(()) + } + }) +} + +/// Pay for `steps` of work that cannot run away on its own, such as one pass +/// over an existing type. Running out is not reported here: the next `tick` +/// fails, because an empty counter stays empty. +#[inline] +pub fn charge(steps: usize) { + REMAINING.with(|remaining| { + if let Fuel::Limited(left) = remaining.get() { + remaining.set(Fuel::Limited(left.saturating_sub(steps as u64))); + } + }); +} + +/// The fuel left on this thread. +pub fn remaining() -> Fuel { + REMAINING.with(Cell::get) +} + +/// Run `work` with a fresh counter of `fuel` on this thread, then restore the +/// counter that was installed before, even if `work` panics. +pub fn run(fuel: Fuel, work: impl FnOnce() -> T) -> T { + struct Restore(Fuel); + impl Drop for Restore { + fn drop(&mut self) { + REMAINING.with(|remaining| remaining.set(self.0)); + } + } + let _restore = Restore(REMAINING.with(|remaining| remaining.replace(fuel))); + work() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn limited_fuel_runs_out_and_the_previous_counter_returns() { + assert_eq!(tick(), Ok(())); + run(Fuel::Limited(2), || { + assert_eq!(tick(), Ok(())); + assert_eq!(tick(), Ok(())); + assert_eq!(tick(), Err(OutOfFuel)); + assert_eq!(remaining(), Fuel::Limited(0)); + }); + run(Fuel::Limited(3), || { + charge(5); + assert_eq!(remaining(), Fuel::Limited(0)); + assert_eq!(tick(), Err(OutOfFuel)); + }); + assert_eq!(remaining(), Fuel::Unlimited); + } +} diff --git a/crates/nash-ast/src/head.rs b/crates/nash-ast/src/head.rs index a4c7aca3..9e3f7ad1 100644 --- a/crates/nash-ast/src/head.rs +++ b/crates/nash-ast/src/head.rs @@ -2,17 +2,11 @@ use std::collections::BTreeMap; use crate::Type; +use crate::fuel::{OutOfFuel, tick}; use crate::primitives::{Repr, ReprSet}; use crate::{Head, HeadCon, QualifiedName}; use nash_region::Located; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Limit; - -// Impl contexts need not decrease, so every trait search has a budget. -pub const WORK_LIMIT: usize = 16_384; -pub const DEPTH_LIMIT: usize = 256; - pub enum Match { Yes(T), No, @@ -23,12 +17,7 @@ pub trait Types<'a> { type Node: Copy; fn in_class(&mut self, node: Self::Node, class: ReprSet) -> Match<()>; fn constructor(&mut self, node: Self::Node, expected: HeadCon<'a>) -> Match>; - fn equal( - &mut self, - first: Self::Node, - second: Self::Node, - remaining: &mut usize, - ) -> Result, Limit>; + fn equal(&mut self, first: Self::Node, second: Self::Node) -> Result, OutOfFuel>; } /// Canonical types whose variables are rigid: a variable equals only itself @@ -105,13 +94,8 @@ impl<'a> Types<'a> for Canonical<'_, 'a> { fn constructor(&mut self, node: Self::Node, expected: HeadCon<'a>) -> Match> { constructor_view(node, expected, false) } - fn equal( - &mut self, - first: Self::Node, - second: Self::Node, - remaining: &mut usize, - ) -> Result, Limit> { - equal_views(first, second, remaining, false) + fn equal(&mut self, first: Self::Node, second: Self::Node) -> Result, OutOfFuel> { + equal_views(first, second, false) } } @@ -123,13 +107,8 @@ impl<'a> Types<'a> for Open<'_, 'a> { fn constructor(&mut self, node: Self::Node, expected: HeadCon<'a>) -> Match> { constructor_view(node, expected, true) } - fn equal( - &mut self, - first: Self::Node, - second: Self::Node, - remaining: &mut usize, - ) -> Result, Limit> { - equal_views(first, second, remaining, true) + fn equal(&mut self, first: Self::Node, second: Self::Node) -> Result, OutOfFuel> { + equal_views(first, second, true) } } @@ -151,13 +130,12 @@ fn constructor_view<'a>( fn equal_views<'a>( first: &'a Located>, second: &'a Located>, - remaining: &mut usize, open: bool, -) -> Result, Limit> { +) -> Result, OutOfFuel> { let mut pending = vec![(first, second)]; let mut deferred = false; while let Some((first, second)) = pending.pop() { - step(remaining)?; + tick()?; let (a, aa) = canonical_view(first); let (b, ba) = canonical_view(second); if a == b && aa.len() == ba.len() { @@ -175,11 +153,6 @@ fn equal_views<'a>( }) } -pub fn step(remaining: &mut usize) -> Result<(), Limit> { - *remaining = remaining.checked_sub(1).ok_or(Limit)?; - Ok(()) -} - pub fn children<'p, 'a>(head: &'p Head<'a>) -> Vec<&'p Head<'a>> { match head { Head::Named { args, .. } | Head::Tuple(args) => args.iter().collect(), @@ -193,8 +166,7 @@ pub fn matches<'a, T: Types<'a>>( heads: &[Head<'a>], arguments: &[T::Node], variable_count: usize, - remaining: &mut usize, -) -> Result>, Limit> { +) -> Result>, OutOfFuel> { if heads.len() != arguments.len() { return Ok(Match::No); } @@ -202,12 +174,12 @@ pub fn matches<'a, T: Types<'a>>( let mut pending: Vec<_> = heads.iter().zip(arguments.iter().copied()).collect(); let mut deferred = false; while let Some((head, argument)) = pending.pop() { - step(remaining)?; + tick()?; match head { Head::Var { index, repr } => { let binding = &mut bindings[usize::from(*index)]; if let Some(previous) = *binding { - match types.equal(previous, argument, remaining)? { + match types.equal(previous, argument)? { Match::Yes(()) => {} Match::No => return Ok(Match::No), Match::Deferred => deferred = true, @@ -276,14 +248,13 @@ pub fn select_impl<'h, 'a: 'h, T: Types<'a>, I>( types: &mut T, candidates: impl IntoIterator], usize, I)>, arguments: &[T::Node], - remaining: &mut usize, policy: SelectPolicy, -) -> Result, Limit> { +) -> Result, OutOfFuel> { let mut first: Option<&'h [Head<'a>]> = None; let mut selected = None; let mut deferred = false; for (heads, variable_count, info) in candidates { - match matches(types, heads, arguments, variable_count, remaining)? { + match matches(types, heads, arguments, variable_count)? { Match::No => {} Match::Deferred => deferred = true, Match::Yes(bound) => { @@ -351,21 +322,20 @@ pub struct CoveredImpl { /// Select an impl for every admitted representation cell of the rigid /// variables at representation-tested head positions. Only such positions /// create dimensions. The limit comes first: every subject needs a given of -/// `trait_` at it, so a signature never hides the trait that selects. One -/// budget pays for the discovery, the cells and every selection. +/// `trait_` at it, so a signature never hides the trait that selects. Every +/// step of the discovery, the cells and every selection draws from the fuel. pub fn cover_impls<'h, 'a: 'h, T: CoverageTypes<'a>, I: Copy>( types: &mut T, trait_: QualifiedName<'a>, candidates: &[(&'h [Head<'a>], usize, I)], arguments: &[T::Node], - remaining: &mut usize, -) -> Result, Limit> { +) -> Result, OutOfFuel> { let mut subjects = BTreeMap::new(); let mut deferred = false; for (heads, _, _) in candidates { let mut pending: Vec<_> = heads.iter().zip(arguments.iter().copied()).collect(); while let Some((head, argument)) = pending.pop() { - step(remaining)?; + tick()?; match head { Head::Var { repr, .. } if repr.is_all() => {} Head::Var { repr, .. } => match types.coverage_subject(argument, *repr) { @@ -407,7 +377,7 @@ pub fn cover_impls<'h, 'a: 'h, T: CoverageTypes<'a>, I: Copy>( for cell in cells { for repr in [Repr::Big, Repr::Const, Repr::Term] { if admitted.contains(repr) { - step(remaining)?; + tick()?; let mut cell: Vec<_> = cell.clone(); cell.push((subject, repr)); next.push(cell); @@ -423,7 +393,6 @@ pub fn cover_impls<'h, 'a: 'h, T: CoverageTypes<'a>, I: Copy>( types, candidates.iter().copied(), arguments, - remaining, SelectPolicy::Defer, ); types.set_coverage_assumptions(&[]); @@ -452,10 +421,9 @@ type Substitution<'p, 'a> = BTreeMap<(bool, u16), Term<'p, 'a>>; fn resolve<'p, 'a>( mut term: Term<'p, 'a>, substitution: &Substitution<'p, 'a>, - remaining: &mut usize, -) -> Result, Limit> { +) -> Result, OutOfFuel> { while let Head::Var { index, .. } = term.pattern { - step(remaining)?; + tick()?; let Some(next) = substitution.get(&(term.side, *index)) else { break; }; @@ -470,9 +438,8 @@ pub fn overlaps( left: &[Head<'_>], right: &[Head<'_>], repr_of: &dyn Fn(&Head<'_>) -> Option, - remaining: &mut usize, -) -> Result { - unifiable(left, right, repr_of, remaining, true) +) -> Result { + unifiable(left, right, repr_of, true) } /// Equality within one impl preserves variables shared between its heads. @@ -480,18 +447,16 @@ pub fn can_equal( left: &[Head<'_>], right: &[Head<'_>], repr_of: &dyn Fn(&Head<'_>) -> Option, - remaining: &mut usize, -) -> Result { - unifiable(left, right, repr_of, remaining, false) +) -> Result { + unifiable(left, right, repr_of, false) } fn unifiable( left: &[Head<'_>], right: &[Head<'_>], repr_of: &dyn Fn(&Head<'_>) -> Option, - remaining: &mut usize, freshen: bool, -) -> Result { +) -> Result { if left.len() != right.len() { return Ok(false); } @@ -514,9 +479,9 @@ fn unifiable( }) .collect(); while let Some((left, right)) = pending.pop() { - step(remaining)?; - let left = resolve(left, &substitution, remaining)?; - let right = resolve(right, &substitution, remaining)?; + tick()?; + let left = resolve(left, &substitution)?; + let right = resolve(right, &substitution)?; if let Head::Var { index, repr } = left.pattern { let mine = classes.get(&(left.side, *index)).copied().unwrap_or(*repr); match right.pattern { @@ -541,8 +506,8 @@ fn unifiable( } let mut occurs = vec![right]; while let Some(term) = occurs.pop() { - let term = resolve(term, &substitution, remaining)?; - step(remaining)?; + let term = resolve(term, &substitution)?; + tick()?; if matches!(term.pattern, Head::Var { index: other, .. } if variable == (term.side, *other)) { return Ok(false); @@ -609,7 +574,7 @@ mod select_tests { fn constructor(&mut self, _: (), _: HeadCon<'a>) -> Match> { unreachable!("candidates are variable heads") } - fn equal(&mut self, _: (), _: (), _: &mut usize) -> Result, Limit> { + fn equal(&mut self, _: (), _: ()) -> Result, OutOfFuel> { unreachable!("each candidate has one variable") } } @@ -620,8 +585,8 @@ mod select_tests { fn select( outcomes: &[Outcome], policy: SelectPolicy, - budget: usize, - ) -> Result, Limit> { + fuel: u64, + ) -> Result, OutOfFuel> { let heads: Vec<_> = CLASSES .iter() .map(|repr| { @@ -643,20 +608,22 @@ mod select_tests { .take(outcomes.len()) .enumerate() .map(|(index, heads)| (heads.as_slice(), 1, index)); - select_impl(&mut types, candidates, &[()], &mut { budget }, policy) + crate::fuel::run(crate::fuel::Fuel::Limited(fuel), || { + select_impl(&mut types, candidates, &[()], policy) + }) } use Outcome::{Deferred, No, Yes}; use SelectPolicy::{Defer, Exact}; - fn render(policy: SelectPolicy, result: Result, Limit>) -> String { + fn render(policy: SelectPolicy, result: Result, OutOfFuel>) -> String { match result { Ok(ImplSelection::Selected { info, .. }) => format!("selects impl {}", info + 1), // Inference waits for its variables; nothing binds an open type. Ok(ImplSelection::Deferred) if policy == Defer => "waits".to_owned(), Ok(ImplSelection::Deferred) => "undecided".to_owned(), Ok(ImplSelection::Missing) => "no impl".to_owned(), - Err(Limit) => "work limit".to_owned(), + Err(OutOfFuel) => "out of fuel".to_owned(), } } @@ -677,7 +644,7 @@ mod select_tests { #[test] fn selection_outcomes_by_policy() { - let scenarios: &[(&[Outcome], usize)] = &[ + let scenarios: &[(&[Outcome], u64)] = &[ (&[], 100), (&[No, No], 100), (&[No, Yes, No], 100), @@ -687,17 +654,17 @@ mod select_tests { (&[No, Yes], 1), ]; let mut output = String::new(); - for (outcomes, budget) in scenarios { - let budget_note = if *budget == 1 { - " (budget for one step)" + for (outcomes, fuel) in scenarios { + let fuel_note = if *fuel == 1 { + " (fuel for one step)" } else { "" }; output.push_str(&format!( - "{}{budget_note}\n inference: {}\n entailment and evidence: {}\n", + "{}{fuel_note}\n inference: {}\n entailment and evidence: {}\n", describe(outcomes), - render(Defer, select(outcomes, Defer, *budget)), - render(Exact, select(outcomes, Exact, *budget)), + render(Defer, select(outcomes, Defer, *fuel)), + render(Exact, select(outcomes, Exact, *fuel)), )); } insta::with_settings!({ @@ -759,7 +726,7 @@ mod coverage_tests { _ => Match::No, } } - fn equal(&mut self, _: Arg, _: Arg, _: &mut usize) -> Result, Limit> { + fn equal(&mut self, _: Arg, _: Arg) -> Result, OutOfFuel> { unreachable!("no head repeats a variable") } } @@ -795,13 +762,16 @@ mod coverage_tests { const PAIR_LITTLE_BIG: [Head<'static>; 1] = [Head::Tuple(&[var(0, LITTLE), var(1, BIG)])]; const PAIR_LITTLE_LITTLE: [Head<'static>; 1] = [Head::Tuple(&[var(0, LITTLE), var(1, LITTLE)])]; + /// Enough fuel that no scenario but the deliberately short one runs out. + const PLENTY: u64 = 1 << 20; + fn search( impls: &[(&'static str, &[Head<'static>])], argument: Arg, given: &[u8], deferred: bool, - budget: usize, - ) -> (Result, Limit>, usize) { + fuel: u64, + ) -> (Result, OutOfFuel>, u64) { let trait_ = QualifiedName { home: crate::ModuleName { package: None, @@ -824,9 +794,13 @@ mod coverage_tests { deferred, assumptions: Vec::new(), }; - let mut remaining = budget; - let result = cover_impls(&mut types, trait_, &candidates, &[argument], &mut remaining); - (result, budget - remaining) + crate::fuel::run(crate::fuel::Fuel::Limited(fuel), || { + let result = cover_impls(&mut types, trait_, &candidates, &[argument]); + let crate::fuel::Fuel::Limited(left) = crate::fuel::remaining() else { + unreachable!("limited fuel stays limited") + }; + (result, fuel - left) + }) } fn cell(assumptions: &[(u8, Repr)]) -> String { @@ -837,7 +811,7 @@ mod coverage_tests { .join(", ") } - fn render(result: Result, Limit>) -> String { + fn render(result: Result, OutOfFuel>) -> String { match result { Ok(Coverage::NotApplicable) => "not applicable".to_owned(), Ok(Coverage::Unstated(subject)) => { @@ -851,7 +825,7 @@ mod coverage_tests { .map(|covered| format!("{} selects {}", cell(&covered.assumptions), covered.info)) .collect::>() .join("; "), - Err(Limit) => "work limit".to_owned(), + Err(OutOfFuel) => "out of fuel".to_owned(), } } @@ -866,7 +840,7 @@ mod coverage_tests { ]; let element = Arg::Subject(0); let both = Arg::Pair(0, 1); - let (_, pairs_cost) = search(pairs, both, &[0, 1], false, WORK_LIMIT); + let (_, pairs_cost) = search(pairs, both, &[0, 1], false, PLENTY); let scenarios = [ ( "Big and Little impls, given at 'a", @@ -874,7 +848,7 @@ mod coverage_tests { element, &[0][..], false, - WORK_LIMIT, + PLENTY, ), ( "only a Big impl, given at 'a", @@ -882,7 +856,7 @@ mod coverage_tests { element, &[0], false, - WORK_LIMIT, + PLENTY, ), ( "Big and Little impls, no given", @@ -890,7 +864,7 @@ mod coverage_tests { element, &[], false, - WORK_LIMIT, + PLENTY, ), ( "only a Big impl, no given (the limit comes first)", @@ -898,7 +872,7 @@ mod coverage_tests { element, &[], false, - WORK_LIMIT, + PLENTY, ), ( "Big and Little impls, the argument can still change", @@ -906,7 +880,7 @@ mod coverage_tests { element, &[0], true, - WORK_LIMIT, + PLENTY, ), ( "pair impls, given at 'a and 'b", @@ -914,7 +888,7 @@ mod coverage_tests { both, &[0, 1], false, - WORK_LIMIT, + PLENTY, ), ( "pair impls, given at 'a only", @@ -922,7 +896,7 @@ mod coverage_tests { both, &[0], false, - WORK_LIMIT, + PLENTY, ), ( "pair impls, one step less than the whole search", @@ -934,13 +908,13 @@ mod coverage_tests { ), ]; let mut output = String::new(); - for (name, impls, argument, given, deferred, budget) in scenarios { - let (result, _) = search(impls, argument, given, deferred, budget); + for (name, impls, argument, given, deferred, fuel) in scenarios { + let (result, _) = search(impls, argument, given, deferred, fuel); output.push_str(&format!("{name}\n {}\n", render(result))); } insta::with_settings!({ description => "Coverage of a wanted predicate whose arguments are rigid variables. \ - Big covers Big; Little covers Const and Term. One budget pays for subject \ + Big covers Big; Little covers Const and Term. One fuel counter pays for subject \ discovery, the cells, and every selection.", omit_expression => true, }, { diff --git a/crates/nash-ast/src/lib.rs b/crates/nash-ast/src/lib.rs index a7c92af3..0d94365b 100644 --- a/crates/nash-ast/src/lib.rs +++ b/crates/nash-ast/src/lib.rs @@ -1,5 +1,6 @@ mod evidence; pub use evidence::same_type; +pub mod fuel; pub mod head; pub mod primitives; diff --git a/crates/nash-ast/src/snapshots/nash_ast__head__coverage_tests__cover_impls_outcomes.snap b/crates/nash-ast/src/snapshots/nash_ast__head__coverage_tests__cover_impls_outcomes.snap index b4e38f00..f8f31c3c 100644 --- a/crates/nash-ast/src/snapshots/nash_ast__head__coverage_tests__cover_impls_outcomes.snap +++ b/crates/nash-ast/src/snapshots/nash_ast__head__coverage_tests__cover_impls_outcomes.snap @@ -1,6 +1,6 @@ --- source: crates/nash-ast/src/head.rs -description: "Coverage of a wanted predicate whose arguments are rigid variables. Big covers Big; Little covers Const and Term. One budget pays for subject discovery, the cells, and every selection." +description: "Coverage of a wanted predicate whose arguments are rigid variables. Big covers Big; Little covers Const and Term. One fuel counter pays for subject discovery, the cells, and every selection." --- Big and Little impls, given at 'a 'a Big selects big; 'a Const selects little; 'a Term selects little @@ -17,4 +17,4 @@ pair impls, given at 'a and 'b pair impls, given at 'a only needs the trait at 'b pair impls, one step less than the whole search - work limit + out of fuel diff --git a/crates/nash-ast/src/snapshots/nash_ast__head__select_tests__selection_outcomes_by_policy.snap b/crates/nash-ast/src/snapshots/nash_ast__head__select_tests__selection_outcomes_by_policy.snap index 57bf12db..20c4390d 100644 --- a/crates/nash-ast/src/snapshots/nash_ast__head__select_tests__selection_outcomes_by_policy.snap +++ b/crates/nash-ast/src/snapshots/nash_ast__head__select_tests__selection_outcomes_by_policy.snap @@ -20,6 +20,6 @@ undecided, matches undecided, does not match inference: waits entailment and evidence: undecided -does not match, matches (budget for one step) - inference: work limit - entailment and evidence: work limit +does not match, matches (fuel for one step) + inference: out of fuel + entailment and evidence: out of fuel diff --git a/crates/nash-can/src/entailment.rs b/crates/nash-can/src/entailment.rs index 20c49cb6..39d66cb3 100644 --- a/crates/nash-can/src/entailment.rs +++ b/crates/nash-can/src/entailment.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; use bumpalo::Bump; -use nash_ast::head::{DEPTH_LIMIT, WORK_LIMIT}; +use nash_ast::fuel::{OutOfFuel, tick}; use nash_ast::{Pred, QualifiedName, Type}; use nash_region::Located; @@ -13,7 +13,25 @@ use crate::environment::{ImplInfo, Tables}; pub enum Failure { Missing, Cycle, - Limit, +} + +/// Why a search stopped: the wanted predicate failed, or the compile ran out of fuel. +#[derive(Clone, Copy)] +enum Stop { + Failed(Failure), + OutOfFuel, +} + +impl From for Stop { + fn from(failure: Failure) -> Self { + Self::Failed(failure) + } +} + +impl From for Stop { + fn from(OutOfFuel: OutOfFuel) -> Self { + Self::OutOfFuel + } } #[derive(Clone, Copy, PartialEq, Eq)] @@ -41,19 +59,14 @@ type Substitution<'a> = BTreeMap<&'a str, &'a Term<'a>>; struct Resolver<'t, 'a> { bump: &'a Bump, tables: &'t Tables<'a>, - remaining: usize, } impl<'a> Resolver<'_, 'a> { - fn canonical( - &mut self, - term: &'a Term<'a>, - depth: usize, - ) -> Result<&'a Located>, Failure> { - self.step(depth)?; + fn canonical(&mut self, term: &'a Term<'a>) -> Result<&'a Located>, Stop> { + tick()?; let mut args = Vec::new(); for arg in term.args { - args.push(self.canonical(arg, depth + 1)?); + args.push(self.canonical(arg)?); } let args = self.bump.alloc_slice_fill_iter(args); let typ = match term.con { @@ -89,21 +102,13 @@ impl<'a> Resolver<'_, 'a> { }; Ok(self.bump.alloc(Located::at_zero(typ))) } - fn step(&mut self, depth: usize) -> Result<(), Failure> { - if depth >= DEPTH_LIMIT || self.remaining == 0 { - return Err(Failure::Limit); - } - self.remaining -= 1; - Ok(()) - } fn term( &mut self, typ: &'a Located>, subst: &Substitution<'a>, - depth: usize, - ) -> Result<&'a Term<'a>, Failure> { - self.step(depth)?; + ) -> Result<&'a Term<'a>, Stop> { + tick()?; let (con, args): (_, Vec<_>) = match &typ.value { Type::Var(name) => { if let Some(term) = subst.get(name) { @@ -143,10 +148,10 @@ impl<'a> Resolver<'_, 'a> { fields.iter().map(|f| f.typ).collect(), ), Type::App { head, args } => { - let head = self.term(head, subst, depth + 1)?; + let head = self.term(head, subst)?; let mut applied = head.args.to_vec(); for arg in *args { - applied.push(self.term(arg, subst, depth + 1)?); + applied.push(self.term(arg, subst)?); } return Ok(self.bump.alloc(Term { con: head.con, @@ -156,7 +161,7 @@ impl<'a> Resolver<'_, 'a> { }; let mut terms = Vec::new(); for arg in args { - terms.push(self.term(arg, subst, depth + 1)?); + terms.push(self.term(arg, subst)?); } Ok(self.bump.alloc(Term { con, @@ -168,11 +173,11 @@ impl<'a> Resolver<'_, 'a> { &mut self, pred: &Pred<'a>, subst: &Substitution<'a>, - ) -> Result, Failure> { - self.step(0)?; + ) -> Result, Stop> { + tick()?; let mut args = Vec::new(); for arg in pred.types() { - args.push(self.term(arg, subst, 0)?); + args.push(self.term(arg, subst)?); } Ok(Predicate { trait_: pred.trait_ref(), @@ -180,8 +185,8 @@ impl<'a> Resolver<'_, 'a> { }) } - fn equal(&mut self, a: Predicate<'a>, b: Predicate<'a>) -> Result { - self.step(0)?; + fn equal(&mut self, a: Predicate<'a>, b: Predicate<'a>) -> Result { + tick()?; if a.trait_ != b.trait_ || a.args.len() != b.args.len() { return Ok(false); } @@ -192,15 +197,15 @@ impl<'a> Resolver<'_, 'a> { .is_some() { for term in left.iter_mut().chain(&mut right) { - let canonical = self.canonical(term, 0)?; + let canonical = self.canonical(term)?; let subject = crate::kinds::representation_subject(self.bump, &self.tables.kinds, canonical); - *term = self.term(subject, &BTreeMap::new(), 0)?; + *term = self.term(subject, &BTreeMap::new())?; } } let mut pending: Vec<_> = left.into_iter().zip(right).collect(); while let Some((a, b)) = pending.pop() { - self.step(0)?; + tick()?; if a.con != b.con || a.args.len() != b.args.len() { return Ok(false); } @@ -209,14 +214,14 @@ impl<'a> Resolver<'_, 'a> { Ok(true) } - fn givens(&mut self, context: &[Pred<'a>]) -> Result>, Failure> { + fn givens(&mut self, context: &[Pred<'a>]) -> Result>, Stop> { let mut pending = Vec::new(); for pred in context { pending.push(self.predicate(pred, &BTreeMap::new())?); } let mut result = Vec::new(); while let Some(pred) = pending.pop() { - self.step(0)?; + tick()?; let mut seen = false; for old in &result { if self.equal(pred, *old)? { @@ -259,8 +264,8 @@ impl<'a> Resolver<'_, 'a> { given: &[Predicate<'a>], wanted: Predicate<'a>, active: &mut Vec>, - ) -> Result<(), Failure> { - self.step(active.len())?; + ) -> Result<(), Stop> { + tick()?; for pred in given { if self.equal(*pred, wanted)? { return Ok(()); @@ -275,7 +280,7 @@ impl<'a> Resolver<'_, 'a> { let args = pred .args .iter() - .map(|arg| self.canonical(arg, 0)) + .map(|arg| self.canonical(arg)) .collect::, _>>()?; class_givens.push(Pred::Implied { trait_, @@ -284,7 +289,7 @@ impl<'a> Resolver<'_, 'a> { } } if let Some(required) = wanted.trait_.and_then(nash_ast::primitives::ReprTrait::of) { - let typ = self.canonical(wanted.args[0], 0)?; + let typ = self.canonical(wanted.args[0])?; return match crate::kinds::in_class( self.bump, &self.tables.kinds, @@ -293,14 +298,14 @@ impl<'a> Resolver<'_, 'a> { &class_givens, ) { nash_ast::head::Match::Yes(()) => Ok(()), - _ => Err(Failure::Missing), + _ => Err(Failure::Missing.into()), }; } if wanted.trait_.is_none() { - let head = self.canonical(wanted.args[0], 0)?; + let head = self.canonical(wanted.args[0])?; let args: Vec<_> = wanted.args[1..] .iter() - .map(|arg| self.canonical(arg, 0)) + .map(|arg| self.canonical(arg)) .collect::>()?; let group = Default::default(); let mut formation = crate::kinds::Formation::new(self.bump, &self.tables.kinds, &group); @@ -313,7 +318,7 @@ impl<'a> Resolver<'_, 'a> { for pred in formation.predicates { let child = self.predicate(&pred, &BTreeMap::new())?; if self.equal(child, wanted)? { - return Err(Failure::Missing); + return Err(Failure::Missing.into()); } self.resolve(given, child, active)?; } @@ -329,8 +334,8 @@ impl<'a> Resolver<'_, 'a> { }; match self.resolve(given, big, active) { Ok(()) => return Ok(()), - Err(Failure::Missing) => {} - Err(reason) => return Err(reason), + Err(Stop::Failed(Failure::Missing)) => {} + Err(stop) => return Err(stop), } } if self.tables.has_reflexive_lift() @@ -351,13 +356,13 @@ impl<'a> Resolver<'_, 'a> { } for pred in active.iter() { if self.equal(*pred, wanted)? { - return Err(Failure::Cycle); + return Err(Failure::Cycle.into()); } } let canonical_args: Vec<_> = wanted .args .iter() - .map(|arg| self.canonical(arg, 0)) + .map(|arg| self.canonical(arg)) .collect::>()?; let candidates = self .tables @@ -369,20 +374,18 @@ impl<'a> Resolver<'_, 'a> { }), candidates, &canonical_args, - &mut self.remaining, nash_ast::head::SelectPolicy::Exact, - ) - .map_err(|_| Failure::Limit)?; + )?; let nash_ast::head::ImplSelection::Selected { info: impl_, arguments, } = selection else { - return Err(Failure::Missing); + return Err(Failure::Missing.into()); }; let mut subst = BTreeMap::new(); for (name, argument) in impl_.variables.iter().zip(arguments) { - subst.insert(*name, self.term(argument, &BTreeMap::new(), 0)?); + subst.insert(*name, self.term(argument, &BTreeMap::new())?); } active.push(wanted); for pred in impl_.context { @@ -414,23 +417,24 @@ pub(crate) fn check<'a>( ) }) .collect(); - let mut resolver = Resolver { - bump, - tables, - remaining: WORK_LIMIT, - }; + let mut resolver = Resolver { bump, tables }; let givens = resolver.givens(impl_.context); for (index, superclass) in trait_.supers.iter().enumerate() { - let checked = (|| { - let givens = givens.as_ref().map_err(|reason| *reason)?; + let checked: Result<(), Stop> = (|| { + let givens = givens.as_ref().map_err(|stop| *stop)?; let mut subst = BTreeMap::new(); for (parameter, typ) in &canonical_subst { - subst.insert(*parameter, resolver.term(typ, &BTreeMap::new(), 0)?); + subst.insert(*parameter, resolver.term(typ, &BTreeMap::new())?); } let wanted = resolver.predicate(superclass, &subst)?; resolver.resolve(givens, wanted, &mut Vec::new()) })(); - if let Err(reason) = checked { + if let Err(stop) = checked { + let Stop::Failed(reason) = stop else { + return Err(vec![Error::OutOfFuel { + region: impl_.region, + }]); + }; return Err(vec![Error::MissingSuperclass { region: impl_.region, trait_: impl_.trait_, diff --git a/crates/nash-can/src/error.rs b/crates/nash-can/src/error.rs index e46ecc7b..69eb3cad 100644 --- a/crates/nash-can/src/error.rs +++ b/crates/nash-can/src/error.rs @@ -59,7 +59,8 @@ pub enum Error<'a> { RecordTypeOutsideAlias { region: Region, }, - ImplPatternLimit { + /// Overlap or superclass search used up the compile's fuel. + OutOfFuel { region: Region, }, NegateWithoutNum { diff --git a/crates/nash-can/src/impls.rs b/crates/nash-can/src/impls.rs index f1a3bd28..d34e419a 100644 --- a/crates/nash-can/src/impls.rs +++ b/crates/nash-can/src/impls.rs @@ -2,7 +2,6 @@ use crate::environment::{Env, TraitInfo, dups}; use crate::error::BadHead; use crate::{Error, kinds, module, types, warning::Warning}; use bumpalo::Bump; -use nash_ast::head::WORK_LIMIT; use nash_ast::{Annotation, Head, Impl, ImplKey, Pred, QualifiedName, Type}; use nash_region::Located; use nash_source::Type as SourceType; @@ -112,22 +111,17 @@ fn insert_impl<'a>( trait_: impl_.trait_, heads: bump.alloc_slice_fill_iter(impl_.heads.iter().map(|h| h.value)), }; - let mut remaining = WORK_LIMIT; for (candidate, first) in table .iter() .filter(|(candidate, _)| candidate.trait_ == key.trait_) { - let overlaps = nash_ast::head::overlaps( - candidate.heads, - key.heads, - &|head| head_repr(kinds, head), - &mut remaining, - ) - .map_err(|_| { - vec![Error::ImplPatternLimit { - region: impl_.region, - }] - })?; + let overlaps = + nash_ast::head::overlaps(candidate.heads, key.heads, &|head| head_repr(kinds, head)) + .map_err(|_| { + vec![Error::OutOfFuel { + region: impl_.region, + }] + })?; if overlaps { return Err(vec![Error::OverlappingImpls { key: bump.alloc(key), @@ -284,14 +278,11 @@ pub(crate) fn canonicalize<'a>( } if trait_ == nash_ast::primitives::lift_trait() && let [left, right] = heads.as_slice() - && nash_ast::head::can_equal( - &[left.value], - &[right.value], - &|head| head_repr(kind_env, head), - &mut { WORK_LIMIT }, - ) + && nash_ast::head::can_equal(&[left.value], &[right.value], &|head| { + head_repr(kind_env, head) + }) .map_err(|_| { - vec![Error::ImplPatternLimit { + vec![Error::OutOfFuel { region: source.region, }] })? diff --git a/crates/nash-can/tests/impls.rs b/crates/nash-can/tests/impls.rs index d20b8141..b5584fe6 100644 --- a/crates/nash-can/tests/impls.rs +++ b/crates/nash-can/tests/impls.rs @@ -3,7 +3,7 @@ use snapshot_support::SnapshotInputs; use bumpalo::Bump; use indoc::indoc; -use nash_ast::head::WORK_LIMIT; +use nash_ast::fuel::{self, Fuel}; #[test] fn inline_impl_bounds_are_retained_for_superclasses() { @@ -45,26 +45,15 @@ fn recursive_overlap_ignores_representation_contexts() { let result = canonicalize(&bump, source).unwrap(); keys.push(*result.tables.impls.keys().next().unwrap()); } - let overlap = |a: usize, b: usize, budget: &mut usize| { - nash_ast::head::overlaps(keys[a].heads, keys[b].heads, &|_| None, budget) - }; + let overlap = + |a: usize, b: usize| nash_ast::head::overlaps(keys[a].heads, keys[b].heads, &|_| None); assert!( - overlap(0, 1, &mut { WORK_LIMIT }).unwrap(), + overlap(0, 1).unwrap(), "representation contexts do not make equal heads disjoint" ); - assert!(overlap(0, 2, &mut { WORK_LIMIT }).unwrap()); - assert!(overlap(1, 2, &mut { WORK_LIMIT }).unwrap()); - assert!( - overlap(0, 0, &mut { WORK_LIMIT }).unwrap(), - "fresh binders preserve overlap" - ); - let mut budget = WORK_LIMIT; - assert!(overlap(0, 0, &mut budget).unwrap()); - let mut exact_budget = WORK_LIMIT - budget; - assert!(exact_budget > 0); - assert!(overlap(0, 0, &mut exact_budget).unwrap()); - assert_eq!(exact_budget, 0); - assert!(overlap(0, 0, &mut 0).is_err()); + assert!(overlap(0, 2).unwrap()); + assert!(overlap(1, 2).unwrap()); + assert!(overlap(0, 0).unwrap(), "fresh binders preserve overlap"); } #[test] @@ -443,13 +432,14 @@ fn superclass_context_uses_given_superclasses() { } #[test] -fn superclass_resolution_bounds_expanding_contexts() { +fn superclass_resolution_reports_running_out_of_fuel_on_expanding_contexts() { let snapshot_inputs = SnapshotInputs::default(); let bump = Bump::new(); - let result = canonicalize( - &bump, - snapshot_inputs.record(indoc!( - " + let result = fuel::run(Fuel::Limited(2_000), || { + canonicalize( + &bump, + snapshot_inputs.record(indoc!( + " module Main exposing (..) trait Eq 'a where eq : 'a -> 'a @@ -460,8 +450,9 @@ fn superclass_resolution_bounds_expanding_contexts() { impl Ord (List 'a) where compare x = x " - )), - ); + )), + ) + }); insta::with_settings!({info => &"diagnostic", description => snapshot_inputs.description(), omit_expression => true}, { insta::assert_snapshot!(snapshot_inputs.errors(&result.unwrap_err())); }); @@ -1161,3 +1152,30 @@ fn superclass_proof_needs_the_split_requirement_named() { insta::assert_snapshot!(snapshot_inputs.results(&results)); }); } + +/// Overlap checks draw from the compile's fuel; running out reports the impl +/// that was being checked. +#[test] +fn overlap_check_reports_running_out_of_fuel_at_the_impl() { + let snapshot_inputs = SnapshotInputs::default(); + let bump = Bump::new(); + let result = fuel::run(Fuel::Limited(1), || { + canonicalize( + &bump, + snapshot_inputs.record(indoc!( + " + module Main exposing (..) + trait Keep 'a where + keep : 'a -> 'a + impl Keep (list 'a) where + keep x = x + impl Keep (list int) where + keep x = x + " + )), + ) + }); + insta::with_settings!({info => &"diagnostic", description => snapshot_inputs.description(), omit_expression => true}, { + insta::assert_snapshot!(snapshot_inputs.errors(&result.unwrap_err())); + }); +} diff --git a/crates/nash-can/tests/snapshots/impls__overlap_check_reports_running_out_of_fuel_at_the_impl.snap b/crates/nash-can/tests/snapshots/impls__overlap_check_reports_running_out_of_fuel_at_the_impl.snap new file mode 100644 index 00000000..d4236d8a --- /dev/null +++ b/crates/nash-can/tests/snapshots/impls__overlap_check_reports_running_out_of_fuel_at_the_impl.snap @@ -0,0 +1,14 @@ +--- +source: crates/nash-can/tests/impls.rs +description: "module Main exposing (..)\ntrait Keep 'a where\n keep : 'a -> 'a\nimpl Keep (list 'a) where\n keep x = x\nimpl Keep (list int) where\n keep x = x\n" +info: diagnostic +--- +nash::type::out_of_fuel + + × Checking this impl needed more compilation steps than the editor allows: + ╭─[src/Main.nash:6:1] + 5 │ keep x = x + 6 │ ╭─▶ impl Keep (list int) where + 7 │ ╰─▶ keep x = x + ╰──── + help: `nash check` has no step limit. Simplify the impl head or its context. diff --git a/crates/nash-can/tests/snapshots/impls__superclass_resolution_bounds_expanding_contexts.snap b/crates/nash-can/tests/snapshots/impls__superclass_resolution_reports_running_out_of_fuel_on_expanding_contexts.snap similarity index 55% rename from crates/nash-can/tests/snapshots/impls__superclass_resolution_bounds_expanding_contexts.snap rename to crates/nash-can/tests/snapshots/impls__superclass_resolution_reports_running_out_of_fuel_on_expanding_contexts.snap index 2df08b22..e275e6ce 100644 --- a/crates/nash-can/tests/snapshots/impls__superclass_resolution_bounds_expanding_contexts.snap +++ b/crates/nash-can/tests/snapshots/impls__superclass_resolution_reports_running_out_of_fuel_on_expanding_contexts.snap @@ -3,15 +3,12 @@ source: crates/nash-can/tests/impls.rs description: "module Main exposing (..)\ntrait Eq 'a where\n eq : 'a -> 'a\ntrait Eq 'a => Ord 'a where\n compare : 'a -> 'a\nimpl Eq (List (List 'a)) => Eq (List 'a) where\n eq x = x\nimpl Ord (List 'a) where\n compare x = x\n" info: diagnostic --- -nash::names::missing_superclass +nash::type::out_of_fuel - × The `Main.Ord` impl for (Primitive.List ('a0 : Big)) does not establish - │ superclass 1: + × Checking this impl needed more compilation steps than the editor allows: ╭─[src/Main.nash:8:1] 7 │ eq x = x 8 │ ╭─▶ impl Ord (List 'a) where 9 │ ╰─▶ compare x = x ╰──── - help: It must also satisfy `Main.Eq (Primitive.List 'a)`. Resolving it exceeded the - search limit because the requirements keep expanding. Add the required impl or - include the necessary constraint in this impl's context. + help: `nash check` has no step limit. Simplify the impl head or its context. diff --git a/crates/nash-cli/src/cmd/build.rs b/crates/nash-cli/src/cmd/build.rs index 66524ed1..ec4743b6 100644 --- a/crates/nash-cli/src/cmd/build.rs +++ b/crates/nash-cli/src/cmd/build.rs @@ -1,5 +1,5 @@ use miette::{IntoDiagnostic, Result}; -use nash_driver::{Database, FileSystemSource, Project, build_graph_production, build_with}; +use nash_driver::{Database, FileSystemSource, Fuel, Project, build_graph_production, build_with}; use std::{path::PathBuf, sync::Arc}; use tokio::sync::Mutex; @@ -104,7 +104,7 @@ impl Args { }) .collect::>() .into_diagnostic()?; - let (report, output) = build_with(db, &graph, &modules, move |solved| { + let (report, output) = build_with(db, &graph, &modules, Fuel::Unlimited, move |solved| { nash_driver::build::build_validators_matching_with(solved, |uri| { configs.get(uri).copied() }) diff --git a/crates/nash-cli/src/cmd/check.rs b/crates/nash-cli/src/cmd/check.rs index 4c4a0f5d..bc82ee75 100644 --- a/crates/nash-cli/src/cmd/check.rs +++ b/crates/nash-cli/src/cmd/check.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use miette::{IntoDiagnostic, Result}; use nash_driver::{ - Database, FileSystemSource, ModuleResult, Project, build, build_graph_with_tests, + Database, FileSystemSource, Fuel, ModuleResult, Project, build, build_graph_with_tests, }; use nash_report::Severity; use tokio::sync::Mutex; @@ -173,6 +173,9 @@ impl Args { ) .await .into_diagnostic()?; - Ok((project.root, build(db, &graph, &modules).await)) + Ok(( + project.root, + build(db, &graph, &modules, Fuel::Unlimited).await, + )) } } diff --git a/crates/nash-cli/src/cmd/test.rs b/crates/nash-cli/src/cmd/test.rs index 6e5d5fc6..5cb4b35c 100644 --- a/crates/nash-cli/src/cmd/test.rs +++ b/crates/nash-cli/src/cmd/test.rs @@ -1,7 +1,7 @@ use std::{path::PathBuf, sync::Arc, time::Instant}; use miette::{IntoDiagnostic, Result}; -use nash_driver::{Database, FileSystemSource, Project, build_graph_with_tests, test_with}; +use nash_driver::{Database, FileSystemSource, Fuel, Project, build_graph_with_tests, test_with}; use tokio::{sync::Mutex, task::spawn_blocking}; use super::build::TraceLevelArg; @@ -138,7 +138,7 @@ impl Args { .into_diagnostic()?; let patterns = self.matches.clone(); let exact = self.exact; - let (report, programs) = test_with(db, &graph, &modules, move |solved| { + let (report, programs) = test_with(db, &graph, &modules, Fuel::Unlimited, move |solved| { nash_driver::build::compile_tests_matching_with( solved, |uri| configs.get(uri).copied(), diff --git a/crates/nash-codegen/src/build.rs b/crates/nash-codegen/src/build.rs index 10246bfb..50463097 100644 --- a/crates/nash-codegen/src/build.rs +++ b/crates/nash-codegen/src/build.rs @@ -1,6 +1,7 @@ //! Reachable, lexical specialization of canonical definitions. use std::collections::{BTreeMap, HashMap}; +use nash_ast::fuel::{OutOfFuel, tick}; use nash_ast::{self as can, *}; use nash_can::environment::Tables; use nash_ir::{ @@ -23,9 +24,6 @@ mod emission; use emission::hoist_strings; pub(crate) use emission::names; -const MAX_SPECIALIZATIONS: usize = 1024; -const MAX_TYPE_DEPTH: usize = 256; - #[derive(Clone, Copy)] pub struct Input<'a, 's> { pub module: &'s can::Module<'a>, @@ -80,10 +78,8 @@ pub enum Error<'a> { RootTypeArguments { expected: usize, actual: usize }, #[error("invalid type instance for {0:?}")] InvalidInstance(NodeId), - #[error( - "specialization exceeded the {MAX_SPECIALIZATIONS}-body or {MAX_TYPE_DEPTH}-level type limit" - )] - SpecializationLimit, + #[error("code generation needed more compilation steps than it was allowed")] + OutOfFuel, #[error("operation needs a concrete runtime layout, got {0}")] RuntimeLayout(Ty<'a>), #[error("missing method body {method} of {trait_:?}")] @@ -99,8 +95,6 @@ pub enum Error<'a> { Resolution(nash_solve::evidence::Failure), #[error("recursive values must be functions")] RecursiveValue, - #[error("recursive function initialization exceeded the 4096-step normalization limit")] - RecursionNormalizationLimit, #[error("invalid constructor or record metadata")] InvalidConstructor, #[error("comptime expression is not closed or could not be assembled: {0}")] @@ -124,7 +118,15 @@ impl<'a> From> for Error<'a> { } impl<'a> From> for Error<'a> { fn from(e: evidence::Error<'a>) -> Self { - Self::Evidence(e) + match e { + evidence::Error::OutOfFuel => Self::OutOfFuel, + e => Self::Evidence(e), + } + } +} +impl From for Error<'_> { + fn from(OutOfFuel: OutOfFuel) -> Self { + Self::OutOfFuel } } impl<'a> From> for Error<'a> { @@ -655,9 +657,7 @@ impl<'a, 'b, 's> Engine<'a, 'b, 's> { if let Some(old) = self.specs.iter().find(|old| old.key == key) { return Ok(old.binder); } - if self.specs.len() >= MAX_SPECIALIZATIONS { - return Err(Error::SpecializationLimit); - } + tick()?; let scheme = self.scheme(template)?; let mut runtime_subst = t.captured.runtime_subst.clone(); for name in scheme.annotation.free_vars { @@ -839,16 +839,14 @@ fn native_type<'a>(arena: &'a Arena, ty: Ty<'a>) -> Result<&'a Located> }))) } fn check_type<'a>(typ: &'a Located>, subst: &Substitution<'a>) -> Result<(), Error<'a>> { - let mut pending = vec![(typ, 0, true)]; - while let Some((t, depth, replace)) = pending.pop() { - if depth > MAX_TYPE_DEPTH { - return Err(Error::SpecializationLimit); - } - let mut push = |t| pending.push((t, depth + 1, replace)); + let mut pending = vec![(typ, true)]; + while let Some((t, replace)) = pending.pop() { + tick()?; + let mut push = |t| pending.push((t, replace)); match &t.value { Type::Var(n) => { if replace && let Some(t) = subst.get(n) { - pending.push((*t, depth + 1, false)); + pending.push((*t, false)); } } Type::Named { args, .. } => { diff --git a/crates/nash-codegen/src/build/emission.rs b/crates/nash-codegen/src/build/emission.rs index 330b05c3..7495a699 100644 --- a/crates/nash-codegen/src/build/emission.rs +++ b/crates/nash-codegen/src/build/emission.rs @@ -68,7 +68,7 @@ impl<'a> Engine<'a, '_, '_> { (spec.binder, spec.value.unwrap()) }) .collect::>(); - body = self.recursive_bindings(&definitions, body, &mut 4096)?; + body = self.recursive_bindings(&definitions, body)?; } else { let spec = &self.specs[selected[component[0]]]; body = self.ir.let_(spec.binder, spec.value.unwrap(), body); @@ -82,12 +82,8 @@ impl<'a> Engine<'a, '_, '_> { &self, definitions: &[(Binder<'a>, &'a Core<'a>)], root: &'a Core<'a>, - remaining: &mut usize, ) -> Result<&'a Core<'a>, Error<'a>> { - if *remaining == 0 { - return Err(Error::RecursionNormalizationLimit); - } - *remaining -= 1; + tick()?; let Some(index) = definitions .iter() .position(|(_, v)| !matches!(v.kind, CoreKind::Lam { .. })) @@ -128,13 +124,10 @@ impl<'a> Engine<'a, '_, '_> { let mut changed = replace(*body); if matches!(value.kind, CoreKind::Lam { .. }) { changed.push((*binder, *value)); - self.recursive_bindings(&changed, root, remaining)? + self.recursive_bindings(&changed, root)? } else if names(value).is_disjoint(&recursive_names) { - self.ir.let_( - *binder, - value, - self.recursive_bindings(&changed, root, remaining)?, - ) + self.ir + .let_(*binder, value, self.recursive_bindings(&changed, root)?) } else { return Err(Error::RecursiveValue); } @@ -146,13 +139,11 @@ impl<'a> Engine<'a, '_, '_> { .iter() .map(|b| (b.binder, self.ir.lam(b.params, b.body))), ); - self.recursive_bindings(&changed, root, remaining)? + self.recursive_bindings(&changed, root)? } CoreKind::Trace { message, body } if names(message).is_disjoint(&recursive_names) => { - self.ir.trace( - message, - self.recursive_bindings(&replace(*body), root, remaining)?, - ) + self.ir + .trace(message, self.recursive_bindings(&replace(*body), root)?) } CoreKind::Case { kind, @@ -164,17 +155,13 @@ impl<'a> Engine<'a, '_, '_> { .iter() .map(|branch| { Ok(Branch { - body: self.recursive_bindings( - &replace(branch.body), - root, - remaining, - )?, + body: self.recursive_bindings(&replace(branch.body), root)?, ..*branch }) }) .collect::, Error<'a>>>()?; let default = default - .map(|body| self.recursive_bindings(&replace(body), root, remaining)) + .map(|body| self.recursive_bindings(&replace(body), root)) .transpose()?; self.ir.case(*kind, scrutinee, &branches, default, root.ty) } @@ -184,11 +171,8 @@ impl<'a> Engine<'a, '_, '_> { let binder = definitions[index].0; let mut rest = definitions.to_vec(); rest.remove(index); - self.ir.let_( - binder, - value, - self.recursive_bindings(&rest, root, remaining)?, - ) + self.ir + .let_(binder, value, self.recursive_bindings(&rest, root)?) } _ => return Err(Error::RecursiveValue), }) diff --git a/crates/nash-codegen/src/build/tests.rs b/crates/nash-codegen/src/build/tests.rs index 2c38a217..7afbff23 100644 --- a/crates/nash-codegen/src/build/tests.rs +++ b/crates/nash-codegen/src/build/tests.rs @@ -690,7 +690,7 @@ fn recursive_function_rhs_preserves_strict_captures_once() { } #[test] -fn growing_native_layouts_stop_at_an_explicit_resource_limit() { +fn growing_native_layouts_run_out_of_fuel() { with_base( indoc::indoc!( r#" @@ -703,10 +703,10 @@ fn growing_native_layouts_stop_at_an_explicit_resource_limit() { "# ), |arena, build, root| { - assert!(matches!( - build.compile(arena, root, None, TraceConfig::default()), - Err(Error::SpecializationLimit) - )); + let compiled = nash_ast::fuel::run(nash_ast::fuel::Fuel::Limited(5_000), || { + build.compile(arena, root, None, TraceConfig::default()) + }); + assert!(matches!(compiled, Err(Error::OutOfFuel))); }, ); } diff --git a/crates/nash-codegen/src/evidence.rs b/crates/nash-codegen/src/evidence.rs index 861143c8..e1ca48ff 100644 --- a/crates/nash-codegen/src/evidence.rs +++ b/crates/nash-codegen/src/evidence.rs @@ -6,7 +6,7 @@ //! the impl. Runtime layout demands are a separate part of specialization identity. use std::collections::HashMap; -use nash_ast::head::{DEPTH_LIMIT, WORK_LIMIT}; +use nash_ast::fuel::{OutOfFuel, tick}; use nash_ast::{AliasType, Evidence, Head, ImplRef, NodeId, Pred, QualifiedName, Type, primitives}; use nash_can::environment::Tables; use nash_plutus::arena::Arena; @@ -37,12 +37,18 @@ pub enum Error<'a> { NoEvidence, #[error("evidence still contains a given or superclass projection")] UnresolvedEvidence, - #[error("evidence normalization exceeded its work or depth limit")] - Limit, + #[error("code generation ran out of compilation steps")] + OutOfFuel, #[error("cannot resolve superclass: {0:?}")] Resolution(nash_solve::evidence::Failure), } +impl From for Error<'_> { + fn from(OutOfFuel: OutOfFuel) -> Self { + Self::OutOfFuel + } +} + /// Executable choice only: type and representation layout demands belong in a /// separate key. Representation proofs are omitted from implementation children. #[derive(Debug, PartialEq, Eq, Hash)] @@ -60,12 +66,7 @@ pub fn ground<'a>( subst: &Substitution<'a>, givens: &HashMap]>, ) -> Result, Error<'a>> { - Grounder { - arena, - tables, - remaining: WORK_LIMIT, - } - .one(evidence, subst, givens, 0) + Grounder { arena, tables }.one(evidence, subst, givens) } pub fn ground_arguments<'a>( @@ -75,23 +76,14 @@ pub fn ground_arguments<'a>( subst: &Substitution<'a>, givens: &HashMap]>, ) -> Result<&'a [Evidence<'a>], Error<'a>> { - Grounder { - arena, - tables, - remaining: WORK_LIMIT, - } - .arguments(evidence, subst, givens, 0) + Grounder { arena, tables }.arguments(evidence, subst, givens) } pub fn executable_identity<'a>( evidence: &Evidence<'a>, ) -> Result, Error<'a>> { - fn visit<'a>( - evidence: &Evidence<'a>, - remaining: &mut usize, - depth: usize, - ) -> Result, Error<'a>> { - step(remaining, depth)?; + fn visit<'a>(evidence: &Evidence<'a>) -> Result, Error<'a>> { + tick()?; Ok(match evidence { Evidence::Repr { .. } => ExecutableEvidence::Erased, Evidence::ReflexiveLift { .. } => ExecutableEvidence::Identity, @@ -101,10 +93,10 @@ pub fn executable_identity<'a>( type_args, args, } => { - check_heads(remaining, impl_.key.heads, type_args.len(), depth)?; + check_heads(impl_.key.heads, type_args.len())?; let mut children = Vec::new(); for arg in *args { - let child = visit(arg, remaining, depth + 1)?; + let child = visit(arg)?; if child != ExecutableEvidence::Erased { children.push(child); } @@ -116,32 +108,15 @@ pub fn executable_identity<'a>( } }) } - let mut remaining = WORK_LIMIT; - visit(evidence, &mut remaining, 0) -} - -fn step<'a>(remaining: &mut usize, depth: usize) -> Result<(), Error<'a>> { - if depth > DEPTH_LIMIT || *remaining == 0 { - return Err(Error::Limit); - } - *remaining -= 1; - Ok(()) + visit(evidence) } // Impl keys participate in recursive ordering and hashing. Check them before // looking them up or copying them into an executable key. -fn check_heads<'a>( - remaining: &mut usize, - heads: &[Head<'a>], - variables: usize, - depth: usize, -) -> Result<(), Error<'a>> { - if heads.len() > *remaining { - return Err(Error::Limit); - } - let mut pending: Vec<_> = heads.iter().map(|head| (head, depth)).collect(); - while let Some((head, depth)) = pending.pop() { - step(remaining, depth)?; +fn check_heads<'a>(heads: &[Head<'a>], variables: usize) -> Result<(), Error<'a>> { + let mut pending: Vec<_> = heads.iter().collect(); + while let Some(head) = pending.pop() { + tick()?; match head { Head::Var { index, .. } if usize::from(*index) >= variables => { return Err(Error::MalformedImpl); @@ -151,14 +126,11 @@ fn check_heads<'a>( if matches!(head, Head::Tuple(_)) && args.len() < 2 { return Err(Error::MalformedImpl); } - if args.len() > *remaining { - return Err(Error::Limit); - } - pending.extend(args.iter().map(|arg| (arg, depth + 1))); + pending.extend(args.iter()); } Head::Function(from, to) => { - pending.push((from, depth + 1)); - pending.push((to, depth + 1)); + pending.push(from); + pending.push(to); } } } @@ -168,7 +140,6 @@ fn check_heads<'a>( struct Grounder<'a, 't> { arena: &'a Arena, tables: &'t Tables<'a>, - remaining: usize, } impl<'a> Grounder<'a, '_> { @@ -177,9 +148,8 @@ impl<'a> Grounder<'a, '_> { evidence: &Evidence<'a>, subst: &Substitution<'a>, givens: &HashMap]>, - depth: usize, ) -> Result, Error<'a>> { - step(&mut self.remaining, depth)?; + tick()?; Ok(match evidence { Evidence::Given { binder, index } => { let values = givens.get(binder).ok_or(Error::MissingGiven(*binder))?; @@ -187,10 +157,10 @@ impl<'a> Grounder<'a, '_> { binder: *binder, index: *index, })?; - return self.one(value, subst, givens, depth + 1); + return self.one(value, subst, givens); } Evidence::Super { of, index } => { - let of = self.one(of, subst, givens, depth + 1)?; + let of = self.one(of, subst, givens)?; // A known representation proof entails its builtin parents // even when the carried type is erased and remains open. if let Evidence::Repr { trait_, typ } = of { @@ -207,19 +177,13 @@ impl<'a> Grounder<'a, '_> { typ, }); } - let predicate = self.super_predicate(&of, *index, depth + 1)?; + let predicate = self.super_predicate(&of, *index)?; self.validate_predicate(predicate)?; let resolved = nash_solve::evidence::resolve(self.arena.as_bump(), self.tables, &predicate) - .map_err(|error| { - if error.reason == nash_solve::evidence::Failure::Limit { - Error::Limit - } else { - Error::Resolution(error.reason) - } - })? + .map_err(resolution_error)? .ok_or(Error::NoEvidence)?; - return self.one(&resolved, &Substitution::new(), &HashMap::new(), depth + 1); + return self.one(&resolved, &Substitution::new(), &HashMap::new()); } Evidence::Specialize { trait_, args } => { // Method B: the specialization key holds these types, so each @@ -234,15 +198,9 @@ impl<'a> Grounder<'a, '_> { }; let resolved = nash_solve::evidence::resolve(self.arena.as_bump(), self.tables, &predicate) - .map_err(|error| { - if error.reason == nash_solve::evidence::Failure::Limit { - Error::Limit - } else { - Error::Resolution(error.reason) - } - })? + .map_err(resolution_error)? .ok_or(Error::NoEvidence)?; - return self.one(&resolved, &Substitution::new(), &HashMap::new(), depth + 1); + return self.one(&resolved, &Substitution::new(), &HashMap::new()); } Evidence::Repr { trait_, typ } => Evidence::Repr { trait_: *trait_, @@ -259,7 +217,7 @@ impl<'a> Grounder<'a, '_> { type_args, args, } => { - check_heads(&mut self.remaining, impl_.key.heads, type_args.len(), depth)?; + check_heads(impl_.key.heads, type_args.len())?; let info = self .tables .impls @@ -283,7 +241,7 @@ impl<'a> Grounder<'a, '_> { Evidence::Impl { impl_: *impl_, type_args: self.arena.alloc_slice_copy(&types), - args: self.arguments(args, subst, givens, depth + 1)?, + args: self.arguments(args, subst, givens)?, } } }) @@ -294,14 +252,10 @@ impl<'a> Grounder<'a, '_> { evidence: &[Evidence<'a>], subst: &Substitution<'a>, givens: &HashMap]>, - depth: usize, ) -> Result<&'a [Evidence<'a>], Error<'a>> { - if evidence.len() > self.remaining { - return Err(Error::Limit); - } let values = evidence .iter() - .map(|e| self.one(e, subst, givens, depth)) + .map(|e| self.one(e, subst, givens)) .collect::, _>>()?; Ok(self.arena.alloc_slice_fill_iter(values)) } @@ -326,14 +280,14 @@ impl<'a> Grounder<'a, '_> { typ: &'a Located>, subst: &Substitution<'a>, ) -> Result<(), Error<'a>> { - let mut pending = vec![(typ, 0, true)]; - while let Some((typ, depth, replace)) = pending.pop() { - step(&mut self.remaining, depth)?; - let mut push = |child| pending.push((child, depth + 1, replace)); + let mut pending = vec![(typ, true)]; + while let Some((typ, replace)) = pending.pop() { + tick()?; + let mut push = |child| pending.push((child, replace)); match &typ.value { Type::Var(name) => { if replace && let Some(value) = subst.get(name) { - pending.push((*value, depth + 1, false)); + pending.push((*value, false)); } } Type::App { head, args } => { @@ -388,7 +342,6 @@ impl<'a> Grounder<'a, '_> { &mut self, evidence: &Evidence<'a>, index: u16, - depth: usize, ) -> Result, Error<'a>> { let (trait_, args) = match evidence { Evidence::StructuralEq { typ } => (primitives::eq_trait(), vec![*typ]), @@ -400,7 +353,7 @@ impl<'a> Grounder<'a, '_> { .key .heads .iter() - .map(|head| self.head_type(head, type_args, depth)) + .map(|head| self.head_type(head, type_args)) .collect::, _>>()?; (impl_.key.trait_, args) } @@ -446,9 +399,8 @@ impl<'a> Grounder<'a, '_> { &mut self, head: &Head<'a>, variables: &[&'a Located>], - depth: usize, ) -> Result<&'a Located>, Error<'a>> { - step(&mut self.remaining, depth)?; + tick()?; let typ = match head { Head::Var { index, .. } => { return variables @@ -459,7 +411,7 @@ impl<'a> Grounder<'a, '_> { Head::Named { reference, args } => { let args = args .iter() - .map(|head| self.head_type(head, variables, depth + 1)) + .map(|head| self.head_type(head, variables)) .collect::, _>>()?; Type::Named { reference: *reference, @@ -472,7 +424,7 @@ impl<'a> Grounder<'a, '_> { } let args = args .iter() - .map(|head| self.head_type(head, variables, depth + 1)) + .map(|head| self.head_type(head, variables)) .collect::, _>>()?; Type::Tuple { first: args[0], @@ -481,8 +433,8 @@ impl<'a> Grounder<'a, '_> { } } Head::Function(from, to) => Type::Lambda { - from: self.head_type(from, variables, depth + 1)?, - to: self.head_type(to, variables, depth + 1)?, + from: self.head_type(from, variables)?, + to: self.head_type(to, variables)?, }, }; Ok(self.arena.alloc(Located::at_zero(typ))) @@ -508,5 +460,14 @@ impl<'a> Grounder<'a, '_> { } } +/// A superclass or specialization lookup fails for a reason of its own, or because +/// the compile ran out of fuel. +fn resolution_error(error: nash_solve::evidence::Error<'_>) -> Error<'_> { + match error.reason { + nash_solve::evidence::Failure::OutOfFuel => Error::OutOfFuel, + reason => Error::Resolution(reason), + } +} + #[cfg(test)] mod tests; diff --git a/crates/nash-codegen/src/evidence/tests.rs b/crates/nash-codegen/src/evidence/tests.rs index 653a7a83..55cd0355 100644 --- a/crates/nash-codegen/src/evidence/tests.rs +++ b/crates/nash-codegen/src/evidence/tests.rs @@ -294,7 +294,8 @@ fn malformed_slots_and_open_types_return_errors() { } #[test] -fn cycles_and_deep_types_stop_before_recursive_allocation() { +fn running_out_of_fuel_stops_before_recursive_allocation() { + use nash_ast::fuel::{self, Fuel}; let arena = Arena::new(); let tables = fixture(&arena); let binder = NodeId::def(arena.alloc(Located::at_zero("f"))); @@ -303,21 +304,21 @@ fn cycles_and_deep_types_stop_before_recursive_allocation() { &*arena.alloc_slice_fill_iter([Evidence::Given { binder, index: 0 }]), )]); assert!(matches!( - ground( + fuel::run(Fuel::Limited(1000), || ground( &arena, &tables, &Evidence::Given { binder, index: 0 }, &Substitution::new(), &givens - ), - Err(Error::Limit) + )), + Err(Error::OutOfFuel) )); let mut typ = named(&arena, "int", &[]); - for _ in 0..=DEPTH_LIMIT { + for _ in 0..100 { typ = named(&arena, "list", arena.alloc_slice_copy(&[typ])); } assert!(matches!( - ground( + fuel::run(Fuel::Limited(50), || ground( &arena, &tables, &Evidence::Repr { @@ -326,8 +327,8 @@ fn cycles_and_deep_types_stop_before_recursive_allocation() { }, &Substitution::new(), &HashMap::new() - ), - Err(Error::Limit) + )), + Err(Error::OutOfFuel) )); } diff --git a/crates/nash-constrain/src/error.rs b/crates/nash-constrain/src/error.rs index d760da93..84999415 100644 --- a/crates/nash-constrain/src/error.rs +++ b/crates/nash-constrain/src/error.rs @@ -94,7 +94,8 @@ pub enum Error<'a> { available: &'a [&'a [nash_ast::Head<'a>]], because: &'a [Requirement<'a>], }, - ImplResolutionLimit { + /// The compile ran out of fuel while resolving this requirement. + OutOfFuel { region: Region, name: &'a str, trait_: nash_ast::QualifiedName<'a>, diff --git a/crates/nash-docs/src/project.rs b/crates/nash-docs/src/project.rs index 35f7f715..1e64ab15 100644 --- a/crates/nash-docs/src/project.rs +++ b/crates/nash-docs/src/project.rs @@ -2,7 +2,7 @@ use crate::{DocsWarning, ModuleDocs, extract, primitives}; use nash_config::Config; use nash_driver::{ - Database, DriverError, FileSystemSource, Project, build_graph_production, build_with, + Database, DriverError, FileSystemSource, Fuel, Project, build_graph_production, build_with, bundled_base, }; use std::{ @@ -71,7 +71,7 @@ pub async fn build(input: Input<'_>) -> Result { let graph = build_graph_production(db.clone(), &origins.keys().cloned().collect::>()).await?; let selected_roots = roots.clone(); - let (compiler, extracted) = build_with(db, &graph, &origins, move |solved| { + let (compiler, extracted) = build_with(db, &graph, &origins, Fuel::Unlimited, move |solved| { solved .modules .iter() diff --git a/crates/nash-docs/src/tests.rs b/crates/nash-docs/src/tests.rs index 2ee8a4d2..5a0f739b 100644 --- a/crates/nash-docs/src/tests.rs +++ b/crates/nash-docs/src/tests.rs @@ -1,5 +1,7 @@ use super::*; -use nash_driver::{Database, InMemorySource, build_graph_production, build_with, bundled_base}; +use nash_driver::{ + Database, Fuel, InMemorySource, build_graph_production, build_with, bundled_base, +}; use std::sync::Arc; use tokio::sync::Mutex; use url::Url; @@ -13,7 +15,7 @@ async fn documented(source: &str) -> Extraction { let graph = build_graph_production(db.clone(), &origins.keys().cloned().collect::>()) .await .unwrap(); - let (result, docs) = build_with(db, &graph, &origins, move |solved| { + let (result, docs) = build_with(db, &graph, &origins, Fuel::Unlimited, move |solved| { let module = solved.modules.iter().find(|m| m.uri == uri).unwrap(); let source = nash_parse::Parser::new(solved.store, module.source) .module() diff --git a/crates/nash-driver/src/compile.rs b/crates/nash-driver/src/compile.rs index e14cc792..985c26a8 100644 --- a/crates/nash-driver/src/compile.rs +++ b/crates/nash-driver/src/compile.rs @@ -11,6 +11,7 @@ use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; use bumpalo::Bump; +use nash_ast::fuel::{self, Fuel}; use nash_can::Interface; use tokio::sync::Mutex; use url::Url; @@ -120,14 +121,19 @@ struct CompileOutput { /// /// The async part only fetches sources; the CPU-bound compilation runs on a /// compiler thread (`stack::run`) behind tokio's blocking pool, so no executor -/// worker is ever stalled. +/// worker is ever stalled. Each module compiles with its own counter of +/// `fuel`; a module that runs out fails with a step-limit report and blocks +/// its dependents. /// `origins` must contain every module in the graph, including applications. pub async fn build( db: Arc>, graph: &DepGraph, origins: &crate::ModuleOrigins, + fuel: Fuel, ) -> BuildResult { - build_with_policy(db, graph, origins, false, |_| ()).await.0 + build_with_policy(db, graph, origins, fuel, false, |_| ()) + .await + .0 } /// Finish a successful frontend build while its original canonical arena and @@ -137,13 +143,14 @@ pub async fn build_with( db: Arc>, graph: &DepGraph, origins: &crate::ModuleOrigins, + fuel: Fuel, finish: F, ) -> (BuildResult, Option) where R: Send + 'static, F: for<'a> FnOnce(Solved<'a>) -> R + Send + 'static, { - build_with_policy(db, graph, origins, true, finish).await + build_with_policy(db, graph, origins, fuel, true, finish).await } /// Compile tests and finish while canonical nodes and solved evidence remain alive. @@ -151,19 +158,21 @@ pub async fn test_with( db: Arc>, graph: &DepGraph, origins: &crate::ModuleOrigins, + fuel: Fuel, finish: F, ) -> (BuildResult, Option) where R: Send + 'static, F: for<'a> FnOnce(Solved<'a>) -> R + Send + 'static, { - build_with_policy(db, graph, origins, false, finish).await + build_with_policy(db, graph, origins, fuel, false, finish).await } async fn build_with_policy( db: Arc>, graph: &DepGraph, origins: &crate::ModuleOrigins, + fuel: Fuel, exclude_tests: bool, finish: F, ) -> (BuildResult, Option) @@ -193,6 +202,7 @@ where build_sync_with_policy( sources, &edges, + fuel, exclude_tests, test_modules.as_ref(), finish, @@ -230,7 +240,7 @@ fn build_sync_with_edges_and( edges: &HashMap>, finish: impl for<'a> FnOnce(Solved<'a>) -> R, ) -> (BuildResult, Option) { - build_sync_with_policy(sources, edges, false, None, finish) + build_sync_with_policy(sources, edges, Fuel::Unlimited, false, None, finish) } fn build_sync_with_policy( @@ -240,6 +250,7 @@ fn build_sync_with_policy( Result, )>, edges: &HashMap>, + fuel: Fuel, exclude_tests: bool, test_modules: Option<&std::collections::HashSet>, finish: impl for<'a> FnOnce(Solved<'a>) -> R, @@ -277,14 +288,16 @@ fn build_sync_with_policy( ); continue; } - let (output, compiled) = compile_module( - uri, - package.as_ref(), - source, - &store, - &interfaces, - exclude_tests || test_modules.is_some_and(|roots| !roots.contains(uri)), - ); + let (output, compiled) = fuel::run(fuel, || { + compile_module( + uri, + package.as_ref(), + source, + &store, + &interfaces, + exclude_tests || test_modules.is_some_and(|roots| !roots.contains(uri)), + ) + }); if let Some((interface, module)) = compiled { public_interfaces.insert( uri.clone(), @@ -304,9 +317,11 @@ fn build_sync_with_policy( .count(); let output = if total == success { - Some(finish(Solved { - store: &store, - modules: solved.into_values().collect(), + Some(fuel::run(fuel, || { + finish(Solved { + store: &store, + modules: solved.into_values().collect(), + }) })) } else { None @@ -754,6 +769,7 @@ mod tests { db, &graph, &graph.order.iter().cloned().map(|uri| (uri, None)).collect(), + Fuel::Unlimited, ) .await; assert_eq!(result.total, 3); @@ -780,6 +796,7 @@ mod tests { db, &graph, &graph.order.iter().cloned().map(|uri| (uri, None)).collect(), + Fuel::Unlimited, ) .await; @@ -814,6 +831,7 @@ mod tests { db, &graph, &graph.order.iter().cloned().map(|uri| (uri, None)).collect(), + Fuel::Unlimited, ) .await; @@ -873,6 +891,7 @@ main = Utils.pong Primitive.True db, &graph, &graph.order.iter().cloned().map(|uri| (uri, None)).collect(), + Fuel::Unlimited, ) .await; @@ -901,6 +920,7 @@ mod trait_tests { db, &graph, &graph.order.iter().cloned().map(|uri| (uri, None)).collect(), + Fuel::Unlimited, ) .await } @@ -984,6 +1004,7 @@ mod kind_tests { db, &graph, &graph.order.iter().cloned().map(|uri| (uri, None)).collect(), + Fuel::Unlimited, ) .await; let diagnostics = result diff --git a/crates/nash-driver/src/compile/collection_tests.rs b/crates/nash-driver/src/compile/collection_tests.rs index 3b546a1f..f03a78f3 100644 --- a/crates/nash-driver/src/compile/collection_tests.rs +++ b/crates/nash-driver/src/compile/collection_tests.rs @@ -28,7 +28,7 @@ async fn independent_failures_block_only_their_dependents() { let uris: Vec<_> = files.iter().map(|(name, _)| url(name)).collect(); let graph = build_graph(db.clone(), &uris).await.unwrap(); let origins = uris.iter().cloned().map(|uri| (uri, None)).collect(); - let result = build(db, &graph, &origins).await; + let result = build(db, &graph, &origins, Fuel::Unlimited).await; assert_eq!(result.success, 1); assert_eq!(result.failed, 4); assert_eq!(result.interfaces.len(), 1); @@ -58,6 +58,7 @@ async fn unreadable_source_does_not_hide_independent_errors() { db, &graph, &uris.iter().cloned().map(|uri| (uri, None)).collect(), + Fuel::Unlimited, ) .await; assert!(matches!( diff --git a/crates/nash-driver/src/lib.rs b/crates/nash-driver/src/lib.rs index b83e1dca..f186599e 100644 --- a/crates/nash-driver/src/lib.rs +++ b/crates/nash-driver/src/lib.rs @@ -12,7 +12,7 @@ //! # Example //! //! ```ignore -//! use nash_driver::{Project, Database, build, build_graph}; +//! use nash_driver::{Fuel, Project, Database, build, build_graph}; //! use nash_driver::source::FileSystemSource; //! use std::sync::Arc; //! use tokio::sync::Mutex; @@ -32,7 +32,7 @@ //! let graph = build_graph(db.clone(), &modules.keys().cloned().collect::>()).await?; //! //! // Compile everything -//! let result = build(db, &graph, &modules).await; +//! let result = build(db, &graph, &modules, Fuel::Unlimited).await; //! //! println!("Compiled {} modules ({} success, {} failed)", //! result.total, result.success, result.failed); @@ -61,5 +61,6 @@ pub use database::Database; pub use error::DriverError; pub use graph::DepGraph; pub use interface::{Export, Interface}; +pub use nash_ast::fuel::Fuel; pub use project::{ModuleOrigins, Project, ProjectMember}; pub use source::{FileSource, FileSystemSource, InMemorySource, OverlaySource}; diff --git a/crates/nash-driver/src/project.rs b/crates/nash-driver/src/project.rs index 4066f17d..c9f84715 100644 --- a/crates/nash-driver/src/project.rs +++ b/crates/nash-driver/src/project.rs @@ -444,10 +444,10 @@ mod tests { .await .unwrap(); assert_eq!(graph.order, [literal.clone(), main.clone()]); - let result = build(db.clone(), &graph, &modules).await; + let result = build(db.clone(), &graph, &modules, crate::Fuel::Unlimited).await; assert!(result.is_success(), "{result:?}"); modules.insert(literal.clone(), Some("example/literals".parse().unwrap())); - let result = build(db.clone(), &graph, &modules).await; + let result = build(db.clone(), &graph, &modules, crate::Fuel::Unlimited).await; assert!( matches!(&result.modules[&main], ModuleResult::Failed(reports) if reports.reports.iter().any(|report| report.title == "AMBIGUOUS TYPE")) ); diff --git a/crates/nash-driver/tests/base_traits.rs b/crates/nash-driver/tests/base_traits.rs index 0a9bab41..da7fd2df 100644 --- a/crates/nash-driver/tests/base_traits.rs +++ b/crates/nash-driver/tests/base_traits.rs @@ -1,4 +1,6 @@ -use nash_driver::{Database, InMemorySource, build_graph_with_tests, bundled_base, test_with}; +use nash_driver::{ + Database, Fuel, InMemorySource, build_graph_with_tests, bundled_base, test_with, +}; use std::sync::Arc; use tokio::sync::Mutex; use url::Url; @@ -17,7 +19,7 @@ async fn run(source: &str, trace: nash_config::TraceLevel) -> String { ) .await .unwrap(); - let (report, programs) = test_with(db, &graph, &modules, move |solved| { + let (report, programs) = test_with(db, &graph, &modules, Fuel::Unlimited, move |solved| { nash_driver::build::compile_tests_with(solved, |uri| { (uri == &main).then_some(nash_config::Build { trace_level: trace, @@ -188,7 +190,7 @@ tests ) .await .unwrap(); - let (report, programs) = test_with(db, &graph, &modules, move |solved| { + let (report, programs) = test_with(db, &graph, &modules, Fuel::Unlimited, move |solved| { nash_driver::build::compile_tests_with(solved, |uri| { roots.contains(uri).then_some(nash_config::Build { optimize: if uri.path().ends_with("Baseline.nash") { diff --git a/crates/nash-driver/tests/build.rs b/crates/nash-driver/tests/build.rs index c73536db..2fa28299 100644 --- a/crates/nash-driver/tests/build.rs +++ b/crates/nash-driver/tests/build.rs @@ -1,4 +1,4 @@ -use nash_driver::{Database, InMemorySource, build_graph, build_with}; +use nash_driver::{Database, Fuel, InMemorySource, build_graph, build_with}; use nash_plutus::{arena::Arena, flat, syn}; use std::{collections::BTreeMap, sync::Arc}; use tokio::sync::Mutex; @@ -33,7 +33,7 @@ async fn outputs_result_with( let graph = build_graph(db.clone(), &modules.keys().cloned().collect::>()) .await .unwrap(); - let (report, result) = build_with(db, &graph, &modules, move |solved| { + let (report, result) = build_with(db, &graph, &modules, Fuel::Unlimited, move |solved| { nash_driver::build::build_validators_with(solved, config_for) }) .await; @@ -413,3 +413,16 @@ async fn o2_validator_settings_and_trace_erasure() { }); } } + +/// An impl context that rewraps its argument needs one evidence node per +/// nesting level. Checking and code generation follow the type to any depth. +#[tokio::test] +async fn deeply_nested_impl_context_checks_and_builds_without_a_depth_limit() { + let depth = 200; + let source = format!( + "validator module Main exposing (main)\ntrait C 'a where\n c : 'a -> int\ntype wrap 'a = Wrap 'a\nimpl C int where\n c _ = 0\nimpl C 'a => C (wrap 'a) where\n c (Wrap x) = c x\nmain : Data -> unit\nmain _ =\n if c {}0{} == 0 then () else fail\n", + "(Wrap ".repeat(depth), + ")".repeat(depth), + ); + assert_eq!(outputs(&[("Main", &source)]).await.len(), 1); +} diff --git a/crates/nash-driver/tests/bundled_base.rs b/crates/nash-driver/tests/bundled_base.rs index b90c5c90..21b6264b 100644 --- a/crates/nash-driver/tests/bundled_base.rs +++ b/crates/nash-driver/tests/bundled_base.rs @@ -1,4 +1,4 @@ -use nash_driver::{Database, InMemorySource, build, build_graph, bundled_base}; +use nash_driver::{Database, Fuel, InMemorySource, build, build_graph, bundled_base}; use std::sync::Arc; use tokio::sync::Mutex; use url::Url; @@ -24,7 +24,7 @@ async fn all_bundled_modules_and_implicit_prelude_compile() { let graph = build_graph(db.clone(), &modules.keys().cloned().collect::>()) .await .unwrap(); - let result = build(db.clone(), &graph, &modules).await; + let result = build(db.clone(), &graph, &modules, Fuel::Unlimited).await; assert!(result.is_success(), "{:#?}", result.ordered_reports()); assert_eq!(result.success, bundled_base::SOURCES.len() + 1); let mut db = db.lock().await; @@ -93,7 +93,7 @@ async fn builtin_rejects_compiler_intrinsics() { let graph = build_graph(db.clone(), &modules.keys().cloned().collect::>()) .await .unwrap(); - let result = build(db, &graph, &modules).await; + let result = build(db, &graph, &modules, Fuel::Unlimited).await; assert!( matches!(&result.modules[&main], nash_driver::ModuleResult::Failed(reports) if !reports.reports.is_empty()) ); @@ -110,7 +110,7 @@ async fn base_application_fixture_compiles_without_imports() { let graph = build_graph(db.clone(), &origins.keys().cloned().collect::>()) .await .unwrap(); - let result = build(db, &graph, &origins).await; + let result = build(db, &graph, &origins, Fuel::Unlimited).await; assert!(result.is_success(), "{:#?}", result.ordered_reports()); } @@ -150,7 +150,7 @@ macro_rules! assert_base_type_error_snapshot { let graph = build_graph(db.clone(), &modules.keys().cloned().collect::>()) .await .unwrap(); - let result = build(db, &graph, &modules).await; + let result = build(db, &graph, &modules, Fuel::Unlimited).await; let nash_driver::ModuleResult::Failed(reports) = &result.modules[&main] else { panic!("invalid source passed: {result:?}"); }; diff --git a/crates/nash-driver/tests/nested_trace.rs b/crates/nash-driver/tests/nested_trace.rs index 54cbc100..e5cd94f2 100644 --- a/crates/nash-driver/tests/nested_trace.rs +++ b/crates/nash-driver/tests/nested_trace.rs @@ -1,7 +1,7 @@ use std::{collections::BTreeMap, sync::Arc}; use nash_codegen::build::{Build, Input, TraceConfig}; -use nash_driver::{Database, InMemorySource, build_graph, build_with}; +use nash_driver::{Database, Fuel, InMemorySource, build_graph, build_with}; use nash_plutus::{ arena::Arena, binder::DeBruijn, flat, machine::PlutusVersion, pretty, term::Term, }; @@ -22,7 +22,7 @@ async fn compile() -> BTreeMap> { let graph = build_graph(db.clone(), &origins.keys().cloned().collect::>()) .await .unwrap(); - let (report, programs) = build_with(db, &graph, &origins, move |solved| { + let (report, programs) = build_with(db, &graph, &origins, Fuel::Unlimited, move |solved| { let arena = Arena::new(); let build = Build::new(solved.modules.iter().map(|module| Input { module: module.module, diff --git a/crates/nash-driver/tests/production.rs b/crates/nash-driver/tests/production.rs index 0a744362..c2eac39a 100644 --- a/crates/nash-driver/tests/production.rs +++ b/crates/nash-driver/tests/production.rs @@ -1,4 +1,4 @@ -use nash_driver::{Database, InMemorySource, build, build_graph, build_with}; +use nash_driver::{Database, Fuel, InMemorySource, build, build_graph, build_with}; use std::{collections::BTreeMap, sync::Arc}; use tokio::sync::Mutex; use url::Url; @@ -66,7 +66,7 @@ async fn production_excludes_test_blocks_and_their_imports() { let graph = build_graph(db.clone(), &origins.keys().cloned().collect::>()) .await .unwrap(); - let (report, output) = build_with(db.clone(), &graph, &origins, |solved| { + let (report, output) = build_with(db.clone(), &graph, &origins, Fuel::Unlimited, |solved| { assert_eq!( solved .modules @@ -84,7 +84,7 @@ async fn production_excludes_test_blocks_and_their_imports() { insta::with_settings!({description => files.iter().map(|(_, source)| *source).collect::>().join("\n"), omit_expression => true}, { insta::assert_snapshot!(output[0].uplc); }); - let checked = build(db, &graph, &origins).await; + let checked = build(db, &graph, &origins, Fuel::Unlimited).await; insta::with_settings!({description => files.iter().map(|(_, source)| *source).collect::>().join("\n"), omit_expression => true}, { insta::assert_snapshot!("check_test_imports", diagnostics(&checked)); }); @@ -106,7 +106,7 @@ async fn production_keeps_normal_import_errors() { let graph = build_graph(db.clone(), &origins.keys().cloned().collect::>()) .await .unwrap(); - let (report, output) = build_with(db, &graph, &origins, |_| { + let (report, output) = build_with(db, &graph, &origins, Fuel::Unlimited, |_| { panic!("invalid production module reached codegen") }) .await; @@ -150,17 +150,23 @@ async fn check_retains_tests_and_production_has_no_test_dependency_edges() { .collect::>(), vec![&helper] ); - let checked = build(db.clone(), &graph, &origins).await; + let checked = build(db.clone(), &graph, &origins, Fuel::Unlimited).await; assert!(checked.is_success(), "{checked:#?}"); - let (checked, retained) = nash_driver::test_with(db.clone(), &graph, &origins, move |solved| { - let main = solved - .modules - .iter() - .find(|module| module.uri == main) - .unwrap(); - assert_eq!(main.source, source); - main.module.tests.len() - }) + let (checked, retained) = nash_driver::test_with( + db.clone(), + &graph, + &origins, + Fuel::Unlimited, + move |solved| { + let main = solved + .modules + .iter() + .find(|module| module.uri == main) + .unwrap(); + assert_eq!(main.source, source); + main.module.tests.len() + }, + ) .await; assert!(checked.is_success()); assert_eq!(retained, Some(1)); @@ -197,7 +203,7 @@ async fn check_rejects_non_unit_test_body() { let graph = build_graph(db.clone(), &origins.keys().cloned().collect::>()) .await .unwrap(); - let checked = build(db, &graph, &origins).await; + let checked = build(db, &graph, &origins, Fuel::Unlimited).await; let nash_driver::ModuleResult::Failed(_) = &checked.modules[&uri] else { panic!("invalid test body passed: {checked:?}") }; @@ -228,7 +234,7 @@ async fn dependency_validators_are_not_emitted_and_selected_roots_keep_their_tar ) .await .unwrap(); - let (report, outputs) = build_with(db, &graph, &origins, move |solved| { + let (report, outputs) = build_with(db, &graph, &origins, Fuel::Unlimited, move |solved| { nash_driver::build::build_validators_matching_with(solved, |uri| { (uri == &main).then_some(nash_config::Build::default()) }) diff --git a/crates/nash-driver/tests/stack.rs b/crates/nash-driver/tests/stack.rs index 7bf61415..9bffb6da 100644 --- a/crates/nash-driver/tests/stack.rs +++ b/crates/nash-driver/tests/stack.rs @@ -1,6 +1,6 @@ //! Deep input compiles on the compiler stack. -use nash_driver::{Database, InMemorySource, build, build_graph}; +use nash_driver::{Database, Fuel, InMemorySource, build, build_graph}; use std::{collections::BTreeMap, sync::Arc}; use tokio::sync::Mutex; use url::Url; @@ -24,6 +24,6 @@ async fn nested_parentheses_have_no_limit() { let graph = build_graph(db.clone(), &modules.keys().cloned().collect::>()) .await .unwrap(); - let report = build(db, &graph, &modules).await; + let report = build(db, &graph, &modules, Fuel::Unlimited).await; assert!(report.is_success(), "{:?}", report.ordered_reports()); } diff --git a/crates/nash-driver/tests/support/mod.rs b/crates/nash-driver/tests/support/mod.rs index f1376c10..c9e4f417 100644 --- a/crates/nash-driver/tests/support/mod.rs +++ b/crates/nash-driver/tests/support/mod.rs @@ -1,4 +1,4 @@ -use nash_driver::{Database, InMemorySource, build_graph, build_with, bundled_base}; +use nash_driver::{Database, Fuel, InMemorySource, build_graph, build_with, bundled_base}; use std::sync::Arc; use tokio::sync::Mutex; use url::Url; @@ -13,7 +13,7 @@ pub async fn compile_validator(source: &str) -> nash_driver::build::ValidatorOut let graph = build_graph(db.clone(), &origins.keys().cloned().collect::>()) .await .unwrap(); - let (report, result) = build_with(db, &graph, &origins, |solved| { + let (report, result) = build_with(db, &graph, &origins, Fuel::Unlimited, |solved| { nash_driver::build::build_validators(solved, nash_config::Build::default()) }) .await; diff --git a/crates/nash-driver/tests/vesting.rs b/crates/nash-driver/tests/vesting.rs index 60755278..4bebad8c 100644 --- a/crates/nash-driver/tests/vesting.rs +++ b/crates/nash-driver/tests/vesting.rs @@ -5,7 +5,7 @@ mod vesting_input; use std::{path::Path, sync::Arc}; use nash_driver::{ - Database, FileSystemSource, Project, build::build_validators, build_graph, build_with, + Database, FileSystemSource, Fuel, Project, build::build_validators, build_graph, build_with, }; use nash_plutus::{arena::Arena, data::PlutusData, flat, syn, term::Term}; use tokio::sync::Mutex; @@ -35,7 +35,7 @@ async fn bundled_base_vesting_artifacts_execute_all_ledger_cases() { let graph = build_graph(db.clone(), &origins.keys().cloned().collect::>()) .await .expect("build dependency graph"); - let (report, result) = build_with(db, &graph, &origins, |solved| { + let (report, result) = build_with(db, &graph, &origins, Fuel::Unlimited, |solved| { build_validators( solved, nash_config::Build { diff --git a/crates/nash-language-server/src/workspace.rs b/crates/nash-language-server/src/workspace.rs index 148594ae..6f6167ee 100644 --- a/crates/nash-language-server/src/workspace.rs +++ b/crates/nash-language-server/src/workspace.rs @@ -4,7 +4,7 @@ use std::path::PathBuf; use std::sync::Arc; use nash_driver::{ - Database, DriverError, FileSystemSource, InMemorySource, ModuleOrigins, ModuleResult, + Database, DriverError, FileSystemSource, Fuel, InMemorySource, ModuleOrigins, ModuleResult, OverlaySource, Project, build, build_graph, }; use nash_report::Source; @@ -16,6 +16,13 @@ use url::Url; use crate::diagnostics::to_lsp; +/// Compilation steps each module may take before the editor gives up on it, so +/// a looping program reports a diagnostic instead of freezing the server. +/// The largest Base module needs about 62 thousand steps; a looping program +/// spends this many in 1 to 2 seconds on a dev build. `nash check` runs with +/// unlimited fuel. +pub(crate) const COMPILE_FUEL: Fuel = Fuel::Limited(10_000_000); + struct Buffer { text: String, version: i32, @@ -144,7 +151,7 @@ impl Workspace { modules.extend(nash_driver::bundled_base::modules()); let graph = build_graph(db.clone(), &modules.keys().cloned().collect::>()).await?; - Ok::<_, DriverError>(build(db, &graph, &modules).await) + Ok::<_, DriverError>(build(db, &graph, &modules, COMPILE_FUEL).await) } .await; let mut diagnostics: BTreeMap> = BTreeMap::new(); @@ -227,6 +234,8 @@ mod tests { const CLEAN: &str = "module Main exposing (..)\nvalue = ()\n"; const BROKEN: &str = "module Main exposing (..)\nvalue = unknown\n"; + /// Resolving `Keep (list unit)` needs `Keep (list (list unit))`, and so on. + const LOOPING: &str = "module Main exposing (..)\ntrait Keep 'a where\n keep : 'a -> 'a\nimpl Keep (list (list 'a)) => Keep (list 'a) where\n keep xs = xs\nvalue : list unit\nvalue = keep [()]\n"; fn fixture() -> (tempfile::TempDir, Uri) { let dir = tempfile::tempdir().unwrap(); @@ -295,6 +304,26 @@ mod tests { ); } + #[tokio::test] + async fn a_looping_program_reports_running_out_of_fuel_instead_of_hanging() { + let (_dir, uri) = fixture(); + let mut workspace = Workspace::default(); + workspace.open(uri.clone(), LOOPING.into(), 1); + let (notifications, error) = workspace.rebuild(&uri).await; + assert!(error.is_none(), "{error:?}"); + let codes: Vec<_> = for_uri(¬ifications, &uri) + .diagnostics + .iter() + .map(|diagnostic| diagnostic.code.clone()) + .collect(); + assert_eq!( + codes, + [Some(NumberOrString::String( + "nash::type::out_of_fuel".into() + ))] + ); + } + #[tokio::test] async fn close_discards_overlay_and_clears_diagnostics() { let (dir, uri) = fixture(); @@ -333,7 +362,7 @@ mod tests { let graph = build_graph(db.clone(), &modules.keys().cloned().collect::>()) .await .unwrap(); - let result = build(db, &graph, &modules).await; + let result = build(db, &graph, &modules, COMPILE_FUEL).await; let modules = result.ordered_reports(); let problems: Vec<_> = modules .iter() diff --git a/crates/nash-report/src/canonicalize.rs b/crates/nash-report/src/canonicalize.rs index 8906b28e..3225c44d 100644 --- a/crates/nash-report/src/canonicalize.rs +++ b/crates/nash-report/src/canonicalize.rs @@ -747,9 +747,6 @@ pub fn to_report_with_name(source: &Source<'_>, error: &Error<'_>, expected_name nash_can::EntailmentFailure::Cycle => { "Resolving it leads back to the same requirement, forming a cycle." } - nash_can::EntailmentFailure::Limit => { - "Resolving it exceeded the search limit because the requirements keep expanding." - } }; simple( "MISSING SUPERCLASS", @@ -897,11 +894,11 @@ pub fn to_report_with_name(source: &Source<'_>, error: &Error<'_>, expected_name &format!("The `{ctor}` constructor has no `{field}` field:"), "Check the field name against the constructor declaration.", ), - Error::ImplPatternLimit { region } => simple( - "IMPL PATTERN LIMIT", + Error::OutOfFuel { region } => simple( + "COMPILATION STEP LIMIT", *region, - "This impl pattern is too large or deeply nested:", - "Simplify the impl head.", + "Checking this impl needed more compilation steps than the editor allows:", + "`nash check` has no step limit. Simplify the impl head or its context.", ), Error::NegateWithoutNum { region } => simple( "NAMING ERROR", @@ -952,7 +949,7 @@ pub fn to_report_with_name(source: &Source<'_>, error: &Error<'_>, expected_name Error::RecordLiteralNoAlias { .. } => "nash::names::record_literal_no_alias", Error::RecordLiteralAmbiguous { .. } => "nash::names::record_literal_ambiguous", Error::RecordTypeOutsideAlias { .. } => "nash::names::record_type_outside_alias", - Error::ImplPatternLimit { .. } => "nash::names::impl_pattern_limit", + Error::OutOfFuel { .. } => "nash::type::out_of_fuel", Error::NegateWithoutNum { .. } => "nash::names::negate_without_num", Error::DoWithoutMonad { .. } => "nash::names::do_without_monad", Error::RefutableBindPattern { .. } => "nash::names::refutable_bind_pattern", @@ -1580,13 +1577,13 @@ mod coverage { ); } #[test] - fn impl_pattern_limit() { + fn out_of_fuel() { source_snapshot!( - "variant_impl_pattern_limit", - "-- Reduced head from an impl-pattern budget exhaustion.\nimpl Equal «(List (List 'a))» where\n equal x y = True", + "variant_out_of_fuel", + "-- Reduced head from a compile that ran out of fuel.\nimpl Equal «(List (List 'a))» where\n equal x y = True", r, r2, - Error::ImplPatternLimit { region: r() }, + Error::OutOfFuel { region: r() }, ); } #[test] @@ -2941,7 +2938,7 @@ mod branches { } } #[test] - fn superclass_failure_reasons() { + fn superclass_cycle() { let trait_ = QualifiedName { home: ModuleName { package: None, @@ -2949,38 +2946,32 @@ mod branches { }, name: "Equal", }; - - for (name, reason) in [ - ("superclass_cycle", nash_can::EntailmentFailure::Cycle), - ("superclass_limit", nash_can::EntailmentFailure::Limit), - ] { - let (_, regions) = marked_source("impl «Core.Equal 'a» where\n equal x y = True"); - let r = || regions[0]; - let arg = Located::at(r(), nash_ast::Type::Var("a")); - source_snapshot!( - name, - "impl «Core.Equal 'a» where\n equal x y = True", - r, - r2, - Error::MissingSuperclass { - region: r(), + let (_, regions) = marked_source("impl «Core.Equal 'a» where\n equal x y = True"); + let r = || regions[0]; + let arg = Located::at(r(), nash_ast::Type::Var("a")); + source_snapshot!( + "superclass_cycle", + "impl «Core.Equal 'a» where\n equal x y = True", + r, + r2, + Error::MissingSuperclass { + region: r(), + trait_, + heads: &[Located::at( + r(), + nash_ast::Head::Var { + index: 0, + repr: nash_ast::primitives::ReprSet::ALL + } + )], + superclass: &nash_ast::Pred::Trait { trait_, - heads: &[Located::at( - r(), - nash_ast::Head::Var { - index: 0, - repr: nash_ast::primitives::ReprSet::ALL - } - )], - superclass: &nash_ast::Pred::Trait { - trait_, - args: &[&arg], - }, - index: 0, - reason, + args: &[&arg], }, - ); - } + index: 0, + reason: nash_can::EntailmentFailure::Cycle, + }, + ); } #[test] fn duplicate_pattern_contexts() { diff --git a/crates/nash-report/src/snapshots/nash_report__canonicalize__branches__superclass_limit.snap b/crates/nash-report/src/snapshots/nash_report__canonicalize__branches__superclass_limit.snap deleted file mode 100644 index 512cabe3..00000000 --- a/crates/nash-report/src/snapshots/nash_report__canonicalize__branches__superclass_limit.snap +++ /dev/null @@ -1,15 +0,0 @@ ---- -source: crates/nash-report/src/canonicalize.rs -description: "impl Core.Equal 'a where\n equal x y = True" ---- -nash::names::missing_superclass - - × The `Core.Equal` impl for 'a0 does not establish superclass 1: - ╭─[Main.nash:1:6] - 1 │ impl Core.Equal 'a where - · ───────────── - 2 │ equal x y = True - ╰──── - help: It must also satisfy `Core.Equal 'a`. Resolving it exceeded the search limit - because the requirements keep expanding. Add the required impl or include the - necessary constraint in this impl's context. diff --git a/crates/nash-report/src/snapshots/nash_report__canonicalize__coverage__variant_impl_pattern_limit.snap b/crates/nash-report/src/snapshots/nash_report__canonicalize__coverage__variant_impl_pattern_limit.snap deleted file mode 100644 index 6d0be58e..00000000 --- a/crates/nash-report/src/snapshots/nash_report__canonicalize__coverage__variant_impl_pattern_limit.snap +++ /dev/null @@ -1,14 +0,0 @@ ---- -source: crates/nash-report/src/canonicalize.rs -description: "-- Reduced head from an impl-pattern budget exhaustion.\nimpl Equal (List (List 'a)) where\n equal x y = True" ---- -nash::names::impl_pattern_limit - - × This impl pattern is too large or deeply nested: - ╭─[Main.nash:2:12] - 1 │ -- Reduced head from an impl-pattern budget exhaustion. - 2 │ impl Equal (List (List 'a)) where - · ──────────────── - 3 │ equal x y = True - ╰──── - help: Simplify the impl head. diff --git a/crates/nash-report/src/snapshots/nash_report__canonicalize__coverage__variant_out_of_fuel.snap b/crates/nash-report/src/snapshots/nash_report__canonicalize__coverage__variant_out_of_fuel.snap new file mode 100644 index 00000000..5b99e40f --- /dev/null +++ b/crates/nash-report/src/snapshots/nash_report__canonicalize__coverage__variant_out_of_fuel.snap @@ -0,0 +1,14 @@ +--- +source: crates/nash-report/src/canonicalize.rs +description: "-- Reduced head from a compile that ran out of fuel.\nimpl Equal (List (List 'a)) where\n equal x y = True" +--- +nash::type::out_of_fuel + + × Checking this impl needed more compilation steps than the editor allows: + ╭─[Main.nash:2:12] + 1 │ -- Reduced head from a compile that ran out of fuel. + 2 │ impl Equal (List (List 'a)) where + · ──────────────── + 3 │ equal x y = True + ╰──── + help: `nash check` has no step limit. Simplify the impl head or its context. diff --git a/crates/nash-report/src/type_.rs b/crates/nash-report/src/type_.rs index 859ac8f4..83be49ea 100644 --- a/crates/nash-report/src/type_.rs +++ b/crates/nash-report/src/type_.rs @@ -117,11 +117,11 @@ pub fn to_report(localizer: &Localizer, error: &Error<'_>) -> Report { available, because, } => traits::missing_impl(localizer, *region, name, *trait_, args, available, because), - Error::ImplResolutionLimit { + Error::OutOfFuel { region, name, trait_, - } => traits::resolution_limit(localizer, *region, name, *trait_), + } => traits::out_of_fuel(localizer, *region, name, *trait_), Error::MissingConstraint { region, name, @@ -184,7 +184,7 @@ pub fn to_report(localizer: &Localizer, error: &Error<'_>) -> Report { Error::UnresolvedConstraint { .. } => "nash::type::unresolved_constraint", Error::UnresolvedApplication { .. } => "nash::type::unresolved_application", Error::MissingImpl { .. } => "nash::type::missing_impl", - Error::ImplResolutionLimit { .. } => "nash::type::impl_resolution_limit", + Error::OutOfFuel { .. } => "nash::type::out_of_fuel", Error::MissingConstraint { .. } => "nash::type::missing_constraint", Error::AnnotationVariableEscapes { .. } => "nash::type::annotation_variable_escapes", Error::BadExpr(..) => "nash::type::mismatch", diff --git a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__impl_resolution_limit.snap b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__out_of_fuel.snap similarity index 70% rename from crates/nash-report/src/type_/snapshots/nash_report__type___tests__impl_resolution_limit.snap rename to crates/nash-report/src/type_/snapshots/nash_report__type___tests__out_of_fuel.snap index 1b82a646..e41b6336 100644 --- a/crates/nash-report/src/type_/snapshots/nash_report__type___tests__impl_resolution_limit.snap +++ b/crates/nash-report/src/type_/snapshots/nash_report__type___tests__out_of_fuel.snap @@ -2,9 +2,9 @@ source: crates/nash-report/src/type_/tests.rs description: "module Main exposing (..)\ntrait Eq 'a where\n eq : 'a -> 'a -> Primitive.bool\nimpl Eq (Primitive.list 'a) => Eq 'a where\n eq xs ys = True\nf xs = eq xs xs\n" --- -nash::type::impl_resolution_limit +nash::type::out_of_fuel - × Impl resolution for `Eq` in `f` exceeded the work limit. + × Resolving `Eq` in `f` needed more compilation steps than the editor allows. ╭─[Main.nash:6:8] 5 │ eq xs ys = True 6 │ f xs = eq xs xs @@ -12,4 +12,4 @@ nash::type::impl_resolution_limit ╰──── help: This requirement remains unchecked; other reported errors still apply. - Simplify cyclic or growing impl constraints. + `nash check` has no step limit. Simplify cyclic or growing impl constraints. diff --git a/crates/nash-report/src/type_/tests.rs b/crates/nash-report/src/type_/tests.rs index 2147ab85..0a6c6835 100644 --- a/crates/nash-report/src/type_/tests.rs +++ b/crates/nash-report/src/type_/tests.rs @@ -889,14 +889,14 @@ fn unresolved_application() { )); } #[test] -fn impl_resolution_limit() { +fn out_of_fuel() { let source = "module Main exposing (..)\ntrait Eq 'a where\n eq : 'a -> 'a -> Primitive.bool\nimpl Eq (Primitive.list 'a) => Eq 'a where\n eq xs ys = True\nf xs = eq xs xs\n"; let region = || source_region(source, "eq xs xs"); let settings = source_settings(source); let _guard = settings.bind_to_scope(); insta::assert_snapshot!(show( source, - &Error::ImplResolutionLimit { + &Error::OutOfFuel { region: region(), name: "f", trait_: nash_ast::primitives::eq_trait() diff --git a/crates/nash-report/src/type_/traits.rs b/crates/nash-report/src/type_/traits.rs index 8562dcaf..af77f190 100644 --- a/crates/nash-report/src/type_/traits.rs +++ b/crates/nash-report/src/type_/traits.rs @@ -205,22 +205,24 @@ pub(super) fn unresolved_application( ) } -pub(super) fn resolution_limit( +pub(super) fn out_of_fuel( l: &Localizer, region: Region, name: &str, trait_: QualifiedName<'_>, ) -> Report { report( - "IMPL RESOLUTION LIMIT", + "COMPILATION STEP LIMIT", region, Doc::text(format!( - "Impl resolution for `{}` in `{name}` exceeded the work limit.", + "Resolving `{}` in `{name}` needed more compilation steps than the editor allows.", l.to_string(trait_.home, trait_.name) )), [ Doc::text("This requirement remains unchecked; other reported errors still apply."), - Doc::text("Simplify cyclic or growing impl constraints."), + Doc::text( + "`nash check` has no step limit. Simplify cyclic or growing impl constraints.", + ), ], ) } diff --git a/crates/nash-solve/src/evidence.rs b/crates/nash-solve/src/evidence.rs index e94c908f..a1be4739 100644 --- a/crates/nash-solve/src/evidence.rs +++ b/crates/nash-solve/src/evidence.rs @@ -1,7 +1,7 @@ //! Impl evidence for canonical predicates after inference. A type variable //! that reaches resolution is open: nothing will bind it. use bumpalo::Bump; -use nash_ast::head::{DEPTH_LIMIT, WORK_LIMIT}; +use nash_ast::fuel::{OutOfFuel, tick}; use nash_ast::{Evidence, ImplRef, Pred, QualifiedName, Type}; use nash_can::environment::Tables; use nash_region::Located; @@ -12,7 +12,13 @@ pub enum Failure { /// A decision needs an open type variable: impl selection, a /// representation test, or the requirements of a type. NonGround, - Limit, + OutOfFuel, +} + +impl From for Failure { + fn from(OutOfFuel: OutOfFuel) -> Self { + Self::OutOfFuel + } } #[derive(Debug)] @@ -25,18 +31,13 @@ pub struct Error<'a> { /// Nominal aliases retain their identity. An open type variable equals only /// itself; resolution never chooses a type or kind to make an impl match, so /// a decision that needs an open variable fails with `NonGround`. Recursive -/// contexts and structural traversal share a bounded work budget. +/// contexts and structural traversal draw from the compile's fuel. pub fn resolve<'a>( bump: &'a Bump, tables: &Tables<'a>, pred: &Pred<'a>, ) -> Result>, Error<'a>> { - Resolver { - bump, - tables, - remaining: WORK_LIMIT, - } - .resolve(pred, 0) + Resolver { bump, tables }.resolve(pred) } #[derive(PartialEq, Eq)] @@ -60,7 +61,6 @@ struct Term<'a> { struct Resolver<'t, 'a> { bump: &'a Bump, tables: &'t Tables<'a>, - remaining: usize, } enum Resolution<'a> { @@ -76,7 +76,7 @@ enum Resolution<'a> { } enum Work<'a> { - Resolve(Pred<'a>, usize), + Resolve(Pred<'a>), Assemble(ImplRef<'a>, &'a [&'a Located>], usize), Apply(usize), } @@ -84,48 +84,48 @@ enum Work<'a> { impl<'a> Resolver<'_, 'a> { // Charge every node that substitute_type will copy before allocating the // result. Open alias bodies are retained; filled bodies are traversed. - fn substitution_work(&mut self, typ: &Type<'a>, depth: usize) -> Result<(), Failure> { - self.step(depth)?; + fn substitution_work(&mut self, typ: &Type<'a>) -> Result<(), Failure> { + tick()?; match typ { Type::App { head, args } => { - self.substitution_work(&head.value, depth + 1)?; + self.substitution_work(&head.value)?; for arg in *args { - self.substitution_work(&arg.value, depth + 1)?; + self.substitution_work(&arg.value)?; } } Type::Named { args, .. } => { for arg in *args { - self.substitution_work(&arg.value, depth + 1)?; + self.substitution_work(&arg.value)?; } } Type::Alias { arguments, target, .. } => { for arg in *arguments { - self.substitution_work(&arg.typ.value, depth + 1)?; + self.substitution_work(&arg.typ.value)?; } if let nash_ast::AliasType::Filled { typ, .. } = target { - self.substitution_work(&typ.value, depth + 1)?; + self.substitution_work(&typ.value)?; } } Type::Lambda { from, to } => { - self.substitution_work(&from.value, depth + 1)?; - self.substitution_work(&to.value, depth + 1)?; + self.substitution_work(&from.value)?; + self.substitution_work(&to.value)?; } Type::Tuple { first, second, rest, } => { - self.substitution_work(&first.value, depth + 1)?; - self.substitution_work(&second.value, depth + 1)?; + self.substitution_work(&first.value)?; + self.substitution_work(&second.value)?; for arg in *rest { - self.substitution_work(&arg.value, depth + 1)?; + self.substitution_work(&arg.value)?; } } Type::Record { fields, .. } => { for field in *fields { - self.substitution_work(&field.typ.value, depth + 1)?; + self.substitution_work(&field.typ.value)?; } } Type::Var(_) => {} @@ -133,25 +133,17 @@ impl<'a> Resolver<'_, 'a> { Ok(()) } - fn step(&mut self, depth: usize) -> Result<(), Failure> { - if depth >= DEPTH_LIMIT || self.remaining == 0 { - return Err(Failure::Limit); - } - self.remaining -= 1; - Ok(()) - } - - fn term(&mut self, typ: &Type<'a>, depth: usize) -> Result, Failure> { - self.step(depth)?; + fn term(&mut self, typ: &Type<'a>) -> Result, Failure> { + tick()?; let (con, args) = match typ { Type::Var(name) => (Constructor::Var(name), Vec::new()), Type::App { head, args } => { - let mut head = self.term(&head.value, depth + 1)?; + let mut head = self.term(&head.value)?; if !matches!(head.con, Constructor::Named(_) | Constructor::Var(_)) { return Err(Failure::MissingImpl); } for arg in *args { - head.args.push(self.term(&arg.value, depth + 1)?); + head.args.push(self.term(&arg.value)?); } return Ok(head); } @@ -184,30 +176,21 @@ impl<'a> Resolver<'_, 'a> { }; let args = args .into_iter() - .map(|arg| self.term(&arg.value, depth + 1)) + .map(|arg| self.term(&arg.value)) .collect::>()?; Ok(Term { con, args }) } - fn resolve( - &mut self, - pred: &Pred<'a>, - depth: usize, - ) -> Result>, Error<'a>> { - let mut pending = vec![Work::Resolve(*pred, depth)]; + fn resolve(&mut self, pred: &Pred<'a>) -> Result>, Error<'a>> { + let mut pending = vec![Work::Resolve(*pred)]; let mut evidence = Vec::new(); while let Some(work) = pending.pop() { match work { - Work::Resolve(pred, depth) => match self.resolve_step(&pred, depth)? { + Work::Resolve(pred) => match self.resolve_step(&pred)? { Resolution::Complete(proof) => evidence.push(Some(proof)), Resolution::Apply { children } => { pending.push(Work::Apply(children.len())); - pending.extend( - children - .into_iter() - .rev() - .map(|pred| Work::Resolve(pred, depth + 1)), - ); + pending.extend(children.into_iter().rev().map(Work::Resolve)); } Resolution::Impl { impl_, @@ -215,12 +198,7 @@ impl<'a> Resolver<'_, 'a> { children, } => { pending.push(Work::Assemble(impl_, type_args, children.len())); - pending.extend( - children - .into_iter() - .rev() - .map(|pred| Work::Resolve(pred, depth + 1)), - ); + pending.extend(children.into_iter().rev().map(Work::Resolve)); } }, Work::Apply(count) => { @@ -242,15 +220,15 @@ impl<'a> Resolver<'_, 'a> { Ok(evidence.pop().expect("root evidence")) } - fn resolve_step(&mut self, pred: &Pred<'a>, depth: usize) -> Result, Error<'a>> { + fn resolve_step(&mut self, pred: &Pred<'a>) -> Result, Error<'a>> { let error = |reason| Error { predicate: *pred, reason, }; - self.step(depth).map_err(error)?; + tick().map_err(|out| error(out.into()))?; let terms = pred .types() - .map(|arg| self.term(&arg.value, 0)) + .map(|arg| self.term(&arg.value)) .collect::, _>>() .map_err(error)?; let group = Default::default(); @@ -334,10 +312,9 @@ impl<'a> Resolver<'_, 'a> { }), candidates, args, - &mut self.remaining, nash_ast::head::SelectPolicy::Exact, ) - .map_err(|_| error(Failure::Limit))?; + .map_err(|_| error(Failure::OutOfFuel))?; let (key, info, type_args) = match selection { nash_ast::head::ImplSelection::Selected { info: (key, info), @@ -358,7 +335,7 @@ impl<'a> Resolver<'_, 'a> { let mut children = Vec::new(); for context in info.context { for typ in context.types() { - self.substitution_work(&typ.value, 0).map_err(error)?; + self.substitution_work(&typ.value).map_err(error)?; } children.push(nash_can::kinds::substitute_predicate( self.bump, diff --git a/crates/nash-solve/src/occurs.rs b/crates/nash-solve/src/occurs.rs index fed09ad4..8ba0cd93 100644 --- a/crates/nash-solve/src/occurs.rs +++ b/crates/nash-solve/src/occurs.rs @@ -79,9 +79,11 @@ enum Visit { /// occurs check of a binding. pub fn reaches_cycle(uf: &mut UnionFind<'_>, roots: &[Variable]) -> bool { let mut visits = BTreeMap::new(); - roots + let found = roots .iter() - .any(|root| reaches_cycle_help(uf, &mut visits, *root)) + .any(|root| reaches_cycle_help(uf, &mut visits, *root)); + nash_ast::fuel::charge(visits.len()); + found } fn reaches_cycle_help( diff --git a/crates/nash-solve/src/preds.rs b/crates/nash-solve/src/preds.rs index 0981aa10..93bb9acf 100644 --- a/crates/nash-solve/src/preds.rs +++ b/crates/nash-solve/src/preds.rs @@ -250,15 +250,6 @@ impl<'a> Store<'a> { &self.predicates[id.0 as usize] } - pub(crate) fn depth(&self, mut id: PredId) -> usize { - let mut depth = 0; - while let Origin::Sub { parent, .. } = self.get(id).origin { - depth += 1; - id = parent; - } - depth - } - pub(crate) fn root(&self, mut id: PredId) -> PredId { while let Origin::Sub { parent, .. } = self.get(id).origin { id = parent; diff --git a/crates/nash-solve/src/recovery.rs b/crates/nash-solve/src/recovery.rs index a9632178..3c75364c 100644 --- a/crates/nash-solve/src/recovery.rs +++ b/crates/nash-solve/src/recovery.rs @@ -50,6 +50,7 @@ impl Dependencies { pending.push(child); } } + nash_ast::fuel::charge(seen.len()); } /// Move the indexes keyed by representative along the merges made since diff --git a/crates/nash-solve/src/resolve.rs b/crates/nash-solve/src/resolve.rs index 735f2d03..b1ac90f6 100644 --- a/crates/nash-solve/src/resolve.rs +++ b/crates/nash-solve/src/resolve.rs @@ -1,6 +1,6 @@ //! Coherent selection from known heads and read-only probes for relational //! equalities. The solver commits only a unique candidate's equalities. -use nash_ast::head::WORK_LIMIT; +use nash_ast::fuel::{OutOfFuel, tick}; use nash_ast::{HeadCon, ImplKey, QualifiedName}; use nash_can::environment::{ImplInfo, Tables}; use nash_constrain::{Content, FlatType, UnionFind, Variable}; @@ -44,7 +44,7 @@ pub(crate) fn has_outer_flex(uf: &mut UnionFind<'_>, args: &[Variable], rank: us } pub(crate) enum Selection<'a> { - Limit, + OutOfFuel, Deferred, Missing, Impl { @@ -153,13 +153,12 @@ impl<'a> nash_ast::head::Types<'a> for InferenceTypes<'_, 'a> { &mut self, first: Variable, second: Variable, - remaining: &mut usize, - ) -> Result, nash_ast::head::Limit> { - use nash_ast::head::{Match, step}; + ) -> Result, OutOfFuel> { + use nash_ast::head::Match; let mut pending = vec![(first, second)]; let mut deferred = false; while let Some((first, second)) = pending.pop() { - step(remaining)?; + tick()?; if self.0.find(first) == self.0.find(second) { continue; } @@ -247,13 +246,8 @@ impl<'a> nash_ast::head::Types<'a> for ClassedTypes<'_, 'a> { ) -> nash_ast::head::Match> { self.types.constructor(node, expected) } - fn equal( - &mut self, - a: Variable, - b: Variable, - remaining: &mut usize, - ) -> Result, nash_ast::head::Limit> { - self.types.equal(a, b, remaining) + fn equal(&mut self, a: Variable, b: Variable) -> Result, OutOfFuel> { + self.types.equal(a, b) } fn in_class( &mut self, @@ -355,10 +349,8 @@ pub(crate) fn select<'a>( ) -> Selection<'a> { use nash_ast::head::{ImplSelection, SelectPolicy, select_impl}; if args.len() >= 2 { - match given_candidates(tables, uf, trait_, args, givens, allocated, &mut { - WORK_LIMIT - }) { - None => return Selection::Limit, + match given_candidates(tables, uf, trait_, args, givens, allocated) { + None => return Selection::OutOfFuel, Some(candidates) if !candidates.is_empty() => return Selection::Deferred, Some(_) => {} } @@ -373,14 +365,8 @@ pub(crate) fn select<'a>( let candidates = tables .impls_for(trait_) .map(|(key, info)| (key.heads, info.variables.len(), (key, *info))); - match select_impl( - &mut types, - candidates, - args, - &mut { WORK_LIMIT }, - SelectPolicy::Defer, - ) { - Err(_) => Selection::Limit, + match select_impl(&mut types, candidates, args, SelectPolicy::Defer) { + Err(_) => Selection::OutOfFuel, Ok(ImplSelection::Deferred) => Selection::Deferred, Ok(ImplSelection::Selected { info: (key, info), @@ -397,7 +383,7 @@ pub(crate) fn select<'a>( pub(crate) enum Coverage<'a> { NotApplicable, - Limit, + OutOfFuel, /// No given holds the wanted trait at this rigid subject. Unstated(Variable), /// A representation cell selects no impl. @@ -422,7 +408,6 @@ pub(crate) fn coverage<'a>( args: &[Variable], givens: &[crate::preds::Body<'a>], allocated: &mut Vec, - remaining: &mut usize, ) -> Coverage<'a> { use nash_ast::head::Coverage as Cells; let candidates: Vec<_> = tables @@ -430,8 +415,8 @@ pub(crate) fn coverage<'a>( .map(|(key, info)| (key.heads, info.variables.len(), *info)) .collect(); let mut types = ClassedTypes::new(uf, tables, givens, allocated); - match nash_ast::head::cover_impls(&mut types, trait_, &candidates, args, remaining) { - Err(_) => Coverage::Limit, + match nash_ast::head::cover_impls(&mut types, trait_, &candidates, args) { + Err(_) => Coverage::OutOfFuel, Ok(Cells::NotApplicable) => Coverage::NotApplicable, Ok(Cells::Unstated(subject)) => Coverage::Unstated(subject), Ok(Cells::Missing(_)) => Coverage::Uncovered, @@ -476,16 +461,11 @@ impl<'a> Probe<'_, 'a> { } } - fn occurs( - &mut self, - needle: Variable, - value: Variable, - remaining: &mut usize, - ) -> Result { + fn occurs(&mut self, needle: Variable, value: Variable) -> Result { let mut pending = vec![value]; let mut seen = std::collections::BTreeSet::new(); while let Some(value) = pending.pop() { - nash_ast::head::step(remaining)?; + tick()?; let value = self.root(value); if value == needle { return Ok(true); @@ -534,17 +514,12 @@ impl<'a> nash_ast::head::Types<'a> for Probe<'_, 'a> { self.classes.push((node, class)); nash_ast::head::Match::Yes(()) } - fn equal( - &mut self, - a: Variable, - b: Variable, - remaining: &mut usize, - ) -> Result, nash_ast::head::Limit> { + fn equal(&mut self, a: Variable, b: Variable) -> Result, OutOfFuel> { use nash_ast::head::Match; let mut pending = vec![(a, b)]; let mut deferred = false; while let Some((a, b)) = pending.pop() { - nash_ast::head::step(remaining)?; + tick()?; let a = self.root(a); let b = self.root(b); if a == b { @@ -554,7 +529,7 @@ impl<'a> nash_ast::head::Types<'a> for Probe<'_, 'a> { let (bv, ba) = self.types.types.view(b); if av == View::Flexible || bv == View::Flexible { let (var, value) = if av == View::Flexible { (a, b) } else { (b, a) }; - if self.occurs(var, value, remaining)? { + if self.occurs(var, value)? { return Ok(Match::No); } self.substitutions.insert(var, value); @@ -601,7 +576,6 @@ fn given_candidates<'a>( args: &[Variable], givens: &[crate::preds::Body<'a>], allocated: &mut Vec, - remaining: &mut usize, ) -> Option { use nash_ast::head::{Match, Types}; let mut candidates = Vec::new(); @@ -633,7 +607,7 @@ fn given_candidates<'a>( }; let mut matched = Match::Yes(()); for (a, b) in args.iter().zip(supplied) { - match probe.equal(*a, *b, remaining).ok()? { + match probe.equal(*a, *b).ok()? { Match::No => { matched = Match::No; break; @@ -665,9 +639,7 @@ pub(crate) fn improvement<'a>( if args.len() < 2 { return None; } - let mut remaining = WORK_LIMIT; - let mut candidates = - given_candidates(tables, uf, trait_, args, givens, allocated, &mut remaining)?; + let mut candidates = given_candidates(tables, uf, trait_, args, givens, allocated)?; if !candidates.is_empty() { return if candidates.len() == 1 { candidates.pop().flatten().filter(|e| !e.is_empty()) @@ -683,14 +655,8 @@ pub(crate) fn improvement<'a>( equations: Vec::new(), classes: Vec::new(), }; - let matched = nash_ast::head::matches( - &mut probe, - key.heads, - args, - info.variables.len(), - &mut remaining, - ) - .ok()?; + let matched = + nash_ast::head::matches(&mut probe, key.heads, args, info.variables.len()).ok()?; if matches!(matched, Match::No) { continue; } @@ -712,7 +678,7 @@ pub(crate) fn improvement<'a>( equations: Vec::new(), classes: Vec::new(), }; - match probe.equal(args[0], args[1], &mut remaining).ok()? { + match probe.equal(args[0], args[1]).ok()? { Match::No => {} Match::Deferred => candidates.push(None), Match::Yes(()) => candidates.push(Some(probe.equations)), @@ -755,15 +721,9 @@ mod tests { [("a", unknown), ("b", unit)].into(), )))); let mut types = InferenceTypes(&mut uf); - assert!(matches!( - types.equal(first, second, &mut 100), - Ok(Match::Yes(())) - )); - assert!(matches!(types.equal(first, fewer, &mut 100), Ok(Match::No))); - assert!(matches!( - types.equal(first, flexible, &mut 100), - Ok(Match::Deferred) - )); + assert!(matches!(types.equal(first, second), Ok(Match::Yes(())))); + assert!(matches!(types.equal(first, fewer), Ok(Match::No))); + assert!(matches!(types.equal(first, flexible), Ok(Match::Deferred))); assert_ne!(types.0.find(first), types.0.find(second)); assert!(matches!(types.0.get(unknown).content, Content::FlexVar(_))); } diff --git a/crates/nash-solve/src/solve.rs b/crates/nash-solve/src/solve.rs index b475dc08..a29bd4d4 100644 --- a/crates/nash-solve/src/solve.rs +++ b/crates/nash-solve/src/solve.rs @@ -6,7 +6,7 @@ use std::collections::{BTreeMap, BTreeSet, VecDeque}; use bumpalo::Bump; use nash_ast::Type as CanType; -use nash_ast::head::{DEPTH_LIMIT, WORK_LIMIT}; +use nash_ast::fuel::tick; use nash_can::Annotations; use nash_constrain::error::{Category, Error, Expected, PExpected}; use nash_constrain::type_::{ @@ -144,7 +144,7 @@ fn representation_requirement<'a>( /// Why representation coverage could not prove a wanted predicate. enum CoverageProblem<'a> { - Limit, + OutOfFuel, /// Some cell cannot prove this predicate: a context of a covered impl, /// or, at the limit, the wanted trait at a rigid subject. MissingContext(Body<'a>), @@ -175,7 +175,6 @@ struct Solver<'a, 'tables> { expr_types: Vec, pattern_types: Vec, owners: Vec, - resolution_work: std::collections::HashMap, has_poison: bool, dependencies: crate::recovery::Dependencies, failed_lineages: BTreeSet, @@ -224,7 +223,6 @@ impl<'a, 'tables> Solver<'a, 'tables> { expr_types: Vec::new(), pattern_types: Vec::new(), owners: Vec::new(), - resolution_work: std::collections::HashMap::new(), has_poison: false, dependencies: crate::recovery::Dependencies::default(), failed_lineages: BTreeSet::new(), @@ -2021,13 +2019,8 @@ impl<'a> Solver<'a, '_> { use nash_ast::primitives::{Repr, ReprTrait}; self.propagate_poison(uf); let report_missing = annotated; - let mut queue: VecDeque<_> = self - .wanted - .split_off(start) - .into_iter() - .map(|(rank, id)| (rank, id, self.predicates.depth(id))) - .collect(); - while let Some((wanted_rank, id, resolution_depth)) = queue.pop_front() { + let mut queue: VecDeque<_> = self.wanted.split_off(start).into(); + while let Some((wanted_rank, id)) = queue.pop_front() { if self.predicate_blocked(uf, id) { self.predicates.detach(uf, id); continue; @@ -2062,7 +2055,7 @@ impl<'a> Solver<'a, '_> { }, ); subs.push(sub); - queue.push_back((wanted_rank, sub, resolution_depth + 1)); + queue.push_back((wanted_rank, sub)); } self.predicates.solve(uf, id, Solution::Apply { subs }); } else { @@ -2207,13 +2200,8 @@ impl<'a> Solver<'a, '_> { }; self.introduce(uf, rank, &fresh); } - queue.push_front((wanted_rank, id, resolution_depth)); - queue.extend( - self.wanted - .split_off(start) - .into_iter() - .map(|(rank, id)| (rank, id, self.predicates.depth(id))), - ); + queue.push_front((wanted_rank, id)); + queue.extend(self.wanted.split_off(start)); continue; } } @@ -2224,8 +2212,7 @@ impl<'a> Solver<'a, '_> { crate::resolve::Selection::Deferred | crate::resolve::Selection::Missing ) && let Some(binder) = binder { - let mut remaining = WORK_LIMIT; - match self.cover(uf, rank, id, trait_, &args, &[], &mut remaining, 0) { + match self.cover(uf, rank, id, trait_, &args, &[]) { Ok(None) => {} Ok(Some(subs)) => { self.predicates.solve(uf, id, Solution::Specialize { subs }); @@ -2237,8 +2224,8 @@ impl<'a> Solver<'a, '_> { continue; }; match problem { - CoverageProblem::Limit => { - state.errors.push(Error::ImplResolutionLimit { + CoverageProblem::OutOfFuel => { + state.errors.push(Error::OutOfFuel { region: site.region, name: site.name, trait_, @@ -2315,13 +2302,8 @@ impl<'a> Solver<'a, '_> { } if binder.is_some() { let site = site.expect("wanteds originate at uses"); - let work = self - .resolution_work - .entry(self.predicates.root(id)) - .or_default(); - *work += 1; - if *work > WORK_LIMIT || resolution_depth >= DEPTH_LIMIT { - state.errors.push(Error::ImplResolutionLimit { + if tick().is_err() { + state.errors.push(Error::OutOfFuel { region: site.region, name: site.name, trait_, @@ -2331,8 +2313,8 @@ impl<'a> Solver<'a, '_> { } match selection { crate::resolve::Selection::Deferred => self.wanted.push((wanted_rank, id)), - crate::resolve::Selection::Limit => { - state.errors.push(Error::ImplResolutionLimit { + crate::resolve::Selection::OutOfFuel => { + state.errors.push(Error::OutOfFuel { region: site.region, name: site.name, trait_, @@ -2378,7 +2360,7 @@ impl<'a> Solver<'a, '_> { }, ); subs.push(sub); - queue.push_back((wanted_rank, sub, resolution_depth + 1)); + queue.push_back((wanted_rank, sub)); } self.predicates.solve( uf, @@ -2470,7 +2452,6 @@ impl<'a> Solver<'a, '_> { /// `Ok(None)`: coverage does not apply. `Ok(Some(subs))`: every admitted /// cell selects an impl, and `subs` prove each impl's context under its /// cell. The cells are never committed to inference. - #[allow(clippy::too_many_arguments)] fn cover( &mut self, uf: &mut UnionFind<'a>, @@ -2479,27 +2460,15 @@ impl<'a> Solver<'a, '_> { trait_: nash_ast::QualifiedName<'a>, args: &[Variable], assumptions: &[Body<'a>], - remaining: &mut usize, - depth: usize, ) -> Result>, CoverageProblem<'a>> { - if depth >= DEPTH_LIMIT { - return Err(CoverageProblem::Limit); - } let givens = self.given_bodies(assumptions); let mut allocated = Vec::new(); - let coverage = crate::resolve::coverage( - self.tables, - uf, - trait_, - args, - &givens, - &mut allocated, - remaining, - ); + let coverage = + crate::resolve::coverage(self.tables, uf, trait_, args, &givens, &mut allocated); self.introduce(uf, rank, &allocated); let covered = match coverage { crate::resolve::Coverage::NotApplicable => return Ok(None), - crate::resolve::Coverage::Limit => return Err(CoverageProblem::Limit), + crate::resolve::Coverage::OutOfFuel => return Err(CoverageProblem::OutOfFuel), crate::resolve::Coverage::Unstated(subject) => { return Err(CoverageProblem::MissingContext(Body::Trait { trait_, @@ -2538,10 +2507,10 @@ impl<'a> Solver<'a, '_> { solution: None, }, ); - if let Err(problem) = self.prove(uf, rank, sub, &cell, remaining, depth + 1) { + if let Err(problem) = self.prove(uf, rank, sub, &cell) { self.predicates.detach(uf, sub); return Err(match problem { - CoverageProblem::Limit => CoverageProblem::Limit, + CoverageProblem::OutOfFuel => CoverageProblem::OutOfFuel, _ => CoverageProblem::MissingContext(body), }); } @@ -2559,15 +2528,10 @@ impl<'a> Solver<'a, '_> { rank: usize, id: type_::PredId, assumptions: &[Body<'a>], - remaining: &mut usize, - depth: usize, ) -> Result<(), CoverageProblem<'a>> { use crate::preds::Solution; use nash_ast::primitives::{Repr, ReprTrait}; - nash_ast::head::step(remaining).map_err(|_| CoverageProblem::Limit)?; - if depth >= DEPTH_LIMIT { - return Err(CoverageProblem::Limit); - } + tick().map_err(|_| CoverageProblem::OutOfFuel)?; let body = self.predicates.get(id).body.clone(); if self.solve_from_givens(uf, rank, id, &body) { return Ok(()); @@ -2588,9 +2552,7 @@ impl<'a> Solver<'a, '_> { solution: None, }, ); - if let Err(problem) = - self.prove(uf, rank, sub, assumptions, remaining, depth + 1) - { + if let Err(problem) = self.prove(uf, rank, sub, assumptions) { self.predicates.detach(uf, sub); return Err(problem); } @@ -2664,9 +2626,7 @@ impl<'a> Solver<'a, '_> { solution: None, }, ); - if let Err(problem) = - self.prove(uf, rank, sub, assumptions, remaining, depth + 1) - { + if let Err(problem) = self.prove(uf, rank, sub, assumptions) { self.predicates.detach(uf, sub); return Err(problem); } @@ -2686,18 +2646,9 @@ impl<'a> Solver<'a, '_> { ); Ok(()) } - crate::resolve::Selection::Limit => Err(CoverageProblem::Limit), + crate::resolve::Selection::OutOfFuel => Err(CoverageProblem::OutOfFuel), crate::resolve::Selection::Deferred | crate::resolve::Selection::Missing => { - match self.cover( - uf, - rank, - id, - trait_, - &args, - assumptions, - remaining, - depth + 1, - )? { + match self.cover(uf, rank, id, trait_, &args, assumptions)? { Some(subs) => { self.predicates.solve(uf, id, Solution::Specialize { subs }); Ok(()) @@ -4371,7 +4322,7 @@ mod copy_tests { } #[test] - fn recovery_work_limit_does_not_drop_the_next_independent_predicate() { + fn recovery_out_of_fuel_does_not_drop_the_next_independent_predicate() { let bump = Bump::new(); let tables = nash_can::environment::Tables::default(); let mut solver = Solver { @@ -4388,7 +4339,6 @@ mod copy_tests { expr_types: Vec::new(), pattern_types: Vec::new(), owners: Vec::new(), - resolution_work: std::collections::HashMap::new(), has_poison: false, dependencies: crate::recovery::Dependencies::default(), failed_lineages: BTreeSet::new(), @@ -4437,21 +4387,22 @@ mod copy_tests { solver.wanted.push((OUTERMOST_RANK, id)); ids.push(id); } - solver.resolution_work.insert(ids[0], WORK_LIMIT); - let result = solver.resolve_wanted( - &mut uf, - OUTERMOST_RANK, - State { - env: Env::new(), - mark: NO_MARK.next(), - errors: Vec::new(), - }, - 0, - Some(binder), - false, - ); + let result = nash_ast::fuel::run(nash_ast::fuel::Fuel::Limited(0), || { + solver.resolve_wanted( + &mut uf, + OUTERMOST_RANK, + State { + env: Env::new(), + mark: NO_MARK.next(), + errors: Vec::new(), + }, + 0, + Some(binder), + false, + ) + }); assert!( - matches!(result.errors.as_slice(), [Error::ImplResolutionLimit { trait_: first, .. }, Error::MissingImpl { trait_: second, .. }] if first.name == "Expanding" && second.name == "Missing"), + matches!(result.errors.as_slice(), [Error::OutOfFuel { trait_: first, .. }, Error::OutOfFuel { trait_: second, .. }] if first.name == "Expanding" && second.name == "Missing"), "{:?}", result.errors ); @@ -4481,7 +4432,6 @@ mod copy_tests { expr_types: Vec::new(), pattern_types: Vec::new(), owners: Vec::new(), - resolution_work: std::collections::HashMap::new(), has_poison: false, dependencies: crate::recovery::Dependencies::default(), failed_lineages: BTreeSet::new(), @@ -4555,7 +4505,6 @@ mod copy_tests { expr_types: Vec::new(), pattern_types: Vec::new(), owners: Vec::new(), - resolution_work: std::collections::HashMap::new(), has_poison: false, dependencies: crate::recovery::Dependencies::default(), failed_lineages: BTreeSet::new(), @@ -4631,7 +4580,6 @@ mod copy_tests { expr_types: Vec::new(), pattern_types: Vec::new(), owners: Vec::new(), - resolution_work: std::collections::HashMap::new(), has_poison: false, dependencies: crate::recovery::Dependencies::default(), failed_lineages: BTreeSet::new(), @@ -4720,7 +4668,6 @@ mod copy_tests { expr_types: Vec::new(), pattern_types: Vec::new(), owners: Vec::new(), - resolution_work: std::collections::HashMap::new(), has_poison: false, dependencies: crate::recovery::Dependencies::default(), failed_lineages: BTreeSet::new(), @@ -4859,7 +4806,6 @@ mod copy_tests { expr_types: Vec::new(), pattern_types: Vec::new(), owners: Vec::new(), - resolution_work: std::collections::HashMap::new(), has_poison: false, dependencies: crate::recovery::Dependencies::default(), failed_lineages: BTreeSet::new(), @@ -5031,7 +4977,6 @@ mod copy_tests { expr_types: Vec::new(), pattern_types: Vec::new(), owners: Vec::new(), - resolution_work: std::collections::HashMap::new(), has_poison: false, dependencies: crate::recovery::Dependencies::default(), failed_lineages: BTreeSet::new(), @@ -5117,7 +5062,6 @@ mod copy_tests { expr_types: Vec::new(), pattern_types: Vec::new(), owners: Vec::new(), - resolution_work: std::collections::HashMap::new(), has_poison: false, dependencies: crate::recovery::Dependencies::default(), failed_lineages: BTreeSet::new(), diff --git a/crates/nash-solve/tests/evidence.rs b/crates/nash-solve/tests/evidence.rs index 706701b3..ef1fbd78 100644 --- a/crates/nash-solve/tests/evidence.rs +++ b/crates/nash-solve/tests/evidence.rs @@ -552,7 +552,10 @@ fn ground_resolution_reports_missing_open_and_expanding_requirements() { trait_, args: bump.alloc_slice_copy(&[input(&annotations, name)]), }; - (name, resolve(&bump, &tables, &pred).unwrap_err().reason) + let result = nash_ast::fuel::run(nash_ast::fuel::Fuel::Limited(20_000), || { + resolve(&bump, &tables, &pred) + }); + (name, result.unwrap_err().reason) }) .collect(); assert_eq!( @@ -560,35 +563,12 @@ fn ground_resolution_reports_missing_open_and_expanding_requirements() { vec![ ("missing", Failure::MissingImpl), ("open", Failure::NonGround), - ("growing", Failure::Limit), - ("cycle", Failure::Limit), + ("growing", Failure::OutOfFuel), + ("cycle", Failure::OutOfFuel), ("function", Failure::MissingImpl), ("openFunction", Failure::MissingImpl), ] ); - let mut deep = input(&annotations, "missing"); - for _ in 0..140 { - deep = bump.alloc(Located::at_zero(Type::Named { - reference: QualifiedName { - home: nash_ast::primitives::primitive_home(), - name: "list", - }, - args: bump.alloc_slice_copy(&[deep]), - })); - } - assert_eq!( - resolve( - &bump, - &tables, - &Pred::Trait { - trait_, - args: bump.alloc_slice_copy(&[deep]) - } - ) - .unwrap_err() - .reason, - Failure::Limit - ); } #[test] diff --git a/crates/nash-solve/tests/inference.rs b/crates/nash-solve/tests/inference.rs index ad892191..38c5fcd7 100644 --- a/crates/nash-solve/tests/inference.rs +++ b/crates/nash-solve/tests/inference.rs @@ -358,12 +358,13 @@ fn recovery_final_recursive_evidence_error_survives_an_independent_mismatch() { } #[test] -fn recovery_resolution_limit_keeps_unrelated_obligations() { +fn recovery_out_of_fuel_keeps_unrelated_obligations() { let bump = Bump::new(); - infer_output_snapshot!( - &bump, - indoc!( - r#" + nash_ast::fuel::run(nash_ast::fuel::Fuel::Limited(5_000), || { + infer_output_snapshot!( + &bump, + indoc!( + r#" module Main exposing (..) trait Keep 'a where keep : 'a -> 'a @@ -375,9 +376,10 @@ fn recovery_resolution_limit_keeps_unrelated_obligations() { sibling : () sibling = \x -> x "# - ), - ) - .expect_err("limit and independent failures"); + ), + ) + }) + .expect_err("out of fuel and independent failures"); } #[test] @@ -1384,8 +1386,9 @@ fn enclosing_given_wins_after_lambda_parameter_types_are_known() { #[test] fn expanding_impl_context_stops_with_a_diagnostic() { - assert_inference_error_snapshot!( - r#" + nash_ast::fuel::run(nash_ast::fuel::Fuel::Limited(5_000), || { + assert_inference_error_snapshot!( + r#" module Main exposing (..) trait Keep 'a where keep : 'a -> 'a @@ -1394,7 +1397,8 @@ fn expanding_impl_context_stops_with_a_diagnostic() { value : list unit value = keep [()] "# - ); + ); + }); } #[test] @@ -5660,36 +5664,6 @@ fn coverage_reports_the_uncovered_representation() { ); } -/// Six subjects give 729 cells, more than one work budget can select. -#[test] -fn coverage_search_stops_at_the_work_limit() { - assert_inference_error_snapshot!( - r#" - module Main exposing (..) - import Primitive exposing (Big, Little) - type six 'a 'b 'c 'd 'e 'f = Six 'a 'b 'c 'd 'e 'f - trait Kind 'a where - kind : 'a -> () - impl Kind (six ('a : Big) 'b 'c 'd 'e 'f) where - kind _ = () - impl Kind (six ('a : Little) ('b : Big) 'c 'd 'e 'f) where - kind _ = () - impl Kind (six ('a : Little) ('b : Little) ('c : Big) 'd 'e 'f) where - kind _ = () - impl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Big) 'e 'f) where - kind _ = () - impl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Little) ('e : Big) 'f) where - kind _ = () - impl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Little) ('e : Little) ('f : Big)) where - kind _ = () - impl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Little) ('e : Little) ('f : Little)) where - kind _ = () - check : ( Kind 'a, Kind 'b, Kind 'c, Kind 'd, Kind 'e, Kind 'f ) => six 'a 'b 'c 'd 'e 'f -> () - check x = kind x - "# - ); -} - /// Coverage applies to rigid variables only: an unannotated definition keeps /// the constraint on the container in its inferred context. #[test] diff --git a/crates/nash-solve/tests/snapshots/inference__coverage_search_stops_at_the_work_limit.snap b/crates/nash-solve/tests/snapshots/inference__coverage_search_stops_at_the_work_limit.snap deleted file mode 100644 index 42cae8e0..00000000 --- a/crates/nash-solve/tests/snapshots/inference__coverage_search_stops_at_the_work_limit.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: crates/nash-solve/tests/inference.rs -description: "module Main exposing (..)\nimport Primitive exposing (Big, Little)\ntype six 'a 'b 'c 'd 'e 'f = Six 'a 'b 'c 'd 'e 'f\ntrait Kind 'a where\n kind : 'a -> ()\nimpl Kind (six ('a : Big) 'b 'c 'd 'e 'f) where\n kind _ = ()\nimpl Kind (six ('a : Little) ('b : Big) 'c 'd 'e 'f) where\n kind _ = ()\nimpl Kind (six ('a : Little) ('b : Little) ('c : Big) 'd 'e 'f) where\n kind _ = ()\nimpl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Big) 'e 'f) where\n kind _ = ()\nimpl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Little) ('e : Big) 'f) where\n kind _ = ()\nimpl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Little) ('e : Little) ('f : Big)) where\n kind _ = ()\nimpl Kind (six ('a : Little) ('b : Little) ('c : Little) ('d : Little) ('e : Little) ('f : Little)) where\n kind _ = ()\ncheck : ( Kind 'a, Kind 'b, Kind 'c, Kind 'd, Kind 'e, Kind 'f ) => six 'a 'b 'c 'd 'e 'f -> ()\ncheck x = kind x\n" -info: diagnostic ---- -nash::type::impl_resolution_limit - - × Impl resolution for `Kind` in `kind` exceeded the work limit. - ╭─[Main.nash:21:11] - 20 │ check : ( Kind 'a, Kind 'b, Kind 'c, Kind 'd, Kind 'e, Kind 'f ) => six 'a 'b 'c 'd 'e 'f -> () - 21 │ check x = kind x - · ──── - ╰──── - help: This requirement remains unchecked; other reported errors still apply. - - Simplify cyclic or growing impl constraints. diff --git a/crates/nash-solve/tests/snapshots/inference__expanding_impl_context_stops_with_a_diagnostic.snap b/crates/nash-solve/tests/snapshots/inference__expanding_impl_context_stops_with_a_diagnostic.snap index 947432bb..37937436 100644 --- a/crates/nash-solve/tests/snapshots/inference__expanding_impl_context_stops_with_a_diagnostic.snap +++ b/crates/nash-solve/tests/snapshots/inference__expanding_impl_context_stops_with_a_diagnostic.snap @@ -3,9 +3,9 @@ source: crates/nash-solve/tests/inference.rs description: "module Main exposing (..)\ntrait Keep 'a where\n keep : 'a -> 'a\nimpl Keep (list (list 'a)) => Keep (list 'a) where\n keep xs = xs\nvalue : list unit\nvalue = keep [()]\n" info: diagnostic --- -nash::type::impl_resolution_limit +nash::type::out_of_fuel - × Impl resolution for `Keep` in `keep` exceeded the work limit. + × Resolving `Keep` in `keep` needed more compilation steps than the editor allows. ╭─[Main.nash:7:9] 6 │ value : list unit 7 │ value = keep [()] @@ -13,4 +13,4 @@ nash::type::impl_resolution_limit ╰──── help: This requirement remains unchecked; other reported errors still apply. - Simplify cyclic or growing impl constraints. + `nash check` has no step limit. Simplify cyclic or growing impl constraints. diff --git a/crates/nash-solve/tests/snapshots/inference__recovery_resolution_limit_keeps_unrelated_obligations.snap b/crates/nash-solve/tests/snapshots/inference__recovery_out_of_fuel_keeps_unrelated_obligations.snap similarity index 88% rename from crates/nash-solve/tests/snapshots/inference__recovery_resolution_limit_keeps_unrelated_obligations.snap rename to crates/nash-solve/tests/snapshots/inference__recovery_out_of_fuel_keeps_unrelated_obligations.snap index 07f556e6..1d1a75d0 100644 --- a/crates/nash-solve/tests/snapshots/inference__recovery_resolution_limit_keeps_unrelated_obligations.snap +++ b/crates/nash-solve/tests/snapshots/inference__recovery_out_of_fuel_keeps_unrelated_obligations.snap @@ -17,9 +17,9 @@ nash::type::mismatch ╰──── -nash::type::impl_resolution_limit +nash::type::out_of_fuel - × Impl resolution for `Keep` in `keep` exceeded the work limit. + × Resolving `Keep` in `keep` needed more compilation steps than the editor allows. ╭─[Main.nash:8:10] 7 │ keep xs = xs 8 │ value = (keep [(assert Primitive.True)], missing (assert Primitive.True)) @@ -28,7 +28,7 @@ nash::type::impl_resolution_limit ╰──── help: This requirement remains unchecked; other reported errors still apply. - Simplify cyclic or growing impl constraints. + `nash check` has no step limit. Simplify cyclic or growing impl constraints. nash::type::missing_impl diff --git a/docs/diagnostics.md b/docs/diagnostics.md index 1c1add04..2febb8db 100644 --- a/docs/diagnostics.md +++ b/docs/diagnostics.md @@ -41,8 +41,8 @@ module exports neither an interface nor successful solved output. Mark its dependents as blocked by the original failure instead of inventing missing imports or missing types. -Resolution limits stop the affected computation and produce a diagnostic; -they do not discard errors already collected or suppress independent work. +Running out of compilation fuel stops the affected computation and produces a +diagnostic; it does not discard errors already collected or suppress independent work. Never silently truncate the result. Any resource limit on diagnostic collection must explicitly report that additional errors may remain. diff --git a/docs/traits.md b/docs/traits.md index e8bbf633..9acabe85 100644 --- a/docs/traits.md +++ b/docs/traits.md @@ -270,9 +270,9 @@ when it needs one that is missing. every *cell*, one representation per subject (Big, Const or Term, as the representation and formation givens admit), must select an impl, and the context of each selected impl must hold in its cell. The evidence is - `Specialize P`; code generation selects the impl for each use. One work - budget (16,384 steps) pays for finding the subjects, the cells and every - selection; more is an impl-resolution-limit error. Rigid variables come only + `Specialize P`; code generation selects the impl for each use. The compile's + fuel pays for finding the subjects, the cells and every selection; running + out is an out-of-fuel error. Rigid variables come only from annotations: an unannotated definition keeps `T (list 'a)` in its inferred context. @@ -292,14 +292,15 @@ constructor at the same application arity conflicts when corresponding argument kinds can unify. This check does not assume that different head variable names make impls disjoint. -Superclass checking during canonicalization performs a bounded search. +Superclass checking during canonicalization performs a search. A predicate already active in the instance-resolution chain is a cycle, -not a proof. Expanding flexible contexts are bounded too: each impl check -allows 16,384 work steps and fewer than 256 nested resolution or type -conversion calls. Predicate comparisons count toward the work limit. +not a proof. Expanding flexible contexts have no fixed bound: every +resolution step, type conversion and predicate comparison draws from the +compile's fuel (see [Compilation fuel](#compilation-fuel)). Failure reports the instantiated superclass requirement and distinguishes -a missing proof, a cycle, and the search limit. The given superclass -closure is computed once per impl and reused for its requirements. +a missing proof and a cycle; running out of fuel is its own error at the impl. +The given superclass closure is computed once per impl and reused for its +requirements. Evidence is the derivation: @@ -317,6 +318,24 @@ Evidence = Impl { impl_: ImplRef, type_args: [Type], args: [Evidence] } -- by_i Context reduction: a retained context never contains both `Ord 'a` and `Eq 'a`; the superclass is dropped and its uses get `Super` evidence. +### Compilation fuel + +Impl contexts need not shrink, so entailment, overlap checks, solver +resolution, evidence resolution and code generation can run forever on a +program the type rules accept. They share one step counter instead of one +budget each. The driver installs a `Fuel` (`nash_ast::fuel`) around each +module's compile; every search step takes one `tick`, and a pass over an +existing type pays for its nodes with `charge`, so the steps track time even +when types grow. `nash check`, `build`, `test` and `docs` run `Unlimited`; +the language server runs `Limited`, so an editor never freezes on a looping +program. Nothing caps depth: a deeper input costs more steps and recursion +runs on the compiler stack. + +Running out is one error kind, `COMPILATION STEP LIMIT` +(`nash::type::out_of_fuel`). The solver reports it at the use that needed the +search, canonicalization at the impl being checked, and code generation as a +plain error without a region. An exhausted search never counts as a proof. + ## Inference Nash keeps Elm's rank-based solver (`nash-solve`). Predicates ride along @@ -406,9 +425,9 @@ context is the given set. Impl selection waits for the surrounding definition's type equalities. Captured outer variables must also be fixed before rejecting an enclosing given in favor of an impl. Impl contexts may expand indefinitely; resolution -is bounded to 256 levels and 16,384 attempts per definition boundary. Exceeding -either bound reports `ImplResolutionLimit` at the originating call. An -exhausted search never counts as evidence that a constraint was satisfied. +draws from the compile's fuel. Running out reports an out-of-fuel error at the +originating call. An exhausted search never counts as evidence that a +constraint was satisfied. Elm's `SaveTheEnvironment` step is unchanged: top-level annotations are read back with `to_annotation`, which now also emits the retained @@ -468,7 +487,7 @@ For each ambiguous variable, in order: Apply available defaults and retry resolution before reporting remaining ambiguity: an impl selected by one default can introduce the literal requirement for another variable. Keep the same enclosing givens, boundary -rank, predicate origins and resolution limits across these rounds. +rank, predicate origins and fuel across these rounds. Defaulting runs at every generalizing Let, not only at the top level, so the error region is the innermost definition that lost the variable. This @@ -584,10 +603,10 @@ selects an impl needs a stated constraint, so type checking reports that case first. The predicate never needs `Given`, so the result is a closed tree of `Impl` and exact-core `ReflexiveLift` evidence. Reflexive Lift requires nominally equal arguments and does not choose a representation. -Failures distinguish `MissingImpl`, `NonGround`, and `Limit`, retaining the -failed predicate. Resolution and type traversal share a 16,384-step work -budget, with a depth limit of 256. Context substitution is charged before -allocation. Callers supply well-kinded canonical types and complete tables. +Failures distinguish `MissingImpl`, `NonGround`, and `OutOfFuel`, retaining the +failed predicate. Resolution and type traversal draw from the compile's fuel. +Context substitution is charged before allocation. Callers supply +well-kinded canonical types and complete tables. Codegen specializes executable trait evidence at compile time. It walks a definition with a substitution `Given { binder, index } -> Evidence` for its diff --git a/plans/02-kind-rewrite-audit.md b/plans/02-kind-rewrite-audit.md index 23537e85..9ea0a114 100644 --- a/plans/02-kind-rewrite-audit.md +++ b/plans/02-kind-rewrite-audit.md @@ -15,7 +15,7 @@ The head-matching and insertion descriptions incorporate the completed - Kind compatibility is checked before head matching. `head::overlaps` unifies recursive heads and intersects variable representation classes; its callback supplies concrete head representations. Independent binders, - repeated variables, occurs checks and work limits remain part of matching. + repeated variables, occurs checks and fuel ticks remain part of matching. - `insert_impl` uses the kind environment to obtain concrete representations during overlap checking. `check_annotation` has no module-name argument. - `KindHead` and the unproduced `KindContext::TypeArg`, `ValuePosition` @@ -91,8 +91,8 @@ base kinds or expose the removed kind-scheme API. In particular: These are contract corrections for later work. Runtime/codegen, optimizer implementation, macros, default imports, Prop and the full validator example -remain deferred. Trait search keeps its existing 128-level and 16,384-work -limits; no Paterson restriction or new impl admission policy is introduced. +remain deferred. Trait search keeps its existing policy; no Paterson +restriction or new impl admission policy is introduced. ## Validation diff --git a/plans/03-traits.md b/plans/03-traits.md index 0c526039..c087e392 100644 --- a/plans/03-traits.md +++ b/plans/03-traits.md @@ -821,9 +821,10 @@ are flexible and may contain nested types or higher-kinded applications. It uses rigid, nominal terms, flattens type applications, and ignores source regions when comparing predicates. Given superclass closure is computed once per impl. Active instance cycles fail; expanding contexts and -structural comparisons share a 16,384-step budget, with a depth limit of -128. `MissingSuperclass` includes the instantiated requirement and a -`Missing`, `Cycle`, or `Limit` reason. No failed or limited search is a proof. +structural comparisons draw from the compile's fuel (`nash_ast::fuel`). +`MissingSuperclass` includes the instantiated requirement and a +`Missing` or `Cycle` reason; running out of fuel is a separate `OutOfFuel` +error at the impl. No failed or exhausted search is a proof. Methods: @@ -1715,8 +1716,8 @@ them to children, and excludes `NO_RANK` generalized variables. A case-branch regression verifies this against both inference and the CLI. Tests cover nested applications of the same impl, context reduction, missing child impls, given precedence through lambdas/local helpers, and expanding -contexts. Resolution reports `ImplResolutionLimit` after 128 levels or 16,384 -expansions at a boundary. A real CLI project imports the trait and impls from +contexts. Resolution reports `OutOfFuel` when the compile's fuel runs out at a +boundary. A real CLI project imports the trait and impls from another module and successfully checks `keep [[()]]`. Replacing the element with a type that has no impl reports `MissingImpl` at the importing module's call and exits with status 1. @@ -1759,7 +1760,7 @@ impl<'a> Solver<'a> { Selected { key, info, substitution } => (key, info, substitution), Deferred => return defer_without_binding(id), Missing => return Err(self.missing_impl(uf, &pred)), - Limit => return Err(self.impl_resolution_limit(uf, &pred)), + OutOfFuel => return Err(self.out_of_fuel(uf, &pred)), }; let rank = self.wanted_rank_of(id); let subs: Vec = info.context.iter().enumerate().map(|(index, ctx)| { @@ -1909,8 +1910,8 @@ uses `nash_can::types::substitute_type`, retaining alias binders. An exact-core Lift predicate on nominally equal, already-Big arguments produces `ReflexiveLift`. The kind proof reuses canonical kind inference and permits inferred record carriers only while their representation stays unrestricted. -Recursive resolution and structural traversal share 16,384 work steps and -depth 128; substitution is charged before allocation. Callers provide +Recursive resolution and structural traversal draw from the compile's fuel; +substitution is charged before allocation. Callers provide well-kinded canonical types and complete metadata. This API has no givens and does not create inference variables. diff --git a/plans/04-representation.md b/plans/04-representation.md index 764a8b07..f4d723d0 100644 --- a/plans/04-representation.md +++ b/plans/04-representation.md @@ -27,7 +27,7 @@ Cover declaration checking, type inference, trait resolution, specialization, generalization, evidence, interfaces, diagnostics and tests. Preserve Haskell 98 semantics, representation predicates, terminating datatype-context inference and Plan 03 behavior. Keep the existing trait-resolution policy and -search limits; do not add Paterson-style restrictions. Preserve later-plan +search bounds; do not add Paterson-style restrictions. Preserve later-plan deferrals and unrelated work. Replace obsolete tests and descriptions with explicit assertions of the new diff --git a/plans/06-diagnostics.md b/plans/06-diagnostics.md index 8944fe40..95219085 100644 --- a/plans/06-diagnostics.md +++ b/plans/06-diagnostics.md @@ -2461,8 +2461,8 @@ or SolvedTypes from a failed solve. and recursive definitions so recovery is not tested only on disjoint trees. - Two independent failing modules both report. A dependent module is blocked by the original failure without fabricated missing-import/type errors. -- An impl-resolution cycle or work limit terminates the affected computation - while preserving collected errors and unrelated diagnostics. +- An impl-resolution cycle or running out of compilation fuel terminates the + affected computation while preserving collected errors and unrelated diagnostics. - Repeated CLI runs and shuffled module discovery have identical ordering: canonical module path, primary span, then stable diagnostic tie-breakers. Terminal snapshots, JSON and LSP assert the same problem set and spans. diff --git a/plans/07-codegen.md b/plans/07-codegen.md index 4124c5b2..144d4906 100644 --- a/plans/07-codegen.md +++ b/plans/07-codegen.md @@ -47,10 +47,10 @@ Concrete integration choices: - Generalized local values needing evidence or native layout are templates, evaluated per requested specialization. Other local values remain strict; there is no arbitrary instance selection for an unused overloaded value. -- Specialization has explicit body/type-depth limits, recursive Data validation - has a helper-count limit, and branch normalization has a work limit. These are - resource errors, not claims that a single observed type-size increase proves - infinite specialization. +- Specialization, evidence normalization and branch normalization draw from the + compile's fuel and report one out-of-fuel error; recursive Data validation + has a helper-count limit. These are resource errors, not claims that a single + observed type-size increase proves infinite specialization. - Strict nullary recursive values are diagnosed during codegen. The historical `ones` sketch below does not create a lazy infinite native list. - Test-only power-assert rewriting remains Plan 10. Validator assertions retain