]> git.lizzy.rs Git - rust.git/blob - src/libstd/macros.rs
9a4c5ec8f6b2e311ebac1415ec1550e6b1583477
[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 /// panic entirely. Each thread's panic can be reaped as the `Box<Any>` type,
21 /// and the single-argument form of the `panic!` macro will be the value which
22 /// 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_panic($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_panic_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 /// Use `print!` only for the primary output of your program.  Use
72 /// `eprint!` instead to print error and progress messages.
73 ///
74 /// # Panics
75 ///
76 /// Panics if writing to `io::stdout()` fails.
77 ///
78 /// # Examples
79 ///
80 /// ```
81 /// use std::io::{self, Write};
82 ///
83 /// print!("this ");
84 /// print!("will ");
85 /// print!("be ");
86 /// print!("on ");
87 /// print!("the ");
88 /// print!("same ");
89 /// print!("line ");
90 ///
91 /// io::stdout().flush().unwrap();
92 ///
93 /// print!("this string has a newline, why not choose println! instead?\n");
94 ///
95 /// io::stdout().flush().unwrap();
96 /// ```
97 #[macro_export]
98 #[stable(feature = "rust1", since = "1.0.0")]
99 #[allow_internal_unstable]
100 macro_rules! print {
101     ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
102 }
103
104 /// Macro for printing to the standard output, with a newline. On all
105 /// platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
106 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
107 ///
108 /// Use the `format!` syntax to write data to the standard output.
109 /// See `std::fmt` for more information.
110 ///
111 /// Use `println!` only for the primary output of your program.  Use
112 /// `eprintln!` instead to print error and progress messages.
113 ///
114 /// # Panics
115 ///
116 /// Panics if writing to `io::stdout` fails.
117 ///
118 /// # Examples
119 ///
120 /// ```
121 /// println!(); // prints just a newline
122 /// println!("hello there!");
123 /// println!("format {} arguments", "some");
124 /// ```
125 #[macro_export]
126 #[stable(feature = "rust1", since = "1.0.0")]
127 macro_rules! println {
128     () => (print!("\n"));
129     ($fmt:expr) => (print!(concat!($fmt, "\n")));
130     ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
131 }
132
133 /// Macro for printing to the standard error.
134 ///
135 /// Equivalent to the `print!` macro, except that output goes to
136 /// `io::stderr` instead of `io::stdout`.  See `print!` for
137 /// example usage.
138 ///
139 /// Use `eprint!` only for error and progress messages.  Use `print!`
140 /// instead for the primary output of your program.
141 ///
142 /// # Panics
143 ///
144 /// Panics if writing to `io::stderr` fails.
145 #[macro_export]
146 #[stable(feature = "eprint", since = "1.19.0")]
147 #[allow_internal_unstable]
148 macro_rules! eprint {
149     ($($arg:tt)*) => ($crate::io::_eprint(format_args!($($arg)*)));
150 }
151
152 /// Macro for printing to the standard error, with a newline.
153 ///
154 /// Equivalent to the `println!` macro, except that output goes to
155 /// `io::stderr` instead of `io::stdout`.  See `println!` for
156 /// example usage.
157 ///
158 /// Use `eprintln!` only for error and progress messages.  Use `println!`
159 /// instead for the primary output of your program.
160 ///
161 /// # Panics
162 ///
163 /// Panics if writing to `io::stderr` fails.
164 #[macro_export]
165 #[stable(feature = "eprint", since = "1.19.0")]
166 macro_rules! eprintln {
167     () => (eprint!("\n"));
168     ($fmt:expr) => (eprint!(concat!($fmt, "\n")));
169     ($fmt:expr, $($arg:tt)*) => (eprint!(concat!($fmt, "\n"), $($arg)*));
170 }
171
172 /// A macro to select an event from a number of receivers.
173 ///
174 /// This macro is used to wait for the first event to occur on a number of
175 /// receivers. It places no restrictions on the types of receivers given to
176 /// this macro, this can be viewed as a heterogeneous select.
177 ///
178 /// # Examples
179 ///
180 /// ```
181 /// #![feature(mpsc_select)]
182 ///
183 /// use std::thread;
184 /// use std::sync::mpsc;
185 ///
186 /// // two placeholder functions for now
187 /// fn long_running_thread() {}
188 /// fn calculate_the_answer() -> u32 { 42 }
189 ///
190 /// let (tx1, rx1) = mpsc::channel();
191 /// let (tx2, rx2) = mpsc::channel();
192 ///
193 /// thread::spawn(move|| { long_running_thread(); tx1.send(()).unwrap(); });
194 /// thread::spawn(move|| { tx2.send(calculate_the_answer()).unwrap(); });
195 ///
196 /// select! {
197 ///     _ = rx1.recv() => println!("the long running thread finished first"),
198 ///     answer = rx2.recv() => {
199 ///         println!("the answer was: {}", answer.unwrap());
200 ///     }
201 /// }
202 /// # drop(rx1.recv());
203 /// # drop(rx2.recv());
204 /// ```
205 ///
206 /// For more information about select, see the `std::sync::mpsc::Select` structure.
207 #[macro_export]
208 #[unstable(feature = "mpsc_select", issue = "27800")]
209 macro_rules! select {
210     (
211         $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
212     ) => ({
213         use $crate::sync::mpsc::Select;
214         let sel = Select::new();
215         $( let mut $rx = sel.handle(&$rx); )+
216         unsafe {
217             $( $rx.add(); )+
218         }
219         let ret = sel.wait();
220         $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
221         { unreachable!() }
222     })
223 }
224
225 #[cfg(test)]
226 macro_rules! assert_approx_eq {
227     ($a:expr, $b:expr) => ({
228         let (a, b) = (&$a, &$b);
229         assert!((*a - *b).abs() < 1.0e-6,
230                 "{} is not approximately equal to {}", *a, *b);
231     })
232 }
233
234 /// Built-in macros to the compiler itself.
235 ///
236 /// These macros do not have any corresponding definition with a `macro_rules!`
237 /// macro, but are documented here. Their implementations can be found hardcoded
238 /// into libsyntax itself.
239 #[cfg(dox)]
240 pub mod builtin {
241
242     /// Unconditionally causes compilation to fail with the given error message when encountered.
243     ///
244     /// For more information, see the [RFC].
245     ///
246     /// [RFC]: https://github.com/rust-lang/rfcs/blob/master/text/1695-add-error-macro.md
247     #[unstable(feature = "compile_error_macro", issue = "40872")]
248     #[macro_export]
249     macro_rules! compile_error { ($msg:expr) => ({ /* compiler built-in */ }) }
250
251     /// The core macro for formatted string creation & output.
252     ///
253     /// This macro produces a value of type [`fmt::Arguments`]. This value can be
254     /// passed to the functions in [`std::fmt`] for performing useful functions.
255     /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
256     /// proxied through this one.
257     ///
258     /// For more information, see the documentation in [`std::fmt`].
259     ///
260     /// [`fmt::Arguments`]: ../std/fmt/struct.Arguments.html
261     /// [`std::fmt`]: ../std/fmt/index.html
262     /// [`format!`]: ../std/macro.format.html
263     /// [`write!`]: ../std/macro.write.html
264     /// [`println!`]: ../std/macro.println.html
265     ///
266     /// # Examples
267     ///
268     /// ```
269     /// use std::fmt;
270     ///
271     /// let s = fmt::format(format_args!("hello {}", "world"));
272     /// assert_eq!(s, format!("hello {}", "world"));
273     ///
274     /// ```
275     #[stable(feature = "rust1", since = "1.0.0")]
276     #[macro_export]
277     macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({
278         /* compiler built-in */
279     }) }
280
281     /// Inspect an environment variable at compile time.
282     ///
283     /// This macro will expand to the value of the named environment variable at
284     /// compile time, yielding an expression of type `&'static str`.
285     ///
286     /// If the environment variable is not defined, then a compilation error
287     /// will be emitted.  To not emit a compile error, use the `option_env!`
288     /// macro instead.
289     ///
290     /// # Examples
291     ///
292     /// ```
293     /// let path: &'static str = env!("PATH");
294     /// println!("the $PATH variable at the time of compiling was: {}", path);
295     /// ```
296     #[stable(feature = "rust1", since = "1.0.0")]
297     #[macro_export]
298     macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
299
300     /// Optionally inspect an environment variable at compile time.
301     ///
302     /// If the named environment variable is present at compile time, this will
303     /// expand into an expression of type `Option<&'static str>` whose value is
304     /// `Some` of the value of the environment variable. If the environment
305     /// variable is not present, then this will expand to `None`.
306     ///
307     /// A compile time error is never emitted when using this macro regardless
308     /// of whether the environment variable is present or not.
309     ///
310     /// # Examples
311     ///
312     /// ```
313     /// let key: Option<&'static str> = option_env!("SECRET_KEY");
314     /// println!("the secret key might be: {:?}", key);
315     /// ```
316     #[stable(feature = "rust1", since = "1.0.0")]
317     #[macro_export]
318     macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
319
320     /// Concatenate identifiers into one identifier.
321     ///
322     /// This macro takes any number of comma-separated identifiers, and
323     /// concatenates them all into one, yielding an expression which is a new
324     /// identifier. Note that hygiene makes it such that this macro cannot
325     /// capture local variables. Also, as a general rule, macros are only
326     /// allowed in item, statement or expression position. That means while
327     /// you may use this macro for referring to existing variables, functions or
328     /// modules etc, you cannot define a new one with it.
329     ///
330     /// # Examples
331     ///
332     /// ```
333     /// #![feature(concat_idents)]
334     ///
335     /// # fn main() {
336     /// fn foobar() -> u32 { 23 }
337     ///
338     /// let f = concat_idents!(foo, bar);
339     /// println!("{}", f());
340     ///
341     /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
342     /// # }
343     /// ```
344     #[unstable(feature = "concat_idents_macro", issue = "29599")]
345     #[macro_export]
346     macro_rules! concat_idents {
347         ($($e:ident),*) => ({ /* compiler built-in */ })
348     }
349
350     /// Concatenates literals into a static string slice.
351     ///
352     /// This macro takes any number of comma-separated literals, yielding an
353     /// expression of type `&'static str` which represents all of the literals
354     /// concatenated left-to-right.
355     ///
356     /// Integer and floating point literals are stringified in order to be
357     /// concatenated.
358     ///
359     /// # Examples
360     ///
361     /// ```
362     /// let s = concat!("test", 10, 'b', true);
363     /// assert_eq!(s, "test10btrue");
364     /// ```
365     #[stable(feature = "rust1", since = "1.0.0")]
366     #[macro_export]
367     macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
368
369     /// A macro which expands to the line number on which it was invoked.
370     ///
371     /// The expanded expression has type `u32`, and the returned line is not
372     /// the invocation of the `line!()` macro itself, but rather the first macro
373     /// invocation leading up to the invocation of the `line!()` macro.
374     ///
375     /// # Examples
376     ///
377     /// ```
378     /// let current_line = line!();
379     /// println!("defined on line: {}", current_line);
380     /// ```
381     #[stable(feature = "rust1", since = "1.0.0")]
382     #[macro_export]
383     macro_rules! line { () => ({ /* compiler built-in */ }) }
384
385     /// A macro which expands to the column number on which it was invoked.
386     ///
387     /// The expanded expression has type `u32`, and the returned column is not
388     /// the invocation of the `column!()` macro itself, but rather the first macro
389     /// invocation leading up to the invocation of the `column!()` macro.
390     ///
391     /// # Examples
392     ///
393     /// ```
394     /// let current_col = column!();
395     /// println!("defined on column: {}", current_col);
396     /// ```
397     #[stable(feature = "rust1", since = "1.0.0")]
398     #[macro_export]
399     macro_rules! column { () => ({ /* compiler built-in */ }) }
400
401     /// A macro which expands to the file name from which it was invoked.
402     ///
403     /// The expanded expression has type `&'static str`, and the returned file
404     /// is not the invocation of the `file!()` macro itself, but rather the
405     /// first macro invocation leading up to the invocation of the `file!()`
406     /// macro.
407     ///
408     /// # Examples
409     ///
410     /// ```
411     /// let this_file = file!();
412     /// println!("defined in file: {}", this_file);
413     /// ```
414     #[stable(feature = "rust1", since = "1.0.0")]
415     #[macro_export]
416     macro_rules! file { () => ({ /* compiler built-in */ }) }
417
418     /// A macro which stringifies its argument.
419     ///
420     /// This macro will yield an expression of type `&'static str` which is the
421     /// stringification of all the tokens passed to the macro. No restrictions
422     /// are placed on the syntax of the macro invocation itself.
423     ///
424     /// Note that the expanded results of the input tokens may change in the
425     /// future. You should be careful if you rely on the output.
426     ///
427     /// # Examples
428     ///
429     /// ```
430     /// let one_plus_one = stringify!(1 + 1);
431     /// assert_eq!(one_plus_one, "1 + 1");
432     /// ```
433     #[stable(feature = "rust1", since = "1.0.0")]
434     #[macro_export]
435     macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
436
437     /// Includes a utf8-encoded file as a string.
438     ///
439     /// The file is located relative to the current file. (similarly to how
440     /// modules are found)
441     ///
442     /// This macro will yield an expression of type `&'static str` which is the
443     /// contents of the file.
444     ///
445     /// # Examples
446     ///
447     /// ```ignore (cannot-doctest-external-file-dependency)
448     /// let secret_key = include_str!("secret-key.ascii");
449     /// ```
450     #[stable(feature = "rust1", since = "1.0.0")]
451     #[macro_export]
452     macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
453
454     /// Includes a file as a reference to a byte array.
455     ///
456     /// The file is located relative to the current file. (similarly to how
457     /// modules are found)
458     ///
459     /// This macro will yield an expression of type `&'static [u8; N]` which is
460     /// the contents of the file.
461     ///
462     /// # Examples
463     ///
464     /// ```ignore (cannot-doctest-external-file-dependency)
465     /// let secret_key = include_bytes!("secret-key.bin");
466     /// ```
467     #[stable(feature = "rust1", since = "1.0.0")]
468     #[macro_export]
469     macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
470
471     /// Expands to a string that represents the current module path.
472     ///
473     /// The current module path can be thought of as the hierarchy of modules
474     /// leading back up to the crate root. The first component of the path
475     /// returned is the name of the crate currently being compiled.
476     ///
477     /// # Examples
478     ///
479     /// ```
480     /// mod test {
481     ///     pub fn foo() {
482     ///         assert!(module_path!().ends_with("test"));
483     ///     }
484     /// }
485     ///
486     /// test::foo();
487     /// ```
488     #[stable(feature = "rust1", since = "1.0.0")]
489     #[macro_export]
490     macro_rules! module_path { () => ({ /* compiler built-in */ }) }
491
492     /// Boolean evaluation of configuration flags.
493     ///
494     /// In addition to the `#[cfg]` attribute, this macro is provided to allow
495     /// boolean expression evaluation of configuration flags. This frequently
496     /// leads to less duplicated code.
497     ///
498     /// The syntax given to this macro is the same syntax as [the `cfg`
499     /// attribute](../book/first-edition/conditional-compilation.html).
500     ///
501     /// # Examples
502     ///
503     /// ```
504     /// let my_directory = if cfg!(windows) {
505     ///     "windows-specific-directory"
506     /// } else {
507     ///     "unix-directory"
508     /// };
509     /// ```
510     #[stable(feature = "rust1", since = "1.0.0")]
511     #[macro_export]
512     macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
513
514     /// Parse a file as an expression or an item according to the context.
515     ///
516     /// The file is located relative to the current file (similarly to how
517     /// modules are found).
518     ///
519     /// Using this macro is often a bad idea, because if the file is
520     /// parsed as an expression, it is going to be placed in the
521     /// surrounding code unhygienically. This could result in variables
522     /// or functions being different from what the file expected if
523     /// there are variables or functions that have the same name in
524     /// the current file.
525     ///
526     /// # Examples
527     ///
528     /// Assume there are two files in the same directory with the following
529     /// contents:
530     ///
531     /// File 'my_str.in':
532     ///
533     /// ```ignore (only-for-syntax-highlight)
534     /// "Hello World!"
535     /// ```
536     ///
537     /// File 'main.rs':
538     ///
539     /// ```ignore (cannot-doctest-external-file-dependency)
540     /// fn main() {
541     ///     let my_str = include!("my_str.in");
542     ///     println!("{}", my_str);
543     /// }
544     /// ```
545     ///
546     /// Compiling 'main.rs' and running the resulting binary will print "Hello
547     /// World!".
548     #[stable(feature = "rust1", since = "1.0.0")]
549     #[macro_export]
550     macro_rules! include { ($file:expr) => ({ /* compiler built-in */ }) }
551 }