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