Skip to main content

core/macros/
mod.rs

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