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