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