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