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