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