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, 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, None, 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        fk: visit::FnKind<'_>,
381        fd: &ast::FnDecl,
382        s: Span,
383        defaultness: ast::Defaultness,
384        inner_attrs: Option<&[ast::Attribute]>,
385    ) {
386        let indent = self.block_indent;
387        let block;
388        let rewrite = match fk {
389            visit::FnKind::Fn(
390                _,
391                ident,
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(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                        item.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(ref def, ref generics) => {
525                    self.format_missing_with_indent(source!(self, item.span).lo());
526                    self.visit_enum(item.ident, &item.vis, def, generics, item.span);
527                    self.last_pos = source!(self, item.span).hi();
528                }
529                ast::ItemKind::Mod(safety, 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, item.ident, attrs);
532                }
533                ast::ItemKind::MacCall(ref mac) => {
534                    self.visit_mac(mac, Some(item.ident), 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                        ref generics,
548                        ref body,
549                        ..
550                    } = **fn_kind;
551                    if body.is_some() {
552                        let inner_attrs = inner_attributes(&item.attrs);
553                        let fn_ctxt = match sig.header.ext {
554                            ast::Extern::None => visit::FnCtxt::Free,
555                            _ => visit::FnCtxt::Foreign,
556                        };
557                        self.visit_fn(
558                            visit::FnKind::Fn(fn_ctxt, &item.ident, &item.vis, fn_kind),
559                            &sig.decl,
560                            item.span,
561                            defaultness,
562                            Some(&inner_attrs),
563                        )
564                    } else {
565                        let indent = self.block_indent;
566                        let rewrite = self
567                            .rewrite_required_fn(
568                                indent, item.ident, sig, &item.vis, generics, item.span,
569                            )
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(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(ref def) => {
583                    let rewrite = rewrite_macro_def(
584                        &self.get_context(),
585                        self.shape(),
586                        self.block_indent,
587                        def,
588                        item.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        visitor_kind: &ItemVisitorKind<'_>,
609        span: Span,
610    ) {
611        let rewrite = rewrite_type_alias(
612            ty_kind,
613            &self.get_context(),
614            self.block_indent,
615            visitor_kind,
616            span,
617        )
618        .ok();
619        self.push_rewrite(span, rewrite);
620    }
621
622    fn visit_assoc_item(&mut self, visitor_kind: &ItemVisitorKind<'_>) {
623        use ItemVisitorKind::*;
624        // TODO(calebcartwright): Not sure the skip spans are correct
625        let (ai, skip_span, assoc_ctxt) = match visitor_kind {
626            AssocTraitItem(ai) => (*ai, ai.span(), visit::AssocCtxt::Trait),
627            // There is no difference between trait and inherent assoc item formatting
628            AssocImplItem(ai) => (*ai, ai.span, visit::AssocCtxt::Impl { of_trait: false }),
629            _ => unreachable!(),
630        };
631        skip_out_of_file_lines_range_visitor!(self, ai.span);
632
633        if self.visit_attrs(&ai.attrs, ast::AttrStyle::Outer) {
634            self.push_skipped_with_span(ai.attrs.as_slice(), skip_span, skip_span);
635            return;
636        }
637
638        // TODO(calebcartwright): consider enabling box_patterns feature gate
639        match (&ai.kind, visitor_kind) {
640            (ast::AssocItemKind::Const(..), AssocTraitItem(_)) => {
641                self.visit_static(&StaticParts::from_trait_item(ai))
642            }
643            (ast::AssocItemKind::Const(..), AssocImplItem(_)) => {
644                self.visit_static(&StaticParts::from_impl_item(ai))
645            }
646            (ast::AssocItemKind::Fn(ref fn_kind), _) => {
647                let ast::Fn {
648                    defaultness,
649                    ref sig,
650                    ref generics,
651                    ref body,
652                    ..
653                } = **fn_kind;
654                if body.is_some() {
655                    let inner_attrs = inner_attributes(&ai.attrs);
656                    let fn_ctxt = visit::FnCtxt::Assoc(assoc_ctxt);
657                    self.visit_fn(
658                        visit::FnKind::Fn(fn_ctxt, &ai.ident, &ai.vis, fn_kind),
659                        &sig.decl,
660                        ai.span,
661                        defaultness,
662                        Some(&inner_attrs),
663                    );
664                } else {
665                    let indent = self.block_indent;
666                    let rewrite = self
667                        .rewrite_required_fn(indent, ai.ident, sig, &ai.vis, generics, ai.span)
668                        .ok();
669                    self.push_rewrite(ai.span, rewrite);
670                }
671            }
672            (ast::AssocItemKind::Type(ref ty_alias), _) => {
673                self.visit_ty_alias_kind(ty_alias, visitor_kind, ai.span);
674            }
675            (ast::AssocItemKind::MacCall(ref mac), _) => {
676                self.visit_mac(mac, Some(ai.ident), MacroPosition::Item);
677            }
678            _ => unreachable!(),
679        }
680    }
681
682    pub(crate) fn visit_trait_item(&mut self, ti: &ast::AssocItem) {
683        self.visit_assoc_item(&ItemVisitorKind::AssocTraitItem(ti));
684    }
685
686    pub(crate) fn visit_impl_item(&mut self, ii: &ast::AssocItem) {
687        self.visit_assoc_item(&ItemVisitorKind::AssocImplItem(ii));
688    }
689
690    fn visit_mac(&mut self, mac: &ast::MacCall, ident: Option<symbol::Ident>, pos: MacroPosition) {
691        skip_out_of_file_lines_range_visitor!(self, mac.span());
692
693        // 1 = ;
694        let shape = self.shape().saturating_sub_width(1);
695        let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos).ok());
696        // As of v638 of the rustc-ap-* crates, the associated span no longer includes
697        // the trailing semicolon. This determines the correct span to ensure scenarios
698        // with whitespace between the delimiters and trailing semi (i.e. `foo!(abc)     ;`)
699        // are formatted correctly.
700        let (span, rewrite) = match macro_style(mac, &self.get_context()) {
701            Delimiter::Bracket | Delimiter::Parenthesis if MacroPosition::Item == pos => {
702                let search_span = mk_sp(mac.span().hi(), self.snippet_provider.end_pos());
703                let hi = self.snippet_provider.span_before(search_span, ";");
704                let target_span = mk_sp(mac.span().lo(), hi + BytePos(1));
705                let rewrite = rewrite.map(|rw| {
706                    if !rw.ends_with(';') {
707                        format!("{};", rw)
708                    } else {
709                        rw
710                    }
711                });
712                (target_span, rewrite)
713            }
714            _ => (mac.span(), rewrite),
715        };
716
717        self.push_rewrite(span, rewrite);
718    }
719
720    pub(crate) fn push_str(&mut self, s: &str) {
721        self.line_number += count_newlines(s);
722        self.buffer.push_str(s);
723    }
724
725    #[allow(clippy::needless_pass_by_value)]
726    fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
727        if let Some(ref s) = rewrite {
728            self.push_str(s);
729        } else {
730            let snippet = self.snippet(span);
731            self.push_str(snippet.trim());
732        }
733        self.last_pos = source!(self, span).hi();
734    }
735
736    pub(crate) fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
737        self.format_missing_with_indent(source!(self, span).lo());
738        self.push_rewrite_inner(span, rewrite);
739    }
740
741    pub(crate) fn push_skipped_with_span(
742        &mut self,
743        attrs: &[ast::Attribute],
744        item_span: Span,
745        main_span: Span,
746    ) {
747        self.format_missing_with_indent(source!(self, item_span).lo());
748        // do not take into account the lines with attributes as part of the skipped range
749        let attrs_end = attrs
750            .iter()
751            .map(|attr| self.psess.line_of_byte_pos(attr.span.hi()))
752            .max()
753            .unwrap_or(1);
754        let first_line = self.psess.line_of_byte_pos(main_span.lo());
755        // Statement can start after some newlines and/or spaces
756        // or it can be on the same line as the last attribute.
757        // So here we need to take a minimum between the two.
758        let lo = std::cmp::min(attrs_end + 1, first_line);
759        self.push_rewrite_inner(item_span, None);
760        let hi = self.line_number + 1;
761        self.skipped_range.borrow_mut().push((lo, hi));
762    }
763
764    pub(crate) fn from_context(ctx: &'a RewriteContext<'_>) -> FmtVisitor<'a> {
765        let mut visitor = FmtVisitor::from_psess(
766            ctx.psess,
767            ctx.config,
768            ctx.snippet_provider,
769            ctx.report.clone(),
770        );
771        visitor.skip_context.update(ctx.skip_context.clone());
772        visitor.set_parent_context(ctx);
773        visitor
774    }
775
776    pub(crate) fn from_psess(
777        psess: &'a ParseSess,
778        config: &'a Config,
779        snippet_provider: &'a SnippetProvider,
780        report: FormatReport,
781    ) -> FmtVisitor<'a> {
782        let mut skip_context = SkipContext::default();
783        let mut macro_names = Vec::new();
784        for macro_selector in config.skip_macro_invocations().0 {
785            match macro_selector {
786                MacroSelector::Name(name) => macro_names.push(name.to_string()),
787                MacroSelector::All => skip_context.macros.skip_all(),
788            }
789        }
790        skip_context.macros.extend(macro_names);
791        FmtVisitor {
792            parent_context: None,
793            psess,
794            buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
795            last_pos: BytePos(0),
796            block_indent: Indent::empty(),
797            config,
798            is_if_else_block: false,
799            snippet_provider,
800            line_number: 0,
801            skipped_range: Rc::new(RefCell::new(vec![])),
802            is_macro_def: false,
803            macro_rewrite_failure: false,
804            report,
805            skip_context,
806        }
807    }
808
809    pub(crate) fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
810        self.snippet_provider.span_to_snippet(span)
811    }
812
813    pub(crate) fn snippet(&'b self, span: Span) -> &'a str {
814        self.opt_snippet(span).unwrap()
815    }
816
817    // Returns true if we should skip the following item.
818    pub(crate) fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
819        for attr in attrs {
820            if attr.has_name(depr_skip_annotation()) {
821                let file_name = self.psess.span_to_filename(attr.span);
822                self.report.append(
823                    file_name,
824                    vec![FormattingError::from_span(
825                        attr.span,
826                        self.psess,
827                        ErrorKind::DeprecatedAttr,
828                    )],
829                );
830            } else {
831                match &attr.kind {
832                    ast::AttrKind::Normal(ref normal)
833                        if self.is_unknown_rustfmt_attr(&normal.item.path.segments) =>
834                    {
835                        let file_name = self.psess.span_to_filename(attr.span);
836                        self.report.append(
837                            file_name,
838                            vec![FormattingError::from_span(
839                                attr.span,
840                                self.psess,
841                                ErrorKind::BadAttr,
842                            )],
843                        );
844                    }
845                    _ => (),
846                }
847            }
848        }
849        if contains_skip(attrs) {
850            return true;
851        }
852
853        let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
854        if attrs.is_empty() {
855            return false;
856        }
857
858        let rewrite = attrs.rewrite(&self.get_context(), self.shape());
859        let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
860        self.push_rewrite(span, rewrite);
861
862        false
863    }
864
865    fn is_unknown_rustfmt_attr(&self, segments: &[ast::PathSegment]) -> bool {
866        if segments[0].ident.to_string() != "rustfmt" {
867            return false;
868        }
869        !is_skip_attr(segments)
870    }
871
872    fn walk_mod_items(&mut self, items: &[rustc_ast::ptr::P<ast::Item>]) {
873        self.visit_items_with_reordering(&ptr_vec_to_ref_vec(items));
874    }
875
876    fn walk_stmts(&mut self, stmts: &[Stmt<'_>], include_current_empty_semi: bool) {
877        if stmts.is_empty() {
878            return;
879        }
880
881        // Extract leading `use ...;`.
882        let items: Vec<_> = stmts
883            .iter()
884            .take_while(|stmt| stmt.to_item().map_or(false, is_use_item))
885            .filter_map(|stmt| stmt.to_item())
886            .collect();
887
888        if items.is_empty() {
889            self.visit_stmt(&stmts[0], include_current_empty_semi);
890
891            // FIXME(calebcartwright 2021-01-03) - This exists strictly to maintain legacy
892            // formatting where rustfmt would preserve redundant semicolons on Items in a
893            // statement position.
894            //
895            // Starting in rustc-ap-* v692 (~2020-12-01) the rustc parser now parses this as
896            // two separate statements (Item and Empty kinds), whereas before it was parsed as
897            // a single statement with the statement's span including the redundant semicolon.
898            //
899            // rustfmt typically tosses unnecessary/redundant semicolons, and eventually we
900            // should toss these as well, but doing so at this time would
901            // break the Stability Guarantee
902            // N.B. This could be updated to utilize the version gates.
903            let include_next_empty = if stmts.len() > 1 {
904                matches!(
905                    (&stmts[0].as_ast_node().kind, &stmts[1].as_ast_node().kind),
906                    (ast::StmtKind::Item(_), ast::StmtKind::Empty)
907                )
908            } else {
909                false
910            };
911
912            self.walk_stmts(&stmts[1..], include_next_empty);
913        } else {
914            self.visit_items_with_reordering(&items);
915            self.walk_stmts(&stmts[items.len()..], false);
916        }
917    }
918
919    fn walk_block_stmts(&mut self, b: &ast::Block) {
920        self.walk_stmts(&Stmt::from_ast_nodes(b.stmts.iter()), false)
921    }
922
923    fn format_mod(
924        &mut self,
925        mod_kind: &ast::ModKind,
926        safety: ast::Safety,
927        vis: &ast::Visibility,
928        s: Span,
929        ident: symbol::Ident,
930        attrs: &[ast::Attribute],
931    ) {
932        let vis_str = utils::format_visibility(&self.get_context(), vis);
933        self.push_str(&*vis_str);
934        self.push_str(format_safety(safety));
935        self.push_str("mod ");
936        // Calling `to_owned()` to work around borrow checker.
937        let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
938        self.push_str(&ident_str);
939
940        if let ast::ModKind::Loaded(ref items, ast::Inline::Yes, ref spans, _) = mod_kind {
941            let ast::ModSpans {
942                inner_span,
943                inject_use_span: _,
944            } = *spans;
945            match self.config.brace_style() {
946                BraceStyle::AlwaysNextLine => {
947                    let indent_str = self.block_indent.to_string_with_newline(self.config);
948                    self.push_str(&indent_str);
949                    self.push_str("{");
950                }
951                _ => self.push_str(" {"),
952            }
953            // Hackery to account for the closing }.
954            let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
955            let body_snippet =
956                self.snippet(mk_sp(mod_lo, source!(self, inner_span).hi() - BytePos(1)));
957            let body_snippet = body_snippet.trim();
958            if body_snippet.is_empty() {
959                self.push_str("}");
960            } else {
961                self.last_pos = mod_lo;
962                self.block_indent = self.block_indent.block_indent(self.config);
963                self.visit_attrs(attrs, ast::AttrStyle::Inner);
964                self.walk_mod_items(items);
965                let missing_span = self.next_span(inner_span.hi() - BytePos(1));
966                self.close_block(missing_span, false);
967            }
968            self.last_pos = source!(self, inner_span).hi();
969        } else {
970            self.push_str(";");
971            self.last_pos = source!(self, s).hi();
972        }
973    }
974
975    pub(crate) fn format_separate_mod(&mut self, m: &Module<'_>, end_pos: BytePos) {
976        self.block_indent = Indent::empty();
977        let skipped = self.visit_attrs(m.attrs(), ast::AttrStyle::Inner);
978        assert!(
979            !skipped,
980            "Skipping module must be handled before reaching this line."
981        );
982        self.walk_mod_items(&m.items);
983        self.format_missing_with_indent(end_pos);
984    }
985
986    pub(crate) fn skip_empty_lines(&mut self, end_pos: BytePos) {
987        while let Some(pos) = self
988            .snippet_provider
989            .opt_span_after(self.next_span(end_pos), "\n")
990        {
991            if let Some(snippet) = self.opt_snippet(self.next_span(pos)) {
992                if snippet.trim().is_empty() {
993                    self.last_pos = pos;
994                } else {
995                    return;
996                }
997            }
998        }
999    }
1000
1001    pub(crate) fn with_context<F>(&mut self, f: F) -> Option<String>
1002    where
1003        F: Fn(&RewriteContext<'_>) -> Option<String>,
1004    {
1005        let context = self.get_context();
1006        let result = f(&context);
1007
1008        self.macro_rewrite_failure |= context.macro_rewrite_failure.get();
1009        result
1010    }
1011
1012    pub(crate) fn get_context(&self) -> RewriteContext<'_> {
1013        RewriteContext {
1014            psess: self.psess,
1015            config: self.config,
1016            inside_macro: Rc::new(Cell::new(false)),
1017            use_block: Cell::new(false),
1018            is_if_else_block: Cell::new(false),
1019            force_one_line_chain: Cell::new(false),
1020            snippet_provider: self.snippet_provider,
1021            macro_rewrite_failure: Cell::new(false),
1022            is_macro_def: self.is_macro_def,
1023            report: self.report.clone(),
1024            skip_context: self.skip_context.clone(),
1025            skipped_range: self.skipped_range.clone(),
1026        }
1027    }
1028}