]> git.lizzy.rs Git - rust.git/blob - library/std/src/macros.rs
Rollup merge of #95040 - frank-king:fix/94981, r=Mark-Simulacrum
[rust.git] / library / std / src / macros.rs
1 //! Standard library macros
2 //!
3 //! This module contains a set of macros which are exported from the standard
4 //! library. Each macro is available for use when linking against the standard
5 //! library.
6
7 #[doc = include_str!("../../core/src/macros/panic.md")]
8 #[macro_export]
9 #[rustc_builtin_macro(std_panic)]
10 #[stable(feature = "rust1", since = "1.0.0")]
11 #[allow_internal_unstable(edition_panic)]
12 #[cfg_attr(not(test), rustc_diagnostic_item = "std_panic_macro")]
13 macro_rules! panic {
14     // Expands to either `$crate::panic::panic_2015` or `$crate::panic::panic_2021`
15     // depending on the edition of the caller.
16     ($($arg:tt)*) => {
17         /* compiler built-in */
18     };
19 }
20
21 /// Prints to the standard output.
22 ///
23 /// Equivalent to the [`println!`] macro except that a newline is not printed at
24 /// the end of the message.
25 ///
26 /// Note that stdout is frequently line-buffered by default so it may be
27 /// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
28 /// immediately.
29 ///
30 /// Use `print!` only for the primary output of your program. Use
31 /// [`eprint!`] instead to print error and progress messages.
32 ///
33 /// [flush]: crate::io::Write::flush
34 /// [`println!`]: crate::println
35 /// [`eprint!`]: crate::eprint
36 ///
37 /// # Panics
38 ///
39 /// Panics if writing to `io::stdout()` fails.
40 ///
41 /// # Examples
42 ///
43 /// ```
44 /// use std::io::{self, Write};
45 ///
46 /// print!("this ");
47 /// print!("will ");
48 /// print!("be ");
49 /// print!("on ");
50 /// print!("the ");
51 /// print!("same ");
52 /// print!("line ");
53 ///
54 /// io::stdout().flush().unwrap();
55 ///
56 /// print!("this string has a newline, why not choose println! instead?\n");
57 ///
58 /// io::stdout().flush().unwrap();
59 /// ```
60 #[macro_export]
61 #[stable(feature = "rust1", since = "1.0.0")]
62 #[cfg_attr(not(test), rustc_diagnostic_item = "print_macro")]
63 #[allow_internal_unstable(print_internals)]
64 macro_rules! print {
65     ($($arg:tt)*) => {{
66         $crate::io::_print($crate::format_args!($($arg)*));
67     }};
68 }
69
70 /// Prints to the standard output, with a newline.
71 ///
72 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
73 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`)).
74 ///
75 /// This macro uses the same syntax as [`format!`], but writes to the standard output instead.
76 /// See [`std::fmt`] for more information.
77 ///
78 /// Use `println!` only for the primary output of your program. Use
79 /// [`eprintln!`] instead to print error and progress messages.
80 ///
81 /// [`std::fmt`]: crate::fmt
82 /// [`eprintln!`]: crate::eprintln
83 ///
84 /// # Panics
85 ///
86 /// Panics if writing to [`io::stdout`] fails.
87 ///
88 /// [`io::stdout`]: crate::io::stdout
89 ///
90 /// # Examples
91 ///
92 /// ```
93 /// println!(); // prints just a newline
94 /// println!("hello there!");
95 /// println!("format {} arguments", "some");
96 /// ```
97 #[macro_export]
98 #[stable(feature = "rust1", since = "1.0.0")]
99 #[cfg_attr(not(test), rustc_diagnostic_item = "println_macro")]
100 #[allow_internal_unstable(print_internals, format_args_nl)]
101 macro_rules! println {
102     () => {
103         $crate::print!("\n")
104     };
105     ($($arg:tt)*) => {{
106         $crate::io::_print($crate::format_args_nl!($($arg)*));
107     }};
108 }
109
110 /// Prints to the standard error.
111 ///
112 /// Equivalent to the [`print!`] macro, except that output goes to
113 /// [`io::stderr`] instead of [`io::stdout`]. See [`print!`] for
114 /// example usage.
115 ///
116 /// Use `eprint!` only for error and progress messages. Use `print!`
117 /// instead for the primary output of your program.
118 ///
119 /// [`io::stderr`]: crate::io::stderr
120 /// [`io::stdout`]: crate::io::stdout
121 ///
122 /// # Panics
123 ///
124 /// Panics if writing to `io::stderr` fails.
125 ///
126 /// # Examples
127 ///
128 /// ```
129 /// eprint!("Error: Could not complete task");
130 /// ```
131 #[macro_export]
132 #[stable(feature = "eprint", since = "1.19.0")]
133 #[cfg_attr(not(test), rustc_diagnostic_item = "eprint_macro")]
134 #[allow_internal_unstable(print_internals)]
135 macro_rules! eprint {
136     ($($arg:tt)*) => {{
137         $crate::io::_eprint($crate::format_args!($($arg)*));
138     }};
139 }
140
141 /// Prints to the standard error, with a newline.
142 ///
143 /// Equivalent to the [`println!`] macro, except that output goes to
144 /// [`io::stderr`] instead of [`io::stdout`]. See [`println!`] for
145 /// example usage.
146 ///
147 /// Use `eprintln!` only for error and progress messages. Use `println!`
148 /// instead for the primary output of your program.
149 ///
150 /// [`io::stderr`]: crate::io::stderr
151 /// [`io::stdout`]: crate::io::stdout
152 /// [`println!`]: crate::println
153 ///
154 /// # Panics
155 ///
156 /// Panics if writing to `io::stderr` fails.
157 ///
158 /// # Examples
159 ///
160 /// ```
161 /// eprintln!("Error: Could not complete task");
162 /// ```
163 #[macro_export]
164 #[stable(feature = "eprint", since = "1.19.0")]
165 #[cfg_attr(not(test), rustc_diagnostic_item = "eprintln_macro")]
166 #[allow_internal_unstable(print_internals, format_args_nl)]
167 macro_rules! eprintln {
168     () => {
169         $crate::eprint!("\n")
170     };
171     ($($arg:tt)*) => {{
172         $crate::io::_eprint($crate::format_args_nl!($($arg)*));
173     }};
174 }
175
176 /// Prints and returns the value of a given expression for quick and dirty
177 /// debugging.
178 ///
179 /// An example:
180 ///
181 /// ```rust
182 /// let a = 2;
183 /// let b = dbg!(a * 2) + 1;
184 /// //      ^-- prints: [src/main.rs:2] a * 2 = 4
185 /// assert_eq!(b, 5);
186 /// ```
187 ///
188 /// The macro works by using the `Debug` implementation of the type of
189 /// the given expression to print the value to [stderr] along with the
190 /// source location of the macro invocation as well as the source code
191 /// of the expression.
192 ///
193 /// Invoking the macro on an expression moves and takes ownership of it
194 /// before returning the evaluated expression unchanged. If the type
195 /// of the expression does not implement `Copy` and you don't want
196 /// to give up ownership, you can instead borrow with `dbg!(&expr)`
197 /// for some expression `expr`.
198 ///
199 /// The `dbg!` macro works exactly the same in release builds.
200 /// This is useful when debugging issues that only occur in release
201 /// builds or when debugging in release mode is significantly faster.
202 ///
203 /// Note that the macro is intended as a debugging tool and therefore you
204 /// should avoid having uses of it in version control for long periods
205 /// (other than in tests and similar).
206 /// Debug output from production code is better done with other facilities
207 /// such as the [`debug!`] macro from the [`log`] crate.
208 ///
209 /// # Stability
210 ///
211 /// The exact output printed by this macro should not be relied upon
212 /// and is subject to future changes.
213 ///
214 /// # Panics
215 ///
216 /// Panics if writing to `io::stderr` fails.
217 ///
218 /// # Further examples
219 ///
220 /// With a method call:
221 ///
222 /// ```rust
223 /// fn foo(n: usize) {
224 ///     if let Some(_) = dbg!(n.checked_sub(4)) {
225 ///         // ...
226 ///     }
227 /// }
228 ///
229 /// foo(3)
230 /// ```
231 ///
232 /// This prints to [stderr]:
233 ///
234 /// ```text,ignore
235 /// [src/main.rs:4] n.checked_sub(4) = None
236 /// ```
237 ///
238 /// Naive factorial implementation:
239 ///
240 /// ```rust
241 /// fn factorial(n: u32) -> u32 {
242 ///     if dbg!(n <= 1) {
243 ///         dbg!(1)
244 ///     } else {
245 ///         dbg!(n * factorial(n - 1))
246 ///     }
247 /// }
248 ///
249 /// dbg!(factorial(4));
250 /// ```
251 ///
252 /// This prints to [stderr]:
253 ///
254 /// ```text,ignore
255 /// [src/main.rs:3] n <= 1 = false
256 /// [src/main.rs:3] n <= 1 = false
257 /// [src/main.rs:3] n <= 1 = false
258 /// [src/main.rs:3] n <= 1 = true
259 /// [src/main.rs:4] 1 = 1
260 /// [src/main.rs:5] n * factorial(n - 1) = 2
261 /// [src/main.rs:5] n * factorial(n - 1) = 6
262 /// [src/main.rs:5] n * factorial(n - 1) = 24
263 /// [src/main.rs:11] factorial(4) = 24
264 /// ```
265 ///
266 /// The `dbg!(..)` macro moves the input:
267 ///
268 /// ```compile_fail
269 /// /// A wrapper around `usize` which importantly is not Copyable.
270 /// #[derive(Debug)]
271 /// struct NoCopy(usize);
272 ///
273 /// let a = NoCopy(42);
274 /// let _ = dbg!(a); // <-- `a` is moved here.
275 /// let _ = dbg!(a); // <-- `a` is moved again; error!
276 /// ```
277 ///
278 /// You can also use `dbg!()` without a value to just print the
279 /// file and line whenever it's reached.
280 ///
281 /// Finally, if you want to `dbg!(..)` multiple values, it will treat them as
282 /// a tuple (and return it, too):
283 ///
284 /// ```
285 /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
286 /// ```
287 ///
288 /// However, a single argument with a trailing comma will still not be treated
289 /// as a tuple, following the convention of ignoring trailing commas in macro
290 /// invocations. You can use a 1-tuple directly if you need one:
291 ///
292 /// ```
293 /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
294 /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
295 /// ```
296 ///
297 /// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)
298 /// [`debug!`]: https://docs.rs/log/*/log/macro.debug.html
299 /// [`log`]: https://crates.io/crates/log
300 #[macro_export]
301 #[cfg_attr(not(test), rustc_diagnostic_item = "dbg_macro")]
302 #[stable(feature = "dbg_macro", since = "1.32.0")]
303 macro_rules! dbg {
304     // NOTE: We cannot use `concat!` to make a static string as a format argument
305     // of `eprintln!` because `file!` could contain a `{` or
306     // `$val` expression could be a block (`{ .. }`), in which case the `eprintln!`
307     // will be malformed.
308     () => {
309         $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!())
310     };
311     ($val:expr $(,)?) => {
312         // Use of `match` here is intentional because it affects the lifetimes
313         // of temporaries - https://stackoverflow.com/a/48732525/1063961
314         match $val {
315             tmp => {
316                 $crate::eprintln!("[{}:{}] {} = {:#?}",
317                     $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
318                 tmp
319             }
320         }
321     };
322     ($($val:expr),+ $(,)?) => {
323         ($($crate::dbg!($val)),+,)
324     };
325 }
326
327 #[cfg(test)]
328 macro_rules! assert_approx_eq {
329     ($a:expr, $b:expr) => {{
330         let (a, b) = (&$a, &$b);
331         assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately equal to {}", *a, *b);
332     }};
333 }