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