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,
44 impl<'a> FmtVisitor<'a> {
45 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
46 debug!("visit_stmt: {:?} {:?}",
47 self.codemap.lookup_char_pos(stmt.span.lo),
48 self.codemap.lookup_char_pos(stmt.span.hi));
50 // FIXME(#434): Move this check to somewhere more central, eg Rewrite.
51 if !self.config.file_lines.contains(&self.codemap.lookup_line_range(stmt.span)) {
56 ast::StmtKind::Item(ref item) => {
57 self.visit_item(item);
59 ast::StmtKind::Local(..) |
60 ast::StmtKind::Expr(..) |
61 ast::StmtKind::Semi(..) => {
62 let rewrite = stmt.rewrite(&self.get_context(),
63 Shape::legacy(self.config.max_width -
64 self.block_indent.width(),
66 self.push_rewrite(stmt.span, rewrite);
68 ast::StmtKind::Mac(ref mac) => {
69 let (ref mac, _macro_style, _) = **mac;
70 self.visit_mac(mac, None, MacroPosition::Statement);
71 self.format_missing(stmt.span.hi);
76 pub fn visit_block(&mut self, b: &ast::Block) {
77 debug!("visit_block: {:?} {:?}",
78 self.codemap.lookup_char_pos(b.span.lo),
79 self.codemap.lookup_char_pos(b.span.hi));
81 // Check if this block has braces.
82 let snippet = self.snippet(b.span);
83 let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
84 let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
86 self.last_pos = self.last_pos + brace_compensation;
87 self.block_indent = self.block_indent.block_indent(self.config);
88 self.buffer.push_str("{");
90 for stmt in &b.stmts {
94 if !b.stmts.is_empty() {
95 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
96 if utils::semicolon_for_expr(expr) {
97 self.buffer.push_str(";");
102 // FIXME: we should compress any newlines here to just one
103 self.format_missing_with_indent(source!(self, b.span).hi - brace_compensation);
105 self.last_pos = source!(self, b.span).hi;
108 // FIXME: this is a terrible hack to indent the comments between the last
109 // item in the block and the closing brace to the block's level.
110 // The closing brace itself, however, should be indented at a shallower
112 fn close_block(&mut self) {
113 let total_len = self.buffer.len;
114 let chars_too_many = if self.config.hard_tabs {
117 self.config.tab_spaces
119 self.buffer.truncate(total_len - chars_too_many);
120 self.buffer.push_str("}");
121 self.block_indent = self.block_indent.block_unindent(self.config);
124 // Note that this only gets called for function definitions. Required methods
125 // on traits do not get handled here.
126 fn visit_fn(&mut self,
131 defaultness: ast::Defaultness) {
132 let indent = self.block_indent;
134 let rewrite = match fk {
135 visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis, b) => {
137 self.rewrite_fn(indent,
146 codemap::mk_sp(s.lo, b.span.lo),
149 visit::FnKind::Method(ident, sig, vis, b) => {
151 self.rewrite_fn(indent,
159 vis.unwrap_or(&ast::Visibility::Inherited),
160 codemap::mk_sp(s.lo, b.span.lo),
163 visit::FnKind::Closure(_) => unreachable!(),
166 if let Some(fn_str) = rewrite {
167 self.format_missing_with_indent(source!(self, s).lo);
168 self.buffer.push_str(&fn_str);
169 if let Some(c) = fn_str.chars().last() {
171 self.last_pos = source!(self, block.span).hi;
176 self.format_missing(source!(self, block.span).lo);
179 self.last_pos = source!(self, block.span).lo;
180 self.visit_block(block)
183 pub fn visit_item(&mut self, item: &ast::Item) {
184 // This is where we bail out if there is a skip attribute. This is only
185 // complex in the module case. It is complex because the module could be
186 // in a separate file and there might be attributes in both files, but
187 // the AST lumps them all together.
189 ast::ItemKind::Mod(ref m) => {
190 let outer_file = self.codemap.lookup_char_pos(item.span.lo).file;
191 let inner_file = self.codemap.lookup_char_pos(m.inner.lo).file;
192 if outer_file.name == inner_file.name {
193 // Module is inline, in this case we treat modules like any
195 if self.visit_attrs(&item.attrs) {
196 self.push_rewrite(item.span, None);
199 } else if utils::contains_skip(&item.attrs) {
200 // Module is not inline, but should be skipped.
203 // Module is not inline and should not be skipped. We want
204 // to process only the attributes in the current file.
205 let attrs = item.attrs
208 let attr_file = self.codemap.lookup_char_pos(a.span.lo).file;
209 if attr_file.name == outer_file.name {
215 .collect::<Vec<_>>();
216 // Assert because if we should skip it should be caught by
218 assert!(!self.visit_attrs(&attrs));
222 if self.visit_attrs(&item.attrs) {
223 self.push_rewrite(item.span, None);
230 ast::ItemKind::Use(ref vp) => {
231 self.format_import(&item.vis, vp, item.span);
233 ast::ItemKind::Impl(..) => {
234 self.format_missing_with_indent(source!(self, item.span).lo);
235 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
236 self.buffer.push_str(&impl_str);
237 self.last_pos = source!(self, item.span).hi;
240 ast::ItemKind::Trait(..) => {
241 self.format_missing_with_indent(item.span.lo);
242 if let Some(trait_str) = format_trait(&self.get_context(),
245 self.buffer.push_str(&trait_str);
246 self.last_pos = source!(self, item.span).hi;
249 ast::ItemKind::ExternCrate(_) => {
250 self.format_missing_with_indent(source!(self, item.span).lo);
251 let new_str = self.snippet(item.span);
252 self.buffer.push_str(&new_str);
253 self.last_pos = source!(self, item.span).hi;
255 ast::ItemKind::Struct(ref def, ref generics) => {
257 let indent = self.block_indent;
258 let context = self.get_context();
259 ::items::format_struct(&context,
268 .map(|s| match *def {
269 ast::VariantData::Tuple(..) => s + ";",
273 self.push_rewrite(item.span, rewrite);
275 ast::ItemKind::Enum(ref def, ref generics) => {
276 self.format_missing_with_indent(source!(self, item.span).lo);
277 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
278 self.last_pos = source!(self, item.span).hi;
280 ast::ItemKind::Mod(ref module) => {
281 self.format_missing_with_indent(source!(self, item.span).lo);
282 self.format_mod(module, &item.vis, item.span, item.ident);
284 ast::ItemKind::Mac(ref mac) => {
285 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
287 ast::ItemKind::ForeignMod(ref foreign_mod) => {
288 self.format_missing_with_indent(source!(self, item.span).lo);
289 self.format_foreign_mod(foreign_mod, item.span);
291 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
292 let rewrite = rewrite_static("static",
299 &self.get_context());
300 self.push_rewrite(item.span, rewrite);
302 ast::ItemKind::Const(ref ty, ref expr) => {
303 let rewrite = rewrite_static("const",
307 ast::Mutability::Immutable,
310 &self.get_context());
311 self.push_rewrite(item.span, rewrite);
313 ast::ItemKind::DefaultImpl(..) => {
314 // FIXME(#78): format impl definitions.
316 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
317 self.visit_fn(visit::FnKind::ItemFn(item.ident,
327 ast::Defaultness::Final)
329 ast::ItemKind::Ty(ref ty, ref generics) => {
330 let rewrite = rewrite_type_alias(&self.get_context(),
337 self.push_rewrite(item.span, rewrite);
339 ast::ItemKind::Union(..) => {
340 // FIXME(#1157): format union definitions.
345 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
346 if self.visit_attrs(&ti.attrs) {
347 self.push_rewrite(ti.span, None);
352 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
353 let rewrite = rewrite_static("const",
354 &ast::Visibility::Inherited,
357 ast::Mutability::Immutable,
360 &self.get_context());
361 self.push_rewrite(ti.span, rewrite);
363 ast::TraitItemKind::Method(ref sig, None) => {
364 let indent = self.block_indent;
365 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
366 self.push_rewrite(ti.span, rewrite);
368 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
369 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None, body),
373 ast::Defaultness::Final);
375 ast::TraitItemKind::Type(ref type_param_bounds, _) => {
376 let rewrite = rewrite_associated_type(ti.ident,
378 Some(type_param_bounds),
381 self.push_rewrite(ti.span, rewrite);
383 ast::TraitItemKind::Macro(..) => {
384 // FIXME(#1158) Macros in trait item position
389 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
390 if self.visit_attrs(&ii.attrs) {
391 self.push_rewrite(ii.span, None);
396 ast::ImplItemKind::Method(ref sig, ref body) => {
397 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
403 ast::ImplItemKind::Const(ref ty, ref expr) => {
404 let rewrite = rewrite_static("const",
408 ast::Mutability::Immutable,
411 &self.get_context());
412 self.push_rewrite(ii.span, rewrite);
414 ast::ImplItemKind::Type(ref ty) => {
415 let rewrite = rewrite_associated_impl_type(ii.ident,
421 self.push_rewrite(ii.span, rewrite);
423 ast::ImplItemKind::Macro(ref mac) => {
424 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
429 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
431 let width = self.config.max_width - self.block_indent.width() - 1;
432 let rewrite = rewrite_macro(mac,
435 Shape::legacy(width, self.block_indent),
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 let result = rewrite.unwrap_or_else(|| self.snippet(span));
443 self.buffer.push_str(&result);
444 self.last_pos = source!(self, span).hi;
447 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
449 parse_session: parse_session,
450 codemap: parse_session.codemap(),
451 buffer: StringBuffer::new(),
452 last_pos: BytePos(0),
453 block_indent: Indent {
461 pub fn snippet(&self, span: Span) -> String {
462 match self.codemap.span_to_snippet(span) {
465 println!("Couldn't make snippet for span {:?}->{:?}",
466 self.codemap.lookup_char_pos(span.lo),
467 self.codemap.lookup_char_pos(span.hi));
473 // Returns true if we should skip the following item.
474 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
475 if utils::contains_skip(attrs) {
479 let outers: Vec<_> = attrs.iter()
480 .filter(|a| a.style == ast::AttrStyle::Outer)
483 if outers.is_empty() {
487 let first = &outers[0];
488 self.format_missing_with_indent(source!(self, first.span).lo);
490 let rewrite = outers.rewrite(&self.get_context(),
491 Shape::legacy(self.config.max_width -
492 self.block_indent.width(),
495 self.buffer.push_str(&rewrite);
496 let last = outers.last().unwrap();
497 self.last_pos = source!(self, last.span).hi;
501 fn walk_mod_items(&mut self, m: &ast::Mod) {
502 let mut items_left: &[ptr::P<ast::Item>] = &m.items;
503 while !items_left.is_empty() {
504 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
505 // to be potentially reordered within `format_imports`. Otherwise, just format the
506 // next item for output.
507 if self.config.reorder_imports && is_use_item(&*items_left[0]) {
508 let use_item_length =
509 items_left.iter().take_while(|ppi| is_use_item(&***ppi)).count();
510 let (use_items, rest) = items_left.split_at(use_item_length);
511 self.format_imports(use_items);
514 // `unwrap()` is safe here because we know `items_left`
515 // has elements from the loop condition
516 let (item, rest) = items_left.split_first().unwrap();
517 self.visit_item(item);
523 fn format_mod(&mut self, m: &ast::Mod, vis: &ast::Visibility, s: Span, ident: ast::Ident) {
524 // Decide whether this is an inline mod or an external mod.
525 let local_file_name = self.codemap.span_to_filename(s);
526 let inner_span = source!(self, m.inner);
527 let is_internal = !(inner_span.lo.0 == 0 && inner_span.hi.0 == 0) &&
528 local_file_name == self.codemap.span_to_filename(inner_span);
530 self.buffer.push_str(&*utils::format_visibility(vis));
531 self.buffer.push_str("mod ");
532 self.buffer.push_str(&ident.to_string());
535 self.buffer.push_str(" {");
536 // Hackery to account for the closing }.
537 let mod_lo = self.codemap.span_after(source!(self, s), "{");
539 self.snippet(codemap::mk_sp(mod_lo, source!(self, m.inner).hi - BytePos(1)));
540 let body_snippet = body_snippet.trim();
541 if body_snippet.is_empty() {
542 self.buffer.push_str("}");
544 self.last_pos = mod_lo;
545 self.block_indent = self.block_indent.block_indent(self.config);
546 self.walk_mod_items(m);
547 self.format_missing_with_indent(source!(self, m.inner).hi - BytePos(1));
550 self.last_pos = source!(self, m.inner).hi;
552 self.buffer.push_str(";");
553 self.last_pos = source!(self, s).hi;
557 pub fn format_separate_mod(&mut self, m: &ast::Mod) {
558 let filemap = self.codemap.lookup_char_pos(m.inner.lo).file;
559 self.last_pos = filemap.start_pos;
560 self.block_indent = Indent::empty();
561 self.walk_mod_items(m);
562 self.format_missing_with_indent(filemap.end_pos);
565 pub fn get_context(&self) -> RewriteContext {
567 parse_session: self.parse_session,
568 codemap: self.codemap,
574 impl<'a> Rewrite for [ast::Attribute] {
575 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
576 let mut result = String::new();
580 let indent = shape.indent.to_string(context.config);
582 for (i, a) in self.iter().enumerate() {
583 let mut a_str = context.snippet(a.span);
585 // Write comments and blank lines between attributes.
587 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
588 // This particular horror show is to preserve line breaks in between doc
589 // comments. An alternative would be to force such line breaks to start
590 // with the usual doc comment token.
591 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
592 let comment = comment.trim();
593 if !comment.is_empty() {
594 let comment = try_opt!(rewrite_comment(comment,
596 Shape::legacy(context.config
598 shape.indent.width(),
601 result.push_str(&indent);
602 result.push_str(&comment);
604 } else if multi_line {
607 result.push_str(&indent);
610 if a_str.starts_with("//") {
611 a_str = try_opt!(rewrite_comment(&a_str,
613 Shape::legacy(context.config.comment_width -
614 shape.indent.width(),
619 // Write the attribute itself.
620 result.push_str(&a_str);
622 if i < self.len() - 1 {