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