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 #[cfg_attr(not(test), rustc_diagnostic_item = "assert_eq_macro")]
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 #[cfg_attr(not(test), rustc_diagnostic_item = "assert_ne_macro")]
85 #[allow_internal_unstable(core_panic)]
86 macro_rules! assert_ne {
87 ($left:expr, $right:expr $(,)?) => ({
88 match (&$left, &$right) {
89 (left_val, right_val) => {
90 if *left_val == *right_val {
91 let kind = $crate::panicking::AssertKind::Ne;
92 // The reborrows below are intentional. Without them, the stack slot for the
93 // borrow is initialized even before the values are compared, leading to a
94 // noticeable slow down.
95 $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None);
100 ($left:expr, $right:expr, $($arg:tt)+) => ({
101 match (&($left), &($right)) {
102 (left_val, right_val) => {
103 if *left_val == *right_val {
104 let kind = $crate::panicking::AssertKind::Ne;
105 // The reborrows below are intentional. Without them, the stack slot for the
106 // borrow is initialized even before the values are compared, leading to a
107 // noticeable slow down.
108 $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::Some($crate::format_args!($($arg)+)));
115 /// Asserts that an expression matches any of the given patterns.
117 /// Like in a `match` expression, the pattern can be optionally followed by `if`
118 /// and a guard expression that has access to names bound by the pattern.
120 /// On panic, this macro will print the value of the expression with its
121 /// debug representation.
123 /// Like [`assert!`], this macro has a second form, where a custom
124 /// panic message can be provided.
129 /// #![feature(assert_matches)]
131 /// use std::assert_matches::assert_matches;
133 /// let a = 1u32.checked_add(2);
134 /// let b = 1u32.checked_sub(2);
135 /// assert_matches!(a, Some(_));
136 /// assert_matches!(b, None);
138 /// let c = Ok("abc".to_string());
139 /// assert_matches!(c, Ok(x) | Err(x) if x.len() < 100);
141 #[unstable(feature = "assert_matches", issue = "82775")]
142 #[allow_internal_unstable(core_panic)]
143 #[rustc_macro_transparency = "semitransparent"]
144 pub macro assert_matches {
145 ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => ({
147 $( $pattern )|+ $( if $guard )? => {}
149 $crate::panicking::assert_matches_failed(
151 $crate::stringify!($($pattern)|+ $(if $guard)?),
152 $crate::option::Option::None
157 ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )?, $($arg:tt)+) => ({
159 $( $pattern )|+ $( if $guard )? => {}
161 $crate::panicking::assert_matches_failed(
163 $crate::stringify!($($pattern)|+ $(if $guard)?),
164 $crate::option::Option::Some($crate::format_args!($($arg)+))
171 /// Asserts that a boolean expression is `true` at runtime.
173 /// This will invoke the [`panic!`] macro if the provided expression cannot be
174 /// evaluated to `true` at runtime.
176 /// Like [`assert!`], this macro also has a second version, where a custom panic
177 /// message can be provided.
181 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
182 /// optimized builds by default. An optimized build will not execute
183 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
184 /// compiler. This makes `debug_assert!` useful for checks that are too
185 /// expensive to be present in a release build but may be helpful during
186 /// development. The result of expanding `debug_assert!` is always type checked.
188 /// An unchecked assertion allows a program in an inconsistent state to keep
189 /// running, which might have unexpected consequences but does not introduce
190 /// unsafety as long as this only happens in safe code. The performance cost
191 /// of assertions, however, is not measurable in general. Replacing [`assert!`]
192 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
193 /// more importantly, only in safe code!
198 /// // the panic message for these assertions is the stringified value of the
199 /// // expression given.
200 /// debug_assert!(true);
202 /// fn some_expensive_computation() -> bool { true } // a very simple function
203 /// debug_assert!(some_expensive_computation());
205 /// // assert with a custom message
207 /// debug_assert!(x, "x wasn't true!");
209 /// let a = 3; let b = 27;
210 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
213 #[stable(feature = "rust1", since = "1.0.0")]
214 #[rustc_diagnostic_item = "debug_assert_macro"]
215 #[allow_internal_unstable(edition_panic)]
216 macro_rules! debug_assert {
217 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert!($($arg)*); })
220 /// Asserts that two expressions are equal to each other.
222 /// On panic, this macro will print the values of the expressions with their
223 /// debug representations.
225 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
226 /// optimized builds by default. An optimized build will not execute
227 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
228 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
229 /// expensive to be present in a release build but may be helpful during
230 /// development. The result of expanding `debug_assert_eq!` is always type checked.
237 /// debug_assert_eq!(a, b);
240 #[stable(feature = "rust1", since = "1.0.0")]
241 #[cfg_attr(not(test), rustc_diagnostic_item = "debug_assert_eq_macro")]
242 macro_rules! debug_assert_eq {
243 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_eq!($($arg)*); })
246 /// Asserts that two expressions are not equal to each other.
248 /// On panic, this macro will print the values of the expressions with their
249 /// debug representations.
251 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
252 /// optimized builds by default. An optimized build will not execute
253 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
254 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
255 /// expensive to be present in a release build but may be helpful during
256 /// development. The result of expanding `debug_assert_ne!` is always type checked.
263 /// debug_assert_ne!(a, b);
266 #[stable(feature = "assert_ne", since = "1.13.0")]
267 #[cfg_attr(not(test), rustc_diagnostic_item = "debug_assert_ne_macro")]
268 macro_rules! debug_assert_ne {
269 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_ne!($($arg)*); })
272 /// Asserts that an expression matches any of the given patterns.
274 /// Like in a `match` expression, the pattern can be optionally followed by `if`
275 /// and a guard expression that has access to names bound by the pattern.
277 /// On panic, this macro will print the value of the expression with its
278 /// debug representation.
280 /// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only
281 /// enabled in non optimized builds by default. An optimized build will not
282 /// execute `debug_assert_matches!` statements unless `-C debug-assertions` is
283 /// passed to the compiler. This makes `debug_assert_matches!` useful for
284 /// checks that are too expensive to be present in a release build but may be
285 /// helpful during development. The result of expanding `debug_assert_matches!`
286 /// is always type checked.
291 /// #![feature(assert_matches)]
293 /// use std::assert_matches::debug_assert_matches;
295 /// let a = 1u32.checked_add(2);
296 /// let b = 1u32.checked_sub(2);
297 /// debug_assert_matches!(a, Some(_));
298 /// debug_assert_matches!(b, None);
300 /// let c = Ok("abc".to_string());
301 /// debug_assert_matches!(c, Ok(x) | Err(x) if x.len() < 100);
304 #[unstable(feature = "assert_matches", issue = "82775")]
305 #[allow_internal_unstable(assert_matches)]
306 #[rustc_macro_transparency = "semitransparent"]
307 pub macro debug_assert_matches($($arg:tt)*) {
308 if $crate::cfg!(debug_assertions) { $crate::assert_matches::assert_matches!($($arg)*); }
311 /// Returns whether the given expression matches any of the given patterns.
313 /// Like in a `match` expression, the pattern can be optionally followed by `if`
314 /// and a guard expression that has access to names bound by the pattern.
320 /// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
322 /// let bar = Some(4);
323 /// assert!(matches!(bar, Some(x) if x > 2));
326 #[stable(feature = "matches_macro", since = "1.42.0")]
327 #[cfg_attr(not(test), rustc_diagnostic_item = "matches_macro")]
328 macro_rules! matches {
329 ($expression:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => {
331 $( $pattern )|+ $( if $guard )? => true,
337 /// Unwraps a result or propagates its error.
339 /// The `?` operator was added to replace `try!` and should be used instead.
340 /// Furthermore, `try` is a reserved word in Rust 2018, so if you must use
341 /// it, you will need to use the [raw-identifier syntax][ris]: `r#try`.
343 /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
345 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
346 /// expression has the value of the wrapped value.
348 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
349 /// performs conversion using `From`. This provides automatic conversion
350 /// between specialized errors and more general ones. The resulting
351 /// error is then immediately returned.
353 /// Because of the early return, `try!` can only be used in functions that
354 /// return [`Result`].
360 /// use std::fs::File;
361 /// use std::io::prelude::*;
367 /// impl From<io::Error> for MyError {
368 /// fn from(e: io::Error) -> MyError {
369 /// MyError::FileWriteError
373 /// // The preferred method of quick returning Errors
374 /// fn write_to_file_question() -> Result<(), MyError> {
375 /// let mut file = File::create("my_best_friends.txt")?;
376 /// file.write_all(b"This is a list of my best friends.")?;
380 /// // The previous method of quick returning Errors
381 /// fn write_to_file_using_try() -> Result<(), MyError> {
382 /// let mut file = r#try!(File::create("my_best_friends.txt"));
383 /// r#try!(file.write_all(b"This is a list of my best friends."));
387 /// // This is equivalent to:
388 /// fn write_to_file_using_match() -> Result<(), MyError> {
389 /// let mut file = r#try!(File::create("my_best_friends.txt"));
390 /// match file.write_all(b"This is a list of my best friends.") {
392 /// Err(e) => return Err(From::from(e)),
398 #[stable(feature = "rust1", since = "1.0.0")]
399 #[rustc_deprecated(since = "1.39.0", reason = "use the `?` operator instead")]
402 ($expr:expr $(,)?) => {
404 $crate::result::Result::Ok(val) => val,
405 $crate::result::Result::Err(err) => {
406 return $crate::result::Result::Err($crate::convert::From::from(err));
412 /// Writes formatted data into a buffer.
414 /// This macro accepts a 'writer', a format string, and a list of arguments. Arguments will be
415 /// formatted according to the specified format string and the result will be passed to the writer.
416 /// The writer may be any value with a `write_fmt` method; generally this comes from an
417 /// implementation of either the [`fmt::Write`] or the [`io::Write`] trait. The macro
418 /// returns whatever the `write_fmt` method returns; commonly a [`fmt::Result`], or an
421 /// See [`std::fmt`] for more information on the format string syntax.
423 /// [`std::fmt`]: ../std/fmt/index.html
424 /// [`fmt::Write`]: crate::fmt::Write
425 /// [`io::Write`]: ../std/io/trait.Write.html
426 /// [`fmt::Result`]: crate::fmt::Result
427 /// [`io::Result`]: ../std/io/type.Result.html
432 /// use std::io::Write;
434 /// fn main() -> std::io::Result<()> {
435 /// let mut w = Vec::new();
436 /// write!(&mut w, "test")?;
437 /// write!(&mut w, "formatted {}", "arguments")?;
439 /// assert_eq!(w, b"testformatted arguments");
444 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
445 /// implementing either, as objects do not typically implement both. However, the module must
446 /// import the traits qualified so their names do not conflict:
449 /// use std::fmt::Write as FmtWrite;
450 /// use std::io::Write as IoWrite;
452 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
453 /// let mut s = String::new();
454 /// let mut v = Vec::new();
456 /// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
457 /// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
458 /// assert_eq!(v, b"s = \"abc 123\"");
463 /// Note: This macro can be used in `no_std` setups as well.
464 /// In a `no_std` setup you are responsible for the implementation details of the components.
467 /// # extern crate core;
468 /// use core::fmt::Write;
472 /// impl Write for Example {
473 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
474 /// unimplemented!();
478 /// let mut m = Example{};
479 /// write!(&mut m, "Hello World").expect("Not written");
482 #[stable(feature = "rust1", since = "1.0.0")]
483 #[cfg_attr(not(test), rustc_diagnostic_item = "write_macro")]
485 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt($crate::format_args!($($arg)*)))
488 /// Write formatted data into a buffer, with a newline appended.
490 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
491 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
493 /// For more information, see [`write!`]. For information on the format string syntax, see
496 /// [`std::fmt`]: ../std/fmt/index.html
501 /// use std::io::{Write, Result};
503 /// fn main() -> Result<()> {
504 /// let mut w = Vec::new();
505 /// writeln!(&mut w)?;
506 /// writeln!(&mut w, "test")?;
507 /// writeln!(&mut w, "formatted {}", "arguments")?;
509 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
514 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
515 /// implementing either, as objects do not typically implement both. However, the module must
516 /// import the traits qualified so their names do not conflict:
519 /// use std::fmt::Write as FmtWrite;
520 /// use std::io::Write as IoWrite;
522 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
523 /// let mut s = String::new();
524 /// let mut v = Vec::new();
526 /// writeln!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
527 /// writeln!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
528 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
533 #[stable(feature = "rust1", since = "1.0.0")]
534 #[cfg_attr(not(test), rustc_diagnostic_item = "writeln_macro")]
535 #[allow_internal_unstable(format_args_nl)]
536 macro_rules! writeln {
537 ($dst:expr $(,)?) => (
538 $crate::write!($dst, "\n")
540 ($dst:expr, $($arg:tt)*) => (
541 $dst.write_fmt($crate::format_args_nl!($($arg)*))
545 /// Indicates unreachable code.
547 /// This is useful any time that the compiler can't determine that some code is unreachable. For
550 /// * Match arms with guard conditions.
551 /// * Loops that dynamically terminate.
552 /// * Iterators that dynamically terminate.
554 /// If the determination that the code is unreachable proves incorrect, the
555 /// program immediately terminates with a [`panic!`].
557 /// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
558 /// will cause undefined behavior if the code is reached.
560 /// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked
564 /// This will always [`panic!`] because `unreachable!` is just a shorthand for `panic!` with a
565 /// fixed, specific message.
567 /// Like `panic!`, this macro has a second form for displaying custom values.
574 /// # #[allow(dead_code)]
575 /// fn foo(x: Option<i32>) {
577 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
578 /// Some(n) if n < 0 => println!("Some(Negative)"),
579 /// Some(_) => unreachable!(), // compile error if commented out
580 /// None => println!("None")
588 /// # #[allow(dead_code)]
589 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
591 /// if 3*i < i { panic!("u32 overflow"); }
592 /// if x < 3*i { return i-1; }
594 /// unreachable!("The loop should always return");
598 #[rustc_builtin_macro(unreachable)]
599 #[allow_internal_unstable(edition_panic)]
600 #[stable(feature = "rust1", since = "1.0.0")]
601 #[cfg_attr(not(test), rustc_diagnostic_item = "unreachable_macro")]
602 macro_rules! unreachable {
603 // Expands to either `$crate::panic::unreachable_2015` or `$crate::panic::unreachable_2021`
604 // depending on the edition of the caller.
606 /* compiler built-in */
610 /// Indicates unimplemented code by panicking with a message of "not implemented".
612 /// This allows your code to type-check, which is useful if you are prototyping or
613 /// implementing a trait that requires multiple methods which you don't plan to use all of.
615 /// The difference between `unimplemented!` and [`todo!`] is that while `todo!`
616 /// conveys an intent of implementing the functionality later and the message is "not yet
617 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
618 /// Also some IDEs will mark `todo!`s.
622 /// This will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a
623 /// fixed, specific message.
625 /// Like `panic!`, this macro has a second form for displaying custom values.
629 /// Say we have a trait `Foo`:
633 /// fn bar(&self) -> u8;
635 /// fn qux(&self) -> Result<u64, ()>;
639 /// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
640 /// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
641 /// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
642 /// to allow our code to compile.
644 /// We still want to have our program stop running if the unimplemented methods are
649 /// # fn bar(&self) -> u8;
651 /// # fn qux(&self) -> Result<u64, ()>;
655 /// impl Foo for MyStruct {
656 /// fn bar(&self) -> u8 {
661 /// // It makes no sense to `baz` a `MyStruct`, so we have no logic here
663 /// // This will display "thread 'main' panicked at 'not implemented'".
664 /// unimplemented!();
667 /// fn qux(&self) -> Result<u64, ()> {
668 /// // We have some logic here,
669 /// // We can add a message to unimplemented! to display our omission.
670 /// // This will display:
671 /// // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
672 /// unimplemented!("MyStruct isn't quxable");
677 /// let s = MyStruct;
682 #[stable(feature = "rust1", since = "1.0.0")]
683 #[cfg_attr(not(test), rustc_diagnostic_item = "unimplemented_macro")]
684 #[allow_internal_unstable(core_panic)]
685 macro_rules! unimplemented {
686 () => ($crate::panicking::panic("not implemented"));
687 ($($arg:tt)+) => ($crate::panic!("not implemented: {}", $crate::format_args!($($arg)+)));
690 /// Indicates unfinished code.
692 /// This can be useful if you are prototyping and are just looking to have your
695 /// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
696 /// an intent of implementing the functionality later and the message is "not yet
697 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
698 /// Also some IDEs will mark `todo!`s.
702 /// This will always [`panic!`].
706 /// Here's an example of some in-progress code. We have a trait `Foo`:
715 /// We want to implement `Foo` on one of our types, but we also want to work on
716 /// just `bar()` first. In order for our code to compile, we need to implement
717 /// `baz()`, so we can use `todo!`:
726 /// impl Foo for MyStruct {
728 /// // implementation goes here
732 /// // let's not worry about implementing baz() for now
738 /// let s = MyStruct;
741 /// // we aren't even using baz(), so this is fine.
745 #[stable(feature = "todo_macro", since = "1.40.0")]
746 #[cfg_attr(not(test), rustc_diagnostic_item = "todo_macro")]
747 #[allow_internal_unstable(core_panic)]
749 () => ($crate::panicking::panic("not yet implemented"));
750 ($($arg:tt)+) => ($crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
753 /// Definitions of built-in macros.
755 /// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
756 /// with exception of expansion functions transforming macro inputs into outputs,
757 /// those functions are provided by the compiler.
758 pub(crate) mod builtin {
760 /// Causes compilation to fail with the given error message when encountered.
762 /// This macro should be used when a crate uses a conditional compilation strategy to provide
763 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
764 /// but emits an error during *compilation* rather than at *runtime*.
768 /// Two such examples are macros and `#[cfg]` environments.
770 /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
771 /// the compiler would still emit an error, but the error's message would not mention the two
775 /// macro_rules! give_me_foo_or_bar {
779 /// compile_error!("This macro only accepts `foo` or `bar`");
783 /// give_me_foo_or_bar!(neither);
784 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
787 /// Emit compiler error if one of a number of features isn't available.
790 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
791 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
793 #[stable(feature = "compile_error_macro", since = "1.20.0")]
794 #[rustc_builtin_macro]
796 #[cfg_attr(not(test), rustc_diagnostic_item = "compile_error_macro")]
797 macro_rules! compile_error {
798 ($msg:expr $(,)?) => {{ /* compiler built-in */ }};
801 /// Constructs parameters for the other string-formatting macros.
803 /// This macro functions by taking a formatting string literal containing
804 /// `{}` for each additional argument passed. `format_args!` prepares the
805 /// additional parameters to ensure the output can be interpreted as a string
806 /// and canonicalizes the arguments into a single type. Any value that implements
807 /// the [`Display`] trait can be passed to `format_args!`, as can any
808 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
810 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
811 /// passed to the macros within [`std::fmt`] for performing useful redirection.
812 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
813 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
814 /// heap allocations.
816 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
817 /// in `Debug` and `Display` contexts as seen below. The example also shows
818 /// that `Debug` and `Display` format to the same thing: the interpolated
819 /// format string in `format_args!`.
822 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
823 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
824 /// assert_eq!("1 foo 2", display);
825 /// assert_eq!(display, debug);
828 /// For more information, see the documentation in [`std::fmt`].
830 /// [`Display`]: crate::fmt::Display
831 /// [`Debug`]: crate::fmt::Debug
832 /// [`fmt::Arguments`]: crate::fmt::Arguments
833 /// [`std::fmt`]: ../std/fmt/index.html
834 /// [`format!`]: ../std/macro.format.html
835 /// [`println!`]: ../std/macro.println.html
842 /// let s = fmt::format(format_args!("hello {}", "world"));
843 /// assert_eq!(s, format!("hello {}", "world"));
845 #[stable(feature = "rust1", since = "1.0.0")]
846 #[cfg_attr(not(test), rustc_diagnostic_item = "format_args_macro")]
847 #[allow_internal_unsafe]
848 #[allow_internal_unstable(fmt_internals)]
849 #[rustc_builtin_macro]
851 macro_rules! format_args {
852 ($fmt:expr) => {{ /* compiler built-in */ }};
853 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
856 /// Same as [`format_args`], but can be used in some const contexts.
858 /// This macro is used by the panic macros for the `const_panic` feature.
860 /// This macro will be removed once `format_args` is allowed in const contexts.
861 #[unstable(feature = "const_format_args", issue = "none")]
862 #[allow_internal_unstable(fmt_internals, const_fmt_arguments_new)]
863 #[rustc_builtin_macro]
865 macro_rules! const_format_args {
866 ($fmt:expr) => {{ /* compiler built-in */ }};
867 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
870 /// Same as [`format_args`], but adds a newline in the end.
872 feature = "format_args_nl",
874 reason = "`format_args_nl` is only for internal \
875 language use and is subject to change"
877 #[allow_internal_unstable(fmt_internals)]
878 #[rustc_builtin_macro]
880 macro_rules! format_args_nl {
881 ($fmt:expr) => {{ /* compiler built-in */ }};
882 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
885 /// Inspects an environment variable at compile time.
887 /// This macro will expand to the value of the named environment variable at
888 /// compile time, yielding an expression of type `&'static str`.
890 /// If the environment variable is not defined, then a compilation error
891 /// will be emitted. To not emit a compile error, use the [`option_env!`]
897 /// let path: &'static str = env!("PATH");
898 /// println!("the $PATH variable at the time of compiling was: {}", path);
901 /// You can customize the error message by passing a string as the second
905 /// let doc: &'static str = env!("documentation", "what's that?!");
908 /// If the `documentation` environment variable is not defined, you'll get
909 /// the following error:
912 /// error: what's that?!
914 #[stable(feature = "rust1", since = "1.0.0")]
915 #[rustc_builtin_macro]
917 #[cfg_attr(not(test), rustc_diagnostic_item = "env_macro")]
919 ($name:expr $(,)?) => {{ /* compiler built-in */ }};
920 ($name:expr, $error_msg:expr $(,)?) => {{ /* compiler built-in */ }};
923 /// Optionally inspects an environment variable at compile time.
925 /// If the named environment variable is present at compile time, this will
926 /// expand into an expression of type `Option<&'static str>` whose value is
927 /// `Some` of the value of the environment variable. If the environment
928 /// variable is not present, then this will expand to `None`. See
929 /// [`Option<T>`][Option] for more information on this type.
931 /// A compile time error is never emitted when using this macro regardless
932 /// of whether the environment variable is present or not.
937 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
938 /// println!("the secret key might be: {:?}", key);
940 #[stable(feature = "rust1", since = "1.0.0")]
941 #[rustc_builtin_macro]
943 #[cfg_attr(not(test), rustc_diagnostic_item = "option_env_macro")]
944 macro_rules! option_env {
945 ($name:expr $(,)?) => {{ /* compiler built-in */ }};
948 /// Concatenates identifiers into one identifier.
950 /// This macro takes any number of comma-separated identifiers, and
951 /// concatenates them all into one, yielding an expression which is a new
952 /// identifier. Note that hygiene makes it such that this macro cannot
953 /// capture local variables. Also, as a general rule, macros are only
954 /// allowed in item, statement or expression position. That means while
955 /// you may use this macro for referring to existing variables, functions or
956 /// modules etc, you cannot define a new one with it.
961 /// #![feature(concat_idents)]
964 /// fn foobar() -> u32 { 23 }
966 /// let f = concat_idents!(foo, bar);
967 /// println!("{}", f());
969 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
973 feature = "concat_idents",
975 reason = "`concat_idents` is not stable enough for use and is subject to change"
977 #[rustc_builtin_macro]
979 macro_rules! concat_idents {
980 ($($e:ident),+ $(,)?) => {{ /* compiler built-in */ }};
983 /// Concatenates literals into a byte slice.
985 /// This macro takes any number of comma-separated literals, and concatenates them all into
986 /// one, yielding an expression of type `&[u8, _]`, which represents all of the literals
987 /// concatenated left-to-right. The literals passed can be any combination of:
989 /// - byte literals (`b'r'`)
990 /// - byte strings (`b"Rust"`)
991 /// - arrays of bytes/numbers (`[b'A', 66, b'C']`)
996 /// #![feature(concat_bytes)]
999 /// let s: &[u8; 6] = concat_bytes!(b'A', b"BC", [68, b'E', 70]);
1000 /// assert_eq!(s, b"ABCDEF");
1003 #[unstable(feature = "concat_bytes", issue = "87555")]
1004 #[rustc_builtin_macro]
1006 macro_rules! concat_bytes {
1007 ($($e:literal),+ $(,)?) => {{ /* compiler built-in */ }};
1010 /// Concatenates literals into a static string slice.
1012 /// This macro takes any number of comma-separated literals, yielding an
1013 /// expression of type `&'static str` which represents all of the literals
1014 /// concatenated left-to-right.
1016 /// Integer and floating point literals are stringified in order to be
1022 /// let s = concat!("test", 10, 'b', true);
1023 /// assert_eq!(s, "test10btrue");
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 #[rustc_builtin_macro]
1028 #[cfg_attr(not(test), rustc_diagnostic_item = "concat_macro")]
1029 macro_rules! concat {
1030 ($($e:expr),* $(,)?) => {{ /* compiler built-in */ }};
1033 /// Expands to the line number on which it was invoked.
1035 /// With [`column!`] and [`file!`], these macros provide debugging information for
1036 /// developers about the location within the source.
1038 /// The expanded expression has type `u32` and is 1-based, so the first line
1039 /// in each file evaluates to 1, the second to 2, etc. This is consistent
1040 /// with error messages by common compilers or popular editors.
1041 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
1042 /// but rather the first macro invocation leading up to the invocation
1043 /// of the `line!` macro.
1048 /// let current_line = line!();
1049 /// println!("defined on line: {}", current_line);
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 #[rustc_builtin_macro]
1054 #[cfg_attr(not(test), rustc_diagnostic_item = "line_macro")]
1057 /* compiler built-in */
1061 /// Expands to the column number at which it was invoked.
1063 /// With [`line!`] and [`file!`], these macros provide debugging information for
1064 /// developers about the location within the source.
1066 /// The expanded expression has type `u32` and is 1-based, so the first column
1067 /// in each line evaluates to 1, the second to 2, etc. This is consistent
1068 /// with error messages by common compilers or popular editors.
1069 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
1070 /// but rather the first macro invocation leading up to the invocation
1071 /// of the `column!` macro.
1076 /// let current_col = column!();
1077 /// println!("defined on column: {}", current_col);
1080 /// `column!` counts Unicode code points, not bytes or graphemes. As a result, the first two
1081 /// invocations return the same value, but the third does not.
1084 /// let a = ("foobar", column!()).1;
1085 /// let b = ("人之初性本善", column!()).1;
1086 /// let c = ("f̅o̅o̅b̅a̅r̅", column!()).1; // Uses combining overline (U+0305)
1088 /// assert_eq!(a, b);
1089 /// assert_ne!(b, c);
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 #[rustc_builtin_macro]
1094 #[cfg_attr(not(test), rustc_diagnostic_item = "column_macro")]
1095 macro_rules! column {
1097 /* compiler built-in */
1101 /// Expands to the file name in which it was invoked.
1103 /// With [`line!`] and [`column!`], these macros provide debugging information for
1104 /// developers about the location within the source.
1106 /// The expanded expression has type `&'static str`, and the returned file
1107 /// is not the invocation of the `file!` macro itself, but rather the
1108 /// first macro invocation leading up to the invocation of the `file!`
1114 /// let this_file = file!();
1115 /// println!("defined in file: {}", this_file);
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 #[rustc_builtin_macro]
1120 #[cfg_attr(not(test), rustc_diagnostic_item = "file_macro")]
1123 /* compiler built-in */
1127 /// Stringifies its arguments.
1129 /// This macro will yield an expression of type `&'static str` which is the
1130 /// stringification of all the tokens passed to the macro. No restrictions
1131 /// are placed on the syntax of the macro invocation itself.
1133 /// Note that the expanded results of the input tokens may change in the
1134 /// future. You should be careful if you rely on the output.
1139 /// let one_plus_one = stringify!(1 + 1);
1140 /// assert_eq!(one_plus_one, "1 + 1");
1142 #[stable(feature = "rust1", since = "1.0.0")]
1143 #[rustc_builtin_macro]
1145 #[cfg_attr(not(test), rustc_diagnostic_item = "stringify_macro")]
1146 macro_rules! stringify {
1148 /* compiler built-in */
1152 /// Includes a UTF-8 encoded file as a string.
1154 /// The file is located relative to the current file (similarly to how
1155 /// modules are found). The provided path is interpreted in a platform-specific
1156 /// way at compile time. So, for instance, an invocation with a Windows path
1157 /// containing backslashes `\` would not compile correctly on Unix.
1159 /// This macro will yield an expression of type `&'static str` which is the
1160 /// contents of the file.
1164 /// Assume there are two files in the same directory with the following
1167 /// File 'spanish.in':
1175 /// ```ignore (cannot-doctest-external-file-dependency)
1177 /// let my_str = include_str!("spanish.in");
1178 /// assert_eq!(my_str, "adiós\n");
1179 /// print!("{}", my_str);
1183 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 #[rustc_builtin_macro]
1187 #[cfg_attr(not(test), rustc_diagnostic_item = "include_str_macro")]
1188 macro_rules! include_str {
1189 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1192 /// Includes a file as a reference to a byte array.
1194 /// The file is located relative to the current file (similarly to how
1195 /// modules are found). The provided path is interpreted in a platform-specific
1196 /// way at compile time. So, for instance, an invocation with a Windows path
1197 /// containing backslashes `\` would not compile correctly on Unix.
1199 /// This macro will yield an expression of type `&'static [u8; N]` which is
1200 /// the contents of the file.
1204 /// Assume there are two files in the same directory with the following
1207 /// File 'spanish.in':
1215 /// ```ignore (cannot-doctest-external-file-dependency)
1217 /// let bytes = include_bytes!("spanish.in");
1218 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
1219 /// print!("{}", String::from_utf8_lossy(bytes));
1223 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1224 #[stable(feature = "rust1", since = "1.0.0")]
1225 #[rustc_builtin_macro]
1227 #[cfg_attr(not(test), rustc_diagnostic_item = "include_bytes_macro")]
1228 macro_rules! include_bytes {
1229 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1232 /// Expands to a string that represents the current module path.
1234 /// The current module path can be thought of as the hierarchy of modules
1235 /// leading back up to the crate root. The first component of the path
1236 /// returned is the name of the crate currently being compiled.
1243 /// assert!(module_path!().ends_with("test"));
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 #[rustc_builtin_macro]
1252 #[cfg_attr(not(test), rustc_diagnostic_item = "module_path_macro")]
1253 macro_rules! module_path {
1255 /* compiler built-in */
1259 /// Evaluates boolean combinations of configuration flags at compile-time.
1261 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1262 /// boolean expression evaluation of configuration flags. This frequently
1263 /// leads to less duplicated code.
1265 /// The syntax given to this macro is the same syntax as the [`cfg`]
1268 /// `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For
1269 /// example, all blocks in an if/else expression need to be valid when `cfg!` is used for
1270 /// the condition, regardless of what `cfg!` is evaluating.
1272 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1277 /// let my_directory = if cfg!(windows) {
1278 /// "windows-specific-directory"
1280 /// "unix-directory"
1283 #[stable(feature = "rust1", since = "1.0.0")]
1284 #[rustc_builtin_macro]
1286 #[cfg_attr(not(test), rustc_diagnostic_item = "cfg_macro")]
1289 /* compiler built-in */
1293 /// Parses a file as an expression or an item according to the context.
1295 /// The file is located relative to the current file (similarly to how
1296 /// modules are found). The provided path is interpreted in a platform-specific
1297 /// way at compile time. So, for instance, an invocation with a Windows path
1298 /// containing backslashes `\` would not compile correctly on Unix.
1300 /// Using this macro is often a bad idea, because if the file is
1301 /// parsed as an expression, it is going to be placed in the
1302 /// surrounding code unhygienically. This could result in variables
1303 /// or functions being different from what the file expected if
1304 /// there are variables or functions that have the same name in
1305 /// the current file.
1309 /// Assume there are two files in the same directory with the following
1312 /// File 'monkeys.in':
1314 /// ```ignore (only-for-syntax-highlight)
1319 /// .collect::<String>()
1324 /// ```ignore (cannot-doctest-external-file-dependency)
1326 /// let my_string = include!("monkeys.in");
1327 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1328 /// println!("{}", my_string);
1332 /// Compiling 'main.rs' and running the resulting binary will print
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 #[rustc_builtin_macro]
1337 #[cfg_attr(not(test), rustc_diagnostic_item = "include_macro")]
1338 macro_rules! include {
1339 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1342 /// Asserts that a boolean expression is `true` at runtime.
1344 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1345 /// evaluated to `true` at runtime.
1349 /// Assertions are always checked in both debug and release builds, and cannot
1350 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1351 /// release builds by default.
1353 /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if
1354 /// violated could lead to unsafety.
1356 /// Other use-cases of `assert!` include testing and enforcing run-time
1357 /// invariants in safe code (whose violation cannot result in unsafety).
1359 /// # Custom Messages
1361 /// This macro has a second form, where a custom panic message can
1362 /// be provided with or without arguments for formatting. See [`std::fmt`]
1363 /// for syntax for this form. Expressions used as format arguments will only
1364 /// be evaluated if the assertion fails.
1366 /// [`std::fmt`]: ../std/fmt/index.html
1371 /// // the panic message for these assertions is the stringified value of the
1372 /// // expression given.
1375 /// fn some_computation() -> bool { true } // a very simple function
1377 /// assert!(some_computation());
1379 /// // assert with a custom message
1381 /// assert!(x, "x wasn't true!");
1383 /// let a = 3; let b = 27;
1384 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 #[rustc_builtin_macro]
1389 #[rustc_diagnostic_item = "assert_macro"]
1390 #[allow_internal_unstable(core_panic, edition_panic)]
1391 macro_rules! assert {
1392 ($cond:expr $(,)?) => {{ /* compiler built-in */ }};
1393 ($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }};
1396 /// Prints passed tokens into the standard output.
1398 feature = "log_syntax",
1400 reason = "`log_syntax!` is not stable enough for use and is subject to change"
1402 #[rustc_builtin_macro]
1404 macro_rules! log_syntax {
1406 /* compiler built-in */
1410 /// Enables or disables tracing functionality used for debugging other macros.
1412 feature = "trace_macros",
1414 reason = "`trace_macros` is not stable enough for use and is subject to change"
1416 #[rustc_builtin_macro]
1418 macro_rules! trace_macros {
1419 (true) => {{ /* compiler built-in */ }};
1420 (false) => {{ /* compiler built-in */ }};
1423 /// Attribute macro used to apply derive macros.
1425 /// See [the reference] for more info.
1427 /// [the reference]: ../../../reference/attributes/derive.html
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 #[rustc_builtin_macro]
1430 pub macro derive($item:item) {
1431 /* compiler built-in */
1434 /// Attribute macro applied to a function to turn it into a unit test.
1436 /// See [the reference] for more info.
1438 /// [the reference]: ../../../reference/attributes/testing.html#the-test-attribute
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 #[allow_internal_unstable(test, rustc_attrs)]
1441 #[rustc_builtin_macro]
1442 pub macro test($item:item) {
1443 /* compiler built-in */
1446 /// Attribute macro applied to a function to turn it into a benchmark test.
1451 reason = "`bench` is a part of custom test frameworks which are unstable"
1453 #[allow_internal_unstable(test, rustc_attrs)]
1454 #[rustc_builtin_macro]
1455 pub macro bench($item:item) {
1456 /* compiler built-in */
1459 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1461 feature = "custom_test_frameworks",
1463 reason = "custom test frameworks are an unstable feature"
1465 #[allow_internal_unstable(test, rustc_attrs)]
1466 #[rustc_builtin_macro]
1467 pub macro test_case($item:item) {
1468 /* compiler built-in */
1471 /// Attribute macro applied to a static to register it as a global allocator.
1473 /// See also [`std::alloc::GlobalAlloc`](../../../std/alloc/trait.GlobalAlloc.html).
1474 #[stable(feature = "global_allocator", since = "1.28.0")]
1475 #[allow_internal_unstable(rustc_attrs)]
1476 #[rustc_builtin_macro]
1477 pub macro global_allocator($item:item) {
1478 /* compiler built-in */
1481 /// Keeps the item it's applied to if the passed path is accessible, and removes it otherwise.
1483 feature = "cfg_accessible",
1485 reason = "`cfg_accessible` is not fully implemented"
1487 #[rustc_builtin_macro]
1488 pub macro cfg_accessible($item:item) {
1489 /* compiler built-in */
1492 /// Expands all `#[cfg]` and `#[cfg_attr]` attributes in the code fragment it's applied to.
1494 feature = "cfg_eval",
1496 reason = "`cfg_eval` is a recently implemented feature"
1498 #[rustc_builtin_macro]
1499 pub macro cfg_eval($($tt:tt)*) {
1500 /* compiler built-in */
1503 /// Unstable implementation detail of the `rustc` compiler, do not use.
1504 #[rustc_builtin_macro]
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 #[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
1509 reason = "rustc-serialize is deprecated and no longer supported"
1511 #[doc(hidden)] // While technically stable, using it is unstable, and deprecated. Hide it.
1512 pub macro RustcDecodable($item:item) {
1513 /* compiler built-in */
1516 /// Unstable implementation detail of the `rustc` compiler, do not use.
1517 #[rustc_builtin_macro]
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 #[allow_internal_unstable(core_intrinsics)]
1522 reason = "rustc-serialize is deprecated and no longer supported"
1524 #[doc(hidden)] // While technically stable, using it is unstable, and deprecated. Hide it.
1525 pub macro RustcEncodable($item:item) {
1526 /* compiler built-in */