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 /// let mut s = String::new();
357 /// let mut v = Vec::new();
358 /// write!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
359 /// write!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
360 /// assert_eq!(v, b"s = \"abc 123\"");
363 /// Note: This macro can be used in `no_std` setups as well.
364 /// In a `no_std` setup you are responsible for the implementation details of the components.
367 /// # extern crate core;
368 /// use core::fmt::Write;
372 /// impl Write for Example {
373 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
374 /// unimplemented!();
378 /// let mut m = Example{};
379 /// write!(&mut m, "Hello World").expect("Not written");
382 #[stable(feature = "rust1", since = "1.0.0")]
384 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
387 /// Write formatted data into a buffer, with a newline appended.
389 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
390 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
392 /// For more information, see [`write!`]. For information on the format string syntax, see
395 /// [`write!`]: macro.write.html
396 /// [`std::fmt`]: ../std/fmt/index.html
402 /// use std::io::Write;
404 /// let mut w = Vec::new();
405 /// writeln!(&mut w).unwrap();
406 /// writeln!(&mut w, "test").unwrap();
407 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
409 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
412 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
413 /// implementing either, as objects do not typically implement both. However, the module must
414 /// import the traits qualified so their names do not conflict:
417 /// use std::fmt::Write as FmtWrite;
418 /// use std::io::Write as IoWrite;
420 /// let mut s = String::new();
421 /// let mut v = Vec::new();
422 /// writeln!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
423 /// writeln!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
424 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
427 #[stable(feature = "rust1", since = "1.0.0")]
428 #[allow_internal_unstable(format_args_nl)]
429 macro_rules! writeln {
431 $crate::write!($dst, "\n")
434 $crate::writeln!($dst)
436 ($dst:expr, $($arg:tt)*) => (
437 $dst.write_fmt(format_args_nl!($($arg)*))
441 /// Indicates unreachable code.
443 /// This is useful any time that the compiler can't determine that some code is unreachable. For
446 /// * Match arms with guard conditions.
447 /// * Loops that dynamically terminate.
448 /// * Iterators that dynamically terminate.
450 /// If the determination that the code is unreachable proves incorrect, the
451 /// program immediately terminates with a [`panic!`].
453 /// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
454 /// will cause undefined behavior if the code is reached.
456 /// [`panic!`]: ../std/macro.panic.html
457 /// [`unreachable_unchecked`]: ../std/hint/fn.unreachable_unchecked.html
458 /// [`std::hint`]: ../std/hint/index.html
462 /// This will always [`panic!`]
464 /// [`panic!`]: ../std/macro.panic.html
470 /// # #[allow(dead_code)]
471 /// fn foo(x: Option<i32>) {
473 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
474 /// Some(n) if n < 0 => println!("Some(Negative)"),
475 /// Some(_) => unreachable!(), // compile error if commented out
476 /// None => println!("None")
484 /// # #[allow(dead_code)]
485 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
487 /// if 3*i < i { panic!("u32 overflow"); }
488 /// if x < 3*i { return i-1; }
494 #[stable(feature = "rust1", since = "1.0.0")]
495 macro_rules! unreachable {
497 panic!("internal error: entered unreachable code")
500 $crate::unreachable!("{}", $msg)
503 $crate::unreachable!($msg)
505 ($fmt:expr, $($arg:tt)*) => ({
506 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
510 /// Indicates unfinished code.
512 /// This can be useful if you are prototyping and are just looking to have your
513 /// code type-check, or if you're implementing a trait that requires multiple
514 /// methods, and you're only planning on using one of them.
518 /// This will always [panic!](macro.panic.html)
522 /// Here's an example of some in-progress code. We have a trait `Foo`:
531 /// We want to implement `Foo` on one of our types, but we also want to work on
532 /// just `bar()` first. In order for our code to compile, we need to implement
533 /// `baz()`, so we can use `unimplemented!`:
542 /// impl Foo for MyStruct {
544 /// // implementation goes here
548 /// // let's not worry about implementing baz() for now
549 /// unimplemented!();
554 /// let s = MyStruct;
557 /// // we aren't even using baz() yet, so this is fine.
561 #[stable(feature = "rust1", since = "1.0.0")]
562 macro_rules! unimplemented {
563 () => (panic!("not yet implemented"));
564 ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)+)));
567 /// Indicates unfinished code.
569 /// This can be useful if you are prototyping and are just looking to have your
570 /// code typecheck. `todo!` works exactly like `unimplemented!`. The only
571 /// difference between the two macros is the name.
575 /// This will always [panic!](macro.panic.html)
579 /// Here's an example of some in-progress code. We have a trait `Foo`:
588 /// We want to implement `Foo` on one of our types, but we also want to work on
589 /// just `bar()` first. In order for our code to compile, we need to implement
590 /// `baz()`, so we can use `todo!`:
593 /// #![feature(todo_macro)]
601 /// impl Foo for MyStruct {
603 /// // implementation goes here
607 /// // let's not worry about implementing baz() for now
613 /// let s = MyStruct;
616 /// // we aren't even using baz() yet, so this is fine.
620 #[unstable(feature = "todo_macro", issue = "59277")]
622 () => (panic!("not yet implemented"));
623 ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)+)));
626 /// Creates an array of [`MaybeUninit`].
628 /// This macro constructs an uninitialized array of the type `[MaybeUninit<K>; N]`.
629 /// It exists solely because bootstrap does not yet support const array-init expressions.
631 /// [`MaybeUninit`]: mem/union.MaybeUninit.html
632 // FIXME: Remove both versions of this macro once bootstrap is 1.38.
634 #[unstable(feature = "maybe_uninit_array", issue = "53491")]
636 macro_rules! uninit_array {
637 // This `assume_init` is safe because an array of `MaybeUninit` does not
638 // require initialization.
639 ($t:ty; $size:expr) => (unsafe {
640 MaybeUninit::<[MaybeUninit<$t>; $size]>::uninit().assume_init()
644 /// Creates an array of [`MaybeUninit`].
646 /// This macro constructs an uninitialized array of the type `[MaybeUninit<K>; N]`.
647 /// It exists solely because bootstrap does not yet support const array-init expressions.
649 /// [`MaybeUninit`]: mem/union.MaybeUninit.html
650 // FIXME: Just inline this version of the macro once bootstrap is 1.38.
652 #[unstable(feature = "maybe_uninit_array", issue = "53491")]
653 #[cfg(not(bootstrap))]
654 macro_rules! uninit_array {
655 ($t:ty; $size:expr) => (
656 [MaybeUninit::<$t>::UNINIT; $size]
660 /// Definitions of built-in macros.
662 /// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
663 /// with exception of expansion functions transforming macro inputs into outputs,
664 /// those functions are provided by the compiler.
665 #[cfg(not(bootstrap))]
666 pub(crate) mod builtin {
668 /// Causes compilation to fail with the given error message when encountered.
670 /// This macro should be used when a crate uses a conditional compilation strategy to provide
671 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
672 /// which emits an error at *runtime*, rather than during compilation.
676 /// Two such examples are macros and `#[cfg]` environments.
678 /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
679 /// the compiler would still emit an error, but the error's message would not mention the two
683 /// macro_rules! give_me_foo_or_bar {
687 /// compile_error!("This macro only accepts `foo` or `bar`");
691 /// give_me_foo_or_bar!(neither);
692 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
695 /// Emit compiler error if one of a number of features isn't available.
698 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
699 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
702 /// [`panic!`]: ../std/macro.panic.html
703 #[stable(feature = "compile_error_macro", since = "1.20.0")]
704 #[rustc_builtin_macro]
705 #[rustc_macro_transparency = "semitransparent"]
706 pub macro compile_error {
707 ($msg:expr) => ({ /* compiler built-in */ }),
708 ($msg:expr,) => ({ /* compiler built-in */ })
711 /// Constructs parameters for the other string-formatting macros.
713 /// This macro functions by taking a formatting string literal containing
714 /// `{}` for each additional argument passed. `format_args!` prepares the
715 /// additional parameters to ensure the output can be interpreted as a string
716 /// and canonicalizes the arguments into a single type. Any value that implements
717 /// the [`Display`] trait can be passed to `format_args!`, as can any
718 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
720 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
721 /// passed to the macros within [`std::fmt`] for performing useful redirection.
722 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
723 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
724 /// heap allocations.
726 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
727 /// in `Debug` and `Display` contexts as seen below. The example also shows
728 /// that `Debug` and `Display` format to the same thing: the interpolated
729 /// format string in `format_args!`.
732 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
733 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
734 /// assert_eq!("1 foo 2", display);
735 /// assert_eq!(display, debug);
738 /// For more information, see the documentation in [`std::fmt`].
740 /// [`Display`]: ../std/fmt/trait.Display.html
741 /// [`Debug`]: ../std/fmt/trait.Debug.html
742 /// [`fmt::Arguments`]: ../std/fmt/struct.Arguments.html
743 /// [`std::fmt`]: ../std/fmt/index.html
744 /// [`format!`]: ../std/macro.format.html
745 /// [`write!`]: ../std/macro.write.html
746 /// [`println!`]: ../std/macro.println.html
753 /// let s = fmt::format(format_args!("hello {}", "world"));
754 /// assert_eq!(s, format!("hello {}", "world"));
756 #[stable(feature = "rust1", since = "1.0.0")]
757 #[allow_internal_unstable(fmt_internals)]
758 #[rustc_builtin_macro]
759 #[rustc_macro_transparency = "semitransparent"]
760 pub macro format_args {
761 ($fmt:expr) => ({ /* compiler built-in */ }),
762 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ })
765 /// Same as `format_args`, but adds a newline in the end.
766 #[unstable(feature = "format_args_nl", issue = "0",
767 reason = "`format_args_nl` is only for internal \
768 language use and is subject to change")]
769 #[allow_internal_unstable(fmt_internals)]
770 #[rustc_builtin_macro]
771 #[rustc_macro_transparency = "semitransparent"]
772 pub macro format_args_nl {
773 ($fmt:expr) => ({ /* compiler built-in */ }),
774 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ })
777 /// Inspects an environment variable at compile time.
779 /// This macro will expand to the value of the named environment variable at
780 /// compile time, yielding an expression of type `&'static str`.
782 /// If the environment variable is not defined, then a compilation error
783 /// will be emitted. To not emit a compile error, use the [`option_env!`]
786 /// [`option_env!`]: ../std/macro.option_env.html
791 /// let path: &'static str = env!("PATH");
792 /// println!("the $PATH variable at the time of compiling was: {}", path);
795 /// You can customize the error message by passing a string as the second
799 /// let doc: &'static str = env!("documentation", "what's that?!");
802 /// If the `documentation` environment variable is not defined, you'll get
803 /// the following error:
806 /// error: what's that?!
808 #[stable(feature = "rust1", since = "1.0.0")]
809 #[rustc_builtin_macro]
810 #[rustc_macro_transparency = "semitransparent"]
812 ($name:expr) => ({ /* compiler built-in */ }),
813 ($name:expr,) => ({ /* compiler built-in */ })
816 /// Optionally inspects an environment variable at compile time.
818 /// If the named environment variable is present at compile time, this will
819 /// expand into an expression of type `Option<&'static str>` whose value is
820 /// `Some` of the value of the environment variable. If the environment
821 /// variable is not present, then this will expand to `None`. See
822 /// [`Option<T>`][option] for more information on this type.
824 /// A compile time error is never emitted when using this macro regardless
825 /// of whether the environment variable is present or not.
827 /// [option]: ../std/option/enum.Option.html
832 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
833 /// println!("the secret key might be: {:?}", key);
835 #[stable(feature = "rust1", since = "1.0.0")]
836 #[rustc_builtin_macro]
837 #[rustc_macro_transparency = "semitransparent"]
838 pub macro option_env {
839 ($name:expr) => ({ /* compiler built-in */ }),
840 ($name:expr,) => ({ /* compiler built-in */ })
843 /// Concatenates identifiers into one identifier.
845 /// This macro takes any number of comma-separated identifiers, and
846 /// concatenates them all into one, yielding an expression which is a new
847 /// identifier. Note that hygiene makes it such that this macro cannot
848 /// capture local variables. Also, as a general rule, macros are only
849 /// allowed in item, statement or expression position. That means while
850 /// you may use this macro for referring to existing variables, functions or
851 /// modules etc, you cannot define a new one with it.
856 /// #![feature(concat_idents)]
859 /// fn foobar() -> u32 { 23 }
861 /// let f = concat_idents!(foo, bar);
862 /// println!("{}", f());
864 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
867 #[unstable(feature = "concat_idents", issue = "29599",
868 reason = "`concat_idents` is not stable enough for use and is subject to change")]
869 #[rustc_builtin_macro]
870 #[rustc_macro_transparency = "semitransparent"]
871 pub macro concat_idents {
872 ($($e:ident),+) => ({ /* compiler built-in */ }),
873 ($($e:ident,)+) => ({ /* compiler built-in */ })
876 /// Concatenates literals into a static string slice.
878 /// This macro takes any number of comma-separated literals, yielding an
879 /// expression of type `&'static str` which represents all of the literals
880 /// concatenated left-to-right.
882 /// Integer and floating point literals are stringified in order to be
888 /// let s = concat!("test", 10, 'b', true);
889 /// assert_eq!(s, "test10btrue");
891 #[stable(feature = "rust1", since = "1.0.0")]
892 #[rustc_builtin_macro]
893 #[rustc_macro_transparency = "semitransparent"]
895 ($($e:expr),*) => ({ /* compiler built-in */ }),
896 ($($e:expr,)*) => ({ /* compiler built-in */ })
899 /// Expands to the line number on which it was invoked.
901 /// With [`column!`] and [`file!`], these macros provide debugging information for
902 /// developers about the location within the source.
904 /// The expanded expression has type `u32` and is 1-based, so the first line
905 /// in each file evaluates to 1, the second to 2, etc. This is consistent
906 /// with error messages by common compilers or popular editors.
907 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
908 /// but rather the first macro invocation leading up to the invocation
909 /// of the `line!` macro.
911 /// [`column!`]: macro.column.html
912 /// [`file!`]: macro.file.html
917 /// let current_line = line!();
918 /// println!("defined on line: {}", current_line);
920 #[stable(feature = "rust1", since = "1.0.0")]
921 #[rustc_builtin_macro]
922 #[rustc_macro_transparency = "semitransparent"]
923 pub macro line() { /* compiler built-in */ }
925 /// Expands to the column number at which it was invoked.
927 /// With [`line!`] and [`file!`], these macros provide debugging information for
928 /// developers about the location within the source.
930 /// The expanded expression has type `u32` and is 1-based, so the first column
931 /// in each line evaluates to 1, the second to 2, etc. This is consistent
932 /// with error messages by common compilers or popular editors.
933 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
934 /// but rather the first macro invocation leading up to the invocation
935 /// of the `column!` macro.
937 /// [`line!`]: macro.line.html
938 /// [`file!`]: macro.file.html
943 /// let current_col = column!();
944 /// println!("defined on column: {}", current_col);
946 #[stable(feature = "rust1", since = "1.0.0")]
947 #[rustc_builtin_macro]
948 #[rustc_macro_transparency = "semitransparent"]
949 pub macro column() { /* compiler built-in */ }
951 /// Same as `column`, but less likely to be shadowed.
952 #[unstable(feature = "__rust_unstable_column", issue = "0",
953 reason = "internal implementation detail of the `panic` macro")]
954 #[rustc_builtin_macro]
955 #[rustc_macro_transparency = "semitransparent"]
956 pub macro __rust_unstable_column() { /* compiler built-in */ }
958 /// Expands to the file name in which it was invoked.
960 /// With [`line!`] and [`column!`], these macros provide debugging information for
961 /// developers about the location within the source.
964 /// The expanded expression has type `&'static str`, and the returned file
965 /// is not the invocation of the `file!` macro itself, but rather the
966 /// first macro invocation leading up to the invocation of the `file!`
969 /// [`line!`]: macro.line.html
970 /// [`column!`]: macro.column.html
975 /// let this_file = file!();
976 /// println!("defined in file: {}", this_file);
978 #[stable(feature = "rust1", since = "1.0.0")]
979 #[rustc_builtin_macro]
980 #[rustc_macro_transparency = "semitransparent"]
981 pub macro file() { /* compiler built-in */ }
983 /// Stringifies its arguments.
985 /// This macro will yield an expression of type `&'static str` which is the
986 /// stringification of all the tokens passed to the macro. No restrictions
987 /// are placed on the syntax of the macro invocation itself.
989 /// Note that the expanded results of the input tokens may change in the
990 /// future. You should be careful if you rely on the output.
995 /// let one_plus_one = stringify!(1 + 1);
996 /// assert_eq!(one_plus_one, "1 + 1");
998 #[stable(feature = "rust1", since = "1.0.0")]
999 #[rustc_builtin_macro]
1000 #[rustc_macro_transparency = "semitransparent"]
1001 pub macro stringify($($t:tt)*) { /* compiler built-in */ }
1003 /// Includes a utf8-encoded file as a string.
1005 /// The file is located relative to the current file. (similarly to how
1006 /// modules are found)
1008 /// This macro will yield an expression of type `&'static str` which is the
1009 /// contents of the file.
1013 /// Assume there are two files in the same directory with the following
1016 /// File 'spanish.in':
1024 /// ```ignore (cannot-doctest-external-file-dependency)
1026 /// let my_str = include_str!("spanish.in");
1027 /// assert_eq!(my_str, "adiós\n");
1028 /// print!("{}", my_str);
1032 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 #[rustc_builtin_macro]
1035 #[rustc_macro_transparency = "semitransparent"]
1036 pub macro include_str {
1037 ($file:expr) => ({ /* compiler built-in */ }),
1038 ($file:expr,) => ({ /* compiler built-in */ })
1041 /// Includes a file as a reference to a byte array.
1043 /// The file is located relative to the current file. (similarly to how
1044 /// modules are found)
1046 /// This macro will yield an expression of type `&'static [u8; N]` which is
1047 /// the contents of the file.
1051 /// Assume there are two files in the same directory with the following
1054 /// File 'spanish.in':
1062 /// ```ignore (cannot-doctest-external-file-dependency)
1064 /// let bytes = include_bytes!("spanish.in");
1065 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
1066 /// print!("{}", String::from_utf8_lossy(bytes));
1070 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1071 #[stable(feature = "rust1", since = "1.0.0")]
1072 #[rustc_builtin_macro]
1073 #[rustc_macro_transparency = "semitransparent"]
1074 pub macro include_bytes {
1075 ($file:expr) => ({ /* compiler built-in */ }),
1076 ($file:expr,) => ({ /* compiler built-in */ })
1079 /// Expands to a string that represents the current module path.
1081 /// The current module path can be thought of as the hierarchy of modules
1082 /// leading back up to the crate root. The first component of the path
1083 /// returned is the name of the crate currently being compiled.
1090 /// assert!(module_path!().ends_with("test"));
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 #[rustc_builtin_macro]
1098 #[rustc_macro_transparency = "semitransparent"]
1099 pub macro module_path() { /* compiler built-in */ }
1101 /// Evaluates boolean combinations of configuration flags at compile-time.
1103 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1104 /// boolean expression evaluation of configuration flags. This frequently
1105 /// leads to less duplicated code.
1107 /// The syntax given to this macro is the same syntax as the [`cfg`]
1110 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1115 /// let my_directory = if cfg!(windows) {
1116 /// "windows-specific-directory"
1118 /// "unix-directory"
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 #[rustc_builtin_macro]
1123 #[rustc_macro_transparency = "semitransparent"]
1124 pub macro cfg($($cfg:tt)*) { /* compiler built-in */ }
1126 /// Parses a file as an expression or an item according to the context.
1128 /// The file is located relative to the current file (similarly to how
1129 /// modules are found).
1131 /// Using this macro is often a bad idea, because if the file is
1132 /// parsed as an expression, it is going to be placed in the
1133 /// surrounding code unhygienically. This could result in variables
1134 /// or functions being different from what the file expected if
1135 /// there are variables or functions that have the same name in
1136 /// the current file.
1140 /// Assume there are two files in the same directory with the following
1143 /// File 'monkeys.in':
1145 /// ```ignore (only-for-syntax-highlight)
1146 /// ['🙈', '🙊', '🙉']
1150 /// .collect::<String>()
1155 /// ```ignore (cannot-doctest-external-file-dependency)
1157 /// let my_string = include!("monkeys.in");
1158 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1159 /// println!("{}", my_string);
1163 /// Compiling 'main.rs' and running the resulting binary will print
1164 /// "🙈🙊🙉🙈🙊🙉".
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 #[rustc_builtin_macro]
1167 #[rustc_macro_transparency = "semitransparent"]
1169 ($file:expr) => ({ /* compiler built-in */ }),
1170 ($file:expr,) => ({ /* compiler built-in */ })
1173 /// Asserts that a boolean expression is `true` at runtime.
1175 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1176 /// evaluated to `true` at runtime.
1180 /// Assertions are always checked in both debug and release builds, and cannot
1181 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1182 /// release builds by default.
1184 /// Unsafe code relies on `assert!` to enforce run-time invariants that, if
1185 /// violated could lead to unsafety.
1187 /// Other use-cases of `assert!` include testing and enforcing run-time
1188 /// invariants in safe code (whose violation cannot result in unsafety).
1190 /// # Custom Messages
1192 /// This macro has a second form, where a custom panic message can
1193 /// be provided with or without arguments for formatting. See [`std::fmt`]
1194 /// for syntax for this form.
1196 /// [`panic!`]: macro.panic.html
1197 /// [`debug_assert!`]: macro.debug_assert.html
1198 /// [`std::fmt`]: ../std/fmt/index.html
1203 /// // the panic message for these assertions is the stringified value of the
1204 /// // expression given.
1207 /// fn some_computation() -> bool { true } // a very simple function
1209 /// assert!(some_computation());
1211 /// // assert with a custom message
1213 /// assert!(x, "x wasn't true!");
1215 /// let a = 3; let b = 27;
1216 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 #[rustc_builtin_macro]
1220 #[rustc_macro_transparency = "semitransparent"]
1222 ($cond:expr) => ({ /* compiler built-in */ }),
1223 ($cond:expr,) => ({ /* compiler built-in */ }),
1224 ($cond:expr, $($arg:tt)+) => ({ /* compiler built-in */ })
1227 /// Inline assembly.
1228 #[unstable(feature = "asm", issue = "29722",
1229 reason = "inline assembly is not stable enough for use and is subject to change")]
1230 #[rustc_builtin_macro]
1231 #[rustc_macro_transparency = "semitransparent"]
1232 pub macro asm("assembly template"
1233 : $("output"(operand),)*
1234 : $("input"(operand),)*
1236 : $("options",)*) { /* compiler built-in */ }
1238 /// Module-level inline assembly.
1239 #[unstable(feature = "global_asm", issue = "35119",
1240 reason = "`global_asm!` is not stable enough for use and is subject to change")]
1241 #[rustc_builtin_macro]
1242 #[rustc_macro_transparency = "semitransparent"]
1243 pub macro global_asm("assembly") { /* compiler built-in */ }
1245 /// Prints passed tokens into the standard output.
1246 #[unstable(feature = "log_syntax", issue = "29598",
1247 reason = "`log_syntax!` is not stable enough for use and is subject to change")]
1248 #[rustc_builtin_macro]
1249 #[rustc_macro_transparency = "semitransparent"]
1250 pub macro log_syntax($($arg:tt)*) { /* compiler built-in */ }
1252 /// Enables or disables tracing functionality used for debugging other macros.
1253 #[unstable(feature = "trace_macros", issue = "29598",
1254 reason = "`trace_macros` is not stable enough for use and is subject to change")]
1255 #[rustc_builtin_macro]
1256 #[rustc_macro_transparency = "semitransparent"]
1257 pub macro trace_macros {
1258 (true) => ({ /* compiler built-in */ }),
1259 (false) => ({ /* compiler built-in */ })
1262 /// Attribute macro applied to a function to turn it into a unit test.
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 #[allow_internal_unstable(test, rustc_attrs)]
1265 #[rustc_builtin_macro]
1266 #[rustc_macro_transparency = "semitransparent"]
1267 pub macro test($item:item) { /* compiler built-in */ }
1269 /// Attribute macro applied to a function to turn it into a benchmark test.
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 #[allow_internal_unstable(test, rustc_attrs)]
1272 #[rustc_builtin_macro]
1273 #[rustc_macro_transparency = "semitransparent"]
1274 pub macro bench($item:item) { /* compiler built-in */ }
1276 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1277 #[unstable(feature = "custom_test_frameworks", issue = "50297",
1278 reason = "custom test frameworks are an unstable feature")]
1279 #[allow_internal_unstable(test, rustc_attrs)]
1280 #[rustc_builtin_macro]
1281 #[rustc_macro_transparency = "semitransparent"]
1282 pub macro test_case($item:item) { /* compiler built-in */ }
1284 /// Attribute macro applied to a static to register it as a global allocator.
1285 #[stable(feature = "global_allocator", since = "1.28.0")]
1286 #[allow_internal_unstable(rustc_attrs)]
1287 #[rustc_builtin_macro]
1288 #[rustc_macro_transparency = "semitransparent"]
1289 pub macro global_allocator($item:item) { /* compiler built-in */ }
1291 /// Derive macro generating an impl of the trait `Clone`.
1292 #[rustc_builtin_macro]
1293 #[rustc_macro_transparency = "semitransparent"]
1294 #[stable(feature = "rust1", since = "1.0.0")]
1295 #[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
1296 pub macro Clone($item:item) { /* compiler built-in */ }
1298 /// Derive macro generating an impl of the trait `Copy`.
1299 #[rustc_builtin_macro]
1300 #[rustc_macro_transparency = "semitransparent"]
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 #[allow_internal_unstable(core_intrinsics, derive_clone_copy)]
1303 pub macro Copy($item:item) { /* compiler built-in */ }
1305 /// Derive macro generating an impl of the trait `Debug`.
1306 #[rustc_builtin_macro]
1307 #[rustc_macro_transparency = "semitransparent"]
1308 #[stable(feature = "rust1", since = "1.0.0")]
1309 #[allow_internal_unstable(core_intrinsics)]
1310 pub macro Debug($item:item) { /* compiler built-in */ }
1312 /// Unstable implementation detail of the `rustc` compiler, do not use.
1313 #[rustc_builtin_macro]
1314 #[rustc_macro_transparency = "semitransparent"]
1315 #[stable(feature = "rust1", since = "1.0.0")]
1318 reason = "derive(Decodable) is deprecated in favor of derive(RustcDecodable)",
1319 suggestion = "RustcDecodable",
1321 #[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
1322 pub macro Decodable($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 /// Unstable implementation detail of the `rustc` compiler, do not use.
1332 #[rustc_builtin_macro]
1333 #[rustc_macro_transparency = "semitransparent"]
1334 #[stable(feature = "rust1", since = "1.0.0")]
1337 reason = "derive(Encodable) is deprecated in favor of derive(RustcEncodable)",
1338 suggestion = "RustcEncodable",
1340 #[allow_internal_unstable(core_intrinsics)]
1341 pub macro Encodable($item:item) { /* compiler built-in */ }
1343 /// Derive macro generating an impl of the trait `Eq`.
1344 #[rustc_builtin_macro]
1345 #[rustc_macro_transparency = "semitransparent"]
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 #[allow_internal_unstable(core_intrinsics, derive_eq)]
1348 pub macro Eq($item:item) { /* compiler built-in */ }
1350 /// Derive macro generating an impl of the trait `Hash`.
1351 #[rustc_builtin_macro]
1352 #[rustc_macro_transparency = "semitransparent"]
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 #[allow_internal_unstable(core_intrinsics)]
1355 pub macro Hash($item:item) { /* compiler built-in */ }
1357 /// Derive macro generating an impl of the trait `Ord`.
1358 #[rustc_builtin_macro]
1359 #[rustc_macro_transparency = "semitransparent"]
1360 #[stable(feature = "rust1", since = "1.0.0")]
1361 #[allow_internal_unstable(core_intrinsics)]
1362 pub macro Ord($item:item) { /* compiler built-in */ }
1364 /// Derive macro generating an impl of the trait `PartialEq`.
1365 #[rustc_builtin_macro]
1366 #[rustc_macro_transparency = "semitransparent"]
1367 #[stable(feature = "rust1", since = "1.0.0")]
1368 #[allow_internal_unstable(core_intrinsics)]
1369 pub macro PartialEq($item:item) { /* compiler built-in */ }
1371 /// Derive macro generating an impl of the trait `PartialOrd`.
1372 #[rustc_builtin_macro]
1373 #[rustc_macro_transparency = "semitransparent"]
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 #[allow_internal_unstable(core_intrinsics)]
1376 pub macro PartialOrd($item:item) { /* compiler built-in */ }
1378 /// Unstable implementation detail of the `rustc` compiler, do not use.
1379 #[rustc_builtin_macro]
1380 #[rustc_macro_transparency = "semitransparent"]
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 #[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
1383 pub macro RustcDecodable($item:item) { /* compiler built-in */ }
1385 /// Unstable implementation detail of the `rustc` compiler, do not use.
1386 #[rustc_builtin_macro]
1387 #[rustc_macro_transparency = "semitransparent"]
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 #[allow_internal_unstable(core_intrinsics)]
1390 pub macro RustcEncodable($item:item) { /* compiler built-in */ }