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