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