]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
fix clippy::redundant_clones warnings.
[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
13 use bytecount;
14
15 use rustc_target::spec::abi;
16 use syntax::ast::{
17     self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NestedMetaItemKind, Path,
18     Visibility, VisibilityKind,
19 };
20 use syntax::ptr;
21 use syntax::source_map::{BytePos, Span, NO_EXPANSION};
22
23 use comment::{filter_normal_code, CharClasses, FullCodeCharKind};
24 use config::Config;
25 use rewrite::RewriteContext;
26 use shape::{Indent, Shape};
27
28 pub const DEPR_SKIP_ANNOTATION: &str = "rustfmt_skip";
29 pub const SKIP_ANNOTATION: &str = "rustfmt::skip";
30
31 pub fn rewrite_ident<'a>(context: &'a RewriteContext, ident: ast::Ident) -> &'a str {
32     context.snippet(ident.span)
33 }
34
35 // Computes the length of a string's last line, minus offset.
36 pub fn extra_offset(text: &str, shape: Shape) -> usize {
37     match text.rfind('\n') {
38         // 1 for newline character
39         Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()),
40         None => text.len(),
41     }
42 }
43
44 pub fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
45     match (&a.node, &b.node) {
46         (
47             VisibilityKind::Restricted { path: p, .. },
48             VisibilityKind::Restricted { path: q, .. },
49         ) => p.to_string() == q.to_string(),
50         (VisibilityKind::Public, VisibilityKind::Public)
51         | (VisibilityKind::Inherited, VisibilityKind::Inherited)
52         | (
53             VisibilityKind::Crate(CrateSugar::PubCrate),
54             VisibilityKind::Crate(CrateSugar::PubCrate),
55         )
56         | (
57             VisibilityKind::Crate(CrateSugar::JustCrate),
58             VisibilityKind::Crate(CrateSugar::JustCrate),
59         ) => true,
60         _ => false,
61     }
62 }
63
64 // Uses Cow to avoid allocating in the common cases.
65 pub fn format_visibility(context: &RewriteContext, vis: &Visibility) -> Cow<'static, str> {
66     match vis.node {
67         VisibilityKind::Public => Cow::from("pub "),
68         VisibilityKind::Inherited => Cow::from(""),
69         VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
70         VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
71         VisibilityKind::Restricted { ref path, .. } => {
72             let Path { ref segments, .. } = **path;
73             let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
74             if path.is_global() {
75                 segments_iter
76                     .next()
77                     .expect("Non-global path in pub(restricted)?");
78             }
79             let is_keyword = |s: &str| s == "self" || s == "super";
80             let path = segments_iter.collect::<Vec<_>>().join("::");
81             let in_str = if is_keyword(&path) { "" } else { "in " };
82
83             Cow::from(format!("pub({}{}) ", in_str, path))
84         }
85     }
86 }
87
88 #[inline]
89 pub fn format_async(is_async: ast::IsAsync) -> &'static str {
90     match is_async {
91         ast::IsAsync::Async { .. } => "async ",
92         ast::IsAsync::NotAsync => "",
93     }
94 }
95
96 #[inline]
97 pub fn format_constness(constness: ast::Constness) -> &'static str {
98     match constness {
99         ast::Constness::Const => "const ",
100         ast::Constness::NotConst => "",
101     }
102 }
103
104 #[inline]
105 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
106     match defaultness {
107         ast::Defaultness::Default => "default ",
108         ast::Defaultness::Final => "",
109     }
110 }
111
112 #[inline]
113 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
114     match unsafety {
115         ast::Unsafety::Unsafe => "unsafe ",
116         ast::Unsafety::Normal => "",
117     }
118 }
119
120 #[inline]
121 pub fn format_auto(is_auto: ast::IsAuto) -> &'static str {
122     match is_auto {
123         ast::IsAuto::Yes => "auto ",
124         ast::IsAuto::No => "",
125     }
126 }
127
128 #[inline]
129 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
130     match mutability {
131         ast::Mutability::Mutable => "mut ",
132         ast::Mutability::Immutable => "",
133     }
134 }
135
136 #[inline]
137 pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
138     if abi == abi::Abi::Rust && !is_mod {
139         Cow::from("")
140     } else if abi == abi::Abi::C && !explicit_abi {
141         Cow::from("extern ")
142     } else {
143         Cow::from(format!("extern {} ", abi))
144     }
145 }
146
147 #[inline]
148 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
149 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
150     vec.iter().map(|x| &**x).collect::<Vec<_>>()
151 }
152
153 #[inline]
154 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
155     attrs
156         .iter()
157         .filter(|a| a.style == style)
158         .cloned()
159         .collect::<Vec<_>>()
160 }
161
162 #[inline]
163 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
164     filter_attributes(attrs, ast::AttrStyle::Inner)
165 }
166
167 #[inline]
168 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
169     filter_attributes(attrs, ast::AttrStyle::Outer)
170 }
171
172 #[inline]
173 pub fn is_single_line(s: &str) -> bool {
174     s.chars().find(|&c| c == '\n').is_none()
175 }
176
177 #[inline]
178 pub fn first_line_contains_single_line_comment(s: &str) -> bool {
179     s.lines().next().map_or(false, |l| l.contains("//"))
180 }
181
182 #[inline]
183 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
184     s.lines().last().map_or(false, |l| l.contains("//"))
185 }
186
187 #[inline]
188 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
189     !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
190 }
191
192 // The width of the first line in s.
193 #[inline]
194 pub fn first_line_width(s: &str) -> usize {
195     match s.find('\n') {
196         Some(n) => n,
197         None => s.len(),
198     }
199 }
200
201 // The width of the last line in s.
202 #[inline]
203 pub fn last_line_width(s: &str) -> usize {
204     match s.rfind('\n') {
205         Some(n) => s.len() - n - 1,
206         None => s.len(),
207     }
208 }
209
210 // The total used width of the last line.
211 #[inline]
212 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
213     if s.contains('\n') {
214         last_line_width(s)
215     } else {
216         offset + s.len()
217     }
218 }
219
220 #[inline]
221 pub fn trimmed_last_line_width(s: &str) -> usize {
222     match s.rfind('\n') {
223         Some(n) => s[(n + 1)..].trim().len(),
224         None => s.trim().len(),
225     }
226 }
227
228 #[inline]
229 pub fn last_line_extendable(s: &str) -> bool {
230     if s.ends_with("\"#") {
231         return true;
232     }
233     for c in s.chars().rev() {
234         match c {
235             '(' | ')' | ']' | '}' | '?' | '>' => continue,
236             '\n' => break,
237             _ if c.is_whitespace() => continue,
238             _ => return false,
239         }
240     }
241     true
242 }
243
244 #[inline]
245 fn is_skip(meta_item: &MetaItem) -> bool {
246     match meta_item.node {
247         MetaItemKind::Word => {
248             let path_str = meta_item.ident.to_string();
249             path_str == SKIP_ANNOTATION || path_str == DEPR_SKIP_ANNOTATION
250         }
251         MetaItemKind::List(ref l) => {
252             meta_item.name() == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
253         }
254         _ => false,
255     }
256 }
257
258 #[inline]
259 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
260     match meta_item.node {
261         NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
262         NestedMetaItemKind::Literal(_) => false,
263     }
264 }
265
266 #[inline]
267 pub fn contains_skip(attrs: &[Attribute]) -> bool {
268     attrs
269         .iter()
270         .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
271 }
272
273 #[inline]
274 pub fn semicolon_for_expr(context: &RewriteContext, expr: &ast::Expr) -> bool {
275     match expr.node {
276         ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
277             context.config.trailing_semicolon()
278         }
279         _ => false,
280     }
281 }
282
283 #[inline]
284 pub fn semicolon_for_stmt(context: &RewriteContext, stmt: &ast::Stmt) -> bool {
285     match stmt.node {
286         ast::StmtKind::Semi(ref expr) => match expr.node {
287             ast::ExprKind::While(..)
288             | ast::ExprKind::WhileLet(..)
289             | ast::ExprKind::Loop(..)
290             | ast::ExprKind::ForLoop(..) => false,
291             ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
292                 context.config.trailing_semicolon()
293             }
294             _ => true,
295         },
296         ast::StmtKind::Expr(..) => false,
297         _ => true,
298     }
299 }
300
301 #[inline]
302 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
303     match stmt.node {
304         ast::StmtKind::Expr(ref expr) => Some(expr),
305         _ => None,
306     }
307 }
308
309 #[inline]
310 pub fn count_newlines(input: &str) -> usize {
311     // Using bytes to omit UTF-8 decoding
312     bytecount::count(input.as_bytes(), b'\n')
313 }
314
315 // For format_missing and last_pos, need to use the source callsite (if applicable).
316 // Required as generated code spans aren't guaranteed to follow on from the last span.
317 macro_rules! source {
318     ($this:ident, $sp:expr) => {
319         $sp.source_callsite()
320     };
321 }
322
323 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
324     Span::new(lo, hi, NO_EXPANSION)
325 }
326
327 // Return true if the given span does not intersect with file lines.
328 macro_rules! out_of_file_lines_range {
329     ($self:ident, $span:expr) => {
330         !$self.config.file_lines().is_all()
331             && !$self
332                 .config
333                 .file_lines()
334                 .intersects(&$self.source_map.lookup_line_range($span))
335     };
336 }
337
338 macro_rules! skip_out_of_file_lines_range {
339     ($self:ident, $span:expr) => {
340         if out_of_file_lines_range!($self, $span) {
341             return None;
342         }
343     };
344 }
345
346 macro_rules! skip_out_of_file_lines_range_visitor {
347     ($self:ident, $span:expr) => {
348         if out_of_file_lines_range!($self, $span) {
349             $self.push_rewrite($span, None);
350             return;
351         }
352     };
353 }
354
355 // Wraps String in an Option. Returns Some when the string adheres to the
356 // Rewrite constraints defined for the Rewrite trait and None otherwise.
357 pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
358     if is_valid_str(&filter_normal_code(&s), max_width, shape) {
359         Some(s)
360     } else {
361         None
362     }
363 }
364
365 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
366     if !snippet.is_empty() {
367         // First line must fits with `shape.width`.
368         if first_line_width(snippet) > shape.width {
369             return false;
370         }
371         // If the snippet does not include newline, we are done.
372         if first_line_width(snippet) == snippet.len() {
373             return true;
374         }
375         // The other lines must fit within the maximum width.
376         if snippet.lines().skip(1).any(|line| line.len() > max_width) {
377             return false;
378         }
379         // A special check for the last line, since the caller may
380         // place trailing characters on this line.
381         if last_line_width(snippet) > shape.used_width() + shape.width {
382             return false;
383         }
384     }
385     true
386 }
387
388 #[inline]
389 pub fn colon_spaces(before: bool, after: bool) -> &'static str {
390     match (before, after) {
391         (true, true) => " : ",
392         (true, false) => " :",
393         (false, true) => ": ",
394         (false, false) => ":",
395     }
396 }
397
398 #[inline]
399 pub fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
400     match e.node {
401         ast::ExprKind::Call(ref e, _)
402         | ast::ExprKind::Binary(_, ref e, _)
403         | ast::ExprKind::Cast(ref e, _)
404         | ast::ExprKind::Type(ref e, _)
405         | ast::ExprKind::Assign(ref e, _)
406         | ast::ExprKind::AssignOp(_, ref e, _)
407         | ast::ExprKind::Field(ref e, _)
408         | ast::ExprKind::Index(ref e, _)
409         | ast::ExprKind::Range(Some(ref e), _, _)
410         | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
411         _ => e,
412     }
413 }
414
415 #[inline]
416 pub fn starts_with_newline(s: &str) -> bool {
417     s.starts_with('\n') || s.starts_with("\r\n")
418 }
419
420 #[inline]
421 pub fn first_line_ends_with(s: &str, c: char) -> bool {
422     s.lines().next().map_or(false, |l| l.ends_with(c))
423 }
424
425 // States whether an expression's last line exclusively consists of closing
426 // parens, braces, and brackets in its idiomatic formatting.
427 pub fn is_block_expr(context: &RewriteContext, expr: &ast::Expr, repr: &str) -> bool {
428     match expr.node {
429         ast::ExprKind::Mac(..)
430         | ast::ExprKind::Call(..)
431         | ast::ExprKind::MethodCall(..)
432         | ast::ExprKind::Array(..)
433         | ast::ExprKind::Struct(..)
434         | ast::ExprKind::While(..)
435         | ast::ExprKind::WhileLet(..)
436         | ast::ExprKind::If(..)
437         | ast::ExprKind::IfLet(..)
438         | ast::ExprKind::Block(..)
439         | ast::ExprKind::Loop(..)
440         | ast::ExprKind::ForLoop(..)
441         | ast::ExprKind::Match(..) => repr.contains('\n'),
442         ast::ExprKind::Paren(ref expr)
443         | ast::ExprKind::Binary(_, _, ref expr)
444         | ast::ExprKind::Index(_, ref expr)
445         | ast::ExprKind::Unary(_, ref expr)
446         | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
447         | ast::ExprKind::Try(ref expr)
448         | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
449         // This can only be a string lit
450         ast::ExprKind::Lit(_) => {
451             repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
452         }
453         _ => false,
454     }
455 }
456
457 /// Remove trailing spaces from the specified snippet. We do not remove spaces
458 /// inside strings or comments.
459 pub fn remove_trailing_white_spaces(text: &str) -> String {
460     let mut buffer = String::with_capacity(text.len());
461     let mut space_buffer = String::with_capacity(128);
462     for (char_kind, c) in CharClasses::new(text.chars()) {
463         match c {
464             '\n' => {
465                 if char_kind == FullCodeCharKind::InString {
466                     buffer.push_str(&space_buffer);
467                 }
468                 space_buffer.clear();
469                 buffer.push('\n');
470             }
471             _ if c.is_whitespace() => {
472                 space_buffer.push(c);
473             }
474             _ => {
475                 if !space_buffer.is_empty() {
476                     buffer.push_str(&space_buffer);
477                     space_buffer.clear();
478                 }
479                 buffer.push(c);
480             }
481         }
482     }
483     buffer
484 }
485
486 /// Trims a minimum of leading whitespaces so that the content layout is kept and aligns to indent.
487 pub fn trim_left_preserve_layout(orig: &str, indent: &Indent, config: &Config) -> String {
488     let prefix_whitespace_min = orig
489         .lines()
490         // skip the line with the starting sigil since the leading whitespace is removed
491         // otherwise, the minimum would always be zero
492         .skip(1)
493         .filter(|line| !line.is_empty())
494         .map(|line| {
495             let mut width = 0;
496             for c in line.chars() {
497                 match c {
498                     ' ' => width += 1,
499                     '\t' => width += config.tab_spaces(),
500                     _ => break,
501                 }
502             }
503             width
504         })
505         .min()
506         .unwrap_or(0);
507
508     let indent_str = indent.to_string(config);
509     let mut lines = orig.lines();
510     let first_line = lines.next().unwrap();
511     let rest = lines
512         .map(|line| {
513             if line.is_empty() {
514                 String::from("\n")
515             } else {
516                 format!("\n{}{}", indent_str, &line[prefix_whitespace_min..])
517             }
518         })
519         .collect::<Vec<String>>()
520         .concat();
521     format!("{}{}", first_line, rest)
522 }
523
524 #[test]
525 fn test_remove_trailing_white_spaces() {
526     let s = "    r#\"\n        test\n    \"#";
527     assert_eq!(remove_trailing_white_spaces(&s), s);
528 }