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 // NOTE(stage0): Remove cfg after a snapshot
22 /// The entry point for panic of Rust tasks.
24 /// This macro is used to inject panic into a Rust task, causing the task to
25 /// unwind and panic entirely. Each task's panic can be reaped as the
26 /// `Box<Any>` type, and the single-argument form of the `panic!` macro will be
27 /// the value which is transmitted.
29 /// The multi-argument form of this macro panics with a string and has the
30 /// `format!` syntax for building a string.
35 /// # #![allow(unreachable_code)]
37 /// panic!("this is a terrible mistake!");
38 /// panic!(4i); // panic with the value of 4 to be collected elsewhere
39 /// panic!("this is a {} {message}", "fancy", message = "message");
44 panic!("explicit panic")
47 // static requires less code at runtime, more constant data
48 static _FILE_LINE: (&'static str, uint) = (file!(), line!());
49 ::std::rt::begin_unwind($msg, &_FILE_LINE)
51 ($fmt:expr, $($arg:tt)*) => ({
52 // The leading _'s are to avoid dead code warnings if this is
53 // used inside a dead function. Just `#[allow(dead_code)]` is
54 // insufficient, since the user may have
55 // `#[forbid(dead_code)]` and which cannot be overridden.
56 static _FILE_LINE: (&'static str, uint) = (file!(), line!());
57 ::std::rt::begin_unwind_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
62 // NOTE(stage0): Remove macro after a snapshot
64 /// The entry point for panic of Rust tasks.
66 /// This macro is used to inject panic into a Rust task, causing the task to
67 /// unwind and panic entirely. Each task's panic can be reaped as the
68 /// `Box<Any>` type, and the single-argument form of the `panic!` macro will be
69 /// the value which is transmitted.
71 /// The multi-argument form of this macro panics with a string and has the
72 /// `format!` syntax for building a string.
77 /// # #![allow(unreachable_code)]
79 /// panic!("this is a terrible mistake!");
80 /// panic!(4i); // panic with the value of 4 to be collected elsewhere
81 /// panic!("this is a {} {message}", "fancy", message = "message");
86 panic!("explicit panic")
89 // static requires less code at runtime, more constant data
90 static _FILE_LINE: (&'static str, uint) = (file!(), line!());
91 ::std::rt::begin_unwind($msg, &_FILE_LINE)
93 ($fmt:expr, $($arg:tt)*) => ({
94 // a closure can't have return type !, so we need a full
95 // function to pass to format_args!, *and* we need the
96 // file and line numbers right here; so an inner bare fn
97 // is our only choice.
99 // LLVM doesn't tend to inline this, presumably because begin_unwind_fmt
100 // is #[cold] and #[inline(never)] and because this is flagged as cold
101 // as returning !. We really do want this to be inlined, however,
102 // because it's just a tiny wrapper. Small wins (156K to 149K in size)
103 // were seen when forcing this to be inlined, and that number just goes
104 // up with the number of calls to panic!()
106 // The leading _'s are to avoid dead code warnings if this is
107 // used inside a dead function. Just `#[allow(dead_code)]` is
108 // insufficient, since the user may have
109 // `#[forbid(dead_code)]` and which cannot be overridden.
111 fn _run_fmt(fmt: &::std::fmt::Arguments) -> ! {
112 static _FILE_LINE: (&'static str, uint) = (file!(), line!());
113 ::std::rt::begin_unwind_fmt(fmt, &_FILE_LINE)
115 format_args!(_run_fmt, $fmt, $($arg)*)
119 /// Ensure that a boolean expression is `true` at runtime.
121 /// This will invoke the `panic!` macro if the provided expression cannot be
122 /// evaluated to `true` at runtime.
127 /// // the panic message for these assertions is the stringified value of the
128 /// // expression given.
130 /// # fn some_computation() -> bool { true }
131 /// assert!(some_computation());
133 /// // assert with a custom message
135 /// assert!(x, "x wasn't true!");
136 /// # let a = 3i; let b = 27i;
137 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
140 macro_rules! assert {
143 panic!(concat!("assertion failed: ", stringify!($cond)))
146 ($cond:expr, $($arg:expr),+) => (
153 /// Asserts that two expressions are equal to each other, testing equality in
156 /// On panic, this macro will print the values of the expressions.
163 /// assert_eq!(a, b);
166 macro_rules! assert_eq {
167 ($left:expr , $right:expr) => ({
168 match (&($left), &($right)) {
169 (left_val, right_val) => {
170 // check both directions of equality....
171 if !((*left_val == *right_val) &&
172 (*right_val == *left_val)) {
173 panic!("assertion failed: `(left == right) && (right == left)` \
174 (left: `{}`, right: `{}`)", *left_val, *right_val)
181 /// Ensure that a boolean expression is `true` at runtime.
183 /// This will invoke the `panic!` macro if the provided expression cannot be
184 /// evaluated to `true` at runtime.
186 /// Unlike `assert!`, `debug_assert!` statements can be disabled by passing
187 /// `--cfg ndebug` to the compiler. This makes `debug_assert!` useful for
188 /// checks that are too expensive to be present in a release build but may be
189 /// helpful during development.
194 /// // the panic message for these assertions is the stringified value of the
195 /// // expression given.
196 /// debug_assert!(true);
197 /// # fn some_expensive_computation() -> bool { true }
198 /// debug_assert!(some_expensive_computation());
200 /// // assert with a custom message
202 /// debug_assert!(x, "x wasn't true!");
203 /// # let a = 3i; let b = 27i;
204 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
207 macro_rules! debug_assert {
208 ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); })
211 /// Asserts that two expressions are equal to each other, testing equality in
214 /// On panic, this macro will print the values of the expressions.
216 /// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by
217 /// passing `--cfg ndebug` to the compiler. This makes `debug_assert_eq!`
218 /// useful for checks that are too expensive to be present in a release build
219 /// but may be helpful during development.
226 /// debug_assert_eq!(a, b);
229 macro_rules! debug_assert_eq {
230 ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); })
233 /// A utility macro for indicating unreachable code.
235 /// This is useful any time that the compiler can't determine that some code is unreachable. For
238 /// * Match arms with guard conditions.
239 /// * Loops that dynamically terminate.
240 /// * Iterators that dynamically terminate.
244 /// This will always panic.
251 /// fn foo(x: Option<int>) {
253 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
254 /// Some(n) if n < 0 => println!("Some(Negative)"),
255 /// Some(_) => unreachable!(), // compile error if commented out
256 /// None => println!("None")
264 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
265 /// for i in std::iter::count(0_u32, 1) {
266 /// if 3*i < i { panic!("u32 overflow"); }
267 /// if x < 3*i { return i-1; }
273 macro_rules! unreachable {
275 panic!("internal error: entered unreachable code")
278 unreachable!("{}", $msg)
280 ($fmt:expr, $($arg:tt)*) => ({
281 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
285 /// A standardised placeholder for marking unfinished code. It panics with the
286 /// message `"not yet implemented"` when executed.
288 macro_rules! unimplemented {
289 () => (panic!("not yet implemented"))
292 // NOTE(stage0): Remove cfg after a snapshot
294 /// Use the syntax described in `std::fmt` to create a value of type `String`.
295 /// See `std::fmt` for more information.
301 /// format!("hello {}", "world!");
302 /// format!("x = {}, y = {y}", 10i, y = 30i);
306 macro_rules! format {
307 ($($arg:tt)*) => (::std::fmt::format(format_args!($($arg)*)))
310 // NOTE(stage0): Remove macro after a snapshot
312 /// Use the syntax described in `std::fmt` to create a value of type `String`.
313 /// See `std::fmt` for more information.
319 /// format!("hello {}", "world!");
320 /// format!("x = {}, y = {y}", 10i, y = 30i);
324 macro_rules! format {
326 format_args!(::std::fmt::format, $($arg)*)
330 // NOTE(stage0): Remove cfg after a snapshot
332 /// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
333 /// See `std::fmt` for more information.
338 /// # #![allow(unused_must_use)]
340 /// let mut w = Vec::new();
341 /// write!(&mut w, "test");
342 /// write!(&mut w, "formatted {}", "arguments");
347 ($dst:expr, $($arg:tt)*) => ((&mut *$dst).write_fmt(format_args!($($arg)*)))
350 // NOTE(stage0): Remove macro after a snapshot
352 /// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
353 /// See `std::fmt` for more information.
358 /// # #![allow(unused_must_use)]
360 /// let mut w = Vec::new();
361 /// write!(&mut w, "test");
362 /// write!(&mut w, "formatted {}", "arguments");
367 ($dst:expr, $($arg:tt)*) => ({
368 let dst = &mut *$dst;
369 format_args!(|args| { dst.write_fmt(args) }, $($arg)*)
373 /// Equivalent to the `write!` macro, except that a newline is appended after
374 /// the message is written.
377 macro_rules! writeln {
378 ($dst:expr, $fmt:expr $($arg:tt)*) => (
379 write!($dst, concat!($fmt, "\n") $($arg)*)
383 // NOTE(stage0): Remove cfg after a snapshot
385 /// Equivalent to the `println!` macro except that a newline is not printed at
386 /// the end of the message.
390 ($($arg:tt)*) => (::std::io::stdio::print_args(format_args!($($arg)*)))
393 // NOTE(stage0): Remove macro after a snapshot
395 /// Equivalent to the `println!` macro except that a newline is not printed at
396 /// the end of the message.
400 ($($arg:tt)*) => (format_args!(::std::io::stdio::print_args, $($arg)*))
403 // NOTE(stage0): Remove cfg after a snapshot
405 /// Macro for printing to a task's stdout handle.
407 /// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
408 /// The syntax of this macro is the same as that used for `format!`. For more
409 /// information, see `std::fmt` and `std::io::stdio`.
414 /// println!("hello there!");
415 /// println!("format {} arguments", "some");
419 macro_rules! println {
420 ($($arg:tt)*) => (::std::io::stdio::println_args(format_args!($($arg)*)))
423 // NOTE(stage0): Remove macro after a snapshot
425 /// Macro for printing to a task's stdout handle.
427 /// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
428 /// The syntax of this macro is the same as that used for `format!`. For more
429 /// information, see `std::fmt` and `std::io::stdio`.
434 /// println!("hello there!");
435 /// println!("format {} arguments", "some");
439 macro_rules! println {
440 ($($arg:tt)*) => (format_args!(::std::io::stdio::println_args, $($arg)*))
443 /// Helper macro for unwrapping `Result` values while returning early with an
444 /// error if the value of the expression is `Err`. For more information, see
451 Err(err) => return Err(::std::error::FromError::from_error(err))
456 /// Create a `std::vec::Vec` containing the arguments.
460 use std::slice::BoxedSliceExt;
461 let xs: ::std::boxed::Box<[_]> = box [$($x),*];
464 ($($x:expr,)*) => (vec![$($x),*])
467 /// A macro to select an event from a number of receivers.
469 /// This macro is used to wait for the first event to occur on a number of
470 /// receivers. It places no restrictions on the types of receivers given to
471 /// this macro, this can be viewed as a heterogeneous select.
476 /// use std::thread::Thread;
478 /// let (tx1, rx1) = channel();
479 /// let (tx2, rx2) = channel();
480 /// # fn long_running_task() {}
481 /// # fn calculate_the_answer() -> int { 42i }
483 /// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach();
484 /// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach();
487 /// () = rx1.recv() => println!("the long running task finished first"),
488 /// answer = rx2.recv() => {
489 /// println!("the answer was: {}", answer);
494 /// For more information about select, see the `std::comm::Select` structure.
497 macro_rules! select {
499 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
501 use std::comm::Select;
502 let sel = Select::new();
503 $( let mut $rx = sel.handle(&$rx); )+
507 let ret = sel.wait();
508 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
513 // When testing the standard library, we link to the liblog crate to get the
514 // logging macros. In doing so, the liblog crate was linked against the real
515 // version of libstd, and uses a different std::fmt module than the test crate
516 // uses. To get around this difference, we redefine the log!() macro here to be
517 // just a dumb version of what it should be.
520 ($lvl:expr, $($args:tt)*) => (
521 if log_enabled!($lvl) { println!($($args)*) }
525 /// Built-in macros to the compiler itself.
527 /// These macros do not have any corresponding definition with a `macro_rules!`
528 /// macro, but are documented here. Their implementations can be found hardcoded
529 /// into libsyntax itself.
532 /// The core macro for formatted string creation & output.
534 /// This macro produces a value of type `fmt::Arguments`. This value can be
535 /// passed to the functions in `std::fmt` for performing useful functions.
536 /// All other formatting macros (`format!`, `write!`, `println!`, etc) are
537 /// proxied through this one.
539 /// For more information, see the documentation in `std::fmt`.
546 /// let s = fmt::format(format_args!("hello {}", "world"));
547 /// assert_eq!(s, format!("hello {}", "world"));
551 macro_rules! format_args { ($fmt:expr $($args:tt)*) => ({
552 /* compiler built-in */
555 /// Inspect an environment variable at compile time.
557 /// This macro will expand to the value of the named environment variable at
558 /// compile time, yielding an expression of type `&'static str`.
560 /// If the environment variable is not defined, then a compilation error
561 /// will be emitted. To not emit a compile error, use the `option_env!`
567 /// let path: &'static str = env!("PATH");
568 /// println!("the $PATH variable at the time of compiling was: {}", path);
571 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
573 /// Optionally inspect an environment variable at compile time.
575 /// If the named environment variable is present at compile time, this will
576 /// expand into an expression of type `Option<&'static str>` whose value is
577 /// `Some` of the value of the environment variable. If the environment
578 /// variable is not present, then this will expand to `None`.
580 /// A compile time error is never emitted when using this macro regardless
581 /// of whether the environment variable is present or not.
586 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
587 /// println!("the secret key might be: {}", key);
590 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
592 /// Concatenate literals into a static byte slice.
594 /// This macro takes any number of comma-separated literal expressions,
595 /// yielding an expression of type `&'static [u8]` which is the
596 /// concatenation (left to right) of all the literals in their byte format.
598 /// This extension currently only supports string literals, character
599 /// literals, and integers less than 256. The byte slice returned is the
600 /// utf8-encoding of strings and characters.
605 /// let rust = bytes!("r", 'u', "st", 255);
606 /// assert_eq!(rust[1], b'u');
607 /// assert_eq!(rust[4], 255);
610 macro_rules! bytes { ($($e:expr),*) => ({ /* compiler built-in */ }) }
612 /// Concatenate identifiers into one identifier.
614 /// This macro takes any number of comma-separated identifiers, and
615 /// concatenates them all into one, yielding an expression which is a new
616 /// identifier. Note that hygiene makes it such that this macro cannot
617 /// capture local variables, and macros are only allowed in item,
618 /// statement or expression position, meaning this macro may be difficult to
619 /// use in some situations.
624 /// #![feature(concat_idents)]
627 /// fn foobar() -> int { 23 }
629 /// let f = concat_idents!(foo, bar);
630 /// println!("{}", f());
634 macro_rules! concat_idents {
635 ($($e:ident),*) => ({ /* compiler built-in */ })
638 /// Concatenates literals into a static string slice.
640 /// This macro takes any number of comma-separated literals, yielding an
641 /// expression of type `&'static str` which represents all of the literals
642 /// concatenated left-to-right.
644 /// Integer and floating point literals are stringified in order to be
650 /// let s = concat!("test", 10i, 'b', true);
651 /// assert_eq!(s, "test10btrue");
654 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
656 /// A macro which expands to the line number on which it was invoked.
658 /// The expanded expression has type `uint`, and the returned line is not
659 /// the invocation of the `line!()` macro itself, but rather the first macro
660 /// invocation leading up to the invocation of the `line!()` macro.
665 /// let current_line = line!();
666 /// println!("defined on line: {}", current_line);
669 macro_rules! line { () => ({ /* compiler built-in */ }) }
671 /// A macro which expands to the column number on which it was invoked.
673 /// The expanded expression has type `uint`, and the returned column is not
674 /// the invocation of the `column!()` macro itself, but rather the first macro
675 /// invocation leading up to the invocation of the `column!()` macro.
680 /// let current_col = column!();
681 /// println!("defined on column: {}", current_col);
684 macro_rules! column { () => ({ /* compiler built-in */ }) }
686 /// A macro which expands to the file name from which it was invoked.
688 /// The expanded expression has type `&'static str`, and the returned file
689 /// is not the invocation of the `file!()` macro itself, but rather the
690 /// first macro invocation leading up to the invocation of the `file!()`
696 /// let this_file = file!();
697 /// println!("defined in file: {}", this_file);
700 macro_rules! file { () => ({ /* compiler built-in */ }) }
702 /// A macro which stringifies its argument.
704 /// This macro will yield an expression of type `&'static str` which is the
705 /// stringification of all the tokens passed to the macro. No restrictions
706 /// are placed on the syntax of the macro invocation itself.
711 /// let one_plus_one = stringify!(1 + 1);
712 /// assert_eq!(one_plus_one, "1 + 1");
715 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
717 /// Includes a utf8-encoded file as a string.
719 /// This macro will yield an expression of type `&'static str` which is the
720 /// contents of the filename specified. The file is located relative to the
721 /// current file (similarly to how modules are found),
726 /// let secret_key = include_str!("secret-key.ascii");
729 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
731 /// Includes a file as a byte slice.
733 /// This macro will yield an expression of type `&'static [u8]` which is
734 /// the contents of the filename specified. The file is located relative to
735 /// the current file (similarly to how modules are found),
740 /// let secret_key = include_bytes!("secret-key.bin");
743 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
745 /// Deprecated alias for `include_bytes!()`.
747 macro_rules! include_bin { ($file:expr) => ({ /* compiler built-in */}) }
749 /// Expands to a string that represents the current module path.
751 /// The current module path can be thought of as the hierarchy of modules
752 /// leading back up to the crate root. The first component of the path
753 /// returned is the name of the crate currently being compiled.
760 /// assert!(module_path!().ends_with("test"));
767 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
769 /// Boolean evaluation of configuration flags.
771 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
772 /// boolean expression evaluation of configuration flags. This frequently
773 /// leads to less duplicated code.
775 /// The syntax given to this macro is the same syntax as the `cfg`
781 /// let my_directory = if cfg!(windows) {
782 /// "windows-specific-directory"
788 macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) }