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