]> git.proxmox.com Git - rustc.git/blame - src/libstd/macros.rs
Imported Upstream version 1.9.0+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///
bd371182
AL
19/// This macro is used to inject panic into a Rust thread, causing the thread to
20/// unwind and panic entirely. Each thread's panic can be reaped as the
9346a6ac
AL
21/// `Box<Any>` type, and the single-argument form of the `panic!` macro will be
22/// the value which is transmitted.
23///
24/// The multi-argument form of this macro panics with a string and has the
25/// `format!` syntax for building a string.
26///
27/// # Examples
28///
29/// ```should_panic
30/// # #![allow(unreachable_code)]
31/// panic!();
32/// panic!("this is a terrible mistake!");
33/// panic!(4); // panic with the value of 4 to be collected elsewhere
34/// panic!("this is a {} {message}", "fancy", message = "message");
35/// ```
36#[macro_export]
37#[stable(feature = "rust1", since = "1.0.0")]
38#[allow_internal_unstable]
9346a6ac
AL
39macro_rules! panic {
40 () => ({
41 panic!("explicit panic")
42 });
43 ($msg:expr) => ({
44 $crate::rt::begin_unwind($msg, {
45 // static requires less code at runtime, more constant data
46 static _FILE_LINE: (&'static str, u32) = (file!(), line!());
47 &_FILE_LINE
48 })
49 });
50 ($fmt:expr, $($arg:tt)+) => ({
51 $crate::rt::begin_unwind_fmt(format_args!($fmt, $($arg)+), {
52 // The leading _'s are to avoid dead code warnings if this is
53 // used inside a dead function. Just `#[allow(dead_code)]` is
54 // insufficient, since the user may have
55 // `#[forbid(dead_code)]` and which cannot be overridden.
56 static _FILE_LINE: (&'static str, u32) = (file!(), line!());
1a4d82fc
JJ
57 &_FILE_LINE
58 })
59 });
60}
61
c34b1796
AL
62/// Macro for printing to the standard output.
63///
1a4d82fc
JJ
64/// Equivalent to the `println!` macro except that a newline is not printed at
65/// the end of the message.
c34b1796
AL
66///
67/// Note that stdout is frequently line-buffered by default so it may be
68/// necessary to use `io::stdout().flush()` to ensure the output is emitted
69/// immediately.
e9174d1e 70///
b039eaaf
SL
71/// # Panics
72///
73/// Panics if writing to `io::stdout()` fails.
74///
e9174d1e
SL
75/// # Examples
76///
77/// ```
78/// use std::io::{self, Write};
79///
80/// print!("this ");
81/// print!("will ");
82/// print!("be ");
83/// print!("on ");
84/// print!("the ");
85/// print!("same ");
86/// print!("line ");
87///
88/// io::stdout().flush().unwrap();
89///
90/// print!("this string has a newline, why not choose println! instead?\n");
91///
92/// io::stdout().flush().unwrap();
93/// ```
1a4d82fc 94#[macro_export]
85aaf69f 95#[stable(feature = "rust1", since = "1.0.0")]
c34b1796 96#[allow_internal_unstable]
1a4d82fc 97macro_rules! print {
c34b1796 98 ($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
1a4d82fc 99}
970d7e83 100
b039eaaf 101/// Macro for printing to the standard output, with a newline.
1a4d82fc 102///
c34b1796
AL
103/// Use the `format!` syntax to write data to the standard output.
104/// See `std::fmt` for more information.
1a4d82fc 105///
b039eaaf
SL
106/// # Panics
107///
108/// Panics if writing to `io::stdout()` fails.
109///
c34b1796 110/// # Examples
1a4d82fc
JJ
111///
112/// ```
113/// println!("hello there!");
114/// println!("format {} arguments", "some");
115/// ```
116#[macro_export]
85aaf69f 117#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 118macro_rules! println {
c34b1796
AL
119 ($fmt:expr) => (print!(concat!($fmt, "\n")));
120 ($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
1a4d82fc
JJ
121}
122
1a4d82fc
JJ
123/// A macro to select an event from a number of receivers.
124///
125/// This macro is used to wait for the first event to occur on a number of
126/// receivers. It places no restrictions on the types of receivers given to
127/// this macro, this can be viewed as a heterogeneous select.
128///
85aaf69f 129/// # Examples
1a4d82fc
JJ
130///
131/// ```
c1a9b12d
SL
132/// #![feature(mpsc_select)]
133///
85aaf69f
SL
134/// use std::thread;
135/// use std::sync::mpsc;
1a4d82fc 136///
85aaf69f 137/// // two placeholder functions for now
bd371182 138/// fn long_running_thread() {}
85aaf69f 139/// fn calculate_the_answer() -> u32 { 42 }
1a4d82fc 140///
85aaf69f
SL
141/// let (tx1, rx1) = mpsc::channel();
142/// let (tx2, rx2) = mpsc::channel();
143///
bd371182 144/// thread::spawn(move|| { long_running_thread(); tx1.send(()).unwrap(); });
85aaf69f 145/// thread::spawn(move|| { tx2.send(calculate_the_answer()).unwrap(); });
1a4d82fc 146///
d9579d0f 147/// select! {
bd371182 148/// _ = rx1.recv() => println!("the long running thread finished first"),
1a4d82fc
JJ
149/// answer = rx2.recv() => {
150/// println!("the answer was: {}", answer.unwrap());
151/// }
d9579d0f
AL
152/// }
153/// # drop(rx1.recv());
154/// # drop(rx2.recv());
1a4d82fc
JJ
155/// ```
156///
157/// For more information about select, see the `std::sync::mpsc::Select` structure.
158#[macro_export]
e9174d1e 159#[unstable(feature = "mpsc_select", issue = "27800")]
1a4d82fc
JJ
160macro_rules! select {
161 (
162 $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
163 ) => ({
164 use $crate::sync::mpsc::Select;
165 let sel = Select::new();
166 $( let mut $rx = sel.handle(&$rx); )+
167 unsafe {
168 $( $rx.add(); )+
970d7e83 169 }
1a4d82fc
JJ
170 let ret = sel.wait();
171 $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
172 { unreachable!() }
173 })
174}
175
e9174d1e
SL
176#[cfg(test)]
177macro_rules! assert_approx_eq {
178 ($a:expr, $b:expr) => ({
179 let (a, b) = (&$a, &$b);
180 assert!((*a - *b).abs() < 1.0e-6,
181 "{} is not approximately equal to {}", *a, *b);
182 })
183}
184
1a4d82fc
JJ
185/// Built-in macros to the compiler itself.
186///
187/// These macros do not have any corresponding definition with a `macro_rules!`
188/// macro, but are documented here. Their implementations can be found hardcoded
189/// into libsyntax itself.
190#[cfg(dox)]
191pub mod builtin {
192 /// The core macro for formatted string creation & output.
193 ///
194 /// This macro produces a value of type `fmt::Arguments`. This value can be
195 /// passed to the functions in `std::fmt` for performing useful functions.
196 /// All other formatting macros (`format!`, `write!`, `println!`, etc) are
197 /// proxied through this one.
198 ///
199 /// For more information, see the documentation in `std::fmt`.
200 ///
c34b1796 201 /// # Examples
1a4d82fc 202 ///
c34b1796 203 /// ```
1a4d82fc
JJ
204 /// use std::fmt;
205 ///
206 /// let s = fmt::format(format_args!("hello {}", "world"));
207 /// assert_eq!(s, format!("hello {}", "world"));
208 ///
209 /// ```
92a42be0 210 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
211 #[macro_export]
212 macro_rules! format_args { ($fmt:expr, $($args:tt)*) => ({
213 /* compiler built-in */
214 }) }
215
216 /// Inspect an environment variable at compile time.
217 ///
218 /// This macro will expand to the value of the named environment variable at
219 /// compile time, yielding an expression of type `&'static str`.
220 ///
221 /// If the environment variable is not defined, then a compilation error
222 /// will be emitted. To not emit a compile error, use the `option_env!`
223 /// macro instead.
224 ///
c34b1796 225 /// # Examples
1a4d82fc 226 ///
c34b1796 227 /// ```
1a4d82fc
JJ
228 /// let path: &'static str = env!("PATH");
229 /// println!("the $PATH variable at the time of compiling was: {}", path);
230 /// ```
92a42be0 231 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
232 #[macro_export]
233 macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
234
235 /// Optionally inspect an environment variable at compile time.
236 ///
237 /// If the named environment variable is present at compile time, this will
238 /// expand into an expression of type `Option<&'static str>` whose value is
239 /// `Some` of the value of the environment variable. If the environment
240 /// variable is not present, then this will expand to `None`.
241 ///
242 /// A compile time error is never emitted when using this macro regardless
243 /// of whether the environment variable is present or not.
244 ///
c34b1796 245 /// # Examples
1a4d82fc 246 ///
c34b1796 247 /// ```
1a4d82fc
JJ
248 /// let key: Option<&'static str> = option_env!("SECRET_KEY");
249 /// println!("the secret key might be: {:?}", key);
250 /// ```
92a42be0 251 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
252 #[macro_export]
253 macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
254
255 /// Concatenate identifiers into one identifier.
256 ///
257 /// This macro takes any number of comma-separated identifiers, and
258 /// concatenates them all into one, yielding an expression which is a new
259 /// identifier. Note that hygiene makes it such that this macro cannot
7453a54e
SL
260 /// capture local variables. Also, as a general rule, macros are only
261 /// allowed in item, statement or expression position. That means while
262 /// you may use this macro for referring to existing variables, functions or
263 /// modules etc, you cannot define a new one with it.
1a4d82fc 264 ///
85aaf69f 265 /// # Examples
1a4d82fc
JJ
266 ///
267 /// ```
268 /// #![feature(concat_idents)]
269 ///
270 /// # fn main() {
85aaf69f 271 /// fn foobar() -> u32 { 23 }
1a4d82fc
JJ
272 ///
273 /// let f = concat_idents!(foo, bar);
274 /// println!("{}", f());
7453a54e
SL
275 ///
276 /// // fn concat_idents!(new, fun, name) { } // not usable in this way!
1a4d82fc
JJ
277 /// # }
278 /// ```
92a42be0 279 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
280 #[macro_export]
281 macro_rules! concat_idents {
282 ($($e:ident),*) => ({ /* compiler built-in */ })
283 }
284
285 /// Concatenates literals into a static string slice.
286 ///
287 /// This macro takes any number of comma-separated literals, yielding an
288 /// expression of type `&'static str` which represents all of the literals
289 /// concatenated left-to-right.
290 ///
291 /// Integer and floating point literals are stringified in order to be
292 /// concatenated.
293 ///
c34b1796 294 /// # Examples
1a4d82fc
JJ
295 ///
296 /// ```
85aaf69f 297 /// let s = concat!("test", 10, 'b', true);
1a4d82fc
JJ
298 /// assert_eq!(s, "test10btrue");
299 /// ```
92a42be0 300 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
301 #[macro_export]
302 macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
303
304 /// A macro which expands to the line number on which it was invoked.
305 ///
62682a34 306 /// The expanded expression has type `u32`, and the returned line is not
1a4d82fc
JJ
307 /// the invocation of the `line!()` macro itself, but rather the first macro
308 /// invocation leading up to the invocation of the `line!()` macro.
309 ///
c34b1796 310 /// # Examples
1a4d82fc
JJ
311 ///
312 /// ```
313 /// let current_line = line!();
314 /// println!("defined on line: {}", current_line);
315 /// ```
92a42be0 316 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
317 #[macro_export]
318 macro_rules! line { () => ({ /* compiler built-in */ }) }
319
320 /// A macro which expands to the column number on which it was invoked.
321 ///
62682a34 322 /// The expanded expression has type `u32`, and the returned column is not
1a4d82fc
JJ
323 /// the invocation of the `column!()` macro itself, but rather the first macro
324 /// invocation leading up to the invocation of the `column!()` macro.
325 ///
c34b1796 326 /// # Examples
1a4d82fc
JJ
327 ///
328 /// ```
329 /// let current_col = column!();
330 /// println!("defined on column: {}", current_col);
331 /// ```
92a42be0 332 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
333 #[macro_export]
334 macro_rules! column { () => ({ /* compiler built-in */ }) }
335
336 /// A macro which expands to the file name from which it was invoked.
337 ///
338 /// The expanded expression has type `&'static str`, and the returned file
339 /// is not the invocation of the `file!()` macro itself, but rather the
340 /// first macro invocation leading up to the invocation of the `file!()`
341 /// macro.
342 ///
c34b1796 343 /// # Examples
1a4d82fc
JJ
344 ///
345 /// ```
346 /// let this_file = file!();
347 /// println!("defined in file: {}", this_file);
348 /// ```
92a42be0 349 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
350 #[macro_export]
351 macro_rules! file { () => ({ /* compiler built-in */ }) }
352
353 /// A macro which stringifies its argument.
354 ///
355 /// This macro will yield an expression of type `&'static str` which is the
356 /// stringification of all the tokens passed to the macro. No restrictions
357 /// are placed on the syntax of the macro invocation itself.
358 ///
7453a54e
SL
359 /// Note that the expanded results of the input tokens may change in the
360 /// future. You should be careful if you rely on the output.
361 ///
c34b1796 362 /// # Examples
1a4d82fc
JJ
363 ///
364 /// ```
365 /// let one_plus_one = stringify!(1 + 1);
366 /// assert_eq!(one_plus_one, "1 + 1");
367 /// ```
92a42be0 368 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
369 #[macro_export]
370 macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
371
372 /// Includes a utf8-encoded file as a string.
373 ///
374 /// This macro will yield an expression of type `&'static str` which is the
375 /// contents of the filename specified. The file is located relative to the
376 /// current file (similarly to how modules are found),
377 ///
c34b1796 378 /// # Examples
1a4d82fc
JJ
379 ///
380 /// ```rust,ignore
381 /// let secret_key = include_str!("secret-key.ascii");
382 /// ```
92a42be0 383 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
384 #[macro_export]
385 macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
386
e9174d1e 387 /// Includes a file as a reference to a byte array.
1a4d82fc 388 ///
e9174d1e 389 /// This macro will yield an expression of type `&'static [u8; N]` which is
1a4d82fc
JJ
390 /// the contents of the filename specified. The file is located relative to
391 /// the current file (similarly to how modules are found),
392 ///
c34b1796 393 /// # Examples
1a4d82fc
JJ
394 ///
395 /// ```rust,ignore
396 /// let secret_key = include_bytes!("secret-key.bin");
397 /// ```
92a42be0 398 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
399 #[macro_export]
400 macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
401
402 /// Expands to a string that represents the current module path.
403 ///
404 /// The current module path can be thought of as the hierarchy of modules
405 /// leading back up to the crate root. The first component of the path
406 /// returned is the name of the crate currently being compiled.
407 ///
c34b1796 408 /// # Examples
1a4d82fc 409 ///
c34b1796 410 /// ```
1a4d82fc
JJ
411 /// mod test {
412 /// pub fn foo() {
413 /// assert!(module_path!().ends_with("test"));
414 /// }
415 /// }
416 ///
417 /// test::foo();
418 /// ```
92a42be0 419 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
420 #[macro_export]
421 macro_rules! module_path { () => ({ /* compiler built-in */ }) }
422
423 /// Boolean evaluation of configuration flags.
424 ///
425 /// In addition to the `#[cfg]` attribute, this macro is provided to allow
426 /// boolean expression evaluation of configuration flags. This frequently
427 /// leads to less duplicated code.
428 ///
92a42be0
SL
429 /// The syntax given to this macro is the same syntax as [the `cfg`
430 /// attribute](../reference.html#conditional-compilation).
1a4d82fc 431 ///
c34b1796 432 /// # Examples
1a4d82fc 433 ///
c34b1796 434 /// ```
1a4d82fc
JJ
435 /// let my_directory = if cfg!(windows) {
436 /// "windows-specific-directory"
437 /// } else {
438 /// "unix-directory"
439 /// };
440 /// ```
92a42be0 441 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 442 #[macro_export]
92a42be0 443 macro_rules! cfg { ($($cfg:tt)*) => ({ /* compiler built-in */ }) }
c34b1796
AL
444
445 /// Parse the current given file as an expression.
446 ///
d9579d0f 447 /// This is generally a bad idea, because it's going to behave unhygienically.
c34b1796
AL
448 ///
449 /// # Examples
450 ///
451 /// ```ignore
452 /// fn foo() {
453 /// include!("/path/to/a/file")
454 /// }
455 /// ```
92a42be0 456 #[stable(feature = "rust1", since = "1.0.0")]
c34b1796 457 #[macro_export]
92a42be0 458 macro_rules! include { ($file:expr) => ({ /* compiler built-in */ }) }
1a4d82fc 459}