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

Compiler: give proper error when trying to access instance variable of union type #7194

Merged
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
16 changes: 16 additions & 0 deletions spec/compiler/semantic/class_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1075,4 +1075,20 @@ describe "Semantic: class" do
{ {{ Foo::Bar.superclass }}, {{ Foo::Baz.superclass }} }
)) { tuple_of [types["Foo"].metaclass, types["Foo"].metaclass] }
end

it "errors if reading instance var of union type (#7187)" do
assert_error %(
class Foo
@x = 1
end

class Bar
@x = 1
end

z = Foo.new || Bar.new
z.@x
),
"can't read instance variables of union types (@x of (Bar | Foo))"
end
end
4 changes: 4 additions & 0 deletions src/compiler/crystal/semantic/bindings.cr
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,10 @@ module Crystal
obj_type = obj.type?
return unless obj_type

if obj_type.is_a?(UnionType)
raise "can't read instance variables of union types (#{name} of #{obj_type})"
end

var = visitor.lookup_instance_var(self, obj_type)
self.type = var.type
end
Expand Down