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 debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
969    /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
970    /// assert_eq!("1 foo 2", display);
971    /// assert_eq!(display, debug);
972    /// ```
973    ///
974    /// See [the formatting documentation in `std::fmt`](../std/fmt/index.html)
975    /// for details of the macro argument syntax, and further information.
976    ///
977    /// [`Display`]: crate::fmt::Display
978    /// [`Debug`]: crate::fmt::Debug
979    /// [`fmt::Arguments`]: crate::fmt::Arguments
980    /// [`std::fmt`]: ../std/fmt/index.html
981    /// [`format!`]: ../std/macro.format.html
982    /// [`println!`]: ../std/macro.println.html
983    ///
984    /// # Examples
985    ///
986    /// ```
987    /// use std::fmt;
988    ///
989    /// let s = fmt::format(format_args!("hello {}", "world"));
990    /// assert_eq!(s, format!("hello {}", "world"));
991    /// ```
992    ///
993    /// # Lifetime limitation
994    ///
995    /// Except when no formatting arguments are used,
996    /// the produced `fmt::Arguments` value borrows temporary values,
997    /// which means it can only be used within the same expression
998    /// and cannot be stored for later use.
999    /// This is a known limitation, see [#92698](https://github.com/rust-lang/rust/issues/92698).
1000    #[stable(feature = "rust1", since = "1.0.0")]
1001    #[rustc_diagnostic_item = "format_args_macro"]
1002    #[allow_internal_unsafe]
1003    #[allow_internal_unstable(fmt_internals)]
1004    #[rustc_builtin_macro]
1005    #[macro_export]
1006    macro_rules! format_args {
1007        ($fmt:expr) => {{ /* compiler built-in */ }};
1008        ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
1009    }
1010
1011    /// Same as [`format_args`], but can be used in some const contexts.
1012    ///
1013    /// This macro is used by the panic macros for the `const_panic` feature.
1014    ///
1015    /// This macro will be removed once `format_args` is allowed in const contexts.
1016    #[unstable(feature = "const_format_args", issue = "none")]
1017    #[allow_internal_unstable(fmt_internals, const_fmt_arguments_new)]
1018    #[rustc_builtin_macro]
1019    #[macro_export]
1020    macro_rules! const_format_args {
1021        ($fmt:expr) => {{ /* compiler built-in */ }};
1022        ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
1023    }
1024
1025    /// Same as [`format_args`], but adds a newline in the end.
1026    #[unstable(
1027        feature = "format_args_nl",
1028        issue = "none",
1029        reason = "`format_args_nl` is only for internal \
1030                  language use and is subject to change"
1031    )]
1032    #[allow_internal_unstable(fmt_internals)]
1033    #[rustc_builtin_macro]
1034    #[macro_export]
1035    macro_rules! format_args_nl {
1036        ($fmt:expr) => {{ /* compiler built-in */ }};
1037        ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
1038    }
1039
1040    /// Inspects an environment variable at compile time.
1041    ///
1042    /// This macro will expand to the value of the named environment variable at
1043    /// compile time, yielding an expression of type `&'static str`. Use
1044    /// [`std::env::var`] instead if you want to read the value at runtime.
1045    ///
1046    /// [`std::env::var`]: ../std/env/fn.var.html
1047    ///
1048    /// If the environment variable is not defined, then a compilation error
1049    /// will be emitted. To not emit a compile error, use the [`option_env!`]
1050    /// macro instead. A compilation error will also be emitted if the
1051    /// environment variable is not a valid Unicode string.
1052    ///
1053    /// # Examples
1054    ///
1055    /// ```
1056    /// let path: &'static str = env!("PATH");
1057    /// println!("the $PATH variable at the time of compiling was: {path}");
1058    /// ```
1059    ///
1060    /// You can customize the error message by passing a string as the second
1061    /// parameter:
1062    ///
1063    /// ```compile_fail
1064    /// let doc: &'static str = env!("documentation", "what's that?!");
1065    /// ```
1066    ///
1067    /// If the `documentation` environment variable is not defined, you'll get
1068    /// the following error:
1069    ///
1070    /// ```text
1071    /// error: what's that?!
1072    /// ```
1073    #[stable(feature = "rust1", since = "1.0.0")]
1074    #[rustc_builtin_macro]
1075    #[macro_export]
1076    #[rustc_diagnostic_item = "env_macro"] // useful for external lints
1077    macro_rules! env {
1078        ($name:expr $(,)?) => {{ /* compiler built-in */ }};
1079        ($name:expr, $error_msg:expr $(,)?) => {{ /* compiler built-in */ }};
1080    }
1081
1082    /// Optionally inspects an environment variable at compile time.
1083    ///
1084    /// If the named environment variable is present at compile time, this will
1085    /// expand into an expression of type `Option<&'static str>` whose value is
1086    /// `Some` of the value of the environment variable (a compilation error
1087    /// will be emitted if the environment variable is not a valid Unicode
1088    /// string). If the environment variable is not present, then this will
1089    /// expand to `None`. See [`Option<T>`][Option] for more information on this
1090    /// type.  Use [`std::env::var`] instead if you want to read the value at
1091    /// runtime.
1092    ///
1093    /// [`std::env::var`]: ../std/env/fn.var.html
1094    ///
1095    /// A compile time error is only emitted when using this macro if the
1096    /// environment variable exists and is not a valid Unicode string. To also
1097    /// emit a compile error if the environment variable is not present, use the
1098    /// [`env!`] macro instead.
1099    ///
1100    /// # Examples
1101    ///
1102    /// ```
1103    /// let key: Option<&'static str> = option_env!("SECRET_KEY");
1104    /// println!("the secret key might be: {key:?}");
1105    /// ```
1106    #[stable(feature = "rust1", since = "1.0.0")]
1107    #[rustc_builtin_macro]
1108    #[macro_export]
1109    #[rustc_diagnostic_item = "option_env_macro"] // useful for external lints
1110    macro_rules! option_env {
1111        ($name:expr $(,)?) => {{ /* compiler built-in */ }};
1112    }
1113
1114    /// Concatenates literals into a byte slice.
1115    ///
1116    /// This macro takes any number of comma-separated literals, and concatenates them all into
1117    /// one, yielding an expression of type `&[u8; _]`, which represents all of the literals
1118    /// concatenated left-to-right. The literals passed can be any combination of:
1119    ///
1120    /// - byte literals (`b'r'`)
1121    /// - byte strings (`b"Rust"`)
1122    /// - arrays of bytes/numbers (`[b'A', 66, b'C']`)
1123    ///
1124    /// # Examples
1125    ///
1126    /// ```
1127    /// #![feature(concat_bytes)]
1128    ///
1129    /// # fn main() {
1130    /// let s: &[u8; 6] = concat_bytes!(b'A', b"BC", [68, b'E', 70]);
1131    /// assert_eq!(s, b"ABCDEF");
1132    /// # }
1133    /// ```
1134    #[unstable(feature = "concat_bytes", issue = "87555")]
1135    #[rustc_builtin_macro]
1136    #[macro_export]
1137    macro_rules! concat_bytes {
1138        ($($e:literal),+ $(,)?) => {{ /* compiler built-in */ }};
1139    }
1140
1141    /// Concatenates literals into a static string slice.
1142    ///
1143    /// This macro takes any number of comma-separated literals, yielding an
1144    /// expression of type `&'static str` which represents all of the literals
1145    /// concatenated left-to-right.
1146    ///
1147    /// Integer and floating point literals are [stringified](core::stringify) in order to be
1148    /// concatenated.
1149    ///
1150    /// # Examples
1151    ///
1152    /// ```
1153    /// let s = concat!("test", 10, 'b', true);
1154    /// assert_eq!(s, "test10btrue");
1155    /// ```
1156    #[stable(feature = "rust1", since = "1.0.0")]
1157    #[rustc_builtin_macro]
1158    #[rustc_diagnostic_item = "macro_concat"]
1159    #[macro_export]
1160    macro_rules! concat {
1161        ($($e:expr),* $(,)?) => {{ /* compiler built-in */ }};
1162    }
1163
1164    /// Expands to the line number on which it was invoked.
1165    ///
1166    /// With [`column!`] and [`file!`], these macros provide debugging information for
1167    /// developers about the location within the source.
1168    ///
1169    /// The expanded expression has type `u32` and is 1-based, so the first line
1170    /// in each file evaluates to 1, the second to 2, etc. This is consistent
1171    /// with error messages by common compilers or popular editors.
1172    /// The returned line is *not necessarily* the line of the `line!` invocation itself,
1173    /// but rather the first macro invocation leading up to the invocation
1174    /// of the `line!` macro.
1175    ///
1176    /// # Examples
1177    ///
1178    /// ```
1179    /// let current_line = line!();
1180    /// println!("defined on line: {current_line}");
1181    /// ```
1182    #[stable(feature = "rust1", since = "1.0.0")]
1183    #[rustc_builtin_macro]
1184    #[macro_export]
1185    macro_rules! line {
1186        () => {
1187            /* compiler built-in */
1188        };
1189    }
1190
1191    /// Expands to the column number at which it was invoked.
1192    ///
1193    /// With [`line!`] and [`file!`], these macros provide debugging information for
1194    /// developers about the location within the source.
1195    ///
1196    /// The expanded expression has type `u32` and is 1-based, so the first column
1197    /// in each line evaluates to 1, the second to 2, etc. This is consistent
1198    /// with error messages by common compilers or popular editors.
1199    /// The returned column is *not necessarily* the line of the `column!` invocation itself,
1200    /// but rather the first macro invocation leading up to the invocation
1201    /// of the `column!` macro.
1202    ///
1203    /// # Examples
1204    ///
1205    /// ```
1206    /// let current_col = column!();
1207    /// println!("defined on column: {current_col}");
1208    /// ```
1209    ///
1210    /// `column!` counts Unicode code points, not bytes or graphemes. As a result, the first two
1211    /// invocations return the same value, but the third does not.
1212    ///
1213    /// ```
1214    /// let a = ("foobar", column!()).1;
1215    /// let b = ("人之初性本善", column!()).1;
1216    /// let c = ("f̅o̅o̅b̅a̅r̅", column!()).1; // Uses combining overline (U+0305)
1217    ///
1218    /// assert_eq!(a, b);
1219    /// assert_ne!(b, c);
1220    /// ```
1221    #[stable(feature = "rust1", since = "1.0.0")]
1222    #[rustc_builtin_macro]
1223    #[macro_export]
1224    macro_rules! column {
1225        () => {
1226            /* compiler built-in */
1227        };
1228    }
1229
1230    /// Expands to the file name in which it was invoked.
1231    ///
1232    /// With [`line!`] and [`column!`], these macros provide debugging information for
1233    /// developers about the location within the source.
1234    ///
1235    /// The expanded expression has type `&'static str`, and the returned file
1236    /// is not the invocation of the `file!` macro itself, but rather the
1237    /// first macro invocation leading up to the invocation of the `file!`
1238    /// macro.
1239    ///
1240    /// The file name is derived from the crate root's source path passed to the Rust compiler
1241    /// and the sequence the compiler takes to get from the crate root to the
1242    /// module containing `file!`, modified by any flags passed to the Rust compiler (e.g.
1243    /// `--remap-path-prefix`).  If the crate's source path is relative, the initial base
1244    /// directory will be the working directory of the Rust compiler.  For example, if the source
1245    /// path passed to the compiler is `./src/lib.rs` which has a `mod foo;` with a source path of
1246    /// `src/foo/mod.rs`, then calling `file!` inside `mod foo;` will return `./src/foo/mod.rs`.
1247    ///
1248    /// Future compiler options might make further changes to the behavior of `file!`,
1249    /// including potentially making it entirely empty. Code (e.g. test libraries)
1250    /// relying on `file!` producing an openable file path would be incompatible
1251    /// with such options, and might wish to recommend not using those options.
1252    ///
1253    /// # Examples
1254    ///
1255    /// ```
1256    /// let this_file = file!();
1257    /// println!("defined in file: {this_file}");
1258    /// ```
1259    #[stable(feature = "rust1", since = "1.0.0")]
1260    #[rustc_builtin_macro]
1261    #[macro_export]
1262    macro_rules! file {
1263        () => {
1264            /* compiler built-in */
1265        };
1266    }
1267
1268    /// Stringifies its arguments.
1269    ///
1270    /// This macro will yield an expression of type `&'static str` which is the
1271    /// stringification of all the tokens passed to the macro. No restrictions
1272    /// are placed on the syntax of the macro invocation itself.
1273    ///
1274    /// Note that the expanded results of the input tokens may change in the
1275    /// future. You should be careful if you rely on the output.
1276    ///
1277    /// # Examples
1278    ///
1279    /// ```
1280    /// let one_plus_one = stringify!(1 + 1);
1281    /// assert_eq!(one_plus_one, "1 + 1");
1282    /// ```
1283    #[stable(feature = "rust1", since = "1.0.0")]
1284    #[rustc_builtin_macro]
1285    #[macro_export]
1286    macro_rules! stringify {
1287        ($($t:tt)*) => {
1288            /* compiler built-in */
1289        };
1290    }
1291
1292    /// Includes a UTF-8 encoded file as a string.
1293    ///
1294    /// The file is located relative to the current file (similarly to how
1295    /// modules are found). The provided path is interpreted in a platform-specific
1296    /// way at compile time. So, for instance, an invocation with a Windows path
1297    /// containing backslashes `\` would not compile correctly on Unix.
1298    ///
1299    /// This macro will yield an expression of type `&'static str` which is the
1300    /// contents of the file.
1301    ///
1302    /// # Examples
1303    ///
1304    /// Assume there are two files in the same directory with the following
1305    /// contents:
1306    ///
1307    /// File 'spanish.in':
1308    ///
1309    /// ```text
1310    /// adiós
1311    /// ```
1312    ///
1313    /// File 'main.rs':
1314    ///
1315    /// ```ignore (cannot-doctest-external-file-dependency)
1316    /// fn main() {
1317    ///     let my_str = include_str!("spanish.in");
1318    ///     assert_eq!(my_str, "adiós\n");
1319    ///     print!("{my_str}");
1320    /// }
1321    /// ```
1322    ///
1323    /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1324    #[stable(feature = "rust1", since = "1.0.0")]
1325    #[rustc_builtin_macro]
1326    #[macro_export]
1327    #[rustc_diagnostic_item = "include_str_macro"]
1328    macro_rules! include_str {
1329        ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1330    }
1331
1332    /// Includes a file as a reference to a byte array.
1333    ///
1334    /// The file is located relative to the current file (similarly to how
1335    /// modules are found). The provided path is interpreted in a platform-specific
1336    /// way at compile time. So, for instance, an invocation with a Windows path
1337    /// containing backslashes `\` would not compile correctly on Unix.
1338    ///
1339    /// This macro will yield an expression of type `&'static [u8; N]` which is
1340    /// the contents of the file.
1341    ///
1342    /// # Examples
1343    ///
1344    /// Assume there are two files in the same directory with the following
1345    /// contents:
1346    ///
1347    /// File 'spanish.in':
1348    ///
1349    /// ```text
1350    /// adiós
1351    /// ```
1352    ///
1353    /// File 'main.rs':
1354    ///
1355    /// ```ignore (cannot-doctest-external-file-dependency)
1356    /// fn main() {
1357    ///     let bytes = include_bytes!("spanish.in");
1358    ///     assert_eq!(bytes, b"adi\xc3\xb3s\n");
1359    ///     print!("{}", String::from_utf8_lossy(bytes));
1360    /// }
1361    /// ```
1362    ///
1363    /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1364    #[stable(feature = "rust1", since = "1.0.0")]
1365    #[rustc_builtin_macro]
1366    #[macro_export]
1367    #[rustc_diagnostic_item = "include_bytes_macro"]
1368    macro_rules! include_bytes {
1369        ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1370    }
1371
1372    /// Expands to a string that represents the current module path.
1373    ///
1374    /// The current module path can be thought of as the hierarchy of modules
1375    /// leading back up to the crate root. The first component of the path
1376    /// returned is the name of the crate currently being compiled.
1377    ///
1378    /// # Examples
1379    ///
1380    /// ```
1381    /// mod test {
1382    ///     pub fn foo() {
1383    ///         assert!(module_path!().ends_with("test"));
1384    ///     }
1385    /// }
1386    ///
1387    /// test::foo();
1388    /// ```
1389    #[stable(feature = "rust1", since = "1.0.0")]
1390    #[rustc_builtin_macro]
1391    #[macro_export]
1392    macro_rules! module_path {
1393        () => {
1394            /* compiler built-in */
1395        };
1396    }
1397
1398    /// Evaluates boolean combinations of configuration flags at compile-time.
1399    ///
1400    /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1401    /// boolean expression evaluation of configuration flags. This frequently
1402    /// leads to less duplicated code.
1403    ///
1404    /// The syntax given to this macro is the same syntax as the [`cfg`]
1405    /// attribute.
1406    ///
1407    /// `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For
1408    /// example, all blocks in an if/else expression need to be valid when `cfg!` is used for
1409    /// the condition, regardless of what `cfg!` is evaluating.
1410    ///
1411    /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1412    ///
1413    /// # Examples
1414    ///
1415    /// ```
1416    /// let my_directory = if cfg!(windows) {
1417    ///     "windows-specific-directory"
1418    /// } else {
1419    ///     "unix-directory"
1420    /// };
1421    /// ```
1422    #[stable(feature = "rust1", since = "1.0.0")]
1423    #[rustc_builtin_macro]
1424    #[macro_export]
1425    macro_rules! cfg {
1426        ($($cfg:tt)*) => {
1427            /* compiler built-in */
1428        };
1429    }
1430
1431    /// Parses a file as an expression or an item according to the context.
1432    ///
1433    /// **Warning**: For multi-file Rust projects, the `include!` macro is probably not what you
1434    /// are looking for. Usually, multi-file Rust projects use
1435    /// [modules](https://doc.rust-lang.org/reference/items/modules.html). Multi-file projects and
1436    /// modules are explained in the Rust-by-Example book
1437    /// [here](https://doc.rust-lang.org/rust-by-example/mod/split.html) and the module system is
1438    /// explained in the Rust Book
1439    /// [here](https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html).
1440    ///
1441    /// The included file is placed in the surrounding code
1442    /// [unhygienically](https://doc.rust-lang.org/reference/macros-by-example.html#hygiene). If
1443    /// the included file is parsed as an expression and variables or functions share names across
1444    /// both files, it could result in variables or functions being different from what the
1445    /// included file expected.
1446    ///
1447    /// The included file is located relative to the current file (similarly to how modules are
1448    /// found). The provided path is interpreted in a platform-specific way at compile time. So,
1449    /// for instance, an invocation with a Windows path containing backslashes `\` would not
1450    /// compile correctly on Unix.
1451    ///
1452    /// # Uses
1453    ///
1454    /// The `include!` macro is primarily used for two purposes. It is used to include
1455    /// documentation that is written in a separate file and it is used to include [build artifacts
1456    /// usually as a result from the `build.rs`
1457    /// script](https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script).
1458    ///
1459    /// When using the `include` macro to include stretches of documentation, remember that the
1460    /// included file still needs to be a valid Rust syntax. It is also possible to
1461    /// use the [`include_str`] macro as `#![doc = include_str!("...")]` (at the module level) or
1462    /// `#[doc = include_str!("...")]` (at the item level) to include documentation from a plain
1463    /// text or markdown file.
1464    ///
1465    /// # Examples
1466    ///
1467    /// Assume there are two files in the same directory with the following contents:
1468    ///
1469    /// File 'monkeys.in':
1470    ///
1471    /// ```ignore (only-for-syntax-highlight)
1472    /// ['🙈', '🙊', '🙉']
1473    ///     .iter()
1474    ///     .cycle()
1475    ///     .take(6)
1476    ///     .collect::<String>()
1477    /// ```
1478    ///
1479    /// File 'main.rs':
1480    ///
1481    /// ```ignore (cannot-doctest-external-file-dependency)
1482    /// fn main() {
1483    ///     let my_string = include!("monkeys.in");
1484    ///     assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1485    ///     println!("{my_string}");
1486    /// }
1487    /// ```
1488    ///
1489    /// Compiling 'main.rs' and running the resulting binary will print
1490    /// "🙈🙊🙉🙈🙊🙉".
1491    #[stable(feature = "rust1", since = "1.0.0")]
1492    #[rustc_builtin_macro]
1493    #[macro_export]
1494    #[rustc_diagnostic_item = "include_macro"] // useful for external lints
1495    macro_rules! include {
1496        ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1497    }
1498
1499    /// This macro uses forward-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_forward(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    #[allow_internal_unstable(core_intrinsics)]
1513    #[rustc_builtin_macro]
1514    pub macro autodiff_forward($item:item) {
1515        /* compiler built-in */
1516    }
1517
1518    /// This macro uses reverse-mode automatic differentiation to generate a new function.
1519    /// It may only be applied to a function. The new function will compute the derivative
1520    /// of the function to which the macro was applied.
1521    ///
1522    /// The expected usage syntax is:
1523    /// `#[autodiff_reverse(NAME, INPUT_ACTIVITIES, OUTPUT_ACTIVITY)]`
1524    ///
1525    /// - `NAME`: A string that represents a valid function name.
1526    /// - `INPUT_ACTIVITIES`: Specifies one valid activity for each input parameter.
1527    /// - `OUTPUT_ACTIVITY`: Must not be set if the function implicitly returns nothing
1528    ///   (or explicitly returns `-> ()`). Otherwise, it must be set to one of the allowed activities.
1529    #[unstable(feature = "autodiff", issue = "124509")]
1530    #[allow_internal_unstable(rustc_attrs)]
1531    #[allow_internal_unstable(core_intrinsics)]
1532    #[rustc_builtin_macro]
1533    pub macro autodiff_reverse($item:item) {
1534        /* compiler built-in */
1535    }
1536
1537    /// Asserts that a boolean expression is `true` at runtime.
1538    ///
1539    /// This will invoke the [`panic!`] macro if the provided expression cannot be
1540    /// evaluated to `true` at runtime.
1541    ///
1542    /// # Uses
1543    ///
1544    /// Assertions are always checked in both debug and release builds, and cannot
1545    /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1546    /// release builds by default.
1547    ///
1548    /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if
1549    /// violated could lead to unsafety.
1550    ///
1551    /// Other use-cases of `assert!` include testing and enforcing run-time
1552    /// invariants in safe code (whose violation cannot result in unsafety).
1553    ///
1554    /// # Custom Messages
1555    ///
1556    /// This macro has a second form, where a custom panic message can
1557    /// be provided with or without arguments for formatting. See [`std::fmt`]
1558    /// for syntax for this form. Expressions used as format arguments will only
1559    /// be evaluated if the assertion fails.
1560    ///
1561    /// [`std::fmt`]: ../std/fmt/index.html
1562    ///
1563    /// # Examples
1564    ///
1565    /// ```
1566    /// // the panic message for these assertions is the stringified value of the
1567    /// // expression given.
1568    /// assert!(true);
1569    ///
1570    /// fn some_computation() -> bool {
1571    ///     // Some expensive computation here
1572    ///     true
1573    /// }
1574    ///
1575    /// assert!(some_computation());
1576    ///
1577    /// // assert with a custom message
1578    /// let x = true;
1579    /// assert!(x, "x wasn't true!");
1580    ///
1581    /// let a = 3; let b = 27;
1582    /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1583    /// ```
1584    #[stable(feature = "rust1", since = "1.0.0")]
1585    #[rustc_builtin_macro]
1586    #[macro_export]
1587    #[rustc_diagnostic_item = "assert_macro"]
1588    #[allow_internal_unstable(
1589        core_intrinsics,
1590        panic_internals,
1591        edition_panic,
1592        generic_assert_internals
1593    )]
1594    macro_rules! assert {
1595        ($cond:expr $(,)?) => {{ /* compiler built-in */ }};
1596        ($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }};
1597    }
1598
1599    /// Prints passed tokens into the standard output.
1600    #[unstable(
1601        feature = "log_syntax",
1602        issue = "29598",
1603        reason = "`log_syntax!` is not stable enough for use and is subject to change"
1604    )]
1605    #[rustc_builtin_macro]
1606    #[macro_export]
1607    macro_rules! log_syntax {
1608        ($($arg:tt)*) => {
1609            /* compiler built-in */
1610        };
1611    }
1612
1613    /// Enables or disables tracing functionality used for debugging other macros.
1614    #[unstable(
1615        feature = "trace_macros",
1616        issue = "29598",
1617        reason = "`trace_macros` is not stable enough for use and is subject to change"
1618    )]
1619    #[rustc_builtin_macro]
1620    #[macro_export]
1621    macro_rules! trace_macros {
1622        (true) => {{ /* compiler built-in */ }};
1623        (false) => {{ /* compiler built-in */ }};
1624    }
1625
1626    /// Attribute macro used to apply derive macros.
1627    ///
1628    /// See [the reference] for more info.
1629    ///
1630    /// [the reference]: ../../../reference/attributes/derive.html
1631    #[stable(feature = "rust1", since = "1.0.0")]
1632    #[rustc_builtin_macro]
1633    pub macro derive($item:item) {
1634        /* compiler built-in */
1635    }
1636
1637    /// Attribute macro used to apply derive macros for implementing traits
1638    /// in a const context.
1639    ///
1640    /// See [the reference] for more info.
1641    ///
1642    /// [the reference]: ../../../reference/attributes/derive.html
1643    #[unstable(feature = "derive_const", issue = "118304")]
1644    #[rustc_builtin_macro]
1645    pub macro derive_const($item:item) {
1646        /* compiler built-in */
1647    }
1648
1649    /// Attribute macro applied to a function to turn it into a unit test.
1650    ///
1651    /// See [the reference] for more info.
1652    ///
1653    /// [the reference]: ../../../reference/attributes/testing.html#the-test-attribute
1654    #[stable(feature = "rust1", since = "1.0.0")]
1655    #[allow_internal_unstable(test, rustc_attrs, coverage_attribute)]
1656    #[rustc_builtin_macro]
1657    pub macro test($item:item) {
1658        /* compiler built-in */
1659    }
1660
1661    /// Attribute macro applied to a function to turn it into a benchmark test.
1662    #[unstable(
1663        feature = "test",
1664        issue = "50297",
1665        reason = "`bench` is a part of custom test frameworks which are unstable"
1666    )]
1667    #[allow_internal_unstable(test, rustc_attrs, coverage_attribute)]
1668    #[rustc_builtin_macro]
1669    pub macro bench($item:item) {
1670        /* compiler built-in */
1671    }
1672
1673    /// An implementation detail of the `#[test]` and `#[bench]` macros.
1674    #[unstable(
1675        feature = "custom_test_frameworks",
1676        issue = "50297",
1677        reason = "custom test frameworks are an unstable feature"
1678    )]
1679    #[allow_internal_unstable(test, rustc_attrs)]
1680    #[rustc_builtin_macro]
1681    pub macro test_case($item:item) {
1682        /* compiler built-in */
1683    }
1684
1685    /// Attribute macro applied to a static to register it as a global allocator.
1686    ///
1687    /// See also [`std::alloc::GlobalAlloc`](../../../std/alloc/trait.GlobalAlloc.html).
1688    #[stable(feature = "global_allocator", since = "1.28.0")]
1689    #[allow_internal_unstable(rustc_attrs)]
1690    #[rustc_builtin_macro]
1691    pub macro global_allocator($item:item) {
1692        /* compiler built-in */
1693    }
1694
1695    /// Attribute macro applied to a function to give it a post-condition.
1696    ///
1697    /// The attribute carries an argument token-tree which is
1698    /// eventually parsed as a unary closure expression that is
1699    /// invoked on a reference to the return value.
1700    #[unstable(feature = "contracts", issue = "128044")]
1701    #[allow_internal_unstable(contracts_internals)]
1702    #[rustc_builtin_macro]
1703    pub macro contracts_ensures($item:item) {
1704        /* compiler built-in */
1705    }
1706
1707    /// Attribute macro applied to a function to give it a precondition.
1708    ///
1709    /// The attribute carries an argument token-tree which is
1710    /// eventually parsed as an boolean expression with access to the
1711    /// function's formal parameters
1712    #[unstable(feature = "contracts", issue = "128044")]
1713    #[allow_internal_unstable(contracts_internals)]
1714    #[rustc_builtin_macro]
1715    pub macro contracts_requires($item:item) {
1716        /* compiler built-in */
1717    }
1718
1719    /// Attribute macro applied to a function to register it as a handler for allocation failure.
1720    ///
1721    /// See also [`std::alloc::handle_alloc_error`](../../../std/alloc/fn.handle_alloc_error.html).
1722    #[unstable(feature = "alloc_error_handler", issue = "51540")]
1723    #[allow_internal_unstable(rustc_attrs)]
1724    #[rustc_builtin_macro]
1725    pub macro alloc_error_handler($item:item) {
1726        /* compiler built-in */
1727    }
1728
1729    /// Keeps the item it's applied to if the passed path is accessible, and removes it otherwise.
1730    #[unstable(
1731        feature = "cfg_accessible",
1732        issue = "64797",
1733        reason = "`cfg_accessible` is not fully implemented"
1734    )]
1735    #[rustc_builtin_macro]
1736    pub macro cfg_accessible($item:item) {
1737        /* compiler built-in */
1738    }
1739
1740    /// Expands all `#[cfg]` and `#[cfg_attr]` attributes in the code fragment it's applied to.
1741    #[unstable(
1742        feature = "cfg_eval",
1743        issue = "82679",
1744        reason = "`cfg_eval` is a recently implemented feature"
1745    )]
1746    #[rustc_builtin_macro]
1747    pub macro cfg_eval($($tt:tt)*) {
1748        /* compiler built-in */
1749    }
1750
1751    /// Provide a list of type aliases and other opaque-type-containing type definitions
1752    /// to an item with a body. This list will be used in that body to define opaque
1753    /// types' hidden types.
1754    /// Can only be applied to things that have bodies.
1755    #[unstable(
1756        feature = "type_alias_impl_trait",
1757        issue = "63063",
1758        reason = "`type_alias_impl_trait` has open design concerns"
1759    )]
1760    #[rustc_builtin_macro]
1761    pub macro define_opaque($($tt:tt)*) {
1762        /* compiler built-in */
1763    }
1764
1765    /// Unstable placeholder for type ascription.
1766    #[allow_internal_unstable(builtin_syntax)]
1767    #[unstable(
1768        feature = "type_ascription",
1769        issue = "23416",
1770        reason = "placeholder syntax for type ascription"
1771    )]
1772    #[rustfmt::skip]
1773    pub macro type_ascribe($expr:expr, $ty:ty) {
1774        builtin # type_ascribe($expr, $ty)
1775    }
1776
1777    /// Unstable placeholder for deref patterns.
1778    #[allow_internal_unstable(builtin_syntax)]
1779    #[unstable(
1780        feature = "deref_patterns",
1781        issue = "87121",
1782        reason = "placeholder syntax for deref patterns"
1783    )]
1784    pub macro deref($pat:pat) {
1785        builtin # deref($pat)
1786    }
1787
1788    /// Derive macro generating an impl of the trait `From`.
1789    /// Currently, it can only be used on single-field structs.
1790    // Note that the macro is in a different module than the `From` trait,
1791    // to avoid triggering an unstable feature being used if someone imports
1792    // `std::convert::From`.
1793    #[rustc_builtin_macro]
1794    #[unstable(feature = "derive_from", issue = "144889")]
1795    pub macro From($item: item) {
1796        /* compiler built-in */
1797    }
1798}