]> git.lizzy.rs Git - rust.git/blob - src/libstd/macros.rs
Rename include_bin! to include_bytes!
[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     ($left:expr , $right:expr) => ({
124         match (&($left), &($right)) {
125             (left_val, right_val) => {
126                 // check both directions of equality....
127                 if !((*left_val == *right_val) &&
128                      (*right_val == *left_val)) {
129                     panic!("assertion failed: `(left == right) && (right == left)` \
130                            (left: `{}`, right: `{}`)", *left_val, *right_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.
190 ///
191 /// This is useful any time that the compiler can't determine that some code is unreachable. For
192 /// example:
193 ///
194 /// * Match arms with guard conditions.
195 /// * Loops that dynamically terminate.
196 /// * Iterators that dynamically terminate.
197 ///
198 /// # Panics
199 ///
200 /// This will always panic.
201 ///
202 /// # Examples
203 ///
204 /// Match arms:
205 ///
206 /// ```rust
207 /// fn foo(x: Option<int>) {
208 ///     match x {
209 ///         Some(n) if n >= 0 => println!("Some(Non-negative)"),
210 ///         Some(n) if n <  0 => println!("Some(Negative)"),
211 ///         Some(_)           => unreachable!(), // compile error if commented out
212 ///         None              => println!("None")
213 ///     }
214 /// }
215 /// ```
216 ///
217 /// Iterators:
218 ///
219 /// ```rust
220 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
221 ///     for i in std::iter::count(0_u32, 1) {
222 ///         if 3*i < i { panic!("u32 overflow"); }
223 ///         if x < 3*i { return i-1; }
224 ///     }
225 ///     unreachable!();
226 /// }
227 /// ```
228 #[macro_export]
229 macro_rules! unreachable {
230     () => ({
231         panic!("internal error: entered unreachable code")
232     });
233     ($msg:expr) => ({
234         unreachable!("{}", $msg)
235     });
236     ($fmt:expr, $($arg:tt)*) => ({
237         panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
238     });
239 }
240
241 /// A standardised placeholder for marking unfinished code. It panics with the
242 /// message `"not yet implemented"` when executed.
243 #[macro_export]
244 macro_rules! unimplemented {
245     () => (panic!("not yet implemented"))
246 }
247
248 /// Use the syntax described in `std::fmt` to create a value of type `String`.
249 /// See `std::fmt` for more information.
250 ///
251 /// # Example
252 ///
253 /// ```
254 /// format!("test");
255 /// format!("hello {}", "world!");
256 /// format!("x = {}, y = {y}", 10i, y = 30i);
257 /// ```
258 #[macro_export]
259 #[stable]
260 macro_rules! format {
261     ($($arg:tt)*) => (
262         format_args!(::std::fmt::format, $($arg)*)
263     )
264 }
265
266 /// Use the `format!` syntax to write data into a buffer of type `&mut Writer`.
267 /// See `std::fmt` for more information.
268 ///
269 /// # Example
270 ///
271 /// ```
272 /// # #![allow(unused_must_use)]
273 ///
274 /// let mut w = Vec::new();
275 /// write!(&mut w, "test");
276 /// write!(&mut w, "formatted {}", "arguments");
277 /// ```
278 #[macro_export]
279 #[stable]
280 macro_rules! write {
281     ($dst:expr, $($arg:tt)*) => ({
282         let dst = &mut *$dst;
283         format_args!(|args| { dst.write_fmt(args) }, $($arg)*)
284     })
285 }
286
287 /// Equivalent to the `write!` macro, except that a newline is appended after
288 /// the message is written.
289 #[macro_export]
290 #[stable]
291 macro_rules! writeln {
292     ($dst:expr, $fmt:expr $($arg:tt)*) => (
293         write!($dst, concat!($fmt, "\n") $($arg)*)
294     )
295 }
296
297 /// Equivalent to the `println!` macro except that a newline is not printed at
298 /// the end of the message.
299 #[macro_export]
300 #[stable]
301 macro_rules! print {
302     ($($arg:tt)*) => (format_args!(::std::io::stdio::print_args, $($arg)*))
303 }
304
305 /// Macro for printing to a task's stdout handle.
306 ///
307 /// Each task can override its stdout handle via `std::io::stdio::set_stdout`.
308 /// The syntax of this macro is the same as that used for `format!`. For more
309 /// information, see `std::fmt` and `std::io::stdio`.
310 ///
311 /// # Example
312 ///
313 /// ```
314 /// println!("hello there!");
315 /// println!("format {} arguments", "some");
316 /// ```
317 #[macro_export]
318 #[stable]
319 macro_rules! println {
320     ($($arg:tt)*) => (format_args!(::std::io::stdio::println_args, $($arg)*))
321 }
322
323 /// Helper macro for unwrapping `Result` values while returning early with an
324 /// error if the value of the expression is `Err`. For more information, see
325 /// `std::io`.
326 #[macro_export]
327 macro_rules! try {
328     ($expr:expr) => ({
329         match $expr {
330             Ok(val) => val,
331             Err(err) => return Err(::std::error::FromError::from_error(err))
332         }
333     })
334 }
335
336 /// Create a `std::vec::Vec` containing the arguments.
337 #[macro_export]
338 macro_rules! vec {
339     ($($x:expr),*) => ({
340         use std::slice::BoxedSliceExt;
341         let xs: ::std::boxed::Box<[_]> = box [$($x),*];
342         xs.into_vec()
343     });
344     ($($x:expr,)*) => (vec![$($x),*])
345 }
346
347 /// A macro to select an event from a number of receivers.
348 ///
349 /// This macro is used to wait for the first event to occur on a number of
350 /// receivers. It places no restrictions on the types of receivers given to
351 /// this macro, this can be viewed as a heterogeneous select.
352 ///
353 /// # Example
354 ///
355 /// ```
356 /// use std::thread::Thread;
357 ///
358 /// let (tx1, rx1) = channel();
359 /// let (tx2, rx2) = channel();
360 /// # fn long_running_task() {}
361 /// # fn calculate_the_answer() -> int { 42i }
362 ///
363 /// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach();
364 /// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach();
365 ///
366 /// select! (
367 ///     () = rx1.recv() => println!("the long running task finished first"),
368 ///     answer = rx2.recv() => {
369 ///         println!("the answer was: {}", answer);
370 ///     }
371 /// )
372 /// ```
373 ///
374 /// For more information about select, see the `std::comm::Select` structure.
375 #[macro_export]
376 #[experimental]
377 macro_rules! select {
378     (
379         $($name:pat = $rx:ident.$meth:ident() => $code:expr),+
380     ) => ({
381         use std::comm::Select;
382         let sel = Select::new();
383         $( let mut $rx = sel.handle(&$rx); )+
384         unsafe {
385             $( $rx.add(); )+
386         }
387         let ret = sel.wait();
388         $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+
389         { unreachable!() }
390     })
391 }
392
393 // When testing the standard library, we link to the liblog crate to get the
394 // logging macros. In doing so, the liblog crate was linked against the real
395 // version of libstd, and uses a different std::fmt module than the test crate
396 // uses. To get around this difference, we redefine the log!() macro here to be
397 // just a dumb version of what it should be.
398 #[cfg(test)]
399 macro_rules! log {
400     ($lvl:expr, $($args:tt)*) => (
401         if log_enabled!($lvl) { println!($($args)*) }
402     )
403 }
404
405 /// Built-in macros to the compiler itself.
406 ///
407 /// These macros do not have any corresponding definition with a `macro_rules!`
408 /// macro, but are documented here. Their implementations can be found hardcoded
409 /// into libsyntax itself.
410 #[cfg(dox)]
411 pub mod builtin {
412     /// The core macro for formatted string creation & output.
413     ///
414     /// This macro takes as its first argument a callable expression which will
415     /// receive as its first argument a value of type `&fmt::Arguments`. This
416     /// value can be passed to the functions in `std::fmt` for performing useful
417     /// functions. All other formatting macros (`format!`, `write!`,
418     /// `println!`, etc) are proxied through this one.
419     ///
420     /// For more information, see the documentation in `std::fmt`.
421     ///
422     /// # Example
423     ///
424     /// ```rust
425     /// use std::fmt;
426     ///
427     /// let s = format_args!(fmt::format, "hello {}", "world");
428     /// assert_eq!(s, format!("hello {}", "world"));
429     ///
430     /// format_args!(|args| {
431     ///     // pass `args` to another function, etc.
432     /// }, "hello {}", "world");
433     /// ```
434     #[macro_export]
435     macro_rules! format_args { ($closure:expr, $fmt:expr $($args:tt)*) => ({
436         /* compiler built-in */
437     }) }
438
439     /// Inspect an environment variable at compile time.
440     ///
441     /// This macro will expand to the value of the named environment variable at
442     /// compile time, yielding an expression of type `&'static str`.
443     ///
444     /// If the environment variable is not defined, then a compilation error
445     /// will be emitted.  To not emit a compile error, use the `option_env!`
446     /// macro instead.
447     ///
448     /// # Example
449     ///
450     /// ```rust
451     /// let path: &'static str = env!("PATH");
452     /// println!("the $PATH variable at the time of compiling was: {}", path);
453     /// ```
454     #[macro_export]
455     macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) }
456
457     /// Optionally inspect an environment variable at compile time.
458     ///
459     /// If the named environment variable is present at compile time, this will
460     /// expand into an expression of type `Option<&'static str>` whose value is
461     /// `Some` of the value of the environment variable. If the environment
462     /// variable is not present, then this will expand to `None`.
463     ///
464     /// A compile time error is never emitted when using this macro regardless
465     /// of whether the environment variable is present or not.
466     ///
467     /// # Example
468     ///
469     /// ```rust
470     /// let key: Option<&'static str> = option_env!("SECRET_KEY");
471     /// println!("the secret key might be: {}", key);
472     /// ```
473     #[macro_export]
474     macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) }
475
476     /// Concatenate literals into a static byte slice.
477     ///
478     /// This macro takes any number of comma-separated literal expressions,
479     /// yielding an expression of type `&'static [u8]` which is the
480     /// concatenation (left to right) of all the literals in their byte format.
481     ///
482     /// This extension currently only supports string literals, character
483     /// literals, and integers less than 256. The byte slice returned is the
484     /// utf8-encoding of strings and characters.
485     ///
486     /// # Example
487     ///
488     /// ```
489     /// let rust = bytes!("r", 'u', "st", 255);
490     /// assert_eq!(rust[1], b'u');
491     /// assert_eq!(rust[4], 255);
492     /// ```
493     #[macro_export]
494     macro_rules! bytes { ($($e:expr),*) => ({ /* compiler built-in */ }) }
495
496     /// Concatenate identifiers into one identifier.
497     ///
498     /// This macro takes any number of comma-separated identifiers, and
499     /// concatenates them all into one, yielding an expression which is a new
500     /// identifier. Note that hygiene makes it such that this macro cannot
501     /// capture local variables, and macros are only allowed in item,
502     /// statement or expression position, meaning this macro may be difficult to
503     /// use in some situations.
504     ///
505     /// # Example
506     ///
507     /// ```
508     /// #![feature(concat_idents)]
509     ///
510     /// # fn main() {
511     /// fn foobar() -> int { 23 }
512     ///
513     /// let f = concat_idents!(foo, bar);
514     /// println!("{}", f());
515     /// # }
516     /// ```
517     #[macro_export]
518     macro_rules! concat_idents {
519         ($($e:ident),*) => ({ /* compiler built-in */ })
520     }
521
522     /// Concatenates literals into a static string slice.
523     ///
524     /// This macro takes any number of comma-separated literals, yielding an
525     /// expression of type `&'static str` which represents all of the literals
526     /// concatenated left-to-right.
527     ///
528     /// Integer and floating point literals are stringified in order to be
529     /// concatenated.
530     ///
531     /// # Example
532     ///
533     /// ```
534     /// let s = concat!("test", 10i, 'b', true);
535     /// assert_eq!(s, "test10btrue");
536     /// ```
537     #[macro_export]
538     macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) }
539
540     /// A macro which expands to the line number on which it was invoked.
541     ///
542     /// The expanded expression has type `uint`, and the returned line is not
543     /// the invocation of the `line!()` macro itself, but rather the first macro
544     /// invocation leading up to the invocation of the `line!()` macro.
545     ///
546     /// # Example
547     ///
548     /// ```
549     /// let current_line = line!();
550     /// println!("defined on line: {}", current_line);
551     /// ```
552     #[macro_export]
553     macro_rules! line { () => ({ /* compiler built-in */ }) }
554
555     /// A macro which expands to the column number on which it was invoked.
556     ///
557     /// The expanded expression has type `uint`, and the returned column is not
558     /// the invocation of the `column!()` macro itself, but rather the first macro
559     /// invocation leading up to the invocation of the `column!()` macro.
560     ///
561     /// # Example
562     ///
563     /// ```
564     /// let current_col = column!();
565     /// println!("defined on column: {}", current_col);
566     /// ```
567     #[macro_export]
568     macro_rules! column { () => ({ /* compiler built-in */ }) }
569
570     /// A macro which expands to the file name from which it was invoked.
571     ///
572     /// The expanded expression has type `&'static str`, and the returned file
573     /// is not the invocation of the `file!()` macro itself, but rather the
574     /// first macro invocation leading up to the invocation of the `file!()`
575     /// macro.
576     ///
577     /// # Example
578     ///
579     /// ```
580     /// let this_file = file!();
581     /// println!("defined in file: {}", this_file);
582     /// ```
583     #[macro_export]
584     macro_rules! file { () => ({ /* compiler built-in */ }) }
585
586     /// A macro which stringifies its argument.
587     ///
588     /// This macro will yield an expression of type `&'static str` which is the
589     /// stringification of all the tokens passed to the macro. No restrictions
590     /// are placed on the syntax of the macro invocation itself.
591     ///
592     /// # Example
593     ///
594     /// ```
595     /// let one_plus_one = stringify!(1 + 1);
596     /// assert_eq!(one_plus_one, "1 + 1");
597     /// ```
598     #[macro_export]
599     macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) }
600
601     /// Includes a utf8-encoded file as a string.
602     ///
603     /// This macro will yield an expression of type `&'static str` which is the
604     /// contents of the filename specified. The file is located relative to the
605     /// current file (similarly to how modules are found),
606     ///
607     /// # Example
608     ///
609     /// ```rust,ignore
610     /// let secret_key = include_str!("secret-key.ascii");
611     /// ```
612     #[macro_export]
613     macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) }
614
615     /// Includes a file as a byte slice.
616     ///
617     /// This macro will yield an expression of type `&'static [u8]` which is
618     /// the contents of the filename specified. The file is located relative to
619     /// the current file (similarly to how modules are found),
620     ///
621     /// # Example
622     ///
623     /// ```rust,ignore
624     /// let secret_key = include_bytes!("secret-key.bin");
625     /// ```
626     #[macro_export]
627     macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) }
628
629     /// Deprecated alias for `include_bytes!()`.
630     #[macro_export]
631     macro_rules! include_bin { ($file:expr) => ({ /* compiler built-in */}) }
632
633     /// Expands to a string that represents the current module path.
634     ///
635     /// The current module path can be thought of as the hierarchy of modules
636     /// leading back up to the crate root. The first component of the path
637     /// returned is the name of the crate currently being compiled.
638     ///
639     /// # Example
640     ///
641     /// ```rust
642     /// mod test {
643     ///     pub fn foo() {
644     ///         assert!(module_path!().ends_with("test"));
645     ///     }
646     /// }
647     ///
648     /// test::foo();
649     /// ```
650     #[macro_export]
651     macro_rules! module_path { () => ({ /* compiler built-in */ }) }
652
653     /// Boolean evaluation of configuration flags.
654     ///
655     /// In addition to the `#[cfg]` attribute, this macro is provided to allow
656     /// boolean expression evaluation of configuration flags. This frequently
657     /// leads to less duplicated code.
658     ///
659     /// The syntax given to this macro is the same syntax as the `cfg`
660     /// attribute.
661     ///
662     /// # Example
663     ///
664     /// ```rust
665     /// let my_directory = if cfg!(windows) {
666     ///     "windows-specific-directory"
667     /// } else {
668     ///     "unix-directory"
669     /// };
670     /// ```
671     #[macro_export]
672     macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) }
673 }