Skip to main content

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