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