Repository navigation
fix(types): a union with a repeated member equals itself - #1365
mareklangiewicz wants to merge 4 commits into
Conversation
LuaUnionMembers::eq collected one side into a HashSet and removed the other side's members from it, so a repeated member failed its second remove: `a == a` was false. unify_call_bindings takes `expanded_arg != arg` as progress, so such a union passed to a generic class param never settled and overflowed the stack. Count members instead, which matches the hash, a sum over members. An in-order compare answers first, so the usual equal case allocates nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUN2Yt6d9cgKQzcoC84
There was a problem hiding this comment.
Code Review
Summary
The change fixes a real correctness bug: PartialEq for LuaUnionMembers used a HashSet, which silently collapses duplicate members. A union containing a repeated member (e.g. A | A | B) could therefore compare unequal to itself, breaking the reflexivity contract of PartialEq and causing infinite recursion/stack overflow during generic expansion. The fix is sound and the tests are appropriate.
Issues & Suggestions
1. PartialEq / Hash contract (important)
The new implementation makes equality multiset-based (order-insensitive, count-sensitive). This is only correct if Hash for LuaUnionMembers is also multiset-based (i.e. order-insensitive and count-sensitive). Please verify:
- If
Hashiterates members in order, thenA|BandB|Awould be equal but hash differently → violates theHash/Eqcontract. - If
Hashuses aHashSet/dedup, thenA|A|BandA|Bwould hash the same but compare unequal → also a violation.
The test comment ("their hashes differ, so they must not be equal") suggests hashing is count-sensitive, but this should be asserted explicitly, e.g.:
assert_eq!(FxBuildHasher.hash_one(&union()), FxBuildHasher.hash_one(&union()));
assert_ne!(FxBuildHasher.hash_one(&union()), FxBuildHasher.hash_one(&other));and ideally a test that A|B == B|A with equal hashes.
2. Fast path is redundant but harmless
if self.types == other.types {
return true;
}This is a reasonable optimization for the common case, but note it relies on Vec element-wise equality. It's fine, though the comment could clarify it's a fast path rather than a semantic requirement.
3. HashMap import
The diff uses HashMap in complex.rs but the import isn't shown. Ensure use rustc_hash::FxHashMap as HashMap; (or equivalent) is present — otherwise this won't compile. Given the file already uses FxBuildHasher, prefer FxHashMap for consistency and performance over std::collections::HashMap.
4. Missing len check in the new path
The old code implicitly relied on types.is_empty() after removal. The new code checks count > 0 per element, which is correct, but if other.types has fewer elements than self.types, leftover counts are never checked. Example: self = [A, A], other = [A] → all() returns true, but the multisets differ. The early self.types.len() != other.types.len() check at the top of the function (visible in context) covers this — please confirm it's still present and runs before the new logic. If it was removed, this is a bug.
5. Test quality
test_union_arg_with_repeated_member_no_crashonly asserts "no panic". Consider also asserting the expected diagnostic count (or at least thatdiagnose_filereturnsOk) to catch regressions where the crash is fixed but diagnostics are wrong.- The test uses undefined globals (
source,buf,ct,TSTree) intentionally to reproduce the bug; a brief comment noting this is deliberate would help future readers.
6. Style nit
let mut counts = HashMap::<_, usize>::with_capacity(self.types.len());The turbofish is unnecessary; HashMap::with_capacity(...) infers fine. Minor.
Verdict
The core fix is correct and well-motivated. Main follow-ups: verify the Hash/Eq contract for the multiset semantics, confirm the length pre-check still exists, and use FxHashMap for consistency.
…changes the hash Answers the review: Eq counts members and the hash sums over them, so order does not count and repeats do, on both sides. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUUPGy5eT16LumQqytKE
|
Thanks. Point by point:
This is now a crash on main, not just a latent one: on Written with help from Claude Code. |
…e check Reduced from snacks.nvim: since the need-check-nil rewrite (EmmyLuaLs#1418), checking the second file compares `table|X|X` against a closure signature. Without the fix that union is unequal to itself, so Comparisons::intern never finds its own key and the check never ends (main 48ef52a: >90 s on the two files). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018NxUURcPwXMM3gTzFZqTDa
|
Merged main Written with help from Claude Code. |
|
Closing: b740a84 ("Refactor the union") fixed this at the source. I checked it on main 2d2374f with only this PR's tests added, without its Written with help from Claude Code. |
Summary
LuaUnionMembers::eqis not reflexive when a member repeats, and that can overflow the stack.unify_call_bindingstakesexpanded_arg != argas progress, so it recurses for as long as a union with a repeated member differs from its own rebuild:The union comes from flow analysis, not from an annotation: here
parseis assigned the same call twice, with a closure in between.It is reduced from neovim's
runtime/lua/vim/treesitter/languagetree.lua.Main reaches the loop on real code too: on
b889a2d1,emmylua_checkaborts with a stack overflow on async.nvim (lua/async/_core.lua). Reduced, with no generic param on the callee:The flow type of
selfatclear(self)isTask|Task<any>|nil|Task, and theGenericarm recurses on it.Since the need-check-nil rewrite (#1418, first bad commit
280987f7by bisect from 0.25.1), main can also hang on it. A return union with a repeated member is unequal to itself, soComparisons::internnever finds its own key, and each read interns a new comparison. On main48ef52a0,emmylua_checkdoes not finish these two files (>90 s, flat memory); with this change it takes 0.14 s. Reduced from snacks.nvim (picker/config/init.lua,picker/actions.lua):On the whole snacks.nvim tree main gets through in 7.4 s, but a small change to flow narrowing elsewhere is enough to route it into this shape and time out (#1361 does).
Evidence
The three tests are in this PR, on the branch merged with main
48ef52a0; "before" isLuaUnionMembers::eqas on main:union_with_a_repeated_member_equals_itself: FAILED,A|A|B != A|A|Btest_union_arg_with_repeated_member_no_crash:has overflowed its stacktest_return_union_with_repeated_member_no_hang: times out at 5 s, 10 runs of 10 (after: 0.02 s, 10 of 10)emmylua_code_analysis1988 andemmylua_ls243 lib tests pass; fmt and clippy pass.emmylua_checkon 59 Neovim plugin trees and neovim'sruntime/, against main48ef52a0):async.nvim,bufferline.nvimandneovim-runtimeno longer crash and finish. On the trees both builds finish, 13 lines change, allassign-type-mismatchon record literals in blink.cmp, diffview.nvim and nui.nvim; main alone flips the same lines from run to run (the field order picked for the message, fix(check): a record literal's first mismatching field is the same every run #1437), so no hit changes (57302 → 57301 is one such pair).Merge Danger
Door: two-way
Blast Radius: diagnostics
Any code comparing unions now gets
truefor equal unions with repeated members, andA|A|Bstays unequal toA|B|B. On a fork of main carrying this change, diagnostics on three Lua repos did not change.Written with help from Claude Code.