Skip to main content

core/macros/
mod.rs

1#[doc = include_str!("panic.md")]
2#[macro_export]
3#[rustc_builtin_macro(core_panic)]
4#[allow_internal_unstable(edition_panic)]
5#[stable(feature = "core", since = "1.6.0")]
6#[rustc_diagnostic_item = "core_panic_macro"]
7macro_rules! panic {
8    // Expands to either `$crate::panic::panic_2015` or `$crate::panic::panic_2021`
9    // depending on the edition of the caller.
10    ($($arg:tt)*) => {
11        /* compiler built-in */
12    };
13}
14
15/// Asserts that two expressions are equal to each other (using [`PartialEq`]).
16///
17/// Assertions are always checked in both debug and release builds, and cannot
18/// be disabled. See [`debug_assert_eq!`] for assertions that are disabled in
19/// release builds by default.
20///
21/// [`debug_assert_eq!`]: crate::debug_assert_eq
22///
23/// On panic, this macro will print the values of the expressions with their
24/// debug representations.
25///
26/// Like [`assert!`], this macro has a second form, where a custom
27/// panic message can be provided.
28///
29/// # Examples
30///
31/// ```
32/// let a = 3;
33/// let b = 1 + 2;
34/// assert_eq!(a, b);
35///
36/// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
37/// ```
38#[macro_export]
39#[stable(feature = "rust1", since = "1.0.0")]
40#[rustc_diagnostic_item = "assert_eq_macro"]
41#[allow_internal_unstable(panic_internals)]
42macro_rules! assert_eq {
43    ($left:expr, $right:expr $(,)?) => {
44        match (&$left, &$right) {
45            (left_val, right_val) => {
46                if !(*left_val == *right_val) {
47                    let kind = $crate::panicking::AssertKind::Eq;
48                    // The reborrows below are intentional. Without them, the stack slot for the
49                    // borrow is initialized even before the values are compared, leading to a
50                    // noticeable slow down.
51                    $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None);
52                }
53            }
54        }
55    };
56    ($left:expr, $right:expr, $($arg:tt)+) => {
57        match (&$left, &$right) {
58            (left_val, right_val) => {
59                if !(*left_val == *right_val) {
60                    let kind = $crate::panicking::AssertKind::Eq;
61                    // The reborrows below are intentional. Without them, the stack slot for the
62                    // borrow is initialized even before the values are compared, leading to a
63                    // noticeable slow down.
64                    $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::Some($crate::format_args!($($arg)+)));
65                }
66            }
67        }
68    };
69}
70
71/// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
72///
73/// Assertions are always checked in both debug and release builds, and cannot
74/// be disabled. See [`debug_assert_ne!`] for assertions that are disabled in
75/// release builds by default.
76///
77/// [`debug_assert_ne!`]: crate::debug_assert_ne
78///
79/// On panic, this macro will print the values of the expressions with their
80/// debug representations.
81///
82/// Like [`assert!`], this macro has a second form, where a custom
83/// panic message can be provided.
84///
85/// # Examples
86///
87/// ```
88/// let a = 3;
89/// let b = 2;
90/// assert_ne!(a, b);
91///
92/// assert_ne!(a, b, "we are testing that the values are not equal");
93/// ```
94#[macro_export]
95#[stable(feature = "assert_ne", since = "1.13.0")]
96#[rustc_diagnostic_item = "assert_ne_macro"]
97#[allow_internal_unstable(panic_internals)]
98macro_rules! assert_ne {
99    ($left:expr, $right:expr $(,)?) => {
100        match (&$left, &$right) {
101            (left_val, right_val) => {
102                if *left_val == *right_val {
103                    let kind = $crate::panicking::AssertKind::Ne;
104                    // The reborrows below are intentional. Without them, the stack slot for the
105                    // borrow is initialized even before the values are compared, leading to a
106                    // noticeable slow down.
107                    $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None);
108                }
109            }
110        }
111    };
112    ($left:expr, $right:expr, $($arg:tt)+) => {
113        match (&($left), &($right)) {
114            (left_val, right_val) => {
115                if *left_val == *right_val {
116                    let kind = $crate::panicking::AssertKind::Ne;
117                    // The reborrows below are intentional. Without them, the stack slot for the
118                    // borrow is initialized even before the values are compared, leading to a
119                    // noticeable slow down.
120                    $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::Some($crate::format_args!($($arg)+)));
121                }
122            }
123        }
124    };
125}
126
127/// Asserts that an expression matches the provided pattern.
128///
129/// This macro is generally preferable to `assert!(matches!(value, pattern))`, because it can print
130/// the debug representation of the actual value shape that did not meet expectations. In contrast,
131/// using [`assert!`] will only print that expectations were not met, but not why.
132///
133/// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The
134/// optional if guard can be used to add additional checks that must be true for the matched value,
135/// otherwise this macro will panic.
136///
137/// Assertions are always checked in both debug and release builds, and cannot
138/// be disabled. See [`debug_assert_matches!`] for assertions that are disabled in
139/// release builds by default.
140///
141/// [`debug_assert_matches!`]: crate::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/// use std::assert_matches;
151///
152/// let a = Some(345);
153/// let b = Some(56);
154/// assert_matches!(a, Some(_));
155/// assert_matches!(b, Some(_));
156///
157/// assert_matches!(a, Some(345));
158/// assert_matches!(a, Some(345) | None);
159///
160/// // assert_matches!(a, None); // panics
161/// // assert_matches!(b, Some(345)); // panics
162/// // assert_matches!(b, Some(345) | None); // panics
163///
164/// assert_matches!(a, Some(x) if x > 100);
165/// // assert_matches!(a, Some(x) if x < 100); // panics
166/// ```
167#[stable(feature = "assert_matches", since = "1.96.0")]
168#[allow_internal_unstable(panic_internals)]
169#[rustc_macro_transparency = "semiopaque"]
170pub macro assert_matches {
171    ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => {{
172        match $left {
173            $( $pattern )|+ $( if $guard )? => {}
174            ref left_val => {
175                $crate::panicking::assert_matches_failed(
176                    left_val,
177                    $crate::stringify!($($pattern)|+ $(if $guard)?),
178                    $crate::option::Option::None
179                );
180            }
181        }
182    }},
183    ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )?, $($arg:tt)+) => {{
184        match $left {
185            $( $pattern )|+ $( if $guard )? => {}
186            ref left_val => {
187                $crate::panicking::assert_matches_failed(
188                    left_val,
189                    $crate::stringify!($($pattern)|+ $(if $guard)?),
190                    $crate::option::Option::Some($crate::format_args!($($arg)+))
191                );
192            }
193        }
194    }},
195}
196
197/// Selects code at compile-time based on `cfg` predicates.
198///
199/// This macro evaluates, at compile-time, a series of `cfg` predicates,
200/// selects the first that is true, and emits the code guarded by that
201/// predicate. The code guarded by other predicates is not emitted.
202///
203/// An optional trailing `_` wildcard can be used to specify a fallback. If
204/// none of the predicates are true, a [`compile_error`] is emitted.
205///
206/// # Example
207///
208/// ```
209/// cfg_select! {
210///     unix => {
211///         fn foo() { /* unix specific functionality */ }
212///     }
213///     target_pointer_width = "32" => {
214///         fn foo() { /* non-unix, 32-bit functionality */ }
215///     }
216///     _ => {
217///         fn foo() { /* fallback implementation */ }
218///     }
219/// }
220/// ```
221///
222/// The `cfg_select!` macro can also be used in expression position, with or without braces on the
223/// right-hand side:
224///
225/// ```
226/// let _some_string = cfg_select! {
227///     unix => "With great power comes great electricity bills",
228///     _ => { "Behind every successful diet is an unwatched pizza" }
229/// };
230/// ```
231#[stable(feature = "cfg_select", since = "1.95.0")]
232#[rustc_diagnostic_item = "cfg_select"]
233#[rustc_builtin_macro]
234pub macro cfg_select($($tt:tt)*) {
235    /* compiler built-in */
236}
237
238/// Asserts that a boolean expression is `true` at runtime.
239///
240/// This will invoke the [`panic!`] macro if the provided expression cannot be
241/// evaluated to `true` at runtime.
242///
243/// Like [`assert!`], this macro also has a second version, where a custom panic
244/// message can be provided.
245///
246/// # Uses
247///
248/// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
249/// optimized builds by default. An optimized build will not execute
250/// `debug_assert!` statements unless `-C debug-assertions` is passed to the
251/// compiler. This makes `debug_assert!` useful for checks that are too
252/// expensive to be present in a release build but may be helpful during
253/// development. The result of expanding `debug_assert!` is always type checked.
254///
255/// An unchecked assertion allows a program in an inconsistent state to keep
256/// running, which might have unexpected consequences but does not introduce
257/// unsafety as long as this only happens in safe code. The performance cost
258/// of assertions, however, is not measurable in general. Replacing [`assert!`]
259/// with `debug_assert!` is thus only encouraged after thorough profiling, and
260/// more importantly, only in safe code!
261///
262/// # Examples
263///
264/// ```
265/// // the panic message for these assertions is the stringified value of the
266/// // expression given.
267/// debug_assert!(true);
268///
269/// fn some_expensive_computation() -> bool {
270///     // Some expensive computation here
271///     true
272/// }
273/// debug_assert!(some_expensive_computation());
274///
275/// // assert with a custom message
276/// let x = true;
277/// debug_assert!(x, "x wasn't true!");
278///
279/// let a = 3; let b = 27;
280/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
281/// ```
282#[macro_export]
283#[stable(feature = "rust1", since = "1.0.0")]
284#[rustc_diagnostic_item = "debug_assert_macro"]
285#[allow_internal_unstable(edition_panic)]
286macro_rules! debug_assert {
287    ($($arg:tt)*) => {
288        if $crate::cfg!(debug_assertions) {
289            $crate::assert!($($arg)*);
290        }
291    };
292}
293
294/// Asserts that two expressions are equal to each other.
295///
296/// On panic, this macro will print the values of the expressions with their
297/// debug representations.
298///
299/// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
300/// optimized builds by default. An optimized build will not execute
301/// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
302/// compiler. This makes `debug_assert_eq!` useful for checks that are too
303/// expensive to be present in a release build but may be helpful during
304/// development. The result of expanding `debug_assert_eq!` is always type checked.
305///
306/// # Examples
307///
308/// ```
309/// let a = 3;
310/// let b = 1 + 2;
311/// debug_assert_eq!(a, b);
312/// ```
313#[macro_export]
314#[stable(feature = "rust1", since = "1.0.0")]
315#[rustc_diagnostic_item = "debug_assert_eq_macro"]
316macro_rules! debug_assert_eq {
317    ($($arg:tt)*) => {
318        if $crate::cfg!(debug_assertions) {
319            $crate::assert_eq!($($arg)*);
320        }
321    };
322}
323
324/// Asserts that two expressions are not equal to each other.
325///
326/// On panic, this macro will print the values of the expressions with their
327/// debug representations.
328///
329/// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
330/// optimized builds by default. An optimized build will not execute
331/// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
332/// compiler. This makes `debug_assert_ne!` useful for checks that are too
333/// expensive to be present in a release build but may be helpful during
334/// development. The result of expanding `debug_assert_ne!` is always type checked.
335///
336/// # Examples
337///
338/// ```
339/// let a = 3;
340/// let b = 2;
341/// debug_assert_ne!(a, b);
342/// ```
343#[macro_export]
344#[stable(feature = "assert_ne", since = "1.13.0")]
345#[rustc_diagnostic_item = "debug_assert_ne_macro"]
346macro_rules! debug_assert_ne {
347    ($($arg:tt)*) => {
348        if $crate::cfg!(debug_assertions) {
349            $crate::assert_ne!($($arg)*);
350        }
351    };
352}
353
354/// Asserts that an expression matches the provided pattern.
355///
356/// This macro is generally preferable to `debug_assert!(matches!(value, pattern))`, because it can
357/// print the debug representation of the actual value shape that did not meet expectations. In
358/// contrast, using [`debug_assert!`] will only print that expectations were not met, but not why.
359///
360/// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The
361/// optional if guard can be used to add additional checks that must be true for the matched value,
362/// otherwise this macro will panic.
363///
364/// On panic, this macro will print the value of the expression with its debug representation.
365///
366/// Like [`assert!`], this macro has a second form, where a custom panic message can be provided.
367///
368/// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only enabled in non optimized
369/// builds by default. An optimized build will not execute `debug_assert_matches!` statements unless
370/// `-C debug-assertions` is passed to the compiler. This makes `debug_assert_matches!` useful for
371/// checks that are too expensive to be present in a release build but may be helpful during
372/// development. The result of expanding `debug_assert_matches!` is always type checked.
373///
374/// # Examples
375///
376/// ```
377/// use std::debug_assert_matches;
378///
379/// let a = Some(345);
380/// let b = Some(56);
381/// debug_assert_matches!(a, Some(_));
382/// debug_assert_matches!(b, Some(_));
383///
384/// debug_assert_matches!(a, Some(345));
385/// debug_assert_matches!(a, Some(345) | None);
386///
387/// // debug_assert_matches!(a, None); // panics
388/// // debug_assert_matches!(b, Some(345)); // panics
389/// // debug_assert_matches!(b, Some(345) | None); // panics
390///
391/// debug_assert_matches!(a, Some(x) if x > 100);
392/// // debug_assert_matches!(a, Some(x) if x < 100); // panics
393/// ```
394#[stable(feature = "assert_matches", since = "1.96.0")]
395#[allow_internal_unstable(assert_matches)]
396#[rustc_macro_transparency = "semiopaque"]
397pub macro debug_assert_matches($($arg:tt)*) {
398    if $crate::cfg!(debug_assertions) {
399        $crate::assert_matches!($($arg)*);
400    }
401}
402
403/// Returns whether the given expression matches the provided pattern.
404///
405/// The pattern syntax is exactly the same as found in a match arm. The optional if guard can be
406/// used to add additional checks that must be true for the matched value, otherwise this macro will
407/// return `false`.
408///
409/// When testing that a value matches a pattern, it's generally preferable to use
410/// [`assert_matches!`] as it will print the debug representation of the value if the assertion
411/// fails.
412///
413/// # Examples
414///
415/// ```
416/// let foo = 'f';
417/// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
418///
419/// let bar = Some(4);
420/// assert!(matches!(bar, Some(x) if x > 2));
421/// ```
422#[macro_export]
423#[stable(feature = "matches_macro", since = "1.42.0")]
424#[rustc_diagnostic_item = "matches_macro"]
425#[allow_internal_unstable(non_exhaustive_omitted_patterns_lint, stmt_expr_attributes)]
426macro_rules! matches {
427    ($expression:expr, $pattern:pat $(if $guard:expr)? $(,)?) => {
428        #[allow(non_exhaustive_omitted_patterns)]
429        match $expression {
430            $pattern $(if $guard)? => true,
431            _ => false
432        }
433    };
434}
435
436/// Unwraps a result or propagates its error.
437///
438/// The [`?` operator][propagating-errors] was added to replace `try!`
439/// and should be used instead. Furthermore, `try` is a reserved word
440/// in Rust 2018, so if you must use it, you will need to use the
441/// [raw-identifier syntax][ris]: `r#try`.
442///
443/// [propagating-errors]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator
444/// [ris]: ../rust-by-example/compatibility/raw_identifiers.html
445///
446/// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
447/// expression has the value of the wrapped value.
448///
449/// In case of the `Err` variant, it retrieves the inner error. `try!` then
450/// performs conversion using `From`. This provides automatic conversion
451/// between specialized errors and more general ones. The resulting
452/// error is then immediately returned.
453///
454/// Because of the early return, `try!` can only be used in functions that
455/// return [`Result`].
456///
457/// # Examples
458///
459/// ```
460/// use std::io;
461/// use std::fs::File;
462/// use std::io::prelude::*;
463///
464/// enum MyError {
465///     FileWriteError
466/// }
467///
468/// impl From<io::Error> for MyError {
469///     fn from(e: io::Error) -> MyError {
470///         MyError::FileWriteError
471///     }
472/// }
473///
474/// // The preferred method of quick returning Errors
475/// fn write_to_file_question() -> Result<(), MyError> {
476///     let mut file = File::create("my_best_friends.txt")?;
477///     file.write_all(b"This is a list of my best friends.")?;
478///     Ok(())
479/// }
480///
481/// // The previous method of quick returning Errors
482/// fn write_to_file_using_try() -> Result<(), MyError> {
483///     let mut file = r#try!(File::create("my_best_friends.txt"));
484///     r#try!(file.write_all(b"This is a list of my best friends."));
485///     Ok(())
486/// }
487///
488/// // This is equivalent to:
489/// fn write_to_file_using_match() -> Result<(), MyError> {
490///     let mut file = r#try!(File::create("my_best_friends.txt"));
491///     match file.write_all(b"This is a list of my best friends.") {
492///         Ok(v) => v,
493///         Err(e) => return Err(From::from(e)),
494///     }
495///     Ok(())
496/// }
497/// ```
498#[macro_export]
499#[stable(feature = "rust1", since = "1.0.0")]
500#[deprecated(since = "1.39.0", note = "use the `?` operator instead")]
501#[doc(alias = "?")]
502macro_rules! r#try {
503    ($expr:expr $(,)?) => {
504        match $expr {
505            $crate::result::Result::Ok(val) => val,
506            $crate::result::Result::Err(err) => {
507                return $crate::result::Result::Err($crate::convert::From::from(err));
508            }
509        }
510    };
511}
512
513/// Writes formatted data into a buffer.
514///
515/// This macro accepts a 'writer', a format string, and a list of arguments. Arguments will be
516/// formatted according to the specified format string and the result will be passed to the writer.
517/// The writer may be any value with a `write_fmt` method; generally this comes from an
518/// implementation of either the [`fmt::Write`] or the [`io::Write`] trait. The macro
519/// returns whatever the `write_fmt` method returns; commonly a [`fmt::Result`], or an
520/// [`io::Result`].
521///
522/// See [`std::fmt`] for more information on the format string syntax.
523///
524/// [`std::fmt`]: ../std/fmt/index.html
525/// [`fmt::Write`]: crate::fmt::Write
526/// [`io::Write`]: ../std/io/trait.Write.html
527/// [`fmt::Result`]: crate::fmt::Result
528/// [`io::Result`]: ../std/io/type.Result.html
529///
530/// # Examples
531///
532/// ```
533/// use std::io::Write;
534///
535/// fn main() -> std::io::Result<()> {
536///     let mut w = Vec::new();
537///     write!(&mut w, "test")?;
538///     write!(&mut w, "formatted {}", "arguments")?;
539///
540///     assert_eq!(w, b"testformatted arguments");
541///     Ok(())
542/// }
543/// ```
544///
545/// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
546/// implementing either, as objects do not typically implement both. However, the module must
547/// avoid conflict between the trait names, such as by importing them as `_` or otherwise renaming
548/// them:
549///
550/// ```
551/// use std::fmt::Write as _;
552/// use std::io::Write as _;
553///
554/// fn main() -> Result<(), Box<dyn std::error::Error>> {
555///     let mut s = String::new();
556///     let mut v = Vec::new();
557///
558///     write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
559///     write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
560///     assert_eq!(v, b"s = \"abc 123\"");
561///     Ok(())
562/// }
563/// ```
564///
565/// If you also need the trait names themselves, such as to implement one or both on your types,
566/// import the containing module and then name them with a prefix:
567///
568/// ```
569/// # #![allow(unused_imports)]
570/// use std::fmt::{self, Write as _};
571/// use std::io::{self, Write as _};
572///
573/// struct Example;
574///
575/// impl fmt::Write for Example {
576///     fn write_str(&mut self, _s: &str) -> core::fmt::Result {
577///          unimplemented!();
578///     }
579/// }
580/// ```
581///
582/// Note: This macro can be used in `no_std` setups as well.
583/// In a `no_std` setup you are responsible for the implementation details of the components.
584///
585/// ```no_run
586/// use core::fmt::Write;
587///
588/// struct Example;
589///
590/// impl Write for Example {
591///     fn write_str(&mut self, _s: &str) -> core::fmt::Result {
592///          unimplemented!();
593///     }
594/// }
595///
596/// let mut m = Example{};
597/// write!(&mut m, "Hello World").expect("Not written");
598/// ```
599#[macro_export]
600#[stable(feature = "rust1", since = "1.0.0")]
601#[rustc_diagnostic_item = "write_macro"]
602macro_rules! write {
603    ($dst:expr, $($arg:tt)*) => {
604        $dst.write_fmt($crate::format_args!($($arg)*))
605    };
606    ($($arg:tt)*) => {
607        compile_error!("requires a destination and format arguments, like `write!(dest, \"format string\", args...)`")
608    };
609}
610
611/// Writes formatted data into a buffer, with a newline appended.
612///
613/// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
614/// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
615///
616/// For more information, see [`write!`]. For information on the format string syntax, see
617/// [`std::fmt`].
618///
619/// [`std::fmt`]: ../std/fmt/index.html
620///
621/// # Examples
622///
623/// ```
624/// use std::io::{Write, Result};
625///
626/// fn main() -> Result<()> {
627///     let mut w = Vec::new();
628///     writeln!(&mut w)?;
629///     writeln!(&mut w, "test")?;
630///     writeln!(&mut w, "formatted {}", "arguments")?;
631///
632///     assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
633///     Ok(())
634/// }
635/// ```
636#[macro_export]
637#[stable(feature = "rust1", since = "1.0.0")]
638#[rustc_diagnostic_item = "writeln_macro"]
639#[allow_internal_unstable(format_args_nl)]
640macro_rules! writeln {
641    ($dst:expr $(,)?) => {
642        $crate::write!($dst, "\n")
643    };
644    ($dst:expr, $($arg:tt)*) => {
645        $dst.write_fmt($crate::format_args_nl!($($arg)*))
646    };
647    ($($arg:tt)*) => {
648        compile_error!("requires a destination and format arguments, like `writeln!(dest, \"format string\", args...)`")
649    };
650}
651
652/// Indicates unreachable code.
653///
654/// This is useful any time that the compiler can't determine that some code is unreachable. For
655/// example:
656///
657/// * Match arms with guard conditions.
658/// * Loops that dynamically terminate.
659/// * Iterators that dynamically terminate.
660///
661/// If the determination that the code is unreachable proves incorrect, the
662/// program immediately terminates with a [`panic!`].
663///
664/// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
665/// will cause undefined behavior if the code is reached.
666///
667/// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked
668///
669/// # Panics
670///
671/// This will always [`panic!`] because `unreachable!` is just a shorthand for `panic!` with a
672/// fixed, specific message.
673///
674/// Like `panic!`, this macro has a second form for displaying custom values.
675///
676/// # Examples
677///
678/// Match arms:
679///
680/// ```
681/// # #[allow(dead_code)]
682/// fn foo(x: Option<i32>) {
683///     match x {
684///         Some(n) if n >= 0 => println!("Some(Non-negative)"),
685///         Some(n) if n <  0 => println!("Some(Negative)"),
686///         Some(_)           => unreachable!(), // compile error if commented out
687///         None              => println!("None")
688///     }
689/// }
690/// ```
691///
692/// Iterators:
693///
694/// ```
695/// # #[allow(dead_code)]
696/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
697///     for i in 0.. {
698///         if 3*i < i { panic!("u32 overflow"); }
699///         if x < 3*i { return i-1; }
700///     }
701///     unreachable!("The loop should always return");
702/// }
703/// ```
704#[macro_export]
705#[rustc_builtin_macro(unreachable)]
706#[allow_internal_unstable(edition_panic)]
707#[stable(feature = "rust1", since = "1.0.0")]
708#[rustc_diagnostic_item = "unreachable_macro"]
709macro_rules! unreachable {
710    // Expands to either `$crate::panic::unreachable_2015` or `$crate::panic::unreachable_2021`
711    // depending on the edition of the caller.
712    ($($arg:tt)*) => {
713        /* compiler built-in */
714    };
715}
716
717/// Indicates unimplemented code by panicking with a message of "not implemented".
718///
719/// This allows your code to type-check, which is useful if you are prototyping or
720/// implementing a trait that requires multiple methods which you don't plan to use all of.
721///
722/// The difference between `unimplemented!` and [`todo!`] is that while `todo!`
723/// conveys an intent of implementing the functionality later and the message is "not yet
724/// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
725///
726/// Also, some IDEs will mark `todo!`s.
727///
728/// # Panics
729///
730/// This will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a
731/// fixed, specific message.
732///
733/// Like `panic!`, this macro has a second form for displaying custom values.
734///
735/// [`todo!`]: crate::todo
736///
737/// # Examples
738///
739/// Say we have a trait `Foo`:
740///
741/// ```
742/// trait Foo {
743///     fn bar(&self) -> u8;
744///     fn baz(&self);
745///     fn qux(&self) -> Result<u64, ()>;
746/// }
747/// ```
748///
749/// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
750/// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
751/// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
752/// to allow our code to compile.
753///
754/// We still want to have our program stop running if the unimplemented methods are
755/// reached.
756///
757/// ```
758/// # trait Foo {
759/// #     fn bar(&self) -> u8;
760/// #     fn baz(&self);
761/// #     fn qux(&self) -> Result<u64, ()>;
762/// # }
763/// struct MyStruct;
764///
765/// impl Foo for MyStruct {
766///     fn bar(&self) -> u8 {
767///         1 + 1
768///     }
769///
770///     fn baz(&self) {
771///         // It makes no sense to `baz` a `MyStruct`, so we have no logic here
772///         // at all.
773///         // This will display "thread 'main' panicked at 'not implemented'".
774///         unimplemented!();
775///     }
776///
777///     fn qux(&self) -> Result<u64, ()> {
778///         // We have some logic here,
779///         // We can add a message to unimplemented! to display our omission.
780///         // This will display:
781///         // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
782///         unimplemented!("MyStruct isn't quxable");
783///     }
784/// }
785///
786/// fn main() {
787///     let s = MyStruct;
788///     s.bar();
789/// }
790/// ```
791#[macro_export]
792#[stable(feature = "rust1", since = "1.0.0")]
793#[rustc_diagnostic_item = "unimplemented_macro"]
794#[allow_internal_unstable(panic_internals)]
795macro_rules! unimplemented {
796    () => {
797        $crate::panicking::panic("not implemented")
798    };
799    ($($arg:tt)+) => {
800        $crate::panic!("not implemented: {}", $crate::format_args!($($arg)+))
801    };
802}
803
804/// Indicates unfinished code.
805///
806/// This can be useful if you are prototyping and just
807/// want a placeholder to let your code pass type analysis.
808///
809/// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
810/// an intent of implementing the functionality later and the message is "not yet
811/// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
812///
813/// Also, some IDEs will mark `todo!`s.
814///
815/// # Panics
816///
817/// This will always [`panic!`] because `todo!` is just a shorthand for `panic!` with a
818/// fixed, specific message.
819///
820/// Like `panic!`, this macro has a second form for displaying custom values.
821///
822/// # Examples
823///
824/// Here's an example of some in-progress code. We have a trait `Foo`:
825///
826/// ```
827/// trait Foo {
828///     fn bar(&self) -> u8;
829///     fn baz(&self);
830///     fn qux(&self) -> Result<u64, ()>;
831/// }
832/// ```
833///
834/// We want to implement `Foo` on one of our types, but we also want to work on
835/// just `bar()` first. In order for our code to compile, we need to implement
836/// `baz()` and `qux()`, so we can use `todo!`:
837///
838/// ```
839/// # trait Foo {
840/// #     fn bar(&self) -> u8;
841/// #     fn baz(&self);
842/// #     fn qux(&self) -> Result<u64, ()>;
843/// # }
844/// struct MyStruct;
845///
846/// impl Foo for MyStruct {
847///     fn bar(&self) -> u8 {
848///         1 + 1
849///     }
850///
851///     fn baz(&self) {
852///         // Let's not worry about implementing baz() for now
853///         todo!();
854///     }
855///
856///     fn qux(&self) -> Result<u64, ()> {
857///         // We can add a message to todo! to display our omission.
858///         // This will display:
859///         // "thread 'main' panicked at 'not yet implemented: MyStruct is not yet quxable'".
860///         todo!("MyStruct is not yet quxable");
861///     }
862/// }
863///
864/// fn main() {
865///     let s = MyStruct;
866///     s.bar();
867///
868///     // We aren't even using baz() or qux(), so this is fine.
869/// }
870/// ```
871#[macro_export]
872#[stable(feature = "todo_macro", since = "1.40.0")]
873#[rustc_diagnostic_item = "todo_macro"]
874#[allow_internal_unstable(panic_internals)]
875macro_rules! todo {
876    () => {
877        $crate::panicking::panic("not yet implemented")
878    };
879    ($($arg:tt)+) => {
880        $crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+))
881    };
882}
883
884/// Definitions of built-in macros.
885///
886/// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
887/// with exception of expansion functions transforming macro inputs into outputs,
888/// those functions are provided by the compiler.
889pub(crate) mod builtin {
890
891    /// Causes compilation to fail with the given error message when encountered.
892    ///
893    /// This macro should be used when a crate uses a conditional compilation strategy to provide
894    /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
895    /// but emits an error during *compilation* rather than at *runtime*.
896    ///
897    /// # Examples
898    ///
899    /// Two such examples are macros and `#[cfg]` environments.
900    ///
901    /// Emit a better compiler error if a macro is passed invalid values. Without the final branch,
902    /// the compiler would still emit an error, but the error's message would not mention the two
903    /// valid values.
904    ///
905    /// ```compile_fail
906    /// macro_rules! give_me_foo_or_bar {
907    ///     (foo) => {};
908    ///     (bar) => {};
909    ///     ($x:ident) => {
910    ///         compile_error!("This macro only accepts `foo` or `bar`");
911    ///     }
912    /// }
913    ///
914    /// give_me_foo_or_bar!(neither);
915    /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
916    /// ```
917    ///
918    /// Emit a compiler error if one of a number of features isn't available.
919    ///
920    /// ```compile_fail
921    /// #[cfg(not(any(feature = "foo", feature = "bar")))]
922    /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
923    /// ```
924    #[stable(feature = "compile_error_macro", since = "1.20.0")]
925    #[rustc_builtin_macro]
926    #[macro_export]
927    macro_rules! compile_error {
928        ($msg:expr $(,)?) => {{ /* compiler built-in */ }};
929    }
930
931    /// Constructs parameters for the other string-formatting macros.
932    ///
933    /// This macro functions by taking a formatting string literal containing
934    /// `{}` for each additional argument passed. `format_args!` prepares the
935    /// additional parameters to ensure the output can be interpreted as a string
936    /// and canonicalizes the arguments into a single type. Any value that implements
937    /// the [`Display`] trait can be passed to `format_args!`, as can any
938    /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
939    ///
940    /// This macro produces a value of type [`fmt::Arguments`]. This value can be
941    /// passed to the macros within [`std::fmt`] for performing useful redirection.
942    /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
943    /// proxied through this one. `format_args!`, unlike its derived macros, avoids
944    /// heap allocations.
945    ///
946    /// You can use the [`fmt::Arguments`] value that `format_args!` returns
947    /// in `Debug` and `Display` contexts as seen below. The example also shows
948    /// that `Debug` and `Display` format to the same thing: the interpolated
949    /// format string in `format_args!`.
950    ///
951    /// ```rust
952    /// let args = format_args!("{} foo {:?}", 1, 2);
953    /// let debug = format!("{args:?}");
954    /// let display = format!("{args}");
955    /// assert_eq!("1 foo 2", display);
956    /// assert_eq!(display, debug);
957    /// ```
958    ///
959    /// See [the formatting documentation in `std::fmt`](../std/fmt/index.html)
960    /// for details of the macro argument syntax, and further information.
961    ///
962    /// [`Display`]: crate::fmt::Display
963    /// [`Debug`]: crate::fmt::Debug
964    /// [`fmt::Arguments`]: crate::fmt::Arguments
965    /// [`std::fmt`]: ../std/fmt/index.html
966    /// [`format!`]: ../std/macro.format.html
967    /// [`println!`]: ../std/macro.println.html
968    ///
969    /// # Examples
970    ///
971    /// ```
972    /// use std::fmt;
973    ///
974    /// let s = fmt::format(format_args!("hello {}", "world"));
975    /// assert_eq!(s, format!("hello {}", "world"));
976    /// ```
977    ///
978    /// # Argument lifetimes
979    ///
980    /// Except when no formatting arguments are used,
981    /// the produced `fmt::Arguments` value borrows temporary values.
982    /// To allow it to be stored for later use, the arguments' lifetimes, as well as those of
983    /// temporaries they borrow, may be [extended] when `format_args!` appears in the initializer
984    /// expression of a `let` statement. The syntactic rules used to determine when temporaries'
985    /// lifetimes are extended are documented in the [Reference].
986    ///
987    /// [extended]: ../reference/destructors.html#temporary-lifetime-extension
988    /// [Reference]: ../reference/destructors.html#extending-based-on-expressions
989    #[stable(feature = "rust1", since = "1.0.0")]
990    #[rustc_diagnostic_item = "format_args_macro"]
991    #[allow_internal_unsafe]
992    #[allow_internal_unstable(fmt_internals, fmt_arguments_from_str)]
993    #[rustc_builtin_macro]
994    #[macro_export]
995    macro_rules! format_args {
996        ($fmt:expr) => {{ /* compiler built-in */ }};
997        ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
998    }
999
1000    /// Same as [`format_args`], but can be used in some const contexts.
1001    ///
1002    /// This macro is used by the panic macros for the `const_panic` feature.
1003    ///
1004    /// This macro will be removed once `format_args` is allowed in const contexts.
1005    #[unstable(feature = "const_format_args", issue = "none")]
1006    #[allow_internal_unstable(fmt_internals, fmt_arguments_from_str)]
1007    #[rustc_builtin_macro]
1008    #[macro_export]
1009    macro_rules! const_format_args {
1010        ($fmt:expr) => {{ /* compiler built-in */ }};
1011        ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
1012    }
1013
1014    /// Same as [`format_args`], but adds a newline in the end.
1015    #[unstable(
1016        feature = "format_args_nl",
1017        issue = "none",
1018        reason = "`format_args_nl` is only for internal \
1019                  language use and is subject to change"
1020    )]
1021    #[allow_internal_unstable(fmt_internals, fmt_arguments_from_str)]
1022    #[rustc_builtin_macro]
1023    #[doc(hidden)]
1024    #[macro_export]
1025    macro_rules! format_args_nl {
1026        ($fmt:expr) => {{ /* compiler built-in */ }};
1027        ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
1028    }
1029
1030    /// Inspects an environment variable at compile time.
1031    ///
1032    /// This macro will expand to the value of the named environment variable at
1033    /// compile time, yielding an expression of type `&'static str`. Use
1034    /// [`std::env::var`] instead if you want to read the value at runtime.
1035    ///
1036    /// [`std::env::var`]: ../std/env/fn.var.html
1037    ///
1038    /// If the environment variable is not defined, then a compilation error
1039    /// will be emitted. To not emit a compile error, use the [`option_env!`]
1040    /// macro instead. A compilation error will also be emitted if the
1041    /// environment variable is not a valid Unicode string.
1042    ///
1043    /// # Examples
1044    ///
1045    /// ```
1046    /// let path: &'static str = env!("PATH");
1047    /// println!("the $PATH variable at the time of compiling was: {path}");
1048    /// ```
1049    ///
1050    /// You can customize the error message by passing a string as the second
1051    /// parameter:
1052    ///
1053    /// ```compile_fail
1054    /// let doc: &'static str = env!("documentation", "what's that?!");
1055    /// ```
1056    ///
1057    /// If the `documentation` environment variable is not defined, you'll get
1058    /// the following error:
1059    ///
1060    /// ```text
1061    /// error: what's that?!
1062    /// ```
1063    #[stable(feature = "rust1", since = "1.0.0")]
1064    #[rustc_builtin_macro]
1065    #[macro_export]
1066    #[rustc_diagnostic_item = "env_macro"] // useful for external lints
1067    macro_rules! env {
1068        ($name:expr $(,)?) => {{ /* compiler built-in */ }};
1069        ($name:expr, $error_msg:expr $(,)?) => {{ /* compiler built-in */ }};
1070    }
1071
1072    /// Optionally inspects an environment variable at compile time.
1073    ///
1074    /// If the named environment variable is present at compile time, this will
1075    /// expand into an expression of type `Option<&'static str>` whose value is
1076    /// `Some` of the value of the environment variable (a compilation error
1077    /// will be emitted if the environment variable is not a valid Unicode
1078    /// string). If the environment variable is not present, then this will
1079    /// expand to `None`. See [`Option<T>`][Option] for more information on this
1080    /// type.  Use [`std::env::var`] instead if you want to read the value at
1081    /// runtime.
1082    ///
1083    /// [`std::env::var`]: ../std/env/fn.var.html
1084    ///
1085    /// A compile time error is only emitted when using this macro if the
1086    /// environment variable exists and is not a valid Unicode string. To also
1087    /// emit a compile error if the environment variable is not present, use the
1088    /// [`env!`] macro instead.
1089    ///
1090    /// # Examples
1091    ///
1092    /// ```
1093    /// let key: Option<&'static str> = option_env!("SECRET_KEY");
1094    /// println!("the secret key might be: {key:?}");
1095    /// ```
1096    #[stable(feature = "rust1", since = "1.0.0")]
1097    #[rustc_builtin_macro]
1098    #[macro_export]
1099    #[rustc_diagnostic_item = "option_env_macro"] // useful for external lints
1100    macro_rules! option_env {
1101        ($name:expr $(,)?) => {{ /* compiler built-in */ }};
1102    }
1103
1104    /// Concatenates literals into a byte slice.
1105    ///
1106    /// This macro takes any number of comma-separated literals, and concatenates them all into
1107    /// one, yielding an expression of type `&[u8; _]`, which represents all of the literals
1108    /// concatenated left-to-right. The literals passed can be any combination of:
1109    ///
1110    /// - byte literals (`b'r'`)
1111    /// - byte strings (`b"Rust"`)
1112    /// - arrays of bytes/numbers (`[b'A', 66, b'C']`)
1113    ///
1114    /// # Examples
1115    ///
1116    /// ```
1117    /// #![feature(concat_bytes)]
1118    ///
1119    /// # fn main() {
1120    /// let s: &[u8; 6] = concat_bytes!(b'A', b"BC", [68, b'E', 70]);
1121    /// assert_eq!(s, b"ABCDEF");
1122    /// # }
1123    /// ```
1124    #[unstable(feature = "concat_bytes", issue = "87555")]
1125    #[rustc_builtin_macro]
1126    #[macro_export]
1127    macro_rules! concat_bytes {
1128        ($($e:literal),+ $(,)?) => {{ /* compiler built-in */ }};
1129    }
1130
1131    /// Concatenates literals into a static string slice.
1132    ///
1133    /// This macro takes any number of comma-separated literals, yielding an
1134    /// expression of type `&'static str` which represents all of the lit