]> git.lizzy.rs Git - rust.git/blob - src/libstd/macros.rs
0995ab3c373ca19fc84b82db8b2950de194e78b2
[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 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/ch09-00-error-handling.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.eprintln.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 /// A macro for quick and dirty debugging with which you can inspect
224 /// the value of a given expression. An example:
225 ///
226 /// ```rust
227 /// #![feature(dbg_macro)]
228 ///
229 /// let a = 2;
230 /// let b = dbg!(a * 2) + 1;
231 /// //      ^-- prints: [src/main.rs:4] a * 2 = 4
232 /// assert_eq!(b, 5);
233 /// ```
234 ///
235 /// The macro works by using the `Debug` implementation of the type of
236 /// the given expression to print the value to [stderr] along with the
237 /// source location of the macro invocation as well as the source code
238 /// of the expression.
239 ///
240 /// Invoking the macro on an expression moves and takes ownership of it
241 /// before returning the evaluated expression unchanged. If the type
242 /// of the expression does not implement `Copy` and you don't want
243 /// to give up ownership, you can instead borrow with `dbg!(&expr)`
244 /// for some expression `expr`.
245 ///
246 /// Note that the macro is intended as a debugging tool and therefore you
247 /// should avoid having uses of it in version control for longer periods.
248 /// Use cases involving debug output that should be added to version control
249 /// may be better served by macros such as `debug!` from the `log` crate.
250 ///
251 /// # Stability
252 ///
253 /// The exact output printed by this macro should not be relied upon
254 /// and is subject to future changes.
255 ///
256 /// # Panics
257 ///
258 /// Panics if writing to `io::stderr` fails.
259 ///
260 /// # Further examples
261 ///
262 /// With a method call:
263 ///
264 /// ```rust
265 /// #![feature(dbg_macro)]
266 ///
267 /// fn foo(n: usize) {
268 ///     if let Some(_) = dbg!(n.checked_sub(4)) {
269 ///         // ...
270 ///     }
271 /// }
272 ///
273 /// foo(3)
274 /// ```
275 ///
276 /// This prints to [stderr]:
277 ///
278 /// ```text,ignore
279 /// [src/main.rs:4] n.checked_sub(4) = None
280 /// ```
281 ///
282 /// Naive factorial implementation:
283 ///
284 /// ```rust
285 /// #![feature(dbg_macro)]
286 ///
287 /// fn factorial(n: u32) -> u32 {
288 ///     if dbg!(n <= 1) {
289 ///         dbg!(1)
290 ///     } else {
291 ///         dbg!(n * factorial(n - 1))
292 ///     }
293 /// }
294 ///
295 /// dbg!(factorial(4));
296 /// ```
297 ///
298 /// This prints to [stderr]:
299 ///
300 /// ```text,ignore
301 /// [src/main.rs:3] n <= 1 = false
302 /// [src/main.rs:3] n <= 1 = false
303 /// [src/main.rs:3] n <= 1 = false
304 /// [src/main.rs:3] n <= 1 = true
305 /// [src/main.rs:4] 1 = 1
306 /// [src/main.rs:5] n * factorial(n - 1) = 2
307 /// [src/main.rs:5] n * factorial(n - 1) = 6
308 /// [src/main.rs:5] n * factorial(n - 1) = 24
309 /// [src/main.rs:11] factorial(4) = 24
310 /// ```
311 ///
312 /// The `dbg!(..)` macro moves the input:
313 ///
314 /// ```compile_fail
315 /// #![feature(dbg_macro)]
316 ///
317 /// /// A wrapper around `usize` which importantly is not Copyable.
318 /// #[derive(Debug)]
319 /// struct NoCopy(usize);
320 ///
321 /// let a = NoCopy(42);
322 /// let _ = dbg!(a); // <-- `a` is moved here.
323 /// let _ = dbg!(a); // <-- `a` is moved again; error!
324 /// ```
325 ///
326 /// [stderr]: https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)
327 #[macro_export]
328 #[unstable(feature = "dbg_macro", issue = "54306")]
329 macro_rules! dbg {
330     ($val:expr) => {
331         // Use of `match` here is intentional because it affects the lifetimes
332         // of temporaries - https://stackoverflow.com/a/48732525/1063961
333         match $val {
334             tmp => {
335                 eprintln!("[{}:{}] {} = {:#?}",
336                     file!(), line!(), stringify!($val), &tmp);
337                 tmp
338             }
339         }
340     }
341 }
342
343 #[macro_export]
344 #[unstable(feature = "await_macro", issue = "50547")]
345 #[allow_internal_unstable]
346 #[allow_internal_unsafe]
347 macro_rules! await {
348     ($e:expr) => { {
349         let mut pinned = $e;
350         loop {
351             if let $crate::task::Poll::Ready(x) =
352                 $crate::future::poll_with_tls_waker(unsafe {
353                     $crate::pin::Pin::new_unchecked(&mut pinned)
354                 })
355             {
356                 break x;
357             }
358             // FIXME(cramertj) prior to stabilizing await, we have to ensure that this
359             // can't be used to create a generator on stable via `|| await!()`.
360             yield
361         }
362     } }
363 }
364
365 /// A macro to select an event from a number of receivers.
366 ///
367 /// This macro is used to wait for the first event to occur on a number of
368 /// receivers. It places no restrictions on the types of receivers given to
369 /// this macro, this can be viewed as a heterogeneous select.
370 ///
371 /// # Examples
372 ///
373 /// ```
374 /// #![feature(mpsc_select)]
375 ///
376 /// use std::thread;
377 /// use std::sync::mpsc;
378 ///
379 /// // two placeholder functions for now
380 /// fn long_running_thread() {}
381 /// fn calculate_the_answer() -> u32 { 42 }
382 ///
383 /// let (tx1, rx1) = mpsc::channel();
384 /// let (tx2, rx2) = mpsc::channel();
385 ///
386 /// thread::spawn(move|| { long_running_thread(); tx1.send(()).unwrap(); });
387 /// thread::spawn(move|| { tx2.send(calculate_the_answer()).unwrap(); });
388 ///
389 /// select! {
390 ///     _ = rx1.recv() => println!("the long running thread finished first"),
391 ///     answer = rx2.recv() => {
392 ///         println!("the answer was: {}", answer.unwrap());
393 ///     }
394 /// }
395 /// # drop(rx1.recv());
396 /// # drop(rx2.recv());
397 /// ```
398 ///
399 /// For more information about select, see the `std::sync::mpsc::Select` structure.
400 #[macro_export]
401 #[unstable(feature = "mpsc_select", issue = "27800")]
402 #[rustc_deprecated(since = "1.32.0",
403                    reason = "channel selection will be removed in a future release")]
404 macro_rules! select {
405     (
406         $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
407     ) => ({
408         use $crate::sync::mpsc::Select;
409         let sel = Select::new();
410         $( let mut $rx = sel.handle(&$rx); )+
411         unsafe {
412             $( $rx.add(); )+
413         }
414         let ret = sel.wait();
415         $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
416         { unreachable!() }
417     })
418 }
419
420 #[cfg(test)]
421 macro_rules! assert_approx_eq {
422     ($a:expr, $b:expr) => ({
423         let (a, b) = (&$a, &$b);
424         assert!((*a - *b).abs() < 1.0e-6,
425                 "{} is not approximately equal to {}", *a, *b);
426     })
427 }
428
429 /// Built-in macros to the compiler itself.
430 ///
431 /// These macros do not have any corresponding definition with a `macro_rules!`
432 /// macro, but are documented here. Their implementations can be found hardcoded
433 /// into libsyntax itself.
434 #[cfg(rustdoc)]
435 mod builtin {
436
437     /// Unconditionally causes compilation to fail with the given error message when encountered.
438     ///
439     /// This macro should be used when a crate uses a conditional compilation strategy to provide
440     /// better error messages for erroneous conditions. It's the compiler-level form of [`panic!`],
441     /// which emits an error at *runtime*, rather than during compilation.
442     ///
443     /// # Examples
444     ///
445     /// Two such examples are macros and `#[cfg]` environments.
446     ///
447     /// Emit better compiler error if a macro is passed invalid values. Without the final branch,
448     /// the compiler would still emit an error, but the error's message would not mention the two
449     /// valid values.
450     ///
451     /// ```compile_fail
452     /// macro_rules! give_me_foo_or_bar {
453     ///     (foo) => {};
454     ///     (bar) => {};
455     ///     ($x:ident) => {
456     ///         compile_error!("This macro only accepts `foo` or `bar`");
457     ///     }
458     /// }
459     ///
460     /// give_me_foo_or_bar!(neither);
461     /// // ^ will fail at compile time with message "This macro only accepts `foo` or `bar`"
462     /// ```
463     ///
464     /// Emit compiler error if one of a number of features isn't available.
465     ///
466     /// ```compile_fail
467     /// #[cfg(not(any(feature = "foo", feature = "bar")))]
468     /// compile_error!("Either feature \"foo\" or \"bar\" must be enabled for this crate.")
469     /// ```
470     ///
471     /// [`panic!`]: ../std/macro.panic.html
472     #[stable(feature = "compile_error_macro", since = "1.20.0")]
473     #[rustc_doc_only_macro]
474     macro_rules! compile_error {
475         ($msg:expr) => ({ /* compiler built-in */ });
476         ($msg:expr,) => ({ /* compiler built-in */ });
477     }
478
479     /// The core macro for formatted string creation & output.
480     ///
481     /// This macro functions by taking a formatting string literal containing
482     /// `{}` for each additional argument passed.  `format_args!` prepares the
483     /// additional parameters to ensure the output can be interpreted as a string
484     /// and canonicalizes the arguments into a single type.  Any value that implements
485     /// the [`Display`] trait can be passed to `format_args!`, as can any
486     /// [`Debug`] implementation be passed to a `{:?}` within the formatting string.
487     ///
488     /// This macro produces a value of type [`fmt::Arguments`]. This value can be
489     /// passed to the macros within [`std::fmt`] for performing useful redirection.
490     /// All other formatting macros ([`format!`], [`write!`], [`println!`], etc) are
491     /// proxied through this one.  `format_args!`, unlike its derived macros, avoids
492     /// heap allocations.
493     ///
494     /// You can use the [`fmt::Arguments`] value that `format_args!` returns
495     /// in `Debug` and `Display` contexts as seen below. The example also shows
496     /// that `Debug` and `Display` format to the same thing: the interpolated
497     /// format string in `format_args!`.
498     ///
499     /// ```rust
500     /// let debug = format!("{:?}", format_args!("{} foo {:?}", 1, 2));
501     /// let display = format!("{}", format_args!("{} foo {:?}", 1, 2));
502     /// assert_eq!("1 foo 2", display);
503     /// assert_eq!(display, debug);
504     /// ```
505     ///
506     /// For more information, see the documentation in [`std::fmt`].
507     ///
508     /// [`Display`]: ../std/fmt/trait.Display.html
509     /// [`Debug`]: ../std/fmt/trait.Debug.html
510     /// [`fmt::Arguments`]: ../std/fmt/struct.Arguments.html
511     /// [`std::fmt`]: ../std/fmt/index.html
512     /// [`format!`]: ../std/macro.format.html
513     /// [`write!`]: ../std/macro.write.html
514     /// [`println!`]: ../std/macro.println.html
515     ///
516     /// # Examples
517     ///
518     /// ```
519     /// use std::fmt;
520     ///
521     /// let s = fmt::format(format_args!("hello {}", "world"));
522     /// assert_eq!(s, format!("hello {}", "world"));
523     /// ```
524     #[stable(feature = "rust1", since = "1.0.0")]
525     #[rustc_doc_only_macro]
526     macro_rules! format_args {
527         ($fmt:expr) => ({ /* compiler built-in */ });
528         ($fmt:expr, $($args:tt)*) => ({ /* compiler built-in */ });
529     }
530
531     /// Inspect an environment variable at compile time.
532     ///
533     /// This macro will expand to the value of the named environment variable at
534     /// compile time, yielding an expression of type `&'static str`.
535     ///
536     /// If the environment variable is not defined, then a compilation error
537     /// will be emitted. To not emit a compile error, use the [`option_env!`]
538     /// macro instead.
539     ///
540     /// [`option_env!`]: ../std/macro.option_env.html
541     ///
542     /// # Examples
543     ///
544     /// ```
545     /// let path: &'static str = env!("PATH");
546     /// println!("the $PATH variable at the time of compiling was: {}", path);
547     /// ```
548     ///
549     /// You can customize the error message by passing a string as the second
550     /// parameter:
551     ///
552     /// ```compile_fail
553     /// let doc: &'static str = env!("documentation", "what's that?!");
554     /// ```
555     ///
556     /// If the `documentation` environment variable is not defined, you'll get
557     /// the following error:
558     ///
559     /// ```text
560     /// error: what's that?!
561     /// ```
562     #[stable(feature = "rust1", since = "1.0.0")]
563     #[rustc_doc_only_macro]
564     macro_rules! env {
565         ($name:expr) => ({ /* compiler built-in */ });
566         ($name:expr,) => ({ /* compiler built-in */ });
567     }
568
569     /// Optionally inspect an environment variable at compile time.
570     ///
571     /// If the named environment variable is present at compile time, this will
572     /// expand into an expression of type `Option<&'static str>` whose value is
573     /// `Some` of the value of the environment variable. If the environment
574     /// variable is not present, then this will expand to `None`.  See
575     /// [`Option<T>`][option] for more information on this type.
576     ///
577     /// A compile time error is never emitted when using this macro regardless
578     /// of whether the environment variable is present or not.
579     ///
580     /// [option]: ../std/option/enum.Option.html
581     ///
582     /// # Examples
583     ///
584     /// ```
585     /// let key: Option<&'static str> = option_env!("SECRET_KEY");
586     /// println!("the secret key might be: {:?}", key);
587     /// ```
588     #[stable(feature = "rust1", since = "1.0.0")]
589     #[rustc_doc_only_macro]
590     macro_rules! option_env {
591         ($name:expr) => ({ /* compiler built-in */ });
592         ($name:expr,) => ({ /* compiler built-in */ });
593     }
594
595     /// Concatenate identifiers into one identifier.
596     ///
597     /// This macro takes any number of comma-separated identifiers, and
598     /// concatenates them all into one, yielding an expression which is a new
599     /// identifier. Note that hygiene makes it such that this macro cannot
600     /// capture local variables. Also, as a general rule, macros are only
601     /// allowed in item, statement or expression position. That means while
602     /// you may use this macro for referring to existing variables, functions or
603     /// modules etc, you cannot define a new one with it.
604     ///
605     /// # Examples
606     ///
607     /// ```
608     /// #![feature(concat_idents)]
609     ///
610     /// # fn main() {
611     /// fn foobar() -> u32 { 23 }
612     ///
613     /// let f = concat_idents!(foo, bar);
614     /// println!("{}", f());
615     ///
616     /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
617     /// # }
618     /// ```
619     #[unstable(feature = "concat_idents_macro", issue = "29599")]
620     #[rustc_doc_only_macro]
621     macro_rules! concat_idents {
622         ($($e:ident),+) => ({ /* compiler built-in */ });
623         ($($e:ident,)+) => ({ /* compiler built-in */ });
624     }
625
626     /// Concatenates literals into a static string slice.
627     ///
628     /// This macro takes any number of comma-separated literals, yielding an
629     /// expression of type `&'static str` which represents all of the literals
630     /// concatenated left-to-right.
631     ///
632     /// Integer and floating point literals are stringified in order to be
633     /// concatenated.
634     ///
635     /// # Examples
636     ///
637     /// ```
638     /// let s = concat!("test", 10, 'b', true);
639     /// assert_eq!(s, "test10btrue");
640     /// ```
641     #[stable(feature = "rust1", since = "1.0.0")]
642     #[rustc_doc_only_macro]
643     macro_rules! concat {
644         ($($e:expr),*) => ({ /* compiler built-in */ });
645         ($($e:expr,)*) => ({ /* compiler built-in */ });
646     }
647
648     /// A macro which expands to the line number on which it was invoked.
649     ///
650     /// With [`column!`] and [`file!`], these macros provide debugging information for
651     /// developers about the location within the source.
652     ///
653     /// The expanded expression has type `u32` and is 1-based, so the first line
654     /// in each file evaluates to 1, the second to 2, etc. This is consistent
655     /// with error messages by common compilers or popular editors.
656     /// The returned line is *not necessarily* the line of the `line!` invocation itself,
657     /// but rather the first macro invocation leading up to the invocation
658     /// of the `line!` macro.
659     ///
660     /// [`column!`]: macro.column.html
661     /// [`file!`]: macro.file.html
662     ///
663     /// # Examples
664     ///
665     /// ```
666     /// let current_line = line!();
667     /// println!("defined on line: {}", current_line);
668     /// ```
669     #[stable(feature = "rust1", since = "1.0.0")]
670     #[rustc_doc_only_macro]
671     macro_rules! line { () => ({ /* compiler built-in */ }) }
672
673     /// A macro which expands to the column number on which it was invoked.
674     ///
675     /// With [`line!`] and [`file!`], these macros provide debugging information for
676     /// developers about the location within the source.
677     ///
678     /// The expanded expression has type `u32` and is 1-based, so the first column
679     /// in each line evaluates to 1, the second to 2, etc. This is consistent
680     /// with error messages by common compilers or popular editors.
681     /// The returned column is *not necessarily* the line of the `column!` invocation itself,
682     /// but rather the first macro invocation leading up to the invocation
683     /// of the `column!` macro.
684     ///
685     /// [`line!`]: macro.line.html
686     /// [`file!`]: macro.file.html
687     ///
688     /// # Examples
689     ///
690     /// ```
691     /// let current_col = column!();
692     /// println!("defined on column: {}", current_col);
693     /// ```
694     #[stable(feature = "rust1", since = "1.0.0")]
695     #[rustc_doc_only_macro]
696     macro_rules! column { () => ({ /* compiler built-in */ }) }
697
698     /// A macro which expands to the file name from which it was invoked.
699     ///
700     /// With [`line!`] and [`column!`], these macros provide debugging information for
701     /// developers about the location within the source.
702     ///
703     ///
704     /// The expanded expression has type `&'static str`, and the returned file
705     /// is not the invocation of the `file!` macro itself, but rather the
706     /// first macro invocation leading up to the invocation of the `file!`
707     /// macro.
708     ///
709     /// [`line!`]: macro.line.html
710     /// [`column!`]: macro.column.html
711     ///
712     /// # Examples
713     ///
714     /// ```
715     /// let this_file = file!();
716     /// println!("defined in file: {}", this_file);
717     /// ```
718     #[stable(feature = "rust1", since = "1.0.0")]
719     #[rustc_doc_only_macro]
720     macro_rules! file { () => ({ /* compiler built-in */ }) }
721
722     /// A macro which stringifies its arguments.
723     ///
724     /// This macro will yield an expression of type `&'static str` which is the
725     /// stringification of all the tokens passed to the macro. No restrictions
726     /// are placed on the syntax of the macro invocation itself.
727     ///
728     /// Note that the expanded results of the input tokens may change in the
729     /// future. You should be careful if you rely on the output.
730     ///
731     /// # Examples
732     ///
733     /// ```
734     /// let one_plus_one = stringify!(1 + 1);
735     /// assert_eq!(one_plus_one, "1 + 1");
736     /// ```
737     #[stable(feature = "rust1", since = "1.0.0")]
738     #[rustc_doc_only_macro]
739     macro_rules! stringify { ($($t:tt)*) => ({ /* compiler built-in */ }) }
740
741     /// Includes a utf8-encoded file as a string.
742     ///
743     /// The file is located relative to the current file. (similarly to how
744     /// modules are found)
745     ///
746     /// This macro will yield an expression of type `&'static str` which is the
747     /// contents of the file.
748     ///
749     /// # Examples
750     ///
751     /// Assume there are two files in the same directory with the following
752     /// contents:
753     ///
754     /// File 'spanish.in':
755     ///
756     /// ```text
757     /// adiós
758     /// ```
759     ///
760     /// File 'main.rs':
761     ///
762     /// ```ignore (cannot-doctest-external-file-dependency)
763     /// fn main() {
764     ///     let my_str = include_str!("spanish.in");
765     ///     assert_eq!(my_str, "adiós\n");
766     ///     print!("{}", my_str);
767     /// }
768     /// ```
769     ///
770     /// Compiling 'main.rs' and running the resulting binary will print "adiós".
771     #[stable(feature = "rust1", since = "1.0.0")]
772     #[rustc_doc_only_macro]
773     macro_rules! include_str {
774         ($file:expr) => ({ /* compiler built-in */ });
775         ($file:expr,) => ({ /* compiler built-in */ });
776     }
777
778     /// Includes a file as a reference to a byte array.
779     ///
780     /// The file is located relative to the current file. (similarly to how
781     /// modules are found)
782     ///
783     /// This macro will yield an expression of type `&'static [u8; N]` which is
784     /// the contents of the file.
785     ///
786     /// # Examples
787     ///
788     /// Assume there are two files in the same directory with the following
789     /// contents:
790     ///
791     /// File 'spanish.in':
792     ///
793     /// ```text
794     /// adiós
795     /// ```
796     ///
797     /// File 'main.rs':
798     ///
799     /// ```ignore (cannot-doctest-external-file-dependency)
800     /// fn main() {
801     ///     let bytes = include_bytes!("spanish.in");
802     ///     assert_eq!(bytes, b"adi\xc3\xb3s\n");
803     ///     print!("{}", String::from_utf8_lossy(bytes));
804     /// }
805     /// ```
806     ///
807     /// Compiling 'main.rs' and running the resulting binary will print "adiós".
808     #[stable(feature = "rust1", since = "1.0.0")]
809     #[rustc_doc_only_macro]
810     macro_rules! include_bytes {
811         ($file:expr) => ({ /* compiler built-in */ });
812         ($file:expr,) => ({ /* compiler built-in */ });
813     }
814
815     /// Expands to a string that represents the current module path.
816     ///
817     /// The current module path can be thought of as the hierarchy of modules
818     /// leading back up to the crate root. The first component of the path
819     /// returned is the name of the crate currently being compiled.
820     ///
821     /// # Examples
822     ///
823     /// ```
824     /// mod test {
825     ///     pub fn foo() {
826     ///         assert!(module_path!().ends_with("test"));
827     ///     }
828     /// }
829     ///
830     /// test::foo();
831     /// ```
832     #[stable(feature = "rust1", since = "1.0.0")]
833     #[rustc_doc_only_macro]
834     macro_rules! module_path { () => ({ /* compiler built-in */ }) }
835
836     /// Boolean evaluation of configuration flags, at compile-time.
837     ///
838     /// In addition to the `#[cfg]` attribute, this macro is provided to allow
839     /// boolean expression evaluation of configuration flags. This frequently
840     /// leads to less duplicated code.
841     ///
842     /// The syntax given to this macro is the same syntax as the `cfg`
843     /// attribute.
844     ///
845     /// # Examples
846     ///
847     /// ```
848     /// let my_directory = if cfg!(windows) {
849     ///     "windows-specific-directory"
850     /// } else {
851     ///     "unix-directory"
852     /// };
853     /// ```
854     #[stable(feature = "rust1", since = "1.0.0")]
855     #[rustc_doc_only_macro]
856     macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
857
858     /// Parse a file as an expression or an item according to the context.
859     ///
860     /// The file is located relative to the current file (similarly to how
861     /// modules are found).
862     ///
863     /// Using this macro is often a bad idea, because if the file is
864     /// parsed as an expression, it is going to be placed in the
865     /// surrounding code unhygienically. This could result in variables
866     /// or functions being different from what the file expected if
867     /// there are variables or functions that have the same name in
868     /// the current file.
869     ///
870     /// # Examples
871     ///
872     /// Assume there are two files in the same directory with the following
873     /// contents:
874     ///
875     /// File 'monkeys.in':
876     ///
877     /// ```ignore (only-for-syntax-highlight)
878     /// ['🙈', '🙊', '🙉']
879     ///     .iter()
880     ///     .cycle()
881     ///     .take(6)
882     ///     .collect::<String>()
883     /// ```
884     ///
885     /// File 'main.rs':
886     ///
887     /// ```ignore (cannot-doctest-external-file-dependency)
888     /// fn main() {
889     ///     let my_string = include!("monkeys.in");
890     ///     assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
891     ///     println!("{}", my_string);
892     /// }
893     /// ```
894     ///
895     /// Compiling 'main.rs' and running the resulting binary will print
896     /// "🙈🙊🙉🙈🙊🙉".
897     #[stable(feature = "rust1", since = "1.0.0")]
898     #[rustc_doc_only_macro]
899     macro_rules! include {
900         ($file:expr) => ({ /* compiler built-in */ });
901         ($file:expr,) => ({ /* compiler built-in */ });
902     }
903
904     /// Ensure that a boolean expression is `true` at runtime.
905     ///
906     /// This will invoke the [`panic!`] macro if the provided expression cannot be
907     /// evaluated to `true` at runtime.
908     ///
909     /// # Uses
910     ///
911     /// Assertions are always checked in both debug and release builds, and cannot
912     /// be disabled. See [`debug_assert!`] for assertions that are not enabled in
913     /// release builds by default.
914     ///
915     /// Unsafe code relies on `assert!` to enforce run-time invariants that, if
916     /// violated could lead to unsafety.
917     ///
918     /// Other use-cases of `assert!` include testing and enforcing run-time
919     /// invariants in safe code (whose violation cannot result in unsafety).
920     ///
921     /// # Custom Messages
922     ///
923     /// This macro has a second form, where a custom panic message can
924     /// be provided with or without arguments for formatting.  See [`std::fmt`]
925     /// for syntax for this form.
926     ///
927     /// [`panic!`]: macro.panic.html
928     /// [`debug_assert!`]: macro.debug_assert.html
929     /// [`std::fmt`]: ../std/fmt/index.html
930     ///
931     /// # Examples
932     ///
933     /// ```
934     /// // the panic message for these assertions is the stringified value of the
935     /// // expression given.
936     /// assert!(true);
937     ///
938     /// fn some_computation() -> bool { true } // a very simple function
939     ///
940     /// assert!(some_computation());
941     ///
942     /// // assert with a custom message
943     /// let x = true;
944     /// assert!(x, "x wasn't true!");
945     ///
946     /// let a = 3; let b = 27;
947     /// assert!(a + b == 30, "a = {}, b = {}", a, b);
948     /// ```
949     #[stable(feature = "rust1", since = "1.0.0")]
950     #[rustc_doc_only_macro]
951     macro_rules! assert {
952         ($cond:expr) => ({ /* compiler built-in */ });
953         ($cond:expr,) => ({ /* compiler built-in */ });
954         ($cond:expr, $($arg:tt)+) => ({ /* compiler built-in */ });
955     }
956 }
957
958 /// A macro for defining `#[cfg]` if-else statements.
959 ///
960 /// This is similar to the `if/elif` C preprocessor macro by allowing definition
961 /// of a cascade of `#[cfg]` cases, emitting the implementation which matches
962 /// first.
963 ///
964 /// This allows you to conveniently provide a long list `#[cfg]`'d blocks of code
965 /// without having to rewrite each clause multiple times.
966 macro_rules! cfg_if {
967     ($(
968         if #[cfg($($meta:meta),*)] { $($it:item)* }
969     ) else * else {
970         $($it2:item)*
971     }) => {
972         __cfg_if_items! {
973             () ;
974             $( ( ($($meta),*) ($($it)*) ), )*
975             ( () ($($it2)*) ),
976         }
977     }
978 }
979
980 macro_rules! __cfg_if_items {
981     (($($not:meta,)*) ; ) => {};
982     (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
983         __cfg_if_apply! { cfg(all(not(any($($not),*)), $($m,)*)), $($it)* }
984         __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
985     }
986 }
987
988 macro_rules! __cfg_if_apply {
989     ($m:meta, $($it:item)*) => {
990         $(#[$m] $it)*
991     }
992 }