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