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