]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
06f1ca2d8d8eb99cf85752176cde64fca8863622
[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,
18     NodeId, Path, Visibility, VisibilityKind,
19 };
20 use syntax::ptr;
21 use syntax::source_map::{BytePos, Span, NO_EXPANSION};
22 use syntax_pos::Mark;
23 use unicode_width::UnicodeWidthStr;
24
25 use crate::comment::{filter_normal_code, CharClasses, FullCodeCharKind, LineClasses};
26 use crate::config::{Config, Version};
27 use crate::rewrite::RewriteContext;
28 use crate::shape::{Indent, Shape};
29
30 pub const DEPR_SKIP_ANNOTATION: &str = "rustfmt_skip";
31 pub const SKIP_ANNOTATION: &str = "rustfmt::skip";
32
33 pub fn rewrite_ident<'a>(context: &'a RewriteContext, ident: ast::Ident) -> &'a str {
34     context.snippet(ident.span)
35 }
36
37 // Computes the length of a string's last line, minus offset.
38 pub fn extra_offset(text: &str, shape: Shape) -> usize {
39     match text.rfind('\n') {
40         // 1 for newline character
41         Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()),
42         None => text.len(),
43     }
44 }
45
46 pub fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
47     match (&a.node, &b.node) {
48         (
49             VisibilityKind::Restricted { path: p, .. },
50             VisibilityKind::Restricted { path: q, .. },
51         ) => p.to_string() == q.to_string(),
52         (VisibilityKind::Public, VisibilityKind::Public)
53         | (VisibilityKind::Inherited, VisibilityKind::Inherited)
54         | (
55             VisibilityKind::Crate(CrateSugar::PubCrate),
56             VisibilityKind::Crate(CrateSugar::PubCrate),
57         )
58         | (
59             VisibilityKind::Crate(CrateSugar::JustCrate),
60             VisibilityKind::Crate(CrateSugar::JustCrate),
61         ) => true,
62         _ => false,
63     }
64 }
65
66 // Uses Cow to avoid allocating in the common cases.
67 pub fn format_visibility(context: &RewriteContext, vis: &Visibility) -> Cow<'static, str> {
68     match vis.node {
69         VisibilityKind::Public => Cow::from("pub "),
70         VisibilityKind::Inherited => Cow::from(""),
71         VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
72         VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
73         VisibilityKind::Restricted { ref path, .. } => {
74             let Path { ref segments, .. } = **path;
75             let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
76             if path.is_global() {
77                 segments_iter
78                     .next()
79                     .expect("Non-global path in pub(restricted)?");
80             }
81             let is_keyword = |s: &str| s == "self" || s == "super";
82             let path = segments_iter.collect::<Vec<_>>().join("::");
83             let in_str = if is_keyword(&path) { "" } else { "in " };
84
85             Cow::from(format!("pub({}{}) ", in_str, path))
86         }
87     }
88 }
89
90 #[inline]
91 pub fn format_async(is_async: ast::IsAsync) -> &'static str {
92     match is_async {
93         ast::IsAsync::Async { .. } => "async ",
94         ast::IsAsync::NotAsync => "",
95     }
96 }
97
98 #[inline]
99 pub fn format_constness(constness: ast::Constness) -> &'static str {
100     match constness {
101         ast::Constness::Const => "const ",
102         ast::Constness::NotConst => "",
103     }
104 }
105
106 #[inline]
107 pub fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
108     match defaultness {
109         ast::Defaultness::Default => "default ",
110         ast::Defaultness::Final => "",
111     }
112 }
113
114 #[inline]
115 pub fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
116     match unsafety {
117         ast::Unsafety::Unsafe => "unsafe ",
118         ast::Unsafety::Normal => "",
119     }
120 }
121
122 #[inline]
123 pub fn format_auto(is_auto: ast::IsAuto) -> &'static str {
124     match is_auto {
125         ast::IsAuto::Yes => "auto ",
126         ast::IsAuto::No => "",
127     }
128 }
129
130 #[inline]
131 pub fn format_mutability(mutability: ast::Mutability) -> &'static str {
132     match mutability {
133         ast::Mutability::Mutable => "mut ",
134         ast::Mutability::Immutable => "",
135     }
136 }
137
138 #[inline]
139 pub fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
140     if abi == abi::Abi::Rust && !is_mod {
141         Cow::from("")
142     } else if abi == abi::Abi::C && !explicit_abi {
143         Cow::from("extern ")
144     } else {
145         Cow::from(format!("extern {} ", abi))
146     }
147 }
148
149 #[inline]
150 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
151 pub fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
152     vec.iter().map(|x| &**x).collect::<Vec<_>>()
153 }
154
155 #[inline]
156 pub fn filter_attributes(attrs: &[ast::Attribute], style: ast::AttrStyle) -> Vec<ast::Attribute> {
157     attrs
158         .iter()
159         .filter(|a| a.style == style)
160         .cloned()
161         .collect::<Vec<_>>()
162 }
163
164 #[inline]
165 pub fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
166     filter_attributes(attrs, ast::AttrStyle::Inner)
167 }
168
169 #[inline]
170 pub fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
171     filter_attributes(attrs, ast::AttrStyle::Outer)
172 }
173
174 #[inline]
175 pub fn is_single_line(s: &str) -> bool {
176     s.chars().find(|&c| c == '\n').is_none()
177 }
178
179 #[inline]
180 pub fn first_line_contains_single_line_comment(s: &str) -> bool {
181     s.lines().next().map_or(false, |l| l.contains("//"))
182 }
183
184 #[inline]
185 pub fn last_line_contains_single_line_comment(s: &str) -> bool {
186     s.lines().last().map_or(false, |l| l.contains("//"))
187 }
188
189 #[inline]
190 pub fn is_attributes_extendable(attrs_str: &str) -> bool {
191     !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
192 }
193
194 // The width of the first line in s.
195 #[inline]
196 pub fn first_line_width(s: &str) -> usize {
197     unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
198 }
199
200 // The width of the last line in s.
201 #[inline]
202 pub fn last_line_width(s: &str) -> usize {
203     unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
204 }
205
206 // The total used width of the last line.
207 #[inline]
208 pub fn last_line_used_width(s: &str, offset: usize) -> usize {
209     if s.contains('\n') {
210         last_line_width(s)
211     } else {
212         offset + unicode_str_width(s)
213     }
214 }
215
216 #[inline]
217 pub fn trimmed_last_line_width(s: &str) -> usize {
218     unicode_str_width(match s.rfind('\n') {
219         Some(n) => s[(n + 1)..].trim(),
220         None => s.trim(),
221     })
222 }
223
224 #[inline]
225 pub fn last_line_extendable(s: &str) -> bool {
226     if s.ends_with("\"#") {
227         return true;
228     }
229     for c in s.chars().rev() {
230         match c {
231             '(' | ')' | ']' | '}' | '?' | '>' => continue,
232             '\n' => break,
233             _ if c.is_whitespace() => continue,
234             _ => return false,
235         }
236     }
237     true
238 }
239
240 #[inline]
241 fn is_skip(meta_item: &MetaItem) -> bool {
242     match meta_item.node {
243         MetaItemKind::Word => {
244             let path_str = meta_item.ident.to_string();
245             path_str == SKIP_ANNOTATION || path_str == DEPR_SKIP_ANNOTATION
246         }
247         MetaItemKind::List(ref l) => {
248             meta_item.name() == "cfg_attr" && l.len() == 2 && is_skip_nested(&l[1])
249         }
250         _ => false,
251     }
252 }
253
254 #[inline]
255 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
256     match meta_item.node {
257         NestedMetaItemKind::MetaItem(ref mi) => is_skip(mi),
258         NestedMetaItemKind::Literal(_) => false,
259     }
260 }
261
262 #[inline]
263 pub fn contains_skip(attrs: &[Attribute]) -> bool {
264     attrs
265         .iter()
266         .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
267 }
268
269 #[inline]
270 pub fn semicolon_for_expr(context: &RewriteContext, expr: &ast::Expr) -> bool {
271     match expr.node {
272         ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
273             context.config.trailing_semicolon()
274         }
275         _ => false,
276     }
277 }
278
279 #[inline]
280 pub fn semicolon_for_stmt(context: &RewriteContext, stmt: &ast::Stmt) -> bool {
281     match stmt.node {
282         ast::StmtKind::Semi(ref expr) => match expr.node {
283             ast::ExprKind::While(..)
284             | ast::ExprKind::WhileLet(..)
285             | ast::ExprKind::Loop(..)
286             | ast::ExprKind::ForLoop(..) => false,
287             ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
288                 context.config.trailing_semicolon()
289             }
290             _ => true,
291         },
292         ast::StmtKind::Expr(..) => false,
293         _ => true,
294     }
295 }
296
297 #[inline]
298 pub fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
299     match stmt.node {
300         ast::StmtKind::Expr(ref expr) => Some(expr),
301         _ => None,
302     }
303 }
304
305 #[inline]
306 pub fn count_newlines(input: &str) -> usize {
307     // Using bytes to omit UTF-8 decoding
308     bytecount::count(input.as_bytes(), b'\n')
309 }
310
311 // For format_missing and last_pos, need to use the source callsite (if applicable).
312 // Required as generated code spans aren't guaranteed to follow on from the last span.
313 macro_rules! source {
314     ($this:ident, $sp:expr) => {
315         $sp.source_callsite()
316     };
317 }
318
319 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
320     Span::new(lo, hi, NO_EXPANSION)
321 }
322
323 // Return true if the given span does not intersect with file lines.
324 macro_rules! out_of_file_lines_range {
325     ($self:ident, $span:expr) => {
326         !$self.config.file_lines().is_all()
327             && !$self
328                 .config
329                 .file_lines()
330                 .intersects(&$self.source_map.lookup_line_range($span))
331     };
332 }
333
334 macro_rules! skip_out_of_file_lines_range {
335     ($self:ident, $span:expr) => {
336         if out_of_file_lines_range!($self, $span) {
337             return None;
338         }
339     };
340 }
341
342 macro_rules! skip_out_of_file_lines_range_visitor {
343     ($self:ident, $span:expr) => {
344         if out_of_file_lines_range!($self, $span) {
345             $self.push_rewrite($span, None);
346             return;
347         }
348     };
349 }
350
351 // Wraps String in an Option. Returns Some when the string adheres to the
352 // Rewrite constraints defined for the Rewrite trait and None otherwise.
353 pub fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
354     if is_valid_str(&filter_normal_code(&s), max_width, shape) {
355         Some(s)
356     } else {
357         None
358     }
359 }
360
361 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
362     if !snippet.is_empty() {
363         // First line must fits with `shape.width`.
364         if first_line_width(snippet) > shape.width {
365             return false;
366         }
367         // If the snippet does not include newline, we are done.
368         if is_single_line(snippet) {
369             return true;
370         }
371         // The other lines must fit within the maximum width.
372         if snippet
373             .lines()
374             .skip(1)
375             .any(|line| unicode_str_width(line) > max_width)
376         {
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 /// Indent each line according to the specified `indent`.
487 /// e.g.
488 ///
489 /// ```rust,ignore
490 /// foo!{
491 /// x,
492 /// y,
493 /// foo(
494 ///     a,
495 ///     b,
496 ///     c,
497 /// ),
498 /// }
499 /// ```
500 ///
501 /// will become
502 ///
503 /// ```rust,ignore
504 /// foo!{
505 ///     x,
506 ///     y,
507 ///     foo(
508 ///         a,
509 ///         b,
510 ///         c,
511 ///     ),
512 /// }
513 /// ```
514 pub fn trim_left_preserve_layout(orig: &str, indent: Indent, config: &Config) -> Option<String> {
515     let mut lines = LineClasses::new(orig);
516     let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
517     let mut trimmed_lines = Vec::with_capacity(16);
518
519     let mut veto_trim = false;
520     let min_prefix_space_width = lines
521         .filter_map(|(kind, line)| {
522             let mut trimmed = true;
523             let prefix_space_width = if is_empty_line(&line) {
524                 None
525             } else {
526                 Some(get_prefix_space_width(config, &line))
527             };
528
529             let new_veto_trim_value = (kind.is_string()
530                 || (config.version() == Version::Two && kind.is_commented_string()))
531                 && !line.ends_with('\\');
532             let line = if veto_trim || new_veto_trim_value {
533                 veto_trim = new_veto_trim_value;
534                 trimmed = false;
535                 line
536             } else {
537                 line.trim().to_owned()
538             };
539             trimmed_lines.push((trimmed, line, prefix_space_width));
540
541             // Because there is a veto against trimming and indenting lines within a string,
542             // such lines should not be taken into account when computing the minimum.
543             match kind {
544                 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
545                     if config.version() == Version::Two =>
546                 {
547                     None
548                 }
549                 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
550                 _ => prefix_space_width,
551             }
552         })
553         .min()?;
554
555     Some(
556         first_line
557             + "\n"
558             + &trimmed_lines
559                 .iter()
560                 .map(
561                     |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
562                         _ if !trimmed => line.to_owned(),
563                         Some(original_indent_width) => {
564                             let new_indent_width = indent.width()
565                                 + original_indent_width.saturating_sub(min_prefix_space_width);
566                             let new_indent = Indent::from_width(config, new_indent_width);
567                             format!("{}{}", new_indent.to_string(config), line)
568                         }
569                         None => String::new(),
570                     },
571                 )
572                 .collect::<Vec<_>>()
573                 .join("\n"),
574     )
575 }
576
577 pub fn is_empty_line(s: &str) -> bool {
578     s.is_empty() || s.chars().all(char::is_whitespace)
579 }
580
581 fn get_prefix_space_width(config: &Config, s: &str) -> usize {
582     let mut width = 0;
583     for c in s.chars() {
584         match c {
585             ' ' => width += 1,
586             '\t' => width += config.tab_spaces(),
587             _ => return width,
588         }
589     }
590     width
591 }
592
593 pub(crate) trait NodeIdExt {
594     fn root() -> Self;
595 }
596
597 impl NodeIdExt for NodeId {
598     fn root() -> NodeId {
599         NodeId::placeholder_from_mark(Mark::root())
600     }
601 }
602
603 pub(crate) fn unicode_str_width(s: &str) -> usize {
604     s.width()
605 }
606
607 #[cfg(test)]
608 mod test {
609     use super::*;
610
611     #[test]
612     fn test_remove_trailing_white_spaces() {
613         let s = "    r#\"\n        test\n    \"#";
614         assert_eq!(remove_trailing_white_spaces(&s), s);
615     }
616
617     #[test]
618     fn test_trim_left_preserve_layout() {
619         let s = "aaa\n\tbbb\n    ccc";
620         let config = Config::default();
621         let indent = Indent::new(4, 0);
622         assert_eq!(
623             trim_left_preserve_layout(&s, indent, &config),
624             Some("aaa\n    bbb\n    ccc".to_string())
625         );
626     }
627 }