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 #[allow_internal_unstable]
400 macro_rules! writeln {
407 ($dst:expr, $($arg:tt)*) => (
408 $dst.write_fmt(format_args_nl!($($arg)*))
412 /// A utility macro for indicating unreachable code.
414 /// This is useful any time that the compiler can't determine that some code is unreachable. For
417 /// * Match arms with guard conditions.
418 /// * Loops that dynamically terminate.
419 /// * Iterators that dynamically terminate.
421 /// If the determination that the code is unreachable proves incorrect, the
422 /// program immediately terminates with a [`panic!`]. The function [`unreachable_unchecked`],
423 /// which belongs to the [`std::hint`] module, informs the compilier to
424 /// optimize the code out of the release version entirely.
426 /// [`panic!`]: ../std/macro.panic.html
427 /// [`unreachable_unchecked`]: ../std/hint/fn.unreachable_unchecked.html
428 /// [`std::hint`]: ../std/hint/index.html
432 /// This will always [`panic!`]
434 /// [`panic!`]: ../std/macro.panic.html
440 /// # #[allow(dead_code)]
441 /// fn foo(x: Option<i32>) {
443 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
444 /// Some(n) if n < 0 => println!("Some(Negative)"),
445 /// Some(_) => unreachable!(), // compile error if commented out
446 /// None => println!("None")
454 /// # #[allow(dead_code)]
455 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
457 /// if 3*i < i { panic!("u32 overflow"); }
458 /// if x < 3*i { return i-1; }
464 #[stable(feature = "rust1", since = "1.0.0")]
465 macro_rules! unreachable {
467 panic!("internal error: entered unreachable code")
470 unreachable!("{}", $msg)
475 ($fmt:expr, $($arg:tt)*) => ({
476 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
480 /// A standardized placeholder for marking unfinished code.
482 /// This can be useful if you are prototyping and are just looking to have your
483 /// code typecheck, or if you're implementing a trait that requires multiple
484 /// methods, and you're only planning on using one of them.
488 /// This will always [panic!](macro.panic.html)
492 /// Here's an example of some in-progress code. We have a trait `Foo`:
501 /// We want to implement `Foo` on one of our types, but we also want to work on
502 /// just `bar()` first. In order for our code to compile, we need to implement
503 /// `baz()`, so we can use `unimplemented!`:
512 /// impl Foo for MyStruct {
514 /// // implementation goes here
518 /// // let's not worry about implementing baz() for now
519 /// unimplemented!();
524 /// let s = MyStruct;
527 /// // we aren't even using baz() yet, so this is fine.
531 #[stable(feature = "rust1", since = "1.0.0")]
532 macro_rules! unimplemented {
533 () => (panic!("not yet implemented"));
534 ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)*)));
537 /// Built-in macros to the compiler itself.
539 /// These macros do not have any corresponding definition with a `macro_rules!`
540 /// macro, but are documented here. Their implementations can be found hardcoded
541 /// into libsyntax itself.
543 /// For more information, see documentation for `std`'s macros.
547 /// Unconditionally causes compilation to fail with the given error message when encountered.
549 /// For more information, see the documentation for [`std::compile_error!`].
551 /// [`std::compile_error!`]: ../std/macro.compile_error.html
552 #[stable(feature = "compile_error_macro", since = "1.20.0")]
553 #[rustc_doc_only_macro]
554 macro_rules! compile_error {
555 ($msg:expr) => ({ /* compiler built-in */ });
556 ($msg:expr,) => ({ /* compiler built-in */ });
559 /// The core macro for formatted string creation & output.
561 /// For more information, see the documentation for [`std::format_args!`].
563 /// [`std::format_args!`]: ../std/macro.format_args.html
564 #[stable(feature = "rust1", since = "1.0.0")]
565 #[rustc_doc_only_macro]
566 macro_rules! format_args {
567 ($fmt:expr) => ({ /* compiler built-in */ });
568 ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ });
571 /// Inspect an environment variable at compile time.
573 /// For more information, see the documentation for [`std::env!`].
575 /// [`std::env!`]: ../std/macro.env.html
576 #[stable(feature = "rust1", since = "1.0.0")]
577 #[rustc_doc_only_macro]
579 ($name:expr) => ({ /* compiler built-in */ });
580 ($name:expr,) => ({ /* compiler built-in */ });
583 /// Optionally inspect an environment variable at compile time.
585 /// For more information, see the documentation for [`std::option_env!`].
587 /// [`std::option_env!`]: ../std/macro.option_env.html
588 #[stable(feature = "rust1", since = "1.0.0")]
589 #[rustc_doc_only_macro]
590 macro_rules! option_env {
591 ($name:expr) => ({ /* compiler built-in */ });
592 ($name:expr,) => ({ /* compiler built-in */ });
595 /// Concatenate identifiers into one identifier.
597 /// For more information, see the documentation for [`std::concat_idents!`].
599 /// [`std::concat_idents!`]: ../std/macro.concat_idents.html
600 #[unstable(feature = "concat_idents_macro", issue = "29599")]
601 #[rustc_doc_only_macro]
602 macro_rules! concat_idents {
603 ($($e:ident),+) => ({ /* compiler built-in */ });
604 ($($e:ident,)+) => ({ /* compiler built-in */ });
607 /// Concatenates literals into a static string slice.
609 /// For more information, see the documentation for [`std::concat!`].
611 /// [`std::concat!`]: ../std/macro.concat.html
612 #[stable(feature = "rust1", since = "1.0.0")]
613 #[rustc_doc_only_macro]
614 macro_rules! concat {
615 ($($e:expr),*) => ({ /* compiler built-in */ });
616 ($($e:expr,)*) => ({ /* compiler built-in */ });
619 /// A macro which expands to the line number on which it was invoked.
621 /// For more information, see the documentation for [`std::line!`].
623 /// [`std::line!`]: ../std/macro.line.html
624 #[stable(feature = "rust1", since = "1.0.0")]
625 #[rustc_doc_only_macro]
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")]
634 #[rustc_doc_only_macro]
635 macro_rules! column { () => ({ /* compiler built-in */ }) }
637 /// A macro which expands to the file name from which it was invoked.
639 /// For more information, see the documentation for [`std::file!`].
641 /// [`std::file!`]: ../std/macro.file.html
642 #[stable(feature = "rust1", since = "1.0.0")]
643 #[rustc_doc_only_macro]
644 macro_rules! file { () => ({ /* compiler built-in */ }) }
646 /// A macro which stringifies its arguments.
648 /// For more information, see the documentation for [`std::stringify!`].
650 /// [`std::stringify!`]: ../std/macro.stringify.html
651 #[stable(feature = "rust1", since = "1.0.0")]
652 #[rustc_doc_only_macro]
653 macro_rules! stringify { ($($t:tt)*) => ({ /* compiler built-in */ }) }
655 /// Includes a utf8-encoded file as a string.
657 /// For more information, see the documentation for [`std::include_str!`].
659 /// [`std::include_str!`]: ../std/macro.include_str.html
660 #[stable(feature = "rust1", since = "1.0.0")]
661 #[rustc_doc_only_macro]
662 macro_rules! include_str {
663 ($file:expr) => ({ /* compiler built-in */ });
664 ($file:expr,) => ({ /* compiler built-in */ });
667 /// Includes a file as a reference to a byte array.
669 /// For more information, see the documentation for [`std::include_bytes!`].
671 /// [`std::include_bytes!`]: ../std/macro.include_bytes.html
672 #[stable(feature = "rust1", since = "1.0.0")]
673 #[rustc_doc_only_macro]
674 macro_rules! include_bytes {
675 ($file:expr) => ({ /* compiler built-in */ });
676 ($file:expr,) => ({ /* compiler built-in */ });
679 /// Expands to a string that represents the current module path.
681 /// For more information, see the documentation for [`std::module_path!`].
683 /// [`std::module_path!`]: ../std/macro.module_path.html
684 #[stable(feature = "rust1", since = "1.0.0")]
685 #[rustc_doc_only_macro]
686 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
688 /// Boolean evaluation of configuration flags, at compile-time.
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")]
694 #[rustc_doc_only_macro]
695 macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
697 /// Parse a file as an expression or an item according to the context.
699 /// For more information, see the documentation for [`std::include!`].
701 /// [`std::include!`]: ../std/macro.include.html
702 #[stable(feature = "rust1", since = "1.0.0")]
703 #[rustc_doc_only_macro]
704 macro_rules! include {
705 ($file:expr) => ({ /* compiler built-in */ });
706 ($file:expr,) => ({ /* compiler built-in */ });
709 /// Ensure that a boolean expression is `true` at runtime.
711 /// For more information, see the documentation for [`std::assert!`].
713 /// [`std::assert!`]: ../std/macro.assert.html
714 #[rustc_doc_only_macro]
715 #[stable(feature = "rust1", since = "1.0.0")]
716 macro_rules! assert {
717 ($cond:expr) => ({ /* compiler built-in */ });
718 ($cond:expr,) => ({ /* compiler built-in */ });
719 ($cond:expr, $($arg:tt)+) => ({ /* compiler built-in */ });