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#[rustc_diagnostic_item = "assert_matches_macro"]
171#[allow_internal_unstable(panic_internals)]
172#[rustc_macro_transparency = "semiopaque"]
173pub macro assert_matches {
174 ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => {{
175 match $left {
176 $( $pattern )|+ $( if $guard )? => {}
177 ref left_val => {
178 $crate::panicking::assert_matches_failed(
179 left_val,
180 $crate::stringify!($($pattern)|+ $(if $guard)?),
181 $crate::option::Option::None
182 );
183 }
184 }
185 }},
186 ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )?, $($arg:tt)+) => {{
187 match $left {
188 $( $pattern )|+ $( if $guard )? => {}
189 ref left_val => {
190 $crate::panicking::assert_matches_failed(
191 left_val,
192 $crate::stringify!($($pattern)|+ $(if $guard)?),
193 $crate::option::Option::Some($crate::format_args!($($arg)+))
194 );
195 }
196 }
197 }},
198}
199
200/// Selects code at compile-time based on `cfg` predicates.
201///
202/// This macro evaluates, at compile-time, a series of `cfg` predicates,
203/// selects the first that is true, and emits the code guarded by that
204/// predicate. The code guarded by other predicates is not emitted.
205///
206/// An optional trailing `_` wildcard can be used to specify a fallback. If
207/// none of the predicates are true, a [`compile_error`] is emitted.
208///
209/// # Example
210///
211/// ```
212/// cfg_select! {
213/// unix => {
214/// fn foo() { /* unix specific functionality */ }
215/// }
216/// target_pointer_width = "32" => {
217/// fn foo() { /* non-unix, 32-bit functionality */ }
218/// }
219/// _ => {
220/// fn foo() { /* fallback implementation */ }
221/// }
222/// }
223/// ```
224///
225/// The `cfg_select!` macro can also be used in expression position, with or without braces on the
226/// right-hand side:
227///
228/// ```
229/// let _some_string = cfg_select! {
230/// unix => "With great power comes great electricity bills",
231/// _ => { "Behind every successful diet is an unwatched pizza" }
232/// };
233/// ```
234#[stable(feature = "cfg_select", since = "1.95.0")]
235#[doc(alias = "cfg_if", alias = "cfg-if")]
236#[rustc_diagnostic_item = "cfg_select"]
237#[rustc_builtin_macro]
238pub macro cfg_select($($tt:tt)*) {
239 /* compiler built-in */
240}
241
242/// Asserts that a boolean expression is `true` at runtime.
243///
244/// This will invoke the [`panic!`] macro if the provided expression cannot be
245/// evaluated to `true` at runtime.
246///
247/// Like [`assert!`], this macro also has a second version, where a custom panic
248/// message can be provided.
249///
250/// # Uses
251///
252/// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
253/// optimized builds by default. An optimized build will not execute
254/// `debug_assert!` statements unless `-C debug-assertions` is passed to the
255/// compiler. This makes `debug_assert!` useful for checks that are too
256/// expensive to be present in a release build but may be helpful during
257/// development. The result of expanding `debug_assert!` is always type checked.
258///
259/// An unchecked assertion allows a program in an inconsistent state to keep
260/// running, which might have unexpected consequences but does not introduce
261/// unsafety as long as this only happens in safe code. The performance cost
262/// of assertions, however, is not measurable in general. Replacing [`assert!`]
263/// with `debug_assert!` is thus only encouraged after thorough profiling, and
264/// more importantly, only in safe code!
265///
266/// # Examples
267///
268/// ```
269/// // the panic message for these assertions is the stringified value of the
270/// // expression given.
271/// debug_assert!(true);
272///
273/// fn some_expensive_computation() -> bool {
274/// // Some expensive computation here
275/// true
276/// }
277/// debug_assert!(some_expensive_computation());
278///
279/// // assert with a custom message
280/// let x = true;
281/// debug_assert!(x, "x wasn't true!");
282///
283/// let a = 3; let b = 27;
284/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
285/// ```
286#[macro_export]
287#[stable(feature = "rust1", since = "1.0.0")]
288#[rustc_diagnostic_item = "debug_assert_macro"]
289#[allow_internal_unstable(edition_panic)]
290#[rustc_diagnostic_opaque]
291macro_rules! debug_assert {
292 ($($arg:tt)*) => {
293 if $crate::cfg!(debug_assertions) {
294 $crate::assert!($($arg)*);
295 }
296 };
297}
298
299/// Asserts that two expressions are equal to each other.
300///
301/// On panic, this macro will print the values of the expressions with their
302/// debug representations.
303///
304/// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
305/// optimized builds by default. An optimized build will not execute
306/// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
307/// compiler. This makes `debug_assert_eq!` useful for checks that are too
308/// expensive to be present in a release build but may be helpful during
309/// development. The result of expanding `debug_assert_eq!` is always type checked.
310///
311/// # Examples
312///
313/// ```
314/// let a = 3;
315/// let b = 1 + 2;
316/// debug_assert_eq!(a, b);
317/// ```
318#[macro_export]
319#[stable(feature = "rust1", since = "1.0.0")]
320#[rustc_diagnostic_item = "debug_assert_eq_macro"]
321macro_rules! debug_assert_eq {
322 ($($arg:tt)*) => {
323 if $crate::cfg!(debug_assertions) {
324 $crate::assert_eq!($($arg)*);
325 }
326 };
327}
328
329/// Asserts that two expressions are not equal to each other.
330///
331/// On panic, this macro will print the values of the expressions with their
332/// debug representations.
333///
334/// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
335/// optimized builds by default. An optimized build will not execute
336/// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
337/// compiler. This makes `debug_assert_ne!` useful for checks that are too
338/// expensive to be present in a release build but may be helpful during
339/// development. The result of expanding `debug_assert_ne!` is always type checked.
340///
341/// # Examples
342///
343/// ```
344/// let a = 3;
345/// let b = 2;
346/// debug_assert_ne!(a, b);
347/// ```
348#[macro_export]
349#[stable(feature = "assert_ne", since = "1.13.0")]
350#[rustc_diagnostic_item = "debug_assert_ne_macro"]
351macro_rules! debug_assert_ne {
352 ($($arg:tt)*) => {
353 if $crate::cfg!(debug_assertions) {
354 $crate::assert_ne!($($arg)*);
355 }
356 };
357}
358
359/// Asserts that an expression matches the provided pattern.
360///
361/// This macro is generally preferable to `debug_assert!(matches!(value, pattern))`, because it can
362/// print the debug representation of the actual value shape that did not meet expectations. In
363/// contrast, using [`debug_assert!`] will only print that expectations were not met, but not why.
364///
365/// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The
366/// optional if guard can be used to add additional checks that must be true for the matched value,
367/// otherwise this macro will panic.
368///
369/// On panic, this macro will print the value of the expression with its debug representation.
370///
371/// Like [`assert!`], this macro has a second form, where a custom panic message can be provided.
372///
373/// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only enabled in non optimized
374/// builds by default. An optimized build will not execute `debug_assert_matches!` statements unless
375/// `-C debug-assertions` is passed to the compiler. This makes `debug_assert_matches!` useful for
376/// checks that are too expensive to be present in a release build but may be helpful during
377/// development. The result of expanding `debug_assert_matches!` is always type checked.
378///
379/// # Examples
380///
381/// ```
382/// use std::debug_assert_matches;
383///
384/// let a = Some(345);
385/// let b = Some(56);
386/// debug_assert_matches!(a, Some(_));
387/// debug_assert_matches!(b, Some(_));
388///
389/// debug_assert_matches!(a, Some(345));
390/// debug_assert_matches!(a, Some(345) | None);
391///
392/// // debug_assert_matches!(a, None); // panics
393/// // debug_assert_matches!(b, Some(345)); // panics
394/// // debug_assert_matches!(b, Some(345) | None); // panics
395///
396/// debug_assert_matches!(a, Some(x) if x > 100);
397/// // debug_assert_matches!(a, Some(x) if x < 100); // panics
398/// ```
399#[stable(feature = "assert_matches", since = "1.96.0")]
400#[rustc_diagnostic_item = "debug_assert_matches_macro"]
401#[allow_internal_unstable(assert_matches)]
402#[rustc_macro_transparency = "semiopaque"]
403pub macro debug_assert_matches($($arg:tt)*) {
404 if $crate::cfg!(debug_assertions) {
405 $crate::assert_matches!($($arg)*);
406 }
407}
408
409/// Returns whether the given expression matches the provided pattern.
410///
411/// The pattern syntax is exactly the same as found in a match arm. The optional if guard can be
412/// used to add additional checks that must be true for the matched value, otherwise this macro will
413/// return `false`.
414///
415/// When testing that a value matches a pattern, it's generally preferable to use
416/// [`assert_matches!`] as it will print the debug representation of the value if the assertion
417/// fails.
418///
419/// # Examples
420///
421/// ```
422/// let foo = 'f';
423/// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
424///
425/// let bar = Some(4);
426/// assert!(matches!(bar, Some(x) if x > 2));
427/// ```
428#[macro_export]
429#[stable(feature = "matches_macro", since = "1.42.0")]
430#[rustc_diagnostic_item = "matches_macro"]
431#[allow_internal_unstable(non_exhaustive_omitted_patterns_lint, stmt_expr_attributes)]
432#[rustc_diagnostic_opaque]
433macro_rules! matches {
434 ($expression:expr, $pattern:pat $(if $guard:expr)? $(,)?) => {
435 #[allow(non_exhaustive_omitted_patterns)]
436 match $expression {
437 $pattern $(if $guard)? => true,
438 _ => false
439 }
440 };
441}
442
443/// Unwraps a result or propagates its error.
444///
445/// The [`?` operator][propagating-errors] was added to replace `try!`
446/// and should be used instead. Furthermore, `try` is a reserved word
447/// in Rust 2018, so if you must use it, you will need to use the
448/// [raw-identifier syntax][ris]: `r#try`.
449///
450/// [propagating-errors]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator
451/// [ris]: ../rust-by-example/compatibility/raw_identifiers.html
452///
453/// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
454/// expression has the value of the wrapped value.
455///
456/// In case of the `Err` variant, it retrieves the inner error. `try!` then
457/// performs conversion using `From`. This provides automatic conversion
458/// between specialized errors and more general ones. The resulting
459/// error is then immediately returned.
460///
461/// Because of the early return, `try!` can only be used in functions that
462/// return [`Result`].
463///
464/// # Examples
465///
466/// ```
467/// use std::io;
468/// use std::fs::File;
469/// use std::io::prelude::*;
470///
471/// enum MyError {
472/// FileWriteError
473/// }
474///
475/// impl From<io::Error> for MyError {
476/// fn from(e: io::Error) -> MyError {
477/// MyError::FileWriteError
478/// }
479/// }
480///
481/// // The preferred method of quick returning Errors
482/// fn write_to_file_question() -> Result<(), MyError> {
483/// let mut file = File::create("my_best_friends.txt")?;
484/// file.write_all(b"This is a list of my best friends.")?;
485/// Ok(())
486/// }
487///
488/// // The previous method of quick returning Errors
489/// fn write_to_file_using_try() -> Result<(), MyError> {
490/// let mut file = r#try!(File::create("my_best_friends.txt"));
491/// r#try!(file.write_all(b"This is a list of my best friends."));
492/// Ok(())
493/// }
494///
495/// // This is equivalent to:
496/// fn write_to_file_using_match() -> Result<(), MyError> {
497/// let mut file = r#try!(File::create("my_best_friends.txt"));
498/// match file.write_all(b"This is a list of my best friends.") {
499/// Ok(v) => v,
500/// Err(e) => return Err(From::from(e)),
501/// }
502/// Ok(())
503/// }
504/// ```
505#[macro_export]
506#[stable(feature = "rust1", since = "1.0.0")]
507#[deprecated(since = "1.39.0", note = "use the `?` operator instead")]
508#[doc(alias = "?")]
509macro_rules! r#try {
510 ($expr:expr $(,)?) => {
511 match $expr {
512 $crate::result::Result::Ok(val) => val,
513 $crate::result::Result::Err(err) => {
514 return $crate::result::Result::Err($crate::convert::From::from(err));
515 }
516 }
517 };
518}
519
520/// Writes formatted data into a buffer.
521///
522/// This macro accepts a 'writer', a format string, and a list of arguments. Arguments will be
523/// formatted according to the specified format string and the result will be passed to the writer.
524/// The writer may be any value with a `write_fmt` method; generally this comes from an
525/// implementation of either the [`fmt::Write`] or the [`io::Write`] trait. The macro
526/// returns whatever the `write_fmt` method returns; commonly a [`fmt::Result`], or an
527/// [`io::Result`].
528///
529/// See [`std::fmt`] for more information on the format string syntax.
530///
531/// [`std::fmt`]: ../std/fmt/index.html
532/// [`fmt::Write`]: crate::fmt::Write
533/// [`io::Write`]: ../std/io/trait.Write.html
534/// [`fmt::Result`]: crate::fmt::Result
535/// [`io::Result`]: ../std/io/type.Result.html
536///
537/// # Examples
538///
539/// ```
540/// use std::io::Write;
541///
542/// fn main() -> std::io::Result<()> {
543/// let mut w = Vec::new();
544/// write!(&mut w, "test")?;
545/// write!(&mut w, "formatted {}", "arguments")?;
546///
547/// assert_eq!(w, b"testformatted arguments");
548/// Ok(())
549/// }
550/// ```
551///
552/// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
553/// implementing either, as objects do not typically implement both. However, the module must
554/// avoid conflict between the trait names, such as by importing them as `_` or otherwise renaming
555/// them:
556///
557/// ```
558/// use std::fmt::Write as _;
559/// use std::io::Write as _;
560///
561/// fn main() -> Result<(), Box<dyn std::error::Error>> {
562/// let mut s = String::new();
563/// let mut v = Vec::new();
564///
565/// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
566/// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
567/// assert_eq!(v, b"s = \"abc 123\"");
568/// Ok(())
569/// }
570/// ```
571///
572/// If you also need the trait names themselves, such as to implement one or both on your types,
573/// import the containing module and then name them with a prefix:
574///
575/// ```
576/// # #![allow(unused_imports)]
577/// use std::fmt::{self, Write as _};
578/// use std::io::{self, Write as _};
579///
580/// struct Example;
581///
582/// impl fmt::Write for Example {
583/// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
584/// unimplemented!();
585/// }
586/// }
587/// ```
588///
589/// Note: This macro can be used in `no_std` setups as well.
590/// In a `no_std` setup you are responsible for the implementation details of the components.
591///
592/// ```no_run
593/// use core::fmt::Write;
594///
595/// struct Example;
596///
597/// impl Write for Example {
598/// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
599/// unimplemented!();
600/// }
601/// }
602///
603/// let mut m = Example{};
604/// write!(&mut m, "Hello World").expect("Writing to `Example` should succeed");
605/// ```
606#[macro_export]
607#[stable(feature = "rust1", since = "1.0.0")]
608#[rustc_diagnostic_item = "write_macro"]
609#[rustc_diagnostic_opaque]
610macro_rules! write {
611 ($dst:expr, $($arg:tt)*) => {
612 $dst.write_fmt($crate::format_args!($($arg)*))
613 };
614 ($($arg:tt)*) => {
615 compile_error!("requires a destination and format arguments, like `write!(dest, \"format string\", args...)`")
616 };
617}
618
619/// Writes formatted data into a buffer, with a newline appended.
620///
621/// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
622/// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
623///
624/// For more information, see [`write!`]. For information on the format string syntax, see
625/// [`std::fmt`].
626///
627/// [`std::fmt`]: ../std/fmt/index.html
628///
629/// # Examples
630///
631/// ```
632/// use std::io::{Write, Result};
633///
634/// fn main() -> Result<()> {
635/// let mut w = Vec::new();
636/// writeln!(&mut w)?;
637/// writeln!(&mut w, "test")?;
638/// writeln!(&mut w, "formatted {}", "arguments")?;
639///
640/// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
641/// Ok(())
642/// }
643/// ```
644#[macro_export]
645#[stable(feature = "rust1", since = "1.0.0")]
646#[rustc_diagnostic_item = "writeln_macro"]
647#[allow_internal_unstable(format_args_nl)]
648#[rustc_diagnostic_opaque]
649macro_rules! writeln {
650 ($dst:expr $(,)?) => {
651 $crate::write!($dst, "\n")
652 };
653 ($dst:expr, $($arg:tt)*) => {
654 $dst.write_fmt($crate::format_args_nl!($($arg)*))
655 };
656 ($($arg:tt)*) => {
657 compile_error!("requires a destination and format arguments, like `writeln!(dest, \"format string\", args...)`")
658 };
659}
660
661/// Indicates unreachable code.
662///
663/// This is useful any time that the compiler can't determine that some code is unreachable. For
664/// example:
665///
666/// * Match arms with guard conditions.
667/// * Loops that dynamically terminate.
668/// * Iterators that dynamically terminate.
669///
670/// If the determination that the code is unreachable proves incorrect, the
671/// program immediately terminates with a [`panic!`].
672///
673/// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
674/// will cause undefined behavior if the code is reached.
675///
676/// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked
677///
678/// # Panics
679///
680/// This will always [`panic!`] because `unreachable!` is just a shorthand for `panic!` with a
681/// fixed, specific message.
682///
683/// Like `panic!`, this macro has a second form for displaying custom values.
684///
685/// # Examples
686///
687/// Match arms:
688///
689/// ```
690/// # #[allow(dead_code)]
691/// fn foo(x: Option<i32>) {
692/// match x {
693/// Some(n) if n >= 0 => println!("Some(Non-negative)"),
694/// Some(n) if n < 0 => println!("Some(Negative)"),
695/// Some(_) => unreachable!(), // compile error if commented out
696/// None => println!("None")
697/// }
698/// }
699/// ```
700///
701/// Iterators:
702///
703/// ```
704/// # #[allow(dead_code)]
705/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
706/// for i in 0.. {
707/// if 3*i < i { panic!("u32 overflow"); }
708/// if x < 3*i { return i-1; }
709/// }
710/// unreachable!("The loop should always return");
711/// }
712/// ```
713#[macro_export]
714#[rustc_builtin_macro(unreachable)]
715#[allow_internal_unstable(edition_panic)]
716#[stable(feature = "rust1", since = "1.0.0")]
717#[rustc_diagnostic_item = "unreachable_macro"]
718macro_rules! unreachable {
719 // Expands to either `$crate::panic::unreachable_2015` or `$crate::panic::unreachable_2021`
720 // depending on the edition of the caller.
721 ($($arg:tt)*) => {
722 /* compiler built-in */
723 };
724}
725
726/// Indicates unimplemented code by panicking with a message of "not implemented".
727///
728/// This allows your code to type-check, which is useful if you are prototyping or
729/// implementing a trait that requires multiple methods which you don't plan to use all of.
730///
731/// The difference between `unimplemented!` and [`todo!`] is that while `todo!`
732/// conveys an intent of implementing the functionality later and the message is "not yet
733/// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
734///
735/// Also, some IDEs will mark `todo!`s.
736///
737/// # Panics
738///
739/// This will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a
740/// fixed, specific message.
741///
742/// Like `panic!`, this macro has a second form for displaying custom values.
743///
744/// [`todo!`]: crate::todo
745///
746/// # Examples
747///
748/// Say we have a trait `Foo`:
749///
750/// ```
751/// trait Foo {
752/// fn bar(&self) -> u8;
753/// fn baz(&self);
754/// fn qux(&self) -> Result<u64, ()>;
755/// }
756/// ```
757///
758/// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
759/// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
760/// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
761/// to allow our code to compile.
762///
763/// We still want to have our program stop running if the unimplemented methods are
764/// reached.
765///
766/// ```
767/// # trait Foo {
768/// # fn bar(&self) -> u8;
769/// # fn baz(&self);
770/// # fn qux(&self) -> Result<u64, ()>;
771/// # }
772/// struct MyStruct;
773///
774/// impl Foo for MyStruct {
775/// fn bar(&self) -> u8 {
776/// 1 + 1
777/// }
778///
779/// fn baz(&self) {
780/// // It makes no sense to `baz` a `MyStruct`, so we have no logic here
781/// // at all.
782/// // This will display "thread 'main' panicked at 'not implemented'".
783/// unimplemented!();
784/// }
785///
786/// fn qux(&self) -> Result<u64, ()> {
787/// // We have some logic here,
788/// // We can add a message to unimplemented! to display our omission.
789/// // This will display:
790/// // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
791/// unimplemented!("MyStruct isn't quxable");
792/// }
793/// }
794///
795/// fn main() {
796/// let s = MyStruct;
797/// s.bar();
798/// }
799/// ```
800#[macro_export]
801#[stable(feature = "rust1", since = "1.0.0")]
802#[rustc_diagnostic_item = "unimplemented_macro"]
803#[allow_internal_unstable(panic_internals)]
804#[rustc_diagnostic_opaque]
805macro_rules! unimplemented {
806 () => {
807 $crate::panicking::unimplemented_default_msg()
808 };
809 ($($arg:tt)+) => {
810 $crate::panic!("not implemented: {}", $crate::format_args!($($arg)+))
811 };
812}
813
814/// Indicates unfinished code.
815///
816/// This can be useful if you are prototyping and just
817/// want a placeholder to let your code pass type analysis.
818///
819/// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
820/// an intent of implementing the functionality later and the message is "not yet
821/// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
822///
823/// Also, some IDEs will mark `todo!`s.
824///
825/// # Panics
826///
827/// This will always [`panic!`] because `todo!` is just a shorthand for `panic!` with a
828/// fixed, specific message.
829///
830/// Like `panic!`, this macro has a second form for displaying custom values.
831///
832/// # Examples
833///
834/// Here's an example of some in-progress code. We have a trait `Foo`:
835///
836/// ```
837/// trait Foo {
838/// fn bar(&self) -> u8;
839/// fn baz(&self);
840/// fn qux(&self) -> Result<u64, ()>;
841/// }
842/// ```
843///
844/// We want to implement `Foo` on one of our types, but we also want to work on
845/// just `bar()` first. In order for our code to compile, we need to implement
846/// `baz()` and `qux()`, so we can use `todo!`:
847///
848/// ```
849/// # trait Foo {
850/// # fn bar(&self) -> u8;
851/// # fn baz(&self);
852/// # fn qux(&self) -> Result<u64, ()>;
853/// # }
854/// struct MyStruct;
855///
856/// impl Foo for MyStruct {
857/// fn bar(&self) -> u8 {
858/// 1 + 1
859/// }
860///
861/// fn baz(&self) {
862/// // Let's not worry about implementing baz() for now
863/// todo!();
864/// }
865///
866/// fn qux(&self) -> Result<u64, ()> {
867/// // We can add a message to todo! to display our omission.
868/// // This will display:
869/// // "thread 'main' panicked at 'not yet implemented: MyStruct is not yet quxable'".
870/// todo!("MyStruct is not yet quxable");
871/// }
872/// }
873///
874/// fn main() {
875/// let s = MyStruct;
876/// s.bar();
877///
878/// // We aren't even using baz() or qux(), so this is fine.
879/// }
880/// ```
881#[macro_export]
882#[stable(feature = "todo_macro", since = "1.40.0")]
883#[rustc_diagnostic_item = "todo_macro"]
884#[allow_internal_unstable(panic_internals)]
885#[rustc_diagnostic_opaque]
886macro_rules! todo {
887 () => {
888 $crate::panicking::todo_default_msg()
889 };
890 ($($arg:tt)+) => {
891 $crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+))
892 };
893}
894
895/// Definitions of built-in macros.
896///
897/// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
898/// with exception of expansion functions transforming macro inputs into outputs,
899/// those functions are provided by the compiler.
900pub(crate) mod builtin {
901
902 /// Causes compilation to fail with the given error message when encountered.
903 ///
904 /// This macro should be used when a crate uses a conditional compilation strategy to provide
905 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
906 /// but emits an error during *compilation* rather than at *runtime*.
907 ///
908 /// # Examples
909 ///
910 /// Two such examples are macros and `#[cfg]` environments.
911 ///
912 /// Emit a better compiler error if a macro is passed invalid values. Without the final branch,
913 /// the compiler would still emit an error, but the error's message would not mention the two
914 /// valid values.
915 ///
916 /// ```compile_fail
917 /// macro_rules! give_me_foo_or_bar {
918 /// (foo) => {};
919 /// (bar) => {};
920 /// ($x:ident) => {
921 /// compile_error!("This macro only accepts `foo` or `bar`");
922 /// }
923 /// }
924 ///
925 /// give_me_foo_or_bar!(neither);
926 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
927 /// ```
928 ///
929 /// Emit a compiler error if one of a number of features isn't available.
930 ///
931 /// ```compile_fail
932 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
933 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
934 /// ```
935 #[stable(feature = "compile_error_macro", since = "1.20.0")]
936 #[rustc_builtin_macro]
937 #[macro_export]
938 macro_rules! compile_error {
939 ($msg:expr $(,)?) => {{ /* compiler built-in */ }};
940 }
941
942 /// Constructs parameters for the other string-formatting macros.
943 ///
944 /// This macro functions by taking a formatting string literal containing
945 /// `{}` for each additional argument passed. `format_args!` prepares the
946 /// additional parameters to ensure the output can be interpreted as a string
947 /// and canonicalizes the arguments into a single type. Any value that implements
948 /// the [`Display`] trait can be passed to `format_args!`, as can any
949 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
950 ///
951 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
952 /// passed to the macros within [`std::fmt`] for performing useful redirection.
953 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
954 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
955 /// heap allocations.
956 ///
957 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
958 /// in `Debug` and `Display` contexts as seen below. The example also shows
959 /// that `Debug` and `Display` format to the same thing: the interpolated
960 /// format string in `format_args!`.
961 ///
962 /// ```rust
963 /// let args = format_args!("{} foo {:?}", 1, 2);
964 /// let debug = format!("{args:?}");
965 /// let display = format!("{args}");
966 /// assert_eq!("1 foo 2", display);
967 /// assert_eq!(display, debug);
968 /// ```
969 ///
970 /// See [the formatting documentation in `std::fmt`](../std/fmt/index.html)
971 /// for details of the macro argument syntax, and further information.
972 ///
973 /// [`Display`]: crate::fmt::Display
974 /// [`Debug`]: crate::fmt::Debug
975 /// [`fmt::Arguments`]: crate::fmt::Arguments
976 /// [`std::fmt`]: ../std/fmt/index.html
977 /// [`format!`]: ../std/macro.format.html
978 /// [`println!`]: ../std/macro.println.html
979 ///
980 /// # Examples
981 ///
982 /// ```
983 /// use std::fmt;
984 ///
985 /// let s = fmt::format(format_args!("hello {}", "world"));
986 /// assert_eq!(s, format!("hello {}", "world"));
987 /// ```
988 ///
989 /// # Argument lifetimes
990 ///
991 /// Except when no formatting arguments are used,
992 /// the produced `fmt::Arguments` value borrows temporary values.
993 /// To allow it to be stored for later use, the arguments' lifetimes, as well as those of
994 /// temporaries they borrow, may be [extended] when `format_args!` appears in the initializer
995 /// expression of a `let` statement. The syntactic rules used to determine when temporaries'
996 /// lifetimes are extended are documented in the [Reference].
997 ///
998 /// [extended]: ../reference/destructors.html#temporary-lifetime-extension
999 /// [Reference]: ../reference/destructors.html#extending-based-on-expressions
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, fmt_arguments_from_str)]
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, fmt_arguments_from_str)]
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, fmt_arguments_from_str)]
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 ///
1512 /// ACTIVITIES might either be `Dual` or `Const`, more options will be exposed later.
1513 ///
1514 /// `Const` should be used on non-float arguments, or float-based arguments as an optimization
1515 /// if we are not interested in computing the derivatives with respect to this argument.
1516 ///
1517 /// `Dual` can be used for float scalar values or for references, raw pointers, or other
1518 /// indirect input arguments. It can also be used on a scalar float return value.
1519 /// If used on a return value, the generated function will return a tuple of two float scalars.
1520 /// If used on an input argument, a new shadow argument of the same type will be created,
1521 /// directly following the original argument.
1522 ///
1523 /// ### Usage examples:
1524 ///
1525 /// ```rust,ignore (autodiff requires a -Z flag as well as fat-lto for testing)
1526 /// #![feature(autodiff)]
1527 /// use std::autodiff::*;
1528 /// #[autodiff_forward(rb_fwd1, Dual, Const, Dual)]
1529 /// #[autodiff_forward(rb_fwd2, Const, Dual, Dual)]
1530 /// #[autodiff_forward(rb_fwd3, Dual, Dual, Dual)]
1531 /// fn rosenbrock(x: f64, y: f64) -> f64 {
1532 /// (1.0 - x).powi(2) + 100.0 * (y - x.powi(2)).powi(2)
1533 /// }
1534 /// #[autodiff_forward(rb_inp_fwd, Dual, Dual, Dual)]
1535 /// fn rosenbrock_inp(x: f64, y: f64, out: &mut f64) {
1536 /// *out = (1.0 - x).powi(2) + 100.0 * (y - x.powi(2)).powi(2);
1537 /// }
1538 ///
1539 /// fn main() {
1540 /// let x0 = rosenbrock(1.0, 3.0); // 400.0
1541 /// let (x1, dx1) = rb_fwd1(1.0, 1.0, 3.0); // (400.0, -800.0)
1542 /// let (x2, dy1) = rb_fwd2(1.0, 3.0, 1.0); // (400.0, 400.0)
1543 /// // When seeding both arguments at once the tangent return is the sum of both.
1544 /// let (x3, dxy) = rb_fwd3(1.0, 1.0, 3.0, 1.0); // (400.0, -400.0)
1545 ///
1546 /// let mut out = 0.0;
1547 /// let mut dout = 0.0;
1548 /// rb_inp_fwd(1.0, 1.0, 3.0, 1.0, &mut out, &mut dout);
1549 /// // (out, dout) == (400.0, -400.0)
1550 /// }
1551 /// ```
1552 ///
1553 /// We might want to track how one input float affects one or more output floats. In this case,
1554 /// the shadow of one input should be initialized to `1.0`, while the shadows of the other
1555 /// inputs should be initialized to `0.0`. The shadow of the output(s) should be initialized to
1556 /// `0.0`. After calling the generated function, the shadow of the input will be zeroed,
1557 /// while the shadow(s) of the output(s) will contain the derivatives. Forward mode is generally
1558 /// more efficient if we have more output floats marked as `Dual` than input floats.
1559 /// Related information can also be found under the term "Vector-Jacobian product" (VJP).
1560 #[unstable(feature = "autodiff", issue = "124509")]
1561 #[allow_internal_unstable(rustc_attrs)]
1562 #[allow_internal_unstable(core_intrinsics)]
1563 #[rustc_builtin_macro]
1564 pub macro autodiff_forward($item:item) {
1565 /* compiler built-in */
1566 }
1567
1568 /// This macro uses reverse-mode automatic differentiation to generate a new function.
1569 /// It may only be applied to a function. The new function will compute the derivative
1570 /// of the function to which the macro was applied.
1571 ///
1572 /// The expected usage syntax is:
1573 /// `#[autodiff_reverse(NAME, INPUT_ACTIVITIES, OUTPUT_ACTIVITY)]`
1574 ///
1575 /// - `NAME`: A string that represents a valid function name.
1576 /// - `INPUT_ACTIVITIES`: Specifies one valid activity for each input parameter.
1577 /// - `OUTPUT_ACTIVITY`: Must not be set if the function implicitly returns nothing
1578 /// (or explicitly returns `-> ()`). Otherwise, it must be set to one of the allowed activities.
1579 ///
1580 /// ACTIVITIES might either be `Active`, `Duplicated` or `Const`, more options will be exposed later.
1581 ///
1582 /// `Active` can be used for float scalar values.
1583 /// If used on an input, a new float will be appended to the return tuple of the generated
1584 /// function. If the function returns a float scalar, `Active` can be used for the return as
1585 /// well. In this case a float scalar will be appended to the argument list, it works as seed.
1586 ///
1587 /// `Duplicated` can be used on references, raw pointers, or other indirect input
1588 /// arguments. It creates a new shadow argument of the same type, following the original argument.
1589 /// A const reference or pointer argument will receive a mutable reference or pointer as shadow.
1590 ///
1591 /// `Const` should be used on non-float arguments, or float-based arguments as an optimization
1592 /// if we are not interested in computing the derivatives with respect to this argument.
1593 ///
1594 /// ### Usage examples:
1595 ///
1596 /// ```rust,ignore (autodiff requires a -Z flag as well as fat-lto for testing)
1597 /// #![feature(autodiff)]
1598 /// use std::autodiff::*;
1599 /// #[autodiff_reverse(rb_rev, Active, Active, Active)]
1600 /// fn rosenbrock(x: f64, y: f64) -> f64 {
1601 /// (1.0 - x).powi(2) + 100.0 * (y - x.powi(2)).powi(2)
1602 /// }
1603 /// #[autodiff_reverse(rb_inp_rev, Active, Active, Duplicated)]
1604 /// fn rosenbrock_inp(x: f64, y: f64, out: &mut f64) {
1605 /// *out = (1.0 - x).powi(2) + 100.0 * (y - x.powi(2)).powi(2);
1606 /// }
1607 ///
1608 /// fn main() {
1609 /// let (output1, dx1, dy1) = rb_rev(1.0, 3.0, 1.0);
1610 /// dbg!(output1, dx1, dy1); // (400.0, -800.0, 400.0)
1611 /// let mut output2 = 0.0;
1612 /// let mut seed = 1.0;
1613 /// let (dx2, dy2) = rb_inp_rev(1.0, 3.0, &mut output2, &mut seed);
1614 /// // (dx2, dy2, output2, seed) == (-800.0, 400.0, 400.0, 0.0)
1615 /// }
1616 /// ```
1617 ///
1618 ///
1619 /// We often want to track how one or more input floats affect one output float. This output can
1620 /// be a scalar return value, or a mutable reference or pointer argument. In the latter case, the
1621 /// mutable input should be marked as duplicated and its shadow initialized to `0.0`. The shadow of
1622 /// the output should be marked as active or duplicated and initialized to `1.0`. After calling
1623 /// the generated function, the shadow(s) of the input(s) will contain the derivatives. The
1624 /// shadow of the outputs ("seed") will be reset to zero.
1625 /// If the function has more than one output float marked as active or duplicated, users might want to
1626 /// set one of them to `1.0` and the others to `0.0` to compute partial derivatives.
1627 /// Unlike forward-mode, a call to the generated function does not reset the shadow of the
1628 /// inputs.
1629 /// Reverse mode is generally more efficient if we have more active/duplicated input than
1630 /// output floats.
1631 ///
1632 /// Related information can also be found under the term "Jacobian-Vector Product" (JVP).
1633 #[unstable(feature = "autodiff", issue = "124509")]
1634 #[allow_internal_unstable(rustc_attrs)]
1635 #[allow_internal_unstable(core_intrinsics)]
1636 #[rustc_builtin_macro]
1637 pub macro autodiff_reverse($item:item) {
1638 /* compiler built-in */
1639 }
1640
1641 /// The `offload_kernel` macro is applied to a function to generate two separate
1642 /// definitions: a host-side wrapper for dispatch and a device-side kernel.
1643 ///
1644 /// The macro does not perform the offload itself. It generates the necessary
1645 /// code required by the compiler's offloading infrastructure.
1646 ///
1647 /// ### Usage example:
1648 ///
1649 /// ```rust,ignore (offload requires a -Z flag)
1650 /// #[offload_kernel]
1651 /// fn foo(a: &[f32], b: &[f32], c: *mut f32) {
1652 /// *c = a[0] + b[0];
1653 /// }
1654 /// ```
1655 ///
1656 /// This expands to the host-side function:
1657 ///
1658 /// ```rust,ignore (offload requires a -Z flag)
1659 /// #[unsafe(no_mangle)]
1660 /// #[inline(never)]
1661 /// fn foo(_: &[f32], _: &[f32], _: *mut f32) {
1662 /// ::core::panicking::panic("not implemented")
1663 /// }
1664 /// ```
1665 ///
1666 /// And the device-side kernel:
1667 ///
1668 /// ```rust,ignore (offload requires a -Z flag)
1669 /// #[rustc_offload_kernel]
1670 /// #[unsafe(no_mangle)]
1671 /// unsafe extern "gpu-kernel" fn foo(a: &[f32], b: &[f32], c: *mut f32) {
1672 /// *c = a[0] + b[0];
1673 /// }
1674 /// ```
1675 #[unstable(feature = "gpu_offload", issue = "131513")]
1676 #[allow_internal_unstable(rustc_attrs)]
1677 #[allow_internal_unstable(core_intrinsics)]
1678 #[rustc_builtin_macro]
1679 pub macro offload_kernel($item:item) {
1680 /* compiler built-in */
1681 }
1682
1683 /// Asserts that a boolean expression is `true` at runtime.
1684 ///
1685 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1686 /// evaluated to `true` at runtime.
1687 ///
1688 /// # Uses
1689 ///
1690 /// Assertions are always checked in both debug and release builds, and cannot
1691 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1692 /// release builds by default.
1693 ///
1694 /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if
1695 /// violated could lead to unsafety.
1696 ///
1697 /// Other use-cases of `assert!` include testing and enforcing run-time
1698 /// invariants in safe code (whose violation cannot result in unsafety).
1699 ///
1700 /// # Custom Messages
1701 ///
1702 /// This macro has a second form, where a custom panic message can
1703 /// be provided with or without arguments for formatting. See [`std::fmt`]
1704 /// for syntax for this form. Expressions used as format arguments will only
1705 /// be evaluated if the assertion fails.
1706 ///
1707 /// [`std::fmt`]: ../std/fmt/index.html
1708 ///
1709 /// # Examples
1710 ///
1711 /// ```
1712 /// // the panic message for these assertions is the stringified value of the
1713 /// // expression given.
1714 /// assert!(true);
1715 ///
1716 /// fn some_computation() -> bool {
1717 /// // Some expensive computation here
1718 /// true
1719 /// }
1720 ///
1721 /// assert!(some_computation());
1722 ///
1723 /// // assert with a custom message
1724 /// let x = true;
1725 /// assert!(x, "x wasn't true!");
1726 ///
1727 /// let a = 3; let b = 27;
1728 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1729 /// ```
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 #[rustc_builtin_macro]
1732 #[macro_export]
1733 #[rustc_diagnostic_item = "assert_macro"]
1734 #[allow_internal_unstable(
1735 core_intrinsics,
1736 panic_internals,
1737 edition_panic,
1738 generic_assert_internals
1739 )]
1740 macro_rules! assert {
1741 ($cond:expr $(,)?) => {{ /* compiler built-in */ }};
1742 ($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }};
1743 }
1744
1745 /// Prints passed tokens into the standard output.
1746 #[unstable(
1747 feature = "log_syntax",
1748 issue = "29598",
1749 reason = "`log_syntax!` is not stable enough for use and is subject to change"
1750 )]
1751 #[rustc_builtin_macro]
1752 #[macro_export]
1753 macro_rules! log_syntax {
1754 ($($arg:tt)*) => {
1755 /* compiler built-in */
1756 };
1757 }
1758
1759 /// Enables or disables tracing functionality used for debugging other macros.
1760 #[unstable(
1761 feature = "trace_macros",
1762 issue = "29598",
1763 reason = "`trace_macros` is not stable enough for use and is subject to change"
1764 )]
1765 #[rustc_builtin_macro]
1766 #[macro_export]
1767 macro_rules! trace_macros {
1768 (true) => {{ /* compiler built-in */ }};
1769 (false) => {{ /* compiler built-in */ }};
1770 }
1771
1772 /// Attribute macro used to apply derive macros.
1773 ///
1774 /// See [the reference] for more info.
1775 ///
1776 /// [the reference]: ../reference/attributes/derive.html
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 #[rustc_builtin_macro]
1779 pub macro derive($item:item) {
1780 /* compiler built-in */
1781 }
1782
1783 /// Attribute macro used to apply derive macros for implementing traits
1784 /// in a const context.
1785 ///
1786 /// See [the reference] for more info.
1787 ///
1788 /// [the reference]: ../../../reference/attributes/derive.html
1789 #[unstable(feature = "derive_const", issue = "143874")]
1790 #[rustc_builtin_macro]
1791 pub macro derive_const($item:item) {
1792 /* compiler built-in */
1793 }
1794
1795 /// Attribute macro applied to a function to turn it into a unit test.
1796 ///
1797 /// See [the reference] for more info.
1798 ///
1799 /// [the reference]: ../../../reference/attributes/testing.html#the-test-attribute
1800 #[stable(feature = "rust1", since = "1.0.0")]
1801 #[allow_internal_unstable(test, rustc_attrs, coverage_attribute)]
1802 #[rustc_builtin_macro]
1803 pub macro test($item:item) {
1804 /* compiler built-in */
1805 }
1806
1807 /// Attribute macro applied to a function to turn it into a benchmark test.
1808 #[unstable(
1809 feature = "test",
1810 issue = "50297",
1811 reason = "`bench` is a part of custom test frameworks which are unstable"
1812 )]
1813 #[allow_internal_unstable(test, rustc_attrs, coverage_attribute)]
1814 #[rustc_builtin_macro]
1815 pub macro bench($item:item) {
1816 /* compiler built-in */
1817 }
1818
1819 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1820 #[unstable(
1821 feature = "custom_test_frameworks",
1822 issue = "50297",
1823 reason = "custom test frameworks are an unstable feature"
1824 )]
1825 #[allow_internal_unstable(test, rustc_attrs)]
1826 #[rustc_builtin_macro]
1827 pub macro test_case($item:item) {
1828 /* compiler built-in */
1829 }
1830
1831 /// Attribute macro applied to a static to register it as a global allocator.
1832 ///
1833 /// See also [`std::alloc::GlobalAlloc`](../../../std/alloc/trait.GlobalAlloc.html).
1834 #[stable(feature = "global_allocator", since = "1.28.0")]
1835 #[allow_internal_unstable(rustc_attrs, ptr_alignment_type)]
1836 #[rustc_builtin_macro]
1837 pub macro global_allocator($item:item) {
1838 /* compiler built-in */
1839 }
1840
1841 /// Attribute macro applied to a function to give it a post-condition.
1842 ///
1843 /// The attribute carries an argument token-tree which is
1844 /// eventually parsed as a unary closure expression that is
1845 /// invoked on a reference to the return value.
1846 #[unstable(feature = "contracts", issue = "128044")]
1847 #[allow_internal_unstable(contracts_internals)]
1848 #[rustc_builtin_macro]
1849 pub macro contracts_ensures($item:item) {
1850 /* compiler built-in */
1851 }
1852
1853 /// Attribute macro applied to a function to give it a precondition.
1854 ///
1855 /// The attribute carries an argument token-tree which is
1856 /// eventually parsed as an boolean expression with access to the
1857 /// function's formal parameters
1858 #[unstable(feature = "contracts", issue = "128044")]
1859 #[allow_internal_unstable(contracts_internals)]
1860 #[rustc_builtin_macro]
1861 pub macro contracts_requires($item:item) {
1862 /* compiler built-in */
1863 }
1864
1865 /// Attribute macro applied to a function to register it as a handler for allocation failure.
1866 ///
1867 /// See also [`std::alloc::handle_alloc_error`](../../../std/alloc/fn.handle_alloc_error.html).
1868 #[unstable(feature = "alloc_error_handler", issue = "51540")]
1869 #[allow_internal_unstable(rustc_attrs)]
1870 #[rustc_builtin_macro]
1871 pub macro alloc_error_handler($item:item) {
1872 /* compiler built-in */
1873 }
1874
1875 /// Keeps the item it's applied to if the passed path is accessible, and removes it otherwise.
1876 #[unstable(
1877 feature = "cfg_accessible",
1878 issue = "64797",
1879 reason = "`cfg_accessible` is not fully implemented"
1880 )]
1881 #[rustc_builtin_macro]
1882 pub macro cfg_accessible($item:item) {
1883 /* compiler built-in */
1884 }
1885
1886 /// Expands all `#[cfg]` and `#[cfg_attr]` attributes in the code fragment it's applied to.
1887 #[unstable(
1888 feature = "cfg_eval",
1889 issue = "82679",
1890 reason = "`cfg_eval` is a recently implemented feature"
1891 )]
1892 #[rustc_builtin_macro]
1893 pub macro cfg_eval($($tt:tt)*) {
1894 /* compiler built-in */
1895 }
1896
1897 /// Provide a list of type aliases and other opaque-type-containing type definitions
1898 /// to an item with a body. This list will be used in that body to define opaque
1899 /// types' hidden types.
1900 /// Can only be applied to things that have bodies.
1901 #[unstable(
1902 feature = "type_alias_impl_trait",
1903 issue = "63063",
1904 reason = "`type_alias_impl_trait` has open design concerns"
1905 )]
1906 #[rustc_builtin_macro]
1907 pub macro define_opaque($($tt:tt)*) {
1908 /* compiler built-in */
1909 }
1910
1911 /// Unstable placeholder for type ascription.
1912 #[allow_internal_unstable(internal_syntax)]
1913 #[unstable(
1914 feature = "type_ascription",
1915 issue = "101728",
1916 reason = "placeholder syntax for type ascription"
1917 )]
1918 #[diagnostic::opaque]
1919 pub macro type_ascribe($expr:expr, $ty:ty) {
1920 k#type_ascribe($expr, $ty)
1921 }
1922
1923 /// Unstable placeholder for deref patterns.
1924 #[allow_internal_unstable(internal_syntax)]
1925 #[unstable(
1926 feature = "deref_patterns",
1927 issue = "87121",
1928 reason = "placeholder syntax for deref patterns"
1929 )]
1930 #[diagnostic::opaque]
1931 pub macro deref($pat:pat) {
1932 k#deref($pat)
1933 }
1934
1935 /// Derive macro generating an impl of the trait `From`.
1936 /// Currently, it can only be used on single-field structs.
1937 // Note that the macro is in a different module than the `From` trait,
1938 // to avoid triggering an unstable feature being used if someone imports
1939 // `std::convert::From`.
1940 #[rustc_builtin_macro]
1941 #[unstable(feature = "derive_from", issue = "144889")]
1942 pub macro From($item: item) {
1943 /* compiler built-in */
1944 }
1945
1946 /// Externally Implementable Item: Defines an attribute macro that can override the item
1947 /// this is applied to.
1948 #[unstable(feature = "extern_item_impls", issue = "125418")]
1949 #[rustc_builtin_macro]
1950 #[allow_internal_unstable(eii_internals, decl_macro, rustc_attrs)]
1951 pub macro eii($item:item) {
1952 /* compiler built-in */
1953 }
1954
1955 /// Unsafely Externally Implementable Item: Defines an unsafe attribute macro that can override
1956 /// the item this is applied to.
1957 #[unstable(feature = "extern_item_impls", issue = "125418")]
1958 #[rustc_builtin_macro]
1959 #[allow_internal_unstable(eii_internals, decl_macro, rustc_attrs)]
1960 pub macro unsafe_eii($item:item) {
1961 /* compiler built-in */
1962 }
1963
1964 /// Impl detail of EII
1965 #[unstable(feature = "eii_internals", issue = "none")]
1966 #[rustc_builtin_macro]
1967 pub macro eii_declaration($item:item) {
1968 /* compiler built-in */
1969 }
1970}