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