]> git.proxmox.com Git - rustc.git/blob - src/libcore/macros.rs
Imported Upstream version 1.3.0+dfsg1
[rustc.git] / src / libcore / 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 /// Entry point of thread panic, for details, see std::macros
12 #[macro_export]
13 #[allow_internal_unstable]
14 macro_rules! panic {
15 () => (
16 panic!("explicit panic")
17 );
18 ($msg:expr) => ({
19 static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!());
20 $crate::panicking::panic(&_MSG_FILE_LINE)
21 });
22 ($fmt:expr, $($arg:tt)*) => ({
23 // The leading _'s are to avoid dead code warnings if this is
24 // used inside a dead function. Just `#[allow(dead_code)]` is
25 // insufficient, since the user may have
26 // `#[forbid(dead_code)]` and which cannot be overridden.
27 static _FILE_LINE: (&'static str, u32) = (file!(), line!());
28 $crate::panicking::panic_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
29 });
30 }
31
32 /// Ensure that a boolean expression is `true` at runtime.
33 ///
34 /// This will invoke the `panic!` macro if the provided expression cannot be
35 /// evaluated to `true` at runtime.
36 ///
37 /// # Examples
38 ///
39 /// ```
40 /// // the panic message for these assertions is the stringified value of the
41 /// // expression given.
42 /// assert!(true);
43 ///
44 /// fn some_computation() -> bool { true } // a very simple function
45 ///
46 /// assert!(some_computation());
47 ///
48 /// // assert with a custom message
49 /// let x = true;
50 /// assert!(x, "x wasn't true!");
51 ///
52 /// let a = 3; let b = 27;
53 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
54 /// ```
55 #[macro_export]
56 #[stable(feature = "rust1", since = "1.0.0")]
57 macro_rules! assert {
58 ($cond:expr) => (
59 if !$cond {
60 panic!(concat!("assertion failed: ", stringify!($cond)))
61 }
62 );
63 ($cond:expr, $($arg:tt)+) => (
64 if !$cond {
65 panic!($($arg)+)
66 }
67 );
68 }
69
70 /// Asserts that two expressions are equal to each other.
71 ///
72 /// On panic, this macro will print the values of the expressions with their
73 /// debug representations.
74 ///
75 /// # Examples
76 ///
77 /// ```
78 /// let a = 3;
79 /// let b = 1 + 2;
80 /// assert_eq!(a, b);
81 /// ```
82 #[macro_export]
83 #[stable(feature = "rust1", since = "1.0.0")]
84 macro_rules! assert_eq {
85 ($left:expr , $right:expr) => ({
86 match (&($left), &($right)) {
87 (left_val, right_val) => {
88 if !(*left_val == *right_val) {
89 panic!("assertion failed: `(left == right)` \
90 (left: `{:?}`, right: `{:?}`)", *left_val, *right_val)
91 }
92 }
93 }
94 })
95 }
96
97 /// Ensure that a boolean expression is `true` at runtime.
98 ///
99 /// This will invoke the `panic!` macro if the provided expression cannot be
100 /// evaluated to `true` at runtime.
101 ///
102 /// Unlike `assert!`, `debug_assert!` statements are only enabled in non
103 /// optimized builds by default. An optimized build will omit all
104 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
105 /// compiler. This makes `debug_assert!` useful for checks that are too
106 /// expensive to be present in a release build but may be helpful during
107 /// development.
108 ///
109 /// # Examples
110 ///
111 /// ```
112 /// // the panic message for these assertions is the stringified value of the
113 /// // expression given.
114 /// debug_assert!(true);
115 ///
116 /// fn some_expensive_computation() -> bool { true } // a very simple function
117 /// debug_assert!(some_expensive_computation());
118 ///
119 /// // assert with a custom message
120 /// let x = true;
121 /// debug_assert!(x, "x wasn't true!");
122 ///
123 /// let a = 3; let b = 27;
124 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
125 /// ```
126 #[macro_export]
127 #[stable(feature = "rust1", since = "1.0.0")]
128 macro_rules! debug_assert {
129 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
130 }
131
132 /// Asserts that two expressions are equal to each other, testing equality in
133 /// both directions.
134 ///
135 /// On panic, this macro will print the values of the expressions.
136 ///
137 /// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
138 /// optimized builds by default. An optimized build will omit all
139 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
140 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
141 /// expensive to be present in a release build but may be helpful during
142 /// development.
143 ///
144 /// # Examples
145 ///
146 /// ```
147 /// let a = 3;
148 /// let b = 1 + 2;
149 /// debug_assert_eq!(a, b);
150 /// ```
151 #[macro_export]
152 macro_rules! debug_assert_eq {
153 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
154 }
155
156 /// Short circuiting evaluation on Err
157 ///
158 /// `libstd` contains a more general `try!` macro that uses `From<E>`.
159 #[macro_export]
160 macro_rules! try {
161 ($e:expr) => ({
162 use $crate::result::Result::{Ok, Err};
163
164 match $e {
165 Ok(e) => e,
166 Err(e) => return Err(e),
167 }
168 })
169 }
170
171 /// Use the `format!` syntax to write data into a buffer of type `&mut Write`.
172 /// See `std::fmt` for more information.
173 ///
174 /// # Examples
175 ///
176 /// ```
177 /// use std::io::Write;
178 ///
179 /// let mut w = Vec::new();
180 /// write!(&mut w, "test").unwrap();
181 /// write!(&mut w, "formatted {}", "arguments").unwrap();
182 /// ```
183 #[macro_export]
184 macro_rules! write {
185 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
186 }
187
188 /// Equivalent to the `write!` macro, except that a newline is appended after
189 /// the message is written.
190 #[macro_export]
191 #[stable(feature = "rust1", since = "1.0.0")]
192 macro_rules! writeln {
193 ($dst:expr, $fmt:expr) => (
194 write!($dst, concat!($fmt, "\n"))
195 );
196 ($dst:expr, $fmt:expr, $($arg:tt)*) => (
197 write!($dst, concat!($fmt, "\n"), $($arg)*)
198 );
199 }
200
201 /// A utility macro for indicating unreachable code.
202 ///
203 /// This is useful any time that the compiler can't determine that some code is unreachable. For
204 /// example:
205 ///
206 /// * Match arms with guard conditions.
207 /// * Loops that dynamically terminate.
208 /// * Iterators that dynamically terminate.
209 ///
210 /// # Panics
211 ///
212 /// This will always panic.
213 ///
214 /// # Examples
215 ///
216 /// Match arms:
217 ///
218 /// ```
219 /// fn foo(x: Option<i32>) {
220 /// match x {
221 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
222 /// Some(n) if n < 0 => println!("Some(Negative)"),
223 /// Some(_) => unreachable!(), // compile error if commented out
224 /// None => println!("None")
225 /// }
226 /// }
227 /// ```
228 ///
229 /// Iterators:
230 ///
231 /// ```
232 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
233 /// for i in 0.. {
234 /// if 3*i < i { panic!("u32 overflow"); }
235 /// if x < 3*i { return i-1; }
236 /// }
237 /// unreachable!();
238 /// }
239 /// ```
240 #[macro_export]
241 #[unstable(feature = "core",
242 reason = "relationship with panic is unclear")]
243 macro_rules! unreachable {
244 () => ({
245 panic!("internal error: entered unreachable code")
246 });
247 ($msg:expr) => ({
248 unreachable!("{}", $msg)
249 });
250 ($fmt:expr, $($arg:tt)*) => ({
251 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
252 });
253 }
254
255 /// A standardised placeholder for marking unfinished code. It panics with the
256 /// message `"not yet implemented"` when executed.
257 #[macro_export]
258 #[unstable(feature = "core",
259 reason = "relationship with panic is unclear")]
260 macro_rules! unimplemented {
261 () => (panic!("not yet implemented"))
262 }