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
20 /// The entry point for panic of Rust tasks.
22 /// This macro is used to inject panic into a Rust task, causing the task to
23 /// unwind and panic entirely. Each task's panic can be reaped as the
24 /// `Box<Any>` type, and the single-argument form of the `panic!` macro will be
25 /// the value which is transmitted.
27 /// The multi-argument form of this macro panics with a string and has the
28 /// `format!` syntax for building a string.
33 /// # #![allow(unreachable_code)]
35 /// panic!("this is a terrible mistake!");
36 /// panic!(4i); // panic with the value of 4 to be collected elsewhere
37 /// panic!("this is a {} {message}", "fancy", message = "message");
42 panic!("explicit panic")
45 // static requires less code at runtime, more constant data
46 static _FILE_LINE: (&'static str, uint) = (file!(), line!());
47 ::std::rt::begin_unwind($msg, &_FILE_LINE)
49 ($fmt:expr, $($arg:tt)*) => ({
50 // The leading _'s are to avoid dead code warnings if this is
51 // used inside a dead function. Just `#[allow(dead_code)]` is
52 // insufficient, since the user may have
53 // `#[forbid(dead_code)]` and which cannot be overridden.
54 static _FILE_LINE: (&'static str, uint) = (file!(), line!());
55 ::std::rt::begin_unwind_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
60 /// Ensure that a boolean expression is `true` at runtime.
62 /// This will invoke the `panic!` macro if the provided expression cannot be
63 /// evaluated to `true` at runtime.
68 /// // the panic message for these assertions is the stringified value of the
69 /// // expression given.
71 /// # fn some_computation() -> bool { true }
72 /// assert!(some_computation());
74 /// // assert with a custom message
76 /// assert!(x, "x wasn't true!");
77 /// # let a = 3i; let b = 27i;
78 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
84 panic!(concat!("assertion failed: ", stringify!($cond)))
87 ($cond:expr, $($arg:expr),+) => (
94 /// Asserts that two expressions are equal to each other, testing equality in
97 /// On panic, this macro will print the values of the expressions.
104 /// assert_eq!(a, b);
107 macro_rules! assert_eq {
108 ($left:expr , $right:expr) => ({
109 match (&($left), &($right)) {
110 (left_val, right_val) => {
111 // check both directions of equality....
112 if !((*left_val == *right_val) &&
113 (*right_val == *left_val)) {
114 panic!("assertion failed: `(left == right) && (right == left)` \
115 (left: `{}`, right: `{}`)", *left_val, *right_val)
122 /// Ensure that a boolean expression is `true` at runtime.
124 /// This will invoke the `panic!` macro if the provided expression cannot be
125 /// evaluated to `true` at runtime.
127 /// Unlike `assert!`, `debug_assert!` statements can be disabled by passing
128 /// `--cfg ndebug` to the compiler. This makes `debug_assert!` useful for
129 /// checks that are too expensive to be present in a release build but may be
130 /// helpful during development.
135 /// // the panic message for these assertions is the stringified value of the
136 /// // expression given.
137 /// debug_assert!(true);
138 /// # fn some_expensive_computation() -> bool { true }
139 /// debug_assert!(some_expensive_computation());
141 /// // assert with a custom message
143 /// debug_assert!(x, "x wasn't true!");
144 /// # let a = 3i; let b = 27i;
145 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
148 macro_rules! debug_assert {
149 ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); })
152 /// Asserts that two expressions are equal to each other, testing equality in
155 /// On panic, this macro will print the values of the expressions.
157 /// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by
158 /// passing `--cfg ndebug` to the compiler. This makes `debug_assert_eq!`
159 /// useful for checks that are too expensive to be present in a release build
160 /// but may be helpful during development.
167 /// debug_assert_eq!(a, b);
170 macro_rules! debug_assert_eq {
171 ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); })
174 /// A utility macro for indicating unreachable code.
176 /// This is useful any time that the compiler can't determine that some code is unreachable. For
179 /// * Match arms with guard conditions.
180 /// * Loops that dynamically terminate.
181 /// * Iterators that dynamically terminate.
185 /// This will always panic.
192 /// fn foo(x: Option<int>) {
194 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
195 /// Some(n) if n < 0 => println!("Some(Negative)"),
196 /// Some(_) => unreachable!(), // compile error if commented out
197 /// None => println!("None")
205 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
206 /// for i in std::iter::count(0_u32, 1) {
207 /// if 3*i < i { panic!("u32 overflow"); }
208 /// if x < 3*i { return i-1; }
214 macro_rules! unreachable {
216 panic!("internal error: entered unreachable code")
219 unreachable!("{}", $msg)
221 ($fmt:expr, $($arg:tt)*) => ({
222 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
226 /// A standardised placeholder for marking unfinished code. It panics with the
227 /// message `"not yet implemented"` when executed.
229 macro_rules! unimplemented {
230 () => (panic!("not yet implemented"))
233 /// Use the syntax described in `std::fmt` to create a value of type `String`.
234 /// See `std::fmt` for more information.
240 /// format!("hello {}", "world!");
241 /// format!("x = {}, y = {y}", 10i, y = 30i);
245 macro_rules! format {
246 ($($arg:tt)*) => (::std::fmt::format(format_args!($($arg)*)))
249 /// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
250 /// See `std::fmt` for more information.
255 /// # #![allow(unused_must_use)]
257 /// let mut w = Vec::new();
258 /// write!(&mut w, "test");
259 /// write!(&mut w, "formatted {}", "arguments");
264 ($dst:expr, $($arg:tt)*) => ((&mut *$dst).write_fmt(format_args!($($arg)*)))
267 /// Equivalent to the `write!` macro, except that a newline is appended after
268 /// the message is written.
271 macro_rules! writeln {
272 ($dst:expr, $fmt:expr $($arg:tt)*) => (
273 write!($dst, concat!($fmt, "\n") $($arg)*)
277 /// Equivalent to the `println!` macro except that a newline is not printed at
278 /// the end of the message.
282 ($($arg:tt)*) => (::std::io::stdio::print_args(format_args!($($arg)*)))
285 /// Macro for printing to a task's stdout handle.
287 /// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
288 /// The syntax of this macro is the same as that used for `format!`. For more
289 /// information, see `std::fmt` and `std::io::stdio`.
294 /// println!("hello there!");
295 /// println!("format {} arguments", "some");
299 macro_rules! println {
300 ($($arg:tt)*) => (::std::io::stdio::println_args(format_args!($($arg)*)))
303 /// Helper macro for unwrapping `Result` values while returning early with an
304 /// error if the value of the expression is `Err`. For more information, see
311 Err(err) => return Err(::std::error::FromError::from_error(err))
316 /// Create a `std::vec::Vec` containing the arguments.
320 use std::slice::BoxedSliceExt;
321 let xs: ::std::boxed::Box<[_]> = box [$($x),*];
324 ($($x:expr,)*) => (vec![$($x),*])
327 /// A macro to select an event from a number of receivers.
329 /// This macro is used to wait for the first event to occur on a number of
330 /// receivers. It places no restrictions on the types of receivers given to
331 /// this macro, this can be viewed as a heterogeneous select.
336 /// use std::thread::Thread;
337 /// use std::sync::mpsc::channel;
339 /// let (tx1, rx1) = channel();
340 /// let (tx2, rx2) = channel();
341 /// # fn long_running_task() {}
342 /// # fn calculate_the_answer() -> int { 42i }
344 /// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach();
345 /// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach();
348 /// _ = rx1.recv() => println!("the long running task finished first"),
349 /// answer = rx2.recv() => {
350 /// println!("the answer was: {}", answer.unwrap());
355 /// For more information about select, see the `std::sync::mpsc::Select` structure.
358 macro_rules! select {
360 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
362 use std::sync::mpsc::Select;
363 let sel = Select::new();
364 $( let mut $rx = sel.handle(&$rx); )+
368 let ret = sel.wait();
369 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
374 // When testing the standard library, we link to the liblog crate to get the
375 // logging macros. In doing so, the liblog crate was linked against the real
376 // version of libstd, and uses a different std::fmt module than the test crate
377 // uses. To get around this difference, we redefine the log!() macro here to be
378 // just a dumb version of what it should be.
381 ($lvl:expr, $($args:tt)*) => (
382 if log_enabled!($lvl) { println!($($args)*) }
386 /// Built-in macros to the compiler itself.
388 /// These macros do not have any corresponding definition with a `macro_rules!`
389 /// macro, but are documented here. Their implementations can be found hardcoded
390 /// into libsyntax itself.
393 /// The core macro for formatted string creation & output.
395 /// This macro produces a value of type `fmt::Arguments`. This value can be
396 /// passed to the functions in `std::fmt` for performing useful functions.
397 /// All other formatting macros (`format!`, `write!`, `println!`, etc) are
398 /// proxied through this one.
400 /// For more information, see the documentation in `std::fmt`.
407 /// let s = fmt::format(format_args!("hello {}", "world"));
408 /// assert_eq!(s, format!("hello {}", "world"));
412 macro_rules! format_args { ($fmt:expr $($args:tt)*) => ({
413 /* compiler built-in */
416 /// Inspect an environment variable at compile time.
418 /// This macro will expand to the value of the named environment variable at
419 /// compile time, yielding an expression of type `&'static str`.
421 /// If the environment variable is not defined, then a compilation error
422 /// will be emitted. To not emit a compile error, use the `option_env!`
428 /// let path: &'static str = env!("PATH");
429 /// println!("the $PATH variable at the time of compiling was: {}", path);
432 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
434 /// Optionally inspect an environment variable at compile time.
436 /// If the named environment variable is present at compile time, this will
437 /// expand into an expression of type `Option<&'static str>` whose value is
438 /// `Some` of the value of the environment variable. If the environment
439 /// variable is not present, then this will expand to `None`.
441 /// A compile time error is never emitted when using this macro regardless
442 /// of whether the environment variable is present or not.
447 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
448 /// println!("the secret key might be: {}", key);
451 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
453 /// Concatenate literals into a static byte slice.
455 /// This macro takes any number of comma-separated literal expressions,
456 /// yielding an expression of type `&'static [u8]` which is the
457 /// concatenation (left to right) of all the literals in their byte format.
459 /// This extension currently only supports string literals, character
460 /// literals, and integers less than 256. The byte slice returned is the
461 /// utf8-encoding of strings and characters.
466 /// let rust = bytes!("r", 'u', "st", 255);
467 /// assert_eq!(rust[1], b'u');
468 /// assert_eq!(rust[4], 255);
471 macro_rules! bytes { ($($e:expr),*) => ({ /* compiler built-in */ }) }
473 /// Concatenate identifiers into one identifier.
475 /// This macro takes any number of comma-separated identifiers, and
476 /// concatenates them all into one, yielding an expression which is a new
477 /// identifier. Note that hygiene makes it such that this macro cannot
478 /// capture local variables, and macros are only allowed in item,
479 /// statement or expression position, meaning this macro may be difficult to
480 /// use in some situations.
485 /// #![feature(concat_idents)]
488 /// fn foobar() -> int { 23 }
490 /// let f = concat_idents!(foo, bar);
491 /// println!("{}", f());
495 macro_rules! concat_idents {
496 ($($e:ident),*) => ({ /* compiler built-in */ })
499 /// Concatenates literals into a static string slice.
501 /// This macro takes any number of comma-separated literals, yielding an
502 /// expression of type `&'static str` which represents all of the literals
503 /// concatenated left-to-right.
505 /// Integer and floating point literals are stringified in order to be
511 /// let s = concat!("test", 10i, 'b', true);
512 /// assert_eq!(s, "test10btrue");
515 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
517 /// A macro which expands to the line number on which it was invoked.
519 /// The expanded expression has type `uint`, and the returned line is not
520 /// the invocation of the `line!()` macro itself, but rather the first macro
521 /// invocation leading up to the invocation of the `line!()` macro.
526 /// let current_line = line!();
527 /// println!("defined on line: {}", current_line);
530 macro_rules! line { () => ({ /* compiler built-in */ }) }
532 /// A macro which expands to the column number on which it was invoked.
534 /// The expanded expression has type `uint`, and the returned column is not
535 /// the invocation of the `column!()` macro itself, but rather the first macro
536 /// invocation leading up to the invocation of the `column!()` macro.
541 /// let current_col = column!();
542 /// println!("defined on column: {}", current_col);
545 macro_rules! column { () => ({ /* compiler built-in */ }) }
547 /// A macro which expands to the file name from which it was invoked.
549 /// The expanded expression has type `&'static str`, and the returned file
550 /// is not the invocation of the `file!()` macro itself, but rather the
551 /// first macro invocation leading up to the invocation of the `file!()`
557 /// let this_file = file!();
558 /// println!("defined in file: {}", this_file);
561 macro_rules! file { () => ({ /* compiler built-in */ }) }
563 /// A macro which stringifies its argument.
565 /// This macro will yield an expression of type `&'static str` which is the
566 /// stringification of all the tokens passed to the macro. No restrictions
567 /// are placed on the syntax of the macro invocation itself.
572 /// let one_plus_one = stringify!(1 + 1);
573 /// assert_eq!(one_plus_one, "1 + 1");
576 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
578 /// Includes a utf8-encoded file as a string.
580 /// This macro will yield an expression of type `&'static str` which is the
581 /// contents of the filename specified. The file is located relative to the
582 /// current file (similarly to how modules are found),
587 /// let secret_key = include_str!("secret-key.ascii");
590 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
592 /// Includes a file as a byte slice.
594 /// This macro will yield an expression of type `&'static [u8]` which is
595 /// the contents of the filename specified. The file is located relative to
596 /// the current file (similarly to how modules are found),
601 /// let secret_key = include_bytes!("secret-key.bin");
604 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
606 /// Deprecated alias for `include_bytes!()`.
608 macro_rules! include_bin { ($file:expr) => ({ /* compiler built-in */}) }
610 /// Expands to a string that represents the current module path.
612 /// The current module path can be thought of as the hierarchy of modules
613 /// leading back up to the crate root. The first component of the path
614 /// returned is the name of the crate currently being compiled.
621 /// assert!(module_path!().ends_with("test"));
628 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
630 /// Boolean evaluation of configuration flags.
632 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
633 /// boolean expression evaluation of configuration flags. This frequently
634 /// leads to less duplicated code.
636 /// The syntax given to this macro is the same syntax as the `cfg`
642 /// let my_directory = if cfg!(windows) {
643 /// "windows-specific-directory"
649 macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) }