1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 /// Entry point of thread panic, for details, see std::macros
13 #[allow_internal_unstable]
14 #[stable(feature = "core", since = "1.6.0")]
17 panic!("explicit panic")
20 static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!());
21 $crate::panicking::panic(&_MSG_FILE_LINE)
23 ($fmt:expr, $($arg:tt)*) => ({
24 // The leading _'s are to avoid dead code warnings if this is
25 // used inside a dead function. Just `#[allow(dead_code)]` is
26 // insufficient, since the user may have
27 // `#[forbid(dead_code)]` and which cannot be overridden.
28 static _FILE_LINE: (&'static str, u32) = (file!(), line!());
29 $crate::panicking::panic_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
33 /// Ensure that a boolean expression is `true` at runtime.
35 /// This will invoke the `panic!` macro if the provided expression cannot be
36 /// evaluated to `true` at runtime.
38 /// Assertions are always checked in both debug and release builds, and cannot
39 /// be disabled. See `debug_assert!` for assertions that are not enabled in
40 /// release builds by default.
42 /// Unsafe code relies on `assert!` to enforce run-time invariants that, if
43 /// violated could lead to unsafety.
45 /// Other use-cases of `assert!` include
46 /// [testing](https://doc.rust-lang.org/book/testing.html) and enforcing
47 /// run-time invariants in safe code (whose violation cannot result in unsafety).
49 /// This macro has a second version, where a custom panic message can be provided.
54 /// // the panic message for these assertions is the stringified value of the
55 /// // expression given.
58 /// fn some_computation() -> bool { true } // a very simple function
60 /// assert!(some_computation());
62 /// // assert with a custom message
64 /// assert!(x, "x wasn't true!");
66 /// let a = 3; let b = 27;
67 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
70 #[stable(feature = "rust1", since = "1.0.0")]
74 panic!(concat!("assertion failed: ", stringify!($cond)))
77 ($cond:expr, $($arg:tt)+) => (
84 /// Asserts that two expressions are equal to each other.
86 /// On panic, this macro will print the values of the expressions with their
87 /// debug representations.
97 #[stable(feature = "rust1", since = "1.0.0")]
98 macro_rules! assert_eq {
99 ($left:expr , $right:expr) => ({
100 match (&$left, &$right) {
101 (left_val, right_val) => {
102 if !(*left_val == *right_val) {
103 panic!("assertion failed: `(left == right)` \
104 (left: `{:?}`, right: `{:?}`)", left_val, right_val)
109 ($left:expr , $right:expr, $($arg:tt)*) => ({
110 match (&($left), &($right)) {
111 (left_val, right_val) => {
112 if !(*left_val == *right_val) {
113 panic!("assertion failed: `(left == right)` \
114 (left: `{:?}`, right: `{:?}`): {}", left_val, right_val,
115 format_args!($($arg)*))
122 /// Ensure that a boolean expression is `true` at runtime.
124 /// This will invoke the `panic!` macro if the provided expression cannot be
125 /// evaluated to `true` at runtime.
127 /// Like `assert!`, this macro also has a second version, where a custom panic
128 /// message can be provided.
130 /// Unlike `assert!`, `debug_assert!` statements are only enabled in non
131 /// optimized builds by default. An optimized build will omit all
132 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
133 /// compiler. This makes `debug_assert!` useful for checks that are too
134 /// expensive to be present in a release build but may be helpful during
137 /// An unchecked assertion allows a program in an inconsistent state to keep
138 /// running, which might have unexpected consequences but does not introduce
139 /// unsafety as long as this only happens in safe code. The performance cost
140 /// of assertions, is however, not measurable in general. Replacing `assert!`
141 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
142 /// more importantly, only in safe code!
147 /// // the panic message for these assertions is the stringified value of the
148 /// // expression given.
149 /// debug_assert!(true);
151 /// fn some_expensive_computation() -> bool { true } // a very simple function
152 /// debug_assert!(some_expensive_computation());
154 /// // assert with a custom message
156 /// debug_assert!(x, "x wasn't true!");
158 /// let a = 3; let b = 27;
159 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
162 #[stable(feature = "rust1", since = "1.0.0")]
163 macro_rules! debug_assert {
164 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
167 /// Asserts that two expressions are equal to each other.
169 /// On panic, this macro will print the values of the expressions with their
170 /// debug representations.
172 /// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
173 /// optimized builds by default. An optimized build will omit all
174 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
175 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
176 /// expensive to be present in a release build but may be helpful during
184 /// debug_assert_eq!(a, b);
187 #[stable(feature = "rust1", since = "1.0.0")]
188 macro_rules! debug_assert_eq {
189 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
192 /// Helper macro for unwrapping `Result` values while returning early with an
193 /// error if the value of the expression is `Err`. Can only be used in
194 /// functions that return `Result` because of the early return of `Err` that
201 /// use std::fs::File;
202 /// use std::io::prelude::*;
204 /// fn write_to_file_using_try() -> Result<(), io::Error> {
205 /// let mut file = try!(File::create("my_best_friends.txt"));
206 /// try!(file.write_all(b"This is a list of my best friends."));
207 /// println!("I wrote to the file");
210 /// // This is equivalent to:
211 /// fn write_to_file_using_match() -> Result<(), io::Error> {
212 /// let mut file = try!(File::create("my_best_friends.txt"));
213 /// match file.write_all(b"This is a list of my best friends.") {
215 /// Err(e) => return Err(e),
217 /// println!("I wrote to the file");
222 #[stable(feature = "rust1", since = "1.0.0")]
224 ($expr:expr) => (match $expr {
225 $crate::result::Result::Ok(val) => val,
226 $crate::result::Result::Err(err) => {
227 return $crate::result::Result::Err($crate::convert::From::from(err))
232 /// Write formatted data into a buffer
234 /// This macro accepts any value with `write_fmt` method as a writer, a format string, and a list
235 /// of arguments to format.
237 /// `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write] or
238 /// [`std::io::Write`][io_write] traits. These are sometimes called 'writers'.
240 /// Passed arguments will be formatted according to the specified format string and the resulting
241 /// string will be passed to the writer.
243 /// See [`std::fmt`][fmt] for more information on format syntax.
245 /// Return value is completely dependent on the 'write_fmt' method.
247 /// Common return values are: [`Result`][enum_result], [`io::Result`][type_result]
249 /// [fmt]: ../std/fmt/index.html
250 /// [fmt_write]: ../std/fmt/trait.Write.html
251 /// [io_write]: ../std/io/trait.Write.html
252 /// [enum_result]: ../std/result/enum.Result.html
253 /// [type_result]: ../std/io/type.Result.html
258 /// use std::io::Write;
260 /// let mut w = Vec::new();
261 /// write!(&mut w, "test").unwrap();
262 /// write!(&mut w, "formatted {}", "arguments").unwrap();
264 /// assert_eq!(w, b"testformatted arguments");
267 #[stable(feature = "core", since = "1.6.0")]
269 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
272 /// Write formatted data into a buffer, with appending a newline.
274 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
275 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
277 /// This macro accepts any value with `write_fmt` method as a writer, a format string, and a list
278 /// of arguments to format.
280 /// `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write] or
281 /// [`std::io::Write`][io_write] traits. These are sometimes called 'writers'.
283 /// Passed arguments will be formatted according to the specified format string and the resulting
284 /// string will be passed to the writer.
286 /// See [`std::fmt`][fmt] for more information on format syntax.
288 /// Return value is completely dependent on the 'write_fmt' method.
290 /// Common return values are: [`Result`][enum_result], [`io::Result`][type_result]
292 /// [fmt]: ../std/fmt/index.html
293 /// [fmt_write]: ../std/fmt/trait.Write.html
294 /// [io_write]: ../std/io/trait.Write.html
295 /// [enum_result]: ../std/result/enum.Result.html
296 /// [type_result]: ../std/io/type.Result.html
301 /// use std::io::Write;
303 /// let mut w = Vec::new();
304 /// writeln!(&mut w, "test").unwrap();
305 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
307 /// assert_eq!(&w[..], "test\nformatted arguments\n".as_bytes());
310 #[stable(feature = "rust1", since = "1.0.0")]
311 macro_rules! writeln {
312 ($dst:expr, $fmt:expr) => (
313 write!($dst, concat!($fmt, "\n"))
315 ($dst:expr, $fmt:expr, $($arg:tt)*) => (
316 write!($dst, concat!($fmt, "\n"), $($arg)*)
320 /// A utility macro for indicating unreachable code.
322 /// This is useful any time that the compiler can't determine that some code is unreachable. For
325 /// * Match arms with guard conditions.
326 /// * Loops that dynamically terminate.
327 /// * Iterators that dynamically terminate.
331 /// This will always panic.
338 /// # #[allow(dead_code)]
339 /// fn foo(x: Option<i32>) {
341 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
342 /// Some(n) if n < 0 => println!("Some(Negative)"),
343 /// Some(_) => unreachable!(), // compile error if commented out
344 /// None => println!("None")
352 /// # #[allow(dead_code)]
353 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
355 /// if 3*i < i { panic!("u32 overflow"); }
356 /// if x < 3*i { return i-1; }
362 #[stable(feature = "core", since = "1.6.0")]
363 macro_rules! unreachable {
365 panic!("internal error: entered unreachable code")
368 unreachable!("{}", $msg)
370 ($fmt:expr, $($arg:tt)*) => ({
371 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
375 /// A standardized placeholder for marking unfinished code. It panics with the
376 /// message `"not yet implemented"` when executed.
378 /// This can be useful if you are prototyping and are just looking to have your
379 /// code typecheck, or if you're implementing a trait that requires multiple
380 /// methods, and you're only planning on using one of them.
384 /// Here's an example of some in-progress code. We have a trait `Foo`:
393 /// We want to implement `Foo` on one of our types, but we also want to work on
394 /// just `bar()` first. In order for our code to compile, we need to implement
395 /// `baz()`, so we can use `unimplemented!`:
404 /// impl Foo for MyStruct {
406 /// // implementation goes here
410 /// // let's not worry about implementing baz() for now
411 /// unimplemented!();
416 /// let s = MyStruct;
419 /// // we aren't even using baz() yet, so this is fine.
423 #[stable(feature = "core", since = "1.6.0")]
424 macro_rules! unimplemented {
425 () => (panic!("not yet implemented"))