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