]> git.lizzy.rs Git - rust.git/blob - src/libstd/macros.rs
rollup merge of #20482: kmcallister/macro-reform
[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 #![experimental]
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!(4); // panic with the value of 4 to be collected elsewhere
36 /// panic!("this is a {} {message}", "fancy", message = "message");
37 /// ```
38 #[macro_export]
39 macro_rules! panic {
40     () => ({
41         panic!("explicit panic")
42     });
43     ($msg:expr) => ({
44         // static requires less code at runtime, more constant data
45         static _FILE_LINE: (&'static str, uint) = (file!(), line!());
46         ::std::rt::begin_unwind($msg, &_FILE_LINE)
47     });
48     ($fmt:expr, $($arg:tt)*) => ({
49         // The leading _'s are to avoid dead code warnings if this is
50         // used inside a dead function. Just `#[allow(dead_code)]` is
51         // insufficient, since the user may have
52         // `#[forbid(dead_code)]` and which cannot be overridden.
53         static _FILE_LINE: (&'static str, uint) = (file!(), line!());
54         ::std::rt::begin_unwind_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
55
56     });
57 }
58
59 /// Ensure that a boolean expression is `true` at runtime.
60 ///
61 /// This will invoke the `panic!` macro if the provided expression cannot be
62 /// evaluated to `true` at runtime.
63 ///
64 /// # Example
65 ///
66 /// ```
67 /// // the panic message for these assertions is the stringified value of the
68 /// // expression given.
69 /// assert!(true);
70 /// # fn some_computation() -> bool { true }
71 /// assert!(some_computation());
72 ///
73 /// // assert with a custom message
74 /// # let x = true;
75 /// assert!(x, "x wasn't true!");
76 /// # let a = 3; let b = 27;
77 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
78 /// ```
79 #[macro_export]
80 macro_rules! assert {
81     ($cond:expr) => (
82         if !$cond {
83             panic!(concat!("assertion failed: ", stringify!($cond)))
84         }
85     );
86     ($cond:expr, $($arg:expr),+) => (
87         if !$cond {
88             panic!($($arg),+)
89         }
90     );
91 }
92
93 /// Asserts that two expressions are equal to each other, testing equality in
94 /// both directions.
95 ///
96 /// On panic, this macro will print the values of the expressions.
97 ///
98 /// # Example
99 ///
100 /// ```
101 /// let a = 3;
102 /// let b = 1 + 2;
103 /// assert_eq!(a, b);
104 /// ```
105 #[macro_export]
106 macro_rules! assert_eq {
107     ($left:expr , $right:expr) => ({
108         match (&($left), &($right)) {
109             (left_val, right_val) => {
110                 // check both directions of equality....
111                 if !((*left_val == *right_val) &&
112                      (*right_val == *left_val)) {
113                     panic!("assertion failed: `(left == right) && (right == left)` \
114                            (left: `{}`, right: `{}`)", *left_val, *right_val)
115                 }
116             }
117         }
118     })
119 }
120
121 /// Ensure that a boolean expression is `true` at runtime.
122 ///
123 /// This will invoke the `panic!` macro if the provided expression cannot be
124 /// evaluated to `true` at runtime.
125 ///
126 /// Unlike `assert!`, `debug_assert!` statements can be disabled by passing
127 /// `--cfg ndebug` to the compiler. This makes `debug_assert!` useful for
128 /// checks that are too expensive to be present in a release build but may be
129 /// helpful during development.
130 ///
131 /// # Example
132 ///
133 /// ```
134 /// // the panic message for these assertions is the stringified value of the
135 /// // expression given.
136 /// debug_assert!(true);
137 /// # fn some_expensive_computation() -> bool { true }
138 /// debug_assert!(some_expensive_computation());
139 ///
140 /// // assert with a custom message
141 /// # let x = true;
142 /// debug_assert!(x, "x wasn't true!");
143 /// # let a = 3; let b = 27;
144 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
145 /// ```
146 #[macro_export]
147 macro_rules! debug_assert {
148     ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); })
149 }
150
151 /// Asserts that two expressions are equal to each other, testing equality in
152 /// both directions.
153 ///
154 /// On panic, this macro will print the values of the expressions.
155 ///
156 /// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by
157 /// passing `--cfg ndebug` to the compiler. This makes `debug_assert_eq!`
158 /// useful for checks that are too expensive to be present in a release build
159 /// but may be helpful during development.
160 ///
161 /// # Example
162 ///
163 /// ```
164 /// let a = 3;
165 /// let b = 1 + 2;
166 /// debug_assert_eq!(a, b);
167 /// ```
168 #[macro_export]
169 macro_rules! debug_assert_eq {
170     ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); })
171 }
172
173 /// A utility macro for indicating unreachable code.
174 ///
175 /// This is useful any time that the compiler can't determine that some code is unreachable. For
176 /// example:
177 ///
178 /// * Match arms with guard conditions.
179 /// * Loops that dynamically terminate.
180 /// * Iterators that dynamically terminate.
181 ///
182 /// # Panics
183 ///
184 /// This will always panic.
185 ///
186 /// # Examples
187 ///
188 /// Match arms:
189 ///
190 /// ```rust
191 /// fn foo(x: Option<int>) {
192 ///     match x {
193 ///         Some(n) if n >= 0 => println!("Some(Non-negative)"),
194 ///         Some(n) if n <  0 => println!("Some(Negative)"),
195 ///         Some(_)           => unreachable!(), // compile error if commented out
196 ///         None              => println!("None")
197 ///     }
198 /// }
199 /// ```
200 ///
201 /// Iterators:
202 ///
203 /// ```rust
204 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
205 ///     for i in std::iter::count(0_u32, 1) {
206 ///         if 3*i < i { panic!("u32 overflow"); }
207 ///         if x < 3*i { return i-1; }
208 ///     }
209 ///     unreachable!();
210 /// }
211 /// ```
212 #[macro_export]
213 macro_rules! unreachable {
214     () => ({
215         panic!("internal error: entered unreachable code")
216     });
217     ($msg:expr) => ({
218         unreachable!("{}", $msg)
219     });
220     ($fmt:expr, $($arg:tt)*) => ({
221         panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
222     });
223 }
224
225 /// A standardised placeholder for marking unfinished code. It panics with the
226 /// message `"not yet implemented"` when executed.
227 #[macro_export]
228 macro_rules! unimplemented {
229     () => (panic!("not yet implemented"))
230 }
231
232 /// Use the syntax described in `std::fmt` to create a value of type `String`.
233 /// See `std::fmt` for more information.
234 ///
235 /// # Example
236 ///
237 /// ```
238 /// format!("test");
239 /// format!("hello {}", "world!");
240 /// format!("x = {}, y = {y}", 10, y = 30);
241 /// ```
242 #[macro_export]
243 #[stable]
244 macro_rules! format {
245     ($($arg:tt)*) => (::std::fmt::format(format_args!($($arg)*)))
246 }
247
248 /// Equivalent to the `println!` macro except that a newline is not printed at
249 /// the end of the message.
250 #[macro_export]
251 #[stable]
252 macro_rules! print {
253     ($($arg:tt)*) => (::std::io::stdio::print_args(format_args!($($arg)*)))
254 }
255
256 /// Macro for printing to a task's stdout handle.
257 ///
258 /// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
259 /// The syntax of this macro is the same as that used for `format!`. For more
260 /// information, see `std::fmt` and `std::io::stdio`.
261 ///
262 /// # Example
263 ///
264 /// ```
265 /// println!("hello there!");
266 /// println!("format {} arguments", "some");
267 /// ```
268 #[macro_export]
269 #[stable]
270 macro_rules! println {
271     ($($arg:tt)*) => (::std::io::stdio::println_args(format_args!($($arg)*)))
272 }
273
274 /// Helper macro for unwrapping `Result` values while returning early with an
275 /// error if the value of the expression is `Err`. For more information, see
276 /// `std::io`.
277 #[macro_export]
278 macro_rules! try {
279     ($expr:expr) => ({
280         use $crate::result::Result::{Ok, Err};
281
282         match $expr {
283             Ok(val) => val,
284             Err(err) => return Err($crate::error::FromError::from_error(err)),
285         }
286     })
287 }
288
289 /// A macro to select an event from a number of receivers.
290 ///
291 /// This macro is used to wait for the first event to occur on a number of
292 /// receivers. It places no restrictions on the types of receivers given to
293 /// this macro, this can be viewed as a heterogeneous select.
294 ///
295 /// # Example
296 ///
297 /// ```
298 /// use std::thread::Thread;
299 /// use std::sync::mpsc::channel;
300 ///
301 /// let (tx1, rx1) = channel();
302 /// let (tx2, rx2) = channel();
303 /// # fn long_running_task() {}
304 /// # fn calculate_the_answer() -> int { 42 }
305 ///
306 /// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach();
307 /// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach();
308 ///
309 /// select! (
310 ///     _ = rx1.recv() => println!("the long running task finished first"),
311 ///     answer = rx2.recv() => {
312 ///         println!("the answer was: {}", answer.unwrap());
313 ///     }
314 /// )
315 /// ```
316 ///
317 /// For more information about select, see the `std::sync::mpsc::Select` structure.
318 #[macro_export]
319 #[experimental]
320 macro_rules! select {
321     (
322         $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
323     ) => ({
324         use $crate::sync::mpsc::Select;
325         let sel = Select::new();
326         $( let mut $rx = sel.handle(&$rx); )+
327         unsafe {
328             $( $rx.add(); )+
329         }
330         let ret = sel.wait();
331         $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
332         { unreachable!() }
333     })
334 }
335
336 // When testing the standard library, we link to the liblog crate to get the
337 // logging macros. In doing so, the liblog crate was linked against the real
338 // version of libstd, and uses a different std::fmt module than the test crate
339 // uses. To get around this difference, we redefine the log!() macro here to be
340 // just a dumb version of what it should be.
341 #[cfg(test)]
342 macro_rules! log {
343     ($lvl:expr, $($args:tt)*) => (
344         if log_enabled!($lvl) { println!($($args)*) }
345     )
346 }
347
348 /// Built-in macros to the compiler itself.
349 ///
350 /// These macros do not have any corresponding definition with a `macro_rules!`
351 /// macro, but are documented here. Their implementations can be found hardcoded
352 /// into libsyntax itself.
353 #[cfg(dox)]
354 pub mod builtin {
355     /// The core macro for formatted string creation & output.
356     ///
357     /// This macro produces a value of type `fmt::Arguments`. This value can be
358     /// passed to the functions in `std::fmt` for performing useful functions.
359     /// All other formatting macros (`format!`, `write!`, `println!`, etc) are
360     /// proxied through this one.
361     ///
362     /// For more information, see the documentation in `std::fmt`.
363     ///
364     /// # Example
365     ///
366     /// ```rust
367     /// use std::fmt;
368     ///
369     /// let s = fmt::format(format_args!("hello {}", "world"));
370     /// assert_eq!(s, format!("hello {}", "world"));
371     ///
372     /// ```
373     #[macro_export]
374     macro_rules! format_args { ($fmt:expr $($args:tt)*) => ({
375         /* compiler built-in */
376     }) }
377
378     /// Inspect an environment variable at compile time.
379     ///
380     /// This macro will expand to the value of the named environment variable at
381     /// compile time, yielding an expression of type `&'static str`.
382     ///
383     /// If the environment variable is not defined, then a compilation error
384     /// will be emitted.  To not emit a compile error, use the `option_env!`
385     /// macro instead.
386     ///
387     /// # Example
388     ///
389     /// ```rust
390     /// let path: &'static str = env!("PATH");
391     /// println!("the $PATH variable at the time of compiling was: {}", path);
392     /// ```
393     #[macro_export]
394     macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
395
396     /// Optionally inspect an environment variable at compile time.
397     ///
398     /// If the named environment variable is present at compile time, this will
399     /// expand into an expression of type `Option<&'static str>` whose value is
400     /// `Some` of the value of the environment variable. If the environment
401     /// variable is not present, then this will expand to `None`.
402     ///
403     /// A compile time error is never emitted when using this macro regardless
404     /// of whether the environment variable is present or not.
405     ///
406     /// # Example
407     ///
408     /// ```rust
409     /// let key: Option<&'static str> = option_env!("SECRET_KEY");
410     /// println!("the secret key might be: {}", key);
411     /// ```
412     #[macro_export]
413     macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
414
415     /// Concatenate literals into a static byte slice.
416     ///
417     /// This macro takes any number of comma-separated literal expressions,
418     /// yielding an expression of type `&'static [u8]` which is the
419     /// concatenation (left to right) of all the literals in their byte format.
420     ///
421     /// This extension currently only supports string literals, character
422     /// literals, and integers less than 256. The byte slice returned is the
423     /// utf8-encoding of strings and characters.
424     ///
425     /// # Example
426     ///
427     /// ```
428     /// let rust = bytes!("r", 'u', "st", 255);
429     /// assert_eq!(rust[1], b'u');
430     /// assert_eq!(rust[4], 255);
431     /// ```
432     #[macro_export]
433     macro_rules! bytes { ($($e:expr),*) => ({ /* compiler built-in */ }) }
434
435     /// Concatenate identifiers into one identifier.
436     ///
437     /// This macro takes any number of comma-separated identifiers, and
438     /// concatenates them all into one, yielding an expression which is a new
439     /// identifier. Note that hygiene makes it such that this macro cannot
440     /// capture local variables, and macros are only allowed in item,
441     /// statement or expression position, meaning this macro may be difficult to
442     /// use in some situations.
443     ///
444     /// # Example
445     ///
446     /// ```
447     /// #![feature(concat_idents)]
448     ///
449     /// # fn main() {
450     /// fn foobar() -> int { 23 }
451     ///
452     /// let f = concat_idents!(foo, bar);
453     /// println!("{}", f());
454     /// # }
455     /// ```
456     #[macro_export]
457     macro_rules! concat_idents {
458         ($($e:ident),*) => ({ /* compiler built-in */ })
459     }
460
461     /// Concatenates literals into a static string slice.
462     ///
463     /// This macro takes any number of comma-separated literals, yielding an
464     /// expression of type `&'static str` which represents all of the literals
465     /// concatenated left-to-right.
466     ///
467     /// Integer and floating point literals are stringified in order to be
468     /// concatenated.
469     ///
470     /// # Example
471     ///
472     /// ```
473     /// let s = concat!("test", 10, 'b', true);
474     /// assert_eq!(s, "test10btrue");
475     /// ```
476     #[macro_export]
477     macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
478
479     /// A macro which expands to the line number on which it was invoked.
480     ///
481     /// The expanded expression has type `uint`, and the returned line is not
482     /// the invocation of the `line!()` macro itself, but rather the first macro
483     /// invocation leading up to the invocation of the `line!()` macro.
484     ///
485     /// # Example
486     ///
487     /// ```
488     /// let current_line = line!();
489     /// println!("defined on line: {}", current_line);
490     /// ```
491     #[macro_export]
492     macro_rules! line { () => ({ /* compiler built-in */ }) }
493
494     /// A macro which expands to the column number on which it was invoked.
495     ///
496     /// The expanded expression has type `uint`, and the returned column is not
497     /// the invocation of the `column!()` macro itself, but rather the first macro
498     /// invocation leading up to the invocation of the `column!()` macro.
499     ///
500     /// # Example
501     ///
502     /// ```
503     /// let current_col = column!();
504     /// println!("defined on column: {}", current_col);
505     /// ```
506     #[macro_export]
507     macro_rules! column { () => ({ /* compiler built-in */ }) }
508
509     /// A macro which expands to the file name from which it was invoked.
510     ///
511     /// The expanded expression has type `&'static str`, and the returned file
512     /// is not the invocation of the `file!()` macro itself, but rather the
513     /// first macro invocation leading up to the invocation of the `file!()`
514     /// macro.
515     ///
516     /// # Example
517     ///
518     /// ```
519     /// let this_file = file!();
520     /// println!("defined in file: {}", this_file);
521     /// ```
522     #[macro_export]
523     macro_rules! file { () => ({ /* compiler built-in */ }) }
524
525     /// A macro which stringifies its argument.
526     ///
527     /// This macro will yield an expression of type `&'static str` which is the
528     /// stringification of all the tokens passed to the macro. No restrictions
529     /// are placed on the syntax of the macro invocation itself.
530     ///
531     /// # Example
532     ///
533     /// ```
534     /// let one_plus_one = stringify!(1 + 1);
535     /// assert_eq!(one_plus_one, "1 + 1");
536     /// ```
537     #[macro_export]
538     macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
539
540     /// Includes a utf8-encoded file as a string.
541     ///
542     /// This macro will yield an expression of type `&'static str` which is the
543     /// contents of the filename specified. The file is located relative to the
544     /// current file (similarly to how modules are found),
545     ///
546     /// # Example
547     ///
548     /// ```rust,ignore
549     /// let secret_key = include_str!("secret-key.ascii");
550     /// ```
551     #[macro_export]
552     macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
553
554     /// Includes a file as a byte slice.
555     ///
556     /// This macro will yield an expression of type `&'static [u8]` which is
557     /// the contents of the filename specified. The file is located relative to
558     /// the current file (similarly to how modules are found),
559     ///
560     /// # Example
561     ///
562     /// ```rust,ignore
563     /// let secret_key = include_bytes!("secret-key.bin");
564     /// ```
565     #[macro_export]
566     macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
567
568     /// Deprecated alias for `include_bytes!()`.
569     #[macro_export]
570     macro_rules! include_bin { ($file:expr) => ({ /* compiler built-in */}) }
571
572     /// Expands to a string that represents the current module path.
573     ///
574     /// The current module path can be thought of as the hierarchy of modules
575     /// leading back up to the crate root. The first component of the path
576     /// returned is the name of the crate currently being compiled.
577     ///
578     /// # Example
579     ///
580     /// ```rust
581     /// mod test {
582     ///     pub fn foo() {
583     ///         assert!(module_path!().ends_with("test"));
584     ///     }
585     /// }
586     ///
587     /// test::foo();
588     /// ```
589     #[macro_export]
590     macro_rules! module_path { () => ({ /* compiler built-in */ }) }
591
592     /// Boolean evaluation of configuration flags.
593     ///
594     /// In addition to the `#[cfg]` attribute, this macro is provided to allow
595     /// boolean expression evaluation of configuration flags. This frequently
596     /// leads to less duplicated code.
597     ///
598     /// The syntax given to this macro is the same syntax as the `cfg`
599     /// attribute.
600     ///
601     /// # Example
602     ///
603     /// ```rust
604     /// let my_directory = if cfg!(windows) {
605     ///     "windows-specific-directory"
606     /// } else {
607     ///     "unix-directory"
608     /// };
609     /// ```
610     #[macro_export]
611     macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) }
612 }