rustfmt_nightly/
visitor.rs

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