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