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!(4); // 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 = 3; let b = 27;
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 = 3; let b = 27;
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}", 10, y = 30);
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 let xs: ::std::boxed::Box<[_]> = box [$($x),*];
321 ::std::slice::SliceExt::into_vec(xs)
323 ($($x:expr,)*) => (vec![$($x),*])
326 /// A macro to select an event from a number of receivers.
328 /// This macro is used to wait for the first event to occur on a number of
329 /// receivers. It places no restrictions on the types of receivers given to
330 /// this macro, this can be viewed as a heterogeneous select.
335 /// use std::thread::Thread;
336 /// use std::sync::mpsc::channel;
338 /// let (tx1, rx1) = channel();
339 /// let (tx2, rx2) = channel();
340 /// # fn long_running_task() {}
341 /// # fn calculate_the_answer() -> int { 42 }
343 /// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach();
344 /// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach();
347 /// _ = rx1.recv() => println!("the long running task finished first"),
348 /// answer = rx2.recv() => {
349 /// println!("the answer was: {}", answer.unwrap());
354 /// For more information about select, see the `std::sync::mpsc::Select` structure.
357 macro_rules! select {
359 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
361 use std::sync::mpsc::Select;
362 let sel = Select::new();
363 $( let mut $rx = sel.handle(&$rx); )+
367 let ret = sel.wait();
368 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
373 // When testing the standard library, we link to the liblog crate to get the
374 // logging macros. In doing so, the liblog crate was linked against the real
375 // version of libstd, and uses a different std::fmt module than the test crate
376 // uses. To get around this difference, we redefine the log!() macro here to be
377 // just a dumb version of what it should be.
380 ($lvl:expr, $($args:tt)*) => (
381 if log_enabled!($lvl) { println!($($args)*) }
385 /// Built-in macros to the compiler itself.
387 /// These macros do not have any corresponding definition with a `macro_rules!`
388 /// macro, but are documented here. Their implementations can be found hardcoded
389 /// into libsyntax itself.
392 /// The core macro for formatted string creation & output.
394 /// This macro produces a value of type `fmt::Arguments`. This value can be
395 /// passed to the functions in `std::fmt` for performing useful functions.
396 /// All other formatting macros (`format!`, `write!`, `println!`, etc) are
397 /// proxied through this one.
399 /// For more information, see the documentation in `std::fmt`.
406 /// let s = fmt::format(format_args!("hello {}", "world"));
407 /// assert_eq!(s, format!("hello {}", "world"));
411 macro_rules! format_args { ($fmt:expr $($args:tt)*) => ({
412 /* compiler built-in */
415 /// Inspect an environment variable at compile time.
417 /// This macro will expand to the value of the named environment variable at
418 /// compile time, yielding an expression of type `&'static str`.
420 /// If the environment variable is not defined, then a compilation error
421 /// will be emitted. To not emit a compile error, use the `option_env!`
427 /// let path: &'static str = env!("PATH");
428 /// println!("the $PATH variable at the time of compiling was: {}", path);
431 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
433 /// Optionally inspect an environment variable at compile time.
435 /// If the named environment variable is present at compile time, this will
436 /// expand into an expression of type `Option<&'static str>` whose value is
437 /// `Some` of the value of the environment variable. If the environment
438 /// variable is not present, then this will expand to `None`.
440 /// A compile time error is never emitted when using this macro regardless
441 /// of whether the environment variable is present or not.
446 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
447 /// println!("the secret key might be: {}", key);
450 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
452 /// Concatenate literals into a static byte slice.
454 /// This macro takes any number of comma-separated literal expressions,
455 /// yielding an expression of type `&'static [u8]` which is the
456 /// concatenation (left to right) of all the literals in their byte format.
458 /// This extension currently only supports string literals, character
459 /// literals, and integers less than 256. The byte slice returned is the
460 /// utf8-encoding of strings and characters.
465 /// let rust = bytes!("r", 'u', "st", 255);
466 /// assert_eq!(rust[1], b'u');
467 /// assert_eq!(rust[4], 255);
470 macro_rules! bytes { ($($e:expr),*) => ({ /* compiler built-in */ }) }
472 /// Concatenate identifiers into one identifier.
474 /// This macro takes any number of comma-separated identifiers, and
475 /// concatenates them all into one, yielding an expression which is a new
476 /// identifier. Note that hygiene makes it such that this macro cannot
477 /// capture local variables, and macros are only allowed in item,
478 /// statement or expression position, meaning this macro may be difficult to
479 /// use in some situations.
484 /// #![feature(concat_idents)]
487 /// fn foobar() -> int { 23 }
489 /// let f = concat_idents!(foo, bar);
490 /// println!("{}", f());
494 macro_rules! concat_idents {
495 ($($e:ident),*) => ({ /* compiler built-in */ })
498 /// Concatenates literals into a static string slice.
500 /// This macro takes any number of comma-separated literals, yielding an
501 /// expression of type `&'static str` which represents all of the literals
502 /// concatenated left-to-right.
504 /// Integer and floating point literals are stringified in order to be
510 /// let s = concat!("test", 10, 'b', true);
511 /// assert_eq!(s, "test10btrue");
514 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
516 /// A macro which expands to the line number on which it was invoked.
518 /// The expanded expression has type `uint`, and the returned line is not
519 /// the invocation of the `line!()` macro itself, but rather the first macro
520 /// invocation leading up to the invocation of the `line!()` macro.
525 /// let current_line = line!();
526 /// println!("defined on line: {}", current_line);
529 macro_rules! line { () => ({ /* compiler built-in */ }) }
531 /// A macro which expands to the column number on which it was invoked.
533 /// The expanded expression has type `uint`, and the returned column is not
534 /// the invocation of the `column!()` macro itself, but rather the first macro
535 /// invocation leading up to the invocation of the `column!()` macro.
540 /// let current_col = column!();
541 /// println!("defined on column: {}", current_col);
544 macro_rules! column { () => ({ /* compiler built-in */ }) }
546 /// A macro which expands to the file name from which it was invoked.
548 /// The expanded expression has type `&'static str`, and the returned file
549 /// is not the invocation of the `file!()` macro itself, but rather the
550 /// first macro invocation leading up to the invocation of the `file!()`
556 /// let this_file = file!();
557 /// println!("defined in file: {}", this_file);
560 macro_rules! file { () => ({ /* compiler built-in */ }) }
562 /// A macro which stringifies its argument.
564 /// This macro will yield an expression of type `&'static str` which is the
565 /// stringification of all the tokens passed to the macro. No restrictions
566 /// are placed on the syntax of the macro invocation itself.
571 /// let one_plus_one = stringify!(1 + 1);
572 /// assert_eq!(one_plus_one, "1 + 1");
575 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
577 /// Includes a utf8-encoded file as a string.
579 /// This macro will yield an expression of type `&'static str` which is the
580 /// contents of the filename specified. The file is located relative to the
581 /// current file (similarly to how modules are found),
586 /// let secret_key = include_str!("secret-key.ascii");
589 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
591 /// Includes a file as a byte slice.
593 /// This macro will yield an expression of type `&'static [u8]` which is
594 /// the contents of the filename specified. The file is located relative to
595 /// the current file (similarly to how modules are found),
600 /// let secret_key = include_bytes!("secret-key.bin");
603 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
605 /// Deprecated alias for `include_bytes!()`.
607 macro_rules! include_bin { ($file:expr) => ({ /* compiler built-in */}) }
609 /// Expands to a string that represents the current module path.
611 /// The current module path can be thought of as the hierarchy of modules
612 /// leading back up to the crate root. The first component of the path
613 /// returned is the name of the crate currently being compiled.
620 /// assert!(module_path!().ends_with("test"));
627 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
629 /// Boolean evaluation of configuration flags.
631 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
632 /// boolean expression evaluation of configuration flags. This frequently
633 /// leads to less duplicated code.
635 /// The syntax given to this macro is the same syntax as the `cfg`
641 /// let my_directory = if cfg!(windows) {
642 /// "windows-specific-directory"
648 macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) }