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