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::codemap::{self, BytePos, CodeMap, Pos, Span};
13 use syntax::parse::ParseSess;
14 use syntax::{ast, visit};
17 use codemap::{LineRangeUtils, SpanUtils};
18 use comment::{CodeCharKind, CommentCodeSlices, FindUncommented};
19 use config::{BraceStyle, Config};
21 format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item,
22 rewrite_associated_impl_type, rewrite_associated_type, rewrite_extern_crate,
23 rewrite_type_alias, FnSig, StaticParts, StructParts,
25 use macros::{rewrite_macro, rewrite_macro_def, MacroPosition};
26 use rewrite::{Rewrite, RewriteContext};
27 use shape::{Indent, Shape};
30 self, contains_skip, count_newlines, inner_attributes, mk_sp, ptr_vec_to_ref_vec,
31 rewrite_ident, DEPR_SKIP_ANNOTATION,
33 use {ErrorKind, FormatReport, FormattingError};
35 use std::cell::RefCell;
37 /// Creates a string slice corresponding to the specified span.
38 pub struct SnippetProvider<'a> {
39 /// A pointer to the content of the file we are formatting.
41 /// A position of the start of `big_snippet`, used as an offset.
45 impl<'a> SnippetProvider<'a> {
46 pub fn span_to_snippet(&self, span: Span) -> Option<&str> {
47 let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
48 let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
49 Some(&self.big_snippet[start_index..end_index])
52 pub fn new(start_pos: BytePos, big_snippet: &'a str) -> Self {
53 let start_pos = start_pos.to_usize();
61 pub struct FmtVisitor<'a> {
62 pub parse_session: &'a ParseSess,
63 pub codemap: &'a CodeMap,
65 pub last_pos: BytePos,
66 // FIXME: use an RAII util or closure for indenting
67 pub block_indent: Indent,
68 pub config: &'a Config,
69 pub is_if_else_block: bool,
70 pub snippet_provider: &'a SnippetProvider<'a>,
71 pub line_number: usize,
72 pub skipped_range: Vec<(usize, usize)>,
73 pub macro_rewrite_failure: bool,
74 pub(crate) report: FormatReport,
77 impl<'b, 'a: 'b> FmtVisitor<'a> {
78 pub fn shape(&self) -> Shape {
79 Shape::indented(self.block_indent, self.config)
82 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
84 "visit_stmt: {:?} {:?}",
85 self.codemap.lookup_char_pos(stmt.span.lo()),
86 self.codemap.lookup_char_pos(stmt.span.hi())
90 ast::StmtKind::Item(ref item) => {
91 self.visit_item(item);
93 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
94 if contains_skip(get_attrs_from_stmt(stmt)) {
95 self.push_skipped_with_span(stmt.span());
97 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
98 self.push_rewrite(stmt.span(), rewrite)
101 ast::StmtKind::Mac(ref mac) => {
102 let (ref mac, _macro_style, ref attrs) = **mac;
103 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
104 self.push_skipped_with_span(stmt.span());
106 self.visit_mac(mac, None, MacroPosition::Statement);
108 self.format_missing(stmt.span.hi());
116 inner_attrs: Option<&[ast::Attribute]>,
120 "visit_block: {:?} {:?}",
121 self.codemap.lookup_char_pos(b.span.lo()),
122 self.codemap.lookup_char_pos(b.span.hi())
125 // Check if this block has braces.
126 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
128 self.last_pos = self.last_pos + brace_compensation;
129 self.block_indent = self.block_indent.block_indent(self.config);
132 if let Some(first_stmt) = b.stmts.first() {
133 let attr_lo = inner_attrs
134 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
136 // Attributes for an item in a statement position
137 // do not belong to the statement. (rust-lang/rust#34459)
138 if let ast::StmtKind::Item(ref item) = first_stmt.node {
141 first_stmt.attrs().first()
143 // Some stmts can have embedded attributes.
144 // e.g. `match { #![attr] ... }`
145 let attr_lo = attr.span.lo();
146 if attr_lo < first_stmt.span.lo() {
154 let snippet = self.snippet(mk_sp(
156 attr_lo.unwrap_or_else(|| first_stmt.span.lo()),
158 let len = CommentCodeSlices::new(snippet)
160 .and_then(|(kind, _, s)| {
161 if kind == CodeCharKind::Normal {
167 if let Some(len) = len {
168 self.last_pos = self.last_pos + BytePos::from_usize(len);
172 // Format inner attributes if available.
173 let skip_rewrite = if let Some(attrs) = inner_attrs {
174 self.visit_attrs(attrs, ast::AttrStyle::Inner)
180 self.push_rewrite(b.span, None);
181 self.close_block(false);
182 self.last_pos = source!(self, b.span).hi();
186 self.walk_block_stmts(b);
188 if !b.stmts.is_empty() {
189 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
190 if utils::semicolon_for_expr(&self.get_context(), expr) {
196 let mut remove_len = BytePos(0);
197 if let Some(stmt) = b.stmts.last() {
198 let snippet = self.snippet(mk_sp(
200 source!(self, b.span).hi() - brace_compensation,
202 let len = CommentCodeSlices::new(snippet)
204 .and_then(|(kind, _, s)| {
205 if kind == CodeCharKind::Normal && s.trim().is_empty() {
211 if let Some(len) = len {
212 remove_len = BytePos::from_usize(len);
216 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
217 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
218 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
219 snippet.contains("//") || snippet.contains("/*")
221 // FIXME: we should compress any newlines here to just one
222 if unindent_comment {
223 self.block_indent = self.block_indent.block_unindent(self.config);
225 self.format_missing_with_indent(
226 source!(self, b.span).hi() - brace_compensation - remove_len,
228 if unindent_comment {
229 self.block_indent = self.block_indent.block_indent(self.config);
231 self.close_block(unindent_comment);
232 self.last_pos = source!(self, b.span).hi();
235 // FIXME: this is a terrible hack to indent the comments between the last
236 // item in the block and the closing brace to the block's level.
237 // The closing brace itself, however, should be indented at a shallower
239 fn close_block(&mut self, unindent_comment: bool) {
240 let total_len = self.buffer.len();
241 let chars_too_many = if unindent_comment {
243 } else if self.config.hard_tabs() {
246 self.config.tab_spaces()
248 self.buffer.truncate(total_len - chars_too_many);
250 self.block_indent = self.block_indent.block_unindent(self.config);
253 // Note that this only gets called for function definitions. Required methods
254 // on traits do not get handled here.
258 generics: &ast::Generics,
261 defaultness: ast::Defaultness,
262 inner_attrs: Option<&[ast::Attribute]>,
264 let indent = self.block_indent;
266 let rewrite = match fk {
267 visit::FnKind::ItemFn(ident, _, _, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
272 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
273 mk_sp(s.lo(), b.span.lo()),
278 visit::FnKind::Closure(_) => unreachable!(),
281 if let Some(fn_str) = rewrite {
282 self.format_missing_with_indent(source!(self, s).lo());
283 self.push_str(&fn_str);
284 if let Some(c) = fn_str.chars().last() {
286 self.last_pos = source!(self, block.span).hi();
291 self.format_missing(source!(self, block.span).lo());
294 self.last_pos = source!(self, block.span).lo();
295 self.visit_block(block, inner_attrs, true)
298 pub fn visit_item(&mut self, item: &ast::Item) {
299 skip_out_of_file_lines_range_visitor!(self, item.span);
301 // This is where we bail out if there is a skip attribute. This is only
302 // complex in the module case. It is complex because the module could be
303 // in a separate file and there might be attributes in both files, but
304 // the AST lumps them all together.
306 let mut attrs = &item.attrs;
308 // For use items, skip rewriting attributes. Just check for a skip attribute.
309 ast::ItemKind::Use(..) => {
310 if contains_skip(attrs) {
311 self.push_skipped_with_span(item.span());
315 // Module is inline, in this case we treat it like any other item.
316 _ if !is_mod_decl(item) => {
317 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
318 self.push_skipped_with_span(item.span());
322 // Module is not inline, but should be skipped.
323 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
326 // Module is not inline and should not be skipped. We want
327 // to process only the attributes in the current file.
328 ast::ItemKind::Mod(..) => {
329 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
330 // Assert because if we should skip it should be caught by
332 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
333 attrs = &filtered_attrs;
336 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
337 self.push_skipped_with_span(item.span());
344 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
345 ast::ItemKind::Impl(..) => {
346 let snippet = self.snippet(item.span);
347 let where_span_end = snippet
348 .find_uncommented("{")
349 .map(|x| BytePos(x as u32) + source!(self, item.span).lo());
350 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
351 self.push_rewrite(item.span, rw);
353 ast::ItemKind::Trait(..) => {
354 let rw = format_trait(&self.get_context(), item, self.block_indent);
355 self.push_rewrite(item.span, rw);
357 ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => {
358 let shape = Shape::indented(self.block_indent, self.config);
359 let rw = format_trait_alias(
366 self.push_rewrite(item.span, rw);
368 ast::ItemKind::ExternCrate(_) => {
369 let rw = rewrite_extern_crate(&self.get_context(), item);
370 self.push_rewrite(item.span, rw);
372 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
373 self.visit_struct(&StructParts::from_item(item));
375 ast::ItemKind::Enum(ref def, ref generics) => {
376 self.format_missing_with_indent(source!(self, item.span).lo());
377 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
378 self.last_pos = source!(self, item.span).hi();
380 ast::ItemKind::Mod(ref module) => {
381 let is_inline = !is_mod_decl(item);
382 self.format_missing_with_indent(source!(self, item.span).lo());
383 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
385 ast::ItemKind::Mac(ref mac) => {
386 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
388 ast::ItemKind::ForeignMod(ref foreign_mod) => {
389 self.format_missing_with_indent(source!(self, item.span).lo());
390 self.format_foreign_mod(foreign_mod, item.span);
392 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
393 self.visit_static(&StaticParts::from_item(item));
395 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
396 let inner_attrs = inner_attributes(&item.attrs);
398 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
402 ast::Defaultness::Final,
406 ast::ItemKind::Ty(ref ty, ref generics) => {
407 let rewrite = rewrite_type_alias(
416 self.push_rewrite(item.span, rewrite);
418 ast::ItemKind::GlobalAsm(..) => {
419 let snippet = Some(self.snippet(item.span).to_owned());
420 self.push_rewrite(item.span, snippet);
422 ast::ItemKind::MacroDef(ref def) => {
423 let rewrite = rewrite_macro_def(
432 self.push_rewrite(item.span, rewrite);
437 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
438 skip_out_of_file_lines_range_visitor!(self, ti.span);
440 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
441 self.push_skipped_with_span(ti.span());
446 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
447 ast::TraitItemKind::Method(ref sig, None) => {
448 let indent = self.block_indent;
450 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
451 self.push_rewrite(ti.span, rewrite);
453 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
454 let inner_attrs = inner_attributes(&ti.attrs);
456 visit::FnKind::Method(ti.ident, sig, None, body),
460 ast::Defaultness::Final,
464 ast::TraitItemKind::Type(ref generic_bounds, ref type_default) => {
465 let rewrite = rewrite_associated_type(
467 type_default.as_ref(),
468 Some(generic_bounds),
472 self.push_rewrite(ti.span, rewrite);
474 ast::TraitItemKind::Macro(ref mac) => {
475 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
480 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
481 skip_out_of_file_lines_range_visitor!(self, ii.span);
483 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
484 self.push_skipped_with_span(ii.span());
489 ast::ImplItemKind::Method(ref sig, ref body) => {
490 let inner_attrs = inner_attributes(&ii.attrs);
492 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
500 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
501 ast::ImplItemKind::Type(ref ty) => {
502 let rewrite = rewrite_associated_impl_type(
510 self.push_rewrite(ii.span, rewrite);
512 ast::ImplItemKind::Macro(ref mac) => {
513 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
518 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
519 skip_out_of_file_lines_range_visitor!(self, mac.span);
522 let shape = self.shape().sub_width(1).unwrap();
523 let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos));
524 self.push_rewrite(mac.span, rewrite);
527 pub fn push_str(&mut self, s: &str) {
528 self.line_number += count_newlines(s);
529 self.buffer.push_str(s);
532 #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
533 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
534 if let Some(ref s) = rewrite {
537 let snippet = self.snippet(span);
538 self.push_str(snippet);
540 self.last_pos = source!(self, span).hi();
543 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
544 self.format_missing_with_indent(source!(self, span).lo());
545 self.push_rewrite_inner(span, rewrite);
548 pub fn push_skipped_with_span(&mut self, span: Span) {
549 self.format_missing_with_indent(source!(self, span).lo());
550 let lo = self.line_number + 1;
551 self.push_rewrite_inner(span, None);
552 let hi = self.line_number + 1;
553 self.skipped_range.push((lo, hi));
556 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
557 FmtVisitor::from_codemap(
560 ctx.snippet_provider,
565 pub(crate) fn from_codemap(
566 parse_session: &'a ParseSess,
568 snippet_provider: &'a SnippetProvider,
569 report: FormatReport,
570 ) -> FmtVisitor<'a> {
573 codemap: parse_session.codemap(),
574 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
575 last_pos: BytePos(0),
576 block_indent: Indent::empty(),
578 is_if_else_block: false,
581 skipped_range: vec![],
582 macro_rewrite_failure: false,
587 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
588 self.snippet_provider.span_to_snippet(span)
591 pub fn snippet(&'b self, span: Span) -> &'a str {
592 self.opt_snippet(span).unwrap()
595 // Returns true if we should skip the following item.
596 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
598 if attr.name() == DEPR_SKIP_ANNOTATION {
599 let file_name = self.codemap.span_to_filename(attr.span).into();
602 vec![FormattingError::from_span(
605 ErrorKind::DeprecatedAttr,
608 } else if attr.path.segments[0].ident.to_string() == "rustfmt" {
609 if attr.path.segments.len() == 1
610 || attr.path.segments[1].ident.to_string() != "skip"
612 let file_name = self.codemap.span_to_filename(attr.span).into();
615 vec![FormattingError::from_span(
624 if contains_skip(attrs) {
628 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
629 if attrs.is_empty() {
633 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
634 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
635 self.push_rewrite(span, rewrite);
640 fn walk_mod_items(&mut self, m: &ast::Mod) {
641 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
644 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
645 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
647 ast::StmtKind::Item(ref item) => Some(&**item),
652 if stmts.is_empty() {
656 // Extract leading `use ...;`.
657 let items: Vec<_> = stmts
659 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
660 .filter_map(|stmt| to_stmt_item(stmt))
663 if items.is_empty() {
664 self.visit_stmt(&stmts[0]);
665 self.walk_stmts(&stmts[1..]);
667 self.visit_items_with_reordering(&items);
668 self.walk_stmts(&stmts[items.len()..]);
672 fn walk_block_stmts(&mut self, b: &ast::Block) {
673 self.walk_stmts(&b.stmts)
679 vis: &ast::Visibility,
682 attrs: &[ast::Attribute],
685 let vis_str = utils::format_visibility(&self.get_context(), vis);
686 self.push_str(&*vis_str);
687 self.push_str("mod ");
688 // Calling `to_owned()` to work around borrow checker.
689 let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
690 self.push_str(&ident_str);
693 match self.config.brace_style() {
694 BraceStyle::AlwaysNextLine => {
695 let indent_str = self.block_indent.to_string_with_newline(self.config);
696 self.push_str(&indent_str);
699 _ => self.push_str(" {"),
701 // Hackery to account for the closing }.
702 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
704 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
705 let body_snippet = body_snippet.trim();
706 if body_snippet.is_empty() {
709 self.last_pos = mod_lo;
710 self.block_indent = self.block_indent.block_indent(self.config);
711 self.visit_attrs(attrs, ast::AttrStyle::Inner);
712 self.walk_mod_items(m);
713 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
714 self.close_block(false);
716 self.last_pos = source!(self, m.inner).hi();
719 self.last_pos = source!(self, s).hi();
723 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
724 self.block_indent = Indent::empty();
725 self.walk_mod_items(m);
726 self.format_missing_with_indent(filemap.end_pos);
729 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
730 while let Some(pos) = self
732 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
734 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
735 if snippet.trim().is_empty() {
744 pub fn with_context<F>(&mut self, f: F) -> Option<String>
746 F: Fn(&RewriteContext) -> Option<String>,
749 let macro_rewrite_failure = {
750 let context = self.get_context();
751 result = f(&context);
752 unsafe { *context.macro_rewrite_failure.as_ptr() }
754 self.macro_rewrite_failure |= macro_rewrite_failure;
758 pub fn get_context(&self) -> RewriteContext {
760 parse_session: self.parse_session,
761 codemap: self.codemap,
763 inside_macro: RefCell::new(false),
764 use_block: RefCell::new(false),
765 is_if_else_block: RefCell::new(false),
766 force_one_line_chain: RefCell::new(false),
767 snippet_provider: self.snippet_provider,
768 macro_rewrite_failure: RefCell::new(false),
769 report: self.report.clone(),