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