Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Infer type annotations for instance variables #3513

Open
jez opened this issue Oct 15, 2020 · 1 comment · May be fixed by #4837
Open

Infer type annotations for instance variables #3513

jez opened this issue Oct 15, 2020 · 1 comment · May be fixed by #4837
Labels
enhancement New feature or surprising current feature good first issue Good for newcomers

Comments

@jez
Copy link
Collaborator

jez commented Oct 15, 2020

Input

→ View on sorbet.run

# typed: strict

class A
  extend T::Sig

  X = 0

  sig {void}
  def initialize
    @y = 0
  end
end

Observed output

editor.rb:10: Use of undeclared variable @y https://srb.help/6002
    10 |    @y = 0
            ^^
Errors: 1

Expected behavior

We should infer the annotation for @x because it is a literal type. We should use the same type defaulting rules that we use for constants (as depicted) to also handle instance variables.


  • This should probably only work for instance variable assignments that happen inside initialize or the top level of a class.
  • Ideally we would consolidate the logic that handles constants to handle instance variables.
    To this end, we can probably move the logic to be done in a rewriter pass.
    The rewriter pass would insert a T.let inside assignments to either constants or instance variables when the RHS is a literal.
    (As opposed to now, where it is done in the internals of namer/resolver.)
@jez jez added enhancement New feature or surprising current feature good first issue Good for newcomers labels Oct 15, 2020
@amomchilov
Copy link
Contributor

amomchilov commented May 18, 2023

With the advent of #6599 (which infers that X = A.new means X = T.let(A.new, A), would there be any desire to apply the same logic to ivars?

E.g.

#typed: strict

class C
  extend T::Sig

  sig { void }
  def initialize
    @foo = Foo.new # inferred as `T.let(Foo.new, Foo)`
  end  
    
  # Stretch goal: A further refinement of https://github.com/sorbet/sorbet/issues/995
  def memoed_bar
    @bar ||= Bar.new # inferred as `T.let(Bar.new, T.nilable(Bar))`
  end
end

Related: #995

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or surprising current feature good first issue Good for newcomers
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants