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