]> git.lizzy.rs Git - rust.git/blob - library/std/src/macros.rs
Rollup merge of #101118 - devnexen:fs_getmode_bsd, r=Mark-Simulacrum
[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 /// Writing to non-blocking stdout can cause an error, which will lead
53 /// this macro to panic.
54 ///
55 /// # Examples
56 ///
57 /// ```
58 /// use std::io::{self, Write};
59 ///
60 /// print!("this ");
61 /// print!("will ");
62 /// print!("be ");
63 /// print!("on ");
64 /// print!("the ");
65 /// print!("same ");
66 /// print!("line ");
67 ///
68 /// io::stdout().flush().unwrap();
69 ///
70 /// print!("this string has a newline, why not choose println! instead?\n");
71 ///
72 /// io::stdout().flush().unwrap();
73 /// ```
74 #[macro_export]
75 #[stable(feature = "rust1", since = "1.0.0")]
76 #[cfg_attr(not(test), rustc_diagnostic_item = "print_macro")]
77 #[allow_internal_unstable(print_internals)]
78 macro_rules! print {
79     ($($arg:tt)*) => {{
80         $crate::io::_print($crate::format_args!($($arg)*));
81     }};
82 }
83
84 /// Prints to the standard output, with a newline.
85 ///
86 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
87 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`)).
88 ///
89 /// This macro uses the same syntax as [`format!`], but writes to the standard output instead.
90 /// See [`std::fmt`] for more information.
91 ///
92 /// The `println!` macro will lock the standard output on each call. If you call
93 /// `println!` within a hot loop, this behavior may be the bottleneck of the loop.
94 /// To avoid this, lock stdout with [`io::stdout().lock()`][lock]:
95 /// ```
96 /// use std::io::{stdout, Write};
97 ///
98 /// let mut lock = stdout().lock();
99 /// writeln!(lock, "hello world").unwrap();
100 /// ```
101 ///
102 /// Use `println!` only for the primary output of your program. Use
103 /// [`eprintln!`] instead to print error and progress messages.
104 ///
105 /// [`std::fmt`]: crate::fmt
106 /// [`eprintln!`]: crate::eprintln
107 /// [lock]: crate::io::Stdout
108 ///
109 /// # Panics
110 ///
111 /// Panics if writing to [`io::stdout`] fails.
112 ///
113 /// Writing to non-blocking stdout can cause an error, which will lead
114 /// this macro to panic.
115 ///
116 /// [`io::stdout`]: crate::io::stdout
117 ///
118 /// # Examples
119 ///
120 /// ```
121 /// println!(); // prints just a newline
122 /// println!("hello there!");
123 /// println!("format {} arguments", "some");
124 /// let local_variable = "some";
125 /// println!("format {local_variable} arguments");
126 /// ```
127 #[macro_export]
128 #[stable(feature = "rust1", since = "1.0.0")]
129 #[cfg_attr(not(test), rustc_diagnostic_item = "println_macro")]
130 #[allow_internal_unstable(print_internals, format_args_nl)]
131 macro_rules! println {
132     () => {
133         $crate::print!("\n")
134     };
135     ($($arg:tt)*) => {{
136         $crate::io::_print($crate::format_args_nl!($($arg)*));
137     }};
138 }
139
140 /// Prints to the standard error.
141 ///
142 /// Equivalent to the [`print!`] macro, except that output goes to
143 /// [`io::stderr`] instead of [`io::stdout`]. See [`print!`] for
144 /// example usage.
145 ///
146 /// Use `eprint!` only for error and progress messages. Use `print!`
147 /// instead for the primary output of your program.
148 ///
149 /// [`io::stderr`]: crate::io::stderr
150 /// [`io::stdout`]: crate::io::stdout
151 ///
152 /// # Panics
153 ///
154 /// Panics if writing to `io::stderr` fails.
155 ///
156 /// Writing to non-blocking stdout can cause an error, which will lead
157 /// this macro to panic.
158 ///
159 /// # Examples
160 ///
161 /// ```
162 /// eprint!("Error: Could not complete task");
163 /// ```
164 #[macro_export]
165 #[stable(feature = "eprint", since = "1.19.0")]
166 #[cfg_attr(not(test), rustc_diagnostic_item = "eprint_macro")]
167 #[allow_internal_unstable(print_internals)]
168 macro_rules! eprint {
169     ($($arg:tt)*) => {{
170         $crate::io::_eprint($crate::format_args!($($arg)*));
171     }};
172 }
173
174 /// Prints to the standard error, with a newline.
175 ///
176 /// Equivalent to the [`println!`] macro, except that output goes to
177 /// [`io::stderr`] instead of [`io::stdout`]. See [`println!`] for
178 /// example usage.
179 ///
180 /// Use `eprintln!` only for error and progress messages. Use `println!`
181 /// instead for the primary output of your program.
182 ///
183 /// [`io::stderr`]: crate::io::stderr
184 /// [`io::stdout`]: crate::io::stdout
185 /// [`println!`]: crate::println
186 ///
187 /// # Panics
188 ///
189 /// Panics if writing to `io::stderr` fails.
190 ///
191 /// Writing to non-blocking stdout can cause an error, which will lead
192 /// this macro to panic.
193 ///
194 /// # Examples
195 ///
196 /// ```
197 /// eprintln!("Error: Could not complete task");
198 /// ```
199 #[macro_export]
200 #[stable(feature = "eprint", since = "1.19.0")]
201 #[cfg_attr(not(test), rustc_diagnostic_item = "eprintln_macro")]
202 #[allow_internal_unstable(print_internals, format_args_nl)]
203 macro_rules! eprintln {
204     () => {
205         $crate::eprint!("\n")
206     };
207     ($($arg:tt)*) => {{
208         $crate::io::_eprint($crate::format_args_nl!($($arg)*));
209     }};
210 }
211
212 /// Prints and returns the value of a given expression for quick and dirty
213 /// debugging.
214 ///
215 /// An example:
216 ///
217 /// ```rust
218 /// let a = 2;
219 /// let b = dbg!(a * 2) + 1;
220 /// //      ^-- prints: [src/main.rs:2] a * 2 = 4
221 /// assert_eq!(b, 5);
222 /// ```
223 ///
224 /// The macro works by using the `Debug` implementation of the type of
225 /// the given expression to print the value to [stderr] along with the
226 /// source location of the macro invocation as well as the source code
227 /// of the expression.
228 ///
229 /// Invoking the macro on an expression moves and takes ownership of it
230 /// before returning the evaluated expression unchanged. If the type
231 /// of the expression does not implement `Copy` and you don't want
232 /// to give up ownership, you can instead borrow with `dbg!(&expr)`
233 /// for some expression `expr`.
234 ///
235 /// The `dbg!` macro works exactly the same in release builds.
236 /// This is useful when debugging issues that only occur in release
237 /// builds or when debugging in release mode is significantly faster.
238 ///
239 /// Note that the macro is intended as a debugging tool and therefore you
240 /// should avoid having uses of it in version control for long periods
241 /// (other than in tests and similar).
242 /// Debug output from production code is better done with other facilities
243 /// such as the [`debug!`] macro 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 #[cfg_attr(not(test), rustc_diagnostic_item = "dbg_macro")]
338 #[stable(feature = "dbg_macro", since = "1.32.0")]
339 macro_rules! dbg {
340     // NOTE: We cannot use `concat!` to make a static string as a format argument
341     // of `eprintln!` because `file!` could contain a `{` or
342     // `$val` expression could be a block (`{ .. }`), in which case the `eprintln!`
343     // will be malformed.
344     () => {
345         $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!())
346     };
347     ($val:expr $(,)?) => {
348         // Use of `match` here is intentional because it affects the lifetimes
349         // of temporaries - https://stackoverflow.com/a/48732525/1063961
350         match $val {
351             tmp => {
352                 $crate::eprintln!("[{}:{}] {} = {:#?}",
353                     $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
354                 tmp
355             }
356         }
357     };
358     ($($val:expr),+ $(,)?) => {
359         ($($crate::dbg!($val)),+,)
360     };
361 }
362
363 #[cfg(test)]
364 macro_rules! assert_approx_eq {
365     ($a:expr, $b:expr) => {{
366         let (a, b) = (&$a, &$b);
367         assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately equal to {}", *a, *b);
368     }};
369 }