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