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/// [`debug_assert_matches!`]: crate::debug_assert_matches
142///
143/// On panic, this macro will print the value of the expression with its debug representation.
144///
145/// Like [`assert!`], this macro has a second form, where a custom panic message can be provided.
146///
147/// # Examples
148///
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#[stable(feature = "assert_matches", since = "1.96.0")]
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/// cfg_select! {
210/// unix => {
211/// fn foo() { /* unix specific functionality */ }
212/// }
213/// target_pointer_width = "32" => {
214/// fn foo() { /* non-unix, 32-bit functionality */ }
215/// }
216/// _ => {
217/// fn foo() { /* fallback implementation */ }
218/// }
219/// }
220/// ```
221///
222/// The `cfg_select!` macro can also be used in expression position, with or without braces on the
223/// right-hand side:
224///
225/// ```
226/// let _some_string = cfg_select! {
227/// unix => "With great power comes great electricity bills",
228/// _ => { "Behind every successful diet is an unwatched pizza" }
229/// };
230/// ```
231#[stable(feature = "cfg_select", since = "1.95.0")]
232#[doc(alias = "cfg_if", alias = "cfg-if")]
233#[rustc_diagnostic_item = "cfg_select"]
234#[rustc_builtin_macro]
235pub macro cfg_select($($tt:tt)*) {
236 /* compiler built-in */
237}
238
239/// Asserts that a boolean expression is `true` at runtime.
240///
241/// This will invoke the [`panic!`] macro if the provided expression cannot be
242/// evaluated to `true` at runtime.
243///
244/// Like [`assert!`], this macro also has a second version, where a custom panic
245/// message can be provided.
246///
247/// # Uses
248///
249/// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
250/// optimized builds by default. An optimized build will not execute
251/// `debug_assert!` statements unless `-C debug-assertions` is passed to the
252/// compiler. This makes `debug_assert!` useful for checks that are too
253/// expensive to be present in a release build but may be helpful during
254/// development. The result of expanding `debug_assert!` is always type checked.
255///
256/// An unchecked assertion allows a program in an inconsistent state to keep
257/// running, which might have unexpected consequences but does not introduce
258/// unsafety as long as this only happens in safe code. The performance cost
259/// of assertions, however, is not measurable in general. Replacing [`assert!`]
260/// with `debug_assert!` is thus only encouraged after thorough profiling, and
261/// more importantly, only in safe code!
262///
263/// # Examples
264///
265/// ```
266/// // the panic message for these assertions is the stringified value of the
267/// // expression given.
268/// debug_assert!(true);
269///
270/// fn some_expensive_computation() -> bool {
271/// // Some expensive computation here
272/// true
273/// }
274/// debug_assert!(some_expensive_computation());
275///
276/// // assert with a custom message
277/// let x = true;
278/// debug_assert!(x, "x wasn't true!");
279///
280/// let a = 3; let b = 27;
281/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
282/// ```
283#[macro_export]
284#[stable(feature = "rust1", since = "1.0.0")]
285#[rustc_diagnostic_item = "debug_assert_macro"]
286#[allow_internal_unstable(edition_panic)]
287macro_rules! debug_assert {
288 ($($arg:tt)*) => {
289 if $crate::cfg!(debug_assertions) {
290 $crate::assert!($($arg)*);
291 }
292 };
293}
294
295/// Asserts that two expressions are equal to each other.
296///
297/// On panic, this macro will print the values of the expressions with their
298/// debug representations.
299///
300/// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
301/// optimized builds by default. An optimized build will not execute
302/// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
303/// compiler. This makes `debug_assert_eq!` useful for checks that are too
304/// expensive to be present in a release build but may be helpful during
305/// development. The result of expanding `debug_assert_eq!` is always type checked.
306///
307/// # Examples
308///
309/// ```
310/// let a = 3;
311/// let b = 1 + 2;
312/// debug_assert_eq!(a, b);
313/// ```
314#[macro_export]
315#[stable(feature = "rust1", since = "1.0.0")]
316#[rustc_diagnostic_item = "debug_assert_eq_macro"]
317macro_rules! debug_assert_eq {
318 ($($arg:tt)*) => {
319 if $crate::cfg!(debug_assertions) {
320 $crate::assert_eq!($($arg)*);
321 }
322 };
323}
324
325/// Asserts that two expressions are not equal to each other.
326///
327/// On panic, this macro will print the values of the expressions with their
328/// debug representations.
329///
330/// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
331/// optimized builds by default. An optimized build will not execute
332/// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
333/// compiler. This makes `debug_assert_ne!` useful for checks that are too
334/// expensive to be present in a release build but may be helpful during
335/// development. The result of expanding `debug_assert_ne!` is always type checked.
336///
337/// # Examples
338///
339/// ```
340/// let a = 3;
341/// let b = 2;
342/// debug_assert_ne!(a, b);
343/// ```
344#[macro_export]
345#[stable(feature = "assert_ne", since = "1.13.0")]
346#[rustc_diagnostic_item = "debug_assert_ne_macro"]
347macro_rules! debug_assert_ne {
348 ($($arg:tt)*) => {
349 if $crate::cfg!(debug_assertions) {
350 $crate::assert_ne!($($arg)*);
351 }
352 };
353}
354
355/// Asserts that an expression matches the provided pattern.
356///
357/// This macro is generally preferable to `debug_assert!(matches!(value, pattern))`, because it can
358/// print the debug representation of the actual value shape that did not meet expectations. In
359/// contrast, using [`debug_assert!`] will only print that expectations were not met, but not why.
360///
361/// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The
362/// optional if guard can be used to add additional checks that must be true for the matched value,
363/// otherwise this macro will panic.
364///
365/// On panic, this macro will print the value of the expression with its debug representation.
366///
367/// Like [`assert!`], this macro has a second form, where a custom panic message can be provided.
368///
369/// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only enabled in non optimized
370/// builds by default. An optimized build will not execute `debug_assert_matches!` statements unless
371/// `-C debug-assertions` is passed to the compiler. This makes `debug_assert_matches!` useful for
372/// checks that are too expensive to be present in a release build but may be helpful during
373/// development. The result of expanding `debug_assert_matches!` is always type checked.
374///
375/// # Examples
376///
377/// ```
378/// use std::debug_assert_matches;
379///
380/// let a = Some(345);
381/// let b = Some(56);
382/// debug_assert_matches!(a, Some(_));
383/// debug_assert_matches!(b, Some(_));
384///
385/// debug_assert_matches!(a, Some(345));
386/// debug_assert_matches!(a, Some(345) | None);
387///
388/// // debug_assert_matches!(a, None); // panics
389/// // debug_assert_matches!(b, Some(345)); // panics
390/// // debug_assert_matches!(b, Some(345) | None); // panics
391///
392/// debug_assert_matches!(a, Some(x) if x > 100);
393/// // debug_assert_matches!(a, Some(x) if x < 100); // panics
394/// ```
395#[stable(feature = "assert_matches", since = "1.96.0")]
396#[allow_internal_unstable(assert_matches)]
397#[rustc_macro_transparency = "semiopaque"]
398pub macro debug_assert_matches($($arg:tt)*) {
399 if $crate::cfg!(debug_assertions) {
400 $crate::assert_matches!($($arg)*);
401 }
402}
403
404/// Returns whether the given expression matches the provided pattern.
405///
406/// The pattern syntax is exactly the same as found in a match arm. The optional if guard can be
407/// used to add additional checks that must be true for the matched value, otherwise this macro will
408/// return `false`.
409///
410/// When testing that a value matches a pattern, it's generally preferable to use
411/// [`assert_matches!`] as it will print the debug representation of the value if the assertion
412/// fails.
413///
414/// # Examples
415///
416/// ```
417/// let foo = 'f';
418/// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
419///
420/// let bar = Some(4);
421/// assert!(matches!(bar, Some(x) if x > 2));
422/// ```
423#[macro_export]
424#[stable(feature = "matches_macro", since = "1.42.0")]
425#[rustc_diagnostic_item = "matches_macro"]
426#[allow_internal_unstable(non_exhaustive_omitted_patterns_lint, stmt_expr_attributes)]
427macro_rules! matches {
428 ($expression:expr, $pattern:pat $(if $guard:expr)? $(,)?) => {
429 #[allow(non_exhaustive_omitted_patterns)]
430 match $expression {
431 $pattern $(if $guard)? => true,
432 _ => false
433 }
434 };
435}
436
437/// Unwraps a result or propagates its error.
438///
439/// The [`?` operator][propagating-errors] was added to replace `try!`
440/// and should be used instead. Furthermore, `try` is a reserved word
441/// in Rust 2018, so if you must use it, you will need to use the
442/// [raw-identifier syntax][ris]: `r#try`.
443///
444/// [propagating-errors]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator
445/// [ris]: ../rust-by-example/compatibility/raw_identifiers.html
446///
447/// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
448/// expression has the value of the wrapped value.
449///
450/// In case of the `Err` variant, it retrieves the inner error. `try!` then
451/// performs conversion using `From`. This provides automatic conversion
452/// between specialized errors and more general ones. The resulting
453/// error is then immediately returned.
454///
455/// Because of the early return, `try!` can only be used in functions that
456/// return [`Result`].
457///
458/// # Examples
459///
460/// ```
461/// use std::io;
462/// use std::fs::File;
463/// use std::io::prelude::*;
464///
465/// enum MyError {
466/// FileWriteError
467/// }
468///
469/// impl From<io::Error> for MyError {
470/// fn from(e: io::Error) -> MyError {
471/// MyError::FileWriteError
472/// }
473/// }
474///
475/// // The preferred method of quick returning Errors
476/// fn write_to_file_question() -> Result<(), MyError> {
477/// let mut file = File::create("my_best_friends.txt")?;
478/// file.write_all(b"This is a list of my best friends.")?;
479/// Ok(())
480/// }
481///
482/// // The previous method of quick returning Errors
483/// fn write_to_file_using_try() -> Result<(), MyError> {
484/// let mut file = r#try!(File::create("my_best_friends.txt"));
485/// r#try!(file.write_all(b"This is a list of my best friends."));
486/// Ok(())
487/// }
488///
489/// // This is equivalent to:
490/// fn write_to_file_using_match() -> Result<(), MyError> {
491/// let mut file = r#try!(File::create("my_best_friends.txt"));
492/// match file.write_all(b"This is a list of my best friends.") {
493/// Ok(v) => v,
494/// Err(e) => return Err(From::from(e)),
495/// }
496/// Ok(())
497/// }
498/// ```
499#[macro_export]
500#[stable(feature = "rust1", since = "1.0.0")]
501#[deprecated(since = "1.39.0", note = "use the `?` operator instead")]
502#[doc(alias = "?")]
503macro_rules! r#try {
504 ($expr:expr $(,)?) => {
505 match $expr {
506 $crate::result::Result::Ok(val) => val,
507 $crate::result::Result::Err(err) => {
508 return $crate::result::Result::Err($crate::convert::From::from(err));
509 }
510 }
511 };
512}
513
514/// Writes formatted data into a buffer.
515///
516/// This macro accepts a 'writer', a format string, and a list of arguments. Arguments will be
517/// formatted according to the specified format string and the result will be passed to the writer.
518/// The writer may be any value with a `write_fmt` method; generally this comes from an
519/// implementation of either the [`fmt::Write`] or the [`io::Write`] trait. The macro
520/// returns whatever the `write_fmt` method returns; commonly a [`fmt::Result`], or an
521/// [`io::Result`].
522///
523/// See [`std::fmt`] for more information on the format string syntax.
524///
525/// [`std::fmt`]: ../std/fmt/index.html
526/// [`fmt::Write`]: crate::fmt::Write
527/// [`io::Write`]: ../std/io/trait.Write.html
528/// [`fmt::Result`]: crate::fmt::Result
529/// [`io::Result`]: ../std/io/type.Result.html
530///
531/// # Examples
532///
533/// ```
534/// use std::io::Write;
535///
536/// fn main() -> std::io::Result<()> {
537/// let mut w = Vec::new();
538/// write!(&mut w, "test")?;
539/// write!(&mut w, "formatted {}", "arguments")?;
540///
541/// assert_eq!(w, b"testformatted arguments");
542/// Ok(())
543/// }
544/// ```
545///
546/// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
547/// implementing either, as objects do not typically implement both. However, the module must
548/// avoid conflict between the trait names, such as by importing them as `_` or otherwise renaming
549/// them:
550///
551/// ```
552/// use std::fmt::Write as _;
553/// use std::io::Write as _;
554///
555/// fn main() -> Result<(), Box<dyn std::error::Error>> {
556/// let mut s = String::new();
557/// let mut v = Vec::new();
558///
559/// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
560/// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
561/// assert_eq!(v, b"s = \"abc 123\"");
562/// Ok(())
563/// }
564/// ```
565///
566/// If you also need the trait names themselves, such as to implement one or both on your types,
567/// import the containing module and then name them with a prefix:
568///
569/// ```
570/// # #![allow(unused_imports)]
571/// use std::fmt::{self, Write as _};
572/// use std::io::{self, Write as _};
573///
574/// struct Example;
575///
576/// impl fmt::Write for Example {
577/// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
578/// unimplemented!();
579/// }
580/// }
581/// ```
582///
583/// Note: This macro can be used in `no_std` setups as well.
584/// In a `no_std` setup you are responsible for the implementation details of the components.
585///
586/// ```no_run
587/// use core::fmt::Write;
588///
589/// struct Example;
590///
591/// impl Write for Example {
592/// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
593/// unimplemented!();
594/// }
595/// }
596///
597/// let mut m = Example{};
598/// write!(&mut m, "Hello World").expect("Not written");
599/// ```
600#[macro_export]
601#[stable(feature = "rust1", since = "1.0.0")]
602#[rustc_diagnostic_item = "write_macro"]
603macro_rules! write {
604 ($dst:expr, $($arg:tt)*) => {
605 $dst.write_fmt($crate::format_args!($($arg)*))
606 };
607 ($($arg:tt)*) => {
608 compile_error!("requires a destination and format arguments, like `write!(dest, \"format string\", args...)`")
609 };
610}
611
612/// Writes formatted data into a buffer, with a newline appended.
613///
614/// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
615/// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
616///
617/// For more information, see [`write!`]. For information on the format string syntax, see
618/// [`std::fmt`].
619///
620/// [`std::fmt`]: ../std/fmt/index.html
621///
622/// # Examples
623///
624/// ```
625/// use std::io::{Write, Result};
626///
627/// fn main() -> Result<()> {
628/// let mut w = Vec::new();
629/// writeln!(&mut w)?;
630/// writeln!(&mut w, "test")?;
631/// writeln!(&mut w, "formatted {}", "arguments")?;
632///
633/// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
634/// Ok(())
635/// }
636/// ```
637#[macro_export]
638#[stable(feature = "rust1", since = "1.0.0")]
639#[rustc_diagnostic_item = "writeln_macro"]
640#[allow_internal_unstable(format_args_nl)]
641macro_rules! writeln {
642 ($dst:expr $(,)?) => {
643 $crate::write!($dst, "\n")
644 };
645 ($dst:expr, $($arg:tt)*) => {
646 $dst.write_fmt($crate::format_args_nl!($($arg)*))
647 };
648 ($($arg:tt)*) => {
649 compile_error!("requires a destination and format arguments, like `writeln!(dest, \"format string\", args...)`")
650 };
651}
652
653/// Indicates unreachable code.
654///
655/// This is useful any time that the compiler can't determine that some code is unreachable. For
656/// example:
657///
658/// * Match arms with guard conditions.
659/// * Loops that dynamically terminate.
660/// * Iterators that dynamically terminate.
661///
662/// If the determination that the code is unreachable proves incorrect, the
663/// program immediately terminates with a [`panic!`].
664///
665/// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
666/// will cause undefined behavior if the code is reached.
667///
668/// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked
669///
670/// # Panics
671///
672/// This will always [`panic!`] because `unreachable!` is just a shorthand for `panic!` with a
673/// fixed, specific message.
674///
675/// Like `panic!`, this macro has a second form for displaying custom values.
676///
677/// # Examples
678///
679/// Match arms:
680///
681/// ```
682/// # #[allow(dead_code)]
683/// fn foo(x: Option<i32>) {
684/// match x {
685/// Some(n) if n >= 0 => println!("Some(Non-negative)"),
686/// Some(n) if n < 0 => println!("Some(Negative)"),
687/// Some(_) => unreachable!(), // compile error if commented out
688/// None => println!("None")
689/// }
690/// }
691/// ```
692///
693/// Iterators:
694///
695/// ```
696/// # #[allow(dead_code)]
697/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
698/// for i in 0.. {
699/// if 3*i < i { panic!("u32 overflow"); }
700/// if x < 3*i { return i-1; }
701/// }
702/// unreachable!("The loop should always return");
703/// }
704/// ```
705#[macro_export]
706#[rustc_builtin_macro(unreachable)]
707#[allow_internal_unstable(edition_panic)]
708#[stable(feature = "rust1", since = "1.0.0")]
709#[rustc_diagnostic_item = "unreachable_macro"]
710macro_rules! unreachable {
711 // Expands to either `$crate::panic::unreachable_2015` or `$crate::panic::unreachable_2021`
712 // depending on the edition of the caller.
713 ($($arg:tt)*) => {
714 /* compiler built-in */
715 };
716}
717
718/// Indicates unimplemented code by panicking with a message of "not implemented".
719///
720/// This allows your code to type-check, which is useful if you are prototyping or
721/// implementing a trait that requires multiple methods which you don't plan to use all of.
722///
723/// The difference between `unimplemented!` and [`todo!`] is that while `todo!`
724/// conveys an intent of implementing the functionality later and the message is "not yet
725/// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
726///
727/// Also, some IDEs will mark `todo!`s.
728///
729/// # Panics
730///
731/// This will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a
732/// fixed, specific message.
733///
734/// Like `panic!`, this macro has a second form for displaying custom values.
735///
736/// [`todo!`]: crate::todo
737///
738/// # Examples
739///
740/// Say we have a trait `Foo`:
741///
742/// ```
743/// trait Foo {
744/// fn bar(&self) -> u8;
745/// fn baz(&self);
746/// fn qux(&self) -> Result<u64, ()>;
747/// }
748/// ```
749///
750/// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
751/// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
752/// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
753/// to allow our code to compile.
754///
755/// We still want to have our program stop running if the unimplemented methods are
756/// reached.
757///
758/// ```
759/// # trait Foo {
760/// # fn bar(&self) -> u8;
761/// # fn baz(&self);
762/// # fn qux(&self) -> Result<u64, ()>;
763/// # }
764/// struct MyStruct;
765///
766/// impl Foo for MyStruct {
767/// fn bar(&self) -> u8 {
768/// 1 + 1
769/// }
770///
771/// fn baz(&self) {
772/// // It makes no sense to `baz` a `MyStruct`, so we have no logic here
773/// // at all.
774/// // This will display "thread 'main' panicked at 'not implemented'".
775/// unimplemented!();
776/// }
777///
778/// fn qux(&self) -> Result<u64, ()> {
779/// // We have some logic here,
780/// // We can add a message to unimplemented! to display our omission.
781/// // This will display:
782/// // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
783/// unimplemented!("MyStruct isn't quxable");
784/// }
785/// }
786///
787/// fn main() {
788/// let s = MyStruct;
789/// s.bar();
790/// }
791/// ```
792#[macro_export]
793#[stable(feature = "rust1", since = "1.0.0")]
794#[rustc_diagnostic_item = "unimplemented_macro"]
795#[allow_internal_unstable(panic_internals)]
796macro_rules! unimplemented {
797 () => {
798 $crate::panicking::panic("not implemented")
799 };
800 ($($arg:tt)+) => {
801 $crate::panic!("not implemented: {}", $crate::format_args!($($arg)+))
802 };
803}
804
805/// Indicates unfinished code.
806///
807/// This can be useful if you are prototyping and just
808/// want a placeholder to let your code pass type analysis.
809///
810/// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
811/// an intent of implementing the functionality later and the message is "not yet
812/// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
813///
814/// Also, some IDEs will mark `todo!`s.
815///
816/// # Panics
817///
818/// This will always [`panic!`] because `todo!` is just a shorthand for `panic!` with a
819/// fixed, specific message.
820///
821/// Like `panic!`, this macro has a second form for displaying custom values.
822///
823/// # Examples
824///
825/// Here's an example of some in-progress code. We have a trait `Foo`:
826///
827/// ```
828/// trait Foo {
829/// fn bar(&self) -> u8;
830/// fn baz(&self);
831/// fn qux(&self) -> Result<u64, ()>;
832/// }
833/// ```
834///
835/// We want to implement `Foo` on one of our types, but we also want to work on
836/// just `bar()` first. In order for our code to compile, we need to implement
837/// `baz()` and `qux()`, so we can use `todo!`:
838///
839/// ```
840/// # trait Foo {
841/// # fn bar(&self) -> u8;
842/// # fn baz(&self);
843/// # fn qux(&self) -> Result<u64, ()>;
844/// # }
845/// struct MyStruct;
846///
847/// impl Foo for MyStruct {
848/// fn bar(&self) -> u8 {
849/// 1 + 1
850/// }
851///
852/// fn baz(&self) {
853/// // Let's not worry about implementing baz() for now
854/// todo!();
855/// }
856///
857/// fn qux(&self) -> Result<u64, ()> {
858/// // We can add a message to todo! to display our omission.
859/// // This will display:
860/// // "thread 'main' panicked at 'not yet implemented: MyStruct is not yet quxable'".
861/// todo!("MyStruct is not yet quxable");
862/// }
863/// }
864///
865/// fn main() {
866/// let s = MyStruct;
867/// s.bar();
868///
869/// // We aren't even using baz() or qux(), so this is fine.
870/// }
871/// ```
872#[macro_export]
873#[stable(feature = "todo_macro", since = "1.40.0")]
874#[rustc_diagnostic_item = "todo_macro"]
875#[allow_internal_unstable(panic_internals)]
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}