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