]> git.lizzy.rs Git - rust.git/blob - src/libstd/macros.rs
std: Remove format_strbuf!()
[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 #![macro_escape]
18
19 /// The entry point for failure of rust tasks.
20 ///
21 /// This macro is used to inject failure into a rust task, causing the task to
22 /// unwind and fail entirely. Each task's failure can be reaped as the
23 /// `Box<Any>` type, and the single-argument form of the `fail!` macro will be
24 /// the value which is transmitted.
25 ///
26 /// The multi-argument form of this macro fails with a string and has the
27 /// `format!` syntax for building a string.
28 ///
29 /// # Example
30 ///
31 /// ```should_fail
32 /// # #![allow(unreachable_code)]
33 /// fail!();
34 /// fail!("this is a terrible mistake!");
35 /// fail!(4); // fail with the value of 4 to be collected elsewhere
36 /// fail!("this is a {} {message}", "fancy", message = "message");
37 /// ```
38 #[macro_export]
39 macro_rules! fail(
40     () => (
41         fail!("explicit failure")
42     );
43     ($msg:expr) => (
44         ::std::rt::begin_unwind($msg, file!(), line!())
45     );
46     ($fmt:expr, $($arg:tt)*) => ({
47         // a closure can't have return type !, so we need a full
48         // function to pass to format_args!, *and* we need the
49         // file and line numbers right here; so an inner bare fn
50         // is our only choice.
51         //
52         // LLVM doesn't tend to inline this, presumably because begin_unwind_fmt
53         // is #[cold] and #[inline(never)] and because this is flagged as cold
54         // as returning !. We really do want this to be inlined, however,
55         // because it's just a tiny wrapper. Small wins (156K to 149K in size)
56         // were seen when forcing this to be inlined, and that number just goes
57         // up with the number of calls to fail!()
58         #[inline(always)]
59         fn run_fmt(fmt: &::std::fmt::Arguments) -> ! {
60             ::std::rt::begin_unwind_fmt(fmt, file!(), line!())
61         }
62         format_args!(run_fmt, $fmt, $($arg)*)
63     });
64 )
65
66 /// Ensure that a boolean expression is `true` at runtime.
67 ///
68 /// This will invoke the `fail!` macro if the provided expression cannot be
69 /// evaluated to `true` at runtime.
70 ///
71 /// # Example
72 ///
73 /// ```
74 /// // the failure message for these assertions is the stringified value of the
75 /// // expression given.
76 /// assert!(true);
77 /// # fn some_computation() -> bool { true }
78 /// assert!(some_computation());
79 ///
80 /// // assert with a custom message
81 /// # let x = true;
82 /// assert!(x, "x wasn't true!");
83 /// # let a = 3; let b = 27;
84 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
85 /// ```
86 #[macro_export]
87 macro_rules! assert(
88     ($cond:expr) => (
89         if !$cond {
90             fail!("assertion failed: {:s}", stringify!($cond))
91         }
92     );
93     ($cond:expr, $($arg:expr),+) => (
94         if !$cond {
95             fail!($($arg),+)
96         }
97     );
98 )
99
100 /// Asserts that two expressions are equal to each other, testing equality in
101 /// both directions.
102 ///
103 /// On failure, this macro will print the values of the expressions.
104 ///
105 /// # Example
106 ///
107 /// ```
108 /// let a = 3;
109 /// let b = 1 + 2;
110 /// assert_eq!(a, b);
111 /// ```
112 #[macro_export]
113 macro_rules! assert_eq(
114     ($given:expr , $expected:expr) => ({
115         match (&($given), &($expected)) {
116             (given_val, expected_val) => {
117                 // check both directions of equality....
118                 if !((*given_val == *expected_val) &&
119                      (*expected_val == *given_val)) {
120                     fail!("assertion failed: `(left == right) && (right == left)` \
121                            (left: `{}`, right: `{}`)", *given_val, *expected_val)
122                 }
123             }
124         }
125     })
126 )
127
128 /// Ensure that a boolean expression is `true` at runtime.
129 ///
130 /// This will invoke the `fail!` macro if the provided expression cannot be
131 /// evaluated to `true` at runtime.
132 ///
133 /// Unlike `assert!`, `debug_assert!` statements can be disabled by passing
134 /// `--cfg ndebug` to the compiler. This makes `debug_assert!` useful for
135 /// checks that are too expensive to be present in a release build but may be
136 /// helpful during development.
137 ///
138 /// # Example
139 ///
140 /// ```
141 /// // the failure message for these assertions is the stringified value of the
142 /// // expression given.
143 /// debug_assert!(true);
144 /// # fn some_expensive_computation() -> bool { true }
145 /// debug_assert!(some_expensive_computation());
146 ///
147 /// // assert with a custom message
148 /// # let x = true;
149 /// debug_assert!(x, "x wasn't true!");
150 /// # let a = 3; let b = 27;
151 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
152 /// ```
153 #[macro_export]
154 macro_rules! debug_assert(
155     ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); })
156 )
157
158 /// Asserts that two expressions are equal to each other, testing equality in
159 /// both directions.
160 ///
161 /// On failure, this macro will print the values of the expressions.
162 ///
163 /// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by
164 /// passing `--cfg ndebug` to the compiler. This makes `debug_assert_eq!`
165 /// useful for checks that are too expensive to be present in a release build
166 /// but may be helpful during development.
167 ///
168 /// # Example
169 ///
170 /// ```
171 /// let a = 3;
172 /// let b = 1 + 2;
173 /// debug_assert_eq!(a, b);
174 /// ```
175 #[macro_export]
176 macro_rules! debug_assert_eq(
177     ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); })
178 )
179
180 /// A utility macro for indicating unreachable code. It will fail if
181 /// executed. This is occasionally useful to put after loops that never
182 /// terminate normally, but instead directly return from a function.
183 ///
184 /// # Example
185 ///
186 /// ~~~rust
187 /// struct Item { weight: uint }
188 ///
189 /// fn choose_weighted_item(v: &[Item]) -> Item {
190 ///     assert!(!v.is_empty());
191 ///     let mut so_far = 0u;
192 ///     for item in v.iter() {
193 ///         so_far += item.weight;
194 ///         if so_far > 100 {
195 ///             return *item;
196 ///         }
197 ///     }
198 ///     // The above loop always returns, so we must hint to the
199 ///     // type checker that it isn't possible to get down here
200 ///     unreachable!();
201 /// }
202 /// ~~~
203 #[macro_export]
204 macro_rules! unreachable(
205     () => (fail!("internal error: entered unreachable code"))
206 )
207
208 /// A standardised placeholder for marking unfinished code. It fails with the
209 /// message `"not yet implemented"` when executed.
210 #[macro_export]
211 macro_rules! unimplemented(
212     () => (fail!("not yet implemented"))
213 )
214
215 /// Use the syntax described in `std::fmt` to create a value of type `~str`.
216 /// See `std::fmt` for more information.
217 ///
218 /// # Example
219 ///
220 /// ```
221 /// format!("test");
222 /// format!("hello {}", "world!");
223 /// format!("x = {}, y = {y}", 10, y = 30);
224 /// ```
225 #[macro_export]
226 macro_rules! format(
227     ($($arg:tt)*) => (
228         format_args!(::std::fmt::format, $($arg)*)
229     )
230 )
231
232 /// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
233 /// See `std::fmt` for more information.
234 ///
235 /// # Example
236 ///
237 /// ```
238 /// # #![allow(unused_must_use)]
239 /// use std::io::MemWriter;
240 ///
241 /// let mut w = MemWriter::new();
242 /// write!(&mut w, "test");
243 /// write!(&mut w, "formatted {}", "arguments");
244 /// ```
245 #[macro_export]
246 macro_rules! write(
247     ($dst:expr, $($arg:tt)*) => ({
248         format_args_method!($dst, write_fmt, $($arg)*)
249     })
250 )
251
252 /// Equivalent to the `write!` macro, except that a newline is appended after
253 /// the message is written.
254 #[macro_export]
255 macro_rules! writeln(
256     ($dst:expr, $fmt:expr $($arg:tt)*) => (
257         write!($dst, concat!($fmt, "\n") $($arg)*)
258     )
259 )
260
261 /// Equivalent to the `println!` macro except that a newline is not printed at
262 /// the end of the message.
263 #[macro_export]
264 macro_rules! print(
265     ($($arg:tt)*) => (format_args!(::std::io::stdio::print_args, $($arg)*))
266 )
267
268 /// Macro for printing to a task's stdout handle.
269 ///
270 /// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
271 /// The syntax of this macro is the same as that used for `format!`. For more
272 /// information, see `std::fmt` and `std::io::stdio`.
273 ///
274 /// # Example
275 ///
276 /// ```
277 /// println!("hello there!");
278 /// println!("format {} arguments", "some");
279 /// ```
280 #[macro_export]
281 macro_rules! println(
282     ($($arg:tt)*) => (format_args!(::std::io::stdio::println_args, $($arg)*))
283 )
284
285 /// Declare a task-local key with a specific type.
286 ///
287 /// # Example
288 ///
289 /// ```
290 /// local_data_key!(my_integer: int)
291 ///
292 /// my_integer.replace(Some(2));
293 /// println!("{}", my_integer.get().map(|a| *a));
294 /// ```
295 #[macro_export]
296 macro_rules! local_data_key(
297     ($name:ident: $ty:ty) => (
298         static $name: ::std::local_data::Key<$ty> = &::std::local_data::Key;
299     );
300     (pub $name:ident: $ty:ty) => (
301         pub static $name: ::std::local_data::Key<$ty> = &::std::local_data::Key;
302     );
303 )
304
305 /// Helper macro for unwrapping `Result` values while returning early with an
306 /// error if the value of the expression is `Err`. For more information, see
307 /// `std::io`.
308 #[macro_export]
309 macro_rules! try(
310     ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
311 )
312
313 /// Create a `std::vec::Vec` containing the arguments.
314 #[macro_export]
315 macro_rules! vec(
316     ($($e:expr),*) => ({
317         // leading _ to allow empty construction without a warning.
318         let mut _temp = ::std::vec::Vec::new();
319         $(_temp.push($e);)*
320         _temp
321     });
322     ($($e:expr),+,) => (vec!($($e),+))
323 )
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 /// let (tx1, rx1) = channel();
336 /// let (tx2, rx2) = channel();
337 /// # fn long_running_task() {}
338 /// # fn calculate_the_answer() -> int { 42 }
339 ///
340 /// spawn(proc() { long_running_task(); tx1.send(()) });
341 /// spawn(proc() { tx2.send(calculate_the_answer()) });
342 ///
343 /// select! (
344 ///     () = rx1.recv() => println!("the long running task finished first"),
345 ///     answer = rx2.recv() => {
346 ///         println!("the answer was: {}", answer);
347 ///     }
348 /// )
349 /// ```
350 ///
351 /// For more information about select, see the `std::comm::Select` structure.
352 #[macro_export]
353 #[experimental]
354 macro_rules! select {
355     (
356         $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
357     ) => ({
358         use std::comm::Select;
359         let sel = Select::new();
360         $( let mut $rx = sel.handle(&$rx); )+
361         unsafe {
362             $( $rx.add(); )+
363         }
364         let ret = sel.wait();
365         $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
366         { unreachable!() }
367     })
368 }
369
370 // When testing the standard library, we link to the liblog crate to get the
371 // logging macros. In doing so, the liblog crate was linked against the real
372 // version of libstd, and uses a different std::fmt module than the test crate
373 // uses. To get around this difference, we redefine the log!() macro here to be
374 // just a dumb version of what it should be.
375 #[cfg(test)]
376 macro_rules! log (
377     ($lvl:expr, $($args:tt)*) => (
378         if log_enabled!($lvl) { println!($($args)*) }
379     )
380 )
381
382 /// Built-in macros to the compiler itself.
383 ///
384 /// These macros do not have any corresponding definition with a `macro_rules!`
385 /// macro, but are documented here. Their implementations can be found hardcoded
386 /// into libsyntax itself.
387 #[cfg(dox)]
388 pub mod builtin {
389     /// The core macro for formatted string creation & output.
390     ///
391     /// This macro takes as its first argument a callable expression which will
392     /// receive as its first argument a value of type `&fmt::Arguments`. This
393     /// value can be passed to the functions in `std::fmt` for performing useful
394     /// functions. All other formatting macros (`format!`, `write!`,
395     /// `println!`, etc) are proxied through this one.
396     ///
397     /// For more information, see the documentation in `std::fmt`.
398     ///
399     /// # Example
400     ///
401     /// ```rust
402     /// use std::fmt;
403     ///
404     /// let s = format_args!(fmt::format, "hello {}", "world");
405     /// assert_eq!(s, format!("hello {}", "world"));
406     ///
407     /// format_args!(|args| {
408     ///     // pass `args` to another function, etc.
409     /// }, "hello {}", "world");
410     /// ```
411     #[macro_export]
412     macro_rules! format_args( ($closure:expr, $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 user: &'static str = env!("USER");
429     /// println!("the user who compiled this code is: {}", user);
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], 'u' as u8);
468     /// assert_eq!(rust[5], 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     /// fn foobar() -> int { 23 }
486     ///
487     /// let f = concat_idents!(foo, bar);
488     /// println!("{}", f());
489     /// ```
490     #[macro_export]
491     macro_rules! concat_idents( ($($e:ident),*) => ({ /* compiler built-in */ }) )
492
493     /// Concatenates literals into a static string slice.
494     ///
495     /// This macro takes any number of comma-separated literals, yielding an
496     /// expression of type `&'static str` which represents all of the literals
497     /// concatenated left-to-right.
498     ///
499     /// Integer and floating point literals are stringified in order to be
500     /// concatenated.
501     ///
502     /// # Example
503     ///
504     /// ```
505     /// let s = concat!("test", 10, 'b', true);
506     /// assert_eq!(s, "test10btrue");
507     /// ```
508     #[macro_export]
509     macro_rules! concat( ($($e:expr),*) => ({ /* compiler built-in */ }) )
510
511     /// A macro which expands to the line number on which it was invoked.
512     ///
513     /// The expanded expression has type `uint`, and the returned line is not
514     /// the invocation of the `line!()` macro itself, but rather the first macro
515     /// invocation leading up to the invocation of the `line!()` macro.
516     ///
517     /// # Example
518     ///
519     /// ```
520     /// let current_line = line!();
521     /// println!("defined on line: {}", current_line);
522     /// ```
523     #[macro_export]
524     macro_rules! line( () => ({ /* compiler built-in */ }) )
525
526     /// A macro which expands to the column number on which it was invoked.
527     ///
528     /// The expanded expression has type `uint`, and the returned column is not
529     /// the invocation of the `col!()` macro itself, but rather the first macro
530     /// invocation leading up to the invocation of the `col!()` macro.
531     ///
532     /// # Example
533     ///
534     /// ```
535     /// let current_col = col!();
536     /// println!("defined on column: {}", current_col);
537     /// ```
538     #[macro_export]
539     macro_rules! col( () => ({ /* compiler built-in */ }) )
540
541     /// A macro which expands to the file name from which it was invoked.
542     ///
543     /// The expanded expression has type `&'static str`, and the returned file
544     /// is not the invocation of the `file!()` macro itself, but rather the
545     /// first macro invocation leading up to the invocation of the `file!()`
546     /// macro.
547     ///
548     /// # Example
549     ///
550     /// ```
551     /// let this_file = file!();
552     /// println!("defined in file: {}", this_file);
553     /// ```
554     #[macro_export]
555     macro_rules! file( () => ({ /* compiler built-in */ }) )
556
557     /// A macro which stringifies its argument.
558     ///
559     /// This macro will yield an expression of type `&'static str` which is the
560     /// stringification of all the tokens passed to the macro. No restrictions
561     /// are placed on the syntax of the macro invocation itself.
562     ///
563     /// # Example
564     ///
565     /// ```
566     /// let one_plus_one = stringify!(1 + 1);
567     /// assert_eq!(one_plus_one, "1 + 1");
568     /// ```
569     #[macro_export]
570     macro_rules! stringify( ($t:tt) => ({ /* compiler built-in */ }) )
571
572     /// Includes a utf8-encoded file as a string.
573     ///
574     /// This macro will yield an expression of type `&'static str` which is the
575     /// contents of the filename specified. The file is located relative to the
576     /// current file (similarly to how modules are found),
577     ///
578     /// # Example
579     ///
580     /// ```rust,ignore
581     /// let secret_key = include_str!("secret-key.ascii");
582     /// ```
583     #[macro_export]
584     macro_rules! include_str( ($file:expr) => ({ /* compiler built-in */ }) )
585
586     /// Includes a file as a byte slice.
587     ///
588     /// This macro will yield an expression of type `&'static [u8]` which is
589     /// the contents of the filename specified. The file is located relative to
590     /// the current file (similarly to how modules are found),
591     ///
592     /// # Example
593     ///
594     /// ```rust,ignore
595     /// let secret_key = include_bin!("secret-key.bin");
596     /// ```
597     #[macro_export]
598     macro_rules! include_bin( ($file:expr) => ({ /* compiler built-in */ }) )
599
600     /// Expands to a string that represents the current module path.
601     ///
602     /// The current module path can be thought of as the hierarchy of modules
603     /// leading back up to the crate root. The first component of the path
604     /// returned is the name of the crate currently being compiled.
605     ///
606     /// # Example
607     ///
608     /// ```rust
609     /// mod test {
610     ///     pub fn foo() {
611     ///         assert!(module_path!().ends_with("test"));
612     ///     }
613     /// }
614     ///
615     /// test::foo();
616     /// ```
617     #[macro_export]
618     macro_rules! module_path( () => ({ /* compiler built-in */ }) )
619
620     /// Boolean evaluation of configuration flags.
621     ///
622     /// In addition to the `#[cfg]` attribute, this macro is provided to allow
623     /// boolean expression evaluation of configuration flags. This frequently
624     /// leads to less duplicated code.
625     ///
626     /// The syntax given to this macro is the same syntax as the `cfg`
627     /// attribute.
628     ///
629     /// # Example
630     ///
631     /// ```rust
632     /// let my_directory = if cfg!(windows) {
633     ///     "windows-specific-directory"
634     /// } else {
635     ///     "unix-directory"
636     /// };
637     /// ```
638     #[macro_export]
639     macro_rules! cfg( ($cfg:tt) => ({ /* compiler built-in */ }) )
640 }