1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Standard library macros
13 //! This modules contains a set of macros which are exported from the standard
14 //! library. Each macro is available for use when linking against the standard
17 /// The entry point for panic of Rust threads.
19 /// This allows a program to to terminate immediately and provide feedback
20 /// to the caller of the program. `panic!` should be used when a program reaches
21 /// an unrecoverable problem.
23 /// This macro is the perfect way to assert conditions in example code and in
24 /// tests. `panic!` is closely tied with the `unwrap` method of both [`Option`]
25 /// and [`Result`][runwrap] enums. Both implementations call `panic!` when they are set
26 /// to None or Err variants.
28 /// This macro is used to inject panic into a Rust thread, causing the thread to
29 /// panic entirely. Each thread's panic can be reaped as the `Box<Any>` type,
30 /// and the single-argument form of the `panic!` macro will be the value which
33 /// [`Result`] enum is often a better solution for recovering from errors than
34 /// using the `panic!` macro. This macro should be used to avoid proceeding using
35 /// incorrect values, such as from external sources. Detailed information about
36 /// error handling is found in the [book].
38 /// The multi-argument form of this macro panics with a string and has the
39 /// [`format!`] syntax for building a string.
41 /// See also the macro [`compile_error!`], for raising errors during compilation.
43 /// [runwrap]: ../std/result/enum.Result.html#method.unwrap
44 /// [`Option`]: ../std/option/enum.Option.html#method.unwrap
45 /// [`Result`]: ../std/result/enum.Result.html
46 /// [`format!`]: ../std/macro.format.html
47 /// [`compile_error!`]: ../std/macro.compile_error.html
48 /// [book]: ../book/second-edition/ch09-01-unrecoverable-errors-with-panic.html
50 /// # Current implementation
52 /// If the main thread panics it will terminate all your threads and end your
53 /// program with code `101`.
58 /// # #![allow(unreachable_code)]
60 /// panic!("this is a terrible mistake!");
61 /// panic!(4); // panic with the value of 4 to be collected elsewhere
62 /// panic!("this is a {} {message}", "fancy", message = "message");
65 #[stable(feature = "rust1", since = "1.0.0")]
66 #[allow_internal_unstable]
69 panic!("explicit panic")
72 $crate::rt::begin_panic($msg, &(file!(), line!(), __rust_unstable_column!()))
77 ($fmt:expr, $($arg:tt)+) => ({
78 $crate::rt::begin_panic_fmt(&format_args!($fmt, $($arg)+),
79 &(file!(), line!(), __rust_unstable_column!()))
83 /// Macro for printing to the standard output.
85 /// Equivalent to the [`println!`] macro except that a newline is not printed at
86 /// the end of the message.
88 /// Note that stdout is frequently line-buffered by default so it may be
89 /// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
92 /// Use `print!` only for the primary output of your program. Use
93 /// [`eprint!`] instead to print error and progress messages.
95 /// [`println!`]: ../std/macro.println.html
96 /// [flush]: ../std/io/trait.Write.html#tymethod.flush
97 /// [`eprint!`]: ../std/macro.eprint.html
101 /// Panics if writing to `io::stdout()` fails.
106 /// use std::io::{self, Write};
116 /// io::stdout().flush().unwrap();
118 /// print!("this string has a newline, why not choose println! instead?\n");
120 /// io::stdout().flush().unwrap();
123 #[stable(feature = "rust1", since = "1.0.0")]
124 #[allow_internal_unstable]
126 ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
129 /// Macro for printing to the standard output, with a newline.
131 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
132 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
134 /// Use the [`format!`] syntax to write data to the standard output.
135 /// See [`std::fmt`] for more information.
137 /// Use `println!` only for the primary output of your program. Use
138 /// [`eprintln!`] instead to print error and progress messages.
140 /// [`format!`]: ../std/macro.format.html
141 /// [`std::fmt`]: ../std/fmt/index.html
142 /// [`eprintln!`]: ../std/macro.eprint.html
145 /// Panics if writing to `io::stdout` fails.
150 /// println!(); // prints just a newline
151 /// println!("hello there!");
152 /// println!("format {} arguments", "some");
155 #[stable(feature = "rust1", since = "1.0.0")]
156 #[allow_internal_unstable]
157 macro_rules! println {
158 () => (print!("\n"));
160 $crate::io::_print(format_args_nl!($($arg)*));
164 /// Macro for printing to the standard error.
166 /// Equivalent to the [`print!`] macro, except that output goes to
167 /// [`io::stderr`] instead of `io::stdout`. See [`print!`] for
170 /// Use `eprint!` only for error and progress messages. Use `print!`
171 /// instead for the primary output of your program.
173 /// [`io::stderr`]: ../std/io/struct.Stderr.html
174 /// [`print!`]: ../std/macro.print.html
178 /// Panics if writing to `io::stderr` fails.
183 /// eprint!("Error: Could not complete task");
186 #[stable(feature = "eprint", since = "1.19.0")]
187 #[allow_internal_unstable]
188 macro_rules! eprint {
189 ($($arg:tt)*) => ($crate::io::_eprint(format_args!($($arg)*)));
192 /// Macro for printing to the standard error, with a newline.
194 /// Equivalent to the [`println!`] macro, except that output goes to
195 /// [`io::stderr`] instead of `io::stdout`. See [`println!`] for
198 /// Use `eprintln!` only for error and progress messages. Use `println!`
199 /// instead for the primary output of your program.
201 /// [`io::stderr`]: ../std/io/struct.Stderr.html
202 /// [`println!`]: ../std/macro.println.html
206 /// Panics if writing to `io::stderr` fails.
211 /// eprintln!("Error: Could not complete task");
214 #[stable(feature = "eprint", since = "1.19.0")]
215 #[allow_internal_unstable]
216 macro_rules! eprintln {
217 () => (eprint!("\n"));
219 $crate::io::_eprint(format_args_nl!($($arg)*));
223 /// A macro for quick and dirty debugging with which you can inspect
224 /// the value of a given expression. An example:
227 /// #![feature(dbg_macro)]
230 /// let b = dbg!(a * 2) + 1;
231 /// // ^-- prints: [src/main.rs:4] a * 2 = 4
232 /// assert_eq!(b, 5);
235 /// The macro works by using the `Debug` implementation of the type of
236 /// the given expression to print the value to [stderr] along with the
237 /// source location of the macro invocation as well as the source code
238 /// of the expression.
240 /// Invoking the macro on an expression moves and takes ownership of it
241 /// before returning the evaluated expression unchanged. If the type
242 /// of the expression does not implement `Copy` and you don't want
243 /// to give up ownership, you can instead borrow with `dbg!(&expr)`
244 /// for some expression `expr`.
246 /// and should be avoided
247 /// for longer periods in version control
251 /// The exact output printed by this macro should not be relied upon
252 /// and is subject to future changes.
256 /// Panics if writing to `io::stderr` fails.
258 /// # Further examples
260 /// With a method call:
263 /// #![feature(dbg_macro)]
265 /// fn foo(n: usize) {
266 /// if let Some(_) = dbg!(n.checked_sub(4)) {
274 /// This prints to [stderr]:
277 /// [src/main.rs:4] n.checked_sub(4) = None
280 /// Naive factorial implementation:
283 /// #![feature(dbg_macro)]
285 /// fn factorial(n: u32) -> u32 {
286 /// if dbg!(n <= 1) {
289 /// dbg!(n * factorial(n - 1))
293 /// dbg!(factorial(4));
296 /// This prints to [stderr]:
299 /// [src/main.rs:3] n <= 1 = false
300 /// [src/main.rs:3] n <= 1 = false
301 /// [src/main.rs:3] n <= 1 = false
302 /// [src/main.rs:3] n <= 1 = true
303 /// [src/main.rs:4] 1 = 1
304 /// [src/main.rs:5] n * factorial(n - 1) = 2
305 /// [src/main.rs:5] n * factorial(n - 1) = 6
306 /// [src/main.rs:5] n * factorial(n - 1) = 24
307 /// [src/main.rs:11] factorial(4) = 24
310 /// The `dbg!(..)` macro moves the input:
313 /// #![feature(dbg_macro)]
315 /// /// A wrapper around `usize` which importantly is not Copyable.
317 /// struct NoCopy(usize);
319 /// let a = NoCopy(42);
320 /// let _ = dbg!(a); // <-- `a` is moved here.
321 /// let _ = dbg!(a); // <-- `a` is moved again; error!
324 /// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)
326 #[unstable(feature = "dbg_macro", issue = "54306")]
329 // Use of `match` here is intentional because it affects the lifetimes
330 // of temporaries - https://stackoverflow.com/a/48732525/1063961
333 eprintln!("[{}:{}] {} = {:#?}",
334 file!(), line!(), stringify!($val), &tmp);
342 #[unstable(feature = "await_macro", issue = "50547")]
343 #[allow_internal_unstable]
344 #[allow_internal_unsafe]
349 if let $crate::task::Poll::Ready(x) =
350 $crate::future::poll_in_task_cx(unsafe {
351 $crate::pin::Pin::new_unchecked(&mut pinned)
356 // FIXME(cramertj) prior to stabilizing await, we have to ensure that this
357 // can't be used to create a generator on stable via `|| await!()`.
363 /// A macro to select an event from a number of receivers.
365 /// This macro is used to wait for the first event to occur on a number of
366 /// receivers. It places no restrictions on the types of receivers given to
367 /// this macro, this can be viewed as a heterogeneous select.
372 /// #![feature(mpsc_select)]
375 /// use std::sync::mpsc;
377 /// // two placeholder functions for now
378 /// fn long_running_thread() {}
379 /// fn calculate_the_answer() -> u32 { 42 }
381 /// let (tx1, rx1) = mpsc::channel();
382 /// let (tx2, rx2) = mpsc::channel();
384 /// thread::spawn(move|| { long_running_thread(); tx1.send(()).unwrap(); });
385 /// thread::spawn(move|| { tx2.send(calculate_the_answer()).unwrap(); });
388 /// _ = rx1.recv() => println!("the long running thread finished first"),
389 /// answer = rx2.recv() => {
390 /// println!("the answer was: {}", answer.unwrap());
393 /// # drop(rx1.recv());
394 /// # drop(rx2.recv());
397 /// For more information about select, see the `std::sync::mpsc::Select` structure.
399 #[unstable(feature = "mpsc_select", issue = "27800")]
400 macro_rules! select {
402 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
404 use $crate::sync::mpsc::Select;
405 let sel = Select::new();
406 $( let mut $rx = sel.handle(&$rx); )+
410 let ret = sel.wait();
411 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
417 macro_rules! assert_approx_eq {
418 ($a:expr, $b:expr) => ({
419 let (a, b) = (&$a, &$b);
420 assert!((*a - *b).abs() < 1.0e-6,
421 "{} is not approximately equal to {}", *a, *b);
425 /// Built-in macros to the compiler itself.
427 /// These macros do not have any corresponding definition with a `macro_rules!`
428 /// macro, but are documented here. Their implementations can be found hardcoded
429 /// into libsyntax itself.
433 /// Unconditionally causes compilation to fail with the given error message when encountered.
435 /// This macro should be used when a crate uses a conditional compilation strategy to provide
436 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
437 /// which emits an error at *runtime*, rather than during compilation.
441 /// Two such examples are macros and `#[cfg]` environments.
443 /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
444 /// the compiler would still emit an error, but the error's message would not mention the two
448 /// macro_rules! give_me_foo_or_bar {
452 /// compile_error!("This macro only accepts `foo` or `bar`");
456 /// give_me_foo_or_bar!(neither);
457 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
460 /// Emit compiler error if one of a number of features isn't available.
463 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
464 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.")
467 /// [`panic!`]: ../std/macro.panic.html
468 #[stable(feature = "compile_error_macro", since = "1.20.0")]
469 #[rustc_doc_only_macro]
470 macro_rules! compile_error {
471 ($msg:expr) => ({ /* compiler built-in */ });
472 ($msg:expr,) => ({ /* compiler built-in */ });
475 /// The core macro for formatted string creation & output.
477 /// This macro functions by taking a formatting string literal containing
478 /// `{}` for each additional argument passed. `format_args!` prepares the
479 /// additional parameters to ensure the output can be interpreted as a string
480 /// and canonicalizes the arguments into a single type. Any value that implements
481 /// the [`Display`] trait can be passed to `format_args!`, as can any
482 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
484 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
485 /// passed to the macros within [`std::fmt`] for performing useful redirection.
486 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
487 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
488 /// heap allocations.
490 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
491 /// in `Debug` and `Display` contexts as seen below. The example also shows
492 /// that `Debug` and `Display` format to the same thing: the interpolated
493 /// format string in `format_args!`.
496 /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
497 /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
498 /// assert_eq!("1 foo 2", display);
499 /// assert_eq!(display, debug);
502 /// For more information, see the documentation in [`std::fmt`].
504 /// [`Display`]: ../std/fmt/trait.Display.html
505 /// [`Debug`]: ../std/fmt/trait.Debug.html
506 /// [`fmt::Arguments`]: ../std/fmt/struct.Arguments.html
507 /// [`std::fmt`]: ../std/fmt/index.html
508 /// [`format!`]: ../std/macro.format.html
509 /// [`write!`]: ../std/macro.write.html
510 /// [`println!`]: ../std/macro.println.html
517 /// let s = fmt::format(format_args!("hello {}", "world"));
518 /// assert_eq!(s, format!("hello {}", "world"));
520 #[stable(feature = "rust1", since = "1.0.0")]
521 #[rustc_doc_only_macro]
522 macro_rules! format_args {
523 ($fmt:expr) => ({ /* compiler built-in */ });
524 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ });
527 /// Inspect an environment variable at compile time.
529 /// This macro will expand to the value of the named environment variable at
530 /// compile time, yielding an expression of type `&'static str`.
532 /// If the environment variable is not defined, then a compilation error
533 /// will be emitted. To not emit a compile error, use the [`option_env!`]
536 /// [`option_env!`]: ../std/macro.option_env.html
541 /// let path: &'static str = env!("PATH");
542 /// println!("the $PATH variable at the time of compiling was: {}", path);
545 /// You can customize the error message by passing a string as the second
549 /// let doc: &'static str = env!("documentation", "what's that?!");
552 /// If the `documentation` environment variable is not defined, you'll get
553 /// the following error:
556 /// error: what's that?!
558 #[stable(feature = "rust1", since = "1.0.0")]
559 #[rustc_doc_only_macro]
561 ($name:expr) => ({ /* compiler built-in */ });
562 ($name:expr,) => ({ /* compiler built-in */ });
565 /// Optionally inspect an environment variable at compile time.
567 /// If the named environment variable is present at compile time, this will
568 /// expand into an expression of type `Option<&'static str>` whose value is
569 /// `Some` of the value of the environment variable. If the environment
570 /// variable is not present, then this will expand to `None`. See
571 /// [`Option<T>`][option] for more information on this type.
573 /// A compile time error is never emitted when using this macro regardless
574 /// of whether the environment variable is present or not.
576 /// [option]: ../std/option/enum.Option.html
581 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
582 /// println!("the secret key might be: {:?}", key);
584 #[stable(feature = "rust1", since = "1.0.0")]
585 #[rustc_doc_only_macro]
586 macro_rules! option_env {
587 ($name:expr) => ({ /* compiler built-in */ });
588 ($name:expr,) => ({ /* compiler built-in */ });
591 /// Concatenate identifiers into one identifier.
593 /// This macro takes any number of comma-separated identifiers, and
594 /// concatenates them all into one, yielding an expression which is a new
595 /// identifier. Note that hygiene makes it such that this macro cannot
596 /// capture local variables. Also, as a general rule, macros are only
597 /// allowed in item, statement or expression position. That means while
598 /// you may use this macro for referring to existing variables, functions or
599 /// modules etc, you cannot define a new one with it.
604 /// #![feature(concat_idents)]
607 /// fn foobar() -> u32 { 23 }
609 /// let f = concat_idents!(foo, bar);
610 /// println!("{}", f());
612 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
615 #[unstable(feature = "concat_idents_macro", issue = "29599")]
616 #[rustc_doc_only_macro]
617 macro_rules! concat_idents {
618 ($($e:ident),+) => ({ /* compiler built-in */ });
619 ($($e:ident,)+) => ({ /* compiler built-in */ });
622 /// Concatenates literals into a static string slice.
624 /// This macro takes any number of comma-separated literals, yielding an
625 /// expression of type `&'static str` which represents all of the literals
626 /// concatenated left-to-right.
628 /// Integer and floating point literals are stringified in order to be
634 /// let s = concat!("test", 10, 'b', true);
635 /// assert_eq!(s, "test10btrue");
637 #[stable(feature = "rust1", since = "1.0.0")]
638 #[rustc_doc_only_macro]
639 macro_rules! concat {
640 ($($e:expr),*) => ({ /* compiler built-in */ });
641 ($($e:expr,)*) => ({ /* compiler built-in */ });
644 /// A macro which expands to the line number on which it was invoked.
646 /// With [`column!`] and [`file!`], these macros provide debugging information for
647 /// developers about the location within the source.
649 /// The expanded expression has type `u32` and is 1-based, so the first line
650 /// in each file evaluates to 1, the second to 2, etc. This is consistent
651 /// with error messages by common compilers or popular editors.
652 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
653 /// but rather the first macro invocation leading up to the invocation
654 /// of the `line!` macro.
656 /// [`column!`]: macro.column.html
657 /// [`file!`]: macro.file.html
662 /// let current_line = line!();
663 /// println!("defined on line: {}", current_line);
665 #[stable(feature = "rust1", since = "1.0.0")]
666 #[rustc_doc_only_macro]
667 macro_rules! line { () => ({ /* compiler built-in */ }) }
669 /// A macro which expands to the column number on which it was invoked.
671 /// With [`line!`] and [`file!`], these macros provide debugging information for
672 /// developers about the location within the source.
674 /// The expanded expression has type `u32` and is 1-based, so the first column
675 /// in each line evaluates to 1, the second to 2, etc. This is consistent
676 /// with error messages by common compilers or popular editors.
677 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
678 /// but rather the first macro invocation leading up to the invocation
679 /// of the `column!` macro.
681 /// [`line!`]: macro.line.html
682 /// [`file!`]: macro.file.html
687 /// let current_col = column!();
688 /// println!("defined on column: {}", current_col);
690 #[stable(feature = "rust1", since = "1.0.0")]
691 #[rustc_doc_only_macro]
692 macro_rules! column { () => ({ /* compiler built-in */ }) }
694 /// A macro which expands to the file name from which it was invoked.
696 /// With [`line!`] and [`column!`], these macros provide debugging information for
697 /// developers about the location within the source.
700 /// The expanded expression has type `&'static str`, and the returned file
701 /// is not the invocation of the `file!` macro itself, but rather the
702 /// first macro invocation leading up to the invocation of the `file!`
705 /// [`line!`]: macro.line.html
706 /// [`column!`]: macro.column.html
711 /// let this_file = file!();
712 /// println!("defined in file: {}", this_file);
714 #[stable(feature = "rust1", since = "1.0.0")]
715 #[rustc_doc_only_macro]
716 macro_rules! file { () => ({ /* compiler built-in */ }) }
718 /// A macro which stringifies its arguments.
720 /// This macro will yield an expression of type `&'static str` which is the
721 /// stringification of all the tokens passed to the macro. No restrictions
722 /// are placed on the syntax of the macro invocation itself.
724 /// Note that the expanded results of the input tokens may change in the
725 /// future. You should be careful if you rely on the output.
730 /// let one_plus_one = stringify!(1 + 1);
731 /// assert_eq!(one_plus_one, "1 + 1");
733 #[stable(feature = "rust1", since = "1.0.0")]
734 #[rustc_doc_only_macro]
735 macro_rules! stringify { ($($t:tt)*) => ({ /* compiler built-in */ }) }
737 /// Includes a utf8-encoded file as a string.
739 /// The file is located relative to the current file. (similarly to how
740 /// modules are found)
742 /// This macro will yield an expression of type `&'static str` which is the
743 /// contents of the file.
747 /// Assume there are two files in the same directory with the following
750 /// File 'spanish.in':
758 /// ```ignore (cannot-doctest-external-file-dependency)
760 /// let my_str = include_str!("spanish.in");
761 /// assert_eq!(my_str, "adiós\n");
762 /// print!("{}", my_str);
766 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
767 #[stable(feature = "rust1", since = "1.0.0")]
768 #[rustc_doc_only_macro]
769 macro_rules! include_str {
770 ($file:expr) => ({ /* compiler built-in */ });
771 ($file:expr,) => ({ /* compiler built-in */ });
774 /// Includes a file as a reference to a byte array.
776 /// The file is located relative to the current file. (similarly to how
777 /// modules are found)
779 /// This macro will yield an expression of type `&'static [u8; N]` which is
780 /// the contents of the file.
784 /// Assume there are two files in the same directory with the following
787 /// File 'spanish.in':
795 /// ```ignore (cannot-doctest-external-file-dependency)
797 /// let bytes = include_bytes!("spanish.in");
798 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
799 /// print!("{}", String::from_utf8_lossy(bytes));
803 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
804 #[stable(feature = "rust1", since = "1.0.0")]
805 #[rustc_doc_only_macro]
806 macro_rules! include_bytes {
807 ($file:expr) => ({ /* compiler built-in */ });
808 ($file:expr,) => ({ /* compiler built-in */ });
811 /// Expands to a string that represents the current module path.
813 /// The current module path can be thought of as the hierarchy of modules
814 /// leading back up to the crate root. The first component of the path
815 /// returned is the name of the crate currently being compiled.
822 /// assert!(module_path!().ends_with("test"));
828 #[stable(feature = "rust1", since = "1.0.0")]
829 #[rustc_doc_only_macro]
830 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
832 /// Boolean evaluation of configuration flags, at compile-time.
834 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
835 /// boolean expression evaluation of configuration flags. This frequently
836 /// leads to less duplicated code.
838 /// The syntax given to this macro is the same syntax as [the `cfg`
839 /// attribute](../book/first-edition/conditional-compilation.html).
844 /// let my_directory = if cfg!(windows) {
845 /// "windows-specific-directory"
850 #[stable(feature = "rust1", since = "1.0.0")]
851 #[rustc_doc_only_macro]
852 macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
854 /// Parse a file as an expression or an item according to the context.
856 /// The file is located relative to the current file (similarly to how
857 /// modules are found).
859 /// Using this macro is often a bad idea, because if the file is
860 /// parsed as an expression, it is going to be placed in the
861 /// surrounding code unhygienically. This could result in variables
862 /// or functions being different from what the file expected if
863 /// there are variables or functions that have the same name in
864 /// the current file.
868 /// Assume there are two files in the same directory with the following
871 /// File 'monkeys.in':
873 /// ```ignore (only-for-syntax-highlight)
878 /// .collect::<String>()
883 /// ```ignore (cannot-doctest-external-file-dependency)
885 /// let my_string = include!("monkeys.in");
886 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
887 /// println!("{}", my_string);
891 /// Compiling 'main.rs' and running the resulting binary will print
893 #[stable(feature = "rust1", since = "1.0.0")]
894 #[rustc_doc_only_macro]
895 macro_rules! include {
896 ($file:expr) => ({ /* compiler built-in */ });
897 ($file:expr,) => ({ /* compiler built-in */ });
900 /// Ensure that a boolean expression is `true` at runtime.
902 /// This will invoke the [`panic!`] macro if the provided expression cannot be
903 /// evaluated to `true` at runtime.
907 /// Assertions are always checked in both debug and release builds, and cannot
908 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
909 /// release builds by default.
911 /// Unsafe code relies on `assert!` to enforce run-time invariants that, if
912 /// violated could lead to unsafety.
914 /// Other use-cases of `assert!` include [testing] and enforcing run-time
915 /// invariants in safe code (whose violation cannot result in unsafety).
917 /// # Custom Messages
919 /// This macro has a second form, where a custom panic message can
920 /// be provided with or without arguments for formatting. See [`std::fmt`]
921 /// for syntax for this form.
923 /// [`panic!`]: macro.panic.html
924 /// [`debug_assert!`]: macro.debug_assert.html
925 /// [testing]: ../book/second-edition/ch11-01-writing-tests.html#checking-results-with-the-assert-macro
926 /// [`std::fmt`]: ../std/fmt/index.html
931 /// // the panic message for these assertions is the stringified value of the
932 /// // expression given.
935 /// fn some_computation() -> bool { true } // a very simple function
937 /// assert!(some_computation());
939 /// // assert with a custom message
941 /// assert!(x, "x wasn't true!");
943 /// let a = 3; let b = 27;
944 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
946 #[stable(feature = "rust1", since = "1.0.0")]
947 #[rustc_doc_only_macro]
948 macro_rules! assert {
949 ($cond:expr) => ({ /* compiler built-in */ });
950 ($cond:expr,) => ({ /* compiler built-in */ });
951 ($cond:expr, $($arg:tt)+) => ({ /* compiler built-in */ });
955 /// A macro for defining `#[cfg]` if-else statements.
957 /// This is similar to the `if/elif` C preprocessor macro by allowing definition
958 /// of a cascade of `#[cfg]` cases, emitting the implementation which matches
961 /// This allows you to conveniently provide a long list `#[cfg]`'d blocks of code
962 /// without having to rewrite each clause multiple times.
963 macro_rules! cfg_if {
965 if #[cfg($($meta:meta),*)] { $($it:item)* }
971 $( ( ($($meta),*) ($($it)*) ), )*
977 macro_rules! __cfg_if_items {
978 (($($not:meta,)*) ; ) => {};
979 (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
980 __cfg_if_apply! { cfg(all(not(any($($not),*)), $($m,)*)), $($it)* }
981 __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
985 macro_rules! __cfg_if_apply {
986 ($m:meta, $($it:item)*) => {