Skip to content

Commit

Permalink
Fix Class#nilable? for recursive unions and root types (#12353)
Browse files Browse the repository at this point in the history
  • Loading branch information
HertzDevil authored and beta-ziliani committed Sep 6, 2022
1 parent fc6dace commit b0b1789
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 14 deletions.
10 changes: 9 additions & 1 deletion spec/std/class_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ private class ClassWithRedefinedName
end
end

private alias RecursiveNilableType = Array(RecursiveNilableType)?

describe Class do
it "does ===" do
(Int32 === 1).should be_true
Expand Down Expand Up @@ -49,11 +51,17 @@ describe Class do
Int32.clone.should eq(Int32)
end

it "#nilable" do
it "#nilable?" do
Int32.nilable?.should be_false
Nil.nilable?.should be_true
(Int32 | String).nilable?.should be_false
Int32?.nilable?.should be_true
NoReturn.nilable?.should be_false
Reference.nilable?.should be_false
Value.nilable?.should be_true
Class.nilable?.should be_false
Object.nilable?.should be_true
RecursiveNilableType.nilable?.should be_true
end

it "does to_s" do
Expand Down
12 changes: 8 additions & 4 deletions src/class.cr
Original file line number Diff line number Diff line change
Expand Up @@ -135,14 +135,18 @@ class Class
typeof(t, u)
end

# Returns `true` if this class is `Nil`.
# Returns `true` if `nil` is an instance of this type.
#
# ```
# Int32.nilable? # => false
# Nil.nilable? # => true
# Int32.nilable? # => false
# Nil.nilable? # => true
# (Int32 | String).nilable? # => false
# (Int32 | Nil).nilable? # => true
# NoReturn.nilable? # => false
# Value.nilable? # => true
# ```
def nilable? : Bool
self == ::Nil
{{ @type >= Nil }}
end

def to_s(io : IO) : Nil
Expand Down
9 changes: 0 additions & 9 deletions src/union.cr
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,4 @@
# Union(Int32, Int32, Int32) # => Int32
# ```
struct Union
# Returns `true` if this union includes the `Nil` type.
#
# ```
# (Int32 | String).nilable? # => false
# (Int32 | Nil).nilable? # => true
# ```
def self.nilable?
{{ T.any? &.==(::Nil) }}
end
end

0 comments on commit b0b1789

Please sign in to comment.