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 format string, a list of arguments, and a 'writer'. Arguments will be
341 /// formatted according to the specified format string and the result will be passed to the writer.
342 /// The writer may be any value with a `write_fmt` method; generally this comes from an
343 /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro
344 /// returns whatever the 'write_fmt' method returns; commonly a [`std::fmt::Result`], or an
347 /// See [`std::fmt`] for more information on the format string syntax.
349 /// [`std::fmt`]: ../std/fmt/index.html
350 /// [`std::fmt::Write`]: ../std/fmt/trait.Write.html
351 /// [`std::io::Write`]: ../std/io/trait.Write.html
352 /// [`std::fmt::Result`]: ../std/fmt/type.Result.html
353 /// [`io::Result`]: ../std/io/type.Result.html
358 /// use std::io::Write;
360 /// let mut w = Vec::new();
361 /// write!(&mut w, "test").unwrap();
362 /// write!(&mut w, "formatted {}", "arguments").unwrap();
364 /// assert_eq!(w, b"testformatted arguments");
367 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
368 /// implementing either, as objects do not typically implement both. However, the module must
369 /// import the traits qualified so their names do not conflict:
372 /// use std::fmt::Write as FmtWrite;
373 /// use std::io::Write as IoWrite;
375 /// let mut s = String::new();
376 /// let mut v = Vec::new();
377 /// write!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
378 /// write!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
379 /// assert_eq!(v, b"s = \"abc 123\"");
382 #[stable(feature = "core", since = "1.6.0")]
384 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
387 /// Write formatted data into a buffer, with a newline appended.
389 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
390 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
392 /// For more information, see [`write!`]. For information on the format string syntax, see
395 /// [`write!`]: macro.write.html
396 /// [`std::fmt`]: ../std/fmt/index.html
402 /// use std::io::Write;
404 /// let mut w = Vec::new();
405 /// writeln!(&mut w).unwrap();
406 /// writeln!(&mut w, "test").unwrap();
407 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
409 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
412 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
413 /// implementing either, as objects do not typically implement both. However, the module must
414 /// import the traits qualified so their names do not conflict:
417 /// use std::fmt::Write as FmtWrite;
418 /// use std::io::Write as IoWrite;
420 /// let mut s = String::new();
421 /// let mut v = Vec::new();
422 /// writeln!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
423 /// writeln!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
424 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
427 #[stable(feature = "rust1", since = "1.0.0")]
428 macro_rules! writeln {
432 ($dst:expr, $fmt:expr) => (
433 write!($dst, concat!($fmt, "\n"))
435 ($dst:expr, $fmt:expr, $($arg:tt)*) => (
436 write!($dst, concat!($fmt, "\n"), $($arg)*)
440 /// A utility macro for indicating unreachable code.
442 /// This is useful any time that the compiler can't determine that some code is unreachable. For
445 /// * Match arms with guard conditions.
446 /// * Loops that dynamically terminate.
447 /// * Iterators that dynamically terminate.
451 /// This will always panic.
458 /// # #[allow(dead_code)]
459 /// fn foo(x: Option<i32>) {
461 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
462 /// Some(n) if n < 0 => println!("Some(Negative)"),
463 /// Some(_) => unreachable!(), // compile error if commented out
464 /// None => println!("None")
472 /// # #[allow(dead_code)]
473 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
475 /// if 3*i < i { panic!("u32 overflow"); }
476 /// if x < 3*i { return i-1; }
482 #[stable(feature = "core", since = "1.6.0")]
483 macro_rules! unreachable {
485 panic!("internal error: entered unreachable code")
488 unreachable!("{}", $msg)
490 ($fmt:expr, $($arg:tt)*) => ({
491 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
495 /// A standardized placeholder for marking unfinished code. It panics with the
496 /// message `"not yet implemented"` when executed.
498 /// This can be useful if you are prototyping and are just looking to have your
499 /// code typecheck, or if you're implementing a trait that requires multiple
500 /// methods, and you're only planning on using one of them.
504 /// Here's an example of some in-progress code. We have a trait `Foo`:
513 /// We want to implement `Foo` on one of our types, but we also want to work on
514 /// just `bar()` first. In order for our code to compile, we need to implement
515 /// `baz()`, so we can use `unimplemented!`:
524 /// impl Foo for MyStruct {
526 /// // implementation goes here
530 /// // let's not worry about implementing baz() for now
531 /// unimplemented!();
536 /// let s = MyStruct;
539 /// // we aren't even using baz() yet, so this is fine.
543 #[stable(feature = "core", since = "1.6.0")]
544 macro_rules! unimplemented {
545 () => (panic!("not yet implemented"))
548 /// Built-in macros to the compiler itself.
550 /// These macros do not have any corresponding definition with a `macro_rules!`
551 /// macro, but are documented here. Their implementations can be found hardcoded
552 /// into libsyntax itself.
554 /// For more information, see documentation for `std`'s macros.
556 /// The core macro for formatted string creation & output.
558 /// For more information, see the documentation for [`std::format_args!`].
560 /// [`std::format_args!`]: ../std/macro.format_args.html
561 #[stable(feature = "rust1", since = "1.0.0")]
564 macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({
565 /* compiler built-in */
568 /// Inspect an environment variable at compile time.
570 /// For more information, see the documentation for [`std::env!`].
572 /// [`std::env!`]: ../std/macro.env.html
573 #[stable(feature = "rust1", since = "1.0.0")]
576 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
578 /// Optionally inspect an environment variable at compile time.
580 /// For more information, see the documentation for [`std::option_env!`].
582 /// [`std::option_env!`]: ../std/macro.option_env.html
583 #[stable(feature = "rust1", since = "1.0.0")]
586 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
588 /// Concatenate identifiers into one identifier.
590 /// For more information, see the documentation for [`std::concat_idents!`].
592 /// [`std::concat_idents!`]: ../std/macro.concat_idents.html
593 #[unstable(feature = "concat_idents_macro", issue = "29599")]
596 macro_rules! concat_idents {
597 ($($e:ident),*) => ({ /* compiler built-in */ })
600 /// Concatenates literals into a static string slice.
602 /// For more information, see the documentation for [`std::concat!`].
604 /// [`std::concat!`]: ../std/macro.concat.html
605 #[stable(feature = "rust1", since = "1.0.0")]
608 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
610 /// A macro which expands to the line number on which it was invoked.
612 /// For more information, see the documentation for [`std::line!`].
614 /// [`std::line!`]: ../std/macro.line.html
615 #[stable(feature = "rust1", since = "1.0.0")]
618 macro_rules! line { () => ({ /* compiler built-in */ }) }
620 /// A macro which expands to the column number on which it was invoked.
622 /// For more information, see the documentation for [`std::column!`].
624 /// [`std::column!`]: ../std/macro.column.html
625 #[stable(feature = "rust1", since = "1.0.0")]
628 macro_rules! column { () => ({ /* compiler built-in */ }) }
630 /// A macro which expands to the file name from which it was invoked.
632 /// For more information, see the documentation for [`std::file!`].
634 /// [`std::file!`]: ../std/macro.file.html
635 #[stable(feature = "rust1", since = "1.0.0")]
638 macro_rules! file { () => ({ /* compiler built-in */ }) }
640 /// A macro which stringifies its argument.
642 /// For more information, see the documentation for [`std::stringify!`].
644 /// [`std::stringify!`]: ../std/macro.stringify.html
645 #[stable(feature = "rust1", since = "1.0.0")]
648 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
650 /// Includes a utf8-encoded file as a string.
652 /// For more information, see the documentation for [`std::include_str!`].
654 /// [`std::include_str!`]: ../std/macro.include_str.html
655 #[stable(feature = "rust1", since = "1.0.0")]
658 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
660 /// Includes a file as a reference to a byte array.
662 /// For more information, see the documentation for [`std::include_bytes!`].
664 /// [`std::include_bytes!`]: ../std/macro.include_bytes.html
665 #[stable(feature = "rust1", since = "1.0.0")]
668 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
670 /// Expands to a string that represents the current module path.
672 /// For more information, see the documentation for [`std::module_path!`].
674 /// [`std::module_path!`]: ../std/macro.module_path.html
675 #[stable(feature = "rust1", since = "1.0.0")]
678 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
680 /// Boolean evaluation of configuration flags.
682 /// For more information, see the documentation for [`std::cfg!`].
684 /// [`std::cfg!`]: ../std/macro.cfg.html
685 #[stable(feature = "rust1", since = "1.0.0")]
688 macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
690 /// Parse a file as an expression or an item according to the context.
692 /// For more information, see the documentation for [`std::include!`].
694 /// [`std::include!`]: ../std/macro.include.html
695 #[stable(feature = "rust1", since = "1.0.0")]
698 macro_rules! include { ($file:expr) => ({ /* compiler built-in */ }) }