]> git.proxmox.com Git - rustc.git/blame - src/libstd/macros.rs
Imported Upstream version 1.3.0+dfsg1
[rustc.git] / src / libstd / macros.rs
CommitLineData
1a4d82fc 1// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
970d7e83
LB
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
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.
10
1a4d82fc
JJ
11//! Standard library macros
12//!
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
15//! library.
970d7e83 16
bd371182 17/// The entry point for panic of Rust threads.
9346a6ac 18///
bd371182
AL
19/// This macro is used to inject panic into a Rust thread, causing the thread to
20/// unwind and panic entirely. Each thread's panic can be reaped as the
9346a6ac
AL
21/// `Box<Any>` type, and the single-argument form of the `panic!` macro will be
22/// the value which is transmitted.
23///
24/// The multi-argument form of this macro panics with a string and has the
25/// `format!` syntax for building a string.
26///
27/// # Examples
28///
29/// ```should_panic
30/// # #![allow(unreachable_code)]
31/// panic!();
32/// panic!("this is a terrible mistake!");
33/// panic!(4); // panic with the value of 4 to be collected elsewhere
34/// panic!("this is a {} {message}", "fancy", message = "message");
35/// ```
36#[macro_export]
37#[stable(feature = "rust1", since = "1.0.0")]
38#[allow_internal_unstable]
9346a6ac
AL
39macro_rules! panic {
40 () => ({
41 panic!("explicit panic")
42 });
43 ($msg:expr) => ({
44 $crate::rt::begin_unwind($msg, {
45 // static requires less code at runtime, more constant data
46 static _FILE_LINE: (&'static str, u32) = (file!(), line!());
47 &_FILE_LINE
48 })
49 });
50 ($fmt:expr, $($arg:tt)+) => ({
51 $crate::rt::begin_unwind_fmt(format_args!($fmt, $($arg)+), {
52 // The leading _'s are to avoid dead code warnings if this is
53 // used inside a dead function. Just `#[allow(dead_code)]` is
54 // insufficient, since the user may have
55 // `#[forbid(dead_code)]` and which cannot be overridden.
56 static _FILE_LINE: (&'static str, u32) = (file!(), line!());
1a4d82fc
JJ
57 &_FILE_LINE
58 })
59 });
60}
61
c34b1796
AL
62/// Macro for printing to the standard output.
63///
1a4d82fc
JJ
64/// Equivalent to the `println!` macro except that a newline is not printed at
65/// the end of the message.
c34b1796
AL
66///
67/// Note that stdout is frequently line-buffered by default so it may be
68/// necessary to use `io::stdout().flush()` to ensure the output is emitted
69/// immediately.
1a4d82fc 70#[macro_export]
85aaf69f 71#[stable(feature = "rust1", since = "1.0.0")]
c34b1796 72#[allow_internal_unstable]
1a4d82fc 73macro_rules! print {
c34b1796 74 ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
1a4d82fc 75}
970d7e83 76
c34b1796 77/// Macro for printing to the standard output.
1a4d82fc 78///
c34b1796
AL
79/// Use the `format!` syntax to write data to the standard output.
80/// See `std::fmt` for more information.
1a4d82fc 81///
c34b1796 82/// # Examples
1a4d82fc
JJ
83///
84/// ```
85/// println!("hello there!");
86/// println!("format {} arguments", "some");
87/// ```
88#[macro_export]
85aaf69f 89#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 90macro_rules! println {
c34b1796
AL
91 ($fmt:expr) => (print!(concat!($fmt, "\n")));
92 ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
1a4d82fc
JJ
93}
94
95/// Helper macro for unwrapping `Result` values while returning early with an
62682a34
SL
96/// error if the value of the expression is `Err`. Can only be used in
97/// functions that return `Result` because of the early return of `Err` that
98/// it provides.
99///
100/// # Examples
101///
102/// ```
103/// use std::io;
104/// use std::fs::File;
105/// use std::io::prelude::*;
106///
107/// fn write_to_file_using_try() -> Result<(), io::Error> {
108/// let mut file = try!(File::create("my_best_friends.txt"));
109/// try!(file.write_all(b"This is a list of my best friends."));
110/// println!("I wrote to the file");
111/// Ok(())
112/// }
113/// // This is equivalent to:
114/// fn write_to_file_using_match() -> Result<(), io::Error> {
115/// let mut file = try!(File::create("my_best_friends.txt"));
116/// match file.write_all(b"This is a list of my best friends.") {
117/// Ok(_) => (),
118/// Err(e) => return Err(e),
119/// }
120/// println!("I wrote to the file");
121/// Ok(())
122/// }
123/// ```
1a4d82fc 124#[macro_export]
85aaf69f 125#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
126macro_rules! try {
127 ($expr:expr) => (match $expr {
128 $crate::result::Result::Ok(val) => val,
129 $crate::result::Result::Err(err) => {
c34b1796 130 return $crate::result::Result::Err($crate::convert::From::from(err))
1a4d82fc
JJ
131 }
132 })
133}
134
135/// A macro to select an event from a number of receivers.
136///
137/// This macro is used to wait for the first event to occur on a number of
138/// receivers. It places no restrictions on the types of receivers given to
139/// this macro, this can be viewed as a heterogeneous select.
140///
85aaf69f 141/// # Examples
1a4d82fc
JJ
142///
143/// ```
c1a9b12d
SL
144/// #![feature(mpsc_select)]
145///
85aaf69f
SL
146/// use std::thread;
147/// use std::sync::mpsc;
1a4d82fc 148///
85aaf69f 149/// // two placeholder functions for now
bd371182 150/// fn long_running_thread() {}
85aaf69f 151/// fn calculate_the_answer() -> u32 { 42 }
1a4d82fc 152///
85aaf69f
SL
153/// let (tx1, rx1) = mpsc::channel();
154/// let (tx2, rx2) = mpsc::channel();
155///
bd371182 156/// thread::spawn(move|| { long_running_thread(); tx1.send(()).unwrap(); });
85aaf69f 157/// thread::spawn(move|| { tx2.send(calculate_the_answer()).unwrap(); });
1a4d82fc 158///
d9579d0f 159/// select! {
bd371182 160/// _ = rx1.recv() => println!("the long running thread finished first"),
1a4d82fc
JJ
161/// answer = rx2.recv() => {
162/// println!("the answer was: {}", answer.unwrap());
163/// }
d9579d0f
AL
164/// }
165/// # drop(rx1.recv());
166/// # drop(rx2.recv());
1a4d82fc
JJ
167/// ```
168///
169/// For more information about select, see the `std::sync::mpsc::Select` structure.
170#[macro_export]
62682a34 171#[unstable(feature = "mpsc_select")]
1a4d82fc
JJ
172macro_rules! select {
173 (
174 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
175 ) => ({
176 use $crate::sync::mpsc::Select;
177 let sel = Select::new();
178 $( let mut $rx = sel.handle(&$rx); )+
179 unsafe {
180 $( $rx.add(); )+
970d7e83 181 }
1a4d82fc
JJ
182 let ret = sel.wait();
183 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
184 { unreachable!() }
185 })
186}
187
188// When testing the standard library, we link to the liblog crate to get the
189// logging macros. In doing so, the liblog crate was linked against the real
190// version of libstd, and uses a different std::fmt module than the test crate
191// uses. To get around this difference, we redefine the log!() macro here to be
192// just a dumb version of what it should be.
193#[cfg(test)]
194macro_rules! log {
195 ($lvl:expr, $($args:tt)*) => (
196 if log_enabled!($lvl) { println!($($args)*) }
197 )
198}
199
200/// Built-in macros to the compiler itself.
201///
202/// These macros do not have any corresponding definition with a `macro_rules!`
203/// macro, but are documented here. Their implementations can be found hardcoded
204/// into libsyntax itself.
205#[cfg(dox)]
206pub mod builtin {
207 /// The core macro for formatted string creation & output.
208 ///
209 /// This macro produces a value of type `fmt::Arguments`. This value can be
210 /// passed to the functions in `std::fmt` for performing useful functions.
211 /// All other formatting macros (`format!`, `write!`, `println!`, etc) are
212 /// proxied through this one.
213 ///
214 /// For more information, see the documentation in `std::fmt`.
215 ///
c34b1796 216 /// # Examples
1a4d82fc 217 ///
c34b1796 218 /// ```
1a4d82fc
JJ
219 /// use std::fmt;
220 ///
221 /// let s = fmt::format(format_args!("hello {}", "world"));
222 /// assert_eq!(s, format!("hello {}", "world"));
223 ///
224 /// ```
225 #[macro_export]
226 macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({
227 /* compiler built-in */
228 }) }
229
230 /// Inspect an environment variable at compile time.
231 ///
232 /// This macro will expand to the value of the named environment variable at
233 /// compile time, yielding an expression of type `&'static str`.
234 ///
235 /// If the environment variable is not defined, then a compilation error
236 /// will be emitted. To not emit a compile error, use the `option_env!`
237 /// macro instead.
238 ///
c34b1796 239 /// # Examples
1a4d82fc 240 ///
c34b1796 241 /// ```
1a4d82fc
JJ
242 /// let path: &'static str = env!("PATH");
243 /// println!("the $PATH variable at the time of compiling was: {}", path);
244 /// ```
245 #[macro_export]
246 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
247
248 /// Optionally inspect an environment variable at compile time.
249 ///
250 /// If the named environment variable is present at compile time, this will
251 /// expand into an expression of type `Option<&'static str>` whose value is
252 /// `Some` of the value of the environment variable. If the environment
253 /// variable is not present, then this will expand to `None`.
254 ///
255 /// A compile time error is never emitted when using this macro regardless
256 /// of whether the environment variable is present or not.
257 ///
c34b1796 258 /// # Examples
1a4d82fc 259 ///
c34b1796 260 /// ```
1a4d82fc
JJ
261 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
262 /// println!("the secret key might be: {:?}", key);
263 /// ```
264 #[macro_export]
265 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
266
267 /// Concatenate identifiers into one identifier.
268 ///
269 /// This macro takes any number of comma-separated identifiers, and
270 /// concatenates them all into one, yielding an expression which is a new
271 /// identifier. Note that hygiene makes it such that this macro cannot
272 /// capture local variables, and macros are only allowed in item,
273 /// statement or expression position, meaning this macro may be difficult to
274 /// use in some situations.
275 ///
85aaf69f 276 /// # Examples
1a4d82fc
JJ
277 ///
278 /// ```
279 /// #![feature(concat_idents)]
280 ///
281 /// # fn main() {
85aaf69f 282 /// fn foobar() -> u32 { 23 }
1a4d82fc
JJ
283 ///
284 /// let f = concat_idents!(foo, bar);
285 /// println!("{}", f());
286 /// # }
287 /// ```
288 #[macro_export]
289 macro_rules! concat_idents {
290 ($($e:ident),*) => ({ /* compiler built-in */ })
291 }
292
293 /// Concatenates literals into a static string slice.
294 ///
295 /// This macro takes any number of comma-separated literals, yielding an
296 /// expression of type `&'static str` which represents all of the literals
297 /// concatenated left-to-right.
298 ///
299 /// Integer and floating point literals are stringified in order to be
300 /// concatenated.
301 ///
c34b1796 302 /// # Examples
1a4d82fc
JJ
303 ///
304 /// ```
85aaf69f 305 /// let s = concat!("test", 10, 'b', true);
1a4d82fc
JJ
306 /// assert_eq!(s, "test10btrue");
307 /// ```
308 #[macro_export]
309 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
310
311 /// A macro which expands to the line number on which it was invoked.
312 ///
62682a34 313 /// The expanded expression has type `u32`, and the returned line is not
1a4d82fc
JJ
314 /// the invocation of the `line!()` macro itself, but rather the first macro
315 /// invocation leading up to the invocation of the `line!()` macro.
316 ///
c34b1796 317 /// # Examples
1a4d82fc
JJ
318 ///
319 /// ```
320 /// let current_line = line!();
321 /// println!("defined on line: {}", current_line);
322 /// ```
323 #[macro_export]
324 macro_rules! line { () => ({ /* compiler built-in */ }) }
325
326 /// A macro which expands to the column number on which it was invoked.
327 ///
62682a34 328 /// The expanded expression has type `u32`, and the returned column is not
1a4d82fc
JJ
329 /// the invocation of the `column!()` macro itself, but rather the first macro
330 /// invocation leading up to the invocation of the `column!()` macro.
331 ///
c34b1796 332 /// # Examples
1a4d82fc
JJ
333 ///
334 /// ```
335 /// let current_col = column!();
336 /// println!("defined on column: {}", current_col);
337 /// ```
338 #[macro_export]
339 macro_rules! column { () => ({ /* compiler built-in */ }) }
340
341 /// A macro which expands to the file name from which it was invoked.
342 ///
343 /// The expanded expression has type `&'static str`, and the returned file
344 /// is not the invocation of the `file!()` macro itself, but rather the
345 /// first macro invocation leading up to the invocation of the `file!()`
346 /// macro.
347 ///
c34b1796 348 /// # Examples
1a4d82fc
JJ
349 ///
350 /// ```
351 /// let this_file = file!();
352 /// println!("defined in file: {}", this_file);
353 /// ```
354 #[macro_export]
355 macro_rules! file { () => ({ /* compiler built-in */ }) }
356
357 /// A macro which stringifies its argument.
358 ///
359 /// This macro will yield an expression of type `&'static str` which is the
360 /// stringification of all the tokens passed to the macro. No restrictions
361 /// are placed on the syntax of the macro invocation itself.
362 ///
c34b1796 363 /// # Examples
1a4d82fc
JJ
364 ///
365 /// ```
366 /// let one_plus_one = stringify!(1 + 1);
367 /// assert_eq!(one_plus_one, "1 + 1");
368 /// ```
369 #[macro_export]
370 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
371
372 /// Includes a utf8-encoded file as a string.
373 ///
374 /// This macro will yield an expression of type `&'static str` which is the
375 /// contents of the filename specified. The file is located relative to the
376 /// current file (similarly to how modules are found),
377 ///
c34b1796 378 /// # Examples
1a4d82fc
JJ
379 ///
380 /// ```rust,ignore
381 /// let secret_key = include_str!("secret-key.ascii");
382 /// ```
383 #[macro_export]
384 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
385
386 /// Includes a file as a byte slice.
387 ///
388 /// This macro will yield an expression of type `&'static [u8]` which is
389 /// the contents of the filename specified. The file is located relative to
390 /// the current file (similarly to how modules are found),
391 ///
c34b1796 392 /// # Examples
1a4d82fc
JJ
393 ///
394 /// ```rust,ignore
395 /// let secret_key = include_bytes!("secret-key.bin");
396 /// ```
397 #[macro_export]
398 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
399
400 /// Expands to a string that represents the current module path.
401 ///
402 /// The current module path can be thought of as the hierarchy of modules
403 /// leading back up to the crate root. The first component of the path
404 /// returned is the name of the crate currently being compiled.
405 ///
c34b1796 406 /// # Examples
1a4d82fc 407 ///
c34b1796 408 /// ```
1a4d82fc
JJ
409 /// mod test {
410 /// pub fn foo() {
411 /// assert!(module_path!().ends_with("test"));
412 /// }
413 /// }
414 ///
415 /// test::foo();
416 /// ```
417 #[macro_export]
418 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
419
420 /// Boolean evaluation of configuration flags.
421 ///
422 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
423 /// boolean expression evaluation of configuration flags. This frequently
424 /// leads to less duplicated code.
425 ///
426 /// The syntax given to this macro is the same syntax as the `cfg`
427 /// attribute.
428 ///
c34b1796 429 /// # Examples
1a4d82fc 430 ///
c34b1796 431 /// ```
1a4d82fc
JJ
432 /// let my_directory = if cfg!(windows) {
433 /// "windows-specific-directory"
434 /// } else {
435 /// "unix-directory"
436 /// };
437 /// ```
438 #[macro_export]
439 macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) }
c34b1796
AL
440
441 /// Parse the current given file as an expression.
442 ///
d9579d0f 443 /// This is generally a bad idea, because it's going to behave unhygienically.
c34b1796
AL
444 ///
445 /// # Examples
446 ///
447 /// ```ignore
448 /// fn foo() {
449 /// include!("/path/to/a/file")
450 /// }
451 /// ```
452 #[macro_export]
453 macro_rules! include { ($cfg:tt) => ({ /* compiler built-in */ }) }
1a4d82fc 454}