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
34pub(crate) struct SnippetProvider {
36 big_snippet: Arc<String>,
38 start_pos: usize,
40 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 _ 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 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => false,
475 ast::ItemKind::Mod(..) => {
478 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
479 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 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 self.push_rewrite(item.span, None)
633 }
634 ast::ItemKind::TestBinderConstraints(..) => self.push_rewrite(item.span, None),
635 };
636 }
637 self.skip_context = skip_context_saved;
638 }
639
640 fn visit_ty_alias_kind(
641 &mut self,
642 ty_kind: &ast::TyAlias,
643 vis: &ast::Visibility,
644 visitor_kind: ItemVisitorKind,
645 span: Span,
646 ) {
647 let rewrite = rewrite_type_alias(
648 ty_kind,
649 vis,
650 &self.get_context(),
651 self.block_indent,
652 visitor_kind,
653 span,
654 )
655 .ok();
656 self.push_rewrite(span, rewrite);
657 }
658
659 fn visit_assoc_item(&mut self, ai: &ast::AssocItem, visitor_kind: ItemVisitorKind) {
660 use ItemVisitorKind::*;
661 let assoc_ctxt = match visitor_kind {
662 AssocTraitItem => visit::AssocCtxt::Trait,
663 AssocImplItem => visit::AssocCtxt::Impl { of_trait: false },
665 _ => unreachable!(),
666 };
667 let skip_span = ai.span;
669 skip_out_of_file_lines_range_visitor!(self, ai.span);
670
671 if self.visit_attrs(&ai.attrs, ast::AttrStyle::Outer) {
672 self.push_skipped_with_span(ai.attrs.as_slice(), skip_span, skip_span);
673 return;
674 }
675
676 match (&ai.kind, assoc_ctxt) {
678 (ast::AssocItemKind::Const(c), visit::AssocCtxt::Trait) => {
679 self.visit_static(&StaticParts::from_trait_item(ai, c.ident))
680 }
681 (ast::AssocItemKind::Const(c), visit::AssocCtxt::Impl { .. }) => {
682 self.visit_static(&StaticParts::from_impl_item(ai, c.ident))
683 }
684 (ast::AssocItemKind::Fn(ref fn_kind), _) => {
685 let ast::Fn {
686 defaultness,
687 ref sig,
688 ident,
689 ref generics,
690 ref body,
691 ..
692 } = **fn_kind;
693 if body.is_some() {
694 let inner_attrs = inner_attributes(&ai.attrs);
695 let fn_ctxt = visit::FnCtxt::Assoc(assoc_ctxt);
696 self.visit_fn(
697 ident,
698 visit::FnKind::Fn(fn_ctxt, &ai.vis, fn_kind),
699 &sig.decl,
700 ai.span,
701 defaultness,
702 Some(&inner_attrs),
703 );
704 } else {
705 let indent = self.block_indent;
706 let rewrite = self
707 .rewrite_required_fn(
708 indent,
709 fn_kind.ident,
710 sig,
711 &ai.vis,
712 generics,
713 defaultness,
714 ai.span,
715 )
716 .ok();
717 self.push_rewrite(ai.span, rewrite);
718 }
719 }
720 (ast::AssocItemKind::Type(ref ty_alias), _) => {
721 self.visit_ty_alias_kind(ty_alias, &ai.vis, visitor_kind, ai.span);
722 }
723 (ast::AssocItemKind::MacCall(ref mac), _) => {
724 self.visit_mac(mac, MacroPosition::Item);
725 }
726 (ast::AssocItemKind::Delegation(_) | ast::AssocItemKind::DelegationMac(_), _) => {
727 self.push_rewrite(ai.span, None);
730 }
731 }
732 }
733
734 pub(crate) fn visit_trait_item(&mut self, ti: &ast::AssocItem) {
735 self.visit_assoc_item(ti, ItemVisitorKind::AssocTraitItem);
736 }
737
738 pub(crate) fn visit_impl_item(&mut self, ii: &ast::AssocItem) {
739 self.visit_assoc_item(ii, ItemVisitorKind::AssocImplItem);
740 }
741
742 fn visit_mac(&mut self, mac: &ast::MacCall, pos: MacroPosition) {
743 skip_out_of_file_lines_range_visitor!(self, mac.span());
744
745 let shape = self.shape().saturating_sub_width(1);
747 let rewrite = self.with_context(|ctx| rewrite_macro(mac, ctx, shape, pos).ok());
748 let (span, rewrite) = match macro_style(mac, &self.get_context()) {
753 Delimiter::Bracket | Delimiter::Parenthesis if MacroPosition::Item == pos => {
754 let search_span = mk_sp(mac.span().hi(), self.snippet_provider.end_pos());
755 let hi = self.snippet_provider.span_before(search_span, ";");
756 let target_span = mk_sp(mac.span().lo(), hi + BytePos(1));
757 let rewrite = rewrite.map(|rw| {
758 if !rw.ends_with(';') {
759 format!("{};", rw)
760 } else {
761 rw
762 }
763 });
764 (target_span, rewrite)
765 }
766 _ => (mac.span(), rewrite),
767 };
768
769 self.push_rewrite(span, rewrite);
770 }
771
772 pub(crate) fn push_str(&mut self, s: &str) {
773 self.line_number += count_newlines(s);
774 self.buffer.push_str(s);
775 }
776
777 #[allow(clippy::needless_pass_by_value)]
778 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
779 if let Some(ref s) = rewrite {
780 self.push_str(s);
781 } else {
782 let snippet = self.snippet(span);
783 self.push_str(snippet.trim());
784 }
785 self.last_pos = source!(self, span).hi();
786 }
787
788 pub(crate) fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
789 self.format_missing_with_indent(source!(self, span).lo());
790 self.push_rewrite_inner(span, rewrite);
791 }
792
793 pub(crate) fn push_skipped_with_span(
794 &mut self,
795 attrs: &[ast::Attribute],
796 item_span: Span,
797 main_span: Span,
798 ) {
799 self.format_missing_with_indent(source!(self, item_span).lo());
800 let attrs_end = attrs
802 .iter()
803 .map(|attr| self.psess.line_of_byte_pos(attr.span.hi()))
804 .max()
805 .unwrap_or(1);
806 let first_line = self.psess.line_of_byte_pos(main_span.lo());
807 let lo = std::cmp::min(attrs_end + 1, first_line);
811 self.push_rewrite_inner(item_span, None);
812 let hi = self.line_number + 1;
813 self.skipped_range.borrow_mut().push((lo, hi));
814 }
815
816 pub(crate) fn from_context(ctx: &'a RewriteContext<'_>) -> FmtVisitor<'a> {
817 let mut visitor = FmtVisitor::from_psess(
818 ctx.psess,
819 ctx.config,
820 ctx.snippet_provider,
821 ctx.report.clone(),
822 );
823 visitor.skip_context.update(ctx.skip_context.clone());
824 visitor.set_parent_context(ctx);
825 visitor
826 }
827
828 pub(crate) fn from_psess(
829 psess: &'a ParseSess,
830 config: &'a Config,
831 snippet_provider: &'a SnippetProvider,
832 report: FormatReport,
833 ) -> FmtVisitor<'a> {
834 let mut skip_context = SkipContext::default();
835 let mut macro_names = Vec::new();
836 for macro_selector in config.skip_macro_invocations().0 {
837 match macro_selector {
838 MacroSelector::Name(name) => macro_names.push(name.to_string()),
839 MacroSelector::All => skip_context.macros.skip_all(),
840 }
841 }
842 skip_context.macros.extend(macro_names);
843 FmtVisitor {
844 parent_context: None,
845 psess,
846 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
847 last_pos: BytePos(0),
848 block_indent: Indent::empty(),
849 config,
850 is_if_else_block: false,
851 is_loop_block: false,
852 snippet_provider,
853 line_number: 0,
854 skipped_range: Rc::new(RefCell::new(vec![])),
855 is_macro_def: false,
856 macro_rewrite_failure: false,
857 report,
858 skip_context,
859 }
860 }
861
862 pub(crate) fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
863 self.snippet_provider.span_to_snippet(span)
864 }
865
866 pub(crate) fn snippet(&'b self, span: Span) -> &'a str {
867 self.opt_snippet(span).unwrap()
868 }
869
870 pub(crate) fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
872 for attr in attrs {
873 if attr.has_name(depr_skip_annotation()) {
874 let file_name = self.psess.span_to_filename(attr.span);
875 self.report.append(
876 file_name,
877 vec![FormattingError::from_span(
878 attr.span,
879 self.psess,
880 ErrorKind::DeprecatedAttr,
881 )],
882 );
883 } else {
884 match &attr.kind {
885 ast::AttrKind::Normal(ref normal)
886 if self.is_unknown_rustfmt_attr(&normal.item.path.segments) =>
887 {
888 let file_name = self.psess.span_to_filename(attr.span);
889 self.report.append(
890 file_name,
891 vec![FormattingError::from_span(
892 attr.span,
893 self.psess,
894 ErrorKind::BadAttr,
895 )],
896 );
897 }
898 _ => (),
899 }
900 }
901 }
902 if contains_skip(attrs) {
903 return true;
904 }
905
906 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
907 if attrs.is_empty() {
908 return false;
909 }
910
911 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
912 if out_of_file_lines_range!(self, span) {
913 return false;
914 }
915
916 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
917 self.push_rewrite(span, rewrite);
918
919 false
920 }
921
922 fn is_unknown_rustfmt_attr(&self, segments: &[ast::PathSegment]) -> bool {
923 if segments[0].ident.to_string() != "rustfmt" {
924 return false;
925 }
926 !is_skip_attr(segments)
927 }
928
929 fn walk_mod_items(&mut self, items: &[Box<ast::Item>]) {
930 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(items));
931 }
932
933 fn walk_stmts(&mut self, stmts: &[Stmt<'_>], include_current_empty_semi: bool) {
934 if stmts.is_empty() {
935 return;
936 }
937
938 let items: Vec<_> = stmts
940 .iter()
941 .take_while(|stmt| stmt.to_item().map_or(false, is_use_item))
942 .filter_map(|stmt| stmt.to_item())
943 .collect();
944
945 if items.is_empty() {
946 self.visit_stmt(&stmts[0], include_current_empty_semi);
947
948 let include_next_empty = if stmts.len() > 1 {
961 matches!(
962 (&stmts[0].as_ast_node().kind, &stmts[1].as_ast_node().kind),
963 (ast::StmtKind::Item(_), ast::StmtKind::Empty)
964 )
965 } else {
966 false
967 };
968
969 self.walk_stmts(&stmts[1..], include_next_empty);
970 } else {
971 self.visit_items_with_reordering(&items);
972 self.walk_stmts(&stmts[items.len()..], false);
973 }
974 }
975
976 fn walk_block_stmts(&mut self, b: &ast::Block) {
977 self.walk_stmts(&Stmt::from_ast_nodes(b.stmts.iter()), false)
978 }
979
980 fn format_mod(
981 &mut self,
982 mod_kind: &ast::ModKind,
983 safety: ast::Safety,
984 vis: &ast::Visibility,
985 s: Span,
986 ident: symbol::Ident,
987 attrs: &[ast::Attribute],
988 ) {
989 let vis_str = utils::format_visibility(&self.get_context(), vis);
990 self.push_str(&*vis_str);
991 self.push_str(format_safety(safety));
992 self.push_str("mod ");
993 let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
995 self.push_str(&ident_str);
996
997 if let ast::ModKind::Loaded(ref items, ast::Inline::Yes, ref spans) = mod_kind {
998 let ast::ModSpans {
999 inner_span,
1000 inject_use_span: _,
1001 } = *spans;
1002 match self.config.brace_style() {
1003 BraceStyle::AlwaysNextLine => {
1004 let indent_str = self.block_indent.to_string_with_newline(self.config);
1005 self.push_str(&indent_str);
1006 self.push_str("{");
1007 }
1008 _ => self.push_str(" {"),
1009 }
1010 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
1012 let body_snippet =
1013 self.snippet(mk_sp(mod_lo, source!(self, inner_span).hi() - BytePos(1)));
1014 let body_snippet = body_snippet.trim();
1015 if body_snippet.is_empty() {
1016 self.push_str("}");
1017 } else {
1018 self.last_pos = mod_lo;
1019 self.block_indent = self.block_indent.block_indent(self.config);
1020 self.visit_attrs(attrs, ast::AttrStyle::Inner);
1021 self.walk_mod_items(items);
1022 let missing_span = self.next_span(inner_span.hi() - BytePos(1));
1023 self.close_block(missing_span, false);
1024 }
1025 self.last_pos = source!(self, inner_span).hi();
1026 } else {
1027 self.push_str(";");
1028 self.last_pos = source!(self, s).hi();
1029 }
1030 }
1031
1032 pub(crate) fn format_separate_mod(&mut self, m: &Module<'_>, end_pos: BytePos) {
1033 self.block_indent = Indent::empty();
1034 let skipped = self.visit_attrs(m.attrs(), ast::AttrStyle::Inner);
1035 assert!(
1036 !skipped,
1037 "Skipping module must be handled before reaching this line."
1038 );
1039 self.walk_mod_items(&m.items);
1040 self.format_missing_with_indent(end_pos);
1041 }
1042
1043 pub(crate) fn skip_empty_lines(&mut self, end_pos: BytePos) {
1044 while let Some(pos) = self
1045 .snippet_provider
1046 .opt_span_after(self.next_span(end_pos), "\n")
1047 {
1048 let span = self.next_span(pos);
1049 if let Some(snippet) = self.opt_snippet(self.next_span(pos)) {
1050 if !snippet.trim().is_empty() {
1051 return;
1052 }
1053
1054 if out_of_file_lines_range!(self, span) {
1055 return;
1056 }
1057 self.last_pos = pos;
1058 }
1059 }
1060 }
1061
1062 pub(crate) fn with_context<T>(&mut self, f: impl Fn(&RewriteContext<'_>) -> T) -> T {
1063 let context = self.get_context();
1064 let result = f(&context);
1065
1066 self.macro_rewrite_failure |= context.macro_rewrite_failure.get();
1067 result
1068 }
1069
1070 pub(crate) fn get_context(&self) -> RewriteContext<'_> {
1071 RewriteContext {
1072 psess: self.psess,
1073 config: self.config,
1074 inside_macro: Rc::new(Cell::new(false)),
1075 use_block: Cell::new(false),
1076 is_if_else_block: Cell::new(false),
1077 is_loop_block: Cell::new(false),
1078 force_one_line_chain: Cell::new(false),
1079 snippet_provider: self.snippet_provider,
1080 macro_rewrite_failure: Cell::new(false),
1081 is_macro_def: self.is_macro_def,
1082 report: self.report.clone(),
1083 skip_context: self.skip_context.clone(),
1084 skipped_range: self.skipped_range.clone(),
1085 }
1086 }
1087
1088 fn add_semi_on_last_block_stmt(&self, stmt: &ast::Stmt) -> bool {
1089 let ast::StmtKind::Expr(expr) = &stmt.kind else {
1090 return false;
1091 };
1092
1093 if self.is_macro_def {
1094 return false;
1095 }
1096
1097 match expr.kind {
1098 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
1099 self.config.trailing_semicolon()
1100 }
1101
1102 ast::ExprKind::Loop(..)
1106 | ast::ExprKind::While(..)
1107 | ast::ExprKind::ForLoop { .. }
1108 | ast::ExprKind::Let(..)
1109 | ast::ExprKind::If(..)
1110 | ast::ExprKind::Match(..) => false,
1111
1112 _ => {
1113 let allowed_to_add_semi = self.is_loop_block
1119 && self.config.edition() >= Edition::Edition2024
1120 && self.config.style_edition() >= StyleEdition::Edition2027;
1121
1122 allowed_to_add_semi && self.config.trailing_semicolon()
1123 }
1124 }
1125 }
1126}