1 #[doc = include_str!("panic.md")]
3 #[rustc_builtin_macro = "core_panic"]
4 #[allow_internal_unstable(edition_panic)]
5 #[stable(feature = "core", since = "1.6.0")]
6 #[rustc_diagnostic_item = "core_panic_macro"]
8 // Expands to either `$crate::panic::panic_2015` or `$crate::panic::panic_2021`
9 // depending on the edition of the caller.
11 /* compiler built-in */
15 /// Asserts that two expressions are equal to each other (using [`PartialEq`]).
17 /// On panic, this macro will print the values of the expressions with their
18 /// debug representations.
20 /// Like [`assert!`], this macro has a second form, where a custom
21 /// panic message can be provided.
30 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
33 #[stable(feature = "rust1", since = "1.0.0")]
34 #[allow_internal_unstable(core_panic)]
35 macro_rules
! assert_eq
{
36 ($left
:expr
, $right
:expr $
(,)?
) => ({
37 match (&$left
, &$right
) {
38 (left_val
, right_val
) => {
39 if !(*left_val
== *right_val
) {
40 let kind
= $
crate::panicking
::AssertKind
::Eq
;
41 // The reborrows below are intentional. Without them, the stack slot for the
42 // borrow is initialized even before the values are compared, leading to a
43 // noticeable slow down.
44 $
crate::panicking
::assert_failed(kind
, &*left_val
, &*right_val
, $
crate::option
::Option
::None
);
49 ($left
:expr
, $right
:expr
, $
($arg
:tt
)+) => ({
50 match (&$left
, &$right
) {
51 (left_val
, right_val
) => {
52 if !(*left_val
== *right_val
) {
53 let kind
= $
crate::panicking
::AssertKind
::Eq
;
54 // The reborrows below are intentional. Without them, the stack slot for the
55 // borrow is initialized even before the values are compared, leading to a
56 // noticeable slow down.
57 $
crate::panicking
::assert_failed(kind
, &*left_val
, &*right_val
, $
crate::option
::Option
::Some($
crate::format_args
!($
($arg
)+)));
64 /// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
66 /// On panic, this macro will print the values of the expressions with their
67 /// debug representations.
69 /// Like [`assert!`], this macro has a second form, where a custom
70 /// panic message can be provided.
79 /// assert_ne!(a, b, "we are testing that the values are not equal");
82 #[stable(feature = "assert_ne", since = "1.13.0")]
83 #[allow_internal_unstable(core_panic)]
84 macro_rules
! assert_ne
{
85 ($left
:expr
, $right
:expr $
(,)?
) => ({
86 match (&$left
, &$right
) {
87 (left_val
, right_val
) => {
88 if *left_val
== *right_val
{
89 let kind
= $
crate::panicking
::AssertKind
::Ne
;
90 // The reborrows below are intentional. Without them, the stack slot for the
91 // borrow is initialized even before the values are compared, leading to a
92 // noticeable slow down.
93 $
crate::panicking
::assert_failed(kind
, &*left_val
, &*right_val
, $
crate::option
::Option
::None
);
98 ($left
:expr
, $right
:expr
, $
($arg
:tt
)+) => ({
99 match (&($left
), &($right
)) {
100 (left_val
, right_val
) => {
101 if *left_val
== *right_val
{
102 let kind
= $
crate::panicking
::AssertKind
::Ne
;
103 // The reborrows below are intentional. Without them, the stack slot for the
104 // borrow is initialized even before the values are compared, leading to a
105 // noticeable slow down.
106 $
crate::panicking
::assert_failed(kind
, &*left_val
, &*right_val
, $
crate::option
::Option
::Some($
crate::format_args
!($
($arg
)+)));
113 /// Asserts that a boolean expression is `true` at runtime.
115 /// This will invoke the [`panic!`] macro if the provided expression cannot be
116 /// evaluated to `true` at runtime.
118 /// Like [`assert!`], this macro also has a second version, where a custom panic
119 /// message can be provided.
123 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
124 /// optimized builds by default. An optimized build will not execute
125 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
126 /// compiler. This makes `debug_assert!` useful for checks that are too
127 /// expensive to be present in a release build but may be helpful during
128 /// development. The result of expanding `debug_assert!` is always type checked.
130 /// An unchecked assertion allows a program in an inconsistent state to keep
131 /// running, which might have unexpected consequences but does not introduce
132 /// unsafety as long as this only happens in safe code. The performance cost
133 /// of assertions, however, is not measurable in general. Replacing [`assert!`]
134 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
135 /// more importantly, only in safe code!
140 /// // the panic message for these assertions is the stringified value of the
141 /// // expression given.
142 /// debug_assert!(true);
144 /// fn some_expensive_computation() -> bool { true } // a very simple function
145 /// debug_assert!(some_expensive_computation());
147 /// // assert with a custom message
149 /// debug_assert!(x, "x wasn't true!");
151 /// let a = 3; let b = 27;
152 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
155 #[stable(feature = "rust1", since = "1.0.0")]
156 #[rustc_diagnostic_item = "debug_assert_macro"]
157 macro_rules
! debug_assert
{
158 ($
($arg
:tt
)*) => (if $
crate::cfg
!(debug_assertions
) { $crate::assert!($($arg)*); }
)
161 /// Asserts that two expressions are equal to each other.
163 /// On panic, this macro will print the values of the expressions with their
164 /// debug representations.
166 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
167 /// optimized builds by default. An optimized build will not execute
168 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
169 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
170 /// expensive to be present in a release build but may be helpful during
171 /// development. The result of expanding `debug_assert_eq!` is always type checked.
178 /// debug_assert_eq!(a, b);
181 #[stable(feature = "rust1", since = "1.0.0")]
182 macro_rules
! debug_assert_eq
{
183 ($
($arg
:tt
)*) => (if $
crate::cfg
!(debug_assertions
) { $crate::assert_eq!($($arg)*); }
)
186 /// Asserts that two expressions are not equal to each other.
188 /// On panic, this macro will print the values of the expressions with their
189 /// debug representations.
191 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
192 /// optimized builds by default. An optimized build will not execute
193 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
194 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
195 /// expensive to be present in a release build but may be helpful during
196 /// development. The result of expanding `debug_assert_ne!` is always type checked.
203 /// debug_assert_ne!(a, b);
206 #[stable(feature = "assert_ne", since = "1.13.0")]
207 macro_rules
! debug_assert_ne
{
208 ($
($arg
:tt
)*) => (if $
crate::cfg
!(debug_assertions
) { $crate::assert_ne!($($arg)*); }
)
211 /// Returns whether the given expression matches any of the given patterns.
213 /// Like in a `match` expression, the pattern can be optionally followed by `if`
214 /// and a guard expression that has access to names bound by the pattern.
220 /// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
222 /// let bar = Some(4);
223 /// assert!(matches!(bar, Some(x) if x > 2));
226 #[stable(feature = "matches_macro", since = "1.42.0")]
227 macro_rules
! matches
{
228 ($expression
:expr
, $
( $pattern
:pat
)|+ $
( if $guard
: expr
)? $
(,)?
) => {
230 $
( $pattern
)|+ $
( if $guard
)?
=> true,
236 /// Unwraps a result or propagates its error.
238 /// The `?` operator was added to replace `try!` and should be used instead.
239 /// Furthermore, `try` is a reserved word in Rust 2018, so if you must use
240 /// it, you will need to use the [raw-identifier syntax][ris]: `r#try`.
242 /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html
244 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
245 /// expression has the value of the wrapped value.
247 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
248 /// performs conversion using `From`. This provides automatic conversion
249 /// between specialized errors and more general ones. The resulting
250 /// error is then immediately returned.
252 /// Because of the early return, `try!` can only be used in functions that
253 /// return [`Result`].
259 /// use std::fs::File;
260 /// use std::io::prelude::*;
266 /// impl From<io::Error> for MyError {
267 /// fn from(e: io::Error) -> MyError {
268 /// MyError::FileWriteError
272 /// // The preferred method of quick returning Errors
273 /// fn write_to_file_question() -> Result<(), MyError> {
274 /// let mut file = File::create("my_best_friends.txt")?;
275 /// file.write_all(b"This is a list of my best friends.")?;
279 /// // The previous method of quick returning Errors
280 /// fn write_to_file_using_try() -> Result<(), MyError> {
281 /// let mut file = r#try!(File::create("my_best_friends.txt"));
282 /// r#try!(file.write_all(b"This is a list of my best friends."));
286 /// // This is equivalent to:
287 /// fn write_to_file_using_match() -> Result<(), MyError> {
288 /// let mut file = r#try!(File::create("my_best_friends.txt"));
289 /// match file.write_all(b"This is a list of my best friends.") {
291 /// Err(e) => return Err(From::from(e)),
297 #[stable(feature = "rust1", since = "1.0.0")]
298 #[rustc_deprecated(since = "1.39.0", reason = "use the `?` operator instead")]
301 ($expr
:expr $
(,)?
) => {
303 $
crate::result
::Result
::Ok(val
) => val
,
304 $
crate::result
::Result
::Err(err
) => {
305 return $
crate::result
::Result
::Err($
crate::convert
::From
::from(err
));
311 /// Writes formatted data into a buffer.
313 /// This macro accepts a 'writer', a format string, and a list of arguments. Arguments will be
314 /// formatted according to the specified format string and the result will be passed to the writer.
315 /// The writer may be any value with a `write_fmt` method; generally this comes from an
316 /// implementation of either the [`fmt::Write`] or the [`io::Write`] trait. The macro
317 /// returns whatever the `write_fmt` method returns; commonly a [`fmt::Result`], or an
320 /// See [`std::fmt`] for more information on the format string syntax.
322 /// [`std::fmt`]: ../std/fmt/index.html
323 /// [`fmt::Write`]: crate::fmt::Write
324 /// [`io::Write`]: ../std/io/trait.Write.html
325 /// [`fmt::Result`]: crate::fmt::Result
326 /// [`io::Result`]: ../std/io/type.Result.html
331 /// use std::io::Write;
333 /// fn main() -> std::io::Result<()> {
334 /// let mut w = Vec::new();
335 /// write!(&mut w, "test")?;
336 /// write!(&mut w, "formatted {}", "arguments")?;
338 /// assert_eq!(w, b"testformatted arguments");
343 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
344 /// implementing either, as objects do not typically implement both. However, the module must
345 /// import the traits qualified so their names do not conflict:
348 /// use std::fmt::Write as FmtWrite;
349 /// use std::io::Write as IoWrite;
351 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
352 /// let mut s = String::new();
353 /// let mut v = Vec::new();
355 /// write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
356 /// write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
357 /// assert_eq!(v, b"s = \"abc 123\"");
362 /// Note: This macro can be used in `no_std` setups as well.
363 /// In a `no_std` setup you are responsible for the implementation details of the components.
366 /// # extern crate core;
367 /// use core::fmt::Write;
371 /// impl Write for Example {
372 /// fn write_str(&mut self, _s: &str) -> core::fmt::Result {
373 /// unimplemented!();
377 /// let mut m = Example{};
378 /// write!(&mut m, "Hello World").expect("Not written");
381 #[stable(feature = "rust1", since = "1.0.0")]
383 ($dst
:expr
, $
($arg
:tt
)*) => ($dst
.write_fmt($
crate::format_args
!($
($arg
)*)))
386 /// Write formatted data into a buffer, with a newline appended.
388 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
389 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
391 /// For more information, see [`write!`]. For information on the format string syntax, see
394 /// [`std::fmt`]: ../std/fmt/index.html
399 /// use std::io::{Write, Result};
401 /// fn main() -> Result<()> {
402 /// let mut w = Vec::new();
403 /// writeln!(&mut w)?;
404 /// writeln!(&mut w, "test")?;
405 /// writeln!(&mut w, "formatted {}", "arguments")?;
407 /// 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 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
421 /// let mut s = String::new();
422 /// let mut v = Vec::new();
424 /// writeln!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
425 /// writeln!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
426 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
431 #[stable(feature = "rust1", since = "1.0.0")]
432 #[allow_internal_unstable(format_args_nl)]
433 macro_rules
! writeln
{
434 ($dst
:expr $
(,)?
) => (
435 $
crate::write
!($dst
, "\n")
437 ($dst
:expr
, $
($arg
:tt
)*) => (
438 $dst
.write_fmt($
crate::format_args_nl
!($
($arg
)*))
442 /// Indicates unreachable code.
444 /// This is useful any time that the compiler can't determine that some code is unreachable. For
447 /// * Match arms with guard conditions.
448 /// * Loops that dynamically terminate.
449 /// * Iterators that dynamically terminate.
451 /// If the determination that the code is unreachable proves incorrect, the
452 /// program immediately terminates with a [`panic!`].
454 /// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
455 /// will cause undefined behavior if the code is reached.
457 /// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked
461 /// This will always [`panic!`].
468 /// # #[allow(dead_code)]
469 /// fn foo(x: Option<i32>) {
471 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
472 /// Some(n) if n < 0 => println!("Some(Negative)"),
473 /// Some(_) => unreachable!(), // compile error if commented out
474 /// None => println!("None")
482 /// # #[allow(dead_code)]
483 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
485 /// if 3*i < i { panic!("u32 overflow"); }
486 /// if x < 3*i { return i-1; }
492 #[stable(feature = "rust1", since = "1.0.0")]
493 macro_rules
! unreachable
{
495 $
crate::panic
!("internal error: entered unreachable code")
497 ($msg
:expr $
(,)?
) => ({
498 $
crate::unreachable
!("{}", $msg
)
500 ($fmt
:expr
, $
($arg
:tt
)*) => ({
501 $
crate::panic
!($
crate::concat
!("internal error: entered unreachable code: ", $fmt
), $
($arg
)*)
505 /// Indicates unimplemented code by panicking with a message of "not implemented".
507 /// This allows your code to type-check, which is useful if you are prototyping or
508 /// implementing a trait that requires multiple methods which you don't plan of using all of.
510 /// The difference between `unimplemented!` and [`todo!`] is that while `todo!`
511 /// conveys an intent of implementing the functionality later and the message is "not yet
512 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
513 /// Also some IDEs will mark `todo!`s.
517 /// This will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a
518 /// fixed, specific message.
520 /// Like `panic!`, this macro has a second form for displaying custom values.
524 /// Say we have a trait `Foo`:
528 /// fn bar(&self) -> u8;
530 /// fn qux(&self) -> Result<u64, ()>;
534 /// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
535 /// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
536 /// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
537 /// to allow our code to compile.
539 /// We still want to have our program stop running if the unimplemented methods are
544 /// # fn bar(&self) -> u8;
546 /// # fn qux(&self) -> Result<u64, ()>;
550 /// impl Foo for MyStruct {
551 /// fn bar(&self) -> u8 {
556 /// // It makes no sense to `baz` a `MyStruct`, so we have no logic here
558 /// // This will display "thread 'main' panicked at 'not implemented'".
559 /// unimplemented!();
562 /// fn qux(&self) -> Result<u64, ()> {
563 /// // We have some logic here,
564 /// // We can add a message to unimplemented! to display our omission.
565 /// // This will display:
566 /// // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
567 /// unimplemented!("MyStruct isn't quxable");
572 /// let s = MyStruct;
577 #[stable(feature = "rust1", since = "1.0.0")]
578 macro_rules
! unimplemented
{
579 () => ($
crate::panic
!("not implemented"));
580 ($
($arg
:tt
)+) => ($
crate::panic
!("not implemented: {}", $
crate::format_args
!($
($arg
)+)));
583 /// Indicates unfinished code.
585 /// This can be useful if you are prototyping and are just looking to have your
588 /// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
589 /// an intent of implementing the functionality later and the message is "not yet
590 /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
591 /// Also some IDEs will mark `todo!`s.
595 /// This will always [`panic!`].
599 /// Here's an example of some in-progress code. We have a trait `Foo`:
608 /// We want to implement `Foo` on one of our types, but we also want to work on
609 /// just `bar()` first. In order for our code to compile, we need to implement
610 /// `baz()`, so we can use `todo!`:
619 /// impl Foo for MyStruct {
621 /// // implementation goes here
625 /// // let's not worry about implementing baz() for now
631 /// let s = MyStruct;
634 /// // we aren't even using baz(), so this is fine.
638 #[stable(feature = "todo_macro", since = "1.40.0")]
640 () => ($
crate::panic
!("not yet implemented"));
641 ($
($arg
:tt
)+) => ($
crate::panic
!("not yet implemented: {}", $
crate::format_args
!($
($arg
)+)));
644 /// Definitions of built-in macros.
646 /// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
647 /// with exception of expansion functions transforming macro inputs into outputs,
648 /// those functions are provided by the compiler.
649 pub(crate) mod builtin
{
651 /// Causes compilation to fail with the given error message when encountered.
653 /// This macro should be used when a crate uses a conditional compilation strategy to provide
654 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
655 /// but emits an error during *compilation* rather than at *runtime*.
659 /// Two such examples are macros and `#[cfg]` environments.
661 /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
662 /// the compiler would still emit an error, but the error's message would not mention the two
666 /// macro_rules! give_me_foo_or_bar {
670 /// compile_error!("This macro only accepts `foo` or `bar`");
674 /// give_me_foo_or_bar!(neither);
675 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
678 /// Emit compiler error if one of a number of features isn't available.
681 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
682 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
684 #[stable(feature = "compile_error_macro", since = "1.20.0")]
685 #[rustc_builtin_macro]
687 macro_rules
! compile_error
{
688 ($msg
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
691 /// Constructs parameters for the other string-formatting macros.
693 /// This macro functions by taking a formatting string literal containing
694 /// `{}` for each additional argument passed. `format_args!` prepares the
695 /// additional parameters to ensure the output can be interpreted as a string
696 /// and canonicalizes the arguments into a single type. Any value that implements
697 /// the [`Display`] trait can be passed to `format_args!`, as can any
698 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
700 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
701 /// passed to the macros within [`std::fmt`] for performing useful redirection.
702 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
703 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
704 /// heap allocations.
706 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
707 /// in `Debug` and `Display` contexts as seen below. The example also shows
708 /// that `Debug` and `Display` format to the same thing: the interpolated
709 /// format string in `format_args!`.
712 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
713 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
714 /// assert_eq!("1 foo 2", display);
715 /// assert_eq!(display, debug);
718 /// For more information, see the documentation in [`std::fmt`].
720 /// [`Display`]: crate::fmt::Display
721 /// [`Debug`]: crate::fmt::Debug
722 /// [`fmt::Arguments`]: crate::fmt::Arguments
723 /// [`std::fmt`]: ../std/fmt/index.html
724 /// [`format!`]: ../std/macro.format.html
725 /// [`println!`]: ../std/macro.println.html
732 /// let s = fmt::format(format_args!("hello {}", "world"));
733 /// assert_eq!(s, format!("hello {}", "world"));
735 #[stable(feature = "rust1", since = "1.0.0")]
736 #[allow_internal_unstable(fmt_internals)]
737 #[rustc_builtin_macro]
739 macro_rules
! format_args
{
740 ($fmt
:expr
) => {{ /* compiler built-in */ }
};
741 ($fmt
:expr
, $
($args
:tt
)*) => {{ /* compiler built-in */ }
};
744 /// Same as `format_args`, but adds a newline in the end.
746 feature
= "format_args_nl",
748 reason
= "`format_args_nl` is only for internal \
749 language use and is subject to change"
751 #[allow_internal_unstable(fmt_internals)]
752 #[rustc_builtin_macro]
754 macro_rules
! format_args_nl
{
755 ($fmt
:expr
) => {{ /* compiler built-in */ }
};
756 ($fmt
:expr
, $
($args
:tt
)*) => {{ /* compiler built-in */ }
};
759 /// Inspects an environment variable at compile time.
761 /// This macro will expand to the value of the named environment variable at
762 /// compile time, yielding an expression of type `&'static str`.
764 /// If the environment variable is not defined, then a compilation error
765 /// will be emitted. To not emit a compile error, use the [`option_env!`]
771 /// let path: &'static str = env!("PATH");
772 /// println!("the $PATH variable at the time of compiling was: {}", path);
775 /// You can customize the error message by passing a string as the second
779 /// let doc: &'static str = env!("documentation", "what's that?!");
782 /// If the `documentation` environment variable is not defined, you'll get
783 /// the following error:
786 /// error: what's that?!
788 #[stable(feature = "rust1", since = "1.0.0")]
789 #[rustc_builtin_macro]
792 ($name
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
793 ($name
:expr
, $error_msg
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
796 /// Optionally inspects an environment variable at compile time.
798 /// If the named environment variable is present at compile time, this will
799 /// expand into an expression of type `Option<&'static str>` whose value is
800 /// `Some` of the value of the environment variable. If the environment
801 /// variable is not present, then this will expand to `None`. See
802 /// [`Option<T>`][Option] for more information on this type.
804 /// A compile time error is never emitted when using this macro regardless
805 /// of whether the environment variable is present or not.
810 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
811 /// println!("the secret key might be: {:?}", key);
813 #[stable(feature = "rust1", since = "1.0.0")]
814 #[rustc_builtin_macro]
816 macro_rules
! option_env
{
817 ($name
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
820 /// Concatenates identifiers into one identifier.
822 /// This macro takes any number of comma-separated identifiers, and
823 /// concatenates them all into one, yielding an expression which is a new
824 /// identifier. Note that hygiene makes it such that this macro cannot
825 /// capture local variables. Also, as a general rule, macros are only
826 /// allowed in item, statement or expression position. That means while
827 /// you may use this macro for referring to existing variables, functions or
828 /// modules etc, you cannot define a new one with it.
833 /// #![feature(concat_idents)]
836 /// fn foobar() -> u32 { 23 }
838 /// let f = concat_idents!(foo, bar);
839 /// println!("{}", f());
841 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
845 feature
= "concat_idents",
847 reason
= "`concat_idents` is not stable enough for use and is subject to change"
849 #[rustc_builtin_macro]
851 macro_rules
! concat_idents
{
852 ($
($e
:ident
),+ $
(,)?
) => {{ /* compiler built-in */ }
};
855 /// Concatenates literals into a static string slice.
857 /// This macro takes any number of comma-separated literals, yielding an
858 /// expression of type `&'static str` which represents all of the literals
859 /// concatenated left-to-right.
861 /// Integer and floating point literals are stringified in order to be
867 /// let s = concat!("test", 10, 'b', true);
868 /// assert_eq!(s, "test10btrue");
870 #[stable(feature = "rust1", since = "1.0.0")]
871 #[rustc_builtin_macro]
873 macro_rules
! concat
{
874 ($
($e
:expr
),* $
(,)?
) => {{ /* compiler built-in */ }
};
877 /// Expands to the line number on which it was invoked.
879 /// With [`column!`] and [`file!`], these macros provide debugging information for
880 /// developers about the location within the source.
882 /// The expanded expression has type `u32` and is 1-based, so the first line
883 /// in each file evaluates to 1, the second to 2, etc. This is consistent
884 /// with error messages by common compilers or popular editors.
885 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
886 /// but rather the first macro invocation leading up to the invocation
887 /// of the `line!` macro.
892 /// let current_line = line!();
893 /// println!("defined on line: {}", current_line);
895 #[stable(feature = "rust1", since = "1.0.0")]
896 #[rustc_builtin_macro]
900 /* compiler built-in */
904 /// Expands to the column number at which it was invoked.
906 /// With [`line!`] and [`file!`], these macros provide debugging information for
907 /// developers about the location within the source.
909 /// The expanded expression has type `u32` and is 1-based, so the first column
910 /// in each line evaluates to 1, the second to 2, etc. This is consistent
911 /// with error messages by common compilers or popular editors.
912 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
913 /// but rather the first macro invocation leading up to the invocation
914 /// of the `column!` macro.
919 /// let current_col = column!();
920 /// println!("defined on column: {}", current_col);
922 #[stable(feature = "rust1", since = "1.0.0")]
923 #[rustc_builtin_macro]
925 macro_rules
! column
{
927 /* compiler built-in */
931 /// Expands to the file name in which it was invoked.
933 /// With [`line!`] and [`column!`], these macros provide debugging information for
934 /// developers about the location within the source.
936 /// The expanded expression has type `&'static str`, and the returned file
937 /// is not the invocation of the `file!` macro itself, but rather the
938 /// first macro invocation leading up to the invocation of the `file!`
944 /// let this_file = file!();
945 /// println!("defined in file: {}", this_file);
947 #[stable(feature = "rust1", since = "1.0.0")]
948 #[rustc_builtin_macro]
952 /* compiler built-in */
956 /// Stringifies its arguments.
958 /// This macro will yield an expression of type `&'static str` which is the
959 /// stringification of all the tokens passed to the macro. No restrictions
960 /// are placed on the syntax of the macro invocation itself.
962 /// Note that the expanded results of the input tokens may change in the
963 /// future. You should be careful if you rely on the output.
968 /// let one_plus_one = stringify!(1 + 1);
969 /// assert_eq!(one_plus_one, "1 + 1");
971 #[stable(feature = "rust1", since = "1.0.0")]
972 #[rustc_builtin_macro]
974 macro_rules
! stringify
{
976 /* compiler built-in */
980 /// Includes a UTF-8 encoded file as a string.
982 /// The file is located relative to the current file (similarly to how
983 /// modules are found). The provided path is interpreted in a platform-specific
984 /// way at compile time. So, for instance, an invocation with a Windows path
985 /// containing backslashes `\` would not compile correctly on Unix.
987 /// This macro will yield an expression of type `&'static str` which is the
988 /// contents of the file.
992 /// Assume there are two files in the same directory with the following
995 /// File 'spanish.in':
1003 /// ```ignore (cannot-doctest-external-file-dependency)
1005 /// let my_str = include_str!("spanish.in");
1006 /// assert_eq!(my_str, "adiós\n");
1007 /// print!("{}", my_str);
1011 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 #[rustc_builtin_macro]
1015 macro_rules
! include_str
{
1016 ($file
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
1019 /// Includes a file as a reference to a byte array.
1021 /// The file is located relative to the current file (similarly to how
1022 /// modules are found). The provided path is interpreted in a platform-specific
1023 /// way at compile time. So, for instance, an invocation with a Windows path
1024 /// containing backslashes `\` would not compile correctly on Unix.
1026 /// This macro will yield an expression of type `&'static [u8; N]` which is
1027 /// the contents of the file.
1031 /// Assume there are two files in the same directory with the following
1034 /// File 'spanish.in':
1042 /// ```ignore (cannot-doctest-external-file-dependency)
1044 /// let bytes = include_bytes!("spanish.in");
1045 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
1046 /// print!("{}", String::from_utf8_lossy(bytes));
1050 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 #[rustc_builtin_macro]
1054 macro_rules
! include_bytes
{
1055 ($file
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
1058 /// Expands to a string that represents the current module path.
1060 /// The current module path can be thought of as the hierarchy of modules
1061 /// leading back up to the crate root. The first component of the path
1062 /// returned is the name of the crate currently being compiled.
1069 /// assert!(module_path!().ends_with("test"));
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 #[rustc_builtin_macro]
1078 macro_rules
! module_path
{
1080 /* compiler built-in */
1084 /// Evaluates boolean combinations of configuration flags at compile-time.
1086 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1087 /// boolean expression evaluation of configuration flags. This frequently
1088 /// leads to less duplicated code.
1090 /// The syntax given to this macro is the same syntax as the [`cfg`]
1093 /// `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For
1094 /// example, all blocks in an if/else expression need to be valid when `cfg!` is used for
1095 /// the condition, regardless of what `cfg!` is evaluating.
1097 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1102 /// let my_directory = if cfg!(windows) {
1103 /// "windows-specific-directory"
1105 /// "unix-directory"
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 #[rustc_builtin_macro]
1113 /* compiler built-in */
1117 /// Parses a file as an expression or an item according to the context.
1119 /// The file is located relative to the current file (similarly to how
1120 /// modules are found). The provided path is interpreted in a platform-specific
1121 /// way at compile time. So, for instance, an invocation with a Windows path
1122 /// containing backslashes `\` would not compile correctly on Unix.
1124 /// Using this macro is often a bad idea, because if the file is
1125 /// parsed as an expression, it is going to be placed in the
1126 /// surrounding code unhygienically. This could result in variables
1127 /// or functions being different from what the file expected if
1128 /// there are variables or functions that have the same name in
1129 /// the current file.
1133 /// Assume there are two files in the same directory with the following
1136 /// File 'monkeys.in':
1138 /// ```ignore (only-for-syntax-highlight)
1139 /// ['🙈', '🙊', '🙉']
1143 /// .collect::<String>()
1148 /// ```ignore (cannot-doctest-external-file-dependency)
1150 /// let my_string = include!("monkeys.in");
1151 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1152 /// println!("{}", my_string);
1156 /// Compiling 'main.rs' and running the resulting binary will print
1157 /// "🙈🙊🙉🙈🙊🙉".
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 #[rustc_builtin_macro]
1161 macro_rules
! include
{
1162 ($file
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
1165 /// Asserts that a boolean expression is `true` at runtime.
1167 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1168 /// evaluated to `true` at runtime.
1172 /// Assertions are always checked in both debug and release builds, and cannot
1173 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1174 /// release builds by default.
1176 /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if
1177 /// violated could lead to unsafety.
1179 /// Other use-cases of `assert!` include testing and enforcing run-time
1180 /// invariants in safe code (whose violation cannot result in unsafety).
1182 /// # Custom Messages
1184 /// This macro has a second form, where a custom panic message can
1185 /// be provided with or without arguments for formatting. See [`std::fmt`]
1186 /// for syntax for this form. Expressions used as format arguments will only
1187 /// be evaluated if the assertion fails.
1189 /// [`std::fmt`]: ../std/fmt/index.html
1194 /// // the panic message for these assertions is the stringified value of the
1195 /// // expression given.
1198 /// fn some_computation() -> bool { true } // a very simple function
1200 /// assert!(some_computation());
1202 /// // assert with a custom message
1204 /// assert!(x, "x wasn't true!");
1206 /// let a = 3; let b = 27;
1207 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1209 #[stable(feature = "rust1", since = "1.0.0")]
1210 #[rustc_builtin_macro]
1212 #[rustc_diagnostic_item = "assert_macro"]
1213 #[allow_internal_unstable(core_panic, edition_panic)]
1214 macro_rules
! assert
{
1215 ($cond
:expr $
(,)?
) => {{ /* compiler built-in */ }
};
1216 ($cond
:expr
, $
($arg
:tt
)+) => {{ /* compiler built-in */ }
};
1219 /// Inline assembly.
1221 /// Read the [unstable book] for the usage.
1223 /// [unstable book]: ../unstable-book/library-features/asm.html
1227 reason
= "inline assembly is not stable enough for use and is subject to change"
1229 #[rustc_builtin_macro]
1232 ("assembly template",
1234 $
(options($
(option
),*))?
1236 /* compiler built-in */
1240 /// LLVM-style inline assembly.
1242 /// Read the [unstable book] for the usage.
1244 /// [unstable book]: ../unstable-book/library-features/llvm-asm.html
1246 feature
= "llvm_asm",
1248 reason
= "prefer using the new asm! syntax instead"
1250 #[rustc_builtin_macro]
1252 macro_rules
! llvm_asm
{
1253 ("assembly template"
1254 : $
("output"(operand
),)*
1255 : $
("input"(operand
),)*
1257 : $
("options",)*) => {
1258 /* compiler built-in */
1262 /// Module-level inline assembly.
1264 feature
= "global_asm",
1266 reason
= "`global_asm!` is not stable enough for use and is subject to change"
1268 #[rustc_builtin_macro]
1270 macro_rules
! global_asm
{
1272 /* compiler built-in */
1276 /// Prints passed tokens into the standard output.
1278 feature
= "log_syntax",
1280 reason
= "`log_syntax!` is not stable enough for use and is subject to change"
1282 #[rustc_builtin_macro]
1284 macro_rules
! log_syntax
{
1286 /* compiler built-in */
1290 /// Enables or disables tracing functionality used for debugging other macros.
1292 feature
= "trace_macros",
1294 reason
= "`trace_macros` is not stable enough for use and is subject to change"
1296 #[rustc_builtin_macro]
1298 macro_rules
! trace_macros
{
1299 (true) => {{ /* compiler built-in */ }
};
1300 (false) => {{ /* compiler built-in */ }
};
1303 /// Attribute macro used to apply derive macros.
1304 #[cfg(not(bootstrap))]
1305 #[stable(feature = "rust1", since = "1.0.0")]
1306 #[rustc_builtin_macro]
1307 pub macro derive($item
:item
) {
1308 /* compiler built-in */
1311 /// Attribute macro applied to a function to turn it into a unit test.
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 #[allow_internal_unstable(test, rustc_attrs)]
1314 #[rustc_builtin_macro]
1315 pub macro test($item
:item
) {
1316 /* compiler built-in */
1319 /// Attribute macro applied to a function to turn it into a benchmark test.
1324 reason
= "`bench` is a part of custom test frameworks which are unstable"
1326 #[allow_internal_unstable(test, rustc_attrs)]
1327 #[rustc_builtin_macro]
1328 pub macro bench($item
:item
) {
1329 /* compiler built-in */
1332 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1334 feature
= "custom_test_frameworks",
1336 reason
= "custom test frameworks are an unstable feature"
1338 #[allow_internal_unstable(test, rustc_attrs)]
1339 #[rustc_builtin_macro]
1340 pub macro test_case($item
:item
) {
1341 /* compiler built-in */
1344 /// Attribute macro applied to a static to register it as a global allocator.
1346 /// See also [`std::alloc::GlobalAlloc`](../std/alloc/trait.GlobalAlloc.html).
1347 #[stable(feature = "global_allocator", since = "1.28.0")]
1348 #[allow_internal_unstable(rustc_attrs)]
1349 #[rustc_builtin_macro]
1350 pub macro global_allocator($item
:item
) {
1351 /* compiler built-in */
1354 /// Keeps the item it's applied to if the passed path is accessible, and removes it otherwise.
1356 feature
= "cfg_accessible",
1358 reason
= "`cfg_accessible` is not fully implemented"
1360 #[rustc_builtin_macro]
1361 pub macro cfg_accessible($item
:item
) {
1362 /* compiler built-in */
1365 /// Expands all `#[cfg]` and `#[cfg_attr]` attributes in the code fragment it's applied to.
1366 #[cfg(not(bootstrap))]
1368 feature
= "cfg_eval",
1370 reason
= "`cfg_eval` is a recently implemented feature"
1372 #[rustc_builtin_macro]
1373 pub macro cfg_eval($
($tt
:tt
)*) {
1374 /* compiler built-in */
1377 /// Unstable implementation detail of the `rustc` compiler, do not use.
1378 #[rustc_builtin_macro]
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 #[allow_internal_unstable(core_intrinsics, libstd_sys_internals)]
1383 reason
= "rustc-serialize is deprecated and no longer supported"
1385 pub macro RustcDecodable($item
:item
) {
1386 /* compiler built-in */
1389 /// Unstable implementation detail of the `rustc` compiler, do not use.
1390 #[rustc_builtin_macro]
1391 #[stable(feature = "rust1", since = "1.0.0")]
1392 #[allow_internal_unstable(core_intrinsics)]
1395 reason
= "rustc-serialize is deprecated and no longer supported"
1397 pub macro RustcEncodable($item
:item
) {
1398 /* compiler built-in */