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 /// let a = 1u32.checked_add(2);
130 /// let b = 1u32.checked_sub(2);
131 /// assert_matches!(a, Some(_));
132 /// assert_matches!(b, None);
134 /// let c = Ok("abc".to_string());
135 /// assert_matches!(c, Ok(x) | Err(x) if x.len() < 100);
138 #[unstable(feature = "assert_matches", issue = "82775")]
139 #[allow_internal_unstable(core_panic)]
140 macro_rules
! assert_matches
{
141 ($left
:expr
, $
( $pattern
:pat
)|+ $
( if $guard
: expr
)? $
(,)?
) => ({
143 $
( $pattern
)|+ $
( if $guard
)?
=> {}
145 $
crate::panicking
::assert_matches_failed(
147 $
crate::stringify
!($
($pattern
)|+ $
(if $guard
)?
),
148 $
crate::option
::Option
::None
153 ($left
:expr
, $
( $pattern
:pat
)|+ $
( if $guard
: expr
)?
, $
($arg
:tt
)+) => ({
155 $
( $pattern
)|+ $
( if $guard
)?
=> {}
157 $
crate::panicking
::assert_matches_failed(
159 $
crate::stringify
!($
($pattern
)|+ $
(if $guard
)?
),
160 $
crate::option
::Option
::Some($
crate::format_args
!($
($arg
)+))
167 /// Asserts that a boolean expression is `true` at runtime.
169 /// This will invoke the [`panic!`] macro if the provided expression cannot be
170 /// evaluated to `true` at runtime.
172 /// Like [`assert!`], this macro also has a second version, where a custom panic
173 /// message can be provided.
177 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
178 /// optimized builds by default. An optimized build will not execute
179 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
180 /// compiler. This makes `debug_assert!` useful for checks that are too
181 /// expensive to be present in a release build but may be helpful during
182 /// development. The result of expanding `debug_assert!` is always type checked.
184 /// An unchecked assertion allows a program in an inconsistent state to keep
185 /// running, which might have unexpected consequences but does not introduce
186 /// unsafety as long as this only happens in safe code. The performance cost
187 /// of assertions, however, is not measurable in general. Replacing [`assert!`]
188 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
189 /// more importantly, only in safe code!
194 /// // the panic message for these assertions is the stringified value of the
195 /// // expression given.
196 /// debug_assert!(true);
198 /// fn some_expensive_computation() -> bool { true } // a very simple function
199 /// debug_assert!(some_expensive_computation());
201 /// // assert with a custom message
203 /// debug_assert!(x, "x wasn't true!");
205 /// let a = 3; let b = 27;
206 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
209 #[stable(feature = "rust1", since = "1.0.0")]
210 #[rustc_diagnostic_item = "debug_assert_macro"]
211 macro_rules
! debug_assert
{
212 ($
($arg
:tt
)*) => (if $
crate::cfg
!(debug_assertions
) { $crate::assert!($($arg)*); }
)
215 /// Asserts that two expressions are equal to each other.
217 /// On panic, this macro will print the values of the expressions with their
218 /// debug representations.
220 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
221 /// optimized builds by default. An optimized build will not execute
222 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
223 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
224 /// expensive to be present in a release build but may be helpful during
225 /// development. The result of expanding `debug_assert_eq!` is always type checked.
232 /// debug_assert_eq!(a, b);
235 #[stable(feature = "rust1", since = "1.0.0")]
236 macro_rules
! debug_assert_eq
{
237 ($
($arg
:tt
)*) => (if $
crate::cfg
!(debug_assertions
) { $crate::assert_eq!($($arg)*); }
)
240 /// Asserts that two expressions are not equal to each other.
242 /// On panic, this macro will print the values of the expressions with their
243 /// debug representations.
245 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
246 /// optimized builds by default. An optimized build will not execute
247 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
248 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
249 /// expensive to be present in a release build but may be helpful during
250 /// development. The result of expanding `debug_assert_ne!` is always type checked.
257 /// debug_assert_ne!(a, b);
260 #[stable(feature = "assert_ne", since = "1.13.0")]
261 macro_rules
! debug_assert_ne
{
262 ($
($arg
:tt
)*) => (if $
crate::cfg
!(debug_assertions
) { $crate::assert_ne!($($arg)*); }
)
265 /// Asserts that an expression matches any of the given patterns.
267 /// Like in a `match` expression, the pattern can be optionally followed by `if`
268 /// and a guard expression that has access to names bound by the pattern.
270 /// On panic, this macro will print the value of the expression with its
271 /// debug representation.
273 /// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only
274 /// enabled in non optimized builds by default. An optimized build will not
275 /// execute `debug_assert_matches!` statements unless `-C debug-assertions` is
276 /// passed to the compiler. This makes `debug_assert_matches!` useful for
277 /// checks that are too expensive to be present in a release build but may be
278 /// helpful during development. The result of expanding `debug_assert_matches!`
279 /// is always type checked.
284 /// #![feature(assert_matches)]
286 /// let a = 1u32.checked_add(2);
287 /// let b = 1u32.checked_sub(2);
288 /// debug_assert_matches!(a, Some(_));
289 /// debug_assert_matches!(b, None);
291 /// let c = Ok("abc".to_string());
292 /// debug_assert_matches!(c, Ok(x) | Err(x) if x.len() < 100);
295 #[unstable(feature = "assert_matches", issue = "82775")]
296 #[allow_internal_unstable(assert_matches)]
297 macro_rules
! debug_assert_matches
{
298 ($
($arg
:tt
)*) => (if $
crate::cfg
!(debug_assertions
) { $crate::assert_matches!($($arg)*); }
)
301 /// Returns whether the given expression matches any of the given patterns.
303 /// Like in a `match` expression, the pattern can be optionally followed by `if`
304 /// and a guard expression that has access to names bound by the pattern.
310 /// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
312 /// let bar = Some(4);
313 /// assert!(matches!(bar, Some(x) if x > 2));
316 #[stable(feature = "matches_macro", since = "1.42.0")]
317 macro_rules
! matches
{
318 ($expression
:expr
, $
( $pattern
:pat
)|+ $
( if $guard
: expr
)? $
(,)?
) => {
320 $
( $pattern
)|+ $
( if $guard
)?
=> true,
326 /// Unwraps a result or propagates its error.
328 /// The `?` operator was added to replace `try!` and should be used instead.
329 /// Furthermore, `try` is a reserved word in Rust 2018, so if you must use
330 /// it, you will need to use the [raw-identifier syntax][ris]: `r#try`.
332 /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
334 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
335 /// expression has the value of the wrapped value.
337 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
338 /// performs conversion using `From`. This provides automatic conversion
339 /// between specialized errors and more general ones. The resulting
340 /// error is then immediately returned.
342 /// Because of the early return, `try!` can only be used in functions that
343 /// return [`Result`].
349 /// use std::fs::File;
350 /// use std::io::prelude::*;
356 /// impl From<io::Error> for MyError {
357 /// fn from(e: io::Error) -> MyError {
358 /// MyError::FileWriteError
362 /// // The preferred method of quick returning Errors
363 /// fn write_to_file_question() -> Result<(), MyError> {
364 /// let mut file = File::create("my_best_friends.txt")?;
365 /// file.write_all(b"This is a list of my best friends.")?;
369 /// // The previous method of quick returning Errors
370 /// fn write_to_file_using_try() -> Result<(), MyError> {
371 /// let mut file = r#try!(File::create("my_best_friends.txt"));
372 /// r#try!(file.write_all(b"This is a list of my best friends."));
376 /// // This is equivalent to:
377 /// fn write_to_file_using_match() -> Result<(), MyError> {
378 /// let mut file = r#try!(File::create("my_best_friends.txt"));
379 /// match file.write_all(b"This is a list of my best friends.") {
381 /// Err(e) => return Err(From::from(e)),
387 #[stable(feature = "rust1", since = "1.0.0")]
388 #[rustc_deprecated(since = "1.39.0", reason = "use the `?` operator instead")]
391 ($expr
:expr $
(,)?
) => {
393 $
crate::result
::Result
::Ok(val
) => val
,
394 $
crate::result
::Result
::Err(err
) => {
395 return $
crate::result
::Result
::Err($
crate::convert
::From
::from(err
));
401 /// Writes formatted data into a buffer.
403 /// This macro accepts a 'writer', a format string, and a list of arguments. Arguments will be
404 /// formatted according to the specified format string and the result will be passed to the writer.
405 /// The writer may be any value with a `write_fmt` method; generally this comes from an
406 /// implementation of either the [`fmt::Write`] or the [`io::Write`] trait. The macro
407 /// returns whatever the `write_fmt` method returns; commonly a [`fmt::Result`], or an
410 /// See [`std::fmt`] for more information on the format string syntax.
412 /// [`std::fmt`]: ../std/fmt/index.html
413 /// [`fmt::Write`]: crate::fmt::Write
414 /// [`io::Write`]: ../std/io/trait.Write.html
415 /// [`fmt::Result`]: crate::fmt::Result
416 /// [`io::Result`]: ../std/io/type.Result.html
421 /// use std::io::Write;
423 /// fn main() -> std::io::Result<()> {
424 /// let mut w = Vec::new();
425 /// write!(&mut w, "test")?;
426 /// write!(&mut w, "formatted {}", "arguments")?;
428 /// assert_eq!(w, b"testformatted arguments");
433 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
434 /// implementing either, as objects do not typically implement both. However, the module must
435 /// import the traits qualified so their names do not conflict:
438 /// use std::fmt::Write as FmtWrite;
439 /// use std::io::Write as IoWrite;
441 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
442 /// let mut s = String::new();
443 /// let mut v = Vec::new();
445 /// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
446 /// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
447 /// assert_eq!(v, b"s = \"abc 123\"");
452 /// Note: This macro can be used in `no_std` setups as well.
453 /// In a `no_std` setup you are responsible for the implementation details of the components.
456 /// # extern crate core;
457 /// use core::fmt::Write;
461 /// impl Write for Example {
462 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
463 /// unimplemented!();
467 /// let mut m = Example{};
468 /// write!(&mut m, "Hello World").expect("Not written");
471 #[stable(feature = "rust1", since = "1.0.0")]
473 ($dst
:expr
, $
($arg
:tt
)*) => ($dst
.write_fmt($
crate::format_args
!($
($arg
)*)))
476 /// Write formatted data into a buffer, with a newline appended.
478 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
479 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
481 /// For more information, see [`write!`]. For information on the format string syntax, see
484 /// [`std::fmt`]: ../std/fmt/index.html
489 /// use std::io::{Write, Result};
491 /// fn main() -> Result<()> {
492 /// let mut w = Vec::new();
493 /// writeln!(&mut w)?;
494 /// writeln!(&mut w, "test")?;
495 /// writeln!(&mut w, "formatted {}", "arguments")?;
497 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
502 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
503 /// implementing either, as objects do not typically implement both. However, the module must
504 /// import the traits qualified so their names do not conflict:
507 /// use std::fmt::Write as FmtWrite;
508 /// use std::io::Write as IoWrite;
510 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
511 /// let mut s = String::new();
512 /// let mut v = Vec::new();
514 /// writeln!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
515 /// writeln!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
516 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
521 #[stable(feature = "rust1", since = "1.0.0")]
522 #[allow_internal_unstable(format_args_nl)]
523 macro_rules
! writeln
{
524 ($dst
:expr $
(,)?
) => (
525 $
crate::write
!($dst
, "\n")
527 ($dst
:expr
, $
($arg
:tt
)*) => (
528 $dst
.write_fmt($
crate::format_args_nl
!($
($arg
)*))
532 /// Indicates unreachable code.
534 /// This is useful any time that the compiler can't determine that some code is unreachable. For
537 /// * Match arms with guard conditions.
538 /// * Loops that dynamically terminate.
539 /// * Iterators that dynamically terminate.
541 /// If the determination that the code is unreachable proves incorrect, the
542 /// program immediately terminates with a [`panic!`].
544 /// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
545 /// will cause undefined behavior if the code is reached.
547 /// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked
551 /// This will always [`panic!`].
558 /// # #[allow(dead_code)]
559 /// fn foo(x: Option<i32>) {
561 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
562 /// Some(n) if n < 0 => println!("Some(Negative)"),
563 /// Some(_) => unreachable!(), // compile error if commented out
564 /// None => println!("None")
572 /// # #[allow(dead_code)]
573 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
575 /// if 3*i < i { panic!("u32 overflow"); }
576 /// if x < 3*i { return i-1; }
582 #[stable(feature = "rust1", since = "1.0.0")]
583 macro_rules
! unreachable
{
585 $
crate::panic
!("internal error: entered unreachable code")
587 ($msg
:expr $
(,)?
) => ({
588 $
crate::unreachable
!("{}", $msg
)
590 ($fmt
:expr
, $
($arg
:tt
)*) => ({
591 $
crate::panic
!($
crate::concat
!("internal error: entered unreachable code: ", $fmt
), $
($arg
)*)
595 /// Indicates unimplemented code by panicking with a message of "not implemented".
597 /// This allows your code to type-check, which is useful if you are prototyping or
598 /// implementing a trait that requires multiple methods which you don't plan of using all of.
600 /// The difference between `unimplemented!` and [`todo!`] is that while `todo!`
601 /// conveys an intent of implementing the functionality later and the message is "not yet
602 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
603 /// Also some IDEs will mark `todo!`s.
607 /// This will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a
608 /// fixed, specific message.
610 /// Like `panic!`, this macro has a second form for displaying custom values.
614 /// Say we have a trait `Foo`:
618 /// fn bar(&self) -> u8;
620 /// fn qux(&self) -> Result<u64, ()>;
624 /// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
625 /// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
626 /// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
627 /// to allow our code to compile.
629 /// We still want to have our program stop running if the unimplemented methods are
634 /// # fn bar(&self) -> u8;
636 /// # fn qux(&self) -> Result<u64, ()>;
640 /// impl Foo for MyStruct {
641 /// fn bar(&self) -> u8 {
646 /// // It makes no sense to `baz` a `MyStruct`, so we have no logic here
648 /// // This will display "thread 'main' panicked at 'not implemented'".
649 /// unimplemented!();
652 /// fn qux(&self) -> Result<u64, ()> {
653 /// // We have some logic here,
654 /// // We can add a message to unimplemented! to display our omission.
655 /// // This will display:
656 /// // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
657 /// unimplemented!("MyStruct isn't quxable");
662 /// let s = MyStruct;
667 #[stable(feature = "rust1", since = "1.0.0")]
668 macro_rules
! unimplemented
{
669 () => ($
crate::panic
!("not implemented"));
670 ($
($arg
:tt
)+) => ($
crate::panic
!("not implemented: {}", $
crate::format_args
!($
($arg
)+)));
673 /// Indicates unfinished code.
675 /// This can be useful if you are prototyping and are just looking to have your
678 /// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
679 /// an intent of implementing the functionality later and the message is "not yet
680 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
681 /// Also some IDEs will mark `todo!`s.
685 /// This will always [`panic!`].
689 /// Here's an example of some in-progress code. We have a trait `Foo`:
698 /// We want to implement `Foo` on one of our types, but we also want to work on
699 /// just `bar()` first. In order for our code to compile, we need to implement
700 /// `baz()`, so we can use `todo!`:
709 /// impl Foo for MyStruct {
711 /// // implementation goes here
715 /// // let's not worry about implementing baz() for now
721 /// let s = MyStruct;
724 /// // we aren't even using baz(), so this is fine.
728 #[stable(feature = "todo_macro", since = "1.40.0")]
730 () => ($
crate::panic
!("not yet implemented"));
731 ($
($arg
:tt
)+) => ($
crate::panic
!("not yet implemented: {}", $
crate::format_args
!($
($arg
)+)));
734 /// Definitions of built-in macros.
736 /// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
737 /// with exception of expansion functions transforming macro inputs into outputs,
738 /// those functions are provided by the compiler.
739 pub(crate) mod builtin
{
741 /// Causes compilation to fail with the given error message when encountered.
743 /// This macro should be used when a crate uses a conditional compilation strategy to provide
744 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
745 /// but emits an error during *compilation* rather than at *runtime*.
749 /// Two such examples are macros and `#[cfg]` environments.
751 /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
752 /// the compiler would still emit an error, but the error's message would not mention the two
756 /// macro_rules! give_me_foo_or_bar {
760 /// compile_error!("This macro only accepts `foo` or `bar`");
764 /// give_me_foo_or_bar!(neither);
765 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
768 /// Emit compiler error if one of a number of features isn't available.
771 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
772 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
774 #[stable(feature = "compile_error_macro", since = "1.20.0")]
775 #[rustc_builtin_macro]
777 macro_rules
! compile_error
{
778 ($msg
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
781 /// Constructs parameters for the other string-formatting macros.
783 /// This macro functions by taking a formatting string literal containing
784 /// `{}` for each additional argument passed. `format_args!` prepares the
785 /// additional parameters to ensure the output can be interpreted as a string
786 /// and canonicalizes the arguments into a single type. Any value that implements
787 /// the [`Display`] trait can be passed to `format_args!`, as can any
788 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
790 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
791 /// passed to the macros within [`std::fmt`] for performing useful redirection.
792 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
793 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
794 /// heap allocations.
796 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
797 /// in `Debug` and `Display` contexts as seen below. The example also shows
798 /// that `Debug` and `Display` format to the same thing: the interpolated
799 /// format string in `format_args!`.
802 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
803 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
804 /// assert_eq!("1 foo 2", display);
805 /// assert_eq!(display, debug);
808 /// For more information, see the documentation in [`std::fmt`].
810 /// [`Display`]: crate::fmt::Display
811 /// [`Debug`]: crate::fmt::Debug
812 /// [`fmt::Arguments`]: crate::fmt::Arguments
813 /// [`std::fmt`]: ../std/fmt/index.html
814 /// [`format!`]: ../std/macro.format.html
815 /// [`println!`]: ../std/macro.println.html
822 /// let s = fmt::format(format_args!("hello {}", "world"));
823 /// assert_eq!(s, format!("hello {}", "world"));
825 #[stable(feature = "rust1", since = "1.0.0")]
826 #[allow_internal_unstable(fmt_internals)]
827 #[rustc_builtin_macro]
829 macro_rules
! format_args
{
830 ($fmt
:expr
) => {{ /* compiler built-in */ }
};
831 ($fmt
:expr
, $
($args
:tt
)*) => {{ /* compiler built-in */ }
};
834 /// Same as `format_args`, but adds a newline in the end.
836 feature
= "format_args_nl",
838 reason
= "`format_args_nl` is only for internal \
839 language use and is subject to change"
841 #[allow_internal_unstable(fmt_internals)]
842 #[rustc_builtin_macro]
844 macro_rules
! format_args_nl
{
845 ($fmt
:expr
) => {{ /* compiler built-in */ }
};
846 ($fmt
:expr
, $
($args
:tt
)*) => {{ /* compiler built-in */ }
};
849 /// Inspects an environment variable at compile time.
851 /// This macro will expand to the value of the named environment variable at
852 /// compile time, yielding an expression of type `&'static str`.
854 /// If the environment variable is not defined, then a compilation error
855 /// will be emitted. To not emit a compile error, use the [`option_env!`]
861 /// let path: &'static str = env!("PATH");
862 /// println!("the $PATH variable at the time of compiling was: {}", path);
865 /// You can customize the error message by passing a string as the second
869 /// let doc: &'static str = env!("documentation", "what's that?!");
872 /// If the `documentation` environment variable is not defined, you'll get
873 /// the following error:
876 /// error: what's that?!
878 #[stable(feature = "rust1", since = "1.0.0")]
879 #[rustc_builtin_macro]
882 ($name
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
883 ($name
:expr
, $error_msg
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
886 /// Optionally inspects an environment variable at compile time.
888 /// If the named environment variable is present at compile time, this will
889 /// expand into an expression of type `Option<&'static str>` whose value is
890 /// `Some` of the value of the environment variable. If the environment
891 /// variable is not present, then this will expand to `None`. See
892 /// [`Option<T>`][Option] for more information on this type.
894 /// A compile time error is never emitted when using this macro regardless
895 /// of whether the environment variable is present or not.
900 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
901 /// println!("the secret key might be: {:?}", key);
903 #[stable(feature = "rust1", since = "1.0.0")]
904 #[rustc_builtin_macro]
906 macro_rules
! option_env
{
907 ($name
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
910 /// Concatenates identifiers into one identifier.
912 /// This macro takes any number of comma-separated identifiers, and
913 /// concatenates them all into one, yielding an expression which is a new
914 /// identifier. Note that hygiene makes it such that this macro cannot
915 /// capture local variables. Also, as a general rule, macros are only
916 /// allowed in item, statement or expression position. That means while
917 /// you may use this macro for referring to existing variables, functions or
918 /// modules etc, you cannot define a new one with it.
923 /// #![feature(concat_idents)]
926 /// fn foobar() -> u32 { 23 }
928 /// let f = concat_idents!(foo, bar);
929 /// println!("{}", f());
931 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
935 feature
= "concat_idents",
937 reason
= "`concat_idents` is not stable enough for use and is subject to change"
939 #[rustc_builtin_macro]
941 macro_rules
! concat_idents
{
942 ($
($e
:ident
),+ $
(,)?
) => {{ /* compiler built-in */ }
};
945 /// Concatenates literals into a static string slice.
947 /// This macro takes any number of comma-separated literals, yielding an
948 /// expression of type `&'static str` which represents all of the literals
949 /// concatenated left-to-right.
951 /// Integer and floating point literals are stringified in order to be
957 /// let s = concat!("test", 10, 'b', true);
958 /// assert_eq!(s, "test10btrue");
960 #[stable(feature = "rust1", since = "1.0.0")]
961 #[rustc_builtin_macro]
963 macro_rules
! concat
{
964 ($
($e
:expr
),* $
(,)?
) => {{ /* compiler built-in */ }
};
967 /// Expands to the line number on which it was invoked.
969 /// With [`column!`] and [`file!`], these macros provide debugging information for
970 /// developers about the location within the source.
972 /// The expanded expression has type `u32` and is 1-based, so the first line
973 /// in each file evaluates to 1, the second to 2, etc. This is consistent
974 /// with error messages by common compilers or popular editors.
975 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
976 /// but rather the first macro invocation leading up to the invocation
977 /// of the `line!` macro.
982 /// let current_line = line!();
983 /// println!("defined on line: {}", current_line);
985 #[stable(feature = "rust1", since = "1.0.0")]
986 #[rustc_builtin_macro]
990 /* compiler built-in */
994 /// Expands to the column number at which it was invoked.
996 /// With [`line!`] and [`file!`], these macros provide debugging information for
997 /// developers about the location within the source.
999 /// The expanded expression has type `u32` and is 1-based, so the first column
1000 /// in each line evaluates to 1, the second to 2, etc. This is consistent
1001 /// with error messages by common compilers or popular editors.
1002 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
1003 /// but rather the first macro invocation leading up to the invocation
1004 /// of the `column!` macro.
1009 /// let current_col = column!();
1010 /// println!("defined on column: {}", current_col);
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 #[rustc_builtin_macro]
1015 macro_rules
! column
{
1017 /* compiler built-in */
1021 /// Expands to the file name in which it was invoked.
1023 /// With [`line!`] and [`column!`], these macros provide debugging information for
1024 /// developers about the location within the source.
1026 /// The expanded expression has type `&'static str`, and the returned file
1027 /// is not the invocation of the `file!` macro itself, but rather the
1028 /// first macro invocation leading up to the invocation of the `file!`
1034 /// let this_file = file!();
1035 /// println!("defined in file: {}", this_file);
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 #[rustc_builtin_macro]
1042 /* compiler built-in */
1046 /// Stringifies its arguments.
1048 /// This macro will yield an expression of type `&'static str` which is the
1049 /// stringification of all the tokens passed to the macro. No restrictions
1050 /// are placed on the syntax of the macro invocation itself.
1052 /// Note that the expanded results of the input tokens may change in the
1053 /// future. You should be careful if you rely on the output.
1058 /// let one_plus_one = stringify!(1 + 1);
1059 /// assert_eq!(one_plus_one, "1 + 1");
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 #[rustc_builtin_macro]
1064 macro_rules
! stringify
{
1066 /* compiler built-in */
1070 /// Includes a UTF-8 encoded file as a string.
1072 /// The file is located relative to the current file (similarly to how
1073 /// modules are found). The provided path is interpreted in a platform-specific
1074 /// way at compile time. So, for instance, an invocation with a Windows path
1075 /// containing backslashes `\` would not compile correctly on Unix.
1077 /// This macro will yield an expression of type `&'static str` which is the
1078 /// contents of the file.
1082 /// Assume there are two files in the same directory with the following
1085 /// File 'spanish.in':
1093 /// ```ignore (cannot-doctest-external-file-dependency)
1095 /// let my_str = include_str!("spanish.in");
1096 /// assert_eq!(my_str, "adiós\n");
1097 /// print!("{}", my_str);
1101 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1102 #[stable(feature = "rust1", since = "1.0.0")]
1103 #[rustc_builtin_macro]
1105 macro_rules
! include_str
{
1106 ($file
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
1109 /// Includes a file as a reference to a byte array.
1111 /// The file is located relative to the current file (similarly to how
1112 /// modules are found). The provided path is interpreted in a platform-specific
1113 /// way at compile time. So, for instance, an invocation with a Windows path
1114 /// containing backslashes `\` would not compile correctly on Unix.
1116 /// This macro will yield an expression of type `&'static [u8; N]` which is
1117 /// the contents of the file.
1121 /// Assume there are two files in the same directory with the following
1124 /// File 'spanish.in':
1132 /// ```ignore (cannot-doctest-external-file-dependency)
1134 /// let bytes = include_bytes!("spanish.in");
1135 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
1136 /// print!("{}", String::from_utf8_lossy(bytes));
1140 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 #[rustc_builtin_macro]
1144 macro_rules
! include_bytes
{
1145 ($file
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
1148 /// Expands to a string that represents the current module path.
1150 /// The current module path can be thought of as the hierarchy of modules
1151 /// leading back up to the crate root. The first component of the path
1152 /// returned is the name of the crate currently being compiled.
1159 /// assert!(module_path!().ends_with("test"));
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 #[rustc_builtin_macro]
1168 macro_rules
! module_path
{
1170 /* compiler built-in */
1174 /// Evaluates boolean combinations of configuration flags at compile-time.
1176 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1177 /// boolean expression evaluation of configuration flags. This frequently
1178 /// leads to less duplicated code.
1180 /// The syntax given to this macro is the same syntax as the [`cfg`]
1183 /// `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For
1184 /// example, all blocks in an if/else expression need to be valid when `cfg!` is used for
1185 /// the condition, regardless of what `cfg!` is evaluating.
1187 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1192 /// let my_directory = if cfg!(windows) {
1193 /// "windows-specific-directory"
1195 /// "unix-directory"
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 #[rustc_builtin_macro]
1203 /* compiler built-in */
1207 /// Parses a file as an expression or an item according to the context.
1209 /// The file is located relative to the current file (similarly to how
1210 /// modules are found). The provided path is interpreted in a platform-specific
1211 /// way at compile time. So, for instance, an invocation with a Windows path
1212 /// containing backslashes `\` would not compile correctly on Unix.
1214 /// Using this macro is often a bad idea, because if the file is
1215 /// parsed as an expression, it is going to be placed in the
1216 /// surrounding code unhygienically. This could result in variables
1217 /// or functions being different from what the file expected if
1218 /// there are variables or functions that have the same name in
1219 /// the current file.
1223 /// Assume there are two files in the same directory with the following
1226 /// File 'monkeys.in':
1228 /// ```ignore (only-for-syntax-highlight)
1229 /// ['🙈', '🙊', '🙉']
1233 /// .collect::<String>()
1238 /// ```ignore (cannot-doctest-external-file-dependency)
1240 /// let my_string = include!("monkeys.in");
1241 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1242 /// println!("{}", my_string);
1246 /// Compiling 'main.rs' and running the resulting binary will print
1247 /// "🙈🙊🙉🙈🙊🙉".
1248 #[stable(feature = "rust1", since = "1.0.0")]
1249 #[rustc_builtin_macro]
1251 macro_rules
! include
{
1252 ($file
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
1255 /// Asserts that a boolean expression is `true` at runtime.
1257 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1258 /// evaluated to `true` at runtime.
1262 /// Assertions are always checked in both debug and release builds, and cannot
1263 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1264 /// release builds by default.
1266 /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if
1267 /// violated could lead to unsafety.
1269 /// Other use-cases of `assert!` include testing and enforcing run-time
1270 /// invariants in safe code (whose violation cannot result in unsafety).
1272 /// # Custom Messages
1274 /// This macro has a second form, where a custom panic message can
1275 /// be provided with or without arguments for formatting. See [`std::fmt`]
1276 /// for syntax for this form. Expressions used as format arguments will only
1277 /// be evaluated if the assertion fails.
1279 /// [`std::fmt`]: ../std/fmt/index.html
1284 /// // the panic message for these assertions is the stringified value of the
1285 /// // expression given.
1288 /// fn some_computation() -> bool { true } // a very simple function
1290 /// assert!(some_computation());
1292 /// // assert with a custom message
1294 /// assert!(x, "x wasn't true!");
1296 /// let a = 3; let b = 27;
1297 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 #[rustc_builtin_macro]
1302 #[rustc_diagnostic_item = "assert_macro"]
1303 #[allow_internal_unstable(core_panic, edition_panic)]
1304 macro_rules
! assert
{
1305 ($cond
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
1306 ($cond
:expr
, $
($arg
:tt
)+) => {{ /* compiler built-in */ }
};
1309 /// Inline assembly.
1311 /// Read the [unstable book] for the usage.
1313 /// [unstable book]: ../unstable-book/library-features/asm.html
1317 reason
= "inline assembly is not stable enough for use and is subject to change"
1319 #[rustc_builtin_macro]
1322 ("assembly template",
1324 $
(options($
(option
),*))?
1326 /* compiler built-in */
1330 /// LLVM-style inline assembly.
1332 /// Read the [unstable book] for the usage.
1334 /// [unstable book]: ../unstable-book/library-features/llvm-asm.html
1336 feature
= "llvm_asm",
1338 reason
= "prefer using the new asm! syntax instead"
1340 #[rustc_builtin_macro]
1342 macro_rules
! llvm_asm
{
1343 ("assembly template"
1344 : $
("output"(operand
),)*
1345 : $
("input"(operand
),)*
1347 : $
("options",)*) => {
1348 /* compiler built-in */
1352 /// Module-level inline assembly.
1354 feature
= "global_asm",
1356 reason
= "`global_asm!` is not stable enough for use and is subject to change"
1358 #[rustc_builtin_macro]
1360 macro_rules
! global_asm
{
1362 /* compiler built-in */
1366 /// Prints passed tokens into the standard output.
1368 feature
= "log_syntax",
1370 reason
= "`log_syntax!` is not stable enough for use and is subject to change"
1372 #[rustc_builtin_macro]
1374 macro_rules
! log_syntax
{
1376 /* compiler built-in */
1380 /// Enables or disables tracing functionality used for debugging other macros.
1382 feature
= "trace_macros",
1384 reason
= "`trace_macros` is not stable enough for use and is subject to change"
1386 #[rustc_builtin_macro]
1388 macro_rules
! trace_macros
{
1389 (true) => {{ /* compiler built-in */ }
};
1390 (false) => {{ /* compiler built-in */ }
};
1393 /// Attribute macro used to apply derive macros.
1394 #[cfg(not(bootstrap))]
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.
1456 #[cfg(not(bootstrap))]
1458 feature
= "cfg_eval",
1460 reason
= "`cfg_eval` is a recently implemented feature"
1462 #[rustc_builtin_macro]
1463 pub macro cfg_eval($
($tt
:tt
)*) {
1464 /* compiler built-in */
1467 /// Unstable implementation detail of the `rustc` compiler, do not use.
1468 #[rustc_builtin_macro]
1469 #[stable(feature = "rust1", since = "1.0.0")]
1470 #[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
1473 reason
= "rustc-serialize is deprecated and no longer supported"
1475 pub macro RustcDecodable($item
:item
) {
1476 /* compiler built-in */
1479 /// Unstable implementation detail of the `rustc` compiler, do not use.
1480 #[rustc_builtin_macro]
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 #[allow_internal_unstable(core_intrinsics)]
1485 reason
= "rustc-serialize is deprecated and no longer supported"
1487 pub macro RustcEncodable($item
:item
) {
1488 /* compiler built-in */