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]: http://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator
464/// [ris]: http://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](http://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 #[deprecated(
1142 since = "1.88.0",
1143 note = "use `${concat(...)}` with the `macro_metavar_expr_concat` feature instead"
1144 )]
1145 #[rustc_builtin_macro]
1146 #[macro_export]
1147 macro_rules! concat_idents {
1148 ($($e:ident),+ $(,)?) => {{ /* compiler built-in */ }};
1149 }
1150
1151 /// Concatenates literals into a byte slice.
1152 ///
1153 /// This macro takes any number of comma-separated literals, and concatenates them all into
1154 /// one, yielding an expression of type `&[u8; _]`, which represents all of the literals
1155 /// concatenated left-to-right. The literals passed can be any combination of:
1156 ///
1157 /// - byte literals (`b'r'`)
1158 /// - byte strings (`b"Rust"`)
1159 /// - arrays of bytes/numbers (`[b'A', 66, b'C']`)
1160 ///
1161 /// # Examples
1162 ///
1163 /// ```
1164 /// #![feature(concat_bytes)]
1165 ///
1166 /// # fn main() {
1167 /// let s: &[u8; 6] = concat_bytes!(b'A', b"BC", [68, b'E', 70]);
1168 /// assert_eq!(s, b"ABCDEF");
1169 /// # }
1170 /// ```
1171 #[unstable(feature = "concat_bytes", issue = "87555")]
1172 #[rustc_builtin_macro]
1173 #[macro_export]
1174 macro_rules! concat_bytes {
1175 ($($e:literal),+ $(,)?) => {{ /* compiler built-in */ }};
1176 }
1177
1178 /// Concatenates literals into a static string slice.
1179 ///
1180 /// This macro takes any number of comma-separated literals, yielding an
1181 /// expression of type `&'static str` which represents all of the literals
1182 /// concatenated left-to-right.
1183 ///
1184 /// Integer and floating point literals are [stringified](core::stringify) in order to be
1185 /// concatenated.
1186 ///
1187 /// # Examples
1188 ///
1189 /// ```
1190 /// let s = concat!("test", 10, 'b', true);
1191 /// assert_eq!(s, "test10btrue");
1192 /// ```
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 #[rustc_builtin_macro]
1195 #[macro_export]
1196 macro_rules! concat {
1197 ($($e:expr),* $(,)?) => {{ /* compiler built-in */ }};
1198 }
1199
1200 /// Expands to the line number on which it was invoked.
1201 ///
1202 /// With [`column!`] and [`file!`], these macros provide debugging information for
1203 /// developers about the location within the source.
1204 ///
1205 /// The expanded expression has type `u32` and is 1-based, so the first line
1206 /// in each file evaluates to 1, the second to 2, etc. This is consistent
1207 /// with error messages by common compilers or popular editors.
1208 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
1209 /// but rather the first macro invocation leading up to the invocation
1210 /// of the `line!` macro.
1211 ///
1212 /// # Examples
1213 ///
1214 /// ```
1215 /// let current_line = line!();
1216 /// println!("defined on line: {current_line}");
1217 /// ```
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 #[rustc_builtin_macro]
1220 #[macro_export]
1221 macro_rules! line {
1222 () => {
1223 /* compiler built-in */
1224 };
1225 }
1226
1227 /// Expands to the column number at which it was invoked.
1228 ///
1229 /// With [`line!`] and [`file!`], these macros provide debugging information for
1230 /// developers about the location within the source.
1231 ///
1232 /// The expanded expression has type `u32` and is 1-based, so the first column
1233 /// in each line evaluates to 1, the second to 2, etc. This is consistent
1234 /// with error messages by common compilers or popular editors.
1235 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
1236 /// but rather the first macro invocation leading up to the invocation
1237 /// of the `column!` macro.
1238 ///
1239 /// # Examples
1240 ///
1241 /// ```
1242 /// let current_col = column!();
1243 /// println!("defined on column: {current_col}");
1244 /// ```
1245 ///
1246 /// `column!` counts Unicode code points, not bytes or graphemes. As a result, the first two
1247 /// invocations return the same value, but the third does not.
1248 ///
1249 /// ```
1250 /// let a = ("foobar", column!()).1;
1251 /// let b = ("人之初性本善", column!()).1;
1252 /// let c = ("f̅o̅o̅b̅a̅r̅", column!()).1; // Uses combining overline (U+0305)
1253 ///
1254 /// assert_eq!(a, b);
1255 /// assert_ne!(b, c);
1256 /// ```
1257 #[stable(feature = "rust1", since = "1.0.0")]
1258 #[rustc_builtin_macro]
1259 #[macro_export]
1260 macro_rules! column {
1261 () => {
1262 /* compiler built-in */
1263 };
1264 }
1265
1266 /// Expands to the file name in which it was invoked.
1267 ///
1268 /// With [`line!`] and [`column!`], these macros provide debugging information for
1269 /// developers about the location within the source.
1270 ///
1271 /// The expanded expression has type `&'static str`, and the returned file
1272 /// is not the invocation of the `file!` macro itself, but rather the
1273 /// first macro invocation leading up to the invocation of the `file!`
1274 /// macro.
1275 ///
1276 /// # Examples
1277 ///
1278 /// ```
1279 /// let this_file = file!();
1280 /// println!("defined in file: {this_file}");
1281 /// ```
1282 #[stable(feature = "rust1", since = "1.0.0")]
1283 #[rustc_builtin_macro]
1284 #[macro_export]
1285 macro_rules! file {
1286 () => {
1287 /* compiler built-in */
1288 };
1289 }
1290
1291 /// Stringifies its arguments.
1292 ///
1293 /// This macro will yield an expression of type `&'static str` which is the
1294 /// stringification of all the tokens passed to the macro. No restrictions
1295 /// are placed on the syntax of the macro invocation itself.
1296 ///
1297 /// Note that the expanded results of the input tokens may change in the
1298 /// future. You should be careful if you rely on the output.
1299 ///
1300 /// # Examples
1301 ///
1302 /// ```
1303 /// let one_plus_one = stringify!(1 + 1);
1304 /// assert_eq!(one_plus_one, "1 + 1");
1305 /// ```
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 #[rustc_builtin_macro]
1308 #[macro_export]
1309 macro_rules! stringify {
1310 ($($t:tt)*) => {
1311 /* compiler built-in */
1312 };
1313 }
1314
1315 /// Includes a UTF-8 encoded file as a string.
1316 ///
1317 /// The file is located relative to the current file (similarly to how
1318 /// modules are found). The provided path is interpreted in a platform-specific
1319 /// way at compile time. So, for instance, an invocation with a Windows path
1320 /// containing backslashes `\` would not compile correctly on Unix.
1321 ///
1322 /// This macro will yield an expression of type `&'static str` which is the
1323 /// contents of the file.
1324 ///
1325 /// # Examples
1326 ///
1327 /// Assume there are two files in the same directory with the following
1328 /// contents:
1329 ///
1330 /// File 'spanish.in':
1331 ///
1332 /// ```text
1333 /// adiós
1334 /// ```
1335 ///
1336 /// File 'main.rs':
1337 ///
1338 /// ```ignore (cannot-doctest-external-file-dependency)
1339 /// fn main() {
1340 /// let my_str = include_str!("spanish.in");
1341 /// assert_eq!(my_str, "adiós\n");
1342 /// print!("{my_str}");
1343 /// }
1344 /// ```
1345 ///
1346 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 #[rustc_builtin_macro]
1349 #[macro_export]
1350 #[rustc_diagnostic_item = "include_str_macro"]
1351 macro_rules! include_str {
1352 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1353 }
1354
1355 /// Includes a file as a reference to a byte array.
1356 ///
1357 /// The file is located relative to the current file (similarly to how
1358 /// modules are found). The provided path is interpreted in a platform-specific
1359 /// way at compile time. So, for instance, an invocation with a Windows path
1360 /// containing backslashes `\` would not compile correctly on Unix.
1361 ///
1362 /// This macro will yield an expression of type `&'static [u8; N]` which is
1363 /// the contents of the file.
1364 ///
1365 /// # Examples
1366 ///
1367 /// Assume there are two files in the same directory with the following
1368 /// contents:
1369 ///
1370 /// File 'spanish.in':
1371 ///
1372 /// ```text
1373 /// adiós
1374 /// ```
1375 ///
1376 /// File 'main.rs':
1377 ///
1378 /// ```ignore (cannot-doctest-external-file-dependency)
1379 /// fn main() {
1380 /// let bytes = include_bytes!("spanish.in");
1381 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
1382 /// print!("{}", String::from_utf8_lossy(bytes));
1383 /// }
1384 /// ```
1385 ///
1386 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1387 #[stable(feature = "rust1", since = "1.0.0")]
1388 #[rustc_builtin_macro]
1389 #[macro_export]
1390 #[rustc_diagnostic_item = "include_bytes_macro"]
1391 macro_rules! include_bytes {
1392 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1393 }
1394
1395 /// Expands to a string that represents the current module path.
1396 ///
1397 /// The current module path can be thought of as the hierarchy of modules
1398 /// leading back up to the crate root. The first component of the path
1399 /// returned is the name of the crate currently being compiled.
1400 ///
1401 /// # Examples
1402 ///
1403 /// ```
1404 /// mod test {
1405 /// pub fn foo() {
1406 /// assert!(module_path!().ends_with("test"));
1407 /// }
1408 /// }
1409 ///
1410 /// test::foo();
1411 /// ```
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 #[rustc_builtin_macro]
1414 #[macro_export]
1415 macro_rules! module_path {
1416 () => {
1417 /* compiler built-in */
1418 };
1419 }
1420
1421 /// Evaluates boolean combinations of configuration flags at compile-time.
1422 ///
1423 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1424 /// boolean expression evaluation of configuration flags. This frequently
1425 /// leads to less duplicated code.
1426 ///
1427 /// The syntax given to this macro is the same syntax as the [`cfg`]
1428 /// attribute.
1429 ///
1430 /// `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For
1431 /// example, all blocks in an if/else expression need to be valid when `cfg!` is used for
1432 /// the condition, regardless of what `cfg!` is evaluating.
1433 ///
1434 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1435 ///
1436 /// # Examples
1437 ///
1438 /// ```
1439 /// let my_directory = if cfg!(windows) {
1440 /// "windows-specific-directory"
1441 /// } else {
1442 /// "unix-directory"
1443 /// };
1444 /// ```
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 #[rustc_builtin_macro]
1447 #[macro_export]
1448 macro_rules! cfg {
1449 ($($cfg:tt)*) => {
1450 /* compiler built-in */
1451 };
1452 }
1453
1454 /// Parses a file as an expression or an item according to the context.
1455 ///
1456 /// **Warning**: For multi-file Rust projects, the `include!` macro is probably not what you
1457 /// are looking for. Usually, multi-file Rust projects use
1458 /// [modules](http://doc.rust-lang.org/reference/items/modules.html). Multi-file projects and
1459 /// modules are explained in the Rust-by-Example book
1460 /// [here](http://doc.rust-lang.org/rust-by-example/mod/split.html) and the module system is
1461 /// explained in the Rust Book
1462 /// [here](http://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html).
1463 ///
1464 /// The included file is placed in the surrounding code
1465 /// [unhygienically](http://doc.rust-lang.org/reference/macros-by-example.html#hygiene). If
1466 /// the included file is parsed as an expression and variables or functions share names across
1467 /// both files, it could result in variables or functions being different from what the
1468 /// included file expected.
1469 ///
1470 /// The included file is located relative to the current file (similarly to how modules are
1471 /// found). The provided path is interpreted in a platform-specific way at compile time. So,
1472 /// for instance, an invocation with a Windows path containing backslashes `\` would not
1473 /// compile correctly on Unix.
1474 ///
1475 /// # Uses
1476 ///
1477 /// The `include!` macro is primarily used for two purposes. It is used to include
1478 /// documentation that is written in a separate file and it is used to include [build artifacts
1479 /// usually as a result from the `build.rs`
1480 /// script](http://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script).
1481 ///
1482 /// When using the `include` macro to include stretches of documentation, remember that the
1483 /// included file still needs to be a valid Rust syntax. It is also possible to
1484 /// use the [`include_str`] macro as `#![doc = include_str!("...")]` (at the module level) or
1485 /// `#[doc = include_str!("...")]` (at the item level) to include documentation from a plain
1486 /// text or markdown file.
1487 ///
1488 /// # Examples
1489 ///
1490 /// Assume there are two files in the same directory with the following contents:
1491 ///
1492 /// File 'monkeys.in':
1493 ///
1494 /// ```ignore (only-for-syntax-highlight)
1495 /// ['🙈', '🙊', '🙉']
1496 /// .iter()
1497 /// .cycle()
1498 /// .take(6)
1499 /// .collect::<String>()
1500 /// ```
1501 ///
1502 /// File 'main.rs':
1503 ///
1504 /// ```ignore (cannot-doctest-external-file-dependency)
1505 /// fn main() {
1506 /// let my_string = include!("monkeys.in");
1507 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1508 /// println!("{my_string}");
1509 /// }
1510 /// ```
1511 ///
1512 /// Compiling 'main.rs' and running the resulting binary will print
1513 /// "🙈🙊🙉🙈🙊🙉".
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 #[rustc_builtin_macro]
1516 #[macro_export]
1517 #[rustc_diagnostic_item = "include_macro"] // useful for external lints
1518 macro_rules! include {
1519 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1520 }
1521
1522 /// Automatic Differentiation macro which allows generating a new function to compute
1523 /// the derivative of a given function. It may only be applied to a function.
1524 /// The expected usage syntax is
1525 /// `#[autodiff(NAME, MODE, INPUT_ACTIVITIES, OUTPUT_ACTIVITY)]`
1526 /// where:
1527 /// NAME is a string that represents a valid function name.
1528 /// MODE is any of Forward, Reverse, ForwardFirst, ReverseFirst.
1529 /// INPUT_ACTIVITIES consists of one valid activity for each input parameter.
1530 /// OUTPUT_ACTIVITY must not be set if we implicitly return nothing (or explicitly return
1531 /// `-> ()`). Otherwise it must be set to one of the allowed activities.
1532 #[unstable(feature = "autodiff", issue = "124509")]
1533 #[allow_internal_unstable(rustc_attrs)]
1534 #[rustc_builtin_macro]
1535 pub macro autodiff($item:item) {
1536 /* compiler built-in */
1537 }
1538
1539 /// Asserts that a boolean expression is `true` at runtime.
1540 ///
1541 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1542 /// evaluated to `true` at runtime.
1543 ///
1544 /// # Uses
1545 ///
1546 /// Assertions are always checked in both debug and release builds, and cannot
1547 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1548 /// release builds by default.
1549 ///
1550 /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if
1551 /// violated could lead to unsafety.
1552 ///
1553 /// Other use-cases of `assert!` include testing and enforcing run-time
1554 /// invariants in safe code (whose violation cannot result in unsafety).
1555 ///
1556 /// # Custom Messages
1557 ///
1558 /// This macro has a second form, where a custom panic message can
1559 /// be provided with or without arguments for formatting. See [`std::fmt`]
1560 /// for syntax for this form. Expressions used as format arguments will only
1561 /// be evaluated if the assertion fails.
1562 ///
1563 /// [`std::fmt`]: ../std/fmt/index.html
1564 ///
1565 /// # Examples
1566 ///
1567 /// ```
1568 /// // the panic message for these assertions is the stringified value of the
1569 /// // expression given.
1570 /// assert!(true);
1571 ///
1572 /// fn some_computation() -> bool { true } // a very simple function
1573 ///
1574 /// assert!(some_computation());
1575 ///
1576 /// // assert with a custom message
1577 /// let x = true;
1578 /// assert!(x, "x wasn't true!");
1579 ///
1580 /// let a = 3; let b = 27;
1581 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1582 /// ```
1583 #[stable(feature = "rust1", since = "1.0.0")]
1584 #[rustc_builtin_macro]
1585 #[macro_export]
1586 #[rustc_diagnostic_item = "assert_macro"]
1587 #[allow_internal_unstable(
1588 core_intrinsics,
1589 panic_internals,
1590 edition_panic,
1591 generic_assert_internals
1592 )]
1593 macro_rules! assert {
1594 ($cond:expr $(,)?) => {{ /* compiler built-in */ }};
1595 ($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }};
1596 }
1597
1598 /// Prints passed tokens into the standard output.
1599 #[unstable(
1600 feature = "log_syntax",
1601 issue = "29598",
1602 reason = "`log_syntax!` is not stable enough for use and is subject to change"
1603 )]
1604 #[rustc_builtin_macro]
1605 #[macro_export]
1606 macro_rules! log_syntax {
1607 ($($arg:tt)*) => {
1608 /* compiler built-in */
1609 };
1610 }
1611
1612 /// Enables or disables tracing functionality used for debugging other macros.
1613 #[unstable(
1614 feature = "trace_macros",
1615 issue = "29598",
1616 reason = "`trace_macros` is not stable enough for use and is subject to change"
1617 )]
1618 #[rustc_builtin_macro]
1619 #[macro_export]
1620 macro_rules! trace_macros {
1621 (true) => {{ /* compiler built-in */ }};
1622 (false) => {{ /* compiler built-in */ }};
1623 }
1624
1625 /// Attribute macro used to apply derive macros.
1626 ///
1627 /// See [the reference] for more info.
1628 ///
1629 /// [the reference]: ../../../reference/attributes/derive.html
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 #[rustc_builtin_macro]
1632 pub macro derive($item:item) {
1633 /* compiler built-in */
1634 }
1635
1636 /// Attribute macro used to apply derive macros for implementing traits
1637 /// in a const context.
1638 ///
1639 /// See [the reference] for more info.
1640 ///
1641 /// [the reference]: ../../../reference/attributes/derive.html
1642 #[unstable(feature = "derive_const", issue = "none")]
1643 #[rustc_builtin_macro]
1644 pub macro derive_const($item:item) {
1645 /* compiler built-in */
1646 }
1647
1648 /// Attribute macro applied to a function to turn it into a unit test.
1649 ///
1650 /// See [the reference] for more info.
1651 ///
1652 /// [the reference]: ../../../reference/attributes/testing.html#the-test-attribute
1653 #[stable(feature = "rust1", since = "1.0.0")]
1654 #[allow_internal_unstable(test, rustc_attrs, coverage_attribute)]
1655 #[rustc_builtin_macro]
1656 pub macro test($item:item) {
1657 /* compiler built-in */
1658 }
1659
1660 /// Attribute macro applied to a function to turn it into a benchmark test.
1661 #[unstable(
1662 feature = "test",
1663 issue = "50297",
1664 soft,
1665 reason = "`bench` is a part of custom test frameworks which are unstable"
1666 )]
1667 #[allow_internal_unstable(test, rustc_attrs, coverage_attribute)]
1668 #[rustc_builtin_macro]
1669 pub macro bench($item:item) {
1670 /* compiler built-in */
1671 }
1672
1673 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1674 #[unstable(
1675 feature = "custom_test_frameworks",
1676 issue = "50297",
1677 reason = "custom test frameworks are an unstable feature"
1678 )]
1679 #[allow_internal_unstable(test, rustc_attrs)]
1680 #[rustc_builtin_macro]
1681 pub macro test_case($item:item) {
1682 /* compiler built-in */
1683 }
1684
1685 /// Attribute macro applied to a static to register it as a global allocator.
1686 ///
1687 /// See also [`std::alloc::GlobalAlloc`](../../../std/alloc/trait.GlobalAlloc.html).
1688 #[stable(feature = "global_allocator", since = "1.28.0")]
1689 #[allow_internal_unstable(rustc_attrs)]
1690 #[rustc_builtin_macro]
1691 pub macro global_allocator($item:item) {
1692 /* compiler built-in */
1693 }
1694
1695 /// Attribute macro applied to a function to give it a post-condition.
1696 ///
1697 /// The attribute carries an argument token-tree which is
1698 /// eventually parsed as a unary closure expression that is
1699 /// invoked on a reference to the return value.
1700 #[unstable(feature = "contracts", issue = "128044")]
1701 #[allow_internal_unstable(contracts_internals)]
1702 #[rustc_builtin_macro]
1703 pub macro contracts_ensures($item:item) {
1704 /* compiler built-in */
1705 }
1706
1707 /// Attribute macro applied to a function to give it a precondition.
1708 ///
1709 /// The attribute carries an argument token-tree which is
1710 /// eventually parsed as an boolean expression with access to the
1711 /// function's formal parameters
1712 #[unstable(feature = "contracts", issue = "128044")]
1713 #[allow_internal_unstable(contracts_internals)]
1714 #[rustc_builtin_macro]
1715 pub macro contracts_requires($item:item) {
1716 /* compiler built-in */
1717 }
1718
1719 /// Attribute macro applied to a function to register it as a handler for allocation failure.
1720 ///
1721 /// See also [`std::alloc::handle_alloc_error`](../../../std/alloc/fn.handle_alloc_error.html).
1722 #[unstable(feature = "alloc_error_handler", issue = "51540")]
1723 #[allow_internal_unstable(rustc_attrs)]
1724 #[rustc_builtin_macro]
1725 pub macro alloc_error_handler($item:item) {
1726 /* compiler built-in */
1727 }
1728
1729 /// Keeps the item it's applied to if the passed path is accessible, and removes it otherwise.
1730 #[unstable(
1731 feature = "cfg_accessible",
1732 issue = "64797",
1733 reason = "`cfg_accessible` is not fully implemented"
1734 )]
1735 #[rustc_builtin_macro]
1736 pub macro cfg_accessible($item:item) {
1737 /* compiler built-in */
1738 }
1739
1740 /// Expands all `#[cfg]` and `#[cfg_attr]` attributes in the code fragment it's applied to.
1741 #[unstable(
1742 feature = "cfg_eval",
1743 issue = "82679",
1744 reason = "`cfg_eval` is a recently implemented feature"
1745 )]
1746 #[rustc_builtin_macro]
1747 pub macro cfg_eval($($tt:tt)*) {
1748 /* compiler built-in */
1749 }
1750
1751 /// Provide a list of type aliases and other opaque-type-containing type definitions.
1752 /// This list will be used in the body of the item it is applied to define opaque
1753 /// types' hidden types.
1754 /// Can only be applied to things that have bodies.
1755 #[unstable(
1756 feature = "type_alias_impl_trait",
1757 issue = "63063",
1758 reason = "`type_alias_impl_trait` has open design concerns"
1759 )]
1760 #[rustc_builtin_macro]
1761 pub macro define_opaque($($tt:tt)*) {
1762 /* compiler built-in */
1763 }
1764
1765 /// Unstable placeholder for type ascription.
1766 #[allow_internal_unstable(builtin_syntax)]
1767 #[unstable(
1768 feature = "type_ascription",
1769 issue = "23416",
1770 reason = "placeholder syntax for type ascription"
1771 )]
1772 #[rustfmt::skip]
1773 pub macro type_ascribe($expr:expr, $ty:ty) {
1774 builtin # type_ascribe($expr, $ty)
1775 }
1776
1777 /// Unstable placeholder for deref patterns.
1778 #[allow_internal_unstable(builtin_syntax)]
1779 #[unstable(
1780 feature = "deref_patterns",
1781 issue = "87121",
1782 reason = "placeholder syntax for deref patterns"
1783 )]
1784 pub macro deref($pat:pat) {
1785 builtin # deref($pat)
1786 }
1787}