]> git.proxmox.com Git - rustc.git/blob - src/libstd/macros.rs
New upstream version 1.39.0+dfsg1
[rustc.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 /// Panics the current thread.
8 ///
9 /// This allows a program to terminate immediately and provide feedback
10 /// to the caller of the program. `panic!` should be used when a program reaches
11 /// an unrecoverable state.
12 ///
13 /// This macro is the perfect way to assert conditions in example code and in
14 /// tests. `panic!` is closely tied with the `unwrap` method of both [`Option`]
15 /// and [`Result`][runwrap] enums. Both implementations call `panic!` when they are set
16 /// to None or Err variants.
17 ///
18 /// This macro is used to inject panic into a Rust thread, causing the thread to
19 /// panic entirely. Each thread's panic can be reaped as the `Box<Any>` type,
20 /// and the single-argument form of the `panic!` macro will be the value which
21 /// is transmitted.
22 ///
23 /// [`Result`] enum is often a better solution for recovering from errors than
24 /// using the `panic!` macro. This macro should be used to avoid proceeding using
25 /// incorrect values, such as from external sources. Detailed information about
26 /// error handling is found in the [book].
27 ///
28 /// The multi-argument form of this macro panics with a string and has the
29 /// [`format!`] syntax for building a string.
30 ///
31 /// See also the macro [`compile_error!`], for raising errors during compilation.
32 ///
33 /// [runwrap]: ../std/result/enum.Result.html#method.unwrap
34 /// [`Option`]: ../std/option/enum.Option.html#method.unwrap
35 /// [`Result`]: ../std/result/enum.Result.html
36 /// [`format!`]: ../std/macro.format.html
37 /// [`compile_error!`]: ../std/macro.compile_error.html
38 /// [book]: ../book/ch09-00-error-handling.html
39 ///
40 /// # Current implementation
41 ///
42 /// If the main thread panics it will terminate all your threads and end your
43 /// program with code `101`.
44 ///
45 /// # Examples
46 ///
47 /// ```should_panic
48 /// # #![allow(unreachable_code)]
49 /// panic!();
50 /// panic!("this is a terrible mistake!");
51 /// panic!(4); // panic with the value of 4 to be collected elsewhere
52 /// panic!("this is a {} {message}", "fancy", message = "message");
53 /// ```
54 #[macro_export]
55 #[stable(feature = "rust1", since = "1.0.0")]
56 #[allow_internal_unstable(libstd_sys_internals)]
57 macro_rules! panic {
58 () => ({
59 $crate::panic!("explicit panic")
60 });
61 ($msg:expr) => ({
62 $crate::rt::begin_panic($msg, &($crate::file!(), $crate::line!(), $crate::column!()))
63 });
64 ($msg:expr,) => ({
65 $crate::panic!($msg)
66 });
67 ($fmt:expr, $($arg:tt)+) => ({
68 $crate::rt::begin_panic_fmt(&$crate::format_args!($fmt, $($arg)+),
69 &($crate::file!(), $crate::line!(), $crate::column!()))
70 });
71 }
72
73 /// Prints to the standard output.
74 ///
75 /// Equivalent to the [`println!`] macro except that a newline is not printed at
76 /// the end of the message.
77 ///
78 /// Note that stdout is frequently line-buffered by default so it may be
79 /// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
80 /// immediately.
81 ///
82 /// Use `print!` only for the primary output of your program. Use
83 /// [`eprint!`] instead to print error and progress messages.
84 ///
85 /// [`println!`]: ../std/macro.println.html
86 /// [flush]: ../std/io/trait.Write.html#tymethod.flush
87 /// [`eprint!`]: ../std/macro.eprint.html
88 ///
89 /// # Panics
90 ///
91 /// Panics if writing to `io::stdout()` fails.
92 ///
93 /// # Examples
94 ///
95 /// ```
96 /// use std::io::{self, Write};
97 ///
98 /// print!("this ");
99 /// print!("will ");
100 /// print!("be ");
101 /// print!("on ");
102 /// print!("the ");
103 /// print!("same ");
104 /// print!("line ");
105 ///
106 /// io::stdout().flush().unwrap();
107 ///
108 /// print!("this string has a newline, why not choose println! instead?\n");
109 ///
110 /// io::stdout().flush().unwrap();
111 /// ```
112 #[macro_export]
113 #[stable(feature = "rust1", since = "1.0.0")]
114 #[allow_internal_unstable(print_internals)]
115 macro_rules! print {
116 ($($arg:tt)*) => ($crate::io::_print($crate::format_args!($($arg)*)));
117 }
118
119 /// Prints to the standard output, with a newline.
120 ///
121 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
122 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`)).
123 ///
124 /// Use the [`format!`] syntax to write data to the standard output.
125 /// See [`std::fmt`] for more information.
126 ///
127 /// Use `println!` only for the primary output of your program. Use
128 /// [`eprintln!`] instead to print error and progress messages.
129 ///
130 /// [`format!`]: ../std/macro.format.html
131 /// [`std::fmt`]: ../std/fmt/index.html
132 /// [`eprintln!`]: ../std/macro.eprintln.html
133 /// # Panics
134 ///
135 /// Panics if writing to `io::stdout` fails.
136 ///
137 /// # Examples
138 ///
139 /// ```
140 /// println!(); // prints just a newline
141 /// println!("hello there!");
142 /// println!("format {} arguments", "some");
143 /// ```
144 #[macro_export]
145 #[stable(feature = "rust1", since = "1.0.0")]
146 #[allow_internal_unstable(print_internals, format_args_nl)]
147 macro_rules! println {
148 () => ($crate::print!("\n"));
149 ($($arg:tt)*) => ({
150 $crate::io::_print($crate::format_args_nl!($($arg)*));
151 })
152 }
153
154 /// Prints to the standard error.
155 ///
156 /// Equivalent to the [`print!`] macro, except that output goes to
157 /// [`io::stderr`] instead of `io::stdout`. See [`print!`] for
158 /// example usage.
159 ///
160 /// Use `eprint!` only for error and progress messages. Use `print!`
161 /// instead for the primary output of your program.
162 ///
163 /// [`io::stderr`]: ../std/io/struct.Stderr.html
164 /// [`print!`]: ../std/macro.print.html
165 ///
166 /// # Panics
167 ///
168 /// Panics if writing to `io::stderr` fails.
169 ///
170 /// # Examples
171 ///
172 /// ```
173 /// eprint!("Error: Could not complete task");
174 /// ```
175 #[macro_export]
176 #[stable(feature = "eprint", since = "1.19.0")]
177 #[allow_internal_unstable(print_internals)]
178 macro_rules! eprint {
179 ($($arg:tt)*) => ($crate::io::_eprint($crate::format_args!($($arg)*)));
180 }
181
182 /// Prints to the standard error, with a newline.
183 ///
184 /// Equivalent to the [`println!`] macro, except that output goes to
185 /// [`io::stderr`] instead of `io::stdout`. See [`println!`] for
186 /// example usage.
187 ///
188 /// Use `eprintln!` only for error and progress messages. Use `println!`
189 /// instead for the primary output of your program.
190 ///
191 /// [`io::stderr`]: ../std/io/struct.Stderr.html
192 /// [`println!`]: ../std/macro.println.html
193 ///
194 /// # Panics
195 ///
196 /// Panics if writing to `io::stderr` fails.
197 ///
198 /// # Examples
199 ///
200 /// ```
201 /// eprintln!("Error: Could not complete task");
202 /// ```
203 #[macro_export]
204 #[stable(feature = "eprint", since = "1.19.0")]
205 #[allow_internal_unstable(print_internals, format_args_nl)]
206 macro_rules! eprintln {
207 () => ($crate::eprint!("\n"));
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 longer periods.
242 /// Use cases involving debug output that should be added to version control
243 /// are better served by macros such as [`debug!`] from the [`log`] crate.
244 ///
245 /// # Stability
246 ///
247 /// The exact output printed by this macro should not be relied upon
248 /// and is subject to future changes.
249 ///
250 /// # Panics
251 ///
252 /// Panics if writing to `io::stderr` fails.
253 ///
254 /// # Further examples
255 ///
256 /// With a method call:
257 ///
258 /// ```rust
259 /// fn foo(n: usize) {
260 /// if let Some(_) = dbg!(n.checked_sub(4)) {
261 /// // ...
262 /// }
263 /// }
264 ///
265 /// foo(3)
266 /// ```
267 ///
268 /// This prints to [stderr]:
269 ///
270 /// ```text,ignore
271 /// [src/main.rs:4] n.checked_sub(4) = None
272 /// ```
273 ///
274 /// Naive factorial implementation:
275 ///
276 /// ```rust
277 /// fn factorial(n: u32) -> u32 {
278 /// if dbg!(n <= 1) {
279 /// dbg!(1)
280 /// } else {
281 /// dbg!(n * factorial(n - 1))
282 /// }
283 /// }
284 ///
285 /// dbg!(factorial(4));
286 /// ```
287 ///
288 /// This prints to [stderr]:
289 ///
290 /// ```text,ignore
291 /// [src/main.rs:3] n <= 1 = false
292 /// [src/main.rs:3] n <= 1 = false
293 /// [src/main.rs:3] n <= 1 = false
294 /// [src/main.rs:3] n <= 1 = true
295 /// [src/main.rs:4] 1 = 1
296 /// [src/main.rs:5] n * factorial(n - 1) = 2
297 /// [src/main.rs:5] n * factorial(n - 1) = 6
298 /// [src/main.rs:5] n * factorial(n - 1) = 24
299 /// [src/main.rs:11] factorial(4) = 24
300 /// ```
301 ///
302 /// The `dbg!(..)` macro moves the input:
303 ///
304 /// ```compile_fail
305 /// /// A wrapper around `usize` which importantly is not Copyable.
306 /// #[derive(Debug)]
307 /// struct NoCopy(usize);
308 ///
309 /// let a = NoCopy(42);
310 /// let _ = dbg!(a); // <-- `a` is moved here.
311 /// let _ = dbg!(a); // <-- `a` is moved again; error!
312 /// ```
313 ///
314 /// You can also use `dbg!()` without a value to just print the
315 /// file and line whenever it's reached.
316 ///
317 /// Finally, if you want to `dbg!(..)` multiple values, it will treat them as
318 /// a tuple (and return it, too):
319 ///
320 /// ```
321 /// assert_eq!(dbg!(1usize, 2u32), (1, 2));
322 /// ```
323 ///
324 /// However, a single argument with a trailing comma will still not be treated
325 /// as a tuple, following the convention of ignoring trailing commas in macro
326 /// invocations. You can use a 1-tuple directly if you need one:
327 ///
328 /// ```
329 /// assert_eq!(1, dbg!(1u32,)); // trailing comma ignored
330 /// assert_eq!((1,), dbg!((1u32,))); // 1-tuple
331 /// ```
332 ///
333 /// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)
334 /// [`debug!`]: https://docs.rs/log/*/log/macro.debug.html
335 /// [`log`]: https://crates.io/crates/log
336 #[macro_export]
337 #[stable(feature = "dbg_macro", since = "1.32.0")]
338 macro_rules! dbg {
339 () => {
340 $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());
341 };
342 ($val:expr) => {
343 // Use of `match` here is intentional because it affects the lifetimes
344 // of temporaries - https://stackoverflow.com/a/48732525/1063961
345 match $val {
346 tmp => {
347 $crate::eprintln!("[{}:{}] {} = {:#?}",
348 $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
349 tmp
350 }
351 }
352 };
353 // Trailing comma with single argument is ignored
354 ($val:expr,) => { $crate::dbg!($val) };
355 ($($val:expr),+ $(,)?) => {
356 ($($crate::dbg!($val)),+,)
357 };
358 }
359
360 #[cfg(test)]
361 macro_rules! assert_approx_eq {
362 ($a:expr, $b:expr) => ({
363 let (a, b) = (&$a, &$b);
364 assert!((*a - *b).abs() < 1.0e-6,
365 "{} is not approximately equal to {}", *a, *b);
366 })
367 }