macros.rs 17.8 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
/// The entry point for panic of Rust threads.
18
///
19
/// This macro is used to inject panic into a Rust thread, causing the thread to
20 21 22
/// panic entirely. Each thread'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.
23 24
///
/// The multi-argument form of this macro panics with a string and has the
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/// `format!` syntax for building a string.
///
/// # Examples
///
/// ```should_panic
/// # #![allow(unreachable_code)]
/// panic!();
/// panic!("this is a terrible mistake!");
/// panic!(4); // panic with the value of 4 to be collected elsewhere
/// panic!("this is a {} {message}", "fancy", message = "message");
/// ```
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
#[allow_internal_unstable]
macro_rules! panic {
    () => ({
        panic!("explicit panic")
    });
    ($msg:expr) => ({
44
        $crate::rt::begin_panic($msg, {
45 46 47 48 49 50
            // static requires less code at runtime, more constant data
            static _FILE_LINE: (&'static str, u32) = (file!(), line!());
            &_FILE_LINE
        })
    });
    ($fmt:expr, $($arg:tt)+) => ({
51
        $crate::rt::begin_panic_fmt(&format_args!($fmt, $($arg)+), {
52 53 54 55 56
            // 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!());
A
Alex Crichton 已提交
57 58
            &_FILE_LINE
        })
59 60 61
    });
}

62 63
/// Macro for printing to the standard output.
///
64 65
/// Equivalent to the `println!` macro except that a newline is not printed at
/// the end of the message.
66 67 68 69
///
/// Note that stdout is frequently line-buffered by default so it may be
/// necessary to use `io::stdout().flush()` to ensure the output is emitted
/// immediately.
70
///
71 72 73
/// Use `print!` only for the primary output of your program.  Use
/// `eprint!` instead to print error and progress messages.
///
74 75 76 77
/// # Panics
///
/// Panics if writing to `io::stdout()` fails.
///
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
/// # Examples
///
/// ```
/// use std::io::{self, Write};
///
/// print!("this ");
/// print!("will ");
/// print!("be ");
/// print!("on ");
/// print!("the ");
/// print!("same ");
/// print!("line ");
///
/// io::stdout().flush().unwrap();
///
/// print!("this string has a newline, why not choose println! instead?\n");
///
/// io::stdout().flush().unwrap();
/// ```
97
#[macro_export]
B
Brian Anderson 已提交
98
#[stable(feature = "rust1", since = "1.0.0")]
99
#[allow_internal_unstable]
100
macro_rules! print {
101
    ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
102 103
}

104 105 106
/// Macro for printing to the standard output, with a newline. On all
/// platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
/// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
107
///
108 109
/// Use the `format!` syntax to write data to the standard output.
/// See `std::fmt` for more information.
110
///
111 112 113
/// Use `println!` only for the primary output of your program.  Use
/// `eprintln!` instead to print error and progress messages.
///
114 115
/// # Panics
///
Z
Zack Weinberg 已提交
116
/// Panics if writing to `io::stdout` fails.
117
///
S
Steve Klabnik 已提交
118
/// # Examples
119 120
///
/// ```
121
/// println!(); // prints just a newline
122 123 124 125
/// println!("hello there!");
/// println!("format {} arguments", "some");
/// ```
#[macro_export]
B
Brian Anderson 已提交
126
#[stable(feature = "rust1", since = "1.0.0")]
127
macro_rules! println {
128
    () => (print!("\n"));
129 130
    ($fmt:expr) => (print!(concat!($fmt, "\n")));
    ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
131 132
}

133 134 135
/// Macro for printing to the standard error.
///
/// Equivalent to the `print!` macro, except that output goes to
Z
Zack Weinberg 已提交
136
/// `io::stderr` instead of `io::stdout`.  See `print!` for
137 138 139 140 141 142 143
/// example usage.
///
/// Use `eprint!` only for error and progress messages.  Use `print!`
/// instead for the primary output of your program.
///
/// # Panics
///
Z
Zack Weinberg 已提交
144
/// Panics if writing to `io::stderr` fails.
145
#[macro_export]
146
#[stable(feature = "eprint", since = "1.19.0")]
147 148 149 150 151 152 153 154
#[allow_internal_unstable]
macro_rules! eprint {
    ($($arg:tt)*) => ($crate::io::_eprint(format_args!($($arg)*)));
}

/// Macro for printing to the standard error, with a newline.
///
/// Equivalent to the `println!` macro, except that output goes to
Z
Zack Weinberg 已提交
155
/// `io::stderr` instead of `io::stdout`.  See `println!` for
156 157 158 159 160 161 162
/// example usage.
///
/// Use `eprintln!` only for error and progress messages.  Use `println!`
/// instead for the primary output of your program.
///
/// # Panics
///
Z
Zack Weinberg 已提交
163
/// Panics if writing to `io::stderr` fails.
164
#[macro_export]
165
#[stable(feature = "eprint", since = "1.19.0")]
166 167 168 169 170 171
macro_rules! eprintln {
    () => (eprint!("\n"));
    ($fmt:expr) => (eprint!(concat!($fmt, "\n")));
    ($fmt:expr, $($arg:tt)*) => (eprint!(concat!($fmt, "\n"), $($arg)*));
}

172
/// A macro to select an event from a number of receivers.
A
Alex Crichton 已提交
173 174
///
/// This macro is used to wait for the first event to occur on a number of
175 176
/// 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 已提交
177
///
S
Steve Klabnik 已提交
178
/// # Examples
A
Alex Crichton 已提交
179 180
///
/// ```
181 182
/// #![feature(mpsc_select)]
///
A
Aaron Turon 已提交
183
/// use std::thread;
S
Steve Klabnik 已提交
184 185 186
/// use std::sync::mpsc;
///
/// // two placeholder functions for now
187
/// fn long_running_thread() {}
S
Steve Klabnik 已提交
188
/// fn calculate_the_answer() -> u32 { 42 }
189
///
S
Steve Klabnik 已提交
190 191
/// let (tx1, rx1) = mpsc::channel();
/// let (tx2, rx2) = mpsc::channel();
A
Alex Crichton 已提交
192
///
193
/// thread::spawn(move|| { long_running_thread(); tx1.send(()).unwrap(); });
A
Aaron Turon 已提交
194
/// thread::spawn(move|| { tx2.send(calculate_the_answer()).unwrap(); });
A
Alex Crichton 已提交
195
///
196
/// select! {
197
///     _ = rx1.recv() => println!("the long running thread finished first"),
198
///     answer = rx2.recv() => {
199
///         println!("the answer was: {}", answer.unwrap());
A
Alex Crichton 已提交
200
///     }
201 202 203
/// }
/// # drop(rx1.recv());
/// # drop(rx2.recv());
A
Alex Crichton 已提交
204 205
/// ```
///
206
/// For more information about select, see the `std::sync::mpsc::Select` structure.
A
Alex Crichton 已提交
207
#[macro_export]
208
#[unstable(feature = "mpsc_select", issue = "27800")]
A
Alex Crichton 已提交
209 210
macro_rules! select {
    (
211
        $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
A
Alex Crichton 已提交
212
    ) => ({
213
        use $crate::sync::mpsc::Select;
A
Alex Crichton 已提交
214
        let sel = Select::new();
215
        $( let mut $rx = sel.handle(&$rx); )+
A
Alex Crichton 已提交
216
        unsafe {
217
            $( $rx.add(); )+
A
Alex Crichton 已提交
218 219
        }
        let ret = sel.wait();
220
        $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
A
Alex Crichton 已提交
221 222 223
        { unreachable!() }
    })
}
224

225 226 227 228 229 230 231 232 233
#[cfg(test)]
macro_rules! assert_approx_eq {
    ($a:expr, $b:expr) => ({
        let (a, b) = (&$a, &$b);
        assert!((*a - *b).abs() < 1.0e-6,
                "{} is not approximately equal to {}", *a, *b);
    })
}

234 235 236 237 238 239 240 241 242
/// 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.
    ///
243 244 245
    /// 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
246
    /// proxied through this one.
247
    ///
248 249 250 251 252 253 254
    /// For more information, see the documentation in [`std::fmt`].
    ///
    /// [`fmt::Arguments`]: ../std/fmt/struct.Arguments.html
    /// [`std::fmt`]: ../std/fmt/index.html
    /// [`format!`]: ../std/macro.format.html
    /// [`write!`]: ../std/macro.write.html
    /// [`println!`]: ../std/macro.println.html
255
    ///
S
Steve Klabnik 已提交
256
    /// # Examples
257
    ///
258
    /// ```
259 260
    /// use std::fmt;
    ///
261
    /// let s = fmt::format(format_args!("hello {}", "world"));
262 263 264
    /// assert_eq!(s, format!("hello {}", "world"));
    ///
    /// ```
265
    #[stable(feature = "rust1", since = "1.0.0")]
266
    #[macro_export]
A
Alex Crichton 已提交
267
    macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({
268
        /* compiler built-in */
269
    }) }
270 271 272 273 274 275 276 277 278 279

    /// 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.
    ///
S
Steve Klabnik 已提交
280
    /// # Examples
281
    ///
282
    /// ```
283 284
    /// let path: &'static str = env!("PATH");
    /// println!("the $PATH variable at the time of compiling was: {}", path);
285
    /// ```
286
    #[stable(feature = "rust1", since = "1.0.0")]
287
    #[macro_export]
288
    macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
289 290 291 292 293 294 295 296 297 298 299

    /// 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.
    ///
S
Steve Klabnik 已提交
300
    /// # Examples
301
    ///
302
    /// ```
303
    /// let key: Option<&'static str> = option_env!("SECRET_KEY");
A
Alex Crichton 已提交
304
    /// println!("the secret key might be: {:?}", key);
305
    /// ```
306
    #[stable(feature = "rust1", since = "1.0.0")]
307
    #[macro_export]
308
    macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
309 310 311 312 313 314

    /// 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
315 316 317 318
    /// capture local variables. Also, as a general rule, macros are only
    /// allowed in item, statement or expression position. That means while
    /// you may use this macro for referring to existing variables, functions or
    /// modules etc, you cannot define a new one with it.
319
    ///
S
Steve Klabnik 已提交
320
    /// # Examples
321 322
    ///
    /// ```
A
Alex Crichton 已提交
323 324
    /// #![feature(concat_idents)]
    ///
S
Steve Klabnik 已提交
325
    /// # fn main() {
S
Steve Klabnik 已提交
326
    /// fn foobar() -> u32 { 23 }
327 328 329
    ///
    /// let f = concat_idents!(foo, bar);
    /// println!("{}", f());
330 331
    ///
    /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
S
Steve Klabnik 已提交
332
    /// # }
333
    /// ```
334
    #[unstable(feature = "concat_idents_macro", issue = "29599")]
335
    #[macro_export]
336 337 338
    macro_rules! concat_idents {
        ($($e:ident),*) => ({ /* compiler built-in */ })
    }
339 340 341 342 343 344 345 346 347 348

    /// 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.
    ///
S
Steve Klabnik 已提交
349
    /// # Examples
350 351
    ///
    /// ```
T
Tobias Bucher 已提交
352
    /// let s = concat!("test", 10, 'b', true);
353 354
    /// assert_eq!(s, "test10btrue");
    /// ```
355
    #[stable(feature = "rust1", since = "1.0.0")]
356
    #[macro_export]
357
    macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
358 359 360

    /// A macro which expands to the line number on which it was invoked.
    ///
S
Steve Klabnik 已提交
361
    /// The expanded expression has type `u32`, and the returned line is not
362 363 364
    /// the invocation of the `line!()` macro itself, but rather the first macro
    /// invocation leading up to the invocation of the `line!()` macro.
    ///
S
Steve Klabnik 已提交
365
    /// # Examples
366 367 368 369 370
    ///
    /// ```
    /// let current_line = line!();
    /// println!("defined on line: {}", current_line);
    /// ```
371
    #[stable(feature = "rust1", since = "1.0.0")]
372
    #[macro_export]
373
    macro_rules! line { () => ({ /* compiler built-in */ }) }
374 375 376

    /// A macro which expands to the column number on which it was invoked.
    ///
S
Steve Klabnik 已提交
377
    /// The expanded expression has type `u32`, and the returned column is not
H
Huon Wilson 已提交
378 379
    /// the invocation of the `column!()` macro itself, but rather the first macro
    /// invocation leading up to the invocation of the `column!()` macro.
380
    ///
S
Steve Klabnik 已提交
381
    /// # Examples
382 383
    ///
    /// ```
H
Huon Wilson 已提交
384
    /// let current_col = column!();
385 386
    /// println!("defined on column: {}", current_col);
    /// ```
387
    #[stable(feature = "rust1", since = "1.0.0")]
388
    #[macro_export]
389
    macro_rules! column { () => ({ /* compiler built-in */ }) }
390 391 392 393 394 395 396 397

    /// 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.
    ///
S
Steve Klabnik 已提交
398
    /// # Examples
399 400 401 402 403
    ///
    /// ```
    /// let this_file = file!();
    /// println!("defined in file: {}", this_file);
    /// ```
404
    #[stable(feature = "rust1", since = "1.0.0")]
405
    #[macro_export]
406
    macro_rules! file { () => ({ /* compiler built-in */ }) }
407 408 409 410 411 412 413

    /// 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.
    ///
414 415 416
    /// Note that the expanded results of the input tokens may change in the
    /// future. You should be careful if you rely on the output.
    ///
S
Steve Klabnik 已提交
417
    /// # Examples
418 419 420 421 422
    ///
    /// ```
    /// let one_plus_one = stringify!(1 + 1);
    /// assert_eq!(one_plus_one, "1 + 1");
    /// ```
423
    #[stable(feature = "rust1", since = "1.0.0")]
424
    #[macro_export]
425
    macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
426 427 428

    /// Includes a utf8-encoded file as a string.
    ///
429 430 431
    /// The file is located relative to the current file. (similarly to how
    /// modules are found)
    ///
432
    /// This macro will yield an expression of type `&'static str` which is the
433
    /// contents of the file.
434
    ///
S
Steve Klabnik 已提交
435
    /// # Examples
436 437 438 439
    ///
    /// ```rust,ignore
    /// let secret_key = include_str!("secret-key.ascii");
    /// ```
440
    #[stable(feature = "rust1", since = "1.0.0")]
441
    #[macro_export]
442
    macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
443

444
    /// Includes a file as a reference to a byte array.
445
    ///
446 447 448
    /// The file is located relative to the current file. (similarly to how
    /// modules are found)
    ///
449
    /// This macro will yield an expression of type `&'static [u8; N]` which is
450
    /// the contents of the file.
451
    ///
S
Steve Klabnik 已提交
452
    /// # Examples
453 454
    ///
    /// ```rust,ignore
C
Chris Wong 已提交
455
    /// let secret_key = include_bytes!("secret-key.bin");
456
    /// ```
457
    #[stable(feature = "rust1", since = "1.0.0")]
458
    #[macro_export]
C
Chris Wong 已提交
459 460
    macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }

461 462 463 464 465 466
    /// 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.
    ///
S
Steve Klabnik 已提交
467
    /// # Examples
468
    ///
469
    /// ```
470 471 472 473 474 475 476 477
    /// mod test {
    ///     pub fn foo() {
    ///         assert!(module_path!().ends_with("test"));
    ///     }
    /// }
    ///
    /// test::foo();
    /// ```
478
    #[stable(feature = "rust1", since = "1.0.0")]
479
    #[macro_export]
480
    macro_rules! module_path { () => ({ /* compiler built-in */ }) }
481 482 483 484 485 486 487

    /// 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.
    ///
A
Alex Burka 已提交
488
    /// The syntax given to this macro is the same syntax as [the `cfg`
S
Steve Klabnik 已提交
489
    /// attribute](../book/conditional-compilation.html).
490
    ///
S
Steve Klabnik 已提交
491
    /// # Examples
492
    ///
493
    /// ```
494 495 496 497 498 499
    /// let my_directory = if cfg!(windows) {
    ///     "windows-specific-directory"
    /// } else {
    ///     "unix-directory"
    /// };
    /// ```
500
    #[stable(feature = "rust1", since = "1.0.0")]
501
    #[macro_export]
A
Alex Burka 已提交
502
    macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
S
Steve Klabnik 已提交
503

504 505
    /// Parse a file as an expression or an item according to the context.
    ///
506 507
    /// The file is located relative to the current file (similarly to how
    /// modules are found).
C
christopherdumas 已提交
508 509 510
    ///
    /// Using this macro is often a bad idea, because if the file is
    /// parsed as an expression, it is going to be placed in the
C
Corey Farwell 已提交
511
    /// surrounding code unhygienically. This could result in variables
C
christopherdumas 已提交
512 513 514
    /// or functions being different from what the file expected if
    /// there are variables or functions that have the same name in
    /// the current file.
S
Steve Klabnik 已提交
515 516 517
    ///
    /// # Examples
    ///
518 519 520 521 522
    /// Assume there are two files in the same directory with the following
    /// contents:
    ///
    /// File 'my_str.in':
    ///
S
Steve Klabnik 已提交
523
    /// ```ignore
524 525 526 527 528 529 530 531 532
    /// "Hello World!"
    /// ```
    ///
    /// File 'main.rs':
    ///
    /// ```ignore
    /// fn main() {
    ///     let my_str = include!("my_str.in");
    ///     println!("{}", my_str);
S
Steve Klabnik 已提交
533 534
    /// }
    /// ```
535 536 537
    ///
    /// Compiling 'main.rs' and running the resulting binary will print "Hello
    /// World!".
538
    #[stable(feature = "rust1", since = "1.0.0")]
S
Steve Klabnik 已提交
539
    #[macro_export]
A
Alex Burka 已提交
540
    macro_rules! include { ($file:expr) => ({ /* compiler built-in */ }) }
541
}