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