]> git.lizzy.rs Git - rust.git/blob - src/libcore/macros.rs
Improve docs for write!/writeln! macros
[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 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.
172 ///
173 /// This macro is typically used with a buffer of `&mut `[`Write`][write].
174 ///
175 /// See [`std::fmt`][fmt] for more information on format syntax.
176 ///
177 /// [fmt]: fmt/index.html
178 /// [write]: io/trait.Write.html
179 ///
180 /// # Examples
181 ///
182 /// ```
183 /// use std::io::Write;
184 ///
185 /// let mut w = Vec::new();
186 /// write!(&mut w, "test").unwrap();
187 /// write!(&mut w, "formatted {}", "arguments").unwrap();
188 ///
189 /// assert_eq!(w, b"testformatted arguments");
190 /// ```
191 #[macro_export]
192 macro_rules! write {
193     ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
194 }
195
196 /// Use the `format!` syntax to write data into a buffer, appending a newline.
197 ///
198 /// This macro is typically used with a buffer of `&mut `[`Write`][write].
199 ///
200 /// See [`std::fmt`][fmt] for more information on format syntax.
201 ///
202 /// [fmt]: fmt/index.html
203 /// [write]: io/trait.Write.html
204 ///
205 /// # Examples
206 ///
207 /// ```
208 /// use std::io::Write;
209 ///
210 /// let mut w = Vec::new();
211 /// writeln!(&mut w, "test").unwrap();
212 /// writeln!(&mut w, "formatted {}", "arguments").unwrap();
213 ///
214 /// assert_eq!(&w[..], "test\nformatted arguments\n".as_bytes());
215 /// ```
216 #[macro_export]
217 #[stable(feature = "rust1", since = "1.0.0")]
218 macro_rules! writeln {
219     ($dst:expr, $fmt:expr) => (
220         write!($dst, concat!($fmt, "\n"))
221     );
222     ($dst:expr, $fmt:expr, $($arg:tt)*) => (
223         write!($dst, concat!($fmt, "\n"), $($arg)*)
224     );
225 }
226
227 /// A utility macro for indicating unreachable code.
228 ///
229 /// This is useful any time that the compiler can't determine that some code is unreachable. For
230 /// example:
231 ///
232 /// * Match arms with guard conditions.
233 /// * Loops that dynamically terminate.
234 /// * Iterators that dynamically terminate.
235 ///
236 /// # Panics
237 ///
238 /// This will always panic.
239 ///
240 /// # Examples
241 ///
242 /// Match arms:
243 ///
244 /// ```
245 /// fn foo(x: Option<i32>) {
246 ///     match x {
247 ///         Some(n) if n >= 0 => println!("Some(Non-negative)"),
248 ///         Some(n) if n <  0 => println!("Some(Negative)"),
249 ///         Some(_)           => unreachable!(), // compile error if commented out
250 ///         None              => println!("None")
251 ///     }
252 /// }
253 /// ```
254 ///
255 /// Iterators:
256 ///
257 /// ```
258 /// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3
259 ///     for i in 0.. {
260 ///         if 3*i < i { panic!("u32 overflow"); }
261 ///         if x < 3*i { return i-1; }
262 ///     }
263 ///     unreachable!();
264 /// }
265 /// ```
266 #[macro_export]
267 #[unstable(feature = "core",
268            reason = "relationship with panic is unclear",
269            issue = "27701")]
270 macro_rules! unreachable {
271     () => ({
272         panic!("internal error: entered unreachable code")
273     });
274     ($msg:expr) => ({
275         unreachable!("{}", $msg)
276     });
277     ($fmt:expr, $($arg:tt)*) => ({
278         panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
279     });
280 }
281
282 /// A standardised placeholder for marking unfinished code. It panics with the
283 /// message `"not yet implemented"` when executed.
284 ///
285 /// This can be useful if you are prototyping and are just looking to have your
286 /// code typecheck, or if you're implementing a trait that requires multiple
287 /// methods, and you're only planning on using one of them.
288 ///
289 /// # Examples
290 ///
291 /// Here's an example of some in-progress code. We have a trait `Foo`:
292 ///
293 /// ```
294 /// trait Foo {
295 ///     fn bar(&self);
296 ///     fn baz(&self);
297 /// }
298 /// ```
299 ///
300 /// We want to implement `Foo` on one of our types, but we also want to work on
301 /// just `bar()` first. In order for our code to compile, we need to implement
302 /// `baz()`, so we can use `unimplemented!`:
303 ///
304 /// ```
305 /// # trait Foo {
306 /// #     fn foo(&self);
307 /// #     fn bar(&self);
308 /// # }
309 /// struct MyStruct;
310 ///
311 /// impl Foo for MyStruct {
312 ///     fn foo(&self) {
313 ///         // implementation goes here
314 ///     }
315 ///
316 ///     fn bar(&self) {
317 ///         // let's not worry about implementing bar() for now
318 ///         unimplemented!();
319 ///     }
320 /// }
321 ///
322 /// fn main() {
323 ///     let s = MyStruct;
324 ///     s.foo();
325 ///
326 ///     // we aren't even using bar() yet, so this is fine.
327 /// }
328 /// ```
329 #[macro_export]
330 #[unstable(feature = "core",
331            reason = "relationship with panic is unclear",
332            issue = "27701")]
333 macro_rules! unimplemented {
334     () => (panic!("not yet implemented"))
335 }