Sorbet: Bad error message for `attr_accessor` with a signature including a type parameter

Created on 5 Sep 2019  Â·  3Comments  Â·  Source: sorbet/sorbet

Input

→ View on sorbet.run

# typed: true

class Foo
  extend T::Sig

  sig do
    type_parameters(:R)
      .returns(T.nilable(
        T.type_parameter(:R)
      ))
  end
  attr_accessor :ko
end

Observed output

editor.rb:9: Unspecified type parameter https://srb.help/5004
     9 |        T.type_parameter(:R)
                                 ^^
Errors: 1

Expected behavior

Not sure, maybe we should forbid signatures on attr_accessor altogether? Or have another way to state the attribute type on it? Anyway the error currently raised is quite confusing here since R is actually defined a few characters before.

Same problem with attr_writer (→ View on sorbet.run) but at least, the second error message gives some hints.

This works like it should with attr_reader (→ View on sorbet.run)

bug

All 3 comments

This looks like it's just a bug in the DSL pass that implements attr_accessor. It should be straightforward to fix—I'll take a stab at it this afternoon.

On reflection, I think we don't ever want type_parameters in attr_* types anyway. Even something simple in the attr_reader case looks innocuous, but can't actually be instantiated:

sig { type_parameters(:R).returns(T.type_parameter(:R)) }
attr_reader :foo

(c.f. the relevant sorbet.run). I'm putting together a PR which will identify type signatures on attrs that include type parameters and warn you, so you'll get a sensible error instead of the misleading ones above.

For the record, the root cause of the bug here is that for attr_accessor, in the setter component, the DSL'd method body ends up using a T.let to declare the type of the instance variable that backs the attr_accessor:

def foo=(foo)
  @foo = T.let(foo, T.nilable(T.type_parameter(:R))
end

But we have an unrelated bug that it's not actually possible to refer to a type_parameter within the method body:

1715

Was this page helpful?
0 / 5 - 0 ratings

Related issues

viraptor picture viraptor  Â·  4Comments

rafaelcgs10 picture rafaelcgs10  Â·  3Comments

deecewan picture deecewan  Â·  4Comments

jaredbeck picture jaredbeck  Â·  4Comments

md-work picture md-work  Â·  3Comments