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!()))
25 ($fmt:expr, $($arg:tt)+) => ({
26 $crate::panicking::panic_fmt(format_args!($fmt, $($arg)*),
27 &(file!(), line!(), __rust_unstable_column!()))
31 /// Asserts that two expressions are equal to each other (using [`PartialEq`]).
33 /// On panic, this macro will print the values of the expressions with their
34 /// debug representations.
36 /// Like [`assert!`], this macro has a second form, where a custom
37 /// panic message can be provided.
39 /// [`PartialEq`]: cmp/trait.PartialEq.html
40 /// [`assert!`]: macro.assert.html
49 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
52 #[stable(feature = "rust1", since = "1.0.0")]
53 macro_rules! assert_eq {
54 ($left:expr, $right:expr) => ({
55 match (&$left, &$right) {
56 (left_val, right_val) => {
57 if !(*left_val == *right_val) {
58 panic!(r#"assertion failed: `(left == right)`
60 right: `{:?}`"#, left_val, right_val)
65 ($left:expr, $right:expr,) => ({
66 assert_eq!($left, $right)
68 ($left:expr, $right:expr, $($arg:tt)+) => ({
69 match (&($left), &($right)) {
70 (left_val, right_val) => {
71 if !(*left_val == *right_val) {
72 panic!(r#"assertion failed: `(left == right)`
74 right: `{:?}`: {}"#, left_val, right_val,
75 format_args!($($arg)+))
82 /// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
84 /// On panic, this macro will print the values of the expressions with their
85 /// debug representations.
87 /// Like [`assert!`], this macro has a second form, where a custom
88 /// panic message can be provided.
90 /// [`PartialEq`]: cmp/trait.PartialEq.html
91 /// [`assert!`]: macro.assert.html
100 /// assert_ne!(a, b, "we are testing that the values are not equal");
103 #[stable(feature = "assert_ne", since = "1.13.0")]
104 macro_rules! assert_ne {
105 ($left:expr, $right:expr) => ({
106 match (&$left, &$right) {
107 (left_val, right_val) => {
108 if *left_val == *right_val {
109 panic!(r#"assertion failed: `(left != right)`
111 right: `{:?}`"#, left_val, right_val)
116 ($left:expr, $right:expr,) => {
117 assert_ne!($left, $right)
119 ($left:expr, $right:expr, $($arg:tt)+) => ({
120 match (&($left), &($right)) {
121 (left_val, right_val) => {
122 if *left_val == *right_val {
123 panic!(r#"assertion failed: `(left != right)`
125 right: `{:?}`: {}"#, left_val, right_val,
126 format_args!($($arg)+))
133 /// Ensure that a boolean expression is `true` at runtime.
135 /// This will invoke the [`panic!`] macro if the provided expression cannot be
136 /// evaluated to `true` at runtime.
138 /// Like [`assert!`], this macro also has a second version, where a custom panic
139 /// message can be provided.
143 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
144 /// optimized builds by default. An optimized build will omit all
145 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
146 /// compiler. This makes `debug_assert!` useful for checks that are too
147 /// expensive to be present in a release build but may be helpful during
150 /// An unchecked assertion allows a program in an inconsistent state to keep
151 /// running, which might have unexpected consequences but does not introduce
152 /// unsafety as long as this only happens in safe code. The performance cost
153 /// of assertions, is however, not measurable in general. Replacing [`assert!`]
154 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
155 /// more importantly, only in safe code!
157 /// [`panic!`]: macro.panic.html
158 /// [`assert!`]: macro.assert.html
163 /// // the panic message for these assertions is the stringified value of the
164 /// // expression given.
165 /// debug_assert!(true);
167 /// fn some_expensive_computation() -> bool { true } // a very simple function
168 /// debug_assert!(some_expensive_computation());
170 /// // assert with a custom message
172 /// debug_assert!(x, "x wasn't true!");
174 /// let a = 3; let b = 27;
175 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
178 #[stable(feature = "rust1", since = "1.0.0")]
179 macro_rules! debug_assert {
180 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
183 /// Asserts that two expressions are equal to each other.
185 /// On panic, this macro will print the values of the expressions with their
186 /// debug representations.
188 /// Unlike [`assert_eq!`], `debug_assert_eq!` statements are only enabled in non
189 /// optimized builds by default. An optimized build will omit all
190 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
191 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
192 /// expensive to be present in a release build but may be helpful during
195 /// [`assert_eq!`]: ../std/macro.assert_eq.html
202 /// debug_assert_eq!(a, b);
205 #[stable(feature = "rust1", since = "1.0.0")]
206 macro_rules! debug_assert_eq {
207 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
210 /// Asserts that two expressions are not equal to each other.
212 /// On panic, this macro will print the values of the expressions with their
213 /// debug representations.
215 /// Unlike [`assert_ne!`], `debug_assert_ne!` statements are only enabled in non
216 /// optimized builds by default. An optimized build will omit all
217 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
218 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
219 /// expensive to be present in a release build but may be helpful during
222 /// [`assert_ne!`]: ../std/macro.assert_ne.html
229 /// debug_assert_ne!(a, b);
232 #[stable(feature = "assert_ne", since = "1.13.0")]
233 macro_rules! debug_assert_ne {
234 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_ne!($($arg)*); })
237 /// Helper macro for reducing boilerplate code for matching `Result` together
238 /// with converting downstream errors.
240 /// The `?` operator was added to replace `try!` and should be used instead.
242 /// `try!` matches the given [`Result`]. In case of the `Ok` variant, the
243 /// expression has the value of the wrapped value.
245 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
246 /// performs conversion using `From`. This provides automatic conversion
247 /// between specialized errors and more general ones. The resulting
248 /// error is then immediately returned.
250 /// Because of the early return, `try!` can only be used in functions that
251 /// return [`Result`].
253 /// [`Result`]: ../std/result/enum.Result.html
259 /// use std::fs::File;
260 /// use std::io::prelude::*;
266 /// impl From<io::Error> for MyError {
267 /// fn from(e: io::Error) -> MyError {
268 /// MyError::FileWriteError
272 /// // The preferred method of quick returning Errors
273 /// fn write_to_file_question() -> Result<(), MyError> {
274 /// let mut file = File::create("my_best_friends.txt")?;
275 /// file.write_all(b"This is a list of my best friends.")?;
279 /// // The previous method of quick returning Errors
280 /// fn write_to_file_using_try() -> Result<(), MyError> {
281 /// let mut file = try!(File::create("my_best_friends.txt"));
282 /// try!(file.write_all(b"This is a list of my best friends."));
286 /// // This is equivalent to:
287 /// fn write_to_file_using_match() -> Result<(), MyError> {
288 /// let mut file = try!(File::create("my_best_friends.txt"));
289 /// match file.write_all(b"This is a list of my best friends.") {
291 /// Err(e) => return Err(From::from(e)),
297 #[stable(feature = "rust1", since = "1.0.0")]
300 ($expr:expr) => (match $expr {
301 $crate::result::Result::Ok(val) => val,
302 $crate::result::Result::Err(err) => {
303 return $crate::result::Result::Err($crate::convert::From::from(err))
306 ($expr:expr,) => (try!($expr));
309 /// Write formatted data into a buffer.
311 /// This macro accepts a format string, a list of arguments, and a 'writer'. Arguments will be
312 /// formatted according to the specified format string and the result will be passed to the writer.
313 /// The writer may be any value with a `write_fmt` method; generally this comes from an
314 /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro
315 /// returns whatever the `write_fmt` method returns; commonly a [`std::fmt::Result`], or an
318 /// See [`std::fmt`] for more information on the format string syntax.
320 /// [`std::fmt`]: ../std/fmt/index.html
321 /// [`std::fmt::Write`]: ../std/fmt/trait.Write.html
322 /// [`std::io::Write`]: ../std/io/trait.Write.html
323 /// [`std::fmt::Result`]: ../std/fmt/type.Result.html
324 /// [`io::Result`]: ../std/io/type.Result.html
329 /// use std::io::Write;
331 /// let mut w = Vec::new();
332 /// write!(&mut w, "test").unwrap();
333 /// write!(&mut w, "formatted {}", "arguments").unwrap();
335 /// assert_eq!(w, b"testformatted arguments");
338 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
339 /// implementing either, as objects do not typically implement both. However, the module must
340 /// import the traits qualified so their names do not conflict:
343 /// use std::fmt::Write as FmtWrite;
344 /// use std::io::Write as IoWrite;
346 /// let mut s = String::new();
347 /// let mut v = Vec::new();
348 /// write!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
349 /// write!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
350 /// assert_eq!(v, b"s = \"abc 123\"");
353 #[stable(feature = "rust1", since = "1.0.0")]
355 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
358 /// Write formatted data into a buffer, with a newline appended.
360 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
361 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
363 /// For more information, see [`write!`]. For information on the format string syntax, see
366 /// [`write!`]: macro.write.html
367 /// [`std::fmt`]: ../std/fmt/index.html
373 /// use std::io::Write;
375 /// let mut w = Vec::new();
376 /// writeln!(&mut w).unwrap();
377 /// writeln!(&mut w, "test").unwrap();
378 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
380 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
383 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
384 /// implementing either, as objects do not typically implement both. However, the module must
385 /// import the traits qualified so their names do not conflict:
388 /// use std::fmt::Write as FmtWrite;
389 /// use std::io::Write as IoWrite;
391 /// let mut s = String::new();
392 /// let mut v = Vec::new();
393 /// writeln!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
394 /// writeln!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
395 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
398 #[stable(feature = "rust1", since = "1.0.0")]
399 macro_rules! writeln {
406 ($dst:expr, $fmt:expr) => (
407 write!($dst, concat!($fmt, "\n"))
409 ($dst:expr, $fmt:expr, $($arg:tt)*) => (
410 write!($dst, concat!($fmt, "\n"), $($arg)*)
414 /// A utility macro for indicating unreachable code.
416 /// This is useful any time that the compiler can't determine that some code is unreachable. For
419 /// * Match arms with guard conditions.
420 /// * Loops that dynamically terminate.
421 /// * Iterators that dynamically terminate.
423 /// If the determination that the code is unreachable proves incorrect, the
424 /// program immediately terminates with a [`panic!`]. The function [`unreachable_unchecked`],
425 /// which belongs to the [`std::hint`] module, informs the compilier to
426 /// optimize the code out of the release version entirely.
428 /// [`panic!`]: ../std/macro.panic.html
429 /// [`unreachable_unchecked`]: ../std/hint/fn.unreachable_unchecked.html
430 /// [`std::hint`]: ../std/hint/index.html
434 /// This will always [`panic!`]
436 /// [`panic!`]: ../std/macro.panic.html
442 /// # #[allow(dead_code)]
443 /// fn foo(x: Option<i32>) {
445 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
446 /// Some(n) if n < 0 => println!("Some(Negative)"),
447 /// Some(_) => unreachable!(), // compile error if commented out
448 /// None => println!("None")
456 /// # #[allow(dead_code)]
457 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
459 /// if 3*i < i { panic!("u32 overflow"); }
460 /// if x < 3*i { return i-1; }
466 #[stable(feature = "rust1", since = "1.0.0")]
467 macro_rules! unreachable {
469 panic!("internal error: entered unreachable code")
472 unreachable!("{}", $msg)
477 ($fmt:expr, $($arg:tt)*) => ({
478 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
482 /// A standardized placeholder for marking unfinished code.
484 /// This can be useful if you are prototyping and are just looking to have your
485 /// code typecheck, or if you're implementing a trait that requires multiple
486 /// methods, and you're only planning on using one of them.
490 /// This will always [panic!](macro.panic.html)
494 /// Here's an example of some in-progress code. We have a trait `Foo`:
503 /// We want to implement `Foo` on one of our types, but we also want to work on
504 /// just `bar()` first. In order for our code to compile, we need to implement
505 /// `baz()`, so we can use `unimplemented!`:
514 /// impl Foo for MyStruct {
516 /// // implementation goes here
520 /// // let's not worry about implementing baz() for now
521 /// unimplemented!();
526 /// let s = MyStruct;
529 /// // we aren't even using baz() yet, so this is fine.
533 #[stable(feature = "rust1", since = "1.0.0")]
534 macro_rules! unimplemented {
535 () => (panic!("not yet implemented"));
536 ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)*)));
539 /// Built-in macros to the compiler itself.
541 /// These macros do not have any corresponding definition with a `macro_rules!`
542 /// macro, but are documented here. Their implementations can be found hardcoded
543 /// into libsyntax itself.
545 /// For more information, see documentation for `std`'s macros.
548 /// Unconditionally causes compilation to fail with the given error message when encountered.
550 /// For more information, see the documentation for [`std::compile_error!`].
552 /// [`std::compile_error!`]: ../std/macro.compile_error.html
553 #[stable(feature = "compile_error_macro", since = "1.20.0")]
556 macro_rules! compile_error {
557 ($msg:expr) => ({ /* compiler built-in */ });
558 ($msg:expr,) => ({ /* compiler built-in */ });
561 /// The core macro for formatted string creation & output.
563 /// For more information, see the documentation for [`std::format_args!`].
565 /// [`std::format_args!`]: ../std/macro.format_args.html
566 #[stable(feature = "rust1", since = "1.0.0")]
569 macro_rules! format_args {
570 ($fmt:expr) => ({ /* compiler built-in */ });
571 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ });
574 /// Inspect an environment variable at compile time.
576 /// For more information, see the documentation for [`std::env!`].
578 /// [`std::env!`]: ../std/macro.env.html
579 #[stable(feature = "rust1", since = "1.0.0")]
583 ($name:expr) => ({ /* compiler built-in */ });
584 ($name:expr,) => ({ /* compiler built-in */ });
587 /// Optionally inspect an environment variable at compile time.
589 /// For more information, see the documentation for [`std::option_env!`].
591 /// [`std::option_env!`]: ../std/macro.option_env.html
592 #[stable(feature = "rust1", since = "1.0.0")]
595 macro_rules! option_env {
596 ($name:expr) => ({ /* compiler built-in */ });
597 ($name:expr,) => ({ /* compiler built-in */ });
600 /// Concatenate identifiers into one identifier.
602 /// For more information, see the documentation for [`std::concat_idents!`].
604 /// [`std::concat_idents!`]: ../std/macro.concat_idents.html
605 #[unstable(feature = "concat_idents_macro", issue = "29599")]
608 macro_rules! concat_idents {
609 ($($e:ident),+) => ({ /* compiler built-in */ });
610 ($($e:ident,)+) => ({ /* compiler built-in */ });
613 /// Concatenates literals into a static string slice.
615 /// For more information, see the documentation for [`std::concat!`].
617 /// [`std::concat!`]: ../std/macro.concat.html
618 #[stable(feature = "rust1", since = "1.0.0")]
621 macro_rules! concat {
622 ($($e:expr),*) => ({ /* compiler built-in */ });
623 ($($e:expr,)*) => ({ /* compiler built-in */ });
626 /// A macro which expands to the line number on which it was invoked.
628 /// For more information, see the documentation for [`std::line!`].
630 /// [`std::line!`]: ../std/macro.line.html
631 #[stable(feature = "rust1", since = "1.0.0")]
634 macro_rules! line { () => ({ /* compiler built-in */ }) }
636 /// A macro which expands to the column number on which it was invoked.
638 /// For more information, see the documentation for [`std::column!`].
640 /// [`std::column!`]: ../std/macro.column.html
641 #[stable(feature = "rust1", since = "1.0.0")]
644 macro_rules! column { () => ({ /* compiler built-in */ }) }
646 /// A macro which expands to the file name from which it was invoked.
648 /// For more information, see the documentation for [`std::file!`].
650 /// [`std::file!`]: ../std/macro.file.html
651 #[stable(feature = "rust1", since = "1.0.0")]
654 macro_rules! file { () => ({ /* compiler built-in */ }) }
656 /// A macro which stringifies its arguments.
658 /// For more information, see the documentation for [`std::stringify!`].
660 /// [`std::stringify!`]: ../std/macro.stringify.html
661 #[stable(feature = "rust1", since = "1.0.0")]
664 macro_rules! stringify { ($($t:tt)*) => ({ /* compiler built-in */ }) }
666 /// Includes a utf8-encoded file as a string.
668 /// For more information, see the documentation for [`std::include_str!`].
670 /// [`std::include_str!`]: ../std/macro.include_str.html
671 #[stable(feature = "rust1", since = "1.0.0")]
674 macro_rules! include_str {
675 ($file:expr) => ({ /* compiler built-in */ });
676 ($file:expr,) => ({ /* compiler built-in */ });
679 /// Includes a file as a reference to a byte array.
681 /// For more information, see the documentation for [`std::include_bytes!`].
683 /// [`std::include_bytes!`]: ../std/macro.include_bytes.html
684 #[stable(feature = "rust1", since = "1.0.0")]
687 macro_rules! include_bytes {
688 ($file:expr) => ({ /* compiler built-in */ });
689 ($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, at compile-time.
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 {
721 ($file:expr) => ({ /* compiler built-in */ });
722 ($file:expr,) => ({ /* compiler built-in */ });
725 /// Ensure that a boolean expression is `true` at runtime.
727 /// For more information, see the documentation for [`std::assert!`].
729 /// [`std::assert!`]: ../std/macro.assert.html
731 #[stable(feature = "rust1", since = "1.0.0")]
733 macro_rules! assert {
734 ($cond:expr) => ({ /* compiler built-in */ });
735 ($cond:expr,) => ({ /* compiler built-in */ });
736 ($cond:expr, $($arg:tt)+) => ({ /* compiler built-in */ });