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!(4i); // 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 = 3i; let b = 27i;
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 = 3i; let b = 27i;
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}", 10i, y = 30i);
244 macro_rules! format {
245 ($($arg:tt)*) => (::std::fmt::format(format_args!($($arg)*)))
248 /// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
249 /// See `std::fmt` for more information.
254 /// # #![allow(unused_must_use)]
256 /// let mut w = Vec::new();
257 /// write!(&mut w, "test");
258 /// write!(&mut w, "formatted {}", "arguments");
263 ($dst:expr, $($arg:tt)*) => ((&mut *$dst).write_fmt(format_args!($($arg)*)))
266 /// Equivalent to the `write!` macro, except that a newline is appended after
267 /// the message is written.
270 macro_rules! writeln {
271 ($dst:expr, $fmt:expr $($arg:tt)*) => (
272 write!($dst, concat!($fmt, "\n") $($arg)*)
276 /// Equivalent to the `println!` macro except that a newline is not printed at
277 /// the end of the message.
281 ($($arg:tt)*) => (::std::io::stdio::print_args(format_args!($($arg)*)))
284 /// Macro for printing to a task's stdout handle.
286 /// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
287 /// The syntax of this macro is the same as that used for `format!`. For more
288 /// information, see `std::fmt` and `std::io::stdio`.
293 /// println!("hello there!");
294 /// println!("format {} arguments", "some");
298 macro_rules! println {
299 ($($arg:tt)*) => (::std::io::stdio::println_args(format_args!($($arg)*)))
302 /// Helper macro for unwrapping `Result` values while returning early with an
303 /// error if the value of the expression is `Err`. For more information, see
310 Err(err) => return Err(::std::error::FromError::from_error(err))
315 /// Create a `std::vec::Vec` containing the arguments.
319 let xs: ::std::boxed::Box<[_]> = box [$($x),*];
320 ::std::slice::SliceExt::into_vec(xs)
322 ($($x:expr,)*) => (vec![$($x),*])
325 /// A macro to select an event from a number of receivers.
327 /// This macro is used to wait for the first event to occur on a number of
328 /// receivers. It places no restrictions on the types of receivers given to
329 /// this macro, this can be viewed as a heterogeneous select.
334 /// use std::thread::Thread;
335 /// use std::sync::mpsc::channel;
337 /// let (tx1, rx1) = channel();
338 /// let (tx2, rx2) = channel();
339 /// # fn long_running_task() {}
340 /// # fn calculate_the_answer() -> int { 42i }
342 /// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach();
343 /// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach();
346 /// _ = rx1.recv() => println!("the long running task finished first"),
347 /// answer = rx2.recv() => {
348 /// println!("the answer was: {}", answer.unwrap());
353 /// For more information about select, see the `std::sync::mpsc::Select` structure.
356 macro_rules! select {
358 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
360 use std::sync::mpsc::Select;
361 let sel = Select::new();
362 $( let mut $rx = sel.handle(&$rx); )+
366 let ret = sel.wait();
367 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
372 // When testing the standard library, we link to the liblog crate to get the
373 // logging macros. In doing so, the liblog crate was linked against the real
374 // version of libstd, and uses a different std::fmt module than the test crate
375 // uses. To get around this difference, we redefine the log!() macro here to be
376 // just a dumb version of what it should be.
379 ($lvl:expr, $($args:tt)*) => (
380 if log_enabled!($lvl) { println!($($args)*) }
384 /// Built-in macros to the compiler itself.
386 /// These macros do not have any corresponding definition with a `macro_rules!`
387 /// macro, but are documented here. Their implementations can be found hardcoded
388 /// into libsyntax itself.
391 /// The core macro for formatted string creation & output.
393 /// This macro produces a value of type `fmt::Arguments`. This value can be
394 /// passed to the functions in `std::fmt` for performing useful functions.
395 /// All other formatting macros (`format!`, `write!`, `println!`, etc) are
396 /// proxied through this one.
398 /// For more information, see the documentation in `std::fmt`.
405 /// let s = fmt::format(format_args!("hello {}", "world"));
406 /// assert_eq!(s, format!("hello {}", "world"));
410 macro_rules! format_args { ($fmt:expr $($args:tt)*) => ({
411 /* compiler built-in */
414 /// Inspect an environment variable at compile time.
416 /// This macro will expand to the value of the named environment variable at
417 /// compile time, yielding an expression of type `&'static str`.
419 /// If the environment variable is not defined, then a compilation error
420 /// will be emitted. To not emit a compile error, use the `option_env!`
426 /// let path: &'static str = env!("PATH");
427 /// println!("the $PATH variable at the time of compiling was: {}", path);
430 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
432 /// Optionally inspect an environment variable at compile time.
434 /// If the named environment variable is present at compile time, this will
435 /// expand into an expression of type `Option<&'static str>` whose value is
436 /// `Some` of the value of the environment variable. If the environment
437 /// variable is not present, then this will expand to `None`.
439 /// A compile time error is never emitted when using this macro regardless
440 /// of whether the environment variable is present or not.
445 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
446 /// println!("the secret key might be: {}", key);
449 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
451 /// Concatenate literals into a static byte slice.
453 /// This macro takes any number of comma-separated literal expressions,
454 /// yielding an expression of type `&'static [u8]` which is the
455 /// concatenation (left to right) of all the literals in their byte format.
457 /// This extension currently only supports string literals, character
458 /// literals, and integers less than 256. The byte slice returned is the
459 /// utf8-encoding of strings and characters.
464 /// let rust = bytes!("r", 'u', "st", 255);
465 /// assert_eq!(rust[1], b'u');
466 /// assert_eq!(rust[4], 255);
469 macro_rules! bytes { ($($e:expr),*) => ({ /* compiler built-in */ }) }
471 /// Concatenate identifiers into one identifier.
473 /// This macro takes any number of comma-separated identifiers, and
474 /// concatenates them all into one, yielding an expression which is a new
475 /// identifier. Note that hygiene makes it such that this macro cannot
476 /// capture local variables, and macros are only allowed in item,
477 /// statement or expression position, meaning this macro may be difficult to
478 /// use in some situations.
483 /// #![feature(concat_idents)]
486 /// fn foobar() -> int { 23 }
488 /// let f = concat_idents!(foo, bar);
489 /// println!("{}", f());
493 macro_rules! concat_idents {
494 ($($e:ident),*) => ({ /* compiler built-in */ })
497 /// Concatenates literals into a static string slice.
499 /// This macro takes any number of comma-separated literals, yielding an
500 /// expression of type `&'static str` which represents all of the literals
501 /// concatenated left-to-right.
503 /// Integer and floating point literals are stringified in order to be
509 /// let s = concat!("test", 10i, 'b', true);
510 /// assert_eq!(s, "test10btrue");
513 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
515 /// A macro which expands to the line number on which it was invoked.
517 /// The expanded expression has type `uint`, and the returned line is not
518 /// the invocation of the `line!()` macro itself, but rather the first macro
519 /// invocation leading up to the invocation of the `line!()` macro.
524 /// let current_line = line!();
525 /// println!("defined on line: {}", current_line);
528 macro_rules! line { () => ({ /* compiler built-in */ }) }
530 /// A macro which expands to the column number on which it was invoked.
532 /// The expanded expression has type `uint`, and the returned column is not
533 /// the invocation of the `column!()` macro itself, but rather the first macro
534 /// invocation leading up to the invocation of the `column!()` macro.
539 /// let current_col = column!();
540 /// println!("defined on column: {}", current_col);
543 macro_rules! column { () => ({ /* compiler built-in */ }) }
545 /// A macro which expands to the file name from which it was invoked.
547 /// The expanded expression has type `&'static str`, and the returned file
548 /// is not the invocation of the `file!()` macro itself, but rather the
549 /// first macro invocation leading up to the invocation of the `file!()`
555 /// let this_file = file!();
556 /// println!("defined in file: {}", this_file);
559 macro_rules! file { () => ({ /* compiler built-in */ }) }
561 /// A macro which stringifies its argument.
563 /// This macro will yield an expression of type `&'static str` which is the
564 /// stringification of all the tokens passed to the macro. No restrictions
565 /// are placed on the syntax of the macro invocation itself.
570 /// let one_plus_one = stringify!(1 + 1);
571 /// assert_eq!(one_plus_one, "1 + 1");
574 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
576 /// Includes a utf8-encoded file as a string.
578 /// This macro will yield an expression of type `&'static str` which is the
579 /// contents of the filename specified. The file is located relative to the
580 /// current file (similarly to how modules are found),
585 /// let secret_key = include_str!("secret-key.ascii");
588 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
590 /// Includes a file as a byte slice.
592 /// This macro will yield an expression of type `&'static [u8]` which is
593 /// the contents of the filename specified. The file is located relative to
594 /// the current file (similarly to how modules are found),
599 /// let secret_key = include_bytes!("secret-key.bin");
602 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
604 /// Deprecated alias for `include_bytes!()`.
606 macro_rules! include_bin { ($file:expr) => ({ /* compiler built-in */}) }
608 /// Expands to a string that represents the current module path.
610 /// The current module path can be thought of as the hierarchy of modules
611 /// leading back up to the crate root. The first component of the path
612 /// returned is the name of the crate currently being compiled.
619 /// assert!(module_path!().ends_with("test"));
626 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
628 /// Boolean evaluation of configuration flags.
630 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
631 /// boolean expression evaluation of configuration flags. This frequently
632 /// leads to less duplicated code.
634 /// The syntax given to this macro is the same syntax as the `cfg`
640 /// let my_directory = if cfg!(windows) {
641 /// "windows-specific-directory"
647 macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) }