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