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 failure of rust tasks.
21 /// This macro is used to inject failure into a rust task, causing the task to
22 /// unwind and fail entirely. Each task's failure can be reaped as the
23 /// `Box<Any>` type, and the single-argument form of the `fail!` macro will be
24 /// the value which is transmitted.
26 /// The multi-argument form of this macro fails with a string and has the
27 /// `format!` syntax for building a string.
32 /// # #![allow(unreachable_code)]
34 /// fail!("this is a terrible mistake!");
35 /// fail!(4); // fail with the value of 4 to be collected elsewhere
36 /// fail!("this is a {} {message}", "fancy", message = "message");
41 fail!("explicit failure")
44 ::std::rt::begin_unwind($msg, file!(), line!())
46 ($fmt:expr, $($arg:tt)*) => ({
47 // a closure can't have return type !, so we need a full
48 // function to pass to format_args!, *and* we need the
49 // file and line numbers right here; so an inner bare fn
50 // is our only choice.
52 // LLVM doesn't tend to inline this, presumably because begin_unwind_fmt
53 // is #[cold] and #[inline(never)] and because this is flagged as cold
54 // as returning !. We really do want this to be inlined, however,
55 // because it's just a tiny wrapper. Small wins (156K to 149K in size)
56 // were seen when forcing this to be inlined, and that number just goes
57 // up with the number of calls to fail!()
59 fn run_fmt(fmt: &::std::fmt::Arguments) -> ! {
60 ::std::rt::begin_unwind_fmt(fmt, file!(), line!())
62 format_args!(run_fmt, $fmt, $($arg)*)
66 /// Ensure that a boolean expression is `true` at runtime.
68 /// This will invoke the `fail!` macro if the provided expression cannot be
69 /// evaluated to `true` at runtime.
74 /// // the failure message for these assertions is the stringified value of the
75 /// // expression given.
77 /// # fn some_computation() -> bool { true }
78 /// assert!(some_computation());
80 /// // assert with a custom message
82 /// assert!(x, "x wasn't true!");
83 /// # let a = 3; let b = 27;
84 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
90 fail!("assertion failed: {:s}", stringify!($cond))
93 ($cond:expr, $($arg:expr),+) => (
100 /// Asserts that two expressions are equal to each other, testing equality in
103 /// On failure, this macro will print the values of the expressions.
110 /// assert_eq!(a, b);
113 macro_rules! assert_eq(
114 ($given:expr , $expected:expr) => ({
115 match (&($given), &($expected)) {
116 (given_val, expected_val) => {
117 // check both directions of equality....
118 if !((*given_val == *expected_val) &&
119 (*expected_val == *given_val)) {
120 fail!("assertion failed: `(left == right) && (right == left)` \
121 (left: `{}`, right: `{}`)", *given_val, *expected_val)
128 /// Ensure that a boolean expression is `true` at runtime.
130 /// This will invoke the `fail!` macro if the provided expression cannot be
131 /// evaluated to `true` at runtime.
133 /// Unlike `assert!`, `debug_assert!` statements can be disabled by passing
134 /// `--cfg ndebug` to the compiler. This makes `debug_assert!` useful for
135 /// checks that are too expensive to be present in a release build but may be
136 /// helpful during development.
141 /// // the failure message for these assertions is the stringified value of the
142 /// // expression given.
143 /// debug_assert!(true);
144 /// # fn some_expensive_computation() -> bool { true }
145 /// debug_assert!(some_expensive_computation());
147 /// // assert with a custom message
149 /// debug_assert!(x, "x wasn't true!");
150 /// # let a = 3; let b = 27;
151 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
154 macro_rules! debug_assert(
155 ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); })
158 /// Asserts that two expressions are equal to each other, testing equality in
161 /// On failure, this macro will print the values of the expressions.
163 /// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by
164 /// passing `--cfg ndebug` to the compiler. This makes `debug_assert_eq!`
165 /// useful for checks that are too expensive to be present in a release build
166 /// but may be helpful during development.
173 /// debug_assert_eq!(a, b);
176 macro_rules! debug_assert_eq(
177 ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); })
180 /// A utility macro for indicating unreachable code. It will fail if
181 /// executed. This is occasionally useful to put after loops that never
182 /// terminate normally, but instead directly return from a function.
187 /// struct Item { weight: uint }
189 /// fn choose_weighted_item(v: &[Item]) -> Item {
190 /// assert!(!v.is_empty());
191 /// let mut so_far = 0u;
192 /// for item in v.iter() {
193 /// so_far += item.weight;
194 /// if so_far > 100 {
198 /// // The above loop always returns, so we must hint to the
199 /// // type checker that it isn't possible to get down here
204 macro_rules! unreachable(
205 () => (fail!("internal error: entered unreachable code"))
208 /// A standardised placeholder for marking unfinished code. It fails with the
209 /// message `"not yet implemented"` when executed.
211 macro_rules! unimplemented(
212 () => (fail!("not yet implemented"))
215 /// Use the syntax described in `std::fmt` to create a value of type `~str`.
216 /// See `std::fmt` for more information.
222 /// format!("hello {}", "world!");
223 /// format!("x = {}, y = {y}", 10, y = 30);
228 format_args!(::std::fmt::format, $($arg)*)
232 /// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
233 /// See `std::fmt` for more information.
238 /// # #![allow(unused_must_use)]
239 /// use std::io::MemWriter;
241 /// let mut w = MemWriter::new();
242 /// write!(&mut w, "test");
243 /// write!(&mut w, "formatted {}", "arguments");
247 ($dst:expr, $($arg:tt)*) => ({
248 format_args_method!($dst, write_fmt, $($arg)*)
252 /// Equivalent to the `write!` macro, except that a newline is appended after
253 /// the message is written.
255 macro_rules! writeln(
256 ($dst:expr, $fmt:expr $($arg:tt)*) => (
257 write!($dst, concat!($fmt, "\n") $($arg)*)
261 /// Equivalent to the `println!` macro except that a newline is not printed at
262 /// the end of the message.
265 ($($arg:tt)*) => (format_args!(::std::io::stdio::print_args, $($arg)*))
268 /// Macro for printing to a task's stdout handle.
270 /// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
271 /// The syntax of this macro is the same as that used for `format!`. For more
272 /// information, see `std::fmt` and `std::io::stdio`.
277 /// println!("hello there!");
278 /// println!("format {} arguments", "some");
281 macro_rules! println(
282 ($($arg:tt)*) => (format_args!(::std::io::stdio::println_args, $($arg)*))
285 /// Declare a task-local key with a specific type.
290 /// local_data_key!(my_integer: int)
292 /// my_integer.replace(Some(2));
293 /// println!("{}", my_integer.get().map(|a| *a));
296 macro_rules! local_data_key(
297 ($name:ident: $ty:ty) => (
298 static $name: ::std::local_data::Key<$ty> = &::std::local_data::Key;
300 (pub $name:ident: $ty:ty) => (
301 pub static $name: ::std::local_data::Key<$ty> = &::std::local_data::Key;
305 /// Helper macro for unwrapping `Result` values while returning early with an
306 /// error if the value of the expression is `Err`. For more information, see
310 ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
313 /// Create a `std::vec::Vec` containing the arguments.
317 // leading _ to allow empty construction without a warning.
318 let mut _temp = ::std::vec::Vec::new();
322 ($($e:expr),+,) => (vec!($($e),+))
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 /// let (tx1, rx1) = channel();
336 /// let (tx2, rx2) = channel();
337 /// # fn long_running_task() {}
338 /// # fn calculate_the_answer() -> int { 42 }
340 /// spawn(proc() { long_running_task(); tx1.send(()) });
341 /// spawn(proc() { tx2.send(calculate_the_answer()) });
344 /// () = rx1.recv() => println!("the long running task finished first"),
345 /// answer = rx2.recv() => {
346 /// println!("the answer was: {}", answer);
351 /// For more information about select, see the `std::comm::Select` structure.
354 macro_rules! select {
356 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
358 use std::comm::Select;
359 let sel = Select::new();
360 $( let mut $rx = sel.handle(&$rx); )+
364 let ret = sel.wait();
365 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
370 // When testing the standard library, we link to the liblog crate to get the
371 // logging macros. In doing so, the liblog crate was linked against the real
372 // version of libstd, and uses a different std::fmt module than the test crate
373 // uses. To get around this difference, we redefine the log!() macro here to be
374 // just a dumb version of what it should be.
377 ($lvl:expr, $($args:tt)*) => (
378 if log_enabled!($lvl) { println!($($args)*) }
382 /// Built-in macros to the compiler itself.
384 /// These macros do not have any corresponding definition with a `macro_rules!`
385 /// macro, but are documented here. Their implementations can be found hardcoded
386 /// into libsyntax itself.
389 /// The core macro for formatted string creation & output.
391 /// This macro takes as its first argument a callable expression which will
392 /// receive as its first argument a value of type `&fmt::Arguments`. This
393 /// value can be passed to the functions in `std::fmt` for performing useful
394 /// functions. All other formatting macros (`format!`, `write!`,
395 /// `println!`, etc) are proxied through this one.
397 /// For more information, see the documentation in `std::fmt`.
404 /// let s = format_args!(fmt::format, "hello {}", "world");
405 /// assert_eq!(s, format!("hello {}", "world"));
407 /// format_args!(|args| {
408 /// // pass `args` to another function, etc.
409 /// }, "hello {}", "world");
412 macro_rules! format_args( ($closure:expr, $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 user: &'static str = env!("USER");
429 /// println!("the user who compiled this code is: {}", user);
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], 'u' as u8);
468 /// assert_eq!(rust[5], 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 /// fn foobar() -> int { 23 }
487 /// let f = concat_idents!(foo, bar);
488 /// println!("{}", f());
491 macro_rules! concat_idents( ($($e:ident),*) => ({ /* compiler built-in */ }) )
493 /// Concatenates literals into a static string slice.
495 /// This macro takes any number of comma-separated literals, yielding an
496 /// expression of type `&'static str` which represents all of the literals
497 /// concatenated left-to-right.
499 /// Integer and floating point literals are stringified in order to be
505 /// let s = concat!("test", 10, 'b', true);
506 /// assert_eq!(s, "test10btrue");
509 macro_rules! concat( ($($e:expr),*) => ({ /* compiler built-in */ }) )
511 /// A macro which expands to the line number on which it was invoked.
513 /// The expanded expression has type `uint`, and the returned line is not
514 /// the invocation of the `line!()` macro itself, but rather the first macro
515 /// invocation leading up to the invocation of the `line!()` macro.
520 /// let current_line = line!();
521 /// println!("defined on line: {}", current_line);
524 macro_rules! line( () => ({ /* compiler built-in */ }) )
526 /// A macro which expands to the column number on which it was invoked.
528 /// The expanded expression has type `uint`, and the returned column is not
529 /// the invocation of the `col!()` macro itself, but rather the first macro
530 /// invocation leading up to the invocation of the `col!()` macro.
535 /// let current_col = col!();
536 /// println!("defined on column: {}", current_col);
539 macro_rules! col( () => ({ /* compiler built-in */ }) )
541 /// A macro which expands to the file name from which it was invoked.
543 /// The expanded expression has type `&'static str`, and the returned file
544 /// is not the invocation of the `file!()` macro itself, but rather the
545 /// first macro invocation leading up to the invocation of the `file!()`
551 /// let this_file = file!();
552 /// println!("defined in file: {}", this_file);
555 macro_rules! file( () => ({ /* compiler built-in */ }) )
557 /// A macro which stringifies its argument.
559 /// This macro will yield an expression of type `&'static str` which is the
560 /// stringification of all the tokens passed to the macro. No restrictions
561 /// are placed on the syntax of the macro invocation itself.
566 /// let one_plus_one = stringify!(1 + 1);
567 /// assert_eq!(one_plus_one, "1 + 1");
570 macro_rules! stringify( ($t:tt) => ({ /* compiler built-in */ }) )
572 /// Includes a utf8-encoded file as a string.
574 /// This macro will yield an expression of type `&'static str` which is the
575 /// contents of the filename specified. The file is located relative to the
576 /// current file (similarly to how modules are found),
581 /// let secret_key = include_str!("secret-key.ascii");
584 macro_rules! include_str( ($file:expr) => ({ /* compiler built-in */ }) )
586 /// Includes a file as a byte slice.
588 /// This macro will yield an expression of type `&'static [u8]` which is
589 /// the contents of the filename specified. The file is located relative to
590 /// the current file (similarly to how modules are found),
595 /// let secret_key = include_bin!("secret-key.bin");
598 macro_rules! include_bin( ($file:expr) => ({ /* compiler built-in */ }) )
600 /// Expands to a string that represents the current module path.
602 /// The current module path can be thought of as the hierarchy of modules
603 /// leading back up to the crate root. The first component of the path
604 /// returned is the name of the crate currently being compiled.
611 /// assert!(module_path!().ends_with("test"));
618 macro_rules! module_path( () => ({ /* compiler built-in */ }) )
620 /// Boolean evaluation of configuration flags.
622 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
623 /// boolean expression evaluation of configuration flags. This frequently
624 /// leads to less duplicated code.
626 /// The syntax given to this macro is the same syntax as the `cfg`
632 /// let my_directory = if cfg!(windows) {
633 /// "windows-specific-directory"
639 macro_rules! cfg( ($cfg:tt) => ({ /* compiler built-in */ }) )