]> git.lizzy.rs Git - rust.git/blob - src/liballoc/macros.rs
rustdoc: pretty-print Unevaluated expressions in types.
[rust.git] / src / liballoc / macros.rs
1 // Copyright 2013-2016 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 /// Creates a [`Vec`] containing the arguments.
12 ///
13 /// `vec!` allows `Vec`s to be defined with the same syntax as array expressions.
14 /// There are two forms of this macro:
15 ///
16 /// - Create a [`Vec`] containing a given list of elements:
17 ///
18 /// ```
19 /// let v = vec![1, 2, 3];
20 /// assert_eq!(v[0], 1);
21 /// assert_eq!(v[1], 2);
22 /// assert_eq!(v[2], 3);
23 /// ```
24 ///
25 /// - Create a [`Vec`] from a given element and size:
26 ///
27 /// ```
28 /// let v = vec![1; 3];
29 /// assert_eq!(v, [1, 1, 1]);
30 /// ```
31 ///
32 /// Note that unlike array expressions this syntax supports all elements
33 /// which implement [`Clone`] and the number of elements doesn't have to be
34 /// a constant.
35 ///
36 /// This will use `clone` to duplicate an expression, so one should be careful
37 /// using this with types having a nonstandard `Clone` implementation. For
38 /// example, `vec![Rc::new(1); 5]` will create a vector of five references
39 /// to the same boxed integer value, not five references pointing to independently
40 /// boxed integers.
41 ///
42 /// [`Vec`]: ../std/vec/struct.Vec.html
43 /// [`Clone`]: ../std/clone/trait.Clone.html
44 #[cfg(not(test))]
45 #[macro_export]
46 #[stable(feature = "rust1", since = "1.0.0")]
47 #[allow_internal_unstable]
48 macro_rules! vec {
49     ($elem:expr; $n:expr) => (
50         $crate::vec::from_elem($elem, $n)
51     );
52     ($($x:expr),*) => (
53         <[_]>::into_vec(box [$($x),*])
54     );
55     ($($x:expr,)*) => (vec![$($x),*])
56 }
57
58 // HACK(japaric): with cfg(test) the inherent `[T]::into_vec` method, which is
59 // required for this macro definition, is not available. Instead use the
60 // `slice::into_vec`  function which is only available with cfg(test)
61 // NB see the slice::hack module in slice.rs for more information
62 #[cfg(test)]
63 macro_rules! vec {
64     ($elem:expr; $n:expr) => (
65         $crate::vec::from_elem($elem, $n)
66     );
67     ($($x:expr),*) => (
68         $crate::slice::into_vec(box [$($x),*])
69     );
70     ($($x:expr,)*) => (vec![$($x),*])
71 }
72
73 /// Creates a `String` using interpolation of runtime expressions.
74 ///
75 /// The first argument `format!` recieves is a format string.  This must be a string
76 /// literal.  The power of the formatting string is in the `{}`s contained.
77 ///
78 /// Additional parameters passed to `format!` replace the `{}`s within the
79 /// formatting string in the order given unless named or positional parameters
80 /// are used, see [`std::fmt`][fmt] for more information.
81 ///
82 /// A common use for `format!` is concatenation and interpolation of strings.
83 /// The same convention is used with [`print!`] and [`write!`] macros,
84 /// depending on the intended destination of the string.
85 ///
86 /// [fmt]: ../std/fmt/index.html
87 /// [`print!`]: ../std/macro.print.html
88 /// [`write!`]: ../std/macro.write.html
89 ///
90 /// # Panics
91 ///
92 /// `format!` panics if a formatting trait implementation returns an error.
93 /// This indicates an incorrect implementation
94 /// since `fmt::Write for String` never returns an error itself.
95 ///
96 /// # Examples
97 ///
98 /// ```
99 /// format!("test");
100 /// format!("hello {}", "world!");
101 /// format!("x = {}, y = {y}", 10, y = 30);
102 /// ```
103 #[macro_export]
104 #[stable(feature = "rust1", since = "1.0.0")]
105 macro_rules! format {
106     ($($arg:tt)*) => ($crate::fmt::format(format_args!($($arg)*)))
107 }
108
109 // Private macro to get the offset of a struct field in bytes from the address of the struct.
110 macro_rules! offset_of {
111     ($container:path, $field:ident) => {{
112         // Make sure the field actually exists. This line ensures that a compile-time error is
113         // generated if $field is accessed through a Deref impl.
114         let $container { $field : _, .. };
115
116         // Create an (invalid) instance of the container and calculate the offset to its
117         // field. Using a null pointer might be UB if `&(*(0 as *const T)).field` is interpreted to
118         // be nullptr deref.
119         let invalid: $container = ::core::mem::uninitialized();
120         let offset = &invalid.$field as *const _ as usize - &invalid as *const _ as usize;
121
122         // Do not run destructors on the made up invalid instance.
123         ::core::mem::forget(invalid);
124         offset as isize
125     }};
126 }