macros.rs.html -- source
Description: Source to the Rust file `src/libstd/macros.rs`.
Keywords: rust, rustlang, rust-lang

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320

    //! Standard library macros
    //!
    //! This modules contains a set of macros which are exported from the standard
    //! library. Each macro is available for use when linking against the standard
    //! library.

    #[doc(include = "../libcore/macros/panic.md")]
    #[macro_export]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[allow_internal_unstable(libstd_sys_internals)]
    macro_rules! panic {
        () => ({
            $crate::panic!("explicit panic")
        });
        ($msg:expr) => ({
            $crate::rt::begin_panic($msg, &($crate::file!(), $crate::line!(), $crate::column!()))
        });
        ($msg:expr,) => ({
            $crate::panic!($msg)
        });
        ($fmt:expr, $($arg:tt)+) => ({
            $crate::rt::begin_panic_fmt(&$crate::format_args!($fmt, $($arg)+),
                                        &($crate::file!(), $crate::line!(), $crate::column!()))
        });
    }

    /// Prints to the standard output.
    ///
    /// Equivalent to the [`println!`] macro except that a newline is not printed at
    /// the end of the message.
    ///
    /// Note that stdout is frequently line-buffered by default so it may be
    /// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
    /// immediately.
    ///
    /// Use `print!` only for the primary output of your program. Use
    /// [`eprint!`] instead to print error and progress messages.
    ///
    /// [`println!`]: ../std/macro.println.html
    /// [flush]: ../std/io/trait.Write.html#tymethod.flush
    /// [`eprint!`]: ../std/macro.eprint.html
    ///
    /// # Panics
    ///
    /// Panics if writing to `io::stdout()` fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::io::{self, Write};
    ///
    /// print!("this ");
    /// print!("will ");
    /// print!("be ");
    /// print!("on ");
    /// print!("the ");
    /// print!("same ");
    /// print!("line ");
    ///
    /// io::stdout().flush().unwrap();
    ///
    /// print!("this string has a newline, why not choose println! instead?\n");
    ///
    /// io::stdout().flush().unwrap();
    /// ```
    #[macro_export]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[allow_internal_unstable(print_internals)]
    macro_rules! print {
        ($($arg:tt)*) => ($crate::io::_print($crate::format_args!($($arg)*)));
    }

    /// Prints to the standard output, with a newline.
    ///
    /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
    /// (no additional CARRIAGE RETURN (`\r`/`U+000D`)).
    ///
    /// Use the [`format!`] syntax to write data to the standard output.
    /// See [`std::fmt`] for more information.
    ///
    /// Use `println!` only for the primary output of your program. Use
    /// [`eprintln!`] instead to print error and progress messages.
    ///
    /// [`format!`]: ../std/macro.format.html
    /// [`std::fmt`]: ../std/fmt/index.html
    /// [`eprintln!`]: ../std/macro.eprintln.html
    /// # Panics
    ///
    /// Panics if writing to `io::stdout` fails.
    ///
    /// # Examples
    ///
    /// ```
    /// println!(); // prints just a newline
    /// println!("hello there!");
    /// println!("format {} arguments", "some");
    /// ```
    #[macro_export]
    #[stable(feature = "rust1", since = "1.0.0")]
    #[allow_internal_unstable(print_internals, format_args_nl)]
    macro_rules! println {
        () => ($crate::print!("\n"));
        ($($arg:tt)*) => ({
            $crate::io::_print($crate::format_args_nl!($($arg)*));
        })
    }

    /// Prints to the standard error.
    ///
    /// Equivalent to the [`print!`] macro, except that output goes to
    /// [`io::stderr`] instead of `io::stdout`. See [`print!`] for
    /// example usage.
    ///
    /// Use `eprint!` only for error and progress messages. Use `print!`
    /// instead for the primary output of your program.
    ///
    /// [`io::stderr`]: ../std/io/struct.Stderr.html
    /// [`print!`]: ../std/macro.print.html
    ///
    /// # Panics
    ///
    /// Panics if writing to `io::stderr` fails.
    ///
    /// # Examples
    ///
    /// ```
    /// eprint!("Error: Could not complete task");
    /// ```
    #[macro_export]
    #[stable(feature = "eprint", since = "1.19.0")]
    #[allow_internal_unstable(print_internals)]
    macro_rules! eprint {
        ($($arg:tt)*) => ($crate::io::_eprint($crate::format_args!($($arg)*)));
    }

    /// Prints to the standard error, with a newline.
    ///
    /// Equivalent to the [`println!`] macro, except that output goes to
    /// [`io::stderr`] instead of `io::stdout`. See [`println!`] for
    /// example usage.
    ///
    /// Use `eprintln!` only for error and progress messages. Use `println!`
    /// instead for the primary output of your program.
    ///
    /// [`io::stderr`]: ../std/io/struct.Stderr.html
    /// [`println!`]: ../std/macro.println.html
    ///
    /// # Panics
    ///
    /// Panics if writing to `io::stderr` fails.
    ///
    /// # Examples
    ///
    /// ```
    /// eprintln!("Error: Could not complete task");
    /// ```
    #[macro_export]
    #[stable(feature = "eprint", since = "1.19.0")]
    #[allow_internal_unstable(print_internals, format_args_nl)]
    macro_rules! eprintln {
        () => ($crate::eprint!("\n"));
        ($($arg:tt)*) => ({
            $crate::io::_eprint($crate::format_args_nl!($($arg)*));
        })
    }

    /// Prints and returns the value of a given expression for quick and dirty
    /// debugging.
    ///
    /// An example:
    ///
    /// ```rust
    /// let a = 2;
    /// let b = dbg!(a * 2) + 1;
    /// //      ^-- prints: [src/main.rs:2] a * 2 = 4
    /// assert_eq!(b, 5);
    /// ```
    ///
    /// The macro works by using the `Debug` implementation of the type of
    /// the given expression to print the value to [stderr] along with the
    /// source location of the macro invocation as well as the source code
    /// of the expression.
    ///
    /// Invoking the macro on an expression moves and takes ownership of it
    /// before returning the evaluated expression unchanged. If the type
    /// of the expression does not implement `Copy` and you don't want
    /// to give up ownership, you can instead borrow with `dbg!(&expr)`
    /// for some expression `expr`.
    ///
    /// The `dbg!` macro works exactly the same in release builds.
    /// This is useful when debugging issues that only occur in release
    /// builds or when debugging in release mode is significantly faster.
    ///
    /// Note that the macro is intended as a debugging tool and therefore you
    /// should avoid having uses of it in version control for longer periods.
    /// Use cases involving debug output that should be added to version control
    /// are better served by macros such as [`debug!`] from the [`log`] crate.
    ///
    /// # Stability
    ///
    /// The exact output printed by this macro should not be relied upon
    /// and is subject to future changes.
    ///
    /// # Panics
    ///
    /// Panics if writing to `io::stderr` fails.
    ///
    /// # Further examples
    ///
    /// With a method call:
    ///
    /// ```rust
    /// fn foo(n: usize) {
    ///     if let Some(_) = dbg!(n.checked_sub(4)) {
    ///         // ...
    ///     }
    /// }
    ///
    /// foo(3)
    /// ```
    ///
    /// This prints to [stderr]:
    ///
    /// ```text,ignore
    /// [src/main.rs:4] n.checked_sub(4) = None
    /// ```
    ///
    /// Naive factorial implementation:
    ///
    /// ```rust
    /// fn factorial(n: u32) -> u32 {
    ///     if dbg!(n <= 1) {
    ///         dbg!(1)
    ///     } else {
    ///         dbg!(n * factorial(n - 1))
    ///     }
    /// }
    ///
    /// dbg!(factorial(4));
    /// ```
    ///
    /// This prints to [stderr]:
    ///
    /// ```text,ignore
    /// [src/main.rs:3] n <= 1 = false
    /// [src/main.rs:3] n <= 1 = false
    /// [src/main.rs:3] n <= 1 = false
    /// [src/main.rs:3] n <= 1 = true
    /// [src/main.rs:4] 1 = 1
    /// [src/main.rs:5] n * factorial(n - 1) = 2
    /// [src/main.rs:5] n * factorial(n - 1) = 6
    /// [src/main.rs:5] n * factorial(n - 1) = 24
    /// [src/main.rs:11] factorial(4) = 24
    /// ```
    ///
    /// The `dbg!(..)` macro moves the input:
    ///
    /// ```compile_fail
    /// /// A wrapper around `usize` which importantly is not Copyable.
    /// #[derive(Debug)]
    /// struct NoCopy(usize);
    ///
    /// let a = NoCopy(42);
    /// let _ = dbg!(a); // <-- `a` is moved here.
    /// let _ = dbg!(a); // <-- `a` is moved again; error!
    /// ```
    ///
    /// You can also use `dbg!()` without a value to just print the
    /// file and line whenever it's reached.
    ///
    /// Finally, if you want to `dbg!(..)` multiple values, it will treat them as
    /// a tuple (and return it, too):
    ///
    /// ```
    /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
    /// ```
    ///
    /// However, a single argument with a trailing comma will still not be treated
    /// as a tuple, following the convention of ignoring trailing commas in macro
    /// invocations. You can use a 1-tuple directly if you need one:
    ///
    /// ```
    /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
    /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
    /// ```
    ///
    /// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)
    /// [`debug!`]: https://docs.rs/log/*/log/macro.debug.html
    /// [`log`]: https://crates.io/crates/log
    #[macro_export]
    #[stable(feature = "dbg_macro", since = "1.32.0")]
    macro_rules! dbg {
        () => {
            $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());
        };
        ($val:expr) => {
            // Use of `match` here is intentional because it affects the lifetimes
            // of temporaries - https://stackoverflow.com/a/48732525/1063961
            match $val {
                tmp => {
                    $crate::eprintln!("[{}:{}] {} = {:#?}",
                        $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
                    tmp
                }
            }
        };
        // Trailing comma with single argument is ignored
        ($val:expr,) => { $crate::dbg!($val) };
        ($($val:expr),+ $(,)?) => {
            ($($crate::dbg!($val)),+,)
        };
    }

    #[cfg(test)]
    macro_rules! assert_approx_eq {
        ($a:expr, $b:expr) => {{
            let (a, b) = (&$a, &$b);
            assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately equal to {}", *a, *b);
        }};
    }