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