1 #[doc = include_str!("panic.md")]
3 #[cfg_attr(bootstrap, rustc_builtin_macro = "core_panic")]
4 #[cfg_attr(not(bootstrap), rustc_builtin_macro(core_panic))]
5 #[allow_internal_unstable(edition_panic)]
6 #[stable(feature = "core", since = "1.6.0")]
7 #[rustc_diagnostic_item = "core_panic_macro"]
9 // Expands to either `$crate::panic::panic_2015` or `$crate::panic::panic_2021`
10 // depending on the edition of the caller.
12 /* compiler built-in */
16 /// Asserts that two expressions are equal to each other (using [`PartialEq`]).
18 /// On panic, this macro will print the values of the expressions with their
19 /// debug representations.
21 /// Like [`assert!`], this macro has a second form, where a custom
22 /// panic message can be provided.
31 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
34 #[stable(feature = "rust1", since = "1.0.0")]
35 #[allow_internal_unstable(core_panic)]
36 macro_rules! assert_eq {
37 ($left:expr, $right:expr $(,)?) => ({
38 match (&$left, &$right) {
39 (left_val, right_val) => {
40 if !(*left_val == *right_val) {
41 let kind = $crate::panicking::AssertKind::Eq;
42 // The reborrows below are intentional. Without them, the stack slot for the
43 // borrow is initialized even before the values are compared, leading to a
44 // noticeable slow down.
45 $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None);
50 ($left:expr, $right:expr, $($arg:tt)+) => ({
51 match (&$left, &$right) {
52 (left_val, right_val) => {
53 if !(*left_val == *right_val) {
54 let kind = $crate::panicking::AssertKind::Eq;
55 // The reborrows below are intentional. Without them, the stack slot for the
56 // borrow is initialized even before the values are compared, leading to a
57 // noticeable slow down.
58 $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::Some($crate::format_args!($($arg)+)));
65 /// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
67 /// On panic, this macro will print the values of the expressions with their
68 /// debug representations.
70 /// Like [`assert!`], this macro has a second form, where a custom
71 /// panic message can be provided.
80 /// assert_ne!(a, b, "we are testing that the values are not equal");
83 #[stable(feature = "assert_ne", since = "1.13.0")]
84 #[allow_internal_unstable(core_panic)]
85 macro_rules! assert_ne {
86 ($left:expr, $right:expr $(,)?) => ({
87 match (&$left, &$right) {
88 (left_val, right_val) => {
89 if *left_val == *right_val {
90 let kind = $crate::panicking::AssertKind::Ne;
91 // The reborrows below are intentional. Without them, the stack slot for the
92 // borrow is initialized even before the values are compared, leading to a
93 // noticeable slow down.
94 $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None);
99 ($left:expr, $right:expr, $($arg:tt)+) => ({
100 match (&($left), &($right)) {
101 (left_val, right_val) => {
102 if *left_val == *right_val {
103 let kind = $crate::panicking::AssertKind::Ne;
104 // The reborrows below are intentional. Without them, the stack slot for the
105 // borrow is initialized even before the values are compared, leading to a
106 // noticeable slow down.
107 $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::Some($crate::format_args!($($arg)+)));
114 /// Asserts that an expression matches any of the given patterns.
116 /// Like in a `match` expression, the pattern can be optionally followed by `if`
117 /// and a guard expression that has access to names bound by the pattern.
119 /// On panic, this macro will print the value of the expression with its
120 /// debug representation.
122 /// Like [`assert!`], this macro has a second form, where a custom
123 /// panic message can be provided.
128 /// #![feature(assert_matches)]
130 /// let a = 1u32.checked_add(2);
131 /// let b = 1u32.checked_sub(2);
132 /// assert_matches!(a, Some(_));
133 /// assert_matches!(b, None);
135 /// let c = Ok("abc".to_string());
136 /// 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 macro_rules! assert_matches {
142 ($left:expr, $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => ({
144 $( $pattern )|+ $( if $guard )? => {}
146 $crate::panicking::assert_matches_failed(
148 $crate::stringify!($($pattern)|+ $(if $guard)?),
149 $crate::option::Option::None
154 ($left:expr, $( $pattern:pat_param )|+ $( if $guard: expr )?, $($arg:tt)+) => ({
156 $( $pattern )|+ $( if $guard )? => {}
158 $crate::panicking::assert_matches_failed(
160 $crate::stringify!($($pattern)|+ $(if $guard)?),
161 $crate::option::Option::Some($crate::format_args!($($arg)+))
168 /// Asserts that a boolean expression is `true` at runtime.
170 /// This will invoke the [`panic!`] macro if the provided expression cannot be
171 /// evaluated to `true` at runtime.
173 /// Like [`assert!`], this macro also has a second version, where a custom panic
174 /// message can be provided.
178 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
179 /// optimized builds by default. An optimized build will not execute
180 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
181 /// compiler. This makes `debug_assert!` useful for checks that are too
182 /// expensive to be present in a release build but may be helpful during
183 /// development. The result of expanding `debug_assert!` is always type checked.
185 /// An unchecked assertion allows a program in an inconsistent state to keep
186 /// running, which might have unexpected consequences but does not introduce
187 /// unsafety as long as this only happens in safe code. The performance cost
188 /// of assertions, however, is not measurable in general. Replacing [`assert!`]
189 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
190 /// more importantly, only in safe code!
195 /// // the panic message for these assertions is the stringified value of the
196 /// // expression given.
197 /// debug_assert!(true);
199 /// fn some_expensive_computation() -> bool { true } // a very simple function
200 /// debug_assert!(some_expensive_computation());
202 /// // assert with a custom message
204 /// debug_assert!(x, "x wasn't true!");
206 /// let a = 3; let b = 27;
207 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
210 #[stable(feature = "rust1", since = "1.0.0")]
211 #[rustc_diagnostic_item = "debug_assert_macro"]
212 macro_rules! debug_assert {
213 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert!($($arg)*); })
216 /// Asserts that two expressions are equal to each other.
218 /// On panic, this macro will print the values of the expressions with their
219 /// debug representations.
221 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
222 /// optimized builds by default. An optimized build will not execute
223 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
224 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
225 /// expensive to be present in a release build but may be helpful during
226 /// development. The result of expanding `debug_assert_eq!` is always type checked.
233 /// debug_assert_eq!(a, b);
236 #[stable(feature = "rust1", since = "1.0.0")]
237 macro_rules! debug_assert_eq {
238 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_eq!($($arg)*); })
241 /// Asserts that two expressions are not equal to each other.
243 /// On panic, this macro will print the values of the expressions with their
244 /// debug representations.
246 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
247 /// optimized builds by default. An optimized build will not execute
248 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
249 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
250 /// expensive to be present in a release build but may be helpful during
251 /// development. The result of expanding `debug_assert_ne!` is always type checked.
258 /// debug_assert_ne!(a, b);
261 #[stable(feature = "assert_ne", since = "1.13.0")]
262 macro_rules! debug_assert_ne {
263 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_ne!($($arg)*); })
266 /// Asserts that an expression matches any of the given patterns.
268 /// Like in a `match` expression, the pattern can be optionally followed by `if`
269 /// and a guard expression that has access to names bound by the pattern.
271 /// On panic, this macro will print the value of the expression with its
272 /// debug representation.
274 /// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only
275 /// enabled in non optimized builds by default. An optimized build will not
276 /// execute `debug_assert_matches!` statements unless `-C debug-assertions` is
277 /// passed to the compiler. This makes `debug_assert_matches!` useful for
278 /// checks that are too expensive to be present in a release build but may be
279 /// helpful during development. The result of expanding `debug_assert_matches!`
280 /// is always type checked.
285 /// #![feature(assert_matches)]
287 /// let a = 1u32.checked_add(2);
288 /// let b = 1u32.checked_sub(2);
289 /// debug_assert_matches!(a, Some(_));
290 /// debug_assert_matches!(b, None);
292 /// let c = Ok("abc".to_string());
293 /// debug_assert_matches!(c, Ok(x) | Err(x) if x.len() < 100);
296 #[unstable(feature = "assert_matches", issue = "82775")]
297 #[allow_internal_unstable(assert_matches)]
298 macro_rules! debug_assert_matches {
299 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_matches!($($arg)*); })
302 /// Returns whether the given expression matches any of the given patterns.
304 /// Like in a `match` expression, the pattern can be optionally followed by `if`
305 /// and a guard expression that has access to names bound by the pattern.
311 /// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
313 /// let bar = Some(4);
314 /// assert!(matches!(bar, Some(x) if x > 2));
317 #[stable(feature = "matches_macro", since = "1.42.0")]
318 macro_rules! matches {
319 ($expression:expr, $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => {
321 $( $pattern )|+ $( if $guard )? => true,
327 /// Unwraps a result or propagates its error.
329 /// The `?` operator was added to replace `try!` and should be used instead.
330 /// Furthermore, `try` is a reserved word in Rust 2018, so if you must use
331 /// it, you will need to use the [raw-identifier syntax][ris]: `r#try`.
333 /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
335 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
336 /// expression has the value of the wrapped value.
338 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
339 /// performs conversion using `From`. This provides automatic conversion
340 /// between specialized errors and more general ones. The resulting
341 /// error is then immediately returned.
343 /// Because of the early return, `try!` can only be used in functions that
344 /// return [`Result`].
350 /// use std::fs::File;
351 /// use std::io::prelude::*;
357 /// impl From<io::Error> for MyError {
358 /// fn from(e: io::Error) -> MyError {
359 /// MyError::FileWriteError
363 /// // The preferred method of quick returning Errors
364 /// fn write_to_file_question() -> Result<(), MyError> {
365 /// let mut file = File::create("my_best_friends.txt")?;
366 /// file.write_all(b"This is a list of my best friends.")?;
370 /// // The previous method of quick returning Errors
371 /// fn write_to_file_using_try() -> Result<(), MyError> {
372 /// let mut file = r#try!(File::create("my_best_friends.txt"));
373 /// r#try!(file.write_all(b"This is a list of my best friends."));
377 /// // This is equivalent to:
378 /// fn write_to_file_using_match() -> Result<(), MyError> {
379 /// let mut file = r#try!(File::create("my_best_friends.txt"));
380 /// match file.write_all(b"This is a list of my best friends.") {
382 /// Err(e) => return Err(From::from(e)),
388 #[stable(feature = "rust1", since = "1.0.0")]
389 #[rustc_deprecated(since = "1.39.0", reason = "use the `?` operator instead")]
392 ($expr:expr $(,)?) => {
394 $crate::result::Result::Ok(val) => val,
395 $crate::result::Result::Err(err) => {
396 return $crate::result::Result::Err($crate::convert::From::from(err));
402 /// Writes formatted data into a buffer.
404 /// This macro accepts a 'writer', a format string, and a list of arguments. Arguments will be
405 /// formatted according to the specified format string and the result will be passed to the writer.
406 /// The writer may be any value with a `write_fmt` method; generally this comes from an
407 /// implementation of either the [`fmt::Write`] or the [`io::Write`] trait. The macro
408 /// returns whatever the `write_fmt` method returns; commonly a [`fmt::Result`], or an
411 /// See [`std::fmt`] for more information on the format string syntax.
413 /// [`std::fmt`]: ../std/fmt/index.html
414 /// [`fmt::Write`]: crate::fmt::Write
415 /// [`io::Write`]: ../std/io/trait.Write.html
416 /// [`fmt::Result`]: crate::fmt::Result
417 /// [`io::Result`]: ../std/io/type.Result.html
422 /// use std::io::Write;
424 /// fn main() -> std::io::Result<()> {
425 /// let mut w = Vec::new();
426 /// write!(&mut w, "test")?;
427 /// write!(&mut w, "formatted {}", "arguments")?;
429 /// assert_eq!(w, b"testformatted arguments");
434 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
435 /// implementing either, as objects do not typically implement both. However, the module must
436 /// import the traits qualified so their names do not conflict:
439 /// use std::fmt::Write as FmtWrite;
440 /// use std::io::Write as IoWrite;
442 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
443 /// let mut s = String::new();
444 /// let mut v = Vec::new();
446 /// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
447 /// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
448 /// assert_eq!(v, b"s = \"abc 123\"");
453 /// Note: This macro can be used in `no_std` setups as well.
454 /// In a `no_std` setup you are responsible for the implementation details of the components.
457 /// # extern crate core;
458 /// use core::fmt::Write;
462 /// impl Write for Example {
463 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
464 /// unimplemented!();
468 /// let mut m = Example{};
469 /// write!(&mut m, "Hello World").expect("Not written");
472 #[stable(feature = "rust1", since = "1.0.0")]
474 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt($crate::format_args!($($arg)*)))
477 /// Write formatted data into a buffer, with a newline appended.
479 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
480 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
482 /// For more information, see [`write!`]. For information on the format string syntax, see
485 /// [`std::fmt`]: ../std/fmt/index.html
490 /// use std::io::{Write, Result};
492 /// fn main() -> Result<()> {
493 /// let mut w = Vec::new();
494 /// writeln!(&mut w)?;
495 /// writeln!(&mut w, "test")?;
496 /// writeln!(&mut w, "formatted {}", "arguments")?;
498 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
503 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
504 /// implementing either, as objects do not typically implement both. However, the module must
505 /// import the traits qualified so their names do not conflict:
508 /// use std::fmt::Write as FmtWrite;
509 /// use std::io::Write as IoWrite;
511 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
512 /// let mut s = String::new();
513 /// let mut v = Vec::new();
515 /// writeln!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
516 /// writeln!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
517 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
522 #[stable(feature = "rust1", since = "1.0.0")]
523 #[allow_internal_unstable(format_args_nl)]
524 macro_rules! writeln {
525 ($dst:expr $(,)?) => (
526 $crate::write!($dst, "\n")
528 ($dst:expr, $($arg:tt)*) => (
529 $dst.write_fmt($crate::format_args_nl!($($arg)*))
533 /// Indicates unreachable code.
535 /// This is useful any time that the compiler can't determine that some code is unreachable. For
538 /// * Match arms with guard conditions.
539 /// * Loops that dynamically terminate.
540 /// * Iterators that dynamically terminate.
542 /// If the determination that the code is unreachable proves incorrect, the
543 /// program immediately terminates with a [`panic!`].
545 /// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
546 /// will cause undefined behavior if the code is reached.
548 /// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked
552 /// This will always [`panic!`].
559 /// # #[allow(dead_code)]
560 /// fn foo(x: Option<i32>) {
562 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
563 /// Some(n) if n < 0 => println!("Some(Negative)"),
564 /// Some(_) => unreachable!(), // compile error if commented out
565 /// None => println!("None")
573 /// # #[allow(dead_code)]
574 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
576 /// if 3*i < i { panic!("u32 overflow"); }
577 /// if x < 3*i { return i-1; }
583 #[stable(feature = "rust1", since = "1.0.0")]
584 macro_rules! unreachable {
586 $crate::panic!("internal error: entered unreachable code")
588 ($msg:expr $(,)?) => ({
589 $crate::unreachable!("{}", $msg)
591 ($fmt:expr, $($arg:tt)*) => ({
592 $crate::panic!($crate::concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
596 /// Indicates unimplemented code by panicking with a message of "not implemented".
598 /// This allows your code to type-check, which is useful if you are prototyping or
599 /// implementing a trait that requires multiple methods which you don't plan to use all of.
601 /// The difference between `unimplemented!` and [`todo!`] is that while `todo!`
602 /// conveys an intent of implementing the functionality later and the message is "not yet
603 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
604 /// Also some IDEs will mark `todo!`s.
608 /// This will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a
609 /// fixed, specific message.
611 /// Like `panic!`, this macro has a second form for displaying custom values.
615 /// Say we have a trait `Foo`:
619 /// fn bar(&self) -> u8;
621 /// fn qux(&self) -> Result<u64, ()>;
625 /// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
626 /// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
627 /// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
628 /// to allow our code to compile.
630 /// We still want to have our program stop running if the unimplemented methods are
635 /// # fn bar(&self) -> u8;
637 /// # fn qux(&self) -> Result<u64, ()>;
641 /// impl Foo for MyStruct {
642 /// fn bar(&self) -> u8 {
647 /// // It makes no sense to `baz` a `MyStruct`, so we have no logic here
649 /// // This will display "thread 'main' panicked at 'not implemented'".
650 /// unimplemented!();
653 /// fn qux(&self) -> Result<u64, ()> {
654 /// // We have some logic here,
655 /// // We can add a message to unimplemented! to display our omission.
656 /// // This will display:
657 /// // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
658 /// unimplemented!("MyStruct isn't quxable");
663 /// let s = MyStruct;
668 #[stable(feature = "rust1", since = "1.0.0")]
669 macro_rules! unimplemented {
670 () => ($crate::panic!("not implemented"));
671 ($($arg:tt)+) => ($crate::panic!("not implemented: {}", $crate::format_args!($($arg)+)));
674 /// Indicates unfinished code.
676 /// This can be useful if you are prototyping and are just looking to have your
679 /// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
680 /// an intent of implementing the functionality later and the message is "not yet
681 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
682 /// Also some IDEs will mark `todo!`s.
686 /// This will always [`panic!`].
690 /// Here's an example of some in-progress code. We have a trait `Foo`:
699 /// We want to implement `Foo` on one of our types, but we also want to work on
700 /// just `bar()` first. In order for our code to compile, we need to implement
701 /// `baz()`, so we can use `todo!`:
710 /// impl Foo for MyStruct {
712 /// // implementation goes here
716 /// // let's not worry about implementing baz() for now
722 /// let s = MyStruct;
725 /// // we aren't even using baz(), so this is fine.
729 #[stable(feature = "todo_macro", since = "1.40.0")]
731 () => ($crate::panic!("not yet implemented"));
732 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
735 /// Definitions of built-in macros.
737 /// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
738 /// with exception of expansion functions transforming macro inputs into outputs,
739 /// those functions are provided by the compiler.
740 pub(crate) mod builtin {
742 /// Causes compilation to fail with the given error message when encountered.
744 /// This macro should be used when a crate uses a conditional compilation strategy to provide
745 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
746 /// but emits an error during *compilation* rather than at *runtime*.
750 /// Two such examples are macros and `#[cfg]` environments.
752 /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
753 /// the compiler would still emit an error, but the error's message would not mention the two
757 /// macro_rules! give_me_foo_or_bar {
761 /// compile_error!("This macro only accepts `foo` or `bar`");
765 /// give_me_foo_or_bar!(neither);
766 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
769 /// Emit compiler error if one of a number of features isn't available.
772 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
773 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
775 #[stable(feature = "compile_error_macro", since = "1.20.0")]
776 #[rustc_builtin_macro]
778 macro_rules! compile_error {
779 ($msg:expr $(,)?) => {{ /* compiler built-in */ }};
782 /// Constructs parameters for the other string-formatting macros.
784 /// This macro functions by taking a formatting string literal containing
785 /// `{}` for each additional argument passed. `format_args!` prepares the
786 /// additional parameters to ensure the output can be interpreted as a string
787 /// and canonicalizes the arguments into a single type. Any value that implements
788 /// the [`Display`] trait can be passed to `format_args!`, as can any
789 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
791 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
792 /// passed to the macros within [`std::fmt`] for performing useful redirection.
793 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
794 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
795 /// heap allocations.
797 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
798 /// in `Debug` and `Display` contexts as seen below. The example also shows
799 /// that `Debug` and `Display` format to the same thing: the interpolated
800 /// format string in `format_args!`.
803 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
804 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
805 /// assert_eq!("1 foo 2", display);
806 /// assert_eq!(display, debug);
809 /// For more information, see the documentation in [`std::fmt`].
811 /// [`Display`]: crate::fmt::Display
812 /// [`Debug`]: crate::fmt::Debug
813 /// [`fmt::Arguments`]: crate::fmt::Arguments
814 /// [`std::fmt`]: ../std/fmt/index.html
815 /// [`format!`]: ../std/macro.format.html
816 /// [`println!`]: ../std/macro.println.html
823 /// let s = fmt::format(format_args!("hello {}", "world"));
824 /// assert_eq!(s, format!("hello {}", "world"));
826 #[stable(feature = "rust1", since = "1.0.0")]
827 #[allow_internal_unstable(fmt_internals)]
828 #[rustc_builtin_macro]
830 macro_rules! format_args {
831 ($fmt:expr) => {{ /* compiler built-in */ }};
832 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
835 /// Same as `format_args`, but adds a newline in the end.
837 feature = "format_args_nl",
839 reason = "`format_args_nl` is only for internal \
840 language use and is subject to change"
842 #[allow_internal_unstable(fmt_internals)]
843 #[rustc_builtin_macro]
845 macro_rules! format_args_nl {
846 ($fmt:expr) => {{ /* compiler built-in */ }};
847 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
850 /// Inspects an environment variable at compile time.
852 /// This macro will expand to the value of the named environment variable at
853 /// compile time, yielding an expression of type `&'static str`.
855 /// If the environment variable is not defined, then a compilation error
856 /// will be emitted. To not emit a compile error, use the [`option_env!`]
862 /// let path: &'static str = env!("PATH");
863 /// println!("the $PATH variable at the time of compiling was: {}", path);
866 /// You can customize the error message by passing a string as the second
870 /// let doc: &'static str = env!("documentation", "what's that?!");
873 /// If the `documentation` environment variable is not defined, you'll get
874 /// the following error:
877 /// error: what's that?!
879 #[stable(feature = "rust1", since = "1.0.0")]
880 #[rustc_builtin_macro]
883 ($name:expr $(,)?) => {{ /* compiler built-in */ }};
884 ($name:expr, $error_msg:expr $(,)?) => {{ /* compiler built-in */ }};
887 /// Optionally inspects an environment variable at compile time.
889 /// If the named environment variable is present at compile time, this will
890 /// expand into an expression of type `Option<&'static str>` whose value is
891 /// `Some` of the value of the environment variable. If the environment
892 /// variable is not present, then this will expand to `None`. See
893 /// [`Option<T>`][Option] for more information on this type.
895 /// A compile time error is never emitted when using this macro regardless
896 /// of whether the environment variable is present or not.
901 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
902 /// println!("the secret key might be: {:?}", key);
904 #[stable(feature = "rust1", since = "1.0.0")]
905 #[rustc_builtin_macro]
907 macro_rules! option_env {
908 ($name:expr $(,)?) => {{ /* compiler built-in */ }};
911 /// Concatenates identifiers into one identifier.
913 /// This macro takes any number of comma-separated identifiers, and
914 /// concatenates them all into one, yielding an expression which is a new
915 /// identifier. Note that hygiene makes it such that this macro cannot
916 /// capture local variables. Also, as a general rule, macros are only
917 /// allowed in item, statement or expression position. That means while
918 /// you may use this macro for referring to existing variables, functions or
919 /// modules etc, you cannot define a new one with it.
924 /// #![feature(concat_idents)]
927 /// fn foobar() -> u32 { 23 }
929 /// let f = concat_idents!(foo, bar);
930 /// println!("{}", f());
932 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
936 feature = "concat_idents",
938 reason = "`concat_idents` is not stable enough for use and is subject to change"
940 #[rustc_builtin_macro]
942 macro_rules! concat_idents {
943 ($($e:ident),+ $(,)?) => {{ /* compiler built-in */ }};
946 /// Concatenates literals into a static string slice.
948 /// This macro takes any number of comma-separated literals, yielding an
949 /// expression of type `&'static str` which represents all of the literals
950 /// concatenated left-to-right.
952 /// Integer and floating point literals are stringified in order to be
958 /// let s = concat!("test", 10, 'b', true);
959 /// assert_eq!(s, "test10btrue");
961 #[stable(feature = "rust1", since = "1.0.0")]
962 #[rustc_builtin_macro]
964 macro_rules! concat {
965 ($($e:expr),* $(,)?) => {{ /* compiler built-in */ }};
968 /// Expands to the line number on which it was invoked.
970 /// With [`column!`] and [`file!`], these macros provide debugging information for
971 /// developers about the location within the source.
973 /// The expanded expression has type `u32` and is 1-based, so the first line
974 /// in each file evaluates to 1, the second to 2, etc. This is consistent
975 /// with error messages by common compilers or popular editors.
976 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
977 /// but rather the first macro invocation leading up to the invocation
978 /// of the `line!` macro.
983 /// let current_line = line!();
984 /// println!("defined on line: {}", current_line);
986 #[stable(feature = "rust1", since = "1.0.0")]
987 #[rustc_builtin_macro]
991 /* compiler built-in */
995 /// Expands to the column number at which it was invoked.
997 /// With [`line!`] and [`file!`], these macros provide debugging information for
998 /// developers about the location within the source.
1000 /// The expanded expression has type `u32` and is 1-based, so the first column
1001 /// in each line evaluates to 1, the second to 2, etc. This is consistent
1002 /// with error messages by common compilers or popular editors.
1003 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
1004 /// but rather the first macro invocation leading up to the invocation
1005 /// of the `column!` macro.
1010 /// let current_col = column!();
1011 /// println!("defined on column: {}", current_col);
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 #[rustc_builtin_macro]
1016 macro_rules! column {
1018 /* compiler built-in */
1022 /// Expands to the file name in which it was invoked.
1024 /// With [`line!`] and [`column!`], these macros provide debugging information for
1025 /// developers about the location within the source.
1027 /// The expanded expression has type `&'static str`, and the returned file
1028 /// is not the invocation of the `file!` macro itself, but rather the
1029 /// first macro invocation leading up to the invocation of the `file!`
1035 /// let this_file = file!();
1036 /// println!("defined in file: {}", this_file);
1038 #[stable(feature = "rust1", since = "1.0.0")]
1039 #[rustc_builtin_macro]
1043 /* compiler built-in */
1047 /// Stringifies its arguments.
1049 /// This macro will yield an expression of type `&'static str` which is the
1050 /// stringification of all the tokens passed to the macro. No restrictions
1051 /// are placed on the syntax of the macro invocation itself.
1053 /// Note that the expanded results of the input tokens may change in the
1054 /// future. You should be careful if you rely on the output.
1059 /// let one_plus_one = stringify!(1 + 1);
1060 /// assert_eq!(one_plus_one, "1 + 1");
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 #[rustc_builtin_macro]
1065 macro_rules! stringify {
1067 /* compiler built-in */
1071 /// Includes a UTF-8 encoded file as a string.
1073 /// The file is located relative to the current file (similarly to how
1074 /// modules are found). The provided path is interpreted in a platform-specific
1075 /// way at compile time. So, for instance, an invocation with a Windows path
1076 /// containing backslashes `\` would not compile correctly on Unix.
1078 /// This macro will yield an expression of type `&'static str` which is the
1079 /// contents of the file.
1083 /// Assume there are two files in the same directory with the following
1086 /// File 'spanish.in':
1094 /// ```ignore (cannot-doctest-external-file-dependency)
1096 /// let my_str = include_str!("spanish.in");
1097 /// assert_eq!(my_str, "adiós\n");
1098 /// print!("{}", my_str);
1102 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1103 #[stable(feature = "rust1", since = "1.0.0")]
1104 #[rustc_builtin_macro]
1106 macro_rules! include_str {
1107 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1110 /// Includes a file as a reference to a byte array.
1112 /// The file is located relative to the current file (similarly to how
1113 /// modules are found). The provided path is interpreted in a platform-specific
1114 /// way at compile time. So, for instance, an invocation with a Windows path
1115 /// containing backslashes `\` would not compile correctly on Unix.
1117 /// This macro will yield an expression of type `&'static [u8; N]` which is
1118 /// the contents of the file.
1122 /// Assume there are two files in the same directory with the following
1125 /// File 'spanish.in':
1133 /// ```ignore (cannot-doctest-external-file-dependency)
1135 /// let bytes = include_bytes!("spanish.in");
1136 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
1137 /// print!("{}", String::from_utf8_lossy(bytes));
1141 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1142 #[stable(feature = "rust1", since = "1.0.0")]
1143 #[rustc_builtin_macro]
1145 macro_rules! include_bytes {
1146 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1149 /// Expands to a string that represents the current module path.
1151 /// The current module path can be thought of as the hierarchy of modules
1152 /// leading back up to the crate root. The first component of the path
1153 /// returned is the name of the crate currently being compiled.
1160 /// assert!(module_path!().ends_with("test"));
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 #[rustc_builtin_macro]
1169 macro_rules! module_path {
1171 /* compiler built-in */
1175 /// Evaluates boolean combinations of configuration flags at compile-time.
1177 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1178 /// boolean expression evaluation of configuration flags. This frequently
1179 /// leads to less duplicated code.
1181 /// The syntax given to this macro is the same syntax as the [`cfg`]
1184 /// `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For
1185 /// example, all blocks in an if/else expression need to be valid when `cfg!` is used for
1186 /// the condition, regardless of what `cfg!` is evaluating.
1188 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1193 /// let my_directory = if cfg!(windows) {
1194 /// "windows-specific-directory"
1196 /// "unix-directory"
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 #[rustc_builtin_macro]
1204 /* compiler built-in */
1208 /// Parses a file as an expression or an item according to the context.
1210 /// The file is located relative to the current file (similarly to how
1211 /// modules are found). The provided path is interpreted in a platform-specific
1212 /// way at compile time. So, for instance, an invocation with a Windows path
1213 /// containing backslashes `\` would not compile correctly on Unix.
1215 /// Using this macro is often a bad idea, because if the file is
1216 /// parsed as an expression, it is going to be placed in the
1217 /// surrounding code unhygienically. This could result in variables
1218 /// or functions being different from what the file expected if
1219 /// there are variables or functions that have the same name in
1220 /// the current file.
1224 /// Assume there are two files in the same directory with the following
1227 /// File 'monkeys.in':
1229 /// ```ignore (only-for-syntax-highlight)
1230 /// ['🙈', '🙊', '🙉']
1234 /// .collect::<String>()
1239 /// ```ignore (cannot-doctest-external-file-dependency)
1241 /// let my_string = include!("monkeys.in");
1242 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1243 /// println!("{}", my_string);
1247 /// Compiling 'main.rs' and running the resulting binary will print
1248 /// "🙈🙊🙉🙈🙊🙉".
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 #[rustc_builtin_macro]
1252 macro_rules! include {
1253 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1256 /// Asserts that a boolean expression is `true` at runtime.
1258 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1259 /// evaluated to `true` at runtime.
1263 /// Assertions are always checked in both debug and release builds, and cannot
1264 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1265 /// release builds by default.
1267 /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if
1268 /// violated could lead to unsafety.
1270 /// Other use-cases of `assert!` include testing and enforcing run-time
1271 /// invariants in safe code (whose violation cannot result in unsafety).
1273 /// # Custom Messages
1275 /// This macro has a second form, where a custom panic message can
1276 /// be provided with or without arguments for formatting. See [`std::fmt`]
1277 /// for syntax for this form. Expressions used as format arguments will only
1278 /// be evaluated if the assertion fails.
1280 /// [`std::fmt`]: ../std/fmt/index.html
1285 /// // the panic message for these assertions is the stringified value of the
1286 /// // expression given.
1289 /// fn some_computation() -> bool { true } // a very simple function
1291 /// assert!(some_computation());
1293 /// // assert with a custom message
1295 /// assert!(x, "x wasn't true!");
1297 /// let a = 3; let b = 27;
1298 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 #[rustc_builtin_macro]
1303 #[rustc_diagnostic_item = "assert_macro"]
1304 #[allow_internal_unstable(core_panic, edition_panic)]
1305 macro_rules! assert {
1306 ($cond:expr $(,)?) => {{ /* compiler built-in */ }};
1307 ($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }};
1310 /// Inline assembly.
1312 /// Read the [unstable book] for the usage.
1314 /// [unstable book]: ../unstable-book/library-features/asm.html
1318 reason = "inline assembly is not stable enough for use and is subject to change"
1320 #[rustc_builtin_macro]
1323 ("assembly template",
1325 $(options($(option),*))?
1327 /* compiler built-in */
1331 /// LLVM-style inline assembly.
1333 /// Read the [unstable book] for the usage.
1335 /// [unstable book]: ../unstable-book/library-features/llvm-asm.html
1337 feature = "llvm_asm",
1339 reason = "prefer using the new asm! syntax instead"
1341 #[rustc_builtin_macro]
1343 macro_rules! llvm_asm {
1344 ("assembly template"
1345 : $("output"(operand),)*
1346 : $("input"(operand),)*
1348 : $("options",)*) => {
1349 /* compiler built-in */
1353 /// Module-level inline assembly.
1355 feature = "global_asm",
1357 reason = "`global_asm!` is not stable enough for use and is subject to change"
1359 #[rustc_builtin_macro]
1361 macro_rules! global_asm {
1362 ("assembly template",
1364 $(options($(option),*))?
1366 /* compiler built-in */
1370 /// Prints passed tokens into the standard output.
1372 feature = "log_syntax",
1374 reason = "`log_syntax!` is not stable enough for use and is subject to change"
1376 #[rustc_builtin_macro]
1378 macro_rules! log_syntax {
1380 /* compiler built-in */
1384 /// Enables or disables tracing functionality used for debugging other macros.
1386 feature = "trace_macros",
1388 reason = "`trace_macros` is not stable enough for use and is subject to change"
1390 #[rustc_builtin_macro]
1392 macro_rules! trace_macros {
1393 (true) => {{ /* compiler built-in */ }};
1394 (false) => {{ /* compiler built-in */ }};
1397 /// Attribute macro used to apply derive macros.
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 #[rustc_builtin_macro]
1400 pub macro derive($item:item) {
1401 /* compiler built-in */
1404 /// Attribute macro applied to a function to turn it into a unit test.
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 #[allow_internal_unstable(test, rustc_attrs)]
1407 #[rustc_builtin_macro]
1408 pub macro test($item:item) {
1409 /* compiler built-in */
1412 /// Attribute macro applied to a function to turn it into a benchmark test.
1417 reason = "`bench` is a part of custom test frameworks which are unstable"
1419 #[allow_internal_unstable(test, rustc_attrs)]
1420 #[rustc_builtin_macro]
1421 pub macro bench($item:item) {
1422 /* compiler built-in */
1425 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1427 feature = "custom_test_frameworks",
1429 reason = "custom test frameworks are an unstable feature"
1431 #[allow_internal_unstable(test, rustc_attrs)]
1432 #[rustc_builtin_macro]
1433 pub macro test_case($item:item) {
1434 /* compiler built-in */
1437 /// Attribute macro applied to a static to register it as a global allocator.
1439 /// See also [`std::alloc::GlobalAlloc`](../std/alloc/trait.GlobalAlloc.html).
1440 #[stable(feature = "global_allocator", since = "1.28.0")]
1441 #[allow_internal_unstable(rustc_attrs)]
1442 #[rustc_builtin_macro]
1443 pub macro global_allocator($item:item) {
1444 /* compiler built-in */
1447 /// Keeps the item it's applied to if the passed path is accessible, and removes it otherwise.
1449 feature = "cfg_accessible",
1451 reason = "`cfg_accessible` is not fully implemented"
1453 #[rustc_builtin_macro]
1454 pub macro cfg_accessible($item:item) {
1455 /* compiler built-in */
1458 /// Expands all `#[cfg]` and `#[cfg_attr]` attributes in the code fragment it's applied to.
1460 feature = "cfg_eval",
1462 reason = "`cfg_eval` is a recently implemented feature"
1464 #[rustc_builtin_macro]
1465 pub macro cfg_eval($($tt:tt)*) {
1466 /* compiler built-in */
1469 /// Unstable implementation detail of the `rustc` compiler, do not use.
1470 #[rustc_builtin_macro]
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 #[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
1475 reason = "rustc-serialize is deprecated and no longer supported"
1477 pub macro RustcDecodable($item:item) {
1478 /* compiler built-in */
1481 /// Unstable implementation detail of the `rustc` compiler, do not use.
1482 #[rustc_builtin_macro]
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 #[allow_internal_unstable(core_intrinsics)]
1487 reason = "rustc-serialize is deprecated and no longer supported"
1489 pub macro RustcEncodable($item:item) {
1490 /* compiler built-in */