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.
38 /// Assertions are always checked in both debug and release builds, and cannot
39 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
40 /// release builds by default.
42 /// Unsafe code relies on `assert!` to enforce run-time invariants that, if
43 /// violated could lead to unsafety.
45 /// Other use-cases of `assert!` include [testing] and enforcing run-time
46 /// invariants in safe code (whose violation cannot result in unsafety).
48 /// This macro has a second version, where a custom panic message can
49 /// be provided with or without arguments for formatting.
51 /// [`panic!`]: macro.panic.html
52 /// [`debug_assert!`]: macro.debug_assert.html
53 /// [testing]: ../book/testing.html
58 /// // the panic message for these assertions is the stringified value of the
59 /// // expression given.
62 /// fn some_computation() -> bool { true } // a very simple function
64 /// assert!(some_computation());
66 /// // assert with a custom message
68 /// assert!(x, "x wasn't true!");
70 /// let a = 3; let b = 27;
71 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
74 #[stable(feature = "rust1", since = "1.0.0")]
78 panic!(concat!("assertion failed: ", stringify!($cond)))
81 ($cond:expr, $($arg:tt)+) => (
88 /// Asserts that two expressions are equal to each other.
90 /// On panic, this macro will print the values of the expressions with their
91 /// debug representations.
93 /// Like [`assert!`], this macro has a second version, where a custom
94 /// panic message can be provided.
96 /// [`assert!`]: macro.assert.html
103 /// assert_eq!(a, b);
105 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
108 #[stable(feature = "rust1", since = "1.0.0")]
109 macro_rules! assert_eq {
110 ($left:expr, $right:expr) => ({
111 match (&$left, &$right) {
112 (left_val, right_val) => {
113 if !(*left_val == *right_val) {
114 panic!("assertion failed: `(left == right)` \
115 (left: `{:?}`, right: `{:?}`)", left_val, right_val)
120 ($left:expr, $right:expr, $($arg:tt)+) => ({
121 match (&($left), &($right)) {
122 (left_val, right_val) => {
123 if !(*left_val == *right_val) {
124 panic!("assertion failed: `(left == right)` \
125 (left: `{:?}`, right: `{:?}`): {}", left_val, right_val,
126 format_args!($($arg)+))
133 /// Asserts that two expressions are not equal to each other.
135 /// On panic, this macro will print the values of the expressions with their
136 /// debug representations.
138 /// Like `assert!()`, this macro has a second version, where a custom
139 /// panic message can be provided.
141 /// [`assert!`]: macro.assert.html
148 /// assert_ne!(a, b);
150 /// assert_ne!(a, b, "we are testing that the values are not equal");
153 #[stable(feature = "assert_ne", since = "1.12.0")]
154 macro_rules! assert_ne {
155 ($left:expr, $right:expr) => ({
156 match (&$left, &$right) {
157 (left_val, right_val) => {
158 if *left_val == *right_val {
159 panic!("assertion failed: `(left != right)` \
160 (left: `{:?}`, right: `{:?}`)", left_val, right_val)
165 ($left:expr, $right:expr, $($arg:tt)+) => ({
166 match (&($left), &($right)) {
167 (left_val, right_val) => {
168 if *left_val == *right_val {
169 panic!("assertion failed: `(left != right)` \
170 (left: `{:?}`, right: `{:?}`): {}", left_val, right_val,
171 format_args!($($arg)+))
178 /// Ensure that a boolean expression is `true` at runtime.
180 /// This will invoke the [`panic!`] macro if the provided expression cannot be
181 /// evaluated to `true` at runtime.
183 /// Like [`assert!`], this macro also has a second version, where a custom panic
184 /// message can be provided.
186 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
187 /// optimized builds by default. An optimized build will omit all
188 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
189 /// compiler. This makes `debug_assert!` useful for checks that are too
190 /// expensive to be present in a release build but may be helpful during
193 /// An unchecked assertion allows a program in an inconsistent state to keep
194 /// running, which might have unexpected consequences but does not introduce
195 /// unsafety as long as this only happens in safe code. The performance cost
196 /// of assertions, is however, not measurable in general. Replacing [`assert!`]
197 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
198 /// more importantly, only in safe code!
200 /// [`panic!`]: macro.panic.html
201 /// [`assert!`]: macro.assert.html
206 /// // the panic message for these assertions is the stringified value of the
207 /// // expression given.
208 /// debug_assert!(true);
210 /// fn some_expensive_computation() -> bool { true } // a very simple function
211 /// debug_assert!(some_expensive_computation());
213 /// // assert with a custom message
215 /// debug_assert!(x, "x wasn't true!");
217 /// let a = 3; let b = 27;
218 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
221 #[stable(feature = "rust1", since = "1.0.0")]
222 macro_rules! debug_assert {
223 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
226 /// Asserts that two expressions are equal to each other.
228 /// On panic, this macro will print the values of the expressions with their
229 /// debug representations.
231 /// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
232 /// optimized builds by default. An optimized build will omit all
233 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
234 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
235 /// expensive to be present in a release build but may be helpful during
243 /// debug_assert_eq!(a, b);
246 #[stable(feature = "rust1", since = "1.0.0")]
247 macro_rules! debug_assert_eq {
248 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
251 /// Asserts that two expressions are not equal to each other.
253 /// On panic, this macro will print the values of the expressions with their
254 /// debug representations.
256 /// Unlike `assert_ne!`, `debug_assert_ne!` statements are only enabled in non
257 /// optimized builds by default. An optimized build will omit all
258 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
259 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
260 /// expensive to be present in a release build but may be helpful during
268 /// debug_assert_ne!(a, b);
271 #[stable(feature = "assert_ne", since = "1.12.0")]
272 macro_rules! debug_assert_ne {
273 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_ne!($($arg)*); })
276 /// Helper macro for reducing boilerplate code for matching `Result` together
277 /// with converting downstream errors.
279 /// Prefer using `?` syntax to `try!`. `?` is built in to the language and is
280 /// more succinct than `try!`. It is the standard method for error propagation.
282 /// `try!` matches the given `Result`. In case of the `Ok` variant, the
283 /// expression has the value of the wrapped value.
285 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
286 /// performs conversion using `From`. This provides automatic conversion
287 /// between specialized errors and more general ones. The resulting
288 /// error is then immediately returned.
290 /// Because of the early return, `try!` can only be used in functions that
297 /// use std::fs::File;
298 /// use std::io::prelude::*;
304 /// impl From<io::Error> for MyError {
305 /// fn from(e: io::Error) -> MyError {
306 /// MyError::FileWriteError
310 /// fn write_to_file_using_try() -> Result<(), MyError> {
311 /// let mut file = try!(File::create("my_best_friends.txt"));
312 /// try!(file.write_all(b"This is a list of my best friends."));
313 /// println!("I wrote to the file");
316 /// // This is equivalent to:
317 /// fn write_to_file_using_match() -> Result<(), MyError> {
318 /// let mut file = try!(File::create("my_best_friends.txt"));
319 /// match file.write_all(b"This is a list of my best friends.") {
321 /// Err(e) => return Err(From::from(e)),
323 /// println!("I wrote to the file");
328 #[stable(feature = "rust1", since = "1.0.0")]
330 ($expr:expr) => (match $expr {
331 $crate::result::Result::Ok(val) => val,
332 $crate::result::Result::Err(err) => {
333 return $crate::result::Result::Err($crate::convert::From::from(err))
338 /// Write formatted data into a buffer
340 /// This macro accepts a 'writer' (any value with a `write_fmt` method), a format string, and a
341 /// list of arguments to format.
343 /// The `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write]
344 /// or [`std::io::Write`][io_write] traits. The term 'writer' refers to an implementation of one of
345 /// these two traits.
347 /// Passed arguments will be formatted according to the specified format string and the resulting
348 /// string will be passed to the writer.
350 /// See [`std::fmt`][fmt] for more information on format syntax.
352 /// `write!` returns whatever the 'write_fmt' method returns.
354 /// Common return values include: [`fmt::Result`][fmt_result], [`io::Result`][io_result]
356 /// [fmt]: ../std/fmt/index.html
357 /// [fmt_write]: ../std/fmt/trait.Write.html
358 /// [io_write]: ../std/io/trait.Write.html
359 /// [fmt_result]: ../std/fmt/type.Result.html
360 /// [io_result]: ../std/io/type.Result.html
365 /// use std::io::Write;
367 /// let mut w = Vec::new();
368 /// write!(&mut w, "test").unwrap();
369 /// write!(&mut w, "formatted {}", "arguments").unwrap();
371 /// assert_eq!(w, b"testformatted arguments");
374 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
375 /// implementing either, as objects do not typically implement both. However, the module must
376 /// import the traits qualified so their names do not conflict:
379 /// use std::fmt::Write as FmtWrite;
380 /// use std::io::Write as IoWrite;
382 /// let mut s = String::new();
383 /// let mut v = Vec::new();
384 /// write!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
385 /// write!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
386 /// assert_eq!(v, b"s = \"abc 123\"");
389 #[stable(feature = "core", since = "1.6.0")]
391 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
394 /// Write formatted data into a buffer, with a newline appended.
396 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
397 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
399 /// This macro accepts a 'writer' (any value with a `write_fmt` method), a format string, and a
400 /// list of arguments to format.
402 /// The `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write]
403 /// or [`std::io::Write`][io_write] traits. The term 'writer' refers to an implementation of one of
404 /// these two traits.
406 /// Passed arguments will be formatted according to the specified format string and the resulting
407 /// string will be passed to the writer, along with the appended newline.
409 /// See [`std::fmt`][fmt] for more information on format syntax.
411 /// `write!` returns whatever the 'write_fmt' method returns.
413 /// Common return values include: [`fmt::Result`][fmt_result], [`io::Result`][io_result]
415 /// [fmt]: ../std/fmt/index.html
416 /// [fmt_write]: ../std/fmt/trait.Write.html
417 /// [io_write]: ../std/io/trait.Write.html
418 /// [fmt_result]: ../std/fmt/type.Result.html
419 /// [io_result]: ../std/io/type.Result.html
424 /// use std::io::Write;
426 /// let mut w = Vec::new();
427 /// writeln!(&mut w).unwrap();
428 /// writeln!(&mut w, "test").unwrap();
429 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
431 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
434 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
435 /// implementing either, as objects do not typically implement both. However, the module must
436 /// import the traits qualified so their names do not conflict:
439 /// use std::fmt::Write as FmtWrite;
440 /// use std::io::Write as IoWrite;
442 /// let mut s = String::new();
443 /// let mut v = Vec::new();
444 /// writeln!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
445 /// writeln!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
446 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
449 #[stable(feature = "rust1", since = "1.0.0")]
450 macro_rules! writeln {
454 ($dst:expr, $fmt:expr) => (
455 write!($dst, concat!($fmt, "\n"))
457 ($dst:expr, $fmt:expr, $($arg:tt)*) => (
458 write!($dst, concat!($fmt, "\n"), $($arg)*)
462 /// A utility macro for indicating unreachable code.
464 /// This is useful any time that the compiler can't determine that some code is unreachable. For
467 /// * Match arms with guard conditions.
468 /// * Loops that dynamically terminate.
469 /// * Iterators that dynamically terminate.
473 /// This will always panic.
480 /// # #[allow(dead_code)]
481 /// fn foo(x: Option<i32>) {
483 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
484 /// Some(n) if n < 0 => println!("Some(Negative)"),
485 /// Some(_) => unreachable!(), // compile error if commented out
486 /// None => println!("None")
494 /// # #[allow(dead_code)]
495 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
497 /// if 3*i < i { panic!("u32 overflow"); }
498 /// if x < 3*i { return i-1; }
504 #[stable(feature = "core", since = "1.6.0")]
505 macro_rules! unreachable {
507 panic!("internal error: entered unreachable code")
510 unreachable!("{}", $msg)
512 ($fmt:expr, $($arg:tt)*) => ({
513 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
517 /// A standardized placeholder for marking unfinished code. It panics with the
518 /// message `"not yet implemented"` when executed.
520 /// This can be useful if you are prototyping and are just looking to have your
521 /// code typecheck, or if you're implementing a trait that requires multiple
522 /// methods, and you're only planning on using one of them.
526 /// Here's an example of some in-progress code. We have a trait `Foo`:
535 /// We want to implement `Foo` on one of our types, but we also want to work on
536 /// just `bar()` first. In order for our code to compile, we need to implement
537 /// `baz()`, so we can use `unimplemented!`:
546 /// impl Foo for MyStruct {
548 /// // implementation goes here
552 /// // let's not worry about implementing baz() for now
553 /// unimplemented!();
558 /// let s = MyStruct;
561 /// // we aren't even using baz() yet, so this is fine.
565 #[stable(feature = "core", since = "1.6.0")]
566 macro_rules! unimplemented {
567 () => (panic!("not yet implemented"))
570 /// Built-in macros to the compiler itself.
572 /// These macros do not have any corresponding definition with a `macro_rules!`
573 /// macro, but are documented here. Their implementations can be found hardcoded
574 /// into libsyntax itself.
576 /// For more information, see documentation for `std`'s macros.
578 /// The core macro for formatted string creation & output.
580 /// For more information, see the documentation for [`std::format_args!`].
582 /// [`std::format_args!`]: ../std/macro.format_args.html
583 #[stable(feature = "rust1", since = "1.0.0")]
586 macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({
587 /* compiler built-in */
590 /// Inspect an environment variable at compile time.
592 /// For more information, see the documentation for [`std::env!`].
594 /// [`std::env!`]: ../std/macro.env.html
595 #[stable(feature = "rust1", since = "1.0.0")]
598 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
600 /// Optionally inspect an environment variable at compile time.
602 /// For more information, see the documentation for [`std::option_env!`].
604 /// [`std::option_env!`]: ../std/macro.option_env.html
605 #[stable(feature = "rust1", since = "1.0.0")]
608 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
610 /// Concatenate identifiers into one identifier.
612 /// For more information, see the documentation for [`std::concat_idents!`].
614 /// [`std::concat_idents!`]: ../std/macro.concat_idents.html
615 #[unstable(feature = "concat_idents_macro", issue = "29599")]
618 macro_rules! concat_idents {
619 ($($e:ident),*) => ({ /* compiler built-in */ })
622 /// Concatenates literals into a static string slice.
624 /// For more information, see the documentation for [`std::concat!`].
626 /// [`std::concat!`]: ../std/macro.concat.html
627 #[stable(feature = "rust1", since = "1.0.0")]
630 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
632 /// A macro which expands to the line number on which it was invoked.
634 /// For more information, see the documentation for [`std::line!`].
636 /// [`std::line!`]: ../std/macro.line.html
637 #[stable(feature = "rust1", since = "1.0.0")]
640 macro_rules! line { () => ({ /* compiler built-in */ }) }
642 /// A macro which expands to the column number on which it was invoked.
644 /// For more information, see the documentation for [`std::column!`].
646 /// [`std::column!`]: ../std/macro.column.html
647 #[stable(feature = "rust1", since = "1.0.0")]
650 macro_rules! column { () => ({ /* compiler built-in */ }) }
652 /// A macro which expands to the file name from which it was invoked.
654 /// For more information, see the documentation for [`std::file!`].
656 /// [`std::file!`]: ../std/macro.file.html
657 #[stable(feature = "rust1", since = "1.0.0")]
660 macro_rules! file { () => ({ /* compiler built-in */ }) }
662 /// A macro which stringifies its argument.
664 /// For more information, see the documentation for [`std::stringify!`].
666 /// [`std::stringify!`]: ../std/macro.stringify.html
667 #[stable(feature = "rust1", since = "1.0.0")]
670 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
672 /// Includes a utf8-encoded file as a string.
674 /// For more information, see the documentation for [`std::include_str!`].
676 /// [`std::include_str!`]: ../std/macro.include_str.html
677 #[stable(feature = "rust1", since = "1.0.0")]
680 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
682 /// Includes a file as a reference to a byte array.
684 /// For more information, see the documentation for [`std::include_bytes!`].
686 /// [`std::include_bytes!`]: ../std/macro.include_bytes.html
687 #[stable(feature = "rust1", since = "1.0.0")]
690 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
692 /// Expands to a string that represents the current module path.
694 /// For more information, see the documentation for [`std::module_path!`].
696 /// [`std::module_path!`]: ../std/macro.module_path.html
697 #[stable(feature = "rust1", since = "1.0.0")]
700 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
702 /// Boolean evaluation of configuration flags.
704 /// For more information, see the documentation for [`std::cfg!`].
706 /// [`std::cfg!`]: ../std/macro.cfg.html
707 #[stable(feature = "rust1", since = "1.0.0")]
710 macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
712 /// Parse a file as an expression or an item according to the context.
714 /// For more information, see the documentation for [`std::include!`].
716 /// [`std::include!`]: ../std/macro.include.html
717 #[stable(feature = "rust1", since = "1.0.0")]
720 macro_rules! include { ($file:expr) => ({ /* compiler built-in */ }) }