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