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