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