]> git.lizzy.rs Git - rust.git/blob - src/libstd/macros.rs
e60ef46e738b415eb82d63ed7a9c1a387e1b09c5
[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 allows a program to to terminate immediately and provide feedback
20 /// to the caller of the program. `panic!` should be used when a program reaches
21 /// an unrecoverable problem.
22 ///
23 /// This macro is the perfect way to assert conditions in example code and in
24 /// tests.  `panic!` is closely tied with the `unwrap` method of both [`Option`]
25 /// and [`Result`][runwrap] enums.  Both implementations call `panic!` when they are set
26 /// to None or Err variants.
27 ///
28 /// This macro is used to inject panic into a Rust thread, causing the thread to
29 /// panic entirely. Each thread's panic can be reaped as the `Box<Any>` type,
30 /// and the single-argument form of the `panic!` macro will be the value which
31 /// is transmitted.
32 ///
33 /// [`Result`] enum is often a better solution for recovering from errors than
34 /// using the `panic!` macro.  This macro should be used to avoid proceeding using
35 /// incorrect values, such as from external sources.  Detailed information about
36 /// error handling is found in the [book].
37 ///
38 /// The multi-argument form of this macro panics with a string and has the
39 /// [`format!`] syntax for building a string.
40 ///
41 /// See also the macro [`compile_error!`], for raising errors during compilation.
42 ///
43 /// [runwrap]: ../std/result/enum.Result.html#method.unwrap
44 /// [`Option`]: ../std/option/enum.Option.html#method.unwrap
45 /// [`Result`]: ../std/result/enum.Result.html
46 /// [`format!`]: ../std/macro.format.html
47 /// [`compile_error!`]: ../std/macro.compile_error.html
48 /// [book]: ../book/second-edition/ch09-01-unrecoverable-errors-with-panic.html
49 ///
50 /// # Current implementation
51 ///
52 /// If the main thread panics it will terminate all your threads and end your
53 /// program with code `101`.
54 ///
55 /// # Examples
56 ///
57 /// ```should_panic
58 /// # #![allow(unreachable_code)]
59 /// panic!();
60 /// panic!("this is a terrible mistake!");
61 /// panic!(4); // panic with the value of 4 to be collected elsewhere
62 /// panic!("this is a {} {message}", "fancy", message = "message");
63 /// ```
64 #[macro_export]
65 #[stable(feature = "rust1", since = "1.0.0")]
66 #[allow_internal_unstable]
67 macro_rules! panic {
68     () => ({
69         panic!("explicit panic")
70     });
71     ($msg:expr) => ({
72         $crate::rt::begin_panic($msg, &(file!(), line!(), __rust_unstable_column!()))
73     });
74     ($msg:expr,) => ({
75         panic!($msg)
76     });
77     ($fmt:expr, $($arg:tt)+) => ({
78         $crate::rt::begin_panic_fmt(&format_args!($fmt, $($arg)+),
79                                     &(file!(), line!(), __rust_unstable_column!()))
80     });
81 }
82
83 /// Macro for printing to the standard output.
84 ///
85 /// Equivalent to the [`println!`] macro except that a newline is not printed at
86 /// the end of the message.
87 ///
88 /// Note that stdout is frequently line-buffered by default so it may be
89 /// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
90 /// immediately.
91 ///
92 /// Use `print!` only for the primary output of your program.  Use
93 /// [`eprint!`] instead to print error and progress messages.
94 ///
95 /// [`println!`]: ../std/macro.println.html
96 /// [flush]: ../std/io/trait.Write.html#tymethod.flush
97 /// [`eprint!`]: ../std/macro.eprint.html
98 ///
99 /// # Panics
100 ///
101 /// Panics if writing to `io::stdout()` fails.
102 ///
103 /// # Examples
104 ///
105 /// ```
106 /// use std::io::{self, Write};
107 ///
108 /// print!("this ");
109 /// print!("will ");
110 /// print!("be ");
111 /// print!("on ");
112 /// print!("the ");
113 /// print!("same ");
114 /// print!("line ");
115 ///
116 /// io::stdout().flush().unwrap();
117 ///
118 /// print!("this string has a newline, why not choose println! instead?\n");
119 ///
120 /// io::stdout().flush().unwrap();
121 /// ```
122 #[macro_export]
123 #[stable(feature = "rust1", since = "1.0.0")]
124 #[allow_internal_unstable]
125 macro_rules! print {
126     ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
127 }
128
129 /// Macro for printing to the standard output, with a newline.
130 ///
131 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
132 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
133 ///
134 /// Use the [`format!`] syntax to write data to the standard output.
135 /// See [`std::fmt`] for more information.
136 ///
137 /// Use `println!` only for the primary output of your program.  Use
138 /// [`eprintln!`] instead to print error and progress messages.
139 ///
140 /// [`format!`]: ../std/macro.format.html
141 /// [`std::fmt`]: ../std/fmt/index.html
142 /// [`eprintln!`]: ../std/macro.eprint.html
143 /// # Panics
144 ///
145 /// Panics if writing to `io::stdout` fails.
146 ///
147 /// # Examples
148 ///
149 /// ```
150 /// println!(); // prints just a newline
151 /// println!("hello there!");
152 /// println!("format {} arguments", "some");
153 /// ```
154 #[macro_export]
155 #[stable(feature = "rust1", since = "1.0.0")]
156 #[allow_internal_unstable]
157 macro_rules! println {
158     () => (print!("\n"));
159     ($($arg:tt)*) => ({
160         $crate::io::_print(format_args_nl!($($arg)*));
161     })
162 }
163
164 /// Macro for printing to the standard error.
165 ///
166 /// Equivalent to the [`print!`] macro, except that output goes to
167 /// [`io::stderr`] instead of `io::stdout`.  See [`print!`] for
168 /// example usage.
169 ///
170 /// Use `eprint!` only for error and progress messages.  Use `print!`
171 /// instead for the primary output of your program.
172 ///
173 /// [`io::stderr`]: ../std/io/struct.Stderr.html
174 /// [`print!`]: ../std/macro.print.html
175 ///
176 /// # Panics
177 ///
178 /// Panics if writing to `io::stderr` fails.
179 ///
180 /// # Examples
181 ///
182 /// ```
183 /// eprint!("Error: Could not complete task");
184 /// ```
185 #[macro_export]
186 #[stable(feature = "eprint", since = "1.19.0")]
187 #[allow_internal_unstable]
188 macro_rules! eprint {
189     ($($arg:tt)*) => ($crate::io::_eprint(format_args!($($arg)*)));
190 }
191
192 /// Macro for printing to the standard error, with a newline.
193 ///
194 /// Equivalent to the [`println!`] macro, except that output goes to
195 /// [`io::stderr`] instead of `io::stdout`.  See [`println!`] for
196 /// example usage.
197 ///
198 /// Use `eprintln!` only for error and progress messages.  Use `println!`
199 /// instead for the primary output of your program.
200 ///
201 /// [`io::stderr`]: ../std/io/struct.Stderr.html
202 /// [`println!`]: ../std/macro.println.html
203 ///
204 /// # Panics
205 ///
206 /// Panics if writing to `io::stderr` fails.
207 ///
208 /// # Examples
209 ///
210 /// ```
211 /// eprintln!("Error: Could not complete task");
212 /// ```
213 #[macro_export]
214 #[stable(feature = "eprint", since = "1.19.0")]
215 #[allow_internal_unstable]
216 macro_rules! eprintln {
217     () => (eprint!("\n"));
218     ($($arg:tt)*) => ({
219         $crate::io::_eprint(format_args_nl!($($arg)*));
220     })
221 }
222
223 #[macro_export]
224 #[unstable(feature = "await_macro", issue = "50547")]
225 #[allow_internal_unstable]
226 #[allow_internal_unsafe]
227 macro_rules! await {
228     ($e:expr) => { {
229         let mut pinned = $e;
230         loop {
231             if let $crate::task::Poll::Ready(x) =
232                 $crate::future::poll_in_task_cx(unsafe {
233                     $crate::pin::Pin::new_unchecked(&mut pinned)
234                 })
235             {
236                 break x;
237             }
238             // FIXME(cramertj) prior to stabilizing await, we have to ensure that this
239             // can't be used to create a generator on stable via `|| await!()`.
240             yield
241         }
242     } }
243 }
244
245 /// A macro to select an event from a number of receivers.
246 ///
247 /// This macro is used to wait for the first event to occur on a number of
248 /// receivers. It places no restrictions on the types of receivers given to
249 /// this macro, this can be viewed as a heterogeneous select.
250 ///
251 /// # Examples
252 ///
253 /// ```
254 /// #![feature(mpsc_select)]
255 ///
256 /// use std::thread;
257 /// use std::sync::mpsc;
258 ///
259 /// // two placeholder functions for now
260 /// fn long_running_thread() {}
261 /// fn calculate_the_answer() -> u32 { 42 }
262 ///
263 /// let (tx1, rx1) = mpsc::channel();
264 /// let (tx2, rx2) = mpsc::channel();
265 ///
266 /// thread::spawn(move|| { long_running_thread(); tx1.send(()).unwrap(); });
267 /// thread::spawn(move|| { tx2.send(calculate_the_answer()).unwrap(); });
268 ///
269 /// select! {
270 ///     _ = rx1.recv() => println!("the long running thread finished first"),
271 ///     answer = rx2.recv() => {
272 ///         println!("the answer was: {}", answer.unwrap());
273 ///     }
274 /// }
275 /// # drop(rx1.recv());
276 /// # drop(rx2.recv());
277 /// ```
278 ///
279 /// For more information about select, see the `std::sync::mpsc::Select` structure.
280 #[macro_export]
281 #[unstable(feature = "mpsc_select", issue = "27800")]
282 macro_rules! select {
283     (
284         $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
285     ) => ({
286         use $crate::sync::mpsc::Select;
287         let sel = Select::new();
288         $( let mut $rx = sel.handle(&$rx); )+
289         unsafe {
290             $( $rx.add(); )+
291         }
292         let ret = sel.wait();
293         $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
294         { unreachable!() }
295     })
296 }
297
298 #[cfg(test)]
299 macro_rules! assert_approx_eq {
300     ($a:expr, $b:expr) => ({
301         let (a, b) = (&$a, &$b);
302         assert!((*a - *b).abs() < 1.0e-6,
303                 "{} is not approximately equal to {}", *a, *b);
304     })
305 }
306
307 /// Built-in macros to the compiler itself.
308 ///
309 /// These macros do not have any corresponding definition with a `macro_rules!`
310 /// macro, but are documented here. Their implementations can be found hardcoded
311 /// into libsyntax itself.
312 #[cfg(rustdoc)]
313 mod builtin {
314
315     /// Unconditionally causes compilation to fail with the given error message when encountered.
316     ///
317     /// This macro should be used when a crate uses a conditional compilation strategy to provide
318     /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
319     /// which emits an error at *runtime*, rather than during compilation.
320     ///
321     /// # Examples
322     ///
323     /// Two such examples are macros and `#[cfg]` environments.
324     ///
325     /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
326     /// the compiler would still emit an error, but the error's message would not mention the two
327     /// valid values.
328     ///
329     /// ```compile_fail
330     /// macro_rules! give_me_foo_or_bar {
331     ///     (foo) => {};
332     ///     (bar) => {};
333     ///     ($x:ident) => {
334     ///         compile_error!("This macro only accepts `foo` or `bar`");
335     ///     }
336     /// }
337     ///
338     /// give_me_foo_or_bar!(neither);
339     /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
340     /// ```
341     ///
342     /// Emit compiler error if one of a number of features isn't available.
343     ///
344     /// ```compile_fail
345     /// #[cfg(not(any(feature = "foo", feature = "bar")))]
346     /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.")
347     /// ```
348     ///
349     /// [`panic!`]: ../std/macro.panic.html
350     #[stable(feature = "compile_error_macro", since = "1.20.0")]
351     #[rustc_doc_only_macro]
352     macro_rules! compile_error {
353         ($msg:expr) => ({ /* compiler built-in */ });
354         ($msg:expr,) => ({ /* compiler built-in */ });
355     }
356
357     /// The core macro for formatted string creation & output.
358     ///
359     /// This macro functions by taking a formatting string literal containing
360     /// `{}` for each additional argument passed.  `format_args!` prepares the
361     /// additional parameters to ensure the output can be interpreted as a string
362     /// and canonicalizes the arguments into a single type.  Any value that implements
363     /// the [`Display`] trait can be passed to `format_args!`, as can any
364     /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
365     ///
366     /// This macro produces a value of type [`fmt::Arguments`]. This value can be
367     /// passed to the macros within [`std::fmt`] for performing useful redirection.
368     /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
369     /// proxied through this one.  `format_args!`, unlike its derived macros, avoids
370     /// heap allocations.
371     ///
372     /// You can use the [`fmt::Arguments`] value that `format_args!` returns
373     /// in `Debug` and `Display` contexts as seen below. The example also shows
374     /// that `Debug` and `Display` format to the same thing: the interpolated
375     /// format string in `format_args!`.
376     ///
377     /// ```rust
378     /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
379     /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
380     /// assert_eq!("1 foo 2", display);
381     /// assert_eq!(display, debug);
382     /// ```
383     ///
384     /// For more information, see the documentation in [`std::fmt`].
385     ///
386     /// [`Display`]: ../std/fmt/trait.Display.html
387     /// [`Debug`]: ../std/fmt/trait.Debug.html
388     /// [`fmt::Arguments`]: ../std/fmt/struct.Arguments.html
389     /// [`std::fmt`]: ../std/fmt/index.html
390     /// [`format!`]: ../std/macro.format.html
391     /// [`write!`]: ../std/macro.write.html
392     /// [`println!`]: ../std/macro.println.html
393     ///
394     /// # Examples
395     ///
396     /// ```
397     /// use std::fmt;
398     ///
399     /// let s = fmt::format(format_args!("hello {}", "world"));
400     /// assert_eq!(s, format!("hello {}", "world"));
401     /// ```
402     #[stable(feature = "rust1", since = "1.0.0")]
403     #[rustc_doc_only_macro]
404     macro_rules! format_args {
405         ($fmt:expr) => ({ /* compiler built-in */ });
406         ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ });
407     }
408
409     /// Inspect an environment variable at compile time.
410     ///
411     /// This macro will expand to the value of the named environment variable at
412     /// compile time, yielding an expression of type `&'static str`.
413     ///
414     /// If the environment variable is not defined, then a compilation error
415     /// will be emitted. To not emit a compile error, use the [`option_env!`]
416     /// macro instead.
417     ///
418     /// [`option_env!`]: ../std/macro.option_env.html
419     ///
420     /// # Examples
421     ///
422     /// ```
423     /// let path: &'static str = env!("PATH");
424     /// println!("the $PATH variable at the time of compiling was: {}", path);
425     /// ```
426     ///
427     /// You can customize the error message by passing a string as the second
428     /// parameter:
429     ///
430     /// ```compile_fail
431     /// let doc: &'static str = env!("documentation", "what's that?!");
432     /// ```
433     ///
434     /// If the `documentation` environment variable is not defined, you'll get
435     /// the following error:
436     ///
437     /// ```text
438     /// error: what's that?!
439     /// ```
440     #[stable(feature = "rust1", since = "1.0.0")]
441     #[rustc_doc_only_macro]
442     macro_rules! env {
443         ($name:expr) => ({ /* compiler built-in */ });
444         ($name:expr,) => ({ /* compiler built-in */ });
445     }
446
447     /// Optionally inspect an environment variable at compile time.
448     ///
449     /// If the named environment variable is present at compile time, this will
450     /// expand into an expression of type `Option<&'static str>` whose value is
451     /// `Some` of the value of the environment variable. If the environment
452     /// variable is not present, then this will expand to `None`.  See
453     /// [`Option<T>`][option] for more information on this type.
454     ///
455     /// A compile time error is never emitted when using this macro regardless
456     /// of whether the environment variable is present or not.
457     ///
458     /// [option]: ../std/option/enum.Option.html
459     ///
460     /// # Examples
461     ///
462     /// ```
463     /// let key: Option<&'static str> = option_env!("SECRET_KEY");
464     /// println!("the secret key might be: {:?}", key);
465     /// ```
466     #[stable(feature = "rust1", since = "1.0.0")]
467     #[rustc_doc_only_macro]
468     macro_rules! option_env {
469         ($name:expr) => ({ /* compiler built-in */ });
470         ($name:expr,) => ({ /* compiler built-in */ });
471     }
472
473     /// Concatenate identifiers into one identifier.
474     ///
475     /// This macro takes any number of comma-separated identifiers, and
476     /// concatenates them all into one, yielding an expression which is a new
477     /// identifier. Note that hygiene makes it such that this macro cannot
478     /// capture local variables. Also, as a general rule, macros are only
479     /// allowed in item, statement or expression position. That means while
480     /// you may use this macro for referring to existing variables, functions or
481     /// modules etc, you cannot define a new one with it.
482     ///
483     /// # Examples
484     ///
485     /// ```
486     /// #![feature(concat_idents)]
487     ///
488     /// # fn main() {
489     /// fn foobar() -> u32 { 23 }
490     ///
491     /// let f = concat_idents!(foo, bar);
492     /// println!("{}", f());
493     ///
494     /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
495     /// # }
496     /// ```
497     #[unstable(feature = "concat_idents_macro", issue = "29599")]
498     #[rustc_doc_only_macro]
499     macro_rules! concat_idents {
500         ($($e:ident),+) => ({ /* compiler built-in */ });
501         ($($e:ident,)+) => ({ /* compiler built-in */ });
502     }
503
504     /// Concatenates literals into a static string slice.
505     ///
506     /// This macro takes any number of comma-separated literals, yielding an
507     /// expression of type `&'static str` which represents all of the literals
508     /// concatenated left-to-right.
509     ///
510     /// Integer and floating point literals are stringified in order to be
511     /// concatenated.
512     ///
513     /// # Examples
514     ///
515     /// ```
516     /// let s = concat!("test", 10, 'b', true);
517     /// assert_eq!(s, "test10btrue");
518     /// ```
519     #[stable(feature = "rust1", since = "1.0.0")]
520     #[rustc_doc_only_macro]
521     macro_rules! concat {
522         ($($e:expr),*) => ({ /* compiler built-in */ });
523         ($($e:expr,)*) => ({ /* compiler built-in */ });
524     }
525
526     /// A macro which expands to the line number on which it was invoked.
527     ///
528     /// With [`column!`] and [`file!`], these macros provide debugging information for
529     /// developers about the location within the source.
530     ///
531     /// The expanded expression has type `u32` and is 1-based, so the first line
532     /// in each file evaluates to 1, the second to 2, etc. This is consistent
533     /// with error messages by common compilers or popular editors.
534     /// The returned line is *not necessarily* the line of the `line!` invocation itself,
535     /// but rather the first macro invocation leading up to the invocation
536     /// of the `line!` macro.
537     ///
538     /// [`column!`]: macro.column.html
539     /// [`file!`]: macro.file.html
540     ///
541     /// # Examples
542     ///
543     /// ```
544     /// let current_line = line!();
545     /// println!("defined on line: {}", current_line);
546     /// ```
547     #[stable(feature = "rust1", since = "1.0.0")]
548     #[rustc_doc_only_macro]
549     macro_rules! line { () => ({ /* compiler built-in */ }) }
550
551     /// A macro which expands to the column number on which it was invoked.
552     ///
553     /// With [`line!`] and [`file!`], these macros provide debugging information for
554     /// developers about the location within the source.
555     ///
556     /// The expanded expression has type `u32` and is 1-based, so the first column
557     /// in each line evaluates to 1, the second to 2, etc. This is consistent
558     /// with error messages by common compilers or popular editors.
559     /// The returned column is *not necessarily* the line of the `column!` invocation itself,
560     /// but rather the first macro invocation leading up to the invocation
561     /// of the `column!` macro.
562     ///
563     /// [`line!`]: macro.line.html
564     /// [`file!`]: macro.file.html
565     ///
566     /// # Examples
567     ///
568     /// ```
569     /// let current_col = column!();
570     /// println!("defined on column: {}", current_col);
571     /// ```
572     #[stable(feature = "rust1", since = "1.0.0")]
573     #[rustc_doc_only_macro]
574     macro_rules! column { () => ({ /* compiler built-in */ }) }
575
576     /// A macro which expands to the file name from which it was invoked.
577     ///
578     /// With [`line!`] and [`column!`], these macros provide debugging information for
579     /// developers about the location within the source.
580     ///
581     ///
582     /// The expanded expression has type `&'static str`, and the returned file
583     /// is not the invocation of the `file!` macro itself, but rather the
584     /// first macro invocation leading up to the invocation of the `file!`
585     /// macro.
586     ///
587     /// [`line!`]: macro.line.html
588     /// [`column!`]: macro.column.html
589     ///
590     /// # Examples
591     ///
592     /// ```
593     /// let this_file = file!();
594     /// println!("defined in file: {}", this_file);
595     /// ```
596     #[stable(feature = "rust1", since = "1.0.0")]
597     #[rustc_doc_only_macro]
598     macro_rules! file { () => ({ /* compiler built-in */ }) }
599
600     /// A macro which stringifies its arguments.
601     ///
602     /// This macro will yield an expression of type `&'static str` which is the
603     /// stringification of all the tokens passed to the macro. No restrictions
604     /// are placed on the syntax of the macro invocation itself.
605     ///
606     /// Note that the expanded results of the input tokens may change in the
607     /// future. You should be careful if you rely on the output.
608     ///
609     /// # Examples
610     ///
611     /// ```
612     /// let one_plus_one = stringify!(1 + 1);
613     /// assert_eq!(one_plus_one, "1 + 1");
614     /// ```
615     #[stable(feature = "rust1", since = "1.0.0")]
616     #[rustc_doc_only_macro]
617     macro_rules! stringify { ($($t:tt)*) => ({ /* compiler built-in */ }) }
618
619     /// Includes a utf8-encoded file as a string.
620     ///
621     /// The file is located relative to the current file. (similarly to how
622     /// modules are found)
623     ///
624     /// This macro will yield an expression of type `&'static str` which is the
625     /// contents of the file.
626     ///
627     /// # Examples
628     ///
629     /// Assume there are two files in the same directory with the following
630     /// contents:
631     ///
632     /// File 'spanish.in':
633     ///
634     /// ```text
635     /// adiós
636     /// ```
637     ///
638     /// File 'main.rs':
639     ///
640     /// ```ignore (cannot-doctest-external-file-dependency)
641     /// fn main() {
642     ///     let my_str = include_str!("spanish.in");
643     ///     assert_eq!(my_str, "adiós\n");
644     ///     print!("{}", my_str);
645     /// }
646     /// ```
647     ///
648     /// Compiling 'main.rs' and running the resulting binary will print "adiós".
649     #[stable(feature = "rust1", since = "1.0.0")]
650     #[rustc_doc_only_macro]
651     macro_rules! include_str {
652         ($file:expr) => ({ /* compiler built-in */ });
653         ($file:expr,) => ({ /* compiler built-in */ });
654     }
655
656     /// Includes a file as a reference to a byte array.
657     ///
658     /// The file is located relative to the current file. (similarly to how
659     /// modules are found)
660     ///
661     /// This macro will yield an expression of type `&'static [u8; N]` which is
662     /// the contents of the file.
663     ///
664     /// # Examples
665     ///
666     /// Assume there are two files in the same directory with the following
667     /// contents:
668     ///
669     /// File 'spanish.in':
670     ///
671     /// ```text
672     /// adiós
673     /// ```
674     ///
675     /// File 'main.rs':
676     ///
677     /// ```ignore (cannot-doctest-external-file-dependency)
678     /// fn main() {
679     ///     let bytes = include_bytes!("spanish.in");
680     ///     assert_eq!(bytes, b"adi\xc3\xb3s\n");
681     ///     print!("{}", String::from_utf8_lossy(bytes));
682     /// }
683     /// ```
684     ///
685     /// Compiling 'main.rs' and running the resulting binary will print "adiós".
686     #[stable(feature = "rust1", since = "1.0.0")]
687     #[rustc_doc_only_macro]
688     macro_rules! include_bytes {
689         ($file:expr) => ({ /* compiler built-in */ });
690         ($file:expr,) => ({ /* compiler built-in */ });
691     }
692
693     /// Expands to a string that represents the current module path.
694     ///
695     /// The current module path can be thought of as the hierarchy of modules
696     /// leading back up to the crate root. The first component of the path
697     /// returned is the name of the crate currently being compiled.
698     ///
699     /// # Examples
700     ///
701     /// ```
702     /// mod test {
703     ///     pub fn foo() {
704     ///         assert!(module_path!().ends_with("test"));
705     ///     }
706     /// }
707     ///
708     /// test::foo();
709     /// ```
710     #[stable(feature = "rust1", since = "1.0.0")]
711     #[rustc_doc_only_macro]
712     macro_rules! module_path { () => ({ /* compiler built-in */ }) }
713
714     /// Boolean evaluation of configuration flags, at compile-time.
715     ///
716     /// In addition to the `#[cfg]` attribute, this macro is provided to allow
717     /// boolean expression evaluation of configuration flags. This frequently
718     /// leads to less duplicated code.
719     ///
720     /// The syntax given to this macro is the same syntax as [the `cfg`
721     /// attribute](../book/first-edition/conditional-compilation.html).
722     ///
723     /// # Examples
724     ///
725     /// ```
726     /// let my_directory = if cfg!(windows) {
727     ///     "windows-specific-directory"
728     /// } else {
729     ///     "unix-directory"
730     /// };
731     /// ```
732     #[stable(feature = "rust1", since = "1.0.0")]
733     #[rustc_doc_only_macro]
734     macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
735
736     /// Parse a file as an expression or an item according to the context.
737     ///
738     /// The file is located relative to the current file (similarly to how
739     /// modules are found).
740     ///
741     /// Using this macro is often a bad idea, because if the file is
742     /// parsed as an expression, it is going to be placed in the
743     /// surrounding code unhygienically. This could result in variables
744     /// or functions being different from what the file expected if
745     /// there are variables or functions that have the same name in
746     /// the current file.
747     ///
748     /// # Examples
749     ///
750     /// Assume there are two files in the same directory with the following
751     /// contents:
752     ///
753     /// File 'monkeys.in':
754     ///
755     /// ```ignore (only-for-syntax-highlight)
756     /// ['🙈', '🙊', '🙉']
757     ///     .iter()
758     ///     .cycle()
759     ///     .take(6)
760     ///     .collect::<String>()
761     /// ```
762     ///
763     /// File 'main.rs':
764     ///
765     /// ```ignore (cannot-doctest-external-file-dependency)
766     /// fn main() {
767     ///     let my_string = include!("monkeys.in");
768     ///     assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
769     ///     println!("{}", my_string);
770     /// }
771     /// ```
772     ///
773     /// Compiling 'main.rs' and running the resulting binary will print
774     /// "🙈🙊🙉🙈🙊🙉".
775     #[stable(feature = "rust1", since = "1.0.0")]
776     #[rustc_doc_only_macro]
777     macro_rules! include {
778         ($file:expr) => ({ /* compiler built-in */ });
779         ($file:expr,) => ({ /* compiler built-in */ });
780     }
781
782     /// Ensure that a boolean expression is `true` at runtime.
783     ///
784     /// This will invoke the [`panic!`] macro if the provided expression cannot be
785     /// evaluated to `true` at runtime.
786     ///
787     /// # Uses
788     ///
789     /// Assertions are always checked in both debug and release builds, and cannot
790     /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
791     /// release builds by default.
792     ///
793     /// Unsafe code relies on `assert!` to enforce run-time invariants that, if
794     /// violated could lead to unsafety.
795     ///
796     /// Other use-cases of `assert!` include [testing] and enforcing run-time
797     /// invariants in safe code (whose violation cannot result in unsafety).
798     ///
799     /// # Custom Messages
800     ///
801     /// This macro has a second form, where a custom panic message can
802     /// be provided with or without arguments for formatting.  See [`std::fmt`]
803     /// for syntax for this form.
804     ///
805     /// [`panic!`]: macro.panic.html
806     /// [`debug_assert!`]: macro.debug_assert.html
807     /// [testing]: ../book/second-edition/ch11-01-writing-tests.html#checking-results-with-the-assert-macro
808     /// [`std::fmt`]: ../std/fmt/index.html
809     ///
810     /// # Examples
811     ///
812     /// ```
813     /// // the panic message for these assertions is the stringified value of the
814     /// // expression given.
815     /// assert!(true);
816     ///
817     /// fn some_computation() -> bool { true } // a very simple function
818     ///
819     /// assert!(some_computation());
820     ///
821     /// // assert with a custom message
822     /// let x = true;
823     /// assert!(x, "x wasn't true!");
824     ///
825     /// let a = 3; let b = 27;
826     /// assert!(a + b == 30, "a = {}, b = {}", a, b);
827     /// ```
828     #[stable(feature = "rust1", since = "1.0.0")]
829     #[rustc_doc_only_macro]
830     macro_rules! assert {
831         ($cond:expr) => ({ /* compiler built-in */ });
832         ($cond:expr,) => ({ /* compiler built-in */ });
833         ($cond:expr, $($arg:tt)+) => ({ /* compiler built-in */ });
834     }
835 }
836
837 /// A macro for defining `#[cfg]` if-else statements.
838 ///
839 /// This is similar to the `if/elif` C preprocessor macro by allowing definition
840 /// of a cascade of `#[cfg]` cases, emitting the implementation which matches
841 /// first.
842 ///
843 /// This allows you to conveniently provide a long list `#[cfg]`'d blocks of code
844 /// without having to rewrite each clause multiple times.
845 macro_rules! cfg_if {
846     ($(
847         if #[cfg($($meta:meta),*)] { $($it:item)* }
848     ) else * else {
849         $($it2:item)*
850     }) => {
851         __cfg_if_items! {
852             () ;
853             $( ( ($($meta),*) ($($it)*) ), )*
854             ( () ($($it2)*) ),
855         }
856     }
857 }
858
859 macro_rules! __cfg_if_items {
860     (($($not:meta,)*) ; ) => {};
861     (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
862         __cfg_if_apply! { cfg(all(not(any($($not),*)), $($m,)*)), $($it)* }
863         __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
864     }
865 }
866
867 macro_rules! __cfg_if_apply {
868     ($m:meta, $($it:item)*) => {
869         $(#[$m] $it)*
870     }
871 }