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