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