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