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.
12 // This stability attribute is totally useless.
13 #[stable(feature = "rust1", since = "1.0.0")]
15 macro_rules! __rust_unstable_column {
21 /// Entry point of thread panic, for details, see std::macros
23 #[allow_internal_unstable]
24 #[stable(feature = "core", since = "1.6.0")]
27 panic!("explicit panic")
30 static _MSG_FILE_LINE_COL: (&'static str, &'static str, u32, u32) =
31 ($msg, file!(), line!(), __rust_unstable_column!());
32 $crate::panicking::panic(&_MSG_FILE_LINE_COL)
34 ($fmt:expr, $($arg:tt)*) => ({
35 // The leading _'s are to avoid dead code warnings if this is
36 // used inside a dead function. Just `#[allow(dead_code)]` is
37 // insufficient, since the user may have
38 // `#[forbid(dead_code)]` and which cannot be overridden.
39 static _MSG_FILE_LINE_COL: (&'static str, u32, u32) =
40 (file!(), line!(), __rust_unstable_column!());
41 $crate::panicking::panic_fmt(format_args!($fmt, $($arg)*), &_MSG_FILE_LINE_COL)
45 /// Ensure that a boolean expression is `true` at runtime.
47 /// This will invoke the [`panic!`] macro if the provided expression cannot be
48 /// evaluated to `true` at runtime.
52 /// Assertions are always checked in both debug and release builds, and cannot
53 /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
54 /// release builds by default.
56 /// Unsafe code relies on `assert!` to enforce run-time invariants that, if
57 /// violated could lead to unsafety.
59 /// Other use-cases of `assert!` include [testing] and enforcing run-time
60 /// invariants in safe code (whose violation cannot result in unsafety).
64 /// This macro has a second form, where a custom panic message can
65 /// be provided with or without arguments for formatting.
67 /// [`panic!`]: macro.panic.html
68 /// [`debug_assert!`]: macro.debug_assert.html
69 /// [testing]: ../book/first-edition/testing.html
74 /// // the panic message for these assertions is the stringified value of the
75 /// // expression given.
78 /// fn some_computation() -> bool { true } // a very simple function
80 /// assert!(some_computation());
82 /// // assert with a custom message
84 /// assert!(x, "x wasn't true!");
86 /// let a = 3; let b = 27;
87 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
90 #[stable(feature = "rust1", since = "1.0.0")]
94 panic!(concat!("assertion failed: ", stringify!($cond)))
97 ($cond:expr, $($arg:tt)+) => (
104 /// Asserts that two expressions are equal to each other (using [`PartialEq`]).
106 /// On panic, this macro will print the values of the expressions with their
107 /// debug representations.
109 /// Like [`assert!`], this macro has a second form, where a custom
110 /// panic message can be provided.
112 /// [`PartialEq`]: cmp/trait.PartialEq.html
113 /// [`assert!`]: macro.assert.html
120 /// assert_eq!(a, b);
122 /// assert_eq!(a, b, "we are testing addition with {} and {}", a, b);
125 #[stable(feature = "rust1", since = "1.0.0")]
126 macro_rules! assert_eq {
127 ($left:expr, $right:expr) => ({
128 match (&$left, &$right) {
129 (left_val, right_val) => {
130 if !(*left_val == *right_val) {
131 panic!(r#"assertion failed: `(left == right)`
133 right: `{:?}`"#, left_val, right_val)
138 ($left:expr, $right:expr, $($arg:tt)+) => ({
139 match (&($left), &($right)) {
140 (left_val, right_val) => {
141 if !(*left_val == *right_val) {
142 panic!(r#"assertion failed: `(left == right)`
144 right: `{:?}`: {}"#, left_val, right_val,
145 format_args!($($arg)+))
152 /// Asserts that two expressions are not equal to each other (using [`PartialEq`]).
154 /// On panic, this macro will print the values of the expressions with their
155 /// debug representations.
157 /// Like [`assert!`], this macro has a second form, where a custom
158 /// panic message can be provided.
160 /// [`PartialEq`]: cmp/trait.PartialEq.html
161 /// [`assert!`]: macro.assert.html
168 /// assert_ne!(a, b);
170 /// assert_ne!(a, b, "we are testing that the values are not equal");
173 #[stable(feature = "assert_ne", since = "1.13.0")]
174 macro_rules! assert_ne {
175 ($left:expr, $right:expr) => ({
176 match (&$left, &$right) {
177 (left_val, right_val) => {
178 if *left_val == *right_val {
179 panic!(r#"assertion failed: `(left != right)`
181 right: `{:?}`"#, left_val, right_val)
186 ($left:expr, $right:expr, $($arg:tt)+) => ({
187 match (&($left), &($right)) {
188 (left_val, right_val) => {
189 if *left_val == *right_val {
190 panic!(r#"assertion failed: `(left != right)`
192 right: `{:?}`: {}"#, left_val, right_val,
193 format_args!($($arg)+))
200 /// Ensure that a boolean expression is `true` at runtime.
202 /// This will invoke the [`panic!`] macro if the provided expression cannot be
203 /// evaluated to `true` at runtime.
205 /// Like [`assert!`], this macro also has a second version, where a custom panic
206 /// message can be provided.
210 /// Unlike [`assert!`], `debug_assert!` statements are only enabled in non
211 /// optimized builds by default. An optimized build will omit all
212 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
213 /// compiler. This makes `debug_assert!` useful for checks that are too
214 /// expensive to be present in a release build but may be helpful during
217 /// An unchecked assertion allows a program in an inconsistent state to keep
218 /// running, which might have unexpected consequences but does not introduce
219 /// unsafety as long as this only happens in safe code. The performance cost
220 /// of assertions, is however, not measurable in general. Replacing [`assert!`]
221 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
222 /// more importantly, only in safe code!
224 /// [`panic!`]: macro.panic.html
225 /// [`assert!`]: macro.assert.html
230 /// // the panic message for these assertions is the stringified value of the
231 /// // expression given.
232 /// debug_assert!(true);
234 /// fn some_expensive_computation() -> bool { true } // a very simple function
235 /// debug_assert!(some_expensive_computation());
237 /// // assert with a custom message
239 /// debug_assert!(x, "x wasn't true!");
241 /// let a = 3; let b = 27;
242 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
245 #[stable(feature = "rust1", since = "1.0.0")]
246 macro_rules! debug_assert {
247 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
250 /// Asserts that two expressions are equal to each other.
252 /// On panic, this macro will print the values of the expressions with their
253 /// debug representations.
255 /// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
256 /// optimized builds by default. An optimized build will omit all
257 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
258 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
259 /// expensive to be present in a release build but may be helpful during
267 /// debug_assert_eq!(a, b);
270 #[stable(feature = "rust1", since = "1.0.0")]
271 macro_rules! debug_assert_eq {
272 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
275 /// Asserts that two expressions are not equal to each other.
277 /// On panic, this macro will print the values of the expressions with their
278 /// debug representations.
280 /// Unlike `assert_ne!`, `debug_assert_ne!` statements are only enabled in non
281 /// optimized builds by default. An optimized build will omit all
282 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
283 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
284 /// expensive to be present in a release build but may be helpful during
292 /// debug_assert_ne!(a, b);
295 #[stable(feature = "assert_ne", since = "1.13.0")]
296 macro_rules! debug_assert_ne {
297 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_ne!($($arg)*); })
300 /// Helper macro for reducing boilerplate code for matching `Result` together
301 /// with converting downstream errors.
303 /// Prefer using `?` syntax to `try!`. `?` is built in to the language and is
304 /// more succinct than `try!`. It is the standard method for error propagation.
306 /// `try!` matches the given `Result`. In case of the `Ok` variant, the
307 /// expression has the value of the wrapped value.
309 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
310 /// performs conversion using `From`. This provides automatic conversion
311 /// between specialized errors and more general ones. The resulting
312 /// error is then immediately returned.
314 /// Because of the early return, `try!` can only be used in functions that
321 /// use std::fs::File;
322 /// use std::io::prelude::*;
328 /// impl From<io::Error> for MyError {
329 /// fn from(e: io::Error) -> MyError {
330 /// MyError::FileWriteError
334 /// fn write_to_file_using_try() -> Result<(), MyError> {
335 /// let mut file = try!(File::create("my_best_friends.txt"));
336 /// try!(file.write_all(b"This is a list of my best friends."));
337 /// println!("I wrote to the file");
340 /// // This is equivalent to:
341 /// fn write_to_file_using_match() -> Result<(), MyError> {
342 /// let mut file = try!(File::create("my_best_friends.txt"));
343 /// match file.write_all(b"This is a list of my best friends.") {
345 /// Err(e) => return Err(From::from(e)),
347 /// println!("I wrote to the file");
352 #[stable(feature = "rust1", since = "1.0.0")]
354 ($expr:expr) => (match $expr {
355 $crate::result::Result::Ok(val) => val,
356 $crate::result::Result::Err(err) => {
357 return $crate::result::Result::Err($crate::convert::From::from(err))
362 /// Write formatted data into a buffer
364 /// This macro accepts a format string, a list of arguments, and a 'writer'. Arguments will be
365 /// formatted according to the specified format string and the result will be passed to the writer.
366 /// The writer may be any value with a `write_fmt` method; generally this comes from an
367 /// implementation of either the [`std::fmt::Write`] or the [`std::io::Write`] trait. The macro
368 /// returns whatever the 'write_fmt' method returns; commonly a [`std::fmt::Result`], or an
371 /// See [`std::fmt`] for more information on the format string syntax.
373 /// [`std::fmt`]: ../std/fmt/index.html
374 /// [`std::fmt::Write`]: ../std/fmt/trait.Write.html
375 /// [`std::io::Write`]: ../std/io/trait.Write.html
376 /// [`std::fmt::Result`]: ../std/fmt/type.Result.html
377 /// [`io::Result`]: ../std/io/type.Result.html
382 /// use std::io::Write;
384 /// let mut w = Vec::new();
385 /// write!(&mut w, "test").unwrap();
386 /// write!(&mut w, "formatted {}", "arguments").unwrap();
388 /// assert_eq!(w, b"testformatted arguments");
391 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
392 /// implementing either, as objects do not typically implement both. However, the module must
393 /// import the traits qualified so their names do not conflict:
396 /// use std::fmt::Write as FmtWrite;
397 /// use std::io::Write as IoWrite;
399 /// let mut s = String::new();
400 /// let mut v = Vec::new();
401 /// write!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
402 /// write!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
403 /// assert_eq!(v, b"s = \"abc 123\"");
406 #[stable(feature = "rust1", since = "1.0.0")]
408 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
411 /// Write formatted data into a buffer, with a newline appended.
413 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
414 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
416 /// For more information, see [`write!`]. For information on the format string syntax, see
419 /// [`write!`]: macro.write.html
420 /// [`std::fmt`]: ../std/fmt/index.html
426 /// use std::io::Write;
428 /// let mut w = Vec::new();
429 /// writeln!(&mut w).unwrap();
430 /// writeln!(&mut w, "test").unwrap();
431 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
433 /// assert_eq!(&w[..], "\ntest\nformatted arguments\n".as_bytes());
436 /// A module can import both `std::fmt::Write` and `std::io::Write` and call `write!` on objects
437 /// implementing either, as objects do not typically implement both. However, the module must
438 /// import the traits qualified so their names do not conflict:
441 /// use std::fmt::Write as FmtWrite;
442 /// use std::io::Write as IoWrite;
444 /// let mut s = String::new();
445 /// let mut v = Vec::new();
446 /// writeln!(&mut s, "{} {}", "abc", 123).unwrap(); // uses fmt::Write::write_fmt
447 /// writeln!(&mut v, "s = {:?}", s).unwrap(); // uses io::Write::write_fmt
448 /// assert_eq!(v, b"s = \"abc 123\\n\"\n");
451 #[stable(feature = "rust1", since = "1.0.0")]
452 macro_rules! writeln {
456 ($dst:expr, $fmt:expr) => (
457 write!($dst, concat!($fmt, "\n"))
459 ($dst:expr, $fmt:expr, $($arg:tt)*) => (
460 write!($dst, concat!($fmt, "\n"), $($arg)*)
464 /// A utility macro for indicating unreachable code.
466 /// This is useful any time that the compiler can't determine that some code is unreachable. For
469 /// * Match arms with guard conditions.
470 /// * Loops that dynamically terminate.
471 /// * Iterators that dynamically terminate.
475 /// This will always [panic!](macro.panic.html)
482 /// # #[allow(dead_code)]
483 /// fn foo(x: Option<i32>) {
485 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
486 /// Some(n) if n < 0 => println!("Some(Negative)"),
487 /// Some(_) => unreachable!(), // compile error if commented out
488 /// None => println!("None")
496 /// # #[allow(dead_code)]
497 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
499 /// if 3*i < i { panic!("u32 overflow"); }
500 /// if x < 3*i { return i-1; }
506 #[stable(feature = "rust1", since = "1.0.0")]
507 macro_rules! unreachable {
509 panic!("internal error: entered unreachable code")
512 unreachable!("{}", $msg)
514 ($fmt:expr, $($arg:tt)*) => ({
515 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
519 /// A standardized placeholder for marking unfinished code. It panics with the
520 /// message `"not yet implemented"` when executed.
522 /// This can be useful if you are prototyping and are just looking to have your
523 /// code typecheck, or if you're implementing a trait that requires multiple
524 /// methods, and you're only planning on using one of them.
528 /// Here's an example of some in-progress code. We have a trait `Foo`:
537 /// We want to implement `Foo` on one of our types, but we also want to work on
538 /// just `bar()` first. In order for our code to compile, we need to implement
539 /// `baz()`, so we can use `unimplemented!`:
548 /// impl Foo for MyStruct {
550 /// // implementation goes here
554 /// // let's not worry about implementing baz() for now
555 /// unimplemented!();
560 /// let s = MyStruct;
563 /// // we aren't even using baz() yet, so this is fine.
567 #[stable(feature = "rust1", since = "1.0.0")]
568 macro_rules! unimplemented {
569 () => (panic!("not yet implemented"));
570 ($($arg:tt)+) => (panic!("not yet implemented: {}", format_args!($($arg)*)));
573 /// Built-in macros to the compiler itself.
575 /// These macros do not have any corresponding definition with a `macro_rules!`
576 /// macro, but are documented here. Their implementations can be found hardcoded
577 /// into libsyntax itself.
579 /// For more information, see documentation for `std`'s macros.
582 /// Unconditionally causes compilation to fail with the given error message when encountered.
584 /// For more information, see the [RFC].
586 /// [RFC]: https://github.com/rust-lang/rfcs/blob/master/text/1695-add-error-macro.md
587 #[stable(feature = "compile_error_macro", since = "1.20.0")]
590 macro_rules! compile_error { ($msg:expr) => ({ /* compiler built-in */ }) }
592 /// The core macro for formatted string creation & output.
594 /// For more information, see the documentation for [`std::format_args!`].
596 /// [`std::format_args!`]: ../std/macro.format_args.html
597 #[stable(feature = "rust1", since = "1.0.0")]
600 macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({
601 /* compiler built-in */
604 /// Inspect an environment variable at compile time.
606 /// For more information, see the documentation for [`std::env!`].
608 /// [`std::env!`]: ../std/macro.env.html
609 #[stable(feature = "rust1", since = "1.0.0")]
612 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
614 /// Optionally inspect an environment variable at compile time.
616 /// For more information, see the documentation for [`std::option_env!`].
618 /// [`std::option_env!`]: ../std/macro.option_env.html
619 #[stable(feature = "rust1", since = "1.0.0")]
622 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
624 /// Concatenate identifiers into one identifier.
626 /// For more information, see the documentation for [`std::concat_idents!`].
628 /// [`std::concat_idents!`]: ../std/macro.concat_idents.html
629 #[unstable(feature = "concat_idents_macro", issue = "29599")]
632 macro_rules! concat_idents {
633 ($($e:ident),*) => ({ /* compiler built-in */ })
636 /// Concatenates literals into a static string slice.
638 /// For more information, see the documentation for [`std::concat!`].
640 /// [`std::concat!`]: ../std/macro.concat.html
641 #[stable(feature = "rust1", since = "1.0.0")]
644 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
646 /// A macro which expands to the line number on which it was invoked.
648 /// For more information, see the documentation for [`std::line!`].
650 /// [`std::line!`]: ../std/macro.line.html
651 #[stable(feature = "rust1", since = "1.0.0")]
654 macro_rules! line { () => ({ /* compiler built-in */ }) }
656 /// A macro which expands to the column number on which it was invoked.
658 /// For more information, see the documentation for [`std::column!`].
660 /// [`std::column!`]: ../std/macro.column.html
661 #[stable(feature = "rust1", since = "1.0.0")]
664 macro_rules! column { () => ({ /* compiler built-in */ }) }
666 /// A macro which expands to the file name from which it was invoked.
668 /// For more information, see the documentation for [`std::file!`].
670 /// [`std::file!`]: ../std/macro.file.html
671 #[stable(feature = "rust1", since = "1.0.0")]
674 macro_rules! file { () => ({ /* compiler built-in */ }) }
676 /// A macro which stringifies its argument.
678 /// For more information, see the documentation for [`std::stringify!`].
680 /// [`std::stringify!`]: ../std/macro.stringify.html
681 #[stable(feature = "rust1", since = "1.0.0")]
684 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
686 /// Includes a utf8-encoded file as a string.
688 /// For more information, see the documentation for [`std::include_str!`].
690 /// [`std::include_str!`]: ../std/macro.include_str.html
691 #[stable(feature = "rust1", since = "1.0.0")]
694 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
696 /// Includes a file as a reference to a byte array.
698 /// For more information, see the documentation for [`std::include_bytes!`].
700 /// [`std::include_bytes!`]: ../std/macro.include_bytes.html
701 #[stable(feature = "rust1", since = "1.0.0")]
704 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
706 /// Expands to a string that represents the current module path.
708 /// For more information, see the documentation for [`std::module_path!`].
710 /// [`std::module_path!`]: ../std/macro.module_path.html
711 #[stable(feature = "rust1", since = "1.0.0")]
714 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
716 /// Boolean evaluation of configuration flags.
718 /// For more information, see the documentation for [`std::cfg!`].
720 /// [`std::cfg!`]: ../std/macro.cfg.html
721 #[stable(feature = "rust1", since = "1.0.0")]
724 macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
726 /// Parse a file as an expression or an item according to the context.
728 /// For more information, see the documentation for [`std::include!`].
730 /// [`std::include!`]: ../std/macro.include.html
731 #[stable(feature = "rust1", since = "1.0.0")]
734 macro_rules! include { ($file:expr) => ({ /* compiler built-in */ }) }