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