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