1 #[doc(include = "panic.md")]
3 #[allow_internal_unstable(core_panic, track_caller)]
4 #[stable(feature = "core", since = "1.6.0")]
7 $crate::panic!("explicit panic")
10 $crate::panicking::panic($msg)
15 ($fmt:expr, $($arg:tt)+) => (
16 $crate::panicking::panic_fmt(
17 $crate::format_args!($fmt, $($arg)+),
18 $crate::panic::Location::caller(),
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 $crate::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 $crate::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 $crate::cfg!(debug_assertions) { $crate::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 $crate::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 $crate::cfg!(debug_assertions) { $crate::assert_ne!($($arg)*); })
241 /// Returns whether the given expression matches any of the given patterns.
243 /// Like in a `match` expression, the pattern can be optionally followed by `if`
244 /// and a guard expression that has access to names bound by the pattern.
250 /// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
252 /// let bar = Some(4);
253 /// assert!(matches!(bar, Some(x) if x > 2));
256 #[stable(feature = "matches_macro", since = "1.42.0")]
257 macro_rules! matches {
258 ($expression:expr, $( $pattern:pat )|+ $( if $guard: expr )?) => {
260 $( $pattern )|+ $( if $guard )? => true,
266 /// Unwraps a result or propagates its error.
268 /// The `?` operator was added to replace `try!` and should be used instead.
269 /// Furthermore, `try` is a reserved word in Rust 2018, so if you must use
270 /// it, you will need to use the [raw-identifier syntax][ris]: `r#try`.
272 /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
274 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
275 /// expression has the value of the wrapped value.
277 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
278 /// performs conversion using `From`. This provides automatic conversion
279 /// between specialized errors and more general ones. The resulting
280 /// error is then immediately returned.
282 /// Because of the early return, `try!` can only be used in functions that
283 /// return [`Result`].
285 /// [`Result`]: ../std/result/enum.Result.html
291 /// use std::fs::File;
292 /// use std::io::prelude::*;
298 /// impl From<io::Error> for MyError {
299 /// fn from(e: io::Error) -> MyError {
300 /// MyError::FileWriteError
304 /// // The preferred method of quick returning Errors
305 /// fn write_to_file_question() -> Result<(), MyError> {
306 /// let mut file = File::create("my_best_friends.txt")?;
307 /// file.write_all(b"This is a list of my best friends.")?;
311 /// // The previous method of quick returning Errors
312 /// fn write_to_file_using_try() -> Result<(), MyError> {
313 /// let mut file = r#try!(File::create("my_best_friends.txt"));
314 /// r#try!(file.write_all(b"This is a list of my best friends."));
318 /// // This is equivalent to:
319 /// fn write_to_file_using_match() -> Result<(), MyError> {
320 /// let mut file = r#try!(File::create("my_best_friends.txt"));
321 /// match file.write_all(b"This is a list of my best friends.") {
323 /// Err(e) => return Err(From::from(e)),
329 #[stable(feature = "rust1", since = "1.0.0")]
330 #[rustc_deprecated(since = "1.39.0", reason = "use the `?` operator instead")]
335 $crate::result::Result::Ok(val) => val,
336 $crate::result::Result::Err(err) => {
337 return $crate::result::Result::Err($crate::convert::From::from(err));
342 $crate::r#try!($expr)
346 /// Writes formatted data into a buffer.
348 /// This macro accepts a format string, a list of arguments, and a 'writer'. Arguments will be
349 /// formatted according to the specified format string and the result will be passed to the writer.
350 /// The writer may be any value with a `write_fmt` method; generally this comes from an
351 /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro
352 /// returns whatever the `write_fmt` method returns; commonly a [`std::fmt::Result`], or an
355 /// See [`std::fmt`] for more information on the format string syntax.
357 /// [`std::fmt`]: ../std/fmt/index.html
358 /// [`std::fmt::Write`]: ../std/fmt/trait.Write.html
359 /// [`std::io::Write`]: ../std/io/trait.Write.html
360 /// [`std::fmt::Result`]: ../std/fmt/type.Result.html
361 /// [`io::Result`]: ../std/io/type.Result.html
366 /// use std::io::Write;
368 /// fn main() -> std::io::Result<()> {
369 /// let mut w = Vec::new();
370 /// write!(&mut w, "test")?;
371 /// write!(&mut w, "formatted {}", "arguments")?;
373 /// assert_eq!(w, b"testformatted arguments");
378 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
379 /// implementing either, as objects do not typically implement both. However, the module must
380 /// import the traits qualified so their names do not conflict:
383 /// use std::fmt::Write as FmtWrite;
384 /// use std::io::Write as IoWrite;
386 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
387 /// let mut s = String::new();
388 /// let mut v = Vec::new();
390 /// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
391 /// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
392 /// assert_eq!(v, b"s = \"abc 123\"");
397 /// Note: This macro can be used in `no_std` setups as well.
398 /// In a `no_std` setup you are responsible for the implementation details of the components.
401 /// # extern crate core;
402 /// use core::fmt::Write;
406 /// impl Write for Example {
407 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
408 /// unimplemented!();
412 /// let mut m = Example{};
413 /// write!(&mut m, "Hello World").expect("Not written");
416 #[stable(feature = "rust1", since = "1.0.0")]
418 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt($crate::format_args!($($arg)*)))
421 /// Write formatted data into a buffer, with a newline appended.
423 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
424 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
426 /// For more information, see [`write!`]. For information on the format string syntax, see
429 /// [`write!`]: macro.write.html
430 /// [`std::fmt`]: ../std/fmt/index.html
436 /// use std::io::{Write, Result};
438 /// fn main() -> Result<()> {
439 /// let mut w = Vec::new();
440 /// writeln!(&mut w)?;
441 /// writeln!(&mut w, "test")?;
442 /// writeln!(&mut w, "formatted {}", "arguments")?;
444 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
449 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
450 /// implementing either, as objects do not typically implement both. However, the module must
451 /// import the traits qualified so their names do not conflict:
454 /// use std::fmt::Write as FmtWrite;
455 /// use std::io::Write as IoWrite;
457 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
458 /// let mut s = String::new();
459 /// let mut v = Vec::new();
461 /// writeln!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
462 /// writeln!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
463 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
468 #[stable(feature = "rust1", since = "1.0.0")]
469 #[allow_internal_unstable(format_args_nl)]
470 macro_rules! writeln {
472 $crate::write!($dst, "\n")
475 $crate::writeln!($dst)
477 ($dst:expr, $($arg:tt)*) => (
478 $dst.write_fmt($crate::format_args_nl!($($arg)*))
482 /// Indicates unreachable code.
484 /// This is useful any time that the compiler can't determine that some code is unreachable. For
487 /// * Match arms with guard conditions.
488 /// * Loops that dynamically terminate.
489 /// * Iterators that dynamically terminate.
491 /// If the determination that the code is unreachable proves incorrect, the
492 /// program immediately terminates with a [`panic!`].
494 /// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
495 /// will cause undefined behavior if the code is reached.
497 /// [`panic!`]: ../std/macro.panic.html
498 /// [`unreachable_unchecked`]: ../std/hint/fn.unreachable_unchecked.html
499 /// [`std::hint`]: ../std/hint/index.html
503 /// This will always [`panic!`]
505 /// [`panic!`]: ../std/macro.panic.html
512 /// # #[allow(dead_code)]
513 /// fn foo(x: Option<i32>) {
515 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
516 /// Some(n) if n < 0 => println!("Some(Negative)"),
517 /// Some(_) => unreachable!(), // compile error if commented out
518 /// None => println!("None")
526 /// # #[allow(dead_code)]
527 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
529 /// if 3*i < i { panic!("u32 overflow"); }
530 /// if x < 3*i { return i-1; }
536 #[stable(feature = "rust1", since = "1.0.0")]
537 macro_rules! unreachable {
539 panic!("internal error: entered unreachable code")
542 $crate::unreachable!("{}", $msg)
545 $crate::unreachable!($msg)
547 ($fmt:expr, $($arg:tt)*) => ({
548 panic!($crate::concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
552 /// Indicates unimplemented code by panicking with a message of "not implemented".
554 /// This allows your code to type-check, which is useful if you are prototyping or
555 /// implementing a trait that requires multiple methods which you don't plan of using all of.
557 /// The difference between `unimplemented!` and [`todo!`](macro.todo.html) is that while `todo!`
558 /// conveys an intent of implementing the functionality later and the message is "not yet
559 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
560 /// Also some IDEs will mark `todo!`s.
564 /// This will always [panic!](macro.panic.html) because `unimplemented!` is just a
565 /// shorthand for `panic!` with a fixed, specific message.
567 /// Like `panic!`, this macro has a second form for displaying custom values.
571 /// Say we have a trait `Foo`:
575 /// fn bar(&self) -> u8;
577 /// fn qux(&self) -> Result<u64, ()>;
581 /// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
582 /// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
583 /// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
584 /// to allow our code to compile.
586 /// We still want to have our program stop running if the unimplemented methods are
591 /// # fn bar(&self) -> u8;
593 /// # fn qux(&self) -> Result<u64, ()>;
597 /// impl Foo for MyStruct {
598 /// fn bar(&self) -> u8 {
603 /// // It makes no sense to `baz` a `MyStruct`, so we have no logic here
605 /// // This will display "thread 'main' panicked at 'not implemented'".
606 /// unimplemented!();
609 /// fn qux(&self) -> Result<u64, ()> {
610 /// // We have some logic here,
611 /// // We can add a message to unimplemented! to display our omission.
612 /// // This will display:
613 /// // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
614 /// unimplemented!("MyStruct isn't quxable");
619 /// let s = MyStruct;
624 #[stable(feature = "rust1", since = "1.0.0")]
625 macro_rules! unimplemented {
626 () => (panic!("not implemented"));
627 ($($arg:tt)+) => (panic!("not implemented: {}", $crate::format_args!($($arg)+)));
630 /// Indicates unfinished code.
632 /// This can be useful if you are prototyping and are just looking to have your
635 /// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
636 /// an intent of implementing the functionality later and the message is "not yet
637 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
638 /// Also some IDEs will mark `todo!`s.
640 /// [`unimplemented!`]: macro.unimplemented.html
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(), so this is fine.
687 #[stable(feature = "todo_macro", since = "1.40.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.
799 feature = "format_args_nl",
801 reason = "`format_args_nl` is only for internal \
802 language use and is subject to change"
804 #[allow_internal_unstable(fmt_internals)]
805 #[rustc_builtin_macro]
807 macro_rules! format_args_nl {
808 ($fmt:expr) => {{ /* compiler built-in */ }};
809 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
812 /// Inspects an environment variable at compile time.
814 /// This macro will expand to the value of the named environment variable at
815 /// compile time, yielding an expression of type `&'static str`.
817 /// If the environment variable is not defined, then a compilation error
818 /// will be emitted. To not emit a compile error, use the [`option_env!`]
821 /// [`option_env!`]: ../std/macro.option_env.html
826 /// let path: &'static str = env!("PATH");
827 /// println!("the $PATH variable at the time of compiling was: {}", path);
830 /// You can customize the error message by passing a string as the second
834 /// let doc: &'static str = env!("documentation", "what's that?!");
837 /// If the `documentation` environment variable is not defined, you'll get
838 /// the following error:
841 /// error: what's that?!
843 #[stable(feature = "rust1", since = "1.0.0")]
844 #[rustc_builtin_macro]
847 ($name:expr) => {{ /* compiler built-in */ }};
848 ($name:expr,) => {{ /* compiler built-in */ }};
851 /// Optionally inspects an environment variable at compile time.
853 /// If the named environment variable is present at compile time, this will
854 /// expand into an expression of type `Option<&'static str>` whose value is
855 /// `Some` of the value of the environment variable. If the environment
856 /// variable is not present, then this will expand to `None`. See
857 /// [`Option<T>`][option] for more information on this type.
859 /// A compile time error is never emitted when using this macro regardless
860 /// of whether the environment variable is present or not.
862 /// [option]: ../std/option/enum.Option.html
867 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
868 /// println!("the secret key might be: {:?}", key);
870 #[stable(feature = "rust1", since = "1.0.0")]
871 #[rustc_builtin_macro]
873 macro_rules! option_env {
874 ($name:expr) => {{ /* compiler built-in */ }};
875 ($name:expr,) => {{ /* compiler built-in */ }};
878 /// Concatenates identifiers into one identifier.
880 /// This macro takes any number of comma-separated identifiers, and
881 /// concatenates them all into one, yielding an expression which is a new
882 /// identifier. Note that hygiene makes it such that this macro cannot
883 /// capture local variables. Also, as a general rule, macros are only
884 /// allowed in item, statement or expression position. That means while
885 /// you may use this macro for referring to existing variables, functions or
886 /// modules etc, you cannot define a new one with it.
891 /// #![feature(concat_idents)]
894 /// fn foobar() -> u32 { 23 }
896 /// let f = concat_idents!(foo, bar);
897 /// println!("{}", f());
899 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
903 feature = "concat_idents",
905 reason = "`concat_idents` is not stable enough for use and is subject to change"
907 #[rustc_builtin_macro]
909 macro_rules! concat_idents {
910 ($($e:ident),+) => {{ /* compiler built-in */ }};
911 ($($e:ident,)+) => {{ /* compiler built-in */ }};
914 /// Concatenates literals into a static string slice.
916 /// This macro takes any number of comma-separated literals, yielding an
917 /// expression of type `&'static str` which represents all of the literals
918 /// concatenated left-to-right.
920 /// Integer and floating point literals are stringified in order to be
926 /// let s = concat!("test", 10, 'b', true);
927 /// assert_eq!(s, "test10btrue");
929 #[stable(feature = "rust1", since = "1.0.0")]
930 #[rustc_builtin_macro]
932 macro_rules! concat {
933 ($($e:expr),*) => {{ /* compiler built-in */ }};
934 ($($e:expr,)*) => {{ /* compiler built-in */ }};
937 /// Expands to the line number on which it was invoked.
939 /// With [`column!`] and [`file!`], these macros provide debugging information for
940 /// developers about the location within the source.
942 /// The expanded expression has type `u32` and is 1-based, so the first line
943 /// in each file evaluates to 1, the second to 2, etc. This is consistent
944 /// with error messages by common compilers or popular editors.
945 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
946 /// but rather the first macro invocation leading up to the invocation
947 /// of the `line!` macro.
949 /// [`column!`]: macro.column.html
950 /// [`file!`]: macro.file.html
955 /// let current_line = line!();
956 /// println!("defined on line: {}", current_line);
958 #[stable(feature = "rust1", since = "1.0.0")]
959 #[rustc_builtin_macro]
963 /* compiler built-in */
967 /// Expands to the column number at which it was invoked.
969 /// With [`line!`] and [`file!`], these macros provide debugging information for
970 /// developers about the location within the source.
972 /// The expanded expression has type `u32` and is 1-based, so the first column
973 /// in each line evaluates to 1, the second to 2, etc. This is consistent
974 /// with error messages by common compilers or popular editors.
975 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
976 /// but rather the first macro invocation leading up to the invocation
977 /// of the `column!` macro.
979 /// [`line!`]: macro.line.html
980 /// [`file!`]: macro.file.html
985 /// let current_col = column!();
986 /// println!("defined on column: {}", current_col);
988 #[stable(feature = "rust1", since = "1.0.0")]
989 #[rustc_builtin_macro]
991 macro_rules! column {
993 /* compiler built-in */
997 /// Expands to the file name in which it was invoked.
999 /// With [`line!`] and [`column!`], these macros provide debugging information for
1000 /// developers about the location within the source.
1003 /// The expanded expression has type `&'static str`, and the returned file
1004 /// is not the invocation of the `file!` macro itself, but rather the
1005 /// first macro invocation leading up to the invocation of the `file!`
1008 /// [`line!`]: macro.line.html
1009 /// [`column!`]: macro.column.html
1014 /// let this_file = file!();
1015 /// println!("defined in file: {}", this_file);
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 #[rustc_builtin_macro]
1022 /* compiler built-in */
1026 /// Stringifies its arguments.
1028 /// This macro will yield an expression of type `&'static str` which is the
1029 /// stringification of all the tokens passed to the macro. No restrictions
1030 /// are placed on the syntax of the macro invocation itself.
1032 /// Note that the expanded results of the input tokens may change in the
1033 /// future. You should be careful if you rely on the output.
1038 /// let one_plus_one = stringify!(1 + 1);
1039 /// assert_eq!(one_plus_one, "1 + 1");
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 #[rustc_builtin_macro]
1044 macro_rules! stringify {
1046 /* compiler built-in */
1050 /// Includes a utf8-encoded file as a string.
1052 /// The file is located relative to the current file. (similarly to how
1053 /// modules are found)
1055 /// This macro will yield an expression of type `&'static str` which is the
1056 /// contents of the file.
1060 /// Assume there are two files in the same directory with the following
1063 /// File 'spanish.in':
1071 /// ```ignore (cannot-doctest-external-file-dependency)
1073 /// let my_str = include_str!("spanish.in");
1074 /// assert_eq!(my_str, "adiós\n");
1075 /// print!("{}", my_str);
1079 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 #[rustc_builtin_macro]
1083 macro_rules! include_str {
1084 ($file:expr) => {{ /* compiler built-in */ }};
1085 ($file:expr,) => {{ /* compiler built-in */ }};
1088 /// Includes a file as a reference to a byte array.
1090 /// The file is located relative to the current file. (similarly to how
1091 /// modules are found)
1093 /// This macro will yield an expression of type `&'static [u8; N]` which is
1094 /// the contents of the file.
1098 /// Assume there are two files in the same directory with the following
1101 /// File 'spanish.in':
1109 /// ```ignore (cannot-doctest-external-file-dependency)
1111 /// let bytes = include_bytes!("spanish.in");
1112 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
1113 /// print!("{}", String::from_utf8_lossy(bytes));
1117 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 #[rustc_builtin_macro]
1121 macro_rules! include_bytes {
1122 ($file:expr) => {{ /* compiler built-in */ }};
1123 ($file:expr,) => {{ /* compiler built-in */ }};
1126 /// Expands to a string that represents the current module path.
1128 /// The current module path can be thought of as the hierarchy of modules
1129 /// leading back up to the crate root. The first component of the path
1130 /// returned is the name of the crate currently being compiled.
1137 /// assert!(module_path!().ends_with("test"));
1143 #[stable(feature = "rust1", since = "1.0.0")]
1144 #[rustc_builtin_macro]
1146 macro_rules! module_path {
1148 /* compiler built-in */
1152 /// Evaluates boolean combinations of configuration flags at compile-time.
1154 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1155 /// boolean expression evaluation of configuration flags. This frequently
1156 /// leads to less duplicated code.
1158 /// The syntax given to this macro is the same syntax as the [`cfg`]
1161 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1166 /// let my_directory = if cfg!(windows) {
1167 /// "windows-specific-directory"
1169 /// "unix-directory"
1172 #[stable(feature = "rust1", since = "1.0.0")]
1173 #[rustc_builtin_macro]
1177 /* compiler built-in */
1181 /// Parses a file as an expression or an item according to the context.
1183 /// The file is located relative to the current file (similarly to how
1184 /// modules are found).
1186 /// Using this macro is often a bad idea, because if the file is
1187 /// parsed as an expression, it is going to be placed in the
1188 /// surrounding code unhygienically. This could result in variables
1189 /// or functions being different from what the file expected if
1190 /// there are variables or functions that have the same name in
1191 /// the current file.
1195 /// Assume there are two files in the same directory with the following
1198 /// File 'monkeys.in':
1200 /// ```ignore (only-for-syntax-highlight)
1201 /// ['🙈', '🙊', '🙉']
1205 /// .collect::<String>()
1210 /// ```ignore (cannot-doctest-external-file-dependency)
1212 /// let my_string = include!("monkeys.in");
1213 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1214 /// println!("{}", my_string);
1218 /// Compiling 'main.rs' and running the resulting binary will print
1219 /// "🙈🙊🙉🙈🙊🙉".
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 #[rustc_builtin_macro]
1223 macro_rules! include {
1224 ($file:expr) => {{ /* compiler built-in */ }};
1225 ($file:expr,) => {{ /* compiler built-in */ }};
1228 /// Asserts that a boolean expression is `true` at runtime.
1230 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1231 /// evaluated to `true` at runtime.
1235 /// Assertions are always checked in both debug and release builds, and cannot
1236 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1237 /// release builds by default.
1239 /// Unsafe code relies on `assert!` to enforce run-time invariants that, if
1240 /// violated could lead to unsafety.
1242 /// Other use-cases of `assert!` include testing and enforcing run-time
1243 /// invariants in safe code (whose violation cannot result in unsafety).
1245 /// # Custom Messages
1247 /// This macro has a second form, where a custom panic message can
1248 /// be provided with or without arguments for formatting. See [`std::fmt`]
1249 /// for syntax for this form.
1251 /// [`panic!`]: macro.panic.html
1252 /// [`debug_assert!`]: macro.debug_assert.html
1253 /// [`std::fmt`]: ../std/fmt/index.html
1258 /// // the panic message for these assertions is the stringified value of the
1259 /// // expression given.
1262 /// fn some_computation() -> bool { true } // a very simple function
1264 /// assert!(some_computation());
1266 /// // assert with a custom message
1268 /// assert!(x, "x wasn't true!");
1270 /// let a = 3; let b = 27;
1271 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 #[rustc_builtin_macro]
1276 macro_rules! assert {
1277 ($cond:expr) => {{ /* compiler built-in */ }};
1278 ($cond:expr,) => {{ /* compiler built-in */ }};
1279 ($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }};
1282 /// Inline assembly.
1284 /// Read the [unstable book] for the usage.
1286 /// [unstable book]: ../unstable-book/library-features/asm.html
1290 reason = "inline assembly is not stable enough for use and is subject to change"
1292 #[rustc_builtin_macro]
1295 ("assembly template"
1296 : $("output"(operand),)*
1297 : $("input"(operand),)*
1299 : $("options",)*) => {
1300 /* compiler built-in */
1304 /// Module-level inline assembly.
1306 feature = "global_asm",
1308 reason = "`global_asm!` is not stable enough for use and is subject to change"
1310 #[rustc_builtin_macro]
1312 macro_rules! global_asm {
1314 /* compiler built-in */
1318 /// Prints passed tokens into the standard output.
1320 feature = "log_syntax",
1322 reason = "`log_syntax!` is not stable enough for use and is subject to change"
1324 #[rustc_builtin_macro]
1326 macro_rules! log_syntax {
1328 /* compiler built-in */
1332 /// Enables or disables tracing functionality used for debugging other macros.
1334 feature = "trace_macros",
1336 reason = "`trace_macros` is not stable enough for use and is subject to change"
1338 #[rustc_builtin_macro]
1340 macro_rules! trace_macros {
1341 (true) => {{ /* compiler built-in */ }};
1342 (false) => {{ /* compiler built-in */ }};
1345 /// Attribute macro applied to a function to turn it into a unit test.
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 #[allow_internal_unstable(test, rustc_attrs)]
1348 #[rustc_builtin_macro]
1349 pub macro test($item:item) {
1350 /* compiler built-in */
1353 /// Attribute macro applied to a function to turn it into a benchmark test.
1358 reason = "`bench` is a part of custom test frameworks which are unstable"
1360 #[allow_internal_unstable(test, rustc_attrs)]
1361 #[rustc_builtin_macro]
1362 pub macro bench($item:item) {
1363 /* compiler built-in */
1366 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1368 feature = "custom_test_frameworks",
1370 reason = "custom test frameworks are an unstable feature"
1372 #[allow_internal_unstable(test, rustc_attrs)]
1373 #[rustc_builtin_macro]
1374 pub macro test_case($item:item) {
1375 /* compiler built-in */
1378 /// Attribute macro applied to a static to register it as a global allocator.
1379 #[stable(feature = "global_allocator", since = "1.28.0")]
1380 #[allow_internal_unstable(rustc_attrs)]
1381 #[rustc_builtin_macro]
1382 pub macro global_allocator($item:item) {
1383 /* compiler built-in */
1386 /// Unstable implementation detail of the `rustc` compiler, do not use.
1387 #[rustc_builtin_macro]
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 #[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
1390 pub macro RustcDecodable($item:item) {
1391 /* compiler built-in */
1394 /// Unstable implementation detail of the `rustc` compiler, do not use.
1395 #[rustc_builtin_macro]
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 #[allow_internal_unstable(core_intrinsics)]
1398 pub macro RustcEncodable($item:item) {
1399 /* compiler built-in */