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

Better splat in array typing #519

Merged
merged 1 commit into from
Mar 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion lib/steep/type_construction.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3945,6 +3945,20 @@ def try_tuple_type(node, hint)
constr.add_typing(node, type: AST::Types::Tuple.new(types: element_types))
end

def try_convert(type, method)
interface = checker.factory.interface(type, private: false)
if entry = interface.methods[method]
method_type = entry.method_types.find do |method_type|
method_type.type.params.optional?
end

method_type.type.return_type
end
rescue => exn
Steep.log_error(exn, message: "Unexpected error when converting #{type.to_s} with #{method}")
nil
end

def try_array_type(node, hint)
element_hint = hint ? hint.args[0] : nil

Expand All @@ -3955,8 +3969,14 @@ def try_array_type(node, hint)
case child.type
when :splat
type, constr = constr.synthesize(child.children[0], hint: hint)
if AST::Builtin::Array.instance_type?(type)

type = try_convert(type, :to_a) || type

case
when AST::Builtin::Array.instance_type?(type)
element_types << type.args[0]
when type.is_a?(AST::Types::Tuple)
element_types.push(*type.types)
else
element_types.push(*flatten_array_elements(type))
end
Expand Down
27 changes: 27 additions & 0 deletions test/type_construction_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8564,4 +8564,31 @@ def foo: (?untyped, *untyped, ?a: untyped, **untyped) -> String
end
end
end

def test_splat_in_array
with_checker(<<-RBS) do |checker|
class Range[T]
def to_a: () -> Array[T]
end
RBS

source = parse_ruby(<<-'RUBY')
a = [*'0'..'9']
b = [*123]

# @type var x: [Integer, String]
x = [1, "a"]
c = [*x]
RUBY

with_standard_construction(checker, source) do |construction, typing|
_, constr = construction.synthesize(source.node)

assert_no_error typing
assert_equal parse_type("::Array[::String]"), constr.context.lvar_env[:a]
assert_equal parse_type("::Array[::Integer]"), constr.context.lvar_env[:b]
assert_equal parse_type("::Array[::Integer | ::String]"), constr.context.lvar_env[:c]
end
end
end
end