1 /// Panics the current thread.
3 /// For details, see `std::macros`.
5 #[allow_internal_unstable(core_panic, __rust_unstable_column)]
6 #[stable(feature = "core", since = "1.6.0")]
9 $crate::panic!("explicit panic")
12 $crate::panicking::panic(&($msg, file!(), line!(), __rust_unstable_column!()))
17 ($fmt:expr, $($arg:tt)+) => ({
18 $crate::panicking::panic_fmt(format_args!($fmt, $($arg)+),
19 &(file!(), line!(), __rust_unstable_column!()))
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.
31 /// [`PartialEq`]: cmp/trait.PartialEq.html
32 /// [`assert!`]: macro.assert.html
41 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
44 #[stable(feature = "rust1", since = "1.0.0")]
45 macro_rules! assert_eq {
46 ($left:expr, $right:expr) => ({
47 match (&$left, &$right) {
48 (left_val, right_val) => {
49 if !(*left_val == *right_val) {
50 // The reborrows below are intentional. Without them, the stack slot for the
51 // borrow is initialized even before the values are compared, leading to a
52 // noticeable slow down.
53 panic!(r#"assertion failed: `(left == right)`
55 right: `{:?}`"#, &*left_val, &*right_val)
60 ($left:expr, $right:expr,) => ({
61 $crate::assert_eq!($left, $right)
63 ($left:expr, $right:expr, $($arg:tt)+) => ({
64 match (&($left), &($right)) {
65 (left_val, right_val) => {
66 if !(*left_val == *right_val) {
67 // The reborrows below are intentional. Without them, the stack slot for the
68 // borrow is initialized even before the values are compared, leading to a
69 // noticeable slow down.
70 panic!(r#"assertion failed: `(left == right)`
72 right: `{:?}`: {}"#, &*left_val, &*right_val,
73 format_args!($($arg)+))
80 /// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
82 /// On panic, this macro will print the values of the expressions with their
83 /// debug representations.
85 /// Like [`assert!`], this macro has a second form, where a custom
86 /// panic message can be provided.
88 /// [`PartialEq`]: cmp/trait.PartialEq.html
89 /// [`assert!`]: macro.assert.html
98 /// assert_ne!(a, b, "we are testing that the values are not equal");
101 #[stable(feature = "assert_ne", since = "1.13.0")]
102 macro_rules! assert_ne {
103 ($left:expr, $right:expr) => ({
104 match (&$left, &$right) {
105 (left_val, right_val) => {
106 if *left_val == *right_val {
107 // The reborrows below are intentional. Without them, the stack slot for the
108 // borrow is initialized even before the values are compared, leading to a
109 // noticeable slow down.
110 panic!(r#"assertion failed: `(left != right)`
112 right: `{:?}`"#, &*left_val, &*right_val)
117 ($left:expr, $right:expr,) => {
118 $crate::assert_ne!($left, $right)
120 ($left:expr, $right:expr, $($arg:tt)+) => ({
121 match (&($left), &($right)) {
122 (left_val, right_val) => {
123 if *left_val == *right_val {
124 // The reborrows below are intentional. Without them, the stack slot for the
125 // borrow is initialized even before the values are compared, leading to a
126 // noticeable slow down.
127 panic!(r#"assertion failed: `(left != right)`
129 right: `{:?}`: {}"#, &*left_val, &*right_val,
130 format_args!($($arg)+))
137 /// Asserts that a boolean expression is `true` at runtime.
139 /// This will invoke the [`panic!`] macro if the provided expression cannot be
140 /// evaluated to `true` at runtime.
142 /// Like [`assert!`], this macro also has a second version, where a custom panic
143 /// message can be provided.
147 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
148 /// optimized builds by default. An optimized build will not execute
149 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
150 /// compiler. This makes `debug_assert!` useful for checks that are too
151 /// expensive to be present in a release build but may be helpful during
152 /// development. The result of expanding `debug_assert!` is always type checked.
154 /// An unchecked assertion allows a program in an inconsistent state to keep
155 /// running, which might have unexpected consequences but does not introduce
156 /// unsafety as long as this only happens in safe code. The performance cost
157 /// of assertions, is however, not measurable in general. Replacing [`assert!`]
158 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
159 /// more importantly, only in safe code!
161 /// [`panic!`]: macro.panic.html
162 /// [`assert!`]: macro.assert.html
167 /// // the panic message for these assertions is the stringified value of the
168 /// // expression given.
169 /// debug_assert!(true);
171 /// fn some_expensive_computation() -> bool { true } // a very simple function
172 /// debug_assert!(some_expensive_computation());
174 /// // assert with a custom message
176 /// debug_assert!(x, "x wasn't true!");
178 /// let a = 3; let b = 27;
179 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
182 #[stable(feature = "rust1", since = "1.0.0")]
183 macro_rules! debug_assert {
184 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
187 /// Asserts that two expressions are equal to each other.
189 /// On panic, this macro will print the values of the expressions with their
190 /// debug representations.
192 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
193 /// optimized builds by default. An optimized build will not execute
194 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
195 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
196 /// expensive to be present in a release build but may be helpful during
197 /// development. The result of expanding `debug_assert_eq!` is always type checked.
199 /// [`assert_eq!`]: ../std/macro.assert_eq.html
206 /// debug_assert_eq!(a, b);
209 #[stable(feature = "rust1", since = "1.0.0")]
210 macro_rules! debug_assert_eq {
211 ($($arg:tt)*) => (if cfg!(debug_assertions) { $crate::assert_eq!($($arg)*); })
214 /// Asserts that two expressions are not equal to each other.
216 /// On panic, this macro will print the values of the expressions with their
217 /// debug representations.
219 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
220 /// optimized builds by default. An optimized build will not execute
221 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
222 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
223 /// expensive to be present in a release build but may be helpful during
224 /// development. The result of expanding `debug_assert_ne!` is always type checked.
226 /// [`assert_ne!`]: ../std/macro.assert_ne.html
233 /// debug_assert_ne!(a, b);
236 #[stable(feature = "assert_ne", since = "1.13.0")]
237 macro_rules! debug_assert_ne {
238 ($($arg:tt)*) => (if cfg!(debug_assertions) { $crate::assert_ne!($($arg)*); })
241 /// Unwraps a result or propagates its error.
243 /// The `?` operator was added to replace `try!` and should be used instead.
244 /// Furthermore, `try` is a reserved word in Rust 2018, so if you must use
245 /// it, you will need to use the [raw-identifier syntax][ris]: `r#try`.
247 /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
249 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
250 /// expression has the value of the wrapped value.
252 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
253 /// performs conversion using `From`. This provides automatic conversion
254 /// between specialized errors and more general ones. The resulting
255 /// error is then immediately returned.
257 /// Because of the early return, `try!` can only be used in functions that
258 /// return [`Result`].
260 /// [`Result`]: ../std/result/enum.Result.html
266 /// use std::fs::File;
267 /// use std::io::prelude::*;
273 /// impl From<io::Error> for MyError {
274 /// fn from(e: io::Error) -> MyError {
275 /// MyError::FileWriteError
279 /// // The preferred method of quick returning Errors
280 /// fn write_to_file_question() -> Result<(), MyError> {
281 /// let mut file = File::create("my_best_friends.txt")?;
282 /// file.write_all(b"This is a list of my best friends.")?;
286 /// // The previous method of quick returning Errors
287 /// fn write_to_file_using_try() -> Result<(), MyError> {
288 /// let mut file = r#try!(File::create("my_best_friends.txt"));
289 /// r#try!(file.write_all(b"This is a list of my best friends."));
293 /// // This is equivalent to:
294 /// fn write_to_file_using_match() -> Result<(), MyError> {
295 /// let mut file = r#try!(File::create("my_best_friends.txt"));
296 /// match file.write_all(b"This is a list of my best friends.") {
298 /// Err(e) => return Err(From::from(e)),
304 #[stable(feature = "rust1", since = "1.0.0")]
307 ($expr:expr) => (match $expr {
308 $crate::result::Result::Ok(val) => val,
309 $crate::result::Result::Err(err) => {
310 return $crate::result::Result::Err($crate::convert::From::from(err))
313 ($expr:expr,) => ($crate::r#try!($expr));
316 /// Writes formatted data into a buffer.
318 /// This macro accepts a format string, a list of arguments, and a 'writer'. Arguments will be
319 /// formatted according to the specified format string and the result will be passed to the writer.
320 /// The writer may be any value with a `write_fmt` method; generally this comes from an
321 /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro
322 /// returns whatever the `write_fmt` method returns; commonly a [`std::fmt::Result`], or an
325 /// See [`std::fmt`] for more information on the format string syntax.
327 /// [`std::fmt`]: ../std/fmt/index.html
328 /// [`std::fmt::Write`]: ../std/fmt/trait.Write.html
329 /// [`std::io::Write`]: ../std/io/trait.Write.html
330 /// [`std::fmt::Result`]: ../std/fmt/type.Result.html
331 /// [`io::Result`]: ../std/io/type.Result.html
336 /// use std::io::Write;
338 /// fn main() -> std::io::Result<()> {
339 /// let mut w = Vec::new();
340 /// write!(&mut w, "test")?;
341 /// write!(&mut w, "formatted {}", "arguments")?;
343 /// assert_eq!(w, b"testformatted arguments");
348 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
349 /// implementing either, as objects do not typically implement both. However, the module must
350 /// import the traits qualified so their names do not conflict:
353 /// use std::fmt::Write as FmtWrite;
354 /// use std::io::Write as IoWrite;
356 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
357 /// let mut s = String::new();
358 /// let mut v = Vec::new();
360 /// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
361 /// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
362 /// assert_eq!(v, b"s = \"abc 123\"");
367 /// Note: This macro can be used in `no_std` setups as well.
368 /// In a `no_std` setup you are responsible for the implementation details of the components.
371 /// # extern crate core;
372 /// use core::fmt::Write;
376 /// impl Write for Example {
377 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
378 /// unimplemented!();
382 /// let mut m = Example{};
383 /// write!(&mut m, "Hello World").expect("Not written");
386 #[stable(feature = "rust1", since = "1.0.0")]
388 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
391 /// Write formatted data into a buffer, with a newline appended.
393 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
394 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
396 /// For more information, see [`write!`]. For information on the format string syntax, see
399 /// [`write!`]: macro.write.html
400 /// [`std::fmt`]: ../std/fmt/index.html
406 /// use std::io::{Write, Result};
408 /// fn main() -> Result<()> {
409 /// let mut w = Vec::new();
410 /// writeln!(&mut w)?;
411 /// writeln!(&mut w, "test")?;
412 /// writeln!(&mut w, "formatted {}", "arguments")?;
414 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
419 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
420 /// implementing either, as objects do not typically implement both. However, the module must
421 /// import the traits qualified so their names do not conflict:
424 /// use std::fmt::Write as FmtWrite;
425 /// use std::io::Write as IoWrite;
427 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
428 /// let mut s = String::new();
429 /// let mut v = Vec::new();
431 /// writeln!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
432 /// writeln!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
433 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
438 #[stable(feature = "rust1", since = "1.0.0")]
439 #[allow_internal_unstable(format_args_nl)]
440 macro_rules! writeln {
442 $crate::write!($dst, "\n")
445 $crate::writeln!($dst)
447 ($dst:expr, $($arg:tt)*) => (
448 $dst.write_fmt(format_args_nl!($($arg)*))
452 /// Indicates unreachable code.
454 /// This is useful any time that the compiler can't determine that some code is unreachable. For
457 /// * Match arms with guard conditions.
458 /// * Loops that dynamically terminate.
459 /// * Iterators that dynamically terminate.
461 /// If the determination that the code is unreachable proves incorrect, the
462 /// program immediately terminates with a [`panic!`].
464 /// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
465 /// will cause undefined behavior if the code is reached.
467 /// [`panic!`]: ../std/macro.panic.html
468 /// [`unreachable_unchecked`]: ../std/hint/fn.unreachable_unchecked.html
469 /// [`std::hint`]: ../std/hint/index.html
473 /// This will always [`panic!`]
475 /// [`panic!`]: ../std/macro.panic.html
481 /// # #[allow(dead_code)]
482 /// fn foo(x: Option<i32>) {
484 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
485 /// Some(n) if n < 0 => println!("Some(Negative)"),
486 /// Some(_) => unreachable!(), // compile error if commented out
487 /// None => println!("None")
495 /// # #[allow(dead_code)]
496 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
498 /// if 3*i < i { panic!("u32 overflow"); }
499 /// if x < 3*i { return i-1; }
505 #[stable(feature = "rust1", since = "1.0.0")]
506 macro_rules! unreachable {
508 panic!("internal error: entered unreachable code")
511 $crate::unreachable!("{}", $msg)
514 $crate::unreachable!($msg)
516 ($fmt:expr, $($arg:tt)*) => ({
517 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
521 /// Indicates unfinished code.
523 /// This can be useful if you are prototyping and are just looking to have your
524 /// code type-check, or if you're implementing a trait that requires multiple
525 /// methods, and you're only planning on using one of them.
529 /// This will always [panic!](macro.panic.html)
533 /// Here's an example of some in-progress code. We have a trait `Foo`:
542 /// We want to implement `Foo` on one of our types, but we also want to work on
543 /// just `bar()` first. In order for our code to compile, we need to implement
544 /// `baz()`, so we can use `unimplemented!`:
553 /// impl Foo for MyStruct {
555 /// // implementation goes here
559 /// // let's not worry about implementing baz() for now
560 /// unimplemented!();
565 /// let s = MyStruct;
568 /// // we aren't even using baz() yet, so this is fine.
572 #[stable(feature = "rust1", since = "1.0.0")]
573 macro_rules! unimplemented {
574 () => (panic!("not yet implemented"));
575 ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)+)));
578 /// Indicates unfinished code.
580 /// This can be useful if you are prototyping and are just looking to have your
581 /// code typecheck. `todo!` works exactly like `unimplemented!`. The only
582 /// difference between the two macros is the name.
586 /// This will always [panic!](macro.panic.html)
590 /// Here's an example of some in-progress code. We have a trait `Foo`:
599 /// We want to implement `Foo` on one of our types, but we also want to work on
600 /// just `bar()` first. In order for our code to compile, we need to implement
601 /// `baz()`, so we can use `todo!`:
604 /// #![feature(todo_macro)]
612 /// impl Foo for MyStruct {
614 /// // implementation goes here
618 /// // let's not worry about implementing baz() for now
624 /// let s = MyStruct;
627 /// // we aren't even using baz() yet, so this is fine.
631 #[unstable(feature = "todo_macro", issue = "59277")]
633 () => (panic!("not yet implemented"));
634 ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)+)));
637 /// Creates an array of [`MaybeUninit`].
639 /// This macro constructs an uninitialized array of the type `[MaybeUninit<K>; N]`.
640 /// It exists solely because bootstrap does not yet support const array-init expressions.
642 /// [`MaybeUninit`]: mem/union.MaybeUninit.html
643 // FIXME: Remove both versions of this macro once bootstrap is 1.38.
645 #[unstable(feature = "maybe_uninit_array", issue = "53491")]
647 macro_rules! uninit_array {
648 // This `assume_init` is safe because an array of `MaybeUninit` does not
649 // require initialization.
650 ($t:ty; $size:expr) => (unsafe {
651 MaybeUninit::<[MaybeUninit<$t>; $size]>::uninit().assume_init()
655 /// Creates an array of [`MaybeUninit`].
657 /// This macro constructs an uninitialized array of the type `[MaybeUninit<K>; N]`.
658 /// It exists solely because bootstrap does not yet support const array-init expressions.
660 /// [`MaybeUninit`]: mem/union.MaybeUninit.html
661 // FIXME: Just inline this version of the macro once bootstrap is 1.38.
663 #[unstable(feature = "maybe_uninit_array", issue = "53491")]
664 #[cfg(not(bootstrap))]
665 macro_rules! uninit_array {
666 ($t:ty; $size:expr) => (
667 [MaybeUninit::<$t>::UNINIT; $size]
671 /// Definitions of built-in macros.
673 /// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
674 /// with exception of expansion functions transforming macro inputs into outputs,
675 /// those functions are provided by the compiler.
676 #[cfg(not(bootstrap))]
677 pub(crate) mod builtin {
679 /// Causes compilation to fail with the given error message when encountered.
681 /// This macro should be used when a crate uses a conditional compilation strategy to provide
682 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
683 /// which emits an error at *runtime*, rather than during compilation.
687 /// Two such examples are macros and `#[cfg]` environments.
689 /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
690 /// the compiler would still emit an error, but the error's message would not mention the two
694 /// macro_rules! give_me_foo_or_bar {
698 /// compile_error!("This macro only accepts `foo` or `bar`");
702 /// give_me_foo_or_bar!(neither);
703 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
706 /// Emit compiler error if one of a number of features isn't available.
709 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
710 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
713 /// [`panic!`]: ../std/macro.panic.html
714 #[stable(feature = "compile_error_macro", since = "1.20.0")]
715 #[rustc_builtin_macro]
716 #[rustc_macro_transparency = "semitransparent"]
717 pub macro compile_error {
718 ($msg:expr) => ({ /* compiler built-in */ }),
719 ($msg:expr,) => ({ /* compiler built-in */ })
722 /// Constructs parameters for the other string-formatting macros.
724 /// This macro functions by taking a formatting string literal containing
725 /// `{}` for each additional argument passed. `format_args!` prepares the
726 /// additional parameters to ensure the output can be interpreted as a string
727 /// and canonicalizes the arguments into a single type. Any value that implements
728 /// the [`Display`] trait can be passed to `format_args!`, as can any
729 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
731 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
732 /// passed to the macros within [`std::fmt`] for performing useful redirection.
733 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
734 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
735 /// heap allocations.
737 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
738 /// in `Debug` and `Display` contexts as seen below. The example also shows
739 /// that `Debug` and `Display` format to the same thing: the interpolated
740 /// format string in `format_args!`.
743 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
744 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
745 /// assert_eq!("1 foo 2", display);
746 /// assert_eq!(display, debug);
749 /// For more information, see the documentation in [`std::fmt`].
751 /// [`Display`]: ../std/fmt/trait.Display.html
752 /// [`Debug`]: ../std/fmt/trait.Debug.html
753 /// [`fmt::Arguments`]: ../std/fmt/struct.Arguments.html
754 /// [`std::fmt`]: ../std/fmt/index.html
755 /// [`format!`]: ../std/macro.format.html
756 /// [`write!`]: ../std/macro.write.html
757 /// [`println!`]: ../std/macro.println.html
764 /// let s = fmt::format(format_args!("hello {}", "world"));
765 /// assert_eq!(s, format!("hello {}", "world"));
767 #[stable(feature = "rust1", since = "1.0.0")]
768 #[allow_internal_unstable(fmt_internals)]
769 #[rustc_builtin_macro]
770 #[rustc_macro_transparency = "semitransparent"]
771 pub macro format_args {
772 ($fmt:expr) => ({ /* compiler built-in */ }),
773 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ })
776 /// Same as `format_args`, but adds a newline in the end.
777 #[unstable(feature = "format_args_nl", issue = "0",
778 reason = "`format_args_nl` is only for internal \
779 language use and is subject to change")]
780 #[allow_internal_unstable(fmt_internals)]
781 #[rustc_builtin_macro]
782 #[rustc_macro_transparency = "semitransparent"]
783 pub macro format_args_nl {
784 ($fmt:expr) => ({ /* compiler built-in */ }),
785 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ })
788 /// Inspects an environment variable at compile time.
790 /// This macro will expand to the value of the named environment variable at
791 /// compile time, yielding an expression of type `&'static str`.
793 /// If the environment variable is not defined, then a compilation error
794 /// will be emitted. To not emit a compile error, use the [`option_env!`]
797 /// [`option_env!`]: ../std/macro.option_env.html
802 /// let path: &'static str = env!("PATH");
803 /// println!("the $PATH variable at the time of compiling was: {}", path);
806 /// You can customize the error message by passing a string as the second
810 /// let doc: &'static str = env!("documentation", "what's that?!");
813 /// If the `documentation` environment variable is not defined, you'll get
814 /// the following error:
817 /// error: what's that?!
819 #[stable(feature = "rust1", since = "1.0.0")]
820 #[rustc_builtin_macro]
821 #[rustc_macro_transparency = "semitransparent"]
823 ($name:expr) => ({ /* compiler built-in */ }),
824 ($name:expr,) => ({ /* compiler built-in */ })
827 /// Optionally inspects an environment variable at compile time.
829 /// If the named environment variable is present at compile time, this will
830 /// expand into an expression of type `Option<&'static str>` whose value is
831 /// `Some` of the value of the environment variable. If the environment
832 /// variable is not present, then this will expand to `None`. See
833 /// [`Option<T>`][option] for more information on this type.
835 /// A compile time error is never emitted when using this macro regardless
836 /// of whether the environment variable is present or not.
838 /// [option]: ../std/option/enum.Option.html
843 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
844 /// println!("the secret key might be: {:?}", key);
846 #[stable(feature = "rust1", since = "1.0.0")]
847 #[rustc_builtin_macro]
848 #[rustc_macro_transparency = "semitransparent"]
849 pub macro option_env {
850 ($name:expr) => ({ /* compiler built-in */ }),
851 ($name:expr,) => ({ /* compiler built-in */ })
854 /// Concatenates identifiers into one identifier.
856 /// This macro takes any number of comma-separated identifiers, and
857 /// concatenates them all into one, yielding an expression which is a new
858 /// identifier. Note that hygiene makes it such that this macro cannot
859 /// capture local variables. Also, as a general rule, macros are only
860 /// allowed in item, statement or expression position. That means while
861 /// you may use this macro for referring to existing variables, functions or
862 /// modules etc, you cannot define a new one with it.
867 /// #![feature(concat_idents)]
870 /// fn foobar() -> u32 { 23 }
872 /// let f = concat_idents!(foo, bar);
873 /// println!("{}", f());
875 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
878 #[unstable(feature = "concat_idents", issue = "29599",
879 reason = "`concat_idents` is not stable enough for use and is subject to change")]
880 #[rustc_builtin_macro]
881 #[rustc_macro_transparency = "semitransparent"]
882 pub macro concat_idents {
883 ($($e:ident),+) => ({ /* compiler built-in */ }),
884 ($($e:ident,)+) => ({ /* compiler built-in */ })
887 /// Concatenates literals into a static string slice.
889 /// This macro takes any number of comma-separated literals, yielding an
890 /// expression of type `&'static str` which represents all of the literals
891 /// concatenated left-to-right.
893 /// Integer and floating point literals are stringified in order to be
899 /// let s = concat!("test", 10, 'b', true);
900 /// assert_eq!(s, "test10btrue");
902 #[stable(feature = "rust1", since = "1.0.0")]
903 #[rustc_builtin_macro]
904 #[rustc_macro_transparency = "semitransparent"]
906 ($($e:expr),*) => ({ /* compiler built-in */ }),
907 ($($e:expr,)*) => ({ /* compiler built-in */ })
910 /// Expands to the line number on which it was invoked.
912 /// With [`column!`] and [`file!`], these macros provide debugging information for
913 /// developers about the location within the source.
915 /// The expanded expression has type `u32` and is 1-based, so the first line
916 /// in each file evaluates to 1, the second to 2, etc. This is consistent
917 /// with error messages by common compilers or popular editors.
918 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
919 /// but rather the first macro invocation leading up to the invocation
920 /// of the `line!` macro.
922 /// [`column!`]: macro.column.html
923 /// [`file!`]: macro.file.html
928 /// let current_line = line!();
929 /// println!("defined on line: {}", current_line);
931 #[stable(feature = "rust1", since = "1.0.0")]
932 #[rustc_builtin_macro]
933 #[rustc_macro_transparency = "semitransparent"]
934 pub macro line() { /* compiler built-in */ }
936 /// Expands to the column number at which it was invoked.
938 /// With [`line!`] and [`file!`], these macros provide debugging information for
939 /// developers about the location within the source.
941 /// The expanded expression has type `u32` and is 1-based, so the first column
942 /// in each line evaluates to 1, the second to 2, etc. This is consistent
943 /// with error messages by common compilers or popular editors.
944 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
945 /// but rather the first macro invocation leading up to the invocation
946 /// of the `column!` macro.
948 /// [`line!`]: macro.line.html
949 /// [`file!`]: macro.file.html
954 /// let current_col = column!();
955 /// println!("defined on column: {}", current_col);
957 #[stable(feature = "rust1", since = "1.0.0")]
958 #[rustc_builtin_macro]
959 #[rustc_macro_transparency = "semitransparent"]
960 pub macro column() { /* compiler built-in */ }
962 /// Same as `column`, but less likely to be shadowed.
963 #[unstable(feature = "__rust_unstable_column", issue = "0",
964 reason = "internal implementation detail of the `panic` macro")]
965 #[rustc_builtin_macro]
966 #[rustc_macro_transparency = "semitransparent"]
967 pub macro __rust_unstable_column() { /* compiler built-in */ }
969 /// Expands to the file name in which it was invoked.
971 /// With [`line!`] and [`column!`], these macros provide debugging information for
972 /// developers about the location within the source.
975 /// The expanded expression has type `&'static str`, and the returned file
976 /// is not the invocation of the `file!` macro itself, but rather the
977 /// first macro invocation leading up to the invocation of the `file!`
980 /// [`line!`]: macro.line.html
981 /// [`column!`]: macro.column.html
986 /// let this_file = file!();
987 /// println!("defined in file: {}", this_file);
989 #[stable(feature = "rust1", since = "1.0.0")]
990 #[rustc_builtin_macro]
991 #[rustc_macro_transparency = "semitransparent"]
992 pub macro file() { /* compiler built-in */ }
994 /// Stringifies its arguments.
996 /// This macro will yield an expression of type `&'static str` which is the
997 /// stringification of all the tokens passed to the macro. No restrictions
998 /// are placed on the syntax of the macro invocation itself.
1000 /// Note that the expanded results of the input tokens may change in the
1001 /// future. You should be careful if you rely on the output.
1006 /// let one_plus_one = stringify!(1 + 1);
1007 /// assert_eq!(one_plus_one, "1 + 1");
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 #[rustc_builtin_macro]
1011 #[rustc_macro_transparency = "semitransparent"]
1012 pub macro stringify($($t:tt)*) { /* compiler built-in */ }
1014 /// Includes a utf8-encoded file as a string.
1016 /// The file is located relative to the current file. (similarly to how
1017 /// modules are found)
1019 /// This macro will yield an expression of type `&'static str` which is the
1020 /// contents of the file.
1024 /// Assume there are two files in the same directory with the following
1027 /// File 'spanish.in':
1035 /// ```ignore (cannot-doctest-external-file-dependency)
1037 /// let my_str = include_str!("spanish.in");
1038 /// assert_eq!(my_str, "adiós\n");
1039 /// print!("{}", my_str);
1043 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 #[rustc_builtin_macro]
1046 #[rustc_macro_transparency = "semitransparent"]
1047 pub macro include_str {
1048 ($file:expr) => ({ /* compiler built-in */ }),
1049 ($file:expr,) => ({ /* compiler built-in */ })
1052 /// Includes a file as a reference to a byte array.
1054 /// The file is located relative to the current file. (similarly to how
1055 /// modules are found)
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]
1084 #[rustc_macro_transparency = "semitransparent"]
1085 pub macro 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]
1109 #[rustc_macro_transparency = "semitransparent"]
1110 pub macro module_path() { /* compiler built-in */ }
1112 /// Evaluates boolean combinations of configuration flags at compile-time.
1114 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1115 /// boolean expression evaluation of configuration flags. This frequently
1116 /// leads to less duplicated code.
1118 /// The syntax given to this macro is the same syntax as the [`cfg`]
1121 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1126 /// let my_directory = if cfg!(windows) {
1127 /// "windows-specific-directory"
1129 /// "unix-directory"
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 #[rustc_builtin_macro]
1134 #[rustc_macro_transparency = "semitransparent"]
1135 pub macro cfg($($cfg:tt)*) { /* compiler built-in */ }
1137 /// Parses a file as an expression or an item according to the context.
1139 /// The file is located relative to the current file (similarly to how
1140 /// modules are found).
1142 /// Using this macro is often a bad idea, because if the file is
1143 /// parsed as an expression, it is going to be placed in the
1144 /// surrounding code unhygienically. This could result in variables
1145 /// or functions being different from what the file expected if
1146 /// there are variables or functions that have the same name in
1147 /// the current file.
1151 /// Assume there are two files in the same directory with the following
1154 /// File 'monkeys.in':
1156 /// ```ignore (only-for-syntax-highlight)
1157 /// ['🙈', '🙊', '🙉']
1161 /// .collect::<String>()
1166 /// ```ignore (cannot-doctest-external-file-dependency)
1168 /// let my_string = include!("monkeys.in");
1169 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1170 /// println!("{}", my_string);
1174 /// Compiling 'main.rs' and running the resulting binary will print
1175 /// "🙈🙊🙉🙈🙊🙉".
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 #[rustc_builtin_macro]
1178 #[rustc_macro_transparency = "semitransparent"]
1180 ($file:expr) => ({ /* compiler built-in */ }),
1181 ($file:expr,) => ({ /* compiler built-in */ })
1184 /// Asserts that a boolean expression is `true` at runtime.
1186 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1187 /// evaluated to `true` at runtime.
1191 /// Assertions are always checked in both debug and release builds, and cannot
1192 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1193 /// release builds by default.
1195 /// Unsafe code relies on `assert!` to enforce run-time invariants that, if
1196 /// violated could lead to unsafety.
1198 /// Other use-cases of `assert!` include testing and enforcing run-time
1199 /// invariants in safe code (whose violation cannot result in unsafety).
1201 /// # Custom Messages
1203 /// This macro has a second form, where a custom panic message can
1204 /// be provided with or without arguments for formatting. See [`std::fmt`]
1205 /// for syntax for this form.
1207 /// [`panic!`]: macro.panic.html
1208 /// [`debug_assert!`]: macro.debug_assert.html
1209 /// [`std::fmt`]: ../std/fmt/index.html
1214 /// // the panic message for these assertions is the stringified value of the
1215 /// // expression given.
1218 /// fn some_computation() -> bool { true } // a very simple function
1220 /// assert!(some_computation());
1222 /// // assert with a custom message
1224 /// assert!(x, "x wasn't true!");
1226 /// let a = 3; let b = 27;
1227 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 #[rustc_builtin_macro]
1231 #[rustc_macro_transparency = "semitransparent"]
1233 ($cond:expr) => ({ /* compiler built-in */ }),
1234 ($cond:expr,) => ({ /* compiler built-in */ }),
1235 ($cond:expr, $($arg:tt)+) => ({ /* compiler built-in */ })
1238 /// Inline assembly.
1239 #[unstable(feature = "asm", issue = "29722",
1240 reason = "inline assembly is not stable enough for use and is subject to change")]
1241 #[rustc_builtin_macro]
1242 #[rustc_macro_transparency = "semitransparent"]
1243 pub macro asm("assembly template"
1244 : $("output"(operand),)*
1245 : $("input"(operand),)*
1247 : $("options",)*) { /* compiler built-in */ }
1249 /// Module-level inline assembly.
1250 #[unstable(feature = "global_asm", issue = "35119",
1251 reason = "`global_asm!` is not stable enough for use and is subject to change")]
1252 #[rustc_builtin_macro]
1253 #[rustc_macro_transparency = "semitransparent"]
1254 pub macro global_asm("assembly") { /* compiler built-in */ }
1256 /// Prints passed tokens into the standard output.
1257 #[unstable(feature = "log_syntax", issue = "29598",
1258 reason = "`log_syntax!` is not stable enough for use and is subject to change")]
1259 #[rustc_builtin_macro]
1260 #[rustc_macro_transparency = "semitransparent"]
1261 pub macro log_syntax($($arg:tt)*) { /* compiler built-in */ }
1263 /// Enables or disables tracing functionality used for debugging other macros.
1264 #[unstable(feature = "trace_macros", issue = "29598",
1265 reason = "`trace_macros` is not stable enough for use and is subject to change")]
1266 #[rustc_builtin_macro]
1267 #[rustc_macro_transparency = "semitransparent"]
1268 pub macro trace_macros {
1269 (true) => ({ /* compiler built-in */ }),
1270 (false) => ({ /* compiler built-in */ })
1273 /// Attribute macro applied to a function to turn it into a unit test.
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 #[allow_internal_unstable(test, rustc_attrs)]
1276 #[rustc_builtin_macro]
1277 #[rustc_macro_transparency = "semitransparent"]
1278 pub macro test($item:item) { /* compiler built-in */ }
1280 /// Attribute macro applied to a function to turn it into a benchmark test.
1281 #[unstable(feature = "test", issue = "50297",
1282 reason = "`bench` is a part of custom test frameworks which are unstable")]
1283 #[allow_internal_unstable(test, rustc_attrs)]
1284 #[rustc_builtin_macro]
1285 #[rustc_macro_transparency = "semitransparent"]
1286 pub macro bench($item:item) { /* compiler built-in */ }
1288 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1289 #[unstable(feature = "custom_test_frameworks", issue = "50297",
1290 reason = "custom test frameworks are an unstable feature")]
1291 #[allow_internal_unstable(test, rustc_attrs)]
1292 #[rustc_builtin_macro]
1293 #[rustc_macro_transparency = "semitransparent"]
1294 pub macro test_case($item:item) { /* compiler built-in */ }
1296 /// Attribute macro applied to a static to register it as a global allocator.
1297 #[stable(feature = "global_allocator", since = "1.28.0")]
1298 #[allow_internal_unstable(rustc_attrs)]
1299 #[rustc_builtin_macro]
1300 #[rustc_macro_transparency = "semitransparent"]
1301 pub macro global_allocator($item:item) { /* compiler built-in */ }
1303 /// Derive macro generating an impl of the trait `Clone`.
1304 #[rustc_builtin_macro]
1305 #[rustc_macro_transparency = "semitransparent"]
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 #[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
1308 pub macro Clone($item:item) { /* compiler built-in */ }
1310 /// Derive macro generating an impl of the trait `Copy`.
1311 #[rustc_builtin_macro]
1312 #[rustc_macro_transparency = "semitransparent"]
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 #[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
1315 pub macro Copy($item:item) { /* compiler built-in */ }
1317 /// Derive macro generating an impl of the trait `Debug`.
1318 #[rustc_builtin_macro]
1319 #[rustc_macro_transparency = "semitransparent"]
1320 #[stable(feature = "rust1", since = "1.0.0")]
1321 #[allow_internal_unstable(core_intrinsics)]
1322 pub macro Debug($item:item) { /* compiler built-in */ }
1324 /// Derive macro generating an impl of the trait `Default`.
1325 #[rustc_builtin_macro]
1326 #[rustc_macro_transparency = "semitransparent"]
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 #[allow_internal_unstable(core_intrinsics)]
1329 pub macro Default($item:item) { /* compiler built-in */ }
1331 /// Derive macro generating an impl of the trait `Eq`.
1332 #[rustc_builtin_macro]
1333 #[rustc_macro_transparency = "semitransparent"]
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 #[allow_internal_unstable(core_intrinsics, derive_eq)]
1336 pub macro Eq($item:item) { /* compiler built-in */ }
1338 /// Derive macro generating an impl of the trait `Hash`.
1339 #[rustc_builtin_macro]
1340 #[rustc_macro_transparency = "semitransparent"]
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 #[allow_internal_unstable(core_intrinsics)]
1343 pub macro Hash($item:item) { /* compiler built-in */ }
1345 /// Derive macro generating an impl of the trait `Ord`.
1346 #[rustc_builtin_macro]
1347 #[rustc_macro_transparency = "semitransparent"]
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 #[allow_internal_unstable(core_intrinsics)]
1350 pub macro Ord($item:item) { /* compiler built-in */ }
1352 /// Derive macro generating an impl of the trait `PartialEq`.
1353 #[rustc_builtin_macro]
1354 #[rustc_macro_transparency = "semitransparent"]
1355 #[stable(feature = "rust1", since = "1.0.0")]
1356 #[allow_internal_unstable(core_intrinsics)]
1357 pub macro PartialEq($item:item) { /* compiler built-in */ }
1359 /// Derive macro generating an impl of the trait `PartialOrd`.
1360 #[rustc_builtin_macro]
1361 #[rustc_macro_transparency = "semitransparent"]
1362 #[stable(feature = "rust1", since = "1.0.0")]
1363 #[allow_internal_unstable(core_intrinsics)]
1364 pub macro PartialOrd($item:item) { /* compiler built-in */ }
1366 /// Unstable implementation detail of the `rustc` compiler, do not use.
1367 #[rustc_builtin_macro]
1368 #[rustc_macro_transparency = "semitransparent"]
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 #[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
1371 pub macro RustcDecodable($item:item) { /* compiler built-in */ }
1373 /// Unstable implementation detail of the `rustc` compiler, do not use.
1374 #[rustc_builtin_macro]
1375 #[rustc_macro_transparency = "semitransparent"]
1376 #[stable(feature = "rust1", since = "1.0.0")]
1377 #[allow_internal_unstable(core_intrinsics)]
1378 pub macro RustcEncodable($item:item) { /* compiler built-in */ }