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