1 #[doc(include = "panic.md")]
3 #[allow_internal_unstable(core_panic, const_caller_location)]
4 #[stable(feature = "core", since = "1.6.0")]
7 $crate::panic!("explicit panic")
10 $crate::panicking::panic($msg)
13 $crate::panic!("{}", $crate::convert::identity::<&str>($msg))
18 ($fmt:expr, $($arg:tt)+) => (
19 $crate::panicking::panic_fmt($crate::format_args!($fmt, $($arg)+))
23 /// Asserts that two expressions are equal to each other (using [`PartialEq`]).
25 /// On panic, this macro will print the values of the expressions with their
26 /// debug representations.
28 /// Like [`assert!`], this macro has a second form, where a custom
29 /// panic message can be provided.
38 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
41 #[stable(feature = "rust1", since = "1.0.0")]
42 macro_rules! assert_eq {
43 ($left:expr, $right:expr) => ({
44 match (&$left, &$right) {
45 (left_val, right_val) => {
46 if !(*left_val == *right_val) {
47 // The reborrows below are intentional. Without them, the stack slot for the
48 // borrow is initialized even before the values are compared, leading to a
49 // noticeable slow down.
50 panic!(r#"assertion failed: `(left == right)`
52 right: `{:?}`"#, &*left_val, &*right_val)
57 ($left:expr, $right:expr,) => ({
58 $crate::assert_eq!($left, $right)
60 ($left:expr, $right:expr, $($arg:tt)+) => ({
61 match (&($left), &($right)) {
62 (left_val, right_val) => {
63 if !(*left_val == *right_val) {
64 // The reborrows below are intentional. Without them, the stack slot for the
65 // borrow is initialized even before the values are compared, leading to a
66 // noticeable slow down.
67 panic!(r#"assertion failed: `(left == right)`
69 right: `{:?}`: {}"#, &*left_val, &*right_val,
70 $crate::format_args!($($arg)+))
77 /// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
79 /// On panic, this macro will print the values of the expressions with their
80 /// debug representations.
82 /// Like [`assert!`], this macro has a second form, where a custom
83 /// panic message can be provided.
92 /// assert_ne!(a, b, "we are testing that the values are not equal");
95 #[stable(feature = "assert_ne", since = "1.13.0")]
96 macro_rules! assert_ne {
97 ($left:expr, $right:expr) => ({
98 match (&$left, &$right) {
99 (left_val, right_val) => {
100 if *left_val == *right_val {
101 // The reborrows below are intentional. Without them, the stack slot for the
102 // borrow is initialized even before the values are compared, leading to a
103 // noticeable slow down.
104 panic!(r#"assertion failed: `(left != right)`
106 right: `{:?}`"#, &*left_val, &*right_val)
111 ($left:expr, $right:expr,) => {
112 $crate::assert_ne!($left, $right)
114 ($left:expr, $right:expr, $($arg:tt)+) => ({
115 match (&($left), &($right)) {
116 (left_val, right_val) => {
117 if *left_val == *right_val {
118 // The reborrows below are intentional. Without them, the stack slot for the
119 // borrow is initialized even before the values are compared, leading to a
120 // noticeable slow down.
121 panic!(r#"assertion failed: `(left != right)`
123 right: `{:?}`: {}"#, &*left_val, &*right_val,
124 $crate::format_args!($($arg)+))
131 /// Asserts that a boolean expression is `true` at runtime.
133 /// This will invoke the [`panic!`] macro if the provided expression cannot be
134 /// evaluated to `true` at runtime.
136 /// Like [`assert!`], this macro also has a second version, where a custom panic
137 /// message can be provided.
141 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
142 /// optimized builds by default. An optimized build will not execute
143 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
144 /// compiler. This makes `debug_assert!` useful for checks that are too
145 /// expensive to be present in a release build but may be helpful during
146 /// development. The result of expanding `debug_assert!` is always type checked.
148 /// An unchecked assertion allows a program in an inconsistent state to keep
149 /// running, which might have unexpected consequences but does not introduce
150 /// unsafety as long as this only happens in safe code. The performance cost
151 /// of assertions, however, is not measurable in general. Replacing [`assert!`]
152 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
153 /// more importantly, only in safe code!
158 /// // the panic message for these assertions is the stringified value of the
159 /// // expression given.
160 /// debug_assert!(true);
162 /// fn some_expensive_computation() -> bool { true } // a very simple function
163 /// debug_assert!(some_expensive_computation());
165 /// // assert with a custom message
167 /// debug_assert!(x, "x wasn't true!");
169 /// let a = 3; let b = 27;
170 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
173 #[stable(feature = "rust1", since = "1.0.0")]
174 macro_rules! debug_assert {
175 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert!($($arg)*); })
178 /// Asserts that two expressions are equal to each other.
180 /// On panic, this macro will print the values of the expressions with their
181 /// debug representations.
183 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
184 /// optimized builds by default. An optimized build will not execute
185 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
186 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
187 /// expensive to be present in a release build but may be helpful during
188 /// development. The result of expanding `debug_assert_eq!` is always type checked.
195 /// debug_assert_eq!(a, b);
198 #[stable(feature = "rust1", since = "1.0.0")]
199 macro_rules! debug_assert_eq {
200 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_eq!($($arg)*); })
203 /// Asserts that two expressions are not equal to each other.
205 /// On panic, this macro will print the values of the expressions with their
206 /// debug representations.
208 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
209 /// optimized builds by default. An optimized build will not execute
210 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
211 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
212 /// expensive to be present in a release build but may be helpful during
213 /// development. The result of expanding `debug_assert_ne!` is always type checked.
220 /// debug_assert_ne!(a, b);
223 #[stable(feature = "assert_ne", since = "1.13.0")]
224 macro_rules! debug_assert_ne {
225 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_ne!($($arg)*); })
228 /// Returns whether the given expression matches any of the given patterns.
230 /// Like in a `match` expression, the pattern can be optionally followed by `if`
231 /// and a guard expression that has access to names bound by the pattern.
237 /// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
239 /// let bar = Some(4);
240 /// assert!(matches!(bar, Some(x) if x > 2));
243 #[stable(feature = "matches_macro", since = "1.42.0")]
244 macro_rules! matches {
245 ($expression:expr, $( $pattern:pat )|+ $( if $guard: expr )?) => {
247 $( $pattern )|+ $( if $guard )? => true,
253 /// Unwraps a result or propagates its error.
255 /// The `?` operator was added to replace `try!` and should be used instead.
256 /// Furthermore, `try` is a reserved word in Rust 2018, so if you must use
257 /// it, you will need to use the [raw-identifier syntax][ris]: `r#try`.
259 /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
261 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
262 /// expression has the value of the wrapped value.
264 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
265 /// performs conversion using `From`. This provides automatic conversion
266 /// between specialized errors and more general ones. The resulting
267 /// error is then immediately returned.
269 /// Because of the early return, `try!` can only be used in functions that
270 /// return [`Result`].
276 /// use std::fs::File;
277 /// use std::io::prelude::*;
283 /// impl From<io::Error> for MyError {
284 /// fn from(e: io::Error) -> MyError {
285 /// MyError::FileWriteError
289 /// // The preferred method of quick returning Errors
290 /// fn write_to_file_question() -> Result<(), MyError> {
291 /// let mut file = File::create("my_best_friends.txt")?;
292 /// file.write_all(b"This is a list of my best friends.")?;
296 /// // The previous method of quick returning Errors
297 /// fn write_to_file_using_try() -> Result<(), MyError> {
298 /// let mut file = r#try!(File::create("my_best_friends.txt"));
299 /// r#try!(file.write_all(b"This is a list of my best friends."));
303 /// // This is equivalent to:
304 /// fn write_to_file_using_match() -> Result<(), MyError> {
305 /// let mut file = r#try!(File::create("my_best_friends.txt"));
306 /// match file.write_all(b"This is a list of my best friends.") {
308 /// Err(e) => return Err(From::from(e)),
314 #[stable(feature = "rust1", since = "1.0.0")]
315 #[rustc_deprecated(since = "1.39.0", reason = "use the `?` operator instead")]
320 $crate::result::Result::Ok(val) => val,
321 $crate::result::Result::Err(err) => {
322 return $crate::result::Result::Err($crate::convert::From::from(err));
327 $crate::r#try!($expr)
331 /// Writes formatted data into a buffer.
333 /// This macro accepts a format string, a list of arguments, and a 'writer'. Arguments will be
334 /// formatted according to the specified format string and the result will be passed to the writer.
335 /// The writer may be any value with a `write_fmt` method; generally this comes from an
336 /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro
337 /// returns whatever the `write_fmt` method returns; commonly a [`std::fmt::Result`], or an
340 /// See [`std::fmt`] for more information on the format string syntax.
342 /// [`std::fmt`]: crate::fmt
343 /// [`std::fmt::Write`]: crate::fmt::Write
344 /// [`std::io::Write`]: ../std/io/trait.Write.html
345 /// [`std::fmt::Result`]: crate::fmt::Result
346 /// [`io::Result`]: ../std/io/type.Result.html
351 /// use std::io::Write;
353 /// fn main() -> std::io::Result<()> {
354 /// let mut w = Vec::new();
355 /// write!(&mut w, "test")?;
356 /// write!(&mut w, "formatted {}", "arguments")?;
358 /// assert_eq!(w, b"testformatted arguments");
363 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
364 /// implementing either, as objects do not typically implement both. However, the module must
365 /// import the traits qualified so their names do not conflict:
368 /// use std::fmt::Write as FmtWrite;
369 /// use std::io::Write as IoWrite;
371 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
372 /// let mut s = String::new();
373 /// let mut v = Vec::new();
375 /// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
376 /// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
377 /// assert_eq!(v, b"s = \"abc 123\"");
382 /// Note: This macro can be used in `no_std` setups as well.
383 /// In a `no_std` setup you are responsible for the implementation details of the components.
386 /// # extern crate core;
387 /// use core::fmt::Write;
391 /// impl Write for Example {
392 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
393 /// unimplemented!();
397 /// let mut m = Example{};
398 /// write!(&mut m, "Hello World").expect("Not written");
401 #[stable(feature = "rust1", since = "1.0.0")]
403 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt($crate::format_args!($($arg)*)))
406 /// Write formatted data into a buffer, with a newline appended.
408 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
409 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
411 /// For more information, see [`write!`]. For information on the format string syntax, see
414 /// [`std::fmt`]: crate::fmt
419 /// use std::io::{Write, Result};
421 /// fn main() -> Result<()> {
422 /// let mut w = Vec::new();
423 /// writeln!(&mut w)?;
424 /// writeln!(&mut w, "test")?;
425 /// writeln!(&mut w, "formatted {}", "arguments")?;
427 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
432 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
433 /// implementing either, as objects do not typically implement both. However, the module must
434 /// import the traits qualified so their names do not conflict:
437 /// use std::fmt::Write as FmtWrite;
438 /// use std::io::Write as IoWrite;
440 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
441 /// let mut s = String::new();
442 /// let mut v = Vec::new();
444 /// writeln!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
445 /// writeln!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
446 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
451 #[stable(feature = "rust1", since = "1.0.0")]
452 #[allow_internal_unstable(format_args_nl)]
453 macro_rules! writeln {
455 $crate::write!($dst, "\n")
458 $crate::writeln!($dst)
460 ($dst:expr, $($arg:tt)*) => (
461 $dst.write_fmt($crate::format_args_nl!($($arg)*))
465 /// Indicates unreachable code.
467 /// This is useful any time that the compiler can't determine that some code is unreachable. For
470 /// * Match arms with guard conditions.
471 /// * Loops that dynamically terminate.
472 /// * Iterators that dynamically terminate.
474 /// If the determination that the code is unreachable proves incorrect, the
475 /// program immediately terminates with a [`panic!`].
477 /// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
478 /// will cause undefined behavior if the code is reached.
480 /// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked
484 /// This will always [`panic!`]
491 /// # #[allow(dead_code)]
492 /// fn foo(x: Option<i32>) {
494 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
495 /// Some(n) if n < 0 => println!("Some(Negative)"),
496 /// Some(_) => unreachable!(), // compile error if commented out
497 /// None => println!("None")
505 /// # #[allow(dead_code)]
506 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
508 /// if 3*i < i { panic!("u32 overflow"); }
509 /// if x < 3*i { return i-1; }
515 #[stable(feature = "rust1", since = "1.0.0")]
516 macro_rules! unreachable {
518 panic!("internal error: entered unreachable code")
521 $crate::unreachable!("{}", $msg)
524 $crate::unreachable!($msg)
526 ($fmt:expr, $($arg:tt)*) => ({
527 panic!($crate::concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
531 /// Indicates unimplemented code by panicking with a message of "not implemented".
533 /// This allows your code to type-check, which is useful if you are prototyping or
534 /// implementing a trait that requires multiple methods which you don't plan of using all of.
536 /// The difference between `unimplemented!` and [`todo!`](macro.todo.html) is that while `todo!`
537 /// conveys an intent of implementing the functionality later and the message is "not yet
538 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
539 /// Also some IDEs will mark `todo!`s.
543 /// This will always [panic!](macro.panic.html) because `unimplemented!` is just a
544 /// shorthand for `panic!` with a fixed, specific message.
546 /// Like `panic!`, this macro has a second form for displaying custom values.
550 /// Say we have a trait `Foo`:
554 /// fn bar(&self) -> u8;
556 /// fn qux(&self) -> Result<u64, ()>;
560 /// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
561 /// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
562 /// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
563 /// to allow our code to compile.
565 /// We still want to have our program stop running if the unimplemented methods are
570 /// # fn bar(&self) -> u8;
572 /// # fn qux(&self) -> Result<u64, ()>;
576 /// impl Foo for MyStruct {
577 /// fn bar(&self) -> u8 {
582 /// // It makes no sense to `baz` a `MyStruct`, so we have no logic here
584 /// // This will display "thread 'main' panicked at 'not implemented'".
585 /// unimplemented!();
588 /// fn qux(&self) -> Result<u64, ()> {
589 /// // We have some logic here,
590 /// // We can add a message to unimplemented! to display our omission.
591 /// // This will display:
592 /// // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
593 /// unimplemented!("MyStruct isn't quxable");
598 /// let s = MyStruct;
603 #[stable(feature = "rust1", since = "1.0.0")]
604 macro_rules! unimplemented {
605 () => (panic!("not implemented"));
606 ($($arg:tt)+) => (panic!("not implemented: {}", $crate::format_args!($($arg)+)));
609 /// Indicates unfinished code.
611 /// This can be useful if you are prototyping and are just looking to have your
614 /// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
615 /// an intent of implementing the functionality later and the message is "not yet
616 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
617 /// Also some IDEs will mark `todo!`s.
621 /// This will always [panic!](macro.panic.html)
625 /// Here's an example of some in-progress code. We have a trait `Foo`:
634 /// We want to implement `Foo` on one of our types, but we also want to work on
635 /// just `bar()` first. In order for our code to compile, we need to implement
636 /// `baz()`, so we can use `todo!`:
645 /// impl Foo for MyStruct {
647 /// // implementation goes here
651 /// // let's not worry about implementing baz() for now
657 /// let s = MyStruct;
660 /// // we aren't even using baz(), so this is fine.
664 #[stable(feature = "todo_macro", since = "1.40.0")]
666 () => (panic!("not yet implemented"));
667 ($($arg:tt)+) => (panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
670 /// Definitions of built-in macros.
672 /// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
673 /// with exception of expansion functions transforming macro inputs into outputs,
674 /// those functions are provided by the compiler.
675 pub(crate) mod builtin {
677 /// Causes compilation to fail with the given error message when encountered.
679 /// This macro should be used when a crate uses a conditional compilation strategy to provide
680 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
681 /// but emits an error during *compilation* rather than at *runtime*.
685 /// Two such examples are macros and `#[cfg]` environments.
687 /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
688 /// the compiler would still emit an error, but the error's message would not mention the two
692 /// macro_rules! give_me_foo_or_bar {
696 /// compile_error!("This macro only accepts `foo` or `bar`");
700 /// give_me_foo_or_bar!(neither);
701 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
704 /// Emit compiler error if one of a number of features isn't available.
707 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
708 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
710 #[stable(feature = "compile_error_macro", since = "1.20.0")]
711 #[rustc_builtin_macro]
713 macro_rules! compile_error {
714 ($msg:expr) => {{ /* compiler built-in */ }};
715 ($msg:expr,) => {{ /* compiler built-in */ }};
718 /// Constructs parameters for the other string-formatting macros.
720 /// This macro functions by taking a formatting string literal containing
721 /// `{}` for each additional argument passed. `format_args!` prepares the
722 /// additional parameters to ensure the output can be interpreted as a string
723 /// and canonicalizes the arguments into a single type. Any value that implements
724 /// the [`Display`] trait can be passed to `format_args!`, as can any
725 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
727 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
728 /// passed to the macros within [`std::fmt`] for performing useful redirection.
729 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
730 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
731 /// heap allocations.
733 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
734 /// in `Debug` and `Display` contexts as seen below. The example also shows
735 /// that `Debug` and `Display` format to the same thing: the interpolated
736 /// format string in `format_args!`.
739 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
740 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
741 /// assert_eq!("1 foo 2", display);
742 /// assert_eq!(display, debug);
745 /// For more information, see the documentation in [`std::fmt`].
747 /// [`Display`]: crate::fmt::Display
748 /// [`Debug`]: crate::fmt::Debug
749 /// [`fmt::Arguments`]: crate::fmt::Arguments
750 /// [`std::fmt`]: crate::fmt
751 /// [`format!`]: ../std/macro.format.html
752 /// [`println!`]: ../std/macro.println.html
759 /// let s = fmt::format(format_args!("hello {}", "world"));
760 /// assert_eq!(s, format!("hello {}", "world"));
762 #[stable(feature = "rust1", since = "1.0.0")]
763 #[allow_internal_unstable(fmt_internals)]
764 #[rustc_builtin_macro]
766 macro_rules! format_args {
767 ($fmt:expr) => {{ /* compiler built-in */ }};
768 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
771 /// Same as `format_args`, but adds a newline in the end.
773 feature = "format_args_nl",
775 reason = "`format_args_nl` is only for internal \
776 language use and is subject to change"
778 #[allow_internal_unstable(fmt_internals)]
779 #[rustc_builtin_macro]
781 macro_rules! format_args_nl {
782 ($fmt:expr) => {{ /* compiler built-in */ }};
783 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
786 /// Inspects an environment variable at compile time.
788 /// This macro will expand to the value of the named environment variable at
789 /// compile time, yielding an expression of type `&'static str`.
791 /// If the environment variable is not defined, then a compilation error
792 /// will be emitted. To not emit a compile error, use the [`option_env!`]
798 /// let path: &'static str = env!("PATH");
799 /// println!("the $PATH variable at the time of compiling was: {}", path);
802 /// You can customize the error message by passing a string as the second
806 /// let doc: &'static str = env!("documentation", "what's that?!");
809 /// If the `documentation` environment variable is not defined, you'll get
810 /// the following error:
813 /// error: what's that?!
815 #[stable(feature = "rust1", since = "1.0.0")]
816 #[rustc_builtin_macro]
819 ($name:expr) => {{ /* compiler built-in */ }};
820 ($name:expr,) => {{ /* compiler built-in */ }};
823 /// Optionally inspects an environment variable at compile time.
825 /// If the named environment variable is present at compile time, this will
826 /// expand into an expression of type `Option<&'static str>` whose value is
827 /// `Some` of the value of the environment variable. If the environment
828 /// variable is not present, then this will expand to `None`. See
829 /// [`Option<T>`][Option] for more information on this type.
831 /// A compile time error is never emitted when using this macro regardless
832 /// of whether the environment variable is present or not.
837 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
838 /// println!("the secret key might be: {:?}", key);
840 #[stable(feature = "rust1", since = "1.0.0")]
841 #[rustc_builtin_macro]
843 macro_rules! option_env {
844 ($name:expr) => {{ /* compiler built-in */ }};
845 ($name:expr,) => {{ /* compiler built-in */ }};
848 /// Concatenates identifiers into one identifier.
850 /// This macro takes any number of comma-separated identifiers, and
851 /// concatenates them all into one, yielding an expression which is a new
852 /// identifier. Note that hygiene makes it such that this macro cannot
853 /// capture local variables. Also, as a general rule, macros are only
854 /// allowed in item, statement or expression position. That means while
855 /// you may use this macro for referring to existing variables, functions or
856 /// modules etc, you cannot define a new one with it.
861 /// #![feature(concat_idents)]
864 /// fn foobar() -> u32 { 23 }
866 /// let f = concat_idents!(foo, bar);
867 /// println!("{}", f());
869 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
873 feature = "concat_idents",
875 reason = "`concat_idents` is not stable enough for use and is subject to change"
877 #[rustc_builtin_macro]
879 macro_rules! concat_idents {
880 ($($e:ident),+) => {{ /* compiler built-in */ }};
881 ($($e:ident,)+) => {{ /* compiler built-in */ }};
884 /// Concatenates literals into a static string slice.
886 /// This macro takes any number of comma-separated literals, yielding an
887 /// expression of type `&'static str` which represents all of the literals
888 /// concatenated left-to-right.
890 /// Integer and floating point literals are stringified in order to be
896 /// let s = concat!("test", 10, 'b', true);
897 /// assert_eq!(s, "test10btrue");
899 #[stable(feature = "rust1", since = "1.0.0")]
900 #[rustc_builtin_macro]
902 macro_rules! concat {
903 ($($e:expr),*) => {{ /* compiler built-in */ }};
904 ($($e:expr,)*) => {{ /* compiler built-in */ }};
907 /// Expands to the line number on which it was invoked.
909 /// With [`column!`] and [`file!`], these macros provide debugging information for
910 /// developers about the location within the source.
912 /// The expanded expression has type `u32` and is 1-based, so the first line
913 /// in each file evaluates to 1, the second to 2, etc. This is consistent
914 /// with error messages by common compilers or popular editors.
915 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
916 /// but rather the first macro invocation leading up to the invocation
917 /// of the `line!` macro.
922 /// let current_line = line!();
923 /// println!("defined on line: {}", current_line);
925 #[stable(feature = "rust1", since = "1.0.0")]
926 #[rustc_builtin_macro]
930 /* compiler built-in */
934 /// Expands to the column number at which it was invoked.
936 /// With [`line!`] and [`file!`], these macros provide debugging information for
937 /// developers about the location within the source.
939 /// The expanded expression has type `u32` and is 1-based, so the first column
940 /// in each line evaluates to 1, the second to 2, etc. This is consistent
941 /// with error messages by common compilers or popular editors.
942 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
943 /// but rather the first macro invocation leading up to the invocation
944 /// of the `column!` macro.
949 /// let current_col = column!();
950 /// println!("defined on column: {}", current_col);
952 #[stable(feature = "rust1", since = "1.0.0")]
953 #[rustc_builtin_macro]
955 macro_rules! column {
957 /* compiler built-in */
961 /// Expands to the file name in which it was invoked.
963 /// With [`line!`] and [`column!`], these macros provide debugging information for
964 /// developers about the location within the source.
966 /// The expanded expression has type `&'static str`, and the returned file
967 /// is not the invocation of the `file!` macro itself, but rather the
968 /// first macro invocation leading up to the invocation of the `file!`
974 /// let this_file = file!();
975 /// println!("defined in file: {}", this_file);
977 #[stable(feature = "rust1", since = "1.0.0")]
978 #[rustc_builtin_macro]
982 /* compiler built-in */
986 /// Stringifies its arguments.
988 /// This macro will yield an expression of type `&'static str` which is the
989 /// stringification of all the tokens passed to the macro. No restrictions
990 /// are placed on the syntax of the macro invocation itself.
992 /// Note that the expanded results of the input tokens may change in the
993 /// future. You should be careful if you rely on the output.
998 /// let one_plus_one = stringify!(1 + 1);
999 /// assert_eq!(one_plus_one, "1 + 1");
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 #[rustc_builtin_macro]
1004 macro_rules! stringify {
1006 /* compiler built-in */
1010 /// Includes a UTF-8 encoded file as a string.
1012 /// The file is located relative to the current file (similarly to how
1013 /// modules are found). The provided path is interpreted in a platform-specific
1014 /// way at compile time. So, for instance, an invocation with a Windows path
1015 /// containing backslashes `\` would not compile correctly on Unix.
1017 /// This macro will yield an expression of type `&'static str` which is the
1018 /// contents of the file.
1022 /// Assume there are two files in the same directory with the following
1025 /// File 'spanish.in':
1033 /// ```ignore (cannot-doctest-external-file-dependency)
1035 /// let my_str = include_str!("spanish.in");
1036 /// assert_eq!(my_str, "adiós\n");
1037 /// print!("{}", my_str);
1041 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 #[rustc_builtin_macro]
1045 macro_rules! include_str {
1046 ($file:expr) => {{ /* compiler built-in */ }};
1047 ($file:expr,) => {{ /* compiler built-in */ }};
1050 /// Includes a file as a reference to a byte array.
1052 /// The file is located relative to the current file (similarly to how
1053 /// modules are found). The provided path is interpreted in a platform-specific
1054 /// way at compile time. So, for instance, an invocation with a Windows path
1055 /// containing backslashes `\` would not compile correctly on Unix.
1057 /// This macro will yield an expression of type `&'static [u8; N]` which is
1058 /// the contents of the file.
1062 /// Assume there are two files in the same directory with the following
1065 /// File 'spanish.in':
1073 /// ```ignore (cannot-doctest-external-file-dependency)
1075 /// let bytes = include_bytes!("spanish.in");
1076 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
1077 /// print!("{}", String::from_utf8_lossy(bytes));
1081 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 #[rustc_builtin_macro]
1085 macro_rules! include_bytes {
1086 ($file:expr) => {{ /* compiler built-in */ }};
1087 ($file:expr,) => {{ /* compiler built-in */ }};
1090 /// Expands to a string that represents the current module path.
1092 /// The current module path can be thought of as the hierarchy of modules
1093 /// leading back up to the crate root. The first component of the path
1094 /// returned is the name of the crate currently being compiled.
1101 /// assert!(module_path!().ends_with("test"));
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 #[rustc_builtin_macro]
1110 macro_rules! module_path {
1112 /* compiler built-in */
1116 /// Evaluates boolean combinations of configuration flags at compile-time.
1118 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1119 /// boolean expression evaluation of configuration flags. This frequently
1120 /// leads to less duplicated code.
1122 /// The syntax given to this macro is the same syntax as the [`cfg`]
1125 /// `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For
1126 /// example, all blocks in an if/else expression need to be valid when `cfg!` is used for
1127 /// the condition, regardless of what `cfg!` is evaluating.
1129 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1134 /// let my_directory = if cfg!(windows) {
1135 /// "windows-specific-directory"
1137 /// "unix-directory"
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 #[rustc_builtin_macro]
1145 /* compiler built-in */
1149 /// Parses a file as an expression or an item according to the context.
1151 /// The file is located relative to the current file (similarly to how
1152 /// modules are found). The provided path is interpreted in a platform-specific
1153 /// way at compile time. So, for instance, an invocation with a Windows path
1154 /// containing backslashes `\` would not compile correctly on Unix.
1156 /// Using this macro is often a bad idea, because if the file is
1157 /// parsed as an expression, it is going to be placed in the
1158 /// surrounding code unhygienically. This could result in variables
1159 /// or functions being different from what the file expected if
1160 /// there are variables or functions that have the same name in
1161 /// the current file.
1165 /// Assume there are two files in the same directory with the following
1168 /// File 'monkeys.in':
1170 /// ```ignore (only-for-syntax-highlight)
1171 /// ['🙈', '🙊', '🙉']
1175 /// .collect::<String>()
1180 /// ```ignore (cannot-doctest-external-file-dependency)
1182 /// let my_string = include!("monkeys.in");
1183 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1184 /// println!("{}", my_string);
1188 /// Compiling 'main.rs' and running the resulting binary will print
1189 /// "🙈🙊🙉🙈🙊🙉".
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 #[rustc_builtin_macro]
1193 macro_rules! include {
1194 ($file:expr) => {{ /* compiler built-in */ }};
1195 ($file:expr,) => {{ /* compiler built-in */ }};
1198 /// Asserts that a boolean expression is `true` at runtime.
1200 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1201 /// evaluated to `true` at runtime.
1205 /// Assertions are always checked in both debug and release builds, and cannot
1206 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1207 /// release builds by default.
1209 /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if
1210 /// violated could lead to unsafety.
1212 /// Other use-cases of `assert!` include testing and enforcing run-time
1213 /// invariants in safe code (whose violation cannot result in unsafety).
1215 /// # Custom Messages
1217 /// This macro has a second form, where a custom panic message can
1218 /// be provided with or without arguments for formatting. See [`std::fmt`]
1219 /// for syntax for this form.
1221 /// [`std::fmt`]: crate::fmt
1226 /// // the panic message for these assertions is the stringified value of the
1227 /// // expression given.
1230 /// fn some_computation() -> bool { true } // a very simple function
1232 /// assert!(some_computation());
1234 /// // assert with a custom message
1236 /// assert!(x, "x wasn't true!");
1238 /// let a = 3; let b = 27;
1239 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 #[rustc_builtin_macro]
1244 macro_rules! assert {
1245 ($cond:expr) => {{ /* compiler built-in */ }};
1246 ($cond:expr,) => {{ /* compiler built-in */ }};
1247 ($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }};
1250 /// Inline assembly.
1252 /// Read the [unstable book] for the usage.
1254 /// [unstable book]: ../unstable-book/library-features/asm.html
1258 reason = "inline assembly is not stable enough for use and is subject to change"
1260 #[rustc_builtin_macro]
1263 ("assembly template",
1265 $(options($(option),*))?
1267 /* compiler built-in */
1271 /// LLVM-style inline assembly.
1273 /// Read the [unstable book] for the usage.
1275 /// [unstable book]: ../unstable-book/library-features/llvm-asm.html
1277 feature = "llvm_asm",
1279 reason = "prefer using the new asm! syntax instead"
1281 #[rustc_builtin_macro]
1283 macro_rules! llvm_asm {
1284 ("assembly template"
1285 : $("output"(operand),)*
1286 : $("input"(operand),)*
1288 : $("options",)*) => {
1289 /* compiler built-in */
1293 /// Module-level inline assembly.
1295 feature = "global_asm",
1297 reason = "`global_asm!` is not stable enough for use and is subject to change"
1299 #[rustc_builtin_macro]
1301 macro_rules! global_asm {
1303 /* compiler built-in */
1307 /// Prints passed tokens into the standard output.
1309 feature = "log_syntax",
1311 reason = "`log_syntax!` is not stable enough for use and is subject to change"
1313 #[rustc_builtin_macro]
1315 macro_rules! log_syntax {
1317 /* compiler built-in */
1321 /// Enables or disables tracing functionality used for debugging other macros.
1323 feature = "trace_macros",
1325 reason = "`trace_macros` is not stable enough for use and is subject to change"
1327 #[rustc_builtin_macro]
1329 macro_rules! trace_macros {
1330 (true) => {{ /* compiler built-in */ }};
1331 (false) => {{ /* compiler built-in */ }};
1334 /// Attribute macro applied to a function to turn it into a unit test.
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 #[allow_internal_unstable(test, rustc_attrs)]
1337 #[rustc_builtin_macro]
1338 pub macro test($item:item) {
1339 /* compiler built-in */
1342 /// Attribute macro applied to a function to turn it into a benchmark test.
1347 reason = "`bench` is a part of custom test frameworks which are unstable"
1349 #[allow_internal_unstable(test, rustc_attrs)]
1350 #[rustc_builtin_macro]
1351 pub macro bench($item:item) {
1352 /* compiler built-in */
1355 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1357 feature = "custom_test_frameworks",
1359 reason = "custom test frameworks are an unstable feature"
1361 #[allow_internal_unstable(test, rustc_attrs)]
1362 #[rustc_builtin_macro]
1363 pub macro test_case($item:item) {
1364 /* compiler built-in */
1367 /// Attribute macro applied to a static to register it as a global allocator.
1368 #[stable(feature = "global_allocator", since = "1.28.0")]
1369 #[allow_internal_unstable(rustc_attrs)]
1370 #[rustc_builtin_macro]
1371 pub macro global_allocator($item:item) {
1372 /* compiler built-in */
1375 /// Keeps the item it's applied to if the passed path is accessible, and removes it otherwise.
1377 feature = "cfg_accessible",
1379 reason = "`cfg_accessible` is not fully implemented"
1381 #[rustc_builtin_macro]
1382 pub macro cfg_accessible($item:item) {
1383 /* compiler built-in */
1386 /// Unstable implementation detail of the `rustc` compiler, do not use.
1387 #[rustc_builtin_macro]
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 #[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
1390 pub macro RustcDecodable($item:item) {
1391 /* compiler built-in */
1394 /// Unstable implementation detail of the `rustc` compiler, do not use.
1395 #[rustc_builtin_macro]
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 #[allow_internal_unstable(core_intrinsics)]
1398 pub macro RustcEncodable($item:item) {
1399 /* compiler built-in */