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,
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 report: FormatReport,
76 impl<'b, 'a: 'b> FmtVisitor<'a> {
77 pub fn shape(&self) -> Shape {
78 Shape::indented(self.block_indent, self.config)
81 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
83 "visit_stmt: {:?} {:?}",
84 self.codemap.lookup_char_pos(stmt.span.lo()),
85 self.codemap.lookup_char_pos(stmt.span.hi())
89 ast::StmtKind::Item(ref item) => {
90 self.visit_item(item);
92 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
93 if contains_skip(get_attrs_from_stmt(stmt)) {
94 self.push_skipped_with_span(stmt.span());
96 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
97 self.push_rewrite(stmt.span(), rewrite)
100 ast::StmtKind::Mac(ref mac) => {
101 let (ref mac, _macro_style, ref attrs) = **mac;
102 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
103 self.push_skipped_with_span(stmt.span());
105 self.visit_mac(mac, None, MacroPosition::Statement);
107 self.format_missing(stmt.span.hi());
115 inner_attrs: Option<&[ast::Attribute]>,
119 "visit_block: {:?} {:?}",
120 self.codemap.lookup_char_pos(b.span.lo()),
121 self.codemap.lookup_char_pos(b.span.hi())
124 // Check if this block has braces.
125 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
127 self.last_pos = self.last_pos + brace_compensation;
128 self.block_indent = self.block_indent.block_indent(self.config);
131 if let Some(first_stmt) = b.stmts.first() {
132 let attr_lo = inner_attrs
133 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
135 // Attributes for an item in a statement position
136 // do not belong to the statement. (rust-lang/rust#34459)
137 if let ast::StmtKind::Item(ref item) = first_stmt.node {
140 first_stmt.attrs().first()
142 // Some stmts can have embedded attributes.
143 // e.g. `match { #![attr] ... }`
144 let attr_lo = attr.span.lo();
145 if attr_lo < first_stmt.span.lo() {
153 let snippet = self.snippet(mk_sp(
155 attr_lo.unwrap_or_else(|| first_stmt.span.lo()),
157 let len = CommentCodeSlices::new(snippet)
159 .and_then(|(kind, _, s)| {
160 if kind == CodeCharKind::Normal {
166 if let Some(len) = len {
167 self.last_pos = self.last_pos + BytePos::from_usize(len);
171 // Format inner attributes if available.
172 let skip_rewrite = if let Some(attrs) = inner_attrs {
173 self.visit_attrs(attrs, ast::AttrStyle::Inner)
179 self.push_rewrite(b.span, None);
180 self.close_block(false);
181 self.last_pos = source!(self, b.span).hi();
185 self.walk_block_stmts(b);
187 if !b.stmts.is_empty() {
188 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
189 if utils::semicolon_for_expr(&self.get_context(), expr) {
195 let mut remove_len = BytePos(0);
196 if let Some(stmt) = b.stmts.last() {
197 let snippet = self.snippet(mk_sp(
199 source!(self, b.span).hi() - brace_compensation,
201 let len = CommentCodeSlices::new(snippet)
203 .and_then(|(kind, _, s)| {
204 if kind == CodeCharKind::Normal && s.trim().is_empty() {
210 if let Some(len) = len {
211 remove_len = BytePos::from_usize(len);
215 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
216 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
217 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
218 snippet.contains("//") || snippet.contains("/*")
220 // FIXME: we should compress any newlines here to just one
221 if unindent_comment {
222 self.block_indent = self.block_indent.block_unindent(self.config);
224 self.format_missing_with_indent(
225 source!(self, b.span).hi() - brace_compensation - remove_len,
227 if unindent_comment {
228 self.block_indent = self.block_indent.block_indent(self.config);
230 self.close_block(unindent_comment);
231 self.last_pos = source!(self, b.span).hi();
234 // FIXME: this is a terrible hack to indent the comments between the last
235 // item in the block and the closing brace to the block's level.
236 // The closing brace itself, however, should be indented at a shallower
238 fn close_block(&mut self, unindent_comment: bool) {
239 let total_len = self.buffer.len();
240 let chars_too_many = if unindent_comment {
242 } else if self.config.hard_tabs() {
245 self.config.tab_spaces()
247 self.buffer.truncate(total_len - chars_too_many);
249 self.block_indent = self.block_indent.block_unindent(self.config);
252 // Note that this only gets called for function definitions. Required methods
253 // on traits do not get handled here.
257 generics: &ast::Generics,
260 defaultness: ast::Defaultness,
261 inner_attrs: Option<&[ast::Attribute]>,
263 let indent = self.block_indent;
265 let rewrite = match fk {
266 visit::FnKind::ItemFn(ident, _, _, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
271 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
272 mk_sp(s.lo(), b.span.lo()),
277 visit::FnKind::Closure(_) => unreachable!(),
280 if let Some(fn_str) = rewrite {
281 self.format_missing_with_indent(source!(self, s).lo());
282 self.push_str(&fn_str);
283 if let Some(c) = fn_str.chars().last() {
285 self.last_pos = source!(self, block.span).hi();
290 self.format_missing(source!(self, block.span).lo());
293 self.last_pos = source!(self, block.span).lo();
294 self.visit_block(block, inner_attrs, true)
297 pub fn visit_item(&mut self, item: &ast::Item) {
298 skip_out_of_file_lines_range_visitor!(self, item.span);
300 // This is where we bail out if there is a skip attribute. This is only
301 // complex in the module case. It is complex because the module could be
302 // in a separate file and there might be attributes in both files, but
303 // the AST lumps them all together.
305 let mut attrs = &item.attrs;
307 // For use items, skip rewriting attributes. Just check for a skip attribute.
308 ast::ItemKind::Use(..) => {
309 if contains_skip(attrs) {
310 self.push_skipped_with_span(item.span());
314 // Module is inline, in this case we treat it like any other item.
315 _ if !is_mod_decl(item) => {
316 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
317 self.push_skipped_with_span(item.span());
321 // Module is not inline, but should be skipped.
322 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
325 // Module is not inline and should not be skipped. We want
326 // to process only the attributes in the current file.
327 ast::ItemKind::Mod(..) => {
328 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
329 // Assert because if we should skip it should be caught by
331 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
332 attrs = &filtered_attrs;
335 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
336 self.push_skipped_with_span(item.span());
343 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
344 ast::ItemKind::Impl(..) => {
345 let snippet = self.snippet(item.span);
346 let where_span_end = snippet
347 .find_uncommented("{")
348 .map(|x| BytePos(x as u32) + source!(self, item.span).lo());
349 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
350 self.push_rewrite(item.span, rw);
352 ast::ItemKind::Trait(..) => {
353 let rw = format_trait(&self.get_context(), item, self.block_indent);
354 self.push_rewrite(item.span, rw);
356 ast::ItemKind::TraitAlias(ref generics, ref ty_param_bounds) => {
357 let shape = Shape::indented(self.block_indent, self.config);
358 let rw = format_trait_alias(
365 self.push_rewrite(item.span, rw);
367 ast::ItemKind::ExternCrate(_) => {
368 let rw = rewrite_extern_crate(&self.get_context(), item);
369 self.push_rewrite(item.span, rw);
371 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
372 self.visit_struct(&StructParts::from_item(item));
374 ast::ItemKind::Enum(ref def, ref generics) => {
375 self.format_missing_with_indent(source!(self, item.span).lo());
376 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
377 self.last_pos = source!(self, item.span).hi();
379 ast::ItemKind::Mod(ref module) => {
380 let is_inline = !is_mod_decl(item);
381 self.format_missing_with_indent(source!(self, item.span).lo());
382 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
384 ast::ItemKind::Mac(ref mac) => {
385 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
387 ast::ItemKind::ForeignMod(ref foreign_mod) => {
388 self.format_missing_with_indent(source!(self, item.span).lo());
389 self.format_foreign_mod(foreign_mod, item.span);
391 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
392 self.visit_static(&StaticParts::from_item(item));
394 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
395 let inner_attrs = inner_attributes(&item.attrs);
397 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
401 ast::Defaultness::Final,
405 ast::ItemKind::Ty(ref ty, ref generics) => {
406 let rewrite = rewrite_type_alias(
415 self.push_rewrite(item.span, rewrite);
417 ast::ItemKind::GlobalAsm(..) => {
418 let snippet = Some(self.snippet(item.span).to_owned());
419 self.push_rewrite(item.span, snippet);
421 ast::ItemKind::MacroDef(ref def) => {
422 let rewrite = rewrite_macro_def(
431 self.push_rewrite(item.span, rewrite);
436 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
437 skip_out_of_file_lines_range_visitor!(self, ti.span);
439 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
440 self.push_skipped_with_span(ti.span());
445 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
446 ast::TraitItemKind::Method(ref sig, None) => {
447 let indent = self.block_indent;
449 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
450 self.push_rewrite(ti.span, rewrite);
452 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
453 let inner_attrs = inner_attributes(&ti.attrs);
455 visit::FnKind::Method(ti.ident, sig, None, body),
459 ast::Defaultness::Final,
463 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
464 let rewrite = rewrite_associated_type(
466 type_default.as_ref(),
467 Some(type_param_bounds),
471 self.push_rewrite(ti.span, rewrite);
473 ast::TraitItemKind::Macro(ref mac) => {
474 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
479 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
480 skip_out_of_file_lines_range_visitor!(self, ii.span);
482 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
483 self.push_skipped_with_span(ii.span());
488 ast::ImplItemKind::Method(ref sig, ref body) => {
489 let inner_attrs = inner_attributes(&ii.attrs);
491 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
499 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
500 ast::ImplItemKind::Type(ref ty) => {
501 let rewrite = rewrite_associated_impl_type(
509 self.push_rewrite(ii.span, rewrite);
511 ast::ImplItemKind::Macro(ref mac) => {
512 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
517 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
518 skip_out_of_file_lines_range_visitor!(self, mac.span);
521 let shape = self.shape().sub_width(1).unwrap();
522 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
523 self.push_rewrite(mac.span, rewrite);
526 pub fn push_str(&mut self, s: &str) {
527 self.line_number += count_newlines(s);
528 self.buffer.push_str(s);
531 #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
532 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
533 if let Some(ref s) = rewrite {
536 let snippet = self.snippet(span);
537 self.push_str(snippet);
539 self.last_pos = source!(self, span).hi();
542 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
543 self.format_missing_with_indent(source!(self, span).lo());
544 self.push_rewrite_inner(span, rewrite);
547 pub fn push_skipped_with_span(&mut self, span: Span) {
548 self.format_missing_with_indent(source!(self, span).lo());
549 let lo = self.line_number + 1;
550 self.push_rewrite_inner(span, None);
551 let hi = self.line_number + 1;
552 self.skipped_range.push((lo, hi));
555 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
556 FmtVisitor::from_codemap(
559 ctx.snippet_provider,
565 parse_session: &'a ParseSess,
567 snippet_provider: &'a SnippetProvider,
568 report: FormatReport,
569 ) -> FmtVisitor<'a> {
572 codemap: parse_session.codemap(),
573 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
574 last_pos: BytePos(0),
575 block_indent: Indent::empty(),
577 is_if_else_block: false,
580 skipped_range: vec![],
585 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
586 self.snippet_provider.span_to_snippet(span)
589 pub fn snippet(&'b self, span: Span) -> &'a str {
590 self.opt_snippet(span).unwrap()
593 // Returns true if we should skip the following item.
594 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
596 if attr.name() == DEPR_SKIP_ANNOTATION {
597 let file_name = self.codemap.span_to_filename(attr.span);
600 vec![FormattingError::from_span(
603 ErrorKind::DeprecatedAttr,
606 } else if attr.path.segments[0].ident.to_string() == "rustfmt" {
607 if attr.path.segments.len() == 1
608 || attr.path.segments[1].ident.to_string() != "skip"
610 let file_name = self.codemap.span_to_filename(attr.span);
613 vec![FormattingError::from_span(
622 if contains_skip(attrs) {
626 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
627 if attrs.is_empty() {
631 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
632 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
633 self.push_rewrite(span, rewrite);
638 fn walk_mod_items(&mut self, m: &ast::Mod) {
639 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
642 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
643 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
645 ast::StmtKind::Item(ref item) => Some(&**item),
650 if stmts.is_empty() {
654 // Extract leading `use ...;`.
655 let items: Vec<_> = stmts
657 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
658 .filter_map(|stmt| to_stmt_item(stmt))
661 if items.is_empty() {
662 self.visit_stmt(&stmts[0]);
663 self.walk_stmts(&stmts[1..]);
665 self.visit_items_with_reordering(&items);
666 self.walk_stmts(&stmts[items.len()..]);
670 fn walk_block_stmts(&mut self, b: &ast::Block) {
671 self.walk_stmts(&b.stmts)
677 vis: &ast::Visibility,
680 attrs: &[ast::Attribute],
683 self.push_str(&*utils::format_visibility(vis));
684 self.push_str("mod ");
685 self.push_str(&ident.to_string());
688 match self.config.brace_style() {
689 BraceStyle::AlwaysNextLine => {
690 let indent_str = self.block_indent.to_string_with_newline(self.config);
691 self.push_str(&indent_str);
694 _ => self.push_str(" {"),
696 // Hackery to account for the closing }.
697 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
699 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
700 let body_snippet = body_snippet.trim();
701 if body_snippet.is_empty() {
704 self.last_pos = mod_lo;
705 self.block_indent = self.block_indent.block_indent(self.config);
706 self.visit_attrs(attrs, ast::AttrStyle::Inner);
707 self.walk_mod_items(m);
708 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
709 self.close_block(false);
711 self.last_pos = source!(self, m.inner).hi();
714 self.last_pos = source!(self, s).hi();
718 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
719 self.block_indent = Indent::empty();
720 self.walk_mod_items(m);
721 self.format_missing_with_indent(filemap.end_pos);
724 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
725 while let Some(pos) = self
727 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
729 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
730 if snippet.trim().is_empty() {
739 pub fn get_context(&self) -> RewriteContext {
741 parse_session: self.parse_session,
742 codemap: self.codemap,
744 inside_macro: RefCell::new(false),
745 use_block: RefCell::new(false),
746 is_if_else_block: RefCell::new(false),
747 force_one_line_chain: RefCell::new(false),
748 snippet_provider: self.snippet_provider,
749 report: self.report.clone(),