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