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"]
805#[cfg(not(feature = "ferrocene_subset"))]
806macro_rules! write {
807 ($dst:expr, $($arg:tt)*) => {
808 $dst.write_fmt($crate::format_args!($($arg)*))
809 };
810}
811
812/// Writes formatted data into a buffer, with a newline appended.
813///
814/// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
815/// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
816///
817/// For more information, see [`write!`]. For information on the format string syntax, see
818/// [`std::fmt`].
819///
820/// [`std::fmt`]: ../std/fmt/index.html
821///
822/// # Examples
823///
824/// ```
825/// use std::io::{Write, Result};
826///
827/// fn main() -> Result<()> {
828/// let mut w = Vec::new();
829/// writeln!(&mut w)?;
830/// writeln!(&mut w, "test")?;
831/// writeln!(&mut w, "formatted {}", "arguments")?;
832///
833/// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
834/// Ok(())
835/// }
836/// ```
837#[macro_export]
838#[stable(feature = "rust1", since = "1.0.0")]
839#[rustc_diagnostic_item = "writeln_macro"]
840#[allow_internal_unstable(format_args_nl)]
841#[cfg(not(feature = "ferrocene_subset"))]
842macro_rules! writeln {
843 ($dst:expr $(,)?) => {
844 $crate::write!($dst, "\n")
845 };
846 ($dst:expr, $($arg:tt)*) => {
847 $dst.write_fmt($crate::format_args_nl!($($arg)*))
848 };
849}
850
851/// Indicates unreachable code.
852///
853/// This is useful any time that the compiler can't determine that some code is unreachable. For
854/// example:
855///
856/// * Match arms with guard conditions.
857/// * Loops that dynamically terminate.
858/// * Iterators that dynamically terminate.
859///
860/// If the determination that the code is unreachable proves incorrect, the
861/// program immediately terminates with a [`panic!`].
862///
863/// The unsafe counterpart of this macro is the [`unreachable_unchecked`] function, which
864/// will cause undefined behavior if the code is reached.
865///
866/// [`unreachable_unchecked`]: crate::hint::unreachable_unchecked
867///
868/// # Panics
869///
870/// This will always [`panic!`] because `unreachable!` is just a shorthand for `panic!` with a
871/// fixed, specific message.
872///
873/// Like `panic!`, this macro has a second form for displaying custom values.
874///
875/// # Examples
876///
877/// Match arms:
878///
879/// ```
880/// # #[allow(dead_code)]
881/// fn foo(x: Option<i32>) {
882/// match x {
883/// Some(n) if n >= 0 => println!("Some(Non-negative)"),
884/// Some(n) if n < 0 => println!("Some(Negative)"),
885/// Some(_) => unreachable!(), // compile error if commented out
886/// None => println!("None")
887/// }
888/// }
889/// ```
890///
891/// Iterators:
892///
893/// ```
894/// # #[allow(dead_code)]
895/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
896/// for i in 0.. {
897/// if 3*i < i { panic!("u32 overflow"); }
898/// if x < 3*i { return i-1; }
899/// }
900/// unreachable!("The loop should always return");
901/// }
902/// ```
903#[macro_export]
904#[rustc_builtin_macro(unreachable)]
905#[allow_internal_unstable(edition_panic)]
906#[stable(feature = "rust1", since = "1.0.0")]
907#[rustc_diagnostic_item = "unreachable_macro"]
908macro_rules! unreachable {
909 // Expands to either `$crate::panic::unreachable_2015` or `$crate::panic::unreachable_2021`
910 // depending on the edition of the caller.
911 ($($arg:tt)*) => {
912 /* compiler built-in */
913 };
914}
915
916/// Indicates unimplemented code by panicking with a message of "not implemented".
917///
918/// This allows your code to type-check, which is useful if you are prototyping or
919/// implementing a trait that requires multiple methods which you don't plan to use all of.
920///
921/// The difference between `unimplemented!` and [`todo!`] is that while `todo!`
922/// conveys an intent of implementing the functionality later and the message is "not yet
923/// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
924///
925/// Also, some IDEs will mark `todo!`s.
926///
927/// # Panics
928///
929/// This will always [`panic!`] because `unimplemented!` is just a shorthand for `panic!` with a
930/// fixed, specific message.
931///
932/// Like `panic!`, this macro has a second form for displaying custom values.
933///
934/// [`todo!`]: crate::todo
935///
936/// # Examples
937///
938/// Say we have a trait `Foo`:
939///
940/// ```
941/// trait Foo {
942/// fn bar(&self) -> u8;
943/// fn baz(&self);
944/// fn qux(&self) -> Result<u64, ()>;
945/// }
946/// ```
947///
948/// We want to implement `Foo` for 'MyStruct', but for some reason it only makes sense
949/// to implement the `bar()` function. `baz()` and `qux()` will still need to be defined
950/// in our implementation of `Foo`, but we can use `unimplemented!` in their definitions
951/// to allow our code to compile.
952///
953/// We still want to have our program stop running if the unimplemented methods are
954/// reached.
955///
956/// ```
957/// # trait Foo {
958/// # fn bar(&self) -> u8;
959/// # fn baz(&self);
960/// # fn qux(&self) -> Result<u64, ()>;
961/// # }
962/// struct MyStruct;
963///
964/// impl Foo for MyStruct {
965/// fn bar(&self) -> u8 {
966/// 1 + 1
967/// }
968///
969/// fn baz(&self) {
970/// // It makes no sense to `baz` a `MyStruct`, so we have no logic here
971/// // at all.
972/// // This will display "thread 'main' panicked at 'not implemented'".
973/// unimplemented!();
974/// }
975///
976/// fn qux(&self) -> Result<u64, ()> {
977/// // We have some logic here,
978/// // We can add a message to unimplemented! to display our omission.
979/// // This will display:
980/// // "thread 'main' panicked at 'not implemented: MyStruct isn't quxable'".
981/// unimplemented!("MyStruct isn't quxable");
982/// }
983/// }
984///
985/// fn main() {
986/// let s = MyStruct;
987/// s.bar();
988/// }
989/// ```
990#[macro_export]
991#[stable(feature = "rust1", since = "1.0.0")]
992#[rustc_diagnostic_item = "unimplemented_macro"]
993#[allow_internal_unstable(panic_internals)]
994#[cfg(not(feature = "ferrocene_subset"))]
995macro_rules! unimplemented {
996 () => {
997 $crate::panicking::panic("not implemented")
998 };
999 ($($arg:tt)+) => {
1000 $crate::panic!("not implemented: {}", $crate::format_args!($($arg)+))
1001 };
1002}
1003
1004/// Indicates unfinished code.
1005///
1006/// This can be useful if you are prototyping and just
1007/// want a placeholder to let your code pass type analysis.
1008///
1009/// The difference between [`unimplemented!`] and `todo!` is that while `todo!` conveys
1010/// an intent of implementing the functionality later and the message is "not yet
1011/// implemented", `unimplemented!` makes no such claims. Its message is "not implemented".
1012///
1013/// Also, some IDEs will mark `todo!`s.
1014///
1015/// # Panics
1016///
1017/// This will always [`panic!`] because `todo!` is just a shorthand for `panic!` with a
1018/// fixed, specific message.
1019///
1020/// Like `panic!`, this macro has a second form for displaying custom values.
1021///
1022/// # Examples
1023///
1024/// Here's an example of some in-progress code. We have a trait `Foo`:
1025///
1026/// ```
1027/// trait Foo {
1028/// fn bar(&self) -> u8;
1029/// fn baz(&self);
1030/// fn qux(&self) -> Result<u64, ()>;
1031/// }
1032/// ```
1033///
1034/// We want to implement `Foo` on one of our types, but we also want to work on
1035/// just `bar()` first. In order for our code to compile, we need to implement
1036/// `baz()` and `qux()`, so we can use `todo!`:
1037///
1038/// ```
1039/// # trait Foo {
1040/// # fn bar(&self) -> u8;
1041/// # fn baz(&self);
1042/// # fn qux(&self) -> Result<u64, ()>;
1043/// # }
1044/// struct MyStruct;
1045///
1046/// impl Foo for MyStruct {
1047/// fn bar(&self) -> u8 {
1048/// 1 + 1
1049/// }
1050///
1051/// fn baz(&self) {
1052/// // Let's not worry about implementing baz() for now
1053/// todo!();
1054/// }
1055///
1056/// fn qux(&self) -> Result<u64, ()> {
1057/// // We can add a message to todo! to display our omission.
1058/// // This will display:
1059/// // "thread 'main' panicked at 'not yet implemented: MyStruct is not yet quxable'".
1060/// todo!("MyStruct is not yet quxable");
1061/// }
1062/// }
1063///
1064/// fn main() {
1065/// let s = MyStruct;
1066/// s.bar();
1067///
1068/// // We aren't even using baz() or qux(), so this is fine.
1069/// }
1070/// ```
1071#[macro_export]
1072#[stable(feature = "todo_macro", since = "1.40.0")]
1073#[rustc_diagnostic_item = "todo_macro"]
1074#[allow_internal_unstable(panic_internals)]
1075#[cfg(not(feature = "ferrocene_subset"))]
1076macro_rules! todo {
1077 () => {
1078 $crate::panicking::panic("not yet implemented")
1079 };
1080 ($($arg:tt)+) => {
1081 $crate::panic!("not yet implemented: {}", $crate::format_args!($($arg)+))
1082 };
1083}
1084
1085/// Definitions of built-in macros.
1086///
1087/// Most of the macro properties (stability, visibility, etc.) are taken from the source code here,
1088/// with exception of expansion functions transforming macro inputs into outputs,
1089/// those functions are provided by the compiler.
1090pub(crate) mod builtin {
1091
1092 /// Causes compilation to fail with the given error message when encountered.
1093 ///
1094 /// This macro should be used when a crate uses a conditional compilation strategy to provide
1095 /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
1096 /// but emits an error during *compilation* rather than at *runtime*.
1097 ///
1098 /// # Examples
1099 ///
1100 /// Two such examples are macros and `#[cfg]` environments.
1101 ///
1102 /// Emit a better compiler error if a macro is passed invalid values. Without the final branch,
1103 /// the compiler would still emit an error, but the error's message would not mention the two
1104 /// valid values.
1105 ///
1106 /// ```compile_fail
1107 /// macro_rules! give_me_foo_or_bar {
1108 /// (foo) => {};
1109 /// (bar) => {};
1110 /// ($x:ident) => {
1111 /// compile_error!("This macro only accepts `foo` or `bar`");
1112 /// }
1113 /// }
1114 ///
1115 /// give_me_foo_or_bar!(neither);
1116 /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
1117 /// ```
1118 ///
1119 /// Emit a compiler error if one of a number of features isn't available.
1120 ///
1121 /// ```compile_fail
1122 /// #[cfg(not(any(feature = "foo", feature = "bar")))]
1123 /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.");
1124 /// ```
1125 #[stable(feature = "compile_error_macro", since = "1.20.0")]
1126 #[rustc_builtin_macro]
1127 #[macro_export]
1128 macro_rules! compile_error {
1129 ($msg:expr $(,)?) => {{ /* compiler built-in */ }};
1130 }
1131
1132 /// Constructs parameters for the other string-formatting macros.
1133 ///
1134 /// This macro functions by taking a formatting string literal containing
1135 /// `{}` for each additional argument passed. `format_args!` prepares the
1136 /// additional parameters to ensure the output can be interpreted as a string
1137 /// and canonicalizes the arguments into a single type. Any value that implements
1138 /// the [`Display`] trait can be passed to `format_args!`, as can any
1139 /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
1140 ///
1141 /// This macro produces a value of type [`fmt::Arguments`]. This value can be
1142 /// passed to the macros within [`std::fmt`] for performing useful redirection.
1143 /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
1144 /// proxied through this one. `format_args!`, unlike its derived macros, avoids
1145 /// heap allocations.
1146 ///
1147 /// You can use the [`fmt::Arguments`] value that `format_args!` returns
1148 /// in `Debug` and `Display` contexts as seen below. The example also shows
1149 /// that `Debug` and `Display` format to the same thing: the interpolated
1150 /// format string in `format_args!`.
1151 ///
1152 /// ```rust
1153 /// let args = format_args!("{} foo {:?}", 1, 2);
1154 /// let debug = format!("{args:?}");
1155 /// let display = format!("{args}");
1156 /// assert_eq!("1 foo 2", display);
1157 /// assert_eq!(display, debug);
1158 /// ```
1159 ///
1160 /// See [the formatting documentation in `std::fmt`](../std/fmt/index.html)
1161 /// for details of the macro argument syntax, and further information.
1162 ///
1163 /// [`Display`]: crate::fmt::Display
1164 /// [`Debug`]: crate::fmt::Debug
1165 /// [`fmt::Arguments`]: crate::fmt::Arguments
1166 /// [`std::fmt`]: ../std/fmt/index.html
1167 /// [`format!`]: ../std/macro.format.html
1168 /// [`println!`]: ../std/macro.println.html
1169 ///
1170 /// # Examples
1171 ///
1172 /// ```
1173 /// use std::fmt;
1174 ///
1175 /// let s = fmt::format(format_args!("hello {}", "world"));
1176 /// assert_eq!(s, format!("hello {}", "world"));
1177 /// ```
1178 ///
1179 /// # Argument lifetimes
1180 ///
1181 /// Except when no formatting arguments are used,
1182 /// the produced `fmt::Arguments` value borrows temporary values.
1183 /// To allow it to be stored for later use, the arguments' lifetimes, as well as those of
1184 /// temporaries they borrow, may be [extended] when `format_args!` appears in the initializer
1185 /// expression of a `let` statement. The syntactic rules used to determine when temporaries'
1186 /// lifetimes are extended are documented in the [Reference].
1187 ///
1188 /// [extended]: ../reference/destructors.html#temporary-lifetime-extension
1189 /// [Reference]: ../reference/destructors.html#extending-based-on-expressions
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 #[rustc_diagnostic_item = "format_args_macro"]
1192 #[allow_internal_unsafe]
1193 #[allow_internal_unstable(fmt_internals, fmt_arguments_from_str)]
1194 #[rustc_builtin_macro]
1195 #[macro_export]
1196 macro_rules! format_args {
1197 ($fmt:expr) => {{ /* compiler built-in */ }};
1198 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
1199 }
1200
1201 /// Same as [`format_args`], but can be used in some const contexts.
1202 ///
1203 /// This macro is used by the panic macros for the `const_panic` feature.
1204 ///
1205 /// This macro will be removed once `format_args` is allowed in const contexts.
1206 #[unstable(feature = "const_format_args", issue = "none")]
1207 #[allow_internal_unstable(fmt_internals, fmt_arguments_from_str)]
1208 #[rustc_builtin_macro]
1209 #[macro_export]
1210 macro_rules! const_format_args {
1211 ($fmt:expr) => {{ /* compiler built-in */ }};
1212 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
1213 }
1214
1215 /// Same as [`format_args`], but adds a newline in the end.
1216 #[unstable(
1217 feature = "format_args_nl",
1218 issue = "none",
1219 reason = "`format_args_nl` is only for internal \
1220 language use and is subject to change"
1221 )]
1222 #[allow_internal_unstable(fmt_internals, fmt_arguments_from_str)]
1223 #[rustc_builtin_macro]
1224 #[doc(hidden)]
1225 #[macro_export]
1226 macro_rules! format_args_nl {
1227 ($fmt:expr) => {{ /* compiler built-in */ }};
1228 ($fmt:expr, $($args:tt)*) => {{ /* compiler built-in */ }};
1229 }
1230
1231 /// Inspects an environment variable at compile time.
1232 ///
1233 /// This macro will expand to the value of the named environment variable at
1234 /// compile time, yielding an expression of type `&'static str`. Use
1235 /// [`std::env::var`] instead if you want to read the value at runtime.
1236 ///
1237 /// [`std::env::var`]: ../std/env/fn.var.html
1238 ///
1239 /// If the environment variable is not defined, then a compilation error
1240 /// will be emitted. To not emit a compile error, use the [`option_env!`]
1241 /// macro instead. A compilation error will also be emitted if the
1242 /// environment variable is not a valid Unicode string.
1243 ///
1244 /// # Examples
1245 ///
1246 /// ```
1247 /// let path: &'static str = env!("PATH");
1248 /// println!("the $PATH variable at the time of compiling was: {path}");
1249 /// ```
1250 ///
1251 /// You can customize the error message by passing a string as the second
1252 /// parameter:
1253 ///
1254 /// ```compile_fail
1255 /// let doc: &'static str = env!("documentation", "what's that?!");
1256 /// ```
1257 ///
1258 /// If the `documentation` environment variable is not defined, you'll get
1259 /// the following error:
1260 ///
1261 /// ```text
1262 /// error: what's that?!
1263 /// ```
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 #[rustc_builtin_macro]
1266 #[macro_export]
1267 #[rustc_diagnostic_item = "env_macro"] // useful for external lints
1268 macro_rules! env {
1269 ($name:expr $(,)?) => {{ /* compiler built-in */ }};
1270 ($name:expr, $error_msg:expr $(,)?) => {{ /* compiler built-in */ }};
1271 }
1272
1273 /// Optionally inspects an environment variable at compile time.
1274 ///
1275 /// If the named environment variable is present at compile time, this will
1276 /// expand into an expression of type `Option<&'static str>` whose value is
1277 /// `Some` of the value of the environment variable (a compilation error
1278 /// will be emitted if the environment variable is not a valid Unicode
1279 /// string). If the environment variable is not present, then this will
1280 /// expand to `None`. See [`Option<T>`][Option] for more information on this
1281 /// type. Use [`std::env::var`] instead if you want to read the value at
1282 /// runtime.
1283 ///
1284 /// [`std::env::var`]: ../std/env/fn.var.html
1285 ///
1286 /// A compile time error is only emitted when using this macro if the
1287 /// environment variable exists and is not a valid Unicode string. To also
1288 /// emit a compile error if the environment variable is not present, use the
1289 /// [`env!`] macro instead.
1290 ///
1291 /// # Examples
1292 ///
1293 /// ```
1294 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
1295 /// println!("the secret key might be: {key:?}");
1296 /// ```
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 #[rustc_builtin_macro]
1299 #[macro_export]
1300 #[rustc_diagnostic_item = "option_env_macro"] // useful for external lints
1301 macro_rules! option_env {
1302 ($name:expr $(,)?) => {{ /* compiler built-in */ }};
1303 }
1304
1305 /// Concatenates literals into a byte slice.
1306 ///
1307 /// This macro takes any number of comma-separated literals, and concatenates them all into
1308 /// one, yielding an expression of type `&[u8; _]`, which represents all of the literals
1309 /// concatenated left-to-right. The literals passed can be any combination of:
1310 ///
1311 /// - byte literals (`b'r'`)
1312 /// - byte strings (`b"Rust"`)
1313 /// - arrays of bytes/numbers (`[b'A', 66, b'C']`)
1314 ///
1315 /// # Examples
1316 ///
1317 /// ```
1318 /// #![feature(concat_bytes)]
1319 ///
1320 /// # fn main() {
1321 /// let s: &[u8; 6] = concat_bytes!(b'A', b"BC", [68, b'E', 70]);
1322 /// assert_eq!(s, b"ABCDEF");
1323 /// # }
1324 /// ```
1325 #[unstable(feature = "concat_bytes", issue = "87555")]
1326 #[rustc_builtin_macro]
1327 #[macro_export]
1328 macro_rules! concat_bytes {
1329 ($($e:literal),+ $(,)?) => {{ /* compiler built-in */ }};
1330 }
1331
1332 /// Concatenates literals into a static string slice.
1333 ///
1334 /// This macro takes any number of comma-separated literals, yielding an
1335 /// expression of type `&'static str` which represents all of the literals
1336 /// concatenated left-to-right.
1337 ///
1338 /// Integer and floating point literals are [stringified](core::stringify) in order to be
1339 /// concatenated.
1340 ///
1341 /// # Examples
1342 ///
1343 /// ```
1344 /// let s = concat!("test", 10, 'b', true);
1345 /// assert_eq!(s, "test10btrue");
1346 /// ```
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 #[rustc_builtin_macro]
1349 #[rustc_diagnostic_item = "macro_concat"]
1350 #[macro_export]
1351 macro_rules! concat {
1352 ($($e:expr),* $(,)?) => {{ /* compiler built-in */ }};
1353 }
1354
1355 /// Expands to the line number on which it was invoked.
1356 ///
1357 /// With [`column!`] and [`file!`], these macros provide debugging information for
1358 /// developers about the location within the source.
1359 ///
1360 /// The expanded expression has type `u32` and is 1-based, so the first line
1361 /// in each file evaluates to 1, the second to 2, etc. This is consistent
1362 /// with error messages by common compilers or popular editors.
1363 /// The returned line is *not necessarily* the line of the `line!` invocation itself,
1364 /// but rather the first macro invocation leading up to the invocation
1365 /// of the `line!` macro.
1366 ///
1367 /// # Examples
1368 ///
1369 /// ```
1370 /// let current_line = line!();
1371 /// println!("defined on line: {current_line}");
1372 /// ```
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 #[rustc_builtin_macro]
1375 #[macro_export]
1376 macro_rules! line {
1377 () => {
1378 /* compiler built-in */
1379 };
1380 }
1381
1382 /// Expands to the column number at which it was invoked.
1383 ///
1384 /// With [`line!`] and [`file!`], these macros provide debugging information for
1385 /// developers about the location within the source.
1386 ///
1387 /// The expanded expression has type `u32` and is 1-based, so the first column
1388 /// in each line evaluates to 1, the second to 2, etc. This is consistent
1389 /// with error messages by common compilers or popular editors.
1390 /// The returned column is *not necessarily* the line of the `column!` invocation itself,
1391 /// but rather the first macro invocation leading up to the invocation
1392 /// of the `column!` macro.
1393 ///
1394 /// # Examples
1395 ///
1396 /// ```
1397 /// let current_col = column!();
1398 /// println!("defined on column: {current_col}");
1399 /// ```
1400 ///
1401 /// `column!` counts Unicode code points, not bytes or graphemes. As a result, the first two
1402 /// invocations return the same value, but the third does not.
1403 ///
1404 /// ```
1405 /// let a = ("foobar", column!()).1;
1406 /// let b = ("人之初性本善", column!()).1;
1407 /// let c = ("f̅o̅o̅b̅a̅r̅", column!()).1; // Uses combining overline (U+0305)
1408 ///
1409 /// assert_eq!(a, b);
1410 /// assert_ne!(b, c);
1411 /// ```
1412 #[stable(feature = "rust1", since = "1.0.0")]
1413 #[rustc_builtin_macro]
1414 #[macro_export]
1415 macro_rules! column {
1416 () => {
1417 /* compiler built-in */
1418 };
1419 }
1420
1421 /// Expands to the file name in which it was invoked.
1422 ///
1423 /// With [`line!`] and [`column!`], these macros provide debugging information for
1424 /// developers about the location within the source.
1425 ///
1426 /// The expanded expression has type `&'static str`, and the returned file
1427 /// is not the invocation of the `file!` macro itself, but rather the
1428 /// first macro invocation leading up to the invocation of the `file!`
1429 /// macro.
1430 ///
1431 /// The file name is derived from the crate root's source path passed to the Rust compiler
1432 /// and the sequence the compiler takes to get from the crate root to the
1433 /// module containing `file!`, modified by any flags passed to the Rust compiler (e.g.
1434 /// `--remap-path-prefix`). If the crate's source path is relative, the initial base
1435 /// directory will be the working directory of the Rust compiler. For example, if the source
1436 /// path passed to the compiler is `./src/lib.rs` which has a `mod foo;` with a source path of
1437 /// `src/foo/mod.rs`, then calling `file!` inside `mod foo;` will return `./src/foo/mod.rs`.
1438 ///
1439 /// Future compiler options might make further changes to the behavior of `file!`,
1440 /// including potentially making it entirely empty. Code (e.g. test libraries)
1441 /// relying on `file!` producing an openable file path would be incompatible
1442 /// with such options, and might wish to recommend not using those options.
1443 ///
1444 /// # Examples
1445 ///
1446 /// ```
1447 /// let this_file = file!();
1448 /// println!("defined in file: {this_file}");
1449 /// ```
1450 #[stable(feature = "rust1", since = "1.0.0")]
1451 #[rustc_builtin_macro]
1452 #[macro_export]
1453 macro_rules! file {
1454 () => {
1455 /* compiler built-in */
1456 };
1457 }
1458
1459 /// Stringifies its arguments.
1460 ///
1461 /// This macro will yield an expression of type `&'static str` which is the
1462 /// stringification of all the tokens passed to the macro. No restrictions
1463 /// are placed on the syntax of the macro invocation itself.
1464 ///
1465 /// Note that the expanded results of the input tokens may change in the
1466 /// future. You should be careful if you rely on the output.
1467 ///
1468 /// # Examples
1469 ///
1470 /// ```
1471 /// let one_plus_one = stringify!(1 + 1);
1472 /// assert_eq!(one_plus_one, "1 + 1");
1473 /// ```
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 #[rustc_builtin_macro]
1476 #[macro_export]
1477 macro_rules! stringify {
1478 ($($t:tt)*) => {
1479 /* compiler built-in */
1480 };
1481 }
1482
1483 /// Includes a UTF-8 encoded file as a string.
1484 ///
1485 /// The file is located relative to the current file (similarly to how
1486 /// modules are found). The provided path is interpreted in a platform-specific
1487 /// way at compile time. So, for instance, an invocation with a Windows path
1488 /// containing backslashes `\` would not compile correctly on Unix.
1489 ///
1490 /// This macro will yield an expression of type `&'static str` which is the
1491 /// contents of the file.
1492 ///
1493 /// # Examples
1494 ///
1495 /// Assume there are two files in the same directory with the following
1496 /// contents:
1497 ///
1498 /// File 'spanish.in':
1499 ///
1500 /// ```text
1501 /// adiós
1502 /// ```
1503 ///
1504 /// File 'main.rs':
1505 ///
1506 /// ```ignore (cannot-doctest-external-file-dependency)
1507 /// fn main() {
1508 /// let my_str = include_str!("spanish.in");
1509 /// assert_eq!(my_str, "adiós\n");
1510 /// print!("{my_str}");
1511 /// }
1512 /// ```
1513 ///
1514 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 #[rustc_builtin_macro]
1517 #[macro_export]
1518 #[rustc_diagnostic_item = "include_str_macro"]
1519 macro_rules! include_str {
1520 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1521 }
1522
1523 /// Includes a file as a reference to a byte array.
1524 ///
1525 /// The file is located relative to the current file (similarly to how
1526 /// modules are found). The provided path is interpreted in a platform-specific
1527 /// way at compile time. So, for instance, an invocation with a Windows path
1528 /// containing backslashes `\` would not compile correctly on Unix.
1529 ///
1530 /// This macro will yield an expression of type `&'static [u8; N]` which is
1531 /// the contents of the file.
1532 ///
1533 /// # Examples
1534 ///
1535 /// Assume there are two files in the same directory with the following
1536 /// contents:
1537 ///
1538 /// File 'spanish.in':
1539 ///
1540 /// ```text
1541 /// adiós
1542 /// ```
1543 ///
1544 /// File 'main.rs':
1545 ///
1546 /// ```ignore (cannot-doctest-external-file-dependency)
1547 /// fn main() {
1548 /// let bytes = include_bytes!("spanish.in");
1549 /// assert_eq!(bytes, b"adi\xc3\xb3s\n");
1550 /// print!("{}", String::from_utf8_lossy(bytes));
1551 /// }
1552 /// ```
1553 ///
1554 /// Compiling 'main.rs' and running the resulting binary will print "adiós".
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 #[rustc_builtin_macro]
1557 #[macro_export]
1558 #[rustc_diagnostic_item = "include_bytes_macro"]
1559 macro_rules! include_bytes {
1560 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1561 }
1562
1563 /// Expands to a string that represents the current module path.
1564 ///
1565 /// The current module path can be thought of as the hierarchy of modules
1566 /// leading back up to the crate root. The first component of the path
1567 /// returned is the name of the crate currently being compiled.
1568 ///
1569 /// # Examples
1570 ///
1571 /// ```
1572 /// mod test {
1573 /// pub fn foo() {
1574 /// assert!(module_path!().ends_with("test"));
1575 /// }
1576 /// }
1577 ///
1578 /// test::foo();
1579 /// ```
1580 #[stable(feature = "rust1", since = "1.0.0")]
1581 #[rustc_builtin_macro]
1582 #[macro_export]
1583 macro_rules! module_path {
1584 () => {
1585 /* compiler built-in */
1586 };
1587 }
1588
1589 /// Evaluates boolean combinations of configuration flags at compile-time.
1590 ///
1591 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
1592 /// boolean expression evaluation of configuration flags. This frequently
1593 /// leads to less duplicated code.
1594 ///
1595 /// The syntax given to this macro is the same syntax as the [`cfg`]
1596 /// attribute.
1597 ///
1598 /// `cfg!`, unlike `#[cfg]`, does not remove any code and only evaluates to true or false. For
1599 /// example, all blocks in an if/else expression need to be valid when `cfg!` is used for
1600 /// the condition, regardless of what `cfg!` is evaluating.
1601 ///
1602 /// [`cfg`]: ../reference/conditional-compilation.html#the-cfg-attribute
1603 ///
1604 /// # Examples
1605 ///
1606 /// ```
1607 /// let my_directory = if cfg!(windows) {
1608 /// "windows-specific-directory"
1609 /// } else {
1610 /// "unix-directory"
1611 /// };
1612 /// ```
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 #[rustc_builtin_macro]
1615 #[macro_export]
1616 macro_rules! cfg {
1617 ($($cfg:tt)*) => {
1618 /* compiler built-in */
1619 };
1620 }
1621
1622 /// Parses a file as an expression or an item according to the context.
1623 ///
1624 /// **Warning**: For multi-file Rust projects, the `include!` macro is probably not what you
1625 /// are looking for. Usually, multi-file Rust projects use
1626 /// [modules](https://doc.rust-lang.org/reference/items/modules.html). Multi-file projects and
1627 /// modules are explained in the Rust-by-Example book
1628 /// [here](https://doc.rust-lang.org/rust-by-example/mod/split.html) and the module system is
1629 /// explained in the Rust Book
1630 /// [here](https://doc.rust-lang.org/book/ch07-02-defining-modules-to-control-scope-and-privacy.html).
1631 ///
1632 /// The included file is placed in the surrounding code
1633 /// [unhygienically](https://doc.rust-lang.org/reference/macros-by-example.html#hygiene). If
1634 /// the included file is parsed as an expression and variables or functions share names across
1635 /// both files, it could result in variables or functions being different from what the
1636 /// included file expected.
1637 ///
1638 /// The included file is located relative to the current file (similarly to how modules are
1639 /// found). The provided path is interpreted in a platform-specific way at compile time. So,
1640 /// for instance, an invocation with a Windows path containing backslashes `\` would not
1641 /// compile correctly on Unix.
1642 ///
1643 /// # Uses
1644 ///
1645 /// The `include!` macro is primarily used for two purposes. It is used to include
1646 /// documentation that is written in a separate file and it is used to include [build artifacts
1647 /// usually as a result from the `build.rs`
1648 /// script](https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script).
1649 ///
1650 /// When using the `include` macro to include stretches of documentation, remember that the
1651 /// included file still needs to be a valid Rust syntax. It is also possible to
1652 /// use the [`include_str`] macro as `#![doc = include_str!("...")]` (at the module level) or
1653 /// `#[doc = include_str!("...")]` (at the item level) to include documentation from a plain
1654 /// text or markdown file.
1655 ///
1656 /// # Examples
1657 ///
1658 /// Assume there are two files in the same directory with the following contents:
1659 ///
1660 /// File 'monkeys.in':
1661 ///
1662 /// ```ignore (only-for-syntax-highlight)
1663 /// ['🙈', '🙊', '🙉']
1664 /// .iter()
1665 /// .cycle()
1666 /// .take(6)
1667 /// .collect::<String>()
1668 /// ```
1669 ///
1670 /// File 'main.rs':
1671 ///
1672 /// ```ignore (cannot-doctest-external-file-dependency)
1673 /// fn main() {
1674 /// let my_string = include!("monkeys.in");
1675 /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
1676 /// println!("{my_string}");
1677 /// }
1678 /// ```
1679 ///
1680 /// Compiling 'main.rs' and running the resulting binary will print
1681 /// "🙈🙊🙉🙈🙊🙉".
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 #[rustc_builtin_macro]
1684 #[macro_export]
1685 #[rustc_diagnostic_item = "include_macro"] // useful for external lints
1686 macro_rules! include {
1687 ($file:expr $(,)?) => {{ /* compiler built-in */ }};
1688 }
1689
1690 /// This macro uses forward-mode automatic differentiation to generate a new function.
1691 /// It may only be applied to a function. The new function will compute the derivative
1692 /// of the function to which the macro was applied.
1693 ///
1694 /// The expected usage syntax is:
1695 /// `#[autodiff_forward(NAME, INPUT_ACTIVITIES, OUTPUT_ACTIVITY)]`
1696 ///
1697 /// - `NAME`: A string that represents a valid function name.
1698 /// - `INPUT_ACTIVITIES`: Specifies one valid activity for each input parameter.
1699 /// - `OUTPUT_ACTIVITY`: Must not be set if the function implicitly returns nothing
1700 /// (or explicitly returns `-> ()`). Otherwise, it must be set to one of the allowed activities.
1701 ///
1702 /// ACTIVITIES might either be `Dual` or `Const`, more options will be exposed later.
1703 ///
1704 /// `Const` should be used on non-float arguments, or float-based arguments as an optimization
1705 /// if we are not interested in computing the derivatives with respect to this argument.
1706 ///
1707 /// `Dual` can be used for float scalar values or for references, raw pointers, or other
1708 /// indirect input arguments. It can also be used on a scalar float return value.
1709 /// If used on a return value, the generated function will return a tuple of two float scalars.
1710 /// If used on an input argument, a new shadow argument of the same type will be created,
1711 /// directly following the original argument.
1712 ///
1713 /// ### Usage examples:
1714 ///
1715 /// ```rust,ignore (autodiff requires a -Z flag as well as fat-lto for testing)
1716 /// #![feature(autodiff)]
1717 /// use std::autodiff::*;
1718 /// #[autodiff_forward(rb_fwd1, Dual, Const, Dual)]
1719 /// #[autodiff_forward(rb_fwd2, Const, Dual, Dual)]
1720 /// #[autodiff_forward(rb_fwd3, Dual, Dual, Dual)]
1721 /// fn rosenbrock(x: f64, y: f64) -> f64 {
1722 /// (1.0 - x).powi(2) + 100.0 * (y - x.powi(2)).powi(2)
1723 /// }
1724 /// #[autodiff_forward(rb_inp_fwd, Dual, Dual, Dual)]
1725 /// fn rosenbrock_inp(x: f64, y: f64, out: &mut f64) {
1726 /// *out = (1.0 - x).powi(2) + 100.0 * (y - x.powi(2)).powi(2);
1727 /// }
1728 ///
1729 /// fn main() {
1730 /// let x0 = rosenbrock(1.0, 3.0); // 400.0
1731 /// let (x1, dx1) = rb_fwd1(1.0, 1.0, 3.0); // (400.0, -800.0)
1732 /// let (x2, dy1) = rb_fwd2(1.0, 3.0, 1.0); // (400.0, 400.0)
1733 /// // When seeding both arguments at once the tangent return is the sum of both.
1734 /// let (x3, dxy) = rb_fwd3(1.0, 1.0, 3.0, 1.0); // (400.0, -400.0)
1735 ///
1736 /// let mut out = 0.0;
1737 /// let mut dout = 0.0;
1738 /// rb_inp_fwd(1.0, 1.0, 3.0, 1.0, &mut out, &mut dout);
1739 /// // (out, dout) == (400.0, -400.0)
1740 /// }
1741 /// ```
1742 ///
1743 /// We might want to track how one input float affects one or more output floats. In this case,
1744 /// the shadow of one input should be initialized to `1.0`, while the shadows of the other
1745 /// inputs should be initialized to `0.0`. The shadow of the output(s) should be initialized to
1746 /// `0.0`. After calling the generated function, the shadow of the input will be zeroed,
1747 /// while the shadow(s) of the output(s) will contain the derivatives. Forward mode is generally
1748 /// more efficient if we have more output floats marked as `Dual` than input floats.
1749 /// Related information can also be found under the term "Vector-Jacobian product" (VJP).
1750 #[unstable(feature = "autodiff", issue = "124509")]
1751 #[allow_internal_unstable(rustc_attrs)]
1752 #[allow_internal_unstable(core_intrinsics)]
1753 #[rustc_builtin_macro]
1754 pub macro autodiff_forward($item:item) {
1755 /* compiler built-in */
1756 }
1757
1758 /// This macro uses reverse-mode automatic differentiation to generate a new function.
1759 /// It may only be applied to a function. The new function will compute the derivative
1760 /// of the function to which the macro was applied.
1761 ///
1762 /// The expected usage syntax is:
1763 /// `#[autodiff_reverse(NAME, INPUT_ACTIVITIES, OUTPUT_ACTIVITY)]`
1764 ///
1765 /// - `NAME`: A string that represents a valid function name.
1766 /// - `INPUT_ACTIVITIES`: Specifies one valid activity for each input parameter.
1767 /// - `OUTPUT_ACTIVITY`: Must not be set if the function implicitly returns nothing
1768 /// (or explicitly returns `-> ()`). Otherwise, it must be set to one of the allowed activities.
1769 ///
1770 /// ACTIVITIES might either be `Active`, `Duplicated` or `Const`, more options will be exposed later.
1771 ///
1772 /// `Active` can be used for float scalar values.
1773 /// If used on an input, a new float will be appended to the return tuple of the generated
1774 /// function. If the function returns a float scalar, `Active` can be used for the return as
1775 /// well. In this case a float scalar will be appended to the argument list, it works as seed.
1776 ///
1777 /// `Duplicated` can be used on references, raw pointers, or other indirect input
1778 /// arguments. It creates a new shadow argument of the same type, following the original argument.
1779 /// A const reference or pointer argument will receive a mutable reference or pointer as shadow.
1780 ///
1781 /// `Const` should be used on non-float arguments, or float-based arguments as an optimization
1782 /// if we are not interested in computing the derivatives with respect to this argument.
1783 ///
1784 /// ### Usage examples:
1785 ///
1786 /// ```rust,ignore (autodiff requires a -Z flag as well as fat-lto for testing)
1787 /// #![feature(autodiff)]
1788 /// use std::autodiff::*;
1789 /// #[autodiff_reverse(rb_rev, Active, Active, Active)]
1790 /// fn rosenbrock(x: f64, y: f64) -> f64 {
1791 /// (1.0 - x).powi(2) + 100.0 * (y - x.powi(2)).powi(2)
1792 /// }
1793 /// #[autodiff_reverse(rb_inp_rev, Active, Active, Duplicated)]
1794 /// fn rosenbrock_inp(x: f64, y: f64, out: &mut f64) {
1795 /// *out = (1.0 - x).powi(2) + 100.0 * (y - x.powi(2)).powi(2);
1796 /// }
1797 ///
1798 /// fn main() {
1799 /// let (output1, dx1, dy1) = rb_rev(1.0, 3.0, 1.0);
1800 /// dbg!(output1, dx1, dy1); // (400.0, -800.0, 400.0)
1801 /// let mut output2 = 0.0;
1802 /// let mut seed = 1.0;
1803 /// let (dx2, dy2) = rb_inp_rev(1.0, 3.0, &mut output2, &mut seed);
1804 /// // (dx2, dy2, output2, seed) == (-800.0, 400.0, 400.0, 0.0)
1805 /// }
1806 /// ```
1807 ///
1808 ///
1809 /// We often want to track how one or more input floats affect one output float. This output can
1810 /// be a scalar return value, or a mutable reference or pointer argument. In the latter case, the
1811 /// mutable input should be marked as duplicated and its shadow initialized to `0.0`. The shadow of
1812 /// the output should be marked as active or duplicated and initialized to `1.0`. After calling
1813 /// the generated function, the shadow(s) of the input(s) will contain the derivatives. The
1814 /// shadow of the outputs ("seed") will be reset to zero.
1815 /// If the function has more than one output float marked as active or duplicated, users might want to
1816 /// set one of them to `1.0` and the others to `0.0` to compute partial derivatives.
1817 /// Unlike forward-mode, a call to the generated function does not reset the shadow of the
1818 /// inputs.
1819 /// Reverse mode is generally more efficient if we have more active/duplicated input than
1820 /// output floats.
1821 ///
1822 /// Related information can also be found under the term "Jacobian-Vector Product" (JVP).
1823 #[unstable(feature = "autodiff", issue = "124509")]
1824 #[allow_internal_unstable(rustc_attrs)]
1825 #[allow_internal_unstable(core_intrinsics)]
1826 #[rustc_builtin_macro]
1827 pub macro autodiff_reverse($item:item) {
1828 /* compiler built-in */
1829 }
1830
1831 /// Asserts that a boolean expression is `true` at runtime.
1832 ///
1833 /// This will invoke the [`panic!`] macro if the provided expression cannot be
1834 /// evaluated to `true` at runtime.
1835 ///
1836 /// # Uses
1837 ///
1838 /// Assertions are always checked in both debug and release builds, and cannot
1839 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
1840 /// release builds by default.
1841 ///
1842 /// Unsafe code may rely on `assert!` to enforce run-time invariants that, if
1843 /// violated could lead to unsafety.
1844 ///
1845 /// Other use-cases of `assert!` include testing and enforcing run-time
1846 /// invariants in safe code (whose violation cannot result in unsafety).
1847 ///
1848 /// # Custom Messages
1849 ///
1850 /// This macro has a second form, where a custom panic message can
1851 /// be provided with or without arguments for formatting. See [`std::fmt`]
1852 /// for syntax for this form. Expressions used as format arguments will only
1853 /// be evaluated if the assertion fails.
1854 ///
1855 /// [`std::fmt`]: ../std/fmt/index.html
1856 ///
1857 /// # Examples
1858 ///
1859 /// ```
1860 /// // the panic message for these assertions is the stringified value of the
1861 /// // expression given.
1862 /// assert!(true);
1863 ///
1864 /// fn some_computation() -> bool {
1865 /// // Some expensive computation here
1866 /// true
1867 /// }
1868 ///
1869 /// assert!(some_computation());
1870 ///
1871 /// // assert with a custom message
1872 /// let x = true;
1873 /// assert!(x, "x wasn't true!");
1874 ///
1875 /// let a = 3; let b = 27;
1876 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
1877 /// ```
1878 #[stable(feature = "rust1", since = "1.0.0")]
1879 #[rustc_builtin_macro]
1880 #[macro_export]
1881 #[rustc_diagnostic_item = "assert_macro"]
1882 #[allow_internal_unstable(
1883 core_intrinsics,
1884 panic_internals,
1885 edition_panic,
1886 generic_assert_internals
1887 )]
1888 macro_rules! assert {
1889 ($cond:expr $(,)?) => {{ /* compiler built-in */ }};
1890 ($cond:expr, $($arg:tt)+) => {{ /* compiler built-in */ }};
1891 }
1892
1893 /// Prints passed tokens into the standard output.
1894 #[unstable(
1895 feature = "log_syntax",
1896 issue = "29598",
1897 reason = "`log_syntax!` is not stable enough for use and is subject to change"
1898 )]
1899 #[rustc_builtin_macro]
1900 #[macro_export]
1901 macro_rules! log_syntax {
1902 ($($arg:tt)*) => {
1903 /* compiler built-in */
1904 };
1905 }
1906
1907 /// Enables or disables tracing functionality used for debugging other macros.
1908 #[unstable(
1909 feature = "trace_macros",
1910 issue = "29598",
1911 reason = "`trace_macros` is not stable enough for use and is subject to change"
1912 )]
1913 #[rustc_builtin_macro]
1914 #[macro_export]
1915 macro_rules! trace_macros {
1916 (true) => {{ /* compiler built-in */ }};
1917 (false) => {{ /* compiler built-in */ }};
1918 }
1919
1920 /// Attribute macro used to apply derive macros.
1921 ///
1922 /// See [the reference] for more info.
1923 ///
1924 /// [the reference]: ../../../reference/attributes/derive.html
1925 #[stable(feature = "rust1", since = "1.0.0")]
1926 #[rustc_builtin_macro]
1927 pub macro derive($item:item) {
1928 /* compiler built-in */
1929 }
1930
1931 /// Attribute macro used to apply derive macros for implementing traits
1932 /// in a const context.
1933 ///
1934 /// See [the reference] for more info.
1935 ///
1936 /// [the reference]: ../../../reference/attributes/derive.html
1937 #[unstable(feature = "derive_const", issue = "118304")]
1938 #[rustc_builtin_macro]
1939 pub macro derive_const($item:item) {
1940 /* compiler built-in */
1941 }
1942
1943 /// Attribute macro applied to a function to turn it into a unit test.
1944 ///
1945 /// See [the reference] for more info.
1946 ///
1947 /// [the reference]: ../../../reference/attributes/testing.html#the-test-attribute
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 #[allow_internal_unstable(test, rustc_attrs, coverage_attribute)]
1950 #[rustc_builtin_macro]
1951 pub macro test($item:item) {
1952 /* compiler built-in */
1953 }
1954
1955 /// Attribute macro applied to a function to turn it into a benchmark test.
1956 #[unstable(
1957 feature = "test",
1958 issue = "50297",
1959 reason = "`bench` is a part of custom test frameworks which are unstable"
1960 )]
1961 #[allow_internal_unstable(test, rustc_attrs, coverage_attribute)]
1962 #[rustc_builtin_macro]
1963 pub macro bench($item:item) {
1964 /* compiler built-in */
1965 }
1966
1967 /// An implementation detail of the `#[test]` and `#[bench]` macros.
1968 #[unstable(
1969 feature = "custom_test_frameworks",
1970 issue = "50297",
1971 reason = "custom test frameworks are an unstable feature"
1972 )]
1973 #[allow_internal_unstable(test, rustc_attrs)]
1974 #[rustc_builtin_macro]
1975 pub macro test_case($item:item) {
1976 /* compiler built-in */
1977 }
1978
1979 /// Attribute macro applied to a static to register it as a global allocator.
1980 ///
1981 /// See also [`std::alloc::GlobalAlloc`](../../../std/alloc/trait.GlobalAlloc.html).
1982 #[stable(feature = "global_allocator", since = "1.28.0")]
1983 #[allow_internal_unstable(rustc_attrs)]
1984 #[rustc_builtin_macro]
1985 pub macro global_allocator($item:item) {
1986 /* compiler built-in */
1987 }
1988
1989 /// Attribute macro applied to a function to give it a post-condition.
1990 ///
1991 /// The attribute carries an argument token-tree which is
1992 /// eventually parsed as a unary closure expression that is
1993 /// invoked on a reference to the return value.
1994 #[unstable(feature = "contracts", issue = "128044")]
1995 #[allow_internal_unstable(contracts_internals)]
1996 #[rustc_builtin_macro]
1997 pub macro contracts_ensures($item:item) {
1998 /* compiler built-in */
1999 }
2000
2001 /// Attribute macro applied to a function to give it a precondition.
2002 ///
2003 /// The attribute carries an argument token-tree which is
2004 /// eventually parsed as an boolean expression with access to the
2005 /// function's formal parameters
2006 #[unstable(feature = "contracts", issue = "128044")]
2007 #[allow_internal_unstable(contracts_internals)]
2008 #[rustc_builtin_macro]
2009 pub macro contracts_requires($item:item) {
2010 /* compiler built-in */
2011 }
2012
2013 /// Attribute macro applied to a function to register it as a handler for allocation failure.
2014 ///
2015 /// See also [`std::alloc::handle_alloc_error`](../../../std/alloc/fn.handle_alloc_error.html).
2016 #[unstable(feature = "alloc_error_handler", issue = "51540")]
2017 #[allow_internal_unstable(rustc_attrs)]
2018 #[rustc_builtin_macro]
2019 pub macro alloc_error_handler($item:item) {
2020 /* compiler built-in */
2021 }
2022
2023 /// Keeps the item it's applied to if the passed path is accessible, and removes it otherwise.
2024 #[unstable(
2025 feature = "cfg_accessible",
2026 issue = "64797",
2027 reason = "`cfg_accessible` is not fully implemented"
2028 )]
2029 #[rustc_builtin_macro]
2030 pub macro cfg_accessible($item:item) {
2031 /* compiler built-in */
2032 }
2033
2034 /// Expands all `#[cfg]` and `#[cfg_attr]` attributes in the code fragment it's applied to.
2035 #[unstable(
2036 feature = "cfg_eval",
2037 issue = "82679",
2038 reason = "`cfg_eval` is a recently implemented feature"
2039 )]
2040 #[rustc_builtin_macro]
2041 pub macro cfg_eval($($tt:tt)*) {
2042 /* compiler built-in */
2043 }
2044
2045 /// Provide a list of type aliases and other opaque-type-containing type definitions
2046 /// to an item with a body. This list will be used in that body to define opaque
2047 /// types' hidden types.
2048 /// Can only be applied to things that have bodies.
2049 #[unstable(
2050 feature = "type_alias_impl_trait",
2051 issue = "63063",
2052 reason = "`type_alias_impl_trait` has open design concerns"
2053 )]
2054 #[rustc_builtin_macro]
2055 pub macro define_opaque($($tt:tt)*) {
2056 /* compiler built-in */
2057 }
2058
2059 /// Unstable placeholder for type ascription.
2060 #[allow_internal_unstable(builtin_syntax)]
2061 #[unstable(
2062 feature = "type_ascription",
2063 issue = "23416",
2064 reason = "placeholder syntax for type ascription"
2065 )]
2066 #[rustfmt::skip]
2067 pub macro type_ascribe($expr:expr, $ty:ty) {
2068 builtin # type_ascribe($expr, $ty)
2069 }
2070
2071 /// Unstable placeholder for deref patterns.
2072 #[allow_internal_unstable(builtin_syntax)]
2073 #[unstable(
2074 feature = "deref_patterns",
2075 issue = "87121",
2076 reason = "placeholder syntax for deref patterns"
2077 )]
2078 pub macro deref($pat:pat) {
2079 builtin # deref($pat)
2080 }
2081
2082 /// Derive macro generating an impl of the trait `From`.
2083 /// Currently, it can only be used on single-field structs.
2084 // Note that the macro is in a different module than the `From` trait,
2085 // to avoid triggering an unstable feature being used if someone imports
2086 // `std::convert::From`.
2087 #[rustc_builtin_macro]
2088 #[unstable(feature = "derive_from", issue = "144889")]
2089 pub macro From($item: item) {
2090 /* compiler built-in */
2091 }
2092}