]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
Merge pull request #618 from zyphrus/master
[rust.git] / src / utils.rs
1 // Copyright 2015 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 use std::cmp::Ordering;
12
13 use syntax::ast::{self, Visibility, Attribute, MetaItem, MetaItem_};
14 use syntax::codemap::{CodeMap, Span, BytePos};
15
16 use Indent;
17 use comment::FindUncommented;
18 use rewrite::{Rewrite, RewriteContext};
19
20 use SKIP_ANNOTATION;
21
22 // Computes the length of a string's last line, minus offset.
23 #[inline]
24 pub fn extra_offset(text: &str, offset: Indent) -> usize {
25     match text.rfind('\n') {
26         // 1 for newline character
27         Some(idx) => text.len() - idx - 1 - offset.width(),
28         None => text.len(),
29     }
30 }
31
32 #[inline]
33 pub fn span_after(original: Span, needle: &str, codemap: &CodeMap) -> BytePos {
34     let snippet = codemap.span_to_snippet(original).unwrap();
35     let offset = snippet.find_uncommented(needle).unwrap() + needle.len();
36
37     original.lo + BytePos(offset as u32)
38 }
39
40 #[inline]
41 pub fn format_visibility(vis: Visibility) -> &'static str {
42     match vis {
43         Visibility::Public => "pub ",
44         Visibility::Inherited => "",
45     }
46 }
47
48 #[inline]
49 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
50     match mutability {
51         ast::Mutability::MutMutable => "mut ",
52         ast::Mutability::MutImmutable => "",
53     }
54 }
55
56 // The width of the first line in s.
57 #[inline]
58 pub fn first_line_width(s: &str) -> usize {
59     match s.find('\n') {
60         Some(n) => n,
61         None => s.len(),
62     }
63 }
64
65 // The width of the last line in s.
66 #[inline]
67 pub fn last_line_width(s: &str) -> usize {
68     match s.rfind('\n') {
69         Some(n) => s.len() - n - 1,
70         None => s.len(),
71     }
72 }
73
74 #[inline]
75 fn is_skip(meta_item: &MetaItem) -> bool {
76     match meta_item.node {
77         MetaItem_::MetaWord(ref s) => *s == SKIP_ANNOTATION,
78         MetaItem_::MetaList(ref s, ref l) => {
79             *s == "cfg_attr" && l.len() == 2 && is_skip(&l[1])
80         }
81         _ => false,
82     }
83 }
84
85 #[inline]
86 pub fn contains_skip(attrs: &[Attribute]) -> bool {
87     attrs.iter().any(|a| is_skip(&a.node.value))
88 }
89
90 // Find the end of a TyParam
91 #[inline]
92 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
93     typaram.bounds
94            .last()
95            .map(|bound| {
96                match *bound {
97                    ast::RegionTyParamBound(ref lt) => lt.span,
98                    ast::TraitTyParamBound(ref prt, _) => prt.span,
99                }
100            })
101            .unwrap_or(typaram.span)
102            .hi
103 }
104
105 #[inline]
106 pub fn semicolon_for_expr(expr: &ast::Expr) -> bool {
107     match expr.node {
108         ast::Expr_::ExprRet(..) |
109         ast::Expr_::ExprAgain(..) |
110         ast::Expr_::ExprBreak(..) => true,
111         _ => false,
112     }
113 }
114
115 #[inline]
116 pub fn semicolon_for_stmt(stmt: &ast::Stmt) -> bool {
117     match stmt.node {
118         ast::Stmt_::StmtSemi(ref expr, _) => {
119             match expr.node {
120                 ast::Expr_::ExprWhile(..) |
121                 ast::Expr_::ExprWhileLet(..) |
122                 ast::Expr_::ExprLoop(..) |
123                 ast::Expr_::ExprForLoop(..) => false,
124                 _ => true,
125             }
126         }
127         ast::Stmt_::StmtExpr(..) => false,
128         _ => true,
129     }
130 }
131
132 #[inline]
133 #[cfg(target_pointer_width="64")]
134 // Based on the trick layed out at
135 // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
136 pub fn round_up_to_power_of_two(mut x: usize) -> usize {
137     x = x.wrapping_sub(1);
138     x |= x >> 1;
139     x |= x >> 2;
140     x |= x >> 4;
141     x |= x >> 8;
142     x |= x >> 16;
143     x |= x >> 32;
144     x.wrapping_add(1)
145 }
146
147 #[inline]
148 #[cfg(target_pointer_width="32")]
149 pub fn round_up_to_power_of_two(mut x: usize) -> usize {
150     x = x.wrapping_sub(1);
151     x |= x >> 1;
152     x |= x >> 2;
153     x |= x >> 4;
154     x |= x >> 8;
155     x |= x >> 16;
156     x.wrapping_add(1)
157 }
158
159 // Macro for deriving implementations of Decodable for enums
160 #[macro_export]
161 macro_rules! impl_enum_decodable {
162     ( $e:ident, $( $x:ident ),* ) => {
163         impl ::rustc_serialize::Decodable for $e {
164             fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
165                 let s = try!(d.read_str());
166                 match &*s {
167                     $(
168                         stringify!($x) => Ok($e::$x),
169                     )*
170                     _ => Err(d.error("Bad variant")),
171                 }
172             }
173         }
174
175         impl ::std::str::FromStr for $e {
176             type Err = &'static str;
177
178             fn from_str(s: &str) -> Result<Self, Self::Err> {
179                 match &*s {
180                     $(
181                         stringify!($x) => Ok($e::$x),
182                     )*
183                     _ => Err("Bad variant"),
184                 }
185             }
186         }
187
188         impl ::config::ConfigType for $e {
189             fn get_variant_names() -> String {
190                 let mut variants = Vec::new();
191                 $(
192                     variants.push(stringify!($x));
193                 )*
194                 format!("[{}]", variants.join("|"))
195             }
196         }
197     };
198 }
199
200 // Same as try!, but for Option
201 #[macro_export]
202 macro_rules! try_opt {
203     ($expr:expr) => (match $expr {
204         Some(val) => val,
205         None => { return None; }
206     })
207 }
208
209 // Wraps string-like values in an Option. Returns Some when the string adheres
210 // to the Rewrite constraints defined for the Rewrite trait and else otherwise.
211 pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, width: usize, offset: Indent) -> Option<S> {
212     {
213         let snippet = s.as_ref();
214
215         if !snippet.contains('\n') && snippet.len() > width {
216             return None;
217         } else {
218             let mut lines = snippet.lines();
219
220             // The caller of this function has already placed `offset`
221             // characters on the first line.
222             let first_line_max_len = try_opt!(max_width.checked_sub(offset.width()));
223             if lines.next().unwrap().len() > first_line_max_len {
224                 return None;
225             }
226
227             // The other lines must fit within the maximum width.
228             if lines.find(|line| line.len() > max_width).is_some() {
229                 return None;
230             }
231
232             // `width` is the maximum length of the last line, excluding
233             // indentation.
234             // A special check for the last line, since the caller may
235             // place trailing characters on this line.
236             if snippet.lines().rev().next().unwrap().len() > offset.width() + width {
237                 return None;
238             }
239         }
240     }
241
242     Some(s)
243 }
244
245 impl Rewrite for String {
246     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
247         wrap_str(self, context.config.max_width, width, offset).map(ToOwned::to_owned)
248     }
249 }
250
251 // Binary search in integer range. Returns the first Ok value returned by the
252 // callback.
253 // The callback takes an integer and returns either an Ok, or an Err indicating
254 // whether the `guess' was too high (Ordering::Less), or too low.
255 // This function is guaranteed to try to the hi value first.
256 pub fn binary_search<C, T>(mut lo: usize, mut hi: usize, callback: C) -> Option<T>
257     where C: Fn(usize) -> Result<T, Ordering>
258 {
259     let mut middle = hi;
260
261     while lo <= hi {
262         match callback(middle) {
263             Ok(val) => return Some(val),
264             Err(Ordering::Less) => {
265                 hi = middle - 1;
266             }
267             Err(..) => {
268                 lo = middle + 1;
269             }
270         }
271         middle = (hi + lo) / 2;
272     }
273
274     None
275 }
276
277 #[test]
278 fn bin_search_test() {
279     let closure = |i| {
280         match i {
281             4 => Ok(()),
282             j if j > 4 => Err(Ordering::Less),
283             j if j < 4 => Err(Ordering::Greater),
284             _ => unreachable!(),
285         }
286     };
287
288     assert_eq!(Some(()), binary_search(1, 10, &closure));
289     assert_eq!(None, binary_search(1, 3, &closure));
290     assert_eq!(Some(()), binary_search(0, 44, &closure));
291     assert_eq!(Some(()), binary_search(4, 125, &closure));
292     assert_eq!(None, binary_search(6, 100, &closure));
293 }
294
295 #[test]
296 fn power_rounding() {
297     assert_eq!(0, round_up_to_power_of_two(0));
298     assert_eq!(1, round_up_to_power_of_two(1));
299     assert_eq!(64, round_up_to_power_of_two(33));
300     assert_eq!(256, round_up_to_power_of_two(256));
301 }