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

Add specialized #first and #last type for tuples #191

Merged
merged 1 commit into from
Aug 21, 2020
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
30 changes: 30 additions & 0 deletions lib/steep/ast/types/factory.rb
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,36 @@ def interface(type, private:, self_type: type)
incompatible: false
)
end

array_interface.methods[:first] = array_interface.methods[:first].yield_self do |first|
Interface::Interface::Combination.overload(
[
Interface::MethodType.new(
type_params: [],
params: Interface::Params.empty,
block: nil,
return_type: type.types[0] || AST::Builtin.nil_type,
location: nil
)
],
incompatible: false
)
end

array_interface.methods[:last] = array_interface.methods[:last].yield_self do |last|
Interface::Interface::Combination.overload(
[
Interface::MethodType.new(
type_params: [],
params: Interface::Params.empty,
block: nil,
return_type: type.types.last || AST::Builtin.nil_type,
location: nil
)
],
incompatible: false
)
end
end
end

Expand Down
3 changes: 3 additions & 0 deletions test/test_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,9 @@ def each: { (A) -> untyped } -> self
def zip: [B] (Array[B]) -> Array[A | B]
def each_with_object: [B] (B) { (A, B) -> untyped } -> B
def map: [X] { (A) -> X } -> Array[X]

def first: () -> A?
def last: () -> A?
end

class Hash[A, B]
Expand Down
21 changes: 21 additions & 0 deletions test/type_construction_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3741,6 +3741,27 @@ def test_tuple5_subtyping
end
end

def test_tuple_first_last
with_checker do |checker|
source = parse_ruby(<<EOF)
# @type var x: [Integer, String]
x = (_=[])

a = x.first
b = x.last
EOF

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

assert_no_error typing

assert_equal parse_type('::Integer'), context.lvar_env[:a]
assert_equal parse_type('::String'), context.lvar_env[:b]
end
end
end

def test_hash_tuple
with_checker do |checker|
source = parse_ruby(<<EOF)
Expand Down