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