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");
42 panic!("explicit panic")
45 $crate::rt::begin_unwind($msg, {
46 // static requires less code at runtime, more constant data
47 static _FILE_LINE: (&'static str, usize) = (file!(), line!());
51 ($fmt:expr, $($arg:tt)+) => ({
52 $crate::rt::begin_unwind_fmt(format_args!($fmt, $($arg)+), {
53 // The leading _'s are to avoid dead code warnings if this is
54 // used inside a dead function. Just `#[allow(dead_code)]` is
55 // insufficient, since the user may have
56 // `#[forbid(dead_code)]` and which cannot be overridden.
57 static _FILE_LINE: (&'static str, usize) = (file!(), line!());
63 /// Use the syntax described in `std::fmt` to create a value of type `String`.
64 /// See `std::fmt` for more information.
70 /// format!("hello {}", "world!");
71 /// format!("x = {}, y = {y}", 10i, y = 30i);
76 ($($arg:tt)*) => ($crate::fmt::format(format_args!($($arg)*)))
79 /// Equivalent to the `println!` macro except that a newline is not printed at
80 /// the end of the message.
84 ($($arg:tt)*) => ($crate::io::stdio::print_args(format_args!($($arg)*)))
87 /// Macro for printing to a task's stdout handle.
89 /// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
90 /// The syntax of this macro is the same as that used for `format!`. For more
91 /// information, see `std::fmt` and `std::io::stdio`.
96 /// println!("hello there!");
97 /// println!("format {} arguments", "some");
101 macro_rules! println {
102 ($($arg:tt)*) => ($crate::io::stdio::println_args(format_args!($($arg)*)))
105 /// Helper macro for unwrapping `Result` values while returning early with an
106 /// error if the value of the expression is `Err`. For more information, see
111 ($expr:expr) => (match $expr {
112 $crate::result::Result::Ok(val) => val,
113 $crate::result::Result::Err(err) => {
114 return $crate::result::Result::Err($crate::error::FromError::from_error(err))
119 /// A macro to select an event from a number of receivers.
121 /// This macro is used to wait for the first event to occur on a number of
122 /// receivers. It places no restrictions on the types of receivers given to
123 /// this macro, this can be viewed as a heterogeneous select.
128 /// use std::thread::Thread;
129 /// use std::sync::mpsc;
131 /// // two placeholder functions for now
132 /// fn long_running_task() {}
133 /// fn calculate_the_answer() -> u32 { 42 }
135 /// let (tx1, rx1) = mpsc::channel();
136 /// let (tx2, rx2) = mpsc::channel();
138 /// Thread::spawn(move|| { long_running_task(); tx1.send(()).unwrap(); });
139 /// Thread::spawn(move|| { tx2.send(calculate_the_answer()).unwrap(); });
142 /// _ = rx1.recv() => println!("the long running task finished first"),
143 /// answer = rx2.recv() => {
144 /// println!("the answer was: {}", answer.unwrap());
149 /// For more information about select, see the `std::sync::mpsc::Select` structure.
152 macro_rules! select {
154 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
156 use $crate::sync::mpsc::Select;
157 let sel = Select::new();
158 $( let mut $rx = sel.handle(&$rx); )+
162 let ret = sel.wait();
163 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
168 // When testing the standard library, we link to the liblog crate to get the
169 // logging macros. In doing so, the liblog crate was linked against the real
170 // version of libstd, and uses a different std::fmt module than the test crate
171 // uses. To get around this difference, we redefine the log!() macro here to be
172 // just a dumb version of what it should be.
175 ($lvl:expr, $($args:tt)*) => (
176 if log_enabled!($lvl) { println!($($args)*) }
180 /// Built-in macros to the compiler itself.
182 /// These macros do not have any corresponding definition with a `macro_rules!`
183 /// macro, but are documented here. Their implementations can be found hardcoded
184 /// into libsyntax itself.
187 /// The core macro for formatted string creation & output.
189 /// This macro produces a value of type `fmt::Arguments`. This value can be
190 /// passed to the functions in `std::fmt` for performing useful functions.
191 /// All other formatting macros (`format!`, `write!`, `println!`, etc) are
192 /// proxied through this one.
194 /// For more information, see the documentation in `std::fmt`.
201 /// let s = fmt::format(format_args!("hello {}", "world"));
202 /// assert_eq!(s, format!("hello {}", "world"));
206 macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({
207 /* compiler built-in */
210 /// Inspect an environment variable at compile time.
212 /// This macro will expand to the value of the named environment variable at
213 /// compile time, yielding an expression of type `&'static str`.
215 /// If the environment variable is not defined, then a compilation error
216 /// will be emitted. To not emit a compile error, use the `option_env!`
222 /// let path: &'static str = env!("PATH");
223 /// println!("the $PATH variable at the time of compiling was: {}", path);
226 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
228 /// Optionally inspect an environment variable at compile time.
230 /// If the named environment variable is present at compile time, this will
231 /// expand into an expression of type `Option<&'static str>` whose value is
232 /// `Some` of the value of the environment variable. If the environment
233 /// variable is not present, then this will expand to `None`.
235 /// A compile time error is never emitted when using this macro regardless
236 /// of whether the environment variable is present or not.
241 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
242 /// println!("the secret key might be: {:?}", key);
245 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
247 /// Concatenate identifiers into one identifier.
249 /// This macro takes any number of comma-separated identifiers, and
250 /// concatenates them all into one, yielding an expression which is a new
251 /// identifier. Note that hygiene makes it such that this macro cannot
252 /// capture local variables, and macros are only allowed in item,
253 /// statement or expression position, meaning this macro may be difficult to
254 /// use in some situations.
259 /// #![feature(concat_idents)]
262 /// fn foobar() -> u32 { 23 }
264 /// let f = concat_idents!(foo, bar);
265 /// println!("{}", f());
269 macro_rules! concat_idents {
270 ($($e:ident),*) => ({ /* compiler built-in */ })
273 /// Concatenates literals into a static string slice.
275 /// This macro takes any number of comma-separated literals, yielding an
276 /// expression of type `&'static str` which represents all of the literals
277 /// concatenated left-to-right.
279 /// Integer and floating point literals are stringified in order to be
285 /// let s = concat!("test", 10i, 'b', true);
286 /// assert_eq!(s, "test10btrue");
289 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
291 /// A macro which expands to the line number on which it was invoked.
293 /// The expanded expression has type `usize`, and the returned line is not
294 /// the invocation of the `line!()` macro itself, but rather the first macro
295 /// invocation leading up to the invocation of the `line!()` macro.
300 /// let current_line = line!();
301 /// println!("defined on line: {}", current_line);
304 macro_rules! line { () => ({ /* compiler built-in */ }) }
306 /// A macro which expands to the column number on which it was invoked.
308 /// The expanded expression has type `usize`, and the returned column is not
309 /// the invocation of the `column!()` macro itself, but rather the first macro
310 /// invocation leading up to the invocation of the `column!()` macro.
315 /// let current_col = column!();
316 /// println!("defined on column: {}", current_col);
319 macro_rules! column { () => ({ /* compiler built-in */ }) }
321 /// A macro which expands to the file name from which it was invoked.
323 /// The expanded expression has type `&'static str`, and the returned file
324 /// is not the invocation of the `file!()` macro itself, but rather the
325 /// first macro invocation leading up to the invocation of the `file!()`
331 /// let this_file = file!();
332 /// println!("defined in file: {}", this_file);
335 macro_rules! file { () => ({ /* compiler built-in */ }) }
337 /// A macro which stringifies its argument.
339 /// This macro will yield an expression of type `&'static str` which is the
340 /// stringification of all the tokens passed to the macro. No restrictions
341 /// are placed on the syntax of the macro invocation itself.
346 /// let one_plus_one = stringify!(1 + 1);
347 /// assert_eq!(one_plus_one, "1 + 1");
350 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
352 /// Includes a utf8-encoded file as a string.
354 /// This macro will yield an expression of type `&'static str` which is the
355 /// contents of the filename specified. The file is located relative to the
356 /// current file (similarly to how modules are found),
361 /// let secret_key = include_str!("secret-key.ascii");
364 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
366 /// Includes a file as a byte slice.
368 /// This macro will yield an expression of type `&'static [u8]` which is
369 /// the contents of the filename specified. The file is located relative to
370 /// the current file (similarly to how modules are found),
375 /// let secret_key = include_bytes!("secret-key.bin");
378 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
380 /// Expands to a string that represents the current module path.
382 /// The current module path can be thought of as the hierarchy of modules
383 /// leading back up to the crate root. The first component of the path
384 /// returned is the name of the crate currently being compiled.
391 /// assert!(module_path!().ends_with("test"));
398 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
400 /// Boolean evaluation of configuration flags.
402 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
403 /// boolean expression evaluation of configuration flags. This frequently
404 /// leads to less duplicated code.
406 /// The syntax given to this macro is the same syntax as the `cfg`
412 /// let my_directory = if cfg!(windows) {
413 /// "windows-specific-directory"
419 macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) }