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