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, ptr, visit};
12 use syntax::codemap::{self, CodeMap, Span, BytePos};
13 use syntax::parse::ParseSess;
15 use strings::string_buffer::StringBuffer;
19 use codemap::{LineRangeUtils, SpanUtils};
21 use rewrite::{Rewrite, RewriteContext};
22 use comment::rewrite_comment;
23 use macros::{rewrite_macro, MacroPosition};
24 use items::{rewrite_static, rewrite_associated_type, rewrite_associated_impl_type,
25 rewrite_type_alias, format_impl, format_trait};
27 fn is_use_item(item: &ast::Item) -> bool {
29 ast::ItemKind::Use(_) => true,
34 pub struct FmtVisitor<'a> {
35 pub parse_session: &'a ParseSess,
36 pub codemap: &'a CodeMap,
37 pub buffer: StringBuffer,
38 pub last_pos: BytePos,
39 // FIXME: use an RAII util or closure for indenting
40 pub block_indent: Indent,
41 pub config: &'a Config,
45 impl<'a> FmtVisitor<'a> {
46 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
47 debug!("visit_stmt: {:?} {:?}",
48 self.codemap.lookup_char_pos(stmt.span.lo),
49 self.codemap.lookup_char_pos(stmt.span.hi));
51 // FIXME(#434): Move this check to somewhere more central, eg Rewrite.
54 .intersects(&self.codemap.lookup_line_range(stmt.span)) {
59 ast::StmtKind::Item(ref item) => {
60 self.visit_item(item);
62 ast::StmtKind::Local(..) |
63 ast::StmtKind::Expr(..) |
64 ast::StmtKind::Semi(..) => {
66 stmt.rewrite(&self.get_context(),
67 Shape::indented(self.block_indent, self.config));
68 self.push_rewrite(stmt.span, rewrite);
70 ast::StmtKind::Mac(ref mac) => {
71 let (ref mac, _macro_style, _) = **mac;
72 self.visit_mac(mac, None, MacroPosition::Statement);
73 self.format_missing(stmt.span.hi);
78 pub fn visit_block(&mut self, b: &ast::Block) {
79 debug!("visit_block: {:?} {:?}",
80 self.codemap.lookup_char_pos(b.span.lo),
81 self.codemap.lookup_char_pos(b.span.hi));
83 // Check if this block has braces.
84 let snippet = self.snippet(b.span);
85 let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
86 let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
88 self.last_pos = self.last_pos + brace_compensation;
89 self.block_indent = self.block_indent.block_indent(self.config);
90 self.buffer.push_str("{");
92 for stmt in &b.stmts {
96 if !b.stmts.is_empty() {
97 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
98 if utils::semicolon_for_expr(expr) {
99 self.buffer.push_str(";");
104 // FIXME: we should compress any newlines here to just one
105 self.format_missing_with_indent(source!(self, b.span).hi - brace_compensation);
107 self.last_pos = source!(self, b.span).hi;
110 // FIXME: this is a terrible hack to indent the comments between the last
111 // item in the block and the closing brace to the block's level.
112 // The closing brace itself, however, should be indented at a shallower
114 fn close_block(&mut self) {
115 let total_len = self.buffer.len;
116 let chars_too_many = if self.config.hard_tabs {
119 self.config.tab_spaces
121 self.buffer.truncate(total_len - chars_too_many);
122 self.buffer.push_str("}");
123 self.block_indent = self.block_indent.block_unindent(self.config);
126 // Note that this only gets called for function definitions. Required methods
127 // on traits do not get handled here.
128 fn visit_fn(&mut self,
133 defaultness: ast::Defaultness) {
134 let indent = self.block_indent;
136 let rewrite = match fk {
137 visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis, b) => {
139 self.rewrite_fn(indent,
148 codemap::mk_sp(s.lo, b.span.lo),
151 visit::FnKind::Method(ident, sig, vis, b) => {
153 self.rewrite_fn(indent,
161 vis.unwrap_or(&ast::Visibility::Inherited),
162 codemap::mk_sp(s.lo, b.span.lo),
165 visit::FnKind::Closure(_) => unreachable!(),
168 if let Some(fn_str) = rewrite {
169 self.format_missing_with_indent(source!(self, s).lo);
170 self.buffer.push_str(&fn_str);
171 if let Some(c) = fn_str.chars().last() {
173 self.last_pos = source!(self, block.span).hi;
178 self.format_missing(source!(self, block.span).lo);
181 self.last_pos = source!(self, block.span).lo;
182 self.visit_block(block)
185 pub fn visit_item(&mut self, item: &ast::Item) {
186 // This is where we bail out if there is a skip attribute. This is only
187 // complex in the module case. It is complex because the module could be
188 // in a separate file and there might be attributes in both files, but
189 // the AST lumps them all together.
191 ast::ItemKind::Mod(ref m) => {
192 let outer_file = self.codemap.lookup_char_pos(item.span.lo).file;
193 let inner_file = self.codemap.lookup_char_pos(m.inner.lo).file;
194 if outer_file.name == inner_file.name {
195 // Module is inline, in this case we treat modules like any
197 if self.visit_attrs(&item.attrs) {
198 self.push_rewrite(item.span, None);
201 } else if utils::contains_skip(&item.attrs) {
202 // Module is not inline, but should be skipped.
205 // Module is not inline and should not be skipped. We want
206 // to process only the attributes in the current file.
207 let attrs = item.attrs
210 let attr_file = self.codemap.lookup_char_pos(a.span.lo).file;
211 if attr_file.name == outer_file.name {
217 .collect::<Vec<_>>();
218 // Assert because if we should skip it should be caught by
220 assert!(!self.visit_attrs(&attrs));
224 if self.visit_attrs(&item.attrs) {
225 self.push_rewrite(item.span, None);
232 ast::ItemKind::Use(ref vp) => {
233 self.format_import(&item.vis, vp, item.span);
235 ast::ItemKind::Impl(..) => {
236 self.format_missing_with_indent(source!(self, item.span).lo);
237 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
238 self.buffer.push_str(&impl_str);
239 self.last_pos = source!(self, item.span).hi;
242 ast::ItemKind::Trait(..) => {
243 self.format_missing_with_indent(item.span.lo);
244 if let Some(trait_str) = format_trait(&self.get_context(),
247 self.buffer.push_str(&trait_str);
248 self.last_pos = source!(self, item.span).hi;
251 ast::ItemKind::ExternCrate(_) => {
252 self.format_missing_with_indent(source!(self, item.span).lo);
253 let new_str = self.snippet(item.span);
254 self.buffer.push_str(&new_str);
255 self.last_pos = source!(self, item.span).hi;
257 ast::ItemKind::Struct(ref def, ref generics) => {
259 let indent = self.block_indent;
260 let context = self.get_context();
261 ::items::format_struct(&context,
270 .map(|s| match *def {
271 ast::VariantData::Tuple(..) => s + ";",
275 self.push_rewrite(item.span, rewrite);
277 ast::ItemKind::Enum(ref def, ref generics) => {
278 self.format_missing_with_indent(source!(self, item.span).lo);
279 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
280 self.last_pos = source!(self, item.span).hi;
282 ast::ItemKind::Mod(ref module) => {
283 self.format_missing_with_indent(source!(self, item.span).lo);
284 self.format_mod(module, &item.vis, item.span, item.ident);
286 ast::ItemKind::Mac(ref mac) => {
287 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
289 ast::ItemKind::ForeignMod(ref foreign_mod) => {
290 self.format_missing_with_indent(source!(self, item.span).lo);
291 self.format_foreign_mod(foreign_mod, item.span);
293 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
294 let rewrite = rewrite_static("static",
301 &self.get_context());
302 self.push_rewrite(item.span, rewrite);
304 ast::ItemKind::Const(ref ty, ref expr) => {
305 let rewrite = rewrite_static("const",
309 ast::Mutability::Immutable,
312 &self.get_context());
313 self.push_rewrite(item.span, rewrite);
315 ast::ItemKind::DefaultImpl(..) => {
316 // FIXME(#78): format impl definitions.
318 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
319 self.visit_fn(visit::FnKind::ItemFn(item.ident,
329 ast::Defaultness::Final)
331 ast::ItemKind::Ty(ref ty, ref generics) => {
332 let rewrite = rewrite_type_alias(&self.get_context(),
339 self.push_rewrite(item.span, rewrite);
341 ast::ItemKind::Union(..) => {
342 // FIXME(#1157): format union definitions.
347 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
348 if self.visit_attrs(&ti.attrs) {
349 self.push_rewrite(ti.span, None);
354 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
355 let rewrite = rewrite_static("const",
356 &ast::Visibility::Inherited,
359 ast::Mutability::Immutable,
362 &self.get_context());
363 self.push_rewrite(ti.span, rewrite);
365 ast::TraitItemKind::Method(ref sig, None) => {
366 let indent = self.block_indent;
367 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
368 self.push_rewrite(ti.span, rewrite);
370 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
371 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None, body),
375 ast::Defaultness::Final);
377 ast::TraitItemKind::Type(ref type_param_bounds, _) => {
378 let rewrite = rewrite_associated_type(ti.ident,
380 Some(type_param_bounds),
383 self.push_rewrite(ti.span, rewrite);
385 ast::TraitItemKind::Macro(ref mac) => {
386 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
391 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
392 if self.visit_attrs(&ii.attrs) {
393 self.push_rewrite(ii.span, None);
398 ast::ImplItemKind::Method(ref sig, ref body) => {
399 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
405 ast::ImplItemKind::Const(ref ty, ref expr) => {
406 let rewrite = rewrite_static("const",
410 ast::Mutability::Immutable,
413 &self.get_context());
414 self.push_rewrite(ii.span, rewrite);
416 ast::ImplItemKind::Type(ref ty) => {
417 let rewrite = rewrite_associated_impl_type(ii.ident,
423 self.push_rewrite(ii.span, rewrite);
425 ast::ImplItemKind::Macro(ref mac) => {
426 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
431 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
433 let shape = Shape::indented(self.block_indent, self.config)
436 let rewrite = rewrite_macro(mac, ident, &self.get_context(), shape, pos);
437 self.push_rewrite(mac.span, rewrite);
440 fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
441 self.format_missing_with_indent(source!(self, span).lo);
442 self.failed = match rewrite {
443 Some(ref s) if s.rewrite(&self.get_context(),
444 Shape::indented(self.block_indent, self.config))
449 let result = rewrite.unwrap_or_else(|| self.snippet(span));
450 self.buffer.push_str(&result);
451 self.last_pos = source!(self, span).hi;
454 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
456 parse_session: parse_session,
457 codemap: parse_session.codemap(),
458 buffer: StringBuffer::new(),
459 last_pos: BytePos(0),
460 block_indent: Indent::empty(),
466 pub fn snippet(&self, span: Span) -> String {
467 match self.codemap.span_to_snippet(span) {
470 println!("Couldn't make snippet for span {:?}->{:?}",
471 self.codemap.lookup_char_pos(span.lo),
472 self.codemap.lookup_char_pos(span.hi));
478 // Returns true if we should skip the following item.
479 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
480 if utils::contains_skip(attrs) {
484 let outers: Vec<_> = attrs
486 .filter(|a| a.style == ast::AttrStyle::Outer)
489 if outers.is_empty() {
493 let first = &outers[0];
494 self.format_missing_with_indent(source!(self, first.span).lo);
497 .rewrite(&self.get_context(),
498 Shape::indented(self.block_indent, self.config))
500 self.buffer.push_str(&rewrite);
501 let last = outers.last().unwrap();
502 self.last_pos = source!(self, last.span).hi;
506 fn walk_mod_items(&mut self, m: &ast::Mod) {
507 let mut items_left: &[ptr::P<ast::Item>] = &m.items;
508 while !items_left.is_empty() {
509 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
510 // to be potentially reordered within `format_imports`. Otherwise, just format the
511 // next item for output.
512 if self.config.reorder_imports && is_use_item(&*items_left[0]) {
513 let use_item_length = items_left
515 .take_while(|ppi| is_use_item(&***ppi))
517 let (use_items, rest) = items_left.split_at(use_item_length);
518 self.format_imports(use_items);
521 // `unwrap()` is safe here because we know `items_left`
522 // has elements from the loop condition
523 let (item, rest) = items_left.split_first().unwrap();
524 self.visit_item(item);
530 fn format_mod(&mut self, m: &ast::Mod, vis: &ast::Visibility, s: Span, ident: ast::Ident) {
531 // Decide whether this is an inline mod or an external mod.
532 let local_file_name = self.codemap.span_to_filename(s);
533 let inner_span = source!(self, m.inner);
534 let is_internal = !(inner_span.lo.0 == 0 && inner_span.hi.0 == 0) &&
535 local_file_name == self.codemap.span_to_filename(inner_span);
537 self.buffer.push_str(&*utils::format_visibility(vis));
538 self.buffer.push_str("mod ");
539 self.buffer.push_str(&ident.to_string());
542 self.buffer.push_str(" {");
543 // Hackery to account for the closing }.
544 let mod_lo = self.codemap.span_after(source!(self, s), "{");
546 self.snippet(codemap::mk_sp(mod_lo, source!(self, m.inner).hi - BytePos(1)));
547 let body_snippet = body_snippet.trim();
548 if body_snippet.is_empty() {
549 self.buffer.push_str("}");
551 self.last_pos = mod_lo;
552 self.block_indent = self.block_indent.block_indent(self.config);
553 self.walk_mod_items(m);
554 self.format_missing_with_indent(source!(self, m.inner).hi - BytePos(1));
557 self.last_pos = source!(self, m.inner).hi;
559 self.buffer.push_str(";");
560 self.last_pos = source!(self, s).hi;
564 pub fn format_separate_mod(&mut self, m: &ast::Mod) {
565 let filemap = self.codemap.lookup_char_pos(m.inner.lo).file;
566 self.last_pos = filemap.start_pos;
567 self.block_indent = Indent::empty();
568 self.walk_mod_items(m);
569 self.format_missing_with_indent(filemap.end_pos);
572 pub fn get_context(&self) -> RewriteContext {
574 parse_session: self.parse_session,
575 codemap: self.codemap,
582 impl<'a> Rewrite for [ast::Attribute] {
583 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
584 let mut result = String::new();
588 let indent = shape.indent.to_string(context.config);
590 for (i, a) in self.iter().enumerate() {
591 let mut a_str = context.snippet(a.span);
593 // Write comments and blank lines between attributes.
595 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
596 // This particular horror show is to preserve line breaks in between doc
597 // comments. An alternative would be to force such line breaks to start
598 // with the usual doc comment token.
599 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
600 let comment = comment.trim();
601 if !comment.is_empty() {
602 let comment = try_opt!(rewrite_comment(comment,
604 Shape::legacy(context.config
606 shape.indent.width(),
609 result.push_str(&indent);
610 result.push_str(&comment);
612 } else if multi_line {
615 result.push_str(&indent);
618 if a_str.starts_with("//") {
619 a_str = try_opt!(rewrite_comment(&a_str,
621 Shape::legacy(context.config.comment_width -
622 shape.indent.width(),
627 // Write the attribute itself.
628 result.push_str(&a_str);
630 if i < self.len() - 1 {