1 /// Panics the current thread.
3 /// For details, see `std::macros`.
5 #[allow_internal_unstable(core_panic,
6 // FIXME(anp, eddyb) `core_intrinsics` is used here to allow calling
7 // the `caller_location` intrinsic, but once `#[track_caller]` is implemented,
8 // `panicking::{panic, panic_fmt}` can use that instead of a `Location` argument.
11 #[stable(feature = "core", since = "1.6.0")]
14 $crate::panic!("explicit panic")
17 $crate::panicking::panic($msg, $crate::intrinsics::caller_location())
22 ($fmt:expr, $($arg:tt)+) => (
23 $crate::panicking::panic_fmt(
24 $crate::format_args!($fmt, $($arg)+),
25 $crate::intrinsics::caller_location(),
30 /// Asserts that two expressions are equal to each other (using [`PartialEq`]).
32 /// On panic, this macro will print the values of the expressions with their
33 /// debug representations.
35 /// Like [`assert!`], this macro has a second form, where a custom
36 /// panic message can be provided.
38 /// [`PartialEq`]: cmp/trait.PartialEq.html
39 /// [`assert!`]: macro.assert.html
48 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
51 #[stable(feature = "rust1", since = "1.0.0")]
52 macro_rules! assert_eq {
53 ($left:expr, $right:expr) => ({
54 match (&$left, &$right) {
55 (left_val, right_val) => {
56 if !(*left_val == *right_val) {
57 // The reborrows below are intentional. Without them, the stack slot for the
58 // borrow is initialized even before the values are compared, leading to a
59 // noticeable slow down.
60 panic!(r#"assertion failed: `(left == right)`
62 right: `{:?}`"#, &*left_val, &*right_val)
67 ($left:expr, $right:expr,) => ({
68 $crate::assert_eq!($left, $right)
70 ($left:expr, $right:expr, $($arg:tt)+) => ({
71 match (&($left), &($right)) {
72 (left_val, right_val) => {
73 if !(*left_val == *right_val) {
74 // The reborrows below are intentional. Without them, the stack slot for the
75 // borrow is initialized even before the values are compared, leading to a
76 // noticeable slow down.
77 panic!(r#"assertion failed: `(left == right)`
79 right: `{:?}`: {}"#, &*left_val, &*right_val,
80 $crate::format_args!($($arg)+))
87 /// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
89 /// On panic, this macro will print the values of the expressions with their
90 /// debug representations.
92 /// Like [`assert!`], this macro has a second form, where a custom
93 /// panic message can be provided.
95 /// [`PartialEq`]: cmp/trait.PartialEq.html
96 /// [`assert!`]: macro.assert.html
103 /// assert_ne!(a, b);
105 /// assert_ne!(a, b, "we are testing that the values are not equal");
108 #[stable(feature = "assert_ne", since = "1.13.0")]
109 macro_rules! assert_ne {
110 ($left:expr, $right:expr) => ({
111 match (&$left, &$right) {
112 (left_val, right_val) => {
113 if *left_val == *right_val {
114 // The reborrows below are intentional. Without them, the stack slot for the
115 // borrow is initialized even before the values are compared, leading to a
116 // noticeable slow down.
117 panic!(r#"assertion failed: `(left != right)`
119 right: `{:?}`"#, &*left_val, &*right_val)
124 ($left:expr, $right:expr,) => {
125 $crate::assert_ne!($left, $right)
127 ($left:expr, $right:expr, $($arg:tt)+) => ({
128 match (&($left), &($right)) {
129 (left_val, right_val) => {
130 if *left_val == *right_val {
131 // The reborrows below are intentional. Without them, the stack slot for the
132 // borrow is initialized even before the values are compared, leading to a
133 // noticeable slow down.
134 panic!(r#"assertion failed: `(left != right)`
136 right: `{:?}`: {}"#, &*left_val, &*right_val,
137 $crate::format_args!($($arg)+))
144 /// Asserts that a boolean expression is `true` at runtime.
146 /// This will invoke the [`panic!`] macro if the provided expression cannot be
147 /// evaluated to `true` at runtime.
149 /// Like [`assert!`], this macro also has a second version, where a custom panic
150 /// message can be provided.
154 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
155 /// optimized builds by default. An optimized build will not execute
156 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
157 /// compiler. This makes `debug_assert!` useful for checks that are too
158 /// expensive to be present in a release build but may be helpful during
159 /// development. The result of expanding `debug_assert!` is always type checked.
161 /// An unchecked assertion allows a program in an inconsistent state to keep
162 /// running, which might have unexpected consequences but does not introduce
163 /// unsafety as long as this only happens in safe code. The performance cost
164 /// of assertions, is however, not measurable in general. Replacing [`assert!`]
165 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
166 /// more importantly, only in safe code!
168 /// [`panic!`]: macro.panic.html
169 /// [`assert!`]: macro.assert.html
174 /// // the panic message for these assertions is the stringified value of the
175 /// // expression given.
176 /// debug_assert!(true);
178 /// fn some_expensive_computation() -> bool { true } // a very simple function
179 /// debug_assert!(some_expensive_computation());
181 /// // assert with a custom message
183 /// debug_assert!(x, "x wasn't true!");
185 /// let a = 3; let b = 27;
186 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
189 #[stable(feature = "rust1", since = "1.0.0")]
190 macro_rules! debug_assert {
191 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert!($($arg)*); })
194 /// Asserts that two expressions are equal to each other.
196 /// On panic, this macro will print the values of the expressions with their
197 /// debug representations.
199 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
200 /// optimized builds by default. An optimized build will not execute
201 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
202 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
203 /// expensive to be present in a release build but may be helpful during
204 /// development. The result of expanding `debug_assert_eq!` is always type checked.
206 /// [`assert_eq!`]: ../std/macro.assert_eq.html
213 /// debug_assert_eq!(a, b);
216 #[stable(feature = "rust1", since = "1.0.0")]
217 macro_rules! debug_assert_eq {
218 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_eq!($($arg)*); })
221 /// Asserts that two expressions are not equal to each other.
223 /// On panic, this macro will print the values of the expressions with their
224 /// debug representations.
226 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
227 /// optimized builds by default. An optimized build will not execute
228 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
229 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
230 /// expensive to be present in a release build but may be helpful during
231 /// development. The result of expanding `debug_assert_ne!` is always type checked.
233 /// [`assert_ne!`]: ../std/macro.assert_ne.html
240 /// debug_assert_ne!(a, b);
243 #[stable(feature = "assert_ne", since = "1.13.0")]
244 macro_rules! debug_assert_ne {
245 ($($arg:tt)*) => (if $crate::cfg!(debug_assertions) { $crate::assert_ne!($($arg)*); })
248 /// Returns whether the given expression matches any of the given patterns.
250 /// Like in a `match` expression, the pattern can be optionally followed by `if`
251 /// and a guard expression that has access to names bound by the pattern.
256 /// #![feature(matches_macro)]
259 /// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
261 /// let bar = Some(4);
262 /// assert!(matches!(bar, Some(x) if x > 2));
265 #[unstable(feature = "matches_macro", issue = "65721")]
266 macro_rules! matches {
267 ($expression:expr, $( $pattern:pat )|+ $( if $guard: expr )?) => {
269 $( $pattern )|+ $( if $guard )? => true,
275 /// Unwraps a result or propagates its error.
277 /// The `?` operator was added to replace `try!` and should be used instead.
278 /// Furthermore, `try` is a reserved word in Rust 2018, so if you must use
279 /// it, you will need to use the [raw-identifier syntax][ris]: `r#try`.
281 /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
283 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
284 /// expression has the value of the wrapped value.
286 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
287 /// performs conversion using `From`. This provides automatic conversion
288 /// between specialized errors and more general ones. The resulting
289 /// error is then immediately returned.
291 /// Because of the early return, `try!` can only be used in functions that
292 /// return [`Result`].
294 /// [`Result`]: ../std/result/enum.Result.html
300 /// use std::fs::File;
301 /// use std::io::prelude::*;
307 /// impl From<io::Error> for MyError {
308 /// fn from(e: io::Error) -> MyError {
309 /// MyError::FileWriteError
313 /// // The preferred method of quick returning Errors
314 /// fn write_to_file_question() -> Result<(), MyError> {
315 /// let mut file = File::create("my_best_friends.txt")?;
316 /// file.write_all(b"This is a list of my best friends.")?;
320 /// // The previous method of quick returning Errors
321 /// fn write_to_file_using_try() -> Result<(), MyError> {
322 /// let mut file = r#try!(File::create("my_best_friends.txt"));
323 /// r#try!(file.write_all(b"This is a list of my best friends."));
327 /// // This is equivalent to:
328 /// fn write_to_file_using_match() -> Result<(), MyError> {
329 /// let mut file = r#try!(File::create("my_best_friends.txt"));
330 /// match file.write_all(b"This is a list of my best friends.") {
332 /// Err(e) => return Err(From::from(e)),
338 #[stable(feature = "rust1", since = "1.0.0")]
339 #[rustc_deprecated(since = "1.39.0", reason = "use the `?` operator instead")]
342 ($expr:expr) => (match $expr {
343 $crate::result::Result::Ok(val) => val,
344 $crate::result::Result::Err(err) => {
345 return $crate::result::Result::Err($crate::convert::From::from(err))
348 ($expr:expr,) => ($crate::r#try!($expr));
351 /// Writes formatted data into a buffer.
353 /// This macro accepts a format string, a list of arguments, and a 'writer'. Arguments will be
354 /// formatted according to the specified format string and the result will be passed to the writer.
355 /// The writer may be any value with a `write_fmt` method; generally this comes from an
356 /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro
357 /// returns whatever the `write_fmt` method returns; commonly a [`std::fmt::Result`], or an
360 /// See [`std::fmt`] for more information on the format string syntax.
362 /// [`std::fmt`]: ../std/fmt/index.html
363 /// [`std::fmt::Write`]: ../std/fmt/trait.Write.html
364 /// [`std::io::Write`]: ../std/io/trait.Write.html
365 /// [`std::fmt::Result`]: ../std/fmt/type.Result.html
366 /// [`io::Result`]: ../std/io/type.Result.html
371 /// use std::io::Write;
373 /// fn main() -> std::io::Result<()> {
374 /// let mut w = Vec::new();
375 /// write!(&mut w, "test")?;
376 /// write!(&mut w, "formatted {}", "arguments")?;
378 /// assert_eq!(w, b"testformatted arguments");
383 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
384 /// implementing either, as objects do not typically implement both. However, the module must
385 /// import the traits qualified so their names do not conflict:
388 /// use std::fmt::Write as FmtWrite;
389 /// use std::io::Write as IoWrite;
391 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
392 /// let mut s = String::new();
393 /// let mut v = Vec::new();
395 /// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
396 /// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
397 /// assert_eq!(v, b"s = \"abc 123\"");
402 /// Note: This macro can be used in `no_std` setups as well.
403 /// In a `no_std` setup you are responsible for the implementation details of the components.
406 /// # extern crate core;
407 /// use core::fmt::Write;
411 /// impl Write for Example {
412 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
413 /// unimplemented!();
417 /// let mut m = Example{};
418 /// write!(&mut m, "Hello World").expect("Not written");
421 #[stable(feature = "rust1", since = "1.0.0")]
423 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt($crate::format_args!($($arg)*)))
426 /// Write formatted data into a buffer, with a newline appended.
428 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
429 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
431 /// For more information, see [`write!`]. For information on the format string syntax, see
434 /// [`write!`]: macro.write.html
435 /// [`std::fmt`]: ../std/fmt/index.html
441 /// use std::io::{Write, Result};
443 /// fn main() -> Result<()> {
444 /// let mut w = Vec::new();
445 /// writeln!(&mut w)?;
446 /// writeln!(&mut w, "test")?;
447 /// writeln!(&mut w, "formatted {}", "arguments")?;
449 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
454 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
455 /// implementing either, as objects do not typically implement both. However, the module must
456 /// import the traits qualified so their names do not conflict:
459 /// use std::fmt::Write as FmtWrite;
460 /// use std::io::Write as IoWrite;
462 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
463 /// let mut s = String::new();
464 /// let mut v = Vec::new();
466 /// writeln!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
467 /// writeln!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
468 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
473 #[stable(feature = "rust1", since = "1.0.0")]
474 #[allow_internal_unstable(format_args_nl)]
475 macro_rules! writeln {
477 $crate::write!($dst, "\n")
480 $crate::writeln!($dst)
482 ($dst:expr, $($arg:tt)*) => (
483 $dst.write_fmt($crate::format_args_nl!($($arg)*))
487 /// Indicates unreachable code.
489 /// This is useful any time that the compiler can't determine that some code is unreachable. For
492 /// * Match arms with guard conditions.
493 /// * Loops that dynamically terminate.
494 /// * Iterators that dynamically terminate.
496 /// If the determination that the code is unreachable proves incorrect, the
497 /// program immediately terminates with a [`panic!`].
499 /// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
500 /// will cause undefined behavior if the code is reached.
502 /// [`panic!`]: ../std/macro.panic.html
503 /// [`unreachable_unchecked`]: ../std/hint/fn.unreachable_unchecked.html
504 /// [`std::hint`]: ../std/hint/index.html
508 /// This will always [`panic!`]
510 /// [`panic!`]: ../std/macro.panic.html
517 /// # #[allow(dead_code)]
518 /// fn foo(x: Option<i32>) {
520 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
521 /// Some(n) if n < 0 => println!("Some(Negative)"),
522 /// Some(_) => unreachable!(), // compile error if commented out
523 /// None => println!("None")
531 /// # #[allow(dead_code)]
532 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
534 /// if 3*i < i { panic!("u32 overflow"); }
535 /// if x < 3*i { return i-1; }
541 #[stable(feature = "rust1", since = "1.0.0")]
542 macro_rules! unreachable {
544 panic!("internal error: entered unreachable code")
547 $crate::unreachable!("{}", $msg)
550 $crate::unreachable!($msg)
552 ($fmt:expr, $($arg:tt)*) => ({
553 panic!($crate::concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
557 /// Indicates unfinished code by panicking with a message of "not yet implemented".
559 /// This allows the your code to type-check, which is useful if you are prototyping or
560 /// implementing a trait that requires multiple methods which you don't plan of using all of.
562 /// There is no difference between `unimplemented!` and `todo!` apart from the
567 /// This will always [panic!](macro.panic.html) because `unimplemented!` is just a
568 /// shorthand for `panic!` with a fixed, specific message.
570 /// Like `panic!`, this macro has a second form for displaying custom values.
574 /// Here's an example of some in-progress code. We have a trait `Foo`:
578 /// fn bar(&self) -> u8;
580 /// fn qux(&self) -> Result<u64, ()>;
584 /// We want to implement `Foo` for 'MyStruct', but so far we only know how to
585 /// implement the `bar()` function. `baz()` and `qux()` will still need to be defined
586 /// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
587 /// to allow our code to compile.
589 /// In the meantime, we want to have our program stop running once these
590 /// unimplemented functions are reached.
594 /// # fn bar(&self) -> u8;
596 /// # fn qux(&self) -> Result<u64, ()>;
600 /// impl Foo for MyStruct {
601 /// fn bar(&self) -> u8 {
606 /// // We aren't sure how to even start writing baz yet,
607 /// // so we have no logic here at all.
608 /// // This will display "thread 'main' panicked at 'not yet implemented'".
609 /// unimplemented!();
612 /// fn qux(&self) -> Result<u64, ()> {
613 /// let n = self.bar();
614 /// // We have some logic here,
615 /// // so we can use unimplemented! to display what we have so far.
616 /// // This will display:
617 /// // "thread 'main' panicked at 'not yet implemented: we need to divide by 2'".
618 /// unimplemented!("we need to divide by {}", n);
623 /// let s = MyStruct;
628 #[stable(feature = "rust1", since = "1.0.0")]
629 macro_rules! unimplemented {
630 () => (panic!("not yet implemented"));
631 ($($arg:tt)+) => (panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
634 /// Indicates unfinished code.
636 /// This can be useful if you are prototyping and are just looking to have your
639 /// There is no difference between `unimplemented!` and `todo!` apart from the
644 /// This will always [panic!](macro.panic.html)
648 /// Here's an example of some in-progress code. We have a trait `Foo`:
657 /// We want to implement `Foo` on one of our types, but we also want to work on
658 /// just `bar()` first. In order for our code to compile, we need to implement
659 /// `baz()`, so we can use `todo!`:
668 /// impl Foo for MyStruct {
670 /// // implementation goes here
674 /// // let's not worry about implementing baz() for now
680 /// let s = MyStruct;
683 /// // we aren't even using baz() yet, so this is fine.
687 #[stable(feature = "todo_macro", since = "1.39.0")]
689 () => (panic!("not yet implemented"));
690 ($($arg:tt)+) => (panic!("not yet implemented: {}", $crate::format_args!($($arg)+)));
693 /// Definitions of built-in macros.
695 /// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
696 /// with exception of expansion functions transforming macro inputs into outputs,
697 /// those functions are provided by the compiler.
698 pub(crate) mod builtin {
700 /// Causes compilation to fail with the given error message when encountered.
702 /// This macro should be used when a crate uses a conditional compilation strategy to provide
703 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
704 /// but emits an error during *compilation* rather than at *runtime*.
708 /// Two such examples are macros and `#[cfg]` environments.
710 /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
711 /// the compiler would still emit an error, but the error's message would not mention the two
715 /// macro_rules! give_me_foo_or_bar {
719 /// compile_error!("This macro only accepts `foo` or `bar`");
723 /// give_me_foo_or_bar!(neither);
724 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
727 /// Emit compiler error if one of a number of features isn't available.
730 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
731 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
734 /// [`panic!`]: ../std/macro.panic.html
735 #[stable(feature = "compile_error_macro", since = "1.20.0")]
736 #[rustc_builtin_macro]
738 macro_rules! compile_error {
739 ($msg:expr) => ({ /* compiler built-in */ });
740 ($msg:expr,) => ({ /* compiler built-in */ })
743 /// Constructs parameters for the other string-formatting macros.
745 /// This macro functions by taking a formatting string literal containing
746 /// `{}` for each additional argument passed. `format_args!` prepares the
747 /// additional parameters to ensure the output can be interpreted as a string
748 /// and canonicalizes the arguments into a single type. Any value that implements
749 /// the [`Display`] trait can be passed to `format_args!`, as can any
750 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
752 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
753 /// passed to the macros within [`std::fmt`] for performing useful redirection.
754 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
755 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
756 /// heap allocations.
758 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
759 /// in `Debug` and `Display` contexts as seen below. The example also shows
760 /// that `Debug` and `Display` format to the same thing: the interpolated
761 /// format string in `format_args!`.
764 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
765 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
766 /// assert_eq!("1 foo 2", display);
767 /// assert_eq!(display, debug);
770 /// For more information, see the documentation in [`std::fmt`].
772 /// [`Display`]: ../std/fmt/trait.Display.html
773 /// [`Debug`]: ../std/fmt/trait.Debug.html
774 /// [`fmt::Arguments`]: ../std/fmt/struct.Arguments.html
775 /// [`std::fmt`]: ../std/fmt/index.html
776 /// [`format!`]: ../std/macro.format.html
777 /// [`write!`]: ../std/macro.write.html
778 /// [`println!`]: ../std/macro.println.html
785 /// let s = fmt::format(format_args!("hello {}", "world"));
786 /// assert_eq!(s, format!("hello {}", "world"));
788 #[stable(feature = "rust1", since = "1.0.0")]
789 #[allow_internal_unstable(fmt_internals)]
790 #[rustc_builtin_macro]
792 macro_rules! format_args {
793 ($fmt:expr) => ({ /* compiler built-in */ });
794 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ })
797 /// Same as `format_args`, but adds a newline in the end.
798 #[unstable(feature = "format_args_nl", issue = "0",
799 reason = "`format_args_nl` is only for internal \
800 language use and is subject to change")]
801 #[allow_internal_unstable(fmt_internals)]
802 #[rustc_builtin_macro]
804 macro_rules! format_args_nl {
805 ($fmt:expr) => ({ /* compiler built-in */ });
806 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ })
809 /// Inspects an environment variable at compile time.
811 /// This macro will expand to the value of the named environment variable at
812 /// compile time, yielding an expression of type `&'static str`.
814 /// If the environment variable is not defined, then a compilation error
815 /// will be emitted. To not emit a compile error, use the [`option_env!`]
818 /// [`option_env!`]: ../std/macro.option_env.html
823 /// let path: &'static str = env!("PATH");
824 /// println!("the $PATH variable at the time of compiling was: {}", path);
827 /// You can customize the error message by passing a string as the second
831 /// let doc: &'static str = env!("documentation", "what's that?!");
834 /// If the `documentation` environment variable is not defined, you'll get
835 /// the following error:
838 /// error: what's that?!
840 #[stable(feature = "rust1", since = "1.0.0")]
841 #[rustc_builtin_macro]
844 ($name:expr) => ({ /* compiler built-in */ });
845 ($name:expr,) => ({ /* compiler built-in */ })
848 /// Optionally inspects an environment variable at compile time.
850 /// If the named environment variable is present at compile time, this will
851 /// expand into an expression of type `Option<&'static str>` whose value is
852 /// `Some` of the value of the environment variable. If the environment
853 /// variable is not present, then this will expand to `None`. See
854 /// [`Option<T>`][option] for more information on this type.
856 /// A compile time error is never emitted when using this macro regardless
857 /// of whether the environment variable is present or not.
859 /// [option]: ../std/option/enum.Option.html
864 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
865 /// println!("the secret key might be: {:?}", key);
867 #[stable(feature = "rust1", since = "1.0.0")]
868 #[rustc_builtin_macro]
870 macro_rules! option_env {
871 ($name:expr) => ({ /* compiler built-in */ });
872 ($name:expr,) => ({ /* compiler built-in */ })
875 /// Concatenates identifiers into one identifier.
877 /// This macro takes any number of comma-separated identifiers, and
878 /// concatenates them all into one, yielding an expression which is a new
879 /// identifier. Note that hygiene makes it such that this macro cannot
880 /// capture local variables. Also, as a general rule, macros are only
881 /// allowed in item, statement or expression position. That means while
882 /// you may use this macro for referring to existing variables, functions or
883 /// modules etc, you cannot define a new one with it.
888 /// #![feature(concat_idents)]
891 /// fn foobar() -> u32 { 23 }
893 /// let f = concat_idents!(foo, bar);
894 /// println!("{}", f());
896 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
899 #[unstable(feature = "concat_idents", issue = "29599",
900 reason = "`concat_idents` is not stable enough for use and is subject to change")]
901 #[rustc_builtin_macro]
903 macro_rules! concat_idents {
904 ($($e:ident),+) => ({ /* compiler built-in */ });
905 ($($e:ident,)+) => ({ /* compiler built-in */ })
908 /// Concatenates literals into a static string slice.
910 /// This macro takes any number of comma-separated literals, yielding an
911 /// expression of type `&'static str` which represents all of the literals
912 /// concatenated left-to-right.
914 /// Integer and floating point literals are stringified in order to be
920 /// let s = concat!("test", 10, 'b', true);
921 /// assert_eq!(s, "test10btrue");
923 #[stable(feature = "rust1", since = "1.0.0")]
924 #[rustc_builtin_macro]
926 macro_rules! concat {
927 ($($e:expr),*) => ({ /* compiler built-in */ });
928 ($($e:expr,)*) => ({ /* compiler built-in */ })
931 /// Expands to the line number on which it was invoked.
933 /// With [`column!`] and [`file!`], these macros provide debugging information for
934 /// developers about the location within the source.
936 /// The expanded expression has type `u32` and is 1-based, so the first line
937 /// in each file evaluates to 1, the second to 2, etc. This is consistent
938 /// with error messages by common compilers or popular editors.
939 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
940 /// but rather the first macro invocation leading up to the invocation
941 /// of the `line!` macro.
943 /// [`column!`]: macro.column.html
944 /// [`file!`]: macro.file.html
949 /// let current_line = line!();
950 /// println!("defined on line: {}", current_line);
952 #[stable(feature = "rust1", since = "1.0.0")]
953 #[rustc_builtin_macro]
955 macro_rules! line { () => { /* compiler built-in */ } }
957 /// Expands to the column number at which it was invoked.
959 /// With [`line!`] and [`file!`], these macros provide debugging information for
960 /// developers about the location within the source.
962 /// The expanded expression has type `u32` and is 1-based, so the first column
963 /// in each line evaluates to 1, the second to 2, etc. This is consistent
964 /// with error messages by common compilers or popular editors.
965 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
966 /// but rather the first macro invocation leading up to the invocation
967 /// of the `column!` macro.
969 /// [`line!`]: macro.line.html
970 /// [`file!`]: macro.file.html
975 /// let current_col = column!();
976 /// println!("defined on column: {}", current_col);
978 #[stable(feature = "rust1", since = "1.0.0")]
979 #[rustc_builtin_macro]
981 macro_rules! column { () => { /* compiler built-in */ } }
983 /// Expands to the file name in which it was invoked.
985 /// With [`line!`] and [`column!`], these macros provide debugging information for
986 /// developers about the location within the source.
989 /// The expanded expression has type `&'static str`, and the returned file
990 /// is not the invocation of the `file!` macro itself, but rather the
991 /// first macro invocation leading up to the invocation of the `file!`
994 /// [`line!`]: macro.line.html
995 /// [`column!`]: macro.column.html
1000 /// let this_file = file!();
1001 /// println!("defined in file: {}", this_file);
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 #[rustc_builtin_macro]
1006 macro_rules! file { () => { /* compiler built-in */ } }
1008 /// Stringifies its arguments.
1010 /// This macro will yield an expression of type `&'static str` which is the
1011 /// stringification of all the tokens passed to the macro. No restrictions
1012 /// are placed on the syntax of the macro invocation itself.
1014 /// Note that the expanded results of the input tokens may change in the
1015 /// future. You should be careful if you rely on the output.
1020 /// let one_plus_one = stringify!(1 + 1);
1021 /// assert_eq!(one_plus_one, "1 + 1");
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 #[rustc_builtin_macro]
1026 macro_rules! stringify { ($($t:tt)*) => { /* compiler built-in */ } }
1028 /// Includes a utf8-encoded file as a string.
1030 /// The file is located relative to the current file. (similarly to how
1031 /// modules are found)
1033 /// This macro will yield an expression of type `&'static str` which is the
1034 /// contents of the file.
1038 /// Assume there are two files in the same directory with the following
1041 /// File 'spanish.in':
1049 /// ```ignore (cannot-doctest-external-file-dependency)
1051 /// let my_str = include_str!("spanish.in");
1052 /// assert_eq!(my_str, "adiós\n");
1053 /// print!("{}", my_str);
1057 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1058 #[stable(feature = "rust1", since = "1.0.0")]
1059 #[rustc_builtin_macro]
1061 macro_rules! include_str {
1062 ($file:expr) => ({ /* compiler built-in */ });
1063 ($file:expr,) => ({ /* compiler built-in */ })
1066 /// Includes a file as a reference to a byte array.
1068 /// The file is located relative to the current file. (similarly to how
1069 /// modules are found)
1071 /// This macro will yield an expression of type `&'static [u8; N]` which is
1072 /// the contents of the file.
1076 /// Assume there are two files in the same directory with the following
1079 /// File 'spanish.in':
1087 /// ```ignore (cannot-doctest-external-file-dependency)
1089 /// let bytes = include_bytes!("spanish.in");
1090 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
1091 /// print!("{}", String::from_utf8_lossy(bytes));
1095 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 #[rustc_builtin_macro]
1099 macro_rules! include_bytes {
1100 ($file:expr) => ({ /* compiler built-in */ });
1101 ($file:expr,) => ({ /* compiler built-in */ })
1104 /// Expands to a string that represents the current module path.
1106 /// The current module path can be thought of as the hierarchy of modules
1107 /// leading back up to the crate root. The first component of the path
1108 /// returned is the name of the crate currently being compiled.
1115 /// assert!(module_path!().ends_with("test"));
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 #[rustc_builtin_macro]
1124 macro_rules! module_path { () => { /* compiler built-in */ } }
1126 /// Evaluates boolean combinations of configuration flags at compile-time.
1128 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1129 /// boolean expression evaluation of configuration flags. This frequently
1130 /// leads to less duplicated code.
1132 /// The syntax given to this macro is the same syntax as the [`cfg`]
1135 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1140 /// let my_directory = if cfg!(windows) {
1141 /// "windows-specific-directory"
1143 /// "unix-directory"
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 #[rustc_builtin_macro]
1149 macro_rules! cfg { ($($cfg:tt)*) => { /* compiler built-in */ } }
1151 /// Parses a file as an expression or an item according to the context.
1153 /// The file is located relative to the current file (similarly to how
1154 /// modules are found).
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 relies 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 /// [`panic!`]: macro.panic.html
1222 /// [`debug_assert!`]: macro.debug_assert.html
1223 /// [`std::fmt`]: ../std/fmt/index.html
1228 /// // the panic message for these assertions is the stringified value of the
1229 /// // expression given.
1232 /// fn some_computation() -> bool { true } // a very simple function
1234 /// assert!(some_computation());
1236 /// // assert with a custom message
1238 /// assert!(x, "x wasn't true!");
1240 /// let a = 3; let b = 27;
1241 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 #[rustc_builtin_macro]
1246 macro_rules! assert {
1247 ($cond:expr) => ({ /* compiler built-in */ });
1248 ($cond:expr,) => ({ /* compiler built-in */ });
1249 ($cond:expr, $($arg:tt)+) => ({ /* compiler built-in */ })
1252 /// Inline assembly.
1254 /// Read the [unstable book] for the usage.
1256 /// [unstable book]: ../unstable-book/library-features/asm.html
1257 #[unstable(feature = "asm", issue = "29722",
1258 reason = "inline assembly is not stable enough for use and is subject to change")]
1259 #[rustc_builtin_macro]
1261 macro_rules! asm { ("assembly template"
1262 : $("output"(operand),)*
1263 : $("input"(operand),)*
1265 : $("options",)*) => { /* compiler built-in */ } }
1267 /// Module-level inline assembly.
1268 #[unstable(feature = "global_asm", issue = "35119",
1269 reason = "`global_asm!` is not stable enough for use and is subject to change")]
1270 #[rustc_builtin_macro]
1272 macro_rules! global_asm { ("assembly") => { /* compiler built-in */ } }
1274 /// Prints passed tokens into the standard output.
1275 #[unstable(feature = "log_syntax", issue = "29598",
1276 reason = "`log_syntax!` is not stable enough for use and is subject to change")]
1277 #[rustc_builtin_macro]
1279 macro_rules! log_syntax { ($($arg:tt)*) => { /* compiler built-in */ } }
1281 /// Enables or disables tracing functionality used for debugging other macros.
1282 #[unstable(feature = "trace_macros", issue = "29598",
1283 reason = "`trace_macros` is not stable enough for use and is subject to change")]
1284 #[rustc_builtin_macro]
1286 macro_rules! trace_macros {
1287 (true) => ({ /* compiler built-in */ });
1288 (false) => ({ /* compiler built-in */ })
1291 /// Attribute macro applied to a function to turn it into a unit test.
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 #[allow_internal_unstable(test, rustc_attrs)]
1294 #[rustc_builtin_macro]
1295 pub macro test($item:item) { /* compiler built-in */ }
1297 /// Attribute macro applied to a function to turn it into a benchmark test.
1298 #[unstable(soft, feature = "test", issue = "50297",
1299 reason = "`bench` is a part of custom test frameworks which are unstable")]
1300 #[allow_internal_unstable(test, rustc_attrs)]
1301 #[rustc_builtin_macro]
1302 pub macro bench($item:item) { /* compiler built-in */ }
1304 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1305 #[unstable(feature = "custom_test_frameworks", issue = "50297",
1306 reason = "custom test frameworks are an unstable feature")]
1307 #[allow_internal_unstable(test, rustc_attrs)]
1308 #[rustc_builtin_macro]
1309 pub macro test_case($item:item) { /* compiler built-in */ }
1311 /// Attribute macro applied to a static to register it as a global allocator.
1312 #[stable(feature = "global_allocator", since = "1.28.0")]
1313 #[allow_internal_unstable(rustc_attrs)]
1314 #[rustc_builtin_macro]
1315 pub macro global_allocator($item:item) { /* compiler built-in */ }
1317 /// Unstable implementation detail of the `rustc` compiler, do not use.
1318 #[rustc_builtin_macro]
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 #[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
1321 pub macro RustcDecodable($item:item) { /* compiler built-in */ }
1323 /// Unstable implementation detail of the `rustc` compiler, do not use.
1324 #[rustc_builtin_macro]
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 #[allow_internal_unstable(core_intrinsics)]
1327 pub macro RustcEncodable($item:item) { /* compiler built-in */ }