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