Skip to content

Commit

Permalink
Showing 2 changed files with 99 additions and 0 deletions.
66 changes: 66 additions & 0 deletions spec/compiler/codegen/nilable_cast_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
require "../../spec_helper"

describe "Code gen: nilable cast" do
it "does nilable cast (true)" do
run(%(
x = 42 || "hello"
y = x.as?(Int32)
y || 84
)).to_i.should eq(42)
end

it "does nilable cast (false)" do
run(%(
x = "hello" || 42
y = x.as?(Int32)
y || 84
)).to_i.should eq(84)
end

it "does nilable cast (always true)" do
run(%(
x = 42
y = x.as?(Int32)
y || 84
)).to_i.should eq(42)
end

it "does upcast" do
run(%(
class Foo
def bar
1
end
end
class Bar < Foo
def bar
2
end
end
foo = Bar.new.as?(Foo)
if foo
foo.bar
else
3
end
)).to_i.should eq(2)
end

it "does cast to nil (1)" do
run(%(
x = 1
y = x.as?(Nil)
y ? 2 : 3
)).to_i.should eq(3)
end

it "does cast to nil (2)" do
run(%(
x = nil
y = x.as?(Nil)
y ? 2 : 3
)).to_i.should eq(3)
end
end
33 changes: 33 additions & 0 deletions spec/compiler/type_inference/nilable_cast_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
require "../../spec_helper"

describe "Type inference: nilable cast" do
it "types as?" do
assert_type(%(
1.as?(Float64)
)) { nilable float64 }
end

it "types as? with nil" do
assert_type(%(
1.as?(Nil)
)) { |mod| mod.nil }
end

it "does upcast" do
assert_type(%(
class Foo
def bar
1
end
end
class Bar < Foo
def bar
2
end
end
Bar.new.as?(Foo)
)) { nilable types["Foo"].virtual_type! }
end
end

0 comments on commit aee06f7

Please sign in to comment.