]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
Merge pull request #1016 from rust-lang-nursery/try-double-indent
[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::borrow::Cow;
12 use std::cmp::Ordering;
13
14 use itertools::Itertools;
15
16 use syntax::ast::{self, Visibility, Attribute, MetaItem, MetaItemKind, Path};
17 use syntax::codemap::BytePos;
18 use syntax::abi;
19
20 use Indent;
21 use rewrite::{Rewrite, RewriteContext};
22
23 use SKIP_ANNOTATION;
24
25 // Computes the length of a string's last line, minus offset.
26 #[inline]
27 pub fn extra_offset(text: &str, offset: Indent) -> usize {
28     match text.rfind('\n') {
29         // 1 for newline character
30         Some(idx) => text.len() - idx - 1 - offset.width(),
31         None => text.len(),
32     }
33 }
34
35 // Uses Cow to avoid allocating in the common cases.
36 pub fn format_visibility(vis: &Visibility) -> Cow<'static, str> {
37     match *vis {
38         Visibility::Public => Cow::from("pub "),
39         Visibility::Inherited => Cow::from(""),
40         Visibility::Crate(_) => Cow::from("pub(crate) "),
41         Visibility::Restricted { ref path, .. } => {
42             let Path { global, ref segments, .. } = **path;
43             let prefix = if global { "::" } else { "" };
44             let mut segments_iter = segments.iter().map(|seg| seg.identifier.name.as_str());
45
46             Cow::from(format!("pub({}{}) ", prefix, segments_iter.join("::")))
47         }
48     }
49 }
50
51 #[inline]
52 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
53     match unsafety {
54         ast::Unsafety::Unsafe => "unsafe ",
55         ast::Unsafety::Normal => "",
56     }
57 }
58
59 #[inline]
60 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
61     match mutability {
62         ast::Mutability::Mutable => "mut ",
63         ast::Mutability::Immutable => "",
64     }
65 }
66
67 #[inline]
68 pub fn format_abi(abi: abi::Abi, explicit_abi: bool) -> String {
69     if abi == abi::Abi::C && !explicit_abi {
70         "extern ".into()
71     } else {
72         format!("extern {} ", abi)
73     }
74 }
75
76 // The width of the first line in s.
77 #[inline]
78 pub fn first_line_width(s: &str) -> usize {
79     match s.find('\n') {
80         Some(n) => n,
81         None => s.len(),
82     }
83 }
84
85 // The width of the last line in s.
86 #[inline]
87 pub fn last_line_width(s: &str) -> usize {
88     match s.rfind('\n') {
89         Some(n) => s.len() - n - 1,
90         None => s.len(),
91     }
92 }
93 #[inline]
94 pub fn trimmed_last_line_width(s: &str) -> usize {
95     match s.rfind('\n') {
96         Some(n) => s[(n + 1)..].trim().len(),
97         None => s.trim().len(),
98     }
99 }
100
101 #[inline]
102 fn is_skip(meta_item: &MetaItem) -> bool {
103     match meta_item.node {
104         MetaItemKind::Word(ref s) => *s == SKIP_ANNOTATION,
105         MetaItemKind::List(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::ExprKind::Ret(..) |
133         ast::ExprKind::Again(..) |
134         ast::ExprKind::Break(..) => true,
135         _ => false,
136     }
137 }
138
139 #[inline]
140 pub fn semicolon_for_stmt(stmt: &ast::Stmt) -> bool {
141     match stmt.node {
142         ast::StmtKind::Semi(ref expr, _) => {
143             match expr.node {
144                 ast::ExprKind::While(..) |
145                 ast::ExprKind::WhileLet(..) |
146                 ast::ExprKind::Loop(..) |
147                 ast::ExprKind::ForLoop(..) => false,
148                 _ => true,
149             }
150         }
151         ast::StmtKind::Expr(..) => 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 // Macro for deriving implementations of Decodable for enums
168 #[macro_export]
169 macro_rules! impl_enum_decodable {
170     ( $e:ident, $( $x:ident ),* ) => {
171         impl ::rustc_serialize::Decodable for $e {
172             fn decode<D: ::rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
173                 use std::ascii::AsciiExt;
174                 let s = try!(d.read_str());
175                 $(
176                     if stringify!($x).eq_ignore_ascii_case(&s) {
177                       return Ok($e::$x);
178                     }
179                 )*
180                 Err(d.error("Bad variant"))
181             }
182         }
183
184         impl ::std::str::FromStr for $e {
185             type Err = &'static str;
186
187             fn from_str(s: &str) -> Result<Self, Self::Err> {
188                 use std::ascii::AsciiExt;
189                 $(
190                     if stringify!($x).eq_ignore_ascii_case(s) {
191                         return Ok($e::$x);
192                     }
193                 )*
194                 Err("Bad variant")
195             }
196         }
197
198         impl ::config::ConfigType for $e {
199             fn doc_hint() -> String {
200                 let mut variants = Vec::new();
201                 $(
202                     variants.push(stringify!($x));
203                 )*
204                 format!("[{}]", variants.join("|"))
205             }
206         }
207     };
208 }
209
210 // Same as try!, but for Option
211 #[macro_export]
212 macro_rules! try_opt {
213     ($expr:expr) => (match $expr {
214         Some(val) => val,
215         None => { return None; }
216     })
217 }
218
219 macro_rules! msg {
220     ($($arg:tt)*) => (
221         match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
222             Ok(_) => {},
223             Err(x) => panic!("Unable to write to stderr: {}", x),
224         }
225     )
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 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
316     match e.node {
317         ast::ExprKind::InPlace(ref e, _) |
318         ast::ExprKind::Call(ref e, _) |
319         ast::ExprKind::Binary(_, ref e, _) |
320         ast::ExprKind::Cast(ref e, _) |
321         ast::ExprKind::Type(ref e, _) |
322         ast::ExprKind::Assign(ref e, _) |
323         ast::ExprKind::AssignOp(_, ref e, _) |
324         ast::ExprKind::Field(ref e, _) |
325         ast::ExprKind::TupField(ref e, _) |
326         ast::ExprKind::Index(ref e, _) |
327         ast::ExprKind::Range(Some(ref e), _, _) => left_most_sub_expr(e),
328         // FIXME needs Try in Syntex
329         // ast::ExprKind::Try(ref f) => left_most_sub_expr(e),
330         _ => e,
331     }
332 }