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