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);
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 {
Ok(re) => Some(re),
Err(e) => {
println!("failed to parse filter /{}/: {}", s, e);
- fail!()
+ panic!()
}
}
} else {
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);
}
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)
}
})
}
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);
"arm-linux-androideabi" => {
if !config.adb_device_status {
- fail!("android device not available");
+ panic!("android device not available");
}
}
------------------------------------------\n\
\n",
expected, actual);
- fail!();
+ panic!();
}
}
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\
\n",
err, proc_res.status, proc_res.cmdline, proc_res.stdout,
proc_res.stderr);
- fail!();
+ panic!();
}
fn _arm_exec_compiled_test(config: &Config,
return os
}
}
- fail!("Cannot determine OS from triple");
+ panic!("Cannot determine OS from triple");
}
#[cfg(target_os = "windows")]
`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:
* 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).
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
// complicated stuff goes here
return result + val;
},
- _ => fail!("Didn't get good_2")
+ _ => panic!("Didn't get good_2")
}
}
_ => return 0 // default value
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;
# 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;
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
# }
```
-# 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:
if some_condition() {
calculate_result()
} else {
- fail!("oops!");
+ panic!("oops!");
}
});
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).
`--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
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
- 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.
failure mechanisms of the compiler. This is often mapped to GCC's
personality function (see the
[libstd implementation](std/rt/unwind/index.html) for more
-information), but crates which do not trigger failure can be assured
+information), but crates which do not trigger a panic can be assured
that this function is never called. The final function, `fail_fmt`, is
also used by the failure mechanisms of the compiler.
## 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;
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
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!();
}
}
```
```
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
typecheck:
```
-# fn my_err(s: &str) -> ! { fail!() }
+# fn my_err(s: &str) -> ! { panic!() }
fn f(i: int) -> int {
if i == 42 {
: 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.
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
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")
}
```
return;
}
_ => {
- fail!();
+ panic!();
}
}
```
Cons(x, ref r @ box Cons(_, _)) => {
match *r {
box Cons(y, _) => (x <= y) && is_sorted(&**r),
- _ => fail!()
+ _ => panic!()
}
}
}
let message = match maybe_digit {
Some(x) if x < 10 => process_digit(x),
Some(x) => process_other(x),
- None => fail!()
+ None => panic!()
};
```
* running
* blocked
-* failing
+* panicked
* dead
A task begins its lifecycle — once it has been spawned — in the
when a message arrives at a sender, or a buffer opens to receive a message
— 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
~~~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
```
~~~
```test_harness
#[test]
fn foo() {
- fail!("oops! (will run & register as failure)")
+ panic!("oops! (will run & register as a failed test)")
}
```
~~~
"|" => token::Or,
"<<" => token::Shl,
">>" => token::Shr,
- _ => fail!("Bad binop str `{}`", s),
+ _ => panic!("Bad binop str `{}`", s),
}
}
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)
}
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.
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>;
/// 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
// 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 {
// things interesting.
arena.alloc(|| { [0u8, 1u8, 2u8] });
}
- // Now, fail while allocating
+ // Now, panic while allocating
arena.alloc::<Rc<int>>(|| {
- // Now fail.
- fail!();
+ panic!();
});
}
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).
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) => {
#[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)
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
}
}
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,
}
}
3 => assert!(v == [2, 3, 1]),
4 => assert!(v == [2, 1, 3]),
5 => assert!(v == [1, 2, 3]),
- _ => fail!(),
+ _ => panic!(),
}
}
}
}
}
- // shouldn't fail/crash
+ // shouldn't panic
let mut v: [uint, .. 0] = [];
v.sort();
#[should_fail]
fn test_from_fn_fail() {
Vec::from_fn(100, |v| {
- if v == 50 { fail!() }
+ if v == 50 { panic!() }
box 0i
});
}
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() }
}
}
let mut v = vec![];
v.grow_fn(100, |i| {
if i == 50 {
- fail!()
+ panic!()
}
(box 0i, Rc::new(0i))
})
let mut i = 0u;
for _ in v.permutations() {
if i == 2 {
- fail!()
+ panic!()
}
i += 1;
}
sum += *x;
}
// sum == 11806, to stop dead code elimination.
- if sum == 0 {fail!()}
+ if sum == 0 {panic!()}
})
}
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));
}
// original problem code path anymore.)
let s = String::from_str("");
let _bytes = s.as_bytes();
- fail!();
+ panic!();
}
#[test]
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);
}
}
}
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);
}
}
}
/// 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)
/// 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
///
/// 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();
/// 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);
/// 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));
}
}
return match node.take() {
- Some(box TreeNode{value, ..}) => Some(value), None => fail!()
+ Some(box TreeNode{value, ..}) => Some(value), None => panic!()
};
}
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));
}
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));
}
*child = Internal(new);
return ret;
}
- _ => fail!("unreachable code"),
+ _ => panic!("unreachable code"),
}
}
External(stored, _) if stored == key => {
match mem::replace(child, Nothing) {
External(_, value) => (Some(value), true),
- _ => fail!()
+ _ => panic!()
}
}
External(..) => (None, false),
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));
}
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)
}
}
/// 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));
/// 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
/// 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);
/// // 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 {
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
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);
}
// +-+-+-+-+-+-+-+-+-+
// | |
// 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);
// +-+-+-+-+-+-+-+-+-+
// | |
// 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);
// +-+-+-+-+-+-+-+-+-+
// | |
// 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);
// +-+-+-+-+-+-+-+-+-+
// | |
// end_u end_t
- // We may fail again.
+ // We may panic again.
}
}
// 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();
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
fn drop(&mut self) {
let BadElem(ref mut x) = *self;
if *x == 0xbadbeef {
- fail!("BadElem failure: 0xbadbeef")
+ panic!("BadElem panic: 0xbadbeef")
}
}
}
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"),
}
}
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"),
}
}
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")
}
}
}
//! 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
//!
//! // 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()
//! }
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")
}
}
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")
}
}
#[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),
#[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 {
+++ /dev/null
-// 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) }
-}
/**
* 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
*
* **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
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),
_ => ()
}
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())
buf[end] = match exp_format {
ExpDec if exp_upper => 'E',
ExpDec if !exp_upper => 'e',
- _ => fail!("unreachable"),
+ _ => panic!("unreachable"),
} as u8;
end += 1;
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),
}
}
}
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),
}
}
}
//!
//! * `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
pub mod bool;
pub mod cell;
pub mod char;
-pub mod failure;
+pub mod panicking;
pub mod finally;
pub mod iter;
pub mod option;
#[doc(hidden)]
mod core {
- pub use failure;
+ pub use panicking;
}
#[doc(hidden)]
#![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
// 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
#[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)*)
});
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)*)
}
);
)
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);
}
})
)
)
#[macro_export]
-macro_rules! unreachable( () => (fail!("unreachable code")) )
+macro_rules! unreachable( () => (panic!("unreachable code")) )
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
/// 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
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.
///
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"),
}
}
--- /dev/null
+// 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;
+
+#[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() }
+}
+
+#[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() }
+}
+
+#[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) }
+}
//! 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);
//! }
//! 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}
//! 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]
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
///
/// ```{.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"]
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)
}
}
}
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`
/// ```
///
/// ```
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
}
}
///
/// assert_eq!(s.slice(1, 9), "öwe 老");
///
- /// // these will fail:
+ /// // these will panic:
/// // byte 2 lies within `ö`:
/// // s.slice(2, 3);
///
#[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);
}
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) }
}
}
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)
}
}
assert_eq!(*x, 5u);
*x = 612;
}
- x => fail!("Unexpected value {}", x)
+ x => panic!("Unexpected value {}", x)
}
match b_r.downcast_mut::<uint>() {
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)
}
}
&mut i, (),
|i, ()| {
*i = 10;
- fail!();
+ panic!();
},
|i| {
assert!(failing());
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]
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]
#[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
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");
}
}
#[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();
}
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();
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));
if msg == "I got this." {
50i
} else {
- fail!("BadBad")
+ panic!("BadBad")
}
}
#[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")
}
}
//! ];
//! 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);
} = (*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,
}
)
},
- (_,_) => fail!("something is wrong with the long-form opt")
+ (_,_) => panic!("something is wrong with the long-form opt")
}
}
}
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)
}
}
/// 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();
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
(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));
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()) {
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)"); }
}
}
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, OptionMissing_),
- _ => fail!()
+ _ => panic!()
}
}
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!()
}
}
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
- _ => fail!()
+ _ => panic!()
}
}
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()) {
assert!((m.opt_present("t")));
assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
}
- _ => fail!()
+ _ => panic!()
}
}
assert!(!m.opt_present("test"));
assert!(!m.opt_present("t"));
}
- _ => fail!()
+ _ => panic!()
}
}
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!()
}
}
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
- _ => fail!()
+ _ => panic!()
}
}
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()) {
assert!(m.opt_present("test"));
assert!(m.opt_present("t"));
}
- _ => fail!()
+ _ => panic!()
}
}
assert!(!m.opt_present("test"));
assert!(!m.opt_present("t"));
}
- _ => fail!()
+ _ => panic!()
}
}
Err(f) => {
check_fail_type(f, UnexpectedArgument_);
}
- _ => fail!()
+ _ => panic!()
}
}
let rs = getopts(args.as_slice(), opts.as_slice());
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
- _ => fail!()
+ _ => panic!()
}
}
assert!(m.free[0] == "20".to_string());
}
- _ => fail!()
+ _ => panic!()
}
}
Ok(ref m) => {
assert_eq!(m.opt_count("v"), 1);
}
- _ => fail!()
+ _ => panic!()
}
}
Ok(ref m) => {
assert_eq!(m.opt_count("v"), 2);
}
- _ => fail!()
+ _ => panic!()
}
}
Ok(ref m) => {
assert_eq!(m.opt_count("v"), 2);
}
- _ => fail!()
+ _ => panic!()
}
}
Ok(ref m) => {
assert_eq!(m.opt_count("verbose"), 1);
}
- _ => fail!()
+ _ => panic!()
}
}
Ok(ref m) => {
assert_eq!(m.opt_count("verbose"), 2);
}
- _ => fail!()
+ _ => panic!()
}
}
assert_eq!(m.opt_count("verbose"), 4);
assert_eq!(m.opt_count("v"), 4);
}
- _ => fail!()
+ _ => panic!()
}
}
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()) {
assert!((m.opt_present("t")));
assert_eq!(m.opt_str("t").unwrap(), "20".to_string());
}
- _ => fail!()
+ _ => panic!()
}
}
assert!(!m.opt_present("test"));
assert!(!m.opt_present("t"));
}
- _ => fail!()
+ _ => panic!()
}
}
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!()
}
}
assert!(pair[0] == "20".to_string());
assert!(pair[1] == "30".to_string());
}
- _ => fail!()
+ _ => panic!()
}
}
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!()
}
}
assert!(pair[1] == "-60 70".to_string());
assert!((!m.opt_present("notpresent")));
}
- _ => fail!()
+ _ => panic!()
}
}
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()]));
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()]));
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());
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());
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),
}
}
}
// 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);
//! 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();
//! # }
//! ```
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");
}
}
}
// 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
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>,
task.put_runtime(green);
return ret;
}
- None => fail!()
+ None => panic!()
}
}
}))) => {
*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
}
}
- // 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> {
// 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.
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
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;
// 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());
}
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 {
}
#[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(()));
}
}
#[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());
}
Some(ops) => {
task.put_runtime(ops);
}
- None => fail!(),
+ None => panic!(),
}
Local::put(task);
tx.send(());
record.level,
record.module_path,
record.args) {
- Err(e) => fail!("failed to log: {}", e),
+ Err(e) => panic!("failed to log: {}", e),
Ok(()) => {}
}
}
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(()) => {}
}
}
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());
assert_eq!(buf[2], 's' as u8);
assert_eq!(buf[3], 't' as u8);
}
- r => fail!("invalid read: {}", r)
+ r => panic!("invalid read: {}", r)
}
}
}
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;
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
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)),
}
}
continue
}
- n => fail!("error in select {} ({})", os::errno(), n),
+ n => panic!("error in select {} ({})", os::errno(), n),
}
// Process any pending messages
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),
}
}
}
} {
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()),
}
}
}
}) {
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),
}
}
}
-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())
}
}
};
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?");
}
}
}
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);
}
}
#[test]
- fn smoke_fail() {
+ fn smoke_panic() {
let (tx, rx) = channel::<()>();
spawn(proc() {
let _tx = tx;
- fail!()
+ panic!()
});
assert_eq!(rx.recv_opt(), Err(()));
}
}
#[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());
}
Some(ops) => {
task.put_runtime(ops);
}
- None => fail!(),
+ None => panic!(),
}
Local::put(task);
tx.send(());
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")
};
/// 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).
///
}
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.");
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.");
#[cfg(not(test))]
mod std {
- pub use core::{option, fmt}; // fail!()
+ pub use core::{option, fmt}; // panic!()
}
#[cfg(test)]
Some(d) => d,
None => {
error!("failed to find block with tag {}", tg);
- fail!();
+ panic!();
}
}
}
/// 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."),
}
}
/// 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."),
}
}
}
//! 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);
//! ```
fn flags(&self) -> Flags {
match *self {
Paren(flags, _, _) => flags,
- _ => fail!("Cannot get flags from {}", self),
+ _ => panic!("Cannot get flags from {}", self),
}
}
match *self {
Paren(_, 0, _) => None,
Paren(_, c, _) => Some(c),
- _ => fail!("Cannot get capture group from {}", self),
+ _ => panic!("Cannot get capture group from {}", self),
}
}
Some(name.clone())
}
}
- _ => fail!("Cannot get capture name from {}", self),
+ _ => panic!("Cannot get capture name from {}", self),
}
}
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),
}
}
}
}
let rep: Repeater = match c {
'?' => ZeroOne, '*' => ZeroMore, '+' => OneMore,
- _ => fail!("Not a valid repeater operator."),
+ _ => panic!("Not a valid repeater operator."),
};
match self.peek(1) {
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 => {},
},
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),
}
}
_ => {},
/// # 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)));
/// ```
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]
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") });
}
);
)
($re:expr) => (
match ::regex::Regex::new($re) {
Ok(re) => re,
- Err(err) => fail!("{}", err),
+ Err(err) => panic!("{}", err),
}
);
)
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),
}
}
);
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);
}
}
// 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>>>,
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");
}
}
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");
}
}
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);
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([]);
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 {
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) {
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);
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(),
}
}
- // 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!();
}
}
}
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),
}
}
return;
}
}
- _ => fail!()
+ _ => panic!()
};
},
ty::ty_uint(t) => {
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,
Some(f) => f,
None => return
},
- _ => fail!()
+ _ => panic!()
};
if lit_val < min || lit_val > max {
cx.span_lint(OVERFLOWING_LITERALS, e.span,
ast::BiGt => v >= min && v < max,
ast::BiGe => v > min && v <= max,
ast::BiEq | ast::BiNe => v >= min && v <= max,
- _ => fail!()
+ _ => panic!()
}
}
ast::LitInt(v, ast::UnsuffixedIntLit(ast::Minus)) => -(v as i64),
_ => return true
},
- _ => fail!()
+ _ => panic!()
};
is_valid(norm_binop, lit_val, min, max)
}
ast::LitInt(v, _) => v,
_ => return true
},
- _ => fail!()
+ _ => panic!()
};
is_valid(norm_binop, lit_val, min, max)
}
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) {
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));
}
format!("{} [-{} {}]", msg,
match level {
Warn => 'W', Deny => 'D', Forbid => 'F',
- Allow => fail!()
+ Allow => panic!()
}, name.replace("_", "-"))
},
Node(src) => {
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),
}
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
}
}
'S' => Struct,
'g' => PublicField,
'N' => InheritedField,
- c => fail!("unexpected family char: {}", c)
+ c => panic!("unexpected family char: {}", c)
}
}
match reader::doc_as_u8(visibility_doc) as char {
'y' => ast::Public,
'i' => ast::Inherited,
- _ => fail!("unknown visibility character")
+ _ => panic!("unknown visibility character")
}
}
}
match ch as char {
'i' => ast::MutImmutable,
'm' => ast::MutMutable,
- _ => fail!("unknown mutability character: `{}`", ch as char),
+ _ => panic!("unknown mutability character: `{}`", ch as char),
}
}
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)
}
}
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
});
}
'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)
}
}
container: container,
}))
}
- _ => fail!("unknown impl/trait item sort"),
+ _ => panic!("unknown impl/trait item sort"),
}
}
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
});
match item_family(impl_method_doc) {
StaticMethod => fn_style = ast::NormalFn,
UnsafeStaticMethod => fn_style = ast::UnsafeFn,
- _ => fail!()
+ _ => panic!()
}
static_impl_methods.push(StaticMethodInfo {
match family {
PublicField => ast::Public,
InheritedField => ast::Inherited,
- _ => fail!()
+ _ => panic!()
}
}
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")
}
}
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
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")
}
}
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")
}
}
ty::BrFresh(id)
}
'e' => ty::BrEnv,
- _ => fail!("parse_bound_region: bad input")
+ _ => panic!("parse_bound_region: bad input")
}
}
'e' => {
ty::ReStatic
}
- _ => fail!("parse_region: bad input")
+ _ => panic!("parse_region: bad input")
}
}
match next(st) {
'n' => None,
's' => Some(f(st)),
- _ => fail!("parse_opt: bad input")
+ _ => panic!("parse_opt: bad input")
}
}
'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(),
'e' => {
return ty::mk_err();
}
- c => { fail!("unexpected char in type string: {}", c);}
+ c => { panic!("unexpected char in type string: {}", c);}
}
}
match c {
'u' => UnsafeFn,
'n' => NormalFn,
- _ => fail!("parse_fn_style: bad fn_style {}", c)
+ _ => panic!("parse_fn_style: bad fn_style {}", c)
}
}
match c {
'o' => ast::Once,
'm' => ast::Many,
- _ => fail!("parse_onceness: bad onceness")
+ _ => panic!("parse_onceness: bad onceness")
}
}
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' => {
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];
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 }
return builtin_bounds;
}
c => {
- fail!("parse_bounds: bad builtin bounds ('{}')", c)
+ panic!("parse_bounds: bad builtin bounds ('{}')", c)
}
}
}
return param_bounds;
}
c => {
- fail!("parse_bounds: bad bounds ('{}')", c)
+ panic!("parse_bounds: bad bounds ('{}')", c)
}
}
}
ast::DeclItem(_) => false,
}
}
- ast::StmtMac(..) => fail!("unexpanded macro in astencode")
+ ast::StmtMac(..) => panic!("unexpanded macro in astencode")
};
if use_stmt {
Some(stmt)
3 => {
typeck::vtable_error
}
- _ => fail!("bad enum variant")
+ _ => panic!("bad enum variant")
})
})
}).unwrap()
}).unwrap()
}
- _ => fail!("..")
+ _ => panic!("..")
})
})
}).unwrap()
ty::AdjustDerefRef(auto_deref_ref)
}
- _ => fail!("bad enum variant for ty::AutoAdjustment")
+ _ => panic!("bad enum variant for ty::AutoAdjustment")
})
})
}).unwrap()
ty::AutoUnsafe(m, a)
}
- _ => fail!("bad enum variant for ty::AutoRef")
+ _ => panic!("bad enum variant for ty::AutoRef")
})
})
}).unwrap()
substs: substs };
ty::UnsizeVtable(ty_trait, self_ty)
}
- _ => fail!("bad enum variant for ty::UnsizeKind")
+ _ => panic!("bad enum variant for ty::UnsizeKind")
})
})
}).unwrap()
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 {
assert!(pprust::item_to_string(&*item_out) ==
pprust::item_to_string(&*item_exp));
}
- _ => fail!()
+ _ => panic!()
}
}
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")
}
}
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)
}
}
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);
})
}
local_def(id)
}
- DefPrimTy(_) => fail!()
+ DefPrimTy(_) => panic!()
}
}
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;
* 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
*
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 {
//! 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); }
}
}
*/
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); }
}
}
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
DefLocal(..) | DefPrimTy(..) | DefTyParam(..) |
DefUse(..) | DefUpvar(..) | DefRegion(..) |
DefTyParamBinder(..) | DefLabel(..) | DefSelfTy(..) => {
- fail!("didn't expect `{}`", def);
+ panic!("didn't expect `{}`", def);
}
}
}
}
UnboundResult => { /* Continue. */ }
UnknownResult => {
- fail!("value result should be known at this point");
+ panic!("value result should be known at this point");
}
}
match type_result {
}
UnboundResult => { /* Continue. */ }
UnknownResult => {
- fail!("type result should be known at this point");
+ panic!("type result should be known at this point");
}
}
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) => {
}
Indeterminate => {
- fail!("unexpected indeterminate result");
+ panic!("unexpected indeterminate result");
}
Failed(err) => {
match err {
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;
}
Indeterminate => {
- fail!("indeterminate unexpected");
+ panic!("indeterminate unexpected");
}
Success((resulting_module, resulting_last_private)) => {
}
}
Indeterminate => {
- fail!("unexpected indeterminate result");
+ panic!("unexpected indeterminate result");
}
Failed(err) => {
match err {
type_used: _
}) => (v, t),
Some(_) => {
- fail!("we should only have LastImport for `use` directives")
+ panic!("we should only have LastImport for `use` directives")
}
_ => return,
};
*/
match self.regions {
- ErasedRegions => fail!("Erased regions only expected in trans"),
+ ErasedRegions => panic!("Erased regions only expected in trans"),
NonerasedRegions(ref r) => r
}
}
*/
match self.regions {
- ErasedRegions => fail!("Erased regions only expected in trans"),
+ ErasedRegions => panic!("Erased regions only expected in trans"),
NonerasedRegions(ref mut r) => r
}
}
0 => TypeSpace,
1 => SelfSpace,
2 => FnSpace,
- _ => fail!("Invalid ParamSpace: {}", u)
+ _ => panic!("Invalid ParamSpace: {}", u)
}
}
}
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"),
}
}
}
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 =>
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);
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);
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());
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(),
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);
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
pub fn check_not_terminated(cx: Block) {
if cx.terminated.get() {
- fail!("already terminated!");
+ panic!("already terminated!");
}
}
// 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) {
let elt = ty.element_type();
ty_align(elt)
}
- _ => fail!("ty_align: unhandled type")
+ _ => panic!("ty_align: unhandled type")
}
}
let eltsz = ty_size(elt);
len * eltsz
}
- _ => fail!("ty_size: unhandled type")
+ _ => panic!("ty_size: unhandled type")
}
}
let elt = ty.element_type();
ty_align(elt)
}
- _ => fail!("ty_size: unhandled type")
+ _ => panic!("ty_size: unhandled type")
}
}
let eltsz = ty_size(elt);
len * eltsz
}
- _ => fail!("ty_size: unhandled type")
+ _ => panic!("ty_size: unhandled type")
}
}
let elt = ty.element_type();
ty_align(elt)
}
- _ => fail!("ty_size: unhandled type")
+ _ => panic!("ty_size: unhandled type")
}
}
let eltsz = ty_size(elt);
len * eltsz
}
- _ => fail!("ty_size: unhandled type")
+ _ => panic!("ty_size: unhandled type")
}
}
i += 1u;
}
}
- _ => fail!("classify: unhandled type")
+ _ => panic!("classify: unhandled type")
}
}
SSEDs => {
tys.push(Type::f64(ccx));
}
- _ => fail!("llregtype: unhandled class")
+ _ => panic!("llregtype: unhandled class")
}
i += 1u;
}
// Introduce a temporary cleanup scope that will contain cleanups
// for the arguments while they are being evaluated. The purpose
- // this cleanup is to ensure that, should a failure occur while
+ // this cleanup is to ensure that, should a panic occur while
// evaluating argument N, the values for arguments 0...N-1 are all
- // cleaned up. If no failure occurs, the values are handed off to
+ // cleaned up. If no panic occurs, the values are handed off to
// the callee, and hence none of the cleanups in this temporary
// scope will ever execute.
let fcx = bcx.fcx;
let (abi, ret_ty) = match ty::get(callee_ty).sty {
ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
ty::ty_closure(ref f) => (f.abi, f.sig.output),
- _ => fail!("expected bare rust fn or closure in trans_call_inner")
+ _ => panic!("expected bare rust fn or closure in trans_call_inner")
};
let (llfn, llenv, llself) = match callee.data {
let mut llargs = Vec::new();
let arg_tys = match args {
ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, &**x)).collect(),
- _ => fail!("expected arg exprs.")
+ _ => panic!("expected arg exprs.")
};
bcx = trans_args(bcx,
args,
bcx, arg_datum.to_appropriate_datum(bcx));
// Technically, ownership of val passes to the callee.
- // However, we must cleanup should we fail before the
+ // However, we must cleanup should we panic before the
// callee is actually invoked.
val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
}
fn needs_invoke(&self) -> bool {
/*!
* Returns true if there are pending cleanups that should
- * execute on failure.
+ * execute on panic.
*/
self.scopes.borrow().iter().rev().any(|s| s.needs_invoke())
fn get_landing_pad(&'blk self) -> BasicBlockRef {
/*!
- * Returns a basic block to branch to in the event of a failure.
- * This block will run the failure cleanups and eventually
+ * Returns a basic block to branch to in the event of a panic.
+ * This block will run the panic cleanups and eventually
* invoke the LLVM `Resume` instruction.
*/
let orig_scopes_len = self.scopes_len();
assert!(orig_scopes_len > 0);
- // Remove any scopes that do not have cleanups on failure:
+ // Remove any scopes that do not have cleanups on panic:
let mut popped_scopes = vec!();
while !self.top_scope(|s| s.needs_invoke()) {
debug!("top scope does not need invoke");
match machine::llbitsize_of_real(ccx, ccx.int_type()) {
32 => assert!(v < (1<<31) && v >= -(1<<31)),
64 => {},
- n => fail!("unsupported target size: {}", n)
+ n => panic!("unsupported target size: {}", n)
}
C_integral(ccx.int_type(), v as u64, true)
match machine::llbitsize_of_real(ccx, ccx.int_type()) {
32 => assert!(v < (1<<32)),
64 => {},
- n => fail!("unsupported target size: {}", n)
+ n => panic!("unsupported target size: {}", n)
}
C_integral(ccx.int_type(), v, false)
/// Create a dummy `CrateContext` from `self` and the provided
/// `SharedCrateContext`. This is somewhat dangerous because `self` may
/// not actually be an element of `shared.local_ccxs`, which can cause some
- /// operations to `fail` unexpectedly.
+ /// operations to panic unexpectedly.
///
/// This is used in the `LocalCrateContext` constructor to allow calling
/// functions that expect a complete `CrateContext`, even before the local
}
match declare_intrinsic(self, key) {
Some(v) => return v,
- None => fail!()
+ None => panic!()
}
}
## The Cleanup module
The cleanup module tracks what values need to be cleaned up as scopes
-are exited, either via failure or just normal control flow. The basic
+are exited, either via panic or just normal control flow. The basic
idea is that the function context maintains a stack of cleanup scopes
that are pushed/popped as we traverse the AST tree. There is typically
at least one cleanup scope per AST node; some AST nodes may introduce
Typically, when a scope is popped, we will also generate the code for
each of its cleanups at that time. This corresponds to a normal exit
from a block (for example, an expression completing evaluation
-successfully without failure). However, it is also possible to pop a
+successfully without panic). However, it is also possible to pop a
block *without* executing its cleanups; this is typically used to
-guard intermediate values that must be cleaned up on failure, but not
+guard intermediate values that must be cleaned up on panic, but not
if everything goes right. See the section on custom scopes below for
more details.
byproducts that need to be freed, then you should use temporary custom
scopes to ensure that those byproducts will get freed on unwind. For
example, an expression like `box foo()` will first allocate a box in the
-heap and then call `foo()` -- if `foo()` should fail, this box needs
+heap and then call `foo()` -- if `foo()` should panic, this box needs
to be *shallowly* freed.
### Long-distance jumps
In addition to popping a scope, which corresponds to normal control
flow exiting the scope, we may also *jump out* of a scope into some
earlier scope on the stack. This can occur in response to a `return`,
-`break`, or `continue` statement, but also in response to failure. In
+`break`, or `continue` statement, but also in response to panic. In
any of these cases, we will generate a series of cleanup blocks for
each of the scopes that is exited. So, if the stack contains scopes A
... Z, and we break out of a loop whose corresponding cleanup scope is
X, we would generate cleanup blocks for the cleanups in X, Y, and Z.
After cleanup is done we would branch to the exit point for scope X.
-But if failure should occur, we would generate cleanups for all the
+But if panic should occur, we would generate cleanups for all the
scopes from A to Z and then resume the unwind process afterwards.
To avoid generating tons of code, we cache the cleanup blocks that we
Custom cleanup scopes are used for a variety of purposes. The most
common though is to handle temporary byproducts, where cleanup only
-needs to occur on failure. The general strategy is to push a custom
+needs to occur on panic. The general strategy is to push a custom
cleanup scope, schedule *shallow* cleanups into the custom scope, and
then pop the custom scope (without transing the cleanups) when
execution succeeds normally. This way the cleanups are only trans'd on
5. Pop the scope C.
6. Return the box as an rvalue.
-This way, if a failure occurs while transing `expr`, the custom
+This way, if a panic occurs while transing `expr`, the custom
cleanup scope C is pushed and hence the box will be freed. The trans
code for `expr` itself is responsible for freeing any other byproducts
that may be in play.
* Helper for enumerating the field types of structs, enums, or records.
* The optional node ID here is the node ID of the path identifying the enum
* variant in use. If none, this cannot possibly an enum variant (so, if it
- * is and `node_id_opt` is none, this function fails).
+ * is and `node_id_opt` is none, this function panics).
*/
match ty::get(ty).sty {
};
// This scope holds intermediates that must be cleaned should
- // failure occur before the ADT as a whole is ready.
+ // panic occur before the ADT as a whole is ready.
let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
// First we trans the base, if we have one, to the dest
let c = llvm_calling_convention(ccx, fn_ty.abi);
c.unwrap_or(llvm::CCallConv)
}
- _ => fail!("expected bare fn in decl_rust_fn_with_foreign_abi")
+ _ => panic!("expected bare fn in decl_rust_fn_with_foreign_abi")
};
let llfn = base::decl_fn(ccx, name, cconv, llfn_ty, ty::FnConverging(ty::mk_nil()));
add_argument_attributes(&tys, llfn);
let c = llvm_calling_convention(ccx, fn_ty.abi);
c.unwrap_or(llvm::CCallConv)
}
- _ => fail!("expected bare fn in register_rust_fn_with_foreign_abi")
+ _ => panic!("expected bare fn in register_rust_fn_with_foreign_abi")
};
let llfn = base::register_fn_llvmty(ccx, sp, sym, node_id, cconv, llfn_ty);
add_argument_attributes(&tys, llfn);
adt::fold_variants(bcx, &*repr, struct_data, |variant_cx, st, value| {
// Be sure to put all of the fields into a scope so we can use an invoke
// instruction to call the user destructor but still call the field
- // destructors if the user destructor fails.
+ // destructors if the user destructor panics.
let field_scope = variant_cx.fcx.push_custom_cleanup_scope();
// Class dtors have no explicit args, so the params should
let ret_ty = match ty::get(callee_ty).sty {
ty::ty_bare_fn(ref f) => f.sig.output,
- _ => fail!("expected bare_fn in trans_intrinsic_call")
+ _ => panic!("expected bare_fn in trans_intrinsic_call")
};
let foreign_item = tcx.map.expect_foreign_item(node);
let name = token::get_ident(foreign_item.ident);
};
ident.name
}
- _ => fail!("callee is not a trait method")
+ _ => panic!("callee is not a trait method")
}
} else {
csearch::get_item_path(bcx.tcx(), method_id).last().unwrap().name()
return bcx;
}
- // Some cleanup would be required in the case in which failure happens
+ // Some cleanup would be required in the case in which panic happens
// during a copy. But given that copy constructors are not overridable,
// this can only happen as a result of OOM. So we just skip out on the
// cleanup since things would *probably* be broken at that point anyways.
Double => 64,
X86_FP80 => 80,
FP128 | PPC_FP128 => 128,
- _ => fail!("llvm_float_width called on a non-float type")
+ _ => panic!("llvm_float_width called on a non-float type")
}
}
}
cx.sess().bug(format!("fictitious type {} in sizing_type_of()",
ppaux::ty_to_string(cx.tcx(), t)).as_slice())
}
- ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => fail!("unreachable")
+ ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => panic!("unreachable")
};
cx.llsizingtypes().borrow_mut().insert(t, llsizingty);
match ty::get(ty::unsized_part_of_type(cx.tcx(), t)).sty {
ty::ty_str | ty::ty_vec(..) => Type::uint_from_ty(cx, ast::TyU),
ty::ty_trait(_) => Type::vtable_ptr(cx),
- _ => fail!("Unexpected type returned from unsized_part_of_type : {}",
+ _ => panic!("Unexpected type returned from unsized_part_of_type : {}",
t.repr(cx.tcx()))
}
}
let fields = lookup_struct_fields(cx, did);
lookup_field_type(cx, did, fields[0].id, substs)
}
- _ => fail!("simd_type called on invalid type")
+ _ => panic!("simd_type called on invalid type")
}
}
let fields = lookup_struct_fields(cx, did);
fields.len()
}
- _ => fail!("simd_size called on invalid type")
+ _ => panic!("simd_size called on invalid type")
}
}
// the current crate; therefore, the only type parameters that
// could be in scope are those defined in the current crate.
// If this assertion fails, it is likely because of a
- // failure in the cross-crate inlining code to translate a
+ // failure of the cross-crate inlining code to translate a
// def-id.
assert_eq!(p.def_id.krate, ast::LOCAL_CRATE);
_ => {
assert!(type_is_sized(cx, ty),
"unsized_part_of_type failed even though ty is unsized");
- fail!("called unsized_part_of_type with sized ty");
+ panic!("called unsized_part_of_type with sized ty");
}
}
}
ty_bare_fn(ref f) => f.sig.variadic,
ty_closure(ref f) => f.sig.variadic,
ref s => {
- fail!("fn_is_variadic() called on non-fn type: {}", s)
+ panic!("fn_is_variadic() called on non-fn type: {}", s)
}
}
}
ty_bare_fn(ref f) => f.sig.clone(),
ty_closure(ref f) => f.sig.clone(),
ref s => {
- fail!("ty_fn_sig() called on non-fn type: {}", s)
+ panic!("ty_fn_sig() called on non-fn type: {}", s)
}
}
}
match get(fty).sty {
ty_bare_fn(ref f) => f.abi,
ty_closure(ref f) => f.abi,
- _ => fail!("ty_fn_abi() called on non-fn type"),
+ _ => panic!("ty_fn_abi() called on non-fn type"),
}
}
ty_bare_fn(ref f) => f.sig.inputs.clone(),
ty_closure(ref f) => f.sig.inputs.clone(),
ref s => {
- fail!("ty_fn_args() called on non-fn type: {}", s)
+ panic!("ty_fn_args() called on non-fn type: {}", s)
}
}
}
UniqTraitStore
}
ref s => {
- fail!("ty_closure_store() called on non-closure type: {}", s)
+ panic!("ty_closure_store() called on non-closure type: {}", s)
}
}
}
ty_bare_fn(ref f) => f.sig.output,
ty_closure(ref f) => f.sig.output,
ref s => {
- fail!("ty_fn_ret() called on non-fn type: {}", s)
+ panic!("ty_fn_ret() called on non-fn type: {}", s)
}
}
}
// Special case `Box<T>` for now:
let definition = match tcx.def_map.borrow().find(&place.id) {
Some(&def) => def,
- None => fail!("no def for place"),
+ None => panic!("no def for place"),
};
let def_id = definition.def_id();
if tcx.lang_items.exchange_heap() == Some(def_id) {
ast::StmtDecl(_, id) | StmtExpr(_, id) | StmtSemi(_, id) => {
return id;
}
- ast::StmtMac(..) => fail!("unexpanded macro in trans")
+ ast::StmtMac(..) => panic!("unexpanded macro in trans")
}
}
}
if def_id.krate == ast::LOCAL_CRATE {
- fail!("No def'n found for {} in tcx.{}", def_id, descr);
+ panic!("No def'n found for {} in tcx.{}", def_id, descr);
}
let v = load_external();
map.insert(def_id, v.clone());
tcx.map.node_to_string(id.node)).as_slice());
}
def::DefPrimTy(_) => {
- fail!("DefPrimTy arm missed in previous ast_ty_to_prim_ty call");
+ panic!("DefPrimTy arm missed in previous ast_ty_to_prim_ty call");
}
def::DefAssociatedTy(trait_type_id) => {
let path_str = tcx.map.path_to_string(
// bottom the type lattice, and we'll be moving up the lattice as
// we process each arm. (Note that any match with 0 arms is matching
// on any empty type and is therefore unreachable; should the flow
- // of execution reach it, we will fail, so bottom is an appropriate
+ // of execution reach it, we will panic, so bottom is an appropriate
// type in that case)
let result_ty = arms.iter().fold(fcx.infcx().next_diverging_ty_var(), |result_ty, arm| {
check_expr(fcx, &*arm.body);
// FIXME(#6129). Default methods can't deal with autoref.
//
// I am a horrible monster and I pray for death. Currently
- // the default method code fails when you try to reborrow
+ // the default method code panics when you try to reborrow
// because it is not handling types correctly. In lieu of
// fixing that, I am introducing this horrible hack. - ndm
self_mt.mutbl == MutImmutable && ty::type_is_self(self_mt.ty)
ty::mk_rptr(tcx, r, ty::mt{ ty: tr, mutbl: m })
})
}
- _ => fail!("Expected ty_trait in auto_slice_trait")
+ _ => panic!("Expected ty_trait in auto_slice_trait")
}
}
ImplSource(def_id)
}
MethodStaticUnboxedClosure(..) => {
- fail!("MethodStaticUnboxedClosure only used in trans")
+ panic!("MethodStaticUnboxedClosure only used in trans")
}
MethodTypeParam(ref param) => {
TraitSource(param.trait_ref.def_id)
fn object_trait<'a>(t: &'a ty::t) -> &'a ty::TyTrait {
match ty::get(*t).sty {
ty::ty_trait(ref ty_trait) => &**ty_trait,
- _ => fail!("expected ty_trait")
+ _ => panic!("expected ty_trait")
}
}
get(original_type).sty);
None
}
- ty_trait(..) => fail!("should have been caught")
+ ty_trait(..) => panic!("should have been caught")
}
}
Some(def_id)
}
_ => {
- fail!("get_base_type() returned a type that wasn't an \
+ panic!("get_base_type() returned a type that wasn't an \
enum, struct, or trait");
}
}
Some(def_id)
}
_ => {
- fail!("get_base_type() returned a type that wasn't an \
+ panic!("get_base_type() returned a type that wasn't an \
enum, struct, or trait");
}
}
return pty;
}
ast::ItemImpl(..) | ast::ItemMod(_) |
- ast::ItemForeignMod(_) | ast::ItemMac(_) => fail!(),
+ ast::ItemForeignMod(_) | ast::ItemMac(_) => panic!(),
}
}
// NB---I do not believe this algorithm computes
// (necessarily) the GLB. As written it can
- // spuriously fail. In particular, if there is a case
+ // spuriously fail. In particular, if there is a case
// like: |fn(&a)| and fn(fn(&b)), where a and b are
// free, it will return fn(&c) where c = GLB(a,b). If
// however this GLB is not defined, then the result is
self.commit_unconditionally(|| self.try(|| f()))
}
- /// Execute `f`, unroll bindings on failure
+ /// Execute `f`, unroll bindings on panic
pub fn try<T,E>(&self, f: || -> Result<T,E>) -> Result<T,E> {
debug!("try()");
let snapshot = self.start_snapshot();
while undo_log.len() > snapshot.length + 1 {
match undo_log.pop().unwrap() {
OpenSnapshot => {
- fail!("Failure to observe stack discipline");
+ panic!("Failure to observe stack discipline");
}
Mark | CommitedSnapshot => { }
AddVar(vid) => {
// We want to generate the intersection of two
// scopes or two free regions. So, if one of
// these scopes is a subscope of the other, return
- // it. Otherwise fail.
+ // it. Otherwise fail.
debug!("intersect_scopes(scope_a={}, scope_b={}, region_a={}, region_b={})",
scope_a, scope_b, region_a, region_b);
match self.tcx.region_maps.nearest_common_ancestor(scope_a, scope_b) {
e.messages.remove(i);
}
None => {
- fail!("Unexpected error: {} Expected: {}",
+ panic!("Unexpected error: {} Expected: {}",
msg, e.messages);
}
}
return match search_mod(self, &self.infcx.tcx.map.krate().module, 0, names) {
Some(id) => id,
None => {
- fail!("no item found: `{}`", names.connect("::"));
+ panic!("no item found: `{}`", names.connect("::"));
}
};
pub fn make_subtype(&self, a: ty::t, b: ty::t) -> bool {
match infer::mk_subty(self.infcx, true, infer::Misc(DUMMY_SP), a, b) {
Ok(_) => true,
- Err(ref e) => fail!("Encountered error: {}",
+ Err(ref e) => panic!("Encountered error: {}",
ty::type_err_to_str(self.infcx.tcx, e))
}
}
pub fn assert_subtype(&self, a: ty::t, b: ty::t) {
if !self.is_subtype(a, b) {
- fail!("{} is not a subtype of {}, but it should be",
+ panic!("{} is not a subtype of {}, but it should be",
self.ty_to_string(a),
self.ty_to_string(b));
}
pub fn assert_not_subtype(&self, a: ty::t, b: ty::t) {
if self.is_subtype(a, b) {
- fail!("{} is a subtype of {}, but it shouldn't be",
+ panic!("{} is a subtype of {}, but it shouldn't be",
self.ty_to_string(a),
self.ty_to_string(b));
}
pub fn make_lub_ty(&self, t1: ty::t, t2: ty::t) -> ty::t {
match self.lub().tys(t1, t2) {
Ok(t) => t,
- Err(ref e) => fail!("unexpected error computing LUB: {}",
+ Err(ref e) => panic!("unexpected error computing LUB: {}",
ty::type_err_to_str(self.infcx.tcx, e))
}
}
self.assert_eq(t, t_lub);
}
Err(ref e) => {
- fail!("unexpected error in LUB: {}",
+ panic!("unexpected error in LUB: {}",
ty::type_err_to_str(self.infcx.tcx, e))
}
}
self.ty_to_string(t_glb));
match self.glb().tys(t1, t2) {
Err(e) => {
- fail!("unexpected error computing LUB: {}", e)
+ panic!("unexpected error computing LUB: {}", e)
}
Ok(t) => {
self.assert_eq(t, t_glb);
match self.lub().tys(t1, t2) {
Err(_) => {}
Ok(t) => {
- fail!("unexpected success computing LUB: {}", self.ty_to_string(t))
+ panic!("unexpected success computing LUB: {}", self.ty_to_string(t))
}
}
}
match self.glb().tys(t1, t2) {
Err(_) => {}
Ok(t) => {
- fail!("unexpected success computing GLB: {}", self.ty_to_string(t))
+ panic!("unexpected success computing GLB: {}", self.ty_to_string(t))
}
}
}
let relations = match old_value {
Bounded(b) => b,
- Known(_) => fail!("Asked to instantiate variable that is \
+ Known(_) => panic!("Asked to instantiate variable that is \
already instantiated")
};
fn relations<'a>(v: &'a mut TypeVariableData) -> &'a mut Vec<Relation> {
match v.value {
- Known(_) => fail!("var_sub_var: variable is known"),
+ Known(_) => panic!("var_sub_var: variable is known"),
Bounded(ref mut relations) => relations
}
}
impl<K,V> sv::SnapshotVecDelegate<VarValue<K,V>,()> for Delegate {
fn reverse(&mut self, _: &mut Vec<VarValue<K,V>>, _: ()) {
- fail!("Nothing to reverse");
+ panic!("Nothing to reverse");
}
}
match tcx.named_region_map.find(¶m_id) {
Some(&rl::DefEarlyBoundRegion(_, _, lifetime_decl_id))
=> lifetime_decl_id,
- Some(_) => fail!("should not encounter non early-bound cases"),
+ Some(_) => panic!("should not encounter non early-bound cases"),
// The lookup should only fail when `param_id` is
// itself a lifetime binding: use it as the decl_id.
assert!(is_lifetime(&tcx.map, param_id));
let parent_id = tcx.map.get_parent(decl_id);
let parent = tcx.map.find(parent_id).unwrap_or_else(
- || fail!("tcx.map missing entry for id: {}", parent_id));
+ || panic!("tcx.map missing entry for id: {}", parent_id));
let is_inferred;
macro_rules! cannot_happen { () => { {
- fail!("invalid parent: {:s} for {:s}",
+ panic!("invalid parent: {:s} for {:s}",
tcx.map.node_to_string(parent_id),
tcx.map.node_to_string(param_id));
} } }
) )
weak_lang_items!(
- fail_fmt, FailFmtLangItem, rust_begin_unwind;
+ panic_fmt, PanicFmtLangItem, rust_begin_unwind;
stack_exhausted, StackExhaustedLangItem, rust_stack_exhausted;
eh_personality, EhPersonalityLangItem, rust_eh_personality;
)
Decorator(ext) => Decorator(ext),
Modifier(ext) => Modifier(ext),
// there's probably a nicer way to signal this:
- LetSyntaxTT(_, _) => fail!("can't register a new LetSyntax!"),
+ LetSyntaxTT(_, _) => panic!("can't register a new LetSyntax!"),
}));
}
match self.undo_log.pop().unwrap() {
OpenSnapshot => {
// This indicates a failure to obey the stack discipline.
- fail!("Cannot rollback an uncommitted snapshot");
+ panic!("Cannot rollback an uncommitted snapshot");
}
CommittedSnapshot => {
handler.err(format!("could not exec `{}`: {}", ar.as_slice(),
e).as_slice());
handler.abort_if_errors();
- fail!("rustc::back::archive::run_ar() should not reach this point");
+ panic!("rustc::back::archive::run_ar() should not reach this point");
}
}
}
os: abi::OsLinux,
used_crates: Vec::new(),
out_filename: Path::new("bin/rustc"),
- get_install_prefix_lib_path: || fail!(),
+ get_install_prefix_lib_path: || panic!(),
realpath: |p| Ok(p.clone())
};
let res = get_rpath_relative_to_output(config, &Path::new("lib/libstd.so"));
os: abi::OsFreebsd,
used_crates: Vec::new(),
out_filename: Path::new("bin/rustc"),
- get_install_prefix_lib_path: || fail!(),
+ get_install_prefix_lib_path: || panic!(),
realpath: |p| Ok(p.clone())
};
let res = get_rpath_relative_to_output(config, &Path::new("lib/libstd.so"));
os: abi::OsDragonfly,
used_crates: Vec::new(),
out_filename: Path::new("bin/rustc"),
- get_install_prefix_lib_path: || fail!(),
+ get_install_prefix_lib_path: || panic!(),
realpath: |p| Ok(p.clone())
};
let res = get_rpath_relative_to_output(config, &Path::new("lib/libstd.so"));
os: abi::OsMacos,
used_crates: Vec::new(),
out_filename: Path::new("bin/rustc"),
- get_install_prefix_lib_path: || fail!(),
+ get_install_prefix_lib_path: || panic!(),
realpath: |p| Ok(p.clone())
};
let res = get_rpath_relative_to_output(config, &Path::new("lib/libstd.so"));
}
}
-/// Adds the specified number of bytes to the bit count. fail!() if this would cause numeric
+/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// overflow.
fn add_bytes_to_bits<T: Int + CheckedAdd + ToBits>(bits: T, bytes: T) -> T {
let (new_high_bits, new_low_bits) = bytes.to_bits();
if new_high_bits > Zero::zero() {
- fail!("numeric overflow occurred.")
+ panic!("numeric overflow occurred.")
}
match bits.checked_add(&new_low_bits) {
Some(x) => return x,
- None => fail!("numeric overflow occurred.")
+ None => panic!("numeric overflow occurred.")
}
}
} else {
// It is not possible to observe any kind of macro
// invocation at this stage except `macro_rules!`.
- fail!("reached macro somehow: {}",
+ panic!("reached macro somehow: {}",
pprust::to_string(|pp_state| pp_state.print_mac(macro)));
}
clean::Function {
decl: match ty::get(t.ty).sty {
ty::ty_bare_fn(ref f) => (did, &f.sig).clean(cx),
- _ => fail!("bad function"),
+ _ => panic!("bad function"),
},
generics: (&t.generics, subst::FnSpace).clean(cx),
fn_style: style,
generics: generics,
})
}
- _ => fail!("not a tymethod"),
+ _ => panic!("not a tymethod"),
};
Some(item)
}
decoder::DlDef(..) => {}
// All impls were inlined above
decoder::DlImpl(..) => {}
- decoder::DlField => fail!("unimplemented field"),
+ decoder::DlField => panic!("unimplemented field"),
}
});
}
TyBareFn(ref barefn) => BareFunction(box barefn.clean(cx)),
TyParen(ref ty) => ty.clean(cx),
TyBot => Bottom,
- ref x => fail!("Unimplemented type {}", x),
+ ref x => panic!("Unimplemented type {}", x),
}
}
}
ty::ty_unboxed_closure(..) => Primitive(Unit), // FIXME(pcwalton)
- ty::ty_infer(..) => fail!("ty_infer"),
- ty::ty_open(..) => fail!("ty_open"),
- ty::ty_err => fail!("ty_err"),
+ ty::ty_infer(..) => panic!("ty_infer"),
+ ty::ty_open(..) => panic!("ty_open"),
+ ty::ty_err => panic!("ty_err"),
}
}
}
which is silly in function arguments");
"()".to_string()
},
- PatRange(..) => fail!("tried to get argument name from PatRange, \
+ PatRange(..) => panic!("tried to get argument name from PatRange, \
which is not allowed in function arguments"),
- PatVec(..) => fail!("tried to get argument name from pat_vec, \
+ PatVec(..) => panic!("tried to get argument name from pat_vec, \
which is not allowed in function arguments"),
PatMac(..) => {
warn!("can't document the name of a function argument \
debug!("searching for {} in defmap", id);
let def = match tcx.def_map.borrow().find(&id) {
Some(&k) => k,
- None => fail!("unresolved id not in defmap")
+ None => panic!("unresolved id not in defmap")
};
match def {
};
if ret == -1 {
unsafe { libc::close(fd); }
- fail!("could not lock `{}`", p.display())
+ panic!("could not lock `{}`", p.display())
}
Lock { fd: fd }
}
ptr::null_mut())
};
if handle == libc::INVALID_HANDLE_VALUE {
- fail!("create file error: {}", os::last_os_error());
+ panic!("create file error: {}", os::last_os_error());
}
let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() };
let ret = unsafe {
};
if ret == 0 {
unsafe { libc::CloseHandle(handle); }
- fail!("could not lock `{}`: {}", p.display(),
+ panic!("could not lock `{}`: {}", p.display(),
os::last_os_error())
}
Lock { handle: handle }
}
}
clean::Unique(..) => {
- fail!("should have been cleaned")
+ panic!("should have been cleaned")
}
}
}
/// sure it always points to the top (relatively)
fn recurse<T>(&mut self, s: String, f: |&mut Context| -> T) -> T {
if s.len() == 0 {
- fail!("Unexpected empty destination: {}", self.current);
+ panic!("Unexpected empty destination: {}", self.current);
}
let prev = self.dst.clone();
self.dst.push(s.as_slice());
Some("html") | None => {
match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc"))) {
Ok(()) => {}
- Err(e) => fail!("failed to generate documentation: {}", e),
+ Err(e) => panic!("failed to generate documentation: {}", e),
}
}
Some("json") => {
match json_output(krate, res, output.unwrap_or(Path::new("doc.json"))) {
Ok(()) => {}
- Err(e) => fail!("failed to write json: {}", e),
+ Err(e) => panic!("failed to write json: {}", e),
}
}
Some(s) => {
};
let crate_json = match json::from_str(crate_json_str.as_slice()) {
Ok(j) => j,
- Err(e) => fail!("Rust generated JSON is invalid: {}", e)
+ Err(e) => panic!("Rust generated JSON is invalid: {}", e)
};
json.insert("crate".to_string(), crate_json);
cmd.env(DynamicLibrary::envvar(), newpath.as_slice());
match cmd.output() {
- Err(e) => fail!("couldn't run the test: {}{}", e,
+ Err(e) => panic!("couldn't run the test: {}{}", e,
if e.kind == io::PermissionDenied {
" - maybe your tempdir is mounted with noexec?"
} else { "" }),
Ok(out) => {
if should_fail && out.status.success() {
- fail!("test executable succeeded when it should have failed");
+ panic!("test executable succeeded when it should have failed");
} else if !should_fail && !out.status.success() {
- fail!("test executable failed:\n{}",
+ panic!("test executable failed:\n{}",
str::from_utf8(out.error.as_slice()));
}
}
self.visit_item(&**i, None, om);
}
}
- _ => { fail!("glob not mapped to a module"); }
+ _ => { panic!("glob not mapped to a module"); }
}
} else {
self.visit_item(it, renamed, om);
om.foreigns.push(fm.clone());
}
ast::ItemMac(_) => {
- fail!("rustdoc: macros should be gone, after expansion");
+ panic!("rustdoc: macros should be gone, after expansion");
}
}
}
}
pub fn take() -> Option<Vec<Vec<u8>>> {
- fail!()
+ panic!()
}
pub fn put(_args: Vec<Vec<u8>>) {
- fail!()
+ panic!()
}
pub fn clone() -> Option<Vec<Vec<u8>>> {
- fail!()
+ panic!()
}
}
fn clone(&self) -> CString {
let len = self.len() + 1;
let buf = unsafe { libc::malloc(len as libc::size_t) } as *mut libc::c_char;
- if buf.is_null() { fail!("out of memory") }
+ if buf.is_null() { panic!("out of memory") }
unsafe { ptr::copy_nonoverlapping_memory(buf, self.buf, len); }
CString { buf: buf as *const libc::c_char, owns_buffer_: true }
}
unsafe fn to_c_str_unchecked(&self) -> CString {
let self_len = self.len();
let buf = libc::malloc(self_len as libc::size_t + 1) as *mut u8;
- if buf.is_null() { fail!("out of memory") }
+ if buf.is_null() { panic!("out of memory") }
ptr::copy_memory(buf, self.as_ptr(), self_len);
*buf.offset(self_len as int) = 0;
fn wrap(self: Box<Self>) -> Box<Any+'static>;
}
-/// The default error code of the rust runtime if the main task fails instead
+/// The default error code of the rust runtime if the main task panics instead
/// of exiting cleanly.
pub const DEFAULT_ERROR_CODE: int = 101;
*slot = Some(TreeMap::new());
match *slot {
Some(ref mut map_ptr) => { return Some(map_ptr) }
- None => fail!("unreachable code"),
+ None => panic!("unreachable code"),
}
}
}
/// If this key is already present in TLD, then the previous value is
/// replaced with the provided data, and then returned.
///
- /// # Failure
+ /// # Panics
///
- /// This function will fail if the key is present in TLD and currently on
+ /// This function will panic if the key is present in TLD and currently on
/// loan with the `get` method.
///
- /// It will also fail if there is no local task (because the current thread
+ /// It will also panic if there is no local task (because the current thread
/// is not owned by the runtime).
///
/// # Example
pub fn replace(&'static self, data: Option<T>) -> Option<T> {
let map = match unsafe { get_local_map() } {
Some(map) => map,
- None => fail!("must have a local task to insert into TLD"),
+ None => panic!("must have a local task to insert into TLD"),
};
let keyval = key_to_key_value(self);
}
_ => {
// Refcount is 2+, which means we have a live borrow.
- fail!("TLD value cannot be replaced because it is already borrowed");
+ panic!("TLD value cannot be replaced because it is already borrowed");
}
}
}
unsafe fn d<T>(p: *mut ()) {
let value_box = p as *mut TLDValueBox<T>;
debug_assert!(*(*value_box).refcount.get() < 2, "TLDValue destructed while borrowed");
- // use a RAII type here to ensure we always deallocate even if we fail while
+ // use a RAII type here to ensure we always deallocate even if we panic while
// running the destructor for the value.
struct Guard<T> {
p: *mut TLDValueBox<T>
#[test]
#[should_fail]
- fn test_tls_cleanup_on_failure() {
+ fn test_tls_cleanup_on_panic() {
static STR_KEY: Key<String> = &KeyValueKey;
static BOX_KEY: Key<Box<int>> = &KeyValueKey;
static INT_KEY: Key<int> = &KeyValueKey;
STR_KEY.replace(Some("string data".to_string()));
BOX_KEY.replace(Some(box 2));
INT_KEY.replace(Some(42));
- fail!();
+ panic!();
});
// Not quite nondeterministic.
INT_KEY.replace(Some(31337));
- fail!();
+ panic!();
}
#[test]
/// destruction.
///
/// Using this makes lock-based code resilient to unwinding/task
-/// failure, because the lock will be automatically unlocked even
+/// panic, because the lock will be automatically unlocked even
/// then.
#[must_use]
pub struct LockGuard<'a> {
PAGE_SIZE = info.dwPageSize as uint;
if AddVectoredExceptionHandler(0, vectored_handler) == ptr::null_mut() {
- fail!("failed to install exception handler");
+ panic!("failed to install exception handler");
}
mem::forget(make_handler());
pub unsafe fn make_handler() -> Handler {
if SetThreadStackGuarantee(&mut 0x5000) == 0 {
- fail!("failed to reserve stack space for exception handling");
+ panic!("failed to reserve stack space for exception handling");
}
super::Handler { _data: 0i as *mut libc::c_void }
pub unsafe fn init() {
let psize = libc::sysconf(libc::consts::os::sysconf::_SC_PAGESIZE);
if psize == -1 {
- fail!("failed to get page size");
+ panic!("failed to get page size");
}
PAGE_SIZE = psize as uint;
-1,
0);
if alt_stack == MAP_FAILED {
- fail!("failed to allocate an alternative stack");
+ panic!("failed to allocate an alternative stack");
}
let mut stack: sigaltstack = mem::zeroed();
///
/// * `run` - This function will execute a closure inside the context of a task.
/// Failure is caught and handled via the task's on_exit callback. If
-/// this fails, the task is still returned, but it can no longer be
+/// this panics, the task is still returned, but it can no longer be
/// used, it is poisoned.
///
/// * `destroy` - This is a required function to call to destroy a task. If a
/// // Create a task using a native runtime
/// let task = native::task::new((0, uint::MAX), 0);
///
-/// // Run some code, catching any possible failures
+/// // Run some code, catching any possible panic
/// let task = task.run(|| {
/// // Run some code inside this task
/// println!("Hello with a native runtime!");
/// });
///
-/// // Run some code again, catching the failure
+/// // Run some code again, catching the panic
/// let task = task.run(|| {
-/// fail!("oh no, what to do!");
+/// panic!("oh no, what to do!");
/// });
///
-/// // Now that the task is failed, it can never be used again
+/// // Now that the task has panicked, it can never be used again
/// assert!(task.is_destroyed());
///
/// // Deallocate the resources associated with this task
pub struct TaskOpts {
/// Invoke this procedure with the result of the task when it finishes.
pub on_exit: Option<proc(Result): Send>,
- /// A name for the task-to-be, for identification in failure messages
+ /// A name for the task-to-be, for identification in panic messages
pub name: Option<SendStr>,
/// The size of the stack for the spawned task
pub stack_size: Option<uint>,
/// Indicates the manner in which a task exited.
///
-/// A task that completes without failing is considered to exit successfully.
+/// A task that completes without panicking is considered to exit successfully.
///
/// If you wish for this result's delivery to block until all
/// children tasks complete, recommend using a result future.
Shared(Arc<AtomicUint>),
}
-/// Per-task state related to task death, killing, failure, etc.
+/// Per-task state related to task death, killing, panic, etc.
pub struct Death {
pub on_exit: Option<proc(Result):Send>,
marker: marker::NoCopy,
/// try/catch). Invoking this function is quite cheap.
///
/// If the closure `f` succeeds, then the returned task can be used again
- /// for another invocation of `run`. If the closure `f` fails then `self`
+ /// for another invocation of `run`. If the closure `f` panics then `self`
/// will be internally destroyed along with all of the other associated
/// resources of this task. The `on_exit` callback is invoked with the
- /// cause of failure (not returned here). This can be discovered by querying
+ /// cause of panic (not returned here). This can be discovered by querying
/// `is_destroyed()`.
///
/// Note that it is possible to view partial execution of the closure `f`
/// because it is not guaranteed to run to completion, but this function is
- /// guaranteed to return if it fails. Care should be taken to ensure that
+ /// guaranteed to return if it panicks. Care should be taken to ensure that
/// stack references made by `f` are handled appropriately.
///
/// It is invalid to call this function with a task that has been previously
// recursive invocations of run(). If there's no one else, then
// relinquish ownership of ourselves back into TLS.
if Local::exists(None::<Task>) {
- fail!("cannot run a task recursively inside another");
+ panic!("cannot run a task recursively inside another");
}
self.state = Armed;
Local::put(self);
let result = unsafe { unwind::try(f) };
// After running the closure given return the task back out if it ran
- // successfully, or clean up the task if it failed.
+ // successfully, or clean up the task if it panicked.
let task: Box<Task> = Local::take();
match result {
Ok(()) => task,
// There is a test for this at fail-during-tld-destroy.rs.
//
// 2. One failure in destruction is tolerable, so long as the task
- // didn't originally fail while it was running.
+ // didn't originally panic while it was running.
//
// And with all that in mind, we attempt to clean things up!
let mut task = self.run(|| {
drop(tld);
});
- // If the above `run` block failed, then it must be the case that the
+ // If the above `run` block panicked, then it must be the case that the
// task had previously succeeded. This also means that the code below
// was recursively run via the `run` method invoking this method. In
// this case, we just make sure the world is as we thought, and return.
// FIXME: this is running in a seriously constrained context. If this
// allocates TLD then it will likely abort the runtime. Similarly,
- // if this fails, this will also likely abort the runtime.
+ // if this panics, this will also likely abort the runtime.
//
// This closure is currently limited to a channel send via the
// standard library's task interface, but this needs
}
// This assertion has two flavours because the wake involves an atomic op.
- // In the faster version, destructors will fail dramatically instead.
+ // In the faster version, destructors will panic dramatically instead.
#[cfg(not(test))] pub fn trash(self) { }
#[cfg(test)] pub fn trash(self) { assert!(self.wake().is_none()); }
let result = task::try(proc()());
rtdebug!("trying first assert");
assert!(result.is_ok());
- let result = task::try::<()>(proc() fail!());
+ let result = task::try::<()>(proc() panic!());
rtdebug!("trying second assert");
assert!(result.is_err());
}
if ret as uint == 0 {
// be sure to not leak the closure
let _p: Box<proc():Send> = mem::transmute(arg);
- fail!("failed to spawn native thread: {}", ret);
+ panic!("failed to spawn native thread: {}", ret);
}
return ret;
}
unsafe fn get_stack_start() -> *mut libc::c_void {
let mut attr: libc::pthread_attr_t = mem::zeroed();
if pthread_getattr_np(pthread_self(), &mut attr) != 0 {
- fail!("failed to get thread attributes");
+ panic!("failed to get thread attributes");
}
let mut stackaddr = ptr::null_mut();
let mut stacksize = 0;
if pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize) != 0 {
- fail!("failed to get stack information");
+ panic!("failed to get stack information");
}
if pthread_attr_destroy(&mut attr) != 0 {
- fail!("failed to destroy thread attributes");
+ panic!("failed to destroy thread attributes");
}
stackaddr
}
pub unsafe fn init() {
let psize = libc::sysconf(libc::consts::os::sysconf::_SC_PAGESIZE);
if psize == -1 {
- fail!("failed to get page size");
+ panic!("failed to get page size");
}
PAGE_SIZE = psize as uint;
0);
if result != stackaddr || result == MAP_FAILED {
- fail!("failed to allocate a guard page");
+ panic!("failed to allocate a guard page");
}
let offset = if cfg!(target_os = "linux") {
pub unsafe fn current() -> uint {
let mut attr: libc::pthread_attr_t = mem::zeroed();
if pthread_getattr_np(pthread_self(), &mut attr) != 0 {
- fail!("failed to get thread attributes");
+ panic!("failed to get thread attributes");
}
let mut guardsize = 0;
if pthread_attr_getguardsize(&attr, &mut guardsize) != 0 {
- fail!("failed to get stack guard page");
+ panic!("failed to get stack guard page");
}
if guardsize == 0 {
- fail!("there is no guard page");
+ panic!("there is no guard page");
}
let mut stackaddr = ptr::null_mut();
let mut stacksize = 0;
if pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize) != 0 {
- fail!("failed to get stack information");
+ panic!("failed to get stack information");
}
if pthread_attr_destroy(&mut attr) != 0 {
- fail!("failed to destroy thread attributes");
+ panic!("failed to destroy thread attributes");
}
stackaddr as uint + guardsize as uint
},
errno => {
// This cannot really happen.
- fail!("pthread_attr_setstacksize() error: {}", errno);
+ panic!("pthread_attr_setstacksize() error: {}", errno);
},
};
if ret != 0 {
// be sure to not leak the closure
let _p: Box<proc():Send> = mem::transmute(arg);
- fail!("failed to spawn native thread: {}", ret);
+ panic!("failed to spawn native thread: {}", ret);
}
native
}
}
}
-/// Invoke a closure, capturing the cause of failure if one occurs.
+/// Invoke a closure, capturing the cause of panic if one occurs.
///
-/// This function will return `None` if the closure did not fail, and will
-/// return `Some(cause)` if the closure fails. The `cause` returned is the
-/// object with which failure was originally invoked.
+/// This function will return `None` if the closure did not panic, and will
+/// return `Some(cause)` if the closure panics. The `cause` returned is the
+/// object with which panic was originally invoked.
///
/// This function also is unsafe for a variety of reasons:
///
}
}
-// Entry point of failure from the libcore crate
+// Entry point of panic from the libcore crate
#[cfg(not(test))]
-#[lang = "fail_fmt"]
+#[lang = "panic_fmt"]
pub extern fn rust_begin_unwind(msg: &fmt::Arguments,
file: &'static str, line: uint) -> ! {
begin_unwind_fmt(msg, &(file, line))
/// The entry point for unwinding with a formatted message.
///
/// This is designed to reduce the amount of code required at the call
-/// site as much as possible (so that `fail!()` has as low an impact
+/// site as much as possible (so that `panic!()` has as low an impact
/// on (e.g.) the inlining of other functions as possible), by moving
/// the actual formatting into this shared place.
#[inline(never)] #[cold]
// We do two allocations here, unfortunately. But (a) they're
// required with the current scheme, and (b) we don't handle
- // failure + OOM properly anyway (see comment in begin_unwind
+ // panic + OOM properly anyway (see comment in begin_unwind
// below).
struct VecWriter<'a> { v: &'a mut Vec<u8> }
begin_unwind_inner(msg, file_line)
}
-/// This is the entry point of unwinding for fail!() and assert!().
+/// This is the entry point of unwinding for panic!() and assert!().
#[inline(never)] #[cold] // avoid code bloat at the call sites as much as possible
pub fn begin_unwind<M: Any + Send>(msg: M, file_line: &(&'static str, uint)) -> ! {
// Note that this should be the only allocation performed in this code path.
- // Currently this means that fail!() on OOM will invoke this code path,
- // but then again we're not really ready for failing on OOM anyway. If
+ // Currently this means that panic!() on OOM will invoke this code path,
+ // but then again we're not really ready for panic on OOM anyway. If
// we do start doing this, then we should propagate this allocation to
// be performed in the parent of this task instead of the task that's
- // failing.
+ // panicking.
// see below for why we do the `Any` coercion here.
begin_unwind_inner(box msg, file_line)
/// we need the `Any` object anyway, we're not just creating it to
/// avoid being generic.)
///
-/// Do this split took the LLVM IR line counts of `fn main() { fail!()
+/// Do this split took the LLVM IR line counts of `fn main() { panic!()
/// }` from ~1900/3700 (-O/no opts) to 180/590.
#[inline(never)] #[cold] // this is the slow path, please never inline this
fn begin_unwind_inner(msg: Box<Any + Send>, file_line: &(&'static str, uint)) -> ! {
- // First, invoke call the user-defined callbacks triggered on task failure.
+ // First, invoke call the user-defined callbacks triggered on task panic.
//
// By the time that we see a callback has been registered (by reading
// MAX_CALLBACKS), the actual callback itself may have not been stored yet,
};
if task.unwinder.unwinding {
- // If a task fails while it's already unwinding then we
+ // If a task panics while it's already unwinding then we
// have limited options. Currently our preference is to
// just abort. In the future we may consider resuming
// unwinding or otherwise exiting the task cleanly.
/// Register a callback to be invoked when a task unwinds.
///
/// This is an unsafe and experimental API which allows for an arbitrary
-/// callback to be invoked when a task fails. This callback is invoked on both
+/// callback to be invoked when a task panics. This callback is invoked on both
/// the initial unwinding and a double unwinding if one occurs. Additionally,
/// the local `Task` will be in place for the duration of the callback, and
/// the callback must ensure that it remains in place once the callback returns.
v.push(b'=');
}
}
- _ => fail!("Algebra is broken, please alert the math police")
+ _ => panic!("Algebra is broken, please alert the math police")
}
unsafe {
let len = self.stack.len();
let idx = match *self.stack.last().unwrap() {
InternalIndex(i) => { i + 1 }
- _ => { fail!(); }
+ _ => { panic!(); }
};
*self.stack.get_mut(len - 1) = InternalIndex(idx);
}
match self.token {
None => {}
Some(Error(e)) => { return Err(e); }
- ref tok => { fail!("unexpected token {}", tok.clone()); }
+ ref tok => { panic!("unexpected token {}", tok.clone()); }
}
result
}
}
let key = match self.parser.stack().top() {
Some(Key(k)) => { k.to_string() }
- _ => { fail!("invalid state"); }
+ _ => { panic!("invalid state"); }
};
match self.build_value() {
Ok(value) => { values.insert(key, value); }
Ok(json) => Decodable::decode(&mut Decoder::new(json))
};
match res {
- Ok(_) => fail!("`{}` parsed & decoded ok, expecting error `{}`",
+ Ok(_) => panic!("`{}` parsed & decoded ok, expecting error `{}`",
to_parse, expected),
- Err(ParseError(e)) => fail!("`{}` is not valid json: {}",
+ Err(ParseError(e)) => panic!("`{}` is not valid json: {}",
to_parse, e),
Err(e) => {
assert_eq!(e, expected);
let bytes = mem_buf.unwrap();
let json_str = from_utf8(bytes.as_slice()).unwrap();
match from_str(json_str) {
- Err(_) => fail!("Unable to parse json_str: {}", json_str),
+ Err(_) => panic!("Unable to parse json_str: {}", json_str),
_ => {} // it parsed and we are good to go
}
}
let bytes = mem_buf.unwrap();
let json_str = from_utf8(bytes.as_slice()).unwrap();
match from_str(json_str) {
- Err(_) => fail!("Unable to parse json_str: {}", json_str),
+ Err(_) => panic!("Unable to parse json_str: {}", json_str),
_ => {} // it parsed and we are good to go
}
}
use Decodable;
let json_str = "{\"1\":true}";
let json_obj = match from_str(json_str) {
- Err(_) => fail!("Unable to parse json_str: {}", json_str),
+ Err(_) => panic!("Unable to parse json_str: {}", json_str),
Ok(o) => o
};
let mut decoder = Decoder::new(json_obj);
use Decodable;
let json_str = "{\"a\":true}";
let json_obj = match from_str(json_str) {
- Err(_) => fail!("Unable to parse json_str: {}", json_str),
+ Err(_) => panic!("Unable to parse json_str: {}", json_str),
Ok(o) => o
};
let mut decoder = Decoder::new(json_obj);
};
let (ref expected_evt, ref expected_stack) = expected[i];
if !parser.stack().is_equal_to(expected_stack.as_slice()) {
- fail!("Parser stack is not equal to {}", expected_stack);
+ panic!("Parser stack is not equal to {}", expected_stack);
}
assert_eq!(&evt, expected_evt);
i+=1;
/// Trait for converting into an ascii type.
pub trait AsciiCast<T> {
- /// Convert to an ascii type, fail on non-ASCII input.
+ /// Convert to an ascii type, panic on non-ASCII input.
#[inline]
fn to_ascii(&self) -> T {
assert!(self.is_ascii());
}
#[test] #[should_fail]
- fn test_ascii_vec_fail_u8_slice() { (&[127u8, 128u8, 255u8]).to_ascii(); }
+ fn test_ascii_vec_panic_u8_slice() { (&[127u8, 128u8, 255u8]).to_ascii(); }
#[test] #[should_fail]
- fn test_ascii_vec_fail_str_slice() { "zoä华".to_ascii(); }
+ fn test_ascii_vec_panic_str_slice() { "zoä华".to_ascii(); }
#[test] #[should_fail]
- fn test_ascii_fail_u8_slice() { 255u8.to_ascii(); }
+ fn test_ascii_panic_u8_slice() { 255u8.to_ascii(); }
#[test] #[should_fail]
- fn test_ascii_fail_char_slice() { 'λ'.to_ascii(); }
+ fn test_ascii_panic_char_slice() { 'λ'.to_ascii(); }
#[test]
fn test_opt() {
fn malloc(n: uint) -> CVec<u8> {
unsafe {
let mem = libc::malloc(n as libc::size_t);
- if mem.is_null() { fail!("out of memory") }
+ if mem.is_null() { panic!("out of memory") }
CVec::new_with_dtor(mem as *mut u8, n,
proc() { libc::free(mem as *mut libc::c_void); })
#[test]
#[should_fail]
- fn test_fail_at_null() {
+ fn test_panic_at_null() {
unsafe {
CVec::new(ptr::null_mut::<u8>(), 9);
}
fn test_unwrap() {
unsafe {
let cv = CVec::new_with_dtor(1 as *mut int, 0,
- proc() { fail!("Don't run this destructor!") });
+ proc() { panic!("Don't run this destructor!") });
let p = cv.unwrap();
assert_eq!(p, 1 as *mut int);
}
// is also memory and cache pressure that this would entail that would be very
// difficult to properly see in a microbenchmark.
//
-// Future Improvements (FIXME!)
-// ============================
+// ## Future Improvements (FIXME!)
//
// Allow the load factor to be changed dynamically and/or at initialization.
//
// underlying table? This is exactly the use case for 'realloc', and may
// be worth exploring.
//
-// Future Optimizations (FIXME!)
-// =============================
+// ## Future Optimizations (FIXME!)
//
// Another possible design choice that I made without any real reason is
// parameterizing the raw table over keys and values. Technically, all we need
};
buckets.next();
}
- fail!("Internal HashMap error: Out of space.");
+ panic!("Internal HashMap error: Out of space.");
}
}
}
/// Retrieves a mutable value for the given key.
- /// See [`find_mut`](../trait.MutableMap.html#tymethod.find_mut) for a non-failing alternative.
+ /// See [`find_mut`](../trait.MutableMap.html#tymethod.find_mut) for a non-panicking
+ /// alternative.
///
/// # Failure
///
pub fn get_mut<'a>(&'a mut self, k: &K) -> &'a mut V {
match self.find_mut(k) {
Some(v) => v,
- None => fail!("no entry found for key")
+ None => panic!("no entry found for key")
}
}
assert!(m.insert(5i, 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));
}
assert!(m.find(&1i).is_none());
m.insert(1i, 2i);
match m.find(&1) {
- None => fail!(),
+ None => panic!(),
Some(v) => assert_eq!(*v, 2)
}
}
for i in range(1i, 10000) {
m.insert(i, i + 7);
match m.find_copy(&i) {
- None => fail!(),
+ None => panic!(),
Some(v) => assert_eq!(v, i + 7)
}
for j in range(1i, i/100) {
match m.find_copy(&j) {
- None => fail!(),
+ None => panic!(),
Some(v) => assert_eq!(v, j + 7)
}
}
pub fn expect_full(self) -> FullBucket<K, V, M> {
match self {
Full(full) => full,
- Empty(..) => fail!("Expected full bucket")
+ Empty(..) => panic!("Expected full bucket")
}
}
}
}
}) {
Ok(()) => {},
- Err(str) => fail!("{}", str)
+ Err(str) => panic!("{}", str)
}
}
}
// statically linked in
let none: Option<Path> = None; // appease the typechecker
let libm = match DynamicLibrary::open(none) {
- Err(error) => fail!("Could not load self as module: {}", error),
+ Err(error) => panic!("Could not load self as module: {}", error),
Ok(libm) => libm
};
let cosine: extern fn(libc::c_double) -> libc::c_double = unsafe {
match libm.symbol("cos") {
- Err(error) => fail!("Could not load function cos: {}", error),
+ Err(error) => panic!("Could not load function cos: {}", error),
Ok(cosine) => mem::transmute::<*mut u8, _>(cosine)
}
};
let expected_result = 1.0;
let result = cosine(argument);
if result != expected_result {
- fail!("cos({}) != {} but equaled {} instead", argument,
+ panic!("cos({}) != {} but equaled {} instead", argument,
expected_result, result)
}
}
let path = Path::new("/dev/null");
match DynamicLibrary::open(Some(&path)) {
Err(_) => {}
- Ok(_) => fail!("Successfully opened the empty library.")
+ Ok(_) => panic!("Successfully opened the empty library.")
}
}
}
// all times. This means that this `exists` will return true almost all of
// the time. There are border cases, however, when the runtime has
// *almost* set up the local task, but hasn't quite gotten there yet. In
- // order to get some better diagnostics, we print on failure and
+ // order to get some better diagnostics, we print on panic and
// immediately abort the whole process if there is no local task
// available.
if !Local::exists(None::<Task>) {
- let _ = writeln!(&mut err, "failed at '{}', {}:{}", msg, file, line);
+ let _ = writeln!(&mut err, "panicked at '{}', {}:{}", msg, file, line);
if backtrace::log_enabled() {
let _ = backtrace::write(&mut err);
} else {
match local_stderr.replace(None) {
Some(mut stderr) => {
- // FIXME: what to do when the task printing fails?
+ // FIXME: what to do when the task printing panics?
let _ = writeln!(stderr,
- "task '{}' failed at '{}', {}:{}\n",
+ "task '{}' panicked at '{}', {}:{}\n",
n, msg, file, line);
if backtrace::log_enabled() {
let _ = backtrace::write(&mut *stderr);
local_stderr.replace(Some(stderr));
}
None => {
- let _ = writeln!(&mut err, "task '{}' failed at '{}', {}:{}",
+ let _ = writeln!(&mut err, "task '{}' panicked at '{}', {}:{}",
n, msg, file, line);
if backtrace::log_enabled() {
let _ = backtrace::write(&mut err);
}
}
- // If this is a double failure, make sure that we printed a backtrace
- // for this failure.
+ // If this is a double panic, make sure that we printed a backtrace
+ // for this panic.
if unwinding && !backtrace::log_enabled() {
let _ = backtrace::write(&mut err);
}
///
/// The buffer is flushed before returning the writer.
pub fn unwrap(mut self) -> W {
- // FIXME(#12628): is failing the right thing to do if flushing fails?
+ // FIXME(#12628): is panicking the right thing to do if flushing panicks?
self.flush_buf().unwrap();
self.inner.take().unwrap()
}
impl<W: Writer> Drop for BufferedWriter<W> {
fn drop(&mut self) {
if self.inner.is_some() {
- // dtors should not fail, so we ignore a failed flush
+ // dtors should not panic, so we ignore a panicked flush
let _ = self.flush_buf();
}
}
#[test]
#[should_fail]
- fn dont_fail_in_drop_on_failed_flush() {
+ fn dont_panic_in_drop_on_panicked_flush() {
struct FailFlushWriter;
impl Writer for FailFlushWriter {
let writer = FailFlushWriter;
let _writer = BufferedWriter::new(writer);
- // Trigger failure. If writer fails *again* due to the flush
- // error then the process will abort.
- fail!();
+ // If writer panics *again* due to the flush error then the process will abort.
+ panic!();
}
#[bench]
assert_eq!(a, buf.as_slice());
match reader.read(buf.as_mut_slice()) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, io::EndOfFile),
}
assert_eq!(a, buf.as_slice());
- // Ensure it continues to fail in the same way.
+ // Ensure it continues to panic in the same way.
match reader.read(buf.as_mut_slice()) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, io::EndOfFile),
}
assert_eq!(a, buf.as_slice());
assert_eq!(Ok("hello world\n".to_string()), reader.read_line());
assert_eq!(Ok("how are you?".to_string()), reader.read_line());
match reader.read_line() {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, io::EndOfFile),
}
}
let wanted = vec![0u8, 0u8, 0u8, 42u8];
let got = match task::try(proc() { rx.recv() }) {
Ok(got) => got,
- Err(_) => fail!(),
+ Err(_) => panic!(),
};
assert_eq!(wanted, got);
match writer.write_u8(1) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, io::BrokenPipe),
}
}
///
/// * `n`: The value to convert.
/// * `size`: The size of the value, in bytes. This must be 8 or less, or task
-/// failure occurs. If this is less than 8, then a value of that
+/// panic occurs. If this is less than 8, then a value of that
/// many bytes is produced. For example, if `size` is 4, then a
/// 32-bit byte representation is produced.
/// * `f`: A callback that receives the value.
///
/// * `n`: The value to convert.
/// * `size`: The size of the value, in bytes. This must be 8 or less, or task
-/// failure occurs. If this is less than 8, then a value of that
+/// panic occurs. If this is less than 8, then a value of that
/// many bytes is produced. For example, if `size` is 4, then a
/// 32-bit byte representation is produced.
/// * `f`: A callback that receives the value.
/// * `data`: The buffer in which to extract the value.
/// * `start`: The offset at which to extract the value.
/// * `size`: The size of the value in bytes to extract. This must be 8 or
-/// less, or task failure occurs. If this is less than 8, then only
+/// less, or task panic occurs. If this is less than 8, then only
/// that many bytes are parsed. For example, if `size` is 4, then a
/// 32-bit value is parsed.
pub fn u64_from_be_bytes(data: &[u8], start: uint, size: uint) -> u64 {
assert!(size <= 8u);
if data.len() - start < size {
- fail!("index out of bounds");
+ panic!("index out of bounds");
}
let mut buf = [0u8, ..8];
///
/// let file = match File::open_mode(&p, Open, ReadWrite) {
/// Ok(f) => f,
- /// Err(e) => fail!("file error: {}", e),
+ /// Err(e) => panic!("file error: {}", e),
/// };
/// // do some stuff with that file
///
macro_rules! check( ($e:expr) => (
match $e {
Ok(t) => t,
- Err(e) => fail!("{} failed with: {}", stringify!($e), e),
+ Err(e) => panic!("{} failed with: {}", stringify!($e), e),
}
) )
macro_rules! error( ($e:expr, $s:expr) => (
match $e {
- Ok(val) => fail!("Unexpected success. Should've been: {}", $s),
+ Ok(val) => panic!("Unexpected success. Should've been: {}", $s),
Err(ref err) => assert!(err.to_string().as_slice().contains($s.as_slice()),
format!("`{}` did not contain `{}`", err, $s))
}
let mut read_stream = File::open_mode(filename, Open, Read);
let mut read_buf = [0, .. 1028];
let read_str = match check!(read_stream.read(read_buf)) {
- -1|0 => fail!("shouldn't happen"),
+ -1|0 => panic!("shouldn't happen"),
n => str::from_utf8(read_buf[..n]).unwrap().to_string()
};
assert_eq!(read_str.as_slice(), message);
check!(File::open(f).read(mem));
let read_str = str::from_utf8(mem).unwrap();
let expected = match n {
- None|Some("") => fail!("really shouldn't happen.."),
+ None|Some("") => panic!("really shouldn't happen.."),
Some(n) => format!("{}{}", prefix, n),
};
assert_eq!(expected.as_slice(), read_str);
from.display(), to.display()));
match copy(&from, &to) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(..) => {
assert!(!from.exists());
assert!(!to.exists());
check!(File::create(&out));
match copy(&out, tmpdir.path()) {
- Ok(..) => fail!(), Err(..) => {}
+ Ok(..) => panic!(), Err(..) => {}
}
}
let out = tmpdir.join("out");
match copy(tmpdir.path(), &out) {
- Ok(..) => fail!(), Err(..) => {}
+ Ok(..) => panic!(), Err(..) => {}
}
assert!(!out.exists());
}
fn readlink_not_symlink() {
let tmpdir = tmpdir();
match readlink(tmpdir.path()) {
- Ok(..) => fail!("wanted a failure"),
+ Ok(..) => panic!("wanted a failure"),
Err(..) => {}
}
}
// can't link to yourself
match link(&input, &input) {
- Ok(..) => fail!("wanted a failure"),
+ Ok(..) => panic!("wanted a failure"),
Err(..) => {}
}
// can't link to something that doesn't exist
match link(&tmpdir.join("foo"), &tmpdir.join("bar")) {
- Ok(..) => fail!("wanted a failure"),
+ Ok(..) => panic!("wanted a failure"),
Err(..) => {}
}
}
assert!(!check!(stat(&file)).perm.contains(io::USER_WRITE));
match chmod(&tmpdir.join("foo"), io::USER_RWX) {
- Ok(..) => fail!("wanted a failure"),
+ Ok(..) => panic!("wanted a panic"),
Err(..) => {}
}
let tmpdir = tmpdir();
match File::open_mode(&tmpdir.join("a"), io::Open, io::Read) {
- Ok(..) => fail!(), Err(..) => {}
+ Ok(..) => panic!(), Err(..) => {}
}
// Perform each one twice to make sure that it succeeds the second time
let mut f = check!(File::open_mode(&tmpdir.join("h"), io::Open,
io::Read));
match f.write("wut".as_bytes()) {
- Ok(..) => fail!(), Err(..) => {}
+ Ok(..) => panic!(), Err(..) => {}
}
}
assert!(check!(stat(&tmpdir.join("h"))).size == 3,
let tmpdir = tmpdir();
match change_file_times(&tmpdir.join("a"), 100, 200) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(..) => {}
}
}
writer.write([0]).unwrap();
match writer.write([0, 0]) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, io::OtherIoError),
}
}
let buf = [0xff];
let mut r = BufReader::new(buf);
match r.read_to_string() {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(..) => {}
}
}
/// # fn foo() {
/// let info = match Path::new("foo.txt").stat() {
/// Ok(stat) => stat,
-/// Err(e) => fail!("couldn't read foo.txt: {}", e),
+/// Err(e) => panic!("couldn't read foo.txt: {}", e),
/// };
///
/// println!("byte size: {}", info.size);
spawn(proc() {
match UnixStream::connect(&path2) {
Ok(c) => client(c),
- Err(e) => fail!("failed connect: {}", e),
+ Err(e) => panic!("failed connect: {}", e),
}
});
match acceptor.accept() {
Ok(c) => server(c),
- Err(e) => fail!("failed accept: {}", e),
+ Err(e) => panic!("failed accept: {}", e),
}
}
fn bind_error() {
let path = "path/to/nowhere";
match UnixListener::bind(&path) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => {
assert!(e.kind == PermissionDenied || e.kind == FileNotFound ||
e.kind == InvalidInput);
"path/to/nowhere"
};
match UnixStream::connect(&path) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => {
assert!(e.kind == FileNotFound || e.kind == OtherIoError);
}
let mut acceptor = match UnixListener::bind(&path1).listen() {
Ok(a) => a,
- Err(e) => fail!("failed listen: {}", e),
+ Err(e) => panic!("failed listen: {}", e),
};
spawn(proc() {
let mut stream = UnixStream::connect(&path2);
match stream.write([100]) {
Ok(..) => {}
- Err(e) => fail!("failed write: {}", e)
+ Err(e) => panic!("failed write: {}", e)
}
}
});
let mut buf = [0];
match client.read(buf) {
Ok(..) => {}
- Err(e) => fail!("failed read/accept: {}", e),
+ Err(e) => panic!("failed read/accept: {}", e),
}
assert_eq!(buf[0], 100);
}
match a.accept() {
Ok(..) => break,
Err(ref e) if e.kind == TimedOut => {}
- Err(e) => fail!("error: {}", e),
+ Err(e) => panic!("error: {}", e),
}
::task::deschedule();
- if i == 1000 { fail!("should have a pending connection") }
+ if i == 1000 { panic!("should have a pending connection") }
}
drop(l);
match s.write([0, .. 128 * 1024]) {
Ok(()) | Err(IoError { kind: ShortWrite(..), .. }) => {},
Err(IoError { kind: TimedOut, .. }) => break,
- Err(e) => fail!("{}", e),
+ Err(e) => panic!("{}", e),
}
- if i == 1000 { fail!("should have filled up?!"); }
+ if i == 1000 { panic!("should have filled up?!"); }
}
// I'm not sure as to why, but apparently the write on windows always
while amt < 100 * 128 * 1024 {
match s.read([0, ..128 * 1024]) {
Ok(n) => { amt += n; }
- Err(e) => fail!("{}", e),
+ Err(e) => panic!("{}", e),
}
}
let _ = rx.recv_opt();
match s.write([0, .. 128 * 1024]) {
Ok(()) | Err(IoError { kind: ShortWrite(..), .. }) => {},
Err(IoError { kind: TimedOut, .. }) => break,
- Err(e) => fail!("{}", e),
+ Err(e) => panic!("{}", e),
}
- if i == 1000 { fail!("should have filled up?!"); }
+ if i == 1000 { panic!("should have filled up?!"); }
}
tx.send(());
/// match socket {
/// Ok(s) => { /* handle s */ }
/// Err(ref e) if e.kind == EndOfFile => break, // closed
- /// Err(e) => fail!("unexpected error: {}", e),
+ /// Err(e) => panic!("unexpected error: {}", e),
/// }
/// }
/// });
#[test]
fn bind_error() {
match TcpListener::bind("0.0.0.0", 1) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, PermissionDenied),
}
}
#[test]
fn connect_error() {
match TcpStream::connect("0.0.0.0", 1) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, ConnectionRefused),
}
}
assert!(nread.is_err());
match stream.read(buf) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(ref e) => {
assert!(e.kind == NotConnected || e.kind == EndOfFile,
"unknown kind: {}", e.kind);
assert!(nread.is_err());
match stream.read(buf) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(ref e) => {
assert!(e.kind == NotConnected || e.kind == EndOfFile,
"unknown kind: {}", e.kind);
let listener = TcpListener::bind(ip_str.as_slice(), port).unwrap().listen();
assert!(listener.is_ok());
match TcpListener::bind(ip_str.as_slice(), port).listen() {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => {
assert!(e.kind == ConnectionRefused || e.kind == OtherIoError,
"unknown error: {} {}", e, e.kind);
match a.accept() {
Ok(..) => break,
Err(ref e) if e.kind == TimedOut => {}
- Err(e) => fail!("error: {}", e),
+ Err(e) => panic!("error: {}", e),
}
::task::deschedule();
- if i == 1000 { fail!("should have a pending connection") }
+ if i == 1000 { panic!("should have a pending connection") }
}
}
match s.write([0, .. 128 * 1024]) {
Ok(()) | Err(IoError { kind: ShortWrite(..), .. }) => {},
Err(IoError { kind: TimedOut, .. }) => break,
- Err(e) => fail!("{}", e),
+ Err(e) => panic!("{}", e),
}
- if i == 1000 { fail!("should have filled up?!"); }
+ if i == 1000 { panic!("should have filled up?!"); }
}
assert_eq!(s.write([0]).err().unwrap().kind, TimedOut);
while amt < 100 * 128 * 1024 {
match s.read([0, ..128 * 1024]) {
Ok(n) => { amt += n; }
- Err(e) => fail!("{}", e),
+ Err(e) => panic!("{}", e),
}
}
let _ = rx.recv_opt();
match s.write([0, .. 128 * 1024]) {
Ok(()) | Err(IoError { kind: ShortWrite(..), .. }) => {},
Err(IoError { kind: TimedOut, .. }) => break,
- Err(e) => fail!("{}", e),
+ Err(e) => panic!("{}", e),
}
- if i == 1000 { fail!("should have filled up?!"); }
+ if i == 1000 { panic!("should have filled up?!"); }
}
assert_eq!(s.write([0]).err().unwrap().kind, TimedOut);
/// let addr = SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 34254 };
/// let mut socket = match UdpSocket::bind(addr) {
/// Ok(s) => s,
-/// Err(e) => fail!("couldn't bind socket: {}", e),
+/// Err(e) => panic!("couldn't bind socket: {}", e),
/// };
///
/// let mut buf = [0, ..10];
fn bind_error() {
let addr = SocketAddr { ip: Ipv4Addr(0, 0, 0, 0), port: 1 };
match UdpSocket::bind(addr) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, PermissionDenied),
}
}
rx1.recv();
client.send_to([99], server_ip).unwrap()
}
- Err(..) => fail!()
+ Err(..) => panic!()
}
tx2.send(());
});
assert_eq!(buf[0], 99);
assert_eq!(src, client_ip);
}
- Err(..) => fail!()
+ Err(..) => panic!()
}
}
- Err(..) => fail!()
+ Err(..) => panic!()
}
rx2.recv();
}
rx.recv();
client.send_to([99], server_ip).unwrap()
}
- Err(..) => fail!()
+ Err(..) => panic!()
}
});
assert_eq!(buf[0], 99);
assert_eq!(src, client_ip);
}
- Err(..) => fail!()
+ Err(..) => panic!()
}
}
- Err(..) => fail!()
+ Err(..) => panic!()
}
}
let mut stream = client.connect(server_ip);
stream.write(val).unwrap();
}
- Err(..) => fail!()
+ Err(..) => panic!()
}
};
rx1.recv();
assert_eq!(nread, 1);
assert_eq!(buf[0], 99);
}
- Err(..) => fail!(),
+ Err(..) => panic!(),
}
}
- Err(..) => fail!()
+ Err(..) => panic!()
}
rx2.recv();
}
rx1.recv();
stream.write([99]).unwrap();
}
- Err(..) => fail!()
+ Err(..) => panic!()
}
tx2.send(());
});
assert_eq!(nread, 1);
assert_eq!(buf[0], 99);
}
- Err(..) => fail!()
+ Err(..) => panic!()
}
}
- Err(..) => fail!()
+ Err(..) => panic!()
}
rx2.recv();
}
rx.recv();
match sock2.recv_from(buf) {
Ok(..) => {}
- Err(e) => fail!("failed receive: {}", e),
+ Err(e) => panic!("failed receive: {}", e),
}
serv_tx.send(());
});
match a.send_to([0, ..4*1024], addr2) {
Ok(()) | Err(IoError { kind: ShortWrite(..), .. }) => {},
Err(IoError { kind: TimedOut, .. }) => break,
- Err(e) => fail!("other error: {}", e),
+ Err(e) => panic!("other error: {}", e),
}
}
}
///
/// let mut child = match Command::new("/bin/cat").arg("file.txt").spawn() {
/// Ok(child) => child,
-/// Err(e) => fail!("failed to execute child: {}", e),
+/// Err(e) => panic!("failed to execute child: {}", e),
/// };
///
/// let contents = child.stdout.as_mut().unwrap().read_to_end();
///
/// let mut process = match Command::new("sh").arg("-c").arg("echo hello").spawn() {
/// Ok(p) => p,
-/// Err(e) => fail!("failed to execute process: {}", e),
+/// Err(e) => panic!("failed to execute process: {}", e),
/// };
///
/// let output = process.stdout.as_mut().unwrap().read_to_end();
///
/// let output = match Command::new("cat").arg("foot.txt").output() {
/// Ok(output) => output,
- /// Err(e) => fail!("failed to execute process: {}", e),
+ /// Err(e) => panic!("failed to execute process: {}", e),
/// };
///
/// println!("status: {}", output.status);
///
/// let status = match Command::new("ls").status() {
/// Ok(status) => status,
- /// Err(e) => fail!("failed to execute process: {}", e),
+ /// Err(e) => panic!("failed to execute process: {}", e),
/// };
///
/// println!("process exited with: {}", status);
#[test]
fn smoke_failure() {
match Command::new("if-this-is-a-binary-then-the-world-has-ended").spawn() {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(..) => {}
}
}
let mut p = p.unwrap();
match p.wait().unwrap() {
process::ExitSignal(1) => {},
- result => fail!("not terminated by signal 1 (instead, {})", result),
+ result => panic!("not terminated by signal 1 (instead, {})", result),
}
}
fn test_process_output_fail_to_start() {
match Command::new("/no-binary-by-this-name-should-exist").output() {
Err(e) => assert_eq!(e.kind, FileNotFound),
- Ok(..) => fail!()
+ Ok(..) => panic!()
}
}
}
timer::sleep(Duration::milliseconds(100));
}
- fail!("never saw the child go away");
+ panic!("never saw the child go away");
}
#[test]
let mut fdes = match file::open(&path.to_c_str(), Truncate, Write) {
Ok(f) => f,
- Err(_) => fail!("failed to open file descriptor"),
+ Err(_) => panic!("failed to open file descriptor"),
};
let mut cmd = pwd_cmd();
Err(io::standard_error(io::EndOfFile));
match writer.write([0, 0, 0]) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, io::EndOfFile),
}
match writer.flush() {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, io::EndOfFile),
}
}
let mut buf = [];
match reader.read(buf) {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
Err(e) => assert_eq!(e.kind, io::EndOfFile),
}
}
/// Resets the task-local stderr handle to the specified writer
///
/// This will replace the current task's stderr handle, returning the old
-/// handle. Currently, the stderr handle is used for printing failure messages
-/// during task failure.
+/// handle. Currently, the stderr handle is used for printing panic messages
+/// during task panic.
///
/// Note that this does not need to be called for all new tasks; the default
/// output handle is to the process's stderr stream.
};
match result {
Ok(()) => {}
- Err(e) => fail!("failed printing to stdout: {}", e),
+ Err(e) => panic!("failed printing to stdout: {}", e),
}
}
let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx));
spawn(proc() {
::realstd::io::stdio::set_stderr(box w);
- fail!("my special message");
+ panic!("my special message");
});
let s = r.read_to_string().unwrap();
assert!(s.as_slice().contains("my special message"));
if sysctl(&mut mib[0], 2, &mut maxfiles as *mut libc::c_int as *mut libc::c_void, &mut size,
null_mut(), 0) != 0 {
let err = last_os_error();
- fail!("raise_fd_limit: error calling sysctl: {}", err);
+ panic!("raise_fd_limit: error calling sysctl: {}", err);
}
// Fetch the current resource limits
let mut rlim = rlimit{rlim_cur: 0, rlim_max: 0};
if getrlimit(RLIMIT_NOFILE, &mut rlim) != 0 {
let err = last_os_error();
- fail!("raise_fd_limit: error calling getrlimit: {}", err);
+ panic!("raise_fd_limit: error calling getrlimit: {}", err);
}
// Bump the soft limit to the smaller of kern.maxfilesperproc and the hard limit
// Set our newly-increased resource limit
if setrlimit(RLIMIT_NOFILE, &rlim) != 0 {
let err = last_os_error();
- fail!("raise_fd_limit: error calling setrlimit: {}", err);
+ panic!("raise_fd_limit: error calling setrlimit: {}", err);
}
}
}
fn oneshot_fail() {
let mut timer = Timer::new().unwrap();
let _rx = timer.oneshot(Duration::milliseconds(1));
- fail!();
+ panic!();
}
#[test]
fn period_fail() {
let mut timer = Timer::new().unwrap();
let _rx = timer.periodic(Duration::milliseconds(1));
- fail!();
+ panic!();
}
#[test]
#[should_fail]
fn normal_fail() {
let _timer = Timer::new().unwrap();
- fail!();
+ panic!();
}
#[test]
//! Finally, the [`prelude`](prelude/index.html) defines a
//! common set of traits, types, and functions that are made available
//! to all code by default. [`macros`](macros/index.html) contains
-//! all the standard macros, such as `assert!`, `fail!`, `println!`,
+//! all the standard macros, such as `assert!`, `panic!`, `println!`,
//! and `format!`, also available to all Rust code.
#![crate_name = "std"]
pub use io; // used for println!()
pub use local_data; // used for local_data_key!()
pub use option; // used for bitflags!{}
- pub use rt; // used for fail!()
+ pub use rt; // used for panic!()
pub use vec; // used for vec![]
// The test runner calls ::std::os::args() but really wants realstd
#![experimental]
#![macro_escape]
-/// The entry point for failure of rust tasks.
+/// The entry point for panic of Rust tasks.
///
-/// This macro is used to inject failure into a rust task, causing the task to
-/// unwind and fail entirely. Each task's failure can be reaped as the
-/// `Box<Any>` type, and the single-argument form of the `fail!` macro will be
+/// This macro is used to inject panic into a Rust task, causing the task to
+/// unwind and panic entirely. Each task's panic can be reaped as the
+/// `Box<Any>` type, and the single-argument form of the `panic!` macro will be
/// the value which is transmitted.
///
-/// The multi-argument form of this macro fails with a string and has the
+/// The multi-argument form of this macro panics with a string and has the
/// `format!` syntax for building a string.
///
/// # Example
///
/// ```should_fail
/// # #![allow(unreachable_code)]
-/// fail!();
-/// fail!("this is a terrible mistake!");
-/// fail!(4i); // fail with the value of 4 to be collected elsewhere
-/// fail!("this is a {} {message}", "fancy", message = "message");
+/// panic!();
+/// panic!("this is a terrible mistake!");
+/// panic!(4i); // panic with the value of 4 to be collected elsewhere
+/// panic!("this is a {} {message}", "fancy", message = "message");
/// ```
#[macro_export]
-macro_rules! fail(
+macro_rules! panic(
() => ({
- fail!("explicit failure")
+ panic!("explicit panic")
});
($msg:expr) => ({
// static requires less code at runtime, more constant data
// 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
/// Ensure that a boolean expression is `true` at runtime.
///
-/// This will invoke the `fail!` macro if the provided expression cannot be
+/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// # Example
///
/// ```
-/// // the failure message for these assertions is the stringified value of the
+/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// assert!(true);
/// # fn some_computation() -> bool { true }
macro_rules! assert(
($cond:expr) => (
if !$cond {
- fail!(concat!("assertion failed: ", stringify!($cond)))
+ panic!(concat!("assertion failed: ", stringify!($cond)))
}
);
($cond:expr, $($arg:expr),+) => (
if !$cond {
- fail!($($arg),+)
+ panic!($($arg),+)
}
);
)
/// Asserts that two expressions are equal to each other, testing equality in
/// both directions.
///
-/// On failure, this macro will print the values of the expressions.
+/// On panic, this macro will print the values of the expressions.
///
/// # Example
///
// check both directions of equality....
if !((*given_val == *expected_val) &&
(*expected_val == *given_val)) {
- fail!("assertion failed: `(left == right) && (right == left)` \
+ panic!("assertion failed: `(left == right) && (right == left)` \
(left: `{}`, right: `{}`)", *given_val, *expected_val)
}
}
/// Ensure that a boolean expression is `true` at runtime.
///
-/// This will invoke the `fail!` macro if the provided expression cannot be
+/// This will invoke the `panic!` macro if the provided expression cannot be
/// evaluated to `true` at runtime.
///
/// Unlike `assert!`, `debug_assert!` statements can be disabled by passing
/// # Example
///
/// ```
-/// // the failure message for these assertions is the stringified value of the
+/// // the panic message for these assertions is the stringified value of the
/// // expression given.
/// debug_assert!(true);
/// # fn some_expensive_computation() -> bool { true }
/// Asserts that two expressions are equal to each other, testing equality in
/// both directions.
///
-/// On failure, this macro will print the values of the expressions.
+/// On panic, this macro will print the values of the expressions.
///
/// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by
/// passing `--cfg ndebug` to the compiler. This makes `debug_assert_eq!`
($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); })
)
-/// A utility macro for indicating unreachable code. It will fail if
+/// A utility macro for indicating unreachable code. It will panic if
/// executed. This is occasionally useful to put after loops that never
/// terminate normally, but instead directly return from a function.
///
/// ```
#[macro_export]
macro_rules! unreachable(
- () => (fail!("internal error: entered unreachable code"))
+ () => (panic!("internal error: entered unreachable code"))
)
-/// A standardised placeholder for marking unfinished code. It fails with the
+/// A standardised placeholder for marking unfinished code. It panics with the
/// message `"not yet implemented"` when executed.
#[macro_export]
macro_rules! unimplemented(
- () => (fail!("not yet implemented"))
+ () => (panic!("not yet implemented"))
)
/// Use the syntax described in `std::fmt` to create a value of type `String`.
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),
ExpBin if radix >= DIGIT_P_RADIX // binary exponent 'p'
- => fail!("float_to_str_bytes_common: radix {} incompatible with \
+ => panic!("float_to_str_bytes_common: radix {} incompatible with \
use of 'p' as binary exponent", radix),
_ => ()
}
) -> Option<T> {
match exponent {
ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e'
- => fail!("from_str_bytes_common: radix {} incompatible with \
+ => panic!("from_str_bytes_common: radix {} incompatible with \
use of 'e' as decimal exponent", radix),
ExpBin if radix >= DIGIT_P_RADIX // binary exponent 'p'
- => fail!("from_str_bytes_common: radix {} incompatible with \
+ => panic!("from_str_bytes_common: radix {} incompatible with \
use of 'p' as binary exponent", radix),
_ if special && radix >= DIGIT_I_RADIX // first digit of 'inf'
- => fail!("from_str_bytes_common: radix {} incompatible with \
+ => panic!("from_str_bytes_common: radix {} incompatible with \
special values 'inf' and 'NaN'", radix),
_ if (radix as int) < 2
- => fail!("from_str_bytes_common: radix {} to low, \
+ => panic!("from_str_bytes_common: radix {} to low, \
must lie in the range [2, 36]", radix),
_ if (radix as int) > 36
- => fail!("from_str_bytes_common: radix {} to high, \
+ => panic!("from_str_bytes_common: radix {} to high, \
must lie in the range [2, 36]", radix),
_ => ()
}
let mut buf = [0 as c_char, ..BUF_BYTES];
unsafe {
if libc::getcwd(buf.as_mut_ptr(), buf.len() as libc::size_t).is_null() {
- fail!()
+ panic!()
}
Path::new(CString::new(buf.as_ptr(), false))
}
let mut buf = [0 as u16, ..BUF_BYTES];
unsafe {
if libc::GetCurrentDirectoryW(buf.len() as DWORD, buf.as_mut_ptr()) == 0 as DWORD {
- fail!();
+ panic!();
}
}
Path::new(String::from_utf16(::str::truncate_utf16_at_nul(buf))
};
let ch = GetEnvironmentStringsW();
if ch as uint == 0 {
- fail!("os::env() failure getting env string from OS: {}",
+ panic!("os::env() failure getting env string from OS: {}",
os::last_os_error());
}
// Here, we lossily decode the string as UTF16.
}
let mut environ = rust_env_pairs();
if environ as uint == 0 {
- fail!("os::env() failure getting env string from OS: {}",
+ panic!("os::env() failure getting env string from OS: {}",
os::last_os_error());
}
let mut result = Vec::new();
let p = buf.as_mut_ptr();
unsafe {
if strerror_r(errnum as c_int, p, buf.len() as libc::size_t) < 0 {
- fail!("strerror_r failure");
+ panic!("strerror_r failure");
}
::string::raw::from_buf(p as *const u8)
* Sets the process exit code
*
* Sets the exit code returned by the process if all supervised tasks
- * terminate successfully (without failing). If the current root task fails
+ * terminate successfully (without panicking). If the current root task panics
* and is supervised by the scheduler then any user-specified exit status is
- * ignored and the process exits with the default failure status.
+ * ignored and the process exits with the default panic status.
*
* Note that this is not synchronized against modifications of other threads.
*/
match rt::args::clone() {
Some(args) => args,
- None => fail!("process arguments not initialized")
+ None => panic!("process arguments not initialized")
}
}
#[cfg(unix)]
impl Drop for MemoryMap {
- /// Unmap the mapping. Fails the task if `munmap` fails.
+ /// Unmap the mapping. Panics the task if `munmap` panics.
fn drop(&mut self) {
if self.len == 0 { /* workaround for dummy_stack */ return; }
unsafe {
- // `munmap` only fails due to logic errors
+ // `munmap` only panics due to logic errors
libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
}
}
os::MapWritable
]) {
Ok(chunk) => chunk,
- Err(msg) => fail!("{}", msg)
+ Err(msg) => panic!("{}", msg)
};
assert!(chunk.len >= 16);
MapOffset(size / 2)
]) {
Ok(chunk) => chunk,
- Err(msg) => fail!("{}", msg)
+ Err(msg) => panic!("{}", msg)
};
assert!(chunk.len > 0);
#[test]
#[should_fail]
- fn test_not_utf8_fail() {
+ fn test_not_utf8_panics() {
Path::new(b"hello\x80.txt");
}
pub fn weak_rng() -> XorShiftRng {
match OsRng::new() {
Ok(mut r) => r.gen(),
- Err(e) => fail!("weak_rng: failed to create seeded RNG: {}", e)
+ Err(e) => panic!("weak_rng: failed to create seeded RNG: {}", e)
}
}
fn reseed(&mut self, rng: &mut StdRng) {
*rng = match StdRng::new() {
Ok(r) => r,
- Err(e) => fail!("could not reseed task_rng: {}", e)
+ Err(e) => panic!("could not reseed task_rng: {}", e)
}
}
}
None => {
let r = match StdRng::new() {
Ok(r) => r,
- Err(e) => fail!("could not initialize task_rng: {}", e)
+ Err(e) => panic!("could not initialize task_rng: {}", e)
};
let rng = reseeding::ReseedingRng::new(r,
TASK_RNG_RESEED_THRESHOLD,
// use this to get nicer error messages.
for (i, &byte) in v.iter().enumerate() {
if byte == 0 {
- fail!("byte {} of {} is zero", i, n)
+ panic!("byte {} of {} is zero", i, n)
}
}
}
#[test]
#[should_fail]
- fn test_gen_range_fail_int() {
+ fn test_gen_range_panic_int() {
let mut r = task_rng();
r.gen_range(5i, -2);
}
#[test]
#[should_fail]
- fn test_gen_range_fail_uint() {
+ fn test_gen_range_panic_uint() {
let mut r = task_rng();
r.gen_range(5u, 2u);
}
SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
};
if ret == -1 {
- fail!("couldn't generate random bytes: {}", os::last_os_error());
+ panic!("couldn't generate random bytes: {}", os::last_os_error());
}
}
}
v.as_mut_ptr())
};
if ret == 0 {
- fail!("couldn't generate random bytes: {}", os::last_os_error());
+ panic!("couldn't generate random bytes: {}", os::last_os_error());
}
}
}
CryptReleaseContext(self.hcryptprov, 0)
};
if ret == 0 {
- fail!("couldn't release context: {}", os::last_os_error());
+ panic!("couldn't release context: {}", os::last_os_error());
}
}
}
/// An RNG that reads random bytes straight from a `Reader`. This will
/// work best with an infinite reader, but this is not required.
///
-/// It will fail if it there is insufficient data to fulfill a request.
+/// # Panics
+///
+/// It will panic if it there is insufficient data to fulfill a request.
///
/// # Example
///
if v.len() == 0 { return }
match self.reader.read_at_least(v.len(), v) {
Ok(_) => {}
- Err(e) => fail!("ReaderRng.fill_bytes error: {}", e)
+ Err(e) => panic!("ReaderRng.fill_bytes error: {}", e)
}
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-//! Simple backtrace functionality (to print on failure)
+//! Simple backtrace functionality (to print on panic)
#![allow(non_camel_case_types)]
// while it doesn't requires lock for work as everything is
// local, it still displays much nicer backtraces when a
- // couple of tasks fail simultaneously
+ // couple of tasks panic simultaneously
static LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
let _g = unsafe { LOCK.lock() };
// FindEnclosingFunction on non-osx platforms. In doing so, we get a
// slightly more accurate stack trace in the process.
//
- // This is often because failure involves the last instruction of a
+ // This is often because panic involves the last instruction of a
// function being "call std::rt::begin_unwind", with no ret
// instructions after it. This means that the return instruction
// pointer points *outside* of the calling function, and by
pub use rustrt::{Stdio, Stdout, Stderr, begin_unwind, begin_unwind_fmt};
pub use rustrt::{bookkeeping, at_exit, unwind, DEFAULT_ERROR_CODE, Runtime};
-// Simple backtrace functionality (to print on failure)
+// Simple backtrace functionality (to print on panic)
pub mod backtrace;
// Just stuff
let opt_n: Option<uint> = FromStr::from_str(nstr.as_slice());
match opt_n {
Some(n) if n > 0 => n,
- _ => fail!("`RUST_THREADS` is `{}`, should be a positive integer", nstr)
+ _ => panic!("`RUST_THREADS` is `{}`, should be a positive integer", nstr)
}
}
None => {
let state = replace(&mut self.state, Evaluating);
match state {
Forced(v) => v,
- _ => fail!( "Logic error." ),
+ _ => panic!( "Logic error." ),
}
}
*/
match self.state {
Forced(ref v) => return v,
- Evaluating => fail!("Recursive forcing of future!"),
+ Evaluating => panic!("Recursive forcing of future!"),
Pending(_) => {
match replace(&mut self.state, Evaluating) {
- Forced(_) | Evaluating => fail!("Logic error."),
+ Forced(_) | Evaluating => panic!("Logic error."),
Pending(f) => {
self.state = Forced(f());
self.get_ref()
let (tx, rx) = channel();
spawn(proc() {
- // Don't fail if the other end has hung up
+ // Don't panic if the other end has hung up
let _ = tx.send_opt(blk());
});
#[test]
#[should_fail]
- fn test_futurefail() {
- let mut f = Future::spawn(proc() fail!());
+ fn test_future_panic() {
+ let mut f = Future::spawn(proc() panic!());
let _x: String = f.get();
}
}
#[test]
- fn test_dropped_future_doesnt_fail() {
+ fn test_dropped_future_doesnt_panic() {
struct Bomb(Sender<bool>);
local_data_key!(LOCAL: Bomb)
}
// Spawn a future, but drop it immediately. When we receive the result
- // later on, we should never view the task as having failed.
+ // later on, we should never view the task as having panicked.
let (tx, rx) = channel();
drop(Future::spawn(proc() {
LOCAL.replace(Some(Bomb(tx)));
}));
- // Make sure the future didn't fail the task.
+ // Make sure the future didn't panic the task.
assert!(!rx.recv());
}
}
/// `init_fn_factory` returns a function which, given the index of the
/// task, should return local data to be kept around in that task.
///
- /// # Failure
+ /// # Panics
///
- /// This function will fail if `n_tasks` is less than 1.
+ /// This function will panic if `n_tasks` is less than 1.
pub fn new(n_tasks: uint,
init_fn_factory: || -> proc(uint):Send -> T)
-> TaskPool<T> {
#[test]
#[should_fail]
-fn test_zero_tasks_failure() {
+fn test_zero_tasks_panic() {
let f: || -> proc(uint):Send -> uint = || { proc(i) i };
TaskPool::new(0, f);
}
//! using the atomically-reference-counted container,
//! [`Arc`](../../std/sync/struct.Arc.html).
//!
-//! Fatal logic errors in Rust cause *task failure*, during which
+//! Fatal logic errors in Rust cause *task panic*, during which
//! a task will unwind the stack, running destructors and freeing
-//! owned resources. Task failure is unrecoverable from within
-//! the failing task (i.e. there is no 'try/catch' in Rust), but
-//! failure may optionally be detected from a different task. If
-//! the main task fails the application will exit with a non-zero
+//! owned resources. Task panic is unrecoverable from within
+//! the panicking task (i.e. there is no 'try/catch' in Rust), but
+//! panic may optionally be detected from a different task. If
+//! the main task panics the application will exit with a non-zero
//! exit code.
//!
//! # Basic task scheduling
let tb: Option<Box<Task>> = Local::try_take();
match tb {
Some(t) => t.spawn_sibling(opts, f),
- None => fail!("need a local task to spawn a sibling task"),
+ None => panic!("need a local task to spawn a sibling task"),
};
}
}
// sidestep that whole issue by making builders uncopyable and making
// the run function move them in.
pub struct TaskBuilder<S = SiblingSpawner> {
- // A name for the task-to-be, for identification in failure messages
+ // A name for the task-to-be, for identification in panic messages
name: Option<SendStr>,
// The size of the stack for the spawned task
stack_size: Option<uint>,
impl<S: Spawner> TaskBuilder<S> {
/// Name the task-to-be. Currently the name is used for identification
- /// only in failure messages.
+ /// only in panic messages.
#[unstable = "IntoMaybeOwned will probably change."]
pub fn named<T: IntoMaybeOwned<'static>>(mut self, name: T) -> TaskBuilder<S> {
self.name = Some(name.into_maybe_owned());
///
/// # Return value
///
- /// If the child task executes successfully (without failing) then the
+ /// If the child task executes successfully (without panicking) then the
/// future returns `result::Ok` containing the value returned by the
- /// function. If the child task fails then the future returns `result::Err`
- /// containing the argument to `fail!(...)` as an `Any` trait object.
+ /// function. If the child task panics then the future returns `result::Err`
+ /// containing the argument to `panic!(...)` as an `Any` trait object.
#[experimental = "Futures are experimental."]
pub fn try_future<T:Send>(self, f: proc():Send -> T)
-> Future<Result<T, Box<Any + Send>>> {
}
/// Execute a function in a newly-spawnedtask and block until the task
- /// completes or fails. Equivalent to `.try_future(f).unwrap()`.
+ /// completes or panics. Equivalent to `.try_future(f).unwrap()`.
#[unstable = "Error type may change."]
pub fn try<T:Send>(self, f: proc():Send -> T) -> Result<T, Box<Any + Send>> {
self.try_future(f).unwrap()
}
/// Execute a function in a newly-spawned task and return either the return
-/// value of the function or an error if the task failed.
+/// value of the function or an error if the task panicked.
///
/// This is equivalent to `TaskBuilder::new().try`.
#[unstable = "Error type may change."]
task.yield_now();
}
-/// True if the running task is currently failing (e.g. will return `true` inside a
-/// destructor that is run while unwinding the stack after a call to `fail!()`).
+/// True if the running task is currently panicking (e.g. will return `true` inside a
+/// destructor that is run while unwinding the stack after a call to `panic!()`).
#[unstable = "May move to a different module."]
pub fn failing() -> bool {
use rt::task::Task;
assert!(result.unwrap().is_ok());
let result = TaskBuilder::new().try_future(proc() -> () {
- fail!();
+ panic!();
});
assert!(result.unwrap().is_err());
}
"Success!".to_string()
}).as_ref().map(|s| s.as_slice()) {
result::Ok("Success!") => (),
- _ => fail!()
+ _ => panic!()
}
}
#[test]
- fn test_try_fail() {
+ fn test_try_panic() {
match try(proc() {
- fail!()
+ panic!()
}) {
result::Err(_) => (),
- result::Ok(()) => fail!()
+ result::Ok(()) => panic!()
}
}
}
#[test]
- fn test_try_fail_message_static_str() {
+ fn test_try_panic_message_static_str() {
match try(proc() {
- fail!("static string");
+ panic!("static string");
}) {
Err(e) => {
type T = &'static str;
assert!(e.is::<T>());
assert_eq!(*e.downcast::<T>().unwrap(), "static string");
}
- Ok(()) => fail!()
+ Ok(()) => panic!()
}
}
#[test]
- fn test_try_fail_message_owned_str() {
+ fn test_try_panic_message_owned_str() {
match try(proc() {
- fail!("owned string".to_string());
+ panic!("owned string".to_string());
}) {
Err(e) => {
type T = String;
assert!(e.is::<T>());
assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
}
- Ok(()) => fail!()
+ Ok(()) => panic!()
}
}
#[test]
- fn test_try_fail_message_any() {
+ fn test_try_panic_message_any() {
match try(proc() {
- fail!(box 413u16 as Box<Any + Send>);
+ panic!(box 413u16 as Box<Any + Send>);
}) {
Err(e) => {
type T = Box<Any + Send>;
assert!(any.is::<u16>());
assert_eq!(*any.downcast::<u16>().unwrap(), 413u16);
}
- Ok(()) => fail!()
+ Ok(()) => panic!()
}
}
#[test]
- fn test_try_fail_message_unit_struct() {
+ fn test_try_panic_message_unit_struct() {
struct Juju;
match try(proc() {
- fail!(Juju)
+ panic!(Juju)
}) {
Err(ref e) if e.is::<Juju>() => {}
- Err(_) | Ok(()) => fail!()
+ Err(_) | Ok(()) => panic!()
}
}
pub fn seconds(seconds: i64) -> Duration {
let d = Duration { secs: seconds, nanos: 0 };
if d < MIN || d > MAX {
- fail!("Duration::seconds out of bounds");
+ panic!("Duration::seconds out of bounds");
}
d
}
//! ## Failure Propagation
//!
//! In addition to being a core primitive for communicating in rust, channels
-//! are the points at which failure is propagated among tasks. Whenever the one
+//! are the points at which panics are propagated among tasks. Whenever the one
//! half of channel is closed, the other half will have its next operation
-//! `fail!`. The purpose of this is to allow propagation of failure among tasks
+//! `panic!`. The purpose of this is to allow propagation of panics among tasks
//! that are linked to one another via channels.
//!
//! There are methods on both of senders and receivers to perform their
-//! respective operations without failing, however.
+//! respective operations without panicking, however.
//!
//! ## Runtime Requirements
//!
//! }
//! ```
//!
-//! Propagating failure:
+//! Propagating panics:
//!
//! ```should_fail
-//! // The call to recv() will fail!() because the channel has already hung
+//! // The call to recv() will panic!() because the channel has already hung
//! // up (or been deallocated)
//! let (tx, rx) = channel::<int>();
//! drop(tx);
/// becomes "rendezvous channel" where each send will not return until a recv
/// is paired with it.
///
-/// As with asynchronous channels, all senders will fail in `send` if the
+/// As with asynchronous channels, all senders will panic in `send` if the
/// `Receiver` has been destroyed.
///
/// # Example
///
/// Rust channels are infinitely buffered so this method will never block.
///
- /// # Failure
+ /// # Panics
///
- /// This function will fail if the other end of the channel has hung up.
+ /// This function will panic if the other end of the channel has hung up.
/// This means that if the corresponding receiver has fallen out of scope,
- /// this function will trigger a fail message saying that a message is
+ /// this function will trigger a panic message saying that a message is
/// being sent on a closed channel.
///
- /// Note that if this function does *not* fail, it does not mean that the
+ /// Note that if this function does *not* panic, it does not mean that the
/// data will be successfully received. All sends are placed into a queue,
/// so it is possible for a send to succeed (the other end is alive), but
/// then the other end could immediately disconnect.
///
- /// The purpose of this functionality is to propagate failure among tasks.
- /// If failure is not desired, then consider using the `send_opt` method
+ /// The purpose of this functionality is to propagate panicks among tasks.
+ /// If a panic is not desired, then consider using the `send_opt` method
#[experimental = "this function is being considered candidate for removal \
to adhere to the general guidelines of rust"]
pub fn send(&self, t: T) {
if self.send_opt(t).is_err() {
- fail!("sending on a closed channel");
+ panic!("sending on a closed channel");
}
}
///
/// Like `send`, this method will never block.
///
- /// # Failure
+ /// # Panics
///
- /// This method will never fail, it will return the message back to the
+ /// This method will never panic, it will return the message back to the
/// caller if the other end is disconnected
///
/// # Example
}
oneshot::UpDisconnected => (a, Err(t)),
oneshot::UpWoke(task) => {
- // This send cannot fail because the task is
+ // This send cannot panic because the task is
// asleep (we're looking at it), so the receiver
// can't go away.
(*a.get()).send(t).ok().unwrap();
/// time. If the buffer size is 0, however, it can be guaranteed that the
/// receiver has indeed received the data if this function returns success.
///
- /// # Failure
+ /// # Panics
///
- /// Similarly to `Sender::send`, this function will fail if the
+ /// Similarly to `Sender::send`, this function will panic if the
/// corresponding `Receiver` for this channel has disconnected. This
- /// behavior is used to propagate failure among tasks.
+ /// behavior is used to propagate panics among tasks.
///
- /// If failure is not desired, you can achieve the same semantics with the
- /// `SyncSender::send_opt` method which will not fail if the receiver
+ /// If a panic is not desired, you can achieve the same semantics with the
+ /// `SyncSender::send_opt` method which will not panic if the receiver
/// disconnects.
#[experimental = "this function is being considered candidate for removal \
to adhere to the general guidelines of rust"]
pub fn send(&self, t: T) {
if self.send_opt(t).is_err() {
- fail!("sending on a closed channel");
+ panic!("sending on a closed channel");
}
}
/// is returned back to the callee. This function is similar to `try_send`,
/// except that it will block if the channel is currently full.
///
- /// # Failure
+ /// # Panics
///
- /// This function cannot fail.
+ /// This function cannot panic.
#[unstable = "this function may be renamed to send() in the future"]
pub fn send_opt(&self, t: T) -> Result<(), T> {
unsafe { (*self.inner.get()).send(t) }
/// See `SyncSender::send` for notes about guarantees of whether the
/// receiver has received the data or not if this function is successful.
///
- /// # Failure
+ /// # Panics
///
- /// This function cannot fail
+ /// This function cannot panic
#[unstable = "the return type of this function is candidate for \
modification"]
pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> {
/// on the channel from its paired `Sender` structure. This receiver will
/// be woken up when data is ready, and the data will be returned.
///
- /// # Failure
+ /// # Panics
///
- /// Similar to channels, this method will trigger a task failure if the
+ /// Similar to channels, this method will trigger a task panic if the
/// other end of the channel has hung up (been deallocated). The purpose of
- /// this is to propagate failure among tasks.
+ /// this is to propagate panicks among tasks.
///
- /// If failure is not desired, then there are two options:
+ /// If a panic is not desired, then there are two options:
///
/// * If blocking is still desired, the `recv_opt` method will return `None`
/// when the other end hangs up
pub fn recv(&self) -> T {
match self.recv_opt() {
Ok(t) => t,
- Err(()) => fail!("receiving on a closed channel"),
+ Err(()) => panic!("receiving on a closed channel"),
}
}
/// This is useful for a flavor of "optimistic check" before deciding to
/// block on a receiver.
///
- /// This function cannot fail.
+ /// # Panics
+ ///
+ /// This function cannot panic.
#[unstable = "the return type of this function may be altered"]
pub fn try_recv(&self) -> Result<T, TryRecvError> {
// If a thread is spinning in try_recv, we should take the opportunity
}
}
- /// Attempt to wait for a value on this receiver, but does not fail if the
+ /// Attempt to wait for a value on this receiver, but does not panic if the
/// corresponding channel has hung up.
///
/// This implementation of iterators for ports will always block if there is
- /// not data available on the receiver, but it will not fail in the case
+ /// not data available on the receiver, but it will not panic in the case
/// that the channel has been deallocated.
///
/// In other words, this function has the same semantics as the `recv`
- /// method except for the failure aspect.
+ /// method except for the panic aspect.
///
/// If the channel has hung up, then `Err` is returned. Otherwise `Ok` of
/// the value found on the receiver is returned.
}
/// Returns an iterator which will block waiting for messages, but never
- /// `fail!`. It will return `None` when the channel has hung up.
+ /// `panic!`. It will return `None` when the channel has hung up.
#[unstable]
pub fn iter<'a>(&'a self) -> Messages<'a, T> {
Messages { rx: self }
assert_eq!(rx.recv(), 1);
}
match rx.try_recv() {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
_ => {}
}
dtx.send(());
} #[should_fail])
test!(fn oneshot_single_thread_recv_chan_close() {
- // Receiving on a closed chan will fail
+ // Receiving on a closed chan will panic
let res = task::try(proc() {
let (tx, rx) = channel::<int>();
drop(tx);
assert_eq!(rx.recv(), 1);
}
match rx.try_recv() {
- Ok(..) => fail!(),
+ Ok(..) => panic!(),
_ => {}
}
dtx.send(());
} #[should_fail])
test!(fn oneshot_single_thread_recv_chan_close() {
- // Receiving on a closed chan will fail
+ // Receiving on a closed chan will panic
let res = task::try(proc() {
let (tx, rx) = sync_channel::<int>(0);
drop(tx);
// Sanity check
match self.upgrade {
NothingSent => {}
- _ => fail!("sending on a oneshot that's already sent on "),
+ _ => panic!("sending on a oneshot that's already sent on "),
}
assert!(self.data.is_none());
self.data = Some(t);
let prev = match self.upgrade {
NothingSent => NothingSent,
SendUsed => SendUsed,
- _ => fail!("upgrading again"),
+ _ => panic!("upgrading again"),
};
self.upgrade = GoUp(up);
impl Select {
/// Creates a new selection structure. This set is initially empty and
- /// `wait` will fail!() if called.
+ /// `wait` will panic!() if called.
///
/// Usage of this struct directly can sometimes be burdensome, and usage is
/// rather much easier through the `select!` macro.
tx1.send(1);
select! (
foo = rx1.recv() => { assert_eq!(foo, 1); },
- _bar = rx2.recv() => { fail!() }
+ _bar = rx2.recv() => { panic!() }
)
tx2.send(2);
select! (
- _foo = rx1.recv() => { fail!() },
+ _foo = rx1.recv() => { panic!() },
bar = rx2.recv() => { assert_eq!(bar, 2) }
)
drop(tx1);
select! (
foo = rx1.recv_opt() => { assert_eq!(foo, Err(())); },
- _bar = rx2.recv() => { fail!() }
+ _bar = rx2.recv() => { panic!() }
)
drop(tx2);
select! (
let (tx5, rx5) = channel::<int>();
tx5.send(4);
select! (
- _foo = rx1.recv() => { fail!("1") },
- _foo = rx2.recv() => { fail!("2") },
- _foo = rx3.recv() => { fail!("3") },
- _foo = rx4.recv() => { fail!("4") },
+ _foo = rx1.recv() => { panic!("1") },
+ _foo = rx2.recv() => { panic!("2") },
+ _foo = rx3.recv() => { panic!("3") },
+ _foo = rx4.recv() => { panic!("4") },
foo = rx5.recv() => { assert_eq!(foo, 4); }
)
})
drop(tx2);
select! (
- _a1 = rx1.recv_opt() => { fail!() },
+ _a1 = rx1.recv_opt() => { panic!() },
a2 = rx2.recv_opt() => { assert_eq!(a2, Err(())); }
)
})
select! (
a = rx1.recv() => { assert_eq!(a, 1); },
- _b = rx2.recv() => { fail!() }
+ _b = rx2.recv() => { panic!() }
)
tx3.send(1);
select! (
a = rx1.recv_opt() => { assert_eq!(a, Err(())); },
- _b = rx2.recv() => { fail!() }
+ _b = rx2.recv() => { panic!() }
)
})
tx3.send(());
select!(
_i1 = rx1.recv() => {},
- _i2 = rx2.recv() => fail!()
+ _i2 = rx2.recv() => panic!()
)
tx3.send(());
})
tx3.send(());
select!(
_i1 = rx1.recv() => {},
- _i2 = rx2.recv() => fail!()
+ _i2 = rx2.recv() => panic!()
)
tx3.send(());
})
Thread::yield_now();
match self.queue.pop() {
mpsc::Data(t) => { data = t; break }
- mpsc::Empty => fail!("inconsistent => empty"),
+ mpsc::Empty => panic!("inconsistent => empty"),
mpsc::Inconsistent => {}
}
}
match self.channels.fetch_sub(1, atomic::SeqCst) {
1 => {}
n if n > 1 => return,
- n => fail!("bad number of channels left {}", n),
+ n => panic!("bad number of channels left {}", n),
}
match self.cnt.swap(DISCONNECTED, atomic::SeqCst) {
/// which means that every successful send is paired with a successful recv.
///
/// This flavor of channels defines a new `send_opt` method for channels which
-/// is the method by which a message is sent but the task does not fail if it
+/// is the method by which a message is sent but the task does not panic if it
/// cannot be delivered.
///
/// Another major difference is that send() will *always* return back the data
// success, someone's about to receive our buffered data.
BlockedReceiver(task) => { wakeup(task, guard); Ok(()) }
- BlockedSender(..) => fail!("lolwut"),
+ BlockedSender(..) => panic!("lolwut"),
}
}
while left > 0 {
match s.steal() {
Data((1, 10)) => { left -= 1; }
- Data(..) => fail!(),
+ Data(..) => panic!(),
Abort | Empty => {}
}
}
Data(box 20) => {
(*unsafe_remaining).fetch_sub(1, SeqCst);
}
- Data(..) => fail!(),
+ Data(..) => panic!(),
Abort | Empty => {}
}
}
while remaining.load(SeqCst) > 0 {
match w.pop() {
Some(box 20) => { remaining.fetch_sub(1, SeqCst); }
- Some(..) => fail!(),
+ Some(..) => panic!(),
None => {}
}
}
loop {
match s.steal() {
Data(2) => { HITS.fetch_add(1, SeqCst); }
- Data(..) => fail!(),
+ Data(..) => panic!(),
_ if DONE.load(SeqCst) => break,
_ => {}
}
match w.pop() {
None => {}
Some(2) => { HITS.fetch_add(1, SeqCst); },
- Some(_) => fail!(),
+ Some(_) => panic!(),
}
} else {
expected += 1;
match w.pop() {
None => {}
Some(2) => { HITS.fetch_add(1, SeqCst); },
- Some(_) => fail!(),
+ Some(_) => panic!(),
}
}
DONE.store(true, SeqCst);
Data((1, 2)) => {
(*thread_box).fetch_add(1, SeqCst);
}
- Data(..) => fail!(),
+ Data(..) => panic!(),
_ if DONE.load(SeqCst) => break,
_ => {}
}
match w.pop() {
None => {}
Some((1, 2)) => myhit = true,
- Some(_) => fail!(),
+ Some(_) => panic!(),
}
} else {
w.push((1, 2));
//!
//! The wrappers in this module build on the primitives from `sync::raw` to
//! provide safe interfaces around using the primitive locks. These primitives
-//! implement a technique called "poisoning" where when a task failed with a
-//! held lock, all future attempts to use the lock will fail.
+//! implement a technique called "poisoning" where when a task panicked with a
+//! held lock, all future attempts to use the lock will panic.
//!
-//! For example, if two tasks are contending on a mutex and one of them fails
-//! after grabbing the lock, the second task will immediately fail because the
+//! For example, if two tasks are contending on a mutex and one of them panics
+//! after grabbing the lock, the second task will immediately panic because the
//! lock is now poisoned.
use core::prelude::*;
impl<'a> PoisonOnFail<'a> {
fn check(flag: bool, name: &str) {
if flag {
- fail!("Poisoned {} - another task failed inside!", name);
+ panic!("Poisoned {} - another task failed inside!", name);
}
}
///
/// wait() is equivalent to wait_on(0).
///
- /// # Failure
+ /// # Panics
///
/// A task which is killed while waiting on a condition variable will wake
- /// up, fail, and unlock the associated lock as it unwinds.
+ /// up, panic, and unlock the associated lock as it unwinds.
#[inline]
pub fn wait(&self) { self.wait_on(0) }
/// when dropped. All concurrent tasks attempting to lock the mutex will
/// block while the returned value is still alive.
///
- /// # Failure
+ /// # Panics
///
- /// Failing while inside the Mutex will unlock the Mutex while unwinding, so
+ /// Panicking while inside the Mutex will unlock the Mutex while unwinding, so
/// that other tasks won't block forever. It will also poison the Mutex:
/// any tasks that subsequently try to access it (including those already
- /// blocked on the mutex) will also fail immediately.
+ /// blocked on the mutex) will also panic immediately.
#[inline]
pub fn lock<'a>(&'a self) -> MutexGuard<'a, T> {
let guard = self.lock.lock();
/// Access the underlying data mutably. Locks the rwlock in write mode;
/// other readers and writers will block.
///
- /// # Failure
+ /// # Panics
///
- /// Failing while inside the lock will unlock the lock while unwinding, so
+ /// Panicking while inside the lock will unlock the lock while unwinding, so
/// that other tasks won't block forever. As Mutex.lock, it will also poison
- /// the lock, so subsequent readers and writers will both also fail.
+ /// the lock, so subsequent readers and writers will both also panic.
#[inline]
pub fn write<'a>(&'a self) -> RWLockWriteGuard<'a, T> {
let guard = self.lock.write();
let lock = arc2.lock();
lock.cond.signal();
// Parent should fail when it wakes up.
- fail!();
+ panic!();
});
let lock = arc.lock();
}
}
let _u = Unwinder { i: arc2 };
- fail!();
+ panic!();
});
let lock = arc.lock();
assert_eq!(*lock, 2);
}
}
let _u = Unwinder { i: arc2 };
- fail!();
+ panic!();
});
let lock = arc.read();
assert_eq!(*lock, 2);
let q = Queue::new();
match q.pop() {
Empty => {}
- Inconsistent | Data(..) => fail!()
+ Inconsistent | Data(..) => panic!()
}
let (tx, rx) = channel();
let q = Arc::new(q);
impl<'a> Condvar<'a> {
/// Atomically drop the associated lock, and block until a signal is sent.
///
- /// # Failure
+ /// # Panics
///
/// A task which is killed while waiting on a condition variable will wake
- /// up, fail, and unlock the associated lock as it unwinds.
+ /// up, panic, and unlock the associated lock as it unwinds.
pub fn wait(&self) { self.wait_on(0) }
/// As wait(), but can specify which of multiple condition variables to
///
/// The associated lock must have been initialised with an appropriate
/// number of condvars. The condvar_id must be between 0 and num_condvars-1
- /// or else this call will fail.
+ /// or else this call will panic.
///
/// wait() is equivalent to wait_on(0).
pub fn wait_on(&self, condvar_id: uint) {
}
}
-// Checks whether a condvar ID was out of bounds, and fails if so, or does
+// Checks whether a condvar ID was out of bounds, and panics if so, or does
// something else next on success.
#[inline]
fn check_cvar_bounds<U>(
-> U {
match out_of_bounds {
Some(0) =>
- fail!("{} with illegal ID {} - this lock has no condvars!", act, id),
+ panic!("{} with illegal ID {} - this lock has no condvars!", act, id),
Some(length) =>
- fail!("{} with illegal ID {} - ID must be less than {}", act, id, length),
+ panic!("{} with illegal ID {} - ID must be less than {}", act, id, length),
None => blk()
}
}
impl Semaphore {
/// Create a new semaphore with the specified count.
///
- /// # Failure
+ /// # Panics
///
- /// This function will fail if `count` is negative.
+ /// This function will panic if `count` is negative.
pub fn new(count: int) -> Semaphore {
Semaphore { sem: Sem::new(count, ()) }
}
/// A blocking, bounded-waiting, mutual exclusion lock with an associated
/// FIFO condition variable.
///
-/// # Failure
-/// A task which fails while holding a mutex will unlock the mutex as it
+/// # Panics
+///
+/// A task which panicks while holding a mutex will unlock the mutex as it
/// unwinds.
pub struct Mutex {
sem: Sem<Vec<WaitQueue>>,
/// Create a new mutex, with a specified number of associated condvars. This
/// will allow calling wait_on/signal_on/broadcast_on with condvar IDs
/// between 0 and num_condvars-1. (If num_condvars is 0, lock_cond will be
- /// allowed but any operations on the condvar will fail.)
+ /// allowed but any operations on the condvar will panic.)
pub fn new_with_condvars(num_condvars: uint) -> Mutex {
Mutex { sem: Sem::new_and_signal(1, num_condvars) }
}
/// A blocking, no-starvation, reader-writer lock with an associated condvar.
///
-/// # Failure
+/// # Panics
///
-/// A task which fails while holding an rwlock will unlock the rwlock as it
+/// A task which panics while holding an rwlock will unlock the rwlock as it
/// unwinds.
pub struct RWLock {
order_lock: Semaphore,
fn test_mutex_killed_simple() {
use std::any::Any;
- // Mutex must get automatically unlocked if failed/killed within.
+ // Mutex must get automatically unlocked if panicked/killed within.
let m = Arc::new(Mutex::new());
let m2 = m.clone();
let result: result::Result<(), Box<Any + Send>> = task::try(proc() {
let _lock = m2.lock();
- fail!();
+ panic!();
});
assert!(result.is_err());
// child task must have finished by the time try returns
fn rwlock_kill_helper(mode1: RWLockMode, mode2: RWLockMode) {
use std::any::Any;
- // Mutex must get automatically unlocked if failed/killed within.
+ // Mutex must get automatically unlocked if panicked/killed within.
let x = Arc::new(RWLock::new());
let x2 = x.clone();
let result: result::Result<(), Box<Any + Send>> = task::try(proc() {
lock_rwlock_in_mode(&x2, mode1, || {
- fail!();
+ panic!();
})
});
assert!(result.is_err());
loop {
match consumer.pop() {
Some(1i) => break,
- Some(_) => fail!(),
+ Some(_) => panic!(),
None => {}
}
}
// one example and its non-hygienic counterpart would be:
// syntax::parse::token::Token::mtwt_eq
// syntax::ext::tt::macro_parser::token_name_eq
- fail!("not allowed to compare these idents: {}, {}. \
+ panic!("not allowed to compare these idents: {}, {}. \
Probably related to issue \\#6993", self, other);
}
}
ident: i.ident, decl: &**decl, style: style, body: &**block,
generics: generics, abi: abi, id: i.id, span: i.span
}),
- _ => fail!("item FnLikeNode that is not fn-like"),
+ _ => panic!("item FnLikeNode that is not fn-like"),
},
ast_map::NodeTraitItem(t) => match *t {
ast::ProvidedMethod(ref m) => method(&**m),
- _ => fail!("trait method FnLikeNode that is not fn-like"),
+ _ => panic!("trait method FnLikeNode that is not fn-like"),
},
ast_map::NodeImplItem(ii) => {
match *ii {
ast::MethodImplItem(ref m) => method(&**m),
ast::TypeImplItem(_) => {
- fail!("impl method FnLikeNode that is not fn-like")
+ panic!("impl method FnLikeNode that is not fn-like")
}
}
}
closure(ClosureParts::new(&**decl, &**block, e.id, e.span)),
ast::ExprProc(ref decl, ref block) =>
closure(ClosureParts::new(&**decl, &**block, e.id, e.span)),
- _ => fail!("expr FnLikeNode that is not fn-like"),
+ _ => panic!("expr FnLikeNode that is not fn-like"),
},
- _ => fail!("other FnLikeNode that is not fn-like"),
+ _ => panic!("other FnLikeNode that is not fn-like"),
}
}
}
&self.forest.krate
}
- /// Retrieve the Node corresponding to `id`, failing if it cannot
+ /// Retrieve the Node corresponding to `id`, panicking if it cannot
/// be found.
pub fn get(&self, id: NodeId) -> Node<'ast> {
match self.find(id) {
Some(node) => node,
- None => fail!("couldn't find node id {} in the AST map", id)
+ None => panic!("couldn't find node id {} in the AST map", id)
}
}
};
match abi {
Some(abi) => abi,
- None => fail!("expected foreign mod or inlined parent, found {}",
+ None => panic!("expected foreign mod or inlined parent, found {}",
self.node_to_string(parent))
}
}
pub fn expect_item(&self, id: NodeId) -> &'ast Item {
match self.find(id) {
Some(NodeItem(item)) => item,
- _ => fail!("expected item, found {}", self.node_to_string(id))
+ _ => panic!("expected item, found {}", self.node_to_string(id))
}
}
Some(NodeItem(i)) => {
match i.node {
ItemStruct(ref struct_def, _) => &**struct_def,
- _ => fail!("struct ID bound to non-struct")
+ _ => panic!("struct ID bound to non-struct")
}
}
Some(NodeVariant(variant)) => {
match variant.node.kind {
StructVariantKind(ref struct_def) => &**struct_def,
- _ => fail!("struct ID bound to enum variant that isn't struct-like"),
+ _ => panic!("struct ID bound to enum variant that isn't struct-like"),
}
}
- _ => fail!(format!("expected struct, found {}", self.node_to_string(id))),
+ _ => panic!(format!("expected struct, found {}", self.node_to_string(id))),
}
}
pub fn expect_variant(&self, id: NodeId) -> &'ast Variant {
match self.find(id) {
Some(NodeVariant(variant)) => variant,
- _ => fail!(format!("expected variant, found {}", self.node_to_string(id))),
+ _ => panic!(format!("expected variant, found {}", self.node_to_string(id))),
}
}
pub fn expect_foreign_item(&self, id: NodeId) -> &'ast ForeignItem {
match self.find(id) {
Some(NodeForeignItem(item)) => item,
- _ => fail!("expected foreign item, found {}", self.node_to_string(id))
+ _ => panic!("expected foreign item, found {}", self.node_to_string(id))
}
}
pub fn expect_expr(&self, id: NodeId) -> &'ast Expr {
match self.find(id) {
Some(NodeExpr(expr)) => expr,
- _ => fail!("expected expr, found {}", self.node_to_string(id))
+ _ => panic!("expected expr, found {}", self.node_to_string(id))
}
}
PathName(ident.name)
}
MethMac(_) => {
- fail!("no path elem for {}", node)
+ panic!("no path elem for {}", node)
}
}
}
MethDecl(ident, _, _, _, _, _, _, _) => {
PathName(ident.name)
}
- MethMac(_) => fail!("no path elem for {}", node),
+ MethMac(_) => panic!("no path elem for {}", node),
}
}
TypeTraitItem(ref m) => PathName(m.ident.name),
},
NodeVariant(v) => PathName(v.node.name.name),
- _ => fail!("no path elem for {}", node)
+ _ => panic!("no path elem for {}", node)
}
}
pub fn span(&self, id: NodeId) -> Span {
self.opt_span(id)
- .unwrap_or_else(|| fail!("AstMap.span: could not find span for id {}", id))
+ .unwrap_or_else(|| panic!("AstMap.span: could not find span for id {}", id))
}
pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span {
fn name(&self) -> Name {
match self.node {
MethDecl(i, _, _, _, _, _, _, _) => i.name,
- MethMac(_) => fail!("encountered unexpanded method macro."),
+ MethMac(_) => panic!("encountered unexpanded method macro."),
}
}
}
// these cases do not carry enough information in the
// ast_map to reconstruct their full structure for pretty
// printing.
- NodeLocal(_) => fail!("cannot print isolated Local"),
- NodeArg(_) => fail!("cannot print isolated Arg"),
- NodeStructCtor(_) => fail!("cannot print isolated StructCtor"),
+ NodeLocal(_) => panic!("cannot print isolated Local"),
+ NodeArg(_) => panic!("cannot print isolated Arg"),
+ NodeStructCtor(_) => panic!("cannot print isolated StructCtor"),
}
}
}
StmtDecl(_, id) => id,
StmtExpr(_, id) => id,
StmtSemi(_, id) => id,
- StmtMac(..) => fail!("attempted to analyze unexpanded stmt")
+ StmtMac(..) => panic!("attempted to analyze unexpanded stmt")
}
}
abi: abi,
}
},
- MethMac(_) => fail!("expected non-macro method declaration")
+ MethMac(_) => panic!("expected non-macro method declaration")
}
}
RequiredMethod(ref m) => (*m).clone(),
ProvidedMethod(ref m) => trait_method_to_ty_method(&**m),
TypeTraitItem(_) => {
- fail!("trait_method_to_ty_method(): expected method but found \
+ panic!("trait_method_to_ty_method(): expected method but found \
typedef")
}
}
slice.iter().all(|p| walk_pat(&**p, |p| it(p))) &&
after.iter().all(|p| walk_pat(&**p, |p| it(p)))
}
- PatMac(_) => fail!("attempted to analyze unexpanded pattern"),
+ PatMac(_) => panic!("attempted to analyze unexpanded pattern"),
PatWild(_) | PatLit(_) | PatRange(_, _) | PatIdent(_, _, _) |
PatEnum(_, _) => {
true
match self.node {
$field_pat => $result,
MethMac(_) => {
- fail!("expected an AST without macro invocations");
+ panic!("expected an AST without macro invocations");
}
}
}
// FIXME #8256: this used to be an assert but whatever precondition
// it's testing isn't true for all spans in the AST, so to allow the
- // caller to not have to fail (and it can't catch it since the CodeMap
+ // caller to not have to panic (and it can't catch it since the CodeMap
// isn't sendable), return None
if begin.fm.start_pos != end.fm.start_pos {
None
return fm.clone();
}
}
- fail!("asking for {} which we don't know about", filename);
+ panic!("asking for {} which we don't know about", filename);
}
pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
break;
}
if a == 0 {
- fail!("position {} does not resolve to a source location",
+ panic!("position {} does not resolve to a source location",
pos.to_uint());
}
a -= 1;
}
if a >= len {
- fail!("position {} does not resolve to a source location",
+ panic!("position {} does not resolve to a source location",
pos.to_uint())
}
sp: RenderSpan, msg: &str, lvl: Level);
}
-/// This structure is used to signify that a task has failed with a fatal error
+/// This structure is used to signify that a task has panicked with a fatal error
/// from the diagnostics. You can use this with the `Any` trait to figure out
/// how a rustc task died (if so desired).
pub struct FatalError;
impl SpanHandler {
pub fn span_fatal(&self, sp: Span, msg: &str) -> ! {
self.handler.emit(Some((&self.cm, sp)), msg, Fatal);
- fail!(FatalError);
+ panic!(FatalError);
}
pub fn span_err(&self, sp: Span, msg: &str) {
self.handler.emit(Some((&self.cm, sp)), msg, Error);
}
pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
self.handler.emit(Some((&self.cm, sp)), msg, Bug);
- fail!(ExplicitBug);
+ panic!(ExplicitBug);
}
pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
self.span_bug(sp, format!("unimplemented {}", msg).as_slice());
impl Handler {
pub fn fatal(&self, msg: &str) -> ! {
self.emit.borrow_mut().emit(None, msg, None, Fatal);
- fail!(FatalError);
+ panic!(FatalError);
}
pub fn err(&self, msg: &str) {
self.emit.borrow_mut().emit(None, msg, None, Error);
}
pub fn bug(&self, msg: &str) -> ! {
self.emit.borrow_mut().emit(None, msg, None, Bug);
- fail!(ExplicitBug);
+ panic!(ExplicitBug);
}
pub fn unimpl(&self, msg: &str) -> ! {
self.bug(format!("unimplemented {}", msg).as_slice());
match error {
Ok(()) => {}
- Err(e) => fail!("failed to print diagnostics: {}", e),
+ Err(e) => panic!("failed to print diagnostics: {}", e),
}
}
sp: RenderSpan, msg: &str, lvl: Level) {
match emit(self, cm, sp, msg, None, lvl, true) {
Ok(()) => {}
- Err(e) => fail!("failed to print diagnostics: {}", e),
+ Err(e) => panic!("failed to print diagnostics: {}", e),
}
}
}
// expand pats... they might contain macro uses:
let expanded_pats = arm.pats.move_map(|pat| fld.fold_pat(pat));
if expanded_pats.len() == 0 {
- fail!("encountered match arm with 0 patterns");
+ panic!("encountered match arm with 0 patterns");
}
// all of the pats must have the same set of bindings, so use the
// first one to extract them and generate new names:
// good lord, you can't make a path with 0 segments, can you?
let final_varref_ident = match varref.segments.last() {
Some(pathsegment) => pathsegment.identifier,
- None => fail!("varref with 0 path segments?")
+ None => panic!("varref with 0 path segments?")
};
let varref_name = mtwt::resolve(final_varref_ident);
let varref_idents : Vec<ast::Ident>
let cxbinds: &[&ast::Ident] = cxbinds.as_slice();
let cxbind = match cxbinds {
[b] => b,
- _ => fail!("expected just one binding for ext_cx")
+ _ => panic!("expected just one binding for ext_cx")
};
let resolved_binding = mtwt::resolve(*cxbind);
let varrefs = crate_varrefs(&cr);
resolvedthis
}
}
- IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt")
+ IllegalCtxt => panic!("expected resolvable context, got IllegalCtxt")
}
};
resolve_table.insert(key, resolved);
loopvar = tl;
}
}
- IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt")
+ IllegalCtxt => panic!("expected resolvable context, got IllegalCtxt")
}
}
}
with_sctable(|sctable| {
match (*sctable.table.borrow())[ctxt as uint] {
Mark(mrk, _) => mrk,
- _ => fail!("can't retrieve outer mark when outside is not a mark")
+ _ => panic!("can't retrieve outer mark when outside is not a mark")
}
})
}
sc = tail;
continue;
}
- IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt")
+ IllegalCtxt => panic!("expected resolvable context, got IllegalCtxt")
}
}
}
Some(ast) => ast,
None => {
error!("parse error");
- fail!()
+ panic!()
}
}
}
vec!(mk_name(cx, sp, ident.ident())));
}
- token::Interpolated(_) => fail!("quote! with interpolated token"),
+ token::Interpolated(_) => panic!("quote! with interpolated token"),
_ => ()
}
token::Dollar => "Dollar",
token::Underscore => "Underscore",
token::Eof => "Eof",
- _ => fail!(),
+ _ => panic!(),
};
mk_token_path(cx, sp, name)
}
.chain(mk_tt(cx, sp, &close.to_tt()).into_iter())
.collect()
},
- ast::TtSequence(..) => fail!("TtSequence in quote!"),
+ ast::TtSequence(..) => panic!("TtSequence in quote!"),
ast::TtNonterminal(sp, ident) => {
// tt.extend($ident.to_tokens(ext_cx).into_iter())
token::get_ident(name),
token::get_ident(bind))).to_string()
}
- _ => fail!()
+ _ => panic!()
} }).collect::<Vec<String>>().connect(" or ");
return Error(sp, format!(
"local ambiguity: multiple parsing options: \
parse_nt(&mut rust_parser, name_string.get()))));
ei.idx += 1u;
}
- _ => fail!()
+ _ => panic!()
}
cur_eis.push(ei);
/// silently drop anything. `allow_semi` is so that "optional"
/// semicolons at the end of normal expressions aren't complained
/// about e.g. the semicolon in `macro_rules! kapow( () => {
- /// fail!(); } )` doesn't get picked up by .parse_expr(), but it's
+ /// panic!(); } )` doesn't get picked up by .parse_expr(), but it's
/// allowed to be there.
fn ensure_complete_parse(&self, allow_semi: bool) {
let mut parser = self.parser.borrow_mut();
}
fn fold_mac(&mut self, _macro: Mac) -> Mac {
- fail!("fold_mac disabled by default");
+ panic!("fold_mac disabled by default");
// NB: see note about macros above.
// if you really want a folder that
// works on macros, use this
let a_val = $a;
let b_val = $b;
if !(pred_val(a_val.as_slice(),b_val.as_slice())) {
- fail!("expected args satisfying {}, got {} and {}",
+ panic!("expected args satisfying {}, got {} and {}",
$predname, a_val, b_val);
}
}
return lines.connect("\n");
}
- fail!("not a doc-comment: {}", comment);
+ panic!("not a doc-comment: {}", comment);
}
fn push_blank_line_comment(rdr: &StringReader, comments: &mut Vec<Comment>) {
read_block_comment(rdr, code_to_the_left, comments);
} else if rdr.curr_is('#') && rdr.nextch_is('!') {
read_shebang_comment(rdr, code_to_the_left, comments);
- } else { fail!(); }
+ } else { panic!(); }
debug!("<<< consume comment");
}
whence: &str) {
match r.curr {
Some(r_c) if r_c == c => r.bump(),
- Some(r_c) => fail!("expected {}, hit {}, {}", described_c, r_c, whence),
- None => fail!("expected {}, hit EOF, {}", described_c, whence),
+ Some(r_c) => panic!("expected {}, hit {}, {}", described_c, r_c, whence),
+ None => panic!("expected {}, hit EOF, {}", described_c, whence),
}
}
self.scan_digits(base);
let encoded_name : u32 = self.with_str_from(start_bpos, |s| {
num::from_str_radix(s, 10).unwrap_or_else(|| {
- fail!("expected digits representing a name, got `{}`, {}, range [{},{}]",
+ panic!("expected digits representing a name, got `{}`, {}, range [{},{}]",
s, whence, start_bpos, self.last_pos);
})
});
self.scan_digits(base);
let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| {
num::from_str_radix(s, 10).unwrap_or_else(|| {
- fail!("expected digits representing a ctxt, got `{}`, {}", s, whence);
+ panic!("expected digits representing a ctxt, got `{}`, {}", s, whence);
})
});
let mut lexer = setup(&sh, "/* /* */ */'a'".to_string());
match lexer.next_token().tok {
token::Comment => { },
- _ => fail!("expected a comment!")
+ _ => panic!("expected a comment!")
}
assert_eq!(lexer.next_token().tok, token::LitChar(token::intern("a")));
}
match v.checked_add(&count) {
Some(next) => { self.node_id.set(next); }
- None => fail!("Input too large, ran out of node ids!")
+ None => panic!("Input too large, ran out of node ids!")
}
v
'0' => Some('\0'),
_ => { None }
},
- _ => fail!("lexer accepted invalid char escape `{}`", lit)
+ _ => panic!("lexer accepted invalid char escape `{}`", lit)
};
match c {
match c {
'\\' => {
let ch = chars.peek().unwrap_or_else(|| {
- fail!("{}", error(i).as_slice())
+ panic!("{}", error(i).as_slice())
}).val1();
if ch == '\n' {
} else if ch == '\r' {
chars.next();
let ch = chars.peek().unwrap_or_else(|| {
- fail!("{}", error(i).as_slice())
+ panic!("{}", error(i).as_slice())
}).val1();
if ch != '\n' {
- fail!("lexer accepted bare CR");
+ panic!("lexer accepted bare CR");
}
eat(&mut chars);
} else {
},
'\r' => {
let ch = chars.peek().unwrap_or_else(|| {
- fail!("{}", error(i).as_slice())
+ panic!("{}", error(i).as_slice())
}).val1();
if ch != '\n' {
- fail!("lexer accepted bare CR");
+ panic!("lexer accepted bare CR");
}
chars.next();
res.push('\n');
Some(c) => {
if c == '\r' {
if *chars.peek().unwrap() != '\n' {
- fail!("lexer accepted bare CR");
+ panic!("lexer accepted bare CR");
}
chars.next();
res.push('\n');
match ::std::num::from_str_radix::<u64>(lit.slice(2, 4), 16) {
Some(c) =>
if c > 0xFF {
- fail!(err(2))
+ panic!(err(2))
} else {
return (c as u8, 4)
},
- None => fail!(err(3))
+ None => panic!(err(3))
}
}
};
b'\r' => {
chars.next();
if chars.peek().expect(em.as_slice()).val1() != b'\n' {
- fail!("lexer accepted bare CR");
+ panic!("lexer accepted bare CR");
}
eat(&mut chars);
}
Some((i, b'\r')) => {
let em = error(i);
if chars.peek().expect(em.as_slice()).val1() != b'\n' {
- fail!("lexer accepted bare CR");
+ panic!("lexer accepted bare CR");
}
chars.next();
res.push(b'\n');
ast::TtToken(_, token::Ident(name, token::Plain))],
&ast::Delimiter { token: token::RParen, .. })
if name.as_str() == "a" => {},
- _ => fail!("value 3: {}", **first_delimed),
+ _ => panic!("value 3: {}", **first_delimed),
}
let (ref second_open, ref second_tts, ref second_close) = **second_delimed;
match (second_open, second_tts.as_slice(), second_close) {
ast::TtToken(_, token::Ident(name, token::Plain))],
&ast::Delimiter { token: token::RParen, .. })
if name.as_str() == "a" => {},
- _ => fail!("value 4: {}", **second_delimed),
+ _ => panic!("value 4: {}", **second_delimed),
}
},
- _ => fail!("value 2: {}", **macro_delimed),
+ _ => panic!("value 2: {}", **macro_delimed),
}
},
- _ => fail!("value: {}",tts),
+ _ => panic!("value: {}",tts),
}
}
break;
}
IoviForeignItem(_) => {
- fail!();
+ panic!();
}
}
attrs = self.parse_outer_attributes();
items.push(item)
}
IoviForeignItem(_) => {
- fail!();
+ panic!();
}
}
}
}
Eof => {
// Eof should never get here.
- fail!();
+ panic!();
}
}
}
Inconsistent, struct_def.fields.as_slice(),
|s, field| {
match field.node.kind {
- ast::NamedField(..) => fail!("unexpected named field"),
+ ast::NamedField(..) => panic!("unexpected named field"),
ast::UnnamedField(vis) => {
try!(s.print_visibility(vis));
try!(s.maybe_print_comment(field.span.lo));
for field in struct_def.fields.iter() {
match field.node.kind {
- ast::UnnamedField(..) => fail!("unexpected unnamed field"),
+ ast::UnnamedField(..) => panic!("unexpected unnamed field"),
ast::NamedField(ident, visibility) => {
try!(self.hardbreak_if_not_bol());
try!(self.maybe_print_comment(field.span.lo));
}
// BLEAH, constraints would be great here
_ => {
- fail!("print_if saw if with weird alternative");
+ panic!("print_if saw if with weird alternative");
}
}
}
match self.repr {
One(ref v) if idx == 0 => v,
Many(ref vs) => &vs[idx],
- _ => fail!("out of bounds access")
+ _ => panic!("out of bounds access")
}
}
if v.len() == 1 {
v.into_iter().next().unwrap()
} else {
- fail!(err)
+ panic!(err)
}
}
- _ => fail!(err)
+ _ => panic!(err)
}
}
walk_explicit_self(self, es)
}
fn visit_mac(&mut self, _macro: &'v Mac) {
- fail!("visit_mac disabled by default");
+ panic!("visit_mac disabled by default");
// NB: see note about macros above.
// if you really want a visitor that
// works on macros, use this
'x' => FormatHex,
'X' => FormatHEX,
's' => FormatString,
- _ => fail!("bad FormatOp char")
+ _ => panic!("bad FormatOp char")
}
}
fn to_char(self) -> char {
}
// A function that runs a test. If the function returns successfully,
-// the test succeeds; if the function fails then the test fails. We
+// the test succeeds; if the function panics then the test fails. We
// may need to come up with a more clever definition of test in order
// to support isolation of tests into tasks.
pub enum TestFn {
let opts =
match parse_opts(args) {
Some(Ok(o)) => o,
- Some(Err(msg)) => fail!("{}", msg),
+ Some(Err(msg)) => panic!("{}", msg),
None => return
};
match run_tests_console(&opts, tests) {
Ok(true) => {}
- Ok(false) => fail!("Some tests failed"),
- Err(e) => fail!("io error when running tests: {}", e),
+ Ok(false) => panic!("Some tests failed"),
+ Err(e) => panic!("io error when running tests: {}", e),
}
}
// A variant optimized for invocation with a static test vector.
-// This will fail (intentionally) when fed any dynamic tests, because
+// This will panic (intentionally) when fed any dynamic tests, because
// it is copying the static values out into a dynamic vector and cannot
// copy dynamic values. It is doing this because from this point on
// a ~[TestDescAndFn] is used in order to effect ownership-transfer
match t.testfn {
StaticTestFn(f) => TestDescAndFn { testfn: StaticTestFn(f), desc: t.desc.clone() },
StaticBenchFn(f) => TestDescAndFn { testfn: StaticBenchFn(f), desc: t.desc.clone() },
- _ => fail!("non-static tests passed to test::test_main_static")
+ _ => panic!("non-static tests passed to test::test_main_static")
}
}).collect();
test_main(args, owned_tests)
#[bench] - Indicates a function is a benchmark to be run. This
function takes one argument (test::Bencher).
#[should_fail] - This function (also labeled with #[test]) will only pass if
- the code causes a failure (an assertion failure or fail!)
+ the code causes a failure (an assertion failure or panic!)
#[ignore] - When applied to a function which is already attributed as a
test, then the test runner will ignore these tests during
normal test runs. Running with --ignored will run these
it.next()) {
(Some(a), Some(b), None) => {
if a <= 0 || a > b {
- fail!("tried to run shard {a}.{b}, but {a} is out of bounds \
+ panic!("tried to run shard {a}.{b}, but {a} is out of bounds \
(should be between 1 and {b}", a=a, b=b)
}
Some((a, b))
let opt_n: Option<uint> = FromStr::from_str(s.as_slice());
match opt_n {
Some(n) if n > 0 => n,
- _ => fail!("RUST_TEST_TASKS is `{}`, should be a positive integer.", s)
+ _ => panic!("RUST_TEST_TASKS is `{}`, should be a positive integer.", s)
}
}
None => {
///
/// # Failure
///
- /// This function will fail if the path does not exist or the path does not
+ /// This function will panic if the path does not exist or the path does not
/// contain a valid metric map.
pub fn load(p: &Path) -> MetricMap {
assert!(p.exists());
let mut decoder = json::Decoder::new(value);
MetricMap(match Decodable::decode(&mut decoder) {
Ok(t) => t,
- Err(e) => fail!("failure decoding JSON: {}", e)
+ Err(e) => panic!("failure decoding JSON: {}", e)
})
}
#[test]
pub fn do_not_run_ignored_tests() {
- fn f() { fail!(); }
+ fn f() { panic!(); }
let desc = TestDescAndFn {
desc: TestDesc {
name: StaticTestName("whatever"),
#[test]
fn test_should_fail() {
- fn f() { fail!(); }
+ fn f() { panic!(); }
let desc = TestDescAndFn {
desc: TestDesc {
name: StaticTestName("whatever"),
let args = vec!("progname".to_string(), "some_regex_filter".to_string());
let opts = match parse_opts(args.as_slice()) {
Some(Ok(o)) => o,
- _ => fail!("Malformed arg in first_free_arg_should_be_a_filter")
+ _ => panic!("Malformed arg in first_free_arg_should_be_a_filter")
};
assert!(opts.filter.expect("should've found filter").is_match("some_regex_filter"))
}
"--ignored".to_string());
let opts = match parse_opts(args.as_slice()) {
Some(Ok(o)) => o,
- _ => fail!("Malformed arg in parse_ignored_flag")
+ _ => panic!("Malformed arg in parse_ignored_flag")
};
assert!((opts.run_ignored));
}
== Err(InvalidTime));
match strptime("Fri Feb 13 15:31:30.01234 2009", format) {
- Err(e) => fail!(e),
+ Err(e) => panic!(e),
Ok(ref tm) => {
assert!(tm.tm_sec == 30_i32);
assert!(tm.tm_min == 31_i32);
fn test(s: &str, format: &str) -> bool {
match strptime(s, format) {
Ok(ref tm) => tm.strftime(format).unwrap() == s.to_string(),
- Err(e) => fail!(e)
+ Err(e) => panic!(e)
}
}
return entry.value.clone();
}
}
- fail!();
+ panic!();
}
#[inline]
pub unsafe fn f(xs: Vec<int> ) {
- xs.iter().map(|_x| { unsafe fn q() { fail!(); } }).collect::<Vec<()>>();
+ xs.iter().map(|_x| { unsafe fn q() { panic!(); } }).collect::<Vec<()>>();
}
#[phase(plugin, link)] extern crate log;
pub fn foo<T>() {
- fn death() -> int { fail!() }
+ fn death() -> int { panic!() }
debug!("{}", (||{ death() })());
}
}
impl<'a> IntoMaybeOwned<'a> for Inv<'a> {
- fn into_maybe_owned(self) -> MaybeOwned<'a> { fail!() }
- fn into_inv(self) -> Inv<'a> { fail!() }
- fn bigger_region<'b:'a>(self, b: Inv<'b>) { fail!() }
+ fn into_maybe_owned(self) -> MaybeOwned<'a> { panic!() }
+ fn into_inv(self) -> Inv<'a> { panic!() }
+ fn bigger_region<'b:'a>(self, b: Inv<'b>) { panic!() }
}
pub fn read<T:read>(s: String) -> T {
match read::readMaybe(s) {
Some(x) => x,
- _ => fail!("read failed!")
+ _ => panic!("read panicked!")
}
}
pub fn foo() {
let _a = A;
- fail!("wut");
+ panic!("wut");
}
mod std {
for _ in range(0u, 20000) {
v.push('b' as u8);
if !str::is_utf8(v.as_slice()) {
- fail!("is_utf8 failed");
+ panic!("is_utf8 panicked");
}
}
}
for _ in range(0u, 5000) {
v.push_all(s.as_bytes());
if !str::is_utf8(v.as_slice()) {
- fail!("is_utf8 failed");
+ panic!("is_utf8 panicked");
}
}
}
7 => {" seven"}
8 => {" eight"}
9 => {" nine"}
- _ => {fail!("expected digits from 0 to 9...")}
+ _ => {panic!("expected digits from 0 to 9...")}
}
}
'C' => 1,
'G' => 2,
'T' => 3,
- _ => fail!("{}", c as char),
+ _ => panic!("{}", c as char),
}
}
for id in range(0u8, 10) {
if m & (1 << (id + 50) as uint) != 0 {return id;}
}
- fail!("{:016x} does not have a valid identifier", m);
+ panic!("{:016x} does not have a valid identifier", m);
}
// Converts a list of mask to a Vec<u8>.
Ok(ref m) => {
return Config {stress: m.opt_present("stress")}
}
- Err(_) => { fail!(); }
+ Err(_) => { panic!(); }
}
}
from_str::<uint>(comps[2]).unwrap() as u8;
}
else {
- fail!("Invalid sudoku file");
+ panic!("Invalid sudoku file");
}
}
return Sudoku::new(g)
ptr = ptr + 1u;
} else {
// no: redo this field aft recoloring pred; unless there is none
- if ptr == 0u { fail!("No solution found for this sudoku"); }
+ if ptr == 0u { panic!("No solution found for this sudoku"); }
ptr = ptr - 1u;
}
}
for _ in range(0, repeat) {
println!("starting {:.4f}", precise_time_s());
task::try(proc() {
- recurse_or_fail(depth, None)
+ recurse_or_panic(depth, None)
});
println!("stopping {:.4f}", precise_time_s());
}
}
}
-fn recurse_or_fail(depth: int, st: Option<State>) {
+fn recurse_or_panic(depth: int, st: Option<State>) {
if depth == 0 {
println!("unwinding {:.4f}", precise_time_s());
- fail!();
+ panic!();
} else {
let depth = depth - 1;
}
};
- recurse_or_fail(depth, Some(st));
+ recurse_or_panic(depth, Some(st));
}
}
let (tx, rx) = channel();
child_generation(from_str::<uint>(args[1].as_slice()).unwrap(), tx);
if rx.recv_opt().is_err() {
- fail!("it happened when we slumbered");
+ panic!("it happened when we slumbered");
}
}
// Tests that a function with a ! annotation always actually fails
fn bad_bang(i: uint) -> ! { //~ ERROR computation may converge in a function marked as diverging
- if i < 0u { } else { fail!(); }
+ if i < 0u { } else { panic!(); }
}
fn main() { bad_bang(5u); }
let x = Some((X { x: () }, X { x: () }));
match x {
Some((ref _y, _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern
- None => fail!()
+ None => panic!()
}
}
let x = some2(X { x: () }, X { x: () });
match x {
some2(ref _y, _z) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern
- none2 => fail!()
+ none2 => panic!()
}
}
let x = Some((X { x: () }, X { x: () }));
match x {
Some((_y, ref _z)) => { }, //~ ERROR cannot bind by-move and by-ref in the same pattern
- None => fail!()
+ None => panic!()
}
}
let x = Some(rx);
tx.send(false);
match x {
- Some(z) if z.recv() => { fail!() }, //~ ERROR cannot bind by-move into a pattern guard
+ Some(z) if z.recv() => { panic!() }, //~ ERROR cannot bind by-move into a pattern guard
Some(z) => { assert!(!z.recv()); },
- None => fail!()
+ None => panic!()
}
}
let a = match y {
Y(ref mut a, _) => a,
- X => fail!()
+ X => panic!()
};
let b = match y {
Y(_, ref mut b) => b,
- X => fail!()
+ X => panic!()
};
*a += 1;
let a = match y {
Y(ref mut a, _) => a,
- X => fail!()
+ X => panic!()
};
let b = match y {
Y(ref mut b, _) => b, //~ ERROR cannot borrow
- X => fail!()
+ X => panic!()
};
*a += 1;
x = X(Left((0,0)));
(*f)()
},
- _ => fail!()
+ _ => panic!()
}
})
}
int2: int,
}
-fn make_foo() -> Box<Foo> { fail!() }
+fn make_foo() -> Box<Foo> { panic!() }
fn borrow_same_field_twice_mut_mut() {
let mut foo = make_foo();
int2: int,
}
-fn make_foo() -> Foo { fail!() }
+fn make_foo() -> Foo { panic!() }
fn borrow_same_field_twice_mut_mut() {
let mut foo = make_foo();
}
fn e(x: &mut int) {
- let c1: || = || x = fail!(); //~ ERROR closure cannot assign to immutable local variable
+ let c1: || = || x = panic!(); //~ ERROR closure cannot assign to immutable local variable
}
fn main() {
fn borrow(_v: &int) {}
fn borrow_mut(_v: &mut int) {}
-fn cond() -> bool { fail!() }
-fn for_func(_f: || -> bool) { fail!() }
-fn produce<T>() -> T { fail!(); }
+fn cond() -> bool { panic!() }
+fn for_func(_f: || -> bool) { panic!() }
+fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<int>) {
*v = box() (**v + 1);
fn borrow(_v: &int) {}
fn borrow_mut(_v: &mut int) {}
-fn cond() -> bool { fail!() }
-fn produce<T>() -> T { fail!(); }
+fn cond() -> bool { panic!() }
+fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<int>) {
*v = box() (**v + 1);
fn borrow(_v: &int) {}
fn borrow_mut(_v: &mut int) {}
-fn cond() -> bool { fail!() }
-fn for_func(_f: || -> bool) { fail!() }
-fn produce<T>() -> T { fail!(); }
+fn cond() -> bool { panic!() }
+fn for_func(_f: || -> bool) { panic!() }
+fn produce<T>() -> T { panic!(); }
fn inc(v: &mut Box<int>) {
*v = box() (**v + 1);
*x = Right(1.0);
*z
}
- _ => fail!()
+ _ => panic!()
}
}
Some(ref m) => { //~ ERROR borrowed value does not live long enough
msg = m;
},
- None => { fail!() }
+ None => { panic!() }
}
println!("{}", *msg);
}
let vec: &[int] = vec.as_slice(); //~ ERROR does not live long enough
let tail = match vec {
[_, tail..] => tail,
- _ => fail!("a")
+ _ => panic!("a")
};
tail
}
let vec: &[int] = vec.as_slice(); //~ ERROR does not live long enough
let init = match vec {
[init.., _] => init,
- _ => fail!("b")
+ _ => panic!("b")
};
init
}
let vec: &[int] = vec.as_slice(); //~ ERROR does not live long enough
let slice = match vec {
[_, slice.., _] => slice,
- _ => fail!("c")
+ _ => panic!("c")
};
slice
}
let vec: &[int] = vec.as_slice(); //~ ERROR `vec` does not live long enough
let tail = match vec {
[_a, tail..] => &tail[0],
- _ => fail!("foo")
+ _ => panic!("foo")
};
tail
}
fn main() {
// Type inference didn't use to be able to handle this:
- foo(|| fail!());
- foo(|| -> ! fail!());
+ foo(|| panic!());
+ foo(|| -> ! panic!());
foo(|| 22i); //~ ERROR computation may converge in a function marked as diverging
foo(|| -> ! 22i); //~ ERROR computation may converge in a function marked as diverging
let x = || -> ! 1i; //~ ERROR computation may converge in a function marked as diverging
impl<T> MyTrait<T> for T { //~ ERROR E0119
fn get(&self) -> T {
- fail!()
+ panic!()
}
}
#![deny(unreachable_code)]
fn main() {
- let x: || -> ! = || fail!();
+ let x: || -> ! = || panic!();
x();
println!("Foo bar"); //~ ERROR: unreachable statement
}
fn main() {
match *1 { //~ ERROR: cannot be dereferenced
- _ => { fail!(); }
+ _ => { panic!(); }
}
}
fn foo() { //~ ERROR function is never used
// none of these should have any dead_code exposed to the user
- fail!();
+ panic!();
- fail!("foo");
+ panic!("foo");
- fail!("bar {}", "baz")
+ panic!("bar {}", "baz")
}
fn foo() { //~ ERROR function is never used
// none of these should have any dead_code exposed to the user
- fail!();
+ panic!();
- fail!("foo");
+ panic!("foo");
- fail!("bar {}", "baz")
+ panic!("bar {}", "baz")
}
// error-pattern:unexpected token
fn main() {
- fail!(@);
+ panic!(@);
}
}
impl<'a> Foo<'a> for &'a str {
- fn bar<T: Bar<'a>>(self) -> &'a str { fail!() } //~ ERROR lifetime
+ fn bar<T: Bar<'a>>(self) -> &'a str { panic!() } //~ ERROR lifetime
}
fn main() {
struct A { foo: int }
-fn a() -> A { fail!() }
+fn a() -> A { panic!() }
fn main() {
let A { .., } = a(); //~ ERROR: expected `}`
struct A { foo: int }
-fn a() -> A { fail!() }
+fn a() -> A { panic!() }
fn main() {
let A { , } = a(); //~ ERROR: expected ident
match a {
Ok(a) => //~ ERROR: mismatched types
println!("{}",a),
- None => fail!()
+ None => panic!()
}
}
&Cons(val, box ref next_list) => tail(next_list),
&Cons(val, box Nil) => Cons(val, box Nil),
//~^ ERROR: unreachable pattern
- _ => fail!()
+ _ => panic!()
}
}
// except according to those terms.
fn new<T>() -> &'static T {
- fail!()
+ panic!()
}
fn main() {
// except according to those terms.
fn new<'r, T>() -> &'r T {
- fail!()
+ panic!()
}
fn main() {
// tricked into looking up a non-existing second type parameter.
let _x: uint = match Some(1u) {
Ok(u) => u, //~ ERROR mismatched types: expected `core::option::Option<uint>`
- Err(e) => fail!(e) //~ ERROR mismatched types: expected `core::option::Option<uint>`
+ Err(e) => panic!(e) //~ ERROR mismatched types: expected `core::option::Option<uint>`
};
}
impl<A> vec_monad<A> for Vec<A> {
fn bind<B>(&self, f: |A| -> Vec<B> ) {
- let mut r = fail!();
+ let mut r = panic!();
for elt in self.iter() { r = r + f(*elt); }
//~^ ERROR the type of this value must be known
//~^^ ERROR not implemented
fn fail_len(v: Vec<int> ) -> uint {
let mut i = 3;
- fail!();
+ panic!();
for x in v.iter() { i += 1u; }
//~^ ERROR: unreachable statement
return i;
// except according to those terms.
fn main() {
- let x = fail!();
+ let x = panic!();
x.clone(); //~ ERROR the type of this value must be known in this context
}
// `chan` is not a trait, it's an enum
impl chan for int { //~ ERROR `chan` is not a trait
- fn send(&self, v: int) { fail!() }
+ fn send(&self, v: int) { panic!() }
}
fn main() {
fn foo() { //~ NOTE Did you mean to close this delimiter?
match Some(x) {
- Some(y) { fail!(); }
- None { fail!(); }
+ Some(y) { panic!(); }
+ None { panic!(); }
}
fn bar() {
}
impl A for E {
- fn b<F: Sync, G>(_x: F) -> F { fail!() } //~ ERROR type parameter 0 requires `Sync`
+ fn b<F: Sync, G>(_x: F) -> F { panic!() } //~ ERROR type parameter 0 requires `Sync`
}
fn main() {}
impl A for E {
// n.b. The error message is awful -- see #3404
- fn b<F:Clone,G>(&self, _x: G) -> G { fail!() } //~ ERROR method `b` has an incompatible type
+ fn b<F:Clone,G>(&self, _x: G) -> G { panic!() } //~ ERROR method `b` has an incompatible type
}
fn main() {}
//~^ ERROR unresolved name `k0`.
}
}
- fail!();
+ panic!();
}
fn main() {}
box Element(ed) => match ed.kind { //~ ERROR non-exhaustive patterns
box HTMLImageElement(ref d) if d.image.is_some() => { true }
},
- _ => fail!("WAT") //~ ERROR unreachable pattern
+ _ => panic!("WAT") //~ ERROR unreachable pattern
};
}
fn getChildOption(&self) -> Option<Box<P>> {
static childVal: Box<P> = self.child.get();
//~^ ERROR attempt to use a non-constant value in a constant
- fail!();
+ panic!();
}
}
let a = 5;
let _iter = TrieMapIterator{node: &a};
_iter.node = & //~ ERROR cannot assign to immutable field
- fail!()
+ panic!()
}
// except according to those terms.
fn foo<T>(t: T) {}
-fn main() { foo(fail!()) }
+fn main() { foo(panic!()) }
//~^ ERROR type annotations required
#![deny(unreachable_code)]
-fn g() -> ! { fail!(); }
+fn g() -> ! { panic!(); }
fn f() -> ! {
return g(); //~ ERROR `return` in a function declared as diverging
g();
#![deny(unreachable_code)]
fn f() -> ! {
- return fail!(); //~ ERROR `return` in a function declared as diverging
- fail!(); // the unreachable statement error is in <std macro>, at this line, there
+ return panic!(); //~ ERROR `return` in a function declared as diverging
+ panic!(); // the unreachable statement error is in <std macro>, at this line, there
// only is a note
}
// Lifetime annotation needed because we have no arguments.
fn f() -> &int { //~ ERROR missing lifetime specifier
//~^ NOTE there is no value for it to be borrowed from
- fail!()
+ panic!()
}
// Lifetime annotation needed because we have two by-reference parameters.
fn g(_x: &int, _y: &int) -> &int { //~ ERROR missing lifetime specifier
//~^ NOTE the signature does not say whether it is borrowed from `_x` or `_y`
- fail!()
+ panic!()
}
struct Foo<'a> {
// and one on the reference.
fn h(_x: &Foo) -> &int { //~ ERROR missing lifetime specifier
//~^ NOTE the signature does not say which one of `_x`'s 2 elided lifetimes it is borrowed from
- fail!()
+ panic!()
}
fn main() {}
}
}
-fn callback<T>(_f: || -> T) -> T { fail!() }
+fn callback<T>(_f: || -> T) -> T { panic!() }
unsafe fn unsf() {}
fn bad1() { unsafe {} } //~ ERROR: unnecessary `unsafe` block
sure that when purity is inherited that the source of the unsafe-ness
is tracked correctly */
unsafe {
- unsafe fn what() -> Vec<String> { fail!() }
+ unsafe fn what() -> Vec<String> { panic!() }
callback(|| {
what();
pub struct Public<T>;
impl Private<Public<int>> {
- pub fn a(&self) -> Private<int> { fail!() }
- fn b(&self) -> Private<int> { fail!() }
+ pub fn a(&self) -> Private<int> { panic!() }
+ fn b(&self) -> Private<int> { panic!() }
- pub fn c() -> Private<int> { fail!() }
- fn d() -> Private<int> { fail!() }
+ pub fn c() -> Private<int> { panic!() }
+ fn d() -> Private<int> { panic!() }
}
impl Private<int> {
- pub fn e(&self) -> Private<int> { fail!() }
- fn f(&self) -> Private<int> { fail!() }
+ pub fn e(&self) -> Private<int> { panic!() }
+ fn f(&self) -> Private<int> { panic!() }
}
impl Public<Private<int>> {
- pub fn a(&self) -> Private<int> { fail!() }
- fn b(&self) -> Private<int> { fail!() }
+ pub fn a(&self) -> Private<int> { panic!() }
+ fn b(&self) -> Private<int> { panic!() }
- pub fn c() -> Private<int> { fail!() } //~ ERROR private type in exported type signature
- fn d() -> Private<int> { fail!() }
+ pub fn c() -> Private<int> { panic!() } //~ ERROR private type in exported type signature
+ fn d() -> Private<int> { panic!() }
}
impl Public<int> {
- pub fn e(&self) -> Private<int> { fail!() } //~ ERROR private type in exported type signature
- fn f(&self) -> Private<int> { fail!() }
+ pub fn e(&self) -> Private<int> { panic!() } //~ ERROR private type in exported type signature
+ fn f(&self) -> Private<int> { panic!() }
}
pub fn x(_: Private<int>) {} //~ ERROR private type in exported type signature
}
pub trait PubTrait {
- fn foo(&self) -> Private<int> { fail!( )} //~ ERROR private type in exported type signature
+ fn foo(&self) -> Private<int> { panic!( )} //~ ERROR private type in exported type signature
fn bar(&self) -> Private<int>; //~ ERROR private type in exported type signature
fn baz() -> Private<int>; //~ ERROR private type in exported type signature
}
impl PubTrait for Public<int> {
- fn bar(&self) -> Private<int> { fail!() }
- fn baz() -> Private<int> { fail!() }
+ fn bar(&self) -> Private<int> { panic!() }
+ fn baz() -> Private<int> { panic!() }
}
impl PubTrait for Public<Private<int>> {
- fn bar(&self) -> Private<int> { fail!() }
- fn baz() -> Private<int> { fail!() }
+ fn bar(&self) -> Private<int> { panic!() }
+ fn baz() -> Private<int> { panic!() }
}
impl PubTrait for Private<int> {
- fn bar(&self) -> Private<int> { fail!() }
- fn baz() -> Private<int> { fail!() }
+ fn bar(&self) -> Private<int> { panic!() }
+ fn baz() -> Private<int> { panic!() }
}
impl PubTrait for (Private<int>,) {
- fn bar(&self) -> Private<int> { fail!() }
- fn baz() -> Private<int> { fail!() }
+ fn bar(&self) -> Private<int> { panic!() }
+ fn baz() -> Private<int> { panic!() }
}
trait PrivTrait {
- fn foo(&self) -> Private<int> { fail!( )}
+ fn foo(&self) -> Private<int> { panic!( )}
fn bar(&self) -> Private<int>;
}
impl PrivTrait for Private<int> {
- fn bar(&self) -> Private<int> { fail!() }
+ fn bar(&self) -> Private<int> { panic!() }
}
impl PrivTrait for (Private<int>,) {
- fn bar(&self) -> Private<int> { fail!() }
+ fn bar(&self) -> Private<int> { panic!() }
}
pub trait ParamTrait<T> {
impl ParamTrait<Private<int>> //~ ERROR private type in exported type signature
for Public<int> {
- fn foo() -> Private<int> { fail!() }
+ fn foo() -> Private<int> { panic!() }
}
impl ParamTrait<Private<int>> for Private<int> {
- fn foo() -> Private<int> { fail!( )}
+ fn foo() -> Private<int> { panic!( )}
}
impl<T: ParamTrait<Private<int>>> //~ ERROR private type in exported type signature
ParamTrait<T> for Public<i8> {
- fn foo() -> T { fail!() }
+ fn foo() -> T { panic!() }
}
fn send<T:Send + std::fmt::Show>(ch: _chan<T>, data: T) {
println!("{}", ch);
println!("{}", data);
- fail!();
+ panic!();
}
#[deriving(Show)]
println!("{}", message); //~ ERROR use of moved value: `message`
}
-fn main() { fail!(); }
+fn main() { panic!(); }
// a good test that we merge paths correctly in the presence of a
// variable that's used before it's declared
-fn my_fail() -> ! { fail!(); }
+fn my_panic() -> ! { panic!(); }
fn main() {
- match true { false => { my_fail(); } true => { } }
+ match true { false => { my_panic(); } true => { } }
println!("{}", x); //~ ERROR unresolved name `x`.
let x: int;
struct Foo<A> { f: A }
-fn guard(_s: String) -> bool {fail!()}
+fn guard(_s: String) -> bool {panic!()}
fn touch<A>(_a: &A) {}
fn f10() {
// terms of the binding, not the discriminant.
struct Foo<A> { f: A }
-fn guard(_s: String) -> bool {fail!()}
+fn guard(_s: String) -> bool {panic!()}
fn touch<A>(_a: &A) {}
fn f10() {
//~^ ERROR: cannot borrow `*f` as mutable because
println!("{}", msg);
},
- None => fail!("oops"),
+ None => panic!("oops"),
}
}
})
fn main() {
let x = a(c);
match x { //~ ERROR non-exhaustive patterns: `a(c)` not covered
- a(d) => { fail!("hello"); }
- b => { fail!("goodbye"); }
+ a(d) => { panic!("hello"); }
+ b => { panic!("goodbye"); }
}
}
// unrelated errors.
fn foo(a: int, b: int, c: int, d:int) {
- fail!();
+ panic!();
}
fn main() {
enum bar { t1((), Option<Vec<int>>), t2, }
// n.b. my change changes this error message, but I think it's right -- tjc
-fn foo(t: bar) -> int { match t { t1(_, Some(x)) => { return x * 3; } _ => { fail!(); } } }
+fn foo(t: bar) -> int { match t { t1(_, Some(x)) => { return x * 3; } _ => { panic!(); } } }
//~^ ERROR binary operation `*` cannot be applied to
fn main() { }
t1(_, Some::<int>(x)) => {
println!("{}", x);
}
- _ => { fail!(); }
+ _ => { panic!(); }
}
}
}
fn check_pp<T>(expr: T, f: |pprust::ps, T|, expect: str) {
- fail!();
+ panic!();
}
}
fn check_pp<T>(expr: T, f: |pprust::ps, T|, expect: str) {
- fail!();
+ panic!();
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn of<T>() -> |T| { fail!(); }
-fn subtype<T>(x: |T|) { fail!(); }
+fn of<T>() -> |T| { panic!(); }
+fn subtype<T>(x: |T|) { panic!(); }
fn test_fn<'x, 'y, 'z, T>(_x: &'x T, _y: &'y T, _z: &'z T) {
// Here, x, y, and z are free. Other letters
// Should meet both.
fn foo(x: &S) -> &'static S {
- fail!()
+ panic!()
}
// Should meet both.
fn bar<'a,'b>(x: &'a S) -> &'b S {
- fail!()
+ panic!()
}
// Meets F, but not G.
fn baz(x: &S) -> &S {
- fail!()
+ panic!()
}
fn supply_F() {
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn of<'a,T>() -> |T|:'a { fail!(); }
-fn subtype<T>(x: |T|) { fail!(); }
+fn of<'a,T>() -> |T|:'a { panic!(); }
+fn subtype<T>(x: |T|) { panic!(); }
fn test_fn<'x,'y,'z,T>(_x: &'x T, _y: &'y T, _z: &'z T) {
// Here, x, y, and z are free. Other letters
// Do not infer an ordering from the return value.
let z: &'b uint = &*x;
//~^ ERROR cannot infer
- fail!();
+ panic!();
}
fn ordering4<'a, 'b>(a: &'a uint, b: &'b uint, x: |&'a &'b uint|) {
use std::vec::Vec;
fn last<T>(v: Vec<&T> ) -> std::option::Option<T> {
- fail!();
+ panic!();
}
fn main() {
fn foo(c: quux) { assert!((false)); }
-fn main() { fail!(); }
+fn main() { panic!(); }
x: 3i
};
- let baz: Foo<uint> = fail!();
+ let baz: Foo<uint> = panic!();
//~^ ERROR not implemented
}
#[must_use = "some message"]
enum MustUseMsg { Test2 }
-fn foo<T>() -> T { fail!() }
+fn foo<T>() -> T { panic!() }
fn bar() -> int { return foo::<int>(); }
fn baz() -> MustUse { return foo::<MustUse>(); }
}
fn _zzz() {()}
-fn _yyy() -> ! {fail!()}
+fn _yyy() -> ! {panic!()}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn f() { if (1i == fail!()) { } else { } }
+fn f() { if (1i == panic!()) { } else { } }
fn main() { }
// error-pattern:meep
-fn f(_a: int, _b: int, _c: Box<int>) { fail!("moop"); }
+fn f(_a: int, _b: int, _c: Box<int>) { panic!("moop"); }
-fn main() { f(1, fail!("meep"), box 42); }
+fn main() { f(1, panic!("meep"), box 42); }
// except according to those terms.
// error-pattern:quux
-fn my_err(s: String) -> ! { println!("{}", s); fail!("quux"); }
+fn my_err(s: String) -> ! { println!("{}", s); panic!("quux"); }
fn main() { 3u == my_err("bye".to_string()); }
fn main() {
let x = vec!(1u,2u,3u);
- // This should cause a bounds-check failure, but may not if we do our
+ // This should cause a bounds-check panic, but may not if we do our
// bounds checking by comparing a scaled index value to the vector's
// length (in bytes), because the scaling of the index will cause it to
// wrap around to a small number.
let idx = uint::MAX & !(uint::MAX >> 1u);
println!("ov2 idx = 0x%x", idx);
- // This should fail.
+ // This should panic.
println!("ov2 0x%x", x[idx]);
}
fn main() {
let x = vec!(1u,2u,3u);
- // This should cause a bounds-check failure, but may not if we do our
+ // This should cause a bounds-check panic, but may not if we do our
// bounds checking by truncating the index value to the size of the
// machine word, losing relevant bits of the index value.
(idx >> 32) as uint,
idx as uint);
- // This should fail.
+ // This should panic.
println!("ov3 0x%x", x.as_slice()[idx]);
}
#[cfg(target_arch="x86_64")]
fn main() {
- // This version just fails anyways, for symmetry on 64-bit hosts.
+ // This version just panics anyways, for symmetry on 64-bit hosts.
let x = vec!(1u,2u,3u);
error!("ov3 0x%x", x.as_slice()[200]);
}
fn main() {
- // This should cause a bounds-check failure, but may not if we do our
+ // This should cause a bounds-check panic, but may not if we do our
// bounds checking by comparing the scaled index to the vector's
// address-bounds, since we've scaled the index to wrap around to the
// address of the 0th cell in the array (even though the index is
println!("ov1 idx * sizeof::<uint>() = 0x{:x}",
idx * mem::size_of::<uint>());
- // This should fail.
+ // This should panic.
println!("ov1 0x{:x}", x[idx]);
}
port: port_id,
}
-fn send<T:Send>(_ch: chan_t<T>, _data: T) { fail!(); }
+fn send<T:Send>(_ch: chan_t<T>, _data: T) { panic!(); }
-fn main() { fail!("quux"); }
+fn main() { panic!("quux"); }
impl Foo for S {
fn foo(self, x: int) {
- fail!()
+ panic!()
}
}
// error-pattern:test
fn main() {
- let _i: int = fail!("test");
+ let _i: int = panic!("test");
}
// error-pattern:test
fn f() {
- fail!("test");
+ panic!("test");
}
fn main() {
// error-pattern:test
fn main() {
- fail!("test");
+ panic!("test");
}
//error-pattern:One
fn main() {
- fail!("One");
- fail!("Two");
+ panic!("One");
+ panic!("Two");
}
fn main() {
let mut a = 1i;
if 1i == 1 { a = 2; }
- fail!(format!("woooo{}", "o"));
+ panic!(format!("woooo{}", "o"));
}
// error-pattern:explicit
-fn main() { fail!(); }
+fn main() { panic!(); }
// error-pattern:explicit failure
-fn f() -> ! { fail!() }
+fn f() -> ! { panic!() }
fn main() { f(); }
// error-pattern:explicit failure
-fn f() -> ! { fail!() }
+fn f() -> ! { panic!() }
fn g() -> int { let x = if true { f() } else { 10 }; return x; }
// error-pattern:explicit failure
-fn main() { let _x = if false { 0i } else if true { fail!() } else { 10i }; }
+fn main() { let _x = if false { 0i } else if true { panic!() } else { 10i }; }
// error-pattern:explicit failure
-fn f() -> ! { fail!() }
+fn f() -> ! { panic!() }
fn g() -> int { let x = match true { true => { f() } false => { 10 } }; return x; }
// error-pattern:explicit failure
-fn main() { let _x = match true { false => { 0i } true => { fail!() } }; }
+fn main() { let _x = match true { false => { 0i } true => { panic!() } }; }
task::spawn(proc() {
let result = count(5u);
println!("result = %?", result);
- fail!();
+ panic!();
});
}
}
// error-pattern:woe
fn f(a: int) { println!("{}", a); }
-fn main() { f(fail!("woe")); }
+fn main() { f(panic!("woe")); }
// error-pattern:failed at 'Box<Any>'
fn main() {
- fail!(box 612_i64);
+ panic!(box 612_i64);
}
fn main() {
- fail!(box 413i as Box<::std::any::Any+Send>);
+ panic!(box 413i as Box<::std::any::Any+Send>);
}
// error-pattern:failed at 'explicit failure'
fn main() {
- fail!();
+ panic!();
}
// error-pattern:failed at 'test-fail-fmt 42 rust'
fn main() {
- fail!("test-fail-fmt {} {}", 42i, "rust");
+ panic!("test-fail-fmt {} {}", 42i, "rust");
}
// error-pattern:failed at 'test-fail-owned'
fn main() {
- fail!("test-fail-owned");
+ panic!("test-fail-owned");
}
// error-pattern:failed at 'test-fail-static'
fn main() {
- fail!("test-fail-static");
+ panic!("test-fail-static");
}
// except according to those terms.
// error-pattern:moop
-fn main() { fail!("moop"); }
+fn main() { panic!("moop"); }
}
}
fn main() {
- fail!("{}", Foo)
+ panic!("{}", Foo)
}
// certain positions
// error-pattern:oops
-fn bigfail() {
- while (fail!("oops")) { if (fail!()) {
- match (fail!()) { () => {
+fn bigpanic() {
+ while (panic!("oops")) { if (panic!()) {
+ match (panic!()) { () => {
}
}
}};
}
-fn main() { bigfail(); }
+fn main() { bigpanic(); }
fn main() {
let r: Result<int,_> = task::try(proc() {
- fail!("test");
+ panic!("test");
1i
});
assert!(r.is_ok());
fn main() {
let r: Result<int,_> = TaskBuilder::new().named("owned name".to_string())
.try(proc() {
- fail!("test");
+ panic!("test");
1i
});
assert!(r.is_ok());
let r: Result<int,_> =
::std::task::TaskBuilder::new().named("send name".into_maybe_owned())
.try(proc() {
- fail!("test");
+ panic!("test");
3i
});
assert!(r.is_ok());
fn main() {
let r: Result<int,_> =
::std::task::TaskBuilder::new().named("static name").try(proc() {
- fail!("test");
+ panic!("test");
});
assert!(r.is_ok());
}
fn main() {
let str_var: String = "meh".to_string();
- fail!("{}", str_var);
+ panic!("{}", str_var);
}
// error-pattern:moop
-fn main() { for _ in range(0u, 10u) { fail!("moop"); } }
+fn main() { for _ in range(0u, 10u) { panic!("moop"); } }
use std::*;
fn main() {
- fail!("fail works")
+ panic!("panic works")
}
if even(x) {
println!("{}", x);
} else {
- fail!("Number is odd");
+ panic!("Number is odd");
}
}
// except according to those terms.
// error-pattern:quux
-fn my_err(s: String) -> ! { println!("{}", s); fail!("quux"); }
+fn my_err(s: String) -> ! { println!("{}", s); panic!("quux"); }
fn main() { if my_err("bye".to_string()) { } }
// error-pattern:explicit failure
pub fn main() {
- fail!(); println!("{}", 1i);
+ panic!(); println!("{}", 1i);
}
// error-pattern:bad input
fn main() {
- Some("foo").unwrap_or(fail!("bad input")).to_string();
+ Some("foo").unwrap_or(panic!("bad input")).to_string();
}
enum e<T> { ee(Arc<T>) }
-fn foo() -> e<int> {fail!();}
+fn foo() -> e<int> {panic!();}
fn main() {
let _f = foo();
fn main() {
let mut x = Vec::new();
let y = vec!(3i);
- fail!("so long");
+ panic!("so long");
x.extend(y.into_iter());
}
fn main() {
let origin = Point {x: 0, y: 0};
- let f: Point = Point {x: (fail!("beep boop")),.. origin};
+ let f: Point = Point {x: (panic!("beep boop")),.. origin};
}
// error-pattern:task '<main>' failed at
fn main() {
- fail!()
+ panic!()
}
fn main() {
let i =
- match Some::<int>(3) { None::<int> => { fail!() } Some::<int>(_) => { fail!() } };
+ match Some::<int>(3) { None::<int> => { panic!() } Some::<int>(_) => { panic!() } };
foo(i);
}
// except according to those terms.
// error-pattern:quux
-fn f() -> ! { fail!("quux") }
+fn f() -> ! { panic!("quux") }
fn g() -> int { match f() { true => { 1 } false => { 0 } } }
fn main() { g(); }
// error-pattern:squirrelcupcake
fn cmp() -> int {
match (Some('a'), None::<char>) {
- (Some(_), _) => { fail!("squirrelcupcake"); }
- (_, Some(_)) => { fail!(); }
- _ => { fail!("wat"); }
+ (Some(_), _) => { panic!("squirrelcupcake"); }
+ (_, Some(_)) => { panic!(); }
+ _ => { panic!("wat"); }
}
}
#[start]
fn start(argc: int, argv: *const *const u8) -> int {
native::start(argc, argv, proc() {
- fail!();
+ panic!();
})
}
struct T { t: String }
fn main() {
- let pth = fail!("bye");
+ let pth = panic!("bye");
let _rs: T = T {t: pth};
}
fn main() {
error!("whatever");
// Setting the exit status only works when the scheduler terminates
- // normally. In this case we're going to fail, so instead of
+ // normally. In this case we're going to panic, so instead of
// returning 50 the process will return the typical rt failure code.
os::set_exit_status(50);
- fail!();
+ panic!();
}
}
// Setting the exit status after the runtime has already
-// failed has no effect and the process exits with the
+// panicked has no effect and the process exits with the
// runtime's exit code
impl Drop for r {
fn drop(&mut self) {
task::spawn(proc() {
let _i = r(5);
});
- fail!();
+ panic!();
}
fn main() {
error!("whatever");
- // 101 is the code the runtime uses on task failure and the value
+ // 101 is the code the runtime uses on task panic and the value
// compiletest expects run-fail tests to return.
os::set_exit_status(101);
}
pub fn exported() { }
#[test]
- fn unexported() { fail!("runned an unexported test"); }
+ fn unexported() { panic!("runned an unexported test"); }
}
fn main() {
let s: String = "hello".to_string();
- // Bounds-check failure.
+ // Bounds-check panic.
assert_eq!(s.as_bytes()[5], 0x0 as u8);
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// error-pattern:Ensure that the child task runs by failing
+// error-pattern:Ensure that the child task runs by panicking
use std::task;
// works when provided with a bare function:
let r = task::try(startfn);
if r.is_err() {
- fail!()
+ panic!()
}
}
fn startfn() {
- assert!("Ensure that the child task runs by failing".is_empty());
+ assert!("Ensure that the child task runs by panicking".is_empty());
}
#[test]
fn test_foo() {
- fail!()
+ panic!()
}
fn main() {
os::args();
- fail!("please have a nonzero exit status");
+ panic!("please have a nonzero exit status");
}
// ignore-test leaks
// error-pattern:ran out of stack
-// Test that the task fails after hitting the recursion limit
+// Test that the task panicks after hitting the recursion limit
// during unwinding
fn recurse() {
// except according to those terms.
// error-pattern: fail
-fn main() { box fail!(); }
+fn main() { box panic!(); }
fn a() { }
-fn b() { fail!(); }
+fn b() { panic!(); }
fn main() {
let _x = vec!(0i);
fn build() -> Vec<int> {
- fail!();
+ panic!();
}
struct Blk { node: Vec<int> }
}
fn build2() -> Vec<int> {
- fail!();
+ panic!();
}
struct Blk { node: Vec<int> , span: Vec<int> }
fn failfn() {
- fail!();
+ panic!();
}
fn main() {
let v: Vec<int> = vec!(10);
let x: uint = 0;
assert_eq!(v[x], 10);
- // Bounds-check failure.
+ // Bounds-check panic.
assert_eq!(v[x + 2], 20);
}
#![allow(while_true)]
// error-pattern:quux
-fn main() { let _x: int = { while true { fail!("quux"); } ; 8 } ; }
+fn main() { let _x: int = { while true { panic!("quux"); } ; 8 } ; }
// error-pattern:giraffe
fn main() {
- fail!({ while true { fail!("giraffe") }; "clandestine" });
+ panic!({ while true { panic!("giraffe") }; "clandestine" });
}
fn main() {
task::try(proc() {
let _a = A;
- lib::callback(|| fail!());
+ lib::callback(|| panic!());
1i
});
pub fn main() {
- fail!()
+ panic!()
}
#[main]
fn foo() {
let _v = vec![1i, 2, 3];
if os::getenv("IS_TEST").is_some() {
- fail!()
+ panic!()
}
}
#[inline(never)]
fn double() {
(|| {
- fail!("once");
+ panic!("once");
}).finally(|| {
- fail!("twice");
+ panic!("twice");
})
}
// Check that issue #954 stays fixed
pub fn main() {
- match -1i { -1 => {}, _ => fail!("wat") }
+ match -1i { -1 => {}, _ => panic!("wat") }
assert_eq!(1i-1, 0i);
}
let x = Some(p);
match x {
Some(z) => { dispose(z); },
- None => fail!()
+ None => panic!()
}
}
);
match s {
box Bar2(id, rest) => declare!(id, self.elaborate_stm(rest)),
- _ => fail!()
+ _ => panic!()
}
}
- fn check_id(&mut self, s: int) { fail!() }
+ fn check_id(&mut self, s: int) { panic!() }
}
pub fn main() { }
match 42 {
b'*' => {},
- _ => fail!()
+ _ => panic!()
}
match 100 {
b'a' ... b'z' => {},
- _ => fail!()
+ _ => panic!()
}
let expected: &[_] = &[97u8, 10u8, 13u8, 9u8, 92u8, 39u8, 34u8, 0u8, 240u8];
let val: &[_] = &[97u8, 10u8];
match val {
b"a\n" => {},
- _ => fail!(),
+ _ => panic!(),
}
let buf = vec!(97u8, 98, 99, 100);
// invoked -- after all, that would permit evil user code to
// abuse `Cell` and trigger crashes.
- fail!();
+ panic!();
}
}
true
}
- fn find_mut(&mut self, _k: &int) -> Option<&mut T> { fail!() }
+ fn find_mut(&mut self, _k: &int) -> Option<&mut T> { panic!() }
fn remove(&mut self, k: &int) -> bool {
if self.find(k).is_some() {
}
}
- fn pop(&mut self, _k: &int) -> Option<T> { fail!() }
+ fn pop(&mut self, _k: &int) -> Option<T> { panic!() }
- fn swap(&mut self, _k: int, _v: T) -> Option<T> { fail!() }
+ fn swap(&mut self, _k: int, _v: T) -> Option<T> { panic!() }
}
impl<T> cat<T> {
pub fn get(&self, k: &int) -> &T {
match self.find(k) {
Some(v) => { v }
- None => { fail!("epic fail"); }
+ None => { panic!("epic fail"); }
}
}
//
// 1. Partial cleanup of `box` is in scope,
// 2. cleanup of return value from `get_bar()` is in scope,
-// 3. do_it() fails.
+// 3. do_it() panics.
//
// This led to a bug because `the top-most frame that was to be
// cleaned (which happens to be the partial cleanup of `box`) required
struct Foo { field: Box<uint> }
fn do_it(x: &[uint]) -> Foo {
- fail!()
+ panic!()
}
fn get_bar(x: uint) -> Vec<uint> { vec!(x * 2) }
}
fn main() {
- let x: || -> ! = || fail!();
+ let x: || -> ! = || panic!();
let _y: || -> ! = || x();
}
// Since the bogus configuration isn't defined main will just be
// parsed, but nothing further will be done with it
#[cfg(bogus)]
-pub fn main() { fail!() }
+pub fn main() { panic!() }
pub fn main() {
// Exercise some of the configured items in ways that wouldn't be possible
fn test_in_fn_ctxt() {
#[cfg(bogus)]
- fn f() { fail!() }
+ fn f() { panic!() }
fn f() { }
f();
extern crate log;
pub fn main() {
- // only fails if println! evaluates its argument.
- debug!("{}", { if true { fail!() } });
+ // only panics if println! evaluates its argument.
+ debug!("{}", { if true { panic!() } });
}
pub fn main() {
// exits early if println! evaluates its arguments, otherwise it
- // will hit the fail.
+ // will hit the panic.
println!("{}", { if true { return; } });
- fail!();
+ panic!();
}
pub fn main() {
match X {
Baz => {}
- _ => fail!()
+ _ => panic!()
}
match Y {
Bar(s) => assert!(s == 2654435769),
- _ => fail!()
+ _ => panic!()
}
match Z {
Quux(d,h) => {
assert_eq!(d, 0x123456789abcdef0);
assert_eq!(h, 0x1234);
}
- _ => fail!()
+ _ => panic!()
}
}
pub fn method(&self) {
match *self {
V => {}
- VV(..) => fail!()
+ VV(..) => panic!()
}
}
}
fn f(a: &E) {
match *a {
V => {}
- VV(..) => fail!()
+ VV(..) => panic!()
}
}
pub fn main() {
match *C {
V0 => (),
- _ => fail!()
+ _ => panic!()
}
}
pub fn main() {
match C {
- S0 { .. } => fail!(),
+ S0 { .. } => panic!(),
S1 { u } => assert!(u == 23)
}
}
pub fn main() {
match C0 {
V0 => (),
- _ => fail!()
+ _ => panic!()
}
match C1 {
V1(n) => assert!(n == 0xDEADBEE),
- _ => fail!()
+ _ => panic!()
}
match D0 {
V0 => (),
- _ => fail!()
+ _ => panic!()
}
match D1 {
V1(n) => assert!(n == 0xDEADBEE),
- _ => fail!()
+ _ => panic!()
}
}
pub fn main() {
match C[1] {
V1(n) => assert!(n == 0xDEADBEE),
- _ => fail!()
+ _ => panic!()
}
match C[2] {
V0 => (),
- _ => fail!()
+ _ => panic!()
}
}
pub fn main() {
match C[1] {
V1(n) => assert!(n == 0xDEADBEE),
- _ => fail!()
+ _ => panic!()
}
match C[2] {
V0 => (),
- _ => fail!()
+ _ => panic!()
}
}
pub fn main() {
match X {
Bar => {}
- Baz | Boo => fail!()
+ Baz | Boo => panic!()
}
match Y {
Baz => {}
- Bar | Boo => fail!()
+ Bar | Boo => panic!()
}
}
use std::str;
macro_rules! succeed( ($e:expr) => (
- match $e { Ok(..) => {}, Err(e) => fail!("failure: {}", e) }
+ match $e { Ok(..) => {}, Err(e) => panic!("panic: {}", e) }
) )
fn test_destroy_once() {
let mut p = sleeper();
match p.signal_exit() {
Ok(()) => {}
- Err(e) => fail!("error: {}", e),
+ Err(e) => panic!("error: {}", e),
}
}
}
});
match p.wait().unwrap() {
- ExitStatus(..) => fail!("expected a signal"),
+ ExitStatus(..) => panic!("expected a signal"),
ExitSignal(..) => tx.send(()),
}
}
// except according to those terms.
// check that the derived impls for the comparison traits shortcircuit
-// where possible, by having a type that fails when compared as the
+// where possible, by having a type that panics when compared as the
// second element, so this passes iff the instances shortcircuit.
pub struct FailCmp;
impl PartialEq for FailCmp {
- fn eq(&self, _: &FailCmp) -> bool { fail!("eq") }
+ fn eq(&self, _: &FailCmp) -> bool { panic!("eq") }
}
impl PartialOrd for FailCmp {
- fn partial_cmp(&self, _: &FailCmp) -> Option<Ordering> { fail!("partial_cmp") }
+ fn partial_cmp(&self, _: &FailCmp) -> Option<Ordering> { panic!("partial_cmp") }
}
impl Eq for FailCmp {}
impl Ord for FailCmp {
- fn cmp(&self, _: &FailCmp) -> Ordering { fail!("cmp") }
+ fn cmp(&self, _: &FailCmp) -> Ordering { panic!("cmp") }
}
#[deriving(PartialEq,PartialOrd,Eq,Ord)]
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// Just testing that fail!() type checks in statement or expr
+// Just testing that panic!() type checks in statement or expr
#![allow(unreachable_code)]
fn f() {
- fail!();
+ panic!();
- let _x: int = fail!();
+ let _x: int = panic!();
}
pub fn main() {
sender.send(DestructorRan);
}
&FailingVariant { .. } => {
- fail!("Failed");
+ panic!("Failed");
}
}
}
impl Deref<[uint]> for Arr {
fn deref(&self) -> &[uint] {
- fail!();
+ panic!();
}
}
pub fn main() {
let x = Some(0u64);
match x {
- None => fail!(),
+ None => panic!(),
Some(ref y) => assert!(is_aligned(y))
}
}
match Cons(10i, box Nil) {
Cons(10i, _) => {}
Nil => {}
- _ => fail!()
+ _ => panic!()
}
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-// When all branches of an if expression result in fail, the entire if
-// expression results in fail.
+// When all branches of an if expression result in panic, the entire if
+// expression results in panic.
pub fn main() {
let _x = if true {
10i
} else {
- if true { fail!() } else { fail!() }
+ if true { panic!() } else { panic!() }
};
}
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn test_if_fail() {
- let x = if false { fail!() } else { 10i };
+fn test_if_panic() {
+ let x = if false { panic!() } else { 10i };
assert!((x == 10));
}
-fn test_else_fail() {
- let x = if true { 10i } else { fail!() };
+fn test_else_panic() {
+ let x = if true { 10i } else { panic!() };
assert_eq!(x, 10i);
}
-fn test_elseif_fail() {
- let x = if false { 0i } else if false { fail!() } else { 10i };
+fn test_elseif_panic() {
+ let x = if false { 0i } else if false { panic!() } else { 10i };
assert_eq!(x, 10i);
}
-pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
+pub fn main() { test_if_panic(); test_else_panic(); test_elseif_panic(); }
-// When all branches of a match expression result in fail, the entire
-// match expression results in fail.
+// When all branches of a match expression result in panic, the entire
+// match expression results in panic.
pub fn main() {
let _x =
match true {
true => { 10i }
- false => { match true { true => { fail!() } false => { fail!() } } }
+ false => { match true { true => { panic!() } false => { panic!() } } }
};
}
fn test_simple() {
- let r = match true { true => { true } false => { fail!() } };
+ let r = match true { true => { true } false => { panic!() } };
assert_eq!(r, true);
}
fn test_box() {
- let r = match true { true => { vec!(10i) } false => { fail!() } };
+ let r = match true { true => { vec!(10i) } false => { panic!() } };
assert_eq!(r[0], 10i);
}
fn test_generic<T:Clone>(expected: Box<T>, eq: compare<T>) {
let actual: Box<T> = match true {
true => { expected.clone() },
- _ => fail!("wat")
+ _ => panic!("wat")
};
assert!((eq(expected, actual)));
}
fn test_generic<T:Clone>(expected: T, eq: compare<T>) {
let actual: T = match true {
true => expected.clone(),
- _ => fail!("wat")
+ _ => panic!("wat")
};
assert!((eq(expected, actual)));
}
type compare<T> = extern "Rust" fn(T, T) -> bool;
fn test_generic<T:Clone>(expected: T, eq: compare<T>) {
- let actual: T = match true { true => { expected.clone() }, _ => fail!("wat") };
+ let actual: T = match true { true => { expected.clone() }, _ => panic!("wat") };
assert!((eq(expected, actual)));
}
struct R { i: int }
fn test_rec() {
- let rs = match true { true => R {i: 100}, _ => fail!() };
+ let rs = match true { true => R {i: 100}, _ => panic!() };
assert_eq!(rs.i, 100);
}
// Tests for match as expressions resulting in boxed types
fn test_box() {
- let res = match true { true => { box 100i }, _ => fail!() };
+ let res = match true { true => { box 100i }, _ => panic!() };
assert_eq!(*res, 100i);
}
impl Drop for Foo {
fn drop(&mut self) {
unsafe { DROPS += 1; }
- fail!()
+ panic!()
}
}
impl Drop for A {
fn drop(&mut self) {
- fail!()
+ panic!()
}
}
// except according to those terms.
-pub fn main() { let x: Vec<int> = Vec::new(); for _ in x.iter() { fail!("moop"); } }
+pub fn main() { let x: Vec<int> = Vec::new(); for _ in x.iter() { panic!("moop"); } }
match getopts(args.as_slice(), opts.as_slice()) {
Ok(ref m) =>
assert!(!m.opt_present("b")),
- Err(ref f) => fail!("{}", *f)
+ Err(ref f) => panic!("{}", *f)
};
}
'x: for _ in range(0i, 1) {
// this 'x should refer to the outer loop, lexically
loop_x!(break 'x);
- fail!("break doesn't act hygienically inside for loop");
+ panic!("break doesn't act hygienically inside for loop");
}
'x: loop {
// ditto
loop_x!(break 'x);
- fail!("break doesn't act hygienically inside infinite loop");
+ panic!("break doesn't act hygienically inside infinite loop");
}
'x: while 1i + 1 == 2 {
while_x!(break 'x);
- fail!("break doesn't act hygienically inside infinite while loop");
+ panic!("break doesn't act hygienically inside infinite while loop");
}
'x: for _ in range(0i, 1) {
// ditto
run_once!(continue 'x);
- fail!("continue doesn't act hygienically inside for loop");
+ panic!("continue doesn't act hygienically inside for loop");
}
}
// except according to those terms.
pub fn main() {
- let i: int = if false { fail!() } else { 5 };
+ let i: int = if false { panic!() } else { 5 };
println!("{}", i);
}
if even(x) {
println!("{}", x);
} else {
- fail!();
+ panic!();
}
}
if let Some(y) = x {
assert_eq!(y, 3i);
} else {
- fail!("if-let failed");
+ panic!("if-let panicked");
}
let mut worked = false;
if let Some(_) = x {
assert_eq!(clause, 4u);
if 3i > 4 {
- fail!("bad math");
+ panic!("bad math");
} else if let 1 = 2i {
- fail!("bad pattern match");
+ panic!("bad pattern match");
}
enum Foo {
let foo = Three("three".to_string(), 42i);
if let One = foo {
- fail!("bad pattern match");
+ panic!("bad pattern match");
} else if let Two(_x) = foo {
- fail!("bad pattern match");
+ panic!("bad pattern match");
} else if let Three(s, _) = foo {
assert_eq!(s.as_slice(), "three");
} else {
- fail!("bad else");
+ panic!("bad else");
}
if false {
- fail!("wat");
+ panic!("wat");
} else if let a@Two(_) = Two(42u) {
if let Two(b) = a {
assert_eq!(b, 42u);
} else {
- fail!("fail in nested if-let");
+ panic!("panic in nested if-let");
}
}
}
impl Foo {
#[allow(dead_code)]
fn foo(self) {
- fail!("wrong method!")
+ panic!("wrong method!")
}
}
struct A { foo: int }
struct B { a: int, b: int, c: int }
-fn mka() -> A { fail!() }
-fn mkb() -> B { fail!() }
+fn mka() -> A { panic!() }
+fn mkb() -> B { panic!() }
fn test() {
let A { foo, } = mka();
// An `if false {} else { expr }` statement should compile the same as `{ expr }`.
if false {
- fail!();
+ panic!();
} else {
let _a = Foo{ dropped: false };
}
{
match n {
&Cell(box Atom(2), box Cell(ref a, _)) => (**a).clone(),
- _ => fail!("Invalid fas pattern")
+ _ => panic!("Invalid fas pattern")
}
}
// ignore-pretty
-// Don't fail on blocks without results
+// Don't panic on blocks without results
// There are several tests in this run-pass that raised
// when this bug was opened. The cases where the compiler
-// failed before the fix have a comment.
+// panics before the fix have a comment.
struct S {x:()}
if b {
!b
} else {
- // `fail!(...)` would break
- fail!("Break the compiler");
+ // `panic!(...)` would break
+ panic!("Break the compiler");
}
}
FormatMessageW(0x1000, 0 as *mut c_void, 1, 0x400,
buf.as_mut_ptr(), buf.len() as u32, 0 as *const c_void)
};
- // On some 32-bit Windowses (Win7-8 at least) this will fail with segmented
+ // On some 32-bit Windowses (Win7-8 at least) this will panic with segmented
// stacks taking control of pvArbitrary
assert!(ret != 0);
}
let x = match Foo(42) {
Foo(..) => 1i,
_ if true => 0,
- Bar(..) => fail!("Oh dear")
+ Bar(..) => panic!("Oh dear")
};
assert_eq!(x, 1);
let x = match Foo(42) {
_ if true => 0i,
Foo(..) => 1,
- Bar(..) => fail!("Oh dear")
+ Bar(..) => panic!("Oh dear")
};
assert_eq!(x, 0);
}
// except according to those terms.
pub fn main() {
- let early_error: |&str|: 'static -> ! = |_msg| { fail!() };
+ let early_error: |&str|: 'static -> ! = |_msg| { panic!() };
}
impl<A> foo<A> {
pub fn bar<B,C:clam<A>>(&self, _c: C) -> B {
- fail!();
+ panic!();
}
}
struct foo(int);
impl foo {
- pub fn bar<B,C:clam<B>>(&self, _c: C) -> B { fail!(); }
+ pub fn bar<B,C:clam<B>>(&self, _c: C) -> B { panic!(); }
}
pub fn main() { }
}
impl A for E {
- fn b<F,G>(_x: F) -> F { fail!() }
+ fn b<F,G>(_x: F) -> F { panic!() }
//~^ ERROR in method `b`, type parameter 0 has 1 bound, but
}
}
mod rusti {
- pub fn atomic_xchg(_dst: &mut int, _src: int) -> int { fail!(); }
- pub fn atomic_xchg_acq(_dst: &mut int, _src: int) -> int { fail!(); }
- pub fn atomic_xchg_rel(_dst: &mut int, _src: int) -> int { fail!(); }
+ pub fn atomic_xchg(_dst: &mut int, _src: int) -> int { panic!(); }
+ pub fn atomic_xchg_acq(_dst: &mut int, _src: int) -> int { panic!(); }
+ pub fn atomic_xchg_rel(_dst: &mut int, _src: int) -> int { panic!(); }
}
// We should consider moving this to ::std::unsafe, although I
// The receiver will eventually clean this up.
unsafe { forget(p); }
}
- full => { fail!("duplicate send") }
+ full => { panic!("duplicate send") }
blocked => {
// The receiver will eventually clean this up.
}
full => {
// This is impossible
- fail!("you dun goofed")
+ panic!("you dun goofed")
}
terminated => {
// I have to clean up, use drop_glue
}
blocked => {
// this shouldn't happen.
- fail!("terminating a blocked packet")
+ panic!("terminating a blocked packet")
}
terminated | full => {
// I have to clean up, use drop_glue
let _addr : *const ::pipes::send_packet<pong> = match &p {
&ping(ref x) => { mem::transmute(x) }
};
- fail!()
+ panic!()
}
}
let _addr : *const ::pipes::send_packet<ping> = match &p {
&pong(ref x) => { mem::transmute(x) }
};
- fail!()
+ panic!()
}
}
pub fn do_pong(c: pong) -> (ping, ()) {
let packet = ::pipes::recv(c);
if packet.is_none() {
- fail!("sender closed the connection")
+ panic!("sender closed the connection")
}
(pingpong::liberate_pong(packet.unwrap()), ())
}
pub fn do_ping(c: ping) -> (pong, ()) {
let packet = ::pipes::recv(c);
if packet.is_none() {
- fail!("sender closed the connection")
+ panic!("sender closed the connection")
}
(pingpong::liberate_ping(packet.unwrap()), ())
}
' ' => { empty }
_ => {
println!("invalid square: {}", c);
- fail!()
+ panic!()
}
}
}
match BadChar {
_ if true => BadChar,
- BadChar | BadSyntax => fail!() ,
+ BadChar | BadSyntax => panic!() ,
};
}
let doc = json::from_str("").unwrap();
let mut decoder = json::Decoder::new(doc);
let _v: T = Decodable::decode(&mut decoder).unwrap();
- fail!()
+ panic!()
}
pub fn main() {}
let v = match io.read_char() {
'$' => parse_bulk(io),
':' => parse_int(io),
- _ => fail!()
+ _ => panic!()
};
list.push(v);
}
priv fn parse_bulk(io: @io::Reader) -> Result {
match from_str::<int>(chop(io.read_line())) {
- None => fail!(),
+ None => panic!(),
Some(-1) => Nil,
Some(len) if len >= 0 => parse_data(len as uint, io),
- Some(_) => fail!()
+ Some(_) => panic!()
}
}
priv fn parse_multi(io: @io::Reader) -> Result {
match from_str::<int>(chop(io.read_line())) {
- None => fail!(),
+ None => panic!(),
Some(-1) => Nil,
Some(0) => List(~[]),
Some(len) if len >= 0 => parse_list(len as uint, io),
- Some(_) => fail!()
+ Some(_) => panic!()
}
}
priv fn parse_int(io: @io::Reader) -> Result {
match from_str::<int>(chop(io.read_line())) {
- None => fail!(),
+ None => panic!(),
Some(i) => Int(i)
}
}
'+' => Status(chop(io.read_line())),
'-' => Error(chop(io.read_line())),
':' => parse_int(io),
- _ => fail!()
+ _ => panic!()
}
}
fn bar(a: foo::map) {
if false {
- fail!();
+ panic!();
} else {
let _b = &(*a)[2];
}
impl<E> Graph<int, E> for HashMap<int, int> {
fn f(&self, _e: E) {
- fail!();
+ panic!();
}
}
fn main() {
match Baz {
- ::Bar(3) => fail!(),
- ::Bar(_) if false => fail!(),
- ::Bar(..) if false => fail!(),
- ::Bar(_n) => fail!(),
+ ::Bar(3) => panic!(),
+ ::Bar(_) if false => panic!(),
+ ::Bar(..) if false => panic!(),
+ ::Bar(_n) => panic!(),
::Baz => {}
}
match Bar(3) {
::Bar(3) => {}
- ::Bar(_) if false => fail!(),
- ::Bar(..) if false => fail!(),
- ::Bar(_n) => fail!(),
- ::Baz => fail!(),
+ ::Bar(_) if false => panic!(),
+ ::Bar(..) if false => panic!(),
+ ::Bar(_n) => panic!(),
+ ::Baz => panic!(),
}
match Bar(4) {
- ::Bar(3) => fail!(),
- ::Bar(_) if false => fail!(),
- ::Bar(..) if false => fail!(),
+ ::Bar(3) => panic!(),
+ ::Bar(_) if false => panic!(),
+ ::Bar(..) if false => panic!(),
::Bar(n) => assert_eq!(n, 4),
- ::Baz => fail!(),
+ ::Baz => panic!(),
}
match Other1(Baz) {
pub fn main() {
let e = Foo{f: 0};
match e {
- Foo{f: 1} => fail!(),
+ Foo{f: 1} => panic!(),
Foo{..} => (),
- _ => fail!(),
+ _ => panic!(),
}
}
pub fn main() {
let e = Foo{f: 0, b: false};
match e {
- Foo{f: 1, b: true} => fail!(),
+ Foo{f: 1, b: true} => panic!(),
Foo{b: false, f: 0} => (),
- _ => fail!(),
+ _ => panic!(),
}
}
let r = f(s);
return (r);
}
- fail!();
+ panic!();
}
fn apply<T>(s: String, f: |String| -> T) -> T {
pub fn main() {
if log_enabled!(log::DEBUG) {
- fail!("what?! debugging?");
+ panic!("what?! debugging?");
}
}
pub fn main() {
if log_enabled!(log::DEBUG) {
- fail!("what?! debugging?");
+ panic!("what?! debugging?");
}
if !log_enabled!(log::INFO) {
- fail!("what?! no info?");
+ panic!("what?! no info?");
}
}
// monomorphized functions from other crates had logging turned on (their
// logging module names were all incorrect). This test ensures that this no
// longer happens by enabling logging for *this* crate and then invoking a
-// function in an external crate which will fail when logging is enabled.
+// function in an external crate which will panic when logging is enabled.
extern crate logging_right_crate;
pub fn main() {
- // this function fails if logging is turned on
+ // this function panicks if logging is turned on
logging_right_crate::foo::<int>();
}
impl Drop for S { fn drop(&mut self) { } }
// user-defined function "returning" bottom (i.e. no return at all).
-fn my_fail() -> ! { loop {} }
+fn my_panic() -> ! { loop {} }
pub fn step(f: bool) {
let mut g = S;
continue;
}
- my_fail();
+ my_panic();
// we never get here, so we do not need to re-initialize g.
}
Some($pat) => {
$res
}
- _ => { fail!(); }
+ _ => { panic!(); }
}
})
// except according to those terms.
// n.b. This was only ever failing with optimization disabled.
-fn a() -> int { match return 1i { 2i => 3i, _ => fail!() } }
+fn a() -> int { match return 1i { 2i => 3i, _ => panic!() } }
pub fn main() { a(); }
pub fn main() {
let i: int =
- match Some::<int>(3) { None::<int> => { fail!() } Some::<int>(_) => { 5 } };
+ match Some::<int>(3) { None::<int> => { panic!() } Some::<int>(_) => { 5 } };
println!("{}", i);
}
pub fn main() {
let e = Bar;
match e {
- Foo{f: _f} => fail!(),
+ Foo{f: _f} => panic!(),
_ => (),
}
}
let e = Foo{f: 1};
match e {
Foo{..} => (),
- _ => fail!(),
+ _ => panic!(),
}
match e {
Foo{f: _f} => (),
- _ => fail!(),
+ _ => panic!(),
}
}
match f {
10 => { println!("case 10"); return 20; }
11 => { println!("case 11"); return 22; }
- _ => fail!("the impossible happened")
+ _ => panic!("the impossible happened")
}
}
assert_eq!(a, "a".to_string());
assert_eq!(b, "b".to_string());
},
- _ => fail!(),
+ _ => panic!(),
}
}
assert_eq!(a, 2);
assert_eq!(b, 3);
},
- _ => fail!(),
+ _ => panic!(),
}
}
assert_eq!(*a, 2);
assert_eq!(*b, 3);
},
- _ => fail!(),
+ _ => panic!(),
}
}
assert_eq!(a, 2);
assert_eq!(b, 3);
},
- _ => fail!(),
+ _ => panic!(),
}
}
assert_eq!(*a, 2);
assert_eq!(*b, 3);
},
- _ => fail!(),
+ _ => panic!(),
}
}
pub fn main() {
match 5u {
1u...5u => {}
- _ => fail!("should match range"),
+ _ => panic!("should match range"),
}
match 5u {
- 6u...7u => fail!("shouldn't match range"),
+ 6u...7u => panic!("shouldn't match range"),
_ => {}
}
match 5u {
- 1u => fail!("should match non-first range"),
+ 1u => panic!("should match non-first range"),
2u...6u => {}
- _ => fail!("math is broken")
+ _ => panic!("math is broken")
}
match 'c' {
'a'...'z' => {}
- _ => fail!("should suppport char ranges")
+ _ => panic!("should suppport char ranges")
}
match -3i {
-7...5 => {}
- _ => fail!("should match signed range")
+ _ => panic!("should match signed range")
}
match 3.0f64 {
1.0...5.0 => {}
- _ => fail!("should match float range")
+ _ => panic!("should match float range")
}
match -1.5f64 {
-3.6...3.6 => {}
- _ => fail!("should match negative float range")
+ _ => panic!("should match negative float range")
}
}
Some(ref z) if *z.lock() => {
assert!(*z.lock());
},
- _ => fail!()
+ _ => panic!()
}
}
}
// Issue #53
pub fn main() {
- match "test" { "not-test" => fail!(), "test" => (), _ => fail!() }
+ match "test" { "not-test" => panic!(), "test" => (), _ => panic!() }
enum t { tag1(String), tag2, }
match tag1("test".to_string()) {
- tag2 => fail!(),
- tag1(ref s) if "test" != s.as_slice() => fail!(),
+ tag2 => panic!(),
+ tag1(ref s) if "test" != s.as_slice() => panic!(),
tag1(ref s) if "test" == s.as_slice() => (),
- _ => fail!()
+ _ => panic!()
}
- let x = match "a" { "a" => 1i, "b" => 2i, _ => fail!() };
+ let x = match "a" { "a" => 1i, "b" => 2i, _ => panic!() };
assert_eq!(x, 1);
- match "a" { "a" => { } "b" => { }, _ => fail!() }
+ match "a" { "a" => { } "b" => { }, _ => panic!() }
}
pub fn main() {
let f = Foo{f: 1};
match f {
- Foo{f: 0} => fail!(),
+ Foo{f: 0} => panic!(),
Foo{..} => (),
}
match f {
- Foo{f: 0} => fail!(),
+ Foo{f: 0} => panic!(),
Foo{f: _f} => (),
}
match f {
- Foo{f: 0} => fail!(),
+ Foo{f: 0} => panic!(),
_ => (),
}
}
pub fn main() {
match -5i {
-5 => {}
- _ => { fail!() }
+ _ => { panic!() }
}
}
/* This test checks that nested comments are supported
/*
- This should not fail
+ This should not panic
*/
*/
}
}
- // fn b(x:int) -> int { fail!(); }
+ // fn b(x:int) -> int { panic!(); }
let z = b(42);
assert_eq!(z.i, 42);
// option. This file may not be copied, modified, or distributed
// except according to those terms.
-fn baz() -> ! { fail!(); }
+fn baz() -> ! { panic!(); }
fn foo() {
match Some::<int>(5) {
fn nested(o: t) {
match o {
- bar(_i, Some::<int>(_)) => { println!("wrong pattern matched"); fail!(); }
+ bar(_i, Some::<int>(_)) => { println!("wrong pattern matched"); panic!(); }
_ => { println!("succeeded"); }
}
}
fn main() {
task::try::<()>(proc() {
let _a = A;
- fail!();
+ panic!();
});
assert!(unsafe { !HIT });
}
}
fn get_ref(&self) -> (int, &T) {
match *self {
- Nothing(..) => fail!("E::get_ref(Nothing::<{}>)", stringify!(T)),
+ Nothing(..) => panic!("E::get_ref(Nothing::<{}>)", stringify!(T)),
Thing(x, ref y) => (x, y)
}
}
let t_ = Thing::<$T>(23, e);
match t_.get_ref() {
(23, $v) => { $chk }
- _ => fail!("Thing::<{}>(23, {}).get_ref() != (23, _)",
+ _ => panic!("Thing::<{}>(23, {}).get_ref() != (23, _)",
stringify!($T), stringify!($e))
}
}}
fn unwrap<T>(o: Option<T>) -> T {
match o {
Some(v) => v,
- None => fail!()
+ None => panic!()
}
}
return &pair.value
}
}
- fail!("No value found for key: {}", index);
+ panic!("No value found for key: {}", index);
}
}
let mut_s = Rc::new(RefCell::new(String::from_str("foo")));
mut_s.borrow_mut().push_str("bar");
- // HACK assert_eq! would fail here because it stores the LHS and RHS in two locals.
+ // HACK assert_eq! would panic here because it stores the LHS and RHS in two locals.
assert!(mut_s.borrow().as_slice() == "foobar");
assert!(mut_s.borrow_mut().as_slice() == "foobar");
let mut_s = Rc::new(RefCell::new(String::from_str("foo")));
(*(*mut_s).borrow_mut()).push_str("bar");
- // assert_eq! would fail here because it stores the LHS and RHS in two locals.
+ // assert_eq! would panic here because it stores the LHS and RHS in two locals.
assert!((*(*mut_s).borrow()).as_slice() == "foobar");
assert!((*(*mut_s).borrow_mut()).as_slice() == "foobar");
#![allow(unreachable_code)]
-fn dont_call_me() { fail!(); println!("{}", 1i); }
+fn dont_call_me() { panic!(); println!("{}", 1i); }
pub fn main() { }
drop(p.stdin.take());
match p.wait().unwrap() {
process::ExitStatus(..) => {}
- process::ExitSignal(..) => fail!()
+ process::ExitSignal(..) => panic!()
}
}
// A very limited test of the "bottom" region
-fn produce_static<T>() -> &'static T { fail!(); }
+fn produce_static<T>() -> &'static T { panic!(); }
fn foo<T>(_x: &T) -> &uint { produce_static() }
fn get_v6_a(a: &A, _i: uint) -> &int {
match a.value.v6 {
Some(ref v) => &v.f,
- None => fail!()
+ None => panic!()
}
}
fn get_v6_b(a: &A, _i: uint) -> &int {
match *a {
A { value: B { v6: Some(ref v), .. } } => &v.f,
- _ => fail!()
+ _ => panic!()
}
}
fn get_v6_c(a: &A, _i: uint) -> &int {
match a {
&A { value: B { v6: Some(ref v), .. } } => &v.f,
- _ => fail!()
+ _ => panic!()
}
}
fn car<'m>(&'m self) -> int {
match self {
&Cons(car, _) => car,
- &Null => fail!(),
+ &Null => panic!(),
}
}
fn cdr<'n>(&'n self) -> &'l List<'l> {
match self {
&Cons(_, cdr) => cdr,
- &Null => fail!(),
+ &Null => panic!(),
}
}
}
fn get<T>(opt: &Option<T>) -> &T {
match *opt {
Some(ref v) => v,
- None => fail!("none")
+ None => panic!("none")
}
}
-fn my_err(s: String) -> ! { println!("{}", s); fail!(); }
+fn my_err(s: String) -> ! { println!("{}", s); panic!(); }
fn okay(i: uint) -> int {
if i == 3u {
unsafe { calls += 1 }
if n >= 0 { return; }
- fail!()
+ panic!()
};
return_works(10);
unsafe { calls += 1 }
if n >= 0 { return; }
- fail!()
+ panic!()
};
return_works_proc(10);
1 => {}
2 => println!("foo"),
3 => assert!(try(|| {}).is_ok()),
- 4 => assert!(try(|| fail!()).is_err()),
+ 4 => assert!(try(|| panic!()).is_err()),
5 => assert!(try(|| spawn(proc() {})).is_err()),
6 => assert!(Command::new("test").spawn().is_err()),
7 => assert!(foo.get().is_none()),
8 => assert!(try(|| { foo.replace(Some(3)); }).is_err()),
- _ => fail!()
+ _ => panic!()
}
}
return 0
mod a {
pub fn f() {
- fail!();
+ panic!();
}
}
match status {
ExitSignal(_) if cfg!(unix) => {},
ExitStatus(0xC0000028) if cfg!(windows) => {},
- _ => fail!("invalid termination (was not signalled): {}", status)
+ _ => panic!("invalid termination (was not signalled): {}", status)
}
}
}
a::<T>(ref _t, ref u) => {
println!("incorrect");
println!("{}", u);
- fail!();
+ panic!();
}
b::<T> => { println!("correct"); }
}
}
fn bar() -> uint {
- fail!();
+ panic!();
}
fn foo() {
pub fn main() {
// check
- if ! cfg!(foo) { fail!() }
- if cfg!(not(foo)) { fail!() }
+ if ! cfg!(foo) { panic!() }
+ if cfg!(not(foo)) { panic!() }
- if ! cfg!(qux="foo") { fail!() }
- if cfg!(not(qux="foo")) { fail!() }
+ if ! cfg!(qux="foo") { panic!() }
+ if cfg!(not(qux="foo")) { panic!() }
- if ! cfg!(all(foo, qux="foo")) { fail!() }
- if cfg!(not(all(foo, qux="foo"))) { fail!() }
- if cfg!(all(not(all(foo, qux="foo")))) { fail!() }
+ if ! cfg!(all(foo, qux="foo")) { panic!() }
+ if cfg!(not(all(foo, qux="foo"))) { panic!() }
+ if cfg!(all(not(all(foo, qux="foo")))) { panic!() }
- if cfg!(not_a_cfg) { fail!() }
- if cfg!(all(not_a_cfg, foo, qux="foo")) { fail!() }
- if cfg!(all(not_a_cfg, foo, qux="foo")) { fail!() }
- if ! cfg!(any(not_a_cfg, foo)) { fail!() }
+ if cfg!(not_a_cfg) { panic!() }
+ if cfg!(all(not_a_cfg, foo, qux="foo")) { panic!() }
+ if cfg!(all(not_a_cfg, foo, qux="foo")) { panic!() }
+ if ! cfg!(any(not_a_cfg, foo)) { panic!() }
- if ! cfg!(not(not_a_cfg)) { fail!() }
- if ! cfg!(all(not(not_a_cfg), foo, qux="foo")) { fail!() }
+ if ! cfg!(not(not_a_cfg)) { panic!() }
+ if ! cfg!(all(not(not_a_cfg), foo, qux="foo")) { panic!() }
}
let stderr = ChanWriter::new(tx);
let res = TaskBuilder::new().stderr(box stderr as Box<Writer + Send>).try(proc() -> () {
- fail!("Hello, world!")
+ panic!("Hello, world!")
});
assert!(res.is_err());
}
}
Err(ref e) if e.kind == EndOfFile => break,
- Err(e) => fail!("{}", e),
+ Err(e) => panic!("{}", e),
}
}
srv_tx.send(());
// wait for senders
if cli_rx.iter().take(N).count() != N {
a.close_accept().unwrap();
- fail!("clients failed");
+ panic!("clients panicked");
}
// wait for one acceptor to die
match TcpStream::connect_timeout(addr, Duration::milliseconds(100)) {
Ok(e) => v.push(e),
Err(ref e) if e.kind == io::TimedOut => return,
- Err(e) => fail!("other error: {}", e),
+ Err(e) => panic!("other error: {}", e),
}
}
- fail!("never timed out!");
+ panic!("never timed out!");
}
fn timeout_success() {
let mut stream = match acceptor.accept() {
Ok(stream) => stream,
Err(error) => {
- debug!("accept failed: {}", error);
+ debug!("accept panicked: {}", error);
continue;
}
};
let f: proc():Send = proc() {
let tmp = TempDir::new("test_rm_tempdir").unwrap();
tx.send(tmp.path().clone());
- fail!("fail to unwind past `tmp`");
+ panic!("panic to unwind past `tmp`");
};
task::try(f);
let path = rx.recv();
let path = tmp.path().clone();
let f: proc():Send = proc() {
let _tmp = tmp;
- fail!("fail to unwind past `tmp`");
+ panic!("panic to unwind past `tmp`");
};
task::try(f);
assert!(!path.exists());
let tmp = TempDir::new("test_rm_tempdir").unwrap();
tx.send(tmp.path().clone());
tmp.close();
- fail!("fail to unwind past `tmp`");
+ panic!("panic when unwinding past `tmp`");
};
task::try(f);
let path = rx.recv();
let f: proc():Send = proc() {
let tmp = tmp;
tmp.close();
- fail!("fail to unwind past `tmp`");
+ panic!("panic when unwinding past `tmp`");
};
task::try(f);
assert!(!path.exists());
assert!(!root.join("bar").join("blat").exists());
}
-pub fn dont_double_fail() {
+pub fn dont_double_panic() {
let r: Result<(), _> = task::try(proc() {
let tmpdir = TempDir::new("test").unwrap();
// Remove the temporary directory so that TempDir sees
// an error on drop
fs::rmdir(tmpdir.path());
- // Trigger failure. If TempDir fails *again* due to the rmdir
+ // Panic. If TempDir panics *again* due to the rmdir
// error then the process will abort.
- fail!();
+ panic!();
});
assert!(r.is_err());
}
in_tmpdir(recursive_mkdir_dot);
in_tmpdir(recursive_mkdir_rel_2);
in_tmpdir(test_rmdir_recursive_ok);
- in_tmpdir(dont_double_fail);
+ in_tmpdir(dont_double_panic);
}
fn test_ret() { let _x: Box<int> = return; }
-fn test_fail() {
- fn f() { let _x: Box<int> = fail!(); }
+fn test_panic() {
+ fn f() { let _x: Box<int> = panic!(); }
task::try(proc() f() );
}
-fn test_fail_indirect() {
- fn f() -> ! { fail!(); }
+fn test_panic_indirect() {
+ fn f() -> ! { panic!(); }
fn g() { let _x: Box<int> = f(); }
task::try(proc() g() );
}
test_break();
test_cont();
test_ret();
- test_fail();
- test_fail_indirect();
+ test_panic();
+ test_panic_indirect();
}
// Building as a test runner means that a synthetic main will be run,
// not ours
-pub fn main() { fail!(); }
+pub fn main() { panic!(); }
pub fn main() {
match default_instance() {
&Request { foo: TestNone, bar: 17 } => {},
- _ => fail!(),
+ _ => panic!(),
};
match non_default_instance() {
&Request { foo: TestSome(0x1020304050607080), bar: 19 } => {},
- _ => fail!(),
+ _ => panic!(),
};
}
match (a, b) {
(A($id1), A($id2)) => A($e),
(B($id1), B($id2)) => B($e),
- _ => fail!()
+ _ => panic!()
}
}
)
t1(a) {
assert_eq!(a, 10);
}
- _ { fail!(); }
+ _ { panic!(); }
}*/
/*alt x {
box t1(a) {
assert_eq!(a, 10);
}
- _ { fail!(); }
+ _ { panic!(); }
}*/
}
}
fn f(_i: Box<int>) -> Box<int> {
- fail!();
+ panic!();
}
fn simple() {
match box true {
box true => { }
- _ => { fail!(); }
+ _ => { panic!(); }
}
}
impl Drop for Foo {
fn drop(&mut self) {
- fail!("This failure should happen.");
+ panic!("This panic should happen.");
}
}
});
let s = x.unwrap_err().downcast::<&'static str>().unwrap();
- assert_eq!(s.as_slice(), "This failure should happen.");
+ assert_eq!(s.as_slice(), "This panic should happen.");
}
};
match process::Process::spawn(cfg) {
- Ok(_) => { fail!("spawn() should have failled"); }
+ Ok(_) => { panic!("spawn() should have panicked"); }
Err(rtio::IoError { code: err, ..}) => {
assert_eq!(err as c_int, EXPECTED_ERRNO);
}
fn id(x: bool) -> bool { x }
fn call_id() {
- let c = fail!();
+ let c = panic!();
id(c); //~ WARNING unreachable statement
}
fn id(x: bool) -> bool { x }
fn call_id() {
- let c = fail!();
+ let c = panic!();
id(c);
}
fn f(tx: Sender<bool>) {
let _tx = complainer(tx);
- fail!();
+ panic!();
}
pub fn main() {
fn f() {
let _a = box 0i;
- fail!();
+ panic!();
}
pub fn main() {
fn foo<T>(o: myoption<T>) -> int {
let mut x: int;
match o {
- none::<T> => { fail!(); }
+ none::<T> => { panic!(); }
some::<T>(_t) => { x = 5; }
}
return x;
pub fn main() {
let x = [1i, 2, 3];
match x {
- [2, _, _] => fail!(),
+ [2, _, _] => panic!(),
[1, a, b] => {
assert!([a, b] == [2, 3]);
}
- [_, _, _] => fail!(),
+ [_, _, _] => panic!(),
}
let y = ([(1i, true), (2i, false)], 0.5f64);
assert_eq!(a, true);
assert_eq!(b, 2);
}
- ([_, _], 0.5) => fail!(),
- ([_, _], _) => fail!(),
+ ([_, _], 0.5) => panic!(),
+ ([_, _], _) => panic!(),
}
}
fn c() {
let x = [1i];
match x {
- [2, ..] => fail!(),
+ [2, ..] => panic!(),
[..] => ()
}
}
let mut count = 0;
main.clone().as_mut_slice().sort_by(|a, b| { count += 1; a.cmp(b) });
- // ... and then fail on each and every single one.
- for fail_countdown in range(0i, count) {
+ // ... and then panic on each and every single one.
+ for panic_countdown in range(0i, count) {
// refresh the counters.
for c in drop_counts.iter() {
c.store(0, Relaxed);
let _ = task::try(proc() {
let mut v = v;
- let mut fail_countdown = fail_countdown;
+ let mut panic_countdown = panic_countdown;
v.as_mut_slice().sort_by(|a, b| {
- if fail_countdown == 0 {
- fail!()
+ if panic_countdown == 0 {
+ panic!()
}
- fail_countdown -= 1;
+ panic_countdown -= 1;
a.cmp(b)
})
});
fn angrydome() {
loop { if break { } }
let mut i = 0i;
- loop { i += 1; if i == 1 { match (continue) { 1i => { }, _ => fail!("wat") } }
+ loop { i += 1; if i == 1 { match (continue) { 1i => { }, _ => panic!("wat") } }
break; }
}
i -= 1;
if i == 95 {
break 'w;
- fail!("Should have broken out of loop");
+ panic!("Should have broken out of loop");
}
}
assert_eq!(i, 95);
Some(ref z) if *z.lock() => {
assert!(*z.lock());
},
- _ => fail!()
+ _ => panic!()
}
}
}