1 /// Entry point of thread panic. For details, see `std::macros`.
3 #[cfg_attr(not(stage0), allow_internal_unstable(core_panic, __rust_unstable_column))]
4 #[cfg_attr(stage0, allow_internal_unstable)]
5 #[stable(feature = "core", since = "1.6.0")]
8 panic!("explicit panic")
11 $crate::panicking::panic(&($msg, file!(), line!(), __rust_unstable_column!()))
16 ($fmt:expr, $($arg:tt)+) => ({
17 $crate::panicking::panic_fmt(format_args!($fmt, $($arg)*),
18 &(file!(), line!(), __rust_unstable_column!()))
22 /// Asserts that two expressions are equal to each other (using [`PartialEq`]).
24 /// On panic, this macro will print the values of the expressions with their
25 /// debug representations.
27 /// Like [`assert!`], this macro has a second form, where a custom
28 /// panic message can be provided.
30 /// [`PartialEq`]: cmp/trait.PartialEq.html
31 /// [`assert!`]: macro.assert.html
40 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
43 #[stable(feature = "rust1", since = "1.0.0")]
44 macro_rules! assert_eq {
45 ($left:expr, $right:expr) => ({
46 match (&$left, &$right) {
47 (left_val, right_val) => {
48 if !(*left_val == *right_val) {
49 panic!(r#"assertion failed: `(left == right)`
51 right: `{:?}`"#, left_val, right_val)
56 ($left:expr, $right:expr,) => ({
57 assert_eq!($left, $right)
59 ($left:expr, $right:expr, $($arg:tt)+) => ({
60 match (&($left), &($right)) {
61 (left_val, right_val) => {
62 if !(*left_val == *right_val) {
63 panic!(r#"assertion failed: `(left == right)`
65 right: `{:?}`: {}"#, left_val, right_val,
66 format_args!($($arg)+))
73 /// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
75 /// On panic, this macro will print the values of the expressions with their
76 /// debug representations.
78 /// Like [`assert!`], this macro has a second form, where a custom
79 /// panic message can be provided.
81 /// [`PartialEq`]: cmp/trait.PartialEq.html
82 /// [`assert!`]: macro.assert.html
91 /// assert_ne!(a, b, "we are testing that the values are not equal");
94 #[stable(feature = "assert_ne", since = "1.13.0")]
95 macro_rules! assert_ne {
96 ($left:expr, $right:expr) => ({
97 match (&$left, &$right) {
98 (left_val, right_val) => {
99 if *left_val == *right_val {
100 panic!(r#"assertion failed: `(left != right)`
102 right: `{:?}`"#, left_val, right_val)
107 ($left:expr, $right:expr,) => {
108 assert_ne!($left, $right)
110 ($left:expr, $right:expr, $($arg:tt)+) => ({
111 match (&($left), &($right)) {
112 (left_val, right_val) => {
113 if *left_val == *right_val {
114 panic!(r#"assertion failed: `(left != right)`
116 right: `{:?}`: {}"#, left_val, right_val,
117 format_args!($($arg)+))
124 /// Ensure that a boolean expression is `true` at runtime.
126 /// This will invoke the [`panic!`] macro if the provided expression cannot be
127 /// evaluated to `true` at runtime.
129 /// Like [`assert!`], this macro also has a second version, where a custom panic
130 /// message can be provided.
134 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
135 /// optimized builds by default. An optimized build will omit all
136 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
137 /// compiler. This makes `debug_assert!` useful for checks that are too
138 /// expensive to be present in a release build but may be helpful during
141 /// An unchecked assertion allows a program in an inconsistent state to keep
142 /// running, which might have unexpected consequences but does not introduce
143 /// unsafety as long as this only happens in safe code. The performance cost
144 /// of assertions, is however, not measurable in general. Replacing [`assert!`]
145 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
146 /// more importantly, only in safe code!
148 /// [`panic!`]: macro.panic.html
149 /// [`assert!`]: macro.assert.html
154 /// // the panic message for these assertions is the stringified value of the
155 /// // expression given.
156 /// debug_assert!(true);
158 /// fn some_expensive_computation() -> bool { true } // a very simple function
159 /// debug_assert!(some_expensive_computation());
161 /// // assert with a custom message
163 /// debug_assert!(x, "x wasn't true!");
165 /// let a = 3; let b = 27;
166 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
169 #[stable(feature = "rust1", since = "1.0.0")]
170 macro_rules! debug_assert {
171 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
174 /// Asserts that two expressions are equal to each other.
176 /// On panic, this macro will print the values of the expressions with their
177 /// debug representations.
179 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
180 /// optimized builds by default. An optimized build will omit all
181 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
182 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
183 /// expensive to be present in a release build but may be helpful during
186 /// [`assert_eq!`]: ../std/macro.assert_eq.html
193 /// debug_assert_eq!(a, b);
196 #[stable(feature = "rust1", since = "1.0.0")]
197 macro_rules! debug_assert_eq {
198 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
201 /// Asserts that two expressions are not equal to each other.
203 /// On panic, this macro will print the values of the expressions with their
204 /// debug representations.
206 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
207 /// optimized builds by default. An optimized build will omit all
208 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
209 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
210 /// expensive to be present in a release build but may be helpful during
213 /// [`assert_ne!`]: ../std/macro.assert_ne.html
220 /// debug_assert_ne!(a, b);
223 #[stable(feature = "assert_ne", since = "1.13.0")]
224 macro_rules! debug_assert_ne {
225 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_ne!($($arg)*); })
228 /// Helper macro for reducing boilerplate code for matching `Result` together
229 /// with converting downstream errors.
231 /// The `?` operator was added to replace `try!` and should be used instead.
232 /// Furthermore, `try` is a reserved word in Rust 2018, so if you must use
233 /// it, you will need to use the [raw-identifier syntax][ris]: `r#try`.
235 /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
237 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
238 /// expression has the value of the wrapped value.
240 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
241 /// performs conversion using `From`. This provides automatic conversion
242 /// between specialized errors and more general ones. The resulting
243 /// error is then immediately returned.
245 /// Because of the early return, `try!` can only be used in functions that
246 /// return [`Result`].
248 /// [`Result`]: ../std/result/enum.Result.html
254 /// use std::fs::File;
255 /// use std::io::prelude::*;
261 /// impl From<io::Error> for MyError {
262 /// fn from(e: io::Error) -> MyError {
263 /// MyError::FileWriteError
267 /// // The preferred method of quick returning Errors
268 /// fn write_to_file_question() -> Result<(), MyError> {
269 /// let mut file = File::create("my_best_friends.txt")?;
270 /// file.write_all(b"This is a list of my best friends.")?;
274 /// // The previous method of quick returning Errors
275 /// fn write_to_file_using_try() -> Result<(), MyError> {
276 /// let mut file = r#try!(File::create("my_best_friends.txt"));
277 /// r#try!(file.write_all(b"This is a list of my best friends."));
281 /// // This is equivalent to:
282 /// fn write_to_file_using_match() -> Result<(), MyError> {
283 /// let mut file = r#try!(File::create("my_best_friends.txt"));
284 /// match file.write_all(b"This is a list of my best friends.") {
286 /// Err(e) => return Err(From::from(e)),
292 #[stable(feature = "rust1", since = "1.0.0")]
295 ($expr:expr) => (match $expr {
296 $crate::result::Result::Ok(val) => val,
297 $crate::result::Result::Err(err) => {
298 return $crate::result::Result::Err($crate::convert::From::from(err))
301 ($expr:expr,) => (r#try!($expr));
304 /// Write formatted data into a buffer.
306 /// This macro accepts a format string, a list of arguments, and a 'writer'. Arguments will be
307 /// formatted according to the specified format string and the result will be passed to the writer.
308 /// The writer may be any value with a `write_fmt` method; generally this comes from an
309 /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro
310 /// returns whatever the `write_fmt` method returns; commonly a [`std::fmt::Result`], or an
313 /// See [`std::fmt`] for more information on the format string syntax.
315 /// [`std::fmt`]: ../std/fmt/index.html
316 /// [`std::fmt::Write`]: ../std/fmt/trait.Write.html
317 /// [`std::io::Write`]: ../std/io/trait.Write.html
318 /// [`std::fmt::Result`]: ../std/fmt/type.Result.html
319 /// [`io::Result`]: ../std/io/type.Result.html
324 /// use std::io::Write;
326 /// let mut w = Vec::new();
327 /// write!(&mut w, "test").unwrap();
328 /// write!(&mut w, "formatted {}", "arguments").unwrap();
330 /// assert_eq!(w, b"testformatted arguments");
333 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
334 /// implementing either, as objects do not typically implement both. However, the module must
335 /// import the traits qualified so their names do not conflict:
338 /// use std::fmt::Write as FmtWrite;
339 /// use std::io::Write as IoWrite;
341 /// let mut s = String::new();
342 /// let mut v = Vec::new();
343 /// write!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
344 /// write!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
345 /// assert_eq!(v, b"s = \"abc 123\"");
348 /// Note: This macro can be used in `no_std` setups as well.
349 /// In a `no_std` setup you are responsible for the implementation details of the components.
352 /// # extern crate core;
353 /// use core::fmt::Write;
357 /// impl Write for Example {
358 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
359 /// unimplemented!();
363 /// let mut m = Example{};
364 /// write!(&mut m, "Hello World").expect("Not written");
367 #[stable(feature = "rust1", since = "1.0.0")]
369 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
372 /// Write formatted data into a buffer, with a newline appended.
374 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
375 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
377 /// For more information, see [`write!`]. For information on the format string syntax, see
380 /// [`write!`]: macro.write.html
381 /// [`std::fmt`]: ../std/fmt/index.html
387 /// use std::io::Write;
389 /// let mut w = Vec::new();
390 /// writeln!(&mut w).unwrap();
391 /// writeln!(&mut w, "test").unwrap();
392 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
394 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
397 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
398 /// implementing either, as objects do not typically implement both. However, the module must
399 /// import the traits qualified so their names do not conflict:
402 /// use std::fmt::Write as FmtWrite;
403 /// use std::io::Write as IoWrite;
405 /// let mut s = String::new();
406 /// let mut v = Vec::new();
407 /// writeln!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
408 /// writeln!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
409 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
412 #[stable(feature = "rust1", since = "1.0.0")]
413 #[cfg_attr(stage0, allow_internal_unstable)]
414 #[cfg_attr(not(stage0), allow_internal_unstable(format_args_nl))]
415 macro_rules! writeln {
422 ($dst:expr, $($arg:tt)*) => (
423 $dst.write_fmt(format_args_nl!($($arg)*))
427 /// A utility macro for indicating unreachable code.
429 /// This is useful any time that the compiler can't determine that some code is unreachable. For
432 /// * Match arms with guard conditions.
433 /// * Loops that dynamically terminate.
434 /// * Iterators that dynamically terminate.
436 /// If the determination that the code is unreachable proves incorrect, the
437 /// program immediately terminates with a [`panic!`]. The function [`unreachable_unchecked`],
438 /// which belongs to the [`std::hint`] module, informs the compiler to
439 /// optimize the code out of the release version entirely.
441 /// [`panic!`]: ../std/macro.panic.html
442 /// [`unreachable_unchecked`]: ../std/hint/fn.unreachable_unchecked.html
443 /// [`std::hint`]: ../std/hint/index.html
447 /// This will always [`panic!`]
449 /// [`panic!`]: ../std/macro.panic.html
455 /// # #[allow(dead_code)]
456 /// fn foo(x: Option<i32>) {
458 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
459 /// Some(n) if n < 0 => println!("Some(Negative)"),
460 /// Some(_) => unreachable!(), // compile error if commented out
461 /// None => println!("None")
469 /// # #[allow(dead_code)]
470 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
472 /// if 3*i < i { panic!("u32 overflow"); }
473 /// if x < 3*i { return i-1; }
479 #[stable(feature = "rust1", since = "1.0.0")]
480 macro_rules! unreachable {
482 panic!("internal error: entered unreachable code")
485 unreachable!("{}", $msg)
490 ($fmt:expr, $($arg:tt)*) => ({
491 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
495 /// A standardized placeholder for marking unfinished code.
497 /// This can be useful if you are prototyping and are just looking to have your
498 /// code type-check, or if you're implementing a trait that requires multiple
499 /// methods, and you're only planning on using one of them.
503 /// This will always [panic!](macro.panic.html)
507 /// Here's an example of some in-progress code. We have a trait `Foo`:
516 /// We want to implement `Foo` on one of our types, but we also want to work on
517 /// just `bar()` first. In order for our code to compile, we need to implement
518 /// `baz()`, so we can use `unimplemented!`:
527 /// impl Foo for MyStruct {
529 /// // implementation goes here
533 /// // let's not worry about implementing baz() for now
534 /// unimplemented!();
539 /// let s = MyStruct;
542 /// // we aren't even using baz() yet, so this is fine.
546 #[stable(feature = "rust1", since = "1.0.0")]
547 macro_rules! unimplemented {
548 () => (panic!("not yet implemented"));
549 ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)*)));
552 /// A macro to create an array of [`MaybeUninit`]
554 /// This macro constructs and uninitialized array of the type `[MaybeUninit<K>; N]`.
556 /// [`MaybeUninit`]: mem/union.MaybeUninit.html
558 #[unstable(feature = "maybe_uninit", issue = "53491")]
559 macro_rules! uninitialized_array {
560 // This `into_initialized` is safe because an array of `MaybeUninit` does not
561 // require initialization.
562 // FIXME(#49147): Could be replaced by an array initializer, once those can
563 // be any const expression.
564 ($t:ty; $size:expr) => (unsafe {
565 MaybeUninit::<[MaybeUninit<$t>; $size]>::uninitialized().into_initialized()
569 /// Built-in macros to the compiler itself.
571 /// These macros do not have any corresponding definition with a `macro_rules!`
572 /// macro, but are documented here. Their implementations can be found hardcoded
573 /// into libsyntax itself.
575 /// For more information, see documentation for `std`'s macros.
579 /// Unconditionally causes compilation to fail with the given error message when encountered.
581 /// For more information, see the documentation for [`std::compile_error!`].
583 /// [`std::compile_error!`]: ../std/macro.compile_error.html
584 #[stable(feature = "compile_error_macro", since = "1.20.0")]
585 #[rustc_doc_only_macro]
586 macro_rules! compile_error {
587 ($msg:expr) => ({ /* compiler built-in */ });
588 ($msg:expr,) => ({ /* compiler built-in */ });
591 /// The core macro for formatted string creation & output.
593 /// For more information, see the documentation for [`std::format_args!`].
595 /// [`std::format_args!`]: ../std/macro.format_args.html
596 #[stable(feature = "rust1", since = "1.0.0")]
597 #[rustc_doc_only_macro]
598 macro_rules! format_args {
599 ($fmt:expr) => ({ /* compiler built-in */ });
600 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ });
603 /// Inspect an environment variable at compile time.
605 /// For more information, see the documentation for [`std::env!`].
607 /// [`std::env!`]: ../std/macro.env.html
608 #[stable(feature = "rust1", since = "1.0.0")]
609 #[rustc_doc_only_macro]
611 ($name:expr) => ({ /* compiler built-in */ });
612 ($name:expr,) => ({ /* compiler built-in */ });
615 /// Optionally inspect an environment variable at compile time.
617 /// For more information, see the documentation for [`std::option_env!`].
619 /// [`std::option_env!`]: ../std/macro.option_env.html
620 #[stable(feature = "rust1", since = "1.0.0")]
621 #[rustc_doc_only_macro]
622 macro_rules! option_env {
623 ($name:expr) => ({ /* compiler built-in */ });
624 ($name:expr,) => ({ /* compiler built-in */ });
627 /// Concatenate identifiers into one identifier.
629 /// For more information, see the documentation for [`std::concat_idents!`].
631 /// [`std::concat_idents!`]: ../std/macro.concat_idents.html
632 #[unstable(feature = "concat_idents_macro", issue = "29599")]
633 #[rustc_doc_only_macro]
634 macro_rules! concat_idents {
635 ($($e:ident),+) => ({ /* compiler built-in */ });
636 ($($e:ident,)+) => ({ /* compiler built-in */ });
639 /// Concatenates literals into a static string slice.
641 /// For more information, see the documentation for [`std::concat!`].
643 /// [`std::concat!`]: ../std/macro.concat.html
644 #[stable(feature = "rust1", since = "1.0.0")]
645 #[rustc_doc_only_macro]
646 macro_rules! concat {
647 ($($e:expr),*) => ({ /* compiler built-in */ });
648 ($($e:expr,)*) => ({ /* compiler built-in */ });
651 /// A macro which expands to the line number on which it was invoked.
653 /// For more information, see the documentation for [`std::line!`].
655 /// [`std::line!`]: ../std/macro.line.html
656 #[stable(feature = "rust1", since = "1.0.0")]
657 #[rustc_doc_only_macro]
658 macro_rules! line { () => ({ /* compiler built-in */ }) }
660 /// A macro which expands to the column number on which it was invoked.
662 /// For more information, see the documentation for [`std::column!`].
664 /// [`std::column!`]: ../std/macro.column.html
665 #[stable(feature = "rust1", since = "1.0.0")]
666 #[rustc_doc_only_macro]
667 macro_rules! column { () => ({ /* compiler built-in */ }) }
669 /// A macro which expands to the file name from which it was invoked.
671 /// For more information, see the documentation for [`std::file!`].
673 /// [`std::file!`]: ../std/macro.file.html
674 #[stable(feature = "rust1", since = "1.0.0")]
675 #[rustc_doc_only_macro]
676 macro_rules! file { () => ({ /* compiler built-in */ }) }
678 /// A macro which stringifies its arguments.
680 /// For more information, see the documentation for [`std::stringify!`].
682 /// [`std::stringify!`]: ../std/macro.stringify.html
683 #[stable(feature = "rust1", since = "1.0.0")]
684 #[rustc_doc_only_macro]
685 macro_rules! stringify { ($($t:tt)*) => ({ /* compiler built-in */ }) }
687 /// Includes a utf8-encoded file as a string.
689 /// For more information, see the documentation for [`std::include_str!`].
691 /// [`std::include_str!`]: ../std/macro.include_str.html
692 #[stable(feature = "rust1", since = "1.0.0")]
693 #[rustc_doc_only_macro]
694 macro_rules! include_str {
695 ($file:expr) => ({ /* compiler built-in */ });
696 ($file:expr,) => ({ /* compiler built-in */ });
699 /// Includes a file as a reference to a byte array.
701 /// For more information, see the documentation for [`std::include_bytes!`].
703 /// [`std::include_bytes!`]: ../std/macro.include_bytes.html
704 #[stable(feature = "rust1", since = "1.0.0")]
705 #[rustc_doc_only_macro]
706 macro_rules! include_bytes {
707 ($file:expr) => ({ /* compiler built-in */ });
708 ($file:expr,) => ({ /* compiler built-in */ });
711 /// Expands to a string that represents the current module path.
713 /// For more information, see the documentation for [`std::module_path!`].
715 /// [`std::module_path!`]: ../std/macro.module_path.html
716 #[stable(feature = "rust1", since = "1.0.0")]
717 #[rustc_doc_only_macro]
718 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
720 /// Boolean evaluation of configuration flags, at compile-time.
722 /// For more information, see the documentation for [`std::cfg!`].
724 /// [`std::cfg!`]: ../std/macro.cfg.html
725 #[stable(feature = "rust1", since = "1.0.0")]
726 #[rustc_doc_only_macro]
727 macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
729 /// Parse a file as an expression or an item according to the context.
731 /// For more information, see the documentation for [`std::include!`].
733 /// [`std::include!`]: ../std/macro.include.html
734 #[stable(feature = "rust1", since = "1.0.0")]
735 #[rustc_doc_only_macro]
736 macro_rules! include {
737 ($file:expr) => ({ /* compiler built-in */ });
738 ($file:expr,) => ({ /* compiler built-in */ });
741 /// Ensure that a boolean expression is `true` at runtime.
743 /// For more information, see the documentation for [`std::assert!`].
745 /// [`std::assert!`]: ../std/macro.assert.html
746 #[rustc_doc_only_macro]
747 #[stable(feature = "rust1", since = "1.0.0")]
748 macro_rules! assert {
749 ($cond:expr) => ({ /* compiler built-in */ });
750 ($cond:expr,) => ({ /* compiler built-in */ });
751 ($cond:expr, $($arg:tt)+) => ({ /* compiler built-in */ });