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