]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Release 1.4.0
[rust.git] / src / visitor.rs
1 use std::cell::RefCell;
2
3 use syntax::parse::ParseSess;
4 use syntax::source_map::{self, BytePos, Pos, SourceMap, Span};
5 use syntax::{ast, visit};
6
7 use crate::attr::*;
8 use crate::comment::{rewrite_comment, CodeCharKind, CommentCodeSlices};
9 use crate::config::{BraceStyle, Config};
10 use crate::coverage::transform_missing_snippet;
11 use crate::items::{
12     format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item,
13     rewrite_associated_impl_type, rewrite_associated_type, rewrite_existential_impl_type,
14     rewrite_existential_type, rewrite_extern_crate, rewrite_type_alias, FnBraceStyle, FnSig,
15     StaticParts, StructParts,
16 };
17 use crate::macros::{rewrite_macro, rewrite_macro_def, MacroPosition};
18 use crate::rewrite::{Rewrite, RewriteContext};
19 use crate::shape::{Indent, Shape};
20 use crate::skip::{is_skip_attr, SkipContext};
21 use crate::source_map::{LineRangeUtils, SpanUtils};
22 use crate::spanned::Spanned;
23 use crate::stmt::Stmt;
24 use crate::utils::{
25     self, contains_skip, count_newlines, depr_skip_annotation, inner_attributes, last_line_width,
26     mk_sp, ptr_vec_to_ref_vec, rewrite_ident, stmt_expr,
27 };
28 use crate::{ErrorKind, FormatReport, FormattingError};
29
30 /// Creates a string slice corresponding to the specified span.
31 pub(crate) struct SnippetProvider<'a> {
32     /// A pointer to the content of the file we are formatting.
33     big_snippet: &'a str,
34     /// A position of the start of `big_snippet`, used as an offset.
35     start_pos: usize,
36 }
37
38 impl<'a> SnippetProvider<'a> {
39     pub(crate) fn span_to_snippet(&self, span: Span) -> Option<&str> {
40         let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
41         let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
42         Some(&self.big_snippet[start_index..end_index])
43     }
44
45     pub(crate) fn new(start_pos: BytePos, big_snippet: &'a str) -> Self {
46         let start_pos = start_pos.to_usize();
47         SnippetProvider {
48             big_snippet,
49             start_pos,
50         }
51     }
52 }
53
54 pub(crate) struct FmtVisitor<'a> {
55     parent_context: Option<&'a RewriteContext<'a>>,
56     pub(crate) parse_session: &'a ParseSess,
57     pub(crate) source_map: &'a SourceMap,
58     pub(crate) buffer: String,
59     pub(crate) last_pos: BytePos,
60     // FIXME: use an RAII util or closure for indenting
61     pub(crate) block_indent: Indent,
62     pub(crate) config: &'a Config,
63     pub(crate) is_if_else_block: bool,
64     pub(crate) snippet_provider: &'a SnippetProvider<'a>,
65     pub(crate) line_number: usize,
66     /// List of 1-based line ranges which were annotated with skip
67     /// Both bounds are inclusifs.
68     pub(crate) skipped_range: Vec<(usize, usize)>,
69     pub(crate) macro_rewrite_failure: bool,
70     pub(crate) report: FormatReport,
71     pub(crate) skip_context: SkipContext,
72 }
73
74 impl<'a> Drop for FmtVisitor<'a> {
75     fn drop(&mut self) {
76         if let Some(ctx) = self.parent_context {
77             if self.macro_rewrite_failure {
78                 ctx.macro_rewrite_failure.replace(true);
79             }
80         }
81     }
82 }
83
84 impl<'b, 'a: 'b> FmtVisitor<'a> {
85     fn set_parent_context(&mut self, context: &'a RewriteContext<'_>) {
86         self.parent_context = Some(context);
87     }
88
89     pub(crate) fn shape(&self) -> Shape {
90         Shape::indented(self.block_indent, self.config)
91     }
92
93     fn next_span(&self, hi: BytePos) -> Span {
94         mk_sp(self.last_pos, hi)
95     }
96
97     fn visit_stmt(&mut self, stmt: &Stmt<'_>) {
98         debug!(
99             "visit_stmt: {:?} {:?}",
100             self.source_map.lookup_char_pos(stmt.span().lo()),
101             self.source_map.lookup_char_pos(stmt.span().hi())
102         );
103
104         match stmt.as_ast_node().node {
105             ast::StmtKind::Item(ref item) => {
106                 self.visit_item(item);
107                 // Handle potential `;` after the item.
108                 self.format_missing(stmt.span().hi());
109             }
110             ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
111                 let attrs = get_attrs_from_stmt(stmt.as_ast_node());
112                 if contains_skip(attrs) {
113                     self.push_skipped_with_span(
114                         attrs,
115                         stmt.span(),
116                         get_span_without_attrs(stmt.as_ast_node()),
117                     );
118                 } else {
119                     let shape = self.shape();
120                     let rewrite = self.with_context(|ctx| stmt.rewrite(&ctx, shape));
121                     self.push_rewrite(stmt.span(), rewrite)
122                 }
123             }
124             ast::StmtKind::Mac(ref mac) => {
125                 let (ref mac, _macro_style, ref attrs) = **mac;
126                 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
127                     self.push_skipped_with_span(
128                         attrs,
129                         stmt.span(),
130                         get_span_without_attrs(stmt.as_ast_node()),
131                     );
132                 } else {
133                     self.visit_mac(mac, None, MacroPosition::Statement);
134                 }
135                 self.format_missing(stmt.span().hi());
136             }
137         }
138     }
139
140     /// Remove spaces between the opening brace and the first statement or the inner attribute
141     /// of the block.
142     fn trim_spaces_after_opening_brace(
143         &mut self,
144         b: &ast::Block,
145         inner_attrs: Option<&[ast::Attribute]>,
146     ) {
147         if let Some(first_stmt) = b.stmts.first() {
148             let hi = inner_attrs
149                 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
150                 .unwrap_or_else(|| first_stmt.span().lo());
151             let missing_span = self.next_span(hi);
152             let snippet = self.snippet(missing_span);
153             let len = CommentCodeSlices::new(snippet)
154                 .nth(0)
155                 .and_then(|(kind, _, s)| {
156                     if kind == CodeCharKind::Normal {
157                         s.rfind('\n')
158                     } else {
159                         None
160                     }
161                 });
162             if let Some(len) = len {
163                 self.last_pos = self.last_pos + BytePos::from_usize(len);
164             }
165         }
166     }
167
168     pub(crate) fn visit_block(
169         &mut self,
170         b: &ast::Block,
171         inner_attrs: Option<&[ast::Attribute]>,
172         has_braces: bool,
173     ) {
174         debug!(
175             "visit_block: {:?} {:?}",
176             self.source_map.lookup_char_pos(b.span.lo()),
177             self.source_map.lookup_char_pos(b.span.hi())
178         );
179
180         // Check if this block has braces.
181         let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
182
183         self.last_pos = self.last_pos + brace_compensation;
184         self.block_indent = self.block_indent.block_indent(self.config);
185         self.push_str("{");
186         self.trim_spaces_after_opening_brace(b, inner_attrs);
187
188         // Format inner attributes if available.
189         if let Some(attrs) = inner_attrs {
190             self.visit_attrs(attrs, ast::AttrStyle::Inner);
191         }
192
193         self.walk_block_stmts(b);
194
195         if !b.stmts.is_empty() {
196             if let Some(expr) = stmt_expr(&b.stmts[b.stmts.len() - 1]) {
197                 if utils::semicolon_for_expr(&self.get_context(), expr) {
198                     self.push_str(";");
199                 }
200             }
201         }
202
203         let rest_span = self.next_span(b.span.hi());
204         if out_of_file_lines_range!(self, rest_span) {
205             self.push_str(self.snippet(rest_span));
206             self.block_indent = self.block_indent.block_unindent(self.config);
207         } else {
208             // Ignore the closing brace.
209             let missing_span = self.next_span(b.span.hi() - brace_compensation);
210             self.close_block(missing_span, self.unindent_comment_on_closing_brace(b));
211         }
212         self.last_pos = source!(self, b.span).hi();
213     }
214
215     fn close_block(&mut self, span: Span, unindent_comment: bool) {
216         let config = self.config;
217
218         let mut last_hi = span.lo();
219         let mut unindented = false;
220         let mut prev_ends_with_newline = false;
221         let mut extra_newline = false;
222
223         let skip_normal = |s: &str| {
224             let trimmed = s.trim();
225             trimmed.is_empty() || trimmed.chars().all(|c| c == ';')
226         };
227
228         for (kind, offset, sub_slice) in CommentCodeSlices::new(self.snippet(span)) {
229             let sub_slice = transform_missing_snippet(config, sub_slice);
230
231             debug!("close_block: {:?} {:?} {:?}", kind, offset, sub_slice);
232
233             match kind {
234                 CodeCharKind::Comment => {
235                     if !unindented && unindent_comment {
236                         unindented = true;
237                         self.block_indent = self.block_indent.block_unindent(config);
238                     }
239                     let span_in_between = mk_sp(last_hi, span.lo() + BytePos::from_usize(offset));
240                     let snippet_in_between = self.snippet(span_in_between);
241                     let mut comment_on_same_line = !snippet_in_between.contains("\n");
242
243                     let mut comment_shape =
244                         Shape::indented(self.block_indent, config).comment(config);
245                     if comment_on_same_line {
246                         // 1 = a space before `//`
247                         let offset_len = 1 + last_line_width(&self.buffer)
248                             .saturating_sub(self.block_indent.width());
249                         match comment_shape
250                             .visual_indent(offset_len)
251                             .sub_width(offset_len)
252                         {
253                             Some(shp) => comment_shape = shp,
254                             None => comment_on_same_line = false,
255                         }
256                     };
257
258                     if comment_on_same_line {
259                         self.push_str(" ");
260                     } else {
261                         if count_newlines(snippet_in_between) >= 2 || extra_newline {
262                             self.push_str("\n");
263                         }
264                         self.push_str(&self.block_indent.to_string_with_newline(config));
265                     }
266
267                     let comment_str = rewrite_comment(&sub_slice, false, comment_shape, config);
268                     match comment_str {
269                         Some(ref s) => self.push_str(s),
270                         None => self.push_str(&sub_slice),
271                     }
272                 }
273                 CodeCharKind::Normal if skip_normal(&sub_slice) => {
274                     extra_newline = prev_ends_with_newline && sub_slice.contains('\n');
275                     continue;
276                 }
277                 CodeCharKind::Normal => {
278                     self.push_str(&self.block_indent.to_string_with_newline(config));
279                     self.push_str(sub_slice.trim());
280                 }
281             }
282             prev_ends_with_newline = sub_slice.ends_with('\n');
283             extra_newline = false;
284             last_hi = span.lo() + BytePos::from_usize(offset + sub_slice.len());
285         }
286         if unindented {
287             self.block_indent = self.block_indent.block_indent(self.config);
288         }
289         self.block_indent = self.block_indent.block_unindent(self.config);
290         self.push_str(&self.block_indent.to_string_with_newline(config));
291         self.push_str("}");
292     }
293
294     fn unindent_comment_on_closing_brace(&self, b: &ast::Block) -> bool {
295         self.is_if_else_block && !b.stmts.is_empty()
296     }
297
298     // Note that this only gets called for function definitions. Required methods
299     // on traits do not get handled here.
300     fn visit_fn(
301         &mut self,
302         fk: visit::FnKind<'_>,
303         generics: &ast::Generics,
304         fd: &ast::FnDecl,
305         s: Span,
306         defaultness: ast::Defaultness,
307         inner_attrs: Option<&[ast::Attribute]>,
308     ) {
309         let indent = self.block_indent;
310         let block;
311         let rewrite = match fk {
312             visit::FnKind::ItemFn(ident, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
313                 block = b;
314                 self.rewrite_fn_before_block(
315                     indent,
316                     ident,
317                     &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
318                     mk_sp(s.lo(), b.span.lo()),
319                 )
320             }
321             visit::FnKind::Closure(_) => unreachable!(),
322         };
323
324         if let Some((fn_str, fn_brace_style)) = rewrite {
325             self.format_missing_with_indent(source!(self, s).lo());
326
327             if let Some(rw) = self.single_line_fn(&fn_str, block, inner_attrs) {
328                 self.push_str(&rw);
329                 self.last_pos = s.hi();
330                 return;
331             }
332
333             self.push_str(&fn_str);
334             match fn_brace_style {
335                 FnBraceStyle::SameLine => self.push_str(" "),
336                 FnBraceStyle::NextLine => {
337                     self.push_str(&self.block_indent.to_string_with_newline(self.config))
338                 }
339                 _ => unreachable!(),
340             }
341             self.last_pos = source!(self, block.span).lo();
342         } else {
343             self.format_missing(source!(self, block.span).lo());
344         }
345
346         self.visit_block(block, inner_attrs, true)
347     }
348
349     pub(crate) fn visit_item(&mut self, item: &ast::Item) {
350         skip_out_of_file_lines_range_visitor!(self, item.span);
351
352         // This is where we bail out if there is a skip attribute. This is only
353         // complex in the module case. It is complex because the module could be
354         // in a separate file and there might be attributes in both files, but
355         // the AST lumps them all together.
356         let filtered_attrs;
357         let mut attrs = &item.attrs;
358         let skip_context_saved = self.skip_context.clone();
359         self.skip_context.update_with_attrs(&attrs);
360
361         let should_visit_node_again = match item.node {
362             // For use/extern crate items, skip rewriting attributes but check for a skip attribute.
363             ast::ItemKind::Use(..) | ast::ItemKind::ExternCrate(_) => {
364                 if contains_skip(attrs) {
365                     self.push_skipped_with_span(attrs.as_slice(), item.span(), item.span());
366                     false
367                 } else {
368                     true
369                 }
370             }
371             // Module is inline, in this case we treat it like any other item.
372             _ if !is_mod_decl(item) => {
373                 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
374                     self.push_skipped_with_span(item.attrs.as_slice(), item.span(), item.span());
375                     false
376                 } else {
377                     true
378                 }
379             }
380             // Module is not inline, but should be skipped.
381             ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => false,
382             // Module is not inline and should not be skipped. We want
383             // to process only the attributes in the current file.
384             ast::ItemKind::Mod(..) => {
385                 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
386                 // Assert because if we should skip it should be caught by
387                 // the above case.
388                 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
389                 attrs = &filtered_attrs;
390                 true
391             }
392             _ => {
393                 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
394                     self.push_skipped_with_span(item.attrs.as_slice(), item.span(), item.span());
395                     false
396                 } else {
397                     true
398                 }
399             }
400         };
401
402         if should_visit_node_again {
403             match item.node {
404                 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
405                 ast::ItemKind::Impl(..) => {
406                     let block_indent = self.block_indent;
407                     let rw = self.with_context(|ctx| format_impl(&ctx, item, block_indent));
408                     self.push_rewrite(item.span, rw);
409                 }
410                 ast::ItemKind::Trait(..) => {
411                     let block_indent = self.block_indent;
412                     let rw = self.with_context(|ctx| format_trait(&ctx, item, block_indent));
413                     self.push_rewrite(item.span, rw);
414                 }
415                 ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => {
416                     let shape = Shape::indented(self.block_indent, self.config);
417                     let rw = format_trait_alias(
418                         &self.get_context(),
419                         item.ident,
420                         &item.vis,
421                         generics,
422                         generic_bounds,
423                         shape,
424                     );
425                     self.push_rewrite(item.span, rw);
426                 }
427                 ast::ItemKind::ExternCrate(_) => {
428                     let rw = rewrite_extern_crate(&self.get_context(), item, self.shape());
429                     let span = if attrs.is_empty() {
430                         item.span
431                     } else {
432                         mk_sp(attrs[0].span.lo(), item.span.hi())
433                     };
434                     self.push_rewrite(span, rw);
435                 }
436                 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
437                     self.visit_struct(&StructParts::from_item(item));
438                 }
439                 ast::ItemKind::Enum(ref def, ref generics) => {
440                     self.format_missing_with_indent(source!(self, item.span).lo());
441                     self.visit_enum(item.ident, &item.vis, def, generics, item.span);
442                     self.last_pos = source!(self, item.span).hi();
443                 }
444                 ast::ItemKind::Mod(ref module) => {
445                     let is_inline = !is_mod_decl(item);
446                     self.format_missing_with_indent(source!(self, item.span).lo());
447                     self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
448                 }
449                 ast::ItemKind::Mac(ref mac) => {
450                     self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
451                 }
452                 ast::ItemKind::ForeignMod(ref foreign_mod) => {
453                     self.format_missing_with_indent(source!(self, item.span).lo());
454                     self.format_foreign_mod(foreign_mod, item.span);
455                 }
456                 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
457                     self.visit_static(&StaticParts::from_item(item));
458                 }
459                 ast::ItemKind::Fn(ref decl, ref fn_header, ref generics, ref body) => {
460                     let inner_attrs = inner_attributes(&item.attrs);
461                     self.visit_fn(
462                         visit::FnKind::ItemFn(item.ident, fn_header, &item.vis, body),
463                         generics,
464                         decl,
465                         item.span,
466                         ast::Defaultness::Final,
467                         Some(&inner_attrs),
468                     )
469                 }
470                 ast::ItemKind::Ty(ref ty, ref generics) => {
471                     let rewrite = rewrite_type_alias(
472                         &self.get_context(),
473                         self.block_indent,
474                         item.ident,
475                         ty,
476                         generics,
477                         &item.vis,
478                     );
479                     self.push_rewrite(item.span, rewrite);
480                 }
481                 ast::ItemKind::Existential(ref generic_bounds, ref generics) => {
482                     let rewrite = rewrite_existential_type(
483                         &self.get_context(),
484                         self.block_indent,
485                         item.ident,
486                         generic_bounds,
487                         generics,
488                         &item.vis,
489                     );
490                     self.push_rewrite(item.span, rewrite);
491                 }
492                 ast::ItemKind::GlobalAsm(..) => {
493                     let snippet = Some(self.snippet(item.span).to_owned());
494                     self.push_rewrite(item.span, snippet);
495                 }
496                 ast::ItemKind::MacroDef(ref def) => {
497                     let rewrite = rewrite_macro_def(
498                         &self.get_context(),
499                         self.shape(),
500                         self.block_indent,
501                         def,
502                         item.ident,
503                         &item.vis,
504                         item.span,
505                     );
506                     self.push_rewrite(item.span, rewrite);
507                 }
508             };
509         }
510         self.skip_context = skip_context_saved;
511     }
512
513     pub(crate) fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
514         skip_out_of_file_lines_range_visitor!(self, ti.span);
515
516         if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
517             self.push_skipped_with_span(ti.attrs.as_slice(), ti.span(), ti.span());
518             return;
519         }
520
521         match ti.node {
522             ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
523             ast::TraitItemKind::Method(ref sig, None) => {
524                 let indent = self.block_indent;
525                 let rewrite =
526                     self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
527                 self.push_rewrite(ti.span, rewrite);
528             }
529             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
530                 let inner_attrs = inner_attributes(&ti.attrs);
531                 self.visit_fn(
532                     visit::FnKind::Method(ti.ident, sig, None, body),
533                     &ti.generics,
534                     &sig.decl,
535                     ti.span,
536                     ast::Defaultness::Final,
537                     Some(&inner_attrs),
538                 );
539             }
540             ast::TraitItemKind::Type(ref generic_bounds, ref type_default) => {
541                 let rewrite = rewrite_associated_type(
542                     ti.ident,
543                     type_default.as_ref(),
544                     &ti.generics,
545                     Some(generic_bounds),
546                     &self.get_context(),
547                     self.block_indent,
548                 );
549                 self.push_rewrite(ti.span, rewrite);
550             }
551             ast::TraitItemKind::Macro(ref mac) => {
552                 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
553             }
554         }
555     }
556
557     pub(crate) fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
558         skip_out_of_file_lines_range_visitor!(self, ii.span);
559
560         if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
561             self.push_skipped_with_span(ii.attrs.as_slice(), ii.span(), ii.span());
562             return;
563         }
564
565         match ii.node {
566             ast::ImplItemKind::Method(ref sig, ref body) => {
567                 let inner_attrs = inner_attributes(&ii.attrs);
568                 self.visit_fn(
569                     visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
570                     &ii.generics,
571                     &sig.decl,
572                     ii.span,
573                     ii.defaultness,
574                     Some(&inner_attrs),
575                 );
576             }
577             ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
578             ast::ImplItemKind::Type(ref ty) => {
579                 let rewrite = rewrite_associated_impl_type(
580                     ii.ident,
581                     ii.defaultness,
582                     Some(ty),
583                     &ii.generics,
584                     &self.get_context(),
585                     self.block_indent,
586                 );
587                 self.push_rewrite(ii.span, rewrite);
588             }
589             ast::ImplItemKind::Existential(ref generic_bounds) => {
590                 let rewrite = rewrite_existential_impl_type(
591                     &self.get_context(),
592                     ii.ident,
593                     &ii.generics,
594                     generic_bounds,
595                     self.block_indent,
596                 );
597                 self.push_rewrite(ii.span, rewrite);
598             }
599             ast::ImplItemKind::Macro(ref mac) => {
600                 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
601             }
602         }
603     }
604
605     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
606         skip_out_of_file_lines_range_visitor!(self, mac.span);
607
608         // 1 = ;
609         let shape = self.shape().saturating_sub_width(1);
610         let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos));
611         self.push_rewrite(mac.span, rewrite);
612     }
613
614     pub(crate) fn push_str(&mut self, s: &str) {
615         self.line_number += count_newlines(s);
616         self.buffer.push_str(s);
617     }
618
619     #[allow(clippy::needless_pass_by_value)]
620     fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
621         if let Some(ref s) = rewrite {
622             self.push_str(s);
623         } else {
624             let snippet = self.snippet(span);
625             self.push_str(snippet);
626         }
627         self.last_pos = source!(self, span).hi();
628     }
629
630     pub(crate) fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
631         self.format_missing_with_indent(source!(self, span).lo());
632         self.push_rewrite_inner(span, rewrite);
633     }
634
635     pub(crate) fn push_skipped_with_span(
636         &mut self,
637         attrs: &[ast::Attribute],
638         item_span: Span,
639         main_span: Span,
640     ) {
641         self.format_missing_with_indent(source!(self, item_span).lo());
642         // do not take into account the lines with attributes as part of the skipped range
643         let attrs_end = attrs
644             .iter()
645             .map(|attr| self.source_map.lookup_char_pos(attr.span.hi()).line)
646             .max()
647             .unwrap_or(1);
648         let first_line = self.source_map.lookup_char_pos(main_span.lo()).line;
649         // Statement can start after some newlines and/or spaces
650         // or it can be on the same line as the last attribute.
651         // So here we need to take a minimum between the two.
652         let lo = std::cmp::min(attrs_end + 1, first_line);
653         self.push_rewrite_inner(item_span, None);
654         let hi = self.line_number + 1;
655         self.skipped_range.push((lo, hi));
656     }
657
658     pub(crate) fn from_context(ctx: &'a RewriteContext<'_>) -> FmtVisitor<'a> {
659         let mut visitor = FmtVisitor::from_source_map(
660             ctx.parse_session,
661             ctx.config,
662             ctx.snippet_provider,
663             ctx.report.clone(),
664         );
665         visitor.skip_context.update(ctx.skip_context.clone());
666         visitor.set_parent_context(ctx);
667         visitor
668     }
669
670     pub(crate) fn from_source_map(
671         parse_session: &'a ParseSess,
672         config: &'a Config,
673         snippet_provider: &'a SnippetProvider<'_>,
674         report: FormatReport,
675     ) -> FmtVisitor<'a> {
676         FmtVisitor {
677             parent_context: None,
678             parse_session,
679             source_map: parse_session.source_map(),
680             buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
681             last_pos: BytePos(0),
682             block_indent: Indent::empty(),
683             config,
684             is_if_else_block: false,
685             snippet_provider,
686             line_number: 0,
687             skipped_range: vec![],
688             macro_rewrite_failure: false,
689             report,
690             skip_context: Default::default(),
691         }
692     }
693
694     pub(crate) fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
695         self.snippet_provider.span_to_snippet(span)
696     }
697
698     pub(crate) fn snippet(&'b self, span: Span) -> &'a str {
699         self.opt_snippet(span).unwrap()
700     }
701
702     // Returns true if we should skip the following item.
703     pub(crate) fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
704         for attr in attrs {
705             if attr.check_name(depr_skip_annotation()) {
706                 let file_name = self.source_map.span_to_filename(attr.span).into();
707                 self.report.append(
708                     file_name,
709                     vec![FormattingError::from_span(
710                         attr.span,
711                         &self.source_map,
712                         ErrorKind::DeprecatedAttr,
713                     )],
714                 );
715             } else if self.is_unknown_rustfmt_attr(&attr.path.segments) {
716                 let file_name = self.source_map.span_to_filename(attr.span).into();
717                 self.report.append(
718                     file_name,
719                     vec![FormattingError::from_span(
720                         attr.span,
721                         &self.source_map,
722                         ErrorKind::BadAttr,
723                     )],
724                 );
725             }
726         }
727         if contains_skip(attrs) {
728             return true;
729         }
730
731         let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
732         if attrs.is_empty() {
733             return false;
734         }
735
736         let rewrite = attrs.rewrite(&self.get_context(), self.shape());
737         let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
738         self.push_rewrite(span, rewrite);
739
740         false
741     }
742
743     fn is_unknown_rustfmt_attr(&self, segments: &[ast::PathSegment]) -> bool {
744         if segments[0].ident.to_string() != "rustfmt" {
745             return false;
746         }
747         !is_skip_attr(segments)
748     }
749
750     fn walk_mod_items(&mut self, m: &ast::Mod) {
751         self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
752     }
753
754     fn walk_stmts(&mut self, stmts: &[Stmt<'_>]) {
755         if stmts.is_empty() {
756             return;
757         }
758
759         // Extract leading `use ...;`.
760         let items: Vec<_> = stmts
761             .iter()
762             .take_while(|stmt| stmt.to_item().map_or(false, is_use_item))
763             .filter_map(|stmt| stmt.to_item())
764             .collect();
765
766         if items.is_empty() {
767             self.visit_stmt(&stmts[0]);
768             self.walk_stmts(&stmts[1..]);
769         } else {
770             self.visit_items_with_reordering(&items);
771             self.walk_stmts(&stmts[items.len()..]);
772         }
773     }
774
775     fn walk_block_stmts(&mut self, b: &ast::Block) {
776         self.walk_stmts(&Stmt::from_ast_nodes(b.stmts.iter()))
777     }
778
779     fn format_mod(
780         &mut self,
781         m: &ast::Mod,
782         vis: &ast::Visibility,
783         s: Span,
784         ident: ast::Ident,
785         attrs: &[ast::Attribute],
786         is_internal: bool,
787     ) {
788         let vis_str = utils::format_visibility(&self.get_context(), vis);
789         self.push_str(&*vis_str);
790         self.push_str("mod ");
791         // Calling `to_owned()` to work around borrow checker.
792         let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
793         self.push_str(&ident_str);
794
795         if is_internal {
796             match self.config.brace_style() {
797                 BraceStyle::AlwaysNextLine => {
798                     let indent_str = self.block_indent.to_string_with_newline(self.config);
799                     self.push_str(&indent_str);
800                     self.push_str("{");
801                 }
802                 _ => self.push_str(" {"),
803             }
804             // Hackery to account for the closing }.
805             let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
806             let body_snippet =
807                 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
808             let body_snippet = body_snippet.trim();
809             if body_snippet.is_empty() {
810                 self.push_str("}");
811             } else {
812                 self.last_pos = mod_lo;
813                 self.block_indent = self.block_indent.block_indent(self.config);
814                 self.visit_attrs(attrs, ast::AttrStyle::Inner);
815                 self.walk_mod_items(m);
816                 let missing_span = self.next_span(m.inner.hi() - BytePos(1));
817                 self.close_block(missing_span, false);
818             }
819             self.last_pos = source!(self, m.inner).hi();
820         } else {
821             self.push_str(";");
822             self.last_pos = source!(self, s).hi();
823         }
824     }
825
826     pub(crate) fn format_separate_mod(
827         &mut self,
828         m: &ast::Mod,
829         source_file: &source_map::SourceFile,
830     ) {
831         self.block_indent = Indent::empty();
832         self.walk_mod_items(m);
833         self.format_missing_with_indent(source_file.end_pos);
834     }
835
836     pub(crate) fn skip_empty_lines(&mut self, end_pos: BytePos) {
837         while let Some(pos) = self
838             .snippet_provider
839             .opt_span_after(self.next_span(end_pos), "\n")
840         {
841             if let Some(snippet) = self.opt_snippet(self.next_span(pos)) {
842                 if snippet.trim().is_empty() {
843                     self.last_pos = pos;
844                 } else {
845                     return;
846                 }
847             }
848         }
849     }
850
851     pub(crate) fn with_context<F>(&mut self, f: F) -> Option<String>
852     where
853         F: Fn(&RewriteContext<'_>) -> Option<String>,
854     {
855         // FIXME borrow checker fighting - can be simplified a lot with NLL.
856         let (result, mrf) = {
857             let context = self.get_context();
858             let result = f(&context);
859             let mrf = &context.macro_rewrite_failure.borrow();
860             (result, *std::ops::Deref::deref(mrf))
861         };
862
863         self.macro_rewrite_failure |= mrf;
864         result
865     }
866
867     pub(crate) fn get_context(&self) -> RewriteContext<'_> {
868         RewriteContext {
869             parse_session: self.parse_session,
870             source_map: self.source_map,
871             config: self.config,
872             inside_macro: RefCell::new(false),
873             use_block: RefCell::new(false),
874             is_if_else_block: RefCell::new(false),
875             force_one_line_chain: RefCell::new(false),
876             snippet_provider: self.snippet_provider,
877             macro_rewrite_failure: RefCell::new(false),
878             report: self.report.clone(),
879             skip_context: self.skip_context.clone(),
880         }
881     }
882 }