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.
12 use syntax::codemap::{self, CodeMap, Span, BytePos};
13 use syntax::parse::ParseSess;
16 use strings::string_buffer::StringBuffer;
20 use config::{Config, WriteMode};
21 use rewrite::{Rewrite, RewriteContext};
22 use comment::rewrite_comment;
23 use macros::rewrite_macro;
24 use items::{rewrite_static, rewrite_type_alias, format_impl};
26 pub struct FmtVisitor<'a> {
27 pub parse_session: &'a ParseSess,
28 pub codemap: &'a CodeMap,
29 pub buffer: StringBuffer,
30 pub last_pos: BytePos,
31 // FIXME: use an RAII util or closure for indenting
32 pub block_indent: Indent,
33 pub config: &'a Config,
34 pub write_mode: Option<WriteMode>,
37 impl<'a> FmtVisitor<'a> {
38 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
40 ast::Stmt_::StmtDecl(ref decl, _) => {
41 if let ast::Decl_::DeclItem(ref item) = decl.node {
42 self.visit_item(item);
44 let rewrite = stmt.rewrite(&self.get_context(),
45 self.config.max_width - self.block_indent.width(),
48 self.push_rewrite(stmt.span, rewrite);
51 ast::Stmt_::StmtExpr(..) | ast::Stmt_::StmtSemi(..) => {
52 let rewrite = stmt.rewrite(&self.get_context(),
53 self.config.max_width - self.block_indent.width(),
56 self.push_rewrite(stmt.span, rewrite);
58 ast::Stmt_::StmtMac(ref mac, _macro_style, _) => {
59 self.format_missing_with_indent(stmt.span.lo);
65 pub fn visit_block(&mut self, b: &ast::Block) {
66 debug!("visit_block: {:?} {:?}",
67 self.codemap.lookup_char_pos(b.span.lo),
68 self.codemap.lookup_char_pos(b.span.hi));
70 // Check if this block has braces.
71 let snippet = self.snippet(b.span);
72 let has_braces = snippet.starts_with("{") || snippet.starts_with("unsafe");
73 let brace_compensation = if has_braces {
79 self.last_pos = self.last_pos + brace_compensation;
80 self.block_indent = self.block_indent.block_indent(self.config);
81 self.buffer.push_str("{");
83 for stmt in &b.stmts {
84 self.visit_stmt(&stmt)
87 if let Some(ref e) = b.expr {
88 self.format_missing_with_indent(e.span.lo);
89 let rewrite = e.rewrite(&self.get_context(),
90 self.config.max_width - self.block_indent.width(),
92 .unwrap_or_else(|| self.snippet(e.span));
94 self.buffer.push_str(&rewrite);
95 self.last_pos = e.span.hi;
97 if utils::semicolon_for_expr(e) {
98 self.buffer.push_str(";");
102 // FIXME: we should compress any newlines here to just one
103 self.format_missing_with_indent(b.span.hi - brace_compensation);
105 self.last_pos = 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,
132 let indent = self.block_indent;
133 let rewrite = match fk {
134 visit::FnKind::ItemFn(ident, ref generics, unsafety, constness, abi, vis) => {
135 self.rewrite_fn(indent,
144 codemap::mk_sp(s.lo, b.span.lo),
147 visit::FnKind::Method(ident, ref sig, vis) => {
148 self.rewrite_fn(indent,
151 Some(&sig.explicit_self),
156 vis.unwrap_or(ast::Visibility::Inherited),
157 codemap::mk_sp(s.lo, b.span.lo),
160 visit::FnKind::Closure => None,
163 if let Some(fn_str) = rewrite {
164 self.format_missing_with_indent(s.lo);
165 self.buffer.push_str(&fn_str);
166 if let Some(c) = fn_str.chars().last() {
168 self.last_pos = b.span.hi;
173 self.format_missing(b.span.lo);
176 self.last_pos = b.span.lo;
180 fn visit_item(&mut self, item: &ast::Item) {
181 // Don't look at attributes for modules (except for rustfmt_skip).
182 // We want to avoid looking at attributes in another file, which the AST
183 // doesn't distinguish.
184 // FIXME This is overly conservative and means we miss attributes on
187 ast::Item_::ItemMod(_) => {
188 if utils::contains_skip(&item.attrs) {
193 if self.visit_attrs(&item.attrs) {
194 self.push_rewrite(item.span, None);
201 ast::Item_::ItemUse(ref vp) => {
202 self.format_import(item.vis, vp, item.span);
204 ast::Item_::ItemImpl(..) => {
205 self.format_missing_with_indent(item.span.lo);
206 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
207 self.buffer.push_str(&impl_str);
208 self.last_pos = item.span.hi;
211 // FIXME(#78): format traits.
212 ast::Item_::ItemTrait(_, _, _, ref trait_items) => {
213 self.format_missing_with_indent(item.span.lo);
214 self.block_indent = self.block_indent.block_indent(self.config);
215 for item in trait_items {
216 self.visit_trait_item(&item);
218 self.block_indent = self.block_indent.block_unindent(self.config);
220 ast::Item_::ItemExternCrate(_) => {
221 self.format_missing_with_indent(item.span.lo);
222 let new_str = self.snippet(item.span);
223 self.buffer.push_str(&new_str);
224 self.last_pos = item.span.hi;
226 ast::Item_::ItemStruct(ref def, ref generics) => {
228 let indent = self.block_indent;
229 let context = self.get_context();
230 ::items::format_struct(&context,
240 ast::VariantData::Tuple(..) => s + ";",
245 self.push_rewrite(item.span, rewrite);
247 ast::Item_::ItemEnum(ref def, ref generics) => {
248 self.format_missing_with_indent(item.span.lo);
249 self.visit_enum(item.ident, item.vis, def, generics, item.span);
250 self.last_pos = item.span.hi;
252 ast::Item_::ItemMod(ref module) => {
253 self.format_missing_with_indent(item.span.lo);
254 self.format_mod(module, item.vis, item.span, item.ident);
256 ast::Item_::ItemMac(ref mac) => {
257 self.format_missing_with_indent(item.span.lo);
260 ast::Item_::ItemForeignMod(ref foreign_mod) => {
261 self.format_missing_with_indent(item.span.lo);
262 self.format_foreign_mod(foreign_mod, item.span);
264 ast::Item_::ItemStatic(ref ty, mutability, ref expr) => {
265 let rewrite = rewrite_static("static",
271 &self.get_context());
272 self.push_rewrite(item.span, rewrite);
274 ast::Item_::ItemConst(ref ty, ref expr) => {
275 let rewrite = rewrite_static("const",
279 ast::Mutability::MutImmutable,
281 &self.get_context());
282 self.push_rewrite(item.span, rewrite);
284 ast::Item_::ItemDefaultImpl(..) => {
285 // FIXME(#78): format impl definitions.
287 ast::ItemFn(ref declaration, unsafety, constness, abi, ref generics, ref body) => {
288 self.visit_fn(visit::FnKind::ItemFn(item.ident,
299 ast::Item_::ItemTy(ref ty, ref generics) => {
300 let rewrite = rewrite_type_alias(&self.get_context(),
307 self.push_rewrite(item.span, rewrite);
312 fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
313 if self.visit_attrs(&ti.attrs) {
318 ast::ConstTraitItem(..) => {
321 ast::MethodTraitItem(ref sig, None) => {
322 let indent = self.block_indent;
323 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
324 self.push_rewrite(ti.span, rewrite);
326 ast::MethodTraitItem(ref sig, Some(ref body)) => {
327 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
333 ast::TypeTraitItem(..) => {
339 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
340 if self.visit_attrs(&ii.attrs) {
345 ast::ImplItemKind::Method(ref sig, ref body) => {
346 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(ii.vis)),
352 ast::ImplItemKind::Const(..) => {
355 ast::ImplItemKind::Type(_) => {
358 ast::ImplItemKind::Macro(ref mac) => {
359 self.format_missing_with_indent(ii.span.lo);
365 fn visit_mac(&mut self, mac: &ast::Mac) {
367 let width = self.config.max_width - self.block_indent.width() - 1;
368 let rewrite = rewrite_macro(mac, &self.get_context(), width, self.block_indent);
370 if let Some(res) = rewrite {
371 self.buffer.push_str(&res);
372 self.last_pos = mac.span.hi;
376 fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
377 self.format_missing_with_indent(span.lo);
378 let result = rewrite.unwrap_or_else(|| self.snippet(span));
379 self.buffer.push_str(&result);
380 self.last_pos = span.hi;
383 pub fn from_codemap(parse_session: &'a ParseSess,
385 mode: Option<WriteMode>)
388 parse_session: parse_session,
389 codemap: parse_session.codemap(),
390 buffer: StringBuffer::new(),
391 last_pos: BytePos(0),
392 block_indent: Indent {
401 pub fn snippet(&self, span: Span) -> String {
402 match self.codemap.span_to_snippet(span) {
405 println!("Couldn't make snippet for span {:?}->{:?}",
406 self.codemap.lookup_char_pos(span.lo),
407 self.codemap.lookup_char_pos(span.hi));
413 // Returns true if we should skip the following item.
414 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
415 if utils::contains_skip(attrs) {
419 let outers: Vec<_> = attrs.iter()
420 .filter(|a| a.node.style == ast::AttrStyle::Outer)
423 if outers.is_empty() {
427 let first = &outers[0];
428 self.format_missing_with_indent(first.span.lo);
430 let rewrite = outers.rewrite(&self.get_context(),
431 self.config.max_width - self.block_indent.width(),
434 self.buffer.push_str(&rewrite);
435 let last = outers.last().unwrap();
436 self.last_pos = last.span.hi;
440 fn walk_mod_items(&mut self, m: &ast::Mod) {
441 for item in &m.items {
442 self.visit_item(&item);
446 fn format_mod(&mut self, m: &ast::Mod, vis: ast::Visibility, s: Span, ident: ast::Ident) {
447 // Decide whether this is an inline mod or an external mod.
448 let local_file_name = self.codemap.span_to_filename(s);
449 let is_internal = local_file_name == self.codemap.span_to_filename(m.inner);
451 self.buffer.push_str(utils::format_visibility(vis));
452 self.buffer.push_str("mod ");
453 self.buffer.push_str(&ident.to_string());
456 self.buffer.push_str(" {");
457 // Hackery to account for the closing }.
458 let mod_lo = ::utils::span_after(s, "{", self.codemap);
459 let body_snippet = self.snippet(codemap::mk_sp(mod_lo, m.inner.hi - BytePos(1)));
460 let body_snippet = body_snippet.trim();
461 if body_snippet.is_empty() {
462 self.buffer.push_str("}");
464 self.last_pos = mod_lo;
465 self.block_indent = self.block_indent.block_indent(self.config);
466 self.walk_mod_items(m);
467 self.format_missing_with_indent(m.inner.hi - BytePos(1));
470 self.last_pos = m.inner.hi;
472 self.buffer.push_str(";");
473 self.last_pos = s.hi;
477 pub fn format_separate_mod(&mut self, m: &ast::Mod) {
478 let filemap = self.codemap.lookup_char_pos(m.inner.lo).file;
479 self.last_pos = filemap.start_pos;
480 self.block_indent = Indent::empty();
481 self.walk_mod_items(m);
482 self.format_missing(filemap.end_pos);
485 fn format_import(&mut self, vis: ast::Visibility, vp: &ast::ViewPath, span: Span) {
486 let vis = utils::format_visibility(vis);
487 let mut offset = self.block_indent;
488 offset.alignment += vis.len() + "use ".len();
490 match vp.rewrite(&self.get_context(),
491 self.config.max_width - offset.width() - 1,
493 Some(ref s) if s.is_empty() => {
494 // Format up to last newline
495 let prev_span = codemap::mk_sp(self.last_pos, span.lo);
496 let span_end = match self.snippet(prev_span).rfind('\n') {
497 Some(offset) => self.last_pos + BytePos(offset as u32),
500 self.format_missing(span_end);
501 self.last_pos = span.hi;
504 let s = format!("{}use {};", vis, s);
505 self.format_missing_with_indent(span.lo);
506 self.buffer.push_str(&s);
507 self.last_pos = span.hi;
510 self.format_missing_with_indent(span.lo);
511 self.format_missing(span.hi);
516 pub fn get_context(&self) -> RewriteContext {
518 parse_session: self.parse_session,
519 codemap: self.codemap,
521 block_indent: self.block_indent,
526 impl<'a> Rewrite for [ast::Attribute] {
527 fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
528 let mut result = String::new();
532 let indent = offset.to_string(context.config);
534 for (i, a) in self.iter().enumerate() {
535 let a_str = context.snippet(a.span);
537 // Write comments and blank lines between attributes.
539 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
540 // This particular horror show is to preserve line breaks in between doc
541 // comments. An alternative would be to force such line breaks to start
542 // with the usual doc comment token.
543 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
544 let comment = comment.trim();
545 if !comment.is_empty() {
546 let comment = try_opt!(rewrite_comment(comment,
548 context.config.max_width -
552 result.push_str(&indent);
553 result.push_str(&comment);
555 } else if multi_line {
558 result.push_str(&indent);
561 // Write the attribute itself.
562 result.push_str(&a_str);
564 if i < self.len() - 1 {