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