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