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