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();
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()
163 // Some stmts can have embedded attributes.
164 // e.g. `match { #![attr] ... }`
165 let attr_lo = attr.span.lo();
166 if attr_lo < first_stmt.span.lo() {
174 let snippet = self.snippet(mk_sp(
176 attr_lo.unwrap_or_else(|| first_stmt.span.lo()),
178 let len = CommentCodeSlices::new(snippet)
180 .and_then(|(kind, _, s)| {
181 if kind == CodeCharKind::Normal {
187 if let Some(len) = len {
188 self.last_pos = self.last_pos + BytePos::from_usize(len);
192 // Format inner attributes if available.
193 let skip_rewrite = if let Some(attrs) = inner_attrs {
194 self.visit_attrs(attrs, ast::AttrStyle::Inner)
200 self.push_rewrite(b.span, None);
201 self.close_block(false);
202 self.last_pos = source!(self, b.span).hi();
206 self.walk_block_stmts(b);
208 if !b.stmts.is_empty() {
209 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
210 if utils::semicolon_for_expr(&self.get_context(), expr) {
216 let mut remove_len = BytePos(0);
217 if let Some(stmt) = b.stmts.last() {
218 let snippet = self.snippet(mk_sp(
220 source!(self, b.span).hi() - brace_compensation,
222 let len = CommentCodeSlices::new(snippet)
224 .and_then(|(kind, _, s)| {
225 if kind == CodeCharKind::Normal && s.trim().is_empty() {
231 if let Some(len) = len {
232 remove_len = BytePos::from_usize(len);
236 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
237 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
238 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
239 snippet.contains("//") || snippet.contains("/*")
241 // FIXME: we should compress any newlines here to just one
242 if unindent_comment {
243 self.block_indent = self.block_indent.block_unindent(self.config);
245 self.format_missing_with_indent(
246 source!(self, b.span).hi() - brace_compensation - remove_len,
248 if unindent_comment {
249 self.block_indent = self.block_indent.block_indent(self.config);
251 self.close_block(unindent_comment);
252 self.last_pos = source!(self, b.span).hi();
255 // FIXME: this is a terrible hack to indent the comments between the last
256 // item in the block and the closing brace to the block's level.
257 // The closing brace itself, however, should be indented at a shallower
259 fn close_block(&mut self, unindent_comment: bool) {
260 let total_len = self.buffer.len();
261 let chars_too_many = if unindent_comment {
263 } else if self.config.hard_tabs() {
266 self.config.tab_spaces()
268 self.buffer.truncate(total_len - chars_too_many);
270 self.block_indent = self.block_indent.block_unindent(self.config);
273 // Note that this only gets called for function definitions. Required methods
274 // on traits do not get handled here.
278 generics: &ast::Generics,
281 defaultness: ast::Defaultness,
282 inner_attrs: Option<&[ast::Attribute]>,
284 let indent = self.block_indent;
286 let rewrite = match fk {
287 visit::FnKind::ItemFn(ident, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
292 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
293 mk_sp(s.lo(), b.span.lo()),
298 visit::FnKind::Closure(_) => unreachable!(),
301 if let Some(fn_str) = rewrite {
302 self.format_missing_with_indent(source!(self, s).lo());
303 self.push_str(&fn_str);
304 if let Some(c) = fn_str.chars().last() {
306 self.last_pos = source!(self, block.span).hi();
311 self.format_missing(source!(self, block.span).lo());
314 self.last_pos = source!(self, block.span).lo();
315 self.visit_block(block, inner_attrs, true)
318 pub fn visit_item(&mut self, item: &ast::Item) {
319 skip_out_of_file_lines_range_visitor!(self, item.span);
321 // This is where we bail out if there is a skip attribute. This is only
322 // complex in the module case. It is complex because the module could be
323 // in a separate file and there might be attributes in both files, but
324 // the AST lumps them all together.
326 let mut attrs = &item.attrs;
328 // For use items, skip rewriting attributes. Just check for a skip attribute.
329 ast::ItemKind::Use(..) => {
330 if contains_skip(attrs) {
331 self.push_skipped_with_span(item.span());
335 // Module is inline, in this case we treat it like any other item.
336 _ if !is_mod_decl(item) => {
337 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
338 self.push_skipped_with_span(item.span());
342 // Module is not inline, but should be skipped.
343 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
346 // Module is not inline and should not be skipped. We want
347 // to process only the attributes in the current file.
348 ast::ItemKind::Mod(..) => {
349 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
350 // Assert because if we should skip it should be caught by
352 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
353 attrs = &filtered_attrs;
356 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
357 self.push_skipped_with_span(item.span());
364 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
365 ast::ItemKind::Impl(..) => {
366 let snippet = self.snippet(item.span);
367 let where_span_end = snippet
368 .find_uncommented("{")
369 .map(|x| BytePos(x as u32) + source!(self, item.span).lo());
370 let block_indent = self.block_indent;
372 self.with_context(|ctx| format_impl(&ctx, item, block_indent, where_span_end));
373 self.push_rewrite(item.span, rw);
375 ast::ItemKind::Trait(..) => {
376 let block_indent = self.block_indent;
377 let rw = self.with_context(|ctx| format_trait(&ctx, item, block_indent));
378 self.push_rewrite(item.span, rw);
380 ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => {
381 let shape = Shape::indented(self.block_indent, self.config);
382 let rw = format_trait_alias(
389 self.push_rewrite(item.span, rw);
391 ast::ItemKind::ExternCrate(_) => {
392 let rw = rewrite_extern_crate(&self.get_context(), item);
393 self.push_rewrite(item.span, rw);
395 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
396 self.visit_struct(&StructParts::from_item(item));
398 ast::ItemKind::Enum(ref def, ref generics) => {
399 self.format_missing_with_indent(source!(self, item.span).lo());
400 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
401 self.last_pos = source!(self, item.span).hi();
403 ast::ItemKind::Mod(ref module) => {
404 let is_inline = !is_mod_decl(item);
405 self.format_missing_with_indent(source!(self, item.span).lo());
406 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
408 ast::ItemKind::Mac(ref mac) => {
409 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
411 ast::ItemKind::ForeignMod(ref foreign_mod) => {
412 self.format_missing_with_indent(source!(self, item.span).lo());
413 self.format_foreign_mod(foreign_mod, item.span);
415 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
416 self.visit_static(&StaticParts::from_item(item));
418 ast::ItemKind::Fn(ref decl, fn_header, ref generics, ref body) => {
419 let inner_attrs = inner_attributes(&item.attrs);
421 visit::FnKind::ItemFn(item.ident, fn_header, &item.vis, body),
425 ast::Defaultness::Final,
429 ast::ItemKind::Ty(ref ty, ref generics) => {
430 let rewrite = rewrite_type_alias(
438 self.push_rewrite(item.span, rewrite);
440 ast::ItemKind::Existential(ref generic_bounds, ref generics) => {
441 let rewrite = rewrite_existential_type(
449 self.push_rewrite(item.span, rewrite);
451 ast::ItemKind::GlobalAsm(..) => {
452 let snippet = Some(self.snippet(item.span).to_owned());
453 self.push_rewrite(item.span, snippet);
455 ast::ItemKind::MacroDef(ref def) => {
456 let rewrite = rewrite_macro_def(
465 self.push_rewrite(item.span, rewrite);
470 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
471 skip_out_of_file_lines_range_visitor!(self, ti.span);
473 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
474 self.push_skipped_with_span(ti.span());
479 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
480 ast::TraitItemKind::Method(ref sig, None) => {
481 let indent = self.block_indent;
483 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
484 self.push_rewrite(ti.span, rewrite);
486 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
487 let inner_attrs = inner_attributes(&ti.attrs);
489 visit::FnKind::Method(ti.ident, sig, None, body),
493 ast::Defaultness::Final,
497 ast::TraitItemKind::Type(ref generic_bounds, ref type_default) => {
498 let rewrite = rewrite_associated_type(
500 type_default.as_ref(),
502 Some(generic_bounds),
506 self.push_rewrite(ti.span, rewrite);
508 ast::TraitItemKind::Macro(ref mac) => {
509 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
514 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
515 skip_out_of_file_lines_range_visitor!(self, ii.span);
517 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
518 self.push_skipped_with_span(ii.span());
523 ast::ImplItemKind::Method(ref sig, ref body) => {
524 let inner_attrs = inner_attributes(&ii.attrs);
526 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
534 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
535 ast::ImplItemKind::Type(ref ty) => {
536 let rewrite = rewrite_associated_impl_type(
544 self.push_rewrite(ii.span, rewrite);
546 ast::ImplItemKind::Existential(ref generic_bounds) => {
547 let rewrite = rewrite_existential_impl_type(
554 self.push_rewrite(ii.span, rewrite);
556 ast::ImplItemKind::Macro(ref mac) => {
557 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
562 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
563 skip_out_of_file_lines_range_visitor!(self, mac.span);
566 let shape = self.shape().sub_width(1).unwrap();
567 let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos));
568 self.push_rewrite(mac.span, rewrite);
571 pub fn push_str(&mut self, s: &str) {
572 self.line_number += count_newlines(s);
573 self.buffer.push_str(s);
576 #[allow(clippy::needless_pass_by_value)]
577 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
578 if let Some(ref s) = rewrite {
581 let snippet = self.snippet(span);
582 self.push_str(snippet);
584 self.last_pos = source!(self, span).hi();
587 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
588 self.format_missing_with_indent(source!(self, span).lo());
589 self.push_rewrite_inner(span, rewrite);
592 pub fn push_skipped_with_span(&mut self, span: Span) {
593 self.format_missing_with_indent(source!(self, span).lo());
594 let lo = self.line_number + 1;
595 self.push_rewrite_inner(span, None);
596 let hi = self.line_number + 1;
597 self.skipped_range.push((lo, hi));
600 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
601 let mut visitor = FmtVisitor::from_source_map(
604 ctx.snippet_provider,
607 visitor.set_parent_context(ctx);
611 pub(crate) fn from_source_map(
612 parse_session: &'a ParseSess,
614 snippet_provider: &'a SnippetProvider,
615 report: FormatReport,
616 ) -> FmtVisitor<'a> {
618 parent_context: None,
620 source_map: parse_session.source_map(),
621 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
622 last_pos: BytePos(0),
623 block_indent: Indent::empty(),
625 is_if_else_block: false,
628 skipped_range: vec![],
629 macro_rewrite_failure: false,
634 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
635 self.snippet_provider.span_to_snippet(span)
638 pub fn snippet(&'b self, span: Span) -> &'a str {
639 self.opt_snippet(span).unwrap()
642 // Returns true if we should skip the following item.
643 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
645 if attr.name() == DEPR_SKIP_ANNOTATION {
646 let file_name = self.source_map.span_to_filename(attr.span).into();
649 vec![FormattingError::from_span(
652 ErrorKind::DeprecatedAttr,
655 } else if attr.path.segments[0].ident.to_string() == "rustfmt"
656 && (attr.path.segments.len() == 1
657 || attr.path.segments[1].ident.to_string() != "skip")
659 let file_name = self.source_map.span_to_filename(attr.span).into();
662 vec![FormattingError::from_span(
670 if contains_skip(attrs) {
674 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
675 if attrs.is_empty() {
679 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
680 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
681 self.push_rewrite(span, rewrite);
686 fn walk_mod_items(&mut self, m: &ast::Mod) {
687 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
690 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
691 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
693 ast::StmtKind::Item(ref item) => Some(&**item),
698 if stmts.is_empty() {
702 // Extract leading `use ...;`.
703 let items: Vec<_> = stmts
705 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
706 .filter_map(|stmt| to_stmt_item(stmt))
709 if items.is_empty() {
710 self.visit_stmt(&stmts[0]);
711 self.walk_stmts(&stmts[1..]);
713 self.visit_items_with_reordering(&items);
714 self.walk_stmts(&stmts[items.len()..]);
718 fn walk_block_stmts(&mut self, b: &ast::Block) {
719 self.walk_stmts(&b.stmts)
725 vis: &ast::Visibility,
728 attrs: &[ast::Attribute],
731 let vis_str = utils::format_visibility(&self.get_context(), vis);
732 self.push_str(&*vis_str);
733 self.push_str("mod ");
734 // Calling `to_owned()` to work around borrow checker.
735 let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
736 self.push_str(&ident_str);
739 match self.config.brace_style() {
740 BraceStyle::AlwaysNextLine => {
741 let indent_str = self.block_indent.to_string_with_newline(self.config);
742 self.push_str(&indent_str);
745 _ => self.push_str(" {"),
747 // Hackery to account for the closing }.
748 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
750 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
751 let body_snippet = body_snippet.trim();
752 if body_snippet.is_empty() {
755 self.last_pos = mod_lo;
756 self.block_indent = self.block_indent.block_indent(self.config);
757 self.visit_attrs(attrs, ast::AttrStyle::Inner);
758 self.walk_mod_items(m);
759 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
760 self.close_block(false);
762 self.last_pos = source!(self, m.inner).hi();
765 self.last_pos = source!(self, s).hi();
769 pub fn format_separate_mod(&mut self, m: &ast::Mod, source_file: &source_map::SourceFile) {
770 self.block_indent = Indent::empty();
771 self.walk_mod_items(m);
772 self.format_missing_with_indent(source_file.end_pos);
775 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
776 while let Some(pos) = self
778 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
780 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
781 if snippet.trim().is_empty() {
790 pub fn with_context<F>(&mut self, f: F) -> Option<String>
792 F: Fn(&RewriteContext) -> Option<String>,
794 // FIXME borrow checker fighting - can be simplified a lot with NLL.
795 let (result, mrf) = {
796 let context = self.get_context();
797 let result = f(&context);
798 let mrf = &context.macro_rewrite_failure.borrow();
799 (result, *std::ops::Deref::deref(mrf))
802 self.macro_rewrite_failure |= mrf;
806 pub fn get_context(&self) -> RewriteContext {
808 parse_session: self.parse_session,
809 source_map: self.source_map,
811 inside_macro: RefCell::new(false),
812 use_block: RefCell::new(false),
813 is_if_else_block: RefCell::new(false),
814 force_one_line_chain: RefCell::new(false),
815 snippet_provider: self.snippet_provider,
816 macro_rewrite_failure: RefCell::new(false),
817 report: self.report.clone(),