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