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 macro_rules! debug_assert {
214 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert!($($arg)*); })
217 /// Asserts that two expressions are equal to each other.
219 /// On panic, this macro will print the values of the expressions with their
220 /// debug representations.
222 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
223 /// optimized builds by default. An optimized build will not execute
224 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
225 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
226 /// expensive to be present in a release build but may be helpful during
227 /// development. The result of expanding `debug_assert_eq!` is always type checked.
234 /// debug_assert_eq!(a, b);
237 #[stable(feature = "rust1", since = "1.0.0")]
238 macro_rules! debug_assert_eq {
239 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_eq!($($arg)*); })
242 /// Asserts that two expressions are not equal to each other.
244 /// On panic, this macro will print the values of the expressions with their
245 /// debug representations.
247 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
248 /// optimized builds by default. An optimized build will not execute
249 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
250 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
251 /// expensive to be present in a release build but may be helpful during
252 /// development. The result of expanding `debug_assert_ne!` is always type checked.
259 /// debug_assert_ne!(a, b);
262 #[stable(feature = "assert_ne", since = "1.13.0")]
263 macro_rules! debug_assert_ne {
264 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_ne!($($arg)*); })
267 /// Asserts that an expression matches any of the given patterns.
269 /// Like in a `match` expression, the pattern can be optionally followed by `if`
270 /// and a guard expression that has access to names bound by the pattern.
272 /// On panic, this macro will print the value of the expression with its
273 /// debug representation.
275 /// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only
276 /// enabled in non optimized builds by default. An optimized build will not
277 /// execute `debug_assert_matches!` statements unless `-C debug-assertions` is
278 /// passed to the compiler. This makes `debug_assert_matches!` useful for
279 /// checks that are too expensive to be present in a release build but may be
280 /// helpful during development. The result of expanding `debug_assert_matches!`
281 /// is always type checked.
286 /// #![feature(assert_matches)]
288 /// use std::assert_matches::debug_assert_matches;
290 /// let a = 1u32.checked_add(2);
291 /// let b = 1u32.checked_sub(2);
292 /// debug_assert_matches!(a, Some(_));
293 /// debug_assert_matches!(b, None);
295 /// let c = Ok("abc".to_string());
296 /// debug_assert_matches!(c, Ok(x) | Err(x) if x.len() < 100);
299 #[unstable(feature = "assert_matches", issue = "82775")]
300 #[allow_internal_unstable(assert_matches)]
301 #[rustc_macro_transparency = "semitransparent"]
302 pub macro debug_assert_matches($($arg:tt)*) {
303 if $crate::cfg!(debug_assertions) { $crate::assert_matches::assert_matches!($($arg)*); }
306 /// Returns whether the given expression matches any of the given patterns.
308 /// Like in a `match` expression, the pattern can be optionally followed by `if`
309 /// and a guard expression that has access to names bound by the pattern.
315 /// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
317 /// let bar = Some(4);
318 /// assert!(matches!(bar, Some(x) if x > 2));
321 #[stable(feature = "matches_macro", since = "1.42.0")]
322 macro_rules! matches {
323 ($expression:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => {
325 $( $pattern )|+ $( if $guard )? => true,
331 /// Unwraps a result or propagates its error.
333 /// The `?` operator was added to replace `try!` and should be used instead.
334 /// Furthermore, `try` is a reserved word in Rust 2018, so if you must use
335 /// it, you will need to use the [raw-identifier syntax][ris]: `r#try`.
337 /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
339 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
340 /// expression has the value of the wrapped value.
342 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
343 /// performs conversion using `From`. This provides automatic conversion
344 /// between specialized errors and more general ones. The resulting
345 /// error is then immediately returned.
347 /// Because of the early return, `try!` can only be used in functions that
348 /// return [`Result`].
354 /// use std::fs::File;
355 /// use std::io::prelude::*;
361 /// impl From<io::Error> for MyError {
362 /// fn from(e: io::Error) -> MyError {
363 /// MyError::FileWriteError
367 /// // The preferred method of quick returning Errors
368 /// fn write_to_file_question() -> Result<(), MyError> {
369 /// let mut file = File::create("my_best_friends.txt")?;
370 /// file.write_all(b"This is a list of my best friends.")?;
374 /// // The previous method of quick returning Errors
375 /// fn write_to_file_using_try() -> Result<(), MyError> {
376 /// let mut file = r#try!(File::create("my_best_friends.txt"));
377 /// r#try!(file.write_all(b"This is a list of my best friends."));
381 /// // This is equivalent to:
382 /// fn write_to_file_using_match() -> Result<(), MyError> {
383 /// let mut file = r#try!(File::create("my_best_friends.txt"));
384 /// match file.write_all(b"This is a list of my best friends.") {
386 /// Err(e) => return Err(From::from(e)),
392 #[stable(feature = "rust1", since = "1.0.0")]
393 #[rustc_deprecated(since = "1.39.0", reason = "use the `?` operator instead")]
396 ($expr:expr $(,)?) => {
398 $crate::result::Result::Ok(val) => val,
399 $crate::result::Result::Err(err) => {
400 return $crate::result::Result::Err($crate::convert::From::from(err));
406 /// Writes formatted data into a buffer.
408 /// This macro accepts a 'writer', a format string, and a list of arguments. Arguments will be
409 /// formatted according to the specified format string and the result will be passed to the writer.
410 /// The writer may be any value with a `write_fmt` method; generally this comes from an
411 /// implementation of either the [`fmt::Write`] or the [`io::Write`] trait. The macro
412 /// returns whatever the `write_fmt` method returns; commonly a [`fmt::Result`], or an
415 /// See [`std::fmt`] for more information on the format string syntax.
417 /// [`std::fmt`]: ../std/fmt/index.html
418 /// [`fmt::Write`]: crate::fmt::Write
419 /// [`io::Write`]: ../std/io/trait.Write.html
420 /// [`fmt::Result`]: crate::fmt::Result
421 /// [`io::Result`]: ../std/io/type.Result.html
426 /// use std::io::Write;
428 /// fn main() -> std::io::Result<()> {
429 /// let mut w = Vec::new();
430 /// write!(&mut w, "test")?;
431 /// write!(&mut w, "formatted {}", "arguments")?;
433 /// assert_eq!(w, b"testformatted arguments");
438 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
439 /// implementing either, as objects do not typically implement both. However, the module must
440 /// import the traits qualified so their names do not conflict:
443 /// use std::fmt::Write as FmtWrite;
444 /// use std::io::Write as IoWrite;
446 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
447 /// let mut s = String::new();
448 /// let mut v = Vec::new();
450 /// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
451 /// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
452 /// assert_eq!(v, b"s = \"abc 123\"");
457 /// Note: This macro can be used in `no_std` setups as well.
458 /// In a `no_std` setup you are responsible for the implementation details of the components.
461 /// # extern crate core;
462 /// use core::fmt::Write;
466 /// impl Write for Example {
467 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
468 /// unimplemented!();
472 /// let mut m = Example{};
473 /// write!(&mut m, "Hello World").expect("Not written");
476 #[stable(feature = "rust1", since = "1.0.0")]
478 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt($crate::format_args!($($arg)*)))
481 /// Write formatted data into a buffer, with a newline appended.
483 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
484 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
486 /// For more information, see [`write!`]. For information on the format string syntax, see
489 /// [`std::fmt`]: ../std/fmt/index.html
494 /// use std::io::{Write, Result};
496 /// fn main() -> Result<()> {
497 /// let mut w = Vec::new();
498 /// writeln!(&mut w)?;
499 /// writeln!(&mut w, "test")?;
500 /// writeln!(&mut w, "formatted {}", "arguments")?;
502 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
507 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
508 /// implementing either, as objects do not typically implement both. However, the module must
509 /// import the traits qualified so their names do not conflict:
512 /// use std::fmt::Write as FmtWrite;
513 /// use std::io::Write as IoWrite;
515 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
516 /// let mut s = String::new();
517 /// let mut v = Vec::new();
519 /// writeln!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
520 /// writeln!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
521 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
526 #[stable(feature = "rust1", since = "1.0.0")]
527 #[allow_internal_unstable(format_args_nl)]
528 macro_rules! writeln {
529 ($dst:expr $(,)?) => (
530 $crate::write!($dst, "\n")
532 ($dst:expr, $($arg:tt)*) => (
533 $dst.write_fmt($crate::format_args_nl!($($arg)*))
537 /// Indicates unreachable code.
539 /// This is useful any time that the compiler can't determine that some code is unreachable. For
542 /// * Match arms with guard conditions.
543 /// * Loops that dynamically terminate.
544 /// * Iterators that dynamically terminate.
546 /// If the determination that the code is unreachable proves incorrect, the
547 /// program immediately terminates with a [`panic!`].
549 /// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
550 /// will cause undefined behavior if the code is reached.
552 /// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked
556 /// This will always [`panic!`].
563 /// # #[allow(dead_code)]
564 /// fn foo(x: Option<i32>) {
566 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
567 /// Some(n) if n < 0 => println!("Some(Negative)"),
568 /// Some(_) => unreachable!(), // compile error if commented out
569 /// None => println!("None")
577 /// # #[allow(dead_code)]
578 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
580 /// if 3*i < i { panic!("u32 overflow"); }
581 /// if x < 3*i { return i-1; }
587 #[stable(feature = "rust1", since = "1.0.0")]
588 macro_rules! unreachable {
590 $crate::panic!("internal error: entered unreachable code")
592 ($msg:expr $(,)?) => ({
593 $crate::unreachable!("{}", $msg)
595 ($fmt:expr, $($arg:tt)*) => ({
596 $crate::panic!($crate::concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
600 /// Indicates unimplemented code by panicking with a message of "not implemented".
602 /// This allows your code to type-check, which is useful if you are prototyping or
603 /// implementing a trait that requires multiple methods which you don't plan to use all of.
605 /// The difference between `unimplemented!` and [`todo!`] is that while `todo!`
606 /// conveys an intent of implementing the functionality later and the message is "not yet
607 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
608 /// Also some IDEs will mark `todo!`s.
612 /// This will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a
613 /// fixed, specific message.
615 /// Like `panic!`, this macro has a second form for displaying custom values.
619 /// Say we have a trait `Foo`:
623 /// fn bar(&self) -> u8;
625 /// fn qux(&self) -> Result<u64, ()>;
629 /// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
630 /// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
631 /// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
632 /// to allow our code to compile.
634 /// We still want to have our program stop running if the unimplemented methods are
639 /// # fn bar(&self) -> u8;
641 /// # fn qux(&self) -> Result<u64, ()>;
645 /// impl Foo for MyStruct {
646 /// fn bar(&self) -> u8 {
651 /// // It makes no sense to `baz` a `MyStruct`, so we have no logic here
653 /// // This will display "thread 'main' panicked at 'not implemented'".
654 /// unimplemented!();
657 /// fn qux(&self) -> Result<u64, ()> {
658 /// // We have some logic here,
659 /// // We can add a message to unimplemented! to display our omission.
660 /// // This will display:
661 /// // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
662 /// unimplemented!("MyStruct isn't quxable");
667 /// let s = MyStruct;
672 #[stable(feature = "rust1", since = "1.0.0")]
673 macro_rules! unimplemented {
674 () => ($crate::panic!("not implemented"));
675 ($($arg:tt)+) => ($crate::panic!("not implemented: {}", $crate::format_args!($($arg)+)));
678 /// Indicates unfinished code.
680 /// This can be useful if you are prototyping and are just looking to have your
683 /// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
684 /// an intent of implementing the functionality later and the message is "not yet
685 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
686 /// Also some IDEs will mark `todo!`s.
690 /// This will always [`panic!`].
694 /// Here's an example of some in-progress code. We have a trait `Foo`:
703 /// We want to implement `Foo` on one of our types, but we also want to work on
704 /// just `bar()` first. In order for our code to compile, we need to implement
705 /// `baz()`, so we can use `todo!`:
714 /// impl Foo for MyStruct {
716 /// // implementation goes here
720 /// // let's not worry about implementing baz() for now
726 /// let s = MyStruct;
729 /// // we aren't even using baz(), so this is fine.
733 #[stable(feature = "todo_macro", since = "1.40.0")]
735 () => ($crate::panic!("not yet implemented"));
736 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
739 /// Definitions of built-in macros.
741 /// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
742 /// with exception of expansion functions transforming macro inputs into outputs,
743 /// those functions are provided by the compiler.
744 pub(crate) mod builtin {
746 /// Causes compilation to fail with the given error message when encountered.
748 /// This macro should be used when a crate uses a conditional compilation strategy to provide
749 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
750 /// but emits an error during *compilation* rather than at *runtime*.
754 /// Two such examples are macros and `#[cfg]` environments.
756 /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
757 /// the compiler would still emit an error, but the error's message would not mention the two
761 /// macro_rules! give_me_foo_or_bar {
765 /// compile_error!("This macro only accepts `foo` or `bar`");
769 /// give_me_foo_or_bar!(neither);
770 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
773 /// Emit compiler error if one of a number of features isn't available.
776 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
777 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
779 #[stable(feature = "compile_error_macro", since = "1.20.0")]
780 #[rustc_builtin_macro]
782 macro_rules! compile_error {
783 ($msg:expr $(,)?) => {{ /* compiler built-in */ }};
786 /// Constructs parameters for the other string-formatting macros.
788 /// This macro functions by taking a formatting string literal containing
789 /// `{}` for each additional argument passed. `format_args!` prepares the
790 /// additional parameters to ensure the output can be interpreted as a string
791 /// and canonicalizes the arguments into a single type. Any value that implements
792 /// the [`Display`] trait can be passed to `format_args!`, as can any
793 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
795 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
796 /// passed to the macros within [`std::fmt`] for performing useful redirection.
797 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
798 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
799 /// heap allocations.
801 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
802 /// in `Debug` and `Display` contexts as seen below. The example also shows
803 /// that `Debug` and `Display` format to the same thing: the interpolated
804 /// format string in `format_args!`.
807 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
808 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
809 /// assert_eq!("1 foo 2", display);
810 /// assert_eq!(display, debug);
813 /// For more information, see the documentation in [`std::fmt`].
815 /// [`Display`]: crate::fmt::Display
816 /// [`Debug`]: crate::fmt::Debug
817 /// [`fmt::Arguments`]: crate::fmt::Arguments
818 /// [`std::fmt`]: ../std/fmt/index.html
819 /// [`format!`]: ../std/macro.format.html
820 /// [`println!`]: ../std/macro.println.html
827 /// let s = fmt::format(format_args!("hello {}", "world"));
828 /// assert_eq!(s, format!("hello {}", "world"));
830 #[stable(feature = "rust1", since = "1.0.0")]
831 #[allow_internal_unsafe]
832 #[allow_internal_unstable(fmt_internals)]
833 #[rustc_builtin_macro]
835 macro_rules! format_args {
836 ($fmt:expr) => {{ /* compiler built-in */ }};
837 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
840 /// Same as `format_args`, but can be used in some const contexts.
842 /// This macro is used by the panic macros for the `const_panic` feature.
844 /// This macro will be removed once `format_args` is allowed in const contexts.
845 #[cfg(not(bootstrap))]
846 #[unstable(feature = "const_format_args", issue = "none")]
847 #[allow_internal_unstable(fmt_internals, const_fmt_arguments_new)]
848 #[rustc_builtin_macro]
850 macro_rules! const_format_args {
851 ($fmt:expr) => {{ /* compiler built-in */ }};
852 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
855 /// Same as `format_args`, but can be used in some const contexts.
857 #[unstable(feature = "const_format_args", issue = "none")]
859 macro_rules! const_format_args {
861 $crate::format_args!($($t)*)
865 /// Same as `format_args`, but adds a newline in the end.
867 feature = "format_args_nl",
869 reason = "`format_args_nl` is only for internal \
870 language use and is subject to change"
872 #[allow_internal_unstable(fmt_internals)]
874 #[rustc_builtin_macro]
876 macro_rules! format_args_nl {
877 ($fmt:expr) => {{ /* compiler built-in */ }};
878 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
881 /// Inspects an environment variable at compile time.
883 /// This macro will expand to the value of the named environment variable at
884 /// compile time, yielding an expression of type `&'static str`.
886 /// If the environment variable is not defined, then a compilation error
887 /// will be emitted. To not emit a compile error, use the [`option_env!`]
893 /// let path: &'static str = env!("PATH");
894 /// println!("the $PATH variable at the time of compiling was: {}", path);
897 /// You can customize the error message by passing a string as the second
901 /// let doc: &'static str = env!("documentation", "what's that?!");
904 /// If the `documentation` environment variable is not defined, you'll get
905 /// the following error:
908 /// error: what's that?!
910 #[stable(feature = "rust1", since = "1.0.0")]
911 #[rustc_builtin_macro]
914 ($name:expr $(,)?) => {{ /* compiler built-in */ }};
915 ($name:expr, $error_msg:expr $(,)?) => {{ /* compiler built-in */ }};
918 /// Optionally inspects an environment variable at compile time.
920 /// If the named environment variable is present at compile time, this will
921 /// expand into an expression of type `Option<&'static str>` whose value is
922 /// `Some` of the value of the environment variable. If the environment
923 /// variable is not present, then this will expand to `None`. See
924 /// [`Option<T>`][Option] for more information on this type.
926 /// A compile time error is never emitted when using this macro regardless
927 /// of whether the environment variable is present or not.
932 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
933 /// println!("the secret key might be: {:?}", key);
935 #[stable(feature = "rust1", since = "1.0.0")]
936 #[rustc_builtin_macro]
938 macro_rules! option_env {
939 ($name:expr $(,)?) => {{ /* compiler built-in */ }};
942 /// Concatenates identifiers into one identifier.
944 /// This macro takes any number of comma-separated identifiers, and
945 /// concatenates them all into one, yielding an expression which is a new
946 /// identifier. Note that hygiene makes it such that this macro cannot
947 /// capture local variables. Also, as a general rule, macros are only
948 /// allowed in item, statement or expression position. That means while
949 /// you may use this macro for referring to existing variables, functions or
950 /// modules etc, you cannot define a new one with it.
955 /// #![feature(concat_idents)]
958 /// fn foobar() -> u32 { 23 }
960 /// let f = concat_idents!(foo, bar);
961 /// println!("{}", f());
963 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
967 feature = "concat_idents",
969 reason = "`concat_idents` is not stable enough for use and is subject to change"
971 #[rustc_builtin_macro]
973 macro_rules! concat_idents {
974 ($($e:ident),+ $(,)?) => {{ /* compiler built-in */ }};
977 /// Concatenates literals into a static string slice.
979 /// This macro takes any number of comma-separated literals, yielding an
980 /// expression of type `&'static str` which represents all of the literals
981 /// concatenated left-to-right.
983 /// Integer and floating point literals are stringified in order to be
989 /// let s = concat!("test", 10, 'b', true);
990 /// assert_eq!(s, "test10btrue");
992 #[stable(feature = "rust1", since = "1.0.0")]
993 #[rustc_builtin_macro]
995 macro_rules! concat {
996 ($($e:expr),* $(,)?) => {{ /* compiler built-in */ }};
999 /// Expands to the line number on which it was invoked.
1001 /// With [`column!`] and [`file!`], these macros provide debugging information for
1002 /// developers about the location within the source.
1004 /// The expanded expression has type `u32` and is 1-based, so the first line
1005 /// in each file evaluates to 1, the second to 2, etc. This is consistent
1006 /// with error messages by common compilers or popular editors.
1007 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
1008 /// but rather the first macro invocation leading up to the invocation
1009 /// of the `line!` macro.
1014 /// let current_line = line!();
1015 /// println!("defined on line: {}", current_line);
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 #[rustc_builtin_macro]
1022 /* compiler built-in */
1026 /// Expands to the column number at which it was invoked.
1028 /// With [`line!`] and [`file!`], these macros provide debugging information for
1029 /// developers about the location within the source.
1031 /// The expanded expression has type `u32` and is 1-based, so the first column
1032 /// in each line evaluates to 1, the second to 2, etc. This is consistent
1033 /// with error messages by common compilers or popular editors.
1034 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
1035 /// but rather the first macro invocation leading up to the invocation
1036 /// of the `column!` macro.
1041 /// let current_col = column!();
1042 /// println!("defined on column: {}", current_col);
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 #[rustc_builtin_macro]
1047 macro_rules! column {
1049 /* compiler built-in */
1053 /// Expands to the file name in which it was invoked.
1055 /// With [`line!`] and [`column!`], these macros provide debugging information for
1056 /// developers about the location within the source.
1058 /// The expanded expression has type `&'static str`, and the returned file
1059 /// is not the invocation of the `file!` macro itself, but rather the
1060 /// first macro invocation leading up to the invocation of the `file!`
1066 /// let this_file = file!();
1067 /// println!("defined in file: {}", this_file);
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 #[rustc_builtin_macro]
1074 /* compiler built-in */
1078 /// Stringifies its arguments.
1080 /// This macro will yield an expression of type `&'static str` which is the
1081 /// stringification of all the tokens passed to the macro. No restrictions
1082 /// are placed on the syntax of the macro invocation itself.
1084 /// Note that the expanded results of the input tokens may change in the
1085 /// future. You should be careful if you rely on the output.
1090 /// let one_plus_one = stringify!(1 + 1);
1091 /// assert_eq!(one_plus_one, "1 + 1");
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 #[rustc_builtin_macro]
1096 macro_rules! stringify {
1098 /* compiler built-in */
1102 /// Includes a UTF-8 encoded file as a string.
1104 /// The file is located relative to the current file (similarly to how
1105 /// modules are found). The provided path is interpreted in a platform-specific
1106 /// way at compile time. So, for instance, an invocation with a Windows path
1107 /// containing backslashes `\` would not compile correctly on Unix.
1109 /// This macro will yield an expression of type `&'static str` which is the
1110 /// contents of the file.
1114 /// Assume there are two files in the same directory with the following
1117 /// File 'spanish.in':
1125 /// ```ignore (cannot-doctest-external-file-dependency)
1127 /// let my_str = include_str!("spanish.in");
1128 /// assert_eq!(my_str, "adiós\n");
1129 /// print!("{}", my_str);
1133 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 #[rustc_builtin_macro]
1137 macro_rules! include_str {
1138 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1141 /// Includes a file as a reference to a byte array.
1143 /// The file is located relative to the current file (similarly to how
1144 /// modules are found). The provided path is interpreted in a platform-specific
1145 /// way at compile time. So, for instance, an invocation with a Windows path
1146 /// containing backslashes `\` would not compile correctly on Unix.
1148 /// This macro will yield an expression of type `&'static [u8; N]` which is
1149 /// the contents of the file.
1153 /// Assume there are two files in the same directory with the following
1156 /// File 'spanish.in':
1164 /// ```ignore (cannot-doctest-external-file-dependency)
1166 /// let bytes = include_bytes!("spanish.in");
1167 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
1168 /// print!("{}", String::from_utf8_lossy(bytes));
1172 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 #[rustc_builtin_macro]
1176 macro_rules! include_bytes {
1177 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1180 /// Expands to a string that represents the current module path.
1182 /// The current module path can be thought of as the hierarchy of modules
1183 /// leading back up to the crate root. The first component of the path
1184 /// returned is the name of the crate currently being compiled.
1191 /// assert!(module_path!().ends_with("test"));
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 #[rustc_builtin_macro]
1200 macro_rules! module_path {
1202 /* compiler built-in */
1206 /// Evaluates boolean combinations of configuration flags at compile-time.
1208 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1209 /// boolean expression evaluation of configuration flags. This frequently
1210 /// leads to less duplicated code.
1212 /// The syntax given to this macro is the same syntax as the [`cfg`]
1215 /// `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For
1216 /// example, all blocks in an if/else expression need to be valid when `cfg!` is used for
1217 /// the condition, regardless of what `cfg!` is evaluating.
1219 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1224 /// let my_directory = if cfg!(windows) {
1225 /// "windows-specific-directory"
1227 /// "unix-directory"
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 #[rustc_builtin_macro]
1235 /* compiler built-in */
1239 /// Parses a file as an expression or an item according to the context.
1241 /// The file is located relative to the current file (similarly to how
1242 /// modules are found). The provided path is interpreted in a platform-specific
1243 /// way at compile time. So, for instance, an invocation with a Windows path
1244 /// containing backslashes `\` would not compile correctly on Unix.
1246 /// Using this macro is often a bad idea, because if the file is
1247 /// parsed as an expression, it is going to be placed in the
1248 /// surrounding code unhygienically. This could result in variables
1249 /// or functions being different from what the file expected if
1250 /// there are variables or functions that have the same name in
1251 /// the current file.
1255 /// Assume there are two files in the same directory with the following
1258 /// File 'monkeys.in':
1260 /// ```ignore (only-for-syntax-highlight)
1261 /// ['🙈', '🙊', '🙉']
1265 /// .collect::<String>()
1270 /// ```ignore (cannot-doctest-external-file-dependency)
1272 /// let my_string = include!("monkeys.in");
1273 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1274 /// println!("{}", my_string);
1278 /// Compiling 'main.rs' and running the resulting binary will print
1279 /// "🙈🙊🙉🙈🙊🙉".
1280 #[stable(feature = "rust1", since = "1.0.0")]
1281 #[rustc_builtin_macro]
1283 macro_rules! include {
1284 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1287 /// Asserts that a boolean expression is `true` at runtime.
1289 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1290 /// evaluated to `true` at runtime.
1294 /// Assertions are always checked in both debug and release builds, and cannot
1295 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1296 /// release builds by default.
1298 /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if
1299 /// violated could lead to unsafety.
1301 /// Other use-cases of `assert!` include testing and enforcing run-time
1302 /// invariants in safe code (whose violation cannot result in unsafety).
1304 /// # Custom Messages
1306 /// This macro has a second form, where a custom panic message can
1307 /// be provided with or without arguments for formatting. See [`std::fmt`]
1308 /// for syntax for this form. Expressions used as format arguments will only
1309 /// be evaluated if the assertion fails.
1311 /// [`std::fmt`]: ../std/fmt/index.html
1316 /// // the panic message for these assertions is the stringified value of the
1317 /// // expression given.
1320 /// fn some_computation() -> bool { true } // a very simple function
1322 /// assert!(some_computation());
1324 /// // assert with a custom message
1326 /// assert!(x, "x wasn't true!");
1328 /// let a = 3; let b = 27;
1329 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 #[rustc_builtin_macro]
1334 #[rustc_diagnostic_item = "assert_macro"]
1335 #[allow_internal_unstable(core_panic, edition_panic)]
1336 macro_rules! assert {
1337 ($cond:expr $(,)?) => {{ /* compiler built-in */ }};
1338 ($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }};
1341 /// LLVM-style inline assembly.
1343 /// Read the [unstable book] for the usage.
1345 /// [unstable book]: ../unstable-book/library-features/llvm-asm.html
1347 feature = "llvm_asm",
1349 reason = "prefer using the new asm! syntax instead"
1353 reason = "will be removed from the compiler, use asm! instead"
1355 #[rustc_builtin_macro]
1357 macro_rules! llvm_asm {
1358 ("assembly template"
1359 : $("output"(operand),)*
1360 : $("input"(operand),)*
1362 : $("options",)*) => {
1363 /* compiler built-in */
1367 /// Prints passed tokens into the standard output.
1369 feature = "log_syntax",
1371 reason = "`log_syntax!` is not stable enough for use and is subject to change"
1373 #[rustc_builtin_macro]
1375 macro_rules! log_syntax {
1377 /* compiler built-in */
1381 /// Enables or disables tracing functionality used for debugging other macros.
1383 feature = "trace_macros",
1385 reason = "`trace_macros` is not stable enough for use and is subject to change"
1387 #[rustc_builtin_macro]
1389 macro_rules! trace_macros {
1390 (true) => {{ /* compiler built-in */ }};
1391 (false) => {{ /* compiler built-in */ }};
1394 /// Attribute macro used to apply derive macros.
1395 #[stable(feature = "rust1", since = "1.0.0")]
1396 #[rustc_builtin_macro]
1397 pub macro derive($item:item) {
1398 /* compiler built-in */
1401 /// Attribute macro applied to a function to turn it into a unit test.
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 #[allow_internal_unstable(test, rustc_attrs)]
1404 #[rustc_builtin_macro]
1405 pub macro test($item:item) {
1406 /* compiler built-in */
1409 /// Attribute macro applied to a function to turn it into a benchmark test.
1414 reason = "`bench` is a part of custom test frameworks which are unstable"
1416 #[allow_internal_unstable(test, rustc_attrs)]
1417 #[rustc_builtin_macro]
1418 pub macro bench($item:item) {
1419 /* compiler built-in */
1422 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1424 feature = "custom_test_frameworks",
1426 reason = "custom test frameworks are an unstable feature"
1428 #[allow_internal_unstable(test, rustc_attrs)]
1429 #[rustc_builtin_macro]
1430 pub macro test_case($item:item) {
1431 /* compiler built-in */
1434 /// Attribute macro applied to a static to register it as a global allocator.
1436 /// See also [`std::alloc::GlobalAlloc`](../std/alloc/trait.GlobalAlloc.html).
1437 #[stable(feature = "global_allocator", since = "1.28.0")]
1438 #[allow_internal_unstable(rustc_attrs)]
1439 #[rustc_builtin_macro]
1440 pub macro global_allocator($item:item) {
1441 /* compiler built-in */
1444 /// Keeps the item it's applied to if the passed path is accessible, and removes it otherwise.
1446 feature = "cfg_accessible",
1448 reason = "`cfg_accessible` is not fully implemented"
1450 #[rustc_builtin_macro]
1451 pub macro cfg_accessible($item:item) {
1452 /* compiler built-in */
1455 /// Expands all `#[cfg]` and `#[cfg_attr]` attributes in the code fragment it's applied to.
1457 feature = "cfg_eval",
1459 reason = "`cfg_eval` is a recently implemented feature"
1461 #[rustc_builtin_macro]
1462 pub macro cfg_eval($($tt:tt)*) {
1463 /* compiler built-in */
1466 /// Unstable implementation detail of the `rustc` compiler, do not use.
1467 #[rustc_builtin_macro]
1468 #[stable(feature = "rust1", since = "1.0.0")]
1469 #[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
1472 reason = "rustc-serialize is deprecated and no longer supported"
1474 pub macro RustcDecodable($item:item) {
1475 /* compiler built-in */
1478 /// Unstable implementation detail of the `rustc` compiler, do not use.
1479 #[rustc_builtin_macro]
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 #[allow_internal_unstable(core_intrinsics)]
1484 reason = "rustc-serialize is deprecated and no longer supported"
1486 pub macro RustcEncodable($item:item) {
1487 /* compiler built-in */