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, visit};
12 use syntax::codemap::{self, CodeMap, Span, BytePos};
13 use syntax::parse::ParseSess;
15 use strings::string_buffer::StringBuffer;
18 use utils::{self, CodeMapSpanUtils};
20 use rewrite::{Rewrite, RewriteContext};
21 use comment::rewrite_comment;
22 use macros::rewrite_macro;
23 use items::{rewrite_static, rewrite_associated_type, rewrite_type_alias, format_impl, format_trait};
25 pub struct FmtVisitor<'a> {
26 pub parse_session: &'a ParseSess,
27 pub codemap: &'a CodeMap,
28 pub buffer: StringBuffer,
29 pub last_pos: BytePos,
30 // FIXME: use an RAII util or closure for indenting
31 pub block_indent: Indent,
32 pub config: &'a Config,
35 impl<'a> FmtVisitor<'a> {
36 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
38 ast::StmtKind::Decl(ref decl, _) => {
39 if let ast::DeclKind::Item(ref item) = decl.node {
40 self.visit_item(item);
42 let rewrite = stmt.rewrite(&self.get_context(),
43 self.config.max_width - self.block_indent.width(),
46 self.push_rewrite(stmt.span, rewrite);
49 ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
50 let rewrite = stmt.rewrite(&self.get_context(),
51 self.config.max_width - self.block_indent.width(),
54 self.push_rewrite(stmt.span, rewrite);
56 ast::StmtKind::Mac(ref mac, _macro_style, _) => {
57 self.format_missing_with_indent(stmt.span.lo);
58 self.visit_mac(mac, None);
63 pub fn visit_block(&mut self, b: &ast::Block) {
64 debug!("visit_block: {:?} {:?}",
65 self.codemap.lookup_char_pos(b.span.lo),
66 self.codemap.lookup_char_pos(b.span.hi));
68 // Check if this block has braces.
69 let snippet = self.snippet(b.span);
70 let has_braces = snippet.starts_with("{") || snippet.starts_with("unsafe");
71 let brace_compensation = if has_braces {
77 self.last_pos = self.last_pos + brace_compensation;
78 self.block_indent = self.block_indent.block_indent(self.config);
79 self.buffer.push_str("{");
81 for stmt in &b.stmts {
82 self.visit_stmt(&stmt)
85 if let Some(ref e) = b.expr {
86 self.format_missing_with_indent(e.span.lo);
87 let rewrite = e.rewrite(&self.get_context(),
88 self.config.max_width - self.block_indent.width(),
90 .unwrap_or_else(|| self.snippet(e.span));
92 self.buffer.push_str(&rewrite);
93 self.last_pos = e.span.hi;
95 if utils::semicolon_for_expr(e) {
96 self.buffer.push_str(";");
100 // FIXME: we should compress any newlines here to just one
101 self.format_missing_with_indent(b.span.hi - brace_compensation);
103 self.last_pos = b.span.hi;
106 // FIXME: this is a terrible hack to indent the comments between the last
107 // item in the block and the closing brace to the block's level.
108 // The closing brace itself, however, should be indented at a shallower
110 fn close_block(&mut self) {
111 let total_len = self.buffer.len;
112 let chars_too_many = if self.config.hard_tabs {
115 self.config.tab_spaces
117 self.buffer.truncate(total_len - chars_too_many);
118 self.buffer.push_str("}");
119 self.block_indent = self.block_indent.block_unindent(self.config);
122 // Note that this only gets called for function definitions. Required methods
123 // on traits do not get handled here.
124 fn visit_fn(&mut self,
130 let indent = self.block_indent;
131 let rewrite = match fk {
132 visit::FnKind::ItemFn(ident, ref generics, unsafety, constness, abi, vis) => {
133 self.rewrite_fn(indent,
142 codemap::mk_sp(s.lo, b.span.lo),
145 visit::FnKind::Method(ident, ref sig, vis) => {
146 self.rewrite_fn(indent,
149 Some(&sig.explicit_self),
154 vis.unwrap_or(ast::Visibility::Inherited),
155 codemap::mk_sp(s.lo, b.span.lo),
158 visit::FnKind::Closure => None,
161 if let Some(fn_str) = rewrite {
162 self.format_missing_with_indent(s.lo);
163 self.buffer.push_str(&fn_str);
164 if let Some(c) = fn_str.chars().last() {
166 self.last_pos = b.span.hi;
171 self.format_missing(b.span.lo);
174 self.last_pos = b.span.lo;
178 fn visit_item(&mut self, item: &ast::Item) {
179 // Don't look at attributes for modules (except for rustfmt_skip).
180 // We want to avoid looking at attributes in another file, which the AST
181 // doesn't distinguish.
182 // FIXME This is overly conservative and means we miss attributes on
185 ast::ItemKind::Mod(_) => {
186 if utils::contains_skip(&item.attrs) {
191 if self.visit_attrs(&item.attrs) {
192 self.push_rewrite(item.span, None);
199 ast::ItemKind::Use(ref vp) => {
200 self.format_import(item.vis, vp, item.span);
202 ast::ItemKind::Impl(..) => {
203 self.format_missing_with_indent(item.span.lo);
204 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
205 self.buffer.push_str(&impl_str);
206 self.last_pos = item.span.hi;
209 ast::ItemKind::Trait(..) => {
210 self.format_missing_with_indent(item.span.lo);
211 if let Some(trait_str) = format_trait(&self.get_context(),
214 self.buffer.push_str(&trait_str);
215 self.last_pos = item.span.hi;
218 ast::ItemKind::ExternCrate(_) => {
219 self.format_missing_with_indent(item.span.lo);
220 let new_str = self.snippet(item.span);
221 self.buffer.push_str(&new_str);
222 self.last_pos = item.span.hi;
224 ast::ItemKind::Struct(ref def, ref generics) => {
226 let indent = self.block_indent;
227 let context = self.get_context();
228 ::items::format_struct(&context,
238 ast::VariantData::Tuple(..) => s + ";",
243 self.push_rewrite(item.span, rewrite);
245 ast::ItemKind::Enum(ref def, ref generics) => {
246 self.format_missing_with_indent(item.span.lo);
247 self.visit_enum(item.ident, item.vis, def, generics, item.span);
248 self.last_pos = item.span.hi;
250 ast::ItemKind::Mod(ref module) => {
251 self.format_missing_with_indent(item.span.lo);
252 self.format_mod(module, item.vis, item.span, item.ident);
254 ast::ItemKind::Mac(ref mac) => {
255 self.format_missing_with_indent(item.span.lo);
256 self.visit_mac(mac, Some(item.ident));
258 ast::ItemKind::ForeignMod(ref foreign_mod) => {
259 self.format_missing_with_indent(item.span.lo);
260 self.format_foreign_mod(foreign_mod, item.span);
262 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
263 let rewrite = rewrite_static("static",
269 &self.get_context());
270 self.push_rewrite(item.span, rewrite);
272 ast::ItemKind::Const(ref ty, ref expr) => {
273 let rewrite = rewrite_static("const",
277 ast::Mutability::Immutable,
279 &self.get_context());
280 self.push_rewrite(item.span, rewrite);
282 ast::ItemKind::DefaultImpl(..) => {
283 // FIXME(#78): format impl definitions.
285 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
286 self.visit_fn(visit::FnKind::ItemFn(item.ident,
297 ast::ItemKind::Ty(ref ty, ref generics) => {
298 let rewrite = rewrite_type_alias(&self.get_context(),
305 self.push_rewrite(item.span, rewrite);
310 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
311 if self.visit_attrs(&ti.attrs) {
316 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
317 let rewrite = rewrite_static("const",
318 ast::Visibility::Inherited,
321 ast::Mutability::Immutable,
323 &self.get_context());
324 self.push_rewrite(ti.span, rewrite);
326 ast::TraitItemKind::Method(ref sig, None) => {
327 let indent = self.block_indent;
328 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
329 self.push_rewrite(ti.span, rewrite);
331 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
332 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
338 ast::TraitItemKind::Type(ref type_param_bounds, _) => {
339 let rewrite = rewrite_associated_type(ti.ident,
341 Some(type_param_bounds),
344 self.push_rewrite(ti.span, rewrite);
349 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
350 if self.visit_attrs(&ii.attrs) {
355 ast::ImplItemKind::Method(ref sig, ref body) => {
356 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(ii.vis)),
362 ast::ImplItemKind::Const(ref ty, ref expr) => {
363 let rewrite = rewrite_static("const",
364 ast::Visibility::Inherited,
367 ast::Mutability::Immutable,
369 &self.get_context());
370 self.push_rewrite(ii.span, rewrite);
372 ast::ImplItemKind::Type(ref ty) => {
373 let rewrite = rewrite_associated_type(ii.ident,
378 self.push_rewrite(ii.span, rewrite);
380 ast::ImplItemKind::Macro(ref mac) => {
381 self.format_missing_with_indent(ii.span.lo);
382 self.visit_mac(mac, Some(ii.ident));
387 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>) {
389 let width = self.config.max_width - self.block_indent.width() - 1;
390 let rewrite = rewrite_macro(mac, ident, &self.get_context(), width, self.block_indent);
392 if let Some(res) = rewrite {
393 self.buffer.push_str(&res);
394 self.last_pos = mac.span.hi;
398 fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
399 self.format_missing_with_indent(span.lo);
400 let result = rewrite.unwrap_or_else(|| self.snippet(span));
401 self.buffer.push_str(&result);
402 self.last_pos = span.hi;
405 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
407 parse_session: parse_session,
408 codemap: parse_session.codemap(),
409 buffer: StringBuffer::new(),
410 last_pos: BytePos(0),
411 block_indent: Indent {
419 pub fn snippet(&self, span: Span) -> String {
420 match self.codemap.span_to_snippet(span) {
423 println!("Couldn't make snippet for span {:?}->{:?}",
424 self.codemap.lookup_char_pos(span.lo),
425 self.codemap.lookup_char_pos(span.hi));
431 // Returns true if we should skip the following item.
432 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
433 if utils::contains_skip(attrs) {
437 let outers: Vec<_> = attrs.iter()
438 .filter(|a| a.node.style == ast::AttrStyle::Outer)
441 if outers.is_empty() {
445 let first = &outers[0];
446 self.format_missing_with_indent(first.span.lo);
448 let rewrite = outers.rewrite(&self.get_context(),
449 self.config.max_width - self.block_indent.width(),
452 self.buffer.push_str(&rewrite);
453 let last = outers.last().unwrap();
454 self.last_pos = last.span.hi;
458 fn walk_mod_items(&mut self, m: &ast::Mod) {
459 for item in &m.items {
460 self.visit_item(&item);
464 fn format_mod(&mut self, m: &ast::Mod, vis: ast::Visibility, s: Span, ident: ast::Ident) {
465 // Decide whether this is an inline mod or an external mod.
466 let local_file_name = self.codemap.span_to_filename(s);
467 let is_internal = local_file_name == self.codemap.span_to_filename(m.inner);
469 self.buffer.push_str(utils::format_visibility(vis));
470 self.buffer.push_str("mod ");
471 self.buffer.push_str(&ident.to_string());
474 self.buffer.push_str(" {");
475 // Hackery to account for the closing }.
476 let mod_lo = self.codemap.span_after(s, "{");
477 let body_snippet = self.snippet(codemap::mk_sp(mod_lo, m.inner.hi - BytePos(1)));
478 let body_snippet = body_snippet.trim();
479 if body_snippet.is_empty() {
480 self.buffer.push_str("}");
482 self.last_pos = mod_lo;
483 self.block_indent = self.block_indent.block_indent(self.config);
484 self.walk_mod_items(m);
485 self.format_missing_with_indent(m.inner.hi - BytePos(1));
488 self.last_pos = m.inner.hi;
490 self.buffer.push_str(";");
491 self.last_pos = s.hi;
495 pub fn format_separate_mod(&mut self, m: &ast::Mod) {
496 let filemap = self.codemap.lookup_char_pos(m.inner.lo).file;
497 self.last_pos = filemap.start_pos;
498 self.block_indent = Indent::empty();
499 self.walk_mod_items(m);
500 self.format_missing(filemap.end_pos);
503 fn format_import(&mut self, vis: ast::Visibility, vp: &ast::ViewPath, span: Span) {
504 let vis = utils::format_visibility(vis);
505 let mut offset = self.block_indent;
506 offset.alignment += vis.len() + "use ".len();
508 match vp.rewrite(&self.get_context(),
509 self.config.max_width - offset.width() - 1,
511 Some(ref s) if s.is_empty() => {
512 // Format up to last newline
513 let prev_span = codemap::mk_sp(self.last_pos, span.lo);
514 let span_end = match self.snippet(prev_span).rfind('\n') {
515 Some(offset) => self.last_pos + BytePos(offset as u32),
518 self.format_missing(span_end);
519 self.last_pos = span.hi;
522 let s = format!("{}use {};", vis, s);
523 self.format_missing_with_indent(span.lo);
524 self.buffer.push_str(&s);
525 self.last_pos = span.hi;
528 self.format_missing_with_indent(span.lo);
529 self.format_missing(span.hi);
534 pub fn get_context(&self) -> RewriteContext {
536 parse_session: self.parse_session,
537 codemap: self.codemap,
539 block_indent: self.block_indent,
544 impl<'a> Rewrite for [ast::Attribute] {
545 fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
546 let mut result = String::new();
550 let indent = offset.to_string(context.config);
552 for (i, a) in self.iter().enumerate() {
553 let a_str = context.snippet(a.span);
555 // Write comments and blank lines between attributes.
557 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
558 // This particular horror show is to preserve line breaks in between doc
559 // comments. An alternative would be to force such line breaks to start
560 // with the usual doc comment token.
561 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
562 let comment = comment.trim();
563 if !comment.is_empty() {
564 let comment = try_opt!(rewrite_comment(comment,
566 context.config.max_width -
570 result.push_str(&indent);
571 result.push_str(&comment);
573 } else if multi_line {
576 result.push_str(&indent);
579 // Write the attribute itself.
580 result.push_str(&a_str);
582 if i < self.len() - 1 {