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 pub parse_session: &'a ParseSess,
64 pub source_map: &'a SourceMap,
66 pub last_pos: BytePos,
67 // FIXME: use an RAII util or closure for indenting
68 pub block_indent: Indent,
69 pub config: &'a Config,
70 pub is_if_else_block: bool,
71 pub snippet_provider: &'a SnippetProvider<'a>,
72 pub line_number: usize,
73 pub skipped_range: Vec<(usize, usize)>,
74 pub macro_rewrite_failure: bool,
75 pub(crate) report: FormatReport,
78 impl<'b, 'a: 'b> FmtVisitor<'a> {
79 pub fn shape(&self) -> Shape {
80 Shape::indented(self.block_indent, self.config)
83 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
85 "visit_stmt: {:?} {:?}",
86 self.source_map.lookup_char_pos(stmt.span.lo()),
87 self.source_map.lookup_char_pos(stmt.span.hi())
91 ast::StmtKind::Item(ref item) => {
92 self.visit_item(item);
93 // Handle potential `;` after the item.
94 self.format_missing(stmt.span.hi());
96 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
97 if contains_skip(get_attrs_from_stmt(stmt)) {
98 self.push_skipped_with_span(stmt.span());
100 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
101 self.push_rewrite(stmt.span(), rewrite)
104 ast::StmtKind::Mac(ref mac) => {
105 let (ref mac, _macro_style, ref attrs) = **mac;
106 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
107 self.push_skipped_with_span(stmt.span());
109 self.visit_mac(mac, None, MacroPosition::Statement);
111 self.format_missing(stmt.span.hi());
119 inner_attrs: Option<&[ast::Attribute]>,
123 "visit_block: {:?} {:?}",
124 self.source_map.lookup_char_pos(b.span.lo()),
125 self.source_map.lookup_char_pos(b.span.hi())
128 // Check if this block has braces.
129 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
131 self.last_pos = self.last_pos + brace_compensation;
132 self.block_indent = self.block_indent.block_indent(self.config);
135 if let Some(first_stmt) = b.stmts.first() {
136 let attr_lo = inner_attrs
137 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
139 // Attributes for an item in a statement position
140 // do not belong to the statement. (rust-lang/rust#34459)
141 if let ast::StmtKind::Item(ref item) = first_stmt.node {
144 first_stmt.attrs().first()
146 // Some stmts can have embedded attributes.
147 // e.g. `match { #![attr] ... }`
148 let attr_lo = attr.span.lo();
149 if attr_lo < first_stmt.span.lo() {
157 let snippet = self.snippet(mk_sp(
159 attr_lo.unwrap_or_else(|| first_stmt.span.lo()),
161 let len = CommentCodeSlices::new(snippet)
163 .and_then(|(kind, _, s)| {
164 if kind == CodeCharKind::Normal {
170 if let Some(len) = len {
171 self.last_pos = self.last_pos + BytePos::from_usize(len);
175 // Format inner attributes if available.
176 let skip_rewrite = if let Some(attrs) = inner_attrs {
177 self.visit_attrs(attrs, ast::AttrStyle::Inner)
183 self.push_rewrite(b.span, None);
184 self.close_block(false);
185 self.last_pos = source!(self, b.span).hi();
189 self.walk_block_stmts(b);
191 if !b.stmts.is_empty() {
192 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
193 if utils::semicolon_for_expr(&self.get_context(), expr) {
199 let mut remove_len = BytePos(0);
200 if let Some(stmt) = b.stmts.last() {
201 let snippet = self.snippet(mk_sp(
203 source!(self, b.span).hi() - brace_compensation,
205 let len = CommentCodeSlices::new(snippet)
207 .and_then(|(kind, _, s)| {
208 if kind == CodeCharKind::Normal && s.trim().is_empty() {
214 if let Some(len) = len {
215 remove_len = BytePos::from_usize(len);
219 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
220 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
221 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
222 snippet.contains("//") || snippet.contains("/*")
224 // FIXME: we should compress any newlines here to just one
225 if unindent_comment {
226 self.block_indent = self.block_indent.block_unindent(self.config);
228 self.format_missing_with_indent(
229 source!(self, b.span).hi() - brace_compensation - remove_len,
231 if unindent_comment {
232 self.block_indent = self.block_indent.block_indent(self.config);
234 self.close_block(unindent_comment);
235 self.last_pos = source!(self, b.span).hi();
238 // FIXME: this is a terrible hack to indent the comments between the last
239 // item in the block and the closing brace to the block's level.
240 // The closing brace itself, however, should be indented at a shallower
242 fn close_block(&mut self, unindent_comment: bool) {
243 let total_len = self.buffer.len();
244 let chars_too_many = if unindent_comment {
246 } else if self.config.hard_tabs() {
249 self.config.tab_spaces()
251 self.buffer.truncate(total_len - chars_too_many);
253 self.block_indent = self.block_indent.block_unindent(self.config);
256 // Note that this only gets called for function definitions. Required methods
257 // on traits do not get handled here.
261 generics: &ast::Generics,
264 defaultness: ast::Defaultness,
265 inner_attrs: Option<&[ast::Attribute]>,
267 let indent = self.block_indent;
269 let rewrite = match fk {
270 visit::FnKind::ItemFn(ident, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
275 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
276 mk_sp(s.lo(), b.span.lo()),
281 visit::FnKind::Closure(_) => unreachable!(),
284 if let Some(fn_str) = rewrite {
285 self.format_missing_with_indent(source!(self, s).lo());
286 self.push_str(&fn_str);
287 if let Some(c) = fn_str.chars().last() {
289 self.last_pos = source!(self, block.span).hi();
294 self.format_missing(source!(self, block.span).lo());
297 self.last_pos = source!(self, block.span).lo();
298 self.visit_block(block, inner_attrs, true)
301 pub fn visit_item(&mut self, item: &ast::Item) {
302 skip_out_of_file_lines_range_visitor!(self, item.span);
304 // This is where we bail out if there is a skip attribute. This is only
305 // complex in the module case. It is complex because the module could be
306 // in a separate file and there might be attributes in both files, but
307 // the AST lumps them all together.
309 let mut attrs = &item.attrs;
311 // For use items, skip rewriting attributes. Just check for a skip attribute.
312 ast::ItemKind::Use(..) => {
313 if contains_skip(attrs) {
314 self.push_skipped_with_span(item.span());
318 // Module is inline, in this case we treat it like any other item.
319 _ if !is_mod_decl(item) => {
320 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
321 self.push_skipped_with_span(item.span());
325 // Module is not inline, but should be skipped.
326 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
329 // Module is not inline and should not be skipped. We want
330 // to process only the attributes in the current file.
331 ast::ItemKind::Mod(..) => {
332 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
333 // Assert because if we should skip it should be caught by
335 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
336 attrs = &filtered_attrs;
339 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
340 self.push_skipped_with_span(item.span());
347 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
348 ast::ItemKind::Impl(..) => {
349 let snippet = self.snippet(item.span);
350 let where_span_end = snippet
351 .find_uncommented("{")
352 .map(|x| BytePos(x as u32) + source!(self, item.span).lo());
353 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
354 self.push_rewrite(item.span, rw);
356 ast::ItemKind::Trait(..) => {
357 let rw = format_trait(&self.get_context(), item, self.block_indent);
358 self.push_rewrite(item.span, rw);
360 ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => {
361 let shape = Shape::indented(self.block_indent, self.config);
362 let rw = format_trait_alias(
369 self.push_rewrite(item.span, rw);
371 ast::ItemKind::ExternCrate(_) => {
372 let rw = rewrite_extern_crate(&self.get_context(), item);
373 self.push_rewrite(item.span, rw);
375 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
376 self.visit_struct(&StructParts::from_item(item));
378 ast::ItemKind::Enum(ref def, ref generics) => {
379 self.format_missing_with_indent(source!(self, item.span).lo());
380 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
381 self.last_pos = source!(self, item.span).hi();
383 ast::ItemKind::Mod(ref module) => {
384 let is_inline = !is_mod_decl(item);
385 self.format_missing_with_indent(source!(self, item.span).lo());
386 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
388 ast::ItemKind::Mac(ref mac) => {
389 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
391 ast::ItemKind::ForeignMod(ref foreign_mod) => {
392 self.format_missing_with_indent(source!(self, item.span).lo());
393 self.format_foreign_mod(foreign_mod, item.span);
395 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
396 self.visit_static(&StaticParts::from_item(item));
398 ast::ItemKind::Fn(ref decl, fn_header, ref generics, ref body) => {
399 let inner_attrs = inner_attributes(&item.attrs);
401 visit::FnKind::ItemFn(item.ident, fn_header, &item.vis, body),
405 ast::Defaultness::Final,
409 ast::ItemKind::Ty(ref ty, ref generics) => {
410 let rewrite = rewrite_type_alias(
418 self.push_rewrite(item.span, rewrite);
420 ast::ItemKind::Existential(ref generic_bounds, ref generics) => {
421 let rewrite = rewrite_existential_type(
429 self.push_rewrite(item.span, rewrite);
431 ast::ItemKind::GlobalAsm(..) => {
432 let snippet = Some(self.snippet(item.span).to_owned());
433 self.push_rewrite(item.span, snippet);
435 ast::ItemKind::MacroDef(ref def) => {
436 let rewrite = rewrite_macro_def(
445 self.push_rewrite(item.span, rewrite);
450 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
451 skip_out_of_file_lines_range_visitor!(self, ti.span);
453 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
454 self.push_skipped_with_span(ti.span());
459 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
460 ast::TraitItemKind::Method(ref sig, None) => {
461 let indent = self.block_indent;
463 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
464 self.push_rewrite(ti.span, rewrite);
466 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
467 let inner_attrs = inner_attributes(&ti.attrs);
469 visit::FnKind::Method(ti.ident, sig, None, body),
473 ast::Defaultness::Final,
477 ast::TraitItemKind::Type(ref generic_bounds, ref type_default) => {
478 let rewrite = rewrite_associated_type(
480 type_default.as_ref(),
481 Some(generic_bounds),
485 self.push_rewrite(ti.span, rewrite);
487 ast::TraitItemKind::Macro(ref mac) => {
488 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
493 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
494 skip_out_of_file_lines_range_visitor!(self, ii.span);
496 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
497 self.push_skipped_with_span(ii.span());
502 ast::ImplItemKind::Method(ref sig, ref body) => {
503 let inner_attrs = inner_attributes(&ii.attrs);
505 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
513 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
514 ast::ImplItemKind::Type(ref ty) => {
515 let rewrite = rewrite_associated_impl_type(
522 self.push_rewrite(ii.span, rewrite);
524 ast::ImplItemKind::Existential(ref generic_bounds) => {
525 let rewrite = rewrite_existential_impl_type(
531 self.push_rewrite(ii.span, rewrite);
533 ast::ImplItemKind::Macro(ref mac) => {
534 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
539 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
540 skip_out_of_file_lines_range_visitor!(self, mac.span);
543 let shape = self.shape().sub_width(1).unwrap();
544 let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos));
545 self.push_rewrite(mac.span, rewrite);
548 pub fn push_str(&mut self, s: &str) {
549 self.line_number += count_newlines(s);
550 self.buffer.push_str(s);
553 #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
554 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
555 if let Some(ref s) = rewrite {
558 let snippet = self.snippet(span);
559 self.push_str(snippet);
561 self.last_pos = source!(self, span).hi();
564 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
565 self.format_missing_with_indent(source!(self, span).lo());
566 self.push_rewrite_inner(span, rewrite);
569 pub fn push_skipped_with_span(&mut self, span: Span) {
570 self.format_missing_with_indent(source!(self, span).lo());
571 let lo = self.line_number + 1;
572 self.push_rewrite_inner(span, None);
573 let hi = self.line_number + 1;
574 self.skipped_range.push((lo, hi));
577 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
578 FmtVisitor::from_source_map(
581 ctx.snippet_provider,
586 pub(crate) fn from_source_map(
587 parse_session: &'a ParseSess,
589 snippet_provider: &'a SnippetProvider,
590 report: FormatReport,
591 ) -> FmtVisitor<'a> {
594 source_map: parse_session.source_map(),
595 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
596 last_pos: BytePos(0),
597 block_indent: Indent::empty(),
599 is_if_else_block: false,
602 skipped_range: vec![],
603 macro_rewrite_failure: false,
608 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
609 self.snippet_provider.span_to_snippet(span)
612 pub fn snippet(&'b self, span: Span) -> &'a str {
613 self.opt_snippet(span).unwrap()
616 // Returns true if we should skip the following item.
617 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
619 if attr.name() == DEPR_SKIP_ANNOTATION {
620 let file_name = self.source_map.span_to_filename(attr.span).into();
623 vec![FormattingError::from_span(
626 ErrorKind::DeprecatedAttr,
629 } else if attr.path.segments[0].ident.to_string() == "rustfmt" {
630 if attr.path.segments.len() == 1
631 || attr.path.segments[1].ident.to_string() != "skip"
633 let file_name = self.source_map.span_to_filename(attr.span).into();
636 vec![FormattingError::from_span(
645 if contains_skip(attrs) {
649 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
650 if attrs.is_empty() {
654 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
655 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
656 self.push_rewrite(span, rewrite);
661 fn walk_mod_items(&mut self, m: &ast::Mod) {
662 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
665 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
666 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
668 ast::StmtKind::Item(ref item) => Some(&**item),
673 if stmts.is_empty() {
677 // Extract leading `use ...;`.
678 let items: Vec<_> = stmts
680 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
681 .filter_map(|stmt| to_stmt_item(stmt))
684 if items.is_empty() {
685 self.visit_stmt(&stmts[0]);
686 self.walk_stmts(&stmts[1..]);
688 self.visit_items_with_reordering(&items);
689 self.walk_stmts(&stmts[items.len()..]);
693 fn walk_block_stmts(&mut self, b: &ast::Block) {
694 self.walk_stmts(&b.stmts)
700 vis: &ast::Visibility,
703 attrs: &[ast::Attribute],
706 let vis_str = utils::format_visibility(&self.get_context(), vis);
707 self.push_str(&*vis_str);
708 self.push_str("mod ");
709 // Calling `to_owned()` to work around borrow checker.
710 let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
711 self.push_str(&ident_str);
714 match self.config.brace_style() {
715 BraceStyle::AlwaysNextLine => {
716 let indent_str = self.block_indent.to_string_with_newline(self.config);
717 self.push_str(&indent_str);
720 _ => self.push_str(" {"),
722 // Hackery to account for the closing }.
723 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
725 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
726 let body_snippet = body_snippet.trim();
727 if body_snippet.is_empty() {
730 self.last_pos = mod_lo;
731 self.block_indent = self.block_indent.block_indent(self.config);
732 self.visit_attrs(attrs, ast::AttrStyle::Inner);
733 self.walk_mod_items(m);
734 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
735 self.close_block(false);
737 self.last_pos = source!(self, m.inner).hi();
740 self.last_pos = source!(self, s).hi();
744 pub fn format_separate_mod(&mut self, m: &ast::Mod, source_file: &source_map::SourceFile) {
745 self.block_indent = Indent::empty();
746 self.walk_mod_items(m);
747 self.format_missing_with_indent(source_file.end_pos);
750 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
751 while let Some(pos) = self
753 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
755 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
756 if snippet.trim().is_empty() {
765 pub fn with_context<F>(&mut self, f: F) -> Option<String>
767 F: Fn(&RewriteContext) -> Option<String>,
770 let macro_rewrite_failure = {
771 let context = self.get_context();
772 result = f(&context);
773 unsafe { *context.macro_rewrite_failure.as_ptr() }
775 self.macro_rewrite_failure |= macro_rewrite_failure;
779 pub fn get_context(&self) -> RewriteContext {
781 parse_session: self.parse_session,
782 source_map: self.source_map,
784 inside_macro: RefCell::new(false),
785 use_block: RefCell::new(false),
786 is_if_else_block: RefCell::new(false),
787 force_one_line_chain: RefCell::new(false),
788 snippet_provider: self.snippet_provider,
789 macro_rewrite_failure: RefCell::new(false),
790 report: self.report.clone(),