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