Skip to content

Commit

Permalink
Rename fail! to panic!
Browse files Browse the repository at this point in the history
rust-lang/rfcs#221

The current terminology of "task failure" often causes problems when
writing or speaking about code. You often want to talk about the
possibility of an operation that returns a Result "failing", but cannot
because of the ambiguity with task failure. Instead, you have to speak
of "the failing case" or "when the operation does not succeed" or other
circumlocutions.

Likewise, we use a "Failure" header in rustdoc to describe when
operations may fail the task, but it would often be helpful to separate
out a section describing the "Err-producing" case.

We have been steadily moving away from task failure and toward Result as
an error-handling mechanism, so we should optimize our terminology
accordingly: Result-producing functions should be easy to describe.

To update your code, rename any call to `fail!` to `panic!` instead.
Assuming you have not created your own macro named `panic!`, this
will work on UNIX based systems:

    grep -lZR 'fail!' . | xargs -0 -l sed -i -e 's/fail!/panic!/g'

You can of course also do this by hand.

[breaking-change]
  • Loading branch information
steveklabnik committed Oct 29, 2014
1 parent 3bc5453 commit 7828c3d
Show file tree
Hide file tree
Showing 505 changed files with 1,623 additions and 1,618 deletions.
12 changes: 6 additions & 6 deletions src/compiletest/compiletest.rs
Expand Up @@ -41,7 +41,7 @@ pub fn main() {
let config = parse_config(args);

if config.valgrind_path.is_none() && config.force_valgrind {
fail!("Can't find Valgrind to run Valgrind tests");
panic!("Can't find Valgrind to run Valgrind tests");
}

log_config(&config);
Expand Down Expand Up @@ -94,20 +94,20 @@ pub fn parse_config(args: Vec<String> ) -> Config {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(message.as_slice(), groups.as_slice()));
println!("");
fail!()
panic!()
}

let matches =
&match getopts::getopts(args_.as_slice(), groups.as_slice()) {
Ok(m) => m,
Err(f) => fail!("{}", f)
Err(f) => panic!("{}", f)
};

if matches.opt_present("h") || matches.opt_present("help") {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(message.as_slice(), groups.as_slice()));
println!("");
fail!()
panic!()
}

fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
Expand All @@ -120,7 +120,7 @@ pub fn parse_config(args: Vec<String> ) -> Config {
Ok(re) => Some(re),
Err(e) => {
println!("failed to parse filter /{}/: {}", s, e);
fail!()
panic!()
}
}
} else {
Expand Down Expand Up @@ -263,7 +263,7 @@ pub fn run_tests(config: &Config) {
let res = test::run_tests_console(&opts, tests.into_iter().collect());
match res {
Ok(true) => {}
Ok(false) => fail!("Some tests failed"),
Ok(false) => panic!("Some tests failed"),
Err(e) => {
println!("I/O failure during tests: {}", e);
}
Expand Down
4 changes: 2 additions & 2 deletions src/compiletest/header.rs
Expand Up @@ -305,7 +305,7 @@ fn parse_exec_env(line: &str) -> Option<(String, String)> {
let end = strs.pop().unwrap();
(strs.pop().unwrap(), end)
}
n => fail!("Expected 1 or 2 strings, not {}", n)
n => panic!("Expected 1 or 2 strings, not {}", n)
}
})
}
Expand Down Expand Up @@ -350,7 +350,7 @@ pub fn gdb_version_to_int(version_string: &str) -> int {
let components: Vec<&str> = version_string.trim().split('.').collect();

if components.len() != 2 {
fail!("{}", error_string);
panic!("{}", error_string);
}

let major: int = FromStr::from_str(components[0]).expect(error_string);
Expand Down
8 changes: 4 additions & 4 deletions src/compiletest/runtest.rs
Expand Up @@ -39,7 +39,7 @@ pub fn run(config: Config, testfile: String) {

"arm-linux-androideabi" => {
if !config.adb_device_status {
fail!("android device not available");
panic!("android device not available");
}
}

Expand Down Expand Up @@ -316,7 +316,7 @@ actual:\n\
------------------------------------------\n\
\n",
expected, actual);
fail!();
panic!();
}
}

Expand Down Expand Up @@ -1453,7 +1453,7 @@ fn maybe_dump_to_stdout(config: &Config, out: &str, err: &str) {

fn error(err: &str) { println!("\nerror: {}", err); }

fn fatal(err: &str) -> ! { error(err); fail!(); }
fn fatal(err: &str) -> ! { error(err); panic!(); }

fn fatal_proc_rec(err: &str, proc_res: &ProcRes) -> ! {
print!("\n\
Expand All @@ -1471,7 +1471,7 @@ stderr:\n\
\n",
err, proc_res.status, proc_res.cmdline, proc_res.stdout,
proc_res.stderr);
fail!();
panic!();
}

fn _arm_exec_compiled_test(config: &Config,
Expand Down
2 changes: 1 addition & 1 deletion src/compiletest/util.rs
Expand Up @@ -31,7 +31,7 @@ pub fn get_os(triple: &str) -> &'static str {
return os
}
}
fail!("Cannot determine OS from triple");
panic!("Cannot determine OS from triple");
}

#[cfg(target_os = "windows")]
Expand Down
4 changes: 2 additions & 2 deletions src/doc/complement-design-faq.md
Expand Up @@ -94,9 +94,9 @@ code should need to run is a stack.

`match` being exhaustive has some useful properties. First, if every
possibility is covered by the `match`, adding further variants to the `enum`
in the future will prompt a compilation failure, rather than runtime failure.
in the future will prompt a compilation failure, rather than runtime panic.
Second, it makes cost explicit. In general, only safe way to have a
non-exhaustive match would be to fail the task if nothing is matched, though
non-exhaustive match would be to panic the task if nothing is matched, though
it could fall through if the type of the `match` expression is `()`. This sort
of hidden cost and special casing is against the language's philosophy. It's
easy to ignore certain cases by using the `_` wildcard:
Expand Down
5 changes: 3 additions & 2 deletions src/doc/complement-lang-faq.md
Expand Up @@ -65,14 +65,15 @@ Data values in the language can only be constructed through a fixed set of initi
* There is no global inter-crate namespace; all name management occurs within a crate.
* Using another crate binds the root of _its_ namespace into the user's namespace.

## Why is failure unwinding non-recoverable within a task? Why not try to "catch exceptions"?
## Why is panic unwinding non-recoverable within a task? Why not try to "catch exceptions"?

In short, because too few guarantees could be made about the dynamic environment of the catch block, as well as invariants holding in the unwound heap, to be able to safely resume; we believe that other methods of signalling and logging errors are more appropriate, with tasks playing the role of a "hard" isolation boundary between separate heaps.

Rust provides, instead, three predictable and well-defined options for handling any combination of the three main categories of "catch" logic:

* Failure _logging_ is done by the integrated logging subsystem.
* _Recovery_ after a failure is done by trapping a task failure from _outside_ the task, where other tasks are known to be unaffected.
* _Recovery_ after a panic is done by trapping a task panic from _outside_
the task, where other tasks are known to be unaffected.
* _Cleanup_ of resources is done by RAII-style objects with destructors.

Cleanup through RAII-style destructors is more likely to work than in catch blocks anyways, since it will be better tested (part of the non-error control paths, so executed all the time).
Expand Down
2 changes: 1 addition & 1 deletion src/doc/guide-ffi.md
Expand Up @@ -191,7 +191,7 @@ the stack of the task which is spawned.

Foreign libraries often hand off ownership of resources to the calling code.
When this occurs, we must use Rust's destructors to provide safety and guarantee
the release of these resources (especially in the case of failure).
the release of these resources (especially in the case of panic).

# Callbacks from C code to Rust functions

Expand Down
6 changes: 3 additions & 3 deletions src/doc/guide-macros.md
Expand Up @@ -240,7 +240,7 @@ match x {
// complicated stuff goes here
return result + val;
},
_ => fail!("Didn't get good_2")
_ => panic!("Didn't get good_2")
}
}
_ => return 0 // default value
Expand Down Expand Up @@ -284,7 +284,7 @@ macro_rules! biased_match (
biased_match!((x) ~ (Good1(g1, val)) else { return 0 };
binds g1, val )
biased_match!((g1.body) ~ (Good2(result) )
else { fail!("Didn't get good_2") };
else { panic!("Didn't get good_2") };
binds result )
// complicated stuff goes here
return result + val;
Expand Down Expand Up @@ -397,7 +397,7 @@ macro_rules! biased_match (
# fn f(x: T1) -> uint {
biased_match!(
(x) ~ (Good1(g1, val)) else { return 0 };
(g1.body) ~ (Good2(result) ) else { fail!("Didn't get Good2") };
(g1.body) ~ (Good2(result) ) else { panic!("Didn't get Good2") };
binds val, result )
// complicated stuff goes here
return result + val;
Expand Down
30 changes: 15 additions & 15 deletions src/doc/guide-tasks.md
Expand Up @@ -8,10 +8,10 @@ relates to the Rust type system, and introduce the fundamental library
abstractions for constructing concurrent programs.

Tasks provide failure isolation and recovery. When a fatal error occurs in Rust
code as a result of an explicit call to `fail!()`, an assertion failure, or
code as a result of an explicit call to `panic!()`, an assertion failure, or
another invalid operation, the runtime system destroys the entire task. Unlike
in languages such as Java and C++, there is no way to `catch` an exception.
Instead, tasks may monitor each other for failure.
Instead, tasks may monitor each other to see if they panic.

Tasks use Rust's type system to provide strong memory safety guarantees. In
particular, the type system guarantees that tasks cannot induce a data race
Expand Down Expand Up @@ -317,19 +317,19 @@ spawn(proc() {
# }
```

# Handling task failure
# Handling task panics

Rust has a built-in mechanism for raising exceptions. The `fail!()` macro
(which can also be written with an error string as an argument: `fail!(
~reason)`) and the `assert!` construct (which effectively calls `fail!()` if a
Rust has a built-in mechanism for raising exceptions. The `panic!()` macro
(which can also be written with an error string as an argument: `panic!(
~reason)`) and the `assert!` construct (which effectively calls `panic!()` if a
boolean expression is false) are both ways to raise exceptions. When a task
raises an exception, the task unwinds its stack—running destructors and
freeing memory along the way—and then exits. Unlike exceptions in C++,
exceptions in Rust are unrecoverable within a single task: once a task fails,
exceptions in Rust are unrecoverable within a single task: once a task panics,
there is no way to "catch" the exception.

While it isn't possible for a task to recover from failure, tasks may notify
each other of failure. The simplest way of handling task failure is with the
While it isn't possible for a task to recover from panicking, tasks may notify
each other if they panic. The simplest way of handling a panic is with the
`try` function, which is similar to `spawn`, but immediately blocks and waits
for the child task to finish. `try` returns a value of type
`Result<T, Box<Any + Send>>`. `Result` is an `enum` type with two variants:
Expand All @@ -346,7 +346,7 @@ let result: Result<int, Box<std::any::Any + Send>> = task::try(proc() {
if some_condition() {
calculate_result()
} else {
fail!("oops!");
panic!("oops!");
}
});
assert!(result.is_err());
Expand All @@ -355,18 +355,18 @@ assert!(result.is_err());
Unlike `spawn`, the function spawned using `try` may return a value, which
`try` will dutifully propagate back to the caller in a [`Result`] enum. If the
child task terminates successfully, `try` will return an `Ok` result; if the
child task fails, `try` will return an `Error` result.
child task panics, `try` will return an `Error` result.

[`Result`]: std/result/index.html

> *Note:* A failed task does not currently produce a useful error
> *Note:* A panicked task does not currently produce a useful error
> value (`try` always returns `Err(())`). In the
> future, it may be possible for tasks to intercept the value passed to
> `fail!()`.
> `panic!()`.
But not all failures are created equal. In some cases you might need to abort
But not all panics are created equal. In some cases you might need to abort
the entire program (perhaps you're writing an assert which, if it trips,
indicates an unrecoverable logic error); in other cases you might want to
contain the failure at a certain boundary (perhaps a small piece of input from
contain the panic at a certain boundary (perhaps a small piece of input from
the outside world, which you happen to be processing in parallel, is malformed
such that the processing task cannot proceed).
4 changes: 2 additions & 2 deletions src/doc/guide-testing.md
Expand Up @@ -49,7 +49,7 @@ value. To run the tests in a crate, it must be compiled with the
`--test` flag: `rustc myprogram.rs --test -o myprogram-tests`. Running
the resulting executable will run all the tests in the crate. A test
is considered successful if its function returns; if the task running
the test fails, through a call to `fail!`, a failed `assert`, or some
the test fails, through a call to `panic!`, a failed `assert`, or some
other (`assert_eq`, ...) means, then the test fails.

When compiling a crate with the `--test` flag `--cfg test` is also
Expand Down Expand Up @@ -77,7 +77,7 @@ test on windows you can write `#[cfg_attr(windows, ignore)]`.

Tests that are intended to fail can be annotated with the
`should_fail` attribute. The test will be run, and if it causes its
task to fail then the test will be counted as successful; otherwise it
task to panic then the test will be counted as successful; otherwise it
will be counted as a failure. For example:

~~~test_harness
Expand Down
4 changes: 2 additions & 2 deletions src/doc/guide-unsafe.md
Expand Up @@ -182,7 +182,7 @@ code:
- implement the `Drop` for resource clean-up via a destructor, and use
RAII (Resource Acquisition Is Initialization). This reduces the need
for any manual memory management by users, and automatically ensures
that clean-up is always run, even when the task fails.
that clean-up is always run, even when the task panics.
- ensure that any data stored behind a raw pointer is destroyed at the
appropriate time.

Expand Down Expand Up @@ -504,7 +504,7 @@ The second of these three functions, `eh_personality`, is used by the
failure mechanisms of the compiler. This is often mapped to GCC's
personality function (see the
[libstd implementation](std/rt/unwind/index.html) for more
information), but crates which do not trigger failure can be assured
information), but crates which do not trigger a panic can be assured
that this function is never called. The final function, `fail_fmt`, is
also used by the failure mechanisms of the compiler.

Expand Down
16 changes: 8 additions & 8 deletions src/doc/guide.md
Expand Up @@ -5213,17 +5213,17 @@ immediately.

## Success and failure

Tasks don't always succeed, they can also fail. A task that wishes to fail
can call the `fail!` macro, passing a message:
Tasks don't always succeed, they can also panic. A task that wishes to panic
can call the `panic!` macro, passing a message:

```{rust}
spawn(proc() {
fail!("Nope.");
panic!("Nope.");
});
```

If a task fails, it is not possible for it to recover. However, it can
notify other tasks that it has failed. We can do this with `task::try`:
If a task panics, it is not possible for it to recover. However, it can
notify other tasks that it has panicked. We can do this with `task::try`:

```{rust}
use std::task;
Expand All @@ -5233,14 +5233,14 @@ let result = task::try(proc() {
if rand::random() {
println!("OK");
} else {
fail!("oops!");
panic!("oops!");
}
});
```

This task will randomly fail or succeed. `task::try` returns a `Result`
This task will randomly panic or succeed. `task::try` returns a `Result`
type, so we can handle the response like any other computation that may
fail.
panic.

# Macros

Expand Down

0 comments on commit 7828c3d

Please sign in to comment.