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