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