]> git.lizzy.rs Git - rust.git/blob - src/libstd/macros.rs
3c6c860f516bb63c8c5cd4724a02af5285fc60a0
[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 failure of rust tasks.
21 ///
22 /// This macro is used to inject failure into a rust task, causing the task to
23 /// unwind and fail entirely. Each task's failure can be reaped as the
24 /// `Box<Any>` type, and the single-argument form of the `fail!` macro will be
25 /// the value which is transmitted.
26 ///
27 /// The multi-argument form of this macro fails 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 /// fail!();
35 /// fail!("this is a terrible mistake!");
36 /// fail!(4i); // fail with the value of 4 to be collected elsewhere
37 /// fail!("this is a {} {message}", "fancy", message = "message");
38 /// ```
39 #[macro_export]
40 macro_rules! fail(
41     () => (
42         ::std::rt::begin_unwind_no_time_to_explain(file!(), line!())
43     );
44     ($msg:expr) => (
45         ::std::rt::begin_unwind($msg, file!(), line!())
46     );
47     ($fmt:expr, $($arg:tt)*) => ({
48         // a closure can't have return type !, so we need a full
49         // function to pass to format_args!, *and* we need the
50         // file and line numbers right here; so an inner bare fn
51         // is our only choice.
52         //
53         // LLVM doesn't tend to inline this, presumably because begin_unwind_fmt
54         // is #[cold] and #[inline(never)] and because this is flagged as cold
55         // as returning !. We really do want this to be inlined, however,
56         // because it's just a tiny wrapper. Small wins (156K to 149K in size)
57         // were seen when forcing this to be inlined, and that number just goes
58         // up with the number of calls to fail!()
59         #[inline(always)]
60         fn run_fmt(fmt: &::std::fmt::Arguments) -> ! {
61             ::std::rt::begin_unwind_fmt(fmt, file!(), line!())
62         }
63         format_args!(run_fmt, $fmt, $($arg)*)
64     });
65 )
66
67 /// Ensure that a boolean expression is `true` at runtime.
68 ///
69 /// This will invoke the `fail!` macro if the provided expression cannot be
70 /// evaluated to `true` at runtime.
71 ///
72 /// # Example
73 ///
74 /// ```
75 /// // the failure message for these assertions is the stringified value of the
76 /// // expression given.
77 /// assert!(true);
78 /// # fn some_computation() -> bool { true }
79 /// assert!(some_computation());
80 ///
81 /// // assert with a custom message
82 /// # let x = true;
83 /// assert!(x, "x wasn't true!");
84 /// # let a = 3i; let b = 27i;
85 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
86 /// ```
87 #[macro_export]
88 macro_rules! assert(
89     ($cond:expr) => (
90         if !$cond {
91             fail!("assertion failed: {:s}", stringify!($cond))
92         }
93     );
94     ($cond:expr, $($arg:expr),+) => (
95         if !$cond {
96             fail!($($arg),+)
97         }
98     );
99 )
100
101 /// Asserts that two expressions are equal to each other, testing equality in
102 /// both directions.
103 ///
104 /// On failure, this macro will print the values of the expressions.
105 ///
106 /// # Example
107 ///
108 /// ```
109 /// let a = 3i;
110 /// let b = 1i + 2i;
111 /// assert_eq!(a, b);
112 /// ```
113 #[macro_export]
114 macro_rules! assert_eq(
115     ($given:expr , $expected:expr) => ({
116         match (&($given), &($expected)) {
117             (given_val, expected_val) => {
118                 // check both directions of equality....
119                 if !((*given_val == *expected_val) &&
120                      (*expected_val == *given_val)) {
121                     fail!("assertion failed: `(left == right) && (right == left)` \
122                            (left: `{}`, right: `{}`)", *given_val, *expected_val)
123                 }
124             }
125         }
126     })
127 )
128
129 /// Ensure that a boolean expression is `true` at runtime.
130 ///
131 /// This will invoke the `fail!` macro if the provided expression cannot be
132 /// evaluated to `true` at runtime.
133 ///
134 /// Unlike `assert!`, `debug_assert!` statements can be disabled by passing
135 /// `--cfg ndebug` to the compiler. This makes `debug_assert!` useful for
136 /// checks that are too expensive to be present in a release build but may be
137 /// helpful during development.
138 ///
139 /// # Example
140 ///
141 /// ```
142 /// // the failure message for these assertions is the stringified value of the
143 /// // expression given.
144 /// debug_assert!(true);
145 /// # fn some_expensive_computation() -> bool { true }
146 /// debug_assert!(some_expensive_computation());
147 ///
148 /// // assert with a custom message
149 /// # let x = true;
150 /// debug_assert!(x, "x wasn't true!");
151 /// # let a = 3i; let b = 27i;
152 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
153 /// ```
154 #[macro_export]
155 macro_rules! debug_assert(
156     ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); })
157 )
158
159 /// Asserts that two expressions are equal to each other, testing equality in
160 /// both directions.
161 ///
162 /// On failure, this macro will print the values of the expressions.
163 ///
164 /// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by
165 /// passing `--cfg ndebug` to the compiler. This makes `debug_assert_eq!`
166 /// useful for checks that are too expensive to be present in a release build
167 /// but may be helpful during development.
168 ///
169 /// # Example
170 ///
171 /// ```
172 /// let a = 3i;
173 /// let b = 1i + 2i;
174 /// debug_assert_eq!(a, b);
175 /// ```
176 #[macro_export]
177 macro_rules! debug_assert_eq(
178     ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); })
179 )
180
181 /// A utility macro for indicating unreachable code. It will fail if
182 /// executed. This is occasionally useful to put after loops that never
183 /// terminate normally, but instead directly return from a function.
184 ///
185 /// # Example
186 ///
187 /// ~~~rust
188 /// struct Item { weight: uint }
189 ///
190 /// fn choose_weighted_item(v: &[Item]) -> Item {
191 ///     assert!(!v.is_empty());
192 ///     let mut so_far = 0u;
193 ///     for item in v.iter() {
194 ///         so_far += item.weight;
195 ///         if so_far > 100 {
196 ///             return *item;
197 ///         }
198 ///     }
199 ///     // The above loop always returns, so we must hint to the
200 ///     // type checker that it isn't possible to get down here
201 ///     unreachable!();
202 /// }
203 /// ~~~
204 #[macro_export]
205 macro_rules! unreachable(
206     () => (fail!("internal error: entered unreachable code"))
207 )
208
209 /// A standardised placeholder for marking unfinished code. It fails with the
210 /// message `"not yet implemented"` when executed.
211 #[macro_export]
212 macro_rules! unimplemented(
213     () => (fail!("not yet implemented"))
214 )
215
216 /// Use the syntax described in `std::fmt` to create a value of type `String`.
217 /// See `std::fmt` for more information.
218 ///
219 /// # Example
220 ///
221 /// ```
222 /// format!("test");
223 /// format!("hello {}", "world!");
224 /// format!("x = {}, y = {y}", 10i, y = 30i);
225 /// ```
226 #[macro_export]
227 macro_rules! format(
228     ($($arg:tt)*) => (
229         format_args!(::std::fmt::format, $($arg)*)
230     )
231 )
232
233 /// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
234 /// See `std::fmt` for more information.
235 ///
236 /// # Example
237 ///
238 /// ```
239 /// # #![allow(unused_must_use)]
240 /// use std::io::MemWriter;
241 ///
242 /// let mut w = MemWriter::new();
243 /// write!(&mut w, "test");
244 /// write!(&mut w, "formatted {}", "arguments");
245 /// ```
246 #[macro_export]
247 macro_rules! write(
248     ($dst:expr, $($arg:tt)*) => ({
249         format_args_method!($dst, write_fmt, $($arg)*)
250     })
251 )
252
253 /// Equivalent to the `write!` macro, except that a newline is appended after
254 /// the message is written.
255 #[macro_export]
256 macro_rules! writeln(
257     ($dst:expr, $fmt:expr $($arg:tt)*) => (
258         write!($dst, concat!($fmt, "\n") $($arg)*)
259     )
260 )
261
262 /// Equivalent to the `println!` macro except that a newline is not printed at
263 /// the end of the message.
264 #[macro_export]
265 macro_rules! print(
266     ($($arg:tt)*) => (format_args!(::std::io::stdio::print_args, $($arg)*))
267 )
268
269 /// Macro for printing to a task's stdout handle.
270 ///
271 /// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
272 /// The syntax of this macro is the same as that used for `format!`. For more
273 /// information, see `std::fmt` and `std::io::stdio`.
274 ///
275 /// # Example
276 ///
277 /// ```
278 /// println!("hello there!");
279 /// println!("format {} arguments", "some");
280 /// ```
281 #[macro_export]
282 macro_rules! println(
283     ($($arg:tt)*) => (format_args!(::std::io::stdio::println_args, $($arg)*))
284 )
285
286 /// Declare a task-local key with a specific type.
287 ///
288 /// # Example
289 ///
290 /// ```
291 /// local_data_key!(my_integer: int)
292 ///
293 /// my_integer.replace(Some(2));
294 /// println!("{}", my_integer.get().map(|a| *a));
295 /// ```
296 #[macro_export]
297 macro_rules! local_data_key(
298     ($name:ident: $ty:ty) => (
299         static $name: ::std::local_data::Key<$ty> = &::std::local_data::Key;
300     );
301     (pub $name:ident: $ty:ty) => (
302         pub static $name: ::std::local_data::Key<$ty> = &::std::local_data::Key;
303     );
304 )
305
306 /// Helper macro for unwrapping `Result` values while returning early with an
307 /// error if the value of the expression is `Err`. For more information, see
308 /// `std::io`.
309 #[macro_export]
310 macro_rules! try(
311     ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
312 )
313
314 /// Create a `std::vec::Vec` containing the arguments.
315 #[macro_export]
316 macro_rules! vec(
317     ($($e:expr),*) => ({
318         // leading _ to allow empty construction without a warning.
319         let mut _temp = ::std::vec::Vec::new();
320         $(_temp.push($e);)*
321         _temp
322     });
323     ($($e:expr),+,) => (vec!($($e),+))
324 )
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 /// let (tx1, rx1) = channel();
337 /// let (tx2, rx2) = channel();
338 /// # fn long_running_task() {}
339 /// # fn calculate_the_answer() -> int { 42i }
340 ///
341 /// spawn(proc() { long_running_task(); tx1.send(()) });
342 /// spawn(proc() { tx2.send(calculate_the_answer()) });
343 ///
344 /// select! (
345 ///     () = rx1.recv() => println!("the long running task finished first"),
346 ///     answer = rx2.recv() => {
347 ///         println!("the answer was: {}", answer);
348 ///     }
349 /// )
350 /// ```
351 ///
352 /// For more information about select, see the `std::comm::Select` structure.
353 #[macro_export]
354 #[experimental]
355 macro_rules! select {
356     (
357         $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
358     ) => ({
359         use std::comm::Select;
360         let sel = Select::new();
361         $( let mut $rx = sel.handle(&$rx); )+
362         unsafe {
363             $( $rx.add(); )+
364         }
365         let ret = sel.wait();
366         $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
367         { unreachable!() }
368     })
369 }
370
371 // When testing the standard library, we link to the liblog crate to get the
372 // logging macros. In doing so, the liblog crate was linked against the real
373 // version of libstd, and uses a different std::fmt module than the test crate
374 // uses. To get around this difference, we redefine the log!() macro here to be
375 // just a dumb version of what it should be.
376 #[cfg(test)]
377 macro_rules! log (
378     ($lvl:expr, $($args:tt)*) => (
379         if log_enabled!($lvl) { println!($($args)*) }
380     )
381 )
382
383 /// Built-in macros to the compiler itself.
384 ///
385 /// These macros do not have any corresponding definition with a `macro_rules!`
386 /// macro, but are documented here. Their implementations can be found hardcoded
387 /// into libsyntax itself.
388 #[cfg(dox)]
389 pub mod builtin {
390     /// The core macro for formatted string creation & output.
391     ///
392     /// This macro takes as its first argument a callable expression which will
393     /// receive as its first argument a value of type `&fmt::Arguments`. This
394     /// value can be passed to the functions in `std::fmt` for performing useful
395     /// functions. All other formatting macros (`format!`, `write!`,
396     /// `println!`, etc) are proxied through this one.
397     ///
398     /// For more information, see the documentation in `std::fmt`.
399     ///
400     /// # Example
401     ///
402     /// ```rust
403     /// use std::fmt;
404     ///
405     /// let s = format_args!(fmt::format, "hello {}", "world");
406     /// assert_eq!(s, format!("hello {}", "world"));
407     ///
408     /// format_args!(|args| {
409     ///     // pass `args` to another function, etc.
410     /// }, "hello {}", "world");
411     /// ```
412     #[macro_export]
413     macro_rules! format_args( ($closure:expr, $fmt:expr $($args:tt)*) => ({
414         /* compiler built-in */
415     }) )
416
417     /// Inspect an environment variable at compile time.
418     ///
419     /// This macro will expand to the value of the named environment variable at
420     /// compile time, yielding an expression of type `&'static str`.
421     ///
422     /// If the environment variable is not defined, then a compilation error
423     /// will be emitted.  To not emit a compile error, use the `option_env!`
424     /// macro instead.
425     ///
426     /// # Example
427     ///
428     /// ```rust
429     /// let home: &'static str = env!("HOME");
430     /// println!("the home directory at the time of compiling was: {}", home);
431     /// ```
432     #[macro_export]
433     macro_rules! env( ($name:expr) => ({ /* compiler built-in */ }) )
434
435     /// Optionally inspect an environment variable at compile time.
436     ///
437     /// If the named environment variable is present at compile time, this will
438     /// expand into an expression of type `Option<&'static str>` whose value is
439     /// `Some` of the value of the environment variable. If the environment
440     /// variable is not present, then this will expand to `None`.
441     ///
442     /// A compile time error is never emitted when using this macro regardless
443     /// of whether the environment variable is present or not.
444     ///
445     /// # Example
446     ///
447     /// ```rust
448     /// let key: Option<&'static str> = option_env!("SECRET_KEY");
449     /// println!("the secret key might be: {}", key);
450     /// ```
451     #[macro_export]
452     macro_rules! option_env( ($name:expr) => ({ /* compiler built-in */ }) )
453
454     /// Concatenate literals into a static byte slice.
455     ///
456     /// This macro takes any number of comma-separated literal expressions,
457     /// yielding an expression of type `&'static [u8]` which is the
458     /// concatenation (left to right) of all the literals in their byte format.
459     ///
460     /// This extension currently only supports string literals, character
461     /// literals, and integers less than 256. The byte slice returned is the
462     /// utf8-encoding of strings and characters.
463     ///
464     /// # Example
465     ///
466     /// ```
467     /// let rust = bytes!("r", 'u', "st", 255);
468     /// assert_eq!(rust[1], 'u' as u8);
469     /// assert_eq!(rust[4], 255);
470     /// ```
471     #[macro_export]
472     macro_rules! bytes( ($($e:expr),*) => ({ /* compiler built-in */ }) )
473
474     /// Concatenate identifiers into one identifier.
475     ///
476     /// This macro takes any number of comma-separated identifiers, and
477     /// concatenates them all into one, yielding an expression which is a new
478     /// identifier. Note that hygiene makes it such that this macro cannot
479     /// capture local variables, and macros are only allowed in item,
480     /// statement or expression position, meaning this macro may be difficult to
481     /// use in some situations.
482     ///
483     /// # Example
484     ///
485     /// ```
486     /// #![feature(concat_idents)]
487     ///
488     /// # fn main() {
489     /// fn foobar() -> int { 23 }
490     ///
491     /// let f = concat_idents!(foo, bar);
492     /// println!("{}", f());
493     /// # }
494     /// ```
495     #[macro_export]
496     macro_rules! concat_idents( ($($e:ident),*) => ({ /* compiler built-in */ }) )
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", 10i, '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 `col!()` macro itself, but rather the first macro
535     /// invocation leading up to the invocation of the `col!()` macro.
536     ///
537     /// # Example
538     ///
539     /// ```
540     /// let current_col = col!();
541     /// println!("defined on column: {}", current_col);
542     /// ```
543     #[macro_export]
544     macro_rules! col( () => ({ /* 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_bin!("secret-key.bin");
601     /// ```
602     #[macro_export]
603     macro_rules! include_bin( ($file:expr) => ({ /* compiler built-in */ }) )
604
605     /// Expands to a string that represents the current module path.
606     ///
607     /// The current module path can be thought of as the hierarchy of modules
608     /// leading back up to the crate root. The first component of the path
609     /// returned is the name of the crate currently being compiled.
610     ///
611     /// # Example
612     ///
613     /// ```rust
614     /// mod test {
615     ///     pub fn foo() {
616     ///         assert!(module_path!().ends_with("test"));
617     ///     }
618     /// }
619     ///
620     /// test::foo();
621     /// ```
622     #[macro_export]
623     macro_rules! module_path( () => ({ /* compiler built-in */ }) )
624
625     /// Boolean evaluation of configuration flags.
626     ///
627     /// In addition to the `#[cfg]` attribute, this macro is provided to allow
628     /// boolean expression evaluation of configuration flags. This frequently
629     /// leads to less duplicated code.
630     ///
631     /// The syntax given to this macro is the same syntax as the `cfg`
632     /// attribute.
633     ///
634     /// # Example
635     ///
636     /// ```rust
637     /// let my_directory = if cfg!(windows) {
638     ///     "windows-specific-directory"
639     /// } else {
640     ///     "unix-directory"
641     /// };
642     /// ```
643     #[macro_export]
644     macro_rules! cfg( ($cfg:tt) => ({ /* compiler built-in */ }) )
645 }