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 failure of rust tasks.
22 /// This macro is used to inject failure into a rust task, causing the task to
23 /// unwind and fail entirely. Each task's failure can be reaped as the
24 /// `Box<Any>` type, and the single-argument form of the `fail!` macro will be
25 /// the value which is transmitted.
27 /// The multi-argument form of this macro fails with a string and has the
28 /// `format!` syntax for building a string.
33 /// # #![allow(unreachable_code)]
35 /// fail!("this is a terrible mistake!");
36 /// fail!(4i); // fail with the value of 4 to be collected elsewhere
37 /// fail!("this is a {} {message}", "fancy", message = "message");
42 ::std::rt::begin_unwind_no_time_to_explain(file!(), line!())
45 ::std::rt::begin_unwind($msg, file!(), line!())
47 ($fmt:expr, $($arg:tt)*) => ({
48 // a closure can't have return type !, so we need a full
49 // function to pass to format_args!, *and* we need the
50 // file and line numbers right here; so an inner bare fn
51 // is our only choice.
53 // LLVM doesn't tend to inline this, presumably because begin_unwind_fmt
54 // is #[cold] and #[inline(never)] and because this is flagged as cold
55 // as returning !. We really do want this to be inlined, however,
56 // because it's just a tiny wrapper. Small wins (156K to 149K in size)
57 // were seen when forcing this to be inlined, and that number just goes
58 // up with the number of calls to fail!()
60 fn run_fmt(fmt: &::std::fmt::Arguments) -> ! {
61 ::std::rt::begin_unwind_fmt(fmt, file!(), line!())
63 format_args!(run_fmt, $fmt, $($arg)*)
67 /// Ensure that a boolean expression is `true` at runtime.
69 /// This will invoke the `fail!` macro if the provided expression cannot be
70 /// evaluated to `true` at runtime.
75 /// // the failure message for these assertions is the stringified value of the
76 /// // expression given.
78 /// # fn some_computation() -> bool { true }
79 /// assert!(some_computation());
81 /// // assert with a custom message
83 /// assert!(x, "x wasn't true!");
84 /// # let a = 3i; let b = 27i;
85 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
91 fail!("assertion failed: {:s}", stringify!($cond))
94 ($cond:expr, $($arg:expr),+) => (
101 /// Asserts that two expressions are equal to each other, testing equality in
104 /// On failure, this macro will print the values of the expressions.
111 /// assert_eq!(a, b);
114 macro_rules! assert_eq(
115 ($given:expr , $expected:expr) => ({
116 match (&($given), &($expected)) {
117 (given_val, expected_val) => {
118 // check both directions of equality....
119 if !((*given_val == *expected_val) &&
120 (*expected_val == *given_val)) {
121 fail!("assertion failed: `(left == right) && (right == left)` \
122 (left: `{}`, right: `{}`)", *given_val, *expected_val)
129 /// Ensure that a boolean expression is `true` at runtime.
131 /// This will invoke the `fail!` macro if the provided expression cannot be
132 /// evaluated to `true` at runtime.
134 /// Unlike `assert!`, `debug_assert!` statements can be disabled by passing
135 /// `--cfg ndebug` to the compiler. This makes `debug_assert!` useful for
136 /// checks that are too expensive to be present in a release build but may be
137 /// helpful during development.
142 /// // the failure message for these assertions is the stringified value of the
143 /// // expression given.
144 /// debug_assert!(true);
145 /// # fn some_expensive_computation() -> bool { true }
146 /// debug_assert!(some_expensive_computation());
148 /// // assert with a custom message
150 /// debug_assert!(x, "x wasn't true!");
151 /// # let a = 3i; let b = 27i;
152 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
155 macro_rules! debug_assert(
156 ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); })
159 /// Asserts that two expressions are equal to each other, testing equality in
162 /// On failure, this macro will print the values of the expressions.
164 /// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by
165 /// passing `--cfg ndebug` to the compiler. This makes `debug_assert_eq!`
166 /// useful for checks that are too expensive to be present in a release build
167 /// but may be helpful during development.
174 /// debug_assert_eq!(a, b);
177 macro_rules! debug_assert_eq(
178 ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); })
181 /// A utility macro for indicating unreachable code. It will fail if
182 /// executed. This is occasionally useful to put after loops that never
183 /// terminate normally, but instead directly return from a function.
188 /// struct Item { weight: uint }
190 /// fn choose_weighted_item(v: &[Item]) -> Item {
191 /// assert!(!v.is_empty());
192 /// let mut so_far = 0u;
193 /// for item in v.iter() {
194 /// so_far += item.weight;
195 /// if so_far > 100 {
199 /// // The above loop always returns, so we must hint to the
200 /// // type checker that it isn't possible to get down here
205 macro_rules! unreachable(
206 () => (fail!("internal error: entered unreachable code"))
209 /// A standardised placeholder for marking unfinished code. It fails with the
210 /// message `"not yet implemented"` when executed.
212 macro_rules! unimplemented(
213 () => (fail!("not yet implemented"))
216 /// Use the syntax described in `std::fmt` to create a value of type `String`.
217 /// See `std::fmt` for more information.
223 /// format!("hello {}", "world!");
224 /// format!("x = {}, y = {y}", 10i, y = 30i);
229 format_args!(::std::fmt::format, $($arg)*)
233 /// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
234 /// See `std::fmt` for more information.
239 /// # #![allow(unused_must_use)]
240 /// use std::io::MemWriter;
242 /// let mut w = MemWriter::new();
243 /// write!(&mut w, "test");
244 /// write!(&mut w, "formatted {}", "arguments");
248 ($dst:expr, $($arg:tt)*) => ({
249 format_args_method!($dst, write_fmt, $($arg)*)
253 /// Equivalent to the `write!` macro, except that a newline is appended after
254 /// the message is written.
256 macro_rules! writeln(
257 ($dst:expr, $fmt:expr $($arg:tt)*) => (
258 write!($dst, concat!($fmt, "\n") $($arg)*)
262 /// Equivalent to the `println!` macro except that a newline is not printed at
263 /// the end of the message.
266 ($($arg:tt)*) => (format_args!(::std::io::stdio::print_args, $($arg)*))
269 /// Macro for printing to a task's stdout handle.
271 /// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
272 /// The syntax of this macro is the same as that used for `format!`. For more
273 /// information, see `std::fmt` and `std::io::stdio`.
278 /// println!("hello there!");
279 /// println!("format {} arguments", "some");
282 macro_rules! println(
283 ($($arg:tt)*) => (format_args!(::std::io::stdio::println_args, $($arg)*))
286 /// Declare a task-local key with a specific type.
291 /// local_data_key!(my_integer: int)
293 /// my_integer.replace(Some(2));
294 /// println!("{}", my_integer.get().map(|a| *a));
297 macro_rules! local_data_key(
298 ($name:ident: $ty:ty) => (
299 static $name: ::std::local_data::Key<$ty> = &::std::local_data::Key;
301 (pub $name:ident: $ty:ty) => (
302 pub static $name: ::std::local_data::Key<$ty> = &::std::local_data::Key;
306 /// Helper macro for unwrapping `Result` values while returning early with an
307 /// error if the value of the expression is `Err`. For more information, see
311 ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
314 /// Create a `std::vec::Vec` containing the arguments.
318 // leading _ to allow empty construction without a warning.
319 let mut _temp = ::std::vec::Vec::new();
323 ($($e:expr),+,) => (vec!($($e),+))
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 /// let (tx1, rx1) = channel();
337 /// let (tx2, rx2) = channel();
338 /// # fn long_running_task() {}
339 /// # fn calculate_the_answer() -> int { 42i }
341 /// spawn(proc() { long_running_task(); tx1.send(()) });
342 /// spawn(proc() { tx2.send(calculate_the_answer()) });
345 /// () = rx1.recv() => println!("the long running task finished first"),
346 /// answer = rx2.recv() => {
347 /// println!("the answer was: {}", answer);
352 /// For more information about select, see the `std::comm::Select` structure.
355 macro_rules! select {
357 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
359 use std::comm::Select;
360 let sel = Select::new();
361 $( let mut $rx = sel.handle(&$rx); )+
365 let ret = sel.wait();
366 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
371 // When testing the standard library, we link to the liblog crate to get the
372 // logging macros. In doing so, the liblog crate was linked against the real
373 // version of libstd, and uses a different std::fmt module than the test crate
374 // uses. To get around this difference, we redefine the log!() macro here to be
375 // just a dumb version of what it should be.
378 ($lvl:expr, $($args:tt)*) => (
379 if log_enabled!($lvl) { println!($($args)*) }
383 /// Built-in macros to the compiler itself.
385 /// These macros do not have any corresponding definition with a `macro_rules!`
386 /// macro, but are documented here. Their implementations can be found hardcoded
387 /// into libsyntax itself.
390 /// The core macro for formatted string creation & output.
392 /// This macro takes as its first argument a callable expression which will
393 /// receive as its first argument a value of type `&fmt::Arguments`. This
394 /// value can be passed to the functions in `std::fmt` for performing useful
395 /// functions. All other formatting macros (`format!`, `write!`,
396 /// `println!`, etc) are proxied through this one.
398 /// For more information, see the documentation in `std::fmt`.
405 /// let s = format_args!(fmt::format, "hello {}", "world");
406 /// assert_eq!(s, format!("hello {}", "world"));
408 /// format_args!(|args| {
409 /// // pass `args` to another function, etc.
410 /// }, "hello {}", "world");
413 macro_rules! format_args( ($closure:expr, $fmt:expr $($args:tt)*) => ({
414 /* compiler built-in */
417 /// Inspect an environment variable at compile time.
419 /// This macro will expand to the value of the named environment variable at
420 /// compile time, yielding an expression of type `&'static str`.
422 /// If the environment variable is not defined, then a compilation error
423 /// will be emitted. To not emit a compile error, use the `option_env!`
429 /// let home: &'static str = env!("HOME");
430 /// println!("the home directory at the time of compiling was: {}", home);
433 macro_rules! env( ($name:expr) => ({ /* compiler built-in */ }) )
435 /// Optionally inspect an environment variable at compile time.
437 /// If the named environment variable is present at compile time, this will
438 /// expand into an expression of type `Option<&'static str>` whose value is
439 /// `Some` of the value of the environment variable. If the environment
440 /// variable is not present, then this will expand to `None`.
442 /// A compile time error is never emitted when using this macro regardless
443 /// of whether the environment variable is present or not.
448 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
449 /// println!("the secret key might be: {}", key);
452 macro_rules! option_env( ($name:expr) => ({ /* compiler built-in */ }) )
454 /// Concatenate literals into a static byte slice.
456 /// This macro takes any number of comma-separated literal expressions,
457 /// yielding an expression of type `&'static [u8]` which is the
458 /// concatenation (left to right) of all the literals in their byte format.
460 /// This extension currently only supports string literals, character
461 /// literals, and integers less than 256. The byte slice returned is the
462 /// utf8-encoding of strings and characters.
467 /// let rust = bytes!("r", 'u', "st", 255);
468 /// assert_eq!(rust[1], 'u' as u8);
469 /// assert_eq!(rust[4], 255);
472 macro_rules! bytes( ($($e:expr),*) => ({ /* compiler built-in */ }) )
474 /// Concatenate identifiers into one identifier.
476 /// This macro takes any number of comma-separated identifiers, and
477 /// concatenates them all into one, yielding an expression which is a new
478 /// identifier. Note that hygiene makes it such that this macro cannot
479 /// capture local variables, and macros are only allowed in item,
480 /// statement or expression position, meaning this macro may be difficult to
481 /// use in some situations.
486 /// #![feature(concat_idents)]
489 /// fn foobar() -> int { 23 }
491 /// let f = concat_idents!(foo, bar);
492 /// println!("{}", f());
496 macro_rules! concat_idents( ($($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", 10i, '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 `col!()` macro itself, but rather the first macro
535 /// invocation leading up to the invocation of the `col!()` macro.
540 /// let current_col = col!();
541 /// println!("defined on column: {}", current_col);
544 macro_rules! col( () => ({ /* 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_bin!("secret-key.bin");
603 macro_rules! include_bin( ($file:expr) => ({ /* compiler built-in */ }) )
605 /// Expands to a string that represents the current module path.
607 /// The current module path can be thought of as the hierarchy of modules
608 /// leading back up to the crate root. The first component of the path
609 /// returned is the name of the crate currently being compiled.
616 /// assert!(module_path!().ends_with("test"));
623 macro_rules! module_path( () => ({ /* compiler built-in */ }) )
625 /// Boolean evaluation of configuration flags.
627 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
628 /// boolean expression evaluation of configuration flags. This frequently
629 /// leads to less duplicated code.
631 /// The syntax given to this macro is the same syntax as the `cfg`
637 /// let my_directory = if cfg!(windows) {
638 /// "windows-specific-directory"
644 macro_rules! cfg( ($cfg:tt) => ({ /* compiler built-in */ }) )