1 | #[doc = include_str!("panic.md" )] |
2 | #[macro_export ] |
3 | #[rustc_builtin_macro (core_panic)] |
4 | #[allow_internal_unstable (edition_panic)] |
5 | #[stable (feature = "core" , since = "1.6.0" )] |
6 | #[rustc_diagnostic_item = "core_panic_macro" ] |
7 | macro_rules! panic { |
8 | // Expands to either `$crate::panic::panic_2015` or `$crate::panic::panic_2021` |
9 | // depending on the edition of the caller. |
10 | ($($arg:tt)*) => { |
11 | /* compiler built-in */ |
12 | }; |
13 | } |
14 | |
15 | /// Asserts that two expressions are equal to each other (using [`PartialEq`]). |
16 | /// |
17 | /// Assertions are always checked in both debug and release builds, and cannot |
18 | /// be disabled. See [`debug_assert_eq!`] for assertions that are disabled in |
19 | /// release builds by default. |
20 | /// |
21 | /// [`debug_assert_eq!`]: crate::debug_assert_eq |
22 | /// |
23 | /// On panic, this macro will print the values of the expressions with their |
24 | /// debug representations. |
25 | /// |
26 | /// Like [`assert!`], this macro has a second form, where a custom |
27 | /// panic message can be provided. |
28 | /// |
29 | /// # Examples |
30 | /// |
31 | /// ``` |
32 | /// let a = 3; |
33 | /// let b = 1 + 2; |
34 | /// assert_eq!(a, b); |
35 | /// |
36 | /// assert_eq!(a, b, "we are testing addition with {} and {}" , a, b); |
37 | /// ``` |
38 | #[macro_export ] |
39 | #[stable (feature = "rust1" , since = "1.0.0" )] |
40 | #[rustc_diagnostic_item = "assert_eq_macro" ] |
41 | #[allow_internal_unstable (panic_internals)] |
42 | macro_rules! assert_eq { |
43 | ($left:expr, $right:expr $(,)?) => { |
44 | match (&$left, &$right) { |
45 | (left_val, right_val) => { |
46 | if !(*left_val == *right_val) { |
47 | let kind = $crate::panicking::AssertKind::Eq; |
48 | // The reborrows below are intentional. Without them, the stack slot for the |
49 | // borrow is initialized even before the values are compared, leading to a |
50 | // noticeable slow down. |
51 | $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None); |
52 | } |
53 | } |
54 | } |
55 | }; |
56 | ($left:expr, $right:expr, $($arg:tt)+) => { |
57 | match (&$left, &$right) { |
58 | (left_val, right_val) => { |
59 | if !(*left_val == *right_val) { |
60 | let kind = $crate::panicking::AssertKind::Eq; |
61 | // The reborrows below are intentional. Without them, the stack slot for the |
62 | // borrow is initialized even before the values are compared, leading to a |
63 | // noticeable slow down. |
64 | $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::Some($crate::format_args!($($arg)+))); |
65 | } |
66 | } |
67 | } |
68 | }; |
69 | } |
70 | |
71 | /// Asserts that two expressions are not equal to each other (using [`PartialEq`]). |
72 | /// |
73 | /// Assertions are always checked in both debug and release builds, and cannot |
74 | /// be disabled. See [`debug_assert_ne!`] for assertions that are disabled in |
75 | /// release builds by default. |
76 | /// |
77 | /// [`debug_assert_ne!`]: crate::debug_assert_ne |
78 | /// |
79 | /// On panic, this macro will print the values of the expressions with their |
80 | /// debug representations. |
81 | /// |
82 | /// Like [`assert!`], this macro has a second form, where a custom |
83 | /// panic message can be provided. |
84 | /// |
85 | /// # Examples |
86 | /// |
87 | /// ``` |
88 | /// let a = 3; |
89 | /// let b = 2; |
90 | /// assert_ne!(a, b); |
91 | /// |
92 | /// assert_ne!(a, b, "we are testing that the values are not equal" ); |
93 | /// ``` |
94 | #[macro_export ] |
95 | #[stable (feature = "assert_ne" , since = "1.13.0" )] |
96 | #[rustc_diagnostic_item = "assert_ne_macro" ] |
97 | #[allow_internal_unstable (panic_internals)] |
98 | macro_rules! assert_ne { |
99 | ($left:expr, $right:expr $(,)?) => { |
100 | match (&$left, &$right) { |
101 | (left_val, right_val) => { |
102 | if *left_val == *right_val { |
103 | let kind = $crate::panicking::AssertKind::Ne; |
104 | // The reborrows below are intentional. Without them, the stack slot for the |
105 | // borrow is initialized even before the values are compared, leading to a |
106 | // noticeable slow down. |
107 | $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None); |
108 | } |
109 | } |
110 | } |
111 | }; |
112 | ($left:expr, $right:expr, $($arg:tt)+) => { |
113 | match (&($left), &($right)) { |
114 | (left_val, right_val) => { |
115 | if *left_val == *right_val { |
116 | let kind = $crate::panicking::AssertKind::Ne; |
117 | // The reborrows below are intentional. Without them, the stack slot for the |
118 | // borrow is initialized even before the values are compared, leading to a |
119 | // noticeable slow down. |
120 | $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::Some($crate::format_args!($($arg)+))); |
121 | } |
122 | } |
123 | } |
124 | }; |
125 | } |
126 | |
127 | /// Asserts that an expression matches the provided pattern. |
128 | /// |
129 | /// This macro is generally preferable to `assert!(matches!(value, pattern))`, because it can print |
130 | /// the debug representation of the actual value shape that did not meet expectations. In contrast, |
131 | /// using [`assert!`] will only print that expectations were not met, but not why. |
132 | /// |
133 | /// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The |
134 | /// optional if guard can be used to add additional checks that must be true for the matched value, |
135 | /// otherwise this macro will panic. |
136 | /// |
137 | /// Assertions are always checked in both debug and release builds, and cannot |
138 | /// be disabled. See [`debug_assert_matches!`] for assertions that are disabled in |
139 | /// release builds by default. |
140 | /// |
141 | /// [`debug_assert_matches!`]: crate::assert_matches::debug_assert_matches |
142 | /// |
143 | /// On panic, this macro will print the value of the expression with its debug representation. |
144 | /// |
145 | /// Like [`assert!`], this macro has a second form, where a custom panic message can be provided. |
146 | /// |
147 | /// # Examples |
148 | /// |
149 | /// ``` |
150 | /// #![feature(assert_matches)] |
151 | /// |
152 | /// use std::assert_matches::assert_matches; |
153 | /// |
154 | /// let a = Some(345); |
155 | /// let b = Some(56); |
156 | /// assert_matches!(a, Some(_)); |
157 | /// assert_matches!(b, Some(_)); |
158 | /// |
159 | /// assert_matches!(a, Some(345)); |
160 | /// assert_matches!(a, Some(345) | None); |
161 | /// |
162 | /// // assert_matches!(a, None); // panics |
163 | /// // assert_matches!(b, Some(345)); // panics |
164 | /// // assert_matches!(b, Some(345) | None); // panics |
165 | /// |
166 | /// assert_matches!(a, Some(x) if x > 100); |
167 | /// // assert_matches!(a, Some(x) if x < 100); // panics |
168 | /// ``` |
169 | #[unstable (feature = "assert_matches" , issue = "82775" )] |
170 | #[allow_internal_unstable (panic_internals)] |
171 | #[rustc_macro_transparency = "semitransparent" ] |
172 | pub macro assert_matches { |
173 | ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => { |
174 | match $left { |
175 | $( $pattern )|+ $( if $guard )? => {} |
176 | ref left_val => { |
177 | $crate::panicking::assert_matches_failed( |
178 | left_val, |
179 | $crate::stringify!($($pattern)|+ $(if $guard)?), |
180 | $crate::option::Option::None |
181 | ); |
182 | } |
183 | } |
184 | }, |
185 | ($left:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )?, $($arg:tt)+) => { |
186 | match $left { |
187 | $( $pattern )|+ $( if $guard )? => {} |
188 | ref left_val => { |
189 | $crate::panicking::assert_matches_failed( |
190 | left_val, |
191 | $crate::stringify!($($pattern)|+ $(if $guard)?), |
192 | $crate::option::Option::Some($crate::format_args!($($arg)+)) |
193 | ); |
194 | } |
195 | } |
196 | }, |
197 | } |
198 | |
199 | /// A macro for defining `#[cfg]` match-like statements. |
200 | /// |
201 | /// It is similar to the `if/elif` C preprocessor macro by allowing definition of a cascade of |
202 | /// `#[cfg]` cases, emitting the implementation which matches first. |
203 | /// |
204 | /// This allows you to conveniently provide a long list `#[cfg]`'d blocks of code |
205 | /// without having to rewrite each clause multiple times. |
206 | /// |
207 | /// Trailing `_` wildcard match arms are **optional** and they indicate a fallback branch when |
208 | /// all previous declarations do not evaluate to true. |
209 | /// |
210 | /// # Example |
211 | /// |
212 | /// ``` |
213 | /// #![feature(cfg_select)] |
214 | /// |
215 | /// cfg_select! { |
216 | /// unix => { |
217 | /// fn foo() { /* unix specific functionality */ } |
218 | /// } |
219 | /// target_pointer_width = "32" => { |
220 | /// fn foo() { /* non-unix, 32-bit functionality */ } |
221 | /// } |
222 | /// _ => { |
223 | /// fn foo() { /* fallback implementation */ } |
224 | /// } |
225 | /// } |
226 | /// ``` |
227 | /// |
228 | /// If desired, it is possible to return expressions through the use of surrounding braces: |
229 | /// |
230 | /// ``` |
231 | /// #![feature(cfg_select)] |
232 | /// |
233 | /// let _some_string = cfg_select! {{ |
234 | /// unix => { "With great power comes great electricity bills" } |
235 | /// _ => { "Behind every successful diet is an unwatched pizza" } |
236 | /// }}; |
237 | /// ``` |
238 | #[unstable (feature = "cfg_select" , issue = "115585" )] |
239 | #[rustc_diagnostic_item = "cfg_select" ] |
240 | #[rustc_macro_transparency = "semitransparent" ] |
241 | pub macro cfg_select { |
242 | ({ $($tt:tt)* }) => {{ |
243 | $crate::cfg_select! { $($tt)* } |
244 | }}, |
245 | (_ => { $($output:tt)* }) => { |
246 | $($output)* |
247 | }, |
248 | ( |
249 | $cfg:meta => $output:tt |
250 | $($( $rest:tt )+)? |
251 | ) => { |
252 | #[cfg($cfg)] |
253 | $crate::cfg_select! { _ => $output } |
254 | $( |
255 | #[cfg(not($cfg))] |
256 | $crate::cfg_select! { $($rest)+ } |
257 | )? |
258 | }, |
259 | } |
260 | |
261 | /// Asserts that a boolean expression is `true` at runtime. |
262 | /// |
263 | /// This will invoke the [`panic!`] macro if the provided expression cannot be |
264 | /// evaluated to `true` at runtime. |
265 | /// |
266 | /// Like [`assert!`], this macro also has a second version, where a custom panic |
267 | /// message can be provided. |
268 | /// |
269 | /// # Uses |
270 | /// |
271 | /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non |
272 | /// optimized builds by default. An optimized build will not execute |
273 | /// `debug_assert!` statements unless `-C debug-assertions` is passed to the |
274 | /// compiler. This makes `debug_assert!` useful for checks that are too |
275 | /// expensive to be present in a release build but may be helpful during |
276 | /// development. The result of expanding `debug_assert!` is always type checked. |
277 | /// |
278 | /// An unchecked assertion allows a program in an inconsistent state to keep |
279 | /// running, which might have unexpected consequences but does not introduce |
280 | /// unsafety as long as this only happens in safe code. The performance cost |
281 | /// of assertions, however, is not measurable in general. Replacing [`assert!`] |
282 | /// with `debug_assert!` is thus only encouraged after thorough profiling, and |
283 | /// more importantly, only in safe code! |
284 | /// |
285 | /// # Examples |
286 | /// |
287 | /// ``` |
288 | /// // the panic message for these assertions is the stringified value of the |
289 | /// // expression given. |
290 | /// debug_assert!(true); |
291 | /// |
292 | /// fn some_expensive_computation() -> bool { true } // a very simple function |
293 | /// debug_assert!(some_expensive_computation()); |
294 | /// |
295 | /// // assert with a custom message |
296 | /// let x = true; |
297 | /// debug_assert!(x, "x wasn't true!" ); |
298 | /// |
299 | /// let a = 3; let b = 27; |
300 | /// debug_assert!(a + b == 30, "a = {}, b = {}" , a, b); |
301 | /// ``` |
302 | #[macro_export ] |
303 | #[stable (feature = "rust1" , since = "1.0.0" )] |
304 | #[rustc_diagnostic_item = "debug_assert_macro" ] |
305 | #[allow_internal_unstable (edition_panic)] |
306 | macro_rules! debug_assert { |
307 | ($($arg:tt)*) => { |
308 | if $crate::cfg!(debug_assertions) { |
309 | $crate::assert!($($arg)*); |
310 | } |
311 | }; |
312 | } |
313 | |
314 | /// Asserts that two expressions are equal to each other. |
315 | /// |
316 | /// On panic, this macro will print the values of the expressions with their |
317 | /// debug representations. |
318 | /// |
319 | /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non |
320 | /// optimized builds by default. An optimized build will not execute |
321 | /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the |
322 | /// compiler. This makes `debug_assert_eq!` useful for checks that are too |
323 | /// expensive to be present in a release build but may be helpful during |
324 | /// development. The result of expanding `debug_assert_eq!` is always type checked. |
325 | /// |
326 | /// # Examples |
327 | /// |
328 | /// ``` |
329 | /// let a = 3; |
330 | /// let b = 1 + 2; |
331 | /// debug_assert_eq!(a, b); |
332 | /// ``` |
333 | #[macro_export ] |
334 | #[stable (feature = "rust1" , since = "1.0.0" )] |
335 | #[rustc_diagnostic_item = "debug_assert_eq_macro" ] |
336 | macro_rules! debug_assert_eq { |
337 | ($($arg:tt)*) => { |
338 | if $crate::cfg!(debug_assertions) { |
339 | $crate::assert_eq!($($arg)*); |
340 | } |
341 | }; |
342 | } |
343 | |
344 | /// Asserts that two expressions are not equal to each other. |
345 | /// |
346 | /// On panic, this macro will print the values of the expressions with their |
347 | /// debug representations. |
348 | /// |
349 | /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non |
350 | /// optimized builds by default. An optimized build will not execute |
351 | /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the |
352 | /// compiler. This makes `debug_assert_ne!` useful for checks that are too |
353 | /// expensive to be present in a release build but may be helpful during |
354 | /// development. The result of expanding `debug_assert_ne!` is always type checked. |
355 | /// |
356 | /// # Examples |
357 | /// |
358 | /// ``` |
359 | /// let a = 3; |
360 | /// let b = 2; |
361 | /// debug_assert_ne!(a, b); |
362 | /// ``` |
363 | #[macro_export ] |
364 | #[stable (feature = "assert_ne" , since = "1.13.0" )] |
365 | #[rustc_diagnostic_item = "debug_assert_ne_macro" ] |
366 | macro_rules! debug_assert_ne { |
367 | ($($arg:tt)*) => { |
368 | if $crate::cfg!(debug_assertions) { |
369 | $crate::assert_ne!($($arg)*); |
370 | } |
371 | }; |
372 | } |
373 | |
374 | /// Asserts that an expression matches the provided pattern. |
375 | /// |
376 | /// This macro is generally preferable to `debug_assert!(matches!(value, pattern))`, because it can |
377 | /// print the debug representation of the actual value shape that did not meet expectations. In |
378 | /// contrast, using [`debug_assert!`] will only print that expectations were not met, but not why. |
379 | /// |
380 | /// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The |
381 | /// optional if guard can be used to add additional checks that must be true for the matched value, |
382 | /// otherwise this macro will panic. |
383 | /// |
384 | /// On panic, this macro will print the value of the expression with its debug representation. |
385 | /// |
386 | /// Like [`assert!`], this macro has a second form, where a custom panic message can be provided. |
387 | /// |
388 | /// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only enabled in non optimized |
389 | /// builds by default. An optimized build will not execute `debug_assert_matches!` statements unless |
390 | /// `-C debug-assertions` is passed to the compiler. This makes `debug_assert_matches!` useful for |
391 | /// checks that are too expensive to be present in a release build but may be helpful during |
392 | /// development. The result of expanding `debug_assert_matches!` is always type checked. |
393 | /// |
394 | /// # Examples |
395 | /// |
396 | /// ``` |
397 | /// #![feature(assert_matches)] |
398 | /// |
399 | /// use std::assert_matches::debug_assert_matches; |
400 | /// |
401 | /// let a = Some(345); |
402 | /// let b = Some(56); |
403 | /// debug_assert_matches!(a, Some(_)); |
404 | /// debug_assert_matches!(b, Some(_)); |
405 | /// |
406 | /// debug_assert_matches!(a, Some(345)); |
407 | /// debug_assert_matches!(a, Some(345) | None); |
408 | /// |
409 | /// // debug_assert_matches!(a, None); // panics |
410 | /// // debug_assert_matches!(b, Some(345)); // panics |
411 | /// // debug_assert_matches!(b, Some(345) | None); // panics |
412 | /// |
413 | /// debug_assert_matches!(a, Some(x) if x > 100); |
414 | /// // debug_assert_matches!(a, Some(x) if x < 100); // panics |
415 | /// ``` |
416 | #[unstable (feature = "assert_matches" , issue = "82775" )] |
417 | #[allow_internal_unstable (assert_matches)] |
418 | #[rustc_macro_transparency = "semitransparent" ] |
419 | pub macro debug_assert_matches($($arg:tt)*) { |
420 | if $crate::cfg!(debug_assertions) { |
421 | $crate::assert_matches::assert_matches!($($arg)*); |
422 | } |
423 | } |
424 | |
425 | /// Returns whether the given expression matches the provided pattern. |
426 | /// |
427 | /// The pattern syntax is exactly the same as found in a match arm. The optional if guard can be |
428 | /// used to add additional checks that must be true for the matched value, otherwise this macro will |
429 | /// return `false`. |
430 | /// |
431 | /// When testing that a value matches a pattern, it's generally preferable to use |
432 | /// [`assert_matches!`] as it will print the debug representation of the value if the assertion |
433 | /// fails. |
434 | /// |
435 | /// # Examples |
436 | /// |
437 | /// ``` |
438 | /// let foo = 'f' ; |
439 | /// assert!(matches!(foo, 'A' ..='Z' | 'a' ..='z' )); |
440 | /// |
441 | /// let bar = Some(4); |
442 | /// assert!(matches!(bar, Some(x) if x > 2)); |
443 | /// ``` |
444 | #[macro_export ] |
445 | #[stable (feature = "matches_macro" , since = "1.42.0" )] |
446 | #[rustc_diagnostic_item = "matches_macro" ] |
447 | macro_rules! matches { |
448 | ($expression:expr, $pattern:pat $(if $guard:expr)? $(,)?) => { |
449 | match $expression { |
450 | $pattern $(if $guard)? => true, |
451 | _ => false |
452 | } |
453 | }; |
454 | } |
455 | |
456 | /// Unwraps a result or propagates its error. |
457 | /// |
458 | /// The [`?` operator][propagating-errors] was added to replace `try!` |
459 | /// and should be used instead. Furthermore, `try` is a reserved word |
460 | /// in Rust 2018, so if you must use it, you will need to use the |
461 | /// [raw-identifier syntax][ris]: `r#try`. |
462 | /// |
463 | /// [propagating-errors]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator |
464 | /// [ris]: https://doc.rust-lang.org/nightly/rust-by-example/compatibility/raw_identifiers.html |
465 | /// |
466 | /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the |
467 | /// expression has the value of the wrapped value. |
468 | /// |
469 | /// In case of the `Err` variant, it retrieves the inner error. `try!` then |
470 | /// performs conversion using `From`. This provides automatic conversion |
471 | /// between specialized errors and more general ones. The resulting |
472 | /// error is then immediately returned. |
473 | /// |
474 | /// Because of the early return, `try!` can only be used in functions that |
475 | /// return [`Result`]. |
476 | /// |
477 | /// # Examples |
478 | /// |
479 | /// ``` |
480 | /// use std::io; |
481 | /// use std::fs::File; |
482 | /// use std::io::prelude::*; |
483 | /// |
484 | /// enum MyError { |
485 | /// FileWriteError |
486 | /// } |
487 | /// |
488 | /// impl From<io::Error> for MyError { |
489 | /// fn from(e: io::Error) -> MyError { |
490 | /// MyError::FileWriteError |
491 | /// } |
492 | /// } |
493 | /// |
494 | /// // The preferred method of quick returning Errors |
495 | /// fn write_to_file_question() -> Result<(), MyError> { |
496 | /// let mut file = File::create("my_best_friends.txt" )?; |
497 | /// file.write_all(b"This is a list of my best friends." )?; |
498 | /// Ok(()) |
499 | /// } |
500 | /// |
501 | /// // The previous method of quick returning Errors |
502 | /// fn write_to_file_using_try() -> Result<(), MyError> { |
503 | /// let mut file = r#try!(File::create("my_best_friends.txt" )); |
504 | /// r#try!(file.write_all(b"This is a list of my best friends." )); |
505 | /// Ok(()) |
506 | /// } |
507 | /// |
508 | /// // This is equivalent to: |
509 | /// fn write_to_file_using_match() -> Result<(), MyError> { |
510 | /// let mut file = r#try!(File::create("my_best_friends.txt" )); |
511 | /// match file.write_all(b"This is a list of my best friends." ) { |
512 | /// Ok(v) => v, |
513 | /// Err(e) => return Err(From::from(e)), |
514 | /// } |
515 | /// Ok(()) |
516 | /// } |
517 | /// ``` |
518 | #[macro_export ] |
519 | #[stable (feature = "rust1" , since = "1.0.0" )] |
520 | #[deprecated (since = "1.39.0" , note = "use the `?` operator instead" )] |
521 | #[doc (alias = "?" )] |
522 | macro_rules! r#try { |
523 | ($expr:expr $(,)?) => { |
524 | match $expr { |
525 | $crate::result::Result::Ok(val) => val, |
526 | $crate::result::Result::Err(err) => { |
527 | return $crate::result::Result::Err($crate::convert::From::from(err)); |
528 | } |
529 | } |
530 | }; |
531 | } |
532 | |
533 | /// Writes formatted data into a buffer. |
534 | /// |
535 | /// This macro accepts a 'writer', a format string, and a list of arguments. Arguments will be |
536 | /// formatted according to the specified format string and the result will be passed to the writer. |
537 | /// The writer may be any value with a `write_fmt` method; generally this comes from an |
538 | /// implementation of either the [`fmt::Write`] or the [`io::Write`] trait. The macro |
539 | /// returns whatever the `write_fmt` method returns; commonly a [`fmt::Result`], or an |
540 | /// [`io::Result`]. |
541 | /// |
542 | /// See [`std::fmt`] for more information on the format string syntax. |
543 | /// |
544 | /// [`std::fmt`]: ../std/fmt/index.html |
545 | /// [`fmt::Write`]: crate::fmt::Write |
546 | /// [`io::Write`]: ../std/io/trait.Write.html |
547 | /// [`fmt::Result`]: crate::fmt::Result |
548 | /// [`io::Result`]: ../std/io/type.Result.html |
549 | /// |
550 | /// # Examples |
551 | /// |
552 | /// ``` |
553 | /// use std::io::Write; |
554 | /// |
555 | /// fn main() -> std::io::Result<()> { |
556 | /// let mut w = Vec::new(); |
557 | /// write!(&mut w, "test" )?; |
558 | /// write!(&mut w, "formatted {}" , "arguments" )?; |
559 | /// |
560 | /// assert_eq!(w, b"testformatted arguments" ); |
561 | /// Ok(()) |
562 | /// } |
563 | /// ``` |
564 | /// |
565 | /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects |
566 | /// implementing either, as objects do not typically implement both. However, the module must |
567 | /// avoid conflict between the trait names, such as by importing them as `_` or otherwise renaming |
568 | /// them: |
569 | /// |
570 | /// ``` |
571 | /// use std::fmt::Write as _; |
572 | /// use std::io::Write as _; |
573 | /// |
574 | /// fn main() -> Result<(), Box<dyn std::error::Error>> { |
575 | /// let mut s = String::new(); |
576 | /// let mut v = Vec::new(); |
577 | /// |
578 | /// write!(&mut s, "{} {}" , "abc" , 123)?; // uses fmt::Write::write_fmt |
579 | /// write!(&mut v, "s = {:?}" , s)?; // uses io::Write::write_fmt |
580 | /// assert_eq!(v, b"s = \"abc 123 \"" ); |
581 | /// Ok(()) |
582 | /// } |
583 | /// ``` |
584 | /// |
585 | /// If you also need the trait names themselves, such as to implement one or both on your types, |
586 | /// import the containing module and then name them with a prefix: |
587 | /// |
588 | /// ``` |
589 | /// # #![allow(unused_imports)] |
590 | /// use std::fmt::{self, Write as _}; |
591 | /// use std::io::{self, Write as _}; |
592 | /// |
593 | /// struct Example; |
594 | /// |
595 | /// impl fmt::Write for Example { |
596 | /// fn write_str(&mut self, _s: &str) -> core::fmt::Result { |
597 | /// unimplemented!(); |
598 | /// } |
599 | /// } |
600 | /// ``` |
601 | /// |
602 | /// Note: This macro can be used in `no_std` setups as well. |
603 | /// In a `no_std` setup you are responsible for the implementation details of the components. |
604 | /// |
605 | /// ```no_run |
606 | /// use core::fmt::Write; |
607 | /// |
608 | /// struct Example; |
609 | /// |
610 | /// impl Write for Example { |
611 | /// fn write_str(&mut self, _s: &str) -> core::fmt::Result { |
612 | /// unimplemented!(); |
613 | /// } |
614 | /// } |
615 | /// |
616 | /// let mut m = Example{}; |
617 | /// write!(&mut m, "Hello World" ).expect("Not written" ); |
618 | /// ``` |
619 | #[macro_export ] |
620 | #[stable (feature = "rust1" , since = "1.0.0" )] |
621 | #[rustc_diagnostic_item = "write_macro" ] |
622 | macro_rules! write { |
623 | ($dst:expr, $($arg:tt)*) => { |
624 | $dst.write_fmt($crate::format_args!($($arg)*)) |
625 | }; |
626 | } |
627 | |
628 | /// Writes formatted data into a buffer, with a newline appended. |
629 | /// |
630 | /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone |
631 | /// (no additional CARRIAGE RETURN (`\r`/`U+000D`). |
632 | /// |
633 | /// For more information, see [`write!`]. For information on the format string syntax, see |
634 | /// [`std::fmt`]. |
635 | /// |
636 | /// [`std::fmt`]: ../std/fmt/index.html |
637 | /// |
638 | /// # Examples |
639 | /// |
640 | /// ``` |
641 | /// use std::io::{Write, Result}; |
642 | /// |
643 | /// fn main() -> Result<()> { |
644 | /// let mut w = Vec::new(); |
645 | /// writeln!(&mut w)?; |
646 | /// writeln!(&mut w, "test" )?; |
647 | /// writeln!(&mut w, "formatted {}" , "arguments" )?; |
648 | /// |
649 | /// assert_eq!(&w[..], " \ntest \nformatted arguments \n" .as_bytes()); |
650 | /// Ok(()) |
651 | /// } |
652 | /// ``` |
653 | #[macro_export ] |
654 | #[stable (feature = "rust1" , since = "1.0.0" )] |
655 | #[rustc_diagnostic_item = "writeln_macro" ] |
656 | #[allow_internal_unstable (format_args_nl)] |
657 | macro_rules! writeln { |
658 | ($dst:expr $(,)?) => { |
659 | $crate::write!($dst, " \n" ) |
660 | }; |
661 | ($dst:expr, $($arg:tt)*) => { |
662 | $dst.write_fmt($crate::format_args_nl!($($arg)*)) |
663 | }; |
664 | } |
665 | |
666 | /// Indicates unreachable code. |
667 | /// |
668 | /// This is useful any time that the compiler can't determine that some code is unreachable. For |
669 | /// example: |
670 | /// |
671 | /// * Match arms with guard conditions. |
672 | /// * Loops that dynamically terminate. |
673 | /// * Iterators that dynamically terminate. |
674 | /// |
675 | /// If the determination that the code is unreachable proves incorrect, the |
676 | /// program immediately terminates with a [`panic!`]. |
677 | /// |
678 | /// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which |
679 | /// will cause undefined behavior if the code is reached. |
680 | /// |
681 | /// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked |
682 | /// |
683 | /// # Panics |
684 | /// |
685 | /// This will always [`panic!`] because `unreachable!` is just a shorthand for `panic!` with a |
686 | /// fixed, specific message. |
687 | /// |
688 | /// Like `panic!`, this macro has a second form for displaying custom values. |
689 | /// |
690 | /// # Examples |
691 | /// |
692 | /// Match arms: |
693 | /// |
694 | /// ``` |
695 | /// # #[allow (dead_code)] |
696 | /// fn foo(x: Option<i32>) { |
697 | /// match x { |
698 | /// Some(n) if n >= 0 => println!("Some(Non-negative)" ), |
699 | /// Some(n) if n < 0 => println!("Some(Negative)" ), |
700 | /// Some(_) => unreachable!(), // compile error if commented out |
701 | /// None => println!("None" ) |
702 | /// } |
703 | /// } |
704 | /// ``` |
705 | /// |
706 | /// Iterators: |
707 | /// |
708 | /// ``` |
709 | /// # #[allow (dead_code)] |
710 | /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3 |
711 | /// for i in 0.. { |
712 | /// if 3*i < i { panic!("u32 overflow" ); } |
713 | /// if x < 3*i { return i-1; } |
714 | /// } |
715 | /// unreachable!("The loop should always return" ); |
716 | /// } |
717 | /// ``` |
718 | #[macro_export ] |
719 | #[rustc_builtin_macro (unreachable)] |
720 | #[allow_internal_unstable (edition_panic)] |
721 | #[stable (feature = "rust1" , since = "1.0.0" )] |
722 | #[rustc_diagnostic_item = "unreachable_macro" ] |
723 | macro_rules! unreachable { |
724 | // Expands to either `$crate::panic::unreachable_2015` or `$crate::panic::unreachable_2021` |
725 | // depending on the edition of the caller. |
726 | ($($arg:tt)*) => { |
727 | /* compiler built-in */ |
728 | }; |
729 | } |
730 | |
731 | /// Indicates unimplemented code by panicking with a message of "not implemented". |
732 | /// |
733 | /// This allows your code to type-check, which is useful if you are prototyping or |
734 | /// implementing a trait that requires multiple methods which you don't plan to use all of. |
735 | /// |
736 | /// The difference between `unimplemented!` and [`todo!`] is that while `todo!` |
737 | /// conveys an intent of implementing the functionality later and the message is "not yet |
738 | /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented". |
739 | /// |
740 | /// Also, some IDEs will mark `todo!`s. |
741 | /// |
742 | /// # Panics |
743 | /// |
744 | /// This will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a |
745 | /// fixed, specific message. |
746 | /// |
747 | /// Like `panic!`, this macro has a second form for displaying custom values. |
748 | /// |
749 | /// [`todo!`]: crate::todo |
750 | /// |
751 | /// # Examples |
752 | /// |
753 | /// Say we have a trait `Foo`: |
754 | /// |
755 | /// ``` |
756 | /// trait Foo { |
757 | /// fn bar(&self) -> u8; |
758 | /// fn baz(&self); |
759 | /// fn qux(&self) -> Result<u64, ()>; |
760 | /// } |
761 | /// ``` |
762 | /// |
763 | /// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense |
764 | /// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined |
765 | /// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions |
766 | /// to allow our code to compile. |
767 | /// |
768 | /// We still want to have our program stop running if the unimplemented methods are |
769 | /// reached. |
770 | /// |
771 | /// ``` |
772 | /// # trait Foo { |
773 | /// # fn bar(&self) -> u8; |
774 | /// # fn baz(&self); |
775 | /// # fn qux(&self) -> Result<u64, ()>; |
776 | /// # } |
777 | /// struct MyStruct; |
778 | /// |
779 | /// impl Foo for MyStruct { |
780 | /// fn bar(&self) -> u8 { |
781 | /// 1 + 1 |
782 | /// } |
783 | /// |
784 | /// fn baz(&self) { |
785 | /// // It makes no sense to `baz` a `MyStruct`, so we have no logic here |
786 | /// // at all. |
787 | /// // This will display "thread 'main' panicked at 'not implemented'". |
788 | /// unimplemented!(); |
789 | /// } |
790 | /// |
791 | /// fn qux(&self) -> Result<u64, ()> { |
792 | /// // We have some logic here, |
793 | /// // We can add a message to unimplemented! to display our omission. |
794 | /// // This will display: |
795 | /// // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'". |
796 | /// unimplemented!("MyStruct isn't quxable" ); |
797 | /// } |
798 | /// } |
799 | /// |
800 | /// fn main() { |
801 | /// let s = MyStruct; |
802 | /// s.bar(); |
803 | /// } |
804 | /// ``` |
805 | #[macro_export ] |
806 | #[stable (feature = "rust1" , since = "1.0.0" )] |
807 | #[rustc_diagnostic_item = "unimplemented_macro" ] |
808 | #[allow_internal_unstable (panic_internals)] |
809 | macro_rules! unimplemented { |
810 | () => { |
811 | $crate::panicking::panic("not implemented" ) |
812 | }; |
813 | ($($arg:tt)+) => { |
814 | $crate::panic!("not implemented: {}" , $crate::format_args!($($arg)+)) |
815 | }; |
816 | } |
817 | |
818 | /// Indicates unfinished code. |
819 | /// |
820 | /// This can be useful if you are prototyping and just |
821 | /// want a placeholder to let your code pass type analysis. |
822 | /// |
823 | /// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys |
824 | /// an intent of implementing the functionality later and the message is "not yet |
825 | /// implemented", `unimplemented!` makes no such claims. Its message is "not implemented". |
826 | /// |
827 | /// Also, some IDEs will mark `todo!`s. |
828 | /// |
829 | /// # Panics |
830 | /// |
831 | /// This will always [`panic!`] because `todo!` is just a shorthand for `panic!` with a |
832 | /// fixed, specific message. |
833 | /// |
834 | /// Like `panic!`, this macro has a second form for displaying custom values. |
835 | /// |
836 | /// # Examples |
837 | /// |
838 | /// Here's an example of some in-progress code. We have a trait `Foo`: |
839 | /// |
840 | /// ``` |
841 | /// trait Foo { |
842 | /// fn bar(&self) -> u8; |
843 | /// fn baz(&self); |
844 | /// fn qux(&self) -> Result<u64, ()>; |
845 | /// } |
846 | /// ``` |
847 | /// |
848 | /// We want to implement `Foo` on one of our types, but we also want to work on |
849 | /// just `bar()` first. In order for our code to compile, we need to implement |
850 | /// `baz()` and `qux()`, so we can use `todo!`: |
851 | /// |
852 | /// ``` |
853 | /// # trait Foo { |
854 | /// # fn bar(&self) -> u8; |
855 | /// # fn baz(&self); |
856 | /// # fn qux(&self) -> Result<u64, ()>; |
857 | /// # } |
858 | /// struct MyStruct; |
859 | /// |
860 | /// impl Foo for MyStruct { |
861 | /// fn bar(&self) -> u8 { |
862 | /// 1 + 1 |
863 | /// } |
864 | /// |
865 | /// fn baz(&self) { |
866 | /// // Let's not worry about implementing baz() for now |
867 | /// todo!(); |
868 | /// } |
869 | /// |
870 | /// fn qux(&self) -> Result<u64, ()> { |
871 | /// // We can add a message to todo! to display our omission. |
872 | /// // This will display: |
873 | /// // "thread 'main' panicked at 'not yet implemented: MyStruct is not yet quxable'". |
874 | /// todo!("MyStruct is not yet quxable" ); |
875 | /// } |
876 | /// } |
877 | /// |
878 | /// fn main() { |
879 | /// let s = MyStruct; |
880 | /// s.bar(); |
881 | /// |
882 | /// // We aren't even using baz() or qux(), so this is fine. |
883 | /// } |
884 | /// ``` |
885 | #[macro_export ] |
886 | #[stable (feature = "todo_macro" , since = "1.40.0" )] |
887 | #[rustc_diagnostic_item = "todo_macro" ] |
888 | #[allow_internal_unstable (panic_internals)] |
889 | macro_rules! todo { |
890 | () => { |
891 | $crate::panicking::panic("not yet implemented" ) |
892 | }; |
893 | ($($arg:tt)+) => { |
894 | $crate::panic!("not yet implemented: {}" , $crate::format_args!($($arg)+)) |
895 | }; |
896 | } |
897 | |
898 | /// Definitions of built-in macros. |
899 | /// |
900 | /// Most of the macro properties (stability, visibility, etc.) are taken from the source code here, |
901 | /// with exception of expansion functions transforming macro inputs into outputs, |
902 | /// those functions are provided by the compiler. |
903 | pub(crate) mod builtin { |
904 | |
905 | /// Causes compilation to fail with the given error message when encountered. |
906 | /// |
907 | /// This macro should be used when a crate uses a conditional compilation strategy to provide |
908 | /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`], |
909 | /// but emits an error during *compilation* rather than at *runtime*. |
910 | /// |
911 | /// # Examples |
912 | /// |
913 | /// Two such examples are macros and `#[cfg]` environments. |
914 | /// |
915 | /// Emit a better compiler error if a macro is passed invalid values. Without the final branch, |
916 | /// the compiler would still emit an error, but the error's message would not mention the two |
917 | /// valid values. |
918 | /// |
919 | /// ```compile_fail |
920 | /// macro_rules! give_me_foo_or_bar { |
921 | /// (foo) => {}; |
922 | /// (bar) => {}; |
923 | /// ($x:ident) => { |
924 | /// compile_error!("This macro only accepts `foo` or `bar`" ); |
925 | /// } |
926 | /// } |
927 | /// |
928 | /// give_me_foo_or_bar!(neither); |
929 | /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`" |
930 | /// ``` |
931 | /// |
932 | /// Emit a compiler error if one of a number of features isn't available. |
933 | /// |
934 | /// ```compile_fail |
935 | /// #[cfg(not(any(feature = "foo" , feature = "bar" )))] |
936 | /// compile_error!("Either feature \"foo \" or \"bar \" must be enabled for this crate." ); |
937 | /// ``` |
938 | #[stable (feature = "compile_error_macro" , since = "1.20.0" )] |
939 | #[rustc_builtin_macro ] |
940 | #[macro_export ] |
941 | macro_rules! compile_error { |
942 | ($msg:expr $(,)?) => {{ /* compiler built-in */ }}; |
943 | } |
944 | |
945 | /// Constructs parameters for the other string-formatting macros. |
946 | /// |
947 | /// This macro functions by taking a formatting string literal containing |
948 | /// `{}` for each additional argument passed. `format_args!` prepares the |
949 | /// additional parameters to ensure the output can be interpreted as a string |
950 | /// and canonicalizes the arguments into a single type. Any value that implements |
951 | /// the [`Display`] trait can be passed to `format_args!`, as can any |
952 | /// [`Debug`] implementation be passed to a `{:?}` within the formatting string. |
953 | /// |
954 | /// This macro produces a value of type [`fmt::Arguments`]. This value can be |
955 | /// passed to the macros within [`std::fmt`] for performing useful redirection. |
956 | /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are |
957 | /// proxied through this one. `format_args!`, unlike its derived macros, avoids |
958 | /// heap allocations. |
959 | /// |
960 | /// You can use the [`fmt::Arguments`] value that `format_args!` returns |
961 | /// in `Debug` and `Display` contexts as seen below. The example also shows |
962 | /// that `Debug` and `Display` format to the same thing: the interpolated |
963 | /// format string in `format_args!`. |
964 | /// |
965 | /// ```rust |
966 | /// let debug = format!("{:?}" , format_args!("{} foo {:?}" , 1, 2)); |
967 | /// let display = format!("{}" , format_args!("{} foo {:?}" , 1, 2)); |
968 | /// assert_eq!("1 foo 2" , display); |
969 | /// assert_eq!(display, debug); |
970 | /// ``` |
971 | /// |
972 | /// See [the formatting documentation in `std::fmt`](../std/fmt/index.html) |
973 | /// for details of the macro argument syntax, and further information. |
974 | /// |
975 | /// [`Display`]: crate::fmt::Display |
976 | /// [`Debug`]: crate::fmt::Debug |
977 | /// [`fmt::Arguments`]: crate::fmt::Arguments |
978 | /// [`std::fmt`]: ../std/fmt/index.html |
979 | /// [`format!`]: ../std/macro.format.html |
980 | /// [`println!`]: ../std/macro.println.html |
981 | /// |
982 | /// # Examples |
983 | /// |
984 | /// ``` |
985 | /// use std::fmt; |
986 | /// |
987 | /// let s = fmt::format(format_args!("hello {}" , "world" )); |
988 | /// assert_eq!(s, format!("hello {}" , "world" )); |
989 | /// ``` |
990 | /// |
991 | /// # Lifetime limitation |
992 | /// |
993 | /// Except when no formatting arguments are used, |
994 | /// the produced `fmt::Arguments` value borrows temporary values, |
995 | /// which means it can only be used within the same expression |
996 | /// and cannot be stored for later use. |
997 | /// This is a known limitation, see [#92698](https://github.com/rust-lang/rust/issues/92698). |
998 | #[stable (feature = "rust1" , since = "1.0.0" )] |
999 | #[rustc_diagnostic_item = "format_args_macro" ] |
1000 | #[allow_internal_unsafe ] |
1001 | #[allow_internal_unstable (fmt_internals)] |
1002 | #[rustc_builtin_macro ] |
1003 | #[macro_export ] |
1004 | macro_rules! format_args { |
1005 | ($fmt:expr) => {{ /* compiler built-in */ }}; |
1006 | ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }}; |
1007 | } |
1008 | |
1009 | /// Same as [`format_args`], but can be used in some const contexts. |
1010 | /// |
1011 | /// This macro is used by the panic macros for the `const_panic` feature. |
1012 | /// |
1013 | /// This macro will be removed once `format_args` is allowed in const contexts. |
1014 | #[unstable (feature = "const_format_args" , issue = "none" )] |
1015 | #[allow_internal_unstable (fmt_internals, const_fmt_arguments_new)] |
1016 | #[rustc_builtin_macro ] |
1017 | #[macro_export ] |
1018 | macro_rules! const_format_args { |
1019 | ($fmt:expr) => {{ /* compiler built-in */ }}; |
1020 | ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }}; |
1021 | } |
1022 | |
1023 | /// Same as [`format_args`], but adds a newline in the end. |
1024 | #[unstable ( |
1025 | feature = "format_args_nl" , |
1026 | issue = "none" , |
1027 | reason = "`format_args_nl` is only for internal \ |
1028 | language use and is subject to change" |
1029 | )] |
1030 | #[allow_internal_unstable (fmt_internals)] |
1031 | #[rustc_builtin_macro ] |
1032 | #[macro_export ] |
1033 | macro_rules! format_args_nl { |
1034 | ($fmt:expr) => {{ /* compiler built-in */ }}; |
1035 | ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }}; |
1036 | } |
1037 | |
1038 | /// Inspects an environment variable at compile time. |
1039 | /// |
1040 | /// This macro will expand to the value of the named environment variable at |
1041 | /// compile time, yielding an expression of type `&'static str`. Use |
1042 | /// [`std::env::var`] instead if you want to read the value at runtime. |
1043 | /// |
1044 | /// [`std::env::var`]: ../std/env/fn.var.html |
1045 | /// |
1046 | /// If the environment variable is not defined, then a compilation error |
1047 | /// will be emitted. To not emit a compile error, use the [`option_env!`] |
1048 | /// macro instead. A compilation error will also be emitted if the |
1049 | /// environment variable is not a valid Unicode string. |
1050 | /// |
1051 | /// # Examples |
1052 | /// |
1053 | /// ``` |
1054 | /// let path: &'static str = env!("PATH" ); |
1055 | /// println!("the $PATH variable at the time of compiling was: {path}" ); |
1056 | /// ``` |
1057 | /// |
1058 | /// You can customize the error message by passing a string as the second |
1059 | /// parameter: |
1060 | /// |
1061 | /// ```compile_fail |
1062 | /// let doc: &'static str = env!("documentation" , "what's that?!" ); |
1063 | /// ``` |
1064 | /// |
1065 | /// If the `documentation` environment variable is not defined, you'll get |
1066 | /// the following error: |
1067 | /// |
1068 | /// ```text |
1069 | /// error: what's that?! |
1070 | /// ``` |
1071 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1072 | #[rustc_builtin_macro ] |
1073 | #[macro_export ] |
1074 | #[rustc_diagnostic_item = "env_macro" ] // useful for external lints |
1075 | macro_rules! env { |
1076 | ($name:expr $(,)?) => {{ /* compiler built-in */ }}; |
1077 | ($name:expr, $error_msg:expr $(,)?) => {{ /* compiler built-in */ }}; |
1078 | } |
1079 | |
1080 | /// Optionally inspects an environment variable at compile time. |
1081 | /// |
1082 | /// If the named environment variable is present at compile time, this will |
1083 | /// expand into an expression of type `Option<&'static str>` whose value is |
1084 | /// `Some` of the value of the environment variable (a compilation error |
1085 | /// will be emitted if the environment variable is not a valid Unicode |
1086 | /// string). If the environment variable is not present, then this will |
1087 | /// expand to `None`. See [`Option<T>`][Option] for more information on this |
1088 | /// type. Use [`std::env::var`] instead if you want to read the value at |
1089 | /// runtime. |
1090 | /// |
1091 | /// [`std::env::var`]: ../std/env/fn.var.html |
1092 | /// |
1093 | /// A compile time error is only emitted when using this macro if the |
1094 | /// environment variable exists and is not a valid Unicode string. To also |
1095 | /// emit a compile error if the environment variable is not present, use the |
1096 | /// [`env!`] macro instead. |
1097 | /// |
1098 | /// # Examples |
1099 | /// |
1100 | /// ``` |
1101 | /// let key: Option<&'static str> = option_env!("SECRET_KEY" ); |
1102 | /// println!("the secret key might be: {key:?}" ); |
1103 | /// ``` |
1104 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1105 | #[rustc_builtin_macro ] |
1106 | #[macro_export ] |
1107 | #[rustc_diagnostic_item = "option_env_macro" ] // useful for external lints |
1108 | macro_rules! option_env { |
1109 | ($name:expr $(,)?) => {{ /* compiler built-in */ }}; |
1110 | } |
1111 | |
1112 | /// Concatenates identifiers into one identifier. |
1113 | /// |
1114 | /// This macro takes any number of comma-separated identifiers, and |
1115 | /// concatenates them all into one, yielding an expression which is a new |
1116 | /// identifier. Note that hygiene makes it such that this macro cannot |
1117 | /// capture local variables. Also, as a general rule, macros are only |
1118 | /// allowed in item, statement or expression position. That means while |
1119 | /// you may use this macro for referring to existing variables, functions or |
1120 | /// modules etc, you cannot define a new one with it. |
1121 | /// |
1122 | /// # Examples |
1123 | /// |
1124 | /// ``` |
1125 | /// #![feature(concat_idents)] |
1126 | /// |
1127 | /// # fn main() { |
1128 | /// fn foobar() -> u32 { 23 } |
1129 | /// |
1130 | /// let f = concat_idents!(foo, bar); |
1131 | /// println!("{}", f()); |
1132 | /// |
1133 | /// // fn concat_idents!(new, fun, name) { } // not usable in this way! |
1134 | /// # } |
1135 | /// ``` |
1136 | #[unstable ( |
1137 | feature = "concat_idents" , |
1138 | issue = "29599" , |
1139 | reason = "`concat_idents` is not stable enough for use and is subject to change" |
1140 | )] |
1141 | #[deprecated ( |
1142 | since = "1.88.0" , |
1143 | note = "use `${concat(...)}` with the `macro_metavar_expr_concat` feature instead" |
1144 | )] |
1145 | #[rustc_builtin_macro ] |
1146 | #[macro_export ] |
1147 | macro_rules! concat_idents { |
1148 | ($($e:ident),+ $(,)?) => {{ /* compiler built-in */ }}; |
1149 | } |
1150 | |
1151 | /// Concatenates literals into a byte slice. |
1152 | /// |
1153 | /// This macro takes any number of comma-separated literals, and concatenates them all into |
1154 | /// one, yielding an expression of type `&[u8; _]`, which represents all of the literals |
1155 | /// concatenated left-to-right. The literals passed can be any combination of: |
1156 | /// |
1157 | /// - byte literals (`b'r'`) |
1158 | /// - byte strings (`b"Rust"`) |
1159 | /// - arrays of bytes/numbers (`[b'A', 66, b'C']`) |
1160 | /// |
1161 | /// # Examples |
1162 | /// |
1163 | /// ``` |
1164 | /// #![feature(concat_bytes)] |
1165 | /// |
1166 | /// # fn main() { |
1167 | /// let s: &[u8; 6] = concat_bytes!(b'A' , b"BC" , [68, b'E' , 70]); |
1168 | /// assert_eq!(s, b"ABCDEF" ); |
1169 | /// # } |
1170 | /// ``` |
1171 | #[unstable (feature = "concat_bytes" , issue = "87555" )] |
1172 | #[rustc_builtin_macro ] |
1173 | #[macro_export ] |
1174 | macro_rules! concat_bytes { |
1175 | ($($e:literal),+ $(,)?) => {{ /* compiler built-in */ }}; |
1176 | } |
1177 | |
1178 | /// Concatenates literals into a static string slice. |
1179 | /// |
1180 | /// This macro takes any number of comma-separated literals, yielding an |
1181 | /// expression of type `&'static str` which represents all of the literals |
1182 | /// concatenated left-to-right. |
1183 | /// |
1184 | /// Integer and floating point literals are [stringified](core::stringify) in order to be |
1185 | /// concatenated. |
1186 | /// |
1187 | /// # Examples |
1188 | /// |
1189 | /// ``` |
1190 | /// let s = concat!("test" , 10, 'b' , true); |
1191 | /// assert_eq!(s, "test10btrue" ); |
1192 | /// ``` |
1193 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1194 | #[rustc_builtin_macro ] |
1195 | #[macro_export ] |
1196 | macro_rules! concat { |
1197 | ($($e:expr),* $(,)?) => {{ /* compiler built-in */ }}; |
1198 | } |
1199 | |
1200 | /// Expands to the line number on which it was invoked. |
1201 | /// |
1202 | /// With [`column!`] and [`file!`], these macros provide debugging information for |
1203 | /// developers about the location within the source. |
1204 | /// |
1205 | /// The expanded expression has type `u32` and is 1-based, so the first line |
1206 | /// in each file evaluates to 1, the second to 2, etc. This is consistent |
1207 | /// with error messages by common compilers or popular editors. |
1208 | /// The returned line is *not necessarily* the line of the `line!` invocation itself, |
1209 | /// but rather the first macro invocation leading up to the invocation |
1210 | /// of the `line!` macro. |
1211 | /// |
1212 | /// # Examples |
1213 | /// |
1214 | /// ``` |
1215 | /// let current_line = line!(); |
1216 | /// println!("defined on line: {current_line}" ); |
1217 | /// ``` |
1218 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1219 | #[rustc_builtin_macro ] |
1220 | #[macro_export ] |
1221 | macro_rules! line { |
1222 | () => { |
1223 | /* compiler built-in */ |
1224 | }; |
1225 | } |
1226 | |
1227 | /// Expands to the column number at which it was invoked. |
1228 | /// |
1229 | /// With [`line!`] and [`file!`], these macros provide debugging information for |
1230 | /// developers about the location within the source. |
1231 | /// |
1232 | /// The expanded expression has type `u32` and is 1-based, so the first column |
1233 | /// in each line evaluates to 1, the second to 2, etc. This is consistent |
1234 | /// with error messages by common compilers or popular editors. |
1235 | /// The returned column is *not necessarily* the line of the `column!` invocation itself, |
1236 | /// but rather the first macro invocation leading up to the invocation |
1237 | /// of the `column!` macro. |
1238 | /// |
1239 | /// # Examples |
1240 | /// |
1241 | /// ``` |
1242 | /// let current_col = column!(); |
1243 | /// println!("defined on column: {current_col}" ); |
1244 | /// ``` |
1245 | /// |
1246 | /// `column!` counts Unicode code points, not bytes or graphemes. As a result, the first two |
1247 | /// invocations return the same value, but the third does not. |
1248 | /// |
1249 | /// ``` |
1250 | /// let a = ("foobar" , column!()).1; |
1251 | /// let b = ("人之初性本善" , column!()).1; |
1252 | /// let c = ("f̅o̅o̅b̅a̅r̅" , column!()).1; // Uses combining overline (U+0305) |
1253 | /// |
1254 | /// assert_eq!(a, b); |
1255 | /// assert_ne!(b, c); |
1256 | /// ``` |
1257 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1258 | #[rustc_builtin_macro ] |
1259 | #[macro_export ] |
1260 | macro_rules! column { |
1261 | () => { |
1262 | /* compiler built-in */ |
1263 | }; |
1264 | } |
1265 | |
1266 | /// Expands to the file name in which it was invoked. |
1267 | /// |
1268 | /// With [`line!`] and [`column!`], these macros provide debugging information for |
1269 | /// developers about the location within the source. |
1270 | /// |
1271 | /// The expanded expression has type `&'static str`, and the returned file |
1272 | /// is not the invocation of the `file!` macro itself, but rather the |
1273 | /// first macro invocation leading up to the invocation of the `file!` |
1274 | /// macro. |
1275 | /// |
1276 | /// The file name is derived from the crate root's source path passed to the Rust compiler |
1277 | /// and the sequence the compiler takes to get from the crate root to the |
1278 | /// module containing `file!`, modified by any flags passed to the Rust compiler (e.g. |
1279 | /// `--remap-path-prefix`). If the crate's source path is relative, the initial base |
1280 | /// directory will be the working directory of the Rust compiler. For example, if the source |
1281 | /// path passed to the compiler is `./src/lib.rs` which has a `mod foo;` with a source path of |
1282 | /// `src/foo/mod.rs`, then calling `file!` inside `mod foo;` will return `./src/foo/mod.rs`. |
1283 | /// |
1284 | /// Future compiler options might make further changes to the behavior of `file!`, |
1285 | /// including potentially making it entirely empty. Code (e.g. test libraries) |
1286 | /// relying on `file!` producing an openable file path would be incompatible |
1287 | /// with such options, and might wish to recommend not using those options. |
1288 | /// |
1289 | /// # Examples |
1290 | /// |
1291 | /// ``` |
1292 | /// let this_file = file!(); |
1293 | /// println!("defined in file: {this_file}" ); |
1294 | /// ``` |
1295 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1296 | #[rustc_builtin_macro ] |
1297 | #[macro_export ] |
1298 | macro_rules! file { |
1299 | () => { |
1300 | /* compiler built-in */ |
1301 | }; |
1302 | } |
1303 | |
1304 | /// Stringifies its arguments. |
1305 | /// |
1306 | /// This macro will yield an expression of type `&'static str` which is the |
1307 | /// stringification of all the tokens passed to the macro. No restrictions |
1308 | /// are placed on the syntax of the macro invocation itself. |
1309 | /// |
1310 | /// Note that the expanded results of the input tokens may change in the |
1311 | /// future. You should be careful if you rely on the output. |
1312 | /// |
1313 | /// # Examples |
1314 | /// |
1315 | /// ``` |
1316 | /// let one_plus_one = stringify!(1 + 1); |
1317 | /// assert_eq!(one_plus_one, "1 + 1" ); |
1318 | /// ``` |
1319 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1320 | #[rustc_builtin_macro ] |
1321 | #[macro_export ] |
1322 | macro_rules! stringify { |
1323 | ($($t:tt)*) => { |
1324 | /* compiler built-in */ |
1325 | }; |
1326 | } |
1327 | |
1328 | /// Includes a UTF-8 encoded file as a string. |
1329 | /// |
1330 | /// The file is located relative to the current file (similarly to how |
1331 | /// modules are found). The provided path is interpreted in a platform-specific |
1332 | /// way at compile time. So, for instance, an invocation with a Windows path |
1333 | /// containing backslashes `\` would not compile correctly on Unix. |
1334 | /// |
1335 | /// This macro will yield an expression of type `&'static str` which is the |
1336 | /// contents of the file. |
1337 | /// |
1338 | /// # Examples |
1339 | /// |
1340 | /// Assume there are two files in the same directory with the following |
1341 | /// contents: |
1342 | /// |
1343 | /// File 'spanish.in': |
1344 | /// |
1345 | /// ```text |
1346 | /// adiós |
1347 | /// ``` |
1348 | /// |
1349 | /// File 'main.rs': |
1350 | /// |
1351 | /// ```ignore (cannot-doctest-external-file-dependency) |
1352 | /// fn main() { |
1353 | /// let my_str = include_str!("spanish.in" ); |
1354 | /// assert_eq!(my_str, "adiós \n" ); |
1355 | /// print!("{my_str}" ); |
1356 | /// } |
1357 | /// ``` |
1358 | /// |
1359 | /// Compiling 'main.rs' and running the resulting binary will print "adiós". |
1360 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1361 | #[rustc_builtin_macro ] |
1362 | #[macro_export ] |
1363 | #[rustc_diagnostic_item = "include_str_macro" ] |
1364 | macro_rules! include_str { |
1365 | ($file:expr $(,)?) => {{ /* compiler built-in */ }}; |
1366 | } |
1367 | |
1368 | /// Includes a file as a reference to a byte array. |
1369 | /// |
1370 | /// The file is located relative to the current file (similarly to how |
1371 | /// modules are found). The provided path is interpreted in a platform-specific |
1372 | /// way at compile time. So, for instance, an invocation with a Windows path |
1373 | /// containing backslashes `\` would not compile correctly on Unix. |
1374 | /// |
1375 | /// This macro will yield an expression of type `&'static [u8; N]` which is |
1376 | /// the contents of the file. |
1377 | /// |
1378 | /// # Examples |
1379 | /// |
1380 | /// Assume there are two files in the same directory with the following |
1381 | /// contents: |
1382 | /// |
1383 | /// File 'spanish.in': |
1384 | /// |
1385 | /// ```text |
1386 | /// adiós |
1387 | /// ``` |
1388 | /// |
1389 | /// File 'main.rs': |
1390 | /// |
1391 | /// ```ignore (cannot-doctest-external-file-dependency) |
1392 | /// fn main() { |
1393 | /// let bytes = include_bytes!("spanish.in" ); |
1394 | /// assert_eq!(bytes, b"adi \xc3\xb3s \n" ); |
1395 | /// print!("{}" , String::from_utf8_lossy(bytes)); |
1396 | /// } |
1397 | /// ``` |
1398 | /// |
1399 | /// Compiling 'main.rs' and running the resulting binary will print "adiós". |
1400 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1401 | #[rustc_builtin_macro ] |
1402 | #[macro_export ] |
1403 | #[rustc_diagnostic_item = "include_bytes_macro" ] |
1404 | macro_rules! include_bytes { |
1405 | ($file:expr $(,)?) => {{ /* compiler built-in */ }}; |
1406 | } |
1407 | |
1408 | /// Expands to a string that represents the current module path. |
1409 | /// |
1410 | /// The current module path can be thought of as the hierarchy of modules |
1411 | /// leading back up to the crate root. The first component of the path |
1412 | /// returned is the name of the crate currently being compiled. |
1413 | /// |
1414 | /// # Examples |
1415 | /// |
1416 | /// ``` |
1417 | /// mod test { |
1418 | /// pub fn foo() { |
1419 | /// assert!(module_path!().ends_with("test" )); |
1420 | /// } |
1421 | /// } |
1422 | /// |
1423 | /// test::foo(); |
1424 | /// ``` |
1425 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1426 | #[rustc_builtin_macro ] |
1427 | #[macro_export ] |
1428 | macro_rules! module_path { |
1429 | () => { |
1430 | /* compiler built-in */ |
1431 | }; |
1432 | } |
1433 | |
1434 | /// Evaluates boolean combinations of configuration flags at compile-time. |
1435 | /// |
1436 | /// In addition to the `#[cfg]` attribute, this macro is provided to allow |
1437 | /// boolean expression evaluation of configuration flags. This frequently |
1438 | /// leads to less duplicated code. |
1439 | /// |
1440 | /// The syntax given to this macro is the same syntax as the [`cfg`] |
1441 | /// attribute. |
1442 | /// |
1443 | /// `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For |
1444 | /// example, all blocks in an if/else expression need to be valid when `cfg!` is used for |
1445 | /// the condition, regardless of what `cfg!` is evaluating. |
1446 | /// |
1447 | /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute |
1448 | /// |
1449 | /// # Examples |
1450 | /// |
1451 | /// ``` |
1452 | /// let my_directory = if cfg!(windows) { |
1453 | /// "windows-specific-directory" |
1454 | /// } else { |
1455 | /// "unix-directory" |
1456 | /// }; |
1457 | /// ``` |
1458 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1459 | #[rustc_builtin_macro ] |
1460 | #[macro_export ] |
1461 | macro_rules! cfg { |
1462 | ($($cfg:tt)*) => { |
1463 | /* compiler built-in */ |
1464 | }; |
1465 | } |
1466 | |
1467 | /// Parses a file as an expression or an item according to the context. |
1468 | /// |
1469 | /// **Warning**: For multi-file Rust projects, the `include!` macro is probably not what you |
1470 | /// are looking for. Usually, multi-file Rust projects use |
1471 | /// [modules](https://doc.rust-lang.org/reference/items/modules.html). Multi-file projects and |
1472 | /// modules are explained in the Rust-by-Example book |
1473 | /// [here](https://doc.rust-lang.org/rust-by-example/mod/split.html) and the module system is |
1474 | /// explained in the Rust Book |
1475 | /// [here](https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html). |
1476 | /// |
1477 | /// The included file is placed in the surrounding code |
1478 | /// [unhygienically](https://doc.rust-lang.org/reference/macros-by-example.html#hygiene). If |
1479 | /// the included file is parsed as an expression and variables or functions share names across |
1480 | /// both files, it could result in variables or functions being different from what the |
1481 | /// included file expected. |
1482 | /// |
1483 | /// The included file is located relative to the current file (similarly to how modules are |
1484 | /// found). The provided path is interpreted in a platform-specific way at compile time. So, |
1485 | /// for instance, an invocation with a Windows path containing backslashes `\` would not |
1486 | /// compile correctly on Unix. |
1487 | /// |
1488 | /// # Uses |
1489 | /// |
1490 | /// The `include!` macro is primarily used for two purposes. It is used to include |
1491 | /// documentation that is written in a separate file and it is used to include [build artifacts |
1492 | /// usually as a result from the `build.rs` |
1493 | /// script](https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script). |
1494 | /// |
1495 | /// When using the `include` macro to include stretches of documentation, remember that the |
1496 | /// included file still needs to be a valid Rust syntax. It is also possible to |
1497 | /// use the [`include_str`] macro as `#![doc = include_str!("...")]` (at the module level) or |
1498 | /// `#[doc = include_str!("...")]` (at the item level) to include documentation from a plain |
1499 | /// text or markdown file. |
1500 | /// |
1501 | /// # Examples |
1502 | /// |
1503 | /// Assume there are two files in the same directory with the following contents: |
1504 | /// |
1505 | /// File 'monkeys.in': |
1506 | /// |
1507 | /// ```ignore (only-for-syntax-highlight) |
1508 | /// ['🙈' , '🙊' , '🙉' ] |
1509 | /// .iter() |
1510 | /// .cycle() |
1511 | /// .take(6) |
1512 | /// .collect::<String>() |
1513 | /// ``` |
1514 | /// |
1515 | /// File 'main.rs': |
1516 | /// |
1517 | /// ```ignore (cannot-doctest-external-file-dependency) |
1518 | /// fn main() { |
1519 | /// let my_string = include!("monkeys.in" ); |
1520 | /// assert_eq!("🙈🙊🙉🙈🙊🙉" , my_string); |
1521 | /// println!("{my_string}" ); |
1522 | /// } |
1523 | /// ``` |
1524 | /// |
1525 | /// Compiling 'main.rs' and running the resulting binary will print |
1526 | /// "🙈🙊🙉🙈🙊🙉". |
1527 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1528 | #[rustc_builtin_macro ] |
1529 | #[macro_export ] |
1530 | #[rustc_diagnostic_item = "include_macro" ] // useful for external lints |
1531 | macro_rules! include { |
1532 | ($file:expr $(,)?) => {{ /* compiler built-in */ }}; |
1533 | } |
1534 | |
1535 | /// This macro uses forward-mode automatic differentiation to generate a new function. |
1536 | /// It may only be applied to a function. The new function will compute the derivative |
1537 | /// of the function to which the macro was applied. |
1538 | /// |
1539 | /// The expected usage syntax is: |
1540 | /// `#[autodiff_forward(NAME, INPUT_ACTIVITIES, OUTPUT_ACTIVITY)]` |
1541 | /// |
1542 | /// - `NAME`: A string that represents a valid function name. |
1543 | /// - `INPUT_ACTIVITIES`: Specifies one valid activity for each input parameter. |
1544 | /// - `OUTPUT_ACTIVITY`: Must not be set if the function implicitly returns nothing |
1545 | /// (or explicitly returns `-> ()`). Otherwise, it must be set to one of the allowed activities. |
1546 | #[unstable (feature = "autodiff" , issue = "124509" )] |
1547 | #[allow_internal_unstable (rustc_attrs)] |
1548 | #[rustc_builtin_macro ] |
1549 | pub macro autodiff_forward($item:item) { |
1550 | /* compiler built-in */ |
1551 | } |
1552 | |
1553 | /// This macro uses reverse-mode automatic differentiation to generate a new function. |
1554 | /// It may only be applied to a function. The new function will compute the derivative |
1555 | /// of the function to which the macro was applied. |
1556 | /// |
1557 | /// The expected usage syntax is: |
1558 | /// `#[autodiff_reverse(NAME, INPUT_ACTIVITIES, OUTPUT_ACTIVITY)]` |
1559 | /// |
1560 | /// - `NAME`: A string that represents a valid function name. |
1561 | /// - `INPUT_ACTIVITIES`: Specifies one valid activity for each input parameter. |
1562 | /// - `OUTPUT_ACTIVITY`: Must not be set if the function implicitly returns nothing |
1563 | /// (or explicitly returns `-> ()`). Otherwise, it must be set to one of the allowed activities. |
1564 | #[unstable (feature = "autodiff" , issue = "124509" )] |
1565 | #[allow_internal_unstable (rustc_attrs)] |
1566 | #[rustc_builtin_macro ] |
1567 | pub macro autodiff_reverse($item:item) { |
1568 | /* compiler built-in */ |
1569 | } |
1570 | |
1571 | /// Asserts that a boolean expression is `true` at runtime. |
1572 | /// |
1573 | /// This will invoke the [`panic!`] macro if the provided expression cannot be |
1574 | /// evaluated to `true` at runtime. |
1575 | /// |
1576 | /// # Uses |
1577 | /// |
1578 | /// Assertions are always checked in both debug and release builds, and cannot |
1579 | /// be disabled. See [`debug_assert!`] for assertions that are not enabled in |
1580 | /// release builds by default. |
1581 | /// |
1582 | /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if |
1583 | /// violated could lead to unsafety. |
1584 | /// |
1585 | /// Other use-cases of `assert!` include testing and enforcing run-time |
1586 | /// invariants in safe code (whose violation cannot result in unsafety). |
1587 | /// |
1588 | /// # Custom Messages |
1589 | /// |
1590 | /// This macro has a second form, where a custom panic message can |
1591 | /// be provided with or without arguments for formatting. See [`std::fmt`] |
1592 | /// for syntax for this form. Expressions used as format arguments will only |
1593 | /// be evaluated if the assertion fails. |
1594 | /// |
1595 | /// [`std::fmt`]: ../std/fmt/index.html |
1596 | /// |
1597 | /// # Examples |
1598 | /// |
1599 | /// ``` |
1600 | /// // the panic message for these assertions is the stringified value of the |
1601 | /// // expression given. |
1602 | /// assert!(true); |
1603 | /// |
1604 | /// fn some_computation() -> bool { true } // a very simple function |
1605 | /// |
1606 | /// assert!(some_computation()); |
1607 | /// |
1608 | /// // assert with a custom message |
1609 | /// let x = true; |
1610 | /// assert!(x, "x wasn't true!" ); |
1611 | /// |
1612 | /// let a = 3; let b = 27; |
1613 | /// assert!(a + b == 30, "a = {}, b = {}" , a, b); |
1614 | /// ``` |
1615 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1616 | #[rustc_builtin_macro ] |
1617 | #[macro_export ] |
1618 | #[rustc_diagnostic_item = "assert_macro" ] |
1619 | #[allow_internal_unstable ( |
1620 | core_intrinsics, |
1621 | panic_internals, |
1622 | edition_panic, |
1623 | generic_assert_internals |
1624 | )] |
1625 | macro_rules! assert { |
1626 | ($cond:expr $(,)?) => {{ /* compiler built-in */ }}; |
1627 | ($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }}; |
1628 | } |
1629 | |
1630 | /// Prints passed tokens into the standard output. |
1631 | #[unstable ( |
1632 | feature = "log_syntax" , |
1633 | issue = "29598" , |
1634 | reason = "`log_syntax!` is not stable enough for use and is subject to change" |
1635 | )] |
1636 | #[rustc_builtin_macro ] |
1637 | #[macro_export ] |
1638 | macro_rules! log_syntax { |
1639 | ($($arg:tt)*) => { |
1640 | /* compiler built-in */ |
1641 | }; |
1642 | } |
1643 | |
1644 | /// Enables or disables tracing functionality used for debugging other macros. |
1645 | #[unstable ( |
1646 | feature = "trace_macros" , |
1647 | issue = "29598" , |
1648 | reason = "`trace_macros` is not stable enough for use and is subject to change" |
1649 | )] |
1650 | #[rustc_builtin_macro ] |
1651 | #[macro_export ] |
1652 | macro_rules! trace_macros { |
1653 | (true) => {{ /* compiler built-in */ }}; |
1654 | (false) => {{ /* compiler built-in */ }}; |
1655 | } |
1656 | |
1657 | /// Attribute macro used to apply derive macros. |
1658 | /// |
1659 | /// See [the reference] for more info. |
1660 | /// |
1661 | /// [the reference]: ../../../reference/attributes/derive.html |
1662 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1663 | #[rustc_builtin_macro ] |
1664 | pub macro derive ($item:item) { |
1665 | /* compiler built-in */ |
1666 | } |
1667 | |
1668 | /// Attribute macro used to apply derive macros for implementing traits |
1669 | /// in a const context. |
1670 | /// |
1671 | /// See [the reference] for more info. |
1672 | /// |
1673 | /// [the reference]: ../../../reference/attributes/derive.html |
1674 | #[unstable (feature = "derive_const" , issue = "none" )] |
1675 | #[rustc_builtin_macro ] |
1676 | pub macro derive_const ($item:item) { |
1677 | /* compiler built-in */ |
1678 | } |
1679 | |
1680 | /// Attribute macro applied to a function to turn it into a unit test. |
1681 | /// |
1682 | /// See [the reference] for more info. |
1683 | /// |
1684 | /// [the reference]: ../../../reference/attributes/testing.html#the-test-attribute |
1685 | #[stable (feature = "rust1" , since = "1.0.0" )] |
1686 | #[allow_internal_unstable (test, rustc_attrs, coverage_attribute)] |
1687 | #[rustc_builtin_macro ] |
1688 | pub macro test ($item:item) { |
1689 | /* compiler built-in */ |
1690 | } |
1691 | |
1692 | /// Attribute macro applied to a function to turn it into a benchmark test. |
1693 | #[unstable ( |
1694 | feature = "test" , |
1695 | issue = "50297" , |
1696 | reason = "`bench` is a part of custom test frameworks which are unstable" |
1697 | )] |
1698 | #[allow_internal_unstable (test, rustc_attrs, coverage_attribute)] |
1699 | #[rustc_builtin_macro ] |
1700 | pub macro bench ($item:item) { |
1701 | /* compiler built-in */ |
1702 | } |
1703 | |
1704 | /// An implementation detail of the `#[test]` and `#[bench]` macros. |
1705 | #[unstable ( |
1706 | feature = "custom_test_frameworks" , |
1707 | issue = "50297" , |
1708 | reason = "custom test frameworks are an unstable feature" |
1709 | )] |
1710 | #[allow_internal_unstable (test, rustc_attrs)] |
1711 | #[rustc_builtin_macro ] |
1712 | pub macro test_case ($item:item) { |
1713 | /* compiler built-in */ |
1714 | } |
1715 | |
1716 | /// Attribute macro applied to a static to register it as a global allocator. |
1717 | /// |
1718 | /// See also [`std::alloc::GlobalAlloc`](../../../std/alloc/trait.GlobalAlloc.html). |
1719 | #[stable (feature = "global_allocator" , since = "1.28.0" )] |
1720 | #[allow_internal_unstable (rustc_attrs)] |
1721 | #[rustc_builtin_macro ] |
1722 | pub macro global_allocator ($item:item) { |
1723 | /* compiler built-in */ |
1724 | } |
1725 | |
1726 | /// Attribute macro applied to a function to give it a post-condition. |
1727 | /// |
1728 | /// The attribute carries an argument token-tree which is |
1729 | /// eventually parsed as a unary closure expression that is |
1730 | /// invoked on a reference to the return value. |
1731 | #[unstable (feature = "contracts" , issue = "128044" )] |
1732 | #[allow_internal_unstable (contracts_internals)] |
1733 | #[rustc_builtin_macro ] |
1734 | pub macro contracts_ensures($item:item) { |
1735 | /* compiler built-in */ |
1736 | } |
1737 | |
1738 | /// Attribute macro applied to a function to give it a precondition. |
1739 | /// |
1740 | /// The attribute carries an argument token-tree which is |
1741 | /// eventually parsed as an boolean expression with access to the |
1742 | /// function's formal parameters |
1743 | #[unstable (feature = "contracts" , issue = "128044" )] |
1744 | #[allow_internal_unstable (contracts_internals)] |
1745 | #[rustc_builtin_macro ] |
1746 | pub macro contracts_requires($item:item) { |
1747 | /* compiler built-in */ |
1748 | } |
1749 | |
1750 | /// Attribute macro applied to a function to register it as a handler for allocation failure. |
1751 | /// |
1752 | /// See also [`std::alloc::handle_alloc_error`](../../../std/alloc/fn.handle_alloc_error.html). |
1753 | #[unstable (feature = "alloc_error_handler" , issue = "51540" )] |
1754 | #[allow_internal_unstable (rustc_attrs)] |
1755 | #[rustc_builtin_macro ] |
1756 | pub macro alloc_error_handler($item:item) { |
1757 | /* compiler built-in */ |
1758 | } |
1759 | |
1760 | /// Keeps the item it's applied to if the passed path is accessible, and removes it otherwise. |
1761 | #[unstable ( |
1762 | feature = "cfg_accessible" , |
1763 | issue = "64797" , |
1764 | reason = "`cfg_accessible` is not fully implemented" |
1765 | )] |
1766 | #[rustc_builtin_macro ] |
1767 | pub macro cfg_accessible ($item:item) { |
1768 | /* compiler built-in */ |
1769 | } |
1770 | |
1771 | /// Expands all `#[cfg]` and `#[cfg_attr]` attributes in the code fragment it's applied to. |
1772 | #[unstable ( |
1773 | feature = "cfg_eval" , |
1774 | issue = "82679" , |
1775 | reason = "`cfg_eval` is a recently implemented feature" |
1776 | )] |
1777 | #[rustc_builtin_macro ] |
1778 | pub macro cfg_eval ($($tt:tt)*) { |
1779 | /* compiler built-in */ |
1780 | } |
1781 | |
1782 | /// Provide a list of type aliases and other opaque-type-containing type definitions |
1783 | /// to an item with a body. This list will be used in that body to define opaque |
1784 | /// types' hidden types. |
1785 | /// Can only be applied to things that have bodies. |
1786 | #[unstable ( |
1787 | feature = "type_alias_impl_trait" , |
1788 | issue = "63063" , |
1789 | reason = "`type_alias_impl_trait` has open design concerns" |
1790 | )] |
1791 | #[rustc_builtin_macro ] |
1792 | pub macro define_opaque($($tt:tt)*) { |
1793 | /* compiler built-in */ |
1794 | } |
1795 | |
1796 | /// Unstable placeholder for type ascription. |
1797 | #[allow_internal_unstable (builtin_syntax)] |
1798 | #[unstable ( |
1799 | feature = "type_ascription" , |
1800 | issue = "23416" , |
1801 | reason = "placeholder syntax for type ascription" |
1802 | )] |
1803 | #[rustfmt::skip] |
1804 | pub macro type_ascribe($expr:expr, $ty:ty) { |
1805 | builtin # type_ascribe($expr, $ty) |
1806 | } |
1807 | |
1808 | /// Unstable placeholder for deref patterns. |
1809 | #[allow_internal_unstable (builtin_syntax)] |
1810 | #[unstable ( |
1811 | feature = "deref_patterns" , |
1812 | issue = "87121" , |
1813 | reason = "placeholder syntax for deref patterns" |
1814 | )] |
1815 | pub macro deref($pat:pat) { |
1816 | builtin # deref($pat) |
1817 | } |
1818 | } |
1819 | |