solargraph icon indicating copy to clipboard operation
solargraph copied to clipboard

Strange inference errors on nullable types

Open jpalmucci opened this issue 3 years ago • 1 comments

Using the following file with --level strict give spurious typecheck errors when you directly annotate the method, but not when you use the @!method tag. Both annotations result in correct type checking as illustrated at the bottom of the file:

class Foo
  # @param foo [Numeric,nil] a foo
  # @return [Numeric,nil]
  def test(foo: nil)
    # strict type inference gives this:
    # types.rb:4 - Declared return type Numeric, nil does not match inferred type Numeric for Foo#test
    # types.rb:4 - Declared type Numeric, nil does not match inferred type nil for variable foo
    foo
  end

  # @!method test2
  #    @param foo [Numeric,nil] a foo
  #    @return [Numeric,nil]
  def test2(foo: nil)
    # strict doesn't give any errors here
    foo
  end
end

f = Foo.new

# both methods type check correctly

f.test2(foo: 1)     # no error
f.test2(foo: nil)   # no error
f.test2(foo: 'av')  # Wrong argument type for Foo#test2: foo expected Numeric, nil, received String

f.test1(foo: 1)     # no error
f.test1(foo: nil)   # no error
f.test1(foo: 'av')  # Wrong argument type for Foo#test2: foo expected Numeric, nil, received String

jpalmucci avatar Aug 24 '22 20:08 jpalmucci

Confirmed. The @!method behavior is expected because it takes precedence over code analysis, but the two errors in Foo#test are false positives.

The second error ("Declared type Numeric, nil does not match inferred type nil for variable foo") should be fixed in 0.46.0. The first one still needs to be addressed.

castwide avatar Sep 07 '22 14:09 castwide

Released in v0.47.2.

castwide avatar Sep 30 '22 12:09 castwide