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

Fix error of prototype rb on hash spread syntax #465

Merged

Conversation

pocke
Copy link
Member

@pocke pocke commented Nov 8, 2020

Fix #464

Cause

Hash key will be a nil on hash spread syntax.
For example

pp RubyVM::AbstractSyntaxTree.parse('{ called: true, **({ foo: foo }.compact) }')
(SCOPE@1:0-1:42
 tbl: []
 args: nil
 body:
   (HASH@1:0-1:42
      (LIST@1:2-1:39 (LIT@1:2-1:9 :called) (TRUE@1:10-1:14) nil # ← here
         (CALL@1:19-1:39
            (HASH@1:19-1:31
               (LIST@1:21-1:29 (LIT@1:21-1:25 :foo) (VCALL@1:26-1:29 :foo)
                  nil)) :compact nil) nil)))

Solution

Determine key and value types as untyped if it a hash has **.

So, the type for the reported code will be the following.

# ruby
def a(foo:)
  { called: true, **({ foo: foo }.compact) }
end
$ exe/rbs prototype rb test.rb
class Object
  def a: (foo: untyped foo) -> ::Hash[:called | untyped, ::TrueClass | untyped]
end

By the way, @ybiquitous says "unless .compact, the command passes:".
Because Ruby optimizes a hash spread for a hash literal.

pp RubyVM::AbstractSyntaxTree.parse('{ called: true, **({ foo: foo }) }')
(SCOPE@1:0-1:34
 tbl: []
 args: nil
 body:
   (HASH@1:0-1:34
      (LIST@1:2-1:29 (LIT@1:2-1:9 :called) (TRUE@1:10-1:14)
         (LIT@1:21-1:25 :foo) (VCALL@1:26-1:29 :foo) nil)))

The AST does not have nil as a key.

@@ -411,16 +411,22 @@ def literal_to_type(node)
when :HASH
list = node.children[0]
if list
children = list.children.compact
children = list.children
children.pop
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In RubyVM::AST, all list has trailing nil. It removed the nil by compact previously. But compact removes a nil for hash spread unexpectedly. So I changed compact to pop.

Copy link
Member

@soutaro soutaro left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉

@soutaro soutaro merged commit 6160a3b into ruby:master Nov 8, 2020
@pocke pocke deleted the Fix-error-of-prototype-rb-on-hash-spread-syntax branch November 8, 2020 15:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

rbs prototype rb raise NoMethodError
2 participants