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