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 //! Standard library macros
13 //! This modules contains a set of macros which are exported from the standard
14 //! library. Each macro is available for use when linking against the standard
19 /// The entry point for panic of Rust tasks.
21 /// This macro is used to inject panic into a Rust task, causing the task to
22 /// unwind and panic entirely. Each task's panic can be reaped as the
23 /// `Box<Any>` type, and the single-argument form of the `panic!` macro will be
24 /// the value which is transmitted.
26 /// The multi-argument form of this macro panics with a string and has the
27 /// `format!` syntax for building a string.
32 /// # #![allow(unreachable_code)]
34 /// panic!("this is a terrible mistake!");
35 /// panic!(4); // panic with the value of 4 to be collected elsewhere
36 /// panic!("this is a {} {message}", "fancy", message = "message");
41 panic!("explicit panic")
44 // static requires less code at runtime, more constant data
45 static _FILE_LINE: (&'static str, uint) = (file!(), line!());
46 ::std::rt::begin_unwind($msg, &_FILE_LINE)
48 ($fmt:expr, $($arg:tt)*) => ({
49 // The leading _'s are to avoid dead code warnings if this is
50 // used inside a dead function. Just `#[allow(dead_code)]` is
51 // insufficient, since the user may have
52 // `#[forbid(dead_code)]` and which cannot be overridden.
53 static _FILE_LINE: (&'static str, uint) = (file!(), line!());
54 ::std::rt::begin_unwind_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
59 /// Ensure that a boolean expression is `true` at runtime.
61 /// This will invoke the `panic!` macro if the provided expression cannot be
62 /// evaluated to `true` at runtime.
67 /// // the panic message for these assertions is the stringified value of the
68 /// // expression given.
70 /// # fn some_computation() -> bool { true }
71 /// assert!(some_computation());
73 /// // assert with a custom message
75 /// assert!(x, "x wasn't true!");
76 /// # let a = 3; let b = 27;
77 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
83 panic!(concat!("assertion failed: ", stringify!($cond)))
86 ($cond:expr, $($arg:expr),+) => (
93 /// Asserts that two expressions are equal to each other, testing equality in
96 /// On panic, this macro will print the values of the expressions.
103 /// assert_eq!(a, b);
106 macro_rules! assert_eq {
107 ($left:expr , $right:expr) => ({
108 match (&($left), &($right)) {
109 (left_val, right_val) => {
110 // check both directions of equality....
111 if !((*left_val == *right_val) &&
112 (*right_val == *left_val)) {
113 panic!("assertion failed: `(left == right) && (right == left)` \
114 (left: `{}`, right: `{}`)", *left_val, *right_val)
121 /// Ensure that a boolean expression is `true` at runtime.
123 /// This will invoke the `panic!` macro if the provided expression cannot be
124 /// evaluated to `true` at runtime.
126 /// Unlike `assert!`, `debug_assert!` statements can be disabled by passing
127 /// `--cfg ndebug` to the compiler. This makes `debug_assert!` useful for
128 /// checks that are too expensive to be present in a release build but may be
129 /// helpful during development.
134 /// // the panic message for these assertions is the stringified value of the
135 /// // expression given.
136 /// debug_assert!(true);
137 /// # fn some_expensive_computation() -> bool { true }
138 /// debug_assert!(some_expensive_computation());
140 /// // assert with a custom message
142 /// debug_assert!(x, "x wasn't true!");
143 /// # let a = 3; let b = 27;
144 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
147 macro_rules! debug_assert {
148 ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); })
151 /// Asserts that two expressions are equal to each other, testing equality in
154 /// On panic, this macro will print the values of the expressions.
156 /// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by
157 /// passing `--cfg ndebug` to the compiler. This makes `debug_assert_eq!`
158 /// useful for checks that are too expensive to be present in a release build
159 /// but may be helpful during development.
166 /// debug_assert_eq!(a, b);
169 macro_rules! debug_assert_eq {
170 ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); })
173 /// A utility macro for indicating unreachable code.
175 /// This is useful any time that the compiler can't determine that some code is unreachable. For
178 /// * Match arms with guard conditions.
179 /// * Loops that dynamically terminate.
180 /// * Iterators that dynamically terminate.
184 /// This will always panic.
191 /// fn foo(x: Option<int>) {
193 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
194 /// Some(n) if n < 0 => println!("Some(Negative)"),
195 /// Some(_) => unreachable!(), // compile error if commented out
196 /// None => println!("None")
204 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
205 /// for i in std::iter::count(0_u32, 1) {
206 /// if 3*i < i { panic!("u32 overflow"); }
207 /// if x < 3*i { return i-1; }
213 macro_rules! unreachable {
215 panic!("internal error: entered unreachable code")
218 unreachable!("{}", $msg)
220 ($fmt:expr, $($arg:tt)*) => ({
221 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
225 /// A standardised placeholder for marking unfinished code. It panics with the
226 /// message `"not yet implemented"` when executed.
228 macro_rules! unimplemented {
229 () => (panic!("not yet implemented"))
232 /// Use the syntax described in `std::fmt` to create a value of type `String`.
233 /// See `std::fmt` for more information.
239 /// format!("hello {}", "world!");
240 /// format!("x = {}, y = {y}", 10, y = 30);
244 macro_rules! format {
245 ($($arg:tt)*) => (::std::fmt::format(format_args!($($arg)*)))
248 /// Equivalent to the `println!` macro except that a newline is not printed at
249 /// the end of the message.
253 ($($arg:tt)*) => (::std::io::stdio::print_args(format_args!($($arg)*)))
256 /// Macro for printing to a task's stdout handle.
258 /// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
259 /// The syntax of this macro is the same as that used for `format!`. For more
260 /// information, see `std::fmt` and `std::io::stdio`.
265 /// println!("hello there!");
266 /// println!("format {} arguments", "some");
270 macro_rules! println {
271 ($($arg:tt)*) => (::std::io::stdio::println_args(format_args!($($arg)*)))
274 /// Helper macro for unwrapping `Result` values while returning early with an
275 /// error if the value of the expression is `Err`. For more information, see
280 use $crate::result::Result::{Ok, Err};
284 Err(err) => return Err($crate::error::FromError::from_error(err)),
289 /// A macro to select an event from a number of receivers.
291 /// This macro is used to wait for the first event to occur on a number of
292 /// receivers. It places no restrictions on the types of receivers given to
293 /// this macro, this can be viewed as a heterogeneous select.
298 /// use std::thread::Thread;
299 /// use std::sync::mpsc::channel;
301 /// let (tx1, rx1) = channel();
302 /// let (tx2, rx2) = channel();
303 /// # fn long_running_task() {}
304 /// # fn calculate_the_answer() -> int { 42 }
306 /// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach();
307 /// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach();
310 /// _ = rx1.recv() => println!("the long running task finished first"),
311 /// answer = rx2.recv() => {
312 /// println!("the answer was: {}", answer.unwrap());
317 /// For more information about select, see the `std::sync::mpsc::Select` structure.
320 macro_rules! select {
322 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
324 use $crate::sync::mpsc::Select;
325 let sel = Select::new();
326 $( let mut $rx = sel.handle(&$rx); )+
330 let ret = sel.wait();
331 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
336 // When testing the standard library, we link to the liblog crate to get the
337 // logging macros. In doing so, the liblog crate was linked against the real
338 // version of libstd, and uses a different std::fmt module than the test crate
339 // uses. To get around this difference, we redefine the log!() macro here to be
340 // just a dumb version of what it should be.
343 ($lvl:expr, $($args:tt)*) => (
344 if log_enabled!($lvl) { println!($($args)*) }
348 /// Built-in macros to the compiler itself.
350 /// These macros do not have any corresponding definition with a `macro_rules!`
351 /// macro, but are documented here. Their implementations can be found hardcoded
352 /// into libsyntax itself.
355 /// The core macro for formatted string creation & output.
357 /// This macro produces a value of type `fmt::Arguments`. This value can be
358 /// passed to the functions in `std::fmt` for performing useful functions.
359 /// All other formatting macros (`format!`, `write!`, `println!`, etc) are
360 /// proxied through this one.
362 /// For more information, see the documentation in `std::fmt`.
369 /// let s = fmt::format(format_args!("hello {}", "world"));
370 /// assert_eq!(s, format!("hello {}", "world"));
374 macro_rules! format_args { ($fmt:expr $($args:tt)*) => ({
375 /* compiler built-in */
378 /// Inspect an environment variable at compile time.
380 /// This macro will expand to the value of the named environment variable at
381 /// compile time, yielding an expression of type `&'static str`.
383 /// If the environment variable is not defined, then a compilation error
384 /// will be emitted. To not emit a compile error, use the `option_env!`
390 /// let path: &'static str = env!("PATH");
391 /// println!("the $PATH variable at the time of compiling was: {}", path);
394 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
396 /// Optionally inspect an environment variable at compile time.
398 /// If the named environment variable is present at compile time, this will
399 /// expand into an expression of type `Option<&'static str>` whose value is
400 /// `Some` of the value of the environment variable. If the environment
401 /// variable is not present, then this will expand to `None`.
403 /// A compile time error is never emitted when using this macro regardless
404 /// of whether the environment variable is present or not.
409 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
410 /// println!("the secret key might be: {}", key);
413 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
415 /// Concatenate literals into a static byte slice.
417 /// This macro takes any number of comma-separated literal expressions,
418 /// yielding an expression of type `&'static [u8]` which is the
419 /// concatenation (left to right) of all the literals in their byte format.
421 /// This extension currently only supports string literals, character
422 /// literals, and integers less than 256. The byte slice returned is the
423 /// utf8-encoding of strings and characters.
428 /// let rust = bytes!("r", 'u', "st", 255);
429 /// assert_eq!(rust[1], b'u');
430 /// assert_eq!(rust[4], 255);
433 macro_rules! bytes { ($($e:expr),*) => ({ /* compiler built-in */ }) }
435 /// Concatenate identifiers into one identifier.
437 /// This macro takes any number of comma-separated identifiers, and
438 /// concatenates them all into one, yielding an expression which is a new
439 /// identifier. Note that hygiene makes it such that this macro cannot
440 /// capture local variables, and macros are only allowed in item,
441 /// statement or expression position, meaning this macro may be difficult to
442 /// use in some situations.
447 /// #![feature(concat_idents)]
450 /// fn foobar() -> int { 23 }
452 /// let f = concat_idents!(foo, bar);
453 /// println!("{}", f());
457 macro_rules! concat_idents {
458 ($($e:ident),*) => ({ /* compiler built-in */ })
461 /// Concatenates literals into a static string slice.
463 /// This macro takes any number of comma-separated literals, yielding an
464 /// expression of type `&'static str` which represents all of the literals
465 /// concatenated left-to-right.
467 /// Integer and floating point literals are stringified in order to be
473 /// let s = concat!("test", 10, 'b', true);
474 /// assert_eq!(s, "test10btrue");
477 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
479 /// A macro which expands to the line number on which it was invoked.
481 /// The expanded expression has type `uint`, and the returned line is not
482 /// the invocation of the `line!()` macro itself, but rather the first macro
483 /// invocation leading up to the invocation of the `line!()` macro.
488 /// let current_line = line!();
489 /// println!("defined on line: {}", current_line);
492 macro_rules! line { () => ({ /* compiler built-in */ }) }
494 /// A macro which expands to the column number on which it was invoked.
496 /// The expanded expression has type `uint`, and the returned column is not
497 /// the invocation of the `column!()` macro itself, but rather the first macro
498 /// invocation leading up to the invocation of the `column!()` macro.
503 /// let current_col = column!();
504 /// println!("defined on column: {}", current_col);
507 macro_rules! column { () => ({ /* compiler built-in */ }) }
509 /// A macro which expands to the file name from which it was invoked.
511 /// The expanded expression has type `&'static str`, and the returned file
512 /// is not the invocation of the `file!()` macro itself, but rather the
513 /// first macro invocation leading up to the invocation of the `file!()`
519 /// let this_file = file!();
520 /// println!("defined in file: {}", this_file);
523 macro_rules! file { () => ({ /* compiler built-in */ }) }
525 /// A macro which stringifies its argument.
527 /// This macro will yield an expression of type `&'static str` which is the
528 /// stringification of all the tokens passed to the macro. No restrictions
529 /// are placed on the syntax of the macro invocation itself.
534 /// let one_plus_one = stringify!(1 + 1);
535 /// assert_eq!(one_plus_one, "1 + 1");
538 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
540 /// Includes a utf8-encoded file as a string.
542 /// This macro will yield an expression of type `&'static str` which is the
543 /// contents of the filename specified. The file is located relative to the
544 /// current file (similarly to how modules are found),
549 /// let secret_key = include_str!("secret-key.ascii");
552 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
554 /// Includes a file as a byte slice.
556 /// This macro will yield an expression of type `&'static [u8]` which is
557 /// the contents of the filename specified. The file is located relative to
558 /// the current file (similarly to how modules are found),
563 /// let secret_key = include_bytes!("secret-key.bin");
566 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
568 /// Deprecated alias for `include_bytes!()`.
570 macro_rules! include_bin { ($file:expr) => ({ /* compiler built-in */}) }
572 /// Expands to a string that represents the current module path.
574 /// The current module path can be thought of as the hierarchy of modules
575 /// leading back up to the crate root. The first component of the path
576 /// returned is the name of the crate currently being compiled.
583 /// assert!(module_path!().ends_with("test"));
590 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
592 /// Boolean evaluation of configuration flags.
594 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
595 /// boolean expression evaluation of configuration flags. This frequently
596 /// leads to less duplicated code.
598 /// The syntax given to this macro is the same syntax as the `cfg`
604 /// let my_directory = if cfg!(windows) {
605 /// "windows-specific-directory"
611 macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) }