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