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 pub skipped_range: Vec<(usize, usize)>,
75 pub macro_rewrite_failure: bool,
76 pub(crate) report: FormatReport,
79 impl<'a> Drop for FmtVisitor<'a> {
81 if let Some(ctx) = self.parent_context {
82 if self.macro_rewrite_failure {
83 ctx.macro_rewrite_failure.replace(true);
89 impl<'b, 'a: 'b> FmtVisitor<'a> {
90 fn set_parent_context(&mut self, context: &'a RewriteContext) {
91 self.parent_context = Some(context);
94 pub fn shape(&self) -> Shape {
95 Shape::indented(self.block_indent, self.config)
98 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
100 "visit_stmt: {:?} {:?}",
101 self.source_map.lookup_char_pos(stmt.span.lo()),
102 self.source_map.lookup_char_pos(stmt.span.hi())
106 ast::StmtKind::Item(ref item) => {
107 self.visit_item(item);
108 // Handle potential `;` after the item.
109 self.format_missing(stmt.span.hi());
111 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
112 if contains_skip(get_attrs_from_stmt(stmt)) {
113 self.push_skipped_with_span(stmt.span());
115 let shape = self.shape().clone();
116 let rewrite = self.with_context(|ctx| stmt.rewrite(&ctx, shape));
117 self.push_rewrite(stmt.span(), rewrite)
120 ast::StmtKind::Mac(ref mac) => {
121 let (ref mac, _macro_style, ref attrs) = **mac;
122 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
123 self.push_skipped_with_span(stmt.span());
125 self.visit_mac(mac, None, MacroPosition::Statement);
127 self.format_missing(stmt.span.hi());
135 inner_attrs: Option<&[ast::Attribute]>,
139 "visit_block: {:?} {:?}",
140 self.source_map.lookup_char_pos(b.span.lo()),
141 self.source_map.lookup_char_pos(b.span.hi())
144 // Check if this block has braces.
145 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
147 self.last_pos = self.last_pos + brace_compensation;
148 self.block_indent = self.block_indent.block_indent(self.config);
151 if let Some(first_stmt) = b.stmts.first() {
152 let attr_lo = inner_attrs
153 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
155 // Attributes for an item in a statement position
156 // do not belong to the statement. (rust-lang/rust#34459)
157 if let ast::StmtKind::Item(ref item) = first_stmt.node {
160 first_stmt.attrs().first()
162 // Some stmts can have embedded attributes.
163 // e.g. `match { #![attr] ... }`
164 let attr_lo = attr.span.lo();
165 if attr_lo < first_stmt.span.lo() {
173 let snippet = self.snippet(mk_sp(
175 attr_lo.unwrap_or_else(|| first_stmt.span.lo()),
177 let len = CommentCodeSlices::new(snippet)
179 .and_then(|(kind, _, s)| {
180 if kind == CodeCharKind::Normal {
186 if let Some(len) = len {
187 self.last_pos = self.last_pos + BytePos::from_usize(len);
191 // Format inner attributes if available.
192 let skip_rewrite = if let Some(attrs) = inner_attrs {
193 self.visit_attrs(attrs, ast::AttrStyle::Inner)
199 self.push_rewrite(b.span, None);
200 self.close_block(false);
201 self.last_pos = source!(self, b.span).hi();
205 self.walk_block_stmts(b);
207 if !b.stmts.is_empty() {
208 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
209 if utils::semicolon_for_expr(&self.get_context(), expr) {
215 let mut remove_len = BytePos(0);
216 if let Some(stmt) = b.stmts.last() {
217 let snippet = self.snippet(mk_sp(
219 source!(self, b.span).hi() - brace_compensation,
221 let len = CommentCodeSlices::new(snippet)
223 .and_then(|(kind, _, s)| {
224 if kind == CodeCharKind::Normal && s.trim().is_empty() {
230 if let Some(len) = len {
231 remove_len = BytePos::from_usize(len);
235 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
236 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
237 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
238 snippet.contains("//") || snippet.contains("/*")
240 // FIXME: we should compress any newlines here to just one
241 if unindent_comment {
242 self.block_indent = self.block_indent.block_unindent(self.config);
244 self.format_missing_with_indent(
245 source!(self, b.span).hi() - brace_compensation - remove_len,
247 if unindent_comment {
248 self.block_indent = self.block_indent.block_indent(self.config);
250 self.close_block(unindent_comment);
251 self.last_pos = source!(self, b.span).hi();
254 // FIXME: this is a terrible hack to indent the comments between the last
255 // item in the block and the closing brace to the block's level.
256 // The closing brace itself, however, should be indented at a shallower
258 fn close_block(&mut self, unindent_comment: bool) {
259 let total_len = self.buffer.len();
260 let chars_too_many = if unindent_comment {
262 } else if self.config.hard_tabs() {
265 self.config.tab_spaces()
267 self.buffer.truncate(total_len - chars_too_many);
269 self.block_indent = self.block_indent.block_unindent(self.config);
272 // Note that this only gets called for function definitions. Required methods
273 // on traits do not get handled here.
277 generics: &ast::Generics,
280 defaultness: ast::Defaultness,
281 inner_attrs: Option<&[ast::Attribute]>,
283 let indent = self.block_indent;
285 let rewrite = match fk {
286 visit::FnKind::ItemFn(ident, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
291 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
292 mk_sp(s.lo(), b.span.lo()),
297 visit::FnKind::Closure(_) => unreachable!(),
300 if let Some(fn_str) = rewrite {
301 self.format_missing_with_indent(source!(self, s).lo());
302 self.push_str(&fn_str);
303 if let Some(c) = fn_str.chars().last() {
305 self.last_pos = source!(self, block.span).hi();
310 self.format_missing(source!(self, block.span).lo());
313 self.last_pos = source!(self, block.span).lo();
314 self.visit_block(block, inner_attrs, true)
317 pub fn visit_item(&mut self, item: &ast::Item) {
318 skip_out_of_file_lines_range_visitor!(self, item.span);
320 // This is where we bail out if there is a skip attribute. This is only
321 // complex in the module case. It is complex because the module could be
322 // in a separate file and there might be attributes in both files, but
323 // the AST lumps them all together.
325 let mut attrs = &item.attrs;
327 // For use items, skip rewriting attributes. Just check for a skip attribute.
328 ast::ItemKind::Use(..) => {
329 if contains_skip(attrs) {
330 self.push_skipped_with_span(item.span());
334 // Module is inline, in this case we treat it like any other item.
335 _ if !is_mod_decl(item) => {
336 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
337 self.push_skipped_with_span(item.span());
341 // Module is not inline, but should be skipped.
342 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
345 // Module is not inline and should not be skipped. We want
346 // to process only the attributes in the current file.
347 ast::ItemKind::Mod(..) => {
348 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
349 // Assert because if we should skip it should be caught by
351 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
352 attrs = &filtered_attrs;
355 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
356 self.push_skipped_with_span(item.span());
363 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
364 ast::ItemKind::Impl(..) => {
365 let snippet = self.snippet(item.span);
366 let where_span_end = snippet
367 .find_uncommented("{")
368 .map(|x| BytePos(x as u32) + source!(self, item.span).lo());
369 let block_indent = self.block_indent.clone();
371 self.with_context(|ctx| format_impl(&ctx, item, block_indent, where_span_end));
372 self.push_rewrite(item.span, rw);
374 ast::ItemKind::Trait(..) => {
375 let block_indent = self.block_indent.clone();
376 let rw = self.with_context(|ctx| format_trait(&ctx, item, block_indent));
377 self.push_rewrite(item.span, rw);
379 ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => {
380 let shape = Shape::indented(self.block_indent, self.config);
381 let rw = format_trait_alias(
388 self.push_rewrite(item.span, rw);
390 ast::ItemKind::ExternCrate(_) => {
391 let rw = rewrite_extern_crate(&self.get_context(), item);
392 self.push_rewrite(item.span, rw);
394 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
395 self.visit_struct(&StructParts::from_item(item));
397 ast::ItemKind::Enum(ref def, ref generics) => {
398 self.format_missing_with_indent(source!(self, item.span).lo());
399 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
400 self.last_pos = source!(self, item.span).hi();
402 ast::ItemKind::Mod(ref module) => {
403 let is_inline = !is_mod_decl(item);
404 self.format_missing_with_indent(source!(self, item.span).lo());
405 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
407 ast::ItemKind::Mac(ref mac) => {
408 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
410 ast::ItemKind::ForeignMod(ref foreign_mod) => {
411 self.format_missing_with_indent(source!(self, item.span).lo());
412 self.format_foreign_mod(foreign_mod, item.span);
414 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
415 self.visit_static(&StaticParts::from_item(item));
417 ast::ItemKind::Fn(ref decl, fn_header, ref generics, ref body) => {
418 let inner_attrs = inner_attributes(&item.attrs);
420 visit::FnKind::ItemFn(item.ident, fn_header, &item.vis, body),
424 ast::Defaultness::Final,
428 ast::ItemKind::Ty(ref ty, ref generics) => {
429 let rewrite = rewrite_type_alias(
437 self.push_rewrite(item.span, rewrite);
439 ast::ItemKind::Existential(ref generic_bounds, ref generics) => {
440 let rewrite = rewrite_existential_type(
448 self.push_rewrite(item.span, rewrite);
450 ast::ItemKind::GlobalAsm(..) => {
451 let snippet = Some(self.snippet(item.span).to_owned());
452 self.push_rewrite(item.span, snippet);
454 ast::ItemKind::MacroDef(ref def) => {
455 let rewrite = rewrite_macro_def(
464 self.push_rewrite(item.span, rewrite);
469 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
470 skip_out_of_file_lines_range_visitor!(self, ti.span);
472 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
473 self.push_skipped_with_span(ti.span());
478 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
479 ast::TraitItemKind::Method(ref sig, None) => {
480 let indent = self.block_indent;
482 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
483 self.push_rewrite(ti.span, rewrite);
485 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
486 let inner_attrs = inner_attributes(&ti.attrs);
488 visit::FnKind::Method(ti.ident, sig, None, body),
492 ast::Defaultness::Final,
496 ast::TraitItemKind::Type(ref generic_bounds, ref type_default) => {
497 let rewrite = rewrite_associated_type(
499 type_default.as_ref(),
500 Some(generic_bounds),
504 self.push_rewrite(ti.span, rewrite);
506 ast::TraitItemKind::Macro(ref mac) => {
507 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
512 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
513 skip_out_of_file_lines_range_visitor!(self, ii.span);
515 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
516 self.push_skipped_with_span(ii.span());
521 ast::ImplItemKind::Method(ref sig, ref body) => {
522 let inner_attrs = inner_attributes(&ii.attrs);
524 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
532 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
533 ast::ImplItemKind::Type(ref ty) => {
534 let rewrite = rewrite_associated_impl_type(
541 self.push_rewrite(ii.span, rewrite);
543 ast::ImplItemKind::Existential(ref generic_bounds) => {
544 let rewrite = rewrite_existential_impl_type(
550 self.push_rewrite(ii.span, rewrite);
552 ast::ImplItemKind::Macro(ref mac) => {
553 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
558 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
559 skip_out_of_file_lines_range_visitor!(self, mac.span);
562 let shape = self.shape().sub_width(1).unwrap();
563 let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos));
564 self.push_rewrite(mac.span, rewrite);
567 pub fn push_str(&mut self, s: &str) {
568 self.line_number += count_newlines(s);
569 self.buffer.push_str(s);
572 #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
573 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
574 if let Some(ref s) = rewrite {
577 let snippet = self.snippet(span);
578 self.push_str(snippet);
580 self.last_pos = source!(self, span).hi();
583 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
584 self.format_missing_with_indent(source!(self, span).lo());
585 self.push_rewrite_inner(span, rewrite);
588 pub fn push_skipped_with_span(&mut self, span: Span) {
589 self.format_missing_with_indent(source!(self, span).lo());
590 let lo = self.line_number + 1;
591 self.push_rewrite_inner(span, None);
592 let hi = self.line_number + 1;
593 self.skipped_range.push((lo, hi));
596 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
597 let mut visitor = FmtVisitor::from_source_map(
600 ctx.snippet_provider,
603 visitor.set_parent_context(ctx);
607 pub(crate) fn from_source_map(
608 parse_session: &'a ParseSess,
610 snippet_provider: &'a SnippetProvider,
611 report: FormatReport,
612 ) -> FmtVisitor<'a> {
614 parent_context: None,
616 source_map: parse_session.source_map(),
617 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
618 last_pos: BytePos(0),
619 block_indent: Indent::empty(),
621 is_if_else_block: false,
624 skipped_range: vec![],
625 macro_rewrite_failure: false,
630 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
631 self.snippet_provider.span_to_snippet(span)
634 pub fn snippet(&'b self, span: Span) -> &'a str {
635 self.opt_snippet(span).unwrap()
638 // Returns true if we should skip the following item.
639 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
641 if attr.name() == DEPR_SKIP_ANNOTATION {
642 let file_name = self.source_map.span_to_filename(attr.span).into();
645 vec![FormattingError::from_span(
648 ErrorKind::DeprecatedAttr,
651 } else if attr.path.segments[0].ident.to_string() == "rustfmt" {
652 if attr.path.segments.len() == 1
653 || attr.path.segments[1].ident.to_string() != "skip"
655 let file_name = self.source_map.span_to_filename(attr.span).into();
658 vec![FormattingError::from_span(
667 if contains_skip(attrs) {
671 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
672 if attrs.is_empty() {
676 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
677 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
678 self.push_rewrite(span, rewrite);
683 fn walk_mod_items(&mut self, m: &ast::Mod) {
684 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
687 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
688 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
690 ast::StmtKind::Item(ref item) => Some(&**item),
695 if stmts.is_empty() {
699 // Extract leading `use ...;`.
700 let items: Vec<_> = stmts
702 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
703 .filter_map(|stmt| to_stmt_item(stmt))
706 if items.is_empty() {
707 self.visit_stmt(&stmts[0]);
708 self.walk_stmts(&stmts[1..]);
710 self.visit_items_with_reordering(&items);
711 self.walk_stmts(&stmts[items.len()..]);
715 fn walk_block_stmts(&mut self, b: &ast::Block) {
716 self.walk_stmts(&b.stmts)
722 vis: &ast::Visibility,
725 attrs: &[ast::Attribute],
728 let vis_str = utils::format_visibility(&self.get_context(), vis);
729 self.push_str(&*vis_str);
730 self.push_str("mod ");
731 // Calling `to_owned()` to work around borrow checker.
732 let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
733 self.push_str(&ident_str);
736 match self.config.brace_style() {
737 BraceStyle::AlwaysNextLine => {
738 let indent_str = self.block_indent.to_string_with_newline(self.config);
739 self.push_str(&indent_str);
742 _ => self.push_str(" {"),
744 // Hackery to account for the closing }.
745 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
747 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
748 let body_snippet = body_snippet.trim();
749 if body_snippet.is_empty() {
752 self.last_pos = mod_lo;
753 self.block_indent = self.block_indent.block_indent(self.config);
754 self.visit_attrs(attrs, ast::AttrStyle::Inner);
755 self.walk_mod_items(m);
756 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
757 self.close_block(false);
759 self.last_pos = source!(self, m.inner).hi();
762 self.last_pos = source!(self, s).hi();
766 pub fn format_separate_mod(&mut self, m: &ast::Mod, source_file: &source_map::SourceFile) {
767 self.block_indent = Indent::empty();
768 self.walk_mod_items(m);
769 self.format_missing_with_indent(source_file.end_pos);
772 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
773 while let Some(pos) = self
775 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
777 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
778 if snippet.trim().is_empty() {
787 pub fn with_context<F>(&mut self, f: F) -> Option<String>
789 F: Fn(&RewriteContext) -> Option<String>,
792 let macro_rewrite_failure = {
793 let context = self.get_context();
794 result = f(&context);
795 unsafe { *context.macro_rewrite_failure.as_ptr() }
797 self.macro_rewrite_failure |= macro_rewrite_failure;
801 pub fn get_context(&self) -> RewriteContext {
803 parse_session: self.parse_session,
804 source_map: self.source_map,
806 inside_macro: RefCell::new(false),
807 use_block: RefCell::new(false),
808 is_if_else_block: RefCell::new(false),
809 force_one_line_chain: RefCell::new(false),
810 snippet_provider: self.snippet_provider,
811 macro_rewrite_failure: RefCell::new(false),
812 report: self.report.clone(),