1 /// Entry point of thread panic. For details, see `std::macros`.
3 #[allow_internal_unstable(core_panic, __rust_unstable_column)]
4 #[stable(feature = "core", since = "1.6.0")]
7 panic!("explicit panic")
10 $crate::panicking::panic(&($msg, file!(), line!(), __rust_unstable_column!()))
15 ($fmt:expr, $($arg:tt)+) => ({
16 $crate::panicking::panic_fmt(format_args!($fmt, $($arg)*),
17 &(file!(), line!(), __rust_unstable_column!()))
21 /// Asserts that two expressions are equal to each other (using [`PartialEq`]).
23 /// On panic, this macro will print the values of the expressions with their
24 /// debug representations.
26 /// Like [`assert!`], this macro has a second form, where a custom
27 /// panic message can be provided.
29 /// [`PartialEq`]: cmp/trait.PartialEq.html
30 /// [`assert!`]: macro.assert.html
39 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
42 #[stable(feature = "rust1", since = "1.0.0")]
43 macro_rules! assert_eq {
44 ($left:expr, $right:expr) => ({
45 match (&$left, &$right) {
46 (left_val, right_val) => {
47 if !(*left_val == *right_val) {
48 // The reborrows below are intentional. Without them, the stack slot for the
49 // borrow is initialized even before the values are compared, leading to a
50 // noticeable slow down.
51 panic!(r#"assertion failed: `(left == right)`
53 right: `{:?}`"#, &*left_val, &*right_val)
58 ($left:expr, $right:expr,) => ({
59 assert_eq!($left, $right)
61 ($left:expr, $right:expr, $($arg:tt)+) => ({
62 match (&($left), &($right)) {
63 (left_val, right_val) => {
64 if !(*left_val == *right_val) {
65 // The reborrows below are intentional. Without them, the stack slot for the
66 // borrow is initialized even before the values are compared, leading to a
67 // noticeable slow down.
68 panic!(r#"assertion failed: `(left == right)`
70 right: `{:?}`: {}"#, &*left_val, &*right_val,
71 format_args!($($arg)+))
78 /// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
80 /// On panic, this macro will print the values of the expressions with their
81 /// debug representations.
83 /// Like [`assert!`], this macro has a second form, where a custom
84 /// panic message can be provided.
86 /// [`PartialEq`]: cmp/trait.PartialEq.html
87 /// [`assert!`]: macro.assert.html
96 /// assert_ne!(a, b, "we are testing that the values are not equal");
99 #[stable(feature = "assert_ne", since = "1.13.0")]
100 macro_rules! assert_ne {
101 ($left:expr, $right:expr) => ({
102 match (&$left, &$right) {
103 (left_val, right_val) => {
104 if *left_val == *right_val {
105 // The reborrows below are intentional. Without them, the stack slot for the
106 // borrow is initialized even before the values are compared, leading to a
107 // noticeable slow down.
108 panic!(r#"assertion failed: `(left != right)`
110 right: `{:?}`"#, &*left_val, &*right_val)
115 ($left:expr, $right:expr,) => {
116 assert_ne!($left, $right)
118 ($left:expr, $right:expr, $($arg:tt)+) => ({
119 match (&($left), &($right)) {
120 (left_val, right_val) => {
121 if *left_val == *right_val {
122 // The reborrows below are intentional. Without them, the stack slot for the
123 // borrow is initialized even before the values are compared, leading to a
124 // noticeable slow down.
125 panic!(r#"assertion failed: `(left != right)`
127 right: `{:?}`: {}"#, &*left_val, &*right_val,
128 format_args!($($arg)+))
135 /// Ensure that a boolean expression is `true` at runtime.
137 /// This will invoke the [`panic!`] macro if the provided expression cannot be
138 /// evaluated to `true` at runtime.
140 /// Like [`assert!`], this macro also has a second version, where a custom panic
141 /// message can be provided.
145 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
146 /// optimized builds by default. An optimized build will omit all
147 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
148 /// compiler. This makes `debug_assert!` useful for checks that are too
149 /// expensive to be present in a release build but may be helpful during
152 /// An unchecked assertion allows a program in an inconsistent state to keep
153 /// running, which might have unexpected consequences but does not introduce
154 /// unsafety as long as this only happens in safe code. The performance cost
155 /// of assertions, is however, not measurable in general. Replacing [`assert!`]
156 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
157 /// more importantly, only in safe code!
159 /// [`panic!`]: macro.panic.html
160 /// [`assert!`]: macro.assert.html
165 /// // the panic message for these assertions is the stringified value of the
166 /// // expression given.
167 /// debug_assert!(true);
169 /// fn some_expensive_computation() -> bool { true } // a very simple function
170 /// debug_assert!(some_expensive_computation());
172 /// // assert with a custom message
174 /// debug_assert!(x, "x wasn't true!");
176 /// let a = 3; let b = 27;
177 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
180 #[stable(feature = "rust1", since = "1.0.0")]
181 macro_rules! debug_assert {
182 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
185 /// Asserts that two expressions are equal to each other.
187 /// On panic, this macro will print the values of the expressions with their
188 /// debug representations.
190 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
191 /// optimized builds by default. An optimized build will omit all
192 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
193 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
194 /// expensive to be present in a release build but may be helpful during
197 /// [`assert_eq!`]: ../std/macro.assert_eq.html
204 /// debug_assert_eq!(a, b);
207 #[stable(feature = "rust1", since = "1.0.0")]
208 macro_rules! debug_assert_eq {
209 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
212 /// Asserts that two expressions are not equal to each other.
214 /// On panic, this macro will print the values of the expressions with their
215 /// debug representations.
217 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
218 /// optimized builds by default. An optimized build will omit all
219 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
220 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
221 /// expensive to be present in a release build but may be helpful during
224 /// [`assert_ne!`]: ../std/macro.assert_ne.html
231 /// debug_assert_ne!(a, b);
234 #[stable(feature = "assert_ne", since = "1.13.0")]
235 macro_rules! debug_assert_ne {
236 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_ne!($($arg)*); })
239 /// Helper macro for reducing boilerplate code for matching `Result` together
240 /// with converting downstream errors.
242 /// The `?` operator was added to replace `try!` and should be used instead.
243 /// Furthermore, `try` is a reserved word in Rust 2018, so if you must use
244 /// it, you will need to use the [raw-identifier syntax][ris]: `r#try`.
246 /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
248 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
249 /// expression has the value of the wrapped value.
251 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
252 /// performs conversion using `From`. This provides automatic conversion
253 /// between specialized errors and more general ones. The resulting
254 /// error is then immediately returned.
256 /// Because of the early return, `try!` can only be used in functions that
257 /// return [`Result`].
259 /// [`Result`]: ../std/result/enum.Result.html
265 /// use std::fs::File;
266 /// use std::io::prelude::*;
272 /// impl From<io::Error> for MyError {
273 /// fn from(e: io::Error) -> MyError {
274 /// MyError::FileWriteError
278 /// // The preferred method of quick returning Errors
279 /// fn write_to_file_question() -> Result<(), MyError> {
280 /// let mut file = File::create("my_best_friends.txt")?;
281 /// file.write_all(b"This is a list of my best friends.")?;
285 /// // The previous method of quick returning Errors
286 /// fn write_to_file_using_try() -> Result<(), MyError> {
287 /// let mut file = r#try!(File::create("my_best_friends.txt"));
288 /// r#try!(file.write_all(b"This is a list of my best friends."));
292 /// // This is equivalent to:
293 /// fn write_to_file_using_match() -> Result<(), MyError> {
294 /// let mut file = r#try!(File::create("my_best_friends.txt"));
295 /// match file.write_all(b"This is a list of my best friends.") {
297 /// Err(e) => return Err(From::from(e)),
303 #[stable(feature = "rust1", since = "1.0.0")]
306 ($expr:expr) => (match $expr {
307 $crate::result::Result::Ok(val) => val,
308 $crate::result::Result::Err(err) => {
309 return $crate::result::Result::Err($crate::convert::From::from(err))
312 ($expr:expr,) => (r#try!($expr));
315 /// Write formatted data into a buffer.
317 /// This macro accepts a format string, a list of arguments, and a 'writer'. Arguments will be
318 /// formatted according to the specified format string and the result will be passed to the writer.
319 /// The writer may be any value with a `write_fmt` method; generally this comes from an
320 /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro
321 /// returns whatever the `write_fmt` method returns; commonly a [`std::fmt::Result`], or an
324 /// See [`std::fmt`] for more information on the format string syntax.
326 /// [`std::fmt`]: ../std/fmt/index.html
327 /// [`std::fmt::Write`]: ../std/fmt/trait.Write.html
328 /// [`std::io::Write`]: ../std/io/trait.Write.html
329 /// [`std::fmt::Result`]: ../std/fmt/type.Result.html
330 /// [`io::Result`]: ../std/io/type.Result.html
335 /// use std::io::Write;
337 /// let mut w = Vec::new();
338 /// write!(&mut w, "test").unwrap();
339 /// write!(&mut w, "formatted {}", "arguments").unwrap();
341 /// assert_eq!(w, b"testformatted arguments");
344 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
345 /// implementing either, as objects do not typically implement both. However, the module must
346 /// import the traits qualified so their names do not conflict:
349 /// use std::fmt::Write as FmtWrite;
350 /// use std::io::Write as IoWrite;
352 /// let mut s = String::new();
353 /// let mut v = Vec::new();
354 /// write!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
355 /// write!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
356 /// assert_eq!(v, b"s = \"abc 123\"");
359 /// Note: This macro can be used in `no_std` setups as well.
360 /// In a `no_std` setup you are responsible for the implementation details of the components.
363 /// # extern crate core;
364 /// use core::fmt::Write;
368 /// impl Write for Example {
369 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
370 /// unimplemented!();
374 /// let mut m = Example{};
375 /// write!(&mut m, "Hello World").expect("Not written");
378 #[stable(feature = "rust1", since = "1.0.0")]
380 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
383 /// Write formatted data into a buffer, with a newline appended.
385 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
386 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
388 /// For more information, see [`write!`]. For information on the format string syntax, see
391 /// [`write!`]: macro.write.html
392 /// [`std::fmt`]: ../std/fmt/index.html
398 /// use std::io::Write;
400 /// let mut w = Vec::new();
401 /// writeln!(&mut w).unwrap();
402 /// writeln!(&mut w, "test").unwrap();
403 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
405 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
408 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
409 /// implementing either, as objects do not typically implement both. However, the module must
410 /// import the traits qualified so their names do not conflict:
413 /// use std::fmt::Write as FmtWrite;
414 /// use std::io::Write as IoWrite;
416 /// let mut s = String::new();
417 /// let mut v = Vec::new();
418 /// writeln!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
419 /// writeln!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
420 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
423 #[stable(feature = "rust1", since = "1.0.0")]
424 #[allow_internal_unstable(format_args_nl)]
425 macro_rules! writeln {
432 ($dst:expr, $($arg:tt)*) => (
433 $dst.write_fmt(format_args_nl!($($arg)*))
437 /// A utility macro for indicating unreachable code.
439 /// This is useful any time that the compiler can't determine that some code is unreachable. For
442 /// * Match arms with guard conditions.
443 /// * Loops that dynamically terminate.
444 /// * Iterators that dynamically terminate.
446 /// If the determination that the code is unreachable proves incorrect, the
447 /// program immediately terminates with a [`panic!`]. The function [`unreachable_unchecked`],
448 /// which belongs to the [`std::hint`] module, informs the compiler to
449 /// optimize the code out of the release version entirely.
451 /// [`panic!`]: ../std/macro.panic.html
452 /// [`unreachable_unchecked`]: ../std/hint/fn.unreachable_unchecked.html
453 /// [`std::hint`]: ../std/hint/index.html
457 /// This will always [`panic!`]
459 /// [`panic!`]: ../std/macro.panic.html
465 /// # #[allow(dead_code)]
466 /// fn foo(x: Option<i32>) {
468 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
469 /// Some(n) if n < 0 => println!("Some(Negative)"),
470 /// Some(_) => unreachable!(), // compile error if commented out
471 /// None => println!("None")
479 /// # #[allow(dead_code)]
480 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
482 /// if 3*i < i { panic!("u32 overflow"); }
483 /// if x < 3*i { return i-1; }
489 #[stable(feature = "rust1", since = "1.0.0")]
490 macro_rules! unreachable {
492 panic!("internal error: entered unreachable code")
495 unreachable!("{}", $msg)
500 ($fmt:expr, $($arg:tt)*) => ({
501 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
505 /// A standardized placeholder for marking unfinished code.
507 /// This can be useful if you are prototyping and are just looking to have your
508 /// code type-check, or if you're implementing a trait that requires multiple
509 /// methods, and you're only planning on using one of them.
513 /// This will always [panic!](macro.panic.html)
517 /// Here's an example of some in-progress code. We have a trait `Foo`:
526 /// We want to implement `Foo` on one of our types, but we also want to work on
527 /// just `bar()` first. In order for our code to compile, we need to implement
528 /// `baz()`, so we can use `unimplemented!`:
537 /// impl Foo for MyStruct {
539 /// // implementation goes here
543 /// // let's not worry about implementing baz() for now
544 /// unimplemented!();
549 /// let s = MyStruct;
552 /// // we aren't even using baz() yet, so this is fine.
556 #[stable(feature = "rust1", since = "1.0.0")]
557 macro_rules! unimplemented {
558 () => (panic!("not yet implemented"));
559 ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)*)));
562 /// A macro to create an array of [`MaybeUninit`]
564 /// This macro constructs an uninitialized array of the type `[MaybeUninit<K>; N]`.
566 /// [`MaybeUninit`]: mem/union.MaybeUninit.html
568 #[unstable(feature = "maybe_uninit_array", issue = "53491")]
569 macro_rules! uninitialized_array {
570 // This `into_initialized` is safe because an array of `MaybeUninit` does not
571 // require initialization.
572 // FIXME(#49147): Could be replaced by an array initializer, once those can
573 // be any const expression.
574 ($t:ty; $size:expr) => (unsafe {
575 MaybeUninit::<[MaybeUninit<$t>; $size]>::uninitialized().into_initialized()
579 /// Built-in macros to the compiler itself.
581 /// These macros do not have any corresponding definition with a `macro_rules!`
582 /// macro, but are documented here. Their implementations can be found hardcoded
583 /// into libsyntax itself.
585 /// For more information, see documentation for `std`'s macros.
589 /// Unconditionally causes compilation to fail with the given error message when encountered.
591 /// For more information, see the documentation for [`std::compile_error!`].
593 /// [`std::compile_error!`]: ../std/macro.compile_error.html
594 #[stable(feature = "compile_error_macro", since = "1.20.0")]
595 #[rustc_doc_only_macro]
596 macro_rules! compile_error {
597 ($msg:expr) => ({ /* compiler built-in */ });
598 ($msg:expr,) => ({ /* compiler built-in */ });
601 /// The core macro for formatted string creation & output.
603 /// For more information, see the documentation for [`std::format_args!`].
605 /// [`std::format_args!`]: ../std/macro.format_args.html
606 #[stable(feature = "rust1", since = "1.0.0")]
607 #[rustc_doc_only_macro]
608 macro_rules! format_args {
609 ($fmt:expr) => ({ /* compiler built-in */ });
610 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ });
613 /// Inspect an environment variable at compile time.
615 /// For more information, see the documentation for [`std::env!`].
617 /// [`std::env!`]: ../std/macro.env.html
618 #[stable(feature = "rust1", since = "1.0.0")]
619 #[rustc_doc_only_macro]
621 ($name:expr) => ({ /* compiler built-in */ });
622 ($name:expr,) => ({ /* compiler built-in */ });
625 /// Optionally inspect an environment variable at compile time.
627 /// For more information, see the documentation for [`std::option_env!`].
629 /// [`std::option_env!`]: ../std/macro.option_env.html
630 #[stable(feature = "rust1", since = "1.0.0")]
631 #[rustc_doc_only_macro]
632 macro_rules! option_env {
633 ($name:expr) => ({ /* compiler built-in */ });
634 ($name:expr,) => ({ /* compiler built-in */ });
637 /// Concatenate identifiers into one identifier.
639 /// For more information, see the documentation for [`std::concat_idents!`].
641 /// [`std::concat_idents!`]: ../std/macro.concat_idents.html
642 #[unstable(feature = "concat_idents_macro", issue = "29599")]
643 #[rustc_doc_only_macro]
644 macro_rules! concat_idents {
645 ($($e:ident),+) => ({ /* compiler built-in */ });
646 ($($e:ident,)+) => ({ /* compiler built-in */ });
649 /// Concatenates literals into a static string slice.
651 /// For more information, see the documentation for [`std::concat!`].
653 /// [`std::concat!`]: ../std/macro.concat.html
654 #[stable(feature = "rust1", since = "1.0.0")]
655 #[rustc_doc_only_macro]
656 macro_rules! concat {
657 ($($e:expr),*) => ({ /* compiler built-in */ });
658 ($($e:expr,)*) => ({ /* compiler built-in */ });
661 /// A macro which expands to the line number on which it was invoked.
663 /// For more information, see the documentation for [`std::line!`].
665 /// [`std::line!`]: ../std/macro.line.html
666 #[stable(feature = "rust1", since = "1.0.0")]
667 #[rustc_doc_only_macro]
668 macro_rules! line { () => ({ /* compiler built-in */ }) }
670 /// A macro which expands to the column number on which it was invoked.
672 /// For more information, see the documentation for [`std::column!`].
674 /// [`std::column!`]: ../std/macro.column.html
675 #[stable(feature = "rust1", since = "1.0.0")]
676 #[rustc_doc_only_macro]
677 macro_rules! column { () => ({ /* compiler built-in */ }) }
679 /// A macro which expands to the file name from which it was invoked.
681 /// For more information, see the documentation for [`std::file!`].
683 /// [`std::file!`]: ../std/macro.file.html
684 #[stable(feature = "rust1", since = "1.0.0")]
685 #[rustc_doc_only_macro]
686 macro_rules! file { () => ({ /* compiler built-in */ }) }
688 /// A macro which stringifies its arguments.
690 /// For more information, see the documentation for [`std::stringify!`].
692 /// [`std::stringify!`]: ../std/macro.stringify.html
693 #[stable(feature = "rust1", since = "1.0.0")]
694 #[rustc_doc_only_macro]
695 macro_rules! stringify { ($($t:tt)*) => ({ /* compiler built-in */ }) }
697 /// Includes a utf8-encoded file as a string.
699 /// For more information, see the documentation for [`std::include_str!`].
701 /// [`std::include_str!`]: ../std/macro.include_str.html
702 #[stable(feature = "rust1", since = "1.0.0")]
703 #[rustc_doc_only_macro]
704 macro_rules! include_str {
705 ($file:expr) => ({ /* compiler built-in */ });
706 ($file:expr,) => ({ /* compiler built-in */ });
709 /// Includes a file as a reference to a byte array.
711 /// For more information, see the documentation for [`std::include_bytes!`].
713 /// [`std::include_bytes!`]: ../std/macro.include_bytes.html
714 #[stable(feature = "rust1", since = "1.0.0")]
715 #[rustc_doc_only_macro]
716 macro_rules! include_bytes {
717 ($file:expr) => ({ /* compiler built-in */ });
718 ($file:expr,) => ({ /* compiler built-in */ });
721 /// Expands to a string that represents the current module path.
723 /// For more information, see the documentation for [`std::module_path!`].
725 /// [`std::module_path!`]: ../std/macro.module_path.html
726 #[stable(feature = "rust1", since = "1.0.0")]
727 #[rustc_doc_only_macro]
728 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
730 /// Boolean evaluation of configuration flags, at compile-time.
732 /// For more information, see the documentation for [`std::cfg!`].
734 /// [`std::cfg!`]: ../std/macro.cfg.html
735 #[stable(feature = "rust1", since = "1.0.0")]
736 #[rustc_doc_only_macro]
737 macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
739 /// Parse a file as an expression or an item according to the context.
741 /// For more information, see the documentation for [`std::include!`].
743 /// [`std::include!`]: ../std/macro.include.html
744 #[stable(feature = "rust1", since = "1.0.0")]
745 #[rustc_doc_only_macro]
746 macro_rules! include {
747 ($file:expr) => ({ /* compiler built-in */ });
748 ($file:expr,) => ({ /* compiler built-in */ });
751 /// Ensure that a boolean expression is `true` at runtime.
753 /// For more information, see the documentation for [`std::assert!`].
755 /// [`std::assert!`]: ../std/macro.assert.html
756 #[rustc_doc_only_macro]
757 #[stable(feature = "rust1", since = "1.0.0")]
758 macro_rules! assert {
759 ($cond:expr) => ({ /* compiler built-in */ });
760 ($cond:expr,) => ({ /* compiler built-in */ });
761 ($cond:expr, $($arg:tt)+) => ({ /* compiler built-in */ });