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