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

Allow rescuing exceptions that include a module #14553

Merged
merged 7 commits into from
May 10, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
93 changes: 93 additions & 0 deletions spec/compiler/codegen/exception_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1319,4 +1319,97 @@ describe "Code gen: exception" do
end
))
end

it "handles rescuing module type" do
run(%(
require "prelude"

module Foo; end

class Ex1 < Exception
include Foo
end

x = 0
begin
raise Ex1.new
rescue Foo
x = 1
end
x
)).to_i.should eq(1)
end

it "handles rescuing union between module type and class type" do
run(%(
require "prelude"

module Foo; end

abstract class BaseError < Exception; end
class Ex2 < BaseError; end

class Ex1 < BaseError
include Foo
end

x = 0
begin
raise Ex1.new
rescue Foo | BaseError
x = 1
end
x
)).to_i.should eq(1)
end

it "handles rescuing union between module types" do
run(%(
require "prelude"

module Foo; end
module Bar; end

class Ex1 < Exception
include Foo
end

class Ex2 < Exception
include Bar
end

x = 0
begin
raise Ex1.new
rescue Foo | Bar
x = 1
end
x
)).to_i.should eq(1)
end

it "does not rescue just any module" do
run(%(
require "prelude"

module Foo; end
module Bar; end

class Ex < Exception
include Foo
end

x = 0
begin
begin
raise Ex.new("oh no")
rescue Bar
x = 1
end
rescue ex
x = 2
end
x
)).to_i.should eq(2)
end
end
2 changes: 1 addition & 1 deletion src/compiler/crystal/semantic/main_visitor.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2775,7 +2775,7 @@ module Crystal
types = node_types.map do |type|
type.accept self
instance_type = type.type.instance_type
unless instance_type.implements?(@program.exception)
unless instance_type.implements?(@program.exception) || instance_type.module?
Blacksmoke16 marked this conversation as resolved.
Show resolved Hide resolved
type.raise "#{instance_type} is not a subclass of Exception"
end
instance_type
Expand Down
Loading