]> git.lizzy.rs Git - rust.git/blob - src/libcore/macros.rs
Rollup merge of #35558 - lukehinds:master, r=nikomatsakis
[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 /// Write formatted data into a buffer
233 ///
234 /// This macro accepts any value with `write_fmt` method as a writer, a format string, and a list
235 /// of arguments to format.
236 ///
237 /// `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write] or
238 /// [`std::io::Write`][io_write] traits. These are sometimes called 'writers'.
239 ///
240 /// Passed arguments will be formatted according to the specified format string and the resulting
241 /// string will be passed to the writer.
242 ///
243 /// See [`std::fmt`][fmt] for more information on format syntax.
244 ///
245 /// Return value is completely dependent on the 'write_fmt' method.
246 ///
247 /// Common return values are: [`Result`][enum_result], [`io::Result`][type_result]
248 ///
249 /// [fmt]: ../std/fmt/index.html
250 /// [fmt_write]: ../std/fmt/trait.Write.html
251 /// [io_write]: ../std/io/trait.Write.html
252 /// [enum_result]: ../std/result/enum.Result.html
253 /// [type_result]: ../std/io/type.Result.html
254 ///
255 /// # Examples
256 ///
257 /// ```
258 /// use std::io::Write;
259 ///
260 /// let mut w = Vec::new();
261 /// write!(&mut w, "test").unwrap();
262 /// write!(&mut w, "formatted {}", "arguments").unwrap();
263 ///
264 /// assert_eq!(w, b"testformatted arguments");
265 /// ```
266 #[macro_export]
267 #[stable(feature = "core", since = "1.6.0")]
268 macro_rules! write {
269     ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
270 }
271
272 /// Write formatted data into a buffer, with appending a newline.
273 ///
274 /// On all platforms, the newline is the LINE FEED character (`\n`/`U+000A`) alone
275 /// (no additional CARRIAGE RETURN (`\r`/`U+000D`).
276 ///
277 /// This macro accepts any value with `write_fmt` method as a writer, a format string, and a list
278 /// of arguments to format.
279 ///
280 /// `write_fmt` method usually comes from an implementation of [`std::fmt::Write`][fmt_write] or
281 /// [`std::io::Write`][io_write] traits. These are sometimes called 'writers'.
282 ///
283 /// Passed arguments will be formatted according to the specified format string and the resulting
284 /// string will be passed to the writer.
285 ///
286 /// See [`std::fmt`][fmt] for more information on format syntax.
287 ///
288 /// Return value is completely dependent on the 'write_fmt' method.
289 ///
290 /// Common return values are: [`Result`][enum_result], [`io::Result`][type_result]
291 ///
292 /// [fmt]: ../std/fmt/index.html
293 /// [fmt_write]: ../std/fmt/trait.Write.html
294 /// [io_write]: ../std/io/trait.Write.html
295 /// [enum_result]: ../std/result/enum.Result.html
296 /// [type_result]: ../std/io/type.Result.html
297 ///
298 /// # Examples
299 ///
300 /// ```
301 /// use std::io::Write;
302 ///
303 /// let mut w = Vec::new();
304 /// writeln!(&mut w, "test").unwrap();
305 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
306 ///
307 /// assert_eq!(&w[..], "test\nformatted arguments\n".as_bytes());
308 /// ```
309 #[macro_export]
310 #[stable(feature = "rust1", since = "1.0.0")]
311 macro_rules! writeln {
312     ($dst:expr, $fmt:expr) => (
313         write!($dst, concat!($fmt, "\n"))
314     );
315     ($dst:expr, $fmt:expr, $($arg:tt)*) => (
316         write!($dst, concat!($fmt, "\n"), $($arg)*)
317     );
318 }
319
320 /// A utility macro for indicating unreachable code.
321 ///
322 /// This is useful any time that the compiler can't determine that some code is unreachable. For
323 /// example:
324 ///
325 /// * Match arms with guard conditions.
326 /// * Loops that dynamically terminate.
327 /// * Iterators that dynamically terminate.
328 ///
329 /// # Panics
330 ///
331 /// This will always panic.
332 ///
333 /// # Examples
334 ///
335 /// Match arms:
336 ///
337 /// ```
338 /// # #[allow(dead_code)]
339 /// fn foo(x: Option<i32>) {
340 ///     match x {
341 ///         Some(n) if n >= 0 => println!("Some(Non-negative)"),
342 ///         Some(n) if n <  0 => println!("Some(Negative)"),
343 ///         Some(_)           => unreachable!(), // compile error if commented out
344 ///         None              => println!("None")
345 ///     }
346 /// }
347 /// ```
348 ///
349 /// Iterators:
350 ///
351 /// ```
352 /// # #[allow(dead_code)]
353 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
354 ///     for i in 0.. {
355 ///         if 3*i < i { panic!("u32 overflow"); }
356 ///         if x < 3*i { return i-1; }
357 ///     }
358 ///     unreachable!();
359 /// }
360 /// ```
361 #[macro_export]
362 #[stable(feature = "core", since = "1.6.0")]
363 macro_rules! unreachable {
364     () => ({
365         panic!("internal error: entered unreachable code")
366     });
367     ($msg:expr) => ({
368         unreachable!("{}", $msg)
369     });
370     ($fmt:expr, $($arg:tt)*) => ({
371         panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
372     });
373 }
374
375 /// A standardized placeholder for marking unfinished code. It panics with the
376 /// message `"not yet implemented"` when executed.
377 ///
378 /// This can be useful if you are prototyping and are just looking to have your
379 /// code typecheck, or if you're implementing a trait that requires multiple
380 /// methods, and you're only planning on using one of them.
381 ///
382 /// # Examples
383 ///
384 /// Here's an example of some in-progress code. We have a trait `Foo`:
385 ///
386 /// ```
387 /// trait Foo {
388 ///     fn bar(&self);
389 ///     fn baz(&self);
390 /// }
391 /// ```
392 ///
393 /// We want to implement `Foo` on one of our types, but we also want to work on
394 /// just `bar()` first. In order for our code to compile, we need to implement
395 /// `baz()`, so we can use `unimplemented!`:
396 ///
397 /// ```
398 /// # trait Foo {
399 /// #     fn bar(&self);
400 /// #     fn baz(&self);
401 /// # }
402 /// struct MyStruct;
403 ///
404 /// impl Foo for MyStruct {
405 ///     fn bar(&self) {
406 ///         // implementation goes here
407 ///     }
408 ///
409 ///     fn baz(&self) {
410 ///         // let's not worry about implementing baz() for now
411 ///         unimplemented!();
412 ///     }
413 /// }
414 ///
415 /// fn main() {
416 ///     let s = MyStruct;
417 ///     s.bar();
418 ///
419 ///     // we aren't even using baz() yet, so this is fine.
420 /// }
421 /// ```
422 #[macro_export]
423 #[stable(feature = "core", since = "1.6.0")]
424 macro_rules! unimplemented {
425     () => (panic!("not yet implemented"))
426 }