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};
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()),
274 visit::FnKind::Closure(_) => unreachable!(),
277 if let Some(fn_str) = rewrite {
278 self.format_missing_with_indent(source!(self, s).lo());
279 self.push_str(&fn_str);
280 if let Some(c) = fn_str.chars().last() {
282 self.last_pos = source!(self, block.span).hi();
287 self.format_missing(source!(self, block.span).lo());
290 self.last_pos = source!(self, block.span).lo();
291 self.visit_block(block, inner_attrs, true)
294 pub fn visit_item(&mut self, item: &ast::Item) {
295 skip_out_of_file_lines_range_visitor!(self, item.span);
297 // This is where we bail out if there is a skip attribute. This is only
298 // complex in the module case. It is complex because the module could be
299 // in a separate file and there might be attributes in both files, but
300 // the AST lumps them all together.
302 let mut attrs = &item.attrs;
304 // Module is inline, in this case we treat it like any other item.
305 _ if !is_mod_decl(item) => {
306 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
307 self.push_skipped_with_span(item.span());
311 // Module is not inline, but should be skipped.
312 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => {
315 // Module is not inline and should not be skipped. We want
316 // to process only the attributes in the current file.
317 ast::ItemKind::Mod(..) => {
318 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
319 // Assert because if we should skip it should be caught by
321 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
322 attrs = &filtered_attrs;
325 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
326 self.push_skipped_with_span(item.span());
333 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
334 ast::ItemKind::Impl(..) => {
335 let snippet = self.snippet(item.span);
336 let where_span_end = snippet
337 .find_uncommented("{")
338 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo());
339 let rw = format_impl(&self.get_context(), item, self.block_indent, where_span_end);
340 self.push_rewrite(item.span, rw);
342 ast::ItemKind::Trait(..) => {
343 let rw = format_trait(&self.get_context(), item, self.block_indent);
344 self.push_rewrite(item.span, rw);
346 ast::ItemKind::TraitAlias(ref generics, ref ty_param_bounds) => {
347 let shape = Shape::indented(self.block_indent, self.config);
348 let rw = format_trait_alias(
355 self.push_rewrite(item.span, rw);
357 ast::ItemKind::ExternCrate(_) => {
358 let rw = rewrite_extern_crate(&self.get_context(), item);
359 self.push_rewrite(item.span, rw);
361 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
362 self.visit_struct(&StructParts::from_item(item));
364 ast::ItemKind::Enum(ref def, ref generics) => {
365 self.format_missing_with_indent(source!(self, item.span).lo());
366 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
367 self.last_pos = source!(self, item.span).hi();
369 ast::ItemKind::Mod(ref module) => {
370 let is_inline = !is_mod_decl(item);
371 self.format_missing_with_indent(source!(self, item.span).lo());
372 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
374 ast::ItemKind::Mac(ref mac) => {
375 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
377 ast::ItemKind::ForeignMod(ref foreign_mod) => {
378 self.format_missing_with_indent(source!(self, item.span).lo());
379 self.format_foreign_mod(foreign_mod, item.span);
381 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
382 self.visit_static(&StaticParts::from_item(item));
384 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
385 let inner_attrs = inner_attributes(&item.attrs);
387 visit::FnKind::ItemFn(item.ident, unsafety, constness, abi, &item.vis, body),
391 ast::Defaultness::Final,
395 ast::ItemKind::Ty(ref ty, ref generics) => {
396 let rewrite = rewrite_type_alias(
405 self.push_rewrite(item.span, rewrite);
407 ast::ItemKind::GlobalAsm(..) => {
408 let snippet = Some(self.snippet(item.span).to_owned());
409 self.push_rewrite(item.span, snippet);
411 ast::ItemKind::MacroDef(ref def) => {
412 let rewrite = rewrite_macro_def(
421 self.push_rewrite(item.span, rewrite);
426 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
427 skip_out_of_file_lines_range_visitor!(self, ti.span);
429 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
430 self.push_skipped_with_span(ti.span());
435 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
436 ast::TraitItemKind::Method(ref sig, None) => {
437 let indent = self.block_indent;
439 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
440 self.push_rewrite(ti.span, rewrite);
442 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
443 let inner_attrs = inner_attributes(&ti.attrs);
445 visit::FnKind::Method(ti.ident, sig, None, body),
449 ast::Defaultness::Final,
453 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
454 let rewrite = rewrite_associated_type(
456 type_default.as_ref(),
457 Some(type_param_bounds),
461 self.push_rewrite(ti.span, rewrite);
463 ast::TraitItemKind::Macro(ref mac) => {
464 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
469 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
470 skip_out_of_file_lines_range_visitor!(self, ii.span);
472 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
473 self.push_skipped_with_span(ii.span());
478 ast::ImplItemKind::Method(ref sig, ref body) => {
479 let inner_attrs = inner_attributes(&ii.attrs);
481 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
489 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
490 ast::ImplItemKind::Type(ref ty) => {
491 let rewrite = rewrite_associated_impl_type(
499 self.push_rewrite(ii.span, rewrite);
501 ast::ImplItemKind::Macro(ref mac) => {
502 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
507 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
508 skip_out_of_file_lines_range_visitor!(self, mac.span);
511 let shape = self.shape().sub_width(1).unwrap();
512 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
513 self.push_rewrite(mac.span, rewrite);
516 pub fn push_str(&mut self, s: &str) {
517 self.line_number += count_newlines(s);
518 self.buffer.push_str(s);
521 #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
522 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
523 if let Some(ref s) = rewrite {
526 let snippet = self.snippet(span);
527 self.push_str(snippet);
529 self.last_pos = source!(self, span).hi();
532 pub fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
533 self.format_missing_with_indent(source!(self, span).lo());
534 self.push_rewrite_inner(span, rewrite);
537 pub fn push_skipped_with_span(&mut self, span: Span) {
538 self.format_missing_with_indent(source!(self, span).lo());
539 let lo = self.line_number + 1;
540 self.push_rewrite_inner(span, None);
541 let hi = self.line_number + 1;
542 self.skipped_range.push((lo, hi));
545 pub fn from_context(ctx: &'a RewriteContext) -> FmtVisitor<'a> {
546 FmtVisitor::from_codemap(ctx.parse_session, ctx.config, ctx.snippet_provider)
550 parse_session: &'a ParseSess,
552 snippet_provider: &'a SnippetProvider,
553 ) -> FmtVisitor<'a> {
556 codemap: parse_session.codemap(),
557 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
558 last_pos: BytePos(0),
559 block_indent: Indent::empty(),
561 is_if_else_block: false,
564 skipped_range: vec![],
568 pub fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
569 self.snippet_provider.span_to_snippet(span)
572 pub fn snippet(&'b self, span: Span) -> &'a str {
573 self.opt_snippet(span).unwrap()
576 // Returns true if we should skip the following item.
577 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
578 if contains_skip(attrs) {
582 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
583 if attrs.is_empty() {
587 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
588 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
589 self.push_rewrite(span, rewrite);
594 fn walk_mod_items(&mut self, m: &ast::Mod) {
595 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
598 fn walk_stmts(&mut self, stmts: &[ast::Stmt]) {
599 fn to_stmt_item(stmt: &ast::Stmt) -> Option<&ast::Item> {
601 ast::StmtKind::Item(ref item) => Some(&**item),
606 if stmts.is_empty() {
610 // Extract leading `use ...;`.
611 let items: Vec<_> = stmts
613 .take_while(|stmt| to_stmt_item(stmt).map_or(false, is_use_item))
614 .filter_map(|stmt| to_stmt_item(stmt))
617 if items.is_empty() {
618 self.visit_stmt(&stmts[0]);
619 self.walk_stmts(&stmts[1..]);
621 self.visit_items_with_reordering(&items);
622 self.walk_stmts(&stmts[items.len()..]);
626 fn walk_block_stmts(&mut self, b: &ast::Block) {
627 self.walk_stmts(&b.stmts)
633 vis: &ast::Visibility,
636 attrs: &[ast::Attribute],
639 self.push_str(&*utils::format_visibility(vis));
640 self.push_str("mod ");
641 self.push_str(&ident.to_string());
644 match self.config.brace_style() {
645 BraceStyle::AlwaysNextLine => {
646 let indent_str = self.block_indent.to_string_with_newline(self.config);
647 self.push_str(&indent_str);
650 _ => self.push_str(" {"),
652 // Hackery to account for the closing }.
653 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
655 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
656 let body_snippet = body_snippet.trim();
657 if body_snippet.is_empty() {
660 self.last_pos = mod_lo;
661 self.block_indent = self.block_indent.block_indent(self.config);
662 self.visit_attrs(attrs, ast::AttrStyle::Inner);
663 self.walk_mod_items(m);
664 self.format_missing_with_indent(source!(self, m.inner).hi() - BytePos(1));
665 self.close_block(false);
667 self.last_pos = source!(self, m.inner).hi();
670 self.last_pos = source!(self, s).hi();
674 pub fn format_separate_mod(&mut self, m: &ast::Mod, filemap: &codemap::FileMap) {
675 self.block_indent = Indent::empty();
676 self.walk_mod_items(m);
677 self.format_missing_with_indent(filemap.end_pos);
680 pub fn skip_empty_lines(&mut self, end_pos: BytePos) {
681 while let Some(pos) = self.snippet_provider
682 .opt_span_after(mk_sp(self.last_pos, end_pos), "\n")
684 if let Some(snippet) = self.opt_snippet(mk_sp(self.last_pos, pos)) {
685 if snippet.trim().is_empty() {
694 pub fn get_context(&self) -> RewriteContext {
696 parse_session: self.parse_session,
697 codemap: self.codemap,
700 use_block: RefCell::new(false),
701 is_if_else_block: false,
702 force_one_line_chain: RefCell::new(false),
703 snippet_provider: self.snippet_provider,