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.
13 use syntax::{ast, ptr, visit};
14 use syntax::codemap::{CodeMap, Span, BytePos};
15 use syntax::parse::ParseSess;
17 use strings::string_buffer::StringBuffer;
20 use utils::{self, mk_sp};
21 use codemap::{LineRangeUtils, SpanUtils};
22 use comment::{contains_comment, FindUncommented};
24 use rewrite::{Rewrite, RewriteContext};
25 use comment::rewrite_comment;
26 use macros::{rewrite_macro, MacroPosition};
27 use items::{rewrite_static, rewrite_associated_type, rewrite_associated_impl_type,
28 rewrite_type_alias, format_impl, format_trait};
29 use lists::{itemize_list, write_list, DefinitiveListTactic, ListFormatting, SeparatorTactic};
31 fn is_use_item(item: &ast::Item) -> bool {
33 ast::ItemKind::Use(_) => true,
38 fn item_bound(item: &ast::Item) -> Span {
39 item.attrs.iter().map(|attr| attr.span).fold(
43 lo: cmp::min(bound.lo, span.lo),
44 hi: cmp::max(bound.hi, span.hi),
51 pub struct FmtVisitor<'a> {
52 pub parse_session: &'a ParseSess,
53 pub codemap: &'a CodeMap,
54 pub buffer: StringBuffer,
55 pub last_pos: BytePos,
56 // FIXME: use an RAII util or closure for indenting
57 pub block_indent: Indent,
58 pub config: &'a Config,
60 pub is_if_else_block: bool,
63 impl<'a> FmtVisitor<'a> {
64 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
66 "visit_stmt: {:?} {:?}",
67 self.codemap.lookup_char_pos(stmt.span.lo),
68 self.codemap.lookup_char_pos(stmt.span.hi)
71 // FIXME(#434): Move this check to somewhere more central, eg Rewrite.
74 .intersects(&self.codemap.lookup_line_range(stmt.span))
80 ast::StmtKind::Item(ref item) => {
81 self.visit_item(item);
83 ast::StmtKind::Local(..) => {
84 let rewrite = stmt.rewrite(
86 Shape::indented(self.block_indent, self.config),
88 self.push_rewrite(stmt.span, rewrite);
90 ast::StmtKind::Expr(ref expr) |
91 ast::StmtKind::Semi(ref expr) => {
92 let rewrite = stmt.rewrite(
94 Shape::indented(self.block_indent, self.config),
96 let span = if expr.attrs.is_empty() {
99 mk_sp(expr.attrs[0].span.lo, stmt.span.hi)
101 self.push_rewrite(span, rewrite)
103 ast::StmtKind::Mac(ref mac) => {
104 let (ref mac, _macro_style, _) = **mac;
105 self.visit_mac(mac, None, MacroPosition::Statement);
106 self.format_missing(stmt.span.hi);
111 pub fn visit_block(&mut self, b: &ast::Block) {
113 "visit_block: {:?} {:?}",
114 self.codemap.lookup_char_pos(b.span.lo),
115 self.codemap.lookup_char_pos(b.span.hi)
118 // Check if this block has braces.
119 let snippet = self.snippet(b.span);
120 let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
121 let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
123 self.last_pos = self.last_pos + brace_compensation;
124 self.block_indent = self.block_indent.block_indent(self.config);
125 self.buffer.push_str("{");
127 for stmt in &b.stmts {
128 self.visit_stmt(stmt)
131 if !b.stmts.is_empty() {
132 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
133 if utils::semicolon_for_expr(expr) {
134 self.buffer.push_str(";");
139 let mut unindent_comment = self.is_if_else_block && !b.stmts.is_empty();
140 if unindent_comment {
141 let end_pos = source!(self, b.span).hi - brace_compensation;
142 let snippet = self.get_context().snippet(mk_sp(self.last_pos, end_pos));
143 unindent_comment = snippet.contains("//") || snippet.contains("/*");
145 // FIXME: we should compress any newlines here to just one
146 if unindent_comment {
147 self.block_indent = self.block_indent.block_unindent(self.config);
149 self.format_missing_with_indent(source!(self, b.span).hi - brace_compensation);
150 if unindent_comment {
151 self.block_indent = self.block_indent.block_indent(self.config);
153 self.close_block(unindent_comment);
154 self.last_pos = source!(self, b.span).hi;
157 // FIXME: this is a terrible hack to indent the comments between the last
158 // item in the block and the closing brace to the block's level.
159 // The closing brace itself, however, should be indented at a shallower
161 fn close_block(&mut self, unindent_comment: bool) {
162 let total_len = self.buffer.len;
163 let chars_too_many = if unindent_comment {
165 } else if self.config.hard_tabs() {
168 self.config.tab_spaces()
170 self.buffer.truncate(total_len - chars_too_many);
171 self.buffer.push_str("}");
172 self.block_indent = self.block_indent.block_unindent(self.config);
175 // Note that this only gets called for function definitions. Required methods
176 // on traits do not get handled here.
183 defaultness: ast::Defaultness,
185 let indent = self.block_indent;
187 let rewrite = match fk {
188 visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis, b) => {
200 mk_sp(s.lo, b.span.lo),
204 visit::FnKind::Method(ident, sig, vis, b) => {
215 vis.unwrap_or(&ast::Visibility::Inherited),
216 mk_sp(s.lo, b.span.lo),
220 visit::FnKind::Closure(_) => unreachable!(),
223 if let Some(fn_str) = rewrite {
224 self.format_missing_with_indent(source!(self, s).lo);
225 self.buffer.push_str(&fn_str);
226 if let Some(c) = fn_str.chars().last() {
228 self.last_pos = source!(self, block.span).hi;
233 self.format_missing(source!(self, block.span).lo);
236 self.last_pos = source!(self, block.span).lo;
237 self.visit_block(block)
240 pub fn visit_item(&mut self, item: &ast::Item) {
241 // This is where we bail out if there is a skip attribute. This is only
242 // complex in the module case. It is complex because the module could be
243 // in a separate file and there might be attributes in both files, but
244 // the AST lumps them all together.
246 ast::ItemKind::Mod(ref m) => {
247 let outer_file = self.codemap.lookup_char_pos(item.span.lo).file;
248 let inner_file = self.codemap.lookup_char_pos(m.inner.lo).file;
249 if outer_file.name == inner_file.name {
250 // Module is inline, in this case we treat modules like any
252 if self.visit_attrs(&item.attrs) {
253 self.push_rewrite(item.span, None);
256 } else if utils::contains_skip(&item.attrs) {
257 // Module is not inline, but should be skipped.
260 // Module is not inline and should not be skipped. We want
261 // to process only the attributes in the current file.
262 let attrs = item.attrs
265 let attr_file = self.codemap.lookup_char_pos(a.span.lo).file;
266 if attr_file.name == outer_file.name {
272 .collect::<Vec<_>>();
273 // Assert because if we should skip it should be caught by
275 assert!(!self.visit_attrs(&attrs));
279 if self.visit_attrs(&item.attrs) {
280 self.push_rewrite(item.span, None);
287 ast::ItemKind::Use(ref vp) => {
288 self.format_import(&item.vis, vp, item.span);
290 ast::ItemKind::Impl(..) => {
291 self.format_missing_with_indent(source!(self, item.span).lo);
292 let snippet = self.get_context().snippet(item.span);
293 let where_span_end = snippet
294 .find_uncommented("{")
295 .map(|x| (BytePos(x as u32)) + source!(self, item.span).lo);
296 if let Some(impl_str) = format_impl(
303 self.buffer.push_str(&impl_str);
304 self.last_pos = source!(self, item.span).hi;
307 ast::ItemKind::Trait(..) => {
308 self.format_missing_with_indent(item.span.lo);
309 if let Some(trait_str) = format_trait(
315 self.buffer.push_str(&trait_str);
316 self.last_pos = source!(self, item.span).hi;
319 ast::ItemKind::ExternCrate(_) => {
320 self.format_missing_with_indent(source!(self, item.span).lo);
321 let new_str = self.snippet(item.span);
322 self.buffer.push_str(&new_str);
323 self.last_pos = source!(self, item.span).hi;
325 ast::ItemKind::Struct(ref def, ref generics) => {
327 let indent = self.block_indent;
328 let context = self.get_context();
329 ::items::format_struct(
339 ).map(|s| match *def {
340 ast::VariantData::Tuple(..) => s + ";",
344 self.push_rewrite(item.span, rewrite);
346 ast::ItemKind::Enum(ref def, ref generics) => {
347 self.format_missing_with_indent(source!(self, item.span).lo);
348 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
349 self.last_pos = source!(self, item.span).hi;
351 ast::ItemKind::Mod(ref module) => {
352 self.format_missing_with_indent(source!(self, item.span).lo);
353 self.format_mod(module, &item.vis, item.span, item.ident);
355 ast::ItemKind::Mac(ref mac) => {
356 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
358 ast::ItemKind::ForeignMod(ref foreign_mod) => {
359 self.format_missing_with_indent(source!(self, item.span).lo);
360 self.format_foreign_mod(foreign_mod, item.span);
362 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
363 let rewrite = rewrite_static(
374 self.push_rewrite(item.span, rewrite);
376 ast::ItemKind::Const(ref ty, ref expr) => {
377 let rewrite = rewrite_static(
382 ast::Mutability::Immutable,
388 self.push_rewrite(item.span, rewrite);
390 ast::ItemKind::DefaultImpl(..) => {
391 // FIXME(#78): format impl definitions.
393 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
395 visit::FnKind::ItemFn(
407 ast::Defaultness::Final,
410 ast::ItemKind::Ty(ref ty, ref generics) => {
411 let rewrite = rewrite_type_alias(
420 self.push_rewrite(item.span, rewrite);
422 ast::ItemKind::Union(..) => {
423 // FIXME(#1157): format union definitions.
425 ast::ItemKind::GlobalAsm(..) => {
426 let snippet = Some(self.snippet(item.span));
427 self.push_rewrite(item.span, snippet);
429 ast::ItemKind::MacroDef(..) => {
430 // FIXME(#1539): macros 2.0
431 let snippet = Some(self.snippet(item.span));
432 self.push_rewrite(item.span, snippet);
437 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
438 if self.visit_attrs(&ti.attrs) {
439 self.push_rewrite(ti.span, None);
444 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
445 let rewrite = rewrite_static(
447 &ast::Visibility::Inherited,
450 ast::Mutability::Immutable,
456 self.push_rewrite(ti.span, rewrite);
458 ast::TraitItemKind::Method(ref sig, None) => {
459 let indent = self.block_indent;
460 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
461 self.push_rewrite(ti.span, rewrite);
463 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
465 visit::FnKind::Method(ti.ident, sig, None, body),
469 ast::Defaultness::Final,
472 ast::TraitItemKind::Type(ref type_param_bounds, ref type_default) => {
473 let rewrite = rewrite_associated_type(
475 type_default.as_ref(),
476 Some(type_param_bounds),
480 self.push_rewrite(ti.span, rewrite);
482 ast::TraitItemKind::Macro(ref mac) => {
483 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
488 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
489 if self.visit_attrs(&ii.attrs) {
490 self.push_rewrite(ii.span, None);
495 ast::ImplItemKind::Method(ref sig, ref body) => {
497 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
504 ast::ImplItemKind::Const(ref ty, ref expr) => {
505 let rewrite = rewrite_static(
510 ast::Mutability::Immutable,
516 self.push_rewrite(ii.span, rewrite);
518 ast::ImplItemKind::Type(ref ty) => {
519 let rewrite = rewrite_associated_impl_type(
527 self.push_rewrite(ii.span, rewrite);
529 ast::ImplItemKind::Macro(ref mac) => {
530 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
535 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
537 let shape = Shape::indented(self.block_indent, self.config)
540 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
541 self.push_rewrite(mac.span, rewrite);
544 fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
545 self.format_missing_with_indent(source!(self, span).lo);
546 self.failed = match rewrite {
550 Shape::indented(self.block_indent, self.config),
555 let result = rewrite.unwrap_or_else(|| self.snippet(span));
556 self.buffer.push_str(&result);
557 self.last_pos = source!(self, span).hi;
560 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
562 parse_session: parse_session,
563 codemap: parse_session.codemap(),
564 buffer: StringBuffer::new(),
565 last_pos: BytePos(0),
566 block_indent: Indent::empty(),
569 is_if_else_block: false,
573 pub fn snippet(&self, span: Span) -> String {
574 match self.codemap.span_to_snippet(span) {
578 "Couldn't make snippet for span {:?}->{:?}",
579 self.codemap.lookup_char_pos(span.lo),
580 self.codemap.lookup_char_pos(span.hi)
587 // Returns true if we should skip the following item.
588 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
589 if utils::contains_skip(attrs) {
593 let outers: Vec<_> = attrs
595 .filter(|a| a.style == ast::AttrStyle::Outer)
598 if outers.is_empty() {
602 let first = &outers[0];
603 self.format_missing_with_indent(source!(self, first.span).lo);
608 Shape::indented(self.block_indent, self.config),
611 self.buffer.push_str(&rewrite);
612 let last = outers.last().unwrap();
613 self.last_pos = source!(self, last.span).hi;
617 fn walk_mod_items(&mut self, m: &ast::Mod) {
618 let mut items_left: &[ptr::P<ast::Item>] = &m.items;
619 while !items_left.is_empty() {
620 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
621 // to be potentially reordered within `format_imports`. Otherwise, just format the
622 // next item for output.
623 if self.config.reorder_imports() && is_use_item(&*items_left[0]) {
624 let reorder_imports_in_group = self.config.reorder_imports_in_group();
625 let mut last = self.codemap.lookup_line_range(item_bound(&items_left[0]));
626 let use_item_length = items_left
629 is_use_item(&***ppi) &&
630 (!reorder_imports_in_group ||
632 let current = self.codemap.lookup_line_range(item_bound(&ppi));
633 let in_same_group = current.lo < last.hi + 2;
639 let (use_items, rest) = items_left.split_at(use_item_length);
640 self.format_imports(use_items);
643 // `unwrap()` is safe here because we know `items_left`
644 // has elements from the loop condition
645 let (item, rest) = items_left.split_first().unwrap();
646 self.visit_item(item);
652 fn format_mod(&mut self, m: &ast::Mod, vis: &ast::Visibility, s: Span, ident: ast::Ident) {
653 // Decide whether this is an inline mod or an external mod.
654 let local_file_name = self.codemap.span_to_filename(s);
655 let inner_span = source!(self, m.inner);
656 let is_internal = !(inner_span.lo.0 == 0 && inner_span.hi.0 == 0) &&
657 local_file_name == self.codemap.span_to_filename(inner_span);
659 self.buffer.push_str(&*utils::format_visibility(vis));
660 self.buffer.push_str("mod ");
661 self.buffer.push_str(&ident.to_string());
664 self.buffer.push_str(" {");
665 // Hackery to account for the closing }.
666 let mod_lo = self.codemap.span_after(source!(self, s), "{");
667 let body_snippet = self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi - BytePos(1)));
668 let body_snippet = body_snippet.trim();
669 if body_snippet.is_empty() {
670 self.buffer.push_str("}");
672 self.last_pos = mod_lo;
673 self.block_indent = self.block_indent.block_indent(self.config);
674 self.walk_mod_items(m);
675 self.format_missing_with_indent(source!(self, m.inner).hi - BytePos(1));
676 self.close_block(false);
678 self.last_pos = source!(self, m.inner).hi;
680 self.buffer.push_str(";");
681 self.last_pos = source!(self, s).hi;
685 pub fn format_separate_mod(&mut self, m: &ast::Mod) {
686 let filemap = self.codemap.lookup_char_pos(m.inner.lo).file;
687 self.last_pos = filemap.start_pos;
688 self.block_indent = Indent::empty();
689 self.walk_mod_items(m);
690 self.format_missing_with_indent(filemap.end_pos);
693 pub fn get_context(&self) -> RewriteContext {
695 parse_session: self.parse_session,
696 codemap: self.codemap,
700 is_if_else_block: false,
701 force_one_line_chain: false,
706 impl Rewrite for ast::NestedMetaItem {
707 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
709 ast::NestedMetaItemKind::MetaItem(ref meta_item) => meta_item.rewrite(context, shape),
710 ast::NestedMetaItemKind::Literal(..) => Some(context.snippet(self.span)),
715 fn count_missing_closing_parens(s: &str) -> u32 {
716 let op_parens = s.chars().filter(|c| *c == '(').count();
717 let cl_parens = s.chars().filter(|c| *c == ')').count();
718 op_parens.checked_sub(cl_parens).unwrap_or(0) as u32
721 impl Rewrite for ast::MetaItem {
722 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
723 Some(match self.node {
724 ast::MetaItemKind::Word => String::from(&*self.name.as_str()),
725 ast::MetaItemKind::List(ref list) => {
726 let name = self.name.as_str();
727 // 3 = `#[` and `(`, 2 = `]` and `)`
728 let item_shape = try_opt!(
730 .shrink_left(name.len() + 3)
731 .and_then(|s| s.sub_width(2))
733 let hi = self.span.hi +
734 BytePos(count_missing_closing_parens(&context.snippet(self.span)));
735 let items = itemize_list(
739 |nested_meta_item| nested_meta_item.span.lo,
740 // FIXME: Span from MetaItem is missing closing parens.
742 let snippet = context.snippet(nested_meta_item.span);
743 nested_meta_item.span.hi + BytePos(count_missing_closing_parens(&snippet))
745 |nested_meta_item| nested_meta_item.rewrite(context, item_shape),
749 let item_vec = items.collect::<Vec<_>>();
750 let fmt = ListFormatting {
751 tactic: DefinitiveListTactic::Mixed,
753 trailing_separator: SeparatorTactic::Never,
755 ends_with_newline: false,
756 config: context.config,
758 format!("{}({})", name, try_opt!(write_list(&item_vec, &fmt)))
760 ast::MetaItemKind::NameValue(ref literal) => {
761 let name = self.name.as_str();
762 let value = context.snippet(literal.span);
763 if &*name == "doc" && contains_comment(&value) {
764 let doc_shape = Shape {
765 width: cmp::min(shape.width, context.config.comment_width())
766 .checked_sub(shape.indent.width())
772 try_opt!(rewrite_comment(&value, false, doc_shape, context.config))
775 format!("{} = {}", name, value)
782 impl Rewrite for ast::Attribute {
783 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
784 try_opt!(self.meta()).rewrite(context, shape).map(
785 |rw| if rw.starts_with("///") {
788 let original = context.snippet(self.span);
789 if contains_comment(&original) {
799 impl<'a> Rewrite for [ast::Attribute] {
800 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
801 let mut result = String::new();
805 let indent = shape.indent.to_string(context.config);
807 for (i, a) in self.iter().enumerate() {
808 let a_str = try_opt!(a.rewrite(context, shape));
810 // Write comments and blank lines between attributes.
812 let comment = context.snippet(mk_sp(self[i - 1].span.hi, a.span.lo));
813 // This particular horror show is to preserve line breaks in between doc
814 // comments. An alternative would be to force such line breaks to start
815 // with the usual doc comment token.
816 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
817 let comment = comment.trim();
818 if !comment.is_empty() {
819 let comment = try_opt!(rewrite_comment(
823 context.config.comment_width() - shape.indent.width(),
828 result.push_str(&indent);
829 result.push_str(&comment);
831 } else if multi_line {
834 result.push_str(&indent);
837 // Write the attribute itself.
838 result.push_str(&a_str);
840 if i < self.len() - 1 {