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 be provided.
50 /// [testing]: ../book/testing.html
55 /// // the panic message for these assertions is the stringified value of the
56 /// // expression given.
59 /// fn some_computation() -> bool { true } // a very simple function
61 /// assert!(some_computation());
63 /// // assert with a custom message
65 /// assert!(x, "x wasn't true!");
67 /// let a = 3; let b = 27;
68 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
71 #[stable(feature = "rust1", since = "1.0.0")]
75 panic
!(concat
!("assertion failed: ", stringify
!($cond
)))
78 ($cond
:expr
, $
($arg
:tt
)+) => (
85 /// Asserts that two expressions are equal to each other.
87 /// On panic, this macro will print the values of the expressions with their
88 /// debug representations.
98 #[stable(feature = "rust1", since = "1.0.0")]
99 macro_rules
! assert_eq
{
100 ($left
:expr
, $right
:expr
) => ({
101 match (&$left
, &$right
) {
102 (left_val
, right_val
) => {
103 if !(*left_val
== *right_val
) {
104 panic
!("assertion failed: `(left == right)` \
105 (left: `{:?}`, right: `{:?}`)", left_val
, right_val
)
110 ($left
:expr
, $right
:expr
, $
($arg
:tt
)*) => ({
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
,
116 format_args
!($
($arg
)*))
123 /// Asserts that two expressions are not equal to each other.
125 /// On panic, this macro will print the values of the expressions with their
126 /// debug representations.
133 /// assert_ne!(a, b);
136 #[stable(feature = "assert_ne", since = "1.12.0")]
137 macro_rules
! assert_ne
{
138 ($left
:expr
, $right
:expr
) => ({
139 match (&$left
, &$right
) {
140 (left_val
, right_val
) => {
141 if *left_val
== *right_val
{
142 panic
!("assertion failed: `(left != right)` \
143 (left: `{:?}`, right: `{:?}`)", left_val
, right_val
)
148 ($left
:expr
, $right
:expr
, $
($arg
:tt
)*) => ({
149 match (&($left
), &($right
)) {
150 (left_val
, right_val
) => {
151 if *left_val
== *right_val
{
152 panic
!("assertion failed: `(left != right)` \
153 (left: `{:?}`, right: `{:?}`): {}", left_val
, right_val
,
154 format_args
!($
($arg
)*))
161 /// Ensure that a boolean expression is `true` at runtime.
163 /// This will invoke the `panic!` macro if the provided expression cannot be
164 /// evaluated to `true` at runtime.
166 /// Like `assert!`, this macro also has a second version, where a custom panic
167 /// message can be provided.
169 /// Unlike `assert!`, `debug_assert!` statements are only enabled in non
170 /// optimized builds by default. An optimized build will omit all
171 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
172 /// compiler. This makes `debug_assert!` useful for checks that are too
173 /// expensive to be present in a release build but may be helpful during
176 /// An unchecked assertion allows a program in an inconsistent state to keep
177 /// running, which might have unexpected consequences but does not introduce
178 /// unsafety as long as this only happens in safe code. The performance cost
179 /// of assertions, is however, not measurable in general. Replacing `assert!`
180 /// with `debug_assert!` is thus only encouraged after thorough profiling, and
181 /// more importantly, only in safe code!
186 /// // the panic message for these assertions is the stringified value of the
187 /// // expression given.
188 /// debug_assert!(true);
190 /// fn some_expensive_computation() -> bool { true } // a very simple function
191 /// debug_assert!(some_expensive_computation());
193 /// // assert with a custom message
195 /// debug_assert!(x, "x wasn't true!");
197 /// let a = 3; let b = 27;
198 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
201 #[stable(feature = "rust1", since = "1.0.0")]
202 macro_rules
! debug_assert
{
203 ($
($arg
:tt
)*) => (if cfg
!(debug_assertions
) { assert!($($arg)*); }
)
206 /// Asserts that two expressions are equal to each other.
208 /// On panic, this macro will print the values of the expressions with their
209 /// debug representations.
211 /// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
212 /// optimized builds by default. An optimized build will omit all
213 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
214 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
215 /// expensive to be present in a release build but may be helpful during
223 /// debug_assert_eq!(a, b);
226 #[stable(feature = "rust1", since = "1.0.0")]
227 macro_rules
! debug_assert_eq
{
228 ($
($arg
:tt
)*) => (if cfg
!(debug_assertions
) { assert_eq!($($arg)*); }
)
231 /// Asserts that two expressions are not equal to each other.
233 /// On panic, this macro will print the values of the expressions with their
234 /// debug representations.
236 /// Unlike `assert_ne!`, `debug_assert_ne!` statements are only enabled in non
237 /// optimized builds by default. An optimized build will omit all
238 /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the
239 /// compiler. This makes `debug_assert_ne!` useful for checks that are too
240 /// expensive to be present in a release build but may be helpful during
248 /// debug_assert_ne!(a, b);
251 #[stable(feature = "assert_ne", since = "1.12.0")]
252 macro_rules
! debug_assert_ne
{
253 ($
($arg
:tt
)*) => (if cfg
!(debug_assertions
) { assert_ne!($($arg)*); }
)
256 /// Helper macro for reducing boilerplate code for matching `Result` together
257 /// with converting downstream errors.
259 /// Prefer using `?` syntax to `try!`. `?` is built in to the language and is
260 /// more succinct than `try!`. It is the standard method for error propagation.
262 /// `try!` matches the given `Result`. In case of the `Ok` variant, the
263 /// expression has the value of the wrapped value.
265 /// In case of the `Err` variant, it retrieves the inner error. `try!` then
266 /// performs conversion using `From`. This provides automatic conversion
267 /// between specialized errors and more general ones. The resulting
268 /// error is then immediately returned.
270 /// Because of the early return, `try!` can only be used in functions that
277 /// use std::fs::File;
278 /// use std::io::prelude::*;
284 /// impl From<io::Error> for MyError {
285 /// fn from(e: io::Error) -> MyError {
286 /// MyError::FileWriteError
290 /// fn write_to_file_using_try() -> Result<(), MyError> {
291 /// let mut file = try!(File::create("my_best_friends.txt"));
292 /// try!(file.write_all(b"This is a list of my best friends."));
293 /// println!("I wrote to the file");
296 /// // This is equivalent to:
297 /// fn write_to_file_using_match() -> Result<(), MyError> {
298 /// let mut file = try!(File::create("my_best_friends.txt"));
299 /// match file.write_all(b"This is a list of my best friends.") {
301 /// Err(e) => return Err(From::from(e)),
303 /// println!("I wrote to the file");
308 #[stable(feature = "rust1", since = "1.0.0")]
310 ($expr
:expr
) => (match $expr
{
311 $
crate::result
::Result
::Ok(val
) => val
,
312 $
crate::result
::Result
::Err(err
) => {
313 return $
crate::result
::Result
::Err($
crate::convert
::From
::from(err
))
318 /// Write formatted data into a buffer
320 /// This macro accepts a 'writer' (any value with a `write_fmt` method), a format string, and a
321 /// list of arguments to format.
323 /// The `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write]
324 /// or [`std::io::Write`][io_write] traits. The term 'writer' refers to an implementation of one of
325 /// these two traits.
327 /// Passed arguments will be formatted according to the specified format string and the resulting
328 /// string will be passed to the writer.
330 /// See [`std::fmt`][fmt] for more information on format syntax.
332 /// `write!` returns whatever the 'write_fmt' method returns.
334 /// Common return values include: [`fmt::Result`][fmt_result], [`io::Result`][io_result]
336 /// [fmt]: ../std/fmt/index.html
337 /// [fmt_write]: ../std/fmt/trait.Write.html
338 /// [io_write]: ../std/io/trait.Write.html
339 /// [fmt_result]: ../std/fmt/type.Result.html
340 /// [io_result]: ../std/io/type.Result.html
345 /// use std::io::Write;
347 /// let mut w = Vec::new();
348 /// write!(&mut w, "test").unwrap();
349 /// write!(&mut w, "formatted {}", "arguments").unwrap();
351 /// assert_eq!(w, b"testformatted arguments");
354 #[stable(feature = "core", since = "1.6.0")]
356 ($dst
:expr
, $
($arg
:tt
)*) => ($dst
.write_fmt(format_args
!($
($arg
)*)))
359 /// Write formatted data into a buffer, with a newline appended.
361 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
362 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
364 /// This macro accepts a 'writer' (any value with a `write_fmt` method), a format string, and a
365 /// list of arguments to format.
367 /// The `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write]
368 /// or [`std::io::Write`][io_write] traits. The term 'writer' refers to an implementation of one of
369 /// these two traits.
371 /// Passed arguments will be formatted according to the specified format string and the resulting
372 /// string will be passed to the writer, along with the appended newline.
374 /// See [`std::fmt`][fmt] for more information on format syntax.
376 /// `write!` returns whatever the 'write_fmt' method returns.
378 /// Common return values include: [`fmt::Result`][fmt_result], [`io::Result`][io_result]
380 /// [fmt]: ../std/fmt/index.html
381 /// [fmt_write]: ../std/fmt/trait.Write.html
382 /// [io_write]: ../std/io/trait.Write.html
383 /// [fmt_result]: ../std/fmt/type.Result.html
384 /// [io_result]: ../std/io/type.Result.html
389 /// use std::io::Write;
391 /// let mut w = Vec::new();
392 /// writeln!(&mut w, "test").unwrap();
393 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
395 /// assert_eq!(&w[..], "test\nformatted arguments\n".as_bytes());
398 #[stable(feature = "rust1", since = "1.0.0")]
399 macro_rules
! writeln
{
400 ($dst
:expr
, $fmt
:expr
) => (
401 write
!($dst
, concat
!($fmt
, "\n"))
403 ($dst
:expr
, $fmt
:expr
, $
($arg
:tt
)*) => (
404 write
!($dst
, concat
!($fmt
, "\n"), $
($arg
)*)
408 /// A utility macro for indicating unreachable code.
410 /// This is useful any time that the compiler can't determine that some code is unreachable. For
413 /// * Match arms with guard conditions.
414 /// * Loops that dynamically terminate.
415 /// * Iterators that dynamically terminate.
419 /// This will always panic.
426 /// # #[allow(dead_code)]
427 /// fn foo(x: Option<i32>) {
429 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
430 /// Some(n) if n < 0 => println!("Some(Negative)"),
431 /// Some(_) => unreachable!(), // compile error if commented out
432 /// None => println!("None")
440 /// # #[allow(dead_code)]
441 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
443 /// if 3*i < i { panic!("u32 overflow"); }
444 /// if x < 3*i { return i-1; }
450 #[stable(feature = "core", since = "1.6.0")]
451 macro_rules
! unreachable
{
453 panic
!("internal error: entered unreachable code")
456 unreachable
!("{}", $msg
)
458 ($fmt
:expr
, $
($arg
:tt
)*) => ({
459 panic
!(concat
!("internal error: entered unreachable code: ", $fmt
), $
($arg
)*)
463 /// A standardized placeholder for marking unfinished code. It panics with the
464 /// message `"not yet implemented"` when executed.
466 /// This can be useful if you are prototyping and are just looking to have your
467 /// code typecheck, or if you're implementing a trait that requires multiple
468 /// methods, and you're only planning on using one of them.
472 /// Here's an example of some in-progress code. We have a trait `Foo`:
481 /// We want to implement `Foo` on one of our types, but we also want to work on
482 /// just `bar()` first. In order for our code to compile, we need to implement
483 /// `baz()`, so we can use `unimplemented!`:
492 /// impl Foo for MyStruct {
494 /// // implementation goes here
498 /// // let's not worry about implementing baz() for now
499 /// unimplemented!();
504 /// let s = MyStruct;
507 /// // we aren't even using baz() yet, so this is fine.
511 #[stable(feature = "core", since = "1.6.0")]
512 macro_rules
! unimplemented
{
513 () => (panic
!("not yet implemented"))
516 /// Built-in macros to the compiler itself.
518 /// These macros do not have any corresponding definition with a `macro_rules!`
519 /// macro, but are documented here. Their implementations can be found hardcoded
520 /// into libsyntax itself.
522 /// For more information, see documentation for `std`'s macros.
524 /// The core macro for formatted string creation & output.
526 /// For more information, see the documentation for [`std::format_args!`].
528 /// [`std::format_args!`]: ../std/macro.format_args.html
529 #[stable(feature = "rust1", since = "1.0.0")]
532 macro_rules
! format_args
{ ($fmt
:expr
, $
($args
:tt
)*) => ({
533 /* compiler built-in */
536 /// Inspect an environment variable at compile time.
538 /// For more information, see the documentation for [`std::env!`].
540 /// [`std::env!`]: ../std/macro.env.html
541 #[stable(feature = "rust1", since = "1.0.0")]
544 macro_rules
! env { ($name:expr) => ({ /* compiler built-in */ }
) }
546 /// Optionally inspect an environment variable at compile time.
548 /// For more information, see the documentation for [`std::option_env!`].
550 /// [`std::option_env!`]: ../std/macro.option_env.html
551 #[stable(feature = "rust1", since = "1.0.0")]
554 macro_rules
! option_env { ($name:expr) => ({ /* compiler built-in */ }
) }
556 /// Concatenate identifiers into one identifier.
558 /// For more information, see the documentation for [`std::concat_idents!`].
560 /// [`std::concat_idents!`]: ../std/macro.concat_idents.html
561 #[unstable(feature = "concat_idents_macro", issue = "29599")]
564 macro_rules
! concat_idents
{
565 ($
($e
:ident
),*) => ({ /* compiler built-in */ }
)
568 /// Concatenates literals into a static string slice.
570 /// For more information, see the documentation for [`std::concat!`].
572 /// [`std::concat!`]: ../std/macro.concat.html
573 #[stable(feature = "rust1", since = "1.0.0")]
576 macro_rules
! concat { ($($e:expr),*) => ({ /* compiler built-in */ }
) }
578 /// A macro which expands to the line number on which it was invoked.
580 /// For more information, see the documentation for [`std::line!`].
582 /// [`std::line!`]: ../std/macro.line.html
583 #[stable(feature = "rust1", since = "1.0.0")]
586 macro_rules
! line { () => ({ /* compiler built-in */ }
) }
588 /// A macro which expands to the column number on which it was invoked.
590 /// For more information, see the documentation for [`std::column!`].
592 /// [`std::column!`]: ../std/macro.column.html
593 #[stable(feature = "rust1", since = "1.0.0")]
596 macro_rules
! column { () => ({ /* compiler built-in */ }
) }
598 /// A macro which expands to the file name from which it was invoked.
600 /// For more information, see the documentation for [`std::file!`].
602 /// [`std::file!`]: ../std/macro.file.html
603 #[stable(feature = "rust1", since = "1.0.0")]
606 macro_rules
! file { () => ({ /* compiler built-in */ }
) }
608 /// A macro which stringifies its argument.
610 /// For more information, see the documentation for [`std::stringify!`].
612 /// [`std::stringify!`]: ../std/macro.stringify.html
613 #[stable(feature = "rust1", since = "1.0.0")]
616 macro_rules
! stringify { ($t:tt) => ({ /* compiler built-in */ }
) }
618 /// Includes a utf8-encoded file as a string.
620 /// For more information, see the documentation for [`std::include_str!`].
622 /// [`std::include_str!`]: ../std/macro.include_str.html
623 #[stable(feature = "rust1", since = "1.0.0")]
626 macro_rules
! include_str { ($file:expr) => ({ /* compiler built-in */ }
) }
628 /// Includes a file as a reference to a byte array.
630 /// For more information, see the documentation for [`std::include_bytes!`].
632 /// [`std::include_bytes!`]: ../std/macro.include_bytes.html
633 #[stable(feature = "rust1", since = "1.0.0")]
636 macro_rules
! include_bytes { ($file:expr) => ({ /* compiler built-in */ }
) }
638 /// Expands to a string that represents the current module path.
640 /// For more information, see the documentation for [`std::module_path!`].
642 /// [`std::module_path!`]: ../std/macro.module_path.html
643 #[stable(feature = "rust1", since = "1.0.0")]
646 macro_rules
! module_path { () => ({ /* compiler built-in */ }
) }
648 /// Boolean evaluation of configuration flags.
650 /// For more information, see the documentation for [`std::cfg!`].
652 /// [`std::cfg!`]: ../std/macro.cfg.html
653 #[stable(feature = "rust1", since = "1.0.0")]
656 macro_rules
! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }
) }
658 /// Parse a file as an expression or an item according to the context.
660 /// For more information, see the documentation for [`std::include!`].
662 /// [`std::include!`]: ../std/macro.include.html
663 #[stable(feature = "rust1", since = "1.0.0")]
666 macro_rules
! include { ($file:expr) => ({ /* compiler built-in */ }
) }