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