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