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