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