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