1 #[doc = include_str!("panic.md")]
3 #[rustc_builtin_macro(core_panic)]
4 #[allow_internal_unstable(edition_panic)]
5 #[stable(feature = "core", since = "1.6.0")]
6 #[rustc_diagnostic_item = "core_panic_macro"]
8 // Expands to either `$crate::panic::panic_2015` or `$crate::panic::panic_2021`
9 // depending on the edition of the caller.
11 /* compiler built-in */
15 /// Asserts that two expressions are equal to each other (using [`PartialEq`]).
17 /// On panic, this macro will print the values of the expressions with their
18 /// debug representations.
20 /// Like [`assert!`], this macro has a second form, where a custom
21 /// panic message can be provided.
30 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
33 #[stable(feature = "rust1", since = "1.0.0")]
34 #[allow_internal_unstable(core_panic)]
35 macro_rules! assert_eq {
36 ($left:expr, $right:expr $(,)?) => ({
37 match (&$left, &$right) {
38 (left_val, right_val) => {
39 if !(*left_val == *right_val) {
40 let kind = $crate::panicking::AssertKind::Eq;
41 // The reborrows below are intentional. Without them, the stack slot for the
42 // borrow is initialized even before the values are compared, leading to a
43 // noticeable slow down.
44 $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None);
49 ($left:expr, $right:expr, $($arg:tt)+) => ({
50 match (&$left, &$right) {
51 (left_val, right_val) => {
52 if !(*left_val == *right_val) {
53 let kind = $crate::panicking::AssertKind::Eq;
54 // The reborrows below are intentional. Without them, the stack slot for the
55 // borrow is initialized even before the values are compared, leading to a
56 // noticeable slow down.
57 $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::Some($crate::format_args!($($arg)+)));
64 /// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
66 /// On panic, this macro will print the values of the expressions with their
67 /// debug representations.
69 /// Like [`assert!`], this macro has a second form, where a custom
70 /// panic message can be provided.
79 /// assert_ne!(a, b, "we are testing that the values are not equal");
82 #[stable(feature = "assert_ne", since = "1.13.0")]
83 #[allow_internal_unstable(core_panic)]
84 macro_rules! assert_ne {
85 ($left:expr, $right:expr $(,)?) => ({
86 match (&$left, &$right) {
87 (left_val, right_val) => {
88 if *left_val == *right_val {
89 let kind = $crate::panicking::AssertKind::Ne;
90 // The reborrows below are intentional. Without them, the stack slot for the
91 // borrow is initialized even before the values are compared, leading to a
92 // noticeable slow down.
93 $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None);
98 ($left:expr, $right:expr, $($arg:tt)+) => ({
99 match (&($left), &($right)) {
100 (left_val, right_val) => {
101 if *left_val == *right_val {
102 let kind = $crate::panicking::AssertKind::Ne;
103 // The reborrows below are intentional. Without them, the stack slot for the
104 // borrow is initialized even before the values are compared, leading to a
105 // noticeable slow down.
106 $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::Some($crate::format_args!($($arg)+)));
113 /// Asserts that an expression matches any of the given patterns.
115 /// Like in a `match` expression, the pattern can be optionally followed by `if`
116 /// and a guard expression that has access to names bound by the pattern.
118 /// On panic, this macro will print the value of the expression with its
119 /// debug representation.
121 /// Like [`assert!`], this macro has a second form, where a custom
122 /// panic message can be provided.
127 /// #![feature(assert_matches)]
129 /// use std::assert_matches::assert_matches;
131 /// let a = 1u32.checked_add(2);
132 /// let b = 1u32.checked_sub(2);
133 /// assert_matches!(a, Some(_));
134 /// assert_matches!(b, None);
136 /// let c = Ok("abc".to_string());
137 /// assert_matches!(c, Ok(x) | Err(x) if x.len() < 100);
139 #[unstable(feature = "assert_matches", issue = "82775")]
140 #[allow_internal_unstable(core_panic)]
141 #[rustc_macro_transparency = "semitransparent"]
142 pub macro assert_matches {
143 ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => ({
145 $( $pattern )|+ $( if $guard )? => {}
147 $crate::panicking::assert_matches_failed(
149 $crate::stringify!($($pattern)|+ $(if $guard)?),
150 $crate::option::Option::None
155 ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )?, $($arg:tt)+) => ({
157 $( $pattern )|+ $( if $guard )? => {}
159 $crate::panicking::assert_matches_failed(
161 $crate::stringify!($($pattern)|+ $(if $guard)?),
162 $crate::option::Option::Some($crate::format_args!($($arg)+))
169 /// Asserts that a boolean expression is `true` at runtime.
171 /// This will invoke the [`panic!`] macro if the provided expression cannot be
172 /// evaluated to `true` at runtime.
174 /// Like [`assert!`], this macro also has a second version, where a custom panic
175 /// message can be provided.
179 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
180 /// optimized builds by default. An optimized build will not execute
181 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
182 /// compiler. This makes `debug_assert!` useful for checks that are too
183 /// expensive to be present in a release build but may be helpful during
184 /// development. The result of expanding `debug_assert!` is always type checked.
186 /// An unchecked assertion allows a program in an inconsistent state to keep
187 /// running, which might have unexpected consequences but does not introduce
188 /// unsafety as long as this only happens in safe code. The performance cost
189 /// of assertions, however, is not measurable in general. Replacing [`assert!`]
190 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
191 /// more importantly, only in safe code!
196 /// // the panic message for these assertions is the stringified value of the
197 /// // expression given.
198 /// debug_assert!(true);
200 /// fn some_expensive_computation() -> bool { true } // a very simple function
201 /// debug_assert!(some_expensive_computation());
203 /// // assert with a custom message
205 /// debug_assert!(x, "x wasn't true!");
207 /// let a = 3; let b = 27;
208 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
211 #[stable(feature = "rust1", since = "1.0.0")]
212 #[rustc_diagnostic_item = "debug_assert_macro"]
213 #[allow_internal_unstable(edition_panic)]
214 macro_rules! debug_assert {
215 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert!($($arg)*); })
218 /// Asserts that two expressions are equal to each other.
220 /// On panic, this macro will print the values of the expressions with their
221 /// debug representations.
223 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
224 /// optimized builds by default. An optimized build will not execute
225 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
226 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
227 /// expensive to be present in a release build but may be helpful during
228 /// development. The result of expanding `debug_assert_eq!` is always type checked.
235 /// debug_assert_eq!(a, b);
238 #[stable(feature = "rust1", since = "1.0.0")]
239 macro_rules! debug_assert_eq {
240 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_eq!($($arg)*); })
243 /// Asserts that two expressions are not equal to each other.
245 /// On panic, this macro will print the values of the expressions with their
246 /// debug representations.
248 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
249 /// optimized builds by default. An optimized build will not execute
250 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
251 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
252 /// expensive to be present in a release build but may be helpful during
253 /// development. The result of expanding `debug_assert_ne!` is always type checked.
260 /// debug_assert_ne!(a, b);
263 #[stable(feature = "assert_ne", since = "1.13.0")]
264 macro_rules! debug_assert_ne {
265 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_ne!($($arg)*); })
268 /// Asserts that an expression matches any of the given patterns.
270 /// Like in a `match` expression, the pattern can be optionally followed by `if`
271 /// and a guard expression that has access to names bound by the pattern.
273 /// On panic, this macro will print the value of the expression with its
274 /// debug representation.
276 /// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only
277 /// enabled in non optimized builds by default. An optimized build will not
278 /// execute `debug_assert_matches!` statements unless `-C debug-assertions` is
279 /// passed to the compiler. This makes `debug_assert_matches!` useful for
280 /// checks that are too expensive to be present in a release build but may be
281 /// helpful during development. The result of expanding `debug_assert_matches!`
282 /// is always type checked.
287 /// #![feature(assert_matches)]
289 /// use std::assert_matches::debug_assert_matches;
291 /// let a = 1u32.checked_add(2);
292 /// let b = 1u32.checked_sub(2);
293 /// debug_assert_matches!(a, Some(_));
294 /// debug_assert_matches!(b, None);
296 /// let c = Ok("abc".to_string());
297 /// debug_assert_matches!(c, Ok(x) | Err(x) if x.len() < 100);
300 #[unstable(feature = "assert_matches", issue = "82775")]
301 #[allow_internal_unstable(assert_matches)]
302 #[rustc_macro_transparency = "semitransparent"]
303 pub macro debug_assert_matches($($arg:tt)*) {
304 if $crate::cfg!(debug_assertions) { $crate::assert_matches::assert_matches!($($arg)*); }
307 /// Returns whether the given expression matches any of the given patterns.
309 /// Like in a `match` expression, the pattern can be optionally followed by `if`
310 /// and a guard expression that has access to names bound by the pattern.
316 /// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
318 /// let bar = Some(4);
319 /// assert!(matches!(bar, Some(x) if x > 2));
322 #[stable(feature = "matches_macro", since = "1.42.0")]
323 macro_rules! matches {
324 ($expression:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => {
326 $( $pattern )|+ $( if $guard )? => true,
332 /// Unwraps a result or propagates its error.
334 /// The `?` operator was added to replace `try!` and should be used instead.
335 /// Furthermore, `try` is a reserved word in Rust 2018, so if you must use
336 /// it, you will need to use the [raw-identifier syntax][ris]: `r#try`.
338 /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
340 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
341 /// expression has the value of the wrapped value.
343 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
344 /// performs conversion using `From`. This provides automatic conversion
345 /// between specialized errors and more general ones. The resulting
346 /// error is then immediately returned.
348 /// Because of the early return, `try!` can only be used in functions that
349 /// return [`Result`].
355 /// use std::fs::File;
356 /// use std::io::prelude::*;
362 /// impl From<io::Error> for MyError {
363 /// fn from(e: io::Error) -> MyError {
364 /// MyError::FileWriteError
368 /// // The preferred method of quick returning Errors
369 /// fn write_to_file_question() -> Result<(), MyError> {
370 /// let mut file = File::create("my_best_friends.txt")?;
371 /// file.write_all(b"This is a list of my best friends.")?;
375 /// // The previous method of quick returning Errors
376 /// fn write_to_file_using_try() -> Result<(), MyError> {
377 /// let mut file = r#try!(File::create("my_best_friends.txt"));
378 /// r#try!(file.write_all(b"This is a list of my best friends."));
382 /// // This is equivalent to:
383 /// fn write_to_file_using_match() -> Result<(), MyError> {
384 /// let mut file = r#try!(File::create("my_best_friends.txt"));
385 /// match file.write_all(b"This is a list of my best friends.") {
387 /// Err(e) => return Err(From::from(e)),
393 #[stable(feature = "rust1", since = "1.0.0")]
394 #[rustc_deprecated(since = "1.39.0", reason = "use the `?` operator instead")]
397 ($expr:expr $(,)?) => {
399 $crate::result::Result::Ok(val) => val,
400 $crate::result::Result::Err(err) => {
401 return $crate::result::Result::Err($crate::convert::From::from(err));
407 /// Writes formatted data into a buffer.
409 /// This macro accepts a 'writer', a format string, and a list of arguments. Arguments will be
410 /// formatted according to the specified format string and the result will be passed to the writer.
411 /// The writer may be any value with a `write_fmt` method; generally this comes from an
412 /// implementation of either the [`fmt::Write`] or the [`io::Write`] trait. The macro
413 /// returns whatever the `write_fmt` method returns; commonly a [`fmt::Result`], or an
416 /// See [`std::fmt`] for more information on the format string syntax.
418 /// [`std::fmt`]: ../std/fmt/index.html
419 /// [`fmt::Write`]: crate::fmt::Write
420 /// [`io::Write`]: ../std/io/trait.Write.html
421 /// [`fmt::Result`]: crate::fmt::Result
422 /// [`io::Result`]: ../std/io/type.Result.html
427 /// use std::io::Write;
429 /// fn main() -> std::io::Result<()> {
430 /// let mut w = Vec::new();
431 /// write!(&mut w, "test")?;
432 /// write!(&mut w, "formatted {}", "arguments")?;
434 /// assert_eq!(w, b"testformatted arguments");
439 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
440 /// implementing either, as objects do not typically implement both. However, the module must
441 /// import the traits qualified so their names do not conflict:
444 /// use std::fmt::Write as FmtWrite;
445 /// use std::io::Write as IoWrite;
447 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
448 /// let mut s = String::new();
449 /// let mut v = Vec::new();
451 /// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
452 /// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
453 /// assert_eq!(v, b"s = \"abc 123\"");
458 /// Note: This macro can be used in `no_std` setups as well.
459 /// In a `no_std` setup you are responsible for the implementation details of the components.
462 /// # extern crate core;
463 /// use core::fmt::Write;
467 /// impl Write for Example {
468 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
469 /// unimplemented!();
473 /// let mut m = Example{};
474 /// write!(&mut m, "Hello World").expect("Not written");
477 #[stable(feature = "rust1", since = "1.0.0")]
479 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt($crate::format_args!($($arg)*)))
482 /// Write formatted data into a buffer, with a newline appended.
484 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
485 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
487 /// For more information, see [`write!`]. For information on the format string syntax, see
490 /// [`std::fmt`]: ../std/fmt/index.html
495 /// use std::io::{Write, Result};
497 /// fn main() -> Result<()> {
498 /// let mut w = Vec::new();
499 /// writeln!(&mut w)?;
500 /// writeln!(&mut w, "test")?;
501 /// writeln!(&mut w, "formatted {}", "arguments")?;
503 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
508 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
509 /// implementing either, as objects do not typically implement both. However, the module must
510 /// import the traits qualified so their names do not conflict:
513 /// use std::fmt::Write as FmtWrite;
514 /// use std::io::Write as IoWrite;
516 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
517 /// let mut s = String::new();
518 /// let mut v = Vec::new();
520 /// writeln!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
521 /// writeln!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
522 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
527 #[stable(feature = "rust1", since = "1.0.0")]
528 #[allow_internal_unstable(format_args_nl)]
529 macro_rules! writeln {
530 ($dst:expr $(,)?) => (
531 $crate::write!($dst, "\n")
533 ($dst:expr, $($arg:tt)*) => (
534 $dst.write_fmt($crate::format_args_nl!($($arg)*))
538 /// Indicates unreachable code.
540 /// This is useful any time that the compiler can't determine that some code is unreachable. For
543 /// * Match arms with guard conditions.
544 /// * Loops that dynamically terminate.
545 /// * Iterators that dynamically terminate.
547 /// If the determination that the code is unreachable proves incorrect, the
548 /// program immediately terminates with a [`panic!`].
550 /// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
551 /// will cause undefined behavior if the code is reached.
553 /// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked
557 /// This will always [`panic!`] because `unreachable!` is just a shorthand for `panic!` with a
558 /// fixed, specific message.
560 /// Like `panic!`, this macro has a second form for displaying custom values.
567 /// # #[allow(dead_code)]
568 /// fn foo(x: Option<i32>) {
570 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
571 /// Some(n) if n < 0 => println!("Some(Negative)"),
572 /// Some(_) => unreachable!(), // compile error if commented out
573 /// None => println!("None")
581 /// # #[allow(dead_code)]
582 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
584 /// if 3*i < i { panic!("u32 overflow"); }
585 /// if x < 3*i { return i-1; }
587 /// unreachable!("The loop should always return");
591 #[stable(feature = "rust1", since = "1.0.0")]
592 macro_rules! unreachable {
594 $crate::panic!("internal error: entered unreachable code")
596 ($msg:expr $(,)?) => ({
597 $crate::unreachable!("{}", $msg)
599 ($fmt:expr, $($arg:tt)*) => ({
600 $crate::panic!($crate::concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
604 /// Indicates unimplemented code by panicking with a message of "not implemented".
606 /// This allows your code to type-check, which is useful if you are prototyping or
607 /// implementing a trait that requires multiple methods which you don't plan to use all of.
609 /// The difference between `unimplemented!` and [`todo!`] is that while `todo!`
610 /// conveys an intent of implementing the functionality later and the message is "not yet
611 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
612 /// Also some IDEs will mark `todo!`s.
616 /// This will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a
617 /// fixed, specific message.
619 /// Like `panic!`, this macro has a second form for displaying custom values.
623 /// Say we have a trait `Foo`:
627 /// fn bar(&self) -> u8;
629 /// fn qux(&self) -> Result<u64, ()>;
633 /// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
634 /// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
635 /// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
636 /// to allow our code to compile.
638 /// We still want to have our program stop running if the unimplemented methods are
643 /// # fn bar(&self) -> u8;
645 /// # fn qux(&self) -> Result<u64, ()>;
649 /// impl Foo for MyStruct {
650 /// fn bar(&self) -> u8 {
655 /// // It makes no sense to `baz` a `MyStruct`, so we have no logic here
657 /// // This will display "thread 'main' panicked at 'not implemented'".
658 /// unimplemented!();
661 /// fn qux(&self) -> Result<u64, ()> {
662 /// // We have some logic here,
663 /// // We can add a message to unimplemented! to display our omission.
664 /// // This will display:
665 /// // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
666 /// unimplemented!("MyStruct isn't quxable");
671 /// let s = MyStruct;
676 #[stable(feature = "rust1", since = "1.0.0")]
677 macro_rules! unimplemented {
678 () => ($crate::panic!("not implemented"));
679 ($($arg:tt)+) => ($crate::panic!("not implemented: {}", $crate::format_args!($($arg)+)));
682 /// Indicates unfinished code.
684 /// This can be useful if you are prototyping and are just looking to have your
687 /// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
688 /// an intent of implementing the functionality later and the message is "not yet
689 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
690 /// Also some IDEs will mark `todo!`s.
694 /// This will always [`panic!`].
698 /// Here's an example of some in-progress code. We have a trait `Foo`:
707 /// We want to implement `Foo` on one of our types, but we also want to work on
708 /// just `bar()` first. In order for our code to compile, we need to implement
709 /// `baz()`, so we can use `todo!`:
718 /// impl Foo for MyStruct {
720 /// // implementation goes here
724 /// // let's not worry about implementing baz() for now
730 /// let s = MyStruct;
733 /// // we aren't even using baz(), so this is fine.
737 #[stable(feature = "todo_macro", since = "1.40.0")]
739 () => ($crate::panic!("not yet implemented"));
740 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
743 /// Definitions of built-in macros.
745 /// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
746 /// with exception of expansion functions transforming macro inputs into outputs,
747 /// those functions are provided by the compiler.
748 pub(crate) mod builtin {
750 /// Causes compilation to fail with the given error message when encountered.
752 /// This macro should be used when a crate uses a conditional compilation strategy to provide
753 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
754 /// but emits an error during *compilation* rather than at *runtime*.
758 /// Two such examples are macros and `#[cfg]` environments.
760 /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
761 /// the compiler would still emit an error, but the error's message would not mention the two
765 /// macro_rules! give_me_foo_or_bar {
769 /// compile_error!("This macro only accepts `foo` or `bar`");
773 /// give_me_foo_or_bar!(neither);
774 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
777 /// Emit compiler error if one of a number of features isn't available.
780 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
781 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
783 #[stable(feature = "compile_error_macro", since = "1.20.0")]
784 #[rustc_builtin_macro]
786 macro_rules! compile_error {
787 ($msg:expr $(,)?) => {{ /* compiler built-in */ }};
790 /// Constructs parameters for the other string-formatting macros.
792 /// This macro functions by taking a formatting string literal containing
793 /// `{}` for each additional argument passed. `format_args!` prepares the
794 /// additional parameters to ensure the output can be interpreted as a string
795 /// and canonicalizes the arguments into a single type. Any value that implements
796 /// the [`Display`] trait can be passed to `format_args!`, as can any
797 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
799 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
800 /// passed to the macros within [`std::fmt`] for performing useful redirection.
801 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
802 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
803 /// heap allocations.
805 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
806 /// in `Debug` and `Display` contexts as seen below. The example also shows
807 /// that `Debug` and `Display` format to the same thing: the interpolated
808 /// format string in `format_args!`.
811 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
812 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
813 /// assert_eq!("1 foo 2", display);
814 /// assert_eq!(display, debug);
817 /// For more information, see the documentation in [`std::fmt`].
819 /// [`Display`]: crate::fmt::Display
820 /// [`Debug`]: crate::fmt::Debug
821 /// [`fmt::Arguments`]: crate::fmt::Arguments
822 /// [`std::fmt`]: ../std/fmt/index.html
823 /// [`format!`]: ../std/macro.format.html
824 /// [`println!`]: ../std/macro.println.html
831 /// let s = fmt::format(format_args!("hello {}", "world"));
832 /// assert_eq!(s, format!("hello {}", "world"));
834 #[stable(feature = "rust1", since = "1.0.0")]
835 #[allow_internal_unsafe]
836 #[allow_internal_unstable(fmt_internals)]
837 #[rustc_builtin_macro]
839 macro_rules! format_args {
840 ($fmt:expr) => {{ /* compiler built-in */ }};
841 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
844 /// Same as `format_args`, but can be used in some const contexts.
846 /// This macro is used by the panic macros for the `const_panic` feature.
848 /// This macro will be removed once `format_args` is allowed in const contexts.
849 #[unstable(feature = "const_format_args", issue = "none")]
850 #[allow_internal_unstable(fmt_internals, const_fmt_arguments_new)]
851 #[rustc_builtin_macro]
853 macro_rules! const_format_args {
854 ($fmt:expr) => {{ /* compiler built-in */ }};
855 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
858 /// Same as `format_args`, but adds a newline in the end.
860 feature = "format_args_nl",
862 reason = "`format_args_nl` is only for internal \
863 language use and is subject to change"
865 #[allow_internal_unstable(fmt_internals)]
867 #[rustc_builtin_macro]
869 macro_rules! format_args_nl {
870 ($fmt:expr) => {{ /* compiler built-in */ }};
871 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
874 /// Inspects an environment variable at compile time.
876 /// This macro will expand to the value of the named environment variable at
877 /// compile time, yielding an expression of type `&'static str`.
879 /// If the environment variable is not defined, then a compilation error
880 /// will be emitted. To not emit a compile error, use the [`option_env!`]
886 /// let path: &'static str = env!("PATH");
887 /// println!("the $PATH variable at the time of compiling was: {}", path);
890 /// You can customize the error message by passing a string as the second
894 /// let doc: &'static str = env!("documentation", "what's that?!");
897 /// If the `documentation` environment variable is not defined, you'll get
898 /// the following error:
901 /// error: what's that?!
903 #[stable(feature = "rust1", since = "1.0.0")]
904 #[rustc_builtin_macro]
907 ($name:expr $(,)?) => {{ /* compiler built-in */ }};
908 ($name:expr, $error_msg:expr $(,)?) => {{ /* compiler built-in */ }};
911 /// Optionally inspects an environment variable at compile time.
913 /// If the named environment variable is present at compile time, this will
914 /// expand into an expression of type `Option<&'static str>` whose value is
915 /// `Some` of the value of the environment variable. If the environment
916 /// variable is not present, then this will expand to `None`. See
917 /// [`Option<T>`][Option] for more information on this type.
919 /// A compile time error is never emitted when using this macro regardless
920 /// of whether the environment variable is present or not.
925 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
926 /// println!("the secret key might be: {:?}", key);
928 #[stable(feature = "rust1", since = "1.0.0")]
929 #[rustc_builtin_macro]
931 macro_rules! option_env {
932 ($name:expr $(,)?) => {{ /* compiler built-in */ }};
935 /// Concatenates identifiers into one identifier.
937 /// This macro takes any number of comma-separated identifiers, and
938 /// concatenates them all into one, yielding an expression which is a new
939 /// identifier. Note that hygiene makes it such that this macro cannot
940 /// capture local variables. Also, as a general rule, macros are only
941 /// allowed in item, statement or expression position. That means while
942 /// you may use this macro for referring to existing variables, functions or
943 /// modules etc, you cannot define a new one with it.
948 /// #![feature(concat_idents)]
951 /// fn foobar() -> u32 { 23 }
953 /// let f = concat_idents!(foo, bar);
954 /// println!("{}", f());
956 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
960 feature = "concat_idents",
962 reason = "`concat_idents` is not stable enough for use and is subject to change"
964 #[rustc_builtin_macro]
966 macro_rules! concat_idents {
967 ($($e:ident),+ $(,)?) => {{ /* compiler built-in */ }};
970 /// Concatenates literals into a static string slice.
972 /// This macro takes any number of comma-separated literals, yielding an
973 /// expression of type `&'static str` which represents all of the literals
974 /// concatenated left-to-right.
976 /// Integer and floating point literals are stringified in order to be
982 /// let s = concat!("test", 10, 'b', true);
983 /// assert_eq!(s, "test10btrue");
985 #[stable(feature = "rust1", since = "1.0.0")]
986 #[rustc_builtin_macro]
988 macro_rules! concat {
989 ($($e:expr),* $(,)?) => {{ /* compiler built-in */ }};
992 /// Expands to the line number on which it was invoked.
994 /// With [`column!`] and [`file!`], these macros provide debugging information for
995 /// developers about the location within the source.
997 /// The expanded expression has type `u32` and is 1-based, so the first line
998 /// in each file evaluates to 1, the second to 2, etc. This is consistent
999 /// with error messages by common compilers or popular editors.
1000 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
1001 /// but rather the first macro invocation leading up to the invocation
1002 /// of the `line!` macro.
1007 /// let current_line = line!();
1008 /// println!("defined on line: {}", current_line);
1010 #[stable(feature = "rust1", since = "1.0.0")]
1011 #[rustc_builtin_macro]
1015 /* compiler built-in */
1019 /// Expands to the column number at which it was invoked.
1021 /// With [`line!`] and [`file!`], these macros provide debugging information for
1022 /// developers about the location within the source.
1024 /// The expanded expression has type `u32` and is 1-based, so the first column
1025 /// in each line evaluates to 1, the second to 2, etc. This is consistent
1026 /// with error messages by common compilers or popular editors.
1027 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
1028 /// but rather the first macro invocation leading up to the invocation
1029 /// of the `column!` macro.
1034 /// let current_col = column!();
1035 /// println!("defined on column: {}", current_col);
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 #[rustc_builtin_macro]
1040 macro_rules! column {
1042 /* compiler built-in */
1046 /// Expands to the file name in which it was invoked.
1048 /// With [`line!`] and [`column!`], these macros provide debugging information for
1049 /// developers about the location within the source.
1051 /// The expanded expression has type `&'static str`, and the returned file
1052 /// is not the invocation of the `file!` macro itself, but rather the
1053 /// first macro invocation leading up to the invocation of the `file!`
1059 /// let this_file = file!();
1060 /// println!("defined in file: {}", this_file);
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 #[rustc_builtin_macro]
1067 /* compiler built-in */
1071 /// Stringifies its arguments.
1073 /// This macro will yield an expression of type `&'static str` which is the
1074 /// stringification of all the tokens passed to the macro. No restrictions
1075 /// are placed on the syntax of the macro invocation itself.
1077 /// Note that the expanded results of the input tokens may change in the
1078 /// future. You should be careful if you rely on the output.
1083 /// let one_plus_one = stringify!(1 + 1);
1084 /// assert_eq!(one_plus_one, "1 + 1");
1086 #[stable(feature = "rust1", since = "1.0.0")]
1087 #[rustc_builtin_macro]
1089 macro_rules! stringify {
1091 /* compiler built-in */
1095 /// Includes a UTF-8 encoded file as a string.
1097 /// The file is located relative to the current file (similarly to how
1098 /// modules are found). The provided path is interpreted in a platform-specific
1099 /// way at compile time. So, for instance, an invocation with a Windows path
1100 /// containing backslashes `\` would not compile correctly on Unix.
1102 /// This macro will yield an expression of type `&'static str` which is the
1103 /// contents of the file.
1107 /// Assume there are two files in the same directory with the following
1110 /// File 'spanish.in':
1118 /// ```ignore (cannot-doctest-external-file-dependency)
1120 /// let my_str = include_str!("spanish.in");
1121 /// assert_eq!(my_str, "adiós\n");
1122 /// print!("{}", my_str);
1126 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 #[rustc_builtin_macro]
1130 macro_rules! include_str {
1131 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1134 /// Includes a file as a reference to a byte array.
1136 /// The file is located relative to the current file (similarly to how
1137 /// modules are found). The provided path is interpreted in a platform-specific
1138 /// way at compile time. So, for instance, an invocation with a Windows path
1139 /// containing backslashes `\` would not compile correctly on Unix.
1141 /// This macro will yield an expression of type `&'static [u8; N]` which is
1142 /// the contents of the file.
1146 /// Assume there are two files in the same directory with the following
1149 /// File 'spanish.in':
1157 /// ```ignore (cannot-doctest-external-file-dependency)
1159 /// let bytes = include_bytes!("spanish.in");
1160 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
1161 /// print!("{}", String::from_utf8_lossy(bytes));
1165 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 #[rustc_builtin_macro]
1169 macro_rules! include_bytes {
1170 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1173 /// Expands to a string that represents the current module path.
1175 /// The current module path can be thought of as the hierarchy of modules
1176 /// leading back up to the crate root. The first component of the path
1177 /// returned is the name of the crate currently being compiled.
1184 /// assert!(module_path!().ends_with("test"));
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 #[rustc_builtin_macro]
1193 macro_rules! module_path {
1195 /* compiler built-in */
1199 /// Evaluates boolean combinations of configuration flags at compile-time.
1201 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1202 /// boolean expression evaluation of configuration flags. This frequently
1203 /// leads to less duplicated code.
1205 /// The syntax given to this macro is the same syntax as the [`cfg`]
1208 /// `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For
1209 /// example, all blocks in an if/else expression need to be valid when `cfg!` is used for
1210 /// the condition, regardless of what `cfg!` is evaluating.
1212 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1217 /// let my_directory = if cfg!(windows) {
1218 /// "windows-specific-directory"
1220 /// "unix-directory"
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 #[rustc_builtin_macro]
1228 /* compiler built-in */
1232 /// Parses a file as an expression or an item according to the context.
1234 /// The file is located relative to the current file (similarly to how
1235 /// modules are found). The provided path is interpreted in a platform-specific
1236 /// way at compile time. So, for instance, an invocation with a Windows path
1237 /// containing backslashes `\` would not compile correctly on Unix.
1239 /// Using this macro is often a bad idea, because if the file is
1240 /// parsed as an expression, it is going to be placed in the
1241 /// surrounding code unhygienically. This could result in variables
1242 /// or functions being different from what the file expected if
1243 /// there are variables or functions that have the same name in
1244 /// the current file.
1248 /// Assume there are two files in the same directory with the following
1251 /// File 'monkeys.in':
1253 /// ```ignore (only-for-syntax-highlight)
1254 /// ['🙈', '🙊', '🙉']
1258 /// .collect::<String>()
1263 /// ```ignore (cannot-doctest-external-file-dependency)
1265 /// let my_string = include!("monkeys.in");
1266 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1267 /// println!("{}", my_string);
1271 /// Compiling 'main.rs' and running the resulting binary will print
1272 /// "🙈🙊🙉🙈🙊🙉".
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 #[rustc_builtin_macro]
1276 macro_rules! include {
1277 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1280 /// Asserts that a boolean expression is `true` at runtime.
1282 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1283 /// evaluated to `true` at runtime.
1287 /// Assertions are always checked in both debug and release builds, and cannot
1288 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1289 /// release builds by default.
1291 /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if
1292 /// violated could lead to unsafety.
1294 /// Other use-cases of `assert!` include testing and enforcing run-time
1295 /// invariants in safe code (whose violation cannot result in unsafety).
1297 /// # Custom Messages
1299 /// This macro has a second form, where a custom panic message can
1300 /// be provided with or without arguments for formatting. See [`std::fmt`]
1301 /// for syntax for this form. Expressions used as format arguments will only
1302 /// be evaluated if the assertion fails.
1304 /// [`std::fmt`]: ../std/fmt/index.html
1309 /// // the panic message for these assertions is the stringified value of the
1310 /// // expression given.
1313 /// fn some_computation() -> bool { true } // a very simple function
1315 /// assert!(some_computation());
1317 /// // assert with a custom message
1319 /// assert!(x, "x wasn't true!");
1321 /// let a = 3; let b = 27;
1322 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1324 #[stable(feature = "rust1", since = "1.0.0")]
1325 #[rustc_builtin_macro]
1327 #[rustc_diagnostic_item = "assert_macro"]
1328 #[allow_internal_unstable(core_panic, edition_panic)]
1329 macro_rules! assert {
1330 ($cond:expr $(,)?) => {{ /* compiler built-in */ }};
1331 ($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }};
1334 /// LLVM-style inline assembly.
1336 /// Read the [unstable book] for the usage.
1338 /// [unstable book]: ../unstable-book/library-features/llvm-asm.html
1340 feature = "llvm_asm",
1342 reason = "prefer using the new asm! syntax instead"
1346 reason = "will be removed from the compiler, use asm! instead"
1348 #[rustc_builtin_macro]
1350 macro_rules! llvm_asm {
1351 ("assembly template"
1352 : $("output"(operand),)*
1353 : $("input"(operand),)*
1355 : $("options",)*) => {
1356 /* compiler built-in */
1360 /// Prints passed tokens into the standard output.
1362 feature = "log_syntax",
1364 reason = "`log_syntax!` is not stable enough for use and is subject to change"
1366 #[rustc_builtin_macro]
1368 macro_rules! log_syntax {
1370 /* compiler built-in */
1374 /// Enables or disables tracing functionality used for debugging other macros.
1376 feature = "trace_macros",
1378 reason = "`trace_macros` is not stable enough for use and is subject to change"
1380 #[rustc_builtin_macro]
1382 macro_rules! trace_macros {
1383 (true) => {{ /* compiler built-in */ }};
1384 (false) => {{ /* compiler built-in */ }};
1387 /// Attribute macro used to apply derive macros.
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 #[rustc_builtin_macro]
1390 pub macro derive($item:item) {
1391 /* compiler built-in */
1394 /// Attribute macro applied to a function to turn it into a unit test.
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 #[allow_internal_unstable(test, rustc_attrs)]
1397 #[rustc_builtin_macro]
1398 pub macro test($item:item) {
1399 /* compiler built-in */
1402 /// Attribute macro applied to a function to turn it into a benchmark test.
1407 reason = "`bench` is a part of custom test frameworks which are unstable"
1409 #[allow_internal_unstable(test, rustc_attrs)]
1410 #[rustc_builtin_macro]
1411 pub macro bench($item:item) {
1412 /* compiler built-in */
1415 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1417 feature = "custom_test_frameworks",
1419 reason = "custom test frameworks are an unstable feature"
1421 #[allow_internal_unstable(test, rustc_attrs)]
1422 #[rustc_builtin_macro]
1423 pub macro test_case($item:item) {
1424 /* compiler built-in */
1427 /// Attribute macro applied to a static to register it as a global allocator.
1429 /// See also [`std::alloc::GlobalAlloc`](../std/alloc/trait.GlobalAlloc.html).
1430 #[stable(feature = "global_allocator", since = "1.28.0")]
1431 #[allow_internal_unstable(rustc_attrs)]
1432 #[rustc_builtin_macro]
1433 pub macro global_allocator($item:item) {
1434 /* compiler built-in */
1437 /// Keeps the item it's applied to if the passed path is accessible, and removes it otherwise.
1439 feature = "cfg_accessible",
1441 reason = "`cfg_accessible` is not fully implemented"
1443 #[rustc_builtin_macro]
1444 pub macro cfg_accessible($item:item) {
1445 /* compiler built-in */
1448 /// Expands all `#[cfg]` and `#[cfg_attr]` attributes in the code fragment it's applied to.
1450 feature = "cfg_eval",
1452 reason = "`cfg_eval` is a recently implemented feature"
1454 #[rustc_builtin_macro]
1455 pub macro cfg_eval($($tt:tt)*) {
1456 /* compiler built-in */
1459 /// Unstable implementation detail of the `rustc` compiler, do not use.
1460 #[rustc_builtin_macro]
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 #[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
1465 reason = "rustc-serialize is deprecated and no longer supported"
1467 pub macro RustcDecodable($item:item) {
1468 /* compiler built-in */
1471 /// Unstable implementation detail of the `rustc` compiler, do not use.
1472 #[rustc_builtin_macro]
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 #[allow_internal_unstable(core_intrinsics)]
1477 reason = "rustc-serialize is deprecated and no longer supported"
1479 pub macro RustcEncodable($item:item) {
1480 /* compiler built-in */