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