]> git.lizzy.rs Git - rust.git/blob - src/libstd/macros.rs
rollup merge of #20377: alexcrichton/issue-20352
[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!(4i); // 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 = 3i; let b = 27i;
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 = 3i;
103 /// let b = 1i + 2i;
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 = 3i; let b = 27i;
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 = 3i;
166 /// let b = 1i + 2i;
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}", 10i, y = 30i);
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         use std::slice::BoxedSliceExt;
321         let xs: ::std::boxed::Box<[_]> = box [$($x),*];
322         xs.into_vec()
323     });
324     ($($x:expr,)*) => (vec![$($x),*])
325 }
326
327 /// A macro to select an event from a number of receivers.
328 ///
329 /// This macro is used to wait for the first event to occur on a number of
330 /// receivers. It places no restrictions on the types of receivers given to
331 /// this macro, this can be viewed as a heterogeneous select.
332 ///
333 /// # Example
334 ///
335 /// ```
336 /// use std::thread::Thread;
337 /// use std::sync::mpsc::channel;
338 ///
339 /// let (tx1, rx1) = channel();
340 /// let (tx2, rx2) = channel();
341 /// # fn long_running_task() {}
342 /// # fn calculate_the_answer() -> int { 42i }
343 ///
344 /// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach();
345 /// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach();
346 ///
347 /// select! (
348 ///     _ = rx1.recv() => println!("the long running task finished first"),
349 ///     answer = rx2.recv() => {
350 ///         println!("the answer was: {}", answer.unwrap());
351 ///     }
352 /// )
353 /// ```
354 ///
355 /// For more information about select, see the `std::sync::mpsc::Select` structure.
356 #[macro_export]
357 #[experimental]
358 macro_rules! select {
359     (
360         $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
361     ) => ({
362         use std::sync::mpsc::Select;
363         let sel = Select::new();
364         $( let mut $rx = sel.handle(&$rx); )+
365         unsafe {
366             $( $rx.add(); )+
367         }
368         let ret = sel.wait();
369         $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
370         { unreachable!() }
371     })
372 }
373
374 // When testing the standard library, we link to the liblog crate to get the
375 // logging macros. In doing so, the liblog crate was linked against the real
376 // version of libstd, and uses a different std::fmt module than the test crate
377 // uses. To get around this difference, we redefine the log!() macro here to be
378 // just a dumb version of what it should be.
379 #[cfg(test)]
380 macro_rules! log {
381     ($lvl:expr, $($args:tt)*) => (
382         if log_enabled!($lvl) { println!($($args)*) }
383     )
384 }
385
386 /// Built-in macros to the compiler itself.
387 ///
388 /// These macros do not have any corresponding definition with a `macro_rules!`
389 /// macro, but are documented here. Their implementations can be found hardcoded
390 /// into libsyntax itself.
391 #[cfg(dox)]
392 pub mod builtin {
393     /// The core macro for formatted string creation & output.
394     ///
395     /// This macro produces a value of type `fmt::Arguments`. This value can be
396     /// passed to the functions in `std::fmt` for performing useful functions.
397     /// All other formatting macros (`format!`, `write!`, `println!`, etc) are
398     /// proxied through this one.
399     ///
400     /// For more information, see the documentation in `std::fmt`.
401     ///
402     /// # Example
403     ///
404     /// ```rust
405     /// use std::fmt;
406     ///
407     /// let s = fmt::format(format_args!("hello {}", "world"));
408     /// assert_eq!(s, format!("hello {}", "world"));
409     ///
410     /// ```
411     #[macro_export]
412     macro_rules! format_args { ($fmt:expr $($args:tt)*) => ({
413         /* compiler built-in */
414     }) }
415
416     /// Inspect an environment variable at compile time.
417     ///
418     /// This macro will expand to the value of the named environment variable at
419     /// compile time, yielding an expression of type `&'static str`.
420     ///
421     /// If the environment variable is not defined, then a compilation error
422     /// will be emitted.  To not emit a compile error, use the `option_env!`
423     /// macro instead.
424     ///
425     /// # Example
426     ///
427     /// ```rust
428     /// let path: &'static str = env!("PATH");
429     /// println!("the $PATH variable at the time of compiling was: {}", path);
430     /// ```
431     #[macro_export]
432     macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
433
434     /// Optionally inspect an environment variable at compile time.
435     ///
436     /// If the named environment variable is present at compile time, this will
437     /// expand into an expression of type `Option<&'static str>` whose value is
438     /// `Some` of the value of the environment variable. If the environment
439     /// variable is not present, then this will expand to `None`.
440     ///
441     /// A compile time error is never emitted when using this macro regardless
442     /// of whether the environment variable is present or not.
443     ///
444     /// # Example
445     ///
446     /// ```rust
447     /// let key: Option<&'static str> = option_env!("SECRET_KEY");
448     /// println!("the secret key might be: {}", key);
449     /// ```
450     #[macro_export]
451     macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
452
453     /// Concatenate literals into a static byte slice.
454     ///
455     /// This macro takes any number of comma-separated literal expressions,
456     /// yielding an expression of type `&'static [u8]` which is the
457     /// concatenation (left to right) of all the literals in their byte format.
458     ///
459     /// This extension currently only supports string literals, character
460     /// literals, and integers less than 256. The byte slice returned is the
461     /// utf8-encoding of strings and characters.
462     ///
463     /// # Example
464     ///
465     /// ```
466     /// let rust = bytes!("r", 'u', "st", 255);
467     /// assert_eq!(rust[1], b'u');
468     /// assert_eq!(rust[4], 255);
469     /// ```
470     #[macro_export]
471     macro_rules! bytes { ($($e:expr),*) => ({ /* compiler built-in */ }) }
472
473     /// Concatenate identifiers into one identifier.
474     ///
475     /// This macro takes any number of comma-separated identifiers, and
476     /// concatenates them all into one, yielding an expression which is a new
477     /// identifier. Note that hygiene makes it such that this macro cannot
478     /// capture local variables, and macros are only allowed in item,
479     /// statement or expression position, meaning this macro may be difficult to
480     /// use in some situations.
481     ///
482     /// # Example
483     ///
484     /// ```
485     /// #![feature(concat_idents)]
486     ///
487     /// # fn main() {
488     /// fn foobar() -> int { 23 }
489     ///
490     /// let f = concat_idents!(foo, bar);
491     /// println!("{}", f());
492     /// # }
493     /// ```
494     #[macro_export]
495     macro_rules! concat_idents {
496         ($($e:ident),*) => ({ /* compiler built-in */ })
497     }
498
499     /// Concatenates literals into a static string slice.
500     ///
501     /// This macro takes any number of comma-separated literals, yielding an
502     /// expression of type `&'static str` which represents all of the literals
503     /// concatenated left-to-right.
504     ///
505     /// Integer and floating point literals are stringified in order to be
506     /// concatenated.
507     ///
508     /// # Example
509     ///
510     /// ```
511     /// let s = concat!("test", 10i, 'b', true);
512     /// assert_eq!(s, "test10btrue");
513     /// ```
514     #[macro_export]
515     macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
516
517     /// A macro which expands to the line number on which it was invoked.
518     ///
519     /// The expanded expression has type `uint`, and the returned line is not
520     /// the invocation of the `line!()` macro itself, but rather the first macro
521     /// invocation leading up to the invocation of the `line!()` macro.
522     ///
523     /// # Example
524     ///
525     /// ```
526     /// let current_line = line!();
527     /// println!("defined on line: {}", current_line);
528     /// ```
529     #[macro_export]
530     macro_rules! line { () => ({ /* compiler built-in */ }) }
531
532     /// A macro which expands to the column number on which it was invoked.
533     ///
534     /// The expanded expression has type `uint`, and the returned column is not
535     /// the invocation of the `column!()` macro itself, but rather the first macro
536     /// invocation leading up to the invocation of the `column!()` macro.
537     ///
538     /// # Example
539     ///
540     /// ```
541     /// let current_col = column!();
542     /// println!("defined on column: {}", current_col);
543     /// ```
544     #[macro_export]
545     macro_rules! column { () => ({ /* compiler built-in */ }) }
546
547     /// A macro which expands to the file name from which it was invoked.
548     ///
549     /// The expanded expression has type `&'static str`, and the returned file
550     /// is not the invocation of the `file!()` macro itself, but rather the
551     /// first macro invocation leading up to the invocation of the `file!()`
552     /// macro.
553     ///
554     /// # Example
555     ///
556     /// ```
557     /// let this_file = file!();
558     /// println!("defined in file: {}", this_file);
559     /// ```
560     #[macro_export]
561     macro_rules! file { () => ({ /* compiler built-in */ }) }
562
563     /// A macro which stringifies its argument.
564     ///
565     /// This macro will yield an expression of type `&'static str` which is the
566     /// stringification of all the tokens passed to the macro. No restrictions
567     /// are placed on the syntax of the macro invocation itself.
568     ///
569     /// # Example
570     ///
571     /// ```
572     /// let one_plus_one = stringify!(1 + 1);
573     /// assert_eq!(one_plus_one, "1 + 1");
574     /// ```
575     #[macro_export]
576     macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
577
578     /// Includes a utf8-encoded file as a string.
579     ///
580     /// This macro will yield an expression of type `&'static str` which is the
581     /// contents of the filename specified. The file is located relative to the
582     /// current file (similarly to how modules are found),
583     ///
584     /// # Example
585     ///
586     /// ```rust,ignore
587     /// let secret_key = include_str!("secret-key.ascii");
588     /// ```
589     #[macro_export]
590     macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
591
592     /// Includes a file as a byte slice.
593     ///
594     /// This macro will yield an expression of type `&'static [u8]` which is
595     /// the contents of the filename specified. The file is located relative to
596     /// the current file (similarly to how modules are found),
597     ///
598     /// # Example
599     ///
600     /// ```rust,ignore
601     /// let secret_key = include_bytes!("secret-key.bin");
602     /// ```
603     #[macro_export]
604     macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
605
606     /// Deprecated alias for `include_bytes!()`.
607     #[macro_export]
608     macro_rules! include_bin { ($file:expr) => ({ /* compiler built-in */}) }
609
610     /// Expands to a string that represents the current module path.
611     ///
612     /// The current module path can be thought of as the hierarchy of modules
613     /// leading back up to the crate root. The first component of the path
614     /// returned is the name of the crate currently being compiled.
615     ///
616     /// # Example
617     ///
618     /// ```rust
619     /// mod test {
620     ///     pub fn foo() {
621     ///         assert!(module_path!().ends_with("test"));
622     ///     }
623     /// }
624     ///
625     /// test::foo();
626     /// ```
627     #[macro_export]
628     macro_rules! module_path { () => ({ /* compiler built-in */ }) }
629
630     /// Boolean evaluation of configuration flags.
631     ///
632     /// In addition to the `#[cfg]` attribute, this macro is provided to allow
633     /// boolean expression evaluation of configuration flags. This frequently
634     /// leads to less duplicated code.
635     ///
636     /// The syntax given to this macro is the same syntax as the `cfg`
637     /// attribute.
638     ///
639     /// # Example
640     ///
641     /// ```rust
642     /// let my_directory = if cfg!(windows) {
643     ///     "windows-specific-directory"
644     /// } else {
645     ///     "unix-directory"
646     /// };
647     /// ```
648     #[macro_export]
649     macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) }
650 }