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