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 static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!());
21 $crate::panicking::panic(&_MSG_FILE_LINE)
23 ($fmt:expr, $($arg:tt)*) => ({
24 // The leading _'s are to avoid dead code warnings if this is
25 // used inside a dead function. Just `#[allow(dead_code)]` is
26 // insufficient, since the user may have
27 // `#[forbid(dead_code)]` and which cannot be overridden.
28 static _FILE_LINE: (&'static str, u32) = (file!(), line!());
29 $crate::panicking::panic_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
33 /// Ensure that a boolean expression is `true` at runtime.
35 /// This will invoke the [`panic!`] macro if the provided expression cannot be
36 /// evaluated to `true` at runtime.
40 /// Assertions are always checked in both debug and release builds, and cannot
41 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
42 /// release builds by default.
44 /// Unsafe code relies on `assert!` to enforce run-time invariants that, if
45 /// violated could lead to unsafety.
47 /// Other use-cases of `assert!` include [testing] and enforcing run-time
48 /// invariants in safe code (whose violation cannot result in unsafety).
52 /// This macro has a second form, where a custom panic message can
53 /// be provided with or without arguments for formatting.
55 /// [`panic!`]: macro.panic.html
56 /// [`debug_assert!`]: macro.debug_assert.html
57 /// [testing]: ../book/testing.html
62 /// // the panic message for these assertions is the stringified value of the
63 /// // expression given.
66 /// fn some_computation() -> bool { true } // a very simple function
68 /// assert!(some_computation());
70 /// // assert with a custom message
72 /// assert!(x, "x wasn't true!");
74 /// let a = 3; let b = 27;
75 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
78 #[stable(feature = "rust1", since = "1.0.0")]
82 panic!(concat!("assertion failed: ", stringify!($cond)))
85 ($cond:expr, $($arg:tt)+) => (
92 /// Asserts that two expressions are equal to each other (using [`PartialEq`]).
94 /// On panic, this macro will print the values of the expressions with their
95 /// debug representations.
97 /// Like [`assert!`], this macro has a second form, where a custom
98 /// panic message can be provided.
100 /// [`PartialEq`]: cmp/trait.PartialEq.html
101 /// [`assert!`]: macro.assert.html
108 /// assert_eq!(a, b);
110 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
113 #[stable(feature = "rust1", since = "1.0.0")]
114 macro_rules! assert_eq {
115 ($left:expr, $right:expr) => ({
116 match (&$left, &$right) {
117 (left_val, right_val) => {
118 if !(*left_val == *right_val) {
119 panic!("assertion failed: `(left == right)` \
120 (left: `{:?}`, right: `{:?}`)", left_val, right_val)
125 ($left:expr, $right:expr, $($arg:tt)+) => ({
126 match (&($left), &($right)) {
127 (left_val, right_val) => {
128 if !(*left_val == *right_val) {
129 panic!("assertion failed: `(left == right)` \
130 (left: `{:?}`, right: `{:?}`): {}", left_val, right_val,
131 format_args!($($arg)+))
138 /// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
140 /// On panic, this macro will print the values of the expressions with their
141 /// debug representations.
143 /// Like [`assert!`], this macro has a second form, where a custom
144 /// panic message can be provided.
146 /// [`PartialEq`]: cmp/trait.PartialEq.html
147 /// [`assert!`]: macro.assert.html
154 /// assert_ne!(a, b);
156 /// assert_ne!(a, b, "we are testing that the values are not equal");
159 #[stable(feature = "assert_ne", since = "1.13.0")]
160 macro_rules! assert_ne {
161 ($left:expr, $right:expr) => ({
162 match (&$left, &$right) {
163 (left_val, right_val) => {
164 if *left_val == *right_val {
165 panic!("assertion failed: `(left != right)` \
166 (left: `{:?}`, right: `{:?}`)", left_val, right_val)
171 ($left:expr, $right:expr, $($arg:tt)+) => ({
172 match (&($left), &($right)) {
173 (left_val, right_val) => {
174 if *left_val == *right_val {
175 panic!("assertion failed: `(left != right)` \
176 (left: `{:?}`, right: `{:?}`): {}", left_val, right_val,
177 format_args!($($arg)+))
184 /// Ensure that a boolean expression is `true` at runtime.
186 /// This will invoke the [`panic!`] macro if the provided expression cannot be
187 /// evaluated to `true` at runtime.
189 /// Like [`assert!`], this macro also has a second version, where a custom panic
190 /// message can be provided.
194 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
195 /// optimized builds by default. An optimized build will omit all
196 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
197 /// compiler. This makes `debug_assert!` useful for checks that are too
198 /// expensive to be present in a release build but may be helpful during
201 /// An unchecked assertion allows a program in an inconsistent state to keep
202 /// running, which might have unexpected consequences but does not introduce
203 /// unsafety as long as this only happens in safe code. The performance cost
204 /// of assertions, is however, not measurable in general. Replacing [`assert!`]
205 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
206 /// more importantly, only in safe code!
208 /// [`panic!`]: macro.panic.html
209 /// [`assert!`]: macro.assert.html
214 /// // the panic message for these assertions is the stringified value of the
215 /// // expression given.
216 /// debug_assert!(true);
218 /// fn some_expensive_computation() -> bool { true } // a very simple function
219 /// debug_assert!(some_expensive_computation());
221 /// // assert with a custom message
223 /// debug_assert!(x, "x wasn't true!");
225 /// let a = 3; let b = 27;
226 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
229 #[stable(feature = "rust1", since = "1.0.0")]
230 macro_rules! debug_assert {
231 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
234 /// Asserts that two expressions are equal to each other.
236 /// On panic, this macro will print the values of the expressions with their
237 /// debug representations.
239 /// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
240 /// optimized builds by default. An optimized build will omit all
241 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
242 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
243 /// expensive to be present in a release build but may be helpful during
251 /// debug_assert_eq!(a, b);
254 #[stable(feature = "rust1", since = "1.0.0")]
255 macro_rules! debug_assert_eq {
256 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
259 /// Asserts that two expressions are not equal to each other.
261 /// On panic, this macro will print the values of the expressions with their
262 /// debug representations.
264 /// Unlike `assert_ne!`, `debug_assert_ne!` statements are only enabled in non
265 /// optimized builds by default. An optimized build will omit all
266 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
267 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
268 /// expensive to be present in a release build but may be helpful during
276 /// debug_assert_ne!(a, b);
279 #[stable(feature = "assert_ne", since = "1.13.0")]
280 macro_rules! debug_assert_ne {
281 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_ne!($($arg)*); })
284 /// Helper macro for reducing boilerplate code for matching `Result` together
285 /// with converting downstream errors.
287 /// Prefer using `?` syntax to `try!`. `?` is built in to the language and is
288 /// more succinct than `try!`. It is the standard method for error propagation.
290 /// `try!` matches the given `Result`. In case of the `Ok` variant, the
291 /// expression has the value of the wrapped value.
293 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
294 /// performs conversion using `From`. This provides automatic conversion
295 /// between specialized errors and more general ones. The resulting
296 /// error is then immediately returned.
298 /// Because of the early return, `try!` can only be used in functions that
305 /// use std::fs::File;
306 /// use std::io::prelude::*;
312 /// impl From<io::Error> for MyError {
313 /// fn from(e: io::Error) -> MyError {
314 /// MyError::FileWriteError
318 /// fn write_to_file_using_try() -> Result<(), MyError> {
319 /// let mut file = try!(File::create("my_best_friends.txt"));
320 /// try!(file.write_all(b"This is a list of my best friends."));
321 /// println!("I wrote to the file");
324 /// // This is equivalent to:
325 /// fn write_to_file_using_match() -> Result<(), MyError> {
326 /// let mut file = try!(File::create("my_best_friends.txt"));
327 /// match file.write_all(b"This is a list of my best friends.") {
329 /// Err(e) => return Err(From::from(e)),
331 /// println!("I wrote to the file");
336 #[stable(feature = "rust1", since = "1.0.0")]
338 ($expr:expr) => (match $expr {
339 $crate::result::Result::Ok(val) => val,
340 $crate::result::Result::Err(err) => {
341 return $crate::result::Result::Err($crate::convert::From::from(err))
346 /// Write formatted data into a buffer
348 /// This macro accepts a format string, a list of arguments, and a 'writer'. Arguments will be
349 /// formatted according to the specified format string and the result will be passed to the writer.
350 /// The writer may be any value with a `write_fmt` method; generally this comes from an
351 /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro
352 /// returns whatever the 'write_fmt' method returns; commonly a [`std::fmt::Result`], or an
355 /// See [`std::fmt`] for more information on the format string syntax.
357 /// [`std::fmt`]: ../std/fmt/index.html
358 /// [`std::fmt::Write`]: ../std/fmt/trait.Write.html
359 /// [`std::io::Write`]: ../std/io/trait.Write.html
360 /// [`std::fmt::Result`]: ../std/fmt/type.Result.html
361 /// [`io::Result`]: ../std/io/type.Result.html
366 /// use std::io::Write;
368 /// let mut w = Vec::new();
369 /// write!(&mut w, "test").unwrap();
370 /// write!(&mut w, "formatted {}", "arguments").unwrap();
372 /// assert_eq!(w, b"testformatted arguments");
375 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
376 /// implementing either, as objects do not typically implement both. However, the module must
377 /// import the traits qualified so their names do not conflict:
380 /// use std::fmt::Write as FmtWrite;
381 /// use std::io::Write as IoWrite;
383 /// let mut s = String::new();
384 /// let mut v = Vec::new();
385 /// write!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
386 /// write!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
387 /// assert_eq!(v, b"s = \"abc 123\"");
390 #[stable(feature = "rust1", since = "1.0.0")]
392 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
395 /// Write formatted data into a buffer, with a newline appended.
397 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
398 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
400 /// For more information, see [`write!`]. For information on the format string syntax, see
403 /// [`write!`]: macro.write.html
404 /// [`std::fmt`]: ../std/fmt/index.html
410 /// use std::io::Write;
412 /// let mut w = Vec::new();
413 /// writeln!(&mut w).unwrap();
414 /// writeln!(&mut w, "test").unwrap();
415 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
417 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
420 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
421 /// implementing either, as objects do not typically implement both. However, the module must
422 /// import the traits qualified so their names do not conflict:
425 /// use std::fmt::Write as FmtWrite;
426 /// use std::io::Write as IoWrite;
428 /// let mut s = String::new();
429 /// let mut v = Vec::new();
430 /// writeln!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
431 /// writeln!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
432 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
435 #[stable(feature = "rust1", since = "1.0.0")]
436 macro_rules! writeln {
440 ($dst:expr, $fmt:expr) => (
441 write!($dst, concat!($fmt, "\n"))
443 ($dst:expr, $fmt:expr, $($arg:tt)*) => (
444 write!($dst, concat!($fmt, "\n"), $($arg)*)
448 /// A utility macro for indicating unreachable code.
450 /// This is useful any time that the compiler can't determine that some code is unreachable. For
453 /// * Match arms with guard conditions.
454 /// * Loops that dynamically terminate.
455 /// * Iterators that dynamically terminate.
459 /// This will always panic.
466 /// # #[allow(dead_code)]
467 /// fn foo(x: Option<i32>) {
469 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
470 /// Some(n) if n < 0 => println!("Some(Negative)"),
471 /// Some(_) => unreachable!(), // compile error if commented out
472 /// None => println!("None")
480 /// # #[allow(dead_code)]
481 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
483 /// if 3*i < i { panic!("u32 overflow"); }
484 /// if x < 3*i { return i-1; }
490 #[stable(feature = "rust1", since = "1.0.0")]
491 macro_rules! unreachable {
493 panic!("internal error: entered unreachable code")
496 unreachable!("{}", $msg)
498 ($fmt:expr, $($arg:tt)*) => ({
499 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
503 /// A standardized placeholder for marking unfinished code. It panics with the
504 /// message `"not yet implemented"` when executed.
506 /// This can be useful if you are prototyping and are just looking to have your
507 /// code typecheck, or if you're implementing a trait that requires multiple
508 /// methods, and you're only planning on using one of them.
512 /// Here's an example of some in-progress code. We have a trait `Foo`:
521 /// We want to implement `Foo` on one of our types, but we also want to work on
522 /// just `bar()` first. In order for our code to compile, we need to implement
523 /// `baz()`, so we can use `unimplemented!`:
532 /// impl Foo for MyStruct {
534 /// // implementation goes here
538 /// // let's not worry about implementing baz() for now
539 /// unimplemented!();
544 /// let s = MyStruct;
547 /// // we aren't even using baz() yet, so this is fine.
551 #[stable(feature = "rust1", since = "1.0.0")]
552 macro_rules! unimplemented {
553 () => (panic!("not yet implemented"))
556 /// Built-in macros to the compiler itself.
558 /// These macros do not have any corresponding definition with a `macro_rules!`
559 /// macro, but are documented here. Their implementations can be found hardcoded
560 /// into libsyntax itself.
562 /// For more information, see documentation for `std`'s macros.
564 /// The core macro for formatted string creation & output.
566 /// For more information, see the documentation for [`std::format_args!`].
568 /// [`std::format_args!`]: ../std/macro.format_args.html
569 #[stable(feature = "rust1", since = "1.0.0")]
572 macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({
573 /* compiler built-in */
576 /// Inspect an environment variable at compile time.
578 /// For more information, see the documentation for [`std::env!`].
580 /// [`std::env!`]: ../std/macro.env.html
581 #[stable(feature = "rust1", since = "1.0.0")]
584 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
586 /// Optionally inspect an environment variable at compile time.
588 /// For more information, see the documentation for [`std::option_env!`].
590 /// [`std::option_env!`]: ../std/macro.option_env.html
591 #[stable(feature = "rust1", since = "1.0.0")]
594 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
596 /// Concatenate identifiers into one identifier.
598 /// For more information, see the documentation for [`std::concat_idents!`].
600 /// [`std::concat_idents!`]: ../std/macro.concat_idents.html
601 #[unstable(feature = "concat_idents_macro", issue = "29599")]
604 macro_rules! concat_idents {
605 ($($e:ident),*) => ({ /* compiler built-in */ })
608 /// Concatenates literals into a static string slice.
610 /// For more information, see the documentation for [`std::concat!`].
612 /// [`std::concat!`]: ../std/macro.concat.html
613 #[stable(feature = "rust1", since = "1.0.0")]
616 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
618 /// A macro which expands to the line number on which it was invoked.
620 /// For more information, see the documentation for [`std::line!`].
622 /// [`std::line!`]: ../std/macro.line.html
623 #[stable(feature = "rust1", since = "1.0.0")]
626 macro_rules! line { () => ({ /* compiler built-in */ }) }
628 /// A macro which expands to the column number on which it was invoked.
630 /// For more information, see the documentation for [`std::column!`].
632 /// [`std::column!`]: ../std/macro.column.html
633 #[stable(feature = "rust1", since = "1.0.0")]
636 macro_rules! column { () => ({ /* compiler built-in */ }) }
638 /// A macro which expands to the file name from which it was invoked.
640 /// For more information, see the documentation for [`std::file!`].
642 /// [`std::file!`]: ../std/macro.file.html
643 #[stable(feature = "rust1", since = "1.0.0")]
646 macro_rules! file { () => ({ /* compiler built-in */ }) }
648 /// A macro which stringifies its argument.
650 /// For more information, see the documentation for [`std::stringify!`].
652 /// [`std::stringify!`]: ../std/macro.stringify.html
653 #[stable(feature = "rust1", since = "1.0.0")]
656 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
658 /// Includes a utf8-encoded file as a string.
660 /// For more information, see the documentation for [`std::include_str!`].
662 /// [`std::include_str!`]: ../std/macro.include_str.html
663 #[stable(feature = "rust1", since = "1.0.0")]
666 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
668 /// Includes a file as a reference to a byte array.
670 /// For more information, see the documentation for [`std::include_bytes!`].
672 /// [`std::include_bytes!`]: ../std/macro.include_bytes.html
673 #[stable(feature = "rust1", since = "1.0.0")]
676 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
678 /// Expands to a string that represents the current module path.
680 /// For more information, see the documentation for [`std::module_path!`].
682 /// [`std::module_path!`]: ../std/macro.module_path.html
683 #[stable(feature = "rust1", since = "1.0.0")]
686 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
688 /// Boolean evaluation of configuration flags.
690 /// For more information, see the documentation for [`std::cfg!`].
692 /// [`std::cfg!`]: ../std/macro.cfg.html
693 #[stable(feature = "rust1", since = "1.0.0")]
696 macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
698 /// Parse a file as an expression or an item according to the context.
700 /// For more information, see the documentation for [`std::include!`].
702 /// [`std::include!`]: ../std/macro.include.html
703 #[stable(feature = "rust1", since = "1.0.0")]
706 macro_rules! include { ($file:expr) => ({ /* compiler built-in */ }) }