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