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

Interpreter: fix as? when there's no resulting type #12328

Merged
merged 2 commits into from
Jul 29, 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
20 changes: 20 additions & 0 deletions spec/compiler/interpreter/casts_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -335,5 +335,25 @@ describe Crystal::Repl::Interpreter do
end
CODE
end

it "does as? with no resulting type (#12327)" do
interpret(<<-CODE).should eq(42)
if nil.as?(Int32)
0
else
42
end
CODE
end

it "does as? with no resulting type, not from nil (#12327)" do
interpret(<<-CODE).should eq(42)
if 1.as?(String)
0
else
42
end
CODE
end
end
end
52 changes: 31 additions & 21 deletions src/compiler/crystal/interpreter/compiler.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1606,37 +1606,47 @@ class Crystal::Repl::Compiler < Crystal::Visitor
end

def visit(node : NilableCast)
# TODO: not tested
node.obj.accept self

obj_type = node.obj.type
to_type = node.to.type.virtual_type

# TODO: check the proper conditions in codegen
if obj_type == to_type
nop
else
# Check if obj is a `to_type`
dup aligned_sizeof_type(node.obj), node: nil
is_a(node, obj_type, to_type)
node.obj.accept self

# If so, branch
branch_if 0, node: nil
cond_jump_location = patch_location
return false
end

# Otherwise it's nil
put_nil node: nil
pop aligned_sizeof_type(node.obj), node: nil
filtered_type = obj_type.filter_by(to_type)
unless filtered_type
# If .as?(...) has no resulting type we must cast
# whatever type we have to nil.
discard_value node.obj
upcast node.obj, @context.program.nil_type, node.type
jump 0, node: nil
otherwise_jump_location = patch_location
return false
end

patch_jump(cond_jump_location)
downcast node.obj, obj_type, to_type
upcast node.obj, to_type, node.type
node.obj.accept self

patch_jump(otherwise_jump_location)
end
# Check if obj is a `to_type`
dup aligned_sizeof_type(node.obj), node: nil
filter_type(node, obj_type, filtered_type)

# If so, branch
branch_if 0, node: nil
cond_jump_location = patch_location

# Otherwise it's nil
put_nil node: nil
pop aligned_sizeof_type(node.obj), node: nil
upcast node.obj, @context.program.nil_type, node.type
jump 0, node: nil
otherwise_jump_location = patch_location

patch_jump(cond_jump_location)
downcast node.obj, obj_type, to_type
upcast node.obj, to_type, node.type

patch_jump(otherwise_jump_location)

false
end
Expand Down