1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// Entry point of thread panic, for details, see std::macros #[macro_export] #[allow_internal_unstable] #[stable(feature = "core", since = "1.6.0")] macro_rules! panic { () => ( panic!("explicit panic") ); ($msg:expr) => ({ static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!()); $crate::panicking::panic(&_MSG_FILE_LINE) }); ($fmt:expr, $($arg:tt)*) => ({ // The leading _'s are to avoid dead code warnings if this is // used inside a dead function. Just `#[allow(dead_code)]` is // insufficient, since the user may have // `#[forbid(dead_code)]` and which cannot be overridden. static _FILE_LINE: (&'static str, u32) = (file!(), line!()); $crate::panicking::panic_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE) }); } /// Ensure that a boolean expression is `true` at runtime. /// /// This will invoke the `panic!` macro if the provided expression cannot be /// evaluated to `true` at runtime. /// /// Assertions are always checked in both debug and release builds, and cannot /// be disabled. See `debug_assert!` for assertions that are not enabled in /// release builds by default. /// /// Unsafe code relies on `assert!` to enforce run-time invariants that, if /// violated could lead to unsafety. /// /// Other use-cases of `assert!` include /// [testing](https://doc.rust-lang.org/book/testing.html) and enforcing /// run-time invariants in safe code (whose violation cannot result in unsafety). /// /// This macro has a second version, where a custom panic message can be provided. /// /// # Examples /// /// ``` /// // the panic message for these assertions is the stringified value of the /// // expression given. /// assert!(true); /// /// fn some_computation() -> bool { true } // a very simple function /// /// assert!(some_computation()); /// /// // assert with a custom message /// let x = true; /// assert!(x, "x wasn't true!"); /// /// let a = 3; let b = 27; /// assert!(a + b == 30, "a = {}, b = {}", a, b); /// ``` #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] macro_rules! assert { ($cond:expr) => ( if !$cond { panic!(concat!("assertion failed: ", stringify!($cond))) } ); ($cond:expr, $($arg:tt)+) => ( if !$cond { panic!($($arg)+) } ); } /// Asserts that two expressions are equal to each other. /// /// On panic, this macro will print the values of the expressions with their /// debug representations. /// /// # Examples /// /// ``` /// let a = 3; /// let b = 1 + 2; /// assert_eq!(a, b); /// ``` #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] macro_rules! assert_eq { ($left:expr , $right:expr) => ({ match (&$left, &$right) { (left_val, right_val) => { if !(*left_val == *right_val) { panic!("assertion failed: `(left == right)` \ (left: `{:?}`, right: `{:?}`)", left_val, right_val) } } } }); ($left:expr , $right:expr, $($arg:tt)*) => ({ match (&($left), &($right)) { (left_val, right_val) => { if !(*left_val == *right_val) { panic!("assertion failed: `(left == right)` \ (left: `{:?}`, right: `{:?}`): {}", left_val, right_val, format_args!($($arg)*)) } } } }); } /// Asserts that two expressions are not equal to each other. /// /// On panic, this macro will print the values of the expressions with their /// debug representations. /// /// # Examples /// /// ``` /// let a = 3; /// let b = 2; /// assert_ne!(a, b); /// ``` #[macro_export] #[stable(feature = "assert_ne", since = "1.12.0")] macro_rules! assert_ne { ($left:expr , $right:expr) => ({ match (&$left, &$right) { (left_val, right_val) => { if *left_val == *right_val { panic!("assertion failed: `(left != right)` \ (left: `{:?}`, right: `{:?}`)", left_val, right_val) } } } }); ($left:expr , $right:expr, $($arg:tt)*) => ({ match (&($left), &($right)) { (left_val, right_val) => { if *left_val == *right_val { panic!("assertion failed: `(left != right)` \ (left: `{:?}`, right: `{:?}`): {}", left_val, right_val, format_args!($($arg)*)) } } } }); } /// Ensure that a boolean expression is `true` at runtime. /// /// This will invoke the `panic!` macro if the provided expression cannot be /// evaluated to `true` at runtime. /// /// Like `assert!`, this macro also has a second version, where a custom panic /// message can be provided. /// /// Unlike `assert!`, `debug_assert!` statements are only enabled in non /// optimized builds by default. An optimized build will omit all /// `debug_assert!` statements unless `-C debug-assertions` is passed to the /// compiler. This makes `debug_assert!` useful for checks that are too /// expensive to be present in a release build but may be helpful during /// development. /// /// An unchecked assertion allows a program in an inconsistent state to keep /// running, which might have unexpected consequences but does not introduce /// unsafety as long as this only happens in safe code. The performance cost /// of assertions, is however, not measurable in general. Replacing `assert!` /// with `debug_assert!` is thus only encouraged after thorough profiling, and /// more importantly, only in safe code! /// /// # Examples /// /// ``` /// // the panic message for these assertions is the stringified value of the /// // expression given. /// debug_assert!(true); /// /// fn some_expensive_computation() -> bool { true } // a very simple function /// debug_assert!(some_expensive_computation()); /// /// // assert with a custom message /// let x = true; /// debug_assert!(x, "x wasn't true!"); /// /// let a = 3; let b = 27; /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b); /// ``` #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] macro_rules! debug_assert { ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); }) } /// Asserts that two expressions are equal to each other. /// /// On panic, this macro will print the values of the expressions with their /// debug representations. /// /// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non /// optimized builds by default. An optimized build will omit all /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the /// compiler. This makes `debug_assert_eq!` useful for checks that are too /// expensive to be present in a release build but may be helpful during /// development. /// /// # Examples /// /// ``` /// let a = 3; /// let b = 1 + 2; /// debug_assert_eq!(a, b); /// ``` #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] macro_rules! debug_assert_eq { ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); }) } /// Asserts that two expressions are not equal to each other. /// /// On panic, this macro will print the values of the expressions with their /// debug representations. /// /// Unlike `assert_ne!`, `debug_assert_ne!` statements are only enabled in non /// optimized builds by default. An optimized build will omit all /// `debug_assert_ne!` statements unless `-C debug-assertions` is passed to the /// compiler. This makes `debug_assert_ne!` useful for checks that are too /// expensive to be present in a release build but may be helpful during /// development. /// /// # Examples /// /// ``` /// let a = 3; /// let b = 2; /// debug_assert_ne!(a, b); /// ``` #[macro_export] #[stable(feature = "assert_ne", since = "1.12.0")] macro_rules! debug_assert_ne { ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_ne!($($arg)*); }) } /// Helper macro for reducing boilerplate code for matching `Result` together /// with converting downstream errors. /// /// Prefer using `?` syntax to `try!`. `?` is built in to the language and is /// more succinct than `try!`. It is the standard method for error propagation. /// /// `try!` matches the given `Result`. In case of the `Ok` variant, the /// expression has the value of the wrapped value. /// /// In case of the `Err` variant, it retrieves the inner error. `try!` then /// performs conversion using `From`. This provides automatic conversion /// between specialized errors and more general ones. The resulting /// error is then immediately returned. /// /// Because of the early return, `try!` can only be used in functions that /// return `Result`. /// /// # Examples /// /// ``` /// use std::io; /// use std::fs::File; /// use std::io::prelude::*; /// /// enum MyError { /// FileWriteError /// } /// /// impl From<io::Error> for MyError { /// fn from(e: io::Error) -> MyError { /// MyError::FileWriteError /// } /// } /// /// fn write_to_file_using_try() -> Result<(), MyError> { /// let mut file = try!(File::create("my_best_friends.txt")); /// try!(file.write_all(b"This is a list of my best friends.")); /// println!("I wrote to the file"); /// Ok(()) /// } /// // This is equivalent to: /// fn write_to_file_using_match() -> Result<(), MyError> { /// let mut file = try!(File::create("my_best_friends.txt")); /// match file.write_all(b"This is a list of my best friends.") { /// Ok(v) => v, /// Err(e) => return Err(From::from(e)), /// } /// println!("I wrote to the file"); /// Ok(()) /// } /// ``` #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] macro_rules! try { ($expr:expr) => (match $expr { $crate::result::Result::Ok(val) => val, $crate::result::Result::Err(err) => { return $crate::result::Result::Err($crate::convert::From::from(err)) } }) } /// Write formatted data into a buffer /// /// This macro accepts any value with `write_fmt` method as a writer, a format string, and a list /// of arguments to format. /// /// `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write] or /// [`std::io::Write`][io_write] traits. These are sometimes called 'writers'. /// /// Passed arguments will be formatted according to the specified format string and the resulting /// string will be passed to the writer. /// /// See [`std::fmt`][fmt] for more information on format syntax. /// /// Return value is completely dependent on the 'write_fmt' method. /// /// Common return values are: [`Result`][enum_result], [`io::Result`][type_result] /// /// [fmt]: ../std/fmt/index.html /// [fmt_write]: ../std/fmt/trait.Write.html /// [io_write]: ../std/io/trait.Write.html /// [enum_result]: ../std/result/enum.Result.html /// [type_result]: ../std/io/type.Result.html /// /// # Examples /// /// ``` /// use std::io::Write; /// /// let mut w = Vec::new(); /// write!(&mut w, "test").unwrap(); /// write!(&mut w, "formatted {}", "arguments").unwrap(); /// /// assert_eq!(w, b"testformatted arguments"); /// ``` #[macro_export] #[stable(feature = "core", since = "1.6.0")] macro_rules! write { ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*))) } /// Write formatted data into a buffer, with appending a newline. /// /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone /// (no additional CARRIAGE RETURN (`\r`/`U+000D`). /// /// This macro accepts any value with `write_fmt` method as a writer, a format string, and a list /// of arguments to format. /// /// `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write] or /// [`std::io::Write`][io_write] traits. These are sometimes called 'writers'. /// /// Passed arguments will be formatted according to the specified format string and the resulting /// string will be passed to the writer. /// /// See [`std::fmt`][fmt] for more information on format syntax. /// /// Return value is completely dependent on the 'write_fmt' method. /// /// Common return values are: [`Result`][enum_result], [`io::Result`][type_result] /// /// [fmt]: ../std/fmt/index.html /// [fmt_write]: ../std/fmt/trait.Write.html /// [io_write]: ../std/io/trait.Write.html /// [enum_result]: ../std/result/enum.Result.html /// [type_result]: ../std/io/type.Result.html /// /// # Examples /// /// ``` /// use std::io::Write; /// /// let mut w = Vec::new(); /// writeln!(&mut w, "test").unwrap(); /// writeln!(&mut w, "formatted {}", "arguments").unwrap(); /// /// assert_eq!(&w[..], "test\nformatted arguments\n".as_bytes()); /// ``` #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] macro_rules! writeln { ($dst:expr, $fmt:expr) => ( write!($dst, concat!($fmt, "\n")) ); ($dst:expr, $fmt:expr, $($arg:tt)*) => ( write!($dst, concat!($fmt, "\n"), $($arg)*) ); } /// A utility macro for indicating unreachable code. /// /// This is useful any time that the compiler can't determine that some code is unreachable. For /// example: /// /// * Match arms with guard conditions. /// * Loops that dynamically terminate. /// * Iterators that dynamically terminate. /// /// # Panics /// /// This will always panic. /// /// # Examples /// /// Match arms: /// /// ``` /// # #[allow(dead_code)] /// fn foo(x: Option<i32>) { /// match x { /// Some(n) if n >= 0 => println!("Some(Non-negative)"), /// Some(n) if n < 0 => println!("Some(Negative)"), /// Some(_) => unreachable!(), // compile error if commented out /// None => println!("None") /// } /// } /// ``` /// /// Iterators: /// /// ``` /// # #[allow(dead_code)] /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3 /// for i in 0.. { /// if 3*i < i { panic!("u32 overflow"); } /// if x < 3*i { return i-1; } /// } /// unreachable!(); /// } /// ``` #[macro_export] #[stable(feature = "core", since = "1.6.0")] macro_rules! unreachable { () => ({ panic!("internal error: entered unreachable code") }); ($msg:expr) => ({ unreachable!("{}", $msg) }); ($fmt:expr, $($arg:tt)*) => ({ panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*) }); } /// A standardized placeholder for marking unfinished code. It panics with the /// message `"not yet implemented"` when executed. /// /// This can be useful if you are prototyping and are just looking to have your /// code typecheck, or if you're implementing a trait that requires multiple /// methods, and you're only planning on using one of them. /// /// # Examples /// /// Here's an example of some in-progress code. We have a trait `Foo`: /// /// ``` /// trait Foo { /// fn bar(&self); /// fn baz(&self); /// } /// ``` /// /// We want to implement `Foo` on one of our types, but we also want to work on /// just `bar()` first. In order for our code to compile, we need to implement /// `baz()`, so we can use `unimplemented!`: /// /// ``` /// # trait Foo { /// # fn bar(&self); /// # fn baz(&self); /// # } /// struct MyStruct; /// /// impl Foo for MyStruct { /// fn bar(&self) { /// // implementation goes here /// } /// /// fn baz(&self) { /// // let's not worry about implementing baz() for now /// unimplemented!(); /// } /// } /// /// fn main() { /// let s = MyStruct; /// s.bar(); /// /// // we aren't even using baz() yet, so this is fine. /// } /// ``` #[macro_export] #[stable(feature = "core", since = "1.6.0")] macro_rules! unimplemented { () => (panic!("not yet implemented")) }