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