macros.rs 19.3 KB
Newer Older
1 2 3 4 5 6 7 8 9
// 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.
10 11 12 13 14 15 16

//! Standard library macros
//!
//! This modules contains a set of macros which are exported from the standard
//! library. Each macro is available for use when linking against the standard
//! library.

17
#![experimental]
18

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/// The entry point for panic of Rust tasks.
///
/// This macro is used to inject panic into a Rust task, causing the task to
/// unwind and panic entirely. Each task's panic can be reaped as the
/// `Box<Any>` type, and the single-argument form of the `panic!` macro will be
/// the value which is transmitted.
///
/// The multi-argument form of this macro panics with a string and has the
/// `format!` syntax for building a string.
///
/// # Example
///
/// ```should_fail
/// # #![allow(unreachable_code)]
/// panic!();
/// panic!("this is a terrible mistake!");
S
Steve Klabnik 已提交
35
/// panic!(4); // panic with the value of 4 to be collected elsewhere
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
/// panic!("this is a {} {message}", "fancy", message = "message");
/// ```
#[macro_export]
macro_rules! panic {
    () => ({
        panic!("explicit panic")
    });
    ($msg:expr) => ({
        // static requires less code at runtime, more constant data
        static _FILE_LINE: (&'static str, uint) = (file!(), line!());
        ::std::rt::begin_unwind($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, uint) = (file!(), line!());
        ::std::rt::begin_unwind_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)

    });
}

59 60
/// Ensure that a boolean expression is `true` at runtime.
///
S
Steve Klabnik 已提交
61
/// This will invoke the `panic!` macro if the provided expression cannot be
62 63 64 65 66
/// evaluated to `true` at runtime.
///
/// # Example
///
/// ```
S
Steve Klabnik 已提交
67
/// // the panic message for these assertions is the stringified value of the
68 69 70 71 72 73 74 75
/// // expression given.
/// assert!(true);
/// # fn some_computation() -> bool { true }
/// assert!(some_computation());
///
/// // assert with a custom message
/// # let x = true;
/// assert!(x, "x wasn't true!");
S
Steve Klabnik 已提交
76
/// # let a = 3; let b = 27;
77 78
/// assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
79
#[macro_export]
80
macro_rules! assert {
81
    ($cond:expr) => (
82
        if !$cond {
S
Steve Klabnik 已提交
83
            panic!(concat!("assertion failed: ", stringify!($cond)))
84
        }
85 86
    );
    ($cond:expr, $($arg:expr),+) => (
87
        if !$cond {
S
Steve Klabnik 已提交
88
            panic!($($arg),+)
89
        }
90
    );
91
}
92

93 94 95
/// Asserts that two expressions are equal to each other, testing equality in
/// both directions.
///
S
Steve Klabnik 已提交
96
/// On panic, this macro will print the values of the expressions.
97 98 99 100
///
/// # Example
///
/// ```
S
Steve Klabnik 已提交
101 102
/// let a = 3;
/// let b = 1 + 2;
103 104
/// assert_eq!(a, b);
/// ```
105
#[macro_export]
106
macro_rules! assert_eq {
107 108 109
    ($left:expr , $right:expr) => ({
        match (&($left), &($right)) {
            (left_val, right_val) => {
110
                // check both directions of equality....
111 112
                if !((*left_val == *right_val) &&
                     (*right_val == *left_val)) {
S
Steve Klabnik 已提交
113
                    panic!("assertion failed: `(left == right) && (right == left)` \
114
                           (left: `{}`, right: `{}`)", *left_val, *right_val)
115 116
                }
            }
117
        }
118
    })
119
}
120

121 122
/// Ensure that a boolean expression is `true` at runtime.
///
S
Steve Klabnik 已提交
123
/// This will invoke the `panic!` macro if the provided expression cannot be
124 125 126 127 128 129 130 131 132 133
/// evaluated to `true` at runtime.
///
/// Unlike `assert!`, `debug_assert!` statements can be disabled by passing
/// `--cfg ndebug` 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.
///
/// # Example
///
/// ```
S
Steve Klabnik 已提交
134
/// // the panic message for these assertions is the stringified value of the
135 136 137 138 139 140 141 142
/// // expression given.
/// debug_assert!(true);
/// # fn some_expensive_computation() -> bool { true }
/// debug_assert!(some_expensive_computation());
///
/// // assert with a custom message
/// # let x = true;
/// debug_assert!(x, "x wasn't true!");
S
Steve Klabnik 已提交
143
/// # let a = 3; let b = 27;
144 145 146
/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
/// ```
#[macro_export]
147
macro_rules! debug_assert {
148
    ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); })
149
}
150 151 152 153

/// Asserts that two expressions are equal to each other, testing equality in
/// both directions.
///
S
Steve Klabnik 已提交
154
/// On panic, this macro will print the values of the expressions.
155 156 157 158 159 160 161 162 163
///
/// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by
/// passing `--cfg ndebug` 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.
///
/// # Example
///
/// ```
S
Steve Klabnik 已提交
164 165
/// let a = 3;
/// let b = 1 + 2;
166 167 168
/// debug_assert_eq!(a, b);
/// ```
#[macro_export]
169
macro_rules! debug_assert_eq {
170
    ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); })
171
}
172

173
/// A utility macro for indicating unreachable code.
174
///
175 176 177 178 179 180 181 182 183 184 185 186 187 188
/// 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:
189
///
190 191
/// ```rust
/// fn foo(x: Option<int>) {
A
Alex Crichton 已提交
192 193 194 195 196 197
///     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")
///     }
198 199 200 201 202 203
/// }
/// ```
///
/// Iterators:
///
/// ```rust
O
olivren 已提交
204 205 206 207
/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
///     for i in std::iter::count(0_u32, 1) {
///         if 3*i < i { panic!("u32 overflow"); }
///         if x < 3*i { return i-1; }
208 209 210
///     }
///     unreachable!();
/// }
J
Jonas Hietala 已提交
211
/// ```
212
#[macro_export]
213
macro_rules! unreachable {
214 215 216 217 218 219 220 221 222
    () => ({
        panic!("internal error: entered unreachable code")
    });
    ($msg:expr) => ({
        unreachable!("{}", $msg)
    });
    ($fmt:expr, $($arg:tt)*) => ({
        panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
    });
223
}
224

S
Steve Klabnik 已提交
225
/// A standardised placeholder for marking unfinished code. It panics with the
B
Brendan Zabarauskas 已提交
226 227
/// message `"not yet implemented"` when executed.
#[macro_export]
228
macro_rules! unimplemented {
S
Steve Klabnik 已提交
229
    () => (panic!("not yet implemented"))
230
}
B
Brendan Zabarauskas 已提交
231

232 233 234 235 236 237 238 239
/// Use the syntax described in `std::fmt` to create a value of type `String`.
/// See `std::fmt` for more information.
///
/// # Example
///
/// ```
/// format!("test");
/// format!("hello {}", "world!");
S
Steve Klabnik 已提交
240
/// format!("x = {}, y = {y}", 10, y = 30);
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
/// ```
#[macro_export]
#[stable]
macro_rules! format {
    ($($arg:tt)*) => (::std::fmt::format(format_args!($($arg)*)))
}

/// Equivalent to the `println!` macro except that a newline is not printed at
/// the end of the message.
#[macro_export]
#[stable]
macro_rules! print {
    ($($arg:tt)*) => (::std::io::stdio::print_args(format_args!($($arg)*)))
}

/// Macro for printing to a task's stdout handle.
///
/// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
/// The syntax of this macro is the same as that used for `format!`. For more
/// information, see `std::fmt` and `std::io::stdio`.
///
/// # Example
///
/// ```
/// println!("hello there!");
/// println!("format {} arguments", "some");
/// ```
#[macro_export]
#[stable]
macro_rules! println {
    ($($arg:tt)*) => (::std::io::stdio::println_args(format_args!($($arg)*)))
}

274 275 276
/// Helper macro for unwrapping `Result` values while returning early with an
/// error if the value of the expression is `Err`. For more information, see
/// `std::io`.
A
Alex Crichton 已提交
277
#[macro_export]
278
macro_rules! try {
279
    ($expr:expr) => ({
280 281
        use $crate::result::Result::{Ok, Err};

282 283
        match $expr {
            Ok(val) => val,
284
            Err(err) => return Err($crate::error::FromError::from_error(err)),
285 286
        }
    })
287
}
288

289
/// A macro to select an event from a number of receivers.
A
Alex Crichton 已提交
290 291
///
/// This macro is used to wait for the first event to occur on a number of
292 293
/// receivers. It places no restrictions on the types of receivers given to
/// this macro, this can be viewed as a heterogeneous select.
A
Alex Crichton 已提交
294 295 296 297
///
/// # Example
///
/// ```
298
/// use std::thread::Thread;
299
/// use std::sync::mpsc::channel;
300
///
301 302
/// let (tx1, rx1) = channel();
/// let (tx2, rx2) = channel();
A
Alex Crichton 已提交
303
/// # fn long_running_task() {}
S
Steve Klabnik 已提交
304
/// # fn calculate_the_answer() -> int { 42 }
A
Alex Crichton 已提交
305
///
306 307
/// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach();
/// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach();
A
Alex Crichton 已提交
308 309
///
/// select! (
310
///     _ = rx1.recv() => println!("the long running task finished first"),
311
///     answer = rx2.recv() => {
312
///         println!("the answer was: {}", answer.unwrap());
A
Alex Crichton 已提交
313 314 315 316
///     }
/// )
/// ```
///
317
/// For more information about select, see the `std::sync::mpsc::Select` structure.
A
Alex Crichton 已提交
318 319 320 321
#[macro_export]
#[experimental]
macro_rules! select {
    (
322
        $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
A
Alex Crichton 已提交
323
    ) => ({
324
        use $crate::sync::mpsc::Select;
A
Alex Crichton 已提交
325
        let sel = Select::new();
326
        $( let mut $rx = sel.handle(&$rx); )+
A
Alex Crichton 已提交
327
        unsafe {
328
            $( $rx.add(); )+
A
Alex Crichton 已提交
329 330
        }
        let ret = sel.wait();
331
        $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
A
Alex Crichton 已提交
332 333 334
        { unreachable!() }
    })
}
335 336 337 338 339 340 341

// When testing the standard library, we link to the liblog crate to get the
// logging macros. In doing so, the liblog crate was linked against the real
// version of libstd, and uses a different std::fmt module than the test crate
// uses. To get around this difference, we redefine the log!() macro here to be
// just a dumb version of what it should be.
#[cfg(test)]
342
macro_rules! log {
343 344 345
    ($lvl:expr, $($args:tt)*) => (
        if log_enabled!($lvl) { println!($($args)*) }
    )
346
}
347 348 349 350 351 352 353 354 355 356

/// Built-in macros to the compiler itself.
///
/// These macros do not have any corresponding definition with a `macro_rules!`
/// macro, but are documented here. Their implementations can be found hardcoded
/// into libsyntax itself.
#[cfg(dox)]
pub mod builtin {
    /// The core macro for formatted string creation & output.
    ///
357 358 359 360
    /// This macro produces a value of type `fmt::Arguments`. This value can be
    /// passed to the functions in `std::fmt` for performing useful functions.
    /// All other formatting macros (`format!`, `write!`, `println!`, etc) are
    /// proxied through this one.
361 362 363 364 365 366 367 368
    ///
    /// For more information, see the documentation in `std::fmt`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::fmt;
    ///
369
    /// let s = fmt::format(format_args!("hello {}", "world"));
370 371 372 373
    /// assert_eq!(s, format!("hello {}", "world"));
    ///
    /// ```
    #[macro_export]
374
    macro_rules! format_args { ($fmt:expr $($args:tt)*) => ({
375
        /* compiler built-in */
376
    }) }
377 378 379 380 381 382 383 384 385 386 387 388 389

    /// Inspect an environment variable at compile time.
    ///
    /// This macro will expand to the value of the named environment variable at
    /// compile time, yielding an expression of type `&'static str`.
    ///
    /// If the environment variable is not defined, then a compilation error
    /// will be emitted.  To not emit a compile error, use the `option_env!`
    /// macro instead.
    ///
    /// # Example
    ///
    /// ```rust
390 391
    /// let path: &'static str = env!("PATH");
    /// println!("the $PATH variable at the time of compiling was: {}", path);
392 393
    /// ```
    #[macro_export]
394
    macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412

    /// Optionally inspect an environment variable at compile time.
    ///
    /// If the named environment variable is present at compile time, this will
    /// expand into an expression of type `Option<&'static str>` whose value is
    /// `Some` of the value of the environment variable. If the environment
    /// variable is not present, then this will expand to `None`.
    ///
    /// A compile time error is never emitted when using this macro regardless
    /// of whether the environment variable is present or not.
    ///
    /// # Example
    ///
    /// ```rust
    /// let key: Option<&'static str> = option_env!("SECRET_KEY");
    /// println!("the secret key might be: {}", key);
    /// ```
    #[macro_export]
413
    macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
414 415 416 417 418 419 420 421 422 423 424 425 426 427

    /// Concatenate literals into a static byte slice.
    ///
    /// This macro takes any number of comma-separated literal expressions,
    /// yielding an expression of type `&'static [u8]` which is the
    /// concatenation (left to right) of all the literals in their byte format.
    ///
    /// This extension currently only supports string literals, character
    /// literals, and integers less than 256. The byte slice returned is the
    /// utf8-encoding of strings and characters.
    ///
    /// # Example
    ///
    /// ```
428
    /// let rust = bytes!("r", 'u', "st", 255);
N
nham 已提交
429
    /// assert_eq!(rust[1], b'u');
A
Alex Crichton 已提交
430
    /// assert_eq!(rust[4], 255);
431 432
    /// ```
    #[macro_export]
433
    macro_rules! bytes { ($($e:expr),*) => ({ /* compiler built-in */ }) }
434 435 436 437 438 439 440 441 442 443 444 445 446

    /// Concatenate identifiers into one identifier.
    ///
    /// This macro takes any number of comma-separated identifiers, and
    /// concatenates them all into one, yielding an expression which is a new
    /// identifier. Note that hygiene makes it such that this macro cannot
    /// capture local variables, and macros are only allowed in item,
    /// statement or expression position, meaning this macro may be difficult to
    /// use in some situations.
    ///
    /// # Example
    ///
    /// ```
A
Alex Crichton 已提交
447 448 449
    /// #![feature(concat_idents)]
    ///
    /// # fn main() {
450 451 452 453
    /// fn foobar() -> int { 23 }
    ///
    /// let f = concat_idents!(foo, bar);
    /// println!("{}", f());
A
Alex Crichton 已提交
454
    /// # }
455 456
    /// ```
    #[macro_export]
457 458 459
    macro_rules! concat_idents {
        ($($e:ident),*) => ({ /* compiler built-in */ })
    }
460 461 462 463 464 465 466 467 468 469 470 471 472

    /// Concatenates literals into a static string slice.
    ///
    /// This macro takes any number of comma-separated literals, yielding an
    /// expression of type `&'static str` which represents all of the literals
    /// concatenated left-to-right.
    ///
    /// Integer and floating point literals are stringified in order to be
    /// concatenated.
    ///
    /// # Example
    ///
    /// ```
S
Steve Klabnik 已提交
473
    /// let s = concat!("test", 10, 'b', true);
474 475 476
    /// assert_eq!(s, "test10btrue");
    /// ```
    #[macro_export]
477
    macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
478 479 480 481 482 483 484 485 486 487 488 489 490 491

    /// A macro which expands to the line number on which it was invoked.
    ///
    /// The expanded expression has type `uint`, and the returned line is not
    /// the invocation of the `line!()` macro itself, but rather the first macro
    /// invocation leading up to the invocation of the `line!()` macro.
    ///
    /// # Example
    ///
    /// ```
    /// let current_line = line!();
    /// println!("defined on line: {}", current_line);
    /// ```
    #[macro_export]
492
    macro_rules! line { () => ({ /* compiler built-in */ }) }
493 494 495 496

    /// A macro which expands to the column number on which it was invoked.
    ///
    /// The expanded expression has type `uint`, and the returned column is not
H
Huon Wilson 已提交
497 498
    /// the invocation of the `column!()` macro itself, but rather the first macro
    /// invocation leading up to the invocation of the `column!()` macro.
499 500 501 502
    ///
    /// # Example
    ///
    /// ```
H
Huon Wilson 已提交
503
    /// let current_col = column!();
504 505 506
    /// println!("defined on column: {}", current_col);
    /// ```
    #[macro_export]
507
    macro_rules! column { () => ({ /* compiler built-in */ }) }
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522

    /// A macro which expands to the file name from which it was invoked.
    ///
    /// The expanded expression has type `&'static str`, and the returned file
    /// is not the invocation of the `file!()` macro itself, but rather the
    /// first macro invocation leading up to the invocation of the `file!()`
    /// macro.
    ///
    /// # Example
    ///
    /// ```
    /// let this_file = file!();
    /// println!("defined in file: {}", this_file);
    /// ```
    #[macro_export]
523
    macro_rules! file { () => ({ /* compiler built-in */ }) }
524 525 526 527 528 529 530 531 532 533 534 535 536 537

    /// A macro which stringifies its argument.
    ///
    /// This macro will yield an expression of type `&'static str` which is the
    /// stringification of all the tokens passed to the macro. No restrictions
    /// are placed on the syntax of the macro invocation itself.
    ///
    /// # Example
    ///
    /// ```
    /// let one_plus_one = stringify!(1 + 1);
    /// assert_eq!(one_plus_one, "1 + 1");
    /// ```
    #[macro_export]
538
    macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
539 540 541 542 543 544 545 546 547 548 549 550 551

    /// Includes a utf8-encoded file as a string.
    ///
    /// This macro will yield an expression of type `&'static str` which is the
    /// contents of the filename specified. The file is located relative to the
    /// current file (similarly to how modules are found),
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let secret_key = include_str!("secret-key.ascii");
    /// ```
    #[macro_export]
552
    macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
553 554 555 556 557 558 559 560 561 562

    /// Includes a file as a byte slice.
    ///
    /// This macro will yield an expression of type `&'static [u8]` which is
    /// the contents of the filename specified. The file is located relative to
    /// the current file (similarly to how modules are found),
    ///
    /// # Example
    ///
    /// ```rust,ignore
C
Chris Wong 已提交
563
    /// let secret_key = include_bytes!("secret-key.bin");
564 565
    /// ```
    #[macro_export]
C
Chris Wong 已提交
566 567 568 569 570
    macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }

    /// Deprecated alias for `include_bytes!()`.
    #[macro_export]
    macro_rules! include_bin { ($file:expr) => ({ /* compiler built-in */}) }
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589

    /// Expands to a string that represents the current module path.
    ///
    /// The current module path can be thought of as the hierarchy of modules
    /// leading back up to the crate root. The first component of the path
    /// returned is the name of the crate currently being compiled.
    ///
    /// # Example
    ///
    /// ```rust
    /// mod test {
    ///     pub fn foo() {
    ///         assert!(module_path!().ends_with("test"));
    ///     }
    /// }
    ///
    /// test::foo();
    /// ```
    #[macro_export]
590
    macro_rules! module_path { () => ({ /* compiler built-in */ }) }
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610

    /// Boolean evaluation of configuration flags.
    ///
    /// In addition to the `#[cfg]` attribute, this macro is provided to allow
    /// boolean expression evaluation of configuration flags. This frequently
    /// leads to less duplicated code.
    ///
    /// The syntax given to this macro is the same syntax as the `cfg`
    /// attribute.
    ///
    /// # Example
    ///
    /// ```rust
    /// let my_directory = if cfg!(windows) {
    ///     "windows-specific-directory"
    /// } else {
    ///     "unix-directory"
    /// };
    /// ```
    #[macro_export]
611
    macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) }
612
}