1
Fork 0

Rename fail! to panic!

https://github.com/rust-lang/rfcs/pull/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]
This commit is contained in:
Steve Klabnik 2014-10-09 15:17:22 -04:00
parent 3bc545373d
commit 7828c3dd28
505 changed files with 1623 additions and 1618 deletions

View file

@ -41,7 +41,7 @@ pub fn main() {
let config = parse_config(args); let config = parse_config(args);
if config.valgrind_path.is_none() && config.force_valgrind { 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); log_config(&config);
@ -94,20 +94,20 @@ pub fn parse_config(args: Vec<String> ) -> Config {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0); let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(message.as_slice(), groups.as_slice())); println!("{}", getopts::usage(message.as_slice(), groups.as_slice()));
println!(""); println!("");
fail!() panic!()
} }
let matches = let matches =
&match getopts::getopts(args_.as_slice(), groups.as_slice()) { &match getopts::getopts(args_.as_slice(), groups.as_slice()) {
Ok(m) => m, Ok(m) => m,
Err(f) => fail!("{}", f) Err(f) => panic!("{}", f)
}; };
if matches.opt_present("h") || matches.opt_present("help") { if matches.opt_present("h") || matches.opt_present("help") {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0); let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(message.as_slice(), groups.as_slice())); println!("{}", getopts::usage(message.as_slice(), groups.as_slice()));
println!(""); println!("");
fail!() panic!()
} }
fn opt_path(m: &getopts::Matches, nm: &str) -> Path { fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
@ -120,7 +120,7 @@ pub fn parse_config(args: Vec<String> ) -> Config {
Ok(re) => Some(re), Ok(re) => Some(re),
Err(e) => { Err(e) => {
println!("failed to parse filter /{}/: {}", s, e); println!("failed to parse filter /{}/: {}", s, e);
fail!() panic!()
} }
} }
} else { } else {
@ -263,7 +263,7 @@ pub fn run_tests(config: &Config) {
let res = test::run_tests_console(&opts, tests.into_iter().collect()); let res = test::run_tests_console(&opts, tests.into_iter().collect());
match res { match res {
Ok(true) => {} Ok(true) => {}
Ok(false) => fail!("Some tests failed"), Ok(false) => panic!("Some tests failed"),
Err(e) => { Err(e) => {
println!("I/O failure during tests: {}", e); println!("I/O failure during tests: {}", e);
} }

View file

@ -305,7 +305,7 @@ fn parse_exec_env(line: &str) -> Option<(String, String)> {
let end = strs.pop().unwrap(); let end = strs.pop().unwrap();
(strs.pop().unwrap(), end) (strs.pop().unwrap(), end)
} }
n => fail!("Expected 1 or 2 strings, not {}", n) n => panic!("Expected 1 or 2 strings, not {}", n)
} }
}) })
} }
@ -350,7 +350,7 @@ pub fn gdb_version_to_int(version_string: &str) -> int {
let components: Vec<&str> = version_string.trim().split('.').collect(); let components: Vec<&str> = version_string.trim().split('.').collect();
if components.len() != 2 { if components.len() != 2 {
fail!("{}", error_string); panic!("{}", error_string);
} }
let major: int = FromStr::from_str(components[0]).expect(error_string); let major: int = FromStr::from_str(components[0]).expect(error_string);

View file

@ -39,7 +39,7 @@ pub fn run(config: Config, testfile: String) {
"arm-linux-androideabi" => { "arm-linux-androideabi" => {
if !config.adb_device_status { if !config.adb_device_status {
fail!("android device not available"); panic!("android device not available");
} }
} }
@ -316,7 +316,7 @@ actual:\n\
------------------------------------------\n\ ------------------------------------------\n\
\n", \n",
expected, actual); expected, actual);
fail!(); panic!();
} }
} }
@ -1453,7 +1453,7 @@ fn maybe_dump_to_stdout(config: &Config, out: &str, err: &str) {
fn error(err: &str) { println!("\nerror: {}", err); } 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) -> ! { fn fatal_proc_rec(err: &str, proc_res: &ProcRes) -> ! {
print!("\n\ print!("\n\
@ -1471,7 +1471,7 @@ stderr:\n\
\n", \n",
err, proc_res.status, proc_res.cmdline, proc_res.stdout, err, proc_res.status, proc_res.cmdline, proc_res.stdout,
proc_res.stderr); proc_res.stderr);
fail!(); panic!();
} }
fn _arm_exec_compiled_test(config: &Config, fn _arm_exec_compiled_test(config: &Config,

View file

@ -31,7 +31,7 @@ pub fn get_os(triple: &str) -> &'static str {
return os return os
} }
} }
fail!("Cannot determine OS from triple"); panic!("Cannot determine OS from triple");
} }
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]

View file

@ -94,9 +94,9 @@ code should need to run is a stack.
`match` being exhaustive has some useful properties. First, if every `match` being exhaustive has some useful properties. First, if every
possibility is covered by the `match`, adding further variants to the `enum` 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 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 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 of hidden cost and special casing is against the language's philosophy. It's
easy to ignore certain cases by using the `_` wildcard: easy to ignore certain cases by using the `_` wildcard:

View file

@ -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. * 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. * 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. 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: 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. * 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_ 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). 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).

View file

@ -191,7 +191,7 @@ the stack of the task which is spawned.
Foreign libraries often hand off ownership of resources to the calling code. 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 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 # Callbacks from C code to Rust functions

View file

@ -240,7 +240,7 @@ match x {
// complicated stuff goes here // complicated stuff goes here
return result + val; return result + val;
}, },
_ => fail!("Didn't get good_2") _ => panic!("Didn't get good_2")
} }
} }
_ => return 0 // default value _ => return 0 // default value
@ -284,7 +284,7 @@ macro_rules! biased_match (
biased_match!((x) ~ (Good1(g1, val)) else { return 0 }; biased_match!((x) ~ (Good1(g1, val)) else { return 0 };
binds g1, val ) binds g1, val )
biased_match!((g1.body) ~ (Good2(result) ) biased_match!((g1.body) ~ (Good2(result) )
else { fail!("Didn't get good_2") }; else { panic!("Didn't get good_2") };
binds result ) binds result )
// complicated stuff goes here // complicated stuff goes here
return result + val; return result + val;
@ -397,7 +397,7 @@ macro_rules! biased_match (
# fn f(x: T1) -> uint { # fn f(x: T1) -> uint {
biased_match!( biased_match!(
(x) ~ (Good1(g1, val)) else { return 0 }; (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 ) binds val, result )
// complicated stuff goes here // complicated stuff goes here
return result + val; return result + val;

View file

@ -8,10 +8,10 @@ relates to the Rust type system, and introduce the fundamental library
abstractions for constructing concurrent programs. abstractions for constructing concurrent programs.
Tasks provide failure isolation and recovery. When a fatal error occurs in Rust 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 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. 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 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 particular, the type system guarantees that tasks cannot induce a data race
@ -317,19 +317,19 @@ spawn(proc() {
# } # }
``` ```
# Handling task failure # Handling task panics
Rust has a built-in mechanism for raising exceptions. The `fail!()` macro Rust has a built-in mechanism for raising exceptions. The `panic!()` macro
(which can also be written with an error string as an argument: `fail!( (which can also be written with an error string as an argument: `panic!(
~reason)`) and the `assert!` construct (which effectively calls `fail!()` if a ~reason)`) and the `assert!` construct (which effectively calls `panic!()` if a
boolean expression is false) are both ways to raise exceptions. When a task boolean expression is false) are both ways to raise exceptions. When a task
raises an exception, the task unwinds its stack—running destructors and raises an exception, the task unwinds its stack—running destructors and
freeing memory along the way—and then exits. Unlike exceptions in C++, 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. there is no way to "catch" the exception.
While it isn't possible for a task to recover from failure, tasks may notify While it isn't possible for a task to recover from panicking, tasks may notify
each other of failure. The simplest way of handling task failure is with the 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 `try` function, which is similar to `spawn`, but immediately blocks and waits
for the child task to finish. `try` returns a value of type 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: `Result<T, Box<Any + Send>>`. `Result` is an `enum` type with two variants:
@ -346,7 +346,7 @@ let result: Result<int, Box<std::any::Any + Send>> = task::try(proc() {
if some_condition() { if some_condition() {
calculate_result() calculate_result()
} else { } else {
fail!("oops!"); panic!("oops!");
} }
}); });
assert!(result.is_err()); assert!(result.is_err());
@ -355,18 +355,18 @@ assert!(result.is_err());
Unlike `spawn`, the function spawned using `try` may return a value, which 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 `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 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 [`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 > value (`try` always returns `Err(())`). In the
> future, it may be possible for tasks to intercept the value passed to > 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, 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 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 the outside world, which you happen to be processing in parallel, is malformed
such that the processing task cannot proceed). such that the processing task cannot proceed).

View file

@ -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 `--test` flag: `rustc myprogram.rs --test -o myprogram-tests`. Running
the resulting executable will run all the tests in the crate. A test the resulting executable will run all the tests in the crate. A test
is considered successful if its function returns; if the task running 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. other (`assert_eq`, ...) means, then the test fails.
When compiling a crate with the `--test` flag `--cfg test` is also When compiling a crate with the `--test` flag `--cfg test` is also
@ -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 Tests that are intended to fail can be annotated with the
`should_fail` attribute. The test will be run, and if it causes its `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: will be counted as a failure. For example:
~~~test_harness ~~~test_harness

View file

@ -182,7 +182,7 @@ code:
- implement the `Drop` for resource clean-up via a destructor, and use - implement the `Drop` for resource clean-up via a destructor, and use
RAII (Resource Acquisition Is Initialization). This reduces the need RAII (Resource Acquisition Is Initialization). This reduces the need
for any manual memory management by users, and automatically ensures 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 - ensure that any data stored behind a raw pointer is destroyed at the
appropriate time. appropriate time.
@ -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 failure mechanisms of the compiler. This is often mapped to GCC's
personality function (see the personality function (see the
[libstd implementation](std/rt/unwind/index.html) for more [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 that this function is never called. The final function, `fail_fmt`, is
also used by the failure mechanisms of the compiler. also used by the failure mechanisms of the compiler.

View file

@ -5213,17 +5213,17 @@ immediately.
## Success and failure ## Success and failure
Tasks don't always succeed, they can also fail. A task that wishes to fail Tasks don't always succeed, they can also panic. A task that wishes to panic
can call the `fail!` macro, passing a message: can call the `panic!` macro, passing a message:
```{rust} ```{rust}
spawn(proc() { spawn(proc() {
fail!("Nope."); panic!("Nope.");
}); });
``` ```
If a task fails, it is not possible for it to recover. However, it can If a task panics, 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`: notify other tasks that it has panicked. We can do this with `task::try`:
```{rust} ```{rust}
use std::task; use std::task;
@ -5233,14 +5233,14 @@ let result = task::try(proc() {
if rand::random() { if rand::random() {
println!("OK"); println!("OK");
} else { } 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 type, so we can handle the response like any other computation that may
fail. panic.
# Macros # Macros

View file

@ -817,15 +817,15 @@ mod math {
type Complex = (f64, f64); type Complex = (f64, f64);
fn sin(f: f64) -> f64 { fn sin(f: f64) -> f64 {
/* ... */ /* ... */
# fail!(); # panic!();
} }
fn cos(f: f64) -> f64 { fn cos(f: f64) -> f64 {
/* ... */ /* ... */
# fail!(); # panic!();
} }
fn tan(f: f64) -> f64 { fn tan(f: f64) -> f64 {
/* ... */ /* ... */
# fail!(); # panic!();
} }
} }
``` ```
@ -1194,12 +1194,12 @@ output slot type would normally be. For example:
``` ```
fn my_err(s: &str) -> ! { fn my_err(s: &str) -> ! {
println!("{}", s); println!("{}", s);
fail!(); panic!();
} }
``` ```
We call such functions "diverging" because they never return a value to the We call such functions "diverging" because they never return a value to the
caller. Every control path in a diverging function must end with a `fail!()` or caller. Every control path in a diverging function must end with a `panic!()` or
a call to another diverging function on every control path. The `!` annotation a call to another diverging function on every control path. The `!` annotation
does *not* denote a type. Rather, the result type of a diverging function is a does *not* denote a type. Rather, the result type of a diverging function is a
special type called $\bot$ ("bottom") that unifies with any type. Rust has no special type called $\bot$ ("bottom") that unifies with any type. Rust has no
@ -1212,7 +1212,7 @@ were declared without the `!` annotation, the following code would not
typecheck: typecheck:
``` ```
# fn my_err(s: &str) -> ! { fail!() } # fn my_err(s: &str) -> ! { panic!() }
fn f(i: int) -> int { fn f(i: int) -> int {
if i == 42 { if i == 42 {
@ -2259,7 +2259,7 @@ These types help drive the compiler's analysis
: Allocate memory on the exchange heap. : Allocate memory on the exchange heap.
* `closure_exchange_malloc` * `closure_exchange_malloc`
: ___Needs filling in___ : ___Needs filling in___
* `fail_` * `panic`
: Abort the program with an error. : Abort the program with an error.
* `fail_bounds_check` * `fail_bounds_check`
: Abort the program with a bounds check error. : Abort the program with a bounds check error.
@ -2866,11 +2866,11 @@ be assigned to.
Indices are zero-based, and may be of any integral type. Vector access is Indices are zero-based, and may be of any integral type. Vector access is
bounds-checked at run-time. When the check fails, it will put the task in a bounds-checked at run-time. When the check fails, it will put the task in a
_failing state_. _panicked state_.
```{should-fail} ```{should-fail}
([1, 2, 3, 4])[0]; ([1, 2, 3, 4])[0];
(["a", "b"])[10]; // fails (["a", "b"])[10]; // panics
``` ```
### Unary operator expressions ### Unary operator expressions
@ -3300,9 +3300,9 @@ enum List<X> { Nil, Cons(X, Box<List<X>>) }
let x: List<int> = Cons(10, box Cons(11, box Nil)); let x: List<int> = Cons(10, box Cons(11, box Nil));
match x { match x {
Cons(_, box Nil) => fail!("singleton list"), Cons(_, box Nil) => panic!("singleton list"),
Cons(..) => return, Cons(..) => return,
Nil => fail!("empty list") Nil => panic!("empty list")
} }
``` ```
@ -3373,7 +3373,7 @@ match x {
return; return;
} }
_ => { _ => {
fail!(); panic!();
} }
} }
``` ```
@ -3395,7 +3395,7 @@ fn is_sorted(list: &List) -> bool {
Cons(x, ref r @ box Cons(_, _)) => { Cons(x, ref r @ box Cons(_, _)) => {
match *r { match *r {
box Cons(y, _) => (x <= y) && is_sorted(&**r), box Cons(y, _) => (x <= y) && is_sorted(&**r),
_ => fail!() _ => panic!()
} }
} }
} }
@ -3459,7 +3459,7 @@ may refer to the variables bound within the pattern they follow.
let message = match maybe_digit { let message = match maybe_digit {
Some(x) if x < 10 => process_digit(x), Some(x) if x < 10 => process_digit(x),
Some(x) => process_other(x), Some(x) => process_other(x),
None => fail!() None => panic!()
}; };
``` ```
@ -4091,7 +4091,7 @@ cause transitions between the states. The lifecycle states of a task are:
* running * running
* blocked * blocked
* failing * panicked
* dead * dead
A task begins its lifecycle &mdash; once it has been spawned &mdash; in the A task begins its lifecycle &mdash; once it has been spawned &mdash; in the
@ -4103,21 +4103,21 @@ it makes a blocking communication call. When the call can be completed &mdash;
when a message arrives at a sender, or a buffer opens to receive a message when a message arrives at a sender, or a buffer opens to receive a message
&mdash; then the blocked task will unblock and transition back to *running*. &mdash; then the blocked task will unblock and transition back to *running*.
A task may transition to the *failing* state at any time, due being killed by A task may transition to the *panicked* state at any time, due being killed by
some external event or internally, from the evaluation of a `fail!()` macro. some external event or internally, from the evaluation of a `panic!()` macro.
Once *failing*, a task unwinds its stack and transitions to the *dead* state. Once *panicking*, a task unwinds its stack and transitions to the *dead* state.
Unwinding the stack of a task is done by the task itself, on its own control Unwinding the stack of a task is done by the task itself, on its own control
stack. If a value with a destructor is freed during unwinding, the code for the stack. If a value with a destructor is freed during unwinding, the code for the
destructor is run, also on the task's control stack. Running the destructor destructor is run, also on the task's control stack. Running the destructor
code causes a temporary transition to a *running* state, and allows the code causes a temporary transition to a *running* state, and allows the
destructor code to cause any subsequent state transitions. The original task destructor code to cause any subsequent state transitions. The original task
of unwinding and failing thereby may suspend temporarily, and may involve of unwinding and panicking thereby may suspend temporarily, and may involve
(recursive) unwinding of the stack of a failed destructor. Nonetheless, the (recursive) unwinding of the stack of a failed destructor. Nonetheless, the
outermost unwinding activity will continue until the stack is unwound and the outermost unwinding activity will continue until the stack is unwound and the
task transitions to the *dead* state. There is no way to "recover" from task task transitions to the *dead* state. There is no way to "recover" from task
failure. Once a task has temporarily suspended its unwinding in the *failing* panics. Once a task has temporarily suspended its unwinding in the *panicking*
state, failure occurring from within this destructor results in *hard* failure. state, a panic occurring from within this destructor results in *hard* panic.
A hard failure currently results in the process aborting. A hard panic currently results in the process aborting.
A task in the *dead* state cannot transition to other states; it exists only to A task in the *dead* state cannot transition to other states; it exists only to
have its termination status inspected by other tasks, and/or to await have its termination status inspected by other tasks, and/or to await

View file

@ -169,7 +169,7 @@ directive.
~~~md ~~~md
```should_fail ```should_fail
// This code block is expected to generate a failure when run // This code block is expected to generate a panic when run
``` ```
~~~ ~~~
@ -189,7 +189,7 @@ were passed to the compiler using the `test_harness` directive.
```test_harness ```test_harness
#[test] #[test]
fn foo() { fn foo() {
fail!("oops! (will run & register as failure)") panic!("oops! (will run & register as a failed test)")
} }
``` ```
~~~ ~~~

View file

@ -131,7 +131,7 @@ fn str_to_binop(s: &str) -> BinOpToken {
"|" => token::Or, "|" => token::Or,
"<<" => token::Shl, "<<" => token::Shl,
">>" => token::Shr, ">>" => token::Shr,
_ => fail!("Bad binop str `{}`", s), _ => panic!("Bad binop str `{}`", s),
} }
} }
@ -276,7 +276,7 @@ fn main() {
warn!("Different names for {} and {}", rustc_tok, antlr_tok); warn!("Different names for {} and {}", rustc_tok, antlr_tok);
} }
} }
_ => fail!("{} is not {}", antlr_tok, rustc_tok) _ => panic!("{} is not {}", antlr_tok, rustc_tok)
},)* },)*
ref c => assert!(c == &antlr_tok.tok, "{} is not {}", rustc_tok, antlr_tok) ref c => assert!(c == &antlr_tok.tok, "{} is not {}", rustc_tok, antlr_tok)
} }

View file

@ -227,9 +227,9 @@ impl<T: Sync + Send> Drop for Arc<T> {
impl<T: Sync + Send> Weak<T> { impl<T: Sync + Send> Weak<T> {
/// Attempts to upgrade this weak reference to a strong reference. /// Attempts to upgrade this weak reference to a strong reference.
/// ///
/// This method will fail to upgrade this reference if the strong reference /// This method will not upgrade this reference if the strong reference count has already
/// count has already reached 0, but if there are still other active strong /// reached 0, but if there are still other active strong references this function will return
/// references this function will return a new strong reference to the data. /// a new strong reference to the data.
pub fn upgrade(&self) -> Option<Arc<T>> { pub fn upgrade(&self) -> Option<Arc<T>> {
// We use a CAS loop to increment the strong count instead of a // We use a CAS loop to increment the strong count instead of a
// fetch_add because once the count hits 0 is must never be above 0. // fetch_add because once the count hits 0 is must never be above 0.

View file

@ -148,11 +148,11 @@ mod test {
match a.downcast::<uint>() { match a.downcast::<uint>() {
Ok(a) => { assert!(a == box 8u); } Ok(a) => { assert!(a == box 8u); }
Err(..) => fail!() Err(..) => panic!()
} }
match b.downcast::<Test>() { match b.downcast::<Test>() {
Ok(a) => { assert!(a == box Test); } Ok(a) => { assert!(a == box Test); }
Err(..) => fail!() Err(..) => panic!()
} }
let a = box 8u as Box<Any>; let a = box 8u as Box<Any>;

View file

@ -69,7 +69,7 @@ impl Chunk {
/// element). When the arena is destroyed, it iterates through all of its /// element). When the arena is destroyed, it iterates through all of its
/// chunks, and uses the tydesc information to trace through the objects, /// chunks, and uses the tydesc information to trace through the objects,
/// calling the destructors on them. One subtle point that needs to be /// calling the destructors on them. One subtle point that needs to be
/// addressed is how to handle failures while running the user provided /// addressed is how to handle panics while running the user provided
/// initializer function. It is important to not run the destructor on /// initializer function. It is important to not run the destructor on
/// uninitialized objects, but how to detect them is somewhat subtle. Since /// uninitialized objects, but how to detect them is somewhat subtle. Since
/// `alloc()` can be invoked recursively, it is not sufficient to simply exclude /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude
@ -162,7 +162,7 @@ unsafe fn destroy_chunk(chunk: &Chunk) {
// We encode whether the object a tydesc describes has been // We encode whether the object a tydesc describes has been
// initialized in the arena in the low bit of the tydesc pointer. This // initialized in the arena in the low bit of the tydesc pointer. This
// is necessary in order to properly do cleanup if a failure occurs // is necessary in order to properly do cleanup if a panic occurs
// during an initializer. // during an initializer.
#[inline] #[inline]
fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> uint { fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> uint {
@ -337,10 +337,9 @@ fn test_arena_destructors_fail() {
// things interesting. // things interesting.
arena.alloc(|| { [0u8, 1u8, 2u8] }); arena.alloc(|| { [0u8, 1u8, 2u8] });
} }
// Now, fail while allocating // Now, panic while allocating
arena.alloc::<Rc<int>>(|| { arena.alloc::<Rc<int>>(|| {
// Now fail. panic!();
fail!();
}); });
} }

View file

@ -68,7 +68,7 @@ pub struct Node<K, V> {
impl<K: Ord, V> Node<K, V> { impl<K: Ord, V> Node<K, V> {
/// Searches for the given key in the node. If it finds an exact match, /// Searches for the given key in the node. If it finds an exact match,
/// `Found` will be yielded with the matching index. If it fails to find an exact match, /// `Found` will be yielded with the matching index. If it doesn't find an exact match,
/// `GoDown` will be yielded with the index of the subtree the key must lie in. /// `GoDown` will be yielded with the index of the subtree the key must lie in.
pub fn search(&self, key: &K) -> SearchResult { pub fn search(&self, key: &K) -> SearchResult {
// FIXME(Gankro): Tune when to search linear or binary based on B (and maybe K/V). // FIXME(Gankro): Tune when to search linear or binary based on B (and maybe K/V).

View file

@ -760,11 +760,11 @@ mod tests {
loop { loop {
match (last_ptr, node_ptr.prev.resolve_immut()) { match (last_ptr, node_ptr.prev.resolve_immut()) {
(None , None ) => {} (None , None ) => {}
(None , _ ) => fail!("prev link for list_head"), (None , _ ) => panic!("prev link for list_head"),
(Some(p), Some(pptr)) => { (Some(p), Some(pptr)) => {
assert_eq!(p as *const Node<T>, pptr as *const Node<T>); assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
} }
_ => fail!("prev link is none, not good"), _ => panic!("prev link is none, not good"),
} }
match node_ptr.next { match node_ptr.next {
Some(ref next) => { Some(ref next) => {

View file

@ -527,8 +527,8 @@ pub fn fixme_14344_be_sure_to_link_to_collections() {}
#[cfg(not(test))] #[cfg(not(test))]
mod std { mod std {
pub use core::fmt; // necessary for fail!() pub use core::fmt; // necessary for panic!()
pub use core::option; // necessary for fail!() pub use core::option; // necessary for panic!()
pub use core::clone; // deriving(Clone) pub use core::clone; // deriving(Clone)
pub use core::cmp; // deriving(Eq, Ord, etc.) pub use core::cmp; // deriving(Eq, Ord, etc.)
pub use hash; // deriving(Hash) pub use hash; // deriving(Hash)

View file

@ -152,7 +152,7 @@ impl<T> RingBuf<T> {
pub fn get_mut<'a>(&'a mut self, i: uint) -> &'a mut T { pub fn get_mut<'a>(&'a mut self, i: uint) -> &'a mut T {
let idx = self.raw_index(i); let idx = self.raw_index(i);
match *self.elts.get_mut(idx) { match *self.elts.get_mut(idx) {
None => fail!(), None => panic!(),
Some(ref mut v) => v Some(ref mut v) => v
} }
} }
@ -460,7 +460,7 @@ impl<A> Index<uint, A> for RingBuf<A> {
fn index<'a>(&'a self, i: &uint) -> &'a A { fn index<'a>(&'a self, i: &uint) -> &'a A {
let idx = self.raw_index(*i); let idx = self.raw_index(*i);
match self.elts[idx] { match self.elts[idx] {
None => fail!(), None => panic!(),
Some(ref v) => v, Some(ref v) => v,
} }
} }

View file

@ -1181,7 +1181,7 @@ mod tests {
3 => assert!(v == [2, 3, 1]), 3 => assert!(v == [2, 3, 1]),
4 => assert!(v == [2, 1, 3]), 4 => assert!(v == [2, 1, 3]),
5 => assert!(v == [1, 2, 3]), 5 => assert!(v == [1, 2, 3]),
_ => fail!(), _ => panic!(),
} }
} }
} }
@ -1391,7 +1391,7 @@ mod tests {
} }
} }
// shouldn't fail/crash // shouldn't panic
let mut v: [uint, .. 0] = []; let mut v: [uint, .. 0] = [];
v.sort(); v.sort();
@ -1545,7 +1545,7 @@ mod tests {
#[should_fail] #[should_fail]
fn test_from_fn_fail() { fn test_from_fn_fail() {
Vec::from_fn(100, |v| { Vec::from_fn(100, |v| {
if v == 50 { fail!() } if v == 50 { panic!() }
box 0i box 0i
}); });
} }
@ -1562,7 +1562,7 @@ mod tests {
impl Clone for S { impl Clone for S {
fn clone(&self) -> S { fn clone(&self) -> S {
self.f.set(self.f.get() + 1); self.f.set(self.f.get() + 1);
if self.f.get() == 10 { fail!() } if self.f.get() == 10 { panic!() }
S { f: self.f, boxes: self.boxes.clone() } S { f: self.f, boxes: self.boxes.clone() }
} }
} }
@ -1577,7 +1577,7 @@ mod tests {
let mut v = vec![]; let mut v = vec![];
v.grow_fn(100, |i| { v.grow_fn(100, |i| {
if i == 50 { if i == 50 {
fail!() panic!()
} }
(box 0i, Rc::new(0i)) (box 0i, Rc::new(0i))
}) })
@ -1591,7 +1591,7 @@ mod tests {
let mut i = 0u; let mut i = 0u;
for _ in v.permutations() { for _ in v.permutations() {
if i == 2 { if i == 2 {
fail!() panic!()
} }
i += 1; i += 1;
} }
@ -2189,7 +2189,7 @@ mod bench {
sum += *x; sum += *x;
} }
// sum == 11806, to stop dead code elimination. // sum == 11806, to stop dead code elimination.
if sum == 0 {fail!()} if sum == 0 {panic!()}
}) })
} }

View file

@ -511,7 +511,7 @@ mod test_map {
assert!(m.insert(5, 14)); assert!(m.insert(5, 14));
let new = 100; let new = 100;
match m.find_mut(&5) { match m.find_mut(&5) {
None => fail!(), Some(x) => *x = new None => panic!(), Some(x) => *x = new
} }
assert_eq!(m.find(&5), Some(&new)); assert_eq!(m.find(&5), Some(&new));
} }

View file

@ -1367,7 +1367,7 @@ mod tests {
// original problem code path anymore.) // original problem code path anymore.)
let s = String::from_str(""); let s = String::from_str("");
let _bytes = s.as_bytes(); let _bytes = s.as_bytes();
fail!(); panic!();
} }
#[test] #[test]
@ -1586,7 +1586,7 @@ mod tests {
let len = c.encode_utf8(bytes).unwrap_or(0); let len = c.encode_utf8(bytes).unwrap_or(0);
let s = ::core::str::from_utf8(bytes[..len]).unwrap(); let s = ::core::str::from_utf8(bytes[..len]).unwrap();
if Some(c) != s.chars().next() { if Some(c) != s.chars().next() {
fail!("character {:x}={} does not decode correctly", c as u32, c); panic!("character {:x}={} does not decode correctly", c as u32, c);
} }
} }
} }
@ -1598,7 +1598,7 @@ mod tests {
let len = c.encode_utf8(bytes).unwrap_or(0); let len = c.encode_utf8(bytes).unwrap_or(0);
let s = ::core::str::from_utf8(bytes[..len]).unwrap(); let s = ::core::str::from_utf8(bytes[..len]).unwrap();
if Some(c) != s.chars().rev().next() { if Some(c) != s.chars().rev().next() {
fail!("character {:x}={} does not decode correctly", c as u32, c); panic!("character {:x}={} does not decode correctly", c as u32, c);
} }
} }
} }

View file

@ -504,7 +504,7 @@ impl String {
/// assert_eq!(s.as_slice(), "he"); /// assert_eq!(s.as_slice(), "he");
/// ``` /// ```
#[inline] #[inline]
#[unstable = "the failure conventions for strings are under development"] #[unstable = "the panic conventions for strings are under development"]
pub fn truncate(&mut self, new_len: uint) { pub fn truncate(&mut self, new_len: uint) {
assert!(self.as_slice().is_char_boundary(new_len)); assert!(self.as_slice().is_char_boundary(new_len));
self.vec.truncate(new_len) self.vec.truncate(new_len)
@ -545,10 +545,10 @@ impl String {
/// This is a O(n) operation as it requires copying every element in the /// This is a O(n) operation as it requires copying every element in the
/// buffer. /// buffer.
/// ///
/// # Failure /// # Panics
/// ///
/// If `idx` does not lie on a character boundary, then this function will /// If `idx` does not lie on a character boundary, then this function will
/// fail. /// panic.
/// ///
/// # Example /// # Example
/// ///
@ -559,7 +559,7 @@ impl String {
/// assert_eq!(s.remove(0), Some('o')); /// assert_eq!(s.remove(0), Some('o'));
/// assert_eq!(s.remove(0), None); /// assert_eq!(s.remove(0), None);
/// ``` /// ```
#[unstable = "the failure semantics of this function and return type \ #[unstable = "the panic semantics of this function and return type \
may change"] may change"]
pub fn remove(&mut self, idx: uint) -> Option<char> { pub fn remove(&mut self, idx: uint) -> Option<char> {
let len = self.len(); let len = self.len();
@ -582,11 +582,11 @@ impl String {
/// This is a O(n) operation as it requires copying every element in the /// This is a O(n) operation as it requires copying every element in the
/// buffer. /// buffer.
/// ///
/// # Failure /// # Panics
/// ///
/// If `idx` does not lie on a character boundary or is out of bounds, then /// If `idx` does not lie on a character boundary or is out of bounds, then
/// this function will fail. /// this function will panic.
#[unstable = "the failure semantics of this function are uncertain"] #[unstable = "the panic semantics of this function are uncertain"]
pub fn insert(&mut self, idx: uint, ch: char) { pub fn insert(&mut self, idx: uint, ch: char) {
let len = self.len(); let len = self.len();
assert!(idx <= len); assert!(idx <= len);

View file

@ -490,7 +490,7 @@ impl<K, V> TreeMap<K, V> {
/// let new_ua = "Safari/156.0"; /// let new_ua = "Safari/156.0";
/// match t.find_with_mut(|k| "User-Agent".cmp(k)) { /// match t.find_with_mut(|k| "User-Agent".cmp(k)) {
/// Some(x) => *x = new_ua, /// Some(x) => *x = new_ua,
/// None => fail!(), /// None => panic!(),
/// } /// }
/// ///
/// assert_eq!(t.find(&"User-Agent"), Some(&new_ua)); /// assert_eq!(t.find(&"User-Agent"), Some(&new_ua));
@ -1616,7 +1616,7 @@ fn remove<K: Ord, V>(node: &mut Option<Box<TreeNode<K, V>>>,
} }
} }
return match node.take() { return match node.take() {
Some(box TreeNode{value, ..}) => Some(value), None => fail!() Some(box TreeNode{value, ..}) => Some(value), None => panic!()
}; };
} }
@ -1726,7 +1726,7 @@ mod test_treemap {
assert!(m.insert(5, 14)); assert!(m.insert(5, 14));
let new = 100; let new = 100;
match m.find_mut(&5) { match m.find_mut(&5) {
None => fail!(), Some(x) => *x = new None => panic!(), Some(x) => *x = new
} }
assert_eq!(m.find(&5), Some(&new)); assert_eq!(m.find(&5), Some(&new));
} }
@ -1739,7 +1739,7 @@ mod test_treemap {
assert!(m.insert("t5", 14)); assert!(m.insert("t5", 14));
let new = 100; let new = 100;
match m.find_with_mut(|k| "t5".cmp(k)) { match m.find_with_mut(|k| "t5".cmp(k)) {
None => fail!(), Some(x) => *x = new None => panic!(), Some(x) => *x = new
} }
assert_eq!(m.find_with(|k| "t5".cmp(k)), Some(&new)); assert_eq!(m.find_with(|k| "t5".cmp(k)), Some(&new));
} }

View file

@ -834,7 +834,7 @@ fn insert<T>(count: &mut uint, child: &mut Child<T>, key: uint, value: T,
*child = Internal(new); *child = Internal(new);
return ret; return ret;
} }
_ => fail!("unreachable code"), _ => panic!("unreachable code"),
} }
} }
@ -844,7 +844,7 @@ fn remove<T>(count: &mut uint, child: &mut Child<T>, key: uint,
External(stored, _) if stored == key => { External(stored, _) if stored == key => {
match mem::replace(child, Nothing) { match mem::replace(child, Nothing) {
External(_, value) => (Some(value), true), External(_, value) => (Some(value), true),
_ => fail!() _ => panic!()
} }
} }
External(..) => (None, false), External(..) => (None, false),
@ -1057,7 +1057,7 @@ mod test_map {
assert!(m.insert(5u, 14i)); assert!(m.insert(5u, 14i));
let new = 100; let new = 100;
match m.find_mut(&5) { match m.find_mut(&5) {
None => fail!(), Some(x) => *x = new None => panic!(), Some(x) => *x = new
} }
assert_eq!(m.find(&5), Some(&new)); assert_eq!(m.find(&5), Some(&new));
} }

View file

@ -583,7 +583,7 @@ impl<T> Vec<T> {
pub fn reserve_additional(&mut self, extra: uint) { pub fn reserve_additional(&mut self, extra: uint) {
if self.cap - self.len < extra { if self.cap - self.len < extra {
match self.len.checked_add(&extra) { match self.len.checked_add(&extra) {
None => fail!("Vec::reserve_additional: `uint` overflow"), None => panic!("Vec::reserve_additional: `uint` overflow"),
Some(new_cap) => self.reserve(new_cap) Some(new_cap) => self.reserve(new_cap)
} }
} }
@ -699,12 +699,12 @@ impl<T> Vec<T> {
/// vec.truncate(2); /// vec.truncate(2);
/// assert_eq!(vec, vec![1, 2]); /// assert_eq!(vec, vec![1, 2]);
/// ``` /// ```
#[unstable = "waiting on failure semantics"] #[unstable = "waiting on panic semantics"]
pub fn truncate(&mut self, len: uint) { pub fn truncate(&mut self, len: uint) {
unsafe { unsafe {
// drop any extra elements // drop any extra elements
while len < self.len { while len < self.len {
// decrement len before the read(), so a failure on Drop doesn't // decrement len before the read(), so a panic on Drop doesn't
// re-drop the just-failed value. // re-drop the just-failed value.
self.len -= 1; self.len -= 1;
ptr::read(self.as_slice().unsafe_get(self.len)); ptr::read(self.as_slice().unsafe_get(self.len));
@ -960,9 +960,9 @@ impl<T> Vec<T> {
/// Inserts an element at position `index` within the vector, shifting all /// Inserts an element at position `index` within the vector, shifting all
/// elements after position `i` one position to the right. /// elements after position `i` one position to the right.
/// ///
/// # Failure /// # Panics
/// ///
/// Fails if `index` is not between `0` and the vector's length (both /// Panics if `index` is not between `0` and the vector's length (both
/// bounds inclusive). /// bounds inclusive).
/// ///
/// # Example /// # Example
@ -974,7 +974,7 @@ impl<T> Vec<T> {
/// vec.insert(4, 5); /// vec.insert(4, 5);
/// assert_eq!(vec, vec![1, 4, 2, 3, 5]); /// assert_eq!(vec, vec![1, 4, 2, 3, 5]);
/// ``` /// ```
#[unstable = "failure semantics need settling"] #[unstable = "panic semantics need settling"]
pub fn insert(&mut self, index: uint, element: T) { pub fn insert(&mut self, index: uint, element: T) {
let len = self.len(); let len = self.len();
assert!(index <= len); assert!(index <= len);
@ -1011,7 +1011,7 @@ impl<T> Vec<T> {
/// // v is unchanged: /// // v is unchanged:
/// assert_eq!(v, vec![1, 3]); /// assert_eq!(v, vec![1, 3]);
/// ``` /// ```
#[unstable = "failure semantics need settling"] #[unstable = "panic semantics need settling"]
pub fn remove(&mut self, index: uint) -> Option<T> { pub fn remove(&mut self, index: uint) -> Option<T> {
let len = self.len(); let len = self.len();
if index < len { if index < len {
@ -1353,7 +1353,7 @@ impl<T: PartialEq> Vec<T> {
pub fn dedup(&mut self) { pub fn dedup(&mut self) {
unsafe { unsafe {
// Although we have a mutable reference to `self`, we cannot make // Although we have a mutable reference to `self`, we cannot make
// *arbitrary* changes. The `PartialEq` comparisons could fail, so we // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
// must ensure that the vector is in a valid state at all time. // must ensure that the vector is in a valid state at all time.
// //
// The way that we handle this is by using swaps; we iterate // The way that we handle this is by using swaps; we iterate
@ -1520,7 +1520,7 @@ impl<T> MutableSeq<T> for Vec<T> {
if self.len == self.cap { if self.len == self.cap {
let old_size = self.cap * mem::size_of::<T>(); let old_size = self.cap * mem::size_of::<T>();
let size = max(old_size, 2 * mem::size_of::<T>()) * 2; let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
if old_size > size { fail!("capacity overflow") } if old_size > size { panic!("capacity overflow") }
unsafe { unsafe {
self.ptr = alloc_or_realloc(self.ptr, old_size, size); self.ptr = alloc_or_realloc(self.ptr, old_size, size);
} }
@ -1877,7 +1877,7 @@ impl<T> Vec<T> {
// +-+-+-+-+-+-+-+-+-+ // +-+-+-+-+-+-+-+-+-+
// | | // | |
// end_u end_t // end_u end_t
// We must not fail here, one cell is marked as `T` // We must not panic here, one cell is marked as `T`
// although it is not `T`. // although it is not `T`.
pv.start_t = pv.start_t.offset(1); pv.start_t = pv.start_t.offset(1);
@ -1888,9 +1888,9 @@ impl<T> Vec<T> {
// +-+-+-+-+-+-+-+-+-+ // +-+-+-+-+-+-+-+-+-+
// | | // | |
// end_u end_t // end_u end_t
// We may fail again. // We may panic again.
// The function given by the user might fail. // The function given by the user might panic.
let u = f(t); let u = f(t);
ptr::write(pv.end_u, u); ptr::write(pv.end_u, u);
@ -1901,7 +1901,7 @@ impl<T> Vec<T> {
// +-+-+-+-+-+-+-+-+-+ // +-+-+-+-+-+-+-+-+-+
// | | // | |
// end_u end_t // end_u end_t
// We should not fail here, because that would leak the `U` // We should not panic here, because that would leak the `U`
// pointed to by `end_u`. // pointed to by `end_u`.
pv.end_u = pv.end_u.offset(1); pv.end_u = pv.end_u.offset(1);
@ -1912,7 +1912,7 @@ impl<T> Vec<T> {
// +-+-+-+-+-+-+-+-+-+ // +-+-+-+-+-+-+-+-+-+
// | | // | |
// end_u end_t // end_u end_t
// We may fail again. // We may panic again.
} }
} }
@ -1926,10 +1926,10 @@ impl<T> Vec<T> {
// end_u // end_u
// Extract `vec` and prevent the destructor of // Extract `vec` and prevent the destructor of
// `PartialVecNonZeroSized` from running. Note that none of the // `PartialVecNonZeroSized` from running. Note that none of the
// function calls can fail, thus no resources can be leaked (as the // function calls can panic, thus no resources can be leaked (as the
// `vec` member of `PartialVec` is the only one which holds // `vec` member of `PartialVec` is the only one which holds
// allocations -- and it is returned from this function. None of // allocations -- and it is returned from this function. None of
// this can fail. // this can panic.
unsafe { unsafe {
let vec_len = pv.vec.len(); let vec_len = pv.vec.len();
let vec_cap = pv.vec.capacity(); let vec_cap = pv.vec.capacity();
@ -1953,24 +1953,24 @@ impl<T> Vec<T> {
while pv.num_t != 0 { while pv.num_t != 0 {
unsafe { unsafe {
// Create a `T` out of thin air and decrement `num_t`. This // Create a `T` out of thin air and decrement `num_t`. This
// must not fail between these steps, as otherwise a // must not panic between these steps, as otherwise a
// destructor of `T` which doesn't exist runs. // destructor of `T` which doesn't exist runs.
let t = mem::uninitialized(); let t = mem::uninitialized();
pv.num_t -= 1; pv.num_t -= 1;
// The function given by the user might fail. // The function given by the user might panic.
let u = f(t); let u = f(t);
// Forget the `U` and increment `num_u`. This increment // Forget the `U` and increment `num_u`. This increment
// cannot overflow the `uint` as we only do this for a // cannot overflow the `uint` as we only do this for a
// number of times that fits into a `uint` (and start with // number of times that fits into a `uint` (and start with
// `0`). Again, we should not fail between these steps. // `0`). Again, we should not panic between these steps.
mem::forget(u); mem::forget(u);
pv.num_u += 1; pv.num_u += 1;
} }
} }
// Create a `Vec` from our `PartialVecZeroSized` and make sure the // Create a `Vec` from our `PartialVecZeroSized` and make sure the
// destructor of the latter will not run. None of this can fail. // destructor of the latter will not run. None of this can panic.
let mut result = Vec::new(); let mut result = Vec::new();
unsafe { result.set_len(pv.num_u); } unsafe { result.set_len(pv.num_u); }
result result
@ -2292,7 +2292,7 @@ mod tests {
fn drop(&mut self) { fn drop(&mut self) {
let BadElem(ref mut x) = *self; let BadElem(ref mut x) = *self;
if *x == 0xbadbeef { if *x == 0xbadbeef {
fail!("BadElem failure: 0xbadbeef") panic!("BadElem panic: 0xbadbeef")
} }
} }
} }

View file

@ -599,8 +599,8 @@ unsafe fn atomic_store<T>(dst: *mut T, val: T, order:Ordering) {
Release => intrinsics::atomic_store_rel(dst, val), Release => intrinsics::atomic_store_rel(dst, val),
Relaxed => intrinsics::atomic_store_relaxed(dst, val), Relaxed => intrinsics::atomic_store_relaxed(dst, val),
SeqCst => intrinsics::atomic_store(dst, val), SeqCst => intrinsics::atomic_store(dst, val),
Acquire => fail!("there is no such thing as an acquire store"), Acquire => panic!("there is no such thing as an acquire store"),
AcqRel => fail!("there is no such thing as an acquire/release store"), AcqRel => panic!("there is no such thing as an acquire/release store"),
} }
} }
@ -610,8 +610,8 @@ unsafe fn atomic_load<T>(dst: *const T, order:Ordering) -> T {
Acquire => intrinsics::atomic_load_acq(dst), Acquire => intrinsics::atomic_load_acq(dst),
Relaxed => intrinsics::atomic_load_relaxed(dst), Relaxed => intrinsics::atomic_load_relaxed(dst),
SeqCst => intrinsics::atomic_load(dst), SeqCst => intrinsics::atomic_load(dst),
Release => fail!("there is no such thing as a release load"), Release => panic!("there is no such thing as a release load"),
AcqRel => fail!("there is no such thing as an acquire/release load"), AcqRel => panic!("there is no such thing as an acquire/release load"),
} }
} }
@ -737,7 +737,7 @@ pub fn fence(order: Ordering) {
Release => intrinsics::atomic_fence_rel(), Release => intrinsics::atomic_fence_rel(),
AcqRel => intrinsics::atomic_fence_acqrel(), AcqRel => intrinsics::atomic_fence_acqrel(),
SeqCst => intrinsics::atomic_fence(), SeqCst => intrinsics::atomic_fence(),
Relaxed => fail!("there is no such thing as a relaxed fence") Relaxed => panic!("there is no such thing as a relaxed fence")
} }
} }
} }

View file

@ -31,7 +31,7 @@
//! tracked statically, at compile time. Because `RefCell` borrows are //! tracked statically, at compile time. Because `RefCell` borrows are
//! dynamic it is possible to attempt to borrow a value that is //! dynamic it is possible to attempt to borrow a value that is
//! already mutably borrowed; when this happens it results in task //! already mutably borrowed; when this happens it results in task
//! failure. //! panic.
//! //!
//! # When to choose interior mutability //! # When to choose interior mutability
//! //!
@ -109,7 +109,7 @@
//! // Recursive call to return the just-cached value. //! // Recursive call to return the just-cached value.
//! // Note that if we had not let the previous borrow //! // Note that if we had not let the previous borrow
//! // of the cache fall out of scope then the subsequent //! // of the cache fall out of scope then the subsequent
//! // recursive borrow would cause a dynamic task failure. //! // recursive borrow would cause a dynamic task panic.
//! // This is the major hazard of using `RefCell`. //! // This is the major hazard of using `RefCell`.
//! self.minimum_spanning_tree() //! self.minimum_spanning_tree()
//! } //! }
@ -281,7 +281,7 @@ impl<T> RefCell<T> {
pub fn borrow<'a>(&'a self) -> Ref<'a, T> { pub fn borrow<'a>(&'a self) -> Ref<'a, T> {
match self.try_borrow() { match self.try_borrow() {
Some(ptr) => ptr, Some(ptr) => ptr,
None => fail!("RefCell<T> already mutably borrowed") None => panic!("RefCell<T> already mutably borrowed")
} }
} }
@ -314,7 +314,7 @@ impl<T> RefCell<T> {
pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> {
match self.try_borrow_mut() { match self.try_borrow_mut() {
Some(ptr) => ptr, Some(ptr) => ptr,
None => fail!("RefCell<T> already borrowed") None => panic!("RefCell<T> already borrowed")
} }
} }

View file

@ -120,7 +120,7 @@ pub fn is_digit_radix(c: char, radix: uint) -> bool {
#[inline] #[inline]
pub fn to_digit(c: char, radix: uint) -> Option<uint> { pub fn to_digit(c: char, radix: uint) -> Option<uint> {
if radix > 36 { if radix > 36 {
fail!("to_digit: radix is too high (maximum 36)"); panic!("to_digit: radix is too high (maximum 36)");
} }
let val = match c { let val = match c {
'0' ... '9' => c as uint - ('0' as uint), '0' ... '9' => c as uint - ('0' as uint),
@ -147,7 +147,7 @@ pub fn to_digit(c: char, radix: uint) -> Option<uint> {
#[inline] #[inline]
pub fn from_digit(num: uint, radix: uint) -> Option<char> { pub fn from_digit(num: uint, radix: uint) -> Option<char> {
if radix > 36 { if radix > 36 {
fail!("from_digit: radix is too high (maximum 36)"); panic!("from_digit: radix is to high (maximum 36)");
} }
if num < radix { if num < radix {
unsafe { unsafe {

View file

@ -60,7 +60,7 @@ impl<T> Finally<T> for fn() -> T {
/** /**
* The most general form of the `finally` functions. The function * The most general form of the `finally` functions. The function
* `try_fn` will be invoked first; whether or not it fails, the * `try_fn` will be invoked first; whether or not it panics, the
* function `finally_fn` will be invoked next. The two parameters * function `finally_fn` will be invoked next. The two parameters
* `mutate` and `drop` are used to thread state through the two * `mutate` and `drop` are used to thread state through the two
* closures. `mutate` is used for any shared, mutable state that both * closures. `mutate` is used for any shared, mutable state that both
@ -69,7 +69,7 @@ impl<T> Finally<T> for fn() -> T {
* *
* **WARNING:** While shared, mutable state between the try and finally * **WARNING:** While shared, mutable state between the try and finally
* function is often necessary, one must be very careful; the `try` * function is often necessary, one must be very careful; the `try`
* function could have failed at any point, so the values of the shared * function could have panicked at any point, so the values of the shared
* state may be inconsistent. * state may be inconsistent.
* *
* # Example * # Example

View file

@ -94,7 +94,7 @@ pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
assert!(2 <= radix && radix <= 36); assert!(2 <= radix && radix <= 36);
match exp_format { match exp_format {
ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e' ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e'
=> fail!("float_to_str_bytes_common: radix {} incompatible with \ => panic!("float_to_str_bytes_common: radix {} incompatible with \
use of 'e' as decimal exponent", radix), use of 'e' as decimal exponent", radix),
_ => () _ => ()
} }
@ -127,7 +127,7 @@ pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
ExpDec => { ExpDec => {
let (exp, exp_base) = match exp_format { let (exp, exp_base) = match exp_format {
ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()), ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()),
ExpNone => fail!("unreachable"), ExpNone => panic!("unreachable"),
}; };
(num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap()) (num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap())
@ -299,7 +299,7 @@ pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
buf[end] = match exp_format { buf[end] = match exp_format {
ExpDec if exp_upper => 'E', ExpDec if exp_upper => 'E',
ExpDec if !exp_upper => 'e', ExpDec if !exp_upper => 'e',
_ => fail!("unreachable"), _ => panic!("unreachable"),
} as u8; } as u8;
end += 1; end += 1;

View file

@ -92,7 +92,7 @@ macro_rules! radix {
fn digit(&self, x: u8) -> u8 { fn digit(&self, x: u8) -> u8 {
match x { match x {
$($x => $conv,)+ $($x => $conv,)+
x => fail!("number not in the range 0..{}: {}", self.base() - 1, x), x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
} }
} }
} }
@ -126,7 +126,7 @@ impl GenericRadix for Radix {
match x { match x {
x @ 0 ... 9 => b'0' + x, x @ 0 ... 9 => b'0' + x,
x if x < self.base() => b'a' + (x - 10), x if x < self.base() => b'a' + (x - 10),
x => fail!("number not in the range 0..{}: {}", self.base() - 1, x), x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
} }
} }
} }

View file

@ -40,8 +40,8 @@
//! //!
//! * `rust_begin_unwind` - This function takes three arguments, a //! * `rust_begin_unwind` - This function takes three arguments, a
//! `&fmt::Arguments`, a `&str`, and a `uint`. These three arguments dictate //! `&fmt::Arguments`, a `&str`, and a `uint`. These three arguments dictate
//! the failure message, the file at which failure was invoked, and the line. //! the panic message, the file at which panic was invoked, and the line.
//! It is up to consumers of this core library to define this failure //! It is up to consumers of this core library to define this panic
//! function; it is only required to never return. //! function; it is only required to never return.
// Since libcore defines many fundamental lang items, all tests live in a // Since libcore defines many fundamental lang items, all tests live in a
@ -111,7 +111,7 @@ pub mod atomic;
pub mod bool; pub mod bool;
pub mod cell; pub mod cell;
pub mod char; pub mod char;
pub mod failure; pub mod panicking;
pub mod finally; pub mod finally;
pub mod iter; pub mod iter;
pub mod option; pub mod option;
@ -129,7 +129,7 @@ pub mod fmt;
#[doc(hidden)] #[doc(hidden)]
mod core { mod core {
pub use failure; pub use panicking;
} }
#[doc(hidden)] #[doc(hidden)]

View file

@ -10,15 +10,15 @@
#![macro_escape] #![macro_escape]
/// Entry point of failure, for details, see std::macros /// Entry point of task panic, for details, see std::macros
#[macro_export] #[macro_export]
macro_rules! fail( macro_rules! panic(
() => ( () => (
fail!("{}", "explicit failure") panic!("{}", "explicit panic")
); );
($msg:expr) => ({ ($msg:expr) => ({
static _MSG_FILE_LINE: (&'static str, &'static str, uint) = ($msg, file!(), line!()); static _MSG_FILE_LINE: (&'static str, &'static str, uint) = ($msg, file!(), line!());
::core::failure::fail(&_MSG_FILE_LINE) ::core::panicking::panic(&_MSG_FILE_LINE)
}); });
($fmt:expr, $($arg:tt)*) => ({ ($fmt:expr, $($arg:tt)*) => ({
// a closure can't have return type !, so we need a full // a closure can't have return type !, so we need a full
@ -31,7 +31,7 @@ macro_rules! fail(
// as returning !. We really do want this to be inlined, however, // as returning !. We really do want this to be inlined, however,
// because it's just a tiny wrapper. Small wins (156K to 149K in size) // because it's just a tiny wrapper. Small wins (156K to 149K in size)
// were seen when forcing this to be inlined, and that number just goes // were seen when forcing this to be inlined, and that number just goes
// up with the number of calls to fail!() // up with the number of calls to panic!()
// //
// The leading _'s are to avoid dead code warnings if this is // The leading _'s are to avoid dead code warnings if this is
// used inside a dead function. Just `#[allow(dead_code)]` is // used inside a dead function. Just `#[allow(dead_code)]` is
@ -40,7 +40,7 @@ macro_rules! fail(
#[inline(always)] #[inline(always)]
fn _run_fmt(fmt: &::std::fmt::Arguments) -> ! { fn _run_fmt(fmt: &::std::fmt::Arguments) -> ! {
static _FILE_LINE: (&'static str, uint) = (file!(), line!()); static _FILE_LINE: (&'static str, uint) = (file!(), line!());
::core::failure::fail_fmt(fmt, &_FILE_LINE) ::core::panicking::panic_fmt(fmt, &_FILE_LINE)
} }
format_args!(_run_fmt, $fmt, $($arg)*) format_args!(_run_fmt, $fmt, $($arg)*)
}); });
@ -51,12 +51,12 @@ macro_rules! fail(
macro_rules! assert( macro_rules! assert(
($cond:expr) => ( ($cond:expr) => (
if !$cond { if !$cond {
fail!(concat!("assertion failed: ", stringify!($cond))) panic!(concat!("assertion failed: ", stringify!($cond)))
} }
); );
($cond:expr, $($arg:tt)*) => ( ($cond:expr, $($arg:tt)*) => (
if !$cond { if !$cond {
fail!($($arg)*) panic!($($arg)*)
} }
); );
) )
@ -78,7 +78,7 @@ macro_rules! assert_eq(
let c1 = $cond1; let c1 = $cond1;
let c2 = $cond2; let c2 = $cond2;
if c1 != c2 || c2 != c1 { if c1 != c2 || c2 != c1 {
fail!("expressions not equal, left: {}, right: {}", c1, c2); panic!("expressions not equal, left: {}, right: {}", c1, c2);
} }
}) })
) )
@ -130,4 +130,4 @@ macro_rules! write(
) )
#[macro_export] #[macro_export]
macro_rules! unreachable( () => (fail!("unreachable code")) ) macro_rules! unreachable( () => (panic!("unreachable code")) )

View file

@ -1349,7 +1349,7 @@ checked_impl!(CheckedMul, checked_mul, i16, intrinsics::i16_mul_with_overflow)
checked_impl!(CheckedMul, checked_mul, i32, intrinsics::i32_mul_with_overflow) checked_impl!(CheckedMul, checked_mul, i32, intrinsics::i32_mul_with_overflow)
checked_impl!(CheckedMul, checked_mul, i64, intrinsics::i64_mul_with_overflow) checked_impl!(CheckedMul, checked_mul, i64, intrinsics::i64_mul_with_overflow)
/// Performs division that returns `None` instead of failing on division by zero and instead of /// Performs division that returns `None` instead of panicking on division by zero and instead of
/// wrapping around on underflow and overflow. /// wrapping around on underflow and overflow.
pub trait CheckedDiv: Div<Self, Self> { pub trait CheckedDiv: Div<Self, Self> {
/// Divides two numbers, checking for underflow, overflow and division by zero. If any of that /// Divides two numbers, checking for underflow, overflow and division by zero. If any of that

View file

@ -291,9 +291,9 @@ impl<T> Option<T> {
/// Unwraps an option, yielding the content of a `Some` /// Unwraps an option, yielding the content of a `Some`
/// ///
/// # Failure /// # Panics
/// ///
/// Fails if the value is a `None` with a custom failure message provided by /// Fails if the value is a `None` with a custom panic message provided by
/// `msg`. /// `msg`.
/// ///
/// # Example /// # Example
@ -312,19 +312,19 @@ impl<T> Option<T> {
pub fn expect(self, msg: &str) -> T { pub fn expect(self, msg: &str) -> T {
match self { match self {
Some(val) => val, Some(val) => val,
None => fail!("{}", msg), None => panic!("{}", msg),
} }
} }
/// Returns the inner `T` of a `Some(T)`. /// Returns the inner `T` of a `Some(T)`.
/// ///
/// # Failure /// # Panics
/// ///
/// Fails if the self value equals `None`. /// Panics if the self value equals `None`.
/// ///
/// # Safety note /// # Safety note
/// ///
/// In general, because this function may fail, its use is discouraged. /// In general, because this function may panic, its use is discouraged.
/// Instead, prefer to use pattern matching and handle the `None` /// Instead, prefer to use pattern matching and handle the `None`
/// case explicitly. /// case explicitly.
/// ///
@ -344,7 +344,7 @@ impl<T> Option<T> {
pub fn unwrap(self) -> T { pub fn unwrap(self) -> T {
match self { match self {
Some(val) => val, Some(val) => val,
None => fail!("called `Option::unwrap()` on a `None` value"), None => panic!("called `Option::unwrap()` on a `None` value"),
} }
} }

View file

@ -8,23 +8,23 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // except according to those terms.
//! Failure support for libcore //! Panic support for libcore
//! //!
//! The core library cannot define failure, but it does *declare* failure. This //! The core library cannot define panicking, but it does *declare* panicking. This
//! means that the functions inside of libcore are allowed to fail, but to be //! means that the functions inside of libcore are allowed to panic, but to be
//! useful an upstream crate must define failure for libcore to use. The current //! useful an upstream crate must define panicking for libcore to use. The current
//! interface for failure is: //! interface for panicking is:
//! //!
//! ```ignore //! ```ignore
//! fn fail_impl(fmt: &fmt::Arguments, &(&'static str, uint)) -> !; //! fn panic_impl(fmt: &fmt::Arguments, &(&'static str, uint)) -> !;
//! ``` //! ```
//! //!
//! This definition allows for failing with any general message, but it does not //! This definition allows for panicking with any general message, but it does not
//! allow for failing with a `~Any` value. The reason for this is that libcore //! allow for failing with a `Box<Any>` value. The reason for this is that libcore
//! is not allowed to allocate. //! is not allowed to allocate.
//! //!
//! This module contains a few other failure functions, but these are just the //! This module contains a few other panicking functions, but these are just the
//! necessary lang items for the compiler. All failure is funneled through this //! necessary lang items for the compiler. All panics are funneled through this
//! one function. Currently, the actual symbol is declared in the standard //! one function. Currently, the actual symbol is declared in the standard
//! library, but the location of this may change over time. //! library, but the location of this may change over time.
@ -34,36 +34,36 @@ use fmt;
use intrinsics; use intrinsics;
#[cold] #[inline(never)] // this is the slow path, always #[cold] #[inline(never)] // this is the slow path, always
#[lang="fail"] #[lang="panic"]
pub fn fail(expr_file_line: &(&'static str, &'static str, uint)) -> ! { pub fn panic(expr_file_line: &(&'static str, &'static str, uint)) -> ! {
let (expr, file, line) = *expr_file_line; let (expr, file, line) = *expr_file_line;
let ref file_line = (file, line); let ref file_line = (file, line);
format_args!(|args| -> () { format_args!(|args| -> () {
fail_fmt(args, file_line); panic_fmt(args, file_line);
}, "{}", expr); }, "{}", expr);
unsafe { intrinsics::abort() } unsafe { intrinsics::abort() }
} }
#[cold] #[inline(never)] #[cold] #[inline(never)]
#[lang="fail_bounds_check"] #[lang="panic_bounds_check"]
fn fail_bounds_check(file_line: &(&'static str, uint), fn panic_bounds_check(file_line: &(&'static str, uint),
index: uint, len: uint) -> ! { index: uint, len: uint) -> ! {
format_args!(|args| -> () { format_args!(|args| -> () {
fail_fmt(args, file_line); panic_fmt(args, file_line);
}, "index out of bounds: the len is {} but the index is {}", len, index); }, "index out of bounds: the len is {} but the index is {}", len, index);
unsafe { intrinsics::abort() } unsafe { intrinsics::abort() }
} }
#[cold] #[inline(never)] #[cold] #[inline(never)]
pub fn fail_fmt(fmt: &fmt::Arguments, file_line: &(&'static str, uint)) -> ! { pub fn panic_fmt(fmt: &fmt::Arguments, file_line: &(&'static str, uint)) -> ! {
#[allow(ctypes)] #[allow(ctypes)]
extern { extern {
#[lang = "fail_fmt"] #[lang = "panic_fmt"]
fn fail_impl(fmt: &fmt::Arguments, file: &'static str, fn panic_impl(fmt: &fmt::Arguments, file: &'static str,
line: uint) -> !; line: uint) -> !;
} }
let (file, line) = *file_line; let (file, line) = *file_line;
unsafe { fail_impl(fmt, file, line) } unsafe { panic_impl(fmt, file, line) }
} }

View file

@ -76,7 +76,7 @@
//! unsafe { //! unsafe {
//! let my_num: *mut int = libc::malloc(mem::size_of::<int>() as libc::size_t) as *mut int; //! let my_num: *mut int = libc::malloc(mem::size_of::<int>() as libc::size_t) as *mut int;
//! if my_num.is_null() { //! if my_num.is_null() {
//! fail!("failed to allocate memory"); //! panic!("failed to allocate memory");
//! } //! }
//! libc::free(my_num as *mut libc::c_void); //! libc::free(my_num as *mut libc::c_void);
//! } //! }

View file

@ -123,8 +123,8 @@
//! warning (by default, controlled by the `unused_must_use` lint). //! warning (by default, controlled by the `unused_must_use` lint).
//! //!
//! You might instead, if you don't want to handle the error, simply //! You might instead, if you don't want to handle the error, simply
//! fail, by converting to an `Option` with `ok`, then asserting //! panic, by converting to an `Option` with `ok`, then asserting
//! success with `expect`. This will fail if the write fails, proving //! success with `expect`. This will panic if the write fails, proving
//! a marginally useful message indicating why: //! a marginally useful message indicating why:
//! //!
//! ```{.no_run} //! ```{.no_run}
@ -250,29 +250,29 @@
//! let mut t = Timer::new().ok().expect("failed to create timer!"); //! let mut t = Timer::new().ok().expect("failed to create timer!");
//! ``` //! ```
//! //!
//! # `Result` vs. `fail!` //! # `Result` vs. `panic!`
//! //!
//! `Result` is for recoverable errors; `fail!` is for unrecoverable //! `Result` is for recoverable errors; `panic!` is for unrecoverable
//! errors. Callers should always be able to avoid failure if they //! errors. Callers should always be able to avoid panics if they
//! take the proper precautions, for example, calling `is_some()` //! take the proper precautions, for example, calling `is_some()`
//! on an `Option` type before calling `unwrap`. //! on an `Option` type before calling `unwrap`.
//! //!
//! The suitability of `fail!` as an error handling mechanism is //! The suitability of `panic!` as an error handling mechanism is
//! limited by Rust's lack of any way to "catch" and resume execution //! limited by Rust's lack of any way to "catch" and resume execution
//! from a thrown exception. Therefore using failure for error //! from a thrown exception. Therefore using panics for error
//! handling requires encapsulating fallible code in a task. Calling //! handling requires encapsulating code that may panic in a task.
//! the `fail!` macro, or invoking `fail!` indirectly should be //! Calling the `panic!` macro, or invoking `panic!` indirectly should be
//! avoided as an error reporting strategy. Failure is only for //! avoided as an error reporting strategy. Panics is only for
//! unrecoverable errors and a failing task is typically the sign of //! unrecoverable errors and a panicking task is typically the sign of
//! a bug. //! a bug.
//! //!
//! A module that instead returns `Results` is alerting the caller //! A module that instead returns `Results` is alerting the caller
//! that failure is possible, and providing precise control over how //! that panics are possible, and providing precise control over how
//! it is handled. //! it is handled.
//! //!
//! Furthermore, failure may not be recoverable at all, depending on //! Furthermore, panics may not be recoverable at all, depending on
//! the context. The caller of `fail!` should assume that execution //! the context. The caller of `panic!` should assume that execution
//! will not resume after failure, that failure is catastrophic. //! will not resume after the panic, that a panic is catastrophic.
#![stable] #![stable]
@ -764,9 +764,9 @@ impl<T, E> Result<T, E> {
impl<T, E: Show> Result<T, E> { impl<T, E: Show> Result<T, E> {
/// Unwraps a result, yielding the content of an `Ok`. /// Unwraps a result, yielding the content of an `Ok`.
/// ///
/// # Failure /// # Panics
/// ///
/// Fails if the value is an `Err`, with a custom failure message provided /// Panics if the value is an `Err`, with a custom panic message provided
/// by the `Err`'s value. /// by the `Err`'s value.
/// ///
/// # Example /// # Example
@ -778,7 +778,7 @@ impl<T, E: Show> Result<T, E> {
/// ///
/// ```{.should_fail} /// ```{.should_fail}
/// let x: Result<uint, &str> = Err("emergency failure"); /// let x: Result<uint, &str> = Err("emergency failure");
/// x.unwrap(); // fails with `emergency failure` /// x.unwrap(); // panics with `emergency failure`
/// ``` /// ```
#[inline] #[inline]
#[unstable = "waiting for conventions"] #[unstable = "waiting for conventions"]
@ -786,7 +786,7 @@ impl<T, E: Show> Result<T, E> {
match self { match self {
Ok(t) => t, Ok(t) => t,
Err(e) => Err(e) =>
fail!("called `Result::unwrap()` on an `Err` value: {}", e) panic!("called `Result::unwrap()` on an `Err` value: {}", e)
} }
} }
} }
@ -794,16 +794,16 @@ impl<T, E: Show> Result<T, E> {
impl<T: Show, E> Result<T, E> { impl<T: Show, E> Result<T, E> {
/// Unwraps a result, yielding the content of an `Err`. /// Unwraps a result, yielding the content of an `Err`.
/// ///
/// # Failure /// # Panics
/// ///
/// Fails if the value is an `Ok`, with a custom failure message provided /// Panics if the value is an `Ok`, with a custom panic message provided
/// by the `Ok`'s value. /// by the `Ok`'s value.
/// ///
/// # Example /// # Example
/// ///
/// ```{.should_fail} /// ```{.should_fail}
/// let x: Result<uint, &str> = Ok(2u); /// let x: Result<uint, &str> = Ok(2u);
/// x.unwrap_err(); // fails with `2` /// x.unwrap_err(); // panics with `2`
/// ``` /// ```
/// ///
/// ``` /// ```
@ -815,7 +815,7 @@ impl<T: Show, E> Result<T, E> {
pub fn unwrap_err(self) -> E { pub fn unwrap_err(self) -> E {
match self { match self {
Ok(t) => Ok(t) =>
fail!("called `Result::unwrap_err()` on an `Ok` value: {}", t), panic!("called `Result::unwrap_err()` on an `Ok` value: {}", t),
Err(e) => e Err(e) => e
} }
} }

View file

@ -1460,7 +1460,7 @@ pub trait StrSlice for Sized? {
/// ///
/// assert_eq!(s.slice(1, 9), "öwe 老"); /// assert_eq!(s.slice(1, 9), "öwe 老");
/// ///
/// // these will fail: /// // these will panic:
/// // byte 2 lies within `ö`: /// // byte 2 lies within `ö`:
/// // s.slice(2, 3); /// // s.slice(2, 3);
/// ///
@ -1832,7 +1832,7 @@ pub trait StrSlice for Sized? {
#[inline(never)] #[inline(never)]
fn slice_error_fail(s: &str, begin: uint, end: uint) -> ! { fn slice_error_fail(s: &str, begin: uint, end: uint) -> ! {
assert!(begin <= end); assert!(begin <= end);
fail!("index {} and/or {} in `{}` do not lie on character boundary", panic!("index {} and/or {} in `{}` do not lie on character boundary",
begin, end, s); begin, end, s);
} }
@ -1986,8 +1986,8 @@ impl StrSlice for str {
if end_byte.is_none() && count == end { end_byte = Some(self.len()) } if end_byte.is_none() && count == end { end_byte = Some(self.len()) }
match (begin_byte, end_byte) { match (begin_byte, end_byte) {
(None, _) => fail!("slice_chars: `begin` is beyond end of string"), (None, _) => panic!("slice_chars: `begin` is beyond end of string"),
(_, None) => fail!("slice_chars: `end` is beyond end of string"), (_, None) => panic!("slice_chars: `end` is beyond end of string"),
(Some(a), Some(b)) => unsafe { raw::slice_bytes(self, a, b) } (Some(a), Some(b)) => unsafe { raw::slice_bytes(self, a, b) }
} }
} }

View file

@ -56,12 +56,12 @@ fn any_downcast_ref() {
match a.downcast_ref::<uint>() { match a.downcast_ref::<uint>() {
Some(&5) => {} Some(&5) => {}
x => fail!("Unexpected value {}", x) x => panic!("Unexpected value {}", x)
} }
match a.downcast_ref::<Test>() { match a.downcast_ref::<Test>() {
None => {} None => {}
x => fail!("Unexpected value {}", x) x => panic!("Unexpected value {}", x)
} }
} }
@ -79,7 +79,7 @@ fn any_downcast_mut() {
assert_eq!(*x, 5u); assert_eq!(*x, 5u);
*x = 612; *x = 612;
} }
x => fail!("Unexpected value {}", x) x => panic!("Unexpected value {}", x)
} }
match b_r.downcast_mut::<uint>() { match b_r.downcast_mut::<uint>() {
@ -87,27 +87,27 @@ fn any_downcast_mut() {
assert_eq!(*x, 7u); assert_eq!(*x, 7u);
*x = 413; *x = 413;
} }
x => fail!("Unexpected value {}", x) x => panic!("Unexpected value {}", x)
} }
match a_r.downcast_mut::<Test>() { match a_r.downcast_mut::<Test>() {
None => (), None => (),
x => fail!("Unexpected value {}", x) x => panic!("Unexpected value {}", x)
} }
match b_r.downcast_mut::<Test>() { match b_r.downcast_mut::<Test>() {
None => (), None => (),
x => fail!("Unexpected value {}", x) x => panic!("Unexpected value {}", x)
} }
match a_r.downcast_mut::<uint>() { match a_r.downcast_mut::<uint>() {
Some(&612) => {} Some(&612) => {}
x => fail!("Unexpected value {}", x) x => panic!("Unexpected value {}", x)
} }
match b_r.downcast_mut::<uint>() { match b_r.downcast_mut::<uint>() {
Some(&413) => {} Some(&413) => {}
x => fail!("Unexpected value {}", x) x => panic!("Unexpected value {}", x)
} }
} }

View file

@ -35,7 +35,7 @@ fn test_fail() {
&mut i, (), &mut i, (),
|i, ()| { |i, ()| {
*i = 10; *i = 10;
fail!(); panic!();
}, },
|i| { |i| {
assert!(failing()); assert!(failing());

View file

@ -373,7 +373,7 @@ fn test_all() {
assert!(v.iter().all(|&x| x < 10)); assert!(v.iter().all(|&x| x < 10));
assert!(!v.iter().all(|&x| x % 2 == 0)); assert!(!v.iter().all(|&x| x % 2 == 0));
assert!(!v.iter().all(|&x| x > 100)); assert!(!v.iter().all(|&x| x > 100));
assert!(v.slice_or_fail(&0, &0).iter().all(|_| fail!())); assert!(v.slice_or_fail(&0, &0).iter().all(|_| panic!()));
} }
#[test] #[test]
@ -382,7 +382,7 @@ fn test_any() {
assert!(v.iter().any(|&x| x < 10)); assert!(v.iter().any(|&x| x < 10));
assert!(v.iter().any(|&x| x % 2 == 0)); assert!(v.iter().any(|&x| x % 2 == 0));
assert!(!v.iter().any(|&x| x > 100)); assert!(!v.iter().any(|&x| x > 100));
assert!(!v.slice_or_fail(&0, &0).iter().any(|_| fail!())); assert!(!v.slice_or_fail(&0, &0).iter().any(|_| panic!()));
} }
#[test] #[test]
@ -528,13 +528,13 @@ fn test_rposition() {
#[test] #[test]
#[should_fail] #[should_fail]
fn test_rposition_fail() { fn test_rposition_panic() {
let v = [(box 0i, box 0i), (box 0i, box 0i), let v = [(box 0i, box 0i), (box 0i, box 0i),
(box 0i, box 0i), (box 0i, box 0i)]; (box 0i, box 0i), (box 0i, box 0i)];
let mut i = 0i; let mut i = 0i;
v.iter().rposition(|_elt| { v.iter().rposition(|_elt| {
if i == 2 { if i == 2 {
fail!() panic!()
} }
i += 1; i += 1;
false false
@ -678,12 +678,12 @@ fn test_random_access_cycle() {
fn test_double_ended_range() { fn test_double_ended_range() {
assert!(range(11i, 14).rev().collect::<Vec<int>>() == vec![13i, 12, 11]); assert!(range(11i, 14).rev().collect::<Vec<int>>() == vec![13i, 12, 11]);
for _ in range(10i, 0).rev() { for _ in range(10i, 0).rev() {
fail!("unreachable"); panic!("unreachable");
} }
assert!(range(11u, 14).rev().collect::<Vec<uint>>() == vec![13u, 12, 11]); assert!(range(11u, 14).rev().collect::<Vec<uint>>() == vec![13u, 12, 11]);
for _ in range(10u, 0).rev() { for _ in range(10u, 0).rev() {
fail!("unreachable"); panic!("unreachable");
} }
} }

View file

@ -139,14 +139,14 @@ fn test_unwrap() {
#[test] #[test]
#[should_fail] #[should_fail]
fn test_unwrap_fail1() { fn test_unwrap_panic1() {
let x: Option<int> = None; let x: Option<int> = None;
x.unwrap(); x.unwrap();
} }
#[test] #[test]
#[should_fail] #[should_fail]
fn test_unwrap_fail2() { fn test_unwrap_panic2() {
let x: Option<String> = None; let x: Option<String> = None;
x.unwrap(); x.unwrap();
} }
@ -233,7 +233,7 @@ fn test_collect() {
assert!(v == None); assert!(v == None);
// test that it does not take more elements than it needs // test that it does not take more elements than it needs
let mut functions = [|| Some(()), || None, || fail!()]; let mut functions = [|| Some(()), || None, || panic!()];
let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect(); let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect();

View file

@ -81,7 +81,7 @@ fn test_collect() {
assert!(v == Err(2)); assert!(v == Err(2));
// test that it does not take more elements than it needs // test that it does not take more elements than it needs
let mut functions = [|| Ok(()), || Err(1i), || fail!()]; let mut functions = [|| Ok(()), || Err(1i), || panic!()];
let v: Result<Vec<()>, int> = functions.iter_mut().map(|f| (*f)()).collect(); let v: Result<Vec<()>, int> = functions.iter_mut().map(|f| (*f)()).collect();
assert!(v == Err(1)); assert!(v == Err(1));
@ -113,7 +113,7 @@ pub fn test_unwrap_or_else() {
if msg == "I got this." { if msg == "I got this." {
50i 50i
} else { } else {
fail!("BadBad") panic!("BadBad")
} }
} }
@ -126,12 +126,12 @@ pub fn test_unwrap_or_else() {
#[test] #[test]
#[should_fail] #[should_fail]
pub fn test_unwrap_or_else_failure() { pub fn test_unwrap_or_else_panic() {
fn handler(msg: &'static str) -> int { fn handler(msg: &'static str) -> int {
if msg == "I got this." { if msg == "I got this." {
50i 50i
} else { } else {
fail!("BadBad") panic!("BadBad")
} }
} }

View file

@ -61,7 +61,7 @@
//! ]; //! ];
//! let matches = match getopts(args.tail(), opts) { //! let matches = match getopts(args.tail(), opts) {
//! Ok(m) => { m } //! Ok(m) => { m }
//! Err(f) => { fail!(f.to_string()) } //! Err(f) => { panic!(f.to_string()) }
//! }; //! };
//! if matches.opt_present("h") { //! if matches.opt_present("h") {
//! print_usage(program.as_slice(), opts); //! print_usage(program.as_slice(), opts);
@ -243,7 +243,7 @@ impl OptGroup {
} = (*self).clone(); } = (*self).clone();
match (short_name.len(), long_name.len()) { match (short_name.len(), long_name.len()) {
(0,0) => fail!("this long-format option was given no name"), (0,0) => panic!("this long-format option was given no name"),
(0,_) => Opt { (0,_) => Opt {
name: Long((long_name)), name: Long((long_name)),
hasarg: hasarg, hasarg: hasarg,
@ -269,7 +269,7 @@ impl OptGroup {
} }
) )
}, },
(_,_) => fail!("something is wrong with the long-form opt") (_,_) => panic!("something is wrong with the long-form opt")
} }
} }
} }
@ -278,7 +278,7 @@ impl Matches {
fn opt_vals(&self, nm: &str) -> Vec<Optval> { fn opt_vals(&self, nm: &str) -> Vec<Optval> {
match find_opt(self.opts.as_slice(), Name::from_str(nm)) { match find_opt(self.opts.as_slice(), Name::from_str(nm)) {
Some(id) => self.vals[id].clone(), Some(id) => self.vals[id].clone(),
None => fail!("No option '{}' defined", nm) None => panic!("No option '{}' defined", nm)
} }
} }
@ -530,8 +530,10 @@ impl fmt::Show for Fail_ {
/// Parse command line arguments according to the provided options. /// Parse command line arguments according to the provided options.
/// ///
/// On success returns `Ok(Matches)`. Use methods such as `opt_present` /// On success returns `Ok(Matches)`. Use methods such as `opt_present`
/// `opt_str`, etc. to interrogate results. Returns `Err(Fail_)` on /// `opt_str`, etc. to interrogate results.
/// failure: use the `Show` implementation of `Fail_` to display /// # Failure
///
/// Returns `Err(Fail_)` on failure: use the `Show` implementation of `Fail_` to display
/// information about it. /// information about it.
pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
let opts: Vec<Opt> = optgrps.iter().map(|x| x.long_to_short()).collect(); let opts: Vec<Opt> = optgrps.iter().map(|x| x.long_to_short()).collect();
@ -688,7 +690,7 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> String {
row.push_str(short_name.as_slice()); row.push_str(short_name.as_slice());
row.push(' '); row.push(' ');
} }
_ => fail!("the short name should only be 1 ascii char long"), _ => panic!("the short name should only be 1 ascii char long"),
} }
// long option // long option
@ -852,7 +854,7 @@ fn each_split_within<'a>(ss: &'a str, lim: uint, it: |&'a str| -> bool)
(B, Cr, UnderLim) => { B } (B, Cr, UnderLim) => { B }
(B, Cr, OverLim) if (i - last_start + 1) > lim (B, Cr, OverLim) if (i - last_start + 1) > lim
=> fail!("word starting with {} longer than limit!", => panic!("word starting with {} longer than limit!",
ss.slice(last_start, i + 1)), ss.slice(last_start, i + 1)),
(B, Cr, OverLim) => { (B, Cr, OverLim) => {
*cont = it(ss.slice(slice_start, last_end)); *cont = it(ss.slice(slice_start, last_end));
@ -951,7 +953,7 @@ mod tests {
assert!(m.opt_present("t")); assert!(m.opt_present("t"));
assert_eq!(m.opt_str("t").unwrap(), "20".to_string()); assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
} }
_ => { fail!("test_reqopt failed (long arg)"); } _ => { panic!("test_reqopt failed (long arg)"); }
} }
let short_args = vec!("-t".to_string(), "20".to_string()); let short_args = vec!("-t".to_string(), "20".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) { match getopts(short_args.as_slice(), opts.as_slice()) {
@ -961,7 +963,7 @@ mod tests {
assert!((m.opt_present("t"))); assert!((m.opt_present("t")));
assert_eq!(m.opt_str("t").unwrap(), "20".to_string()); assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
} }
_ => { fail!("test_reqopt failed (short arg)"); } _ => { panic!("test_reqopt failed (short arg)"); }
} }
} }
@ -972,7 +974,7 @@ mod tests {
let rs = getopts(args.as_slice(), opts.as_slice()); let rs = getopts(args.as_slice(), opts.as_slice());
match rs { match rs {
Err(f) => check_fail_type(f, OptionMissing_), Err(f) => check_fail_type(f, OptionMissing_),
_ => fail!() _ => panic!()
} }
} }
@ -983,12 +985,12 @@ mod tests {
let rs = getopts(long_args.as_slice(), opts.as_slice()); let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs { match rs {
Err(f) => check_fail_type(f, ArgumentMissing_), Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!() _ => panic!()
} }
let short_args = vec!("-t".to_string()); let short_args = vec!("-t".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) { match getopts(short_args.as_slice(), opts.as_slice()) {
Err(f) => check_fail_type(f, ArgumentMissing_), Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!() _ => panic!()
} }
} }
@ -999,7 +1001,7 @@ mod tests {
let rs = getopts(args.as_slice(), opts.as_slice()); let rs = getopts(args.as_slice(), opts.as_slice());
match rs { match rs {
Err(f) => check_fail_type(f, OptionDuplicated_), Err(f) => check_fail_type(f, OptionDuplicated_),
_ => fail!() _ => panic!()
} }
} }
@ -1016,7 +1018,7 @@ mod tests {
assert!((m.opt_present("t"))); assert!((m.opt_present("t")));
assert_eq!(m.opt_str("t").unwrap(), "20".to_string()); assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
} }
_ => fail!() _ => panic!()
} }
let short_args = vec!("-t".to_string(), "20".to_string()); let short_args = vec!("-t".to_string(), "20".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) { match getopts(short_args.as_slice(), opts.as_slice()) {
@ -1026,7 +1028,7 @@ mod tests {
assert!((m.opt_present("t"))); assert!((m.opt_present("t")));
assert_eq!(m.opt_str("t").unwrap(), "20".to_string()); assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
} }
_ => fail!() _ => panic!()
} }
} }
@ -1040,7 +1042,7 @@ mod tests {
assert!(!m.opt_present("test")); assert!(!m.opt_present("test"));
assert!(!m.opt_present("t")); assert!(!m.opt_present("t"));
} }
_ => fail!() _ => panic!()
} }
} }
@ -1051,12 +1053,12 @@ mod tests {
let rs = getopts(long_args.as_slice(), opts.as_slice()); let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs { match rs {
Err(f) => check_fail_type(f, ArgumentMissing_), Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!() _ => panic!()
} }
let short_args = vec!("-t".to_string()); let short_args = vec!("-t".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) { match getopts(short_args.as_slice(), opts.as_slice()) {
Err(f) => check_fail_type(f, ArgumentMissing_), Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!() _ => panic!()
} }
} }
@ -1067,7 +1069,7 @@ mod tests {
let rs = getopts(args.as_slice(), opts.as_slice()); let rs = getopts(args.as_slice(), opts.as_slice());
match rs { match rs {
Err(f) => check_fail_type(f, OptionDuplicated_), Err(f) => check_fail_type(f, OptionDuplicated_),
_ => fail!() _ => panic!()
} }
} }
@ -1082,7 +1084,7 @@ mod tests {
assert!(m.opt_present("test")); assert!(m.opt_present("test"));
assert!(m.opt_present("t")); assert!(m.opt_present("t"));
} }
_ => fail!() _ => panic!()
} }
let short_args = vec!("-t".to_string()); let short_args = vec!("-t".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) { match getopts(short_args.as_slice(), opts.as_slice()) {
@ -1090,7 +1092,7 @@ mod tests {
assert!(m.opt_present("test")); assert!(m.opt_present("test"));
assert!(m.opt_present("t")); assert!(m.opt_present("t"));
} }
_ => fail!() _ => panic!()
} }
} }
@ -1104,7 +1106,7 @@ mod tests {
assert!(!m.opt_present("test")); assert!(!m.opt_present("test"));
assert!(!m.opt_present("t")); assert!(!m.opt_present("t"));
} }
_ => fail!() _ => panic!()
} }
} }
@ -1117,7 +1119,7 @@ mod tests {
Err(f) => { Err(f) => {
check_fail_type(f, UnexpectedArgument_); check_fail_type(f, UnexpectedArgument_);
} }
_ => fail!() _ => panic!()
} }
} }
@ -1128,7 +1130,7 @@ mod tests {
let rs = getopts(args.as_slice(), opts.as_slice()); let rs = getopts(args.as_slice(), opts.as_slice());
match rs { match rs {
Err(f) => check_fail_type(f, OptionDuplicated_), Err(f) => check_fail_type(f, OptionDuplicated_),
_ => fail!() _ => panic!()
} }
} }
@ -1143,7 +1145,7 @@ mod tests {
assert!(m.free[0] == "20".to_string()); assert!(m.free[0] == "20".to_string());
} }
_ => fail!() _ => panic!()
} }
} }
@ -1157,7 +1159,7 @@ mod tests {
Ok(ref m) => { Ok(ref m) => {
assert_eq!(m.opt_count("v"), 1); assert_eq!(m.opt_count("v"), 1);
} }
_ => fail!() _ => panic!()
} }
} }
@ -1170,7 +1172,7 @@ mod tests {
Ok(ref m) => { Ok(ref m) => {
assert_eq!(m.opt_count("v"), 2); assert_eq!(m.opt_count("v"), 2);
} }
_ => fail!() _ => panic!()
} }
} }
@ -1183,7 +1185,7 @@ mod tests {
Ok(ref m) => { Ok(ref m) => {
assert_eq!(m.opt_count("v"), 2); assert_eq!(m.opt_count("v"), 2);
} }
_ => fail!() _ => panic!()
} }
} }
@ -1196,7 +1198,7 @@ mod tests {
Ok(ref m) => { Ok(ref m) => {
assert_eq!(m.opt_count("verbose"), 1); assert_eq!(m.opt_count("verbose"), 1);
} }
_ => fail!() _ => panic!()
} }
} }
@ -1209,7 +1211,7 @@ mod tests {
Ok(ref m) => { Ok(ref m) => {
assert_eq!(m.opt_count("verbose"), 2); assert_eq!(m.opt_count("verbose"), 2);
} }
_ => fail!() _ => panic!()
} }
} }
@ -1224,7 +1226,7 @@ mod tests {
assert_eq!(m.opt_count("verbose"), 4); assert_eq!(m.opt_count("verbose"), 4);
assert_eq!(m.opt_count("v"), 4); assert_eq!(m.opt_count("v"), 4);
} }
_ => fail!() _ => panic!()
} }
} }
@ -1241,7 +1243,7 @@ mod tests {
assert!((m.opt_present("t"))); assert!((m.opt_present("t")));
assert_eq!(m.opt_str("t").unwrap(), "20".to_string()); assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
} }
_ => fail!() _ => panic!()
} }
let short_args = vec!("-t".to_string(), "20".to_string()); let short_args = vec!("-t".to_string(), "20".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) { match getopts(short_args.as_slice(), opts.as_slice()) {
@ -1251,7 +1253,7 @@ mod tests {
assert!((m.opt_present("t"))); assert!((m.opt_present("t")));
assert_eq!(m.opt_str("t").unwrap(), "20".to_string()); assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
} }
_ => fail!() _ => panic!()
} }
} }
@ -1265,7 +1267,7 @@ mod tests {
assert!(!m.opt_present("test")); assert!(!m.opt_present("test"));
assert!(!m.opt_present("t")); assert!(!m.opt_present("t"));
} }
_ => fail!() _ => panic!()
} }
} }
@ -1276,12 +1278,12 @@ mod tests {
let rs = getopts(long_args.as_slice(), opts.as_slice()); let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs { match rs {
Err(f) => check_fail_type(f, ArgumentMissing_), Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!() _ => panic!()
} }
let short_args = vec!("-t".to_string()); let short_args = vec!("-t".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) { match getopts(short_args.as_slice(), opts.as_slice()) {
Err(f) => check_fail_type(f, ArgumentMissing_), Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!() _ => panic!()
} }
} }
@ -1300,7 +1302,7 @@ mod tests {
assert!(pair[0] == "20".to_string()); assert!(pair[0] == "20".to_string());
assert!(pair[1] == "30".to_string()); assert!(pair[1] == "30".to_string());
} }
_ => fail!() _ => panic!()
} }
} }
@ -1311,12 +1313,12 @@ mod tests {
let rs = getopts(long_args.as_slice(), opts.as_slice()); let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs { match rs {
Err(f) => check_fail_type(f, UnrecognizedOption_), Err(f) => check_fail_type(f, UnrecognizedOption_),
_ => fail!() _ => panic!()
} }
let short_args = vec!("-u".to_string()); let short_args = vec!("-u".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) { match getopts(short_args.as_slice(), opts.as_slice()) {
Err(f) => check_fail_type(f, UnrecognizedOption_), Err(f) => check_fail_type(f, UnrecognizedOption_),
_ => fail!() _ => panic!()
} }
} }
@ -1365,7 +1367,7 @@ mod tests {
assert!(pair[1] == "-60 70".to_string()); assert!(pair[1] == "-60 70".to_string());
assert!((!m.opt_present("notpresent"))); assert!((!m.opt_present("notpresent")));
} }
_ => fail!() _ => panic!()
} }
} }
@ -1379,7 +1381,7 @@ mod tests {
let matches_single = &match getopts(args_single.as_slice(), let matches_single = &match getopts(args_single.as_slice(),
opts.as_slice()) { opts.as_slice()) {
result::Ok(m) => m, result::Ok(m) => m,
result::Err(_) => fail!() result::Err(_) => panic!()
}; };
assert!(matches_single.opts_present(["e".to_string()])); assert!(matches_single.opts_present(["e".to_string()]));
assert!(matches_single.opts_present(["encrypt".to_string(), "e".to_string()])); assert!(matches_single.opts_present(["encrypt".to_string(), "e".to_string()]));
@ -1399,7 +1401,7 @@ mod tests {
let matches_both = &match getopts(args_both.as_slice(), let matches_both = &match getopts(args_both.as_slice(),
opts.as_slice()) { opts.as_slice()) {
result::Ok(m) => m, result::Ok(m) => m,
result::Err(_) => fail!() result::Err(_) => panic!()
}; };
assert!(matches_both.opts_present(["e".to_string()])); assert!(matches_both.opts_present(["e".to_string()]));
assert!(matches_both.opts_present(["encrypt".to_string()])); assert!(matches_both.opts_present(["encrypt".to_string()]));
@ -1424,7 +1426,7 @@ mod tests {
optmulti("M", "", "something", "MMMM")); optmulti("M", "", "something", "MMMM"));
let matches = &match getopts(args.as_slice(), opts.as_slice()) { let matches = &match getopts(args.as_slice(), opts.as_slice()) {
result::Ok(m) => m, result::Ok(m) => m,
result::Err(_) => fail!() result::Err(_) => panic!()
}; };
assert!(matches.opts_present(["L".to_string()])); assert!(matches.opts_present(["L".to_string()]));
assert_eq!(matches.opts_str(["L".to_string()]).unwrap(), "foo".to_string()); assert_eq!(matches.opts_str(["L".to_string()]).unwrap(), "foo".to_string());
@ -1440,7 +1442,7 @@ mod tests {
optflagmulti("v", "verbose", "Verbose")); optflagmulti("v", "verbose", "Verbose"));
let matches = &match getopts(args.as_slice(), opts.as_slice()) { let matches = &match getopts(args.as_slice(), opts.as_slice()) {
result::Ok(m) => m, result::Ok(m) => m,
result::Err(e) => fail!( "{}", e ) result::Err(e) => panic!( "{}", e )
}; };
assert!(matches.opts_present(["L".to_string()])); assert!(matches.opts_present(["L".to_string()]));
assert_eq!(matches.opts_str(["L".to_string()]).unwrap(), "verbose".to_string()); assert_eq!(matches.opts_str(["L".to_string()]).unwrap(), "verbose".to_string());

View file

@ -73,13 +73,13 @@ impl BasicLoop {
RunRemote(i) => { RunRemote(i) => {
match self.remotes.iter_mut().find(|& &(id, _)| id == i) { match self.remotes.iter_mut().find(|& &(id, _)| id == i) {
Some(&(_, ref mut f)) => f.call(), Some(&(_, ref mut f)) => f.call(),
None => fail!("bad remote: {}", i), None => panic!("bad remote: {}", i),
} }
} }
RemoveRemote(i) => { RemoveRemote(i) => {
match self.remotes.iter().position(|&(id, _)| id == i) { match self.remotes.iter().position(|&(id, _)| id == i) {
Some(i) => { self.remotes.remove(i).unwrap(); } Some(i) => { self.remotes.remove(i).unwrap(); }
None => fail!("bad remote: {}", i), None => panic!("bad remote: {}", i),
} }
} }
} }

View file

@ -102,14 +102,14 @@ impl Context {
// Right before we switch to the new context, set the new context's // Right before we switch to the new context, set the new context's
// stack limit in the OS-specified TLS slot. This also means that // stack limit in the OS-specified TLS slot. This also means that
// we cannot call any more rust functions after record_stack_bounds // we cannot call any more rust functions after record_stack_bounds
// returns because they would all likely fail due to the limit being // returns because they would all likely panic due to the limit being
// invalid for the current task. Lucky for us `rust_swap_registers` // invalid for the current task. Lucky for us `rust_swap_registers`
// is a C function so we don't have to worry about that! // is a C function so we don't have to worry about that!
match in_context.stack_bounds { match in_context.stack_bounds {
Some((lo, hi)) => stack::record_rust_managed_stack_bounds(lo, hi), Some((lo, hi)) => stack::record_rust_managed_stack_bounds(lo, hi),
// If we're going back to one of the original contexts or // If we're going back to one of the original contexts or
// something that's possibly not a "normal task", then reset // something that's possibly not a "normal task", then reset
// the stack limit to 0 to make morestack never fail // the stack limit to 0 to make morestack never panic
None => stack::record_rust_managed_stack_bounds(0, uint::MAX), None => stack::record_rust_managed_stack_bounds(0, uint::MAX),
} }
rust_swap_registers(out_regs, in_regs); rust_swap_registers(out_regs, in_regs);

View file

@ -168,7 +168,7 @@
//! drop(handle); //! drop(handle);
//! //!
//! // Required to shut down this scheduler pool. //! // Required to shut down this scheduler pool.
//! // The task will fail if `shutdown` is not called. //! // The task will panic if `shutdown` is not called.
//! pool.shutdown(); //! pool.shutdown();
//! # } //! # }
//! ``` //! ```
@ -511,7 +511,7 @@ impl TaskState {
impl Drop for SchedPool { impl Drop for SchedPool {
fn drop(&mut self) { fn drop(&mut self) {
if self.threads.len() > 0 { if self.threads.len() > 0 {
fail!("dropping a M:N scheduler pool that wasn't shut down"); panic!("dropping a M:N scheduler pool that wasn't shut down");
} }
} }
} }

View file

@ -761,7 +761,7 @@ impl Scheduler {
// task-local lock around this block. The resumption of the task in // task-local lock around this block. The resumption of the task in
// context switching will bounce on the lock, thereby waiting for this // context switching will bounce on the lock, thereby waiting for this
// block to finish, eliminating the race mentioned above. // block to finish, eliminating the race mentioned above.
// fail!("should never return!"); // panic!("should never return!");
// //
// To actually maintain a handle to the lock, we use an unsafe pointer // To actually maintain a handle to the lock, we use an unsafe pointer
// to it, but we're guaranteed that the task won't exit until we've // to it, but we're guaranteed that the task won't exit until we've
@ -806,7 +806,7 @@ impl Scheduler {
coroutine.recycle(&mut sched.stack_pool); coroutine.recycle(&mut sched.stack_pool);
sched.task_state.decrement(); sched.task_state.decrement();
}); });
fail!("should never return!"); panic!("should never return!");
} }
pub fn run_task(self: Box<Scheduler>, pub fn run_task(self: Box<Scheduler>,
@ -1054,7 +1054,7 @@ mod test {
task.put_runtime(green); task.put_runtime(green);
return ret; return ret;
} }
None => fail!() None => panic!()
} }
} }
@ -1202,8 +1202,8 @@ mod test {
}))) => { }))) => {
*id == sched_id *id == sched_id
} }
TypeGreen(None) => { fail!("task without home"); } TypeGreen(None) => { panic!("task without home"); }
TypeSched => { fail!("expected green task"); } TypeSched => { panic!("expected green task"); }
}; };
task.put(); task.put();
ret ret

View file

@ -67,23 +67,23 @@ impl Runtime for SimpleTask {
} }
} }
// These functions are all unimplemented and fail as a result. This is on // These functions are all unimplemented and panic as a result. This is on
// purpose. A "simple task" is just that, a very simple task that can't // purpose. A "simple task" is just that, a very simple task that can't
// really do a whole lot. The only purpose of the task is to get us off our // really do a whole lot. The only purpose of the task is to get us off our
// feet and running. // feet and running.
fn yield_now(self: Box<SimpleTask>, _cur_task: Box<Task>) { fail!() } fn yield_now(self: Box<SimpleTask>, _cur_task: Box<Task>) { panic!() }
fn maybe_yield(self: Box<SimpleTask>, _cur_task: Box<Task>) { fail!() } fn maybe_yield(self: Box<SimpleTask>, _cur_task: Box<Task>) { panic!() }
fn spawn_sibling(self: Box<SimpleTask>, fn spawn_sibling(self: Box<SimpleTask>,
_cur_task: Box<Task>, _cur_task: Box<Task>,
_opts: TaskOpts, _opts: TaskOpts,
_f: proc():Send) { _f: proc():Send) {
fail!() panic!()
} }
fn local_io<'a>(&'a mut self) -> Option<rtio::LocalIo<'a>> { None } fn local_io<'a>(&'a mut self) -> Option<rtio::LocalIo<'a>> { None }
fn stack_bounds(&self) -> (uint, uint) { fail!() } fn stack_bounds(&self) -> (uint, uint) { panic!() }
fn stack_guard(&self) -> Option<uint> { fail!() } fn stack_guard(&self) -> Option<uint> { panic!() }
fn can_block(&self) -> bool { true } fn can_block(&self) -> bool { true }
fn wrap(self: Box<SimpleTask>) -> Box<Any+'static> { fail!() } fn wrap(self: Box<SimpleTask>) -> Box<Any+'static> { panic!() }
} }
pub fn task() -> Box<Task> { pub fn task() -> Box<Task> {

View file

@ -24,7 +24,7 @@ pub struct Stack {
// Try to use MAP_STACK on platforms that support it (it's what we're doing // Try to use MAP_STACK on platforms that support it (it's what we're doing
// anyway), but some platforms don't support it at all. For example, it appears // anyway), but some platforms don't support it at all. For example, it appears
// that there's a bug in freebsd that MAP_STACK implies MAP_FIXED (so it always // that there's a bug in freebsd that MAP_STACK implies MAP_FIXED (so it always
// fails): http://lists.freebsd.org/pipermail/freebsd-bugs/2011-July/044840.html // panics): http://lists.freebsd.org/pipermail/freebsd-bugs/2011-July/044840.html
// //
// DragonFly BSD also seems to suffer from the same problem. When MAP_STACK is // DragonFly BSD also seems to suffer from the same problem. When MAP_STACK is
// used, it returns the same `ptr` multiple times. // used, it returns the same `ptr` multiple times.
@ -37,7 +37,7 @@ static STACK_FLAGS: libc::c_int = libc::MAP_PRIVATE | libc::MAP_ANON;
static STACK_FLAGS: libc::c_int = 0; static STACK_FLAGS: libc::c_int = 0;
impl Stack { impl Stack {
/// Allocate a new stack of `size`. If size = 0, this will fail. Use /// Allocate a new stack of `size`. If size = 0, this will panic. Use
/// `dummy_stack` if you want a zero-sized stack. /// `dummy_stack` if you want a zero-sized stack.
pub fn new(size: uint) -> Stack { pub fn new(size: uint) -> Stack {
// Map in a stack. Eventually we might be able to handle stack // Map in a stack. Eventually we might be able to handle stack
@ -47,7 +47,7 @@ impl Stack {
let stack = match MemoryMap::new(size, [MapReadable, MapWritable, let stack = match MemoryMap::new(size, [MapReadable, MapWritable,
MapNonStandardFlags(STACK_FLAGS)]) { MapNonStandardFlags(STACK_FLAGS)]) {
Ok(map) => map, Ok(map) => map,
Err(e) => fail!("mmap for stack of size {} failed: {}", size, e) Err(e) => panic!("mmap for stack of size {} failed: {}", size, e)
}; };
// Change the last page to be inaccessible. This is to provide safety; // Change the last page to be inaccessible. This is to provide safety;
@ -55,7 +55,7 @@ impl Stack {
// page. It isn't guaranteed, but that's why FFI is unsafe. buf.data is // page. It isn't guaranteed, but that's why FFI is unsafe. buf.data is
// guaranteed to be aligned properly. // guaranteed to be aligned properly.
if !protect_last_page(&stack) { if !protect_last_page(&stack) {
fail!("Could not memory-protect guard page. stack={}, errno={}", panic!("Could not memory-protect guard page. stack={}, errno={}",
stack.data(), errno()); stack.data(), errno());
} }

View file

@ -443,7 +443,7 @@ impl Runtime for GreenTask {
self.put_task(cur_task); self.put_task(cur_task);
// First, set up a bomb which when it goes off will restore the local // First, set up a bomb which when it goes off will restore the local
// task unless its disarmed. This will allow us to gracefully fail from // task unless its disarmed. This will allow us to gracefully panic from
// inside of `configure` which allocates a new task. // inside of `configure` which allocates a new task.
struct Bomb { inner: Option<Box<GreenTask>> } struct Bomb { inner: Option<Box<GreenTask>> }
impl Drop for Bomb { impl Drop for Bomb {
@ -529,11 +529,11 @@ mod tests {
} }
#[test] #[test]
fn smoke_fail() { fn smoke_panic() {
let (tx, rx) = channel::<int>(); let (tx, rx) = channel::<int>();
spawn_opts(TaskOpts::new(), proc() { spawn_opts(TaskOpts::new(), proc() {
let _tx = tx; let _tx = tx;
fail!() panic!()
}); });
assert_eq!(rx.recv_opt(), Err(())); assert_eq!(rx.recv_opt(), Err(()));
} }
@ -550,11 +550,11 @@ mod tests {
} }
#[test] #[test]
fn smoke_opts_fail() { fn smoke_opts_panic() {
let mut opts = TaskOpts::new(); let mut opts = TaskOpts::new();
let (tx, rx) = channel(); let (tx, rx) = channel();
opts.on_exit = Some(proc(r) tx.send(r)); opts.on_exit = Some(proc(r) tx.send(r));
spawn_opts(opts, proc() { fail!() }); spawn_opts(opts, proc() { panic!() });
assert!(rx.recv().is_err()); assert!(rx.recv().is_err());
} }
@ -597,7 +597,7 @@ mod tests {
Some(ops) => { Some(ops) => {
task.put_runtime(ops); task.put_runtime(ops);
} }
None => fail!(), None => panic!(),
} }
Local::put(task); Local::put(task);
tx.send(()); tx.send(());

View file

@ -255,7 +255,7 @@ impl Logger for DefaultLogger {
record.level, record.level,
record.module_path, record.module_path,
record.args) { record.args) {
Err(e) => fail!("failed to log: {}", e), Err(e) => panic!("failed to log: {}", e),
Ok(()) => {} Ok(()) => {}
} }
} }
@ -263,9 +263,9 @@ impl Logger for DefaultLogger {
impl Drop for DefaultLogger { impl Drop for DefaultLogger {
fn drop(&mut self) { fn drop(&mut self) {
// FIXME(#12628): is failure the right thing to do? // FIXME(#12628): is panicking the right thing to do?
match self.handle.flush() { match self.handle.flush() {
Err(e) => fail!("failed to flush a logger: {}", e), Err(e) => panic!("failed to flush a logger: {}", e),
Ok(()) => {} Ok(()) => {}
} }
} }

View file

@ -523,7 +523,7 @@ mod tests {
assert_eq!(buf[2], 's' as u8); assert_eq!(buf[2], 's' as u8);
assert_eq!(buf[3], 't' as u8); assert_eq!(buf[3], 't' as u8);
} }
r => fail!("invalid read: {}", r) r => panic!("invalid read: {}", r),
} }
assert!(writer.inner_read(buf).is_err()); assert!(writer.inner_read(buf).is_err());
@ -547,7 +547,7 @@ mod tests {
assert_eq!(buf[2], 's' as u8); assert_eq!(buf[2], 's' as u8);
assert_eq!(buf[3], 't' as u8); assert_eq!(buf[3], 't' as u8);
} }
r => fail!("invalid read: {}", r) r => panic!("invalid read: {}", r)
} }
} }
} }

View file

@ -710,7 +710,7 @@ impl UnixAcceptor {
if new_handle == libc::INVALID_HANDLE_VALUE { if new_handle == libc::INVALID_HANDLE_VALUE {
let ret = Err(super::last_error()); let ret = Err(super::last_error());
// If our disconnection fails, then there's not really a whole lot // If our disconnection fails, then there's not really a whole lot
// that we can do, so fail the task. // that we can do, so panic
let err = unsafe { libc::DisconnectNamedPipe(handle) }; let err = unsafe { libc::DisconnectNamedPipe(handle) };
assert!(err != 0); assert!(err != 0);
return ret; return ret;

View file

@ -600,7 +600,7 @@ fn spawn_process_os(cfg: ProcessConfig,
handle: ptr::null_mut() handle: ptr::null_mut()
}) })
} }
Ok(..) => fail!("short read on the cloexec pipe"), Ok(..) => panic!("short read on the cloexec pipe"),
}; };
} }
// And at this point we've reached a special time in the life of the // And at this point we've reached a special time in the life of the
@ -944,7 +944,7 @@ fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> {
let mut status = 0 as c_int; let mut status = 0 as c_int;
if deadline == 0 { if deadline == 0 {
return match retry(|| unsafe { c::waitpid(pid, &mut status, 0) }) { return match retry(|| unsafe { c::waitpid(pid, &mut status, 0) }) {
-1 => fail!("unknown waitpid error: {}", super::last_error().code), -1 => panic!("unknown waitpid error: {}", super::last_error().code),
_ => Ok(translate_status(status)), _ => Ok(translate_status(status)),
} }
} }
@ -1069,7 +1069,7 @@ fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> {
continue continue
} }
n => fail!("error in select {} ({})", os::errno(), n), n => panic!("error in select {} ({})", os::errno(), n),
} }
// Process any pending messages // Process any pending messages
@ -1149,7 +1149,7 @@ fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> {
n if n > 0 => { ret = true; } n if n > 0 => { ret = true; }
0 => return true, 0 => return true,
-1 if util::wouldblock() => return ret, -1 if util::wouldblock() => return ret,
n => fail!("bad read {} ({})", os::last_os_error(), n), n => panic!("bad read {} ({})", os::last_os_error(), n),
} }
} }
} }
@ -1172,7 +1172,7 @@ fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> {
} { } {
1 => {} 1 => {}
-1 if util::wouldblock() => {} // see above comments -1 if util::wouldblock() => {} // see above comments
n => fail!("bad error on write fd: {} {}", n, os::errno()), n => panic!("bad error on write fd: {} {}", n, os::errno()),
} }
} }
} }
@ -1192,7 +1192,7 @@ fn waitpid_nowait(pid: pid_t) -> Option<rtio::ProcessExit> {
}) { }) {
n if n == pid => Some(translate_status(status)), n if n == pid => Some(translate_status(status)),
0 => None, 0 => None,
n => fail!("unknown waitpid error `{}`: {}", n, n => panic!("unknown waitpid error `{}`: {}", n,
super::last_error().code), super::last_error().code),
} }
} }

View file

@ -194,7 +194,7 @@ fn helper(input: libc::c_int, messages: Receiver<Req>, _: ()) {
} }
-1 if os::errno() == libc::EINTR as int => {} -1 if os::errno() == libc::EINTR as int => {}
n => fail!("helper thread failed in select() with error: {} ({})", n => panic!("helper thread panicked in select() with error: {} ({})",
n, os::last_os_error()) n, os::last_os_error())
} }
} }
@ -227,7 +227,7 @@ impl Timer {
}; };
while unsafe { libc::nanosleep(&to_sleep, &mut to_sleep) } != 0 { while unsafe { libc::nanosleep(&to_sleep, &mut to_sleep) } != 0 {
if os::errno() as int != libc::EINTR as int { if os::errno() as int != libc::EINTR as int {
fail!("failed to sleep, but not because of EINTR?"); panic!("failed to sleep, but not because of EINTR?");
} }
} }
} }

View file

@ -142,7 +142,7 @@ pub fn start(argc: int, argv: *const *const u8, main: proc()) -> int {
exit_code = Some(run(main.take().unwrap())); exit_code = Some(run(main.take().unwrap()));
}).destroy()); }).destroy());
unsafe { rt::cleanup(); } unsafe { rt::cleanup(); }
// If the exit code wasn't set, then the task block must have failed. // If the exit code wasn't set, then the task block must have panicked.
return exit_code.unwrap_or(rt::DEFAULT_ERROR_CODE); return exit_code.unwrap_or(rt::DEFAULT_ERROR_CODE);
} }

View file

@ -297,11 +297,11 @@ mod tests {
} }
#[test] #[test]
fn smoke_fail() { fn smoke_panic() {
let (tx, rx) = channel::<()>(); let (tx, rx) = channel::<()>();
spawn(proc() { spawn(proc() {
let _tx = tx; let _tx = tx;
fail!() panic!()
}); });
assert_eq!(rx.recv_opt(), Err(())); assert_eq!(rx.recv_opt(), Err(()));
} }
@ -318,11 +318,11 @@ mod tests {
} }
#[test] #[test]
fn smoke_opts_fail() { fn smoke_opts_panic() {
let mut opts = TaskOpts::new(); let mut opts = TaskOpts::new();
let (tx, rx) = channel(); let (tx, rx) = channel();
opts.on_exit = Some(proc(r) tx.send(r)); opts.on_exit = Some(proc(r) tx.send(r));
NativeSpawner.spawn(opts, proc() { fail!() }); NativeSpawner.spawn(opts, proc() { panic!() });
assert!(rx.recv().is_err()); assert!(rx.recv().is_err());
} }
@ -365,7 +365,7 @@ mod tests {
Some(ops) => { Some(ops) => {
task.put_runtime(ops); task.put_runtime(ops);
} }
None => fail!(), None => panic!(),
} }
Local::put(task); Local::put(task);
tx.send(()); tx.send(());

View file

@ -129,7 +129,7 @@ impl<'a, T: Clone> WeightedChoice<'a, T> {
for item in items.iter_mut() { for item in items.iter_mut() {
running_total = match running_total.checked_add(&item.weight) { running_total = match running_total.checked_add(&item.weight) {
Some(n) => n, Some(n) => n,
None => fail!("WeightedChoice::new called with a total weight \ None => panic!("WeightedChoice::new called with a total weight \
larger than a uint can contain") larger than a uint can contain")
}; };

View file

@ -92,7 +92,7 @@ pub trait Rng {
/// not be relied upon. /// not be relied upon.
/// ///
/// This method should guarantee that `dest` is entirely filled /// This method should guarantee that `dest` is entirely filled
/// with new data, and may fail if this is impossible /// with new data, and may panic if this is impossible
/// (e.g. reading past the end of a file that is being used as the /// (e.g. reading past the end of a file that is being used as the
/// source of randomness). /// source of randomness).
/// ///
@ -375,7 +375,7 @@ impl Rng for XorShiftRng {
} }
impl SeedableRng<[u32, .. 4]> for XorShiftRng { impl SeedableRng<[u32, .. 4]> for XorShiftRng {
/// Reseed an XorShiftRng. This will fail if `seed` is entirely 0. /// Reseed an XorShiftRng. This will panic if `seed` is entirely 0.
fn reseed(&mut self, seed: [u32, .. 4]) { fn reseed(&mut self, seed: [u32, .. 4]) {
assert!(!seed.iter().all(|&x| x == 0), assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng.reseed called with an all zero seed."); "XorShiftRng.reseed called with an all zero seed.");
@ -386,7 +386,7 @@ impl SeedableRng<[u32, .. 4]> for XorShiftRng {
self.w = seed[3]; self.w = seed[3];
} }
/// Create a new XorShiftRng. This will fail if `seed` is entirely 0. /// Create a new XorShiftRng. This will panic if `seed` is entirely 0.
fn from_seed(seed: [u32, .. 4]) -> XorShiftRng { fn from_seed(seed: [u32, .. 4]) -> XorShiftRng {
assert!(!seed.iter().all(|&x| x == 0), assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng::from_seed called with an all zero seed."); "XorShiftRng::from_seed called with an all zero seed.");
@ -446,7 +446,7 @@ pub struct Closed01<F>(pub F);
#[cfg(not(test))] #[cfg(not(test))]
mod std { mod std {
pub use core::{option, fmt}; // fail!() pub use core::{option, fmt}; // panic!()
} }
#[cfg(test)] #[cfg(test)]

View file

@ -244,7 +244,7 @@ pub mod reader {
Some(d) => d, Some(d) => d,
None => { None => {
error!("failed to find block with tag {}", tg); error!("failed to find block with tag {}", tg);
fail!(); panic!();
} }
} }
} }

View file

@ -240,13 +240,13 @@ impl<'r> Compiler<'r> {
/// Sets the left and right locations of a `Split` instruction at index /// Sets the left and right locations of a `Split` instruction at index
/// `i` to `pc1` and `pc2`, respectively. /// `i` to `pc1` and `pc2`, respectively.
/// If the instruction at index `i` isn't a `Split` instruction, then /// If the instruction at index `i` isn't a `Split` instruction, then
/// `fail!` is called. /// `panic!` is called.
#[inline] #[inline]
fn set_split(&mut self, i: InstIdx, pc1: InstIdx, pc2: InstIdx) { fn set_split(&mut self, i: InstIdx, pc1: InstIdx, pc2: InstIdx) {
let split = self.insts.get_mut(i); let split = self.insts.get_mut(i);
match *split { match *split {
Split(_, _) => *split = Split(pc1, pc2), Split(_, _) => *split = Split(pc1, pc2),
_ => fail!("BUG: Invalid split index."), _ => panic!("BUG: Invalid split index."),
} }
} }
@ -260,13 +260,13 @@ impl<'r> Compiler<'r> {
/// Sets the location of a `Jump` instruction at index `i` to `pc`. /// Sets the location of a `Jump` instruction at index `i` to `pc`.
/// If the instruction at index `i` isn't a `Jump` instruction, then /// If the instruction at index `i` isn't a `Jump` instruction, then
/// `fail!` is called. /// `panic!` is called.
#[inline] #[inline]
fn set_jump(&mut self, i: InstIdx, pc: InstIdx) { fn set_jump(&mut self, i: InstIdx, pc: InstIdx) {
let jmp = self.insts.get_mut(i); let jmp = self.insts.get_mut(i);
match *jmp { match *jmp {
Jump(_) => *jmp = Jump(pc), Jump(_) => *jmp = Jump(pc),
_ => fail!("BUG: Invalid jump index."), _ => panic!("BUG: Invalid jump index."),
} }
} }
} }

View file

@ -31,7 +31,7 @@
//! use regex::Regex; //! use regex::Regex;
//! let re = match Regex::new(r"^\d{4}-\d{2}-\d{2}$") { //! let re = match Regex::new(r"^\d{4}-\d{2}-\d{2}$") {
//! Ok(re) => re, //! Ok(re) => re,
//! Err(err) => fail!("{}", err), //! Err(err) => panic!("{}", err),
//! }; //! };
//! assert_eq!(re.is_match("2014-01-01"), true); //! assert_eq!(re.is_match("2014-01-01"), true);
//! ``` //! ```

View file

@ -117,7 +117,7 @@ impl BuildAst {
fn flags(&self) -> Flags { fn flags(&self) -> Flags {
match *self { match *self {
Paren(flags, _, _) => flags, Paren(flags, _, _) => flags,
_ => fail!("Cannot get flags from {}", self), _ => panic!("Cannot get flags from {}", self),
} }
} }
@ -125,7 +125,7 @@ impl BuildAst {
match *self { match *self {
Paren(_, 0, _) => None, Paren(_, 0, _) => None,
Paren(_, c, _) => Some(c), Paren(_, c, _) => Some(c),
_ => fail!("Cannot get capture group from {}", self), _ => panic!("Cannot get capture group from {}", self),
} }
} }
@ -139,7 +139,7 @@ impl BuildAst {
Some(name.clone()) Some(name.clone())
} }
} }
_ => fail!("Cannot get capture name from {}", self), _ => panic!("Cannot get capture name from {}", self),
} }
} }
@ -153,7 +153,7 @@ impl BuildAst {
fn unwrap(self) -> Result<Ast, Error> { fn unwrap(self) -> Result<Ast, Error> {
match self { match self {
Expr(x) => Ok(x), Expr(x) => Ok(x),
_ => fail!("Tried to unwrap non-AST item: {}", self), _ => panic!("Tried to unwrap non-AST item: {}", self),
} }
} }
} }
@ -321,7 +321,7 @@ impl<'a> Parser<'a> {
} }
let rep: Repeater = match c { let rep: Repeater = match c {
'?' => ZeroOne, '*' => ZeroMore, '+' => OneMore, '?' => ZeroOne, '*' => ZeroMore, '+' => OneMore,
_ => fail!("Not a valid repeater operator."), _ => panic!("Not a valid repeater operator."),
}; };
match self.peek(1) { match self.peek(1) {
@ -393,7 +393,7 @@ impl<'a> Parser<'a> {
continue continue
} }
Some(ast) => Some(ast) =>
fail!("Expected Class AST but got '{}'", ast), panic!("Expected Class AST but got '{}'", ast),
// Just drop down and try to add as a regular character. // Just drop down and try to add as a regular character.
None => {}, None => {},
}, },
@ -408,7 +408,7 @@ impl<'a> Parser<'a> {
return self.err( return self.err(
"\\A, \\z, \\b and \\B are not valid escape \ "\\A, \\z, \\b and \\B are not valid escape \
sequences inside a character class."), sequences inside a character class."),
ast => fail!("Unexpected AST item '{}'", ast), ast => panic!("Unexpected AST item '{}'", ast),
} }
} }
_ => {}, _ => {},

View file

@ -76,7 +76,7 @@ pub fn is_match(regex: &str, text: &str) -> Result<bool, parse::Error> {
/// # use regex::Regex; /// # use regex::Regex;
/// let re = match Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}") { /// let re = match Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}") {
/// Ok(re) => re, /// Ok(re) => re,
/// Err(err) => fail!("{}", err), /// Err(err) => panic!("{}", err),
/// }; /// };
/// assert_eq!(re.find("phone: 111-222-3333"), Some((7, 19))); /// assert_eq!(re.find("phone: 111-222-3333"), Some((7, 19)));
/// ``` /// ```

View file

@ -15,7 +15,7 @@ use stdtest::Bencher;
use regex::{Regex, NoExpand}; use regex::{Regex, NoExpand};
fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) { fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) {
b.iter(|| if !re.is_match(text) { fail!("no match") }); b.iter(|| if !re.is_match(text) { panic!("no match") });
} }
#[bench] #[bench]
@ -143,7 +143,7 @@ macro_rules! throughput(
fn $name(b: &mut Bencher) { fn $name(b: &mut Bencher) {
let text = gen_text($size); let text = gen_text($size);
b.bytes = $size; b.bytes = $size;
b.iter(|| if $regex.is_match(text.as_slice()) { fail!("match") }); b.iter(|| if $regex.is_match(text.as_slice()) { panic!("match") });
} }
); );
) )

View file

@ -30,7 +30,7 @@ macro_rules! regex(
($re:expr) => ( ($re:expr) => (
match ::regex::Regex::new($re) { match ::regex::Regex::new($re) {
Ok(re) => re, Ok(re) => re,
Err(err) => fail!("{}", err), Err(err) => panic!("{}", err),
} }
); );
) )

View file

@ -75,7 +75,7 @@ macro_rules! noparse(
let re = $re; let re = $re;
match Regex::new(re) { match Regex::new(re) {
Err(_) => {}, Err(_) => {},
Ok(_) => fail!("Regex '{}' should cause a parse error.", re), Ok(_) => panic!("Regex '{}' should cause a parse error.", re),
} }
} }
); );
@ -133,7 +133,7 @@ macro_rules! mat(
sgot = sgot[0..sexpect.len()] sgot = sgot[0..sexpect.len()]
} }
if sexpect != sgot { if sexpect != sgot {
fail!("For RE '{}' against '{}', expected '{}' but got '{}'", panic!("For RE '{}' against '{}', expected '{}' but got '{}'",
$re, text, sexpect, sgot); $re, text, sexpect, sgot);
} }
} }

View file

@ -85,7 +85,7 @@ struct Diagnostic {
// We use an Arc instead of just returning a list of diagnostics from the // We use an Arc instead of just returning a list of diagnostics from the
// child task because we need to make sure that the messages are seen even // child task because we need to make sure that the messages are seen even
// if the child task fails (for example, when `fatal` is called). // if the child task panics (for example, when `fatal` is called).
#[deriving(Clone)] #[deriving(Clone)]
struct SharedEmitter { struct SharedEmitter {
buffer: Arc<Mutex<Vec<Diagnostic>>>, buffer: Arc<Mutex<Vec<Diagnostic>>>,
@ -133,7 +133,7 @@ impl Emitter for SharedEmitter {
fn custom_emit(&mut self, _cm: &codemap::CodeMap, fn custom_emit(&mut self, _cm: &codemap::CodeMap,
_sp: diagnostic::RenderSpan, _msg: &str, _lvl: Level) { _sp: diagnostic::RenderSpan, _msg: &str, _lvl: Level) {
fail!("SharedEmitter doesn't support custom_emit"); panic!("SharedEmitter doesn't support custom_emit");
} }
} }
@ -897,19 +897,19 @@ fn run_work_multithreaded(sess: &Session,
futures.push(future); futures.push(future);
} }
let mut failed = false; let mut panicked = false;
for future in futures.into_iter() { for future in futures.into_iter() {
match future.unwrap() { match future.unwrap() {
Ok(()) => {}, Ok(()) => {},
Err(_) => { Err(_) => {
failed = true; panicked = true;
}, },
} }
// Display any new diagnostics. // Display any new diagnostics.
diag_emitter.dump(sess.diagnostic().handler()); diag_emitter.dump(sess.diagnostic().handler());
} }
if failed { if panicked {
sess.fatal("aborting due to worker thread failure"); sess.fatal("aborting due to worker thread panic");
} }
} }

View file

@ -898,7 +898,7 @@ mod test {
let matches = let matches =
&match getopts(["--test".to_string()], optgroups().as_slice()) { &match getopts(["--test".to_string()], optgroups().as_slice()) {
Ok(m) => m, Ok(m) => m,
Err(f) => fail!("test_switch_implies_cfg_test: {}", f) Err(f) => panic!("test_switch_implies_cfg_test: {}", f)
}; };
let registry = diagnostics::registry::Registry::new([]); let registry = diagnostics::registry::Registry::new([]);
let sessopts = build_session_options(matches); let sessopts = build_session_options(matches);
@ -916,7 +916,7 @@ mod test {
optgroups().as_slice()) { optgroups().as_slice()) {
Ok(m) => m, Ok(m) => m,
Err(f) => { Err(f) => {
fail!("test_switch_implies_cfg_test_unless_cfg_test: {}", f) panic!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
} }
}; };
let registry = diagnostics::registry::Registry::new([]); let registry = diagnostics::registry::Registry::new([]);

View file

@ -269,7 +269,7 @@ Available lint options:
println!("Compiler plugins can provide additional lints and lint groups. To see a \ println!("Compiler plugins can provide additional lints and lint groups. To see a \
listing of these, re-run `rustc -W help` with a crate filename."); listing of these, re-run `rustc -W help` with a crate filename.");
} }
(false, _, _) => fail!("didn't load lint plugins but got them anyway!"), (false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
(true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."), (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
(true, l, g) => { (true, l, g) => {
if l > 0 { if l > 0 {
@ -424,7 +424,7 @@ fn parse_crate_attrs(sess: &Session, input: &Input) ->
pub fn early_error(msg: &str) -> ! { pub fn early_error(msg: &str) -> ! {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None); let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
emitter.emit(None, msg, None, diagnostic::Fatal); emitter.emit(None, msg, None, diagnostic::Fatal);
fail!(diagnostic::FatalError); panic!(diagnostic::FatalError);
} }
pub fn early_warn(msg: &str) { pub fn early_warn(msg: &str) {
@ -466,7 +466,7 @@ pub fn monitor(f: proc():Send) {
match task.try(f) { match task.try(f) {
Ok(()) => { /* fallthrough */ } Ok(()) => { /* fallthrough */ }
Err(value) => { Err(value) => {
// Task failed without emitting a fatal diagnostic // Task panicked without emitting a fatal diagnostic
if !value.is::<diagnostic::FatalError>() { if !value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None); let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
@ -475,13 +475,13 @@ pub fn monitor(f: proc():Send) {
if !value.is::<diagnostic::ExplicitBug>() { if !value.is::<diagnostic::ExplicitBug>() {
emitter.emit( emitter.emit(
None, None,
"unexpected failure", "unexpected panic",
None, None,
diagnostic::Bug); diagnostic::Bug);
} }
let xs = [ let xs = [
"the compiler hit an unexpected failure path. this is a bug.".to_string(), "the compiler unexpectedly panicked. this is a bug.".to_string(),
format!("we would appreciate a bug report: {}", format!("we would appreciate a bug report: {}",
BUG_REPORT_URL), BUG_REPORT_URL),
"run with `RUST_BACKTRACE=1` for a backtrace".to_string(), "run with `RUST_BACKTRACE=1` for a backtrace".to_string(),
@ -503,11 +503,11 @@ pub fn monitor(f: proc():Send) {
} }
} }
// Fail so the process returns a failure code, but don't pollute the // Panic so the process returns a failure code, but don't pollute the
// output with some unnecessary failure messages, we've already // output with some unnecessary failure messages, we've already
// printed everything that we needed to. // printed everything that we needed to.
io::stdio::set_stderr(box io::util::NullWriter); io::stdio::set_stderr(box io::util::NullWriter);
fail!(); panic!();
} }
} }
} }

View file

@ -444,7 +444,7 @@ pub fn pretty_print_input(sess: Session,
let r = io::File::create(&p); let r = io::File::create(&p);
match r { match r {
Ok(w) => box w as Box<Writer+'static>, Ok(w) => box w as Box<Writer+'static>,
Err(e) => fail!("print-print failed to open {} due to {}", Err(e) => panic!("print-print failed to open {} due to {}",
p.display(), e), p.display(), e),
} }
} }

View file

@ -190,7 +190,7 @@ impl LintPass for TypeLimits {
return; return;
} }
} }
_ => fail!() _ => panic!()
}; };
}, },
ty::ty_uint(t) => { ty::ty_uint(t) => {
@ -201,7 +201,7 @@ impl LintPass for TypeLimits {
let lit_val: u64 = match lit.node { let lit_val: u64 = match lit.node {
ast::LitByte(_v) => return, // _v is u8, within range by definition ast::LitByte(_v) => return, // _v is u8, within range by definition
ast::LitInt(v, _) => v, ast::LitInt(v, _) => v,
_ => fail!() _ => panic!()
}; };
if lit_val < min || lit_val > max { if lit_val < min || lit_val > max {
cx.span_lint(OVERFLOWING_LITERALS, e.span, cx.span_lint(OVERFLOWING_LITERALS, e.span,
@ -216,7 +216,7 @@ impl LintPass for TypeLimits {
Some(f) => f, Some(f) => f,
None => return None => return
}, },
_ => fail!() _ => panic!()
}; };
if lit_val < min || lit_val > max { if lit_val < min || lit_val > max {
cx.span_lint(OVERFLOWING_LITERALS, e.span, cx.span_lint(OVERFLOWING_LITERALS, e.span,
@ -237,7 +237,7 @@ impl LintPass for TypeLimits {
ast::BiGt => v >= min && v < max, ast::BiGt => v >= min && v < max,
ast::BiGe => v > min && v <= max, ast::BiGe => v > min && v <= max,
ast::BiEq | ast::BiNe => v >= min && v <= max, ast::BiEq | ast::BiNe => v >= min && v <= max,
_ => fail!() _ => panic!()
} }
} }
@ -301,7 +301,7 @@ impl LintPass for TypeLimits {
ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64), ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64),
_ => return true _ => return true
}, },
_ => fail!() _ => panic!()
}; };
is_valid(norm_binop, lit_val, min, max) is_valid(norm_binop, lit_val, min, max)
} }
@ -312,7 +312,7 @@ impl LintPass for TypeLimits {
ast::LitInt(v, _) => v, ast::LitInt(v, _) => v,
_ => return true _ => return true
}, },
_ => fail!() _ => panic!()
}; };
is_valid(norm_binop, lit_val, min, max) is_valid(norm_binop, lit_val, min, max)
} }
@ -353,7 +353,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
def::DefTy(..) => { def::DefTy(..) => {
let tty = match self.cx.tcx.ast_ty_to_ty_cache.borrow().find(&ty_id) { let tty = match self.cx.tcx.ast_ty_to_ty_cache.borrow().find(&ty_id) {
Some(&ty::atttce_resolved(t)) => t, Some(&ty::atttce_resolved(t)) => t,
_ => fail!("ast_ty_to_ty_cache was incomplete after typeck!") _ => panic!("ast_ty_to_ty_cache was incomplete after typeck!")
}; };
if !ty::is_ffi_safe(self.cx.tcx, tty) { if !ty::is_ffi_safe(self.cx.tcx, tty) {

View file

@ -166,7 +166,7 @@ impl LintStore {
fn register_renamed(&mut self, old_name: &str, new_name: &str) { fn register_renamed(&mut self, old_name: &str, new_name: &str) {
let target = match self.by_name.find_equiv(&new_name) { let target = match self.by_name.find_equiv(&new_name) {
Some(&Id(lint_id)) => lint_id.clone(), Some(&Id(lint_id)) => lint_id.clone(),
_ => fail!("invalid lint renaming of {} to {}", old_name, new_name) _ => panic!("invalid lint renaming of {} to {}", old_name, new_name)
}; };
self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target)); self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
} }
@ -388,7 +388,7 @@ pub fn raw_emit_lint(sess: &Session, lint: &'static Lint,
format!("{} [-{} {}]", msg, format!("{} [-{} {}]", msg,
match level { match level {
Warn => 'W', Deny => 'D', Forbid => 'F', Warn => 'W', Deny => 'D', Forbid => 'F',
Allow => fail!() Allow => panic!()
}, name.replace("_", "-")) }, name.replace("_", "-"))
}, },
Node(src) => { Node(src) => {

View file

@ -174,7 +174,7 @@ fn extract_crate_info(e: &Env, i: &ast::ViewItem) -> Option<CrateInfo> {
pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) { pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
let err = |s: &str| { let err = |s: &str| {
match (sp, sess) { match (sp, sess) {
(_, None) => fail!("{}", s), (_, None) => panic!("{}", s),
(Some(sp), Some(sess)) => sess.span_err(sp, s), (Some(sp), Some(sess)) => sess.span_err(sp, s),
(None, Some(sess)) => sess.err(s), (None, Some(sess)) => sess.err(s),
} }

View file

@ -94,7 +94,7 @@ pub fn maybe_find_item<'a>(item_id: ast::NodeId,
fn find_item<'a>(item_id: ast::NodeId, items: rbml::Doc<'a>) -> rbml::Doc<'a> { fn find_item<'a>(item_id: ast::NodeId, items: rbml::Doc<'a>) -> rbml::Doc<'a> {
match maybe_find_item(item_id, items) { match maybe_find_item(item_id, items) {
None => fail!("lookup_item: id not found: {}", item_id), None => panic!("lookup_item: id not found: {}", item_id),
Some(d) => d Some(d) => d
} }
} }
@ -153,7 +153,7 @@ fn item_family(item: rbml::Doc) -> Family {
'S' => Struct, 'S' => Struct,
'g' => PublicField, 'g' => PublicField,
'N' => InheritedField, 'N' => InheritedField,
c => fail!("unexpected family char: {}", c) c => panic!("unexpected family char: {}", c)
} }
} }
@ -164,7 +164,7 @@ fn item_visibility(item: rbml::Doc) -> ast::Visibility {
match reader::doc_as_u8(visibility_doc) as char { match reader::doc_as_u8(visibility_doc) as char {
'y' => ast::Public, 'y' => ast::Public,
'i' => ast::Inherited, 'i' => ast::Inherited,
_ => fail!("unknown visibility character") _ => panic!("unknown visibility character")
} }
} }
} }
@ -707,7 +707,7 @@ fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
match ch as char { match ch as char {
'i' => ast::MutImmutable, 'i' => ast::MutImmutable,
'm' => ast::MutMutable, 'm' => ast::MutMutable,
_ => fail!("unknown mutability character: `{}`", ch as char), _ => panic!("unknown mutability character: `{}`", ch as char),
} }
} }
@ -725,7 +725,7 @@ fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
ty::ReEmpty, ty::ReEmpty,
get_mutability(string.as_bytes()[1])) get_mutability(string.as_bytes()[1]))
} }
_ => fail!("unknown self type code: `{}`", explicit_self_kind as char) _ => panic!("unknown self type code: `{}`", explicit_self_kind as char)
} }
} }
@ -739,7 +739,7 @@ pub fn get_impl_items(cdata: Cmd, impl_id: ast::NodeId)
match item_sort(doc) { match item_sort(doc) {
'r' | 'p' => impl_items.push(ty::MethodTraitItemId(def_id)), 'r' | 'p' => impl_items.push(ty::MethodTraitItemId(def_id)),
't' => impl_items.push(ty::TypeTraitItemId(def_id)), 't' => impl_items.push(ty::TypeTraitItemId(def_id)),
_ => fail!("unknown impl item sort"), _ => panic!("unknown impl item sort"),
} }
true true
}); });
@ -760,7 +760,7 @@ pub fn get_trait_item_name_and_kind(intr: Rc<IdentInterner>,
} }
't' => (name, TypeTraitItemKind), 't' => (name, TypeTraitItemKind),
c => { c => {
fail!("get_trait_item_name_and_kind(): unknown trait item kind \ panic!("get_trait_item_name_and_kind(): unknown trait item kind \
in metadata: `{}`", c) in metadata: `{}`", c)
} }
} }
@ -811,7 +811,7 @@ pub fn get_impl_or_trait_item(intr: Rc<IdentInterner>,
container: container, container: container,
})) }))
} }
_ => fail!("unknown impl/trait item sort"), _ => panic!("unknown impl/trait item sort"),
} }
} }
@ -825,7 +825,7 @@ pub fn get_trait_item_def_ids(cdata: Cmd, id: ast::NodeId)
match item_sort(mth) { match item_sort(mth) {
'r' | 'p' => result.push(ty::MethodTraitItemId(def_id)), 'r' | 'p' => result.push(ty::MethodTraitItemId(def_id)),
't' => result.push(ty::TypeTraitItemId(def_id)), 't' => result.push(ty::TypeTraitItemId(def_id)),
_ => fail!("unknown trait item sort"), _ => panic!("unknown trait item sort"),
} }
true true
}); });
@ -937,7 +937,7 @@ pub fn get_static_methods_if_impl(intr: Rc<IdentInterner>,
match item_family(impl_method_doc) { match item_family(impl_method_doc) {
StaticMethod => fn_style = ast::NormalFn, StaticMethod => fn_style = ast::NormalFn,
UnsafeStaticMethod => fn_style = ast::UnsafeFn, UnsafeStaticMethod => fn_style = ast::UnsafeFn,
_ => fail!() _ => panic!()
} }
static_impl_methods.push(StaticMethodInfo { static_impl_methods.push(StaticMethodInfo {
@ -998,7 +998,7 @@ fn struct_field_family_to_visibility(family: Family) -> ast::Visibility {
match family { match family {
PublicField => ast::Public, PublicField => ast::Public,
InheritedField => ast::Inherited, InheritedField => ast::Inherited,
_ => fail!() _ => panic!()
} }
} }
@ -1207,7 +1207,7 @@ pub fn translate_def_id(cdata: Cmd, did: ast::DefId) -> ast::DefId {
node: did.node, node: did.node,
} }
} }
None => fail!("didn't find a crate in the cnum_map") None => panic!("didn't find a crate in the cnum_map")
} }
} }
@ -1314,7 +1314,7 @@ pub fn get_dylib_dependency_formats(cdata: Cmd)
let cnum = from_str(cnum).unwrap(); let cnum = from_str(cnum).unwrap();
let cnum = match cdata.cnum_map.find(&cnum) { let cnum = match cdata.cnum_map.find(&cnum) {
Some(&n) => n, Some(&n) => n,
None => fail!("didn't find a crate in the cnum_map") None => panic!("didn't find a crate in the cnum_map")
}; };
result.push((cnum, if link == "d" { result.push((cnum, if link == "d" {
cstore::RequireDynamic cstore::RequireDynamic

View file

@ -187,13 +187,13 @@ pub fn get_or_default_sysroot() -> Path {
path.and_then(|path| path.and_then(|path|
match myfs::realpath(&path) { match myfs::realpath(&path) {
Ok(canon) => Some(canon), Ok(canon) => Some(canon),
Err(e) => fail!("failed to get realpath: {}", e), Err(e) => panic!("failed to get realpath: {}", e),
}) })
} }
match canonicalize(os::self_exe_name()) { match canonicalize(os::self_exe_name()) {
Some(mut p) => { p.pop(); p.pop(); p } Some(mut p) => { p.pop(); p.pop(); p }
None => fail!("can't determine value for sysroot") None => panic!("can't determine value for sysroot")
} }
} }

View file

@ -260,7 +260,7 @@ fn parse_region_substs(st: &mut PState, conv: conv_did) -> subst::RegionSubsts {
parse_vec_per_param_space( parse_vec_per_param_space(
st, |st| parse_region(st, |x,y| conv(x,y)))) st, |st| parse_region(st, |x,y| conv(x,y))))
} }
_ => fail!("parse_bound_region: bad input") _ => panic!("parse_bound_region: bad input")
} }
} }
@ -282,7 +282,7 @@ fn parse_bound_region(st: &mut PState, conv: conv_did) -> ty::BoundRegion {
ty::BrFresh(id) ty::BrFresh(id)
} }
'e' => ty::BrEnv, 'e' => ty::BrEnv,
_ => fail!("parse_bound_region: bad input") _ => panic!("parse_bound_region: bad input")
} }
} }
@ -327,7 +327,7 @@ fn parse_region(st: &mut PState, conv: conv_did) -> ty::Region {
'e' => { 'e' => {
ty::ReStatic ty::ReStatic
} }
_ => fail!("parse_region: bad input") _ => panic!("parse_region: bad input")
} }
} }
@ -335,7 +335,7 @@ fn parse_opt<T>(st: &mut PState, f: |&mut PState| -> T) -> Option<T> {
match next(st) { match next(st) {
'n' => None, 'n' => None,
's' => Some(f(st)), 's' => Some(f(st)),
_ => fail!("parse_opt: bad input") _ => panic!("parse_opt: bad input")
} }
} }
@ -374,7 +374,7 @@ fn parse_ty(st: &mut PState, conv: conv_did) -> ty::t {
'D' => return ty::mk_mach_int(ast::TyI64), 'D' => return ty::mk_mach_int(ast::TyI64),
'f' => return ty::mk_mach_float(ast::TyF32), 'f' => return ty::mk_mach_float(ast::TyF32),
'F' => return ty::mk_mach_float(ast::TyF64), 'F' => return ty::mk_mach_float(ast::TyF64),
_ => fail!("parse_ty: bad numeric type") _ => panic!("parse_ty: bad numeric type")
} }
} }
'c' => return ty::mk_char(), 'c' => return ty::mk_char(),
@ -474,7 +474,7 @@ fn parse_ty(st: &mut PState, conv: conv_did) -> ty::t {
'e' => { 'e' => {
return ty::mk_err(); return ty::mk_err();
} }
c => { fail!("unexpected char in type string: {}", c);} c => { panic!("unexpected char in type string: {}", c);}
} }
} }
@ -527,7 +527,7 @@ fn parse_fn_style(c: char) -> FnStyle {
match c { match c {
'u' => UnsafeFn, 'u' => UnsafeFn,
'n' => NormalFn, 'n' => NormalFn,
_ => fail!("parse_fn_style: bad fn_style {}", c) _ => panic!("parse_fn_style: bad fn_style {}", c)
} }
} }
@ -543,7 +543,7 @@ fn parse_onceness(c: char) -> ast::Onceness {
match c { match c {
'o' => ast::Once, 'o' => ast::Once,
'm' => ast::Many, 'm' => ast::Many,
_ => fail!("parse_onceness: bad onceness") _ => panic!("parse_onceness: bad onceness")
} }
} }
@ -587,7 +587,7 @@ fn parse_sig(st: &mut PState, conv: conv_did) -> ty::FnSig {
let variadic = match next(st) { let variadic = match next(st) {
'V' => true, 'V' => true,
'N' => false, 'N' => false,
r => fail!(format!("bad variadic: {}", r)), r => panic!(format!("bad variadic: {}", r)),
}; };
let output = match peek(st) { let output = match peek(st) {
'z' => { 'z' => {
@ -609,7 +609,7 @@ pub fn parse_def_id(buf: &[u8]) -> ast::DefId {
while colon_idx < len && buf[colon_idx] != ':' as u8 { colon_idx += 1u; } while colon_idx < len && buf[colon_idx] != ':' as u8 { colon_idx += 1u; }
if colon_idx == len { if colon_idx == len {
error!("didn't find ':' when parsing def id"); error!("didn't find ':' when parsing def id");
fail!(); panic!();
} }
let crate_part = buf[0u..colon_idx]; let crate_part = buf[0u..colon_idx];
@ -617,12 +617,12 @@ pub fn parse_def_id(buf: &[u8]) -> ast::DefId {
let crate_num = match uint::parse_bytes(crate_part, 10u) { let crate_num = match uint::parse_bytes(crate_part, 10u) {
Some(cn) => cn as ast::CrateNum, Some(cn) => cn as ast::CrateNum,
None => fail!("internal error: parse_def_id: crate number expected, found {}", None => panic!("internal error: parse_def_id: crate number expected, found {}",
crate_part) crate_part)
}; };
let def_num = match uint::parse_bytes(def_part, 10u) { let def_num = match uint::parse_bytes(def_part, 10u) {
Some(dn) => dn as ast::NodeId, Some(dn) => dn as ast::NodeId,
None => fail!("internal error: parse_def_id: id expected, found {}", None => panic!("internal error: parse_def_id: id expected, found {}",
def_part) def_part)
}; };
ast::DefId { krate: crate_num, node: def_num } ast::DefId { krate: crate_num, node: def_num }
@ -688,7 +688,7 @@ fn parse_builtin_bounds(st: &mut PState, _conv: conv_did) -> ty::BuiltinBounds {
return builtin_bounds; return builtin_bounds;
} }
c => { c => {
fail!("parse_bounds: bad builtin bounds ('{}')", c) panic!("parse_bounds: bad builtin bounds ('{}')", c)
} }
} }
} }
@ -714,7 +714,7 @@ fn parse_bounds(st: &mut PState, conv: conv_did) -> ty::ParamBounds {
return param_bounds; return param_bounds;
} }
c => { c => {
fail!("parse_bounds: bad bounds ('{}')", c) panic!("parse_bounds: bad bounds ('{}')", c)
} }
} }
} }

View file

@ -341,7 +341,7 @@ impl Folder for NestedItemsDropper {
ast::DeclItem(_) => false, ast::DeclItem(_) => false,
} }
} }
ast::StmtMac(..) => fail!("unexpanded macro in astencode") ast::StmtMac(..) => panic!("unexpanded macro in astencode")
}; };
if use_stmt { if use_stmt {
Some(stmt) Some(stmt)
@ -795,7 +795,7 @@ impl<'a> vtable_decoder_helpers for reader::Decoder<'a> {
3 => { 3 => {
typeck::vtable_error typeck::vtable_error
} }
_ => fail!("bad enum variant") _ => panic!("bad enum variant")
}) })
}) })
}).unwrap() }).unwrap()
@ -1488,7 +1488,7 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> {
}).unwrap() }).unwrap()
} }
_ => fail!("..") _ => panic!("..")
}) })
}) })
}).unwrap() }).unwrap()
@ -1618,7 +1618,7 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> {
ty::AdjustDerefRef(auto_deref_ref) ty::AdjustDerefRef(auto_deref_ref)
} }
_ => fail!("bad enum variant for ty::AutoAdjustment") _ => panic!("bad enum variant for ty::AutoAdjustment")
}) })
}) })
}).unwrap() }).unwrap()
@ -1695,7 +1695,7 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> {
ty::AutoUnsafe(m, a) ty::AutoUnsafe(m, a)
} }
_ => fail!("bad enum variant for ty::AutoRef") _ => panic!("bad enum variant for ty::AutoRef")
}) })
}) })
}).unwrap() }).unwrap()
@ -1736,7 +1736,7 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> {
substs: substs }; substs: substs };
ty::UnsizeVtable(ty_trait, self_ty) ty::UnsizeVtable(ty_trait, self_ty)
} }
_ => fail!("bad enum variant for ty::UnsizeKind") _ => panic!("bad enum variant for ty::UnsizeKind")
}) })
}) })
}).unwrap() }).unwrap()
@ -1762,7 +1762,7 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> {
0 => ty::FnUnboxedClosureKind, 0 => ty::FnUnboxedClosureKind,
1 => ty::FnMutUnboxedClosureKind, 1 => ty::FnMutUnboxedClosureKind,
2 => ty::FnOnceUnboxedClosureKind, 2 => ty::FnOnceUnboxedClosureKind,
_ => fail!("bad enum variant for ty::UnboxedClosureKind"), _ => panic!("bad enum variant for ty::UnboxedClosureKind"),
}) })
}).unwrap(); }).unwrap();
ty::UnboxedClosure { ty::UnboxedClosure {
@ -2032,6 +2032,6 @@ fn test_simplification() {
assert!(pprust::item_to_string(&*item_out) == assert!(pprust::item_to_string(&*item_out) ==
pprust::item_to_string(&*item_exp)); pprust::item_to_string(&*item_exp));
} }
_ => fail!() _ => panic!()
} }
} }

View file

@ -133,10 +133,10 @@ fn report_cannot_move_out_of(bccx: &BorrowckCtxt, move_from: mc::cmt) {
which defines the `Drop` trait", which defines the `Drop` trait",
b.ty.user_string(bccx.tcx)).as_slice()); b.ty.user_string(bccx.tcx)).as_slice());
}, },
_ => fail!("this path should not cause illegal move") _ => panic!("this path should not cause illegal move")
} }
} }
_ => fail!("this path should not cause illegal move") _ => panic!("this path should not cause illegal move")
} }
} }

View file

@ -284,9 +284,9 @@ pub fn closure_to_block(closure_id: ast::NodeId,
ast::ExprProc(_, ref block) | ast::ExprProc(_, ref block) |
ast::ExprFnBlock(_, _, ref block) | ast::ExprFnBlock(_, _, ref block) |
ast::ExprUnboxedFn(_, _, _, ref block) => { block.id } ast::ExprUnboxedFn(_, _, _, ref block) => { block.id }
_ => fail!("encountered non-closure id: {}", closure_id) _ => panic!("encountered non-closure id: {}", closure_id)
}, },
_ => fail!("encountered non-expr id: {}", closure_id) _ => panic!("encountered non-expr id: {}", closure_id)
} }
} }

View file

@ -88,7 +88,7 @@ struct PropagationContext<'a, 'b: 'a, 'tcx: 'b, O: 'a> {
fn to_cfgidx_or_die(id: ast::NodeId, index: &NodeMap<CFGIndex>) -> CFGIndex { fn to_cfgidx_or_die(id: ast::NodeId, index: &NodeMap<CFGIndex>) -> CFGIndex {
let opt_cfgindex = index.find(&id).map(|&i|i); let opt_cfgindex = index.find(&id).map(|&i|i);
opt_cfgindex.unwrap_or_else(|| { opt_cfgindex.unwrap_or_else(|| {
fail!("nodeid_to_index does not have entry for NodeId {}", id); panic!("nodeid_to_index does not have entry for NodeId {}", id);
}) })
} }

View file

@ -74,7 +74,7 @@ impl Def {
local_def(id) local_def(id)
} }
DefPrimTy(_) => fail!() DefPrimTy(_) => panic!()
} }
} }

View file

@ -264,18 +264,18 @@ lets_do_this! {
StrEqFnLangItem, "str_eq", str_eq_fn; StrEqFnLangItem, "str_eq", str_eq_fn;
// A number of failure-related lang items. The `fail` item corresponds to // A number of panic-related lang items. The `panic` item corresponds to
// divide-by-zero and various failure cases with `match`. The // divide-by-zero and various panic cases with `match`. The
// `fail_bounds_check` item is for indexing arrays. // `panic_bounds_check` item is for indexing arrays.
// //
// The `begin_unwind` lang item has a predefined symbol name and is sort of // The `begin_unwind` lang item has a predefined symbol name and is sort of
// a "weak lang item" in the sense that a crate is not required to have it // a "weak lang item" in the sense that a crate is not required to have it
// defined to use it, but a final product is required to define it // defined to use it, but a final product is required to define it
// somewhere. Additionally, there are restrictions on crates that use a weak // somewhere. Additionally, there are restrictions on crates that use a weak
// lang item, but do not have it defined. // lang item, but do not have it defined.
FailFnLangItem, "fail", fail_fn; PanicFnLangItem, "panic", panic_fn;
FailBoundsCheckFnLangItem, "fail_bounds_check", fail_bounds_check_fn; PanicBoundsCheckFnLangItem, "panic_bounds_check", panic_bounds_check_fn;
FailFmtLangItem, "fail_fmt", fail_fmt; PanicFmtLangItem, "panic_fmt", panic_fmt;
ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn; ExchangeMallocFnLangItem, "exchange_malloc", exchange_malloc_fn;
ExchangeFreeFnLangItem, "exchange_free", exchange_free_fn; ExchangeFreeFnLangItem, "exchange_free", exchange_free_fn;

View file

@ -93,7 +93,7 @@
* These are described in the `specials` struct: * These are described in the `specials` struct:
* *
* - `exit_ln`: a live node that is generated to represent every 'exit' from * - `exit_ln`: a live node that is generated to represent every 'exit' from
* the function, whether it be by explicit return, fail, or other means. * the function, whether it be by explicit return, panic, or other means.
* *
* - `fallthrough_ln`: a live node that represents a fallthrough * - `fallthrough_ln`: a live node that represents a fallthrough
* *
@ -400,7 +400,7 @@ fn visit_fn(ir: &mut IrMaps,
visit::walk_fn(&mut fn_maps, fk, decl, body, sp); visit::walk_fn(&mut fn_maps, fk, decl, body, sp);
// Special nodes and variables: // Special nodes and variables:
// - exit_ln represents the end of the fn, either by return or fail // - exit_ln represents the end of the fn, either by return or panic
// - implicit_ret_var is a pseudo-variable that represents // - implicit_ret_var is a pseudo-variable that represents
// an implicit return // an implicit return
let specials = Specials { let specials = Specials {

View file

@ -157,7 +157,7 @@ impl RegionMaps {
//! Returns the narrowest scope that encloses `id`, if any. //! Returns the narrowest scope that encloses `id`, if any.
match self.scope_map.borrow().find(&id) { match self.scope_map.borrow().find(&id) {
Some(&r) => r, Some(&r) => r,
None => { fail!("no enclosing scope for id {}", id); } None => { panic!("no enclosing scope for id {}", id); }
} }
} }
@ -167,7 +167,7 @@ impl RegionMaps {
*/ */
match self.var_map.borrow().find(&var_id) { match self.var_map.borrow().find(&var_id) {
Some(&r) => r, Some(&r) => r,
None => { fail!("no enclosing scope for id {}", var_id); } None => { panic!("no enclosing scope for id {}", var_id); }
} }
} }

View file

@ -728,7 +728,7 @@ impl NameBindings {
fn get_module(&self) -> Rc<Module> { fn get_module(&self) -> Rc<Module> {
match self.get_module_if_available() { match self.get_module_if_available() {
None => { None => {
fail!("get_module called on a node with no module \ panic!("get_module called on a node with no module \
definition!") definition!")
} }
Some(module_def) => module_def Some(module_def) => module_def
@ -1910,7 +1910,7 @@ impl<'a> Resolver<'a> {
DefLocal(..) | DefPrimTy(..) | DefTyParam(..) | DefLocal(..) | DefPrimTy(..) | DefTyParam(..) |
DefUse(..) | DefUpvar(..) | DefRegion(..) | DefUse(..) | DefUpvar(..) | DefRegion(..) |
DefTyParamBinder(..) | DefLabel(..) | DefSelfTy(..) => { DefTyParamBinder(..) | DefLabel(..) | DefSelfTy(..) => {
fail!("didn't expect `{}`", def); panic!("didn't expect `{}`", def);
} }
} }
} }
@ -2618,7 +2618,7 @@ impl<'a> Resolver<'a> {
} }
UnboundResult => { /* Continue. */ } UnboundResult => { /* Continue. */ }
UnknownResult => { UnknownResult => {
fail!("value result should be known at this point"); panic!("value result should be known at this point");
} }
} }
match type_result { match type_result {
@ -2641,7 +2641,7 @@ impl<'a> Resolver<'a> {
} }
UnboundResult => { /* Continue. */ } UnboundResult => { /* Continue. */ }
UnknownResult => { UnknownResult => {
fail!("type result should be known at this point"); panic!("type result should be known at this point");
} }
} }
@ -5161,7 +5161,7 @@ impl<'a> Resolver<'a> {
target.bindings.value_def.borrow()); target.bindings.value_def.borrow());
match *target.bindings.value_def.borrow() { match *target.bindings.value_def.borrow() {
None => { None => {
fail!("resolved name in the value namespace to a \ panic!("resolved name in the value namespace to a \
set of name bindings with no def?!"); set of name bindings with no def?!");
} }
Some(def) => { Some(def) => {
@ -5191,7 +5191,7 @@ impl<'a> Resolver<'a> {
} }
Indeterminate => { Indeterminate => {
fail!("unexpected indeterminate result"); panic!("unexpected indeterminate result");
} }
Failed(err) => { Failed(err) => {
match err { match err {
@ -5389,7 +5389,7 @@ impl<'a> Resolver<'a> {
msg.as_slice())); msg.as_slice()));
return None; return None;
} }
Indeterminate => fail!("indeterminate unexpected"), Indeterminate => panic!("indeterminate unexpected"),
Success((resulting_module, resulting_last_private)) => { Success((resulting_module, resulting_last_private)) => {
containing_module = resulting_module; containing_module = resulting_module;
last_private = resulting_last_private; last_private = resulting_last_private;
@ -5451,7 +5451,7 @@ impl<'a> Resolver<'a> {
} }
Indeterminate => { Indeterminate => {
fail!("indeterminate unexpected"); panic!("indeterminate unexpected");
} }
Success((resulting_module, resulting_last_private)) => { Success((resulting_module, resulting_last_private)) => {
@ -5537,7 +5537,7 @@ impl<'a> Resolver<'a> {
} }
} }
Indeterminate => { Indeterminate => {
fail!("unexpected indeterminate result"); panic!("unexpected indeterminate result");
} }
Failed(err) => { Failed(err) => {
match err { match err {
@ -6155,7 +6155,7 @@ impl<'a> Resolver<'a> {
type_used: _ type_used: _
}) => (v, t), }) => (v, t),
Some(_) => { Some(_) => {
fail!("we should only have LastImport for `use` directives") panic!("we should only have LastImport for `use` directives")
} }
_ => return, _ => return,
}; };

View file

@ -177,7 +177,7 @@ impl Substs {
*/ */
match self.regions { match self.regions {
ErasedRegions => fail!("Erased regions only expected in trans"), ErasedRegions => panic!("Erased regions only expected in trans"),
NonerasedRegions(ref r) => r NonerasedRegions(ref r) => r
} }
} }
@ -190,7 +190,7 @@ impl Substs {
*/ */
match self.regions { match self.regions {
ErasedRegions => fail!("Erased regions only expected in trans"), ErasedRegions => panic!("Erased regions only expected in trans"),
NonerasedRegions(ref mut r) => r NonerasedRegions(ref mut r) => r
} }
} }
@ -249,7 +249,7 @@ impl ParamSpace {
0 => TypeSpace, 0 => TypeSpace,
1 => SelfSpace, 1 => SelfSpace,
2 => FnSpace, 2 => FnSpace,
_ => fail!("Invalid ParamSpace: {}", u) _ => panic!("Invalid ParamSpace: {}", u)
} }
} }
} }

View file

@ -235,7 +235,7 @@ impl<'a> ConstantExpr<'a> {
let ConstantExpr(other_expr) = other; let ConstantExpr(other_expr) = other;
match const_eval::compare_lit_exprs(tcx, expr, other_expr) { match const_eval::compare_lit_exprs(tcx, expr, other_expr) {
Some(val1) => val1 == 0, Some(val1) => val1 == 0,
None => fail!("compare_list_exprs: type mismatch"), None => panic!("compare_list_exprs: type mismatch"),
} }
} }
} }
@ -734,7 +734,7 @@ impl FailureHandler {
fn handle_fail(&self, bcx: Block) { fn handle_fail(&self, bcx: Block) {
match *self { match *self {
Infallible => Infallible =>
fail!("attempted to fail in an infallible failure handler!"), panic!("attempted to panic in a non-panicking panic handler!"),
JumpToBasicBlock(basic_block) => JumpToBasicBlock(basic_block) =>
Br(bcx, basic_block), Br(bcx, basic_block),
Unreachable => Unreachable =>

View file

@ -586,7 +586,7 @@ fn generic_type_of(cx: &CrateContext,
Type::array(&Type::i64(cx), align_units), Type::array(&Type::i64(cx), align_units),
a if a.count_ones() == 1 => Type::array(&Type::vector(&Type::i32(cx), a / 4), a if a.count_ones() == 1 => Type::array(&Type::vector(&Type::i32(cx), a / 4),
align_units), align_units),
_ => fail!("unsupported enum alignment: {}", align) _ => panic!("unsupported enum alignment: {}", align)
}; };
assert_eq!(machine::llalign_of_min(cx, pad_ty), align); assert_eq!(machine::llalign_of_min(cx, pad_ty), align);
assert_eq!(align_s % discr_size, 0); assert_eq!(align_s % discr_size, 0);

View file

@ -291,7 +291,7 @@ pub fn decl_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
RustCall, RustCall,
Some(llenvironment_type)) Some(llenvironment_type))
} }
_ => fail!("expected closure or fn") _ => panic!("expected closure or fn")
}; };
let llfty = type_of_rust_fn(ccx, env, inputs.as_slice(), output, abi); let llfty = type_of_rust_fn(ccx, env, inputs.as_slice(), output, abi);
@ -2349,7 +2349,7 @@ fn register_fn(ccx: &CrateContext,
ty::ty_bare_fn(ref f) => { ty::ty_bare_fn(ref f) => {
assert!(f.abi == Rust || f.abi == RustCall); assert!(f.abi == Rust || f.abi == RustCall);
} }
_ => fail!("expected bare rust fn") _ => panic!("expected bare rust fn")
}; };
let llfn = decl_rust_fn(ccx, node_type, sym.as_slice()); let llfn = decl_rust_fn(ccx, node_type, sym.as_slice());
@ -2744,7 +2744,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
llfn llfn
} }
_ => fail!("get_item_val: weird result in table") _ => panic!("get_item_val: weird result in table")
}; };
match attr::first_attr_value_str_by_name(i.attrs.as_slice(), match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
@ -2811,7 +2811,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
let args = match v.node.kind { let args = match v.node.kind {
ast::TupleVariantKind(ref args) => args, ast::TupleVariantKind(ref args) => args,
ast::StructVariantKind(_) => { ast::StructVariantKind(_) => {
fail!("struct variant kind unexpected in get_item_val") panic!("struct variant kind unexpected in get_item_val")
} }
}; };
assert!(args.len() != 0u); assert!(args.len() != 0u);
@ -2827,7 +2827,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
ast::ItemEnum(_, _) => { ast::ItemEnum(_, _) => {
register_fn(ccx, (*v).span, sym, id, ty) register_fn(ccx, (*v).span, sym, id, ty)
} }
_ => fail!("NodeVariant, shouldn't happen") _ => panic!("NodeVariant, shouldn't happen")
}; };
set_inline_hint(llfn); set_inline_hint(llfn);
llfn llfn

View file

@ -30,7 +30,7 @@ pub fn terminate(cx: Block, _: &str) {
pub fn check_not_terminated(cx: Block) { pub fn check_not_terminated(cx: Block) {
if cx.terminated.get() { if cx.terminated.get() {
fail!("already terminated!"); panic!("already terminated!");
} }
} }
@ -45,7 +45,7 @@ pub fn B<'blk, 'tcx>(cx: Block<'blk, 'tcx>) -> Builder<'blk, 'tcx> {
// terminated, we're saying that trying to add any further statements in the // terminated, we're saying that trying to add any further statements in the
// block is an error. On the other hand, if something is unreachable, that // block is an error. On the other hand, if something is unreachable, that
// means that the block was terminated in some way that we don't want to check // means that the block was terminated in some way that we don't want to check
// for (fail/break/return statements, call to diverging functions, etc), and // for (panic/break/return statements, call to diverging functions, etc), and
// further instructions to the block should simply be ignored. // further instructions to the block should simply be ignored.
pub fn RetVoid(cx: Block) { pub fn RetVoid(cx: Block) {

View file

@ -50,7 +50,7 @@ fn ty_align(ty: Type) -> uint {
let elt = ty.element_type(); let elt = ty.element_type();
ty_align(elt) ty_align(elt)
} }
_ => fail!("ty_align: unhandled type") _ => panic!("ty_align: unhandled type")
} }
} }
@ -80,7 +80,7 @@ fn ty_size(ty: Type) -> uint {
let eltsz = ty_size(elt); let eltsz = ty_size(elt);
len * eltsz len * eltsz
} }
_ => fail!("ty_size: unhandled type") _ => panic!("ty_size: unhandled type")
} }
} }

View file

@ -50,7 +50,7 @@ fn ty_align(ty: Type) -> uint {
let elt = ty.element_type(); let elt = ty.element_type();
ty_align(elt) ty_align(elt)
} }
_ => fail!("ty_size: unhandled type") _ => panic!("ty_size: unhandled type")
} }
} }
@ -80,7 +80,7 @@ fn ty_size(ty: Type) -> uint {
let eltsz = ty_size(elt); let eltsz = ty_size(elt);
len * eltsz len * eltsz
} }
_ => fail!("ty_size: unhandled type") _ => panic!("ty_size: unhandled type")
} }
} }

View file

@ -111,7 +111,7 @@ fn classify_ty(ty: Type) -> Vec<RegClass> {
let elt = ty.element_type(); let elt = ty.element_type();
ty_align(elt) ty_align(elt)
} }
_ => fail!("ty_size: unhandled type") _ => panic!("ty_size: unhandled type")
} }
} }
@ -140,7 +140,7 @@ fn classify_ty(ty: Type) -> Vec<RegClass> {
let eltsz = ty_size(elt); let eltsz = ty_size(elt);
len * eltsz len * eltsz
} }
_ => fail!("ty_size: unhandled type") _ => panic!("ty_size: unhandled type")
} }
} }
@ -235,7 +235,7 @@ fn classify_ty(ty: Type) -> Vec<RegClass> {
i += 1u; i += 1u;
} }
} }
_ => fail!("classify: unhandled type") _ => panic!("classify: unhandled type")
} }
} }
@ -328,7 +328,7 @@ fn llreg_ty(ccx: &CrateContext, cls: &[RegClass]) -> Type {
SSEDs => { SSEDs => {
tys.push(Type::f64(ccx)); tys.push(Type::f64(ccx));
} }
_ => fail!("llregtype: unhandled class") _ => panic!("llregtype: unhandled class")
} }
i += 1u; i += 1u;
} }

Some files were not shown because too many files have changed in this diff Show more