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