Skip to content

Commit

Permalink
Add 'unreachable!' method to express unreachable code explicitly
Browse files Browse the repository at this point in the history
This is an implementation of crystal-lang#4749.
  • Loading branch information
makenowjust committed Aug 2, 2017
1 parent d23db08 commit a9b6e56
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
13 changes: 13 additions & 0 deletions spec/std/unreachable_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
require "spec"

describe "unreachable!" do
it "raises UnreachableError with 'BUG: unreachable' message" do
expect_raises(UnreachableError, "BUG: unreachable") { unreachable! }
end

it "can set an error message" do
expect_raises UnreachableError, "BUG: i'm bag" do
unreachable! "i'm bag"
end
end
end
8 changes: 8 additions & 0 deletions src/exception.cr
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,11 @@ class DivisionByZero < Exception
super(message)
end
end

# Raised when `unreachable!` is called (It must mean a BUG.)
#
# ```
# unreachable! # raises UnreachableError (BUG: unreachable)
# ```
class UnreachableError < Exception
end
8 changes: 8 additions & 0 deletions src/kernel.cr
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,14 @@ def abort(message, status = 1) : NoReturn
exit status
end

# Expresses an unreachable code explicitly.
#
# When it is called, it raises `UnreachableError` with given *message*.
# However you will never see it if you use this method accurately.
def unreachable!(message = "unreachable") : NoReturn
raise UnreachableError.new("BUG: #{message}")
end

class Process
# Hooks are defined here due to load order problems.
def self.after_fork_child_callbacks
Expand Down

0 comments on commit a9b6e56

Please sign in to comment.