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;
21 use rewrite::{Rewrite, RewriteContext};
22 use comment::rewrite_comment;
23 use macros::rewrite_macro;
24 use items::{rewrite_static, rewrite_associated_static, rewrite_associated_type, rewrite_type_alias, format_impl, format_trait};
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,
36 impl<'a> FmtVisitor<'a> {
37 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
39 ast::StmtKind::Decl(ref decl, _) => {
40 if let ast::DeclKind::Item(ref item) = decl.node {
41 self.visit_item(item);
43 let rewrite = stmt.rewrite(&self.get_context(),
44 self.config.max_width - self.block_indent.width(),
47 self.push_rewrite(stmt.span, rewrite);
50 ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
51 let rewrite = stmt.rewrite(&self.get_context(),
52 self.config.max_width - self.block_indent.width(),
55 self.push_rewrite(stmt.span, rewrite);
57 ast::StmtKind::Mac(ref mac, _macro_style, _) => {
58 self.format_missing_with_indent(stmt.span.lo);
64 pub fn visit_block(&mut self, b: &ast::Block) {
65 debug!("visit_block: {:?} {:?}",
66 self.codemap.lookup_char_pos(b.span.lo),
67 self.codemap.lookup_char_pos(b.span.hi));
69 // Check if this block has braces.
70 let snippet = self.snippet(b.span);
71 let has_braces = snippet.starts_with("{") || snippet.starts_with("unsafe");
72 let brace_compensation = if has_braces {
78 self.last_pos = self.last_pos + brace_compensation;
79 self.block_indent = self.block_indent.block_indent(self.config);
80 self.buffer.push_str("{");
82 for stmt in &b.stmts {
83 self.visit_stmt(&stmt)
86 if let Some(ref e) = b.expr {
87 self.format_missing_with_indent(e.span.lo);
88 let rewrite = e.rewrite(&self.get_context(),
89 self.config.max_width - self.block_indent.width(),
91 .unwrap_or_else(|| self.snippet(e.span));
93 self.buffer.push_str(&rewrite);
94 self.last_pos = e.span.hi;
96 if utils::semicolon_for_expr(e) {
97 self.buffer.push_str(";");
101 // FIXME: we should compress any newlines here to just one
102 self.format_missing_with_indent(b.span.hi - brace_compensation);
104 self.last_pos = b.span.hi;
107 // FIXME: this is a terrible hack to indent the comments between the last
108 // item in the block and the closing brace to the block's level.
109 // The closing brace itself, however, should be indented at a shallower
111 fn close_block(&mut self) {
112 let total_len = self.buffer.len;
113 let chars_too_many = if self.config.hard_tabs {
116 self.config.tab_spaces
118 self.buffer.truncate(total_len - chars_too_many);
119 self.buffer.push_str("}");
120 self.block_indent = self.block_indent.block_unindent(self.config);
123 // Note that this only gets called for function definitions. Required methods
124 // on traits do not get handled here.
125 fn visit_fn(&mut self,
131 let indent = self.block_indent;
132 let rewrite = match fk {
133 visit::FnKind::ItemFn(ident, ref generics, unsafety, constness, abi, vis) => {
134 self.rewrite_fn(indent,
143 codemap::mk_sp(s.lo, b.span.lo),
146 visit::FnKind::Method(ident, ref sig, vis) => {
147 self.rewrite_fn(indent,
150 Some(&sig.explicit_self),
155 vis.unwrap_or(ast::Visibility::Inherited),
156 codemap::mk_sp(s.lo, b.span.lo),
159 visit::FnKind::Closure => None,
162 if let Some(fn_str) = rewrite {
163 self.format_missing_with_indent(s.lo);
164 self.buffer.push_str(&fn_str);
165 if let Some(c) = fn_str.chars().last() {
167 self.last_pos = b.span.hi;
172 self.format_missing(b.span.lo);
175 self.last_pos = b.span.lo;
179 fn visit_item(&mut self, item: &ast::Item) {
180 // Don't look at attributes for modules (except for rustfmt_skip).
181 // We want to avoid looking at attributes in another file, which the AST
182 // doesn't distinguish.
183 // FIXME This is overly conservative and means we miss attributes on
186 ast::ItemKind::Mod(_) => {
187 if utils::contains_skip(&item.attrs) {
192 if self.visit_attrs(&item.attrs) {
193 self.push_rewrite(item.span, None);
200 ast::ItemKind::Use(ref vp) => {
201 self.format_import(item.vis, vp, item.span);
203 ast::ItemKind::Impl(..) => {
204 self.format_missing_with_indent(item.span.lo);
205 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
206 self.buffer.push_str(&impl_str);
207 self.last_pos = item.span.hi;
210 ast::ItemKind::Trait(..) => {
211 self.format_missing_with_indent(item.span.lo);
212 if let Some(trait_str) = format_trait(&self.get_context(),
215 self.buffer.push_str(&trait_str);
216 self.last_pos = item.span.hi;
219 ast::ItemKind::ExternCrate(_) => {
220 self.format_missing_with_indent(item.span.lo);
221 let new_str = self.snippet(item.span);
222 self.buffer.push_str(&new_str);
223 self.last_pos = item.span.hi;
225 ast::ItemKind::Struct(ref def, ref generics) => {
227 let indent = self.block_indent;
228 let context = self.get_context();
229 ::items::format_struct(&context,
239 ast::VariantData::Tuple(..) => s + ";",
244 self.push_rewrite(item.span, rewrite);
246 ast::ItemKind::Enum(ref def, ref generics) => {
247 self.format_missing_with_indent(item.span.lo);
248 self.visit_enum(item.ident, item.vis, def, generics, item.span);
249 self.last_pos = item.span.hi;
251 ast::ItemKind::Mod(ref module) => {
252 self.format_missing_with_indent(item.span.lo);
253 self.format_mod(module, item.vis, item.span, item.ident);
255 ast::ItemKind::Mac(ref mac) => {
256 self.format_missing_with_indent(item.span.lo);
259 ast::ItemKind::ForeignMod(ref foreign_mod) => {
260 self.format_missing_with_indent(item.span.lo);
261 self.format_foreign_mod(foreign_mod, item.span);
263 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
264 let rewrite = rewrite_static("static",
270 &self.get_context());
271 self.push_rewrite(item.span, rewrite);
273 ast::ItemKind::Const(ref ty, ref expr) => {
274 let rewrite = rewrite_static("const",
278 ast::Mutability::Immutable,
280 &self.get_context());
281 self.push_rewrite(item.span, rewrite);
283 ast::ItemKind::DefaultImpl(..) => {
284 // FIXME(#78): format impl definitions.
286 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
287 self.visit_fn(visit::FnKind::ItemFn(item.ident,
298 ast::ItemKind::Ty(ref ty, ref generics) => {
299 let rewrite = rewrite_type_alias(&self.get_context(),
306 self.push_rewrite(item.span, rewrite);
311 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
312 if self.visit_attrs(&ti.attrs) {
317 ast::TraitItemKind::Const(ref ty, ref expr) => {
318 let rewrite = rewrite_associated_static("const",
319 ast::Visibility::Inherited,
322 ast::Mutability::Immutable,
324 &self.get_context());
325 self.push_rewrite(ti.span, rewrite);
327 ast::TraitItemKind::Method(ref sig, None) => {
328 let indent = self.block_indent;
329 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
330 self.push_rewrite(ti.span, rewrite);
332 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
333 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
339 ast::TraitItemKind::Type(ref type_param_bounds, _) => {
340 let rewrite = rewrite_associated_type("type",
343 Some(type_param_bounds),
346 self.push_rewrite(ti.span, rewrite);
351 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
352 if self.visit_attrs(&ii.attrs) {
357 ast::ImplItemKind::Method(ref sig, ref body) => {
358 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(ii.vis)),
364 ast::ImplItemKind::Const(ref ty, ref expr) => {
365 let rewrite = rewrite_static("const",
366 ast::Visibility::Inherited,
369 ast::Mutability::Immutable,
371 &self.get_context());
372 self.push_rewrite(ii.span, rewrite);
374 ast::ImplItemKind::Type(ref ty) => {
375 let rewrite = rewrite_associated_type("type",
381 self.push_rewrite(ii.span, rewrite);
383 ast::ImplItemKind::Macro(ref mac) => {
384 self.format_missing_with_indent(ii.span.lo);
390 fn visit_mac(&mut self, mac: &ast::Mac) {
392 let width = self.config.max_width - self.block_indent.width() - 1;
393 let rewrite = rewrite_macro(mac, &self.get_context(), width, self.block_indent);
395 if let Some(res) = rewrite {
396 self.buffer.push_str(&res);
397 self.last_pos = mac.span.hi;
401 fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
402 self.format_missing_with_indent(span.lo);
403 let result = rewrite.unwrap_or_else(|| self.snippet(span));
404 self.buffer.push_str(&result);
405 self.last_pos = span.hi;
408 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
410 parse_session: parse_session,
411 codemap: parse_session.codemap(),
412 buffer: StringBuffer::new(),
413 last_pos: BytePos(0),
414 block_indent: Indent {
422 pub fn snippet(&self, span: Span) -> String {
423 match self.codemap.span_to_snippet(span) {
426 println!("Couldn't make snippet for span {:?}->{:?}",
427 self.codemap.lookup_char_pos(span.lo),
428 self.codemap.lookup_char_pos(span.hi));
434 // Returns true if we should skip the following item.
435 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
436 if utils::contains_skip(attrs) {
440 let outers: Vec<_> = attrs.iter()
441 .filter(|a| a.node.style == ast::AttrStyle::Outer)
444 if outers.is_empty() {
448 let first = &outers[0];
449 self.format_missing_with_indent(first.span.lo);
451 let rewrite = outers.rewrite(&self.get_context(),
452 self.config.max_width - self.block_indent.width(),
455 self.buffer.push_str(&rewrite);
456 let last = outers.last().unwrap();
457 self.last_pos = last.span.hi;
461 fn walk_mod_items(&mut self, m: &ast::Mod) {
462 for item in &m.items {
463 self.visit_item(&item);
467 fn format_mod(&mut self, m: &ast::Mod, vis: ast::Visibility, s: Span, ident: ast::Ident) {
468 // Decide whether this is an inline mod or an external mod.
469 let local_file_name = self.codemap.span_to_filename(s);
470 let is_internal = local_file_name == self.codemap.span_to_filename(m.inner);
472 self.buffer.push_str(utils::format_visibility(vis));
473 self.buffer.push_str("mod ");
474 self.buffer.push_str(&ident.to_string());
477 self.buffer.push_str(" {");
478 // Hackery to account for the closing }.
479 let mod_lo = ::utils::span_after(s, "{", self.codemap);
480 let body_snippet = self.snippet(codemap::mk_sp(mod_lo, m.inner.hi - BytePos(1)));
481 let body_snippet = body_snippet.trim();
482 if body_snippet.is_empty() {
483 self.buffer.push_str("}");
485 self.last_pos = mod_lo;
486 self.block_indent = self.block_indent.block_indent(self.config);
487 self.walk_mod_items(m);
488 self.format_missing_with_indent(m.inner.hi - BytePos(1));
491 self.last_pos = m.inner.hi;
493 self.buffer.push_str(";");
494 self.last_pos = s.hi;
498 pub fn format_separate_mod(&mut self, m: &ast::Mod) {
499 let filemap = self.codemap.lookup_char_pos(m.inner.lo).file;
500 self.last_pos = filemap.start_pos;
501 self.block_indent = Indent::empty();
502 self.walk_mod_items(m);
503 self.format_missing(filemap.end_pos);
506 fn format_import(&mut self, vis: ast::Visibility, vp: &ast::ViewPath, span: Span) {
507 let vis = utils::format_visibility(vis);
508 let mut offset = self.block_indent;
509 offset.alignment += vis.len() + "use ".len();
511 match vp.rewrite(&self.get_context(),
512 self.config.max_width - offset.width() - 1,
514 Some(ref s) if s.is_empty() => {
515 // Format up to last newline
516 let prev_span = codemap::mk_sp(self.last_pos, span.lo);
517 let span_end = match self.snippet(prev_span).rfind('\n') {
518 Some(offset) => self.last_pos + BytePos(offset as u32),
521 self.format_missing(span_end);
522 self.last_pos = span.hi;
525 let s = format!("{}use {};", vis, s);
526 self.format_missing_with_indent(span.lo);
527 self.buffer.push_str(&s);
528 self.last_pos = span.hi;
531 self.format_missing_with_indent(span.lo);
532 self.format_missing(span.hi);
537 pub fn get_context(&self) -> RewriteContext {
539 parse_session: self.parse_session,
540 codemap: self.codemap,
542 block_indent: self.block_indent,
547 impl<'a> Rewrite for [ast::Attribute] {
548 fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
549 let mut result = String::new();
553 let indent = offset.to_string(context.config);
555 for (i, a) in self.iter().enumerate() {
556 let a_str = context.snippet(a.span);
558 // Write comments and blank lines between attributes.
560 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
561 // This particular horror show is to preserve line breaks in between doc
562 // comments. An alternative would be to force such line breaks to start
563 // with the usual doc comment token.
564 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
565 let comment = comment.trim();
566 if !comment.is_empty() {
567 let comment = try_opt!(rewrite_comment(comment,
569 context.config.max_width -
573 result.push_str(&indent);
574 result.push_str(&comment);
576 } else if multi_line {
579 result.push_str(&indent);
582 // Write the attribute itself.
583 result.push_str(&a_str);
585 if i < self.len() - 1 {