core/macros/
mod.rs

1#[doc = include_str!("panic.md")]
2#[macro_export]
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"]
7macro_rules! panic {
8    // Expands to either `$crate::panic::panic_2015` or `$crate::panic::panic_2021`
9    // depending on the edition of the caller.
10    ($($arg:tt)*) => {
11        /* compiler built-in */
12    };
13}
14
15/// Asserts that two expressions are equal to each other (using [`PartialEq`]).
16///
17/// Assertions are always checked in both debug and release builds, and cannot
18/// be disabled. See [`debug_assert_eq!`] for assertions that are disabled in
19/// release builds by default.
20///
21/// [`debug_assert_eq!`]: crate::debug_assert_eq
22///
23/// On panic, this macro will print the values of the expressions with their
24/// debug representations.
25///
26/// Like [`assert!`], this macro has a second form, where a custom
27/// panic message can be provided.
28///
29/// # Examples
30///
31/// ```
32/// let a = 3;
33/// let b = 1 + 2;
34/// assert_eq!(a, b);
35///
36/// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
37/// ```
38#[macro_export]
39#[stable(feature = "rust1", since = "1.0.0")]
40#[cfg_attr(not(test), rustc_diagnostic_item = "assert_eq_macro")]
41#[allow_internal_unstable(panic_internals)]
42macro_rules! assert_eq {
43    ($left:expr, $right:expr $(,)?) => {
44        match (&$left, &$right) {
45            (left_val, right_val) => {
46                if !(*left_val == *right_val) {
47                    let kind = $crate::panicking::AssertKind::Eq;
48                    // The reborrows below are intentional. Without them, the stack slot for the
49                    // borrow is initialized even before the values are compared, leading to a
50                    // noticeable slow down.
51                    $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None);
52                }
53            }
54        }
55    };
56    ($left:expr, $right:expr, $($arg:tt)+) => {
57        match (&$left, &$right) {
58            (left_val, right_val) => {
59                if !(*left_val == *right_val) {
60                    let kind = $crate::panicking::AssertKind::Eq;
61                    // The reborrows below are intentional. Without them, the stack slot for the
62                    // borrow is initialized even before the values are compared, leading to a
63                    // noticeable slow down.
64                    $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::Some($crate::format_args!($($arg)+)));
65                }
66            }
67        }
68    };
69}
70
71/// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
72///
73/// Assertions are always checked in both debug and release builds, and cannot
74/// be disabled. See [`debug_assert_ne!`] for assertions that are disabled in
75/// release builds by default.
76///
77/// [`debug_assert_ne!`]: crate::debug_assert_ne
78///
79/// On panic, this macro will print the values of the expressions with their
80/// debug representations.
81///
82/// Like [`assert!`], this macro has a second form, where a custom
83/// panic message can be provided.
84///
85/// # Examples
86///
87/// ```
88/// let a = 3;
89/// let b = 2;
90/// assert_ne!(a, b);
91///
92/// assert_ne!(a, b, "we are testing that the values are not equal");
93/// ```
94#[macro_export]
95#[stable(feature = "assert_ne", since = "1.13.0")]
96#[cfg_attr(not(test), rustc_diagnostic_item = "assert_ne_macro")]
97#[allow_internal_unstable(panic_internals)]
98macro_rules! assert_ne {
99    ($left:expr, $right:expr $(,)?) => {
100        match (&$left, &$right) {
101            (left_val, right_val) => {
102                if *left_val == *right_val {
103                    let kind = $crate::panicking::AssertKind::Ne;
104                    // The reborrows below are intentional. Without them, the stack slot for the
105                    // borrow is initialized even before the values are compared, leading to a
106                    // noticeable slow down.
107                    $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None);
108                }
109            }
110        }
111    };
112    ($left:expr, $right:expr, $($arg:tt)+) => {
113        match (&($left), &($right)) {
114            (left_val, right_val) => {
115                if *left_val == *right_val {
116                    let kind = $crate::panicking::AssertKind::Ne;
117                    // The reborrows below are intentional. Without them, the stack slot for the
118                    // borrow is initialized even before the values are compared, leading to a
119                    // noticeable slow down.
120                    $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::Some($crate::format_args!($($arg)+)));
121                }
122            }
123        }
124    };
125}
126
127/// Asserts that an expression matches the provided pattern.
128///
129/// This macro is generally preferable to `assert!(matches!(value, pattern))`, because it can print
130/// the debug representation of the actual value shape that did not meet expectations. In contrast,
131/// using [`assert!`] will only print that expectations were not met, but not why.
132///
133/// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The
134/// optional if guard can be used to add additional checks that must be true for the matched value,
135/// otherwise this macro will panic.
136///
137/// Assertions are always checked in both debug and release builds, and cannot
138/// be disabled. See [`debug_assert_matches!`] for assertions that are disabled in
139/// release builds by default.
140///
141/// [`debug_assert_matches!`]: crate::assert_matches::debug_assert_matches
142///
143/// On panic, this macro will print the value of the expression with its debug representation.
144///
145/// Like [`assert!`], this macro has a second form, where a custom panic message can be provided.
146///
147/// # Examples
148///
149/// ```
150/// #![feature(assert_matches)]
151///
152/// use std::assert_matches::assert_matches;
153///
154/// let a = Some(345);
155/// let b = Some(56);
156/// assert_matches!(a, Some(_));
157/// assert_matches!(b, Some(_));
158///
159/// assert_matches!(a, Some(345));
160/// assert_matches!(a, Some(345) | None);
161///
162/// // assert_matches!(a, None); // panics
163/// // assert_matches!(b, Some(345)); // panics
164/// // assert_matches!(b, Some(345) | None); // panics
165///
166/// assert_matches!(a, Some(x) if x > 100);
167/// // assert_matches!(a, Some(x) if x < 100); // panics
168/// ```
169#[unstable(feature = "assert_matches", issue = "82775")]
170#[allow_internal_unstable(panic_internals)]
171#[rustc_macro_transparency = "semitransparent"]
172pub macro assert_matches {
173    ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => {
174        match $left {
175            $( $pattern )|+ $( if $guard )? => {}
176            ref left_val => {
177                $crate::panicking::assert_matches_failed(
178                    left_val,
179                    $crate::stringify!($($pattern)|+ $(if $guard)?),
180                    $crate::option::Option::None
181                );
182            }
183        }
184    },
185    ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )?, $($arg:tt)+) => {
186        match $left {
187            $( $pattern )|+ $( if $guard )? => {}
188            ref left_val => {
189                $crate::panicking::assert_matches_failed(
190                    left_val,
191                    $crate::stringify!($($pattern)|+ $(if $guard)?),
192                    $crate::option::Option::Some($crate::format_args!($($arg)+))
193                );
194            }
195        }
196    },
197}
198
199/// A macro for defining `#[cfg]` match-like statements.
200///
201/// It is similar to the `if/elif` C preprocessor macro by allowing definition of a cascade of
202/// `#[cfg]` cases, emitting the implementation which matches first.
203///
204/// This allows you to conveniently provide a long list `#[cfg]`'d blocks of code
205/// without having to rewrite each clause multiple times.
206///
207/// Trailing `_` wildcard match arms are **optional** and they indicate a fallback branch when
208/// all previous declarations do not evaluate to true.
209///
210/// # Example
211///
212/// ```
213/// #![feature(cfg_match)]
214///
215/// cfg_match! {
216///     unix => {
217///         fn foo() { /* unix specific functionality */ }
218///     }
219///     target_pointer_width = "32" => {
220///         fn foo() { /* non-unix, 32-bit functionality */ }
221///     }
222///     _ => {
223///         fn foo() { /* fallback implementation */ }
224///     }
225/// }
226/// ```
227///
228/// If desired, it is possible to return expressions through the use of surrounding braces:
229///
230/// ```
231/// #![feature(cfg_match)]
232///
233/// let _some_string = cfg_match! {{
234///     unix => { "With great power comes great electricity bills" }
235///     _ => { "Behind every successful diet is an unwatched pizza" }
236/// }};
237/// ```
238#[unstable(feature = "cfg_match", issue = "115585")]
239#[rustc_diagnostic_item = "cfg_match"]
240pub macro cfg_match {
241    ({ $($tt:tt)* }) => {{
242        cfg_match! { $($tt)* }
243    }},
244    (_ => { $($output:tt)* }) => {
245        $($output)*
246    },
247    (
248        $cfg:meta => $output:tt
249        $($( $rest:tt )+)?
250    ) => {
251        #[cfg($cfg)]
252        cfg_match! { _ => $output }
253        $(
254            #[cfg(not($cfg))]
255            cfg_match! { $($rest)+ }
256        )?
257    },
258}
259
260/// Asserts that a boolean expression is `true` at runtime.
261///
262/// This will invoke the [`panic!`] macro if the provided expression cannot be
263/// evaluated to `true` at runtime.
264///
265/// Like [`assert!`], this macro also has a second version, where a custom panic
266/// message can be provided.
267///
268/// # Uses
269///
270/// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
271/// optimized builds by default. An optimized build will not execute
272/// `debug_assert!` statements unless `-C debug-assertions` is passed to the
273/// compiler. This makes `debug_assert!` useful for checks that are too
274/// expensive to be present in a release build but may be helpful during
275/// development. The result of expanding `debug_assert!` is always type checked.
276///
277/// An unchecked assertion allows a program in an inconsistent state to keep
278/// running, which might have unexpected consequences but does not introduce
279/// unsafety as long as this only happens in safe code. The performance cost
280/// of assertions, however, is not measurable in general. Replacing [`assert!`]
281/// with `debug_assert!` is thus only encouraged after thorough profiling, and
282/// more importantly, only in safe code!
283///
284/// # Examples
285///
286/// ```
287/// // the panic message for these assertions is the stringified value of the
288/// // expression given.
289/// debug_assert!(true);
290///
291/// fn some_expensive_computation() -> bool { true } // a very simple function
292/// debug_assert!(some_expensive_computation());
293///
294/// // assert with a custom message
295/// let x = true;
296/// debug_assert!(x, "x wasn't true!");
297///
298/// let a = 3; let b = 27;
299/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
300/// ```
301#[macro_export]
302#[stable(feature = "rust1", since = "1.0.0")]
303#[rustc_diagnostic_item = "debug_assert_macro"]
304#[allow_internal_unstable(edition_panic)]
305macro_rules! debug_assert {
306    ($($arg:tt)*) => {
307        if $crate::cfg!(debug_assertions) {
308            $crate::assert!($($arg)*);
309        }
310    };
311}
312
313/// Asserts that two expressions are equal to each other.
314///
315/// On panic, this macro will print the values of the expressions with their
316/// debug representations.
317///
318/// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
319/// optimized builds by default. An optimized build will not execute
320/// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
321/// compiler. This makes `debug_assert_eq!` useful for checks that are too
322/// expensive to be present in a release build but may be helpful during
323/// development. The result of expanding `debug_assert_eq!` is always type checked.
324///
325/// # Examples
326///
327/// ```
328/// let a = 3;
329/// let b = 1 + 2;
330/// debug_assert_eq!(a, b);
331/// ```
332#[macro_export]
333#[stable(feature = "rust1", since = "1.0.0")]
334#[cfg_attr(not(test), rustc_diagnostic_item = "debug_assert_eq_macro")]
335macro_rules! debug_assert_eq {
336    ($($arg:tt)*) => {
337        if $crate::cfg!(debug_assertions) {
338            $crate::assert_eq!($($arg)*);
339        }
340    };
341}
342
343/// Asserts that two expressions are not equal to each other.
344///
345/// On panic, this macro will print the values of the expressions with their
346/// debug representations.
347///
348/// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
349/// optimized builds by default. An optimized build will not execute
350/// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
351/// compiler. This makes `debug_assert_ne!` useful for checks that are too
352/// expensive to be present in a release build but may be helpful during
353/// development. The result of expanding `debug_assert_ne!` is always type checked.
354///
355/// # Examples
356///
357/// ```
358/// let a = 3;
359/// let b = 2;
360/// debug_assert_ne!(a, b);
361/// ```
362#[macro_export]
363#[stable(feature = "assert_ne", since = "1.13.0")]
364#[cfg_attr(not(test), rustc_diagnostic_item = "debug_assert_ne_macro")]
365macro_rules! debug_assert_ne {
366    ($($arg:tt)*) => {
367        if $crate::cfg!(debug_assertions) {
368            $crate::assert_ne!($($arg)*);
369        }
370    };
371}
372
373/// Asserts that an expression matches the provided pattern.
374///
375/// This macro is generally preferable to `debug_assert!(matches!(value, pattern))`, because it can
376/// print the debug representation of the actual value shape that did not meet expectations. In
377/// contrast, using [`debug_assert!`] will only print that expectations were not met, but not why.
378///
379/// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The
380/// optional if guard can be used to add additional checks that must be true for the matched value,
381/// otherwise this macro will panic.
382///
383/// On panic, this macro will print the value of the expression with its debug representation.
384///
385/// Like [`assert!`], this macro has a second form, where a custom panic message can be provided.
386///
387/// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only enabled in non optimized
388/// builds by default. An optimized build will not execute `debug_assert_matches!` statements unless
389/// `-C debug-assertions` is passed to the compiler. This makes `debug_assert_matches!` useful for
390/// checks that are too expensive to be present in a release build but may be helpful during
391/// development. The result of expanding `debug_assert_matches!` is always type checked.
392///
393/// # Examples
394///
395/// ```
396/// #![feature(assert_matches)]
397///
398/// use std::assert_matches::debug_assert_matches;
399///
400/// let a = Some(345);
401/// let b = Some(56);
402/// debug_assert_matches!(a, Some(_));
403/// debug_assert_matches!(b, Some(_));
404///
405/// debug_assert_matches!(a, Some(345));
406/// debug_assert_matches!(a, Some(345) | None);
407///
408/// // debug_assert_matches!(a, None); // panics
409/// // debug_assert_matches!(b, Some(345)); // panics
410/// // debug_assert_matches!(b, Some(345) | None); // panics
411///
412/// debug_assert_matches!(a, Some(x) if x > 100);
413/// // debug_assert_matches!(a, Some(x) if x < 100); // panics
414/// ```
415#[unstable(feature = "assert_matches", issue = "82775")]
416#[allow_internal_unstable(assert_matches)]
417#[rustc_macro_transparency = "semitransparent"]
418pub macro debug_assert_matches($($arg:tt)*) {
419    if $crate::cfg!(debug_assertions) {
420        $crate::assert_matches::assert_matches!($($arg)*);
421    }
422}
423
424/// Returns whether the given expression matches the provided pattern.
425///
426/// The pattern syntax is exactly the same as found in a match arm. The optional if guard can be
427/// used to add additional checks that must be true for the matched value, otherwise this macro will
428/// return `false`.
429///
430/// When testing that a value matches a pattern, it's generally preferable to use
431/// [`assert_matches!`] as it will print the debug representation of the value if the assertion
432/// fails.
433///
434/// # Examples
435///
436/// ```
437/// let foo = 'f';
438/// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
439///
440/// let bar = Some(4);
441/// assert!(matches!(bar, Some(x) if x > 2));
442/// ```
443#[macro_export]
444#[stable(feature = "matches_macro", since = "1.42.0")]
445#[cfg_attr(not(test), rustc_diagnostic_item = "matches_macro")]
446macro_rules! matches {
447    ($expression:expr, $pattern:pat $(if $guard:expr)? $(,)?) => {
448        match $expression {
449            $pattern $(if $guard)? => true,
450            _ => false
451        }
452    };
453}
454
455/// Unwraps a result or propagates its error.
456///
457/// The [`?` operator][propagating-errors] was added to replace `try!`
458/// and should be used instead. Furthermore, `try` is a reserved word
459/// in Rust 2018, so if you must use it, you will need to use the
460/// [raw-identifier syntax][ris]: `r#try`.
461///
462/// [propagating-errors]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator
463/// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
464///
465/// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
466/// expression has the value of the wrapped value.
467///
468/// In case of the `Err` variant, it retrieves the inner error. `try!` then
469/// performs conversion using `From`. This provides automatic conversion
470/// between specialized errors and more general ones. The resulting
471/// error is then immediately returned.
472///
473/// Because of the early return, `try!` can only be used in functions that
474/// return [`Result`].
475///
476/// # Examples
477///
478/// ```
479/// use std::io;
480/// use std::fs::File;
481/// use std::io::prelude::*;
482///
483/// enum MyError {
484///     FileWriteError
485/// }
486///
487/// impl From<io::Error> for MyError {
488///     fn from(e: io::Error) -> MyError {
489///         MyError::FileWriteError
490///     }
491/// }
492///
493/// // The preferred method of quick returning Errors
494/// fn write_to_file_question() -> Result<(), MyError> {
495///     let mut file = File::create("my_best_friends.txt")?;
496///     file.write_all(b"This is a list of my best friends.")?;
497///     Ok(())
498/// }
499///
500/// // The previous method of quick returning Errors
501/// fn write_to_file_using_try() -> Result<(), MyError> {
502///     let mut file = r#try!(File::create("my_best_friends.txt"));
503///     r#try!(file.write_all(b"This is a list of my best friends."));
504///     Ok(())
505/// }
506///
507/// // This is equivalent to:
508/// fn write_to_file_using_match() -> Result<(), MyError> {
509///     let mut file = r#try!(File::create("my_best_friends.txt"));
510///     match file.write_all(b"This is a list of my best friends.") {
511///         Ok(v) => v,
512///         Err(e) => return Err(From::from(e)),
513///     }
514///     Ok(())
515/// }
516/// ```
517#[macro_export]
518#[stable(feature = "rust1", since = "1.0.0")]
519#[deprecated(since = "1.39.0", note = "use the `?` operator instead")]
520#[doc(alias = "?")]
521macro_rules! r#try {
522    ($expr:expr $(,)?) => {
523        match $expr {
524            $crate::result::Result::Ok(val) => val,
525            $crate::result::Result::Err(err) => {
526                return $crate::result::Result::Err($crate::convert::From::from(err));
527            }
528        }
529    };
530}
531
532/// Writes formatted data into a buffer.
533///
534/// This macro accepts a 'writer', a format string, and a list of arguments. Arguments will be
535/// formatted according to the specified format string and the result will be passed to the writer.
536/// The writer may be any value with a `write_fmt` method; generally this comes from an
537/// implementation of either the [`fmt::Write`] or the [`io::Write`] trait. The macro
538/// returns whatever the `write_fmt` method returns; commonly a [`fmt::Result`], or an
539/// [`io::Result`].
540///
541/// See [`std::fmt`] for more information on the format string syntax.
542///
543/// [`std::fmt`]: ../std/fmt/index.html
544/// [`fmt::Write`]: crate::fmt::Write
545/// [`io::Write`]: ../std/io/trait.Write.html
546/// [`fmt::Result`]: crate::fmt::Result
547/// [`io::Result`]: ../std/io/type.Result.html
548///
549/// # Examples
550///
551/// ```
552/// use std::io::Write;
553///
554/// fn main() -> std::io::Result<()> {
555///     let mut w = Vec::new();
556///     write!(&mut w, "test")?;
557///     write!(&mut w, "formatted {}", "arguments")?;
558///
559///     assert_eq!(w, b"testformatted arguments");
560///     Ok(())
561/// }
562/// ```
563///
564/// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
565/// implementing either, as objects do not typically implement both. However, the module must
566/// avoid conflict between the trait names, such as by importing them as `_` or otherwise renaming
567/// them:
568///
569/// ```
570/// use std::fmt::Write as _;
571/// use std::io::Write as _;
572///
573/// fn main() -> Result<(), Box<dyn std::error::Error>> {
574///     let mut s = String::new();
575///     let mut v = Vec::new();
576///
577///     write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
578///     write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
579///     assert_eq!(v, b"s = \"abc 123\"");
580///     Ok(())
581/// }
582/// ```
583///
584/// If you also need the trait names themselves, such as to implement one or both on your types,
585/// import the containing module and then name them with a prefix:
586///
587/// ```
588/// # #![allow(unused_imports)]
589/// use std::fmt::{self, Write as _};
590/// use std::io::{self, Write as _};
591///
592/// struct Example;
593///
594/// impl fmt::Write for Example {
595///     fn write_str(&mut self, _s: &str) -> core::fmt::Result {
596///          unimplemented!();
597///     }
598/// }
599/// ```
600///
601/// Note: This macro can be used in `no_std` setups as well.
602/// In a `no_std` setup you are responsible for the implementation details of the components.
603///
604/// ```no_run
605/// use core::fmt::Write;
606///
607/// struct Example;
608///
609/// impl Write for Example {
610///     fn write_str(&mut self, _s: &str) -> core::fmt::Result {
611///          unimplemented!();
612///     }
613/// }
614///
615/// let mut m = Example{};
616/// write!(&mut m, "Hello World").expect("Not written");
617/// ```
618#[macro_export]
619#[stable(feature = "rust1", since = "1.0.0")]
620#[cfg_attr(not(test), rustc_diagnostic_item = "write_macro")]
621macro_rules! write {
622    ($dst:expr, $($arg:tt)*) => {
623        $dst.write_fmt($crate::format_args!($($arg)*))
624    };
625}
626
627/// Writes formatted data into a buffer, with a newline appended.
628///
629/// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
630/// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
631///
632/// For more information, see [`write!`]. For information on the format string syntax, see
633/// [`std::fmt`].
634///
635/// [`std::fmt`]: ../std/fmt/index.html
636///
637/// # Examples
638///
639/// ```
640/// use std::io::{Write, Result};
641///
642/// fn main() -> Result<()> {
643///     let mut w = Vec::new();
644///     writeln!(&mut w)?;
645///     writeln!(&mut w, "test")?;
646///     writeln!(&mut w, "formatted {}", "arguments")?;
647///
648///     assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
649///     Ok(())
650/// }
651/// ```
652#[macro_export]
653#[stable(feature = "rust1", since = "1.0.0")]
654#[cfg_attr(not(test), rustc_diagnostic_item = "writeln_macro")]
655#[allow_internal_unstable(format_args_nl)]
656macro_rules! writeln {
657    ($dst:expr $(,)?) => {
658        $crate::write!($dst, "\n")
659    };
660    ($dst:expr, $($arg:tt)*) => {
661        $dst.write_fmt($crate::format_args_nl!($($arg)*))
662    };
663}
664
665/// Indicates unreachable code.
666///
667/// This is useful any time that the compiler can't determine that some code is unreachable. For
668/// example:
669///
670/// * Match arms with guard conditions.
671/// * Loops that dynamically terminate.
672/// * Iterators that dynamically terminate.
673///
674/// If the determination that the code is unreachable proves incorrect, the
675/// program immediately terminates with a [`panic!`].
676///
677/// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
678/// will cause undefined behavior if the code is reached.
679///
680/// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked
681///
682/// # Panics
683///
684/// This will always [`panic!`] because `unreachable!` is just a shorthand for `panic!` with a
685/// fixed, specific message.
686///
687/// Like `panic!`, this macro has a second form for displaying custom values.
688///
689/// # Examples
690///
691/// Match arms:
692///
693/// ```
694/// # #[allow(dead_code)]
695/// fn foo(x: Option<i32>) {
696///     match x {
697///         Some(n) if n >= 0 => println!("Some(Non-negative)"),
698///         Some(n) if n <  0 => println!("Some(Negative)"),
699///         Some(_)           => unreachable!(), // compile error if commented out
700///         None              => println!("None")
701///     }
702/// }
703/// ```
704///
705/// Iterators:
706///
707/// ```
708/// # #[allow(dead_code)]
709/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
710///     for i in 0.. {
711///         if 3*i < i { panic!("u32 overflow"); }
712///         if x < 3*i { return i-1; }
713///     }
714///     unreachable!("The loop should always return");
715/// }
716/// ```
717#[macro_export]
718#[rustc_builtin_macro(unreachable)]
719#[allow_internal_unstable(edition_panic)]
720#[stable(feature = "rust1", since = "1.0.0")]
721#[cfg_attr(not(test), rustc_diagnostic_item = "unreachable_macro")]
722macro_rules! unreachable {
723    // Expands to either `$crate::panic::unreachable_2015` or `$crate::panic::unreachable_2021`
724    // depending on the edition of the caller.
725    ($($arg:tt)*) => {
726        /* compiler built-in */
727    };
728}
729
730/// Indicates unimplemented code by panicking with a message of "not implemented".
731///
732/// This allows your code to type-check, which is useful if you are prototyping or
733/// implementing a trait that requires multiple methods which you don't plan to use all of.
734///
735/// The difference between `unimplemented!` and [`todo!`] is that while `todo!`
736/// conveys an intent of implementing the functionality later and the message is "not yet
737/// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
738///
739/// Also, some IDEs will mark `todo!`s.
740///
741/// # Panics
742///
743/// This will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a
744/// fixed, specific message.
745///
746/// Like `panic!`, this macro has a second form for displaying custom values.
747///
748/// [`todo!`]: crate::todo
749///
750/// # Examples
751///
752/// Say we have a trait `Foo`:
753///
754/// ```
755/// trait Foo {
756///     fn bar(&self) -> u8;
757///     fn baz(&self);
758///     fn qux(&self) -> Result<u64, ()>;
759/// }
760/// ```
761///
762/// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
763/// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
764/// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
765/// to allow our code to compile.
766///
767/// We still want to have our program stop running if the unimplemented methods are
768/// reached.
769///
770/// ```
771/// # trait Foo {
772/// #     fn bar(&self) -> u8;
773/// #     fn baz(&self);
774/// #     fn qux(&self) -> Result<u64, ()>;
775/// # }
776/// struct MyStruct;
777///
778/// impl Foo for MyStruct {
779///     fn bar(&self) -> u8 {
780///         1 + 1
781///     }
782///
783///     fn baz(&self) {
784///         // It makes no sense to `baz` a `MyStruct`, so we have no logic here
785///         // at all.
786///         // This will display "thread 'main' panicked at 'not implemented'".
787///         unimplemented!();
788///     }
789///
790///     fn qux(&self) -> Result<u64, ()> {
791///         // We have some logic here,
792///         // We can add a message to unimplemented! to display our omission.
793///         // This will display:
794///         // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
795///         unimplemented!("MyStruct isn't quxable");
796///     }
797/// }
798///
799/// fn main() {
800///     let s = MyStruct;
801///     s.bar();
802/// }
803/// ```
804#[macro_export]
805#[stable(feature = "rust1", since = "1.0.0")]
806#[cfg_attr(not(test), rustc_diagnostic_item = "unimplemented_macro")]
807#[allow_internal_unstable(panic_internals)]
808macro_rules! unimplemented {
809    () => {
810        $crate::panicking::panic("not implemented")
811    };
812    ($($arg:tt)+) => {
813        $crate::panic!("not implemented: {}", $crate::format_args!($($arg)+))
814    };
815}
816
817/// Indicates unfinished code.
818///
819/// This can be useful if you are prototyping and just
820/// want a placeholder to let your code pass type analysis.
821///
822/// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
823/// an intent of implementing the functionality later and the message is "not yet
824/// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
825///
826/// Also, some IDEs will mark `todo!`s.
827///
828/// # Panics
829///
830/// This will always [`panic!`] because `todo!` is just a shorthand for `panic!` with a
831/// fixed, specific message.
832///
833/// Like `panic!`, this macro has a second form for displaying custom values.
834///
835/// # Examples
836///
837/// Here's an example of some in-progress code. We have a trait `Foo`:
838///
839/// ```
840/// trait Foo {
841///     fn bar(&self) -> u8;
842///     fn baz(&self);
843///     fn qux(&self) -> Result<u64, ()>;
844/// }
845/// ```
846///
847/// We want to implement `Foo` on one of our types, but we also want to work on
848/// just `bar()` first. In order for our code to compile, we need to implement
849/// `baz()` and `qux()`, so we can use `todo!`:
850///
851/// ```
852/// # trait Foo {
853/// #     fn bar(&self) -> u8;
854/// #     fn baz(&self);
855/// #     fn qux(&self) -> Result<u64, ()>;
856/// # }
857/// struct MyStruct;
858///
859/// impl Foo for MyStruct {
860///     fn bar(&self) -> u8 {
861///         1 + 1
862///     }
863///
864///     fn baz(&self) {
865///         // Let's not worry about implementing baz() for now
866///         todo!();
867///     }
868///
869///     fn qux(&self) -> Result<u64, ()> {
870///         // We can add a message to todo! to display our omission.
871///         // This will display:
872///         // "thread 'main' panicked at 'not yet implemented: MyStruct is not yet quxable'".
873///         todo!("MyStruct is not yet quxable");
874///     }
875/// }
876///
877/// fn main() {
878///     let s = MyStruct;
879///     s.bar();
880///
881///     // We aren't even using baz() or qux(), so this is fine.
882/// }
883/// ```
884#[macro_export]
885#[stable(feature = "todo_macro", since = "1.40.0")]
886#[cfg_attr(not(test), rustc_diagnostic_item = "todo_macro")]
887#[allow_internal_unstable(panic_internals)]
888macro_rules! todo {
889    () => {
890        $crate::panicking::panic("not yet implemented")
891    };
892    ($($arg:tt)+) => {
893        $crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+))
894    };
895}
896
897/// Definitions of built-in macros.
898///
899/// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
900/// with exception of expansion functions transforming macro inputs into outputs,
901/// those functions are provided by the compiler.
902pub(crate) mod builtin {
903
904    /// Causes compilation to fail with the given error message when encountered.
905    ///
906    /// This macro should be used when a crate uses a conditional compilation strategy to provide
907    /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
908    /// but emits an error during *compilation* rather than at *runtime*.
909    ///
910    /// # Examples
911    ///
912    /// Two such examples are macros and `#[cfg]` environments.
913    ///
914    /// Emit a better compiler error if a macro is passed invalid values. Without the final branch,
915    /// the compiler would still emit an error, but the error's message would not mention the two
916    /// valid values.
917    ///
918    /// ```compile_fail
919    /// macro_rules! give_me_foo_or_bar {
920    ///     (foo) => {};
921    ///     (bar) => {};
922    ///     ($x:ident) => {
923    ///         compile_error!("This macro only accepts `foo` or `bar`");
924    ///     }
925    /// }
926    ///
927    /// give_me_foo_or_bar!(neither);
928    /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
929    /// ```
930    ///
931    /// Emit a compiler error if one of a number of features isn't available.
932    ///
933    /// ```compile_fail
934    /// #[cfg(not(any(feature = "foo", feature = "bar")))]
935    /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
936    /// ```
937    #[stable(feature = "compile_error_macro", since = "1.20.0")]
938    #[rustc_builtin_macro]
939    #[macro_export]
940    macro_rules! compile_error {
941        ($msg:expr $(,)?) => {{ /* compiler built-in */ }};
942    }
943
944    /// Constructs parameters for the other string-formatting macros.
945    ///
946    /// This macro functions by taking a formatting string literal containing
947    /// `{}` for each additional argument passed. `format_args!` prepares the
948    /// additional parameters to ensure the output can be interpreted as a string
949    /// and canonicalizes the arguments into a single type. Any value that implements
950    /// the [`Display`] trait can be passed to `format_args!`, as can any
951    /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
952    ///
953    /// This macro produces a value of type [`fmt::Arguments`]. This value can be
954    /// passed to the macros within [`std::fmt`] for performing useful redirection.
955    /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
956    /// proxied through this one. `format_args!`, unlike its derived macros, avoids
957    /// heap allocations.
958    ///
959    /// You can use the [`fmt::Arguments`] value that `format_args!` returns
960    /// in `Debug` and `Display` contexts as seen below. The example also shows
961    /// that `Debug` and `Display` format to the same thing: the interpolated
962    /// format string in `format_args!`.
963    ///
964    /// ```rust
965    /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
966    /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
967    /// assert_eq!("1 foo 2", display);
968    /// assert_eq!(display, debug);
969    /// ```
970    ///
971    /// See [the formatting documentation in `std::fmt`](../std/fmt/index.html)
972    /// for details of the macro argument syntax, and further information.
973    ///
974    /// [`Display`]: crate::fmt::Display
975    /// [`Debug`]: crate::fmt::Debug
976    /// [`fmt::Arguments`]: crate::fmt::Arguments
977    /// [`std::fmt`]: ../std/fmt/index.html
978    /// [`format!`]: ../std/macro.format.html
979    /// [`println!`]: ../std/macro.println.html
980    ///
981    /// # Examples
982    ///
983    /// ```
984    /// use std::fmt;
985    ///
986    /// let s = fmt::format(format_args!("hello {}", "world"));
987    /// assert_eq!(s, format!("hello {}", "world"));
988    /// ```
989    ///
990    /// # Lifetime limitation
991    ///
992    /// Except when no formatting arguments are used,
993    /// the produced `fmt::Arguments` value borrows temporary values,
994    /// which means it can only be used within the same expression
995    /// and cannot be stored for later use.
996    /// This is a known limitation, see [#92698](https://github.com/rust-lang/rust/issues/92698).
997    #[stable(feature = "rust1", since = "1.0.0")]
998    #[cfg_attr(not(test), rustc_diagnostic_item = "format_args_macro")]
999    #[allow_internal_unsafe]
1000    #[allow_internal_unstable(fmt_internals)]
1001    #[rustc_builtin_macro]
1002    #[macro_export]
1003    macro_rules! format_args {
1004        ($fmt:expr) => {{ /* compiler built-in */ }};
1005        ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
1006    }
1007
1008    /// Same as [`format_args`], but can be used in some const contexts.
1009    ///
1010    /// This macro is used by the panic macros for the `const_panic` feature.
1011    ///
1012    /// This macro will be removed once `format_args` is allowed in const contexts.
1013    #[unstable(feature = "const_format_args", issue = "none")]
1014    #[allow_internal_unstable(fmt_internals, const_fmt_arguments_new)]
1015    #[rustc_builtin_macro]
1016    #[macro_export]
1017    macro_rules! const_format_args {
1018        ($fmt:expr) => {{ /* compiler built-in */ }};
1019        ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
1020    }
1021
1022    /// Same as [`format_args`], but adds a newline in the end.
1023    #[unstable(
1024        feature = "format_args_nl",
1025        issue = "none",
1026        reason = "`format_args_nl` is only for internal \
1027                  language use and is subject to change"
1028    )]
1029    #[allow_internal_unstable(fmt_internals)]
1030    #[rustc_builtin_macro]
1031    #[macro_export]
1032    macro_rules! format_args_nl {
1033        ($fmt:expr) => {{ /* compiler built-in */ }};
1034        ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
1035    }
1036
1037    /// Inspects an environment variable at compile time.
1038    ///
1039    /// This macro will expand to the value of the named environment variable at
1040    /// compile time, yielding an expression of type `&'static str`. Use
1041    /// [`std::env::var`] instead if you want to read the value at runtime.
1042    ///
1043    /// [`std::env::var`]: ../std/env/fn.var.html
1044    ///
1045    /// If the environment variable is not defined, then a compilation error
1046    /// will be emitted. To not emit a compile error, use the [`option_env!`]
1047    /// macro instead. A compilation error will also be emitted if the
1048    /// environment variable is not a valid Unicode string.
1049    ///
1050    /// # Examples
1051    ///
1052    /// ```
1053    /// let path: &'static str = env!("PATH");
1054    /// println!("the $PATH variable at the time of compiling was: {path}");
1055    /// ```
1056    ///
1057    /// You can customize the error message by passing a string as the second
1058    /// parameter:
1059    ///
1060    /// ```compile_fail
1061    /// let doc: &'static str = env!("documentation", "what's that?!");
1062    /// ```
1063    ///
1064    /// If the `documentation` environment variable is not defined, you'll get
1065    /// the following error:
1066    ///
1067    /// ```text
1068    /// error: what's that?!
1069    /// ```
1070    #[stable(feature = "rust1", since = "1.0.0")]
1071    #[rustc_builtin_macro]
1072    #[macro_export]
1073    #[rustc_diagnostic_item = "env_macro"] // useful for external lints
1074    macro_rules! env {
1075        ($name:expr $(,)?) => {{ /* compiler built-in */ }};
1076        ($name:expr, $error_msg:expr $(,)?) => {{ /* compiler built-in */ }};
1077    }
1078
1079    /// Optionally inspects an environment variable at compile time.
1080    ///
1081    /// If the named environment variable is present at compile time, this will
1082    /// expand into an expression of type `Option<&'static str>` whose value is
1083    /// `Some` of the value of the environment variable (a compilation error
1084    /// will be emitted if the environment variable is not a valid Unicode
1085    /// string). If the environment variable is not present, then this will
1086    /// expand to `None`. See [`Option<T>`][Option] for more information on this
1087    /// type.  Use [`std::env::var`] instead if you want to read the value at
1088    /// runtime.
1089    ///
1090    /// [`std::env::var`]: ../std/env/fn.var.html
1091    ///
1092    /// A compile time error is only emitted when using this macro if the
1093    /// environment variable exists and is not a valid Unicode string. To also
1094    /// emit a compile error if the environment variable is not present, use the
1095    /// [`env!`] macro instead.
1096    ///
1097    /// # Examples
1098    ///
1099    /// ```
1100    /// let key: Option<&'static str> = option_env!("SECRET_KEY");
1101    /// println!("the secret key might be: {key:?}");
1102    /// ```
1103    #[stable(feature = "rust1", since = "1.0.0")]
1104    #[rustc_builtin_macro]
1105    #[macro_export]
1106    #[rustc_diagnostic_item = "option_env_macro"] // useful for external lints
1107    macro_rules! option_env {
1108        ($name:expr $(,)?) => {{ /* compiler built-in */ }};
1109    }
1110
1111    /// Concatenates identifiers into one identifier.
1112    ///
1113    /// This macro takes any number of comma-separated identifiers, and
1114    /// concatenates them all into one, yielding an expression which is a new
1115    /// identifier. Note that hygiene makes it such that this macro cannot
1116    /// capture local variables. Also, as a general rule, macros are only
1117    /// allowed in item, statement or expression position. That means while
1118    /// you may use this macro for referring to existing variables, functions or
1119    /// modules etc, you cannot define a new one with it.
1120    ///
1121    /// # Examples
1122    ///
1123    /// ```
1124    /// #![feature(concat_idents)]
1125    ///
1126    /// # fn main() {
1127    /// fn foobar() -> u32 { 23 }
1128    ///
1129    /// let f = concat_idents!(foo, bar);
1130    /// println!("{}", f());
1131    ///
1132    /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
1133    /// # }
1134    /// ```
1135    #[unstable(
1136        feature = "concat_idents",
1137        issue = "29599",
1138        reason = "`concat_idents` is not stable enough for use and is subject to change"
1139    )]
1140    #[rustc_builtin_macro]
1141    #[macro_export]
1142    macro_rules! concat_idents {
1143        ($($e:ident),+ $(,)?) => {{ /* compiler built-in */ }};
1144    }
1145
1146    /// Concatenates literals into a byte slice.
1147    ///
1148    /// This macro takes any number of comma-separated literals, and concatenates them all into
1149    /// one, yielding an expression of type `&[u8; _]`, which represents all of the literals
1150    /// concatenated left-to-right. The literals passed can be any combination of:
1151    ///
1152    /// - byte literals (`b'r'`)
1153    /// - byte strings (`b"Rust"`)
1154    /// - arrays of bytes/numbers (`[b'A', 66, b'C']`)
1155    ///
1156    /// # Examples
1157    ///
1158    /// ```
1159    /// #![feature(concat_bytes)]
1160    ///
1161    /// # fn main() {
1162    /// let s: &[u8; 6] = concat_bytes!(b'A', b"BC", [68, b'E', 70]);
1163    /// assert_eq!(s, b"ABCDEF");
1164    /// # }
1165    /// ```
1166    #[unstable(feature = "concat_bytes", issue = "87555")]
1167    #[rustc_builtin_macro]
1168    #[macro_export]
1169    macro_rules! concat_bytes {
1170        ($($e:literal),+ $(,)?) => {{ /* compiler built-in */ }};
1171    }
1172
1173    /// Concatenates literals into a static string slice.
1174    ///
1175    /// This macro takes any number of comma-separated literals, yielding an
1176    /// expression of type `&'static str` which represents all of the literals
1177    /// concatenated left-to-right.
1178    ///
1179    /// Integer and floating point literals are [stringified](core::stringify) in order to be
1180    /// concatenated.
1181    ///
1182    /// # Examples
1183    ///
1184    /// ```
1185    /// let s = concat!("test", 10, 'b', true);
1186    /// assert_eq!(s, "test10btrue");
1187    /// ```
1188    #[stable(feature = "rust1", since = "1.0.0")]
1189    #[rustc_builtin_macro]
1190    #[macro_export]
1191    macro_rules! concat {
1192        ($($e:expr),* $(,)?) => {{ /* compiler built-in */ }};
1193    }
1194
1195    /// Expands to the line number on which it was invoked.
1196    ///
1197    /// With [`column!`] and [`file!`], these macros provide debugging information for
1198    /// developers about the location within the source.
1199    ///
1200    /// The expanded expression has type `u32` and is 1-based, so the first line
1201    /// in each file evaluates to 1, the second to 2, etc. This is consistent
1202    /// with error messages by common compilers or popular editors.
1203    /// The returned line is *not necessarily* the line of the `line!` invocation itself,
1204    /// but rather the first macro invocation leading up to the invocation
1205    /// of the `line!` macro.
1206    ///
1207    /// # Examples
1208    ///
1209    /// ```
1210    /// let current_line = line!();
1211    /// println!("defined on line: {current_line}");
1212    /// ```
1213    #[stable(feature = "rust1", since = "1.0.0")]
1214    #[rustc_builtin_macro]
1215    #[macro_export]
1216    macro_rules! line {
1217        () => {
1218            /* compiler built-in */
1219        };
1220    }
1221
1222    /// Expands to the column number at which it was invoked.
1223    ///
1224    /// With [`line!`] and [`file!`], these macros provide debugging information for
1225    /// developers about the location within the source.
1226    ///
1227    /// The expanded expression has type `u32` and is 1-based, so the first column
1228    /// in each line evaluates to 1, the second to 2, etc. This is consistent
1229    /// with error messages by common compilers or popular editors.
1230    /// The returned column is *not necessarily* the line of the `column!` invocation itself,
1231    /// but rather the first macro invocation leading up to the invocation
1232    /// of the `column!` macro.
1233    ///
1234    /// # Examples
1235    ///
1236    /// ```
1237    /// let current_col = column!();
1238    /// println!("defined on column: {current_col}");
1239    /// ```
1240    ///
1241    /// `column!` counts Unicode code points, not bytes or graphemes. As a result, the first two
1242    /// invocations return the same value, but the third does not.
1243    ///
1244    /// ```
1245    /// let a = ("foobar", column!()).1;
1246    /// let b = ("人之初性本善", column!()).1;
1247    /// let c = ("f̅o̅o̅b̅a̅r̅", column!()).1; // Uses combining overline (U+0305)
1248    ///
1249    /// assert_eq!(a, b);
1250    /// assert_ne!(b, c);
1251    /// ```
1252    #[stable(feature = "rust1", since = "1.0.0")]
1253    #[rustc_builtin_macro]
1254    #[macro_export]
1255    macro_rules! column {
1256        () => {
1257            /* compiler built-in */
1258        };
1259    }
1260
1261    /// Expands to the file name in which it was invoked.
1262    ///
1263    /// With [`line!`] and [`column!`], these macros provide debugging information for
1264    /// developers about the location within the source.
1265    ///
1266    /// The expanded expression has type `&'static str`, and the returned file
1267    /// is not the invocation of the `file!` macro itself, but rather the
1268    /// first macro invocation leading up to the invocation of the `file!`
1269    /// macro.
1270    ///
1271    /// # Examples
1272    ///
1273    /// ```
1274    /// let this_file = file!();
1275    /// println!("defined in file: {this_file}");
1276    /// ```
1277    #[stable(feature = "rust1", since = "1.0.0")]
1278    #[rustc_builtin_macro]
1279    #[macro_export]
1280    macro_rules! file {
1281        () => {
1282            /* compiler built-in */
1283        };
1284    }
1285
1286    /// Stringifies its arguments.
1287    ///
1288    /// This macro will yield an expression of type `&'static str` which is the
1289    /// stringification of all the tokens passed to the macro. No restrictions
1290    /// are placed on the syntax of the macro invocation itself.
1291    ///
1292    /// Note that the expanded results of the input tokens may change in the
1293    /// future. You should be careful if you rely on the output.
1294    ///
1295    /// # Examples
1296    ///
1297    /// ```
1298    /// let one_plus_one = stringify!(1 + 1);
1299    /// assert_eq!(one_plus_one, "1 + 1");
1300    /// ```
1301    #[stable(feature = "rust1", since = "1.0.0")]
1302    #[rustc_builtin_macro]
1303    #[macro_export]
1304    macro_rules! stringify {
1305        ($($t:tt)*) => {
1306            /* compiler built-in */
1307        };
1308    }
1309
1310    /// Includes a UTF-8 encoded file as a string.
1311    ///
1312    /// The file is located relative to the current file (similarly to how
1313    /// modules are found). The provided path is interpreted in a platform-specific
1314    /// way at compile time. So, for instance, an invocation with a Windows path
1315    /// containing backslashes `\` would not compile correctly on Unix.
1316    ///
1317    /// This macro will yield an expression of type `&'static str` which is the
1318    /// contents of the file.
1319    ///
1320    /// # Examples
1321    ///
1322    /// Assume there are two files in the same directory with the following
1323    /// contents:
1324    ///
1325    /// File 'spanish.in':
1326    ///
1327    /// ```text
1328    /// adiós
1329    /// ```
1330    ///
1331    /// File 'main.rs':
1332    ///
1333    /// ```ignore (cannot-doctest-external-file-dependency)
1334    /// fn main() {
1335    ///     let my_str = include_str!("spanish.in");
1336    ///     assert_eq!(my_str, "adiós\n");
1337    ///     print!("{my_str}");
1338    /// }
1339    /// ```
1340    ///
1341    /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1342    #[stable(feature = "rust1", since = "1.0.0")]
1343    #[rustc_builtin_macro]
1344    #[macro_export]
1345    #[cfg_attr(not(test), rustc_diagnostic_item = "include_str_macro")]
1346    macro_rules! include_str {
1347        ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1348    }
1349
1350    /// Includes a file as a reference to a byte array.
1351    ///
1352    /// The file is located relative to the current file (similarly to how
1353    /// modules are found). The provided path is interpreted in a platform-specific
1354    /// way at compile time. So, for instance, an invocation with a Windows path
1355    /// containing backslashes `\` would not compile correctly on Unix.
1356    ///
1357    /// This macro will yield an expression of type `&'static [u8; N]` which is
1358    /// the contents of the file.
1359    ///
1360    /// # Examples
1361    ///
1362    /// Assume there are two files in the same directory with the following
1363    /// contents:
1364    ///
1365    /// File 'spanish.in':
1366    ///
1367    /// ```text
1368    /// adiós
1369    /// ```
1370    ///
1371    /// File 'main.rs':
1372    ///
1373    /// ```ignore (cannot-doctest-external-file-dependency)
1374    /// fn main() {
1375    ///     let bytes = include_bytes!("spanish.in");
1376    ///     assert_eq!(bytes, b"adi\xc3\xb3s\n");
1377    ///     print!("{}", String::from_utf8_lossy(bytes));
1378    /// }
1379    /// ```
1380    ///
1381    /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1382    #[stable(feature = "rust1", since = "1.0.0")]
1383    #[rustc_builtin_macro]
1384    #[macro_export]
1385    #[cfg_attr(not(test), rustc_diagnostic_item = "include_bytes_macro")]
1386    macro_rules! include_bytes {
1387        ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1388    }
1389
1390    /// Expands to a string that represents the current module path.
1391    ///
1392    /// The current module path can be thought of as the hierarchy of modules
1393    /// leading back up to the crate root. The first component of the path
1394    /// returned is the name of the crate currently being compiled.
1395    ///
1396    /// # Examples
1397    ///
1398    /// ```
1399    /// mod test {
1400    ///     pub fn foo() {
1401    ///         assert!(module_path!().ends_with("test"));
1402    ///     }
1403    /// }
1404    ///
1405    /// test::foo();
1406    /// ```
1407    #[stable(feature = "rust1", since = "1.0.0")]
1408    #[rustc_builtin_macro]
1409    #[macro_export]
1410    macro_rules! module_path {
1411        () => {
1412            /* compiler built-in */
1413        };
1414    }
1415
1416    /// Evaluates boolean combinations of configuration flags at compile-time.
1417    ///
1418    /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1419    /// boolean expression evaluation of configuration flags. This frequently
1420    /// leads to less duplicated code.
1421    ///
1422    /// The syntax given to this macro is the same syntax as the [`cfg`]
1423    /// attribute.
1424    ///
1425    /// `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For
1426    /// example, all blocks in an if/else expression need to be valid when `cfg!` is used for
1427    /// the condition, regardless of what `cfg!` is evaluating.
1428    ///
1429    /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1430    ///
1431    /// # Examples
1432    ///
1433    /// ```
1434    /// let my_directory = if cfg!(windows) {
1435    ///     "windows-specific-directory"
1436    /// } else {
1437    ///     "unix-directory"
1438    /// };
1439    /// ```
1440    #[stable(feature = "rust1", since = "1.0.0")]
1441    #[rustc_builtin_macro]
1442    #[macro_export]
1443    macro_rules! cfg {
1444        ($($cfg:tt)*) => {
1445            /* compiler built-in */
1446        };
1447    }
1448
1449    /// Parses a file as an expression or an item according to the context.
1450    ///
1451    /// **Warning**: For multi-file Rust projects, the `include!` macro is probably not what you
1452    /// are looking for. Usually, multi-file Rust projects use
1453    /// [modules](https://doc.rust-lang.org/reference/items/modules.html). Multi-file projects and
1454    /// modules are explained in the Rust-by-Example book
1455    /// [here](https://doc.rust-lang.org/rust-by-example/mod/split.html) and the module system is
1456    /// explained in the Rust Book
1457    /// [here](https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html).
1458    ///
1459    /// The included file is placed in the surrounding code
1460    /// [unhygienically](https://doc.rust-lang.org/reference/macros-by-example.html#hygiene). If
1461    /// the included file is parsed as an expression and variables or functions share names across
1462    /// both files, it could result in variables or functions being different from what the
1463    /// included file expected.
1464    ///
1465    /// The included file is located relative to the current file (similarly to how modules are
1466    /// found). The provided path is interpreted in a platform-specific way at compile time. So,
1467    /// for instance, an invocation with a Windows path containing backslashes `\` would not
1468    /// compile correctly on Unix.
1469    ///
1470    /// # Uses
1471    ///
1472    /// The `include!` macro is primarily used for two purposes. It is used to include
1473    /// documentation that is written in a separate file and it is used to include [build artifacts
1474    /// usually as a result from the `build.rs`
1475    /// script](https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script).
1476    ///
1477    /// When using the `include` macro to include stretches of documentation, remember that the
1478    /// included file still needs to be a valid Rust syntax. It is also possible to
1479    /// use the [`include_str`] macro as `#![doc = include_str!("...")]` (at the module level) or
1480    /// `#[doc = include_str!("...")]` (at the item level) to include documentation from a plain
1481    /// text or markdown file.
1482    ///
1483    /// # Examples
1484    ///
1485    /// Assume there are two files in the same directory with the following contents:
1486    ///
1487    /// File 'monkeys.in':
1488    ///
1489    /// ```ignore (only-for-syntax-highlight)
1490    /// ['🙈', '🙊', '🙉']
1491    ///     .iter()
1492    ///     .cycle()
1493    ///     .take(6)
1494    ///     .collect::<String>()
1495    /// ```
1496    ///
1497    /// File 'main.rs':
1498    ///
1499    /// ```ignore (cannot-doctest-external-file-dependency)
1500    /// fn main() {
1501    ///     let my_string = include!("monkeys.in");
1502    ///     assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1503    ///     println!("{my_string}");
1504    /// }
1505    /// ```
1506    ///
1507    /// Compiling 'main.rs' and running the resulting binary will print
1508    /// "🙈🙊🙉🙈🙊🙉".
1509    #[stable(feature = "rust1", since = "1.0.0")]
1510    #[rustc_builtin_macro]
1511    #[macro_export]
1512    #[rustc_diagnostic_item = "include_macro"] // useful for external lints
1513    macro_rules! include {
1514        ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1515    }
1516
1517    /// Automatic Differentiation macro which allows generating a new function to compute
1518    /// the derivative of a given function. It may only be applied to a function.
1519    /// The expected usage syntax is
1520    /// `#[autodiff(NAME, MODE, INPUT_ACTIVITIES, OUTPUT_ACTIVITY)]`
1521    /// where:
1522    /// NAME is a string that represents a valid function name.
1523    /// MODE is any of Forward, Reverse, ForwardFirst, ReverseFirst.
1524    /// INPUT_ACTIVITIES consists of one valid activity for each input parameter.
1525    /// OUTPUT_ACTIVITY must not be set if we implicitly return nothing (or explicitly return
1526    /// `-> ()`). Otherwise it must be set to one of the allowed activities.
1527    #[unstable(feature = "autodiff", issue = "124509")]
1528    #[allow_internal_unstable(rustc_attrs)]
1529    #[rustc_builtin_macro]
1530    pub macro autodiff($item:item) {
1531        /* compiler built-in */
1532    }
1533
1534    /// Asserts that a boolean expression is `true` at runtime.
1535    ///
1536    /// This will invoke the [`panic!`] macro if the provided expression cannot be
1537    /// evaluated to `true` at runtime.
1538    ///
1539    /// # Uses
1540    ///
1541    /// Assertions are always checked in both debug and release builds, and cannot
1542    /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1543    /// release builds by default.
1544    ///
1545    /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if
1546    /// violated could lead to unsafety.
1547    ///
1548    /// Other use-cases of `assert!` include testing and enforcing run-time
1549    /// invariants in safe code (whose violation cannot result in unsafety).
1550    ///
1551    /// # Custom Messages
1552    ///
1553    /// This macro has a second form, where a custom panic message can
1554    /// be provided with or without arguments for formatting. See [`std::fmt`]
1555    /// for syntax for this form. Expressions used as format arguments will only
1556    /// be evaluated if the assertion fails.
1557    ///
1558    /// [`std::fmt`]: ../std/fmt/index.html
1559    ///
1560    /// # Examples
1561    ///
1562    /// ```
1563    /// // the panic message for these assertions is the stringified value of the
1564    /// // expression given.
1565    /// assert!(true);
1566    ///
1567    /// fn some_computation() -> bool { true } // a very simple function
1568    ///
1569    /// assert!(some_computation());
1570    ///
1571    /// // assert with a custom message
1572    /// let x = true;
1573    /// assert!(x, "x wasn't true!");
1574    ///
1575    /// let a = 3; let b = 27;
1576    /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1577    /// ```
1578    #[stable(feature = "rust1", since = "1.0.0")]
1579    #[rustc_builtin_macro]
1580    #[macro_export]
1581    #[rustc_diagnostic_item = "assert_macro"]
1582    #[allow_internal_unstable(
1583        core_intrinsics,
1584        panic_internals,
1585        edition_panic,
1586        generic_assert_internals
1587    )]
1588    macro_rules! assert {
1589        ($cond:expr $(,)?) => {{ /* compiler built-in */ }};
1590        ($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }};
1591    }
1592
1593    /// Prints passed tokens into the standard output.
1594    #[unstable(
1595        feature = "log_syntax",
1596        issue = "29598",
1597        reason = "`log_syntax!` is not stable enough for use and is subject to change"
1598    )]
1599    #[rustc_builtin_macro]
1600    #[macro_export]
1601    macro_rules! log_syntax {
1602        ($($arg:tt)*) => {
1603            /* compiler built-in */
1604        };
1605    }
1606
1607    /// Enables or disables tracing functionality used for debugging other macros.
1608    #[unstable(
1609        feature = "trace_macros",
1610        issue = "29598",
1611        reason = "`trace_macros` is not stable enough for use and is subject to change"
1612    )]
1613    #[rustc_builtin_macro]
1614    #[macro_export]
1615    macro_rules! trace_macros {
1616        (true) => {{ /* compiler built-in */ }};
1617        (false) => {{ /* compiler built-in */ }};
1618    }
1619
1620    /// Attribute macro used to apply derive macros.
1621    ///
1622    /// See [the reference] for more info.
1623    ///
1624    /// [the reference]: ../../../reference/attributes/derive.html
1625    #[stable(feature = "rust1", since = "1.0.0")]
1626    #[rustc_builtin_macro]
1627    pub macro derive($item:item) {
1628        /* compiler built-in */
1629    }
1630
1631    /// Attribute macro used to apply derive macros for implementing traits
1632    /// in a const context.
1633    ///
1634    /// See [the reference] for more info.
1635    ///
1636    /// [the reference]: ../../../reference/attributes/derive.html
1637    #[unstable(feature = "derive_const", issue = "none")]
1638    #[rustc_builtin_macro]
1639    pub macro derive_const($item:item) {
1640        /* compiler built-in */
1641    }
1642
1643    /// Attribute macro applied to a function to turn it into a unit test.
1644    ///
1645    /// See [the reference] for more info.
1646    ///
1647    /// [the reference]: ../../../reference/attributes/testing.html#the-test-attribute
1648    #[stable(feature = "rust1", since = "1.0.0")]
1649    #[allow_internal_unstable(test, rustc_attrs, coverage_attribute)]
1650    #[rustc_builtin_macro]
1651    pub macro test($item:item) {
1652        /* compiler built-in */
1653    }
1654
1655    /// Attribute macro applied to a function to turn it into a benchmark test.
1656    #[unstable(
1657        feature = "test",
1658        issue = "50297",
1659        soft,
1660        reason = "`bench` is a part of custom test frameworks which are unstable"
1661    )]
1662    #[allow_internal_unstable(test, rustc_attrs, coverage_attribute)]
1663    #[rustc_builtin_macro]
1664    pub macro bench($item:item) {
1665        /* compiler built-in */
1666    }
1667
1668    /// An implementation detail of the `#[test]` and `#[bench]` macros.
1669    #[unstable(
1670        feature = "custom_test_frameworks",
1671        issue = "50297",
1672        reason = "custom test frameworks are an unstable feature"
1673    )]
1674    #[allow_internal_unstable(test, rustc_attrs)]
1675    #[rustc_builtin_macro]
1676    pub macro test_case($item:item) {
1677        /* compiler built-in */
1678    }
1679
1680    /// Attribute macro applied to a static to register it as a global allocator.
1681    ///
1682    /// See also [`std::alloc::GlobalAlloc`](../../../std/alloc/trait.GlobalAlloc.html).
1683    #[stable(feature = "global_allocator", since = "1.28.0")]
1684    #[allow_internal_unstable(rustc_attrs)]
1685    #[rustc_builtin_macro]
1686    pub macro global_allocator($item:item) {
1687        /* compiler built-in */
1688    }
1689
1690    /// Attribute macro applied to a function to give it a post-condition.
1691    ///
1692    /// The attribute carries an argument token-tree which is
1693    /// eventually parsed as a unary closure expression that is
1694    /// invoked on a reference to the return value.
1695    #[unstable(feature = "contracts", issue = "128044")]
1696    #[allow_internal_unstable(contracts_internals)]
1697    #[rustc_builtin_macro]
1698    pub macro contracts_ensures($item:item) {
1699        /* compiler built-in */
1700    }
1701
1702    /// Attribute macro applied to a function to give it a precondition.
1703    ///
1704    /// The attribute carries an argument token-tree which is
1705    /// eventually parsed as an boolean expression with access to the
1706    /// function's formal parameters
1707    #[unstable(feature = "contracts", issue = "128044")]
1708    #[allow_internal_unstable(contracts_internals)]
1709    #[rustc_builtin_macro]
1710    pub macro contracts_requires($item:item) {
1711        /* compiler built-in */
1712    }
1713
1714    /// Attribute macro applied to a function to register it as a handler for allocation failure.
1715    ///
1716    /// See also [`std::alloc::handle_alloc_error`](../../../std/alloc/fn.handle_alloc_error.html).
1717    #[unstable(feature = "alloc_error_handler", issue = "51540")]
1718    #[allow_internal_unstable(rustc_attrs)]
1719    #[rustc_builtin_macro]
1720    pub macro alloc_error_handler($item:item) {
1721        /* compiler built-in */
1722    }
1723
1724    /// Keeps the item it's applied to if the passed path is accessible, and removes it otherwise.
1725    #[unstable(
1726        feature = "cfg_accessible",
1727        issue = "64797",
1728        reason = "`cfg_accessible` is not fully implemented"
1729    )]
1730    #[rustc_builtin_macro]
1731    pub macro cfg_accessible($item:item) {
1732        /* compiler built-in */
1733    }
1734
1735    /// Expands all `#[cfg]` and `#[cfg_attr]` attributes in the code fragment it's applied to.
1736    #[unstable(
1737        feature = "cfg_eval",
1738        issue = "82679",
1739        reason = "`cfg_eval` is a recently implemented feature"
1740    )]
1741    #[rustc_builtin_macro]
1742    pub macro cfg_eval($($tt:tt)*) {
1743        /* compiler built-in */
1744    }
1745
1746    /// Unstable placeholder for type ascription.
1747    #[allow_internal_unstable(builtin_syntax)]
1748    #[unstable(
1749        feature = "type_ascription",
1750        issue = "23416",
1751        reason = "placeholder syntax for type ascription"
1752    )]
1753    #[rustfmt::skip]
1754    pub macro type_ascribe($expr:expr, $ty:ty) {
1755        builtin # type_ascribe($expr, $ty)
1756    }
1757
1758    /// Unstable placeholder for deref patterns.
1759    #[allow_internal_unstable(builtin_syntax)]
1760    #[unstable(
1761        feature = "deref_patterns",
1762        issue = "87121",
1763        reason = "placeholder syntax for deref patterns"
1764    )]
1765    pub macro deref($pat:pat) {
1766        builtin # deref($pat)
1767    }
1768}