auto merge of #17894 : steveklabnik/rust/fail_to_panic, r=aturon

This in-progress PR implements https://github.com/rust-lang/rust/issues/17489.

I made the code changes in this commit, next is to go through alllllllll the documentation and fix various things.

- Rename column headings as appropriate, `# Panics` for panic conditions and `# Errors` for `Result`s.
- clean up usage of words like 'fail' in error messages

Anything else to add to the list, @aturon ? I think I should leave the actual functions with names like `slice_or_fail` alone, since you'll get to those in your conventions work?

I'm submitting just the code bits now so that we can see it separately, and I also don't want to have to keep re-building rust over and over again if I don't have to 😉 

Listing all the bits so I can remember as I go:

- [x] compiler-rt
- [x] compiletest
- [x] doc
- [x] driver
- [x] etc
- [x] grammar
- [x] jemalloc
- [x] liballoc
- [x] libarena
- [x] libbacktrace
- [x] libcollections
- [x] libcore
- [x] libcoretest
- [x] libdebug
- [x] libflate
- [x] libfmt_macros
- [x] libfourcc
- [x] libgetopts
- [x] libglob
- [x] libgraphviz
- [x] libgreen
- [x] libhexfloat
- [x] liblibc
- [x] liblog
- [x] libnative
- [x] libnum
- [x] librand
- [x] librbml
- [x] libregex
- [x] libregex_macros
- [x] librlibc
- [x] librustc
- [x] librustc_back
- [x] librustc_llvm
- [x] librustdoc
- [x] librustrt
- [x] libsemver
- [x] libserialize
- [x] libstd
- [x] libsync
- [x] libsyntax
- [x] libterm
- [x] libtest
- [x] libtime
- [x] libunicode
- [x] liburl
- [x] libuuid
- [x] llvm
- [x] rt
- [x] test
This commit is contained in:
bors 2014-10-29 20:16:57 +00:00
commit 77f44d4a7b
518 changed files with 1776 additions and 1727 deletions

View File

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

View File

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

View File

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

View File

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

View File

@ -94,9 +94,9 @@ code should need to run is a stack.
`match` being exhaustive has some useful properties. First, if every
possibility is covered by the `match`, adding further variants to the `enum`
in the future will prompt a compilation failure, rather than runtime failure.
in the future will prompt a compilation failure, rather than runtime panic.
Second, it makes cost explicit. In general, only safe way to have a
non-exhaustive match would be to fail the task if nothing is matched, though
non-exhaustive match would be to panic the task if nothing is matched, though
it could fall through if the type of the `match` expression is `()`. This sort
of hidden cost and special casing is against the language's philosophy. It's
easy to ignore certain cases by using the `_` wildcard:

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.
* Using another crate binds the root of _its_ namespace into the user's namespace.
## Why is failure unwinding non-recoverable within a task? Why not try to "catch exceptions"?
## Why is panic unwinding non-recoverable within a task? Why not try to "catch exceptions"?
In short, because too few guarantees could be made about the dynamic environment of the catch block, as well as invariants holding in the unwound heap, to be able to safely resume; we believe that other methods of signalling and logging errors are more appropriate, with tasks playing the role of a "hard" isolation boundary between separate heaps.
Rust provides, instead, three predictable and well-defined options for handling any combination of the three main categories of "catch" logic:
* Failure _logging_ is done by the integrated logging subsystem.
* _Recovery_ after a failure is done by trapping a task failure from _outside_ the task, where other tasks are known to be unaffected.
* _Recovery_ after a panic is done by trapping a task panic from _outside_
the task, where other tasks are known to be unaffected.
* _Cleanup_ of resources is done by RAII-style objects with destructors.
Cleanup through RAII-style destructors is more likely to work than in catch blocks anyways, since it will be better tested (part of the non-error control paths, so executed all the time).

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.
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

View File

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

View File

@ -8,10 +8,10 @@ relates to the Rust type system, and introduce the fundamental library
abstractions for constructing concurrent programs.
Tasks provide failure isolation and recovery. When a fatal error occurs in Rust
code as a result of an explicit call to `fail!()`, an assertion failure, or
code as a result of an explicit call to `panic!()`, an assertion failure, or
another invalid operation, the runtime system destroys the entire task. Unlike
in languages such as Java and C++, there is no way to `catch` an exception.
Instead, tasks may monitor each other for failure.
Instead, tasks may monitor each other to see if they panic.
Tasks use Rust's type system to provide strong memory safety guarantees. In
particular, the type system guarantees that tasks cannot induce a data race
@ -317,19 +317,19 @@ spawn(proc() {
# }
```
# Handling task failure
# Handling task panics
Rust has a built-in mechanism for raising exceptions. The `fail!()` macro
(which can also be written with an error string as an argument: `fail!(
~reason)`) and the `assert!` construct (which effectively calls `fail!()` if a
Rust has a built-in mechanism for raising exceptions. The `panic!()` macro
(which can also be written with an error string as an argument: `panic!(
~reason)`) and the `assert!` construct (which effectively calls `panic!()` if a
boolean expression is false) are both ways to raise exceptions. When a task
raises an exception, the task unwinds its stack—running destructors and
freeing memory along the way—and then exits. Unlike exceptions in C++,
exceptions in Rust are unrecoverable within a single task: once a task fails,
exceptions in Rust are unrecoverable within a single task: once a task panics,
there is no way to "catch" the exception.
While it isn't possible for a task to recover from failure, tasks may notify
each other of failure. The simplest way of handling task failure is with the
While it isn't possible for a task to recover from panicking, tasks may notify
each other if they panic. The simplest way of handling a panic is with the
`try` function, which is similar to `spawn`, but immediately blocks and waits
for the child task to finish. `try` returns a value of type
`Result<T, Box<Any + Send>>`. `Result` is an `enum` type with two variants:
@ -346,7 +346,7 @@ let result: Result<int, Box<std::any::Any + Send>> = task::try(proc() {
if some_condition() {
calculate_result()
} else {
fail!("oops!");
panic!("oops!");
}
});
assert!(result.is_err());
@ -355,18 +355,18 @@ assert!(result.is_err());
Unlike `spawn`, the function spawned using `try` may return a value, which
`try` will dutifully propagate back to the caller in a [`Result`] enum. If the
child task terminates successfully, `try` will return an `Ok` result; if the
child task fails, `try` will return an `Error` result.
child task panics, `try` will return an `Error` result.
[`Result`]: std/result/index.html
> *Note:* A failed task does not currently produce a useful error
> *Note:* A panicked task does not currently produce a useful error
> value (`try` always returns `Err(())`). In the
> future, it may be possible for tasks to intercept the value passed to
> `fail!()`.
> `panic!()`.
But not all failures are created equal. In some cases you might need to abort
But not all panics are created equal. In some cases you might need to abort
the entire program (perhaps you're writing an assert which, if it trips,
indicates an unrecoverable logic error); in other cases you might want to
contain the failure at a certain boundary (perhaps a small piece of input from
contain the panic at a certain boundary (perhaps a small piece of input from
the outside world, which you happen to be processing in parallel, is malformed
such that the processing task cannot proceed).

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
the resulting executable will run all the tests in the crate. A test
is considered successful if its function returns; if the task running
the test fails, through a call to `fail!`, a failed `assert`, or some
the test fails, through a call to `panic!`, a failed `assert`, or some
other (`assert_eq`, ...) means, then the test fails.
When compiling a crate with the `--test` flag `--cfg test` is also
@ -77,7 +77,7 @@ test on windows you can write `#[cfg_attr(windows, ignore)]`.
Tests that are intended to fail can be annotated with the
`should_fail` attribute. The test will be run, and if it causes its
task to fail then the test will be counted as successful; otherwise it
task to panic then the test will be counted as successful; otherwise it
will be counted as a failure. For example:
~~~test_harness

View File

@ -182,7 +182,7 @@ code:
- implement the `Drop` for resource clean-up via a destructor, and use
RAII (Resource Acquisition Is Initialization). This reduces the need
for any manual memory management by users, and automatically ensures
that clean-up is always run, even when the task fails.
that clean-up is always run, even when the task panics.
- ensure that any data stored behind a raw pointer is destroyed at the
appropriate time.
@ -462,7 +462,7 @@ fn start(_argc: int, _argv: *const *const u8) -> int {
// provided by libstd.
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
#[lang = "eh_personality"] extern fn eh_personality() {}
#[lang = "fail_fmt"] fn fail_fmt() -> ! { loop {} }
#[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
# // fn main() {} tricked you, rustdoc!
```
@ -485,7 +485,7 @@ pub extern fn main(argc: int, argv: *const *const u8) -> int {
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
#[lang = "eh_personality"] extern fn eh_personality() {}
#[lang = "fail_fmt"] fn fail_fmt() -> ! { loop {} }
#[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
# // fn main() {} tricked you, rustdoc!
```
@ -504,8 +504,8 @@ The second of these three functions, `eh_personality`, is used by the
failure mechanisms of the compiler. This is often mapped to GCC's
personality function (see the
[libstd implementation](std/rt/unwind/index.html) for more
information), but crates which do not trigger failure can be assured
that this function is never called. The final function, `fail_fmt`, is
information), but crates which do not trigger a panic can be assured
that this function is never called. The final function, `panic_fmt`, is
also used by the failure mechanisms of the compiler.
## Using libcore
@ -565,8 +565,8 @@ pub extern fn dot_product(a: *const u32, a_len: u32,
return ret;
}
#[lang = "fail_fmt"]
extern fn fail_fmt(args: &core::fmt::Arguments,
#[lang = "panic_fmt"]
extern fn panic_fmt(args: &core::fmt::Arguments,
file: &str,
line: uint) -> ! {
loop {}
@ -579,9 +579,9 @@ extern fn fail_fmt(args: &core::fmt::Arguments,
```
Note that there is one extra lang item here which differs from the examples
above, `fail_fmt`. This must be defined by consumers of libcore because the
core library declares failure, but it does not define it. The `fail_fmt`
lang item is this crate's definition of failure, and it must be guaranteed to
above, `panic_fmt`. This must be defined by consumers of libcore because the
core library declares panics, but it does not define it. The `panic_fmt`
lang item is this crate's definition of panic, and it must be guaranteed to
never return.
As can be seen in this example, the core library is intended to provide the
@ -686,7 +686,7 @@ fn main(argc: int, argv: *const *const u8) -> int {
#[lang = "stack_exhausted"] extern fn stack_exhausted() {}
#[lang = "eh_personality"] extern fn eh_personality() {}
#[lang = "fail_fmt"] fn fail_fmt() -> ! { loop {} }
#[lang = "panic_fmt"] fn panic_fmt() -> ! { loop {} }
```
Note the use of `abort`: the `exchange_malloc` lang item is assumed to

View File

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

View File

@ -818,15 +818,15 @@ mod math {
type Complex = (f64, f64);
fn sin(f: f64) -> f64 {
/* ... */
# fail!();
# panic!();
}
fn cos(f: f64) -> f64 {
/* ... */
# fail!();
# panic!();
}
fn tan(f: f64) -> f64 {
/* ... */
# fail!();
# panic!();
}
}
```
@ -1195,12 +1195,12 @@ output slot type would normally be. For example:
```
fn my_err(s: &str) -> ! {
println!("{}", s);
fail!();
panic!();
}
```
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
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
@ -1213,7 +1213,7 @@ were declared without the `!` annotation, the following code would not
typecheck:
```
# fn my_err(s: &str) -> ! { fail!() }
# fn my_err(s: &str) -> ! { panic!() }
fn f(i: int) -> int {
if i == 42 {
@ -2260,7 +2260,7 @@ These types help drive the compiler's analysis
: Allocate memory on the exchange heap.
* `closure_exchange_malloc`
: ___Needs filling in___
* `fail_`
* `panic`
: Abort the program with an error.
* `fail_bounds_check`
: Abort the program with a bounds check error.
@ -2867,11 +2867,11 @@ be assigned to.
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
_failing state_.
_panicked state_.
```{should-fail}
([1, 2, 3, 4])[0];
(["a", "b"])[10]; // fails
(["a", "b"])[10]; // panics
```
### Unary operator expressions
@ -3301,9 +3301,9 @@ enum List<X> { Nil, Cons(X, Box<List<X>>) }
let x: List<int> = Cons(10, box Cons(11, box Nil));
match x {
Cons(_, box Nil) => fail!("singleton list"),
Cons(_, box Nil) => panic!("singleton list"),
Cons(..) => return,
Nil => fail!("empty list")
Nil => panic!("empty list")
}
```
@ -3374,7 +3374,7 @@ match x {
return;
}
_ => {
fail!();
panic!();
}
}
```
@ -3396,7 +3396,7 @@ fn is_sorted(list: &List) -> bool {
Cons(x, ref r @ box Cons(_, _)) => {
match *r {
box Cons(y, _) => (x <= y) && is_sorted(&**r),
_ => fail!()
_ => panic!()
}
}
}
@ -3460,7 +3460,7 @@ may refer to the variables bound within the pattern they follow.
let message = match maybe_digit {
Some(x) if x < 10 => process_digit(x),
Some(x) => process_other(x),
None => fail!()
None => panic!()
};
```
@ -4092,7 +4092,7 @@ cause transitions between the states. The lifecycle states of a task are:
* running
* blocked
* failing
* panicked
* dead
A task begins its lifecycle &mdash; once it has been spawned &mdash; in the
@ -4104,21 +4104,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
&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
some external event or internally, from the evaluation of a `fail!()` macro.
Once *failing*, a task unwinds its stack and transitions to the *dead* state.
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 `panic!()` macro.
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
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
code causes a temporary transition to a *running* state, and allows the
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
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
failure. Once a task has temporarily suspended its unwinding in the *failing*
state, failure occurring from within this destructor results in *hard* failure.
A hard failure currently results in the process aborting.
panics. Once a task has temporarily suspended its unwinding in the *panicking*
state, a panic occurring from within this destructor results in *hard* panic.
A hard panic currently results in the process aborting.
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

View File

@ -169,7 +169,7 @@ directive.
~~~md
```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]
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::Shl,
">>" => 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);
}
}
_ => 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)
}

View File

@ -227,9 +227,9 @@ impl<T: Sync + Send> Drop for Arc<T> {
impl<T: Sync + Send> Weak<T> {
/// Attempts to upgrade this weak reference to a strong reference.
///
/// This method will fail to upgrade this reference if the strong reference
/// count has already reached 0, but if there are still other active strong
/// references this function will return a new strong reference to the data.
/// This method will not upgrade this reference if the strong reference count has already
/// reached 0, but if there are still other active strong references this function will return
/// a new strong reference to the data.
pub fn upgrade(&self) -> Option<Arc<T>> {
// 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.

View File

@ -148,11 +148,11 @@ mod test {
match a.downcast::<uint>() {
Ok(a) => { assert!(a == box 8u); }
Err(..) => fail!()
Err(..) => panic!()
}
match b.downcast::<Test>() {
Ok(a) => { assert!(a == box Test); }
Err(..) => fail!()
Err(..) => panic!()
}
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
/// chunks, and uses the tydesc information to trace through the objects,
/// 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
/// uninitialized objects, but how to detect them is somewhat subtle. Since
/// `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
// 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.
#[inline]
fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> uint {
@ -337,10 +337,9 @@ fn test_arena_destructors_fail() {
// things interesting.
arena.alloc(|| { [0u8, 1u8, 2u8] });
}
// Now, fail while allocating
// Now, panic while allocating
arena.alloc::<Rc<int>>(|| {
// Now fail.
fail!();
panic!();
});
}

View File

@ -68,7 +68,7 @@ pub struct Node<K, V> {
impl<K: Ord, V> Node<K, V> {
/// 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.
pub fn search(&self, key: &K) -> SearchResult {
// 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 {
match (last_ptr, node_ptr.prev.resolve_immut()) {
(None , None ) => {}
(None , _ ) => fail!("prev link for list_head"),
(None , _ ) => panic!("prev link for list_head"),
(Some(p), Some(pptr)) => {
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 {
Some(ref next) => {

View File

@ -527,8 +527,8 @@ pub fn fixme_14344_be_sure_to_link_to_collections() {}
#[cfg(not(test))]
mod std {
pub use core::fmt; // necessary for fail!()
pub use core::option; // necessary for fail!()
pub use core::fmt; // necessary for panic!()
pub use core::option; // necessary for panic!()
pub use core::clone; // deriving(Clone)
pub use core::cmp; // deriving(Eq, Ord, etc.)
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 {
let idx = self.raw_index(i);
match *self.elts.get_mut(idx) {
None => fail!(),
None => panic!(),
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 {
let idx = self.raw_index(*i);
match self.elts[idx] {
None => fail!(),
None => panic!(),
Some(ref v) => v,
}
}

View File

@ -1181,7 +1181,7 @@ mod tests {
3 => assert!(v == [2, 3, 1]),
4 => assert!(v == [2, 1, 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] = [];
v.sort();
@ -1545,7 +1545,7 @@ mod tests {
#[should_fail]
fn test_from_fn_fail() {
Vec::from_fn(100, |v| {
if v == 50 { fail!() }
if v == 50 { panic!() }
box 0i
});
}
@ -1562,7 +1562,7 @@ mod tests {
impl Clone for S {
fn clone(&self) -> S {
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() }
}
}
@ -1577,7 +1577,7 @@ mod tests {
let mut v = vec![];
v.grow_fn(100, |i| {
if i == 50 {
fail!()
panic!()
}
(box 0i, Rc::new(0i))
})
@ -1591,7 +1591,7 @@ mod tests {
let mut i = 0u;
for _ in v.permutations() {
if i == 2 {
fail!()
panic!()
}
i += 1;
}
@ -2189,7 +2189,7 @@ mod bench {
sum += *x;
}
// 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));
let new = 100;
match m.find_mut(&5) {
None => fail!(), Some(x) => *x = new
None => panic!(), Some(x) => *x = new
}
assert_eq!(m.find(&5), Some(&new));
}

View File

@ -1367,7 +1367,7 @@ mod tests {
// original problem code path anymore.)
let s = String::from_str("");
let _bytes = s.as_bytes();
fail!();
panic!();
}
#[test]
@ -1586,7 +1586,7 @@ mod tests {
let len = c.encode_utf8(bytes).unwrap_or(0);
let s = ::core::str::from_utf8(bytes[..len]).unwrap();
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 s = ::core::str::from_utf8(bytes[..len]).unwrap();
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");
/// ```
#[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) {
assert!(self.as_slice().is_char_boundary(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
/// buffer.
///
/// # Failure
/// # Panics
///
/// If `idx` does not lie on a character boundary, then this function will
/// fail.
/// panic.
///
/// # Example
///
@ -559,7 +559,7 @@ impl String {
/// assert_eq!(s.remove(0), Some('o'));
/// 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"]
pub fn remove(&mut self, idx: uint) -> Option<char> {
let len = self.len();
@ -582,11 +582,11 @@ impl String {
/// This is a O(n) operation as it requires copying every element in the
/// buffer.
///
/// # Failure
/// # Panics
///
/// If `idx` does not lie on a character boundary or is out of bounds, then
/// this function will fail.
#[unstable = "the failure semantics of this function are uncertain"]
/// this function will panic.
#[unstable = "the panic semantics of this function are uncertain"]
pub fn insert(&mut self, idx: uint, ch: char) {
let len = self.len();
assert!(idx <= len);

View File

@ -490,7 +490,7 @@ impl<K, V> TreeMap<K, V> {
/// let new_ua = "Safari/156.0";
/// match t.find_with_mut(|k| "User-Agent".cmp(k)) {
/// Some(x) => *x = new_ua,
/// None => fail!(),
/// None => panic!(),
/// }
///
/// 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() {
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));
let new = 100;
match m.find_mut(&5) {
None => fail!(), Some(x) => *x = new
None => panic!(), Some(x) => *x = new
}
assert_eq!(m.find(&5), Some(&new));
}
@ -1739,7 +1739,7 @@ mod test_treemap {
assert!(m.insert("t5", 14));
let new = 100;
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));
}

View File

@ -834,7 +834,7 @@ fn insert<T>(count: &mut uint, child: &mut Child<T>, key: uint, value: T,
*child = Internal(new);
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 => {
match mem::replace(child, Nothing) {
External(_, value) => (Some(value), true),
_ => fail!()
_ => panic!()
}
}
External(..) => (None, false),
@ -1057,7 +1057,7 @@ mod test_map {
assert!(m.insert(5u, 14i));
let new = 100;
match m.find_mut(&5) {
None => fail!(), Some(x) => *x = new
None => panic!(), Some(x) => *x = 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) {
if self.cap - self.len < 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)
}
}
@ -699,12 +699,12 @@ impl<T> Vec<T> {
/// vec.truncate(2);
/// assert_eq!(vec, vec![1, 2]);
/// ```
#[unstable = "waiting on failure semantics"]
#[unstable = "waiting on panic semantics"]
pub fn truncate(&mut self, len: uint) {
unsafe {
// drop any extra elements
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.
self.len -= 1;
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
/// 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).
///
/// # Example
@ -974,7 +974,7 @@ impl<T> Vec<T> {
/// vec.insert(4, 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) {
let len = self.len();
assert!(index <= len);
@ -1011,7 +1011,7 @@ impl<T> Vec<T> {
/// // v is unchanged:
/// 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> {
let len = self.len();
if index < len {
@ -1353,7 +1353,7 @@ impl<T: PartialEq> Vec<T> {
pub fn dedup(&mut self) {
unsafe {
// 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.
//
// 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 {
let old_size = self.cap * mem::size_of::<T>();
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 {
self.ptr = alloc_or_realloc(self.ptr, old_size, size);
}
@ -1877,7 +1877,7 @@ impl<T> Vec<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`.
pv.start_t = pv.start_t.offset(1);
@ -1888,9 +1888,9 @@ impl<T> Vec<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);
ptr::write(pv.end_u, u);
@ -1901,7 +1901,7 @@ impl<T> Vec<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`.
pv.end_u = pv.end_u.offset(1);
@ -1912,7 +1912,7 @@ impl<T> Vec<T> {
// +-+-+-+-+-+-+-+-+-+
// | |
// end_u end_t
// We may fail again.
// We may panic again.
}
}
@ -1926,10 +1926,10 @@ impl<T> Vec<T> {
// end_u
// Extract `vec` and prevent the destructor of
// `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
// allocations -- and it is returned from this function. None of
// this can fail.
// this can panic.
unsafe {
let vec_len = pv.vec.len();
let vec_cap = pv.vec.capacity();
@ -1953,24 +1953,24 @@ impl<T> Vec<T> {
while pv.num_t != 0 {
unsafe {
// 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.
let t = mem::uninitialized();
pv.num_t -= 1;
// The function given by the user might fail.
// The function given by the user might panic.
let u = f(t);
// Forget the `U` and increment `num_u`. This increment
// cannot overflow the `uint` as we only do this for a
// 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);
pv.num_u += 1;
}
}
// 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();
unsafe { result.set_len(pv.num_u); }
result
@ -2292,7 +2292,7 @@ mod tests {
fn drop(&mut self) {
let BadElem(ref mut x) = *self;
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),
Relaxed => intrinsics::atomic_store_relaxed(dst, val),
SeqCst => intrinsics::atomic_store(dst, val),
Acquire => fail!("there is no such thing as an acquire store"),
AcqRel => fail!("there is no such thing as an acquire/release store"),
Acquire => panic!("there is no such thing as an acquire 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),
Relaxed => intrinsics::atomic_load_relaxed(dst),
SeqCst => intrinsics::atomic_load(dst),
Release => fail!("there is no such thing as a release load"),
AcqRel => fail!("there is no such thing as an acquire/release load"),
Release => panic!("there is no such thing as a 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(),
AcqRel => intrinsics::atomic_fence_acqrel(),
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
//! dynamic it is possible to attempt to borrow a value that is
//! already mutably borrowed; when this happens it results in task
//! failure.
//! panic.
//!
//! # When to choose interior mutability
//!
@ -109,7 +109,7 @@
//! // Recursive call to return the just-cached value.
//! // Note that if we had not let the previous borrow
//! // 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`.
//! self.minimum_spanning_tree()
//! }
@ -281,7 +281,7 @@ impl<T> RefCell<T> {
pub fn borrow<'a>(&'a self) -> Ref<'a, T> {
match self.try_borrow() {
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> {
match self.try_borrow_mut() {
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]
pub fn to_digit(c: char, radix: uint) -> Option<uint> {
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 {
'0' ... '9' => c as uint - ('0' as uint),
@ -147,7 +147,7 @@ pub fn to_digit(c: char, radix: uint) -> Option<uint> {
#[inline]
pub fn from_digit(num: uint, radix: uint) -> Option<char> {
if radix > 36 {
fail!("from_digit: radix is too high (maximum 36)");
panic!("from_digit: radix is to high (maximum 36)");
}
if num < radix {
unsafe {

View File

@ -1,69 +0,0 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Failure support for libcore
//!
//! The core library cannot define failure, but it does *declare* failure. This
//! means that the functions inside of libcore are allowed to fail, but to be
//! useful an upstream crate must define failure for libcore to use. The current
//! interface for failure is:
//!
//! ```ignore
//! fn fail_impl(fmt: &fmt::Arguments, &(&'static str, uint)) -> !;
//! ```
//!
//! This definition allows for failing with any general message, but it does not
//! allow for failing with a `~Any` value. The reason for this is that libcore
//! is not allowed to allocate.
//!
//! This module contains a few other failure functions, but these are just the
//! necessary lang items for the compiler. All failure is funneled through this
//! one function. Currently, the actual symbol is declared in the standard
//! library, but the location of this may change over time.
#![allow(dead_code, missing_doc)]
use fmt;
use intrinsics;
#[cold] #[inline(never)] // this is the slow path, always
#[lang="fail"]
pub fn fail(expr_file_line: &(&'static str, &'static str, uint)) -> ! {
let (expr, file, line) = *expr_file_line;
let ref file_line = (file, line);
format_args!(|args| -> () {
fail_fmt(args, file_line);
}, "{}", expr);
unsafe { intrinsics::abort() }
}
#[cold] #[inline(never)]
#[lang="fail_bounds_check"]
fn fail_bounds_check(file_line: &(&'static str, uint),
index: uint, len: uint) -> ! {
format_args!(|args| -> () {
fail_fmt(args, file_line);
}, "index out of bounds: the len is {} but the index is {}", len, index);
unsafe { intrinsics::abort() }
}
#[cold] #[inline(never)]
pub fn fail_fmt(fmt: &fmt::Arguments, file_line: &(&'static str, uint)) -> ! {
#[allow(ctypes)]
extern {
#[lang = "fail_fmt"]
fn fail_impl(fmt: &fmt::Arguments, file: &'static str,
line: uint) -> !;
}
let (file, line) = *file_line;
unsafe { fail_impl(fmt, file, line) }
}

View File

@ -60,7 +60,7 @@ impl<T> Finally<T> for fn() -> T {
/**
* 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
* `mutate` and `drop` are used to thread state through the two
* 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
* 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.
*
* # Example

View File

@ -94,7 +94,7 @@ pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
assert!(2 <= radix && radix <= 36);
match exp_format {
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),
_ => ()
}
@ -127,7 +127,7 @@ pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
ExpDec => {
let (exp, exp_base) = match exp_format {
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())
@ -299,7 +299,7 @@ pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
buf[end] = match exp_format {
ExpDec if exp_upper => 'E',
ExpDec if !exp_upper => 'e',
_ => fail!("unreachable"),
_ => panic!("unreachable"),
} as u8;
end += 1;

View File

@ -92,7 +92,7 @@ macro_rules! radix {
fn digit(&self, x: u8) -> u8 {
match x {
$($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 {
x @ 0 ... 9 => b'0' + x,
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
//! `&fmt::Arguments`, a `&str`, and a `uint`. These three arguments dictate
//! the failure message, the file at which failure was invoked, and the line.
//! It is up to consumers of this core library to define this failure
//! 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 panic
//! function; it is only required to never return.
// Since libcore defines many fundamental lang items, all tests live in a
@ -111,7 +111,7 @@ pub mod atomic;
pub mod bool;
pub mod cell;
pub mod char;
pub mod failure;
pub mod panicking;
pub mod finally;
pub mod iter;
pub mod option;
@ -129,7 +129,7 @@ pub mod fmt;
#[doc(hidden)]
mod core {
pub use failure;
pub use panicking;
}
#[doc(hidden)]

View File

@ -10,15 +10,15 @@
#![macro_escape]
/// Entry point of failure, for details, see std::macros
/// Entry point of task panic, for details, see std::macros
#[macro_export]
macro_rules! fail(
macro_rules! panic(
() => (
fail!("{}", "explicit failure")
panic!("{}", "explicit panic")
);
($msg:expr) => ({
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)*) => ({
// 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,
// 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
// 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
// used inside a dead function. Just `#[allow(dead_code)]` is
@ -40,7 +40,7 @@ macro_rules! fail(
#[inline(always)]
fn _run_fmt(fmt: &::std::fmt::Arguments) -> ! {
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)*)
});
@ -51,12 +51,12 @@ macro_rules! fail(
macro_rules! assert(
($cond:expr) => (
if !$cond {
fail!(concat!("assertion failed: ", stringify!($cond)))
panic!(concat!("assertion failed: ", stringify!($cond)))
}
);
($cond:expr, $($arg:tt)*) => (
if !$cond {
fail!($($arg)*)
panic!($($arg)*)
}
);
)
@ -78,7 +78,7 @@ macro_rules! assert_eq(
let c1 = $cond1;
let c2 = $cond2;
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_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, 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.
pub trait CheckedDiv: Div<Self, Self> {
/// 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`
///
/// # 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`.
///
/// # Example
@ -312,19 +312,19 @@ impl<T> Option<T> {
pub fn expect(self, msg: &str) -> T {
match self {
Some(val) => val,
None => fail!("{}", msg),
None => panic!("{}", msg),
}
}
/// 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
///
/// 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`
/// case explicitly.
///
@ -344,7 +344,7 @@ impl<T> Option<T> {
pub fn unwrap(self) -> T {
match self {
Some(val) => val,
None => fail!("called `Option::unwrap()` on a `None` value"),
None => panic!("called `Option::unwrap()` on a `None` value"),
}
}

116
src/libcore/panicking.rs Normal file
View File

@ -0,0 +1,116 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Panic support for libcore
//!
//! The core library cannot define panicking, but it does *declare* panicking. This
//! means that the functions inside of libcore are allowed to panic, but to be
//! useful an upstream crate must define panicking for libcore to use. The current
//! interface for panicking is:
//!
//! ```ignore
//! fn panic_impl(fmt: &fmt::Arguments, &(&'static str, uint)) -> !;
//! ```
//!
//! This definition allows for panicking with any general message, but it does not
//! allow for failing with a `Box<Any>` value. The reason for this is that libcore
//! is not allowed to allocate.
//!
//! This module contains a few other panicking functions, but these are just the
//! necessary lang items for the compiler. All panics are funneled through this
//! one function. Currently, the actual symbol is declared in the standard
//! library, but the location of this may change over time.
#![allow(dead_code, missing_doc)]
use fmt;
use intrinsics;
// NOTE(stage0): remove after a snapshot
#[cfg(stage0)]
#[cold] #[inline(never)] // this is the slow path, always
#[lang="fail"]
pub fn panic(expr_file_line: &(&'static str, &'static str, uint)) -> ! {
let (expr, file, line) = *expr_file_line;
let ref file_line = (file, line);
format_args!(|args| -> () {
panic_fmt(args, file_line);
}, "{}", expr);
unsafe { intrinsics::abort() }
}
// NOTE(stage0): remove after a snapshot
#[cfg(stage0)]
#[cold] #[inline(never)]
#[lang="fail_bounds_check"]
fn panic_bounds_check(file_line: &(&'static str, uint),
index: uint, len: uint) -> ! {
format_args!(|args| -> () {
panic_fmt(args, file_line);
}, "index out of bounds: the len is {} but the index is {}", len, index);
unsafe { intrinsics::abort() }
}
// NOTE(stage0): remove after a snapshot
#[cfg(stage0)]
#[cold] #[inline(never)]
pub fn panic_fmt(fmt: &fmt::Arguments, file_line: &(&'static str, uint)) -> ! {
#[allow(ctypes)]
extern {
#[lang = "fail_fmt"]
fn panic_impl(fmt: &fmt::Arguments, file: &'static str,
line: uint) -> !;
}
let (file, line) = *file_line;
unsafe { panic_impl(fmt, file, line) }
}
// NOTE(stage0): remove cfg after a snapshot
#[cfg(not(stage0))]
#[cold] #[inline(never)] // this is the slow path, always
#[lang="panic"]
pub fn panic(expr_file_line: &(&'static str, &'static str, uint)) -> ! {
let (expr, file, line) = *expr_file_line;
let ref file_line = (file, line);
format_args!(|args| -> () {
panic_fmt(args, file_line);
}, "{}", expr);
unsafe { intrinsics::abort() }
}
// NOTE(stage0): remove cfg after a snapshot
#[cfg(not(stage0))]
#[cold] #[inline(never)]
#[lang="panic_bounds_check"]
fn panic_bounds_check(file_line: &(&'static str, uint),
index: uint, len: uint) -> ! {
format_args!(|args| -> () {
panic_fmt(args, file_line);
}, "index out of bounds: the len is {} but the index is {}", len, index);
unsafe { intrinsics::abort() }
}
// NOTE(stage0): remove cfg after a snapshot
#[cfg(not(stage0))]
#[cold] #[inline(never)]
pub fn panic_fmt(fmt: &fmt::Arguments, file_line: &(&'static str, uint)) -> ! {
#[allow(ctypes)]
extern {
#[lang = "panic_fmt"]
fn panic_impl(fmt: &fmt::Arguments, file: &'static str,
line: uint) -> !;
}
let (file, line) = *file_line;
unsafe { panic_impl(fmt, file, line) }
}

View File

@ -76,7 +76,7 @@
//! unsafe {
//! let my_num: *mut int = libc::malloc(mem::size_of::<int>() as libc::size_t) as *mut int;
//! if my_num.is_null() {
//! fail!("failed to allocate memory");
//! panic!("failed to allocate memory");
//! }
//! 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).
//!
//! You might instead, if you don't want to handle the error, simply
//! fail, by converting to an `Option` with `ok`, then asserting
//! success with `expect`. This will fail if the write fails, proving
//! panic, by converting to an `Option` with `ok`, then asserting
//! success with `expect`. This will panic if the write fails, proving
//! a marginally useful message indicating why:
//!
//! ```{.no_run}
@ -250,29 +250,29 @@
//! 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
//! errors. Callers should always be able to avoid failure if they
//! `Result` is for recoverable errors; `panic!` is for unrecoverable
//! errors. Callers should always be able to avoid panics if they
//! take the proper precautions, for example, calling `is_some()`
//! 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
//! from a thrown exception. Therefore using failure for error
//! handling requires encapsulating fallible code in a task. Calling
//! the `fail!` macro, or invoking `fail!` indirectly should be
//! avoided as an error reporting strategy. Failure is only for
//! unrecoverable errors and a failing task is typically the sign of
//! from a thrown exception. Therefore using panics for error
//! handling requires encapsulating code that may panic in a task.
//! Calling the `panic!` macro, or invoking `panic!` indirectly should be
//! avoided as an error reporting strategy. Panics is only for
//! unrecoverable errors and a panicking task is typically the sign of
//! a bug.
//!
//! 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.
//!
//! Furthermore, failure may not be recoverable at all, depending on
//! the context. The caller of `fail!` should assume that execution
//! will not resume after failure, that failure is catastrophic.
//! Furthermore, panics may not be recoverable at all, depending on
//! the context. The caller of `panic!` should assume that execution
//! will not resume after the panic, that a panic is catastrophic.
#![stable]
@ -764,9 +764,9 @@ impl<T, E> Result<T, E> {
impl<T, E: Show> Result<T, E> {
/// 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.
///
/// # Example
@ -778,7 +778,7 @@ impl<T, E: Show> Result<T, E> {
///
/// ```{.should_fail}
/// let x: Result<uint, &str> = Err("emergency failure");
/// x.unwrap(); // fails with `emergency failure`
/// x.unwrap(); // panics with `emergency failure`
/// ```
#[inline]
#[unstable = "waiting for conventions"]
@ -786,7 +786,7 @@ impl<T, E: Show> Result<T, E> {
match self {
Ok(t) => t,
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> {
/// 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.
///
/// # Example
///
/// ```{.should_fail}
/// 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 {
match self {
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
}
}

View File

@ -1460,7 +1460,7 @@ pub trait StrSlice for Sized? {
///
/// assert_eq!(s.slice(1, 9), "öwe 老");
///
/// // these will fail:
/// // these will panic:
/// // byte 2 lies within `ö`:
/// // s.slice(2, 3);
///
@ -1832,7 +1832,7 @@ pub trait StrSlice for Sized? {
#[inline(never)]
fn slice_error_fail(s: &str, begin: uint, end: uint) -> ! {
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);
}
@ -1986,8 +1986,8 @@ impl StrSlice for str {
if end_byte.is_none() && count == end { end_byte = Some(self.len()) }
match (begin_byte, end_byte) {
(None, _) => fail!("slice_chars: `begin` is beyond end of string"),
(_, None) => fail!("slice_chars: `end` is beyond end of string"),
(None, _) => panic!("slice_chars: `begin` 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) }
}
}

View File

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

View File

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

View File

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

View File

@ -139,14 +139,14 @@ fn test_unwrap() {
#[test]
#[should_fail]
fn test_unwrap_fail1() {
fn test_unwrap_panic1() {
let x: Option<int> = None;
x.unwrap();
}
#[test]
#[should_fail]
fn test_unwrap_fail2() {
fn test_unwrap_panic2() {
let x: Option<String> = None;
x.unwrap();
}
@ -233,7 +233,7 @@ fn test_collect() {
assert!(v == None);
// 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();

View File

@ -81,7 +81,7 @@ fn test_collect() {
assert!(v == Err(2));
// 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();
assert!(v == Err(1));
@ -113,7 +113,7 @@ pub fn test_unwrap_or_else() {
if msg == "I got this." {
50i
} else {
fail!("BadBad")
panic!("BadBad")
}
}
@ -126,12 +126,12 @@ pub fn test_unwrap_or_else() {
#[test]
#[should_fail]
pub fn test_unwrap_or_else_failure() {
pub fn test_unwrap_or_else_panic() {
fn handler(msg: &'static str) -> int {
if msg == "I got this." {
50i
} else {
fail!("BadBad")
panic!("BadBad")
}
}

View File

@ -61,7 +61,7 @@
//! ];
//! let matches = match getopts(args.tail(), opts) {
//! Ok(m) => { m }
//! Err(f) => { fail!(f.to_string()) }
//! Err(f) => { panic!(f.to_string()) }
//! };
//! if matches.opt_present("h") {
//! print_usage(program.as_slice(), opts);
@ -243,7 +243,7 @@ impl OptGroup {
} = (*self).clone();
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 {
name: Long((long_name)),
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> {
match find_opt(self.opts.as_slice(), Name::from_str(nm)) {
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.
///
/// On success returns `Ok(Matches)`. Use methods such as `opt_present`
/// `opt_str`, etc. to interrogate results. Returns `Err(Fail_)` on
/// failure: use the `Show` implementation of `Fail_` to display
/// `opt_str`, etc. to interrogate results.
/// # Failure
///
/// Returns `Err(Fail_)` on failure: use the `Show` implementation of `Fail_` to display
/// information about it.
pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
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(' ');
}
_ => fail!("the short name should only be 1 ascii char long"),
_ => panic!("the short name should only be 1 ascii char long"),
}
// 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, 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)),
(B, Cr, OverLim) => {
*cont = it(ss.slice(slice_start, last_end));
@ -951,7 +953,7 @@ mod tests {
assert!(m.opt_present("t"));
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());
match getopts(short_args.as_slice(), opts.as_slice()) {
@ -961,7 +963,7 @@ mod tests {
assert!((m.opt_present("t")));
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());
match rs {
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());
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
_ => panic!()
}
let short_args = vec!("-t".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
_ => panic!()
}
}
@ -999,7 +1001,7 @@ mod tests {
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
_ => fail!()
_ => panic!()
}
}
@ -1016,7 +1018,7 @@ mod tests {
assert!((m.opt_present("t")));
assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
}
_ => fail!()
_ => panic!()
}
let short_args = vec!("-t".to_string(), "20".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) {
@ -1026,7 +1028,7 @@ mod tests {
assert!((m.opt_present("t")));
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("t"));
}
_ => fail!()
_ => panic!()
}
}
@ -1051,12 +1053,12 @@ mod tests {
let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
_ => panic!()
}
let short_args = vec!("-t".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
_ => panic!()
}
}
@ -1067,7 +1069,7 @@ mod tests {
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
_ => fail!()
_ => panic!()
}
}
@ -1082,7 +1084,7 @@ mod tests {
assert!(m.opt_present("test"));
assert!(m.opt_present("t"));
}
_ => fail!()
_ => panic!()
}
let short_args = vec!("-t".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) {
@ -1090,7 +1092,7 @@ mod tests {
assert!(m.opt_present("test"));
assert!(m.opt_present("t"));
}
_ => fail!()
_ => panic!()
}
}
@ -1104,7 +1106,7 @@ mod tests {
assert!(!m.opt_present("test"));
assert!(!m.opt_present("t"));
}
_ => fail!()
_ => panic!()
}
}
@ -1117,7 +1119,7 @@ mod tests {
Err(f) => {
check_fail_type(f, UnexpectedArgument_);
}
_ => fail!()
_ => panic!()
}
}
@ -1128,7 +1130,7 @@ mod tests {
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
_ => fail!()
_ => panic!()
}
}
@ -1143,7 +1145,7 @@ mod tests {
assert!(m.free[0] == "20".to_string());
}
_ => fail!()
_ => panic!()
}
}
@ -1157,7 +1159,7 @@ mod tests {
Ok(ref m) => {
assert_eq!(m.opt_count("v"), 1);
}
_ => fail!()
_ => panic!()
}
}
@ -1170,7 +1172,7 @@ mod tests {
Ok(ref m) => {
assert_eq!(m.opt_count("v"), 2);
}
_ => fail!()
_ => panic!()
}
}
@ -1183,7 +1185,7 @@ mod tests {
Ok(ref m) => {
assert_eq!(m.opt_count("v"), 2);
}
_ => fail!()
_ => panic!()
}
}
@ -1196,7 +1198,7 @@ mod tests {
Ok(ref m) => {
assert_eq!(m.opt_count("verbose"), 1);
}
_ => fail!()
_ => panic!()
}
}
@ -1209,7 +1211,7 @@ mod tests {
Ok(ref m) => {
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("v"), 4);
}
_ => fail!()
_ => panic!()
}
}
@ -1241,7 +1243,7 @@ mod tests {
assert!((m.opt_present("t")));
assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
}
_ => fail!()
_ => panic!()
}
let short_args = vec!("-t".to_string(), "20".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) {
@ -1251,7 +1253,7 @@ mod tests {
assert!((m.opt_present("t")));
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("t"));
}
_ => fail!()
_ => panic!()
}
}
@ -1276,12 +1278,12 @@ mod tests {
let rs = getopts(long_args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
_ => panic!()
}
let short_args = vec!("-t".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
_ => panic!()
}
}
@ -1300,7 +1302,7 @@ mod tests {
assert!(pair[0] == "20".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());
match rs {
Err(f) => check_fail_type(f, UnrecognizedOption_),
_ => fail!()
_ => panic!()
}
let short_args = vec!("-u".to_string());
match getopts(short_args.as_slice(), opts.as_slice()) {
Err(f) => check_fail_type(f, UnrecognizedOption_),
_ => fail!()
_ => panic!()
}
}
@ -1365,7 +1367,7 @@ mod tests {
assert!(pair[1] == "-60 70".to_string());
assert!((!m.opt_present("notpresent")));
}
_ => fail!()
_ => panic!()
}
}
@ -1379,7 +1381,7 @@ mod tests {
let matches_single = &match getopts(args_single.as_slice(),
opts.as_slice()) {
result::Ok(m) => m,
result::Err(_) => fail!()
result::Err(_) => panic!()
};
assert!(matches_single.opts_present(["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(),
opts.as_slice()) {
result::Ok(m) => m,
result::Err(_) => fail!()
result::Err(_) => panic!()
};
assert!(matches_both.opts_present(["e".to_string()]));
assert!(matches_both.opts_present(["encrypt".to_string()]));
@ -1424,7 +1426,7 @@ mod tests {
optmulti("M", "", "something", "MMMM"));
let matches = &match getopts(args.as_slice(), opts.as_slice()) {
result::Ok(m) => m,
result::Err(_) => fail!()
result::Err(_) => panic!()
};
assert!(matches.opts_present(["L".to_string()]));
assert_eq!(matches.opts_str(["L".to_string()]).unwrap(), "foo".to_string());
@ -1440,7 +1442,7 @@ mod tests {
optflagmulti("v", "verbose", "Verbose"));
let matches = &match getopts(args.as_slice(), opts.as_slice()) {
result::Ok(m) => m,
result::Err(e) => fail!( "{}", e )
result::Err(e) => panic!( "{}", e )
};
assert!(matches.opts_present(["L".to_string()]));
assert_eq!(matches.opts_str(["L".to_string()]).unwrap(), "verbose".to_string());

View File

@ -73,13 +73,13 @@ impl BasicLoop {
RunRemote(i) => {
match self.remotes.iter_mut().find(|& &(id, _)| id == i) {
Some(&(_, ref mut f)) => f.call(),
None => fail!("bad remote: {}", i),
None => panic!("bad remote: {}", i),
}
}
RemoveRemote(i) => {
match self.remotes.iter().position(|&(id, _)| id == i) {
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
// stack limit in the OS-specified TLS slot. This also means that
// 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`
// is a C function so we don't have to worry about that!
match in_context.stack_bounds {
Some((lo, hi)) => stack::record_rust_managed_stack_bounds(lo, hi),
// If we're going back to one of the original contexts or
// 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),
}
rust_swap_registers(out_regs, in_regs);

View File

@ -168,7 +168,7 @@
//! drop(handle);
//!
//! // 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();
//! # }
//! ```
@ -511,7 +511,7 @@ impl TaskState {
impl Drop for SchedPool {
fn drop(&mut self) {
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
// context switching will bounce on the lock, thereby waiting for this
// 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 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);
sched.task_state.decrement();
});
fail!("should never return!");
panic!("should never return!");
}
pub fn run_task(self: Box<Scheduler>,
@ -1054,7 +1054,7 @@ mod test {
task.put_runtime(green);
return ret;
}
None => fail!()
None => panic!()
}
}
@ -1202,8 +1202,8 @@ mod test {
}))) => {
*id == sched_id
}
TypeGreen(None) => { fail!("task without home"); }
TypeSched => { fail!("expected green task"); }
TypeGreen(None) => { panic!("task without home"); }
TypeSched => { panic!("expected green task"); }
};
task.put();
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
// really do a whole lot. The only purpose of the task is to get us off our
// feet and running.
fn yield_now(self: Box<SimpleTask>, _cur_task: Box<Task>) { fail!() }
fn maybe_yield(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>) { panic!() }
fn spawn_sibling(self: Box<SimpleTask>,
_cur_task: Box<Task>,
_opts: TaskOpts,
_f: proc():Send) {
fail!()
panic!()
}
fn local_io<'a>(&'a mut self) -> Option<rtio::LocalIo<'a>> { None }
fn stack_bounds(&self) -> (uint, uint) { fail!() }
fn stack_guard(&self) -> Option<uint> { fail!() }
fn stack_bounds(&self) -> (uint, uint) { panic!() }
fn stack_guard(&self) -> Option<uint> { panic!() }
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> {

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
// 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
// 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
// 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;
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.
pub fn new(size: uint) -> 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,
MapNonStandardFlags(STACK_FLAGS)]) {
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;
@ -55,7 +55,7 @@ impl Stack {
// page. It isn't guaranteed, but that's why FFI is unsafe. buf.data is
// guaranteed to be aligned properly.
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());
}

View File

@ -443,7 +443,7 @@ impl Runtime for GreenTask {
self.put_task(cur_task);
// 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.
struct Bomb { inner: Option<Box<GreenTask>> }
impl Drop for Bomb {
@ -529,11 +529,11 @@ mod tests {
}
#[test]
fn smoke_fail() {
fn smoke_panic() {
let (tx, rx) = channel::<int>();
spawn_opts(TaskOpts::new(), proc() {
let _tx = tx;
fail!()
panic!()
});
assert_eq!(rx.recv_opt(), Err(()));
}
@ -550,11 +550,11 @@ mod tests {
}
#[test]
fn smoke_opts_fail() {
fn smoke_opts_panic() {
let mut opts = TaskOpts::new();
let (tx, rx) = channel();
opts.on_exit = Some(proc(r) tx.send(r));
spawn_opts(opts, proc() { fail!() });
spawn_opts(opts, proc() { panic!() });
assert!(rx.recv().is_err());
}
@ -597,7 +597,7 @@ mod tests {
Some(ops) => {
task.put_runtime(ops);
}
None => fail!(),
None => panic!(),
}
Local::put(task);
tx.send(());

View File

@ -255,7 +255,7 @@ impl Logger for DefaultLogger {
record.level,
record.module_path,
record.args) {
Err(e) => fail!("failed to log: {}", e),
Err(e) => panic!("failed to log: {}", e),
Ok(()) => {}
}
}
@ -263,9 +263,9 @@ impl Logger for DefaultLogger {
impl Drop for DefaultLogger {
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() {
Err(e) => fail!("failed to flush a logger: {}", e),
Err(e) => panic!("failed to flush a logger: {}", e),
Ok(()) => {}
}
}

View File

@ -523,7 +523,7 @@ mod tests {
assert_eq!(buf[2], 's' 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());
@ -547,7 +547,7 @@ mod tests {
assert_eq!(buf[2], 's' 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 {
let ret = Err(super::last_error());
// 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) };
assert!(err != 0);
return ret;

View File

@ -600,7 +600,7 @@ fn spawn_process_os(cfg: ProcessConfig,
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
@ -944,7 +944,7 @@ fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> {
let mut status = 0 as c_int;
if deadline == 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)),
}
}
@ -1069,7 +1069,7 @@ fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> {
continue
}
n => fail!("error in select {} ({})", os::errno(), n),
n => panic!("error in select {} ({})", os::errno(), n),
}
// Process any pending messages
@ -1149,7 +1149,7 @@ fn waitpid(pid: pid_t, deadline: u64) -> IoResult<rtio::ProcessExit> {
n if n > 0 => { ret = true; }
0 => return true,
-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 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)),
0 => None,
n => fail!("unknown waitpid error `{}`: {}", n,
n => panic!("unknown waitpid error `{}`: {}", n,
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 => {}
n => fail!("helper thread failed in select() with error: {} ({})",
n => panic!("helper thread panicked in select() with error: {} ({})",
n, os::last_os_error())
}
}
@ -227,7 +227,7 @@ impl Timer {
};
while unsafe { libc::nanosleep(&to_sleep, &mut to_sleep) } != 0 {
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()));
}).destroy());
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);
}

View File

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

View File

@ -129,7 +129,7 @@ impl<'a, T: Clone> WeightedChoice<'a, T> {
for item in items.iter_mut() {
running_total = match running_total.checked_add(&item.weight) {
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")
};

View File

@ -92,7 +92,7 @@ pub trait Rng {
/// not be relied upon.
///
/// 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
/// source of randomness).
///
@ -375,7 +375,7 @@ impl Rng 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]) {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng.reseed called with an all zero seed.");
@ -386,7 +386,7 @@ impl SeedableRng<[u32, .. 4]> for XorShiftRng {
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 {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng::from_seed called with an all zero seed.");
@ -446,7 +446,7 @@ pub struct Closed01<F>(pub F);
#[cfg(not(test))]
mod std {
pub use core::{option, fmt}; // fail!()
pub use core::{option, fmt}; // panic!()
}
#[cfg(test)]

View File

@ -244,7 +244,7 @@ pub mod reader {
Some(d) => d,
None => {
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
/// `i` to `pc1` and `pc2`, respectively.
/// If the instruction at index `i` isn't a `Split` instruction, then
/// `fail!` is called.
/// `panic!` is called.
#[inline]
fn set_split(&mut self, i: InstIdx, pc1: InstIdx, pc2: InstIdx) {
let split = self.insts.get_mut(i);
match *split {
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`.
/// If the instruction at index `i` isn't a `Jump` instruction, then
/// `fail!` is called.
/// `panic!` is called.
#[inline]
fn set_jump(&mut self, i: InstIdx, pc: InstIdx) {
let jmp = self.insts.get_mut(i);
match *jmp {
Jump(_) => *jmp = Jump(pc),
_ => fail!("BUG: Invalid jump index."),
_ => panic!("BUG: Invalid jump index."),
}
}
}

View File

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

View File

@ -117,7 +117,7 @@ impl BuildAst {
fn flags(&self) -> Flags {
match *self {
Paren(flags, _, _) => flags,
_ => fail!("Cannot get flags from {}", self),
_ => panic!("Cannot get flags from {}", self),
}
}
@ -125,7 +125,7 @@ impl BuildAst {
match *self {
Paren(_, 0, _) => None,
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())
}
}
_ => 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> {
match self {
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 {
'?' => ZeroOne, '*' => ZeroMore, '+' => OneMore,
_ => fail!("Not a valid repeater operator."),
_ => panic!("Not a valid repeater operator."),
};
match self.peek(1) {
@ -389,7 +389,7 @@ impl<'a> Parser<'a> {
continue
}
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.
None => {},
},
@ -404,7 +404,7 @@ impl<'a> Parser<'a> {
return self.err(
"\\A, \\z, \\b and \\B are not valid escape \
sequences inside a character class."),
ast => fail!("Unexpected AST item '{}'", ast),
ast => panic!("Unexpected AST item '{}'", ast),
}
}
']' if ranges.len() > 0 || alts.len() > 0 => {

View File

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

View File

@ -15,7 +15,7 @@ use stdtest::Bencher;
use regex::{Regex, NoExpand};
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]
@ -143,7 +143,7 @@ macro_rules! throughput(
fn $name(b: &mut Bencher) {
let text = gen_text($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) => (
match ::regex::Regex::new($re) {
Ok(re) => re,
Err(err) => fail!("{}", err),
Err(err) => panic!("{}", err),
}
);
)

View File

@ -99,7 +99,7 @@ macro_rules! noparse(
let re = $re;
match Regex::new(re) {
Err(_) => {},
Ok(_) => fail!("Regex '{}' should cause a parse error.", re),
Ok(_) => panic!("Regex '{}' should cause a parse error.", re),
}
}
);
@ -161,7 +161,7 @@ macro_rules! mat(
sgot = sgot[0..sexpect.len()]
}
if sexpect != sgot {
fail!("For RE '{}' against '{}', expected '{}' but got '{}'",
panic!("For RE '{}' against '{}', expected '{}' but got '{}'",
$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
// 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)]
struct SharedEmitter {
buffer: Arc<Mutex<Vec<Diagnostic>>>,
@ -133,7 +133,7 @@ impl Emitter for SharedEmitter {
fn custom_emit(&mut self, _cm: &codemap::CodeMap,
_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);
}
let mut failed = false;
let mut panicked = false;
for future in futures.into_iter() {
match future.unwrap() {
Ok(()) => {},
Err(_) => {
failed = true;
panicked = true;
},
}
// Display any new diagnostics.
diag_emitter.dump(sess.diagnostic().handler());
}
if failed {
sess.fatal("aborting due to worker thread failure");
if panicked {
sess.fatal("aborting due to worker thread panic");
}
}

View File

@ -898,7 +898,7 @@ mod test {
let matches =
&match getopts(["--test".to_string()], optgroups().as_slice()) {
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 sessopts = build_session_options(matches);
@ -916,7 +916,7 @@ mod test {
optgroups().as_slice()) {
Ok(m) => m,
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([]);

View File

@ -269,7 +269,7 @@ Available lint options:
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.");
}
(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, l, g) => {
if l > 0 {
@ -424,7 +424,7 @@ fn parse_crate_attrs(sess: &Session, input: &Input) ->
pub fn early_error(msg: &str) -> ! {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
emitter.emit(None, msg, None, diagnostic::Fatal);
fail!(diagnostic::FatalError);
panic!(diagnostic::FatalError);
}
pub fn early_warn(msg: &str) {
@ -466,7 +466,7 @@ pub fn monitor(f: proc():Send) {
match task.try(f) {
Ok(()) => { /* fallthrough */ }
Err(value) => {
// Task failed without emitting a fatal diagnostic
// Task panicked without emitting a fatal diagnostic
if !value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
@ -475,13 +475,13 @@ pub fn monitor(f: proc():Send) {
if !value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected failure",
"unexpected panic",
None,
diagnostic::Bug);
}
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: {}",
BUG_REPORT_URL),
"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
// printed everything that we needed to.
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);
match r {
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),
}
}

View File

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

View File

@ -166,7 +166,7 @@ impl LintStore {
fn register_renamed(&mut self, old_name: &str, new_name: &str) {
let target = match self.by_name.find_equiv(&new_name) {
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));
}
@ -388,7 +388,7 @@ pub fn raw_emit_lint(sess: &Session, lint: &'static Lint,
format!("{} [-{} {}]", msg,
match level {
Warn => 'W', Deny => 'D', Forbid => 'F',
Allow => fail!()
Allow => panic!()
}, name.replace("_", "-"))
},
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>) {
let err = |s: &str| {
match (sp, sess) {
(_, None) => fail!("{}", s),
(_, None) => panic!("{}", s),
(Some(sp), Some(sess)) => sess.span_err(sp, 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> {
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
}
}
@ -153,7 +153,7 @@ fn item_family(item: rbml::Doc) -> Family {
'S' => Struct,
'g' => PublicField,
'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 {
'y' => ast::Public,
'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 {
'i' => ast::MutImmutable,
'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,
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) {
'r' | 'p' => impl_items.push(ty::MethodTraitItemId(def_id)),
't' => impl_items.push(ty::TypeTraitItemId(def_id)),
_ => fail!("unknown impl item sort"),
_ => panic!("unknown impl item sort"),
}
true
});
@ -760,7 +760,7 @@ pub fn get_trait_item_name_and_kind(intr: Rc<IdentInterner>,
}
't' => (name, TypeTraitItemKind),
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)
}
}
@ -811,7 +811,7 @@ pub fn get_impl_or_trait_item(intr: Rc<IdentInterner>,
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) {
'r' | 'p' => result.push(ty::MethodTraitItemId(def_id)),
't' => result.push(ty::TypeTraitItemId(def_id)),
_ => fail!("unknown trait item sort"),
_ => panic!("unknown trait item sort"),
}
true
});
@ -937,7 +937,7 @@ pub fn get_static_methods_if_impl(intr: Rc<IdentInterner>,
match item_family(impl_method_doc) {
StaticMethod => fn_style = ast::NormalFn,
UnsafeStaticMethod => fn_style = ast::UnsafeFn,
_ => fail!()
_ => panic!()
}
static_impl_methods.push(StaticMethodInfo {
@ -998,7 +998,7 @@ fn struct_field_family_to_visibility(family: Family) -> ast::Visibility {
match family {
PublicField => ast::Public,
InheritedField => ast::Inherited,
_ => fail!()
_ => panic!()
}
}
@ -1207,7 +1207,7 @@ pub fn translate_def_id(cdata: Cmd, did: ast::DefId) -> ast::DefId {
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 = match cdata.cnum_map.find(&cnum) {
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" {
cstore::RequireDynamic

View File

@ -187,13 +187,13 @@ pub fn get_or_default_sysroot() -> Path {
path.and_then(|path|
match myfs::realpath(&path) {
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()) {
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(
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)
}
'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' => {
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) {
'n' => None,
'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),
'f' => return ty::mk_mach_float(ast::TyF32),
'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(),
@ -474,7 +474,7 @@ fn parse_ty(st: &mut PState, conv: conv_did) -> ty::t {
'e' => {
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 {
'u' => UnsafeFn,
'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 {
'o' => ast::Once,
'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) {
'V' => true,
'N' => false,
r => fail!(format!("bad variadic: {}", r)),
r => panic!(format!("bad variadic: {}", r)),
};
let output = match peek(st) {
'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; }
if colon_idx == len {
error!("didn't find ':' when parsing def id");
fail!();
panic!();
}
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) {
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)
};
let def_num = match uint::parse_bytes(def_part, 10u) {
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)
};
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;
}
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;
}
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::StmtMac(..) => fail!("unexpanded macro in astencode")
ast::StmtMac(..) => panic!("unexpanded macro in astencode")
};
if use_stmt {
Some(stmt)
@ -795,7 +795,7 @@ impl<'a> vtable_decoder_helpers for reader::Decoder<'a> {
3 => {
typeck::vtable_error
}
_ => fail!("bad enum variant")
_ => panic!("bad enum variant")
})
})
}).unwrap()
@ -1488,7 +1488,7 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> {
}).unwrap()
}
_ => fail!("..")
_ => panic!("..")
})
})
}).unwrap()
@ -1618,7 +1618,7 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> {
ty::AdjustDerefRef(auto_deref_ref)
}
_ => fail!("bad enum variant for ty::AutoAdjustment")
_ => panic!("bad enum variant for ty::AutoAdjustment")
})
})
}).unwrap()
@ -1695,7 +1695,7 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> {
ty::AutoUnsafe(m, a)
}
_ => fail!("bad enum variant for ty::AutoRef")
_ => panic!("bad enum variant for ty::AutoRef")
})
})
}).unwrap()
@ -1736,7 +1736,7 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> {
substs: substs };
ty::UnsizeVtable(ty_trait, self_ty)
}
_ => fail!("bad enum variant for ty::UnsizeKind")
_ => panic!("bad enum variant for ty::UnsizeKind")
})
})
}).unwrap()
@ -1762,7 +1762,7 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> {
0 => ty::FnUnboxedClosureKind,
1 => ty::FnMutUnboxedClosureKind,
2 => ty::FnOnceUnboxedClosureKind,
_ => fail!("bad enum variant for ty::UnboxedClosureKind"),
_ => panic!("bad enum variant for ty::UnboxedClosureKind"),
})
}).unwrap();
ty::UnboxedClosure {
@ -2032,6 +2032,6 @@ fn test_simplification() {
assert!(pprust::item_to_string(&*item_out) ==
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",
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::ExprFnBlock(_, _, ref block) |
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 {
let opt_cfgindex = index.find(&id).map(|&i|i);
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)
}
DefPrimTy(_) => fail!()
DefPrimTy(_) => panic!()
}
}

View File

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

View File

@ -93,7 +93,7 @@
* These are described in the `specials` struct:
*
* - `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
*
@ -400,7 +400,7 @@ fn visit_fn(ir: &mut IrMaps,
visit::walk_fn(&mut fn_maps, fk, decl, body, sp);
// 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
// an implicit return
let specials = Specials {

View File

@ -157,7 +157,7 @@ impl RegionMaps {
//! Returns the narrowest scope that encloses `id`, if any.
match self.scope_map.borrow().find(&id) {
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) {
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> {
match self.get_module_if_available() {
None => {
fail!("get_module called on a node with no module \
panic!("get_module called on a node with no module \
definition!")
}
Some(module_def) => module_def
@ -1910,7 +1910,7 @@ impl<'a> Resolver<'a> {
DefLocal(..) | DefPrimTy(..) | DefTyParam(..) |
DefUse(..) | DefUpvar(..) | DefRegion(..) |
DefTyParamBinder(..) | DefLabel(..) | DefSelfTy(..) => {
fail!("didn't expect `{}`", def);
panic!("didn't expect `{}`", def);
}
}
}
@ -2618,7 +2618,7 @@ impl<'a> Resolver<'a> {
}
UnboundResult => { /* Continue. */ }
UnknownResult => {
fail!("value result should be known at this point");
panic!("value result should be known at this point");
}
}
match type_result {
@ -2641,7 +2641,7 @@ impl<'a> Resolver<'a> {
}
UnboundResult => { /* Continue. */ }
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());
match *target.bindings.value_def.borrow() {
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?!");
}
Some(def) => {
@ -5191,7 +5191,7 @@ impl<'a> Resolver<'a> {
}
Indeterminate => {
fail!("unexpected indeterminate result");
panic!("unexpected indeterminate result");
}
Failed(err) => {
match err {
@ -5389,7 +5389,7 @@ impl<'a> Resolver<'a> {
msg.as_slice()));
return None;
}
Indeterminate => fail!("indeterminate unexpected"),
Indeterminate => panic!("indeterminate unexpected"),
Success((resulting_module, resulting_last_private)) => {
containing_module = resulting_module;
last_private = resulting_last_private;
@ -5451,7 +5451,7 @@ impl<'a> Resolver<'a> {
}
Indeterminate => {
fail!("indeterminate unexpected");
panic!("indeterminate unexpected");
}
Success((resulting_module, resulting_last_private)) => {
@ -5537,7 +5537,7 @@ impl<'a> Resolver<'a> {
}
}
Indeterminate => {
fail!("unexpected indeterminate result");
panic!("unexpected indeterminate result");
}
Failed(err) => {
match err {
@ -6155,7 +6155,7 @@ impl<'a> Resolver<'a> {
type_used: _
}) => (v, t),
Some(_) => {
fail!("we should only have LastImport for `use` directives")
panic!("we should only have LastImport for `use` directives")
}
_ => return,
};

View File

@ -177,7 +177,7 @@ impl Substs {
*/
match self.regions {
ErasedRegions => fail!("Erased regions only expected in trans"),
ErasedRegions => panic!("Erased regions only expected in trans"),
NonerasedRegions(ref r) => r
}
}
@ -190,7 +190,7 @@ impl Substs {
*/
match self.regions {
ErasedRegions => fail!("Erased regions only expected in trans"),
ErasedRegions => panic!("Erased regions only expected in trans"),
NonerasedRegions(ref mut r) => r
}
}
@ -249,7 +249,7 @@ impl ParamSpace {
0 => TypeSpace,
1 => SelfSpace,
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;
match const_eval::compare_lit_exprs(tcx, expr, other_expr) {
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) {
match *self {
Infallible =>
fail!("attempted to fail in an infallible failure handler!"),
panic!("attempted to panic in a non-panicking panic handler!"),
JumpToBasicBlock(basic_block) =>
Br(bcx, basic_block),
Unreachable =>

View File

@ -586,7 +586,7 @@ fn generic_type_of(cx: &CrateContext,
Type::array(&Type::i64(cx), align_units),
a if a.count_ones() == 1 => Type::array(&Type::vector(&Type::i32(cx), a / 4),
align_units),
_ => fail!("unsupported enum alignment: {}", align)
_ => panic!("unsupported enum alignment: {}", align)
};
assert_eq!(machine::llalign_of_min(cx, pad_ty), align);
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,
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);
@ -2349,7 +2349,7 @@ fn register_fn(ccx: &CrateContext,
ty::ty_bare_fn(ref f) => {
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());
@ -2744,7 +2744,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
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(),
@ -2811,7 +2811,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
let args = match v.node.kind {
ast::TupleVariantKind(ref args) => args,
ast::StructVariantKind(_) => {
fail!("struct variant kind unexpected in get_item_val")
panic!("struct variant kind unexpected in get_item_val")
}
};
assert!(args.len() != 0u);
@ -2827,7 +2827,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
ast::ItemEnum(_, _) => {
register_fn(ccx, (*v).span, sym, id, ty)
}
_ => fail!("NodeVariant, shouldn't happen")
_ => panic!("NodeVariant, shouldn't happen")
};
set_inline_hint(llfn);
llfn

View File

@ -30,7 +30,7 @@ pub fn terminate(cx: Block, _: &str) {
pub fn check_not_terminated(cx: Block) {
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
// 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
// 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.
pub fn RetVoid(cx: Block) {

View File

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

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