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 use std::cell::RefCell;
31 /// Creates a string slice corresponding to the specified span.
32 pub struct SnippetProvider<'a> {
33 /// A pointer to the content of the file we are formatting.
35 /// A position of the start of `big_snippet`, used as an offset.
39 impl<'a> SnippetProvider<'a> {
40 pub fn span_to_snippet(&self, span: Span) -> Option<&str> {
41 let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
42 let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
43 Some(&self.big_snippet[start_index..end_index])
46 pub fn new(start_pos: BytePos, big_snippet: &'a str) -> Self {
47 let start_pos = start_pos.to_usize();
55 pub struct FmtVisitor<'a> {
56 pub parse_session: &'a ParseSess,
57 pub codemap: &'a CodeMap,
59 pub last_pos: BytePos,
60 // FIXME: use an RAII util or closure for indenting
61 pub block_indent: Indent,
62 pub config: &'a Config,
63 pub is_if_else_block: bool,
64 pub snippet_provider: &'a SnippetProvider<'a>,
65 pub line_number: usize,
66 pub skipped_range: Vec<(usize, usize)>,
69 impl<'b, 'a: 'b> FmtVisitor<'a> {
70 pub fn shape(&self) -> Shape {
71 Shape::indented(self.block_indent, self.config)
74 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
76 "visit_stmt: {:?} {:?}",
77 self.codemap.lookup_char_pos(stmt.span.lo()),
78 self.codemap.lookup_char_pos(stmt.span.hi())
82 ast::StmtKind::Item(ref item) => {
83 self.visit_item(item);
85 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
86 if contains_skip(get_attrs_from_stmt(stmt)) {
87 self.push_skipped_with_span(stmt.span());
89 let rewrite = stmt.rewrite(&self.get_context(), self.shape());
90 self.push_rewrite(stmt.span(), rewrite)
93 ast::StmtKind::Mac(ref mac) => {
94 let (ref mac, _macro_style, ref attrs) = **mac;
95 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
96 self.push_skipped_with_span(stmt.span());
98 self.visit_mac(mac, None, MacroPosition::Statement);
100 self.format_missing(stmt.span.hi());
108 inner_attrs: Option<&[ast::Attribute]>,
112 "visit_block: {:?} {:?}",
113 self.codemap.lookup_char_pos(b.span.lo()),
114 self.codemap.lookup_char_pos(b.span.hi())
117 // Check if this block has braces.
118 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
120 self.last_pos = self.last_pos + brace_compensation;
121 self.block_indent = self.block_indent.block_indent(self.config);
124 if self.config.remove_blank_lines_at_start_or_end_of_block() {
125 if let Some(first_stmt) = b.stmts.first() {
126 let attr_lo = inner_attrs
127 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
129 // Attributes for an item in a statement position
130 // do not belong to the statement. (rust-lang/rust#34459)
131 if let ast::StmtKind::Item(ref item) = first_stmt.node {
134 first_stmt.attrs().first()
136 // Some stmts can have embedded attributes.
137 // e.g. `match { #![attr] ... }`
138 let attr_lo = attr.span.lo();
139 if attr_lo < first_stmt.span.lo() {
147 let snippet = self.snippet(mk_sp(
149 attr_lo.unwrap_or_else(|| first_stmt.span.lo()),
151 let len = CommentCodeSlices::new(snippet)
153 .and_then(|(kind, _, s)| {
154 if kind == CodeCharKind::Normal {
160 if let Some(len) = len {
161 self.last_pos = self.last_pos + BytePos::from_usize(len);
166 // Format inner attributes if available.
167 let skip_rewrite = if let Some(attrs) = inner_attrs {
168 self.visit_attrs(attrs, ast::AttrStyle::Inner)
174 self.push_rewrite(b.span, None);
175 self.close_block(false);
176 self.last_pos = source!(self, b.span).hi();
180 self.walk_block_stmts(b);
182 if !b.stmts.is_empty() {
183 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
184 if utils::semicolon_for_expr(&self.get_context(), expr) {
190 let mut remove_len = BytePos(0);
191 if self.config.remove_blank_lines_at_start_or_end_of_block() {
192 if let Some(stmt) = b.stmts.last() {
193 let snippet = self.snippet(mk_sp(
195 source!(self, b.span).hi() - brace_compensation,
197 let len = CommentCodeSlices::new(snippet)
199 .and_then(|(kind, _, s)| {
200 if kind == CodeCharKind::Normal && s.trim().is_empty() {
206 if let Some(len) = len {
207 remove_len = BytePos::from_usize(len);
212 let unindent_comment = (self.is_if_else_block && !b.stmts.is_empty()) && {
213 let end_pos = source!(self, b.span).hi() - brace_compensation - remove_len;
214 let snippet = self.snippet(mk_sp(self.last_pos, end_pos));
215 snippet.contains("//") || snippet.contains("/*")
217 // FIXME: we should compress any newlines here to just one
218 if unindent_comment {
219 self.block_indent = self.block_indent.block_unindent(self.config);
221 self.format_missing_with_indent(
222 source!(self, b.span).hi() - brace_compensation - remove_len,
224 if unindent_comment {
225 self.block_indent = self.block_indent.block_indent(self.config);
227 self.close_block(unindent_comment);
228 self.last_pos = source!(self, b.span).hi();
231 // FIXME: this is a terrible hack to indent the comments between the last
232 // item in the block and the closing brace to the block's level.
233 // The closing brace itself, however, should be indented at a shallower
235 fn close_block(&mut self, unindent_comment: bool) {
236 let total_len = self.buffer.len();
237 let chars_too_many = if unindent_comment {
239 } else if self.config.hard_tabs() {
242 self.config.tab_spaces()
244 self.buffer.truncate(total_len - chars_too_many);
246 self.block_indent = self.block_indent.block_unindent(self.config);
249 // Note that this only gets called for function definitions. Required methods
250 // on traits do not get handled here.
254 generics: &ast::Generics,
257 defaultness: ast::Defaultness,
258 inner_attrs: Option<&[ast::Attribute]>,
260 let indent = self.block_indent;
262 let rewrite = match fk {
263 visit::FnKind::ItemFn(ident, _, _, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
268 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
269 mk_sp(s.lo(), b.span.lo()),
273 visit::FnKind::Closure(_) => unreachable!(),
276 if let Some(fn_str) = rewrite {
277 self.format_missing_with_indent(source!(self, s).lo());
278 self.push_str(&fn_str);
279 if let Some(c) = fn_str.chars().last() {
281 self.last_pos = source!(self, block.span).hi();
286 self.format_missing(source!(self, block.span).lo());
289 self.last_pos = source!(self, block.span).lo();
290 self.visit_block(block, inner_attrs, true)
293 pub fn visit_item(&mut self, item: &ast::Item) {
294 skip_out_of_file_lines_range_visitor!(self, item.span);
296 // This is where we bail out if there is a skip attribute. This is only
297 // complex in the module case. It is complex because the module could be
298 // in a separate file and there might be attributes in both files, but
299 // the AST lumps them all together.
301 let mut attrs = &item.attrs;
303 // Module is inline, in this case we treat it like any other item.
304 _ if !is_mod_decl(item) => {
305 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
306 self.push_skipped_with_span(item.span());
310 // Module is not inline, but should be skipped.
311 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
314 // Module is not inline and should not be skipped. We want
315 // to process only the attributes in the current file.
316 ast::ItemKind::Mod(..) => {
317 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
318 // Assert because if we should skip it should be caught by
320 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
321 attrs = &filtered_attrs;
324 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
325 self.push_skipped_with_span(item.span());
332 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
333 ast::ItemKind::Impl(..) => {
334 let snippet = self.snippet(item.span);
335 let where_span_end = snippet
336 .find_uncommented("{")
337 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
338 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
339 self.push_rewrite(item.span, rw);
341 ast::ItemKind::Trait(..) => {
342 let rw = format_trait(&self.get_context(), item, self.block_indent);
343 self.push_rewrite(item.span, rw);
345 ast::ItemKind::TraitAlias(ref generics, ref ty_param_bounds) => {
346 let shape = Shape::indented(self.block_indent, self.config);
347 let rw = format_trait_alias(
354 self.push_rewrite(item.span, rw);
356 ast::ItemKind::ExternCrate(_) => {
357 let rw = rewrite_extern_crate(&self.get_context(), item);
358 self.push_rewrite(item.span, rw);
360 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
361 self.visit_struct(&StructParts::from_item(item));
363 ast::ItemKind::Enum(ref def, ref generics) => {
364 self.format_missing_with_indent(source!(self, item.span).lo());
365 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
366 self.last_pos = source!(self, item.span).hi();
368 ast::ItemKind::Mod(ref module) => {
369 let is_inline = !is_mod_decl(item);
370 self.format_missing_with_indent(source!(self, item.span).lo());
371 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
373 ast::ItemKind::Mac(ref mac) => {
374 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
376 ast::ItemKind::ForeignMod(ref foreign_mod) => {
377 self.format_missing_with_indent(source!(self, item.span).lo());
378 self.format_foreign_mod(foreign_mod, item.span);
380 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
381 self.visit_static(&StaticParts::from_item(item));
383 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
385 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
389 ast::Defaultness::Final,
393 ast::ItemKind::Ty(ref ty, ref generics) => {
394 let rewrite = rewrite_type_alias(
403 self.push_rewrite(item.span, rewrite);
405 ast::ItemKind::GlobalAsm(..) => {
406 let snippet = Some(self.snippet(item.span).to_owned());
407 self.push_rewrite(item.span, snippet);
409 ast::ItemKind::MacroDef(ref def) => {
410 let rewrite = rewrite_macro_def(
419 self.push_rewrite(item.span, rewrite);
424 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
425 skip_out_of_file_lines_range_visitor!(self, ti.span);
427 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
428 self.push_skipped_with_span(ti.span());
433 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
434 ast::TraitItemKind::Method(ref sig, None) => {
435 let indent = self.block_indent;
437 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
438 self.push_rewrite(ti.span, rewrite);
440 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
442 visit::FnKind::Method(ti.ident, sig, None, body),
446 ast::Defaultness::Final,
450 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
451 let rewrite = rewrite_associated_type(
453 type_default.as_ref(),
454 Some(type_param_bounds),
458 self.push_rewrite(ti.span, rewrite);
460 ast::TraitItemKind::Macro(ref mac) => {
461 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
466 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
467 skip_out_of_file_lines_range_visitor!(self, ii.span);
469 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
470 self.push_skipped_with_span(ii.span());
475 ast::ImplItemKind::Method(ref sig, ref body) => {
477 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
485 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
486 ast::ImplItemKind::Type(ref ty) => {
487 let rewrite = rewrite_associated_impl_type(
495 self.push_rewrite(ii.span, rewrite);
497 ast::ImplItemKind::Macro(ref mac) => {
498 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
503 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
504 skip_out_of_file_lines_range_visitor!(self, mac.span);
507 let shape = self.shape().sub_width(1).unwrap();
508 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
509 self.push_rewrite(mac.span, rewrite);
512 pub fn push_str(&mut self, s: &str) {
513 self.line_number += count_newlines(s);
514 self.buffer.push_str(s);
517 #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
518 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
519 if let Some(ref s) = rewrite {
522 let snippet = self.snippet(span);
523 self.push_str(snippet);
525 self.last_pos = source!(self, span).hi();
528 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
529 self.format_missing_with_indent(source!(self, span).lo());
530 self.push_rewrite_inner(span, rewrite);
533 pub fn push_skipped_with_span(&mut self, span: Span) {
534 self.format_missing_with_indent(source!(self, span).lo());
535 let lo = self.line_number + 1;
536 self.push_rewrite_inner(span, None);
537 let hi = self.line_number + 1;
538 self.skipped_range.push((lo, hi));
541 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
542 FmtVisitor::from_codemap(ctx.parse_session, ctx.config, ctx.snippet_provider)
546 parse_session: &'a ParseSess,
548 snippet_provider: &'a SnippetProvider,
549 ) -> FmtVisitor<'a> {
552 codemap: parse_session.codemap(),
553 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
554 last_pos: BytePos(0),
555 block_indent: Indent::empty(),
557 is_if_else_block: false,
560 skipped_range: vec![],
564 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
565 self.snippet_provider.span_to_snippet(span)
568 pub fn snippet(&'b self, span: Span) -> &'a str {
569 self.opt_snippet(span).unwrap()
572 // Returns true if we should skip the following item.
573 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
574 if contains_skip(attrs) {
578 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
579 if attrs.is_empty() {
583 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
584 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
585 self.push_rewrite(span, rewrite);
590 fn walk_mod_items(&mut self, m: &ast::Mod) {
591 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
594 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
595 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
597 ast::StmtKind::Item(ref item) => Some(&**item),
602 if stmts.is_empty() {
606 // Extract leading `use ...;`.
607 let items: Vec<_> = stmts
609 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
610 .filter_map(|stmt| to_stmt_item(stmt))
613 if items.is_empty() {
614 self.visit_stmt(&stmts[0]);
615 self.walk_stmts(&stmts[1..]);
617 self.visit_items_with_reordering(&items);
618 self.walk_stmts(&stmts[items.len()..]);
622 fn walk_block_stmts(&mut self, b: &ast::Block) {
623 self.walk_stmts(&b.stmts)
629 vis: &ast::Visibility,
632 attrs: &[ast::Attribute],
635 self.push_str(&*utils::format_visibility(vis));
636 self.push_str("mod ");
637 self.push_str(&ident.to_string());
640 match self.config.brace_style() {
641 BraceStyle::AlwaysNextLine => {
642 let indent_str = self.block_indent.to_string_with_newline(self.config);
643 self.push_str(&indent_str);
646 _ => self.push_str(" {"),
648 // Hackery to account for the closing }.
649 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
651 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
652 let body_snippet = body_snippet.trim();
653 if body_snippet.is_empty() {
656 self.last_pos = mod_lo;
657 self.block_indent = self.block_indent.block_indent(self.config);
658 self.visit_attrs(attrs, ast::AttrStyle::Inner);
659 self.walk_mod_items(m);
660 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
661 self.close_block(false);
663 self.last_pos = source!(self, m.inner).hi();
666 self.last_pos = source!(self, s).hi();
670 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
671 self.block_indent = Indent::empty();
672 self.walk_mod_items(m);
673 self.format_missing_with_indent(filemap.end_pos);
676 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
677 while let Some(pos) = self.snippet_provider
678 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
680 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
681 if snippet.trim().is_empty() {
690 pub fn get_context(&self) -> RewriteContext {
692 parse_session: self.parse_session,
693 codemap: self.codemap,
696 use_block: RefCell::new(false),
697 is_if_else_block: false,
698 force_one_line_chain: RefCell::new(false),
699 snippet_provider: self.snippet_provider,