castwide / solargraph

A Ruby language server.
https://solargraph.org
MIT License
1.88k stars 157 forks source link

[bug]type checker ignore break return type #480

Open SolaWing opened 2 years ago

SolaWing commented 2 years ago
# @type [Array<Integer>]
a = [1]
# @type [String]
b = a.find { |v| break v.to_s if v == 1 } # <-- [Typecheck] [E] Declared type String does not match inferred type Integer for variable b
castwide commented 2 years ago

Confirmed. Solargraph assumes that the return type of Array#find is the array's parameter type (or nil if no match is found). In most cases this is true, but the use of break is an exception. I didn't even know that inserting a different value through break was possible 😅

The problem is definitely specific to the break behavior, since this gets inferred correctly:

b = a.find { |v| v == 1 }.to_s

I'll look further into this, but it might be tricky to fix. It presents some additional logic required by type inference that isn't currently supported.