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