1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use syntax::attr::HasAttrs;
12 use syntax::parse::ParseSess;
13 use syntax::source_map::{self, BytePos, Pos, SourceMap, Span};
14 use syntax::{ast, visit};
17 use comment::{CodeCharKind, CommentCodeSlices, FindUncommented};
18 use config::{BraceStyle, Config};
20 format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item,
21 rewrite_associated_impl_type, rewrite_associated_type, rewrite_existential_impl_type,
22 rewrite_existential_type, rewrite_extern_crate, rewrite_type_alias, FnSig, StaticParts,
25 use macros::{rewrite_macro, rewrite_macro_def, MacroPosition};
26 use rewrite::{Rewrite, RewriteContext};
27 use shape::{Indent, Shape};
28 use source_map::{LineRangeUtils, SpanUtils};
31 self, contains_skip, count_newlines, inner_attributes, mk_sp, ptr_vec_to_ref_vec,
32 rewrite_ident, DEPR_SKIP_ANNOTATION,
34 use {ErrorKind, FormatReport, FormattingError};
36 use std::cell::RefCell;
38 /// Creates a string slice corresponding to the specified span.
39 pub struct SnippetProvider<'a> {
40 /// A pointer to the content of the file we are formatting.
42 /// A position of the start of `big_snippet`, used as an offset.
46 impl<'a> SnippetProvider<'a> {
47 pub fn span_to_snippet(&self, span: Span) -> Option<&str> {
48 let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
49 let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
50 Some(&self.big_snippet[start_index..end_index])
53 pub fn new(start_pos: BytePos, big_snippet: &'a str) -> Self {
54 let start_pos = start_pos.to_usize();
62 pub struct FmtVisitor<'a> {
63 parent_context: Option<&'a RewriteContext<'a>>,
64 pub parse_session: &'a ParseSess,
65 pub source_map: &'a SourceMap,
67 pub last_pos: BytePos,
68 // FIXME: use an RAII util or closure for indenting
69 pub block_indent: Indent,
70 pub config: &'a Config,
71 pub is_if_else_block: bool,
72 pub snippet_provider: &'a SnippetProvider<'a>,
73 pub line_number: usize,
74 /// List of 1-based line ranges which were annotated with skip
75 /// Both bounds are inclusifs.
76 pub skipped_range: Vec<(usize, usize)>,
77 pub macro_rewrite_failure: bool,
78 pub(crate) report: FormatReport,
81 impl<'a> Drop for FmtVisitor<'a> {
83 if let Some(ctx) = self.parent_context {
84 if self.macro_rewrite_failure {
85 ctx.macro_rewrite_failure.replace(true);
91 impl<'b, 'a: 'b> FmtVisitor<'a> {
92 fn set_parent_context(&mut self, context: &'a RewriteContext) {
93 self.parent_context = Some(context);
96 pub fn shape(&self) -> Shape {
97 Shape::indented(self.block_indent, self.config)
100 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
102 "visit_stmt: {:?} {:?}",
103 self.source_map.lookup_char_pos(stmt.span.lo()),
104 self.source_map.lookup_char_pos(stmt.span.hi())
108 ast::StmtKind::Item(ref item) => {
109 self.visit_item(item);
110 // Handle potential `;` after the item.
111 self.format_missing(stmt.span.hi());
113 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
114 let attrs = get_attrs_from_stmt(stmt);
115 if contains_skip(attrs) {
116 self.push_skipped_with_span(attrs, stmt.span());
118 let shape = self.shape();
119 let rewrite = self.with_context(|ctx| stmt.rewrite(&ctx, shape));
120 self.push_rewrite(stmt.span(), rewrite)
123 ast::StmtKind::Mac(ref mac) => {
124 let (ref mac, _macro_style, ref attrs) = **mac;
125 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
126 self.push_skipped_with_span(attrs, stmt.span());
128 self.visit_mac(mac, None, MacroPosition::Statement);
130 self.format_missing(stmt.span.hi());
138 inner_attrs: Option<&[ast::Attribute]>,
142 "visit_block: {:?} {:?}",
143 self.source_map.lookup_char_pos(b.span.lo()),
144 self.source_map.lookup_char_pos(b.span.hi())
147 // Check if this block has braces.
148 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
150 self.last_pos = self.last_pos + brace_compensation;
151 self.block_indent = self.block_indent.block_indent(self.config);
154 if let Some(first_stmt) = b.stmts.first() {
155 let attr_lo = inner_attrs
156 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
158 // Attributes for an item in a statement position
159 // do not belong to the statement. (rust-lang/rust#34459)
160 if let ast::StmtKind::Item(ref item) = first_stmt.node {
163 first_stmt.attrs().first()
166 // Some stmts can have embedded attributes.
167 // e.g. `match { #![attr] ... }`
168 let attr_lo = attr.span.lo();
169 if attr_lo < first_stmt.span.lo() {
177 let snippet = self.snippet(mk_sp(
179 attr_lo.unwrap_or_else(|| first_stmt.span.lo()),
181 let len = CommentCodeSlices::new(snippet)
183 .and_then(|(kind, _, s)| {
184 if kind == CodeCharKind::Normal {
190 if let Some(len) = len {
191 self.last_pos = self.last_pos + BytePos::from_usize(len);
195 // Format inner attributes if available.
196 let skip_rewrite = if let Some(attrs) = inner_attrs {
197 self.visit_attrs(attrs, ast::AttrStyle::Inner)
203 self.push_rewrite(b.span, None);
204 self.close_block(false);
205 self.last_pos = source!(self, b.span).hi();
209 self.walk_block_stmts(b);
211 if !b.stmts.is_empty() {
212 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
213 if utils::semicolon_for_expr(&self.get_context(), expr) {
219 let mut remove_len = BytePos(0);
220 if let Some(stmt) = b.stmts.last() {
221 let snippet = self.snippet(mk_sp(
223 source!(self, b.span).hi() - brace_compensation,
225 let len = CommentCodeSlices::new(snippet)
227 .and_then(|(kind, _, s)| {
228 if kind == CodeCharKind::Normal && s.trim().is_empty() {
234 if let Some(len) = len {
235 remove_len = BytePos::from_usize(len);
239 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
240 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
241 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
242 snippet.contains("//") || snippet.contains("/*")
244 // FIXME: we should compress any newlines here to just one
245 if unindent_comment {
246 self.block_indent = self.block_indent.block_unindent(self.config);
248 self.format_missing_with_indent(
249 source!(self, b.span).hi() - brace_compensation - remove_len,
251 if unindent_comment {
252 self.block_indent = self.block_indent.block_indent(self.config);
254 self.close_block(unindent_comment);
255 self.last_pos = source!(self, b.span).hi();
258 // FIXME: this is a terrible hack to indent the comments between the last
259 // item in the block and the closing brace to the block's level.
260 // The closing brace itself, however, should be indented at a shallower
262 fn close_block(&mut self, unindent_comment: bool) {
263 let total_len = self.buffer.len();
264 let chars_too_many = if unindent_comment {
266 } else if self.config.hard_tabs() {
269 self.config.tab_spaces()
271 self.buffer.truncate(total_len - chars_too_many);
273 self.block_indent = self.block_indent.block_unindent(self.config);
276 // Note that this only gets called for function definitions. Required methods
277 // on traits do not get handled here.
281 generics: &ast::Generics,
284 defaultness: ast::Defaultness,
285 inner_attrs: Option<&[ast::Attribute]>,
287 let indent = self.block_indent;
289 let rewrite = match fk {
290 visit::FnKind::ItemFn(ident, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
295 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
296 mk_sp(s.lo(), b.span.lo()),
301 visit::FnKind::Closure(_) => unreachable!(),
304 if let Some(fn_str) = rewrite {
305 self.format_missing_with_indent(source!(self, s).lo());
306 self.push_str(&fn_str);
307 if let Some(c) = fn_str.chars().last() {
309 self.last_pos = source!(self, block.span).hi();
314 self.format_missing(source!(self, block.span).lo());
317 self.last_pos = source!(self, block.span).lo();
318 self.visit_block(block, inner_attrs, true)
321 pub fn visit_item(&mut self, item: &ast::Item) {
322 skip_out_of_file_lines_range_visitor!(self, item.span);
324 // This is where we bail out if there is a skip attribute. This is only
325 // complex in the module case. It is complex because the module could be
326 // in a separate file and there might be attributes in both files, but
327 // the AST lumps them all together.
329 let mut attrs = &item.attrs;
331 // For use items, skip rewriting attributes. Just check for a skip attribute.
332 ast::ItemKind::Use(..) => {
333 if contains_skip(attrs) {
334 self.push_skipped_with_span(attrs.as_slice(), item.span());
338 // Module is inline, in this case we treat it like any other item.
339 _ if !is_mod_decl(item) => {
340 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
341 self.push_skipped_with_span(item.attrs.as_slice(), item.span());
345 // Module is not inline, but should be skipped.
346 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
349 // Module is not inline and should not be skipped. We want
350 // to process only the attributes in the current file.
351 ast::ItemKind::Mod(..) => {
352 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
353 // Assert because if we should skip it should be caught by
355 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
356 attrs = &filtered_attrs;
359 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
360 self.push_skipped_with_span(item.attrs.as_slice(), item.span());
367 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
368 ast::ItemKind::Impl(..) => {
369 let snippet = self.snippet(item.span);
370 let where_span_end = snippet
371 .find_uncommented("{")
372 .map(|x| BytePos(x as u32) + source!(self, item.span).lo());
373 let block_indent = self.block_indent;
375 self.with_context(|ctx| format_impl(&ctx, item, block_indent, where_span_end));
376 self.push_rewrite(item.span, rw);
378 ast::ItemKind::Trait(..) => {
379 let block_indent = self.block_indent;
380 let rw = self.with_context(|ctx| format_trait(&ctx, item, block_indent));
381 self.push_rewrite(item.span, rw);
383 ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => {
384 let shape = Shape::indented(self.block_indent, self.config);
385 let rw = format_trait_alias(
392 self.push_rewrite(item.span, rw);
394 ast::ItemKind::ExternCrate(_) => {
395 let rw = rewrite_extern_crate(&self.get_context(), item);
396 self.push_rewrite(item.span, rw);
398 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
399 self.visit_struct(&StructParts::from_item(item));
401 ast::ItemKind::Enum(ref def, ref generics) => {
402 self.format_missing_with_indent(source!(self, item.span).lo());
403 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
404 self.last_pos = source!(self, item.span).hi();
406 ast::ItemKind::Mod(ref module) => {
407 let is_inline = !is_mod_decl(item);
408 self.format_missing_with_indent(source!(self, item.span).lo());
409 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
411 ast::ItemKind::Mac(ref mac) => {
412 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
414 ast::ItemKind::ForeignMod(ref foreign_mod) => {
415 self.format_missing_with_indent(source!(self, item.span).lo());
416 self.format_foreign_mod(foreign_mod, item.span);
418 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
419 self.visit_static(&StaticParts::from_item(item));
421 ast::ItemKind::Fn(ref decl, fn_header, ref generics, ref body) => {
422 let inner_attrs = inner_attributes(&item.attrs);
424 visit::FnKind::ItemFn(item.ident, fn_header, &item.vis, body),
428 ast::Defaultness::Final,
432 ast::ItemKind::Ty(ref ty, ref generics) => {
433 let rewrite = rewrite_type_alias(
441 self.push_rewrite(item.span, rewrite);
443 ast::ItemKind::Existential(ref generic_bounds, ref generics) => {
444 let rewrite = rewrite_existential_type(
452 self.push_rewrite(item.span, rewrite);
454 ast::ItemKind::GlobalAsm(..) => {
455 let snippet = Some(self.snippet(item.span).to_owned());
456 self.push_rewrite(item.span, snippet);
458 ast::ItemKind::MacroDef(ref def) => {
459 let rewrite = rewrite_macro_def(
468 self.push_rewrite(item.span, rewrite);
473 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
474 skip_out_of_file_lines_range_visitor!(self, ti.span);
476 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
477 self.push_skipped_with_span(ti.attrs.as_slice(), ti.span());
482 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
483 ast::TraitItemKind::Method(ref sig, None) => {
484 let indent = self.block_indent;
486 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
487 self.push_rewrite(ti.span, rewrite);
489 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
490 let inner_attrs = inner_attributes(&ti.attrs);
492 visit::FnKind::Method(ti.ident, sig, None, body),
496 ast::Defaultness::Final,
500 ast::TraitItemKind::Type(ref generic_bounds, ref type_default) => {
501 let rewrite = rewrite_associated_type(
503 type_default.as_ref(),
505 Some(generic_bounds),
509 self.push_rewrite(ti.span, rewrite);
511 ast::TraitItemKind::Macro(ref mac) => {
512 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
517 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
518 skip_out_of_file_lines_range_visitor!(self, ii.span);
520 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
521 self.push_skipped_with_span(ii.attrs.as_slice(), ii.span());
526 ast::ImplItemKind::Method(ref sig, ref body) => {
527 let inner_attrs = inner_attributes(&ii.attrs);
529 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
537 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
538 ast::ImplItemKind::Type(ref ty) => {
539 let rewrite = rewrite_associated_impl_type(
547 self.push_rewrite(ii.span, rewrite);
549 ast::ImplItemKind::Existential(ref generic_bounds) => {
550 let rewrite = rewrite_existential_impl_type(
557 self.push_rewrite(ii.span, rewrite);
559 ast::ImplItemKind::Macro(ref mac) => {
560 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
565 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
566 skip_out_of_file_lines_range_visitor!(self, mac.span);
569 let shape = self.shape().sub_width(1).unwrap();
570 let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos));
571 self.push_rewrite(mac.span, rewrite);
574 pub fn push_str(&mut self, s: &str) {
575 self.line_number += count_newlines(s);
576 self.buffer.push_str(s);
579 #[allow(clippy::needless_pass_by_value)]
580 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
581 if let Some(ref s) = rewrite {
584 let snippet = self.snippet(span);
585 self.push_str(snippet);
587 self.last_pos = source!(self, span).hi();
590 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
591 self.format_missing_with_indent(source!(self, span).lo());
592 self.push_rewrite_inner(span, rewrite);
595 pub fn push_skipped_with_span(&mut self, attrs: &[ast::Attribute], item_span: Span) {
596 self.format_missing_with_indent(source!(self, item_span).lo());
597 // do not take into account the lines with attributes as part of the skipped range
598 let attrs_end = attrs
600 .map(|attr| self.source_map.lookup_char_pos(attr.span().hi()).line)
603 // Add 1 to get the line past the last attribute
604 let lo = attrs_end + 1;
605 self.push_rewrite_inner(item_span, None);
606 let hi = self.line_number + 1;
607 self.skipped_range.push((lo, hi));
610 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
611 let mut visitor = FmtVisitor::from_source_map(
614 ctx.snippet_provider,
617 visitor.set_parent_context(ctx);
621 pub(crate) fn from_source_map(
622 parse_session: &'a ParseSess,
624 snippet_provider: &'a SnippetProvider,
625 report: FormatReport,
626 ) -> FmtVisitor<'a> {
628 parent_context: None,
630 source_map: parse_session.source_map(),
631 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
632 last_pos: BytePos(0),
633 block_indent: Indent::empty(),
635 is_if_else_block: false,
638 skipped_range: vec![],
639 macro_rewrite_failure: false,
644 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
645 self.snippet_provider.span_to_snippet(span)
648 pub fn snippet(&'b self, span: Span) -> &'a str {
649 self.opt_snippet(span).unwrap()
652 // Returns true if we should skip the following item.
653 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
655 if attr.name() == DEPR_SKIP_ANNOTATION {
656 let file_name = self.source_map.span_to_filename(attr.span).into();
659 vec![FormattingError::from_span(
662 ErrorKind::DeprecatedAttr,
665 } else if attr.path.segments[0].ident.to_string() == "rustfmt"
666 && (attr.path.segments.len() == 1
667 || attr.path.segments[1].ident.to_string() != "skip")
669 let file_name = self.source_map.span_to_filename(attr.span).into();
672 vec![FormattingError::from_span(
680 if contains_skip(attrs) {
684 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
685 if attrs.is_empty() {
689 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
690 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
691 self.push_rewrite(span, rewrite);
696 fn walk_mod_items(&mut self, m: &ast::Mod) {
697 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
700 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
701 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
703 ast::StmtKind::Item(ref item) => Some(&**item),
708 if stmts.is_empty() {
712 // Extract leading `use ...;`.
713 let items: Vec<_> = stmts
715 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
716 .filter_map(|stmt| to_stmt_item(stmt))
719 if items.is_empty() {
720 self.visit_stmt(&stmts[0]);
721 self.walk_stmts(&stmts[1..]);
723 self.visit_items_with_reordering(&items);
724 self.walk_stmts(&stmts[items.len()..]);
728 fn walk_block_stmts(&mut self, b: &ast::Block) {
729 self.walk_stmts(&b.stmts)
735 vis: &ast::Visibility,
738 attrs: &[ast::Attribute],
741 let vis_str = utils::format_visibility(&self.get_context(), vis);
742 self.push_str(&*vis_str);
743 self.push_str("mod ");
744 // Calling `to_owned()` to work around borrow checker.
745 let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
746 self.push_str(&ident_str);
749 match self.config.brace_style() {
750 BraceStyle::AlwaysNextLine => {
751 let indent_str = self.block_indent.to_string_with_newline(self.config);
752 self.push_str(&indent_str);
755 _ => self.push_str(" {"),
757 // Hackery to account for the closing }.
758 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
760 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
761 let body_snippet = body_snippet.trim();
762 if body_snippet.is_empty() {
765 self.last_pos = mod_lo;
766 self.block_indent = self.block_indent.block_indent(self.config);
767 self.visit_attrs(attrs, ast::AttrStyle::Inner);
768 self.walk_mod_items(m);
769 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
770 self.close_block(false);
772 self.last_pos = source!(self, m.inner).hi();
775 self.last_pos = source!(self, s).hi();
779 pub fn format_separate_mod(&mut self, m: &ast::Mod, source_file: &source_map::SourceFile) {
780 self.block_indent = Indent::empty();
781 self.walk_mod_items(m);
782 self.format_missing_with_indent(source_file.end_pos);
785 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
786 while let Some(pos) = self
788 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
790 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
791 if snippet.trim().is_empty() {
800 pub fn with_context<F>(&mut self, f: F) -> Option<String>
802 F: Fn(&RewriteContext) -> Option<String>,
804 // FIXME borrow checker fighting - can be simplified a lot with NLL.
805 let (result, mrf) = {
806 let context = self.get_context();
807 let result = f(&context);
808 let mrf = &context.macro_rewrite_failure.borrow();
809 (result, *std::ops::Deref::deref(mrf))
812 self.macro_rewrite_failure |= mrf;
816 pub fn get_context(&self) -> RewriteContext {
818 parse_session: self.parse_session,
819 source_map: self.source_map,
821 inside_macro: RefCell::new(false),
822 use_block: RefCell::new(false),
823 is_if_else_block: RefCell::new(false),
824 force_one_line_chain: RefCell::new(false),
825 snippet_provider: self.snippet_provider,
826 macro_rewrite_failure: RefCell::new(false),
827 report: self.report.clone(),