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/first-edition/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!(r#"assertion failed: `(left == right)`
121 right: `{:?}`"#, left_val, right_val)
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, $($arg:tt)+) => ({
175 match (&($left), &($right)) {
176 (left_val, right_val) => {
177 if *left_val == *right_val {
178 panic!(r#"assertion failed: `(left != right)`
180 right: `{:?}`: {}"#, left_val, right_val,
181 format_args!($($arg)+))
188 /// Ensure that a boolean expression is `true` at runtime.
190 /// This will invoke the [`panic!`] macro if the provided expression cannot be
191 /// evaluated to `true` at runtime.
193 /// Like [`assert!`], this macro also has a second version, where a custom panic
194 /// message can be provided.
198 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
199 /// optimized builds by default. An optimized build will omit all
200 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
201 /// compiler. This makes `debug_assert!` useful for checks that are too
202 /// expensive to be present in a release build but may be helpful during
205 /// An unchecked assertion allows a program in an inconsistent state to keep
206 /// running, which might have unexpected consequences but does not introduce
207 /// unsafety as long as this only happens in safe code. The performance cost
208 /// of assertions, is however, not measurable in general. Replacing [`assert!`]
209 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
210 /// more importantly, only in safe code!
212 /// [`panic!`]: macro.panic.html
213 /// [`assert!`]: macro.assert.html
218 /// // the panic message for these assertions is the stringified value of the
219 /// // expression given.
220 /// debug_assert!(true);
222 /// fn some_expensive_computation() -> bool { true } // a very simple function
223 /// debug_assert!(some_expensive_computation());
225 /// // assert with a custom message
227 /// debug_assert!(x, "x wasn't true!");
229 /// let a = 3; let b = 27;
230 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
233 #[stable(feature = "rust1", since = "1.0.0")]
234 macro_rules! debug_assert {
235 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
238 /// Asserts that two expressions are equal to each other.
240 /// On panic, this macro will print the values of the expressions with their
241 /// debug representations.
243 /// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
244 /// optimized builds by default. An optimized build will omit all
245 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
246 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
247 /// expensive to be present in a release build but may be helpful during
255 /// debug_assert_eq!(a, b);
258 #[stable(feature = "rust1", since = "1.0.0")]
259 macro_rules! debug_assert_eq {
260 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
263 /// Asserts that two expressions are not equal to each other.
265 /// On panic, this macro will print the values of the expressions with their
266 /// debug representations.
268 /// Unlike `assert_ne!`, `debug_assert_ne!` statements are only enabled in non
269 /// optimized builds by default. An optimized build will omit all
270 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
271 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
272 /// expensive to be present in a release build but may be helpful during
280 /// debug_assert_ne!(a, b);
283 #[stable(feature = "assert_ne", since = "1.13.0")]
284 macro_rules! debug_assert_ne {
285 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_ne!($($arg)*); })
288 /// Helper macro for reducing boilerplate code for matching `Result` together
289 /// with converting downstream errors.
291 /// Prefer using `?` syntax to `try!`. `?` is built in to the language and is
292 /// more succinct than `try!`. It is the standard method for error propagation.
294 /// `try!` matches the given `Result`. In case of the `Ok` variant, the
295 /// expression has the value of the wrapped value.
297 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
298 /// performs conversion using `From`. This provides automatic conversion
299 /// between specialized errors and more general ones. The resulting
300 /// error is then immediately returned.
302 /// Because of the early return, `try!` can only be used in functions that
309 /// use std::fs::File;
310 /// use std::io::prelude::*;
316 /// impl From<io::Error> for MyError {
317 /// fn from(e: io::Error) -> MyError {
318 /// MyError::FileWriteError
322 /// fn write_to_file_using_try() -> Result<(), MyError> {
323 /// let mut file = try!(File::create("my_best_friends.txt"));
324 /// try!(file.write_all(b"This is a list of my best friends."));
325 /// println!("I wrote to the file");
328 /// // This is equivalent to:
329 /// fn write_to_file_using_match() -> Result<(), MyError> {
330 /// let mut file = try!(File::create("my_best_friends.txt"));
331 /// match file.write_all(b"This is a list of my best friends.") {
333 /// Err(e) => return Err(From::from(e)),
335 /// println!("I wrote to the file");
340 #[stable(feature = "rust1", since = "1.0.0")]
342 ($expr:expr) => (match $expr {
343 $crate::result::Result::Ok(val) => val,
344 $crate::result::Result::Err(err) => {
345 return $crate::result::Result::Err($crate::convert::From::from(err))
350 /// Write formatted data into a buffer
352 /// This macro accepts a format string, a list of arguments, and a 'writer'. Arguments will be
353 /// formatted according to the specified format string and the result will be passed to the writer.
354 /// The writer may be any value with a `write_fmt` method; generally this comes from an
355 /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro
356 /// returns whatever the 'write_fmt' method returns; commonly a [`std::fmt::Result`], or an
359 /// See [`std::fmt`] for more information on the format string syntax.
361 /// [`std::fmt`]: ../std/fmt/index.html
362 /// [`std::fmt::Write`]: ../std/fmt/trait.Write.html
363 /// [`std::io::Write`]: ../std/io/trait.Write.html
364 /// [`std::fmt::Result`]: ../std/fmt/type.Result.html
365 /// [`io::Result`]: ../std/io/type.Result.html
370 /// use std::io::Write;
372 /// let mut w = Vec::new();
373 /// write!(&mut w, "test").unwrap();
374 /// write!(&mut w, "formatted {}", "arguments").unwrap();
376 /// assert_eq!(w, b"testformatted arguments");
379 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
380 /// implementing either, as objects do not typically implement both. However, the module must
381 /// import the traits qualified so their names do not conflict:
384 /// use std::fmt::Write as FmtWrite;
385 /// use std::io::Write as IoWrite;
387 /// let mut s = String::new();
388 /// let mut v = Vec::new();
389 /// write!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
390 /// write!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
391 /// assert_eq!(v, b"s = \"abc 123\"");
394 #[stable(feature = "rust1", since = "1.0.0")]
396 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
399 /// Write formatted data into a buffer, with a newline appended.
401 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
402 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
404 /// For more information, see [`write!`]. For information on the format string syntax, see
407 /// [`write!`]: macro.write.html
408 /// [`std::fmt`]: ../std/fmt/index.html
414 /// use std::io::Write;
416 /// let mut w = Vec::new();
417 /// writeln!(&mut w).unwrap();
418 /// writeln!(&mut w, "test").unwrap();
419 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
421 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
424 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
425 /// implementing either, as objects do not typically implement both. However, the module must
426 /// import the traits qualified so their names do not conflict:
429 /// use std::fmt::Write as FmtWrite;
430 /// use std::io::Write as IoWrite;
432 /// let mut s = String::new();
433 /// let mut v = Vec::new();
434 /// writeln!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
435 /// writeln!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
436 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
439 #[stable(feature = "rust1", since = "1.0.0")]
440 macro_rules! writeln {
444 ($dst:expr, $fmt:expr) => (
445 write!($dst, concat!($fmt, "\n"))
447 ($dst:expr, $fmt:expr, $($arg:tt)*) => (
448 write!($dst, concat!($fmt, "\n"), $($arg)*)
452 /// A utility macro for indicating unreachable code.
454 /// This is useful any time that the compiler can't determine that some code is unreachable. For
457 /// * Match arms with guard conditions.
458 /// * Loops that dynamically terminate.
459 /// * Iterators that dynamically terminate.
463 /// This will always panic.
470 /// # #[allow(dead_code)]
471 /// fn foo(x: Option<i32>) {
473 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
474 /// Some(n) if n < 0 => println!("Some(Negative)"),
475 /// Some(_) => unreachable!(), // compile error if commented out
476 /// None => println!("None")
484 /// # #[allow(dead_code)]
485 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
487 /// if 3*i < i { panic!("u32 overflow"); }
488 /// if x < 3*i { return i-1; }
494 #[stable(feature = "rust1", since = "1.0.0")]
495 macro_rules! unreachable {
497 panic!("internal error: entered unreachable code")
500 unreachable!("{}", $msg)
502 ($fmt:expr, $($arg:tt)*) => ({
503 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
507 /// A standardized placeholder for marking unfinished code. It panics with the
508 /// message `"not yet implemented"` when executed.
510 /// This can be useful if you are prototyping and are just looking to have your
511 /// code typecheck, or if you're implementing a trait that requires multiple
512 /// methods, and you're only planning on using one of them.
516 /// Here's an example of some in-progress code. We have a trait `Foo`:
525 /// We want to implement `Foo` on one of our types, but we also want to work on
526 /// just `bar()` first. In order for our code to compile, we need to implement
527 /// `baz()`, so we can use `unimplemented!`:
536 /// impl Foo for MyStruct {
538 /// // implementation goes here
542 /// // let's not worry about implementing baz() for now
543 /// unimplemented!();
548 /// let s = MyStruct;
551 /// // we aren't even using baz() yet, so this is fine.
555 #[stable(feature = "rust1", since = "1.0.0")]
556 macro_rules! unimplemented {
557 () => (panic!("not yet implemented"));
558 ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)*)));
561 /// Built-in macros to the compiler itself.
563 /// These macros do not have any corresponding definition with a `macro_rules!`
564 /// macro, but are documented here. Their implementations can be found hardcoded
565 /// into libsyntax itself.
567 /// For more information, see documentation for `std`'s macros.
570 /// Unconditionally causes compilation to fail with the given error message when encountered.
572 /// For more information, see the [RFC].
574 /// [RFC]: https://github.com/rust-lang/rfcs/blob/master/text/1695-add-error-macro.md
575 #[unstable(feature = "compile_error_macro", issue = "40872")]
578 macro_rules! compile_error { ($msg:expr) => ({ /* compiler built-in */ }) }
580 /// The core macro for formatted string creation & output.
582 /// For more information, see the documentation for [`std::format_args!`].
584 /// [`std::format_args!`]: ../std/macro.format_args.html
585 #[stable(feature = "rust1", since = "1.0.0")]
588 macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({
589 /* compiler built-in */
592 /// Inspect an environment variable at compile time.
594 /// For more information, see the documentation for [`std::env!`].
596 /// [`std::env!`]: ../std/macro.env.html
597 #[stable(feature = "rust1", since = "1.0.0")]
600 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
602 /// Optionally inspect an environment variable at compile time.
604 /// For more information, see the documentation for [`std::option_env!`].
606 /// [`std::option_env!`]: ../std/macro.option_env.html
607 #[stable(feature = "rust1", since = "1.0.0")]
610 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
612 /// Concatenate identifiers into one identifier.
614 /// For more information, see the documentation for [`std::concat_idents!`].
616 /// [`std::concat_idents!`]: ../std/macro.concat_idents.html
617 #[unstable(feature = "concat_idents_macro", issue = "29599")]
620 macro_rules! concat_idents {
621 ($($e:ident),*) => ({ /* compiler built-in */ })
624 /// Concatenates literals into a static string slice.
626 /// For more information, see the documentation for [`std::concat!`].
628 /// [`std::concat!`]: ../std/macro.concat.html
629 #[stable(feature = "rust1", since = "1.0.0")]
632 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
634 /// A macro which expands to the line number on which it was invoked.
636 /// For more information, see the documentation for [`std::line!`].
638 /// [`std::line!`]: ../std/macro.line.html
639 #[stable(feature = "rust1", since = "1.0.0")]
642 macro_rules! line { () => ({ /* compiler built-in */ }) }
644 /// A macro which expands to the column number on which it was invoked.
646 /// For more information, see the documentation for [`std::column!`].
648 /// [`std::column!`]: ../std/macro.column.html
649 #[stable(feature = "rust1", since = "1.0.0")]
652 macro_rules! column { () => ({ /* compiler built-in */ }) }
654 /// A macro which expands to the file name from which it was invoked.
656 /// For more information, see the documentation for [`std::file!`].
658 /// [`std::file!`]: ../std/macro.file.html
659 #[stable(feature = "rust1", since = "1.0.0")]
662 macro_rules! file { () => ({ /* compiler built-in */ }) }
664 /// A macro which stringifies its argument.
666 /// For more information, see the documentation for [`std::stringify!`].
668 /// [`std::stringify!`]: ../std/macro.stringify.html
669 #[stable(feature = "rust1", since = "1.0.0")]
672 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
674 /// Includes a utf8-encoded file as a string.
676 /// For more information, see the documentation for [`std::include_str!`].
678 /// [`std::include_str!`]: ../std/macro.include_str.html
679 #[stable(feature = "rust1", since = "1.0.0")]
682 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
684 /// Includes a file as a reference to a byte array.
686 /// For more information, see the documentation for [`std::include_bytes!`].
688 /// [`std::include_bytes!`]: ../std/macro.include_bytes.html
689 #[stable(feature = "rust1", since = "1.0.0")]
692 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
694 /// Expands to a string that represents the current module path.
696 /// For more information, see the documentation for [`std::module_path!`].
698 /// [`std::module_path!`]: ../std/macro.module_path.html
699 #[stable(feature = "rust1", since = "1.0.0")]
702 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
704 /// Boolean evaluation of configuration flags.
706 /// For more information, see the documentation for [`std::cfg!`].
708 /// [`std::cfg!`]: ../std/macro.cfg.html
709 #[stable(feature = "rust1", since = "1.0.0")]
712 macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
714 /// Parse a file as an expression or an item according to the context.
716 /// For more information, see the documentation for [`std::include!`].
718 /// [`std::include!`]: ../std/macro.include.html
719 #[stable(feature = "rust1", since = "1.0.0")]
722 macro_rules! include { ($file:expr) => ({ /* compiler built-in */ }) }