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::{ast, visit};
12 use syntax::attr::HasAttrs;
13 use syntax::codemap::{self, BytePos, CodeMap, Pos, Span};
14 use syntax::parse::ParseSess;
17 use codemap::{LineRangeUtils, SpanUtils};
18 use comment::{CodeCharKind, CommentCodeSlices, FindUncommented};
19 use config::{BraceStyle, Config};
20 use items::{format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item,
21 rewrite_associated_impl_type, rewrite_associated_type, rewrite_extern_crate,
22 rewrite_type_alias, FnSig, StaticParts, StructParts};
23 use macros::{rewrite_macro, rewrite_macro_def, MacroPosition};
24 use rewrite::{Rewrite, RewriteContext};
25 use shape::{Indent, Shape};
27 use utils::{self, contains_skip, count_newlines, inner_attributes, mk_sp, ptr_vec_to_ref_vec};
29 /// Creates a string slice corresponding to the specified span.
30 pub struct SnippetProvider<'a> {
31 /// A pointer to the content of the file we are formatting.
33 /// A position of the start of `big_snippet`, used as an offset.
37 impl<'a> SnippetProvider<'a> {
38 pub fn span_to_snippet(&self, span: Span) -> Option<&str> {
39 let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
40 let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
41 Some(&self.big_snippet[start_index..end_index])
44 pub fn new(start_pos: BytePos, big_snippet: &'a str) -> Self {
45 let start_pos = start_pos.to_usize();
53 pub struct FmtVisitor<'a> {
54 pub parse_session: &'a ParseSess,
55 pub codemap: &'a CodeMap,
57 pub last_pos: BytePos,
58 // FIXME: use an RAII util or closure for indenting
59 pub block_indent: Indent,
60 pub config: &'a Config,
61 pub is_if_else_block: bool,
62 pub snippet_provider: &'a SnippetProvider<'a>,
63 pub line_number: usize,
64 pub skipped_range: Vec<(usize, usize)>,
67 impl<'b, 'a: 'b> FmtVisitor<'a> {
68 pub fn shape(&self) -> Shape {
69 Shape::indented(self.block_indent, self.config)
72 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
74 "visit_stmt: {:?} {:?}",
75 self.codemap.lookup_char_pos(stmt.span.lo()),
76 self.codemap.lookup_char_pos(stmt.span.hi())
80 ast::StmtKind::Item(ref item) => {
81 self.visit_item(item);
83 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
84 if contains_skip(get_attrs_from_stmt(stmt)) {
85 self.push_skipped_with_span(stmt.span());
87 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
88 self.push_rewrite(stmt.span(), rewrite)
91 ast::StmtKind::Mac(ref mac) => {
92 let (ref mac, _macro_style, ref attrs) = **mac;
93 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
94 self.push_skipped_with_span(stmt.span());
96 self.visit_mac(mac, None, MacroPosition::Statement);
98 self.format_missing(stmt.span.hi());
106 inner_attrs: Option<&[ast::Attribute]>,
110 "visit_block: {:?} {:?}",
111 self.codemap.lookup_char_pos(b.span.lo()),
112 self.codemap.lookup_char_pos(b.span.hi())
115 // Check if this block has braces.
116 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
118 self.last_pos = self.last_pos + brace_compensation;
119 self.block_indent = self.block_indent.block_indent(self.config);
122 if self.config.remove_blank_lines_at_start_or_end_of_block() {
123 if let Some(first_stmt) = b.stmts.first() {
124 let attr_lo = inner_attrs
125 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
127 // Attributes for an item in a statement position
128 // do not belong to the statement. (rust-lang/rust#34459)
129 if let ast::StmtKind::Item(ref item) = first_stmt.node {
132 first_stmt.attrs().first()
134 // Some stmts can have embedded attributes.
135 // e.g. `match { #![attr] ... }`
136 let attr_lo = attr.span.lo();
137 if attr_lo < first_stmt.span.lo() {
145 let snippet = self.snippet(mk_sp(
147 attr_lo.unwrap_or_else(|| first_stmt.span.lo()),
149 let len = CommentCodeSlices::new(snippet)
151 .and_then(|(kind, _, s)| {
152 if kind == CodeCharKind::Normal {
158 if let Some(len) = len {
159 self.last_pos = self.last_pos + BytePos::from_usize(len);
164 // Format inner attributes if available.
165 let skip_rewrite = if let Some(attrs) = inner_attrs {
166 self.visit_attrs(attrs, ast::AttrStyle::Inner)
172 self.push_rewrite(b.span, None);
173 self.close_block(false);
174 self.last_pos = source!(self, b.span).hi();
178 self.walk_block_stmts(b);
180 if !b.stmts.is_empty() {
181 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
182 if utils::semicolon_for_expr(&self.get_context(), expr) {
188 let mut remove_len = BytePos(0);
189 if self.config.remove_blank_lines_at_start_or_end_of_block() {
190 if let Some(stmt) = b.stmts.last() {
191 let snippet = self.snippet(mk_sp(
193 source!(self, b.span).hi() - brace_compensation,
195 let len = CommentCodeSlices::new(snippet)
197 .and_then(|(kind, _, s)| {
198 if kind == CodeCharKind::Normal && s.trim().is_empty() {
204 if let Some(len) = len {
205 remove_len = BytePos::from_usize(len);
210 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
211 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
212 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
213 snippet.contains("//") || snippet.contains("/*")
215 // FIXME: we should compress any newlines here to just one
216 if unindent_comment {
217 self.block_indent = self.block_indent.block_unindent(self.config);
219 self.format_missing_with_indent(
220 source!(self, b.span).hi() - brace_compensation - remove_len,
222 if unindent_comment {
223 self.block_indent = self.block_indent.block_indent(self.config);
225 self.close_block(unindent_comment);
226 self.last_pos = source!(self, b.span).hi();
229 // FIXME: this is a terrible hack to indent the comments between the last
230 // item in the block and the closing brace to the block's level.
231 // The closing brace itself, however, should be indented at a shallower
233 fn close_block(&mut self, unindent_comment: bool) {
234 let total_len = self.buffer.len();
235 let chars_too_many = if unindent_comment {
237 } else if self.config.hard_tabs() {
240 self.config.tab_spaces()
242 self.buffer.truncate(total_len - chars_too_many);
244 self.block_indent = self.block_indent.block_unindent(self.config);
247 // Note that this only gets called for function definitions. Required methods
248 // on traits do not get handled here.
252 generics: &ast::Generics,
255 defaultness: ast::Defaultness,
256 inner_attrs: Option<&[ast::Attribute]>,
258 let indent = self.block_indent;
260 let rewrite = match fk {
261 visit::FnKind::ItemFn(ident, _, _, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
266 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
267 mk_sp(s.lo(), b.span.lo()),
271 visit::FnKind::Closure(_) => unreachable!(),
274 if let Some(fn_str) = rewrite {
275 self.format_missing_with_indent(source!(self, s).lo());
276 self.push_str(&fn_str);
277 if let Some(c) = fn_str.chars().last() {
279 self.last_pos = source!(self, block.span).hi();
284 self.format_missing(source!(self, block.span).lo());
287 self.last_pos = source!(self, block.span).lo();
288 self.visit_block(block, inner_attrs, true)
291 pub fn visit_item(&mut self, item: &ast::Item) {
292 skip_out_of_file_lines_range_visitor!(self, item.span);
294 // This is where we bail out if there is a skip attribute. This is only
295 // complex in the module case. It is complex because the module could be
296 // in a separate file and there might be attributes in both files, but
297 // the AST lumps them all together.
299 let mut attrs = &item.attrs;
301 // Module is inline, in this case we treat it like any other item.
302 _ if !is_mod_decl(item) => {
303 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
304 self.push_skipped_with_span(item.span());
308 // Module is not inline, but should be skipped.
309 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
312 // Module is not inline and should not be skipped. We want
313 // to process only the attributes in the current file.
314 ast::ItemKind::Mod(..) => {
315 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
316 // Assert because if we should skip it should be caught by
318 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
319 attrs = &filtered_attrs;
322 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
323 self.push_skipped_with_span(item.span());
330 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
331 ast::ItemKind::Impl(..) => {
332 let snippet = self.snippet(item.span);
333 let where_span_end = snippet
334 .find_uncommented("{")
335 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
336 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
337 self.push_rewrite(item.span, rw);
339 ast::ItemKind::Trait(..) => {
340 let rw = format_trait(&self.get_context(), item, self.block_indent);
341 self.push_rewrite(item.span, rw);
343 ast::ItemKind::TraitAlias(ref generics, ref ty_param_bounds) => {
344 let shape = Shape::indented(self.block_indent, self.config);
345 let rw = format_trait_alias(
352 self.push_rewrite(item.span, rw);
354 ast::ItemKind::ExternCrate(_) => {
355 let rw = rewrite_extern_crate(&self.get_context(), item);
356 self.push_rewrite(item.span, rw);
358 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
359 self.visit_struct(&StructParts::from_item(item));
361 ast::ItemKind::Enum(ref def, ref generics) => {
362 self.format_missing_with_indent(source!(self, item.span).lo());
363 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
364 self.last_pos = source!(self, item.span).hi();
366 ast::ItemKind::Mod(ref module) => {
367 let is_inline = !is_mod_decl(item);
368 self.format_missing_with_indent(source!(self, item.span).lo());
369 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
371 ast::ItemKind::Mac(ref mac) => {
372 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
374 ast::ItemKind::ForeignMod(ref foreign_mod) => {
375 self.format_missing_with_indent(source!(self, item.span).lo());
376 self.format_foreign_mod(foreign_mod, item.span);
378 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
379 self.visit_static(&StaticParts::from_item(item));
381 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
383 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
387 ast::Defaultness::Final,
391 ast::ItemKind::Ty(ref ty, ref generics) => {
392 let rewrite = rewrite_type_alias(
401 self.push_rewrite(item.span, rewrite);
403 ast::ItemKind::GlobalAsm(..) => {
404 let snippet = Some(self.snippet(item.span).to_owned());
405 self.push_rewrite(item.span, snippet);
407 ast::ItemKind::MacroDef(ref def) => {
408 let rewrite = rewrite_macro_def(
417 self.push_rewrite(item.span, rewrite);
422 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
423 skip_out_of_file_lines_range_visitor!(self, ti.span);
425 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
426 self.push_skipped_with_span(ti.span());
431 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
432 ast::TraitItemKind::Method(ref sig, None) => {
433 let indent = self.block_indent;
435 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
436 self.push_rewrite(ti.span, rewrite);
438 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
440 visit::FnKind::Method(ti.ident, sig, None, body),
444 ast::Defaultness::Final,
448 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
449 let rewrite = rewrite_associated_type(
451 type_default.as_ref(),
452 Some(type_param_bounds),
456 self.push_rewrite(ti.span, rewrite);
458 ast::TraitItemKind::Macro(ref mac) => {
459 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
464 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
465 skip_out_of_file_lines_range_visitor!(self, ii.span);
467 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
468 self.push_skipped_with_span(ii.span());
473 ast::ImplItemKind::Method(ref sig, ref body) => {
475 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
483 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
484 ast::ImplItemKind::Type(ref ty) => {
485 let rewrite = rewrite_associated_impl_type(
493 self.push_rewrite(ii.span, rewrite);
495 ast::ImplItemKind::Macro(ref mac) => {
496 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
501 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
502 skip_out_of_file_lines_range_visitor!(self, mac.span);
505 let shape = self.shape().sub_width(1).unwrap();
506 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
507 self.push_rewrite(mac.span, rewrite);
510 pub fn push_str(&mut self, s: &str) {
511 self.line_number += count_newlines(s);
512 self.buffer.push_str(s);
515 #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
516 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
517 if let Some(ref s) = rewrite {
520 let snippet = self.snippet(span);
521 self.push_str(snippet);
523 self.last_pos = source!(self, span).hi();
526 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
527 self.format_missing_with_indent(source!(self, span).lo());
528 self.push_rewrite_inner(span, rewrite);
531 pub fn push_skipped_with_span(&mut self, span: Span) {
532 self.format_missing_with_indent(source!(self, span).lo());
533 let lo = self.line_number + 1;
534 self.push_rewrite_inner(span, None);
535 let hi = self.line_number + 1;
536 self.skipped_range.push((lo, hi));
539 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
540 FmtVisitor::from_codemap(ctx.parse_session, ctx.config, ctx.snippet_provider)
544 parse_session: &'a ParseSess,
546 snippet_provider: &'a SnippetProvider,
547 ) -> FmtVisitor<'a> {
550 codemap: parse_session.codemap(),
551 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
552 last_pos: BytePos(0),
553 block_indent: Indent::empty(),
555 is_if_else_block: false,
558 skipped_range: vec![],
562 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
563 self.snippet_provider.span_to_snippet(span)
566 pub fn snippet(&'b self, span: Span) -> &'a str {
567 self.opt_snippet(span).unwrap()
570 // Returns true if we should skip the following item.
571 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
572 if contains_skip(attrs) {
576 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
577 if attrs.is_empty() {
581 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
582 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
583 self.push_rewrite(span, rewrite);
588 fn walk_mod_items(&mut self, m: &ast::Mod) {
589 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
592 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
593 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
595 ast::StmtKind::Item(ref item) => Some(&**item),
600 if stmts.is_empty() {
604 // Extract leading `use ...;`.
605 let items: Vec<_> = stmts
607 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
608 .filter_map(|stmt| to_stmt_item(stmt))
611 if items.is_empty() {
612 self.visit_stmt(&stmts[0]);
613 self.walk_stmts(&stmts[1..]);
615 self.visit_items_with_reordering(&items);
616 self.walk_stmts(&stmts[items.len()..]);
620 fn walk_block_stmts(&mut self, b: &ast::Block) {
621 self.walk_stmts(&b.stmts)
627 vis: &ast::Visibility,
630 attrs: &[ast::Attribute],
633 self.push_str(&*utils::format_visibility(vis));
634 self.push_str("mod ");
635 self.push_str(&ident.to_string());
638 match self.config.brace_style() {
639 BraceStyle::AlwaysNextLine => {
640 let indent_str = self.block_indent.to_string_with_newline(self.config);
641 self.push_str(&indent_str);
644 _ => self.push_str(" {"),
646 // Hackery to account for the closing }.
647 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
649 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
650 let body_snippet = body_snippet.trim();
651 if body_snippet.is_empty() {
654 self.last_pos = mod_lo;
655 self.block_indent = self.block_indent.block_indent(self.config);
656 self.visit_attrs(attrs, ast::AttrStyle::Inner);
657 self.walk_mod_items(m);
658 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
659 self.close_block(false);
661 self.last_pos = source!(self, m.inner).hi();
664 self.last_pos = source!(self, s).hi();
668 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
669 self.block_indent = Indent::empty();
670 self.walk_mod_items(m);
671 self.format_missing_with_indent(filemap.end_pos);
674 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
675 while let Some(pos) = self.snippet_provider
676 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
678 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
679 if snippet.trim().is_empty() {
688 pub fn get_context(&self) -> RewriteContext {
690 parse_session: self.parse_session,
691 codemap: self.codemap,
695 is_if_else_block: false,
696 force_one_line_chain: false,
697 snippet_provider: self.snippet_provider,