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