]> git.lizzy.rs Git - rust.git/blob - src/utils.rs
fix: async expression indentation (#3789)
[rust.git] / src / utils.rs
1 use std::borrow::Cow;
2
3 use rustc_target::spec::abi;
4 use syntax::ast::{
5     self, Attribute, CrateSugar, MetaItem, MetaItemKind, NestedMetaItem, NodeId, Path, Visibility,
6     VisibilityKind,
7 };
8 use syntax::ptr;
9 use syntax::source_map::{BytePos, Span, SyntaxContext};
10 use syntax::symbol::{sym, Symbol};
11 use syntax_pos::ExpnId;
12 use unicode_width::UnicodeWidthStr;
13
14 use crate::comment::{filter_normal_code, CharClasses, FullCodeCharKind, LineClasses};
15 use crate::config::{Config, Version};
16 use crate::rewrite::RewriteContext;
17 use crate::shape::{Indent, Shape};
18
19 #[inline]
20 pub(crate) fn depr_skip_annotation() -> Symbol {
21     Symbol::intern("rustfmt_skip")
22 }
23
24 #[inline]
25 pub(crate) fn skip_annotation() -> Symbol {
26     Symbol::intern("rustfmt::skip")
27 }
28
29 pub(crate) fn rewrite_ident<'a>(context: &'a RewriteContext<'_>, ident: ast::Ident) -> &'a str {
30     context.snippet(ident.span)
31 }
32
33 // Computes the length of a string's last line, minus offset.
34 pub(crate) fn extra_offset(text: &str, shape: Shape) -> usize {
35     match text.rfind('\n') {
36         // 1 for newline character
37         Some(idx) => text.len().saturating_sub(idx + 1 + shape.used_width()),
38         None => text.len(),
39     }
40 }
41
42 pub(crate) fn is_same_visibility(a: &Visibility, b: &Visibility) -> bool {
43     match (&a.node, &b.node) {
44         (
45             VisibilityKind::Restricted { path: p, .. },
46             VisibilityKind::Restricted { path: q, .. },
47         ) => p.to_string() == q.to_string(),
48         (VisibilityKind::Public, VisibilityKind::Public)
49         | (VisibilityKind::Inherited, VisibilityKind::Inherited)
50         | (
51             VisibilityKind::Crate(CrateSugar::PubCrate),
52             VisibilityKind::Crate(CrateSugar::PubCrate),
53         )
54         | (
55             VisibilityKind::Crate(CrateSugar::JustCrate),
56             VisibilityKind::Crate(CrateSugar::JustCrate),
57         ) => true,
58         _ => false,
59     }
60 }
61
62 // Uses Cow to avoid allocating in the common cases.
63 pub(crate) fn format_visibility(
64     context: &RewriteContext<'_>,
65     vis: &Visibility,
66 ) -> Cow<'static, str> {
67     match vis.node {
68         VisibilityKind::Public => Cow::from("pub "),
69         VisibilityKind::Inherited => Cow::from(""),
70         VisibilityKind::Crate(CrateSugar::PubCrate) => Cow::from("pub(crate) "),
71         VisibilityKind::Crate(CrateSugar::JustCrate) => Cow::from("crate "),
72         VisibilityKind::Restricted { ref path, .. } => {
73             let Path { ref segments, .. } = **path;
74             let mut segments_iter = segments.iter().map(|seg| rewrite_ident(context, seg.ident));
75             if path.is_global() {
76                 segments_iter
77                     .next()
78                     .expect("Non-global path in pub(restricted)?");
79             }
80             let is_keyword = |s: &str| s == "self" || s == "super";
81             let path = segments_iter.collect::<Vec<_>>().join("::");
82             let in_str = if is_keyword(&path) { "" } else { "in " };
83
84             Cow::from(format!("pub({}{}) ", in_str, path))
85         }
86     }
87 }
88
89 #[inline]
90 pub(crate) fn format_async(is_async: &ast::IsAsync) -> &'static str {
91     match is_async {
92         ast::IsAsync::Async { .. } => "async ",
93         ast::IsAsync::NotAsync => "",
94     }
95 }
96
97 #[inline]
98 pub(crate) fn format_constness(constness: ast::Constness) -> &'static str {
99     match constness {
100         ast::Constness::Const => "const ",
101         ast::Constness::NotConst => "",
102     }
103 }
104
105 #[inline]
106 pub(crate) fn format_defaultness(defaultness: ast::Defaultness) -> &'static str {
107     match defaultness {
108         ast::Defaultness::Default => "default ",
109         ast::Defaultness::Final => "",
110     }
111 }
112
113 #[inline]
114 pub(crate) fn format_unsafety(unsafety: ast::Unsafety) -> &'static str {
115     match unsafety {
116         ast::Unsafety::Unsafe => "unsafe ",
117         ast::Unsafety::Normal => "",
118     }
119 }
120
121 #[inline]
122 pub(crate) fn format_auto(is_auto: ast::IsAuto) -> &'static str {
123     match is_auto {
124         ast::IsAuto::Yes => "auto ",
125         ast::IsAuto::No => "",
126     }
127 }
128
129 #[inline]
130 pub(crate) fn format_mutability(mutability: ast::Mutability) -> &'static str {
131     match mutability {
132         ast::Mutability::Mutable => "mut ",
133         ast::Mutability::Immutable => "",
134     }
135 }
136
137 #[inline]
138 pub(crate) fn format_abi(abi: abi::Abi, explicit_abi: bool, is_mod: bool) -> Cow<'static, str> {
139     if abi == abi::Abi::Rust && !is_mod {
140         Cow::from("")
141     } else if abi == abi::Abi::C && !explicit_abi {
142         Cow::from("extern ")
143     } else {
144         Cow::from(format!("extern {} ", abi))
145     }
146 }
147
148 #[inline]
149 // Transform `Vec<syntax::ptr::P<T>>` into `Vec<&T>`
150 pub(crate) fn ptr_vec_to_ref_vec<T>(vec: &[ptr::P<T>]) -> Vec<&T> {
151     vec.iter().map(|x| &**x).collect::<Vec<_>>()
152 }
153
154 #[inline]
155 pub(crate) fn filter_attributes(
156     attrs: &[ast::Attribute],
157     style: ast::AttrStyle,
158 ) -> Vec<ast::Attribute> {
159     attrs
160         .iter()
161         .filter(|a| a.style == style)
162         .cloned()
163         .collect::<Vec<_>>()
164 }
165
166 #[inline]
167 pub(crate) fn inner_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
168     filter_attributes(attrs, ast::AttrStyle::Inner)
169 }
170
171 #[inline]
172 pub(crate) fn outer_attributes(attrs: &[ast::Attribute]) -> Vec<ast::Attribute> {
173     filter_attributes(attrs, ast::AttrStyle::Outer)
174 }
175
176 #[inline]
177 pub(crate) fn is_single_line(s: &str) -> bool {
178     s.chars().find(|&c| c == '\n').is_none()
179 }
180
181 #[inline]
182 pub(crate) fn first_line_contains_single_line_comment(s: &str) -> bool {
183     s.lines().next().map_or(false, |l| l.contains("//"))
184 }
185
186 #[inline]
187 pub(crate) fn last_line_contains_single_line_comment(s: &str) -> bool {
188     s.lines().last().map_or(false, |l| l.contains("//"))
189 }
190
191 #[inline]
192 pub(crate) fn is_attributes_extendable(attrs_str: &str) -> bool {
193     !attrs_str.contains('\n') && !last_line_contains_single_line_comment(attrs_str)
194 }
195
196 // The width of the first line in s.
197 #[inline]
198 pub(crate) fn first_line_width(s: &str) -> usize {
199     unicode_str_width(s.splitn(2, '\n').next().unwrap_or(""))
200 }
201
202 // The width of the last line in s.
203 #[inline]
204 pub(crate) fn last_line_width(s: &str) -> usize {
205     unicode_str_width(s.rsplitn(2, '\n').next().unwrap_or(""))
206 }
207
208 // The total used width of the last line.
209 #[inline]
210 pub(crate) fn last_line_used_width(s: &str, offset: usize) -> usize {
211     if s.contains('\n') {
212         last_line_width(s)
213     } else {
214         offset + unicode_str_width(s)
215     }
216 }
217
218 #[inline]
219 pub(crate) fn trimmed_last_line_width(s: &str) -> usize {
220     unicode_str_width(match s.rfind('\n') {
221         Some(n) => s[(n + 1)..].trim(),
222         None => s.trim(),
223     })
224 }
225
226 #[inline]
227 pub(crate) fn last_line_extendable(s: &str) -> bool {
228     if s.ends_with("\"#") {
229         return true;
230     }
231     for c in s.chars().rev() {
232         match c {
233             '(' | ')' | ']' | '}' | '?' | '>' => continue,
234             '\n' => break,
235             _ if c.is_whitespace() => continue,
236             _ => return false,
237         }
238     }
239     true
240 }
241
242 #[inline]
243 fn is_skip(meta_item: &MetaItem) -> bool {
244     match meta_item.node {
245         MetaItemKind::Word => {
246             let path_str = meta_item.path.to_string();
247             path_str == skip_annotation().as_str() || path_str == depr_skip_annotation().as_str()
248         }
249         MetaItemKind::List(ref l) => {
250             meta_item.check_name(sym::cfg_attr) && l.len() == 2 && is_skip_nested(&l[1])
251         }
252         _ => false,
253     }
254 }
255
256 #[inline]
257 fn is_skip_nested(meta_item: &NestedMetaItem) -> bool {
258     match meta_item {
259         NestedMetaItem::MetaItem(ref mi) => is_skip(mi),
260         NestedMetaItem::Literal(_) => false,
261     }
262 }
263
264 #[inline]
265 pub(crate) fn contains_skip(attrs: &[Attribute]) -> bool {
266     attrs
267         .iter()
268         .any(|a| a.meta().map_or(false, |a| is_skip(&a)))
269 }
270
271 #[inline]
272 pub(crate) fn semicolon_for_expr(context: &RewriteContext<'_>, expr: &ast::Expr) -> bool {
273     match expr.node {
274         ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
275             context.config.trailing_semicolon()
276         }
277         _ => false,
278     }
279 }
280
281 #[inline]
282 pub(crate) fn semicolon_for_stmt(context: &RewriteContext<'_>, stmt: &ast::Stmt) -> bool {
283     match stmt.node {
284         ast::StmtKind::Semi(ref expr) => match expr.node {
285             ast::ExprKind::While(..) | ast::ExprKind::Loop(..) | ast::ExprKind::ForLoop(..) => {
286                 false
287             }
288             ast::ExprKind::Break(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Ret(..) => {
289                 context.config.trailing_semicolon()
290             }
291             _ => true,
292         },
293         ast::StmtKind::Expr(..) => false,
294         _ => true,
295     }
296 }
297
298 #[inline]
299 pub(crate) fn stmt_expr(stmt: &ast::Stmt) -> Option<&ast::Expr> {
300     match stmt.node {
301         ast::StmtKind::Expr(ref expr) => Some(expr),
302         _ => None,
303     }
304 }
305
306 /// Returns the number of LF and CRLF respectively.
307 pub(crate) fn count_lf_crlf(input: &str) -> (usize, usize) {
308     let mut lf = 0;
309     let mut crlf = 0;
310     let mut is_crlf = false;
311     for c in input.as_bytes() {
312         match c {
313             b'\r' => is_crlf = true,
314             b'\n' if is_crlf => crlf += 1,
315             b'\n' => lf += 1,
316             _ => is_crlf = false,
317         }
318     }
319     (lf, crlf)
320 }
321
322 pub(crate) fn count_newlines(input: &str) -> usize {
323     // Using bytes to omit UTF-8 decoding
324     bytecount::count(input.as_bytes(), b'\n')
325 }
326
327 // For format_missing and last_pos, need to use the source callsite (if applicable).
328 // Required as generated code spans aren't guaranteed to follow on from the last span.
329 macro_rules! source {
330     ($this:ident, $sp:expr) => {
331         $sp.source_callsite()
332     };
333 }
334
335 pub(crate) fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
336     Span::new(lo, hi, SyntaxContext::root())
337 }
338
339 // Returns `true` if the given span does not intersect with file lines.
340 macro_rules! out_of_file_lines_range {
341     ($self:ident, $span:expr) => {
342         !$self.config.file_lines().is_all()
343             && !$self
344                 .config
345                 .file_lines()
346                 .intersects(&$self.source_map.lookup_line_range($span))
347     };
348 }
349
350 macro_rules! skip_out_of_file_lines_range {
351     ($self:ident, $span:expr) => {
352         if out_of_file_lines_range!($self, $span) {
353             return None;
354         }
355     };
356 }
357
358 macro_rules! skip_out_of_file_lines_range_visitor {
359     ($self:ident, $span:expr) => {
360         if out_of_file_lines_range!($self, $span) {
361             $self.push_rewrite($span, None);
362             return;
363         }
364     };
365 }
366
367 // Wraps String in an Option. Returns Some when the string adheres to the
368 // Rewrite constraints defined for the Rewrite trait and None otherwise.
369 pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option<String> {
370     if is_valid_str(&filter_normal_code(&s), max_width, shape) {
371         Some(s)
372     } else {
373         None
374     }
375 }
376
377 fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool {
378     if !snippet.is_empty() {
379         // First line must fits with `shape.width`.
380         if first_line_width(snippet) > shape.width {
381             return false;
382         }
383         // If the snippet does not include newline, we are done.
384         if is_single_line(snippet) {
385             return true;
386         }
387         // The other lines must fit within the maximum width.
388         if snippet
389             .lines()
390             .skip(1)
391             .any(|line| unicode_str_width(line) > max_width)
392         {
393             return false;
394         }
395         // A special check for the last line, since the caller may
396         // place trailing characters on this line.
397         if last_line_width(snippet) > shape.used_width() + shape.width {
398             return false;
399         }
400     }
401     true
402 }
403
404 #[inline]
405 pub(crate) fn colon_spaces(config: &Config) -> &'static str {
406     let before = config.space_before_colon();
407     let after = config.space_after_colon();
408     match (before, after) {
409         (true, true) => " : ",
410         (true, false) => " :",
411         (false, true) => ": ",
412         (false, false) => ":",
413     }
414 }
415
416 #[inline]
417 pub(crate) fn left_most_sub_expr(e: &ast::Expr) -> &ast::Expr {
418     match e.node {
419         ast::ExprKind::Call(ref e, _)
420         | ast::ExprKind::Binary(_, ref e, _)
421         | ast::ExprKind::Cast(ref e, _)
422         | ast::ExprKind::Type(ref e, _)
423         | ast::ExprKind::Assign(ref e, _)
424         | ast::ExprKind::AssignOp(_, ref e, _)
425         | ast::ExprKind::Field(ref e, _)
426         | ast::ExprKind::Index(ref e, _)
427         | ast::ExprKind::Range(Some(ref e), _, _)
428         | ast::ExprKind::Try(ref e) => left_most_sub_expr(e),
429         _ => e,
430     }
431 }
432
433 #[inline]
434 pub(crate) fn starts_with_newline(s: &str) -> bool {
435     s.starts_with('\n') || s.starts_with("\r\n")
436 }
437
438 #[inline]
439 pub(crate) fn first_line_ends_with(s: &str, c: char) -> bool {
440     s.lines().next().map_or(false, |l| l.ends_with(c))
441 }
442
443 // States whether an expression's last line exclusively consists of closing
444 // parens, braces, and brackets in its idiomatic formatting.
445 pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr: &str) -> bool {
446     match expr.node {
447         ast::ExprKind::Mac(..)
448         | ast::ExprKind::Call(..)
449         | ast::ExprKind::MethodCall(..)
450         | ast::ExprKind::Array(..)
451         | ast::ExprKind::Struct(..)
452         | ast::ExprKind::While(..)
453         | ast::ExprKind::If(..)
454         | ast::ExprKind::Block(..)
455         | ast::ExprKind::Async(..)
456         | ast::ExprKind::Loop(..)
457         | ast::ExprKind::ForLoop(..)
458         | ast::ExprKind::TryBlock(..)
459         | ast::ExprKind::Match(..) => repr.contains('\n'),
460         ast::ExprKind::Paren(ref expr)
461         | ast::ExprKind::Binary(_, _, ref expr)
462         | ast::ExprKind::Index(_, ref expr)
463         | ast::ExprKind::Unary(_, ref expr)
464         | ast::ExprKind::Closure(_, _, _, _, ref expr, _)
465         | ast::ExprKind::Try(ref expr)
466         | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr),
467         // This can only be a string lit
468         ast::ExprKind::Lit(_) => {
469             repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces()
470         }
471         ast::ExprKind::AddrOf(..)
472         | ast::ExprKind::Assign(..)
473         | ast::ExprKind::AssignOp(..)
474         | ast::ExprKind::Await(..)
475         | ast::ExprKind::Box(..)
476         | ast::ExprKind::Break(..)
477         | ast::ExprKind::Cast(..)
478         | ast::ExprKind::Continue(..)
479         | ast::ExprKind::Err
480         | ast::ExprKind::Field(..)
481         | ast::ExprKind::InlineAsm(..)
482         | ast::ExprKind::Let(..)
483         | ast::ExprKind::Path(..)
484         | ast::ExprKind::Range(..)
485         | ast::ExprKind::Repeat(..)
486         | ast::ExprKind::Ret(..)
487         | ast::ExprKind::Tup(..)
488         | ast::ExprKind::Type(..)
489         | ast::ExprKind::Yield(None) => false,
490     }
491 }
492
493 /// Removes trailing spaces from the specified snippet. We do not remove spaces
494 /// inside strings or comments.
495 pub(crate) fn remove_trailing_white_spaces(text: &str) -> String {
496     let mut buffer = String::with_capacity(text.len());
497     let mut space_buffer = String::with_capacity(128);
498     for (char_kind, c) in CharClasses::new(text.chars()) {
499         match c {
500             '\n' => {
501                 if char_kind == FullCodeCharKind::InString {
502                     buffer.push_str(&space_buffer);
503                 }
504                 space_buffer.clear();
505                 buffer.push('\n');
506             }
507             _ if c.is_whitespace() => {
508                 space_buffer.push(c);
509             }
510             _ => {
511                 if !space_buffer.is_empty() {
512                     buffer.push_str(&space_buffer);
513                     space_buffer.clear();
514                 }
515                 buffer.push(c);
516             }
517         }
518     }
519     buffer
520 }
521
522 /// Indent each line according to the specified `indent`.
523 /// e.g.
524 ///
525 /// ```rust,compile_fail
526 /// foo!{
527 /// x,
528 /// y,
529 /// foo(
530 ///     a,
531 ///     b,
532 ///     c,
533 /// ),
534 /// }
535 /// ```
536 ///
537 /// will become
538 ///
539 /// ```rust,compile_fail
540 /// foo!{
541 ///     x,
542 ///     y,
543 ///     foo(
544 ///         a,
545 ///         b,
546 ///         c,
547 ///     ),
548 /// }
549 /// ```
550 pub(crate) fn trim_left_preserve_layout(
551     orig: &str,
552     indent: Indent,
553     config: &Config,
554 ) -> Option<String> {
555     let mut lines = LineClasses::new(orig);
556     let first_line = lines.next().map(|(_, s)| s.trim_end().to_owned())?;
557     let mut trimmed_lines = Vec::with_capacity(16);
558
559     let mut veto_trim = false;
560     let min_prefix_space_width = lines
561         .filter_map(|(kind, line)| {
562             let mut trimmed = true;
563             let prefix_space_width = if is_empty_line(&line) {
564                 None
565             } else {
566                 Some(get_prefix_space_width(config, &line))
567             };
568
569             // just InString{Commented} in order to allow the start of a string to be indented
570             let new_veto_trim_value = (kind == FullCodeCharKind::InString
571                 || (config.version() == Version::Two
572                     && kind == FullCodeCharKind::InStringCommented))
573                 && !line.ends_with('\\');
574             let line = if veto_trim || new_veto_trim_value {
575                 veto_trim = new_veto_trim_value;
576                 trimmed = false;
577                 line
578             } else {
579                 line.trim().to_owned()
580             };
581             trimmed_lines.push((trimmed, line, prefix_space_width));
582
583             // Because there is a veto against trimming and indenting lines within a string,
584             // such lines should not be taken into account when computing the minimum.
585             match kind {
586                 FullCodeCharKind::InStringCommented | FullCodeCharKind::EndStringCommented
587                     if config.version() == Version::Two =>
588                 {
589                     None
590                 }
591                 FullCodeCharKind::InString | FullCodeCharKind::EndString => None,
592                 _ => prefix_space_width,
593             }
594         })
595         .min()?;
596
597     Some(
598         first_line
599             + "\n"
600             + &trimmed_lines
601                 .iter()
602                 .map(
603                     |&(trimmed, ref line, prefix_space_width)| match prefix_space_width {
604                         _ if !trimmed => line.to_owned(),
605                         Some(original_indent_width) => {
606                             let new_indent_width = indent.width()
607                                 + original_indent_width.saturating_sub(min_prefix_space_width);
608                             let new_indent = Indent::from_width(config, new_indent_width);
609                             format!("{}{}", new_indent.to_string(config), line)
610                         }
611                         None => String::new(),
612                     },
613                 )
614                 .collect::<Vec<_>>()
615                 .join("\n"),
616     )
617 }
618
619 /// Based on the given line, determine if the next line can be indented or not.
620 /// This allows to preserve the indentation of multi-line literals.
621 pub(crate) fn indent_next_line(kind: FullCodeCharKind, line: &str, config: &Config) -> bool {
622     !(kind.is_string() || (config.version() == Version::Two && kind.is_commented_string()))
623         || line.ends_with('\\')
624 }
625
626 pub(crate) fn is_empty_line(s: &str) -> bool {
627     s.is_empty() || s.chars().all(char::is_whitespace)
628 }
629
630 fn get_prefix_space_width(config: &Config, s: &str) -> usize {
631     let mut width = 0;
632     for c in s.chars() {
633         match c {
634             ' ' => width += 1,
635             '\t' => width += config.tab_spaces(),
636             _ => return width,
637         }
638     }
639     width
640 }
641
642 pub(crate) trait NodeIdExt {
643     fn root() -> Self;
644 }
645
646 impl NodeIdExt for NodeId {
647     fn root() -> NodeId {
648         NodeId::placeholder_from_expn_id(ExpnId::root())
649     }
650 }
651
652 pub(crate) fn unicode_str_width(s: &str) -> usize {
653     s.width()
654 }
655
656 #[cfg(test)]
657 mod test {
658     use super::*;
659
660     #[test]
661     fn test_remove_trailing_white_spaces() {
662         let s = "    r#\"\n        test\n    \"#";
663         assert_eq!(remove_trailing_white_spaces(&s), s);
664     }
665
666     #[test]
667     fn test_trim_left_preserve_layout() {
668         let s = "aaa\n\tbbb\n    ccc";
669         let config = Config::default();
670         let indent = Indent::new(4, 0);
671         assert_eq!(
672             trim_left_preserve_layout(&s, indent, &config),
673             Some("aaa\n    bbb\n    ccc".to_string())
674         );
675     }
676 }