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