1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 /// Entry point of thread panic, for details, see std::macros
13 #[allow_internal_unstable]
14 #[stable(feature = "core", since = "1.6.0")]
17 panic!("explicit panic")
20 $crate::panicking::panic(&($msg, file!(), line!(), __rust_unstable_column!()))
22 ($fmt:expr, $($arg:tt)*) => ({
23 $crate::panicking::panic_fmt(format_args!($fmt, $($arg)*),
24 &(file!(), line!(), __rust_unstable_column!()))
28 /// Ensure that a boolean expression is `true` at runtime.
30 /// This will invoke the [`panic!`] macro if the provided expression cannot be
31 /// evaluated to `true` at runtime.
35 /// Assertions are always checked in both debug and release builds, and cannot
36 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
37 /// release builds by default.
39 /// Unsafe code relies on `assert!` to enforce run-time invariants that, if
40 /// violated could lead to unsafety.
42 /// Other use-cases of `assert!` include [testing] and enforcing run-time
43 /// invariants in safe code (whose violation cannot result in unsafety).
47 /// This macro has a second form, where a custom panic message can
48 /// be provided with or without arguments for formatting. See [`std::fmt`]
49 /// for syntax for this form.
51 /// [`panic!`]: macro.panic.html
52 /// [`debug_assert!`]: macro.debug_assert.html
53 /// [testing]: ../book/second-edition/ch11-01-writing-tests.html#checking-results-with-the-assert-macro
54 /// [`std::fmt`]: ../std/fmt/index.html
59 /// // the panic message for these assertions is the stringified value of the
60 /// // expression given.
63 /// fn some_computation() -> bool { true } // a very simple function
65 /// assert!(some_computation());
67 /// // assert with a custom message
69 /// assert!(x, "x wasn't true!");
71 /// let a = 3; let b = 27;
72 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
75 #[stable(feature = "rust1", since = "1.0.0")]
79 panic!(concat!("assertion failed: ", stringify!($cond)))
82 ($cond:expr, $($arg:tt)+) => (
89 /// Asserts that two expressions are equal to each other (using [`PartialEq`]).
91 /// On panic, this macro will print the values of the expressions with their
92 /// debug representations.
94 /// Like [`assert!`], this macro has a second form, where a custom
95 /// panic message can be provided.
97 /// [`PartialEq`]: cmp/trait.PartialEq.html
98 /// [`assert!`]: macro.assert.html
105 /// assert_eq!(a, b);
107 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
110 #[stable(feature = "rust1", since = "1.0.0")]
111 macro_rules! assert_eq {
112 ($left:expr, $right:expr) => ({
113 match (&$left, &$right) {
114 (left_val, right_val) => {
115 if !(*left_val == *right_val) {
116 panic!(r#"assertion failed: `(left == right)`
118 right: `{:?}`"#, left_val, right_val)
123 ($left:expr, $right:expr,) => ({
124 assert_eq!($left, $right)
126 ($left:expr, $right:expr, $($arg:tt)+) => ({
127 match (&($left), &($right)) {
128 (left_val, right_val) => {
129 if !(*left_val == *right_val) {
130 panic!(r#"assertion failed: `(left == right)`
132 right: `{:?}`: {}"#, left_val, right_val,
133 format_args!($($arg)+))
140 /// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
142 /// On panic, this macro will print the values of the expressions with their
143 /// debug representations.
145 /// Like [`assert!`], this macro has a second form, where a custom
146 /// panic message can be provided.
148 /// [`PartialEq`]: cmp/trait.PartialEq.html
149 /// [`assert!`]: macro.assert.html
156 /// assert_ne!(a, b);
158 /// assert_ne!(a, b, "we are testing that the values are not equal");
161 #[stable(feature = "assert_ne", since = "1.13.0")]
162 macro_rules! assert_ne {
163 ($left:expr, $right:expr) => ({
164 match (&$left, &$right) {
165 (left_val, right_val) => {
166 if *left_val == *right_val {
167 panic!(r#"assertion failed: `(left != right)`
169 right: `{:?}`"#, left_val, right_val)
174 ($left:expr, $right:expr,) => {
175 assert_ne!($left, $right)
177 ($left:expr, $right:expr, $($arg:tt)+) => ({
178 match (&($left), &($right)) {
179 (left_val, right_val) => {
180 if *left_val == *right_val {
181 panic!(r#"assertion failed: `(left != right)`
183 right: `{:?}`: {}"#, left_val, right_val,
184 format_args!($($arg)+))
191 /// Ensure that a boolean expression is `true` at runtime.
193 /// This will invoke the [`panic!`] macro if the provided expression cannot be
194 /// evaluated to `true` at runtime.
196 /// Like [`assert!`], this macro also has a second version, where a custom panic
197 /// message can be provided.
201 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
202 /// optimized builds by default. An optimized build will omit all
203 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
204 /// compiler. This makes `debug_assert!` useful for checks that are too
205 /// expensive to be present in a release build but may be helpful during
208 /// An unchecked assertion allows a program in an inconsistent state to keep
209 /// running, which might have unexpected consequences but does not introduce
210 /// unsafety as long as this only happens in safe code. The performance cost
211 /// of assertions, is however, not measurable in general. Replacing [`assert!`]
212 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
213 /// more importantly, only in safe code!
215 /// [`panic!`]: macro.panic.html
216 /// [`assert!`]: macro.assert.html
221 /// // the panic message for these assertions is the stringified value of the
222 /// // expression given.
223 /// debug_assert!(true);
225 /// fn some_expensive_computation() -> bool { true } // a very simple function
226 /// debug_assert!(some_expensive_computation());
228 /// // assert with a custom message
230 /// debug_assert!(x, "x wasn't true!");
232 /// let a = 3; let b = 27;
233 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
236 #[stable(feature = "rust1", since = "1.0.0")]
237 macro_rules! debug_assert {
238 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
241 /// Asserts that two expressions are equal to each other.
243 /// On panic, this macro will print the values of the expressions with their
244 /// debug representations.
246 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
247 /// optimized builds by default. An optimized build will omit all
248 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
249 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
250 /// expensive to be present in a release build but may be helpful during
253 /// [`assert_eq!`]: ../std/macro.assert_eq.html
260 /// debug_assert_eq!(a, b);
263 #[stable(feature = "rust1", since = "1.0.0")]
264 macro_rules! debug_assert_eq {
265 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
268 /// Asserts that two expressions are not equal to each other.
270 /// On panic, this macro will print the values of the expressions with their
271 /// debug representations.
273 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
274 /// optimized builds by default. An optimized build will omit all
275 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
276 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
277 /// expensive to be present in a release build but may be helpful during
280 /// [`assert_ne!`]: ../std/macro.assert_ne.html
287 /// debug_assert_ne!(a, b);
290 #[stable(feature = "assert_ne", since = "1.13.0")]
291 macro_rules! debug_assert_ne {
292 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_ne!($($arg)*); })
295 /// Helper macro for reducing boilerplate code for matching `Result` together
296 /// with converting downstream errors.
298 /// The `?` operator was added to replace `try!` and should be used instead.
300 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
301 /// expression has the value of the wrapped value.
303 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
304 /// performs conversion using `From`. This provides automatic conversion
305 /// between specialized errors and more general ones. The resulting
306 /// error is then immediately returned.
308 /// Because of the early return, `try!` can only be used in functions that
309 /// return [`Result`].
311 /// [`Result`]: ../std/result/enum.Result.html
317 /// use std::fs::File;
318 /// use std::io::prelude::*;
324 /// impl From<io::Error> for MyError {
325 /// fn from(e: io::Error) -> MyError {
326 /// MyError::FileWriteError
330 /// // The preferred method of quick returning Errors
331 /// fn write_to_file_question() -> Result<(), MyError> {
332 /// let mut file = File::create("my_best_friends.txt")?;
333 /// file.write_all(b"This is a list of my best friends.")?;
337 /// // The previous method of quick returning Errors
338 /// fn write_to_file_using_try() -> Result<(), MyError> {
339 /// let mut file = try!(File::create("my_best_friends.txt"));
340 /// try!(file.write_all(b"This is a list of my best friends."));
344 /// // This is equivalent to:
345 /// fn write_to_file_using_match() -> Result<(), MyError> {
346 /// let mut file = try!(File::create("my_best_friends.txt"));
347 /// match file.write_all(b"This is a list of my best friends.") {
349 /// Err(e) => return Err(From::from(e)),
355 #[stable(feature = "rust1", since = "1.0.0")]
357 ($expr:expr) => (match $expr {
358 $crate::result::Result::Ok(val) => val,
359 $crate::result::Result::Err(err) => {
360 return $crate::result::Result::Err($crate::convert::From::from(err))
365 /// Write formatted data into a buffer.
367 /// This macro accepts a format string, a list of arguments, and a 'writer'. Arguments will be
368 /// formatted according to the specified format string and the result will be passed to the writer.
369 /// The writer may be any value with a `write_fmt` method; generally this comes from an
370 /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro
371 /// returns whatever the `write_fmt` method returns; commonly a [`std::fmt::Result`], or an
374 /// See [`std::fmt`] for more information on the format string syntax.
376 /// [`std::fmt`]: ../std/fmt/index.html
377 /// [`std::fmt::Write`]: ../std/fmt/trait.Write.html
378 /// [`std::io::Write`]: ../std/io/trait.Write.html
379 /// [`std::fmt::Result`]: ../std/fmt/type.Result.html
380 /// [`io::Result`]: ../std/io/type.Result.html
385 /// use std::io::Write;
387 /// let mut w = Vec::new();
388 /// write!(&mut w, "test").unwrap();
389 /// write!(&mut w, "formatted {}", "arguments").unwrap();
391 /// assert_eq!(w, b"testformatted arguments");
394 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
395 /// implementing either, as objects do not typically implement both. However, the module must
396 /// import the traits qualified so their names do not conflict:
399 /// use std::fmt::Write as FmtWrite;
400 /// use std::io::Write as IoWrite;
402 /// let mut s = String::new();
403 /// let mut v = Vec::new();
404 /// write!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
405 /// write!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
406 /// assert_eq!(v, b"s = \"abc 123\"");
409 #[stable(feature = "rust1", since = "1.0.0")]
411 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
414 /// Write formatted data into a buffer, with a newline appended.
416 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
417 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
419 /// For more information, see [`write!`]. For information on the format string syntax, see
422 /// [`write!`]: macro.write.html
423 /// [`std::fmt`]: ../std/fmt/index.html
429 /// use std::io::Write;
431 /// let mut w = Vec::new();
432 /// writeln!(&mut w).unwrap();
433 /// writeln!(&mut w, "test").unwrap();
434 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
436 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
439 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
440 /// implementing either, as objects do not typically implement both. However, the module must
441 /// import the traits qualified so their names do not conflict:
444 /// use std::fmt::Write as FmtWrite;
445 /// use std::io::Write as IoWrite;
447 /// let mut s = String::new();
448 /// let mut v = Vec::new();
449 /// writeln!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
450 /// writeln!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
451 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
454 #[stable(feature = "rust1", since = "1.0.0")]
455 macro_rules! writeln {
459 ($dst:expr, $fmt:expr) => (
460 write!($dst, concat!($fmt, "\n"))
462 ($dst:expr, $fmt:expr, $($arg:tt)*) => (
463 write!($dst, concat!($fmt, "\n"), $($arg)*)
467 /// A utility macro for indicating unreachable code.
469 /// This is useful any time that the compiler can't determine that some code is unreachable. For
472 /// * Match arms with guard conditions.
473 /// * Loops that dynamically terminate.
474 /// * Iterators that dynamically terminate.
476 /// If the determination that the code is unreachable proves incorrect, the
477 /// program immediately terminates with a [`panic!`]. The function [`unreachable`],
478 /// which belongs to the [`std::intrinsics`] module, informs the compilier to
479 /// optimize the code out of the release version entirely.
481 /// [`panic!`]: ../std/macro.panic.html
482 /// [`unreachable`]: ../std/intrinsics/fn.unreachable.html
483 /// [`std::intrinsics`]: ../std/intrinsics/index.html
487 /// This will always [`panic!`]
489 /// [`panic!`]: ../std/macro.panic.html
495 /// # #[allow(dead_code)]
496 /// fn foo(x: Option<i32>) {
498 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
499 /// Some(n) if n < 0 => println!("Some(Negative)"),
500 /// Some(_) => unreachable!(), // compile error if commented out
501 /// None => println!("None")
509 /// # #[allow(dead_code)]
510 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
512 /// if 3*i < i { panic!("u32 overflow"); }
513 /// if x < 3*i { return i-1; }
519 #[stable(feature = "rust1", since = "1.0.0")]
520 macro_rules! unreachable {
522 panic!("internal error: entered unreachable code")
525 unreachable!("{}", $msg)
527 ($fmt:expr, $($arg:tt)*) => ({
528 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
532 /// A standardized placeholder for marking unfinished code.
534 /// This can be useful if you are prototyping and are just looking to have your
535 /// code typecheck, or if you're implementing a trait that requires multiple
536 /// methods, and you're only planning on using one of them.
540 /// This will always [panic!](macro.panic.html)
544 /// Here's an example of some in-progress code. We have a trait `Foo`:
553 /// We want to implement `Foo` on one of our types, but we also want to work on
554 /// just `bar()` first. In order for our code to compile, we need to implement
555 /// `baz()`, so we can use `unimplemented!`:
564 /// impl Foo for MyStruct {
566 /// // implementation goes here
570 /// // let's not worry about implementing baz() for now
571 /// unimplemented!();
576 /// let s = MyStruct;
579 /// // we aren't even using baz() yet, so this is fine.
583 #[stable(feature = "rust1", since = "1.0.0")]
584 macro_rules! unimplemented {
585 () => (panic!("not yet implemented"));
586 ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)*)));
589 /// Built-in macros to the compiler itself.
591 /// These macros do not have any corresponding definition with a `macro_rules!`
592 /// macro, but are documented here. Their implementations can be found hardcoded
593 /// into libsyntax itself.
595 /// For more information, see documentation for `std`'s macros.
598 /// Unconditionally causes compilation to fail with the given error message when encountered.
600 /// For more information, see the documentation for [`std::compile_error!`].
602 /// [`std::compile_error!`]: ../std/macro.compile_error.html
603 #[stable(feature = "compile_error_macro", since = "1.20.0")]
606 macro_rules! compile_error { ($msg:expr) => ({ /* compiler built-in */ }) }
608 /// The core macro for formatted string creation & output.
610 /// For more information, see the documentation for [`std::format_args!`].
612 /// [`std::format_args!`]: ../std/macro.format_args.html
613 #[stable(feature = "rust1", since = "1.0.0")]
616 macro_rules! format_args {
617 ($fmt:expr) => ({ /* compiler built-in */ });
618 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ });
621 /// Inspect an environment variable at compile time.
623 /// For more information, see the documentation for [`std::env!`].
625 /// [`std::env!`]: ../std/macro.env.html
626 #[stable(feature = "rust1", since = "1.0.0")]
630 ($name:expr) => ({ /* compiler built-in */ });
631 ($name:expr,) => ({ /* compiler built-in */ });
634 /// Optionally inspect an environment variable at compile time.
636 /// For more information, see the documentation for [`std::option_env!`].
638 /// [`std::option_env!`]: ../std/macro.option_env.html
639 #[stable(feature = "rust1", since = "1.0.0")]
642 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
644 /// Concatenate identifiers into one identifier.
646 /// For more information, see the documentation for [`std::concat_idents!`].
648 /// [`std::concat_idents!`]: ../std/macro.concat_idents.html
649 #[unstable(feature = "concat_idents_macro", issue = "29599")]
652 macro_rules! concat_idents {
653 ($($e:ident),*) => ({ /* compiler built-in */ });
654 ($($e:ident,)*) => ({ /* compiler built-in */ });
657 /// Concatenates literals into a static string slice.
659 /// For more information, see the documentation for [`std::concat!`].
661 /// [`std::concat!`]: ../std/macro.concat.html
662 #[stable(feature = "rust1", since = "1.0.0")]
665 macro_rules! concat {
666 ($($e:expr),*) => ({ /* compiler built-in */ });
667 ($($e:expr,)*) => ({ /* compiler built-in */ });
670 /// A macro which expands to the line number on which it was invoked.
672 /// For more information, see the documentation for [`std::line!`].
674 /// [`std::line!`]: ../std/macro.line.html
675 #[stable(feature = "rust1", since = "1.0.0")]
678 macro_rules! line { () => ({ /* compiler built-in */ }) }
680 /// A macro which expands to the column number on which it was invoked.
682 /// For more information, see the documentation for [`std::column!`].
684 /// [`std::column!`]: ../std/macro.column.html
685 #[stable(feature = "rust1", since = "1.0.0")]
688 macro_rules! column { () => ({ /* compiler built-in */ }) }
690 /// A macro which expands to the file name from which it was invoked.
692 /// For more information, see the documentation for [`std::file!`].
694 /// [`std::file!`]: ../std/macro.file.html
695 #[stable(feature = "rust1", since = "1.0.0")]
698 macro_rules! file { () => ({ /* compiler built-in */ }) }
700 /// A macro which stringifies its arguments.
702 /// For more information, see the documentation for [`std::stringify!`].
704 /// [`std::stringify!`]: ../std/macro.stringify.html
705 #[stable(feature = "rust1", since = "1.0.0")]
708 macro_rules! stringify { ($($t:tt)*) => ({ /* compiler built-in */ }) }
710 /// Includes a utf8-encoded file as a string.
712 /// For more information, see the documentation for [`std::include_str!`].
714 /// [`std::include_str!`]: ../std/macro.include_str.html
715 #[stable(feature = "rust1", since = "1.0.0")]
718 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
720 /// Includes a file as a reference to a byte array.
722 /// For more information, see the documentation for [`std::include_bytes!`].
724 /// [`std::include_bytes!`]: ../std/macro.include_bytes.html
725 #[stable(feature = "rust1", since = "1.0.0")]
728 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
730 /// Expands to a string that represents the current module path.
732 /// For more information, see the documentation for [`std::module_path!`].
734 /// [`std::module_path!`]: ../std/macro.module_path.html
735 #[stable(feature = "rust1", since = "1.0.0")]
738 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
740 /// Boolean evaluation of configuration flags, at compile-time.
742 /// For more information, see the documentation for [`std::cfg!`].
744 /// [`std::cfg!`]: ../std/macro.cfg.html
745 #[stable(feature = "rust1", since = "1.0.0")]
748 macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
750 /// Parse a file as an expression or an item according to the context.
752 /// For more information, see the documentation for [`std::include!`].
754 /// [`std::include!`]: ../std/macro.include.html
755 #[stable(feature = "rust1", since = "1.0.0")]
758 macro_rules! include { ($file:expr) => ({ /* compiler built-in */ }) }