]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/visitor.rs
more clippy fixes
[rust.git] / src / tools / rustfmt / src / visitor.rs
1 use std::cell::{Cell, RefCell};
2 use std::rc::Rc;
3
4 use rustc_ast::{ast, token::DelimToken, visit, AstLike};
5 use rustc_data_structures::sync::Lrc;
6 use rustc_span::{symbol, BytePos, Pos, Span};
7
8 use crate::attr::*;
9 use crate::comment::{contains_comment, rewrite_comment, CodeCharKind, CommentCodeSlices};
10 use crate::config::Version;
11 use crate::config::{BraceStyle, Config};
12 use crate::coverage::transform_missing_snippet;
13 use crate::items::{
14     format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item, rewrite_extern_crate,
15     rewrite_impl_type, rewrite_opaque_type, rewrite_type, FnBraceStyle, FnSig, StaticParts,
16     StructParts,
17 };
18 use crate::macros::{macro_style, rewrite_macro, rewrite_macro_def, MacroPosition};
19 use crate::modules::Module;
20 use crate::rewrite::{Rewrite, RewriteContext};
21 use crate::shape::{Indent, Shape};
22 use crate::skip::{is_skip_attr, SkipContext};
23 use crate::source_map::{LineRangeUtils, SpanUtils};
24 use crate::spanned::Spanned;
25 use crate::stmt::Stmt;
26 use crate::syntux::session::ParseSess;
27 use crate::utils::{
28     self, contains_skip, count_newlines, depr_skip_annotation, format_unsafety, inner_attributes,
29     last_line_width, mk_sp, ptr_vec_to_ref_vec, rewrite_ident, starts_with_newline, stmt_expr,
30 };
31 use crate::{ErrorKind, FormatReport, FormattingError};
32
33 /// Creates a string slice corresponding to the specified span.
34 pub(crate) struct SnippetProvider {
35     /// A pointer to the content of the file we are formatting.
36     big_snippet: Lrc<String>,
37     /// A position of the start of `big_snippet`, used as an offset.
38     start_pos: usize,
39     /// An end position of the file that this snippet lives.
40     end_pos: usize,
41 }
42
43 impl SnippetProvider {
44     pub(crate) fn span_to_snippet(&self, span: Span) -> Option<&str> {
45         let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
46         let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
47         Some(&self.big_snippet[start_index..end_index])
48     }
49
50     pub(crate) fn new(start_pos: BytePos, end_pos: BytePos, big_snippet: Lrc<String>) -> Self {
51         let start_pos = start_pos.to_usize();
52         let end_pos = end_pos.to_usize();
53         SnippetProvider {
54             big_snippet,
55             start_pos,
56             end_pos,
57         }
58     }
59
60     pub(crate) fn entire_snippet(&self) -> &str {
61         self.big_snippet.as_str()
62     }
63
64     pub(crate) fn start_pos(&self) -> BytePos {
65         BytePos::from_usize(self.start_pos)
66     }
67
68     pub(crate) fn end_pos(&self) -> BytePos {
69         BytePos::from_usize(self.end_pos)
70     }
71 }
72
73 pub(crate) struct FmtVisitor<'a> {
74     parent_context: Option<&'a RewriteContext<'a>>,
75     pub(crate) parse_sess: &'a ParseSess,
76     pub(crate) buffer: String,
77     pub(crate) last_pos: BytePos,
78     // FIXME: use an RAII util or closure for indenting
79     pub(crate) block_indent: Indent,
80     pub(crate) config: &'a Config,
81     pub(crate) is_if_else_block: bool,
82     pub(crate) snippet_provider: &'a SnippetProvider,
83     pub(crate) line_number: usize,
84     /// List of 1-based line ranges which were annotated with skip
85     /// Both bounds are inclusifs.
86     pub(crate) skipped_range: Rc<RefCell<Vec<(usize, usize)>>>,
87     pub(crate) macro_rewrite_failure: bool,
88     pub(crate) report: FormatReport,
89     pub(crate) skip_context: SkipContext,
90     pub(crate) is_macro_def: bool,
91 }
92
93 impl<'a> Drop for FmtVisitor<'a> {
94     fn drop(&mut self) {
95         if let Some(ctx) = self.parent_context {
96             if self.macro_rewrite_failure {
97                 ctx.macro_rewrite_failure.replace(true);
98             }
99         }
100     }
101 }
102
103 impl<'b, 'a: 'b> FmtVisitor<'a> {
104     fn set_parent_context(&mut self, context: &'a RewriteContext<'_>) {
105         self.parent_context = Some(context);
106     }
107
108     pub(crate) fn shape(&self) -> Shape {
109         Shape::indented(self.block_indent, self.config)
110     }
111
112     fn next_span(&self, hi: BytePos) -> Span {
113         mk_sp(self.last_pos, hi)
114     }
115
116     fn visit_stmt(&mut self, stmt: &Stmt<'_>, include_empty_semi: bool) {
117         debug!(
118             "visit_stmt: {}",
119             self.parse_sess.span_to_debug_info(stmt.span())
120         );
121
122         if stmt.is_empty() {
123             // If the statement is empty, just skip over it. Before that, make sure any comment
124             // snippet preceding the semicolon is picked up.
125             let snippet = self.snippet(mk_sp(self.last_pos, stmt.span().lo()));
126             let original_starts_with_newline = snippet
127                 .find(|c| c != ' ')
128                 .map_or(false, |i| starts_with_newline(&snippet[i..]));
129             let snippet = snippet.trim();
130             if !snippet.is_empty() {
131                 // FIXME(calebcartwright 2021-01-03) - This exists strictly to maintain legacy
132                 // formatting where rustfmt would preserve redundant semicolons on Items in a
133                 // statement position.
134                 // See comment within `walk_stmts` for more info
135                 if include_empty_semi {
136                     self.format_missing(stmt.span().hi());
137                 } else {
138                     if original_starts_with_newline {
139                         self.push_str("\n");
140                     }
141
142                     self.push_str(&self.block_indent.to_string(self.config));
143                     self.push_str(snippet);
144                 }
145             } else if include_empty_semi {
146                 self.push_str(";");
147             }
148             self.last_pos = stmt.span().hi();
149             return;
150         }
151
152         match stmt.as_ast_node().kind {
153             ast::StmtKind::Item(ref item) => {
154                 self.visit_item(item);
155                 self.last_pos = stmt.span().hi();
156             }
157             ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
158                 let attrs = get_attrs_from_stmt(stmt.as_ast_node());
159                 if contains_skip(attrs) {
160                     self.push_skipped_with_span(
161                         attrs,
162                         stmt.span(),
163                         get_span_without_attrs(stmt.as_ast_node()),
164                     );
165                 } else {
166                     let shape = self.shape();
167                     let rewrite = self.with_context(|ctx| stmt.rewrite(&ctx, shape));
168                     self.push_rewrite(stmt.span(), rewrite)
169                 }
170             }
171             ast::StmtKind::MacCall(ref mac_stmt) => {
172                 if self.visit_attrs(&mac_stmt.attrs, ast::AttrStyle::Outer) {
173                     self.push_skipped_with_span(
174                         &mac_stmt.attrs,
175                         stmt.span(),
176                         get_span_without_attrs(stmt.as_ast_node()),
177                     );
178                 } else {
179                     self.visit_mac(&mac_stmt.mac, None, MacroPosition::Statement);
180                 }
181                 self.format_missing(stmt.span().hi());
182             }
183             ast::StmtKind::Empty => (),
184         }
185     }
186
187     /// Remove spaces between the opening brace and the first statement or the inner attribute
188     /// of the block.
189     fn trim_spaces_after_opening_brace(
190         &mut self,
191         b: &ast::Block,
192         inner_attrs: Option<&[ast::Attribute]>,
193     ) {
194         if let Some(first_stmt) = b.stmts.first() {
195             let hi = inner_attrs
196                 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
197                 .unwrap_or_else(|| first_stmt.span().lo());
198             let missing_span = self.next_span(hi);
199             let snippet = self.snippet(missing_span);
200             let len = CommentCodeSlices::new(snippet)
201                 .next()
202                 .and_then(|(kind, _, s)| {
203                     if kind == CodeCharKind::Normal {
204                         s.rfind('\n')
205                     } else {
206                         None
207                     }
208                 });
209             if let Some(len) = len {
210                 self.last_pos = self.last_pos + BytePos::from_usize(len);
211             }
212         }
213     }
214
215     pub(crate) fn visit_block(
216         &mut self,
217         b: &ast::Block,
218         inner_attrs: Option<&[ast::Attribute]>,
219         has_braces: bool,
220     ) {
221         debug!(
222             "visit_block: {}",
223             self.parse_sess.span_to_debug_info(b.span),
224         );
225
226         // Check if this block has braces.
227         let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
228
229         self.last_pos = self.last_pos + brace_compensation;
230         self.block_indent = self.block_indent.block_indent(self.config);
231         self.push_str("{");
232         self.trim_spaces_after_opening_brace(b, inner_attrs);
233
234         // Format inner attributes if available.
235         if let Some(attrs) = inner_attrs {
236             self.visit_attrs(attrs, ast::AttrStyle::Inner);
237         }
238
239         self.walk_block_stmts(b);
240
241         if !b.stmts.is_empty() {
242             if let Some(expr) = stmt_expr(&b.stmts[b.stmts.len() - 1]) {
243                 if utils::semicolon_for_expr(&self.get_context(), expr) {
244                     self.push_str(";");
245                 }
246             }
247         }
248
249         let rest_span = self.next_span(b.span.hi());
250         if out_of_file_lines_range!(self, rest_span) {
251             self.push_str(self.snippet(rest_span));
252             self.block_indent = self.block_indent.block_unindent(self.config);
253         } else {
254             // Ignore the closing brace.
255             let missing_span = self.next_span(b.span.hi() - brace_compensation);
256             self.close_block(missing_span, self.unindent_comment_on_closing_brace(b));
257         }
258         self.last_pos = source!(self, b.span).hi();
259     }
260
261     fn close_block(&mut self, span: Span, unindent_comment: bool) {
262         let config = self.config;
263
264         let mut last_hi = span.lo();
265         let mut unindented = false;
266         let mut prev_ends_with_newline = false;
267         let mut extra_newline = false;
268
269         let skip_normal = |s: &str| {
270             let trimmed = s.trim();
271             trimmed.is_empty() || trimmed.chars().all(|c| c == ';')
272         };
273
274         let comment_snippet = self.snippet(span);
275
276         let align_to_right = if unindent_comment && contains_comment(&comment_snippet) {
277             let first_lines = comment_snippet.splitn(2, '/').next().unwrap_or("");
278             last_line_width(first_lines) > last_line_width(&comment_snippet)
279         } else {
280             false
281         };
282
283         for (kind, offset, sub_slice) in CommentCodeSlices::new(comment_snippet) {
284             let sub_slice = transform_missing_snippet(config, sub_slice);
285
286             debug!("close_block: {:?} {:?} {:?}", kind, offset, sub_slice);
287
288             match kind {
289                 CodeCharKind::Comment => {
290                     if !unindented && unindent_comment && !align_to_right {
291                         unindented = true;
292                         self.block_indent = self.block_indent.block_unindent(config);
293                     }
294                     let span_in_between = mk_sp(last_hi, span.lo() + BytePos::from_usize(offset));
295                     let snippet_in_between = self.snippet(span_in_between);
296                     let mut comment_on_same_line = !snippet_in_between.contains('\n');
297
298                     let mut comment_shape =
299                         Shape::indented(self.block_indent, config).comment(config);
300                     if self.config.version() == Version::Two && comment_on_same_line {
301                         self.push_str(" ");
302                         // put the first line of the comment on the same line as the
303                         // block's last line
304                         match sub_slice.find('\n') {
305                             None => {
306                                 self.push_str(&sub_slice);
307                             }
308                             Some(offset) if offset + 1 == sub_slice.len() => {
309                                 self.push_str(&sub_slice[..offset]);
310                             }
311                             Some(offset) => {
312                                 let first_line = &sub_slice[..offset];
313                                 self.push_str(first_line);
314                                 self.push_str(&self.block_indent.to_string_with_newline(config));
315
316                                 // put the other lines below it, shaping it as needed
317                                 let other_lines = &sub_slice[offset + 1..];
318                                 let comment_str =
319                                     rewrite_comment(other_lines, false, comment_shape, config);
320                                 match comment_str {
321                                     Some(ref s) => self.push_str(s),
322                                     None => self.push_str(other_lines),
323                                 }
324                             }
325                         }
326                     } else {
327                         if comment_on_same_line {
328                             // 1 = a space before `//`
329                             let offset_len = 1 + last_line_width(&self.buffer)
330                                 .saturating_sub(self.block_indent.width());
331                             match comment_shape
332                                 .visual_indent(offset_len)
333                                 .sub_width(offset_len)
334                             {
335                                 Some(shp) => comment_shape = shp,
336                                 None => comment_on_same_line = false,
337                             }
338                         };
339
340                         if comment_on_same_line {
341                             self.push_str(" ");
342                         } else {
343                             if count_newlines(snippet_in_between) >= 2 || extra_newline {
344                                 self.push_str("\n");
345                             }
346                             self.push_str(&self.block_indent.to_string_with_newline(config));
347                         }
348
349                         let comment_str = rewrite_comment(&sub_slice, false, comment_shape, config);
350                         match comment_str {
351                             Some(ref s) => self.push_str(s),
352                             None => self.push_str(&sub_slice),
353                         }
354                     }
355                 }
356                 CodeCharKind::Normal if skip_normal(&sub_slice) => {
357                     extra_newline = prev_ends_with_newline && sub_slice.contains('\n');
358                     continue;
359                 }
360                 CodeCharKind::Normal => {
361                     self.push_str(&self.block_indent.to_string_with_newline(config));
362                     self.push_str(sub_slice.trim());
363                 }
364             }
365             prev_ends_with_newline = sub_slice.ends_with('\n');
366             extra_newline = false;
367             last_hi = span.lo() + BytePos::from_usize(offset + sub_slice.len());
368         }
369         if unindented {
370             self.block_indent = self.block_indent.block_indent(self.config);
371         }
372         self.block_indent = self.block_indent.block_unindent(self.config);
373         self.push_str(&self.block_indent.to_string_with_newline(config));
374         self.push_str("}");
375     }
376
377     fn unindent_comment_on_closing_brace(&self, b: &ast::Block) -> bool {
378         self.is_if_else_block && !b.stmts.is_empty()
379     }
380
381     // Note that this only gets called for function definitions. Required methods
382     // on traits do not get handled here.
383     pub(crate) fn visit_fn(
384         &mut self,
385         fk: visit::FnKind<'_>,
386         generics: &ast::Generics,
387         fd: &ast::FnDecl,
388         s: Span,
389         defaultness: ast::Defaultness,
390         inner_attrs: Option<&[ast::Attribute]>,
391     ) {
392         let indent = self.block_indent;
393         let block;
394         let rewrite = match fk {
395             visit::FnKind::Fn(_, ident, _, _, Some(ref b)) => {
396                 block = b;
397                 self.rewrite_fn_before_block(
398                     indent,
399                     ident,
400                     &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
401                     mk_sp(s.lo(), b.span.lo()),
402                 )
403             }
404             _ => unreachable!(),
405         };
406
407         if let Some((fn_str, fn_brace_style)) = rewrite {
408             self.format_missing_with_indent(source!(self, s).lo());
409
410             if let Some(rw) = self.single_line_fn(&fn_str, block, inner_attrs) {
411                 self.push_str(&rw);
412                 self.last_pos = s.hi();
413                 return;
414             }
415
416             self.push_str(&fn_str);
417             match fn_brace_style {
418                 FnBraceStyle::SameLine => self.push_str(" "),
419                 FnBraceStyle::NextLine => {
420                     self.push_str(&self.block_indent.to_string_with_newline(self.config))
421                 }
422                 _ => unreachable!(),
423             }
424             self.last_pos = source!(self, block.span).lo();
425         } else {
426             self.format_missing(source!(self, block.span).lo());
427         }
428
429         self.visit_block(block, inner_attrs, true)
430     }
431
432     pub(crate) fn visit_item(&mut self, item: &ast::Item) {
433         skip_out_of_file_lines_range_visitor!(self, item.span);
434
435         // This is where we bail out if there is a skip attribute. This is only
436         // complex in the module case. It is complex because the module could be
437         // in a separate file and there might be attributes in both files, but
438         // the AST lumps them all together.
439         let filtered_attrs;
440         let mut attrs = &item.attrs;
441         let skip_context_saved = self.skip_context.clone();
442         self.skip_context.update_with_attrs(&attrs);
443
444         let should_visit_node_again = match item.kind {
445             // For use/extern crate items, skip rewriting attributes but check for a skip attribute.
446             ast::ItemKind::Use(..) | ast::ItemKind::ExternCrate(_) => {
447                 if contains_skip(attrs) {
448                     self.push_skipped_with_span(attrs.as_slice(), item.span(), item.span());
449                     false
450                 } else {
451                     true
452                 }
453             }
454             // Module is inline, in this case we treat it like any other item.
455             _ if !is_mod_decl(item) => {
456                 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
457                     self.push_skipped_with_span(item.attrs.as_slice(), item.span(), item.span());
458                     false
459                 } else {
460                     true
461                 }
462             }
463             // Module is not inline, but should be skipped.
464             ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => false,
465             // Module is not inline and should not be skipped. We want
466             // to process only the attributes in the current file.
467             ast::ItemKind::Mod(..) => {
468                 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
469                 // Assert because if we should skip it should be caught by
470                 // the above case.
471                 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
472                 attrs = &filtered_attrs;
473                 true
474             }
475             _ => {
476                 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
477                     self.push_skipped_with_span(item.attrs.as_slice(), item.span(), item.span());
478                     false
479                 } else {
480                     true
481                 }
482             }
483         };
484
485         // TODO(calebcartwright): consider enabling box_patterns feature gate
486         if should_visit_node_again {
487             match item.kind {
488                 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
489                 ast::ItemKind::Impl { .. } => {
490                     let block_indent = self.block_indent;
491                     let rw = self.with_context(|ctx| format_impl(&ctx, item, block_indent));
492                     self.push_rewrite(item.span, rw);
493                 }
494                 ast::ItemKind::Trait(..) => {
495                     let block_indent = self.block_indent;
496                     let rw = self.with_context(|ctx| format_trait(&ctx, item, block_indent));
497                     self.push_rewrite(item.span, rw);
498                 }
499                 ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => {
500                     let shape = Shape::indented(self.block_indent, self.config);
501                     let rw = format_trait_alias(
502                         &self.get_context(),
503                         item.ident,
504                         &item.vis,
505                         generics,
506                         generic_bounds,
507                         shape,
508                     );
509                     self.push_rewrite(item.span, rw);
510                 }
511                 ast::ItemKind::ExternCrate(_) => {
512                     let rw = rewrite_extern_crate(&self.get_context(), item, self.shape());
513                     let span = if attrs.is_empty() {
514                         item.span
515                     } else {
516                         mk_sp(attrs[0].span.lo(), item.span.hi())
517                     };
518                     self.push_rewrite(span, rw);
519                 }
520                 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
521                     self.visit_struct(&StructParts::from_item(item));
522                 }
523                 ast::ItemKind::Enum(ref def, ref generics) => {
524                     self.format_missing_with_indent(source!(self, item.span).lo());
525                     self.visit_enum(item.ident, &item.vis, def, generics, item.span);
526                     self.last_pos = source!(self, item.span).hi();
527                 }
528                 ast::ItemKind::Mod(unsafety, ref mod_kind) => {
529                     self.format_missing_with_indent(source!(self, item.span).lo());
530                     self.format_mod(mod_kind, unsafety, &item.vis, item.span, item.ident, attrs);
531                 }
532                 ast::ItemKind::MacCall(ref mac) => {
533                     self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
534                 }
535                 ast::ItemKind::ForeignMod(ref foreign_mod) => {
536                     self.format_missing_with_indent(source!(self, item.span).lo());
537                     self.format_foreign_mod(foreign_mod, item.span);
538                 }
539                 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
540                     self.visit_static(&StaticParts::from_item(item));
541                 }
542                 ast::ItemKind::Fn(ref fn_kind) => {
543                     let ast::FnKind(defaultness, ref fn_signature, ref generics, ref block) =
544                         **fn_kind;
545                     if let Some(ref body) = block {
546                         let inner_attrs = inner_attributes(&item.attrs);
547                         let fn_ctxt = match fn_signature.header.ext {
548                             ast::Extern::None => visit::FnCtxt::Free,
549                             _ => visit::FnCtxt::Foreign,
550                         };
551                         self.visit_fn(
552                             visit::FnKind::Fn(
553                                 fn_ctxt,
554                                 item.ident,
555                                 &fn_signature,
556                                 &item.vis,
557                                 Some(body),
558                             ),
559                             generics,
560                             &fn_signature.decl,
561                             item.span,
562                             defaultness,
563                             Some(&inner_attrs),
564                         )
565                     } else {
566                         let indent = self.block_indent;
567                         let rewrite = self.rewrite_required_fn(
568                             indent,
569                             item.ident,
570                             &fn_signature,
571                             &item.vis,
572                             generics,
573                             item.span,
574                         );
575                         self.push_rewrite(item.span, rewrite);
576                     }
577                 }
578                 ast::ItemKind::TyAlias(ref alias_kind) => {
579                     let ast::TyAliasKind(_, ref generics, ref generic_bounds, ref ty) =
580                         **alias_kind;
581                     match ty {
582                         Some(ty) => {
583                             let rewrite = rewrite_type(
584                                 &self.get_context(),
585                                 self.block_indent,
586                                 item.ident,
587                                 &item.vis,
588                                 generics,
589                                 Some(generic_bounds),
590                                 Some(&*ty),
591                                 item.span,
592                             );
593                             self.push_rewrite(item.span, rewrite);
594                         }
595                         None => {
596                             let rewrite = rewrite_opaque_type(
597                                 &self.get_context(),
598                                 self.block_indent,
599                                 item.ident,
600                                 generic_bounds,
601                                 generics,
602                                 &item.vis,
603                                 item.span,
604                             );
605                             self.push_rewrite(item.span, rewrite);
606                         }
607                     }
608                 }
609                 ast::ItemKind::GlobalAsm(..) => {
610                     let snippet = Some(self.snippet(item.span).to_owned());
611                     self.push_rewrite(item.span, snippet);
612                 }
613                 ast::ItemKind::MacroDef(ref def) => {
614                     let rewrite = rewrite_macro_def(
615                         &self.get_context(),
616                         self.shape(),
617                         self.block_indent,
618                         def,
619                         item.ident,
620                         &item.vis,
621                         item.span,
622                     );
623                     self.push_rewrite(item.span, rewrite);
624                 }
625             };
626         }
627         self.skip_context = skip_context_saved;
628     }
629
630     pub(crate) fn visit_trait_item(&mut self, ti: &ast::AssocItem) {
631         skip_out_of_file_lines_range_visitor!(self, ti.span);
632
633         if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
634             self.push_skipped_with_span(ti.attrs.as_slice(), ti.span(), ti.span());
635             return;
636         }
637
638         // TODO(calebcartwright): consider enabling box_patterns feature gate
639         match ti.kind {
640             ast::AssocItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
641             ast::AssocItemKind::Fn(ref fn_kind) => {
642                 let ast::FnKind(defaultness, ref sig, ref generics, ref block) = **fn_kind;
643                 if let Some(ref body) = block {
644                     let inner_attrs = inner_attributes(&ti.attrs);
645                     let fn_ctxt = visit::FnCtxt::Assoc(visit::AssocCtxt::Trait);
646                     self.visit_fn(
647                         visit::FnKind::Fn(fn_ctxt, ti.ident, sig, &ti.vis, Some(body)),
648                         generics,
649                         &sig.decl,
650                         ti.span,
651                         defaultness,
652                         Some(&inner_attrs),
653                     );
654                 } else {
655                     let indent = self.block_indent;
656                     let rewrite =
657                         self.rewrite_required_fn(indent, ti.ident, sig, &ti.vis, generics, ti.span);
658                     self.push_rewrite(ti.span, rewrite);
659                 }
660             }
661             ast::AssocItemKind::TyAlias(ref ty_alias_kind) => {
662                 let ast::TyAliasKind(_, ref generics, ref generic_bounds, ref type_default) =
663                     **ty_alias_kind;
664                 let rewrite = rewrite_type(
665                     &self.get_context(),
666                     self.block_indent,
667                     ti.ident,
668                     &ti.vis,
669                     generics,
670                     Some(generic_bounds),
671                     type_default.as_ref(),
672                     ti.span,
673                 );
674                 self.push_rewrite(ti.span, rewrite);
675             }
676             ast::AssocItemKind::MacCall(ref mac) => {
677                 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
678             }
679         }
680     }
681
682     pub(crate) fn visit_impl_item(&mut self, ii: &ast::AssocItem) {
683         skip_out_of_file_lines_range_visitor!(self, ii.span);
684
685         if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
686             self.push_skipped_with_span(ii.attrs.as_slice(), ii.span, ii.span);
687             return;
688         }
689
690         match ii.kind {
691             ast::AssocItemKind::Fn(ref fn_kind) => {
692                 let ast::FnKind(defaultness, ref sig, ref generics, ref block) = **fn_kind;
693                 if let Some(ref body) = block {
694                     let inner_attrs = inner_attributes(&ii.attrs);
695                     let fn_ctxt = visit::FnCtxt::Assoc(visit::AssocCtxt::Impl);
696                     self.visit_fn(
697                         visit::FnKind::Fn(fn_ctxt, ii.ident, sig, &ii.vis, Some(body)),
698                         generics,
699                         &sig.decl,
700                         ii.span,
701                         defaultness,
702                         Some(&inner_attrs),
703                     );
704                 } else {
705                     let indent = self.block_indent;
706                     let rewrite =
707                         self.rewrite_required_fn(indent, ii.ident, sig, &ii.vis, generics, ii.span);
708                     self.push_rewrite(ii.span, rewrite);
709                 }
710             }
711             ast::AssocItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
712             ast::AssocItemKind::TyAlias(ref ty_alias_kind) => {
713                 let ast::TyAliasKind(defaultness, ref generics, _, ref ty) = **ty_alias_kind;
714                 self.push_rewrite(
715                     ii.span,
716                     rewrite_impl_type(
717                         ii.ident,
718                         &ii.vis,
719                         defaultness,
720                         ty.as_ref(),
721                         &generics,
722                         &self.get_context(),
723                         self.block_indent,
724                         ii.span,
725                     ),
726                 );
727             }
728             ast::AssocItemKind::MacCall(ref mac) => {
729                 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
730             }
731         }
732     }
733
734     fn visit_mac(&mut self, mac: &ast::MacCall, ident: Option<symbol::Ident>, pos: MacroPosition) {
735         skip_out_of_file_lines_range_visitor!(self, mac.span());
736
737         // 1 = ;
738         let shape = self.shape().saturating_sub_width(1);
739         let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos));
740         // As of v638 of the rustc-ap-* crates, the associated span no longer includes
741         // the trailing semicolon. This determines the correct span to ensure scenarios
742         // with whitespace between the delimiters and trailing semi (i.e. `foo!(abc)     ;`)
743         // are formatted correctly.
744         let (span, rewrite) = match macro_style(mac, &self.get_context()) {
745             DelimToken::Bracket | DelimToken::Paren if MacroPosition::Item == pos => {
746                 let search_span = mk_sp(mac.span().hi(), self.snippet_provider.end_pos());
747                 let hi = self.snippet_provider.span_before(search_span, ";");
748                 let target_span = mk_sp(mac.span().lo(), hi + BytePos(1));
749                 let rewrite = rewrite.map(|rw| {
750                     if !rw.ends_with(';') {
751                         format!("{};", rw)
752                     } else {
753                         rw
754                     }
755                 });
756                 (target_span, rewrite)
757             }
758             _ => (mac.span(), rewrite),
759         };
760
761         self.push_rewrite(span, rewrite);
762     }
763
764     pub(crate) fn push_str(&mut self, s: &str) {
765         self.line_number += count_newlines(s);
766         self.buffer.push_str(s);
767     }
768
769     #[allow(clippy::needless_pass_by_value)]
770     fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
771         if let Some(ref s) = rewrite {
772             self.push_str(s);
773         } else {
774             let snippet = self.snippet(span);
775             self.push_str(snippet.trim());
776         }
777         self.last_pos = source!(self, span).hi();
778     }
779
780     pub(crate) fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
781         self.format_missing_with_indent(source!(self, span).lo());
782         self.push_rewrite_inner(span, rewrite);
783     }
784
785     pub(crate) fn push_skipped_with_span(
786         &mut self,
787         attrs: &[ast::Attribute],
788         item_span: Span,
789         main_span: Span,
790     ) {
791         self.format_missing_with_indent(source!(self, item_span).lo());
792         // do not take into account the lines with attributes as part of the skipped range
793         let attrs_end = attrs
794             .iter()
795             .map(|attr| self.parse_sess.line_of_byte_pos(attr.span.hi()))
796             .max()
797             .unwrap_or(1);
798         let first_line = self.parse_sess.line_of_byte_pos(main_span.lo());
799         // Statement can start after some newlines and/or spaces
800         // or it can be on the same line as the last attribute.
801         // So here we need to take a minimum between the two.
802         let lo = std::cmp::min(attrs_end + 1, first_line);
803         self.push_rewrite_inner(item_span, None);
804         let hi = self.line_number + 1;
805         self.skipped_range.borrow_mut().push((lo, hi));
806     }
807
808     pub(crate) fn from_context(ctx: &'a RewriteContext<'_>) -> FmtVisitor<'a> {
809         let mut visitor = FmtVisitor::from_parse_sess(
810             ctx.parse_sess,
811             ctx.config,
812             ctx.snippet_provider,
813             ctx.report.clone(),
814         );
815         visitor.skip_context.update(ctx.skip_context.clone());
816         visitor.set_parent_context(ctx);
817         visitor
818     }
819
820     pub(crate) fn from_parse_sess(
821         parse_session: &'a ParseSess,
822         config: &'a Config,
823         snippet_provider: &'a SnippetProvider,
824         report: FormatReport,
825     ) -> FmtVisitor<'a> {
826         FmtVisitor {
827             parent_context: None,
828             parse_sess: parse_session,
829             buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
830             last_pos: BytePos(0),
831             block_indent: Indent::empty(),
832             config,
833             is_if_else_block: false,
834             snippet_provider,
835             line_number: 0,
836             skipped_range: Rc::new(RefCell::new(vec![])),
837             is_macro_def: false,
838             macro_rewrite_failure: false,
839             report,
840             skip_context: Default::default(),
841         }
842     }
843
844     pub(crate) fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
845         self.snippet_provider.span_to_snippet(span)
846     }
847
848     pub(crate) fn snippet(&'b self, span: Span) -> &'a str {
849         self.opt_snippet(span).unwrap()
850     }
851
852     // Returns true if we should skip the following item.
853     pub(crate) fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
854         for attr in attrs {
855             if attr.has_name(depr_skip_annotation()) {
856                 let file_name = self.parse_sess.span_to_filename(attr.span);
857                 self.report.append(
858                     file_name,
859                     vec![FormattingError::from_span(
860                         attr.span,
861                         self.parse_sess,
862                         ErrorKind::DeprecatedAttr,
863                     )],
864                 );
865             } else {
866                 match &attr.kind {
867                     ast::AttrKind::Normal(ref attribute_item, _)
868                         if self.is_unknown_rustfmt_attr(&attribute_item.path.segments) =>
869                     {
870                         let file_name = self.parse_sess.span_to_filename(attr.span);
871                         self.report.append(
872                             file_name,
873                             vec![FormattingError::from_span(
874                                 attr.span,
875                                 self.parse_sess,
876                                 ErrorKind::BadAttr,
877                             )],
878                         );
879                     }
880                     _ => (),
881                 }
882             }
883         }
884         if contains_skip(attrs) {
885             return true;
886         }
887
888         let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
889         if attrs.is_empty() {
890             return false;
891         }
892
893         let rewrite = attrs.rewrite(&self.get_context(), self.shape());
894         let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
895         self.push_rewrite(span, rewrite);
896
897         false
898     }
899
900     fn is_unknown_rustfmt_attr(&self, segments: &[ast::PathSegment]) -> bool {
901         if segments[0].ident.to_string() != "rustfmt" {
902             return false;
903         }
904         !is_skip_attr(segments)
905     }
906
907     fn walk_mod_items(&mut self, items: &[rustc_ast::ptr::P<ast::Item>]) {
908         self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&items));
909     }
910
911     fn walk_stmts(&mut self, stmts: &[Stmt<'_>], include_current_empty_semi: bool) {
912         if stmts.is_empty() {
913             return;
914         }
915
916         // Extract leading `use ...;`.
917         let items: Vec<_> = stmts
918             .iter()
919             .take_while(|stmt| stmt.to_item().map_or(false, is_use_item))
920             .filter_map(|stmt| stmt.to_item())
921             .collect();
922
923         if items.is_empty() {
924             self.visit_stmt(&stmts[0], include_current_empty_semi);
925
926             // FIXME(calebcartwright 2021-01-03) - This exists strictly to maintain legacy
927             // formatting where rustfmt would preserve redundant semicolons on Items in a
928             // statement position.
929             //
930             // Starting in rustc-ap-* v692 (~2020-12-01) the rustc parser now parses this as
931             // two separate statements (Item and Empty kinds), whereas before it was parsed as
932             // a single statement with the statement's span including the redundant semicolon.
933             //
934             // rustfmt typically tosses unnecessary/redundant semicolons, and eventually we
935             // should toss these as well, but doing so at this time would
936             // break the Stability Guarantee
937             // N.B. This could be updated to utilize the version gates.
938             let include_next_empty = if stmts.len() > 1 {
939                 matches!(
940                     (&stmts[0].as_ast_node().kind, &stmts[1].as_ast_node().kind),
941                     (ast::StmtKind::Item(_), ast::StmtKind::Empty)
942                 )
943             } else {
944                 false
945             };
946
947             self.walk_stmts(&stmts[1..], include_next_empty);
948         } else {
949             self.visit_items_with_reordering(&items);
950             self.walk_stmts(&stmts[items.len()..], false);
951         }
952     }
953
954     fn walk_block_stmts(&mut self, b: &ast::Block) {
955         self.walk_stmts(&Stmt::from_ast_nodes(b.stmts.iter()), false)
956     }
957
958     fn format_mod(
959         &mut self,
960         mod_kind: &ast::ModKind,
961         unsafety: ast::Unsafe,
962         vis: &ast::Visibility,
963         s: Span,
964         ident: symbol::Ident,
965         attrs: &[ast::Attribute],
966     ) {
967         let vis_str = utils::format_visibility(&self.get_context(), vis);
968         self.push_str(&*vis_str);
969         self.push_str(format_unsafety(unsafety));
970         self.push_str("mod ");
971         // Calling `to_owned()` to work around borrow checker.
972         let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
973         self.push_str(&ident_str);
974
975         if let ast::ModKind::Loaded(ref items, ast::Inline::Yes, inner_span) = mod_kind {
976             match self.config.brace_style() {
977                 BraceStyle::AlwaysNextLine => {
978                     let indent_str = self.block_indent.to_string_with_newline(self.config);
979                     self.push_str(&indent_str);
980                     self.push_str("{");
981                 }
982                 _ => self.push_str(" {"),
983             }
984             // Hackery to account for the closing }.
985             let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
986             let body_snippet =
987                 self.snippet(mk_sp(mod_lo, source!(self, inner_span).hi() - BytePos(1)));
988             let body_snippet = body_snippet.trim();
989             if body_snippet.is_empty() {
990                 self.push_str("}");
991             } else {
992                 self.last_pos = mod_lo;
993                 self.block_indent = self.block_indent.block_indent(self.config);
994                 self.visit_attrs(attrs, ast::AttrStyle::Inner);
995                 self.walk_mod_items(items);
996                 let missing_span = self.next_span(inner_span.hi() - BytePos(1));
997                 self.close_block(missing_span, false);
998             }
999             self.last_pos = source!(self, inner_span).hi();
1000         } else {
1001             self.push_str(";");
1002             self.last_pos = source!(self, s).hi();
1003         }
1004     }
1005
1006     pub(crate) fn format_separate_mod(&mut self, m: &Module<'_>, end_pos: BytePos) {
1007         self.block_indent = Indent::empty();
1008         if self.visit_attrs(m.attrs(), ast::AttrStyle::Inner) {
1009             self.push_skipped_with_span(m.attrs(), m.span, m.span);
1010         } else {
1011             self.walk_mod_items(&m.items);
1012             self.format_missing_with_indent(end_pos);
1013         }
1014     }
1015
1016     pub(crate) fn skip_empty_lines(&mut self, end_pos: BytePos) {
1017         while let Some(pos) = self
1018             .snippet_provider
1019             .opt_span_after(self.next_span(end_pos), "\n")
1020         {
1021             if let Some(snippet) = self.opt_snippet(self.next_span(pos)) {
1022                 if snippet.trim().is_empty() {
1023                     self.last_pos = pos;
1024                 } else {
1025                     return;
1026                 }
1027             }
1028         }
1029     }
1030
1031     pub(crate) fn with_context<F>(&mut self, f: F) -> Option<String>
1032     where
1033         F: Fn(&RewriteContext<'_>) -> Option<String>,
1034     {
1035         let context = self.get_context();
1036         let result = f(&context);
1037
1038         self.macro_rewrite_failure |= context.macro_rewrite_failure.get();
1039         result
1040     }
1041
1042     pub(crate) fn get_context(&self) -> RewriteContext<'_> {
1043         RewriteContext {
1044             parse_sess: self.parse_sess,
1045             config: self.config,
1046             inside_macro: Rc::new(Cell::new(false)),
1047             use_block: Cell::new(false),
1048             is_if_else_block: Cell::new(false),
1049             force_one_line_chain: Cell::new(false),
1050             snippet_provider: self.snippet_provider,
1051             macro_rewrite_failure: Cell::new(false),
1052             is_macro_def: self.is_macro_def,
1053             report: self.report.clone(),
1054             skip_context: self.skip_context.clone(),
1055             skipped_range: self.skipped_range.clone(),
1056         }
1057     }
1058 }