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