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