Skip to content

fix(semantic): a binding that mentions a bound generic does not enter the function solver - #1371

Open
mareklangiewicz wants to merge 4 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-solver-self-mentioning-binding
Open

mareklangiewicz wants to merge 4 commits into
EmmyLuaLs:mainfrom
mareklangiewicz:fix-solver-self-mentioning-binding

Conversation

@mareklangiewicz

Copy link
Copy Markdown
Contributor

Summary

A generic bound to a type that mentions a bound generic makes functions_compatible run until memory is gone. emmylua_check on mason.nvim reaches about 11 GB. This is enough to do it:

local _ = {}
---@generic T : fun(...)
---@param fn T
_.curry = function(fn)
    return function(...) end
end
---@generic T, V
---@param fn fun(...): T
_.converge = _.curry(function(fn, fns, val) end)

seen_pairs stops the solver when a function pair comes round again. Solving substitutes on every expansion, so with such a binding each pair is larger than the last and none repeats:

 functions_compatible(actual, expected, bindings)
   bindings = bindings.clone()
+  drop each binding whose value mentions a bound generic
   while constraint = queue.pop()
     FnPair: if seen_pairs has it, skip
       substitute, then push nested pairs

The check sits here because this is the one loop that substitutes repeatedly, while bindings are inserted in about ten places. A dropped generic stays open.

Evidence

  • Before: test_generic_bound_to_a_type_that_mentions_it_terminates: has overflowed its stack in a debug build. A release emmylua_check on the source above hits any memory cap; on mason.nvim, about 11 GB and the OOM killer. 0.25.1 is fine on both.
    After: the test passes, with 1703 passed, 0 failed in emmylua_code_analysis.

Merge Danger

Door: two-way

Revert restores the old behaviour. No API or config change.

Blast Radius: generics

An open generic accepts more, so this can only lose a report, not add one. On a fork with this change, 57 Neovim plugins plus runtime/ gave the same 51081 diagnostics before and after, and mason.nvim finishes in 4 s. That was measured on the fork, not on this branch.


Written with help from Claude Code.

… the function solver

Solving substitutes repeatedly, so such a binding grew each function pair and the
`seen_pairs` guard never saw one twice: mason.nvim's functional/function.lua took
about 11 GB. Dropped, the generic stays open, which only ever accepts more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUURL8eZPTs95zm47G6C

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review

Summary

The change fixes a non-termination bug in the function solver by dropping bindings whose value references a generic that is itself bound. The fix is reasonable, but there are a few concerns.

Issues & Suggestions

1. bound is computed from the input bindings, not the retained ones — likely correct but subtle

let bound: Vec<_> = bindings.keys().cloned().collect();
bindings.retain(|_, value| {
    !value.any_type(|ty| matches!(ty, LuaType::TplRef(tpl) if bound.contains(&tpl.get_tpl_id())))
});
  • bound is a Vec, so bound.contains(...) is O(n) per type node. For small generic sets this is fine, but a HashSet (or FxHashSet) would be clearer and faster. TplId presumably implements Hash + Eq (it's used as a map key), so this is a trivial improvement.
  • The semantics: a binding T -> ...T... is dropped. This is the intended fix, but note it also drops legitimate recursive/self-referential bindings (e.g. T -> fun(T): T), not just the pathological growth case. That may be acceptable (the comment says "its generic stays open"), but it's a behavioral change worth documenting in the commit message / changelog, since previously such bindings were kept.

2. retain closure captures bound by reference — fine, but consider retain vs. rebuilding
No issue, just noting the closure borrows bound immutably while bindings is mutably borrowed; this compiles because they're distinct locals. OK.

3. Missing use ordering / style
use crate::LuaTypeNode; is inserted between LuaFunctionType and LuaType. If the project uses rustfmt with group_imports/imports_granularity, this may be reordered. Minor; run cargo fmt.

4. Test does not assert termination explicitly

_.converge = _.curry(function(fn, fns, val) end)

The test only calls check_source and relies on the test harness not hanging. If the solver regresses to infinite looping, the test will hang rather than fail — CI timeouts are the only signal. Consider:

  • Adding a comment noting the test is a regression guard for termination (already partially done).
  • If the harness supports it, wrapping in a timeout, or at minimum asserting the expected diagnostics are empty/known so a silent behavior change is caught.

5. Test doesn't verify the result of dropping the binding
Because the binding is dropped, T "stays open." The test passes as long as no panic/hang occurs, but it doesn't check that the inferred type or diagnostics are sensible. Consider asserting on diagnostics (e.g. assert!(diagnostics.is_empty())) so the test also guards against over-eager dropping producing spurious errors.

6. Comment wording

"Solving substitutes again and again, so a binding that mentions a bound generic would grow each pair and seen_pairs would never see one twice."

This is a bit terse. Suggest clarifying why dropping is safe: e.g. "Dropping the binding leaves the generic unconstrained (open), which is the conservative choice; keeping it causes unbounded type growth." Also mention the trade-off from point 1.

Minor

  • LuaTypeNode import: confirm it's actually used (it is, via any_type's closure param type inference — but the explicit import may be unnecessary if the closure param is inferred; check whether the compiler warns about unused import).

Verdict

The core fix is sound and addresses a real termination bug. Recommended before merge:

  1. Use a HashSet for bound.
  2. Add an assertion on diagnostics in the test.
  3. Clarify the comment about the trade-off (dropping legitimate recursive bindings).
  4. Run cargo fmt for import ordering.

…cks the result

From the bot review. The comment now names the trade-off: a dropped
binding can lose a catch, not add one. The test also asserts the call
stays free of `param-type-mismatch`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUPAKyiJnPD57aeKcPG
@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Thanks. Applied in 31054fb:

  • bound is a HashSet.
  • The comment names the trade-off: a self-mention that would have stopped growing is dropped too, so this can lose a catch but not add one.
  • The test asserts the call stays free of param-type-mismatch.

Not applied: a timeout around the test. The harness has none, and the regression shows up as a test that never ends, with memory growing until it is killed.


Written with help from Claude Code.

@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Still reproduces on current main b889a2d1: emmylua_check on mason.nvim grows past 3 GB and is OOM-killed after about 20 s, deep in unify::substitute under functions_compatible. With this PR on top of b889a2d1 (plus #1365, #1370, #1372 and the variadic-callback panic fix), it finishes in under 2 s. 0.25.1 finishes too.


Written with help from Claude Code.

@CppCXY

CppCXY commented Nov 17, 2026

Copy link
Copy Markdown
Member

please resolve conflicts

Both sides appended a test at the end of param_type_check_test.rs; keep both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUURuHC3PYn4Usu9dy1H
@mareklangiewicz

Copy link
Copy Markdown
Contributor Author

Resolved: merged current main (4136671) in 5f7d76f. The only conflict was in param_type_check_test.rs, where this PR and main each appended a test at the end; both are kept. All emmylua_code_analysis tests pass, as do cargo fmt and clippy.


Written with help from Claude Code.

Test-file conflicts only: main's version of the file, with this
branch's tests re-added at the end of the module and its test-helper
imports kept. The branch's changed lines are unchanged against main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018NxUUQZHt6a5njk8trY5BZ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants