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::{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, 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 ident: Ident,
381 fk: visit::FnKind<'_>,
382 fd: &ast::FnDecl,
383 s: Span,
384 defaultness: ast::Defaultness,
385 inner_attrs: Option<&[ast::Attribute]>,
386 ) {
387 let indent = self.block_indent;
388 let block;
389 let rewrite = match fk {
390 visit::FnKind::Fn(
391 _,
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 ta) => {
501 let shape = Shape::indented(self.block_indent, self.config);
502 let rw = format_trait_alias(&self.get_context(), ta, &item.vis, shape);
503 self.push_rewrite(item.span, rw);
504 }
505 ast::ItemKind::ExternCrate(..) => {
506 let rw = rewrite_extern_crate(&self.get_context(), item, self.shape());
507 let span = if attrs.is_empty() {
508 item.span
509 } else {
510 mk_sp(attrs[0].span.lo(), item.span.hi())
511 };
512 self.push_rewrite(span, rw);
513 }
514 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
515 self.visit_struct(&StructParts::from_item(item));
516 }
517 ast::ItemKind::Enum(ident, ref generics, ref def) => {
518 self.format_missing_with_indent(source!(self, item.span).lo());
519 self.visit_enum(ident, &item.vis, def, generics, item.span);
520 self.last_pos = source!(self, item.span).hi();
521 }
522 ast::ItemKind::Mod(safety, ident, ref mod_kind) => {
523 self.format_missing_with_indent(source!(self, item.span).lo());
524 self.format_mod(mod_kind, safety, &item.vis, item.span, ident, attrs);
525 }
526 ast::ItemKind::MacCall(ref mac) => {
527 self.visit_mac(mac, MacroPosition::Item);
528 }
529 ast::ItemKind::ForeignMod(ref foreign_mod) => {
530 self.format_missing_with_indent(source!(self, item.span).lo());
531 self.format_foreign_mod(foreign_mod, item.span);
532 }
533 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
534 self.visit_static(&StaticParts::from_item(item));
535 }
536 ast::ItemKind::Fn(ref fn_kind) => {
537 let ast::Fn {
538 defaultness,
539 ref sig,
540 ident,
541 ref generics,
542 ref body,
543 ..
544 } = **fn_kind;
545 if body.is_some() {
546 let inner_attrs = inner_attributes(&item.attrs);
547 let fn_ctxt = match sig.header.ext {
548 ast::Extern::None => visit::FnCtxt::Free,
549 _ => visit::FnCtxt::Foreign,
550 };
551 self.visit_fn(
552 ident,
553 visit::FnKind::Fn(fn_ctxt, &item.vis, fn_kind),
554 &sig.decl,
555 item.span,
556 defaultness,
557 Some(&inner_attrs),
558 )
559 } else {
560 let indent = self.block_indent;
561 let rewrite = self
562 .rewrite_required_fn(indent, ident, sig, &item.vis, generics, item.span)
563 .ok();
564 self.push_rewrite(item.span, rewrite);
565 }
566 }
567 ast::ItemKind::TyAlias(ref ty_alias) => {
568 use ItemVisitorKind::Item;
569 self.visit_ty_alias_kind(ty_alias, &item.vis, Item, item.span);
570 }
571 ast::ItemKind::GlobalAsm(..) => {
572 let snippet = Some(self.snippet(item.span).to_owned());
573 self.push_rewrite(item.span, snippet);
574 }
575 ast::ItemKind::MacroDef(ident, ref def) => {
576 let rewrite = rewrite_macro_def(
577 &self.get_context(),
578 self.shape(),
579 self.block_indent,
580 def,
581 ident,
582 &item.vis,
583 item.span,
584 )
585 .ok();
586 self.push_rewrite(item.span, rewrite);
587 }
588 ast::ItemKind::Delegation(..) | ast::ItemKind::DelegationMac(..) => {
589 self.push_rewrite(item.span, None)
592 }
593 };
594 }
595 self.skip_context = skip_context_saved;
596 }
597
598 fn visit_ty_alias_kind(
599 &mut self,
600 ty_kind: &ast::TyAlias,
601 vis: &ast::Visibility,
602 visitor_kind: ItemVisitorKind,
603 span: Span,
604 ) {
605 let rewrite = rewrite_type_alias(
606 ty_kind,
607 vis,
608 &self.get_context(),
609 self.block_indent,
610 visitor_kind,
611 span,
612 )
613 .ok();
614 self.push_rewrite(span, rewrite);
615 }
616
617 fn visit_assoc_item(&mut self, ai: &ast::AssocItem, visitor_kind: ItemVisitorKind) {
618 use ItemVisitorKind::*;
619 let assoc_ctxt = match visitor_kind {
620 AssocTraitItem => visit::AssocCtxt::Trait,
621 AssocImplItem => visit::AssocCtxt::Impl { of_trait: false },
623 _ => unreachable!(),
624 };
625 let skip_span = ai.span;
627 skip_out_of_file_lines_range_visitor!(self, ai.span);
628
629 if self.visit_attrs(&ai.attrs, ast::AttrStyle::Outer) {
630 self.push_skipped_with_span(ai.attrs.as_slice(), skip_span, skip_span);
631 return;
632 }
633
634 match (&ai.kind, visitor_kind) {
636 (ast::AssocItemKind::Const(c), AssocTraitItem) => {
637 self.visit_static(&StaticParts::from_trait_item(ai, c.ident))
638 }
639 (ast::AssocItemKind::Const(c), AssocImplItem) => {
640 self.visit_static(&StaticParts::from_impl_item(ai, c.ident))
641 }
642 (ast::AssocItemKind::Fn(ref fn_kind), _) => {
643 let ast::Fn {
644 defaultness,
645 ref sig,
646 ident,
647 ref generics,
648 ref body,
649 ..
650 } = **fn_kind;
651 if body.is_some() {
652 let inner_attrs = inner_attributes(&ai.attrs);
653 let fn_ctxt = visit::FnCtxt::Assoc(assoc_ctxt);
654 self.visit_fn(
655 ident,
656 visit::FnKind::Fn(fn_ctxt, &ai.vis, fn_kind),
657 &sig.decl,
658 ai.span,
659 defaultness,
660 Some(&inner_attrs),
661 );
662 } else {
663 let indent = self.block_indent;
664 let rewrite = self
665 .rewrite_required_fn(indent, fn_kind.ident, sig, &ai.vis, generics, ai.span)
666 .ok();
667 self.push_rewrite(ai.span, rewrite);
668 }
669 }
670 (ast::AssocItemKind::Type(ref ty_alias), _) => {
671 self.visit_ty_alias_kind(ty_alias, &ai.vis, visitor_kind, ai.span);
672 }
673 (ast::AssocItemKind::MacCall(ref mac), _) => {
674 self.visit_mac(mac, MacroPosition::Item);
675 }
676 _ => unreachable!(),
677 }
678 }
679
680 pub(crate) fn visit_trait_item(&mut self, ti: &ast::AssocItem) {
681 self.visit_assoc_item(ti, ItemVisitorKind::AssocTraitItem);
682 }
683
684 pub(crate) fn visit_impl_item(&mut self, ii: &ast::AssocItem) {
685 self.visit_assoc_item(ii, ItemVisitorKind::AssocImplItem);
686 }
687
688 fn visit_mac(&mut self, mac: &ast::MacCall, pos: MacroPosition) {
689 skip_out_of_file_lines_range_visitor!(self, mac.span());
690
691 let shape = self.shape().saturating_sub_width(1);
693 let rewrite = self.with_context(|ctx| rewrite_macro(mac, ctx, shape, pos).ok());
694 let (span, rewrite) = match macro_style(mac, &self.get_context()) {
699 Delimiter::Bracket | Delimiter::Parenthesis if MacroPosition::Item == pos => {
700 let search_span = mk_sp(mac.span().hi(), self.snippet_provider.end_pos());
701 let hi = self.snippet_provider.span_before(search_span, ";");
702 let target_span = mk_sp(mac.span().lo(), hi + BytePos(1));
703 let rewrite = rewrite.map(|rw| {
704 if !rw.ends_with(';') {
705 format!("{};", rw)
706 } else {
707 rw
708 }
709 });
710 (target_span, rewrite)
711 }
712 _ => (mac.span(), rewrite),
713 };
714
715 self.push_rewrite(span, rewrite);
716 }
717
718 pub(crate) fn push_str(&mut self, s: &str) {
719 self.line_number += count_newlines(s);
720 self.buffer.push_str(s);
721 }
722
723 #[allow(clippy::needless_pass_by_value)]
724 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
725 if let Some(ref s) = rewrite {
726 self.push_str(s);
727 } else {
728 let snippet = self.snippet(span);
729 self.push_str(snippet.trim());
730 }
731 self.last_pos = source!(self, span).hi();
732 }
733
734 pub(crate) fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
735 self.format_missing_with_indent(source!(self, span).lo());
736 self.push_rewrite_inner(span, rewrite);
737 }
738
739 pub(crate) fn push_skipped_with_span(
740 &mut self,
741 attrs: &[ast::Attribute],
742 item_span: Span,
743 main_span: Span,
744 ) {
745 self.format_missing_with_indent(source!(self, item_span).lo());
746 let attrs_end = attrs
748 .iter()
749 .map(|attr| self.psess.line_of_byte_pos(attr.span.hi()))
750 .max()
751 .unwrap_or(1);
752 let first_line = self.psess.line_of_byte_pos(main_span.lo());
753 let lo = std::cmp::min(attrs_end + 1, first_line);
757 self.push_rewrite_inner(item_span, None);
758 let hi = self.line_number + 1;
759 self.skipped_range.borrow_mut().push((lo, hi));
760 }
761
762 pub(crate) fn from_context(ctx: &'a RewriteContext<'_>) -> FmtVisitor<'a> {
763 let mut visitor = FmtVisitor::from_psess(
764 ctx.psess,
765 ctx.config,
766 ctx.snippet_provider,
767 ctx.report.clone(),
768 );
769 visitor.skip_context.update(ctx.skip_context.clone());
770 visitor.set_parent_context(ctx);
771 visitor
772 }
773
774 pub(crate) fn from_psess(
775 psess: &'a ParseSess,
776 config: &'a Config,
777 snippet_provider: &'a SnippetProvider,
778 report: FormatReport,
779 ) -> FmtVisitor<'a> {
780 let mut skip_context = SkipContext::default();
781 let mut macro_names = Vec::new();
782 for macro_selector in config.skip_macro_invocations().0 {
783 match macro_selector {
784 MacroSelector::Name(name) => macro_names.push(name.to_string()),
785 MacroSelector::All => skip_context.macros.skip_all(),
786 }
787 }
788 skip_context.macros.extend(macro_names);
789 FmtVisitor {
790 parent_context: None,
791 psess,
792 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
793 last_pos: BytePos(0),
794 block_indent: Indent::empty(),
795 config,
796 is_if_else_block: false,
797 snippet_provider,
798 line_number: 0,
799 skipped_range: Rc::new(RefCell::new(vec![])),
800 is_macro_def: false,
801 macro_rewrite_failure: false,
802 report,
803 skip_context,
804 }
805 }
806
807 pub(crate) fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
808 self.snippet_provider.span_to_snippet(span)
809 }
810
811 pub(crate) fn snippet(&'b self, span: Span) -> &'a str {
812 self.opt_snippet(span).unwrap()
813 }
814
815 pub(crate) fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
817 for attr in attrs {
818 if attr.has_name(depr_skip_annotation()) {
819 let file_name = self.psess.span_to_filename(attr.span);
820 self.report.append(
821 file_name,
822 vec![FormattingError::from_span(
823 attr.span,
824 self.psess,
825 ErrorKind::DeprecatedAttr,
826 )],
827 );
828 } else {
829 match &attr.kind {
830 ast::AttrKind::Normal(ref normal)
831 if self.is_unknown_rustfmt_attr(&normal.item.path.segments) =>
832 {
833 let file_name = self.psess.span_to_filename(attr.span);
834 self.report.append(
835 file_name,
836 vec![FormattingError::from_span(
837 attr.span,
838 self.psess,
839 ErrorKind::BadAttr,
840 )],
841 );
842 }
843 _ => (),
844 }
845 }
846 }
847 if contains_skip(attrs) {
848 return true;
849 }
850
851 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
852 if attrs.is_empty() {
853 return false;
854 }
855
856 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
857 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
858 self.push_rewrite(span, rewrite);
859
860 false
861 }
862
863 fn is_unknown_rustfmt_attr(&self, segments: &[ast::PathSegment]) -> bool {
864 if segments[0].ident.to_string() != "rustfmt" {
865 return false;
866 }
867 !is_skip_attr(segments)
868 }
869
870 fn walk_mod_items(&mut self, items: &[Box<ast::Item>]) {
871 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(items));
872 }
873
874 fn walk_stmts(&mut self, stmts: &[Stmt<'_>], include_current_empty_semi: bool) {
875 if stmts.is_empty() {
876 return;
877 }
878
879 let items: Vec<_> = stmts
881 .iter()
882 .take_while(|stmt| stmt.to_item().map_or(false, is_use_item))
883 .filter_map(|stmt| stmt.to_item())
884 .collect();
885
886 if items.is_empty() {
887 self.visit_stmt(&stmts[0], include_current_empty_semi);
888
889 let include_next_empty = if stmts.len() > 1 {
902 matches!(
903 (&stmts[0].as_ast_node().kind, &stmts[1].as_ast_node().kind),
904 (ast::StmtKind::Item(_), ast::StmtKind::Empty)
905 )
906 } else {
907 false
908 };
909
910 self.walk_stmts(&stmts[1..], include_next_empty);
911 } else {
912 self.visit_items_with_reordering(&items);
913 self.walk_stmts(&stmts[items.len()..], false);
914 }
915 }
916
917 fn walk_block_stmts(&mut self, b: &ast::Block) {
918 self.walk_stmts(&Stmt::from_ast_nodes(b.stmts.iter()), false)
919 }
920
921 fn format_mod(
922 &mut self,
923 mod_kind: &ast::ModKind,
924 safety: ast::Safety,
925 vis: &ast::Visibility,
926 s: Span,
927 ident: symbol::Ident,
928 attrs: &[ast::Attribute],
929 ) {
930 let vis_str = utils::format_visibility(&self.get_context(), vis);
931 self.push_str(&*vis_str);
932 self.push_str(format_safety(safety));
933 self.push_str("mod ");
934 let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
936 self.push_str(&ident_str);
937
938 if let ast::ModKind::Loaded(ref items, ast::Inline::Yes, ref spans) = mod_kind {
939 let ast::ModSpans {
940 inner_span,
941 inject_use_span: _,
942 } = *spans;
943 match self.config.brace_style() {
944 BraceStyle::AlwaysNextLine => {
945 let indent_str = self.block_indent.to_string_with_newline(self.config);
946 self.push_str(&indent_str);
947 self.push_str("{");
948 }
949 _ => self.push_str(" {"),
950 }
951 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
953 let body_snippet =
954 self.snippet(mk_sp(mod_lo, source!(self, inner_span).hi() - BytePos(1)));
955 let body_snippet = body_snippet.trim();
956 if body_snippet.is_empty() {
957 self.push_str("}");
958 } else {
959 self.last_pos = mod_lo;
960 self.block_indent = self.block_indent.block_indent(self.config);
961 self.visit_attrs(attrs, ast::AttrStyle::Inner);
962 self.walk_mod_items(items);
963 let missing_span = self.next_span(inner_span.hi() - BytePos(1));
964 self.close_block(missing_span, false);
965 }
966 self.last_pos = source!(self, inner_span).hi();
967 } else {
968 self.push_str(";");
969 self.last_pos = source!(self, s).hi();
970 }
971 }
972
973 pub(crate) fn format_separate_mod(&mut self, m: &Module<'_>, end_pos: BytePos) {
974 self.block_indent = Indent::empty();
975 let skipped = self.visit_attrs(m.attrs(), ast::AttrStyle::Inner);
976 assert!(
977 !skipped,
978 "Skipping module must be handled before reaching this line."
979 );
980 self.walk_mod_items(&m.items);
981 self.format_missing_with_indent(end_pos);
982 }
983
984 pub(crate) fn skip_empty_lines(&mut self, end_pos: BytePos) {
985 while let Some(pos) = self
986 .snippet_provider
987 .opt_span_after(self.next_span(end_pos), "\n")
988 {
989 if let Some(snippet) = self.opt_snippet(self.next_span(pos)) {
990 if snippet.trim().is_empty() {
991 self.last_pos = pos;
992 } else {
993 return;
994 }
995 }
996 }
997 }
998
999 pub(crate) fn with_context<F>(&mut self, f: F) -> Option<String>
1000 where
1001 F: Fn(&RewriteContext<'_>) -> Option<String>,
1002 {
1003 let context = self.get_context();
1004 let result = f(&context);
1005
1006 self.macro_rewrite_failure |= context.macro_rewrite_failure.get();
1007 result
1008 }
1009
1010 pub(crate) fn get_context(&self) -> RewriteContext<'_> {
1011 RewriteContext {
1012 psess: self.psess,
1013 config: self.config,
1014 inside_macro: Rc::new(Cell::new(false)),
1015 use_block: Cell::new(false),
1016 is_if_else_block: Cell::new(false),
1017 force_one_line_chain: Cell::new(false),
1018 snippet_provider: self.snippet_provider,
1019 macro_rewrite_failure: Cell::new(false),
1020 is_macro_def: self.is_macro_def,
1021 report: self.report.clone(),
1022 skip_context: self.skip_context.clone(),
1023 skipped_range: self.skipped_range.clone(),
1024 }
1025 }
1026}