]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
Merge pull request #1785 from topecongiro/rfc/import
[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 syntax::abi;
15 use syntax::ast::{self, Attribute, MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind,
16                   Path, Visibility};
17 use syntax::codemap::{BytePos, Span, NO_EXPANSION};
18
19 use Shape;
20 use rewrite::{Rewrite, RewriteContext};
21
22 // When we get scoped annotations, we should have rustfmt::skip.
23 const SKIP_ANNOTATION: &'static str = "rustfmt_skip";
24
25 // Computes the length of a string's last line, minus offset.
26 pub fn extra_offset(text: &str, shape: Shape) -> usize {
27     match text.rfind('\n') {
28         // 1 for newline character
29         Some(idx) => text.len()
30             .checked_sub(idx + 1 + shape.used_width())
31             .unwrap_or(0),
32         None => text.len(),
33     }
34 }
35
36 // Uses Cow to avoid allocating in the common cases.
37 pub fn format_visibility(vis: &Visibility) -> Cow<'static, str> {
38     match *vis {
39         Visibility::Public => Cow::from("pub "),
40         Visibility::Inherited => Cow::from(""),
41         Visibility::Crate(_) => Cow::from("pub(crate) "),
42         Visibility::Restricted { ref path, .. } => {
43             let Path { ref segments, .. } = **path;
44             let mut segments_iter = segments.iter().map(|seg| seg.identifier.name.to_string());
45             if path.is_global() {
46                 segments_iter
47                     .next()
48                     .expect("Non-global path in pub(restricted)?");
49             }
50             let is_keyword = |s: &str| s == "self" || s == "super";
51             let path = segments_iter.collect::<Vec<_>>().join("::");
52             let in_str = if is_keyword(&path) { "" } else { "in " };
53
54             Cow::from(format!("pub({}{}) ", in_str, path))
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
102 #[inline]
103 pub fn trimmed_last_line_width(s: &str) -> usize {
104     match s.rfind('\n') {
105         Some(n) => s[(n + 1)..].trim().len(),
106         None => s.trim().len(),
107     }
108 }
109
110 #[inline]
111 pub fn last_line_extendable(s: &str) -> bool {
112     s.lines().last().map_or(false, |s| {
113         s.ends_with("\"#") ||
114             s.trim()
115                 .chars()
116                 .all(|c| c == ')' || c == ']' || c == '}' || c == '?')
117     })
118 }
119
120 #[inline]
121 fn is_skip(meta_item: &MetaItem) -> bool {
122     match meta_item.node {
123         MetaItemKind::Word => meta_item.name == SKIP_ANNOTATION,
124         MetaItemKind::List(ref l) => {
125             meta_item.name == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
126         }
127         _ => false,
128     }
129 }
130
131 #[inline]
132 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
133     match meta_item.node {
134         NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
135         NestedMetaItemKind::Literal(_) => false,
136     }
137 }
138
139 #[inline]
140 pub fn contains_skip(attrs: &[Attribute]) -> bool {
141     attrs
142         .iter()
143         .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
144 }
145
146 // Find the end of a TyParam
147 #[inline]
148 pub fn end_typaram(typaram: &ast::TyParam) -> BytePos {
149     typaram
150         .bounds
151         .last()
152         .map_or(typaram.span, |bound| match *bound {
153             ast::RegionTyParamBound(ref lt) => lt.span,
154             ast::TraitTyParamBound(ref prt, _) => prt.span,
155         })
156         .hi
157 }
158
159 #[inline]
160 pub fn semicolon_for_expr(context: &RewriteContext, expr: &ast::Expr) -> bool {
161     match expr.node {
162         ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
163             context.config.trailing_semicolon()
164         }
165         _ => false,
166     }
167 }
168
169 #[inline]
170 pub fn semicolon_for_stmt(context: &RewriteContext, stmt: &ast::Stmt) -> bool {
171     match stmt.node {
172         ast::StmtKind::Semi(ref expr) => match expr.node {
173             ast::ExprKind::While(..) |
174             ast::ExprKind::WhileLet(..) |
175             ast::ExprKind::Loop(..) |
176             ast::ExprKind::ForLoop(..) => false,
177             ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
178                 context.config.trailing_semicolon()
179             }
180             _ => true,
181         },
182         ast::StmtKind::Expr(..) => false,
183         _ => true,
184     }
185 }
186
187 #[inline]
188 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
189     match stmt.node {
190         ast::StmtKind::Expr(ref expr) => Some(expr),
191         _ => None,
192     }
193 }
194
195 #[inline]
196 pub fn trim_newlines(input: &str) -> &str {
197     match input.find(|c| c != '\n' && c != '\r') {
198         Some(start) => {
199             let end = input.rfind(|c| c != '\n' && c != '\r').unwrap_or(0) + 1;
200             &input[start..end]
201         }
202         None => "",
203     }
204 }
205
206 // Macro for deriving implementations of Serialize/Deserialize for enums
207 #[macro_export]
208 macro_rules! impl_enum_serialize_and_deserialize {
209     ( $e:ident, $( $x:ident ),* ) => {
210         impl ::serde::ser::Serialize for $e {
211             fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
212                 where S: ::serde::ser::Serializer
213             {
214                 use serde::ser::Error;
215
216                 // We don't know whether the user of the macro has given us all options.
217                 #[allow(unreachable_patterns)]
218                 match *self {
219                     $(
220                         $e::$x => serializer.serialize_str(stringify!($x)),
221                     )*
222                     _ => {
223                         Err(S::Error::custom(format!("Cannot serialize {:?}", self)))
224                     }
225                 }
226             }
227         }
228
229         impl<'de> ::serde::de::Deserialize<'de> for $e {
230             fn deserialize<D>(d: D) -> Result<Self, D::Error>
231                     where D: ::serde::Deserializer<'de> {
232                 use std::ascii::AsciiExt;
233                 use serde::de::{Error, Visitor};
234                 use std::marker::PhantomData;
235                 use std::fmt;
236                 struct StringOnly<T>(PhantomData<T>);
237                 impl<'de, T> Visitor<'de> for StringOnly<T>
238                         where T: ::serde::Deserializer<'de> {
239                     type Value = String;
240                     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
241                         formatter.write_str("string")
242                     }
243                     fn visit_str<E>(self, value: &str) -> Result<String, E> {
244                         Ok(String::from(value))
245                     }
246                 }
247                 let s = d.deserialize_string(StringOnly::<D>(PhantomData))?;
248                 $(
249                     if stringify!($x).eq_ignore_ascii_case(&s) {
250                       return Ok($e::$x);
251                     }
252                 )*
253                 static ALLOWED: &'static[&str] = &[$(stringify!($x),)*];
254                 Err(D::Error::unknown_variant(&s, ALLOWED))
255             }
256         }
257
258         impl ::std::str::FromStr for $e {
259             type Err = &'static str;
260
261             fn from_str(s: &str) -> Result<Self, Self::Err> {
262                 use std::ascii::AsciiExt;
263                 $(
264                     if stringify!($x).eq_ignore_ascii_case(s) {
265                         return Ok($e::$x);
266                     }
267                 )*
268                 Err("Bad variant")
269             }
270         }
271
272         impl ::config::ConfigType for $e {
273             fn doc_hint() -> String {
274                 let mut variants = Vec::new();
275                 $(
276                     variants.push(stringify!($x));
277                 )*
278                 format!("[{}]", variants.join("|"))
279             }
280         }
281     };
282 }
283
284 // Same as try!, but for Option
285 #[macro_export]
286 macro_rules! try_opt {
287     ($expr:expr) => (match $expr {
288         Some(val) => val,
289         None => { return None; }
290     })
291 }
292
293 macro_rules! msg {
294     ($($arg:tt)*) => (
295         match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
296             Ok(_) => {},
297             Err(x) => panic!("Unable to write to stderr: {}", x),
298         }
299     )
300 }
301
302 // For format_missing and last_pos, need to use the source callsite (if applicable).
303 // Required as generated code spans aren't guaranteed to follow on from the last span.
304 macro_rules! source {
305     ($this:ident, $sp: expr) => {
306         $sp.source_callsite()
307     }
308 }
309
310 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
311     Span {
312         lo,
313         hi,
314         ctxt: NO_EXPANSION,
315     }
316 }
317
318 // Wraps string-like values in an Option. Returns Some when the string adheres
319 // to the Rewrite constraints defined for the Rewrite trait and else otherwise.
320 pub fn wrap_str<S: AsRef<str>>(s: S, max_width: usize, shape: Shape) -> Option<S> {
321     {
322         let snippet = s.as_ref();
323
324         if !snippet.is_empty() {
325             if !snippet.contains('\n') && snippet.len() > shape.width {
326                 return None;
327             } else {
328                 let mut lines = snippet.lines();
329
330                 if lines.next().unwrap().len() > shape.width {
331                     return None;
332                 }
333
334                 // The other lines must fit within the maximum width.
335                 if lines.any(|line| line.len() > max_width) {
336                     return None;
337                 }
338
339                 // `width` is the maximum length of the last line, excluding
340                 // indentation.
341                 // A special check for the last line, since the caller may
342                 // place trailing characters on this line.
343                 if snippet.lines().rev().next().unwrap().len() > shape.used_width() + shape.width {
344                     return None;
345                 }
346             }
347         }
348     }
349
350     Some(s)
351 }
352
353 impl Rewrite for String {
354     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
355         wrap_str(self, context.config.max_width(), shape).map(ToOwned::to_owned)
356     }
357 }
358
359 // Binary search in integer range. Returns the first Ok value returned by the
360 // callback.
361 // The callback takes an integer and returns either an Ok, or an Err indicating
362 // whether the `guess' was too high (Ordering::Less), or too low.
363 // This function is guaranteed to try to the hi value first.
364 pub fn binary_search<C, T>(mut lo: usize, mut hi: usize, callback: C) -> Option<T>
365 where
366     C: Fn(usize) -> Result<T, Ordering>,
367 {
368     let mut middle = hi;
369
370     while lo <= hi {
371         match callback(middle) {
372             Ok(val) => return Some(val),
373             Err(Ordering::Less) => {
374                 hi = middle - 1;
375             }
376             Err(..) => {
377                 lo = middle + 1;
378             }
379         }
380         middle = (hi + lo) / 2;
381     }
382
383     None
384 }
385
386 #[inline]
387 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
388     match (before, after) {
389         (true, true) => " : ",
390         (true, false) => " :",
391         (false, true) => ": ",
392         (false, false) => ":",
393     }
394 }
395
396 #[inline]
397 pub fn paren_overhead(context: &RewriteContext) -> usize {
398     if context.config.spaces_within_parens() {
399         4
400     } else {
401         2
402     }
403 }
404
405 #[test]
406 fn bin_search_test() {
407     let closure = |i| match i {
408         4 => Ok(()),
409         j if j > 4 => Err(Ordering::Less),
410         j if j < 4 => Err(Ordering::Greater),
411         _ => unreachable!(),
412     };
413
414     assert_eq!(Some(()), binary_search(1, 10, &closure));
415     assert_eq!(None, binary_search(1, 3, &closure));
416     assert_eq!(Some(()), binary_search(0, 44, &closure));
417     assert_eq!(Some(()), binary_search(4, 125, &closure));
418     assert_eq!(None, binary_search(6, 100, &closure));
419 }
420
421 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
422     match e.node {
423         ast::ExprKind::InPlace(ref e, _) |
424         ast::ExprKind::Call(ref e, _) |
425         ast::ExprKind::Binary(_, ref e, _) |
426         ast::ExprKind::Cast(ref e, _) |
427         ast::ExprKind::Type(ref e, _) |
428         ast::ExprKind::Assign(ref e, _) |
429         ast::ExprKind::AssignOp(_, ref e, _) |
430         ast::ExprKind::Field(ref e, _) |
431         ast::ExprKind::TupField(ref e, _) |
432         ast::ExprKind::Index(ref e, _) |
433         ast::ExprKind::Range(Some(ref e), _, _) |
434         ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
435         _ => e,
436     }
437 }