macros.rs 15.1 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 20
/// This macro is used to inject panic into a Rust thread, causing the thread to
/// unwind and panic entirely. Each thread's panic can be reaped as the
21 22 23 24
/// `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
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
/// `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) => ({
        $crate::rt::begin_unwind($msg, {
            // static requires less code at runtime, more constant data
            static _FILE_LINE: (&'static str, u32) = (file!(), line!());
            &_FILE_LINE
        })
    });
    ($fmt:expr, $($arg:tt)+) => ({
        $crate::rt::begin_unwind_fmt(format_args!($fmt, $($arg)+), {
            // 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 74
/// # Panics
///
/// Panics if writing to `io::stdout()` fails.
///
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
/// # 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();
/// ```
94
#[macro_export]
B
Brian Anderson 已提交
95
#[stable(feature = "rust1", since = "1.0.0")]
96
#[allow_internal_unstable]
97
macro_rules! print {
98
    ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
99 100
}

101
/// Macro for printing to the standard output, with a newline.
102
///
103 104
/// Use the `format!` syntax to write data to the standard output.
/// See `std::fmt` for more information.
105
///
106 107 108 109
/// # Panics
///
/// Panics if writing to `io::stdout()` fails.
///
S
Steve Klabnik 已提交
110
/// # Examples
111 112 113 114 115 116
///
/// ```
/// println!("hello there!");
/// println!("format {} arguments", "some");
/// ```
#[macro_export]
B
Brian Anderson 已提交
117
#[stable(feature = "rust1", since = "1.0.0")]
118
macro_rules! println {
119 120
    ($fmt:expr) => (print!(concat!($fmt, "\n")));
    ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
121 122
}

123
/// A macro to select an event from a number of receivers.
A
Alex Crichton 已提交
124 125
///
/// This macro is used to wait for the first event to occur on a number of
126 127
/// 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 已提交
128
///
S
Steve Klabnik 已提交
129
/// # Examples
A
Alex Crichton 已提交
130 131
///
/// ```
132 133
/// #![feature(mpsc_select)]
///
A
Aaron Turon 已提交
134
/// use std::thread;
S
Steve Klabnik 已提交
135 136 137
/// use std::sync::mpsc;
///
/// // two placeholder functions for now
138
/// fn long_running_thread() {}
S
Steve Klabnik 已提交
139
/// fn calculate_the_answer() -> u32 { 42 }
140
///
S
Steve Klabnik 已提交
141 142
/// let (tx1, rx1) = mpsc::channel();
/// let (tx2, rx2) = mpsc::channel();
A
Alex Crichton 已提交
143
///
144
/// thread::spawn(move|| { long_running_thread(); tx1.send(()).unwrap(); });
A
Aaron Turon 已提交
145
/// thread::spawn(move|| { tx2.send(calculate_the_answer()).unwrap(); });
A
Alex Crichton 已提交
146
///
147
/// select! {
148
///     _ = rx1.recv() => println!("the long running thread finished first"),
149
///     answer = rx2.recv() => {
150
///         println!("the answer was: {}", answer.unwrap());
A
Alex Crichton 已提交
151
///     }
152 153 154
/// }
/// # drop(rx1.recv());
/// # drop(rx2.recv());
A
Alex Crichton 已提交
155 156
/// ```
///
157
/// For more information about select, see the `std::sync::mpsc::Select` structure.
A
Alex Crichton 已提交
158
#[macro_export]
159
#[unstable(feature = "mpsc_select", issue = "27800")]
A
Alex Crichton 已提交
160 161
macro_rules! select {
    (
162
        $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
A
Alex Crichton 已提交
163
    ) => ({
164
        use $crate::sync::mpsc::Select;
A
Alex Crichton 已提交
165
        let sel = Select::new();
166
        $( let mut $rx = sel.handle(&$rx); )+
A
Alex Crichton 已提交
167
        unsafe {
168
            $( $rx.add(); )+
A
Alex Crichton 已提交
169 170
        }
        let ret = sel.wait();
171
        $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
A
Alex Crichton 已提交
172 173 174
        { unreachable!() }
    })
}
175

176 177 178 179 180 181 182 183 184
#[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);
    })
}

185 186 187 188 189 190 191 192 193
/// 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.
    ///
194 195 196 197
    /// 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.
198 199 200
    ///
    /// For more information, see the documentation in `std::fmt`.
    ///
S
Steve Klabnik 已提交
201
    /// # Examples
202
    ///
203
    /// ```
204 205
    /// use std::fmt;
    ///
206
    /// let s = fmt::format(format_args!("hello {}", "world"));
207 208 209
    /// assert_eq!(s, format!("hello {}", "world"));
    ///
    /// ```
210
    #[stable(feature = "rust1", since = "1.0.0")]
211
    #[macro_export]
A
Alex Crichton 已提交
212
    macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({
213
        /* compiler built-in */
214
    }) }
215 216 217 218 219 220 221 222 223 224

    /// 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 已提交
225
    /// # Examples
226
    ///
227
    /// ```
228 229
    /// let path: &'static str = env!("PATH");
    /// println!("the $PATH variable at the time of compiling was: {}", path);
230
    /// ```
231
    #[stable(feature = "rust1", since = "1.0.0")]
232
    #[macro_export]
233
    macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
234 235 236 237 238 239 240 241 242 243 244

    /// 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 已提交
245
    /// # Examples
246
    ///
247
    /// ```
248
    /// let key: Option<&'static str> = option_env!("SECRET_KEY");
A
Alex Crichton 已提交
249
    /// println!("the secret key might be: {:?}", key);
250
    /// ```
251
    #[stable(feature = "rust1", since = "1.0.0")]
252
    #[macro_export]
253
    macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
254 255 256 257 258 259

    /// 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
260 261 262 263
    /// 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.
264
    ///
S
Steve Klabnik 已提交
265
    /// # Examples
266 267
    ///
    /// ```
A
Alex Crichton 已提交
268 269
    /// #![feature(concat_idents)]
    ///
S
Steve Klabnik 已提交
270
    /// # fn main() {
S
Steve Klabnik 已提交
271
    /// fn foobar() -> u32 { 23 }
272 273 274
    ///
    /// let f = concat_idents!(foo, bar);
    /// println!("{}", f());
275 276
    ///
    /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
S
Steve Klabnik 已提交
277
    /// # }
278
    /// ```
279
    #[stable(feature = "rust1", since = "1.0.0")]
280
    #[macro_export]
281 282 283
    macro_rules! concat_idents {
        ($($e:ident),*) => ({ /* compiler built-in */ })
    }
284 285 286 287 288 289 290 291 292 293

    /// 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 已提交
294
    /// # Examples
295 296
    ///
    /// ```
T
Tobias Bucher 已提交
297
    /// let s = concat!("test", 10, 'b', true);
298 299
    /// assert_eq!(s, "test10btrue");
    /// ```
300
    #[stable(feature = "rust1", since = "1.0.0")]
301
    #[macro_export]
302
    macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
303 304 305

    /// A macro which expands to the line number on which it was invoked.
    ///
S
Steve Klabnik 已提交
306
    /// The expanded expression has type `u32`, and the returned line is not
307 308 309
    /// 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 已提交
310
    /// # Examples
311 312 313 314 315
    ///
    /// ```
    /// let current_line = line!();
    /// println!("defined on line: {}", current_line);
    /// ```
316
    #[stable(feature = "rust1", since = "1.0.0")]
317
    #[macro_export]
318
    macro_rules! line { () => ({ /* compiler built-in */ }) }
319 320 321

    /// A macro which expands to the column number on which it was invoked.
    ///
S
Steve Klabnik 已提交
322
    /// The expanded expression has type `u32`, and the returned column is not
H
Huon Wilson 已提交
323 324
    /// the invocation of the `column!()` macro itself, but rather the first macro
    /// invocation leading up to the invocation of the `column!()` macro.
325
    ///
S
Steve Klabnik 已提交
326
    /// # Examples
327 328
    ///
    /// ```
H
Huon Wilson 已提交
329
    /// let current_col = column!();
330 331
    /// println!("defined on column: {}", current_col);
    /// ```
332
    #[stable(feature = "rust1", since = "1.0.0")]
333
    #[macro_export]
334
    macro_rules! column { () => ({ /* compiler built-in */ }) }
335 336 337 338 339 340 341 342

    /// 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 已提交
343
    /// # Examples
344 345 346 347 348
    ///
    /// ```
    /// let this_file = file!();
    /// println!("defined in file: {}", this_file);
    /// ```
349
    #[stable(feature = "rust1", since = "1.0.0")]
350
    #[macro_export]
351
    macro_rules! file { () => ({ /* compiler built-in */ }) }
352 353 354 355 356 357 358

    /// 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.
    ///
359 360 361
    /// 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 已提交
362
    /// # Examples
363 364 365 366 367
    ///
    /// ```
    /// let one_plus_one = stringify!(1 + 1);
    /// assert_eq!(one_plus_one, "1 + 1");
    /// ```
368
    #[stable(feature = "rust1", since = "1.0.0")]
369
    #[macro_export]
370
    macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
371 372 373 374 375 376 377

    /// 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),
    ///
S
Steve Klabnik 已提交
378
    /// # Examples
379 380 381 382
    ///
    /// ```rust,ignore
    /// let secret_key = include_str!("secret-key.ascii");
    /// ```
383
    #[stable(feature = "rust1", since = "1.0.0")]
384
    #[macro_export]
385
    macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
386

387
    /// Includes a file as a reference to a byte array.
388
    ///
389
    /// This macro will yield an expression of type `&'static [u8; N]` which is
390 391 392
    /// the contents of the filename specified. The file is located relative to
    /// the current file (similarly to how modules are found),
    ///
S
Steve Klabnik 已提交
393
    /// # Examples
394 395
    ///
    /// ```rust,ignore
C
Chris Wong 已提交
396
    /// let secret_key = include_bytes!("secret-key.bin");
397
    /// ```
398
    #[stable(feature = "rust1", since = "1.0.0")]
399
    #[macro_export]
C
Chris Wong 已提交
400 401
    macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }

402 403 404 405 406 407
    /// 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 已提交
408
    /// # Examples
409
    ///
410
    /// ```
411 412 413 414 415 416 417 418
    /// mod test {
    ///     pub fn foo() {
    ///         assert!(module_path!().ends_with("test"));
    ///     }
    /// }
    ///
    /// test::foo();
    /// ```
419
    #[stable(feature = "rust1", since = "1.0.0")]
420
    #[macro_export]
421
    macro_rules! module_path { () => ({ /* compiler built-in */ }) }
422 423 424 425 426 427 428

    /// 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 已提交
429 430
    /// The syntax given to this macro is the same syntax as [the `cfg`
    /// attribute](../reference.html#conditional-compilation).
431
    ///
S
Steve Klabnik 已提交
432
    /// # Examples
433
    ///
434
    /// ```
435 436 437 438 439 440
    /// let my_directory = if cfg!(windows) {
    ///     "windows-specific-directory"
    /// } else {
    ///     "unix-directory"
    /// };
    /// ```
441
    #[stable(feature = "rust1", since = "1.0.0")]
442
    #[macro_export]
A
Alex Burka 已提交
443
    macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
S
Steve Klabnik 已提交
444 445 446

    /// Parse the current given file as an expression.
    ///
447
    /// This is generally a bad idea, because it's going to behave unhygienically.
S
Steve Klabnik 已提交
448 449 450 451 452 453 454 455
    ///
    /// # Examples
    ///
    /// ```ignore
    /// fn foo() {
    ///     include!("/path/to/a/file")
    /// }
    /// ```
456
    #[stable(feature = "rust1", since = "1.0.0")]
S
Steve Klabnik 已提交
457
    #[macro_export]
A
Alex Burka 已提交
458
    macro_rules! include { ($file:expr) => ({ /* compiler built-in */ }) }
459
}