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