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, Pos, Span, symbol};
7use tracing::debug;
8
9use crate::attr::*;
10use crate::comment::{CodeCharKind, CommentCodeSlices, contains_comment, rewrite_comment};
11use crate::config::{BraceStyle, Config, MacroSelector, StyleEdition};
12use crate::coverage::transform_missing_snippet;
13use crate::items::{
14 FnBraceStyle, FnSig, ItemVisitorKind, StaticParts, StructParts, format_impl, format_trait,
15 format_trait_alias, is_mod_decl, is_use_item, rewrite_extern_crate, rewrite_type_alias,
16};
17use crate::macros::{MacroPosition, macro_style, rewrite_macro, rewrite_macro_def};
18use crate::modules::Module;
19use crate::parse::session::ParseSess;
20use crate::rewrite::{Rewrite, RewriteContext};
21use crate::shape::{Indent, Shape};
22use crate::skip::{SkipContext, is_skip_attr};
23use crate::source_map::{LineRangeUtils, SpanUtils};
24use crate::spanned::Spanned;
25use crate::stmt::Stmt;
26use crate::utils::{
27 self, contains_skip, count_newlines, depr_skip_annotation, format_safety, inner_attributes,
28 last_line_width, mk_sp, ptr_vec_to_ref_vec, rewrite_ident, starts_with_newline, stmt_expr,
29};
30use crate::{ErrorKind, FormatReport, FormattingError};
31
32pub(crate) struct SnippetProvider {
34 big_snippet: Arc<String>,
36 start_pos: usize,
38 end_pos: usize,
40}
41
42impl SnippetProvider {
43 pub(crate) fn span_to_snippet(&self, span: Span) -> Option<&str> {
44 let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
45 let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
46 Some(&self.big_snippet[start_index..end_index])
47 }
48
49 pub(crate) fn new(start_pos: BytePos, end_pos: BytePos, big_snippet: Arc<String>) -> Self {
50 let start_pos = start_pos.to_usize();
51 let end_pos = end_pos.to_usize();
52 SnippetProvider {
53 big_snippet,
54 start_pos,
55 end_pos,
56 }
57 }
58
59 pub(crate) fn entire_snippet(&self) -> &str {
60 self.big_snippet.as_str()
61 }
62
63 pub(crate) fn start_pos(&self) -> BytePos {
64 BytePos::from_usize(self.start_pos)
65 }
66
67 pub(crate) fn end_pos(&self) -> BytePos {
68 BytePos::from_usize(self.end_pos)
69 }
70}
71
72pub(crate) struct FmtVisitor<'a> {
73 parent_context: Option<&'a RewriteContext<'a>>,
74 pub(crate) psess: &'a ParseSess,
75 pub(crate) buffer: String,
76 pub(crate) last_pos: BytePos,
77 pub(crate) block_indent: Indent,
79 pub(crate) config: &'a Config,
80 pub(crate) is_if_else_block: bool,
81 pub(crate) snippet_provider: &'a SnippetProvider,
82 pub(crate) line_number: usize,
83 pub(crate) skipped_range: Rc<RefCell<Vec<(usize, usize)>>>,
86 pub(crate) macro_rewrite_failure: bool,
87 pub(crate) report: FormatReport,
88 pub(crate) skip_context: SkipContext,
89 pub(crate) is_macro_def: bool,
90}
91
92impl<'a> Drop for FmtVisitor<'a> {
93 fn drop(&mut self) {
94 if let Some(ctx) = self.parent_context {
95 if self.macro_rewrite_failure {
96 ctx.macro_rewrite_failure.replace(true);
97 }
98 }
99 }
100}
101
102impl<'b, 'a: 'b> FmtVisitor<'a> {
103 fn set_parent_context(&mut self, context: &'a RewriteContext<'_>) {
104 self.parent_context = Some(context);
105 }
106
107 pub(crate) fn shape(&self) -> Shape {
108 Shape::indented(self.block_indent, self.config)
109 }
110
111 fn next_span(&self, hi: BytePos) -> Span {
112 mk_sp(self.last_pos, hi)
113 }
114
115 fn visit_stmt(&mut self, stmt: &Stmt<'_>, include_empty_semi: bool) {
116 debug!("visit_stmt: {}", self.psess.span_to_debug_info(stmt.span()));
117
118 if stmt.is_empty() {
119 let snippet = self.snippet(mk_sp(self.last_pos, stmt.span().lo()));
122 let original_starts_with_newline = snippet
123 .find(|c| c != ' ')
124 .map_or(false, |i| starts_with_newline(&snippet[i..]));
125 let snippet = snippet.trim();
126 if !snippet.is_empty() {
127 if include_empty_semi {
132 self.format_missing(stmt.span().hi());
133 } else {
134 if original_starts_with_newline {
135 self.push_str("\n");
136 }
137
138 self.push_str(&self.block_indent.to_string(self.config));
139 self.push_str(snippet);
140 }
141 } else if include_empty_semi {
142 self.push_str(";");
143 }
144 self.last_pos = stmt.span().hi();
145 return;
146 }
147
148 match stmt.as_ast_node().kind {
149 ast::StmtKind::Item(ref item) => {
150 self.visit_item(item);
151 self.last_pos = stmt.span().hi();
152 }
153 ast::StmtKind::Let(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
154 let attrs = get_attrs_from_stmt(stmt.as_ast_node());
155 if contains_skip(attrs) {
156 self.push_skipped_with_span(
157 attrs,
158 stmt.span(),
159 get_span_without_attrs(stmt.as_ast_node()),
160 );
161 } else {
162 let shape = self.shape();
163 let rewrite = self.with_context(|ctx| stmt.rewrite(ctx, shape));
164 self.push_rewrite(stmt.span(), rewrite)
165 }
166 }
167 ast::StmtKind::MacCall(ref mac_stmt) => {
168 if self.visit_attrs(&mac_stmt.attrs, ast::AttrStyle::Outer) {
169 self.push_skipped_with_span(
170 &mac_stmt.attrs,
171 stmt.span(),
172 get_span_without_attrs(stmt.as_ast_node()),
173 );
174 } else {
175 self.visit_mac(&mac_stmt.mac, None, MacroPosition::Statement);
176 }
177 self.format_missing(stmt.span().hi());
178 }
179 ast::StmtKind::Empty => (),
180 }
181 }
182
183 fn trim_spaces_after_opening_brace(
186 &mut self,
187 b: &ast::Block,
188 inner_attrs: Option<&[ast::Attribute]>,
189 ) {
190 if let Some(first_stmt) = b.stmts.first() {
191 let hi = inner_attrs
192 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
193 .unwrap_or_else(|| first_stmt.span().lo());
194 let missing_span = self.next_span(hi);
195 let snippet = self.snippet(missing_span);
196 let len = CommentCodeSlices::new(snippet)
197 .next()
198 .and_then(|(kind, _, s)| {
199 if kind == CodeCharKind::Normal {
200 s.rfind('\n')
201 } else {
202 None
203 }
204 });
205 if let Some(len) = len {
206 self.last_pos = self.last_pos + BytePos::from_usize(len);
207 }
208 }
209 }
210
211 pub(crate) fn visit_block(
212 &mut self,
213 b: &ast::Block,
214 inner_attrs: Option<&[ast::Attribute]>,
215 has_braces: bool,
216 ) {
217 debug!("visit_block: {}", self.psess.span_to_debug_info(b.span));
218
219 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
221
222 self.last_pos = self.last_pos + brace_compensation;
223 self.block_indent = self.block_indent.block_indent(self.config);
224 self.push_str("{");
225 self.trim_spaces_after_opening_brace(b, inner_attrs);
226
227 if let Some(attrs) = inner_attrs {
229 self.visit_attrs(attrs, ast::AttrStyle::Inner);
230 }
231
232 self.walk_block_stmts(b);
233
234 if !b.stmts.is_empty() {
235 if let Some(expr) = stmt_expr(&b.stmts[b.stmts.len() - 1]) {
236 if utils::semicolon_for_expr(&self.get_context(), expr) {
237 self.push_str(";");
238 }
239 }
240 }
241
242 let rest_span = self.next_span(b.span.hi());
243 if out_of_file_lines_range!(self, rest_span) {
244 self.push_str(self.snippet(rest_span));
245 self.block_indent = self.block_indent.block_unindent(self.config);
246 } else {
247 let missing_span = self.next_span(b.span.hi() - brace_compensation);
249 self.close_block(missing_span, self.unindent_comment_on_closing_brace(b));
250 }
251 self.last_pos = source!(self, b.span).hi();
252 }
253
254 fn close_block(&mut self, span: Span, unindent_comment: bool) {
255 let config = self.config;
256
257 let mut last_hi = span.lo();
258 let mut unindented = false;
259 let mut prev_ends_with_newline = false;
260 let mut extra_newline = false;
261
262 let skip_normal = |s: &str| {
263 let trimmed = s.trim();
264 trimmed.is_empty() || trimmed.chars().all(|c| c == ';')
265 };
266
267 let comment_snippet = self.snippet(span);
268
269 let align_to_right = if unindent_comment && contains_comment(comment_snippet) {
270 let first_lines = comment_snippet.splitn(2, '/').next().unwrap_or("");
271 last_line_width(first_lines) > last_line_width(comment_snippet)
272 } else {
273 false
274 };
275
276 for (kind, offset, sub_slice) in CommentCodeSlices::new(comment_snippet) {
277 let sub_slice = transform_missing_snippet(config, sub_slice);
278
279 debug!("close_block: {:?} {:?} {:?}", kind, offset, sub_slice);
280
281 match kind {
282 CodeCharKind::Comment => {
283 if !unindented && unindent_comment && !align_to_right {
284 unindented = true;
285 self.block_indent = self.block_indent.block_unindent(config);
286 }
287 let span_in_between = mk_sp(last_hi, span.lo() + BytePos::from_usize(offset));
288 let snippet_in_between = self.snippet(span_in_between);
289 let mut comment_on_same_line = !snippet_in_between.contains('\n');
290
291 let mut comment_shape =
292 Shape::indented(self.block_indent, config).comment(config);
293 if self.config.style_edition() >= StyleEdition::Edition2024
294 && comment_on_same_line
295 {
296 self.push_str(" ");
297 match sub_slice.find('\n') {
300 None => {
301 self.push_str(&sub_slice);
302 }
303 Some(offset) if offset + 1 == sub_slice.len() => {
304 self.push_str(&sub_slice[..offset]);
305 }
306 Some(offset) => {
307 let first_line = &sub_slice[..offset];
308 self.push_str(first_line);
309 self.push_str(&self.block_indent.to_string_with_newline(config));
310
311 let other_lines = &sub_slice[offset + 1..];
313 let comment_str =
314 rewrite_comment(other_lines, false, comment_shape, config);
315 match comment_str {
316 Ok(ref s) => self.push_str(s),
317 Err(_) => self.push_str(other_lines),
318 }
319 }
320 }
321 } else {
322 if comment_on_same_line {
323 let offset_len = 1 + last_line_width(&self.buffer)
325 .saturating_sub(self.block_indent.width());
326 match comment_shape
327 .visual_indent(offset_len)
328 .sub_width(offset_len)
329 {
330 Some(shp) => comment_shape = shp,
331 None => comment_on_same_line = false,
332 }
333 };
334
335 if comment_on_same_line {
336 self.push_str(" ");
337 } else {
338 if count_newlines(snippet_in_between) >= 2 || extra_newline {
339 self.push_str("\n");
340 }
341 self.push_str(&self.block_indent.to_string_with_newline(config));
342 }
343
344 let comment_str = rewrite_comment(&sub_slice, false, comment_shape, config);
345 match comment_str {
346 Ok(ref s) => self.push_str(s),
347 Err(_) => self.push_str(&sub_slice),
348 }
349 }
350 }
351 CodeCharKind::Normal if skip_normal(&sub_slice) => {
352 extra_newline = prev_ends_with_newline && sub_slice.contains('\n');
353 continue;
354 }
355 CodeCharKind::Normal => {
356 self.push_str(&self.block_indent.to_string_with_newline(config));
357 self.push_str(sub_slice.trim());
358 }
359 }
360 prev_ends_with_newline = sub_slice.ends_with('\n');
361 extra_newline = false;
362 last_hi = span.lo() + BytePos::from_usize(offset + sub_slice.len());
363 }
364 if unindented {
365 self.block_indent = self.block_indent.block_indent(self.config);
366 }
367 self.block_indent = self.block_indent.block_unindent(self.config);
368 self.push_str(&self.block_indent.to_string_with_newline(config));
369 self.push_str("}");
370 }
371
372 fn unindent_comment_on_closing_brace(&self, b: &ast::Block) -> bool {
373 self.is_if_else_block && !b.stmts.is_empty()
374 }
375
376 pub(crate) fn visit_fn(
379 &mut self,
380 fk: visit::FnKind<'_>,
381 fd: &ast::FnDecl,
382 s: Span,
383 defaultness: ast::Defaultness,
384 inner_attrs: Option<&[ast::Attribute]>,
385 ) {
386 let indent = self.block_indent;
387 let block;
388 let rewrite = match fk {
389 visit::FnKind::Fn(
390 _,
391 ident,
392 _,
393 ast::Fn {
394 body: Some(ref b), ..
395 },
396 ) => {
397 block = b;
398 self.rewrite_fn_before_block(
399 indent,
400 *ident,
401 &FnSig::from_fn_kind(&fk, fd, defaultness),
402 mk_sp(s.lo(), b.span.lo()),
403 )
404 }
405 _ => unreachable!(),
406 };
407
408 if let Some((fn_str, fn_brace_style)) = rewrite {
409 self.format_missing_with_indent(source!(self, s).lo());
410
411 if let Some(rw) = self.single_line_fn(&fn_str, block, inner_attrs) {
412 self.push_str(&rw);
413 self.last_pos = s.hi();
414 return;
415 }
416
417 self.push_str(&fn_str);
418 match fn_brace_style {
419 FnBraceStyle::SameLine => self.push_str(" "),
420 FnBraceStyle::NextLine => {
421 self.push_str(&self.block_indent.to_string_with_newline(self.config))
422 }
423 _ => unreachable!(),
424 }
425 self.last_pos = source!(self, block.span).lo();
426 } else {
427 self.format_missing(source!(self, block.span).lo());
428 }
429
430 self.visit_block(block, inner_attrs, true)
431 }
432
433 pub(crate) fn visit_item(&mut self, item: &ast::Item) {
434 skip_out_of_file_lines_range_visitor!(self, item.span);
435
436 let filtered_attrs;
441 let mut attrs = &item.attrs;
442 let skip_context_saved = self.skip_context.clone();
443 self.skip_context.update_with_attrs(attrs);
444
445 let should_visit_node_again = match item.kind {
446 ast::ItemKind::Use(..) | ast::ItemKind::ExternCrate(_) => {
448 if contains_skip(attrs) {
449 self.push_skipped_with_span(attrs.as_slice(), item.span(), item.span());
450 false
451 } else {
452 true
453 }
454 }
455 _ if !is_mod_decl(item) => {
457 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
458 self.push_skipped_with_span(item.attrs.as_slice(), item.span(), item.span());
459 false
460 } else {
461 true
462 }
463 }
464 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => false,
466 ast::ItemKind::Mod(..) => {
469 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
470 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
473 attrs = &filtered_attrs;
474 true
475 }
476 _ => {
477 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
478 self.push_skipped_with_span(item.attrs.as_slice(), item.span(), item.span());
479 false
480 } else {
481 true
482 }
483 }
484 };
485
486 if should_visit_node_again {
488 match item.kind {
489 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
490 ast::ItemKind::Impl(ref iimpl) => {
491 let block_indent = self.block_indent;
492 let rw = self.with_context(|ctx| format_impl(ctx, item, iimpl, block_indent));
493 self.push_rewrite(item.span, rw);
494 }
495 ast::ItemKind::Trait(..) => {
496 let block_indent = self.block_indent;
497 let rw = self.with_context(|ctx| format_trait(ctx, item, block_indent));
498 self.push_rewrite(item.span, rw);
499 }
500 ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => {
501 let shape = Shape::indented(self.block_indent, self.config);
502 let rw = format_trait_alias(
503 &self.get_context(),
504 item.ident,
505 &item.vis,
506 generics,
507 generic_bounds,
508 shape,
509 );
510 self.push_rewrite(item.span, rw);
511 }
512 ast::ItemKind::ExternCrate(_) => {
513 let rw = rewrite_extern_crate(&self.get_context(), item, self.shape());
514 let span = if attrs.is_empty() {
515 item.span
516 } else {
517 mk_sp(attrs[0].span.lo(), item.span.hi())
518 };
519 self.push_rewrite(span, rw);
520 }
521 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
522 self.visit_struct(&StructParts::from_item(item));
523 }
524 ast::ItemKind::Enum(ref def, ref generics) => {
525 self.format_missing_with_indent(source!(self, item.span).lo());
526 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
527 self.last_pos = source!(self, item.span).hi();
528 }
529 ast::ItemKind::Mod(safety, ref mod_kind) => {
530 self.format_missing_with_indent(source!(self, item.span).lo());
531 self.format_mod(mod_kind, safety, &item.vis, item.span, item.ident, attrs);
532 }
533 ast::ItemKind::MacCall(ref mac) => {
534 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
535 }
536 ast::ItemKind::ForeignMod(ref foreign_mod) => {
537 self.format_missing_with_indent(source!(self, item.span).lo());
538 self.format_foreign_mod(foreign_mod, item.span);
539 }
540 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
541 self.visit_static(&StaticParts::from_item(item));
542 }
543 ast::ItemKind::Fn(ref fn_kind) => {
544 let ast::Fn {
545 defaultness,
546 ref sig,
547 ref generics,
548 ref body,
549 ..
550 } = **fn_kind;
551 if body.is_some() {
552 let inner_attrs = inner_attributes(&item.attrs);
553 let fn_ctxt = match sig.header.ext {
554 ast::Extern::None => visit::FnCtxt::Free,
555 _ => visit::FnCtxt::Foreign,
556 };
557 self.visit_fn(
558 visit::FnKind::Fn(fn_ctxt, &item.ident, &item.vis, fn_kind),
559 &sig.decl,
560 item.span,
561 defaultness,
562 Some(&inner_attrs),
563 )
564 } else {
565 let indent = self.block_indent;
566 let rewrite = self
567 .rewrite_required_fn(
568 indent, item.ident, sig, &item.vis, generics, item.span,
569 )
570 .ok();
571 self.push_rewrite(item.span, rewrite);
572 }
573 }
574 ast::ItemKind::TyAlias(ref ty_alias) => {
575 use ItemVisitorKind::Item;
576 self.visit_ty_alias_kind(ty_alias, &Item(item), item.span);
577 }
578 ast::ItemKind::GlobalAsm(..) => {
579 let snippet = Some(self.snippet(item.span).to_owned());
580 self.push_rewrite(item.span, snippet);
581 }
582 ast::ItemKind::MacroDef(ref def) => {
583 let rewrite = rewrite_macro_def(
584 &self.get_context(),
585 self.shape(),
586 self.block_indent,
587 def,
588 item.ident,
589 &item.vis,
590 item.span,
591 )
592 .ok();
593 self.push_rewrite(item.span, rewrite);
594 }
595 ast::ItemKind::Delegation(..) | ast::ItemKind::DelegationMac(..) => {
596 self.push_rewrite(item.span, None)
599 }
600 };
601 }
602 self.skip_context = skip_context_saved;
603 }
604
605 fn visit_ty_alias_kind(
606 &mut self,
607 ty_kind: &ast::TyAlias,
608 visitor_kind: &ItemVisitorKind<'_>,
609 span: Span,
610 ) {
611 let rewrite = rewrite_type_alias(
612 ty_kind,
613 &self.get_context(),
614 self.block_indent,
615 visitor_kind,
616 span,
617 )
618 .ok();
619 self.push_rewrite(span, rewrite);
620 }
621
622 fn visit_assoc_item(&mut self, visitor_kind: &ItemVisitorKind<'_>) {
623 use ItemVisitorKind::*;
624 let (ai, skip_span, assoc_ctxt) = match visitor_kind {
626 AssocTraitItem(ai) => (*ai, ai.span(), visit::AssocCtxt::Trait),
627 AssocImplItem(ai) => (*ai, ai.span, visit::AssocCtxt::Impl),
628 _ => unreachable!(),
629 };
630 skip_out_of_file_lines_range_visitor!(self, ai.span);
631
632 if self.visit_attrs(&ai.attrs, ast::AttrStyle::Outer) {
633 self.push_skipped_with_span(ai.attrs.as_slice(), skip_span, skip_span);
634 return;
635 }
636
637 match (&ai.kind, visitor_kind) {
639 (ast::AssocItemKind::Const(..), AssocTraitItem(_)) => {
640 self.visit_static(&StaticParts::from_trait_item(ai))
641 }
642 (ast::AssocItemKind::Const(..), AssocImplItem(_)) => {
643 self.visit_static(&StaticParts::from_impl_item(ai))
644 }
645 (ast::AssocItemKind::Fn(ref fn_kind), _) => {
646 let ast::Fn {
647 defaultness,
648 ref sig,
649 ref generics,
650 ref body,
651 ..
652 } = **fn_kind;
653 if body.is_some() {
654 let inner_attrs = inner_attributes(&ai.attrs);
655 let fn_ctxt = visit::FnCtxt::Assoc(assoc_ctxt);
656 self.visit_fn(
657 visit::FnKind::Fn(fn_ctxt, &ai.ident, &ai.vis, fn_kind),
658 &sig.decl,
659 ai.span,
660 defaultness,
661 Some(&inner_attrs),
662 );
663 } else {
664 let indent = self.block_indent;
665 let rewrite = self
666 .rewrite_required_fn(indent, ai.ident, sig, &ai.vis, generics, ai.span)
667 .ok();
668 self.push_rewrite(ai.span, rewrite);
669 }
670 }
671 (ast::AssocItemKind::Type(ref ty_alias), _) => {
672 self.visit_ty_alias_kind(ty_alias, visitor_kind, ai.span);
673 }
674 (ast::AssocItemKind::MacCall(ref mac), _) => {
675 self.visit_mac(mac, Some(ai.ident), MacroPosition::Item);
676 }
677 _ => unreachable!(),
678 }
679 }
680
681 pub(crate) fn visit_trait_item(&mut self, ti: &ast::AssocItem) {
682 self.visit_assoc_item(&ItemVisitorKind::AssocTraitItem(ti));
683 }
684
685 pub(crate) fn visit_impl_item(&mut self, ii: &ast::AssocItem) {
686 self.visit_assoc_item(&ItemVisitorKind::AssocImplItem(ii));
687 }
688
689 fn visit_mac(&mut self, mac: &ast::MacCall, ident: Option<symbol::Ident>, pos: MacroPosition) {
690 skip_out_of_file_lines_range_visitor!(self, mac.span());
691
692 let shape = self.shape().saturating_sub_width(1);
694 let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos).ok());
695 let (span, rewrite) = match macro_style(mac, &self.get_context()) {
700 Delimiter::Bracket | Delimiter::Parenthesis if MacroPosition::Item == pos => {
701 let search_span = mk_sp(mac.span().hi(), self.snippet_provider.end_pos());
702 let hi = self.snippet_provider.span_before(search_span, ";");
703 let target_span = mk_sp(mac.span().lo(), hi + BytePos(1));
704 let rewrite = rewrite.map(|rw| {
705 if !rw.ends_with(';') {
706 format!("{};", rw)
707 } else {
708 rw
709 }
710 });
711 (target_span, rewrite)
712 }
713 _ => (mac.span(), rewrite),
714 };
715
716 self.push_rewrite(span, rewrite);
717 }
718
719 pub(crate) fn push_str(&mut self, s: &str) {
720 self.line_number += count_newlines(s);
721 self.buffer.push_str(s);
722 }
723
724 #[allow(clippy::needless_pass_by_value)]
725 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
726 if let Some(ref s) = rewrite {
727 self.push_str(s);
728 } else {
729 let snippet = self.snippet(span);
730 self.push_str(snippet.trim());
731 }
732 self.last_pos = source!(self, span).hi();
733 }
734
735 pub(crate) fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
736 self.format_missing_with_indent(source!(self, span).lo());
737 self.push_rewrite_inner(span, rewrite);
738 }
739
740 pub(crate) fn push_skipped_with_span(
741 &mut self,
742 attrs: &[ast::Attribute],
743 item_span: Span,
744 main_span: Span,
745 ) {
746 self.format_missing_with_indent(source!(self, item_span).lo());
747 let attrs_end = attrs
749 .iter()
750 .map(|attr| self.psess.line_of_byte_pos(attr.span.hi()))
751 .max()
752 .unwrap_or(1);
753 let first_line = self.psess.line_of_byte_pos(main_span.lo());
754 let lo = std::cmp::min(attrs_end + 1, first_line);
758 self.push_rewrite_inner(item_span, None);
759 let hi = self.line_number + 1;
760 self.skipped_range.borrow_mut().push((lo, hi));
761 }
762
763 pub(crate) fn from_context(ctx: &'a RewriteContext<'_>) -> FmtVisitor<'a> {
764 let mut visitor = FmtVisitor::from_psess(
765 ctx.psess,
766 ctx.config,
767 ctx.snippet_provider,
768 ctx.report.clone(),
769 );
770 visitor.skip_context.update(ctx.skip_context.clone());
771 visitor.set_parent_context(ctx);
772 visitor
773 }
774
775 pub(crate) fn from_psess(
776 psess: &'a ParseSess,
777 config: &'a Config,
778 snippet_provider: &'a SnippetProvider,
779 report: FormatReport,
780 ) -> FmtVisitor<'a> {
781 let mut skip_context = SkipContext::default();
782 let mut macro_names = Vec::new();
783 for macro_selector in config.skip_macro_invocations().0 {
784 match macro_selector {
785 MacroSelector::Name(name) => macro_names.push(name.to_string()),
786 MacroSelector::All => skip_context.macros.skip_all(),
787 }
788 }
789 skip_context.macros.extend(macro_names);
790 FmtVisitor {
791 parent_context: None,
792 psess,
793 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
794 last_pos: BytePos(0),
795 block_indent: Indent::empty(),
796 config,
797 is_if_else_block: false,
798 snippet_provider,
799 line_number: 0,
800 skipped_range: Rc::new(RefCell::new(vec![])),
801 is_macro_def: false,
802 macro_rewrite_failure: false,
803 report,
804 skip_context,
805 }
806 }
807
808 pub(crate) fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
809 self.snippet_provider.span_to_snippet(span)
810 }
811
812 pub(crate) fn snippet(&'b self, span: Span) -> &'a str {
813 self.opt_snippet(span).unwrap()
814 }
815
816 pub(crate) fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
818 for attr in attrs {
819 if attr.has_name(depr_skip_annotation()) {
820 let file_name = self.psess.span_to_filename(attr.span);
821 self.report.append(
822 file_name,
823 vec![FormattingError::from_span(
824 attr.span,
825 self.psess,
826 ErrorKind::DeprecatedAttr,
827 )],
828 );
829 } else {
830 match &attr.kind {
831 ast::AttrKind::Normal(ref normal)
832 if self.is_unknown_rustfmt_attr(&normal.item.path.segments) =>
833 {
834 let file_name = self.psess.span_to_filename(attr.span);
835 self.report.append(
836 file_name,
837 vec![FormattingError::from_span(
838 attr.span,
839 self.psess,
840 ErrorKind::BadAttr,
841 )],
842 );
843 }
844 _ => (),
845 }
846 }
847 }
848 if contains_skip(attrs) {
849 return true;
850 }
851
852 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
853 if attrs.is_empty() {
854 return false;
855 }
856
857 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
858 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
859 self.push_rewrite(span, rewrite);
860
861 false
862 }
863
864 fn is_unknown_rustfmt_attr(&self, segments: &[ast::PathSegment]) -> bool {
865 if segments[0].ident.to_string() != "rustfmt" {
866 return false;
867 }
868 !is_skip_attr(segments)
869 }
870
871 fn walk_mod_items(&mut self, items: &[rustc_ast::ptr::P<ast::Item>]) {
872 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(items));
873 }
874
875 fn walk_stmts(&mut self, stmts: &[Stmt<'_>], include_current_empty_semi: bool) {
876 if stmts.is_empty() {
877 return;
878 }
879
880 let items: Vec<_> = stmts
882 .iter()
883 .take_while(|stmt| stmt.to_item().map_or(false, is_use_item))
884 .filter_map(|stmt| stmt.to_item())
885 .collect();
886
887 if items.is_empty() {
888 self.visit_stmt(&stmts[0], include_current_empty_semi);
889
890 let include_next_empty = if stmts.len() > 1 {
903 matches!(
904 (&stmts[0].as_ast_node().kind, &stmts[1].as_ast_node().kind),
905 (ast::StmtKind::Item(_), ast::StmtKind::Empty)
906 )
907 } else {
908 false
909 };
910
911 self.walk_stmts(&stmts[1..], include_next_empty);
912 } else {
913 self.visit_items_with_reordering(&items);
914 self.walk_stmts(&stmts[items.len()..], false);
915 }
916 }
917
918 fn walk_block_stmts(&mut self, b: &ast::Block) {
919 self.walk_stmts(&Stmt::from_ast_nodes(b.stmts.iter()), false)
920 }
921
922 fn format_mod(
923 &mut self,
924 mod_kind: &ast::ModKind,
925 safety: ast::Safety,
926 vis: &ast::Visibility,
927 s: Span,
928 ident: symbol::Ident,
929 attrs: &[ast::Attribute],
930 ) {
931 let vis_str = utils::format_visibility(&self.get_context(), vis);
932 self.push_str(&*vis_str);
933 self.push_str(format_safety(safety));
934 self.push_str("mod ");
935 let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
937 self.push_str(&ident_str);
938
939 if let ast::ModKind::Loaded(ref items, ast::Inline::Yes, ref spans, _) = mod_kind {
940 let ast::ModSpans {
941 inner_span,
942 inject_use_span: _,
943 } = *spans;
944 match self.config.brace_style() {
945 BraceStyle::AlwaysNextLine => {
946 let indent_str = self.block_indent.to_string_with_newline(self.config);
947 self.push_str(&indent_str);
948 self.push_str("{");
949 }
950 _ => self.push_str(" {"),
951 }
952 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
954 let body_snippet =
955 self.snippet(mk_sp(mod_lo, source!(self, inner_span).hi() - BytePos(1)));
956 let body_snippet = body_snippet.trim();
957 if body_snippet.is_empty() {
958 self.push_str("}");
959 } else {
960 self.last_pos = mod_lo;
961 self.block_indent = self.block_indent.block_indent(self.config);
962 self.visit_attrs(attrs, ast::AttrStyle::Inner);
963 self.walk_mod_items(items);
964 let missing_span = self.next_span(inner_span.hi() - BytePos(1));
965 self.close_block(missing_span, false);
966 }
967 self.last_pos = source!(self, inner_span).hi();
968 } else {
969 self.push_str(";");
970 self.last_pos = source!(self, s).hi();
971 }
972 }
973
974 pub(crate) fn format_separate_mod(&mut self, m: &Module<'_>, end_pos: BytePos) {
975 self.block_indent = Indent::empty();
976 let skipped = self.visit_attrs(m.attrs(), ast::AttrStyle::Inner);
977 assert!(
978 !skipped,
979 "Skipping module must be handled before reaching this line."
980 );
981 self.walk_mod_items(&m.items);
982 self.format_missing_with_indent(end_pos);
983 }
984
985 pub(crate) fn skip_empty_lines(&mut self, end_pos: BytePos) {
986 while let Some(pos) = self
987 .snippet_provider
988 .opt_span_after(self.next_span(end_pos), "\n")
989 {
990 if let Some(snippet) = self.opt_snippet(self.next_span(pos)) {
991 if snippet.trim().is_empty() {
992 self.last_pos = pos;
993 } else {
994 return;
995 }
996 }
997 }
998 }
999
1000 pub(crate) fn with_context<F>(&mut self, f: F) -> Option<String>
1001 where
1002 F: Fn(&RewriteContext<'_>) -> Option<String>,
1003 {
1004 let context = self.get_context();
1005 let result = f(&context);
1006
1007 self.macro_rewrite_failure |= context.macro_rewrite_failure.get();
1008 result
1009 }
1010
1011 pub(crate) fn get_context(&self) -> RewriteContext<'_> {
1012 RewriteContext {
1013 psess: self.psess,
1014 config: self.config,
1015 inside_macro: Rc::new(Cell::new(false)),
1016 use_block: Cell::new(false),
1017 is_if_else_block: Cell::new(false),
1018 force_one_line_chain: Cell::new(false),
1019 snippet_provider: self.snippet_provider,
1020 macro_rewrite_failure: Cell::new(false),
1021 is_macro_def: self.is_macro_def,
1022 report: self.report.clone(),
1023 skip_context: self.skip_context.clone(),
1024 skipped_range: self.skipped_range.clone(),
1025 }
1026 }
1027}