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