]> git.proxmox.com Git - rustc.git/blob - src/libcore/macros.rs
Imported Upstream version 1.9.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 #[stable(feature = "core", since = "1.6.0")]
15 macro_rules! panic {
16 () => (
17 panic!("explicit panic")
18 );
19 ($msg:expr) => ({
20 static _MSG_FILE_LINE: (&'static str, &'static str, u32) = ($msg, file!(), line!());
21 $crate::panicking::panic(&_MSG_FILE_LINE)
22 });
23 ($fmt:expr, $($arg:tt)*) => ({
24 // The leading _'s are to avoid dead code warnings if this is
25 // used inside a dead function. Just `#[allow(dead_code)]` is
26 // insufficient, since the user may have
27 // `#[forbid(dead_code)]` and which cannot be overridden.
28 static _FILE_LINE: (&'static str, u32) = (file!(), line!());
29 $crate::panicking::panic_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE)
30 });
31 }
32
33 /// Ensure that a boolean expression is `true` at runtime.
34 ///
35 /// This will invoke the `panic!` macro if the provided expression cannot be
36 /// evaluated to `true` at runtime.
37 ///
38 /// This macro has a second version, where a custom panic message can be provided.
39 ///
40 /// # Examples
41 ///
42 /// ```
43 /// // the panic message for these assertions is the stringified value of the
44 /// // expression given.
45 /// assert!(true);
46 ///
47 /// fn some_computation() -> bool { true } // a very simple function
48 ///
49 /// assert!(some_computation());
50 ///
51 /// // assert with a custom message
52 /// let x = true;
53 /// assert!(x, "x wasn't true!");
54 ///
55 /// let a = 3; let b = 27;
56 /// assert!(a + b == 30, "a = {}, b = {}", a, b);
57 /// ```
58 #[macro_export]
59 #[stable(feature = "rust1", since = "1.0.0")]
60 macro_rules! assert {
61 ($cond:expr) => (
62 if !$cond {
63 panic!(concat!("assertion failed: ", stringify!($cond)))
64 }
65 );
66 ($cond:expr, $($arg:tt)+) => (
67 if !$cond {
68 panic!($($arg)+)
69 }
70 );
71 }
72
73 /// Asserts that two expressions are equal to each other.
74 ///
75 /// On panic, this macro will print the values of the expressions with their
76 /// debug representations.
77 ///
78 /// # Examples
79 ///
80 /// ```
81 /// let a = 3;
82 /// let b = 1 + 2;
83 /// assert_eq!(a, b);
84 /// ```
85 #[macro_export]
86 #[stable(feature = "rust1", since = "1.0.0")]
87 macro_rules! assert_eq {
88 ($left:expr , $right:expr) => ({
89 match (&($left), &($right)) {
90 (left_val, right_val) => {
91 if !(*left_val == *right_val) {
92 panic!("assertion failed: `(left == right)` \
93 (left: `{:?}`, right: `{:?}`)", left_val, right_val)
94 }
95 }
96 }
97 })
98 }
99
100 /// Ensure that a boolean expression is `true` at runtime.
101 ///
102 /// This will invoke the `panic!` macro if the provided expression cannot be
103 /// evaluated to `true` at runtime.
104 ///
105 /// Like `assert!`, this macro also has a second version, where a custom panic
106 /// message can be provided.
107 ///
108 /// Unlike `assert!`, `debug_assert!` statements are only enabled in non
109 /// optimized builds by default. An optimized build will omit all
110 /// `debug_assert!` statements unless `-C debug-assertions` is passed to the
111 /// compiler. This makes `debug_assert!` useful for checks that are too
112 /// expensive to be present in a release build but may be helpful during
113 /// development.
114 ///
115 /// # Examples
116 ///
117 /// ```
118 /// // the panic message for these assertions is the stringified value of the
119 /// // expression given.
120 /// debug_assert!(true);
121 ///
122 /// fn some_expensive_computation() -> bool { true } // a very simple function
123 /// debug_assert!(some_expensive_computation());
124 ///
125 /// // assert with a custom message
126 /// let x = true;
127 /// debug_assert!(x, "x wasn't true!");
128 ///
129 /// let a = 3; let b = 27;
130 /// debug_assert!(a + b == 30, "a = {}, b = {}", a, b);
131 /// ```
132 #[macro_export]
133 #[stable(feature = "rust1", since = "1.0.0")]
134 macro_rules! debug_assert {
135 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert!($($arg)*); })
136 }
137
138 /// Asserts that two expressions are equal to each other.
139 ///
140 /// On panic, this macro will print the values of the expressions with their
141 /// debug representations.
142 ///
143 /// Unlike `assert_eq!`, `debug_assert_eq!` statements are only enabled in non
144 /// optimized builds by default. An optimized build will omit all
145 /// `debug_assert_eq!` statements unless `-C debug-assertions` is passed to the
146 /// compiler. This makes `debug_assert_eq!` useful for checks that are too
147 /// expensive to be present in a release build but may be helpful during
148 /// development.
149 ///
150 /// # Examples
151 ///
152 /// ```
153 /// let a = 3;
154 /// let b = 1 + 2;
155 /// debug_assert_eq!(a, b);
156 /// ```
157 #[macro_export]
158 #[stable(feature = "rust1", since = "1.0.0")]
159 macro_rules! debug_assert_eq {
160 ($($arg:tt)*) => (if cfg!(debug_assertions) { assert_eq!($($arg)*); })
161 }
162
163 /// Helper macro for unwrapping `Result` values while returning early with an
164 /// error if the value of the expression is `Err`. Can only be used in
165 /// functions that return `Result` because of the early return of `Err` that
166 /// it provides.
167 ///
168 /// # Examples
169 ///
170 /// ```
171 /// use std::io;
172 /// use std::fs::File;
173 /// use std::io::prelude::*;
174 ///
175 /// fn write_to_file_using_try() -> Result<(), io::Error> {
176 /// let mut file = try!(File::create("my_best_friends.txt"));
177 /// try!(file.write_all(b"This is a list of my best friends."));
178 /// println!("I wrote to the file");
179 /// Ok(())
180 /// }
181 /// // This is equivalent to:
182 /// fn write_to_file_using_match() -> Result<(), io::Error> {
183 /// let mut file = try!(File::create("my_best_friends.txt"));
184 /// match file.write_all(b"This is a list of my best friends.") {
185 /// Ok(_) => (),
186 /// Err(e) => return Err(e),
187 /// }
188 /// println!("I wrote to the file");
189 /// Ok(())
190 /// }
191 /// ```
192 #[macro_export]
193 #[stable(feature = "rust1", since = "1.0.0")]
194 macro_rules! try {
195 ($expr:expr) => (match $expr {
196 $crate::result::Result::Ok(val) => val,
197 $crate::result::Result::Err(err) => {
198 return $crate::result::Result::Err($crate::convert::From::from(err))
199 }
200 })
201 }
202
203 /// Use the `format!` syntax to write data into a buffer.
204 ///
205 /// This macro is typically used with a buffer of `&mut `[`Write`][write].
206 ///
207 /// See [`std::fmt`][fmt] for more information on format syntax.
208 ///
209 /// [fmt]: ../std/fmt/index.html
210 /// [write]: ../std/io/trait.Write.html
211 ///
212 /// # Examples
213 ///
214 /// ```
215 /// use std::io::Write;
216 ///
217 /// let mut w = Vec::new();
218 /// write!(&mut w, "test").unwrap();
219 /// write!(&mut w, "formatted {}", "arguments").unwrap();
220 ///
221 /// assert_eq!(w, b"testformatted arguments");
222 /// ```
223 #[macro_export]
224 #[stable(feature = "core", since = "1.6.0")]
225 macro_rules! write {
226 ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
227 }
228
229 /// Use the `format!` syntax to write data into a buffer, appending a newline.
230 ///
231 /// This macro is typically used with a buffer of `&mut `[`Write`][write].
232 ///
233 /// See [`std::fmt`][fmt] for more information on format syntax.
234 ///
235 /// [fmt]: ../std/fmt/index.html
236 /// [write]: ../std/io/trait.Write.html
237 ///
238 /// # Examples
239 ///
240 /// ```
241 /// use std::io::Write;
242 ///
243 /// let mut w = Vec::new();
244 /// writeln!(&mut w, "test").unwrap();
245 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
246 ///
247 /// assert_eq!(&w[..], "test\nformatted arguments\n".as_bytes());
248 /// ```
249 #[macro_export]
250 #[stable(feature = "rust1", since = "1.0.0")]
251 macro_rules! writeln {
252 ($dst:expr, $fmt:expr) => (
253 write!($dst, concat!($fmt, "\n"))
254 );
255 ($dst:expr, $fmt:expr, $($arg:tt)*) => (
256 write!($dst, concat!($fmt, "\n"), $($arg)*)
257 );
258 }
259
260 /// A utility macro for indicating unreachable code.
261 ///
262 /// This is useful any time that the compiler can't determine that some code is unreachable. For
263 /// example:
264 ///
265 /// * Match arms with guard conditions.
266 /// * Loops that dynamically terminate.
267 /// * Iterators that dynamically terminate.
268 ///
269 /// # Panics
270 ///
271 /// This will always panic.
272 ///
273 /// # Examples
274 ///
275 /// Match arms:
276 ///
277 /// ```
278 /// # #[allow(dead_code)]
279 /// fn foo(x: Option<i32>) {
280 /// match x {
281 /// Some(n) if n >= 0 => println!("Some(Non-negative)"),
282 /// Some(n) if n < 0 => println!("Some(Negative)"),
283 /// Some(_) => unreachable!(), // compile error if commented out
284 /// None => println!("None")
285 /// }
286 /// }
287 /// ```
288 ///
289 /// Iterators:
290 ///
291 /// ```
292 /// # #[allow(dead_code)]
293 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
294 /// for i in 0.. {
295 /// if 3*i < i { panic!("u32 overflow"); }
296 /// if x < 3*i { return i-1; }
297 /// }
298 /// unreachable!();
299 /// }
300 /// ```
301 #[macro_export]
302 #[stable(feature = "core", since = "1.6.0")]
303 macro_rules! unreachable {
304 () => ({
305 panic!("internal error: entered unreachable code")
306 });
307 ($msg:expr) => ({
308 unreachable!("{}", $msg)
309 });
310 ($fmt:expr, $($arg:tt)*) => ({
311 panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
312 });
313 }
314
315 /// A standardized placeholder for marking unfinished code. It panics with the
316 /// message `"not yet implemented"` when executed.
317 ///
318 /// This can be useful if you are prototyping and are just looking to have your
319 /// code typecheck, or if you're implementing a trait that requires multiple
320 /// methods, and you're only planning on using one of them.
321 ///
322 /// # Examples
323 ///
324 /// Here's an example of some in-progress code. We have a trait `Foo`:
325 ///
326 /// ```
327 /// trait Foo {
328 /// fn bar(&self);
329 /// fn baz(&self);
330 /// }
331 /// ```
332 ///
333 /// We want to implement `Foo` on one of our types, but we also want to work on
334 /// just `bar()` first. In order for our code to compile, we need to implement
335 /// `baz()`, so we can use `unimplemented!`:
336 ///
337 /// ```
338 /// # trait Foo {
339 /// # fn bar(&self);
340 /// # fn baz(&self);
341 /// # }
342 /// struct MyStruct;
343 ///
344 /// impl Foo for MyStruct {
345 /// fn bar(&self) {
346 /// // implementation goes here
347 /// }
348 ///
349 /// fn baz(&self) {
350 /// // let's not worry about implementing baz() for now
351 /// unimplemented!();
352 /// }
353 /// }
354 ///
355 /// fn main() {
356 /// let s = MyStruct;
357 /// s.bar();
358 ///
359 /// // we aren't even using baz() yet, so this is fine.
360 /// }
361 /// ```
362 #[macro_export]
363 #[stable(feature = "core", since = "1.6.0")]
364 macro_rules! unimplemented {
365 () => (panic!("not yet implemented"))
366 }