1use std::cell::{Cell, RefCell};2use std::rc::Rc;3use std::sync::Arc;45use rustc_ast::{ast, token::Delimiter, visit};6use rustc_span::{BytePos, Ident, Pos, Span, symbol};7use tracing::debug;89use 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};3334/// 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}4344impl 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 }5051 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 }6061 pub(crate) fn entire_snippet(&self) -> &str {62 self.big_snippet.as_str()63 }6465 pub(crate) fn start_pos(&self) -> BytePos {66 BytePos::from_usize(self.start_pos)67 }6869 pub(crate) fn end_pos(&self) -> BytePos {70 BytePos::from_usize(self.end_pos)71 }72}7374pub(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 indenting80 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 skip87 /// 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}9495impl<'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}104105impl<'b, 'a: 'b> FmtVisitor<'a> {106 fn set_parent_context(&mut self, context: &'a RewriteContext<'_>) {107 self.parent_context = Some(context);108 }109110 pub(crate) fn shape(&self) -> Shape {111 Shape::indented(self.block_indent, self.config)112 }113114 fn next_span(&self, hi: BytePos) -> Span {115 mk_sp(self.last_pos, hi)116 }117118 fn visit_stmt(&mut self, stmt: &Stmt<'_>, include_empty_semi: bool) {119 debug!("visit_stmt: {}", self.psess.span_to_debug_info(stmt.span()));120121 if stmt.is_empty() {122 // If the statement is empty, just skip over it. Before that, make sure any comment123 // snippet preceding the semicolon is picked up.124 let snippet = self.snippet(mk_sp(self.last_pos, stmt.span().lo()));125 let original_starts_with_newline = snippet126 .find(|c| c != ' ')127 .map_or(false, |i| starts_with_newline(&snippet[i..]));128 let snippet = snippet.trim();129 if !snippet.is_empty() {130 // FIXME(calebcartwright 2021-01-03) - This exists strictly to maintain legacy131 // formatting where rustfmt would preserve redundant semicolons on Items in a132 // statement position.133 // See comment within `walk_stmts` for more info134 if include_empty_semi {135 self.format_missing(stmt.span().hi());136 } else {137 if original_starts_with_newline {138 self.push_str("\n");139 }140141 self.push_str(&self.block_indent.to_string(self.config));142 self.push_str(snippet);143 }144 } else if include_empty_semi {145 self.push_str(";");146 }147 self.last_pos = stmt.span().hi();148 return;149 }150151 match stmt.as_ast_node().kind {152 ast::StmtKind::Item(ref item) => {153 self.visit_item(item);154 self.last_pos = stmt.span().hi();155 }156 ast::StmtKind::Let(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {157 let attrs = get_attrs_from_stmt(stmt.as_ast_node());158 if contains_skip(attrs) {159 self.push_skipped_with_span(160 attrs,161 stmt.span(),162 get_span_without_attrs(stmt.as_ast_node()),163 );164 } else {165 let shape = self.shape();166 let rewrite = self.with_context(|ctx| stmt.rewrite(ctx, shape));167 self.push_rewrite(stmt.span(), rewrite)168 }169 }170 ast::StmtKind::MacCall(ref mac_stmt) => {171 if self.visit_attrs(&mac_stmt.attrs, ast::AttrStyle::Outer) {172 self.push_skipped_with_span(173 &mac_stmt.attrs,174 stmt.span(),175 get_span_without_attrs(stmt.as_ast_node()),176 );177 } else {178 self.visit_mac(&mac_stmt.mac, MacroPosition::Statement);179 }180 self.format_missing(stmt.span().hi());181 }182 ast::StmtKind::Empty => (),183 }184 }185186 /// Remove spaces between the opening brace and the first statement or the inner attribute187 /// of the block.188 fn trim_spaces_after_opening_brace(189 &mut self,190 b: &ast::Block,191 inner_attrs: Option<&[ast::Attribute]>,192 ) {193 if let Some(first_stmt) = b.stmts.first() {194 let hi = inner_attrs195 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))196 .unwrap_or_else(|| first_stmt.span().lo());197 let missing_span = self.next_span(hi);198 let snippet = self.snippet(missing_span);199 let len = CommentCodeSlices::new(snippet)200 .next()201 .and_then(|(kind, _, s)| {202 if kind == CodeCharKind::Normal {203 s.rfind('\n')204 } else {205 None206 }207 });208 if let Some(len) = len {209 self.last_pos = self.last_pos + BytePos::from_usize(len);210 }211 }212 }213214 pub(crate) fn visit_block(215 &mut self,216 b: &ast::Block,217 inner_attrs: Option<&[ast::Attribute]>,218 has_braces: bool,219 ) {220 debug!("visit_block: {}", self.psess.span_to_debug_info(b.span));221222 // Check if this block has braces.223 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });224225 self.last_pos = self.last_pos + brace_compensation;226 self.block_indent = self.block_indent.block_indent(self.config);227 self.push_str("{");228 self.trim_spaces_after_opening_brace(b, inner_attrs);229230 // Format inner attributes if available.231 if let Some(attrs) = inner_attrs {232 self.visit_attrs(attrs, ast::AttrStyle::Inner);233 }234235 self.walk_block_stmts(b);236237 if let Some(stmt) = b.stmts.last() {238 if self.add_semi_on_last_block_stmt(stmt) {239 self.push_str(";");240 }241 }242243 let rest_span = self.next_span(b.span.hi());244 if out_of_file_lines_range!(self, rest_span) {245 self.push_str(self.snippet(rest_span));246 self.block_indent = self.block_indent.block_unindent(self.config);247 } else {248 // Ignore the closing brace.249 let missing_span = self.next_span(b.span.hi() - brace_compensation);250 self.close_block(missing_span, self.unindent_comment_on_closing_brace(b));251 }252 self.last_pos = source!(self, b.span).hi();253 }254255 fn close_block(&mut self, span: Span, unindent_comment: bool) {256 let config = self.config;257258 let mut last_hi = span.lo();259 let mut unindented = false;260 let mut prev_ends_with_newline = false;261 let mut extra_newline = false;262263 let skip_normal = |s: &str| {264 let trimmed = s.trim();265 trimmed.is_empty() || trimmed.chars().all(|c| c == ';')266 };267268 let comment_snippet = self.snippet(span);269270 let align_to_right = if unindent_comment && contains_comment(comment_snippet) {271 let first_lines = comment_snippet.splitn(2, '/').next().unwrap_or("");272 last_line_width(first_lines) > last_line_width(comment_snippet)273 } else {274 false275 };276277 for (kind, offset, sub_slice) in CommentCodeSlices::new(comment_snippet) {278 let sub_slice = transform_missing_snippet(config, sub_slice);279280 debug!("close_block: {:?} {:?} {:?}", kind, offset, sub_slice);281282 match kind {283 CodeCharKind::Comment => {284 if !unindented && unindent_comment && !align_to_right {285 unindented = true;286 self.block_indent = self.block_indent.block_unindent(config);287 }288 let span_in_between = mk_sp(last_hi, span.lo() + BytePos::from_usize(offset));289 let snippet_in_between = self.snippet(span_in_between);290 let mut comment_on_same_line = !snippet_in_between.contains('\n');291292 let mut comment_shape =293 Shape::indented(self.block_indent, config).comment(config);294 if self.config.style_edition() >= StyleEdition::Edition2024295 && comment_on_same_line296 {297 self.push_str(" ");298 // put the first line of the comment on the same line as the299 // block's last line300 match sub_slice.find('\n') {301 None => {302 self.push_str(&sub_slice);303 }304 Some(offset) if offset + 1 == sub_slice.len() => {305 self.push_str(&sub_slice[..offset]);306 }307 Some(offset) => {308 let first_line = &sub_slice[..offset];309 self.push_str(first_line);310 self.push_str(&self.block_indent.to_string_with_newline(config));311312 // put the other lines below it, shaping it as needed313 let other_lines = &sub_slice[offset + 1..];314 let comment_str =315 rewrite_comment(other_lines, false, comment_shape, config);316 match comment_str {317 Ok(ref s) => self.push_str(s),318 Err(_) => self.push_str(other_lines),319 }320 }321 }322 } else {323 if comment_on_same_line {324 // 1 = a space before `//`325 let offset_len = 1 + last_line_width(&self.buffer)326 .saturating_sub(self.block_indent.width());327 match comment_shape328 .visual_indent(offset_len)329 .sub_width_opt(offset_len)330 {331 Some(shp) => comment_shape = shp,332 None => comment_on_same_line = false,333 }334 };335336 if comment_on_same_line {337 self.push_str(" ");338 } else {339 if count_newlines(snippet_in_between) >= 2 || extra_newline {340 self.push_str("\n");341 }342 self.push_str(&self.block_indent.to_string_with_newline(config));343 }344345 let comment_str = rewrite_comment(&sub_slice, false, comment_shape, config);346 match comment_str {347 Ok(ref s) => self.push_str(s),348 Err(_) => self.push_str(&sub_slice),349 }350 }351 }352 CodeCharKind::Normal if skip_normal(&sub_slice) => {353 extra_newline = prev_ends_with_newline && sub_slice.contains('\n');354 continue;355 }356 CodeCharKind::Normal => {357 self.push_str(&self.block_indent.to_string_with_newline(config));358 self.push_str(sub_slice.trim());359 }360 }361 prev_ends_with_newline = sub_slice.ends_with('\n');362 extra_newline = false;363 last_hi = span.lo() + BytePos::from_usize(offset + sub_slice.len());364 }365 if unindented {366 self.block_indent = self.block_indent.block_indent(self.config);367 }368 self.block_indent = self.block_indent.block_unindent(self.config);369 self.push_str(&self.block_indent.to_string_with_newline(config));370 self.push_str("}");371 }372373 fn unindent_comment_on_closing_brace(&self, b: &ast::Block) -> bool {374 self.is_if_else_block && !b.stmts.is_empty()375 }376377 // Note that this only gets called for function definitions. Required methods378 // on traits do not get handled here.379 pub(crate) fn visit_fn(380 &mut self,381 ident: Ident,382 fk: visit::FnKind<'_>,383 fd: &ast::FnDecl,384 s: Span,385 defaultness: ast::Defaultness,386 inner_attrs: Option<&[ast::Attribute]>,387 ) {388 let indent = self.block_indent;389 let block;390 let rewrite = match fk {391 visit::FnKind::Fn(392 _,393 _,394 ast::Fn {395 body: Some(ref b), ..396 },397 ) => {398 block = b;399 self.rewrite_fn_before_block(400 indent,401 ident,402 &FnSig::from_fn_kind(&fk, fd, defaultness),403 mk_sp(s.lo(), b.span.lo()),404 )405 }406 _ => unreachable!(),407 };408409 if let Some((fn_str, fn_brace_style)) = rewrite {410 self.format_missing_with_indent(source!(self, s).lo());411412 if let Some(rw) = self.single_line_fn(&fn_str, block, inner_attrs) {413 self.push_str(&rw);414 self.last_pos = s.hi();415 return;416 }417418 self.push_str(&fn_str);419 match fn_brace_style {420 FnBraceStyle::SameLine => self.push_str(" "),421 FnBraceStyle::NextLine => {422 self.push_str(&self.block_indent.to_string_with_newline(self.config))423 }424 _ => unreachable!(),425 }426 self.last_pos = source!(self, block.span).lo();427 } else {428 self.format_missing(source!(self, block.span).lo());429 }430431 self.visit_block(block, inner_attrs, true)432 }433434 pub(crate) fn visit_item(&mut self, item: &ast::Item) {435 skip_out_of_file_lines_range_visitor!(self, item.span);436437 // This is where we bail out if there is a skip attribute. This is only438 // complex in the module case. It is complex because the module could be439 // in a separate file and there might be attributes in both files, but440 // the AST lumps them all together.441 let filtered_attrs;442 let mut attrs = &item.attrs;443 let skip_context_saved = self.skip_context.clone();444 self.skip_context.update_with_attrs(attrs);445446 let should_visit_node_again = match item.kind {447 // For use/extern crate items, skip rewriting attributes but check for a skip attribute.448 ast::ItemKind::Use(..) | ast::ItemKind::ExternCrate(..) => {449 if contains_skip(attrs) {450 self.push_skipped_with_span(attrs.as_slice(), item.span(), item.span());451 false452 } else {453 true454 }455 }456 // Module is inline, in this case we treat it like any other item.457 _ if !is_mod_decl(item) => {458 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {459 self.push_skipped_with_span(item.attrs.as_slice(), item.span(), item.span());460 false461 } else {462 true463 }464 }465 // Module is not inline, but should be skipped.466 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => false,467 // Module is not inline and should not be skipped. We want468 // to process only the attributes in the current file.469 ast::ItemKind::Mod(..) => {470 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());471 // Assert because if we should skip it should be caught by472 // the above case.473 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));474 attrs = &filtered_attrs;475 true476 }477 _ => {478 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {479 self.push_skipped_with_span(item.attrs.as_slice(), item.span(), item.span());480 false481 } else {482 true483 }484 }485 };486487 // TODO(calebcartwright): consider enabling box_patterns feature gate488 if should_visit_node_again {489 match item.kind {490 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),491 ast::ItemKind::Impl(ref iimpl) => {492 let block_indent = self.block_indent;493 let rw = self.with_context(|ctx| format_impl(ctx, item, iimpl, block_indent));494 self.push_rewrite(item.span, rw.ok());495 }496 ast::ItemKind::Trait(ref trait_kind) => {497 let block_indent = self.block_indent;498 let rw =499 self.with_context(|ctx| format_trait(ctx, item, trait_kind, block_indent));500 self.push_rewrite(item.span, rw.ok());501 }502 ast::ItemKind::TraitAlias(ref ta) => {503 let shape = Shape::indented(self.block_indent, self.config);504 let rw =505 format_trait_alias(&self.get_context(), ta, &item.vis, item.span, shape);506 self.push_rewrite(item.span, rw.ok());507 }508 ast::ItemKind::ExternCrate(..) => {509 let rw = rewrite_extern_crate(&self.get_context(), item, self.shape());510 let span = if attrs.is_empty() {511 item.span512 } else {513 mk_sp(attrs[0].span.lo(), item.span.hi())514 };515 self.push_rewrite(span, rw.ok());516 }517 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {518 self.visit_struct(&StructParts::from_item(item));519 }520 ast::ItemKind::Enum(ident, ref generics, ref def) => {521 self.format_missing_with_indent(source!(self, item.span).lo());522 self.visit_enum(ident, &item.vis, def, generics, item.span);523 self.last_pos = source!(self, item.span).hi();524 }525 ast::ItemKind::Mod(safety, ident, ref mod_kind) => {526 self.format_missing_with_indent(source!(self, item.span).lo());527 self.format_mod(mod_kind, safety, &item.vis, item.span, ident, attrs);528 }529 ast::ItemKind::MacCall(ref mac) => {530 self.visit_mac(mac, MacroPosition::Item);531 }532 ast::ItemKind::ForeignMod(ref foreign_mod) => {533 self.format_missing_with_indent(source!(self, item.span).lo());534 self.format_foreign_mod(foreign_mod, item.span);535 }536 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {537 self.visit_static(&StaticParts::from_item(item));538 }539 ast::ItemKind::ConstBlock(ast::ConstBlockItem {540 id: _,541 span,542 ref block,543 }) => {544 let context = &self.get_context();545 let offset = self.block_indent;546 self.push_rewrite(547 item.span,548 block549 .rewrite(550 context,551 Shape::legacy(552 context.budget(offset.block_indent),553 offset.block_only(),554 ),555 )556 .map(|rhs| {557 recover_comment_removed(format!("const {rhs}"), span, context)558 }),559 );560 }561 ast::ItemKind::Fn(ref fn_kind) => {562 let ast::Fn {563 defaultness,564 ref sig,565 ident,566 ref generics,567 ref body,568 ..569 } = **fn_kind;570 if body.is_some() {571 let inner_attrs = inner_attributes(&item.attrs);572 let fn_ctxt = match sig.header.ext {573 ast::Extern::None => visit::FnCtxt::Free,574 _ => visit::FnCtxt::Foreign,575 };576 self.visit_fn(577 ident,578 visit::FnKind::Fn(fn_ctxt, &item.vis, fn_kind),579 &sig.decl,580 item.span,581 defaultness,582 Some(&inner_attrs),583 )584 } else {585 let indent = self.block_indent;586 let rewrite = self587 .rewrite_required_fn(588 indent,589 ident,590 sig,591 &item.vis,592 generics,593 defaultness,594 item.span,595 )596 .ok();597 self.push_rewrite(item.span, rewrite);598 }599 }600 ast::ItemKind::TyAlias(ref ty_alias) => {601 use ItemVisitorKind::Item;602 self.visit_ty_alias_kind(ty_alias, &item.vis, Item, item.span);603 }604 ast::ItemKind::GlobalAsm(..) => {605 let snippet = Some(self.snippet(item.span).to_owned());606 self.push_rewrite(item.span, snippet);607 }608 ast::ItemKind::MacroDef(ident, ref def) => {609 let rewrite = rewrite_macro_def(610 &self.get_context(),611 self.shape(),612 self.block_indent,613 def,614 ident,615 &item.vis,616 item.span,617 )618 .ok();619 self.push_rewrite(item.span, rewrite);620 }621 ast::ItemKind::Delegation(..) | ast::ItemKind::DelegationMac(..) => {622 // TODO: rewrite delegation items once syntax is established.623 // For now, leave the contents of the Span unformatted.624 self.push_rewrite(item.span, None)625 }626 };627 }628 self.skip_context = skip_context_saved;629 }630631 fn visit_ty_alias_kind(632 &mut self,633 ty_kind: &ast::TyAlias,634 vis: &ast::Visibility,635 visitor_kind: ItemVisitorKind,636 span: Span,637 ) {638 let rewrite = rewrite_type_alias(639 ty_kind,640 vis,641 &self.get_context(),642 self.block_indent,643 visitor_kind,644 span,645 )646 .ok();647 self.push_rewrite(span, rewrite);648 }649650 fn visit_assoc_item(&mut self, ai: &ast::AssocItem, visitor_kind: ItemVisitorKind) {651 use ItemVisitorKind::*;652 let assoc_ctxt = match visitor_kind {653 AssocTraitItem => visit::AssocCtxt::Trait,654 // There is no difference between trait and inherent assoc item formatting655 AssocImplItem => visit::AssocCtxt::Impl { of_trait: false },656 _ => unreachable!(),657 };658 // TODO(calebcartwright): Not sure the skip spans are correct659 let skip_span = ai.span;660 skip_out_of_file_lines_range_visitor!(self, ai.span);661662 if self.visit_attrs(&ai.attrs, ast::AttrStyle::Outer) {663 self.push_skipped_with_span(ai.attrs.as_slice(), skip_span, skip_span);664 return;665 }666667 // TODO(calebcartwright): consider enabling box_patterns feature gate668 match (&ai.kind, assoc_ctxt) {669 (ast::AssocItemKind::Const(c), visit::AssocCtxt::Trait) => {670 self.visit_static(&StaticParts::from_trait_item(ai, c.ident))671 }672 (ast::AssocItemKind::Const(c), visit::AssocCtxt::Impl { .. }) => {673 self.visit_static(&StaticParts::from_impl_item(ai, c.ident))674 }675 (ast::AssocItemKind::Fn(ref fn_kind), _) => {676 let ast::Fn {677 defaultness,678 ref sig,679 ident,680 ref generics,681 ref body,682 ..683 } = **fn_kind;684 if body.is_some() {685 let inner_attrs = inner_attributes(&ai.attrs);686 let fn_ctxt = visit::FnCtxt::Assoc(assoc_ctxt);687 self.visit_fn(688 ident,689 visit::FnKind::Fn(fn_ctxt, &ai.vis, fn_kind),690 &sig.decl,691 ai.span,692 defaultness,693 Some(&inner_attrs),694 );695 } else {696 let indent = self.block_indent;697 let rewrite = self698 .rewrite_required_fn(699 indent,700 fn_kind.ident,701 sig,702 &ai.vis,703 generics,704 defaultness,705 ai.span,706 )707 .ok();708 self.push_rewrite(ai.span, rewrite);709 }710 }711 (ast::AssocItemKind::Type(ref ty_alias), _) => {712 self.visit_ty_alias_kind(ty_alias, &ai.vis, visitor_kind, ai.span);713 }714 (ast::AssocItemKind::MacCall(ref mac), _) => {715 self.visit_mac(mac, MacroPosition::Item);716 }717 (ast::AssocItemKind::Delegation(_) | ast::AssocItemKind::DelegationMac(_), _) => {718 // TODO(ytmimi) #![feature(fn_delegation)]719 // add formatting for `AssocItemKind::Delegation` and `AssocItemKind::DelegationMac`720 self.push_rewrite(ai.span, None);721 }722 }723 }724725 pub(crate) fn visit_trait_item(&mut self, ti: &ast::AssocItem) {726 self.visit_assoc_item(ti, ItemVisitorKind::AssocTraitItem);727 }728729 pub(crate) fn visit_impl_item(&mut self, ii: &ast::AssocItem) {730 self.visit_assoc_item(ii, ItemVisitorKind::AssocImplItem);731 }732733 fn visit_mac(&mut self, mac: &ast::MacCall, pos: MacroPosition) {734 skip_out_of_file_lines_range_visitor!(self, mac.span());735736 // 1 = ;737 let shape = self.shape().saturating_sub_width(1);738 let rewrite = self.with_context(|ctx| rewrite_macro(mac, ctx, shape, pos).ok());739 // As of v638 of the rustc-ap-* crates, the associated span no longer includes740 // the trailing semicolon. This determines the correct span to ensure scenarios741 // with whitespace between the delimiters and trailing semi (i.e. `foo!(abc) ;`)742 // are formatted correctly.743 let (span, rewrite) = match macro_style(mac, &self.get_context()) {744 Delimiter::Bracket | Delimiter::Parenthesis if MacroPosition::Item == pos => {745 let search_span = mk_sp(mac.span().hi(), self.snippet_provider.end_pos());746 let hi = self.snippet_provider.span_before(search_span, ";");747 let target_span = mk_sp(mac.span().lo(), hi + BytePos(1));748 let rewrite = rewrite.map(|rw| {749 if !rw.ends_with(';') {750 format!("{};", rw)751 } else {752 rw753 }754 });755 (target_span, rewrite)756 }757 _ => (mac.span(), rewrite),758 };759760 self.push_rewrite(span, rewrite);761 }762763 pub(crate) fn push_str(&mut self, s: &str) {764 self.line_number += count_newlines(s);765 self.buffer.push_str(s);766 }767768 #[allow(clippy::needless_pass_by_value)]769 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {770 if let Some(ref s) = rewrite {771 self.push_str(s);772 } else {773 let snippet = self.snippet(span);774 self.push_str(snippet.trim());775 }776 self.last_pos = source!(self, span).hi();777 }778779 pub(crate) fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {780 self.format_missing_with_indent(source!(self, span).lo());781 self.push_rewrite_inner(span, rewrite);782 }783784 pub(crate) fn push_skipped_with_span(785 &mut self,786 attrs: &[ast::Attribute],787 item_span: Span,788 main_span: Span,789 ) {790 self.format_missing_with_indent(source!(self, item_span).lo());791 // do not take into account the lines with attributes as part of the skipped range792 let attrs_end = attrs793 .iter()794 .map(|attr| self.psess.line_of_byte_pos(attr.span.hi()))795 .max()796 .unwrap_or(1);797 let first_line = self.psess.line_of_byte_pos(main_span.lo());798 // Statement can start after some newlines and/or spaces799 // or it can be on the same line as the last attribute.800 // So here we need to take a minimum between the two.801 let lo = std::cmp::min(attrs_end + 1, first_line);802 self.push_rewrite_inner(item_span, None);803 let hi = self.line_number + 1;804 self.skipped_range.borrow_mut().push((lo, hi));805 }806807 pub(crate) fn from_context(ctx: &'a RewriteContext<'_>) -> FmtVisitor<'a> {808 let mut visitor = FmtVisitor::from_psess(809 ctx.psess,810 ctx.config,811 ctx.snippet_provider,812 ctx.report.clone(),813 );814 visitor.skip_context.update(ctx.skip_context.clone());815 visitor.set_parent_context(ctx);816 visitor817 }818819 pub(crate) fn from_psess(820 psess: &'a ParseSess,821 config: &'a Config,822 snippet_provider: &'a SnippetProvider,823 report: FormatReport,824 ) -> FmtVisitor<'a> {825 let mut skip_context = SkipContext::default();826 let mut macro_names = Vec::new();827 for macro_selector in config.skip_macro_invocations().0 {828 match macro_selector {829 MacroSelector::Name(name) => macro_names.push(name.to_string()),830 MacroSelector::All => skip_context.macros.skip_all(),831 }832 }833 skip_context.macros.extend(macro_names);834 FmtVisitor {835 parent_context: None,836 psess,837 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),838 last_pos: BytePos(0),839 block_indent: Indent::empty(),840 config,841 is_if_else_block: false,842 is_loop_block: false,843 snippet_provider,844 line_number: 0,845 skipped_range: Rc::new(RefCell::new(vec![])),846 is_macro_def: false,847 macro_rewrite_failure: false,848 report,849 skip_context,850 }851 }852853 pub(crate) fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {854 self.snippet_provider.span_to_snippet(span)855 }856857 pub(crate) fn snippet(&'b self, span: Span) -> &'a str {858 self.opt_snippet(span).unwrap()859 }860861 // Returns true if we should skip the following item.862 pub(crate) fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {863 for attr in attrs {864 if attr.has_name(depr_skip_annotation()) {865 let file_name = self.psess.span_to_filename(attr.span);866 self.report.append(867 file_name,868 vec![FormattingError::from_span(869 attr.span,870 self.psess,871 ErrorKind::DeprecatedAttr,872 )],873 );874 } else {875 match &attr.kind {876 ast::AttrKind::Normal(ref normal)877 if self.is_unknown_rustfmt_attr(&normal.item.path.segments) =>878 {879 let file_name = self.psess.span_to_filename(attr.span);880 self.report.append(881 file_name,882 vec![FormattingError::from_span(883 attr.span,884 self.psess,885 ErrorKind::BadAttr,886 )],887 );888 }889 _ => (),890 }891 }892 }893 if contains_skip(attrs) {894 return true;895 }896897 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();898 if attrs.is_empty() {899 return false;900 }901902 let rewrite = attrs.rewrite(&self.get_context(), self.shape());903 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());904 self.push_rewrite(span, rewrite);905906 false907 }908909 fn is_unknown_rustfmt_attr(&self, segments: &[ast::PathSegment]) -> bool {910 if segments[0].ident.to_string() != "rustfmt" {911 return false;912 }913 !is_skip_attr(segments)914 }915916 fn walk_mod_items(&mut self, items: &[Box<ast::Item>]) {917 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(items));918 }919920 fn walk_stmts(&mut self, stmts: &[Stmt<'_>], include_current_empty_semi: bool) {921 if stmts.is_empty() {922 return;923 }924925 // Extract leading `use ...;`.926 let items: Vec<_> = stmts927 .iter()928 .take_while(|stmt| stmt.to_item().map_or(false, is_use_item))929 .filter_map(|stmt| stmt.to_item())930 .collect();931932 if items.is_empty() {933 self.visit_stmt(&stmts[0], include_current_empty_semi);934935 // FIXME(calebcartwright 2021-01-03) - This exists strictly to maintain legacy936 // formatting where rustfmt would preserve redundant semicolons on Items in a937 // statement position.938 //939 // Starting in rustc-ap-* v692 (~2020-12-01) the rustc parser now parses this as940 // two separate statements (Item and Empty kinds), whereas before it was parsed as941 // a single statement with the statement's span including the redundant semicolon.942 //943 // rustfmt typically tosses unnecessary/redundant semicolons, and eventually we944 // should toss these as well, but doing so at this time would945 // break the Stability Guarantee946 // N.B. This could be updated to utilize the version gates.947 let include_next_empty = if stmts.len() > 1 {948 matches!(949 (&stmts[0].as_ast_node().kind, &stmts[1].as_ast_node().kind),950 (ast::StmtKind::Item(_), ast::StmtKind::Empty)951 )952 } else {953 false954 };955956 self.walk_stmts(&stmts[1..], include_next_empty);957 } else {958 self.visit_items_with_reordering(&items);959 self.walk_stmts(&stmts[items.len()..], false);960 }961 }962963 fn walk_block_stmts(&mut self, b: &ast::Block) {964 self.walk_stmts(&Stmt::from_ast_nodes(b.stmts.iter()), false)965 }966967 fn format_mod(968 &mut self,969 mod_kind: &ast::ModKind,970 safety: ast::Safety,971 vis: &ast::Visibility,972 s: Span,973 ident: symbol::Ident,974 attrs: &[ast::Attribute],975 ) {976 let vis_str = utils::format_visibility(&self.get_context(), vis);977 self.push_str(&*vis_str);978 self.push_str(format_safety(safety));979 self.push_str("mod ");980 // Calling `to_owned()` to work around borrow checker.981 let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();982 self.push_str(&ident_str);983984 if let ast::ModKind::Loaded(ref items, ast::Inline::Yes, ref spans) = mod_kind {985 let ast::ModSpans {986 inner_span,987 inject_use_span: _,988 } = *spans;989 match self.config.brace_style() {990 BraceStyle::AlwaysNextLine => {991 let indent_str = self.block_indent.to_string_with_newline(self.config);992 self.push_str(&indent_str);993 self.push_str("{");994 }995 _ => self.push_str(" {"),996 }997 // Hackery to account for the closing }.998 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");999 let body_snippet =1000 self.snippet(mk_sp(mod_lo, source!(self, inner_span).hi() - BytePos(1)));1001 let body_snippet = body_snippet.trim();1002 if body_snippet.is_empty() {1003 self.push_str("}");1004 } else {1005 self.last_pos = mod_lo;1006 self.block_indent = self.block_indent.block_indent(self.config);1007 self.visit_attrs(attrs, ast::AttrStyle::Inner);1008 self.walk_mod_items(items);1009 let missing_span = self.next_span(inner_span.hi() - BytePos(1));1010 self.close_block(missing_span, false);1011 }1012 self.last_pos = source!(self, inner_span).hi();1013 } else {1014 self.push_str(";");1015 self.last_pos = source!(self, s).hi();1016 }1017 }10181019 pub(crate) fn format_separate_mod(&mut self, m: &Module<'_>, end_pos: BytePos) {1020 self.block_indent = Indent::empty();1021 let skipped = self.visit_attrs(m.attrs(), ast::AttrStyle::Inner);1022 assert!(1023 !skipped,1024 "Skipping module must be handled before reaching this line."1025 );1026 self.walk_mod_items(&m.items);1027 self.format_missing_with_indent(end_pos);1028 }10291030 pub(crate) fn skip_empty_lines(&mut self, end_pos: BytePos) {1031 while let Some(pos) = self1032 .snippet_provider1033 .opt_span_after(self.next_span(end_pos), "\n")1034 {1035 if let Some(snippet) = self.opt_snippet(self.next_span(pos)) {1036 if snippet.trim().is_empty() {1037 self.last_pos = pos;1038 } else {1039 return;1040 }1041 }1042 }1043 }10441045 pub(crate) fn with_context<T>(&mut self, f: impl Fn(&RewriteContext<'_>) -> T) -> T {1046 let context = self.get_context();1047 let result = f(&context);10481049 self.macro_rewrite_failure |= context.macro_rewrite_failure.get();1050 result1051 }10521053 pub(crate) fn get_context(&self) -> RewriteContext<'_> {1054 RewriteContext {1055 psess: self.psess,1056 config: self.config,1057 inside_macro: Rc::new(Cell::new(false)),1058 use_block: Cell::new(false),1059 is_if_else_block: Cell::new(false),1060 is_loop_block: Cell::new(false),1061 force_one_line_chain: Cell::new(false),1062 snippet_provider: self.snippet_provider,1063 macro_rewrite_failure: Cell::new(false),1064 is_macro_def: self.is_macro_def,1065 report: self.report.clone(),1066 skip_context: self.skip_context.clone(),1067 skipped_range: self.skipped_range.clone(),1068 }1069 }10701071 fn add_semi_on_last_block_stmt(&self, stmt: &ast::Stmt) -> bool {1072 let ast::StmtKind::Expr(expr) = &stmt.kind else {1073 return false;1074 };10751076 if self.is_macro_def {1077 return false;1078 }10791080 match expr.kind {1081 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {1082 self.config.trailing_semicolon()1083 }10841085 // TODO[reviewer-help]: This is roughly "does it end in a1086 // curly". There might be a helper for this, or cases I'm1087 // missing.1088 ast::ExprKind::Loop(..)1089 | ast::ExprKind::While(..)1090 | ast::ExprKind::ForLoop { .. }1091 | ast::ExprKind::Let(..)1092 | ast::ExprKind::If(..)1093 | ast::ExprKind::Match(..) => false,10941095 _ => {1096 // Checking the edition as before 2024 the lack of a1097 // semicolon could impact temporary lifetimes[1].1098 //1099 // 1: https://rust-lang.github.io/rfcs/1100 // 3606-temporary-lifetimes-in-tail-expressions.html1101 let allowed_to_add_semi = self.is_loop_block1102 && self.config.edition() >= Edition::Edition20241103 && self.config.style_edition() >= StyleEdition::Edition2027;11041105 allowed_to_add_semi && self.config.trailing_semicolon()1106 }1107 }1108 }1109}