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