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;
18 use {Indent, WriteMode};
21 use rewrite::{Rewrite, RewriteContext};
22 use comment::rewrite_comment;
23 use macros::rewrite_macro;
24 use items::rewrite_static;
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 // TODO: RAII util 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[..1] == "{" || &snippet[..6] == "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 // TODO: we should compress any newlines here to just one
103 self.format_missing_with_indent(b.span.hi - brace_compensation);
104 // FIXME: this is a terrible hack to indent the comments between the last
105 // item in the block and the closing brace to the block's level.
106 // The closing brace itself, however, should be indented at a shallower
108 let total_len = self.buffer.len;
109 let chars_too_many = if self.config.hard_tabs {
112 self.config.tab_spaces
114 self.buffer.truncate(total_len - chars_too_many);
115 self.buffer.push_str("}");
116 self.last_pos = b.span.hi;
117 self.block_indent = self.block_indent.block_unindent(self.config);
120 // Note that this only gets called for function definitions. Required methods
121 // on traits do not get handled here.
122 fn visit_fn(&mut self,
128 let indent = self.block_indent;
129 let rewrite = match fk {
130 visit::FnKind::ItemFn(ident, ref generics, unsafety, constness, abi, vis) => {
131 self.rewrite_fn(indent,
140 codemap::mk_sp(s.lo, b.span.lo))
142 visit::FnKind::Method(ident, ref sig, vis) => {
143 self.rewrite_fn(indent,
146 Some(&sig.explicit_self),
151 vis.unwrap_or(ast::Visibility::Inherited),
152 codemap::mk_sp(s.lo, b.span.lo))
154 visit::FnKind::Closure => None,
157 if let Some(ref single_line_fn) = self.rewrite_single_line_fn(&rewrite, &b) {
158 self.format_missing_with_indent(s.lo);
159 self.buffer.push_str(single_line_fn);
160 self.last_pos = b.span.hi;
164 if let Some(fn_str) = rewrite {
165 self.format_missing_with_indent(s.lo);
166 self.buffer.push_str(&fn_str);
168 self.format_missing(b.span.lo);
171 self.last_pos = b.span.lo;
175 fn visit_item(&mut self, item: &ast::Item) {
176 // Don't look at attributes for modules.
177 // We want to avoid looking at attributes in another file, which the AST
178 // doesn't distinguish. FIXME This is overly conservative and means we miss
179 // attributes on inline modules.
181 ast::Item_::ItemMod(_) => {}
183 if self.visit_attrs(&item.attrs) {
190 ast::Item_::ItemUse(ref vp) => {
191 self.format_import(item.vis, vp, item.span);
193 // FIXME(#78): format impl definitions.
194 ast::Item_::ItemImpl(_, _, _, _, _, ref impl_items) => {
195 self.format_missing_with_indent(item.span.lo);
196 self.block_indent = self.block_indent.block_indent(self.config);
197 for item in impl_items {
198 self.visit_impl_item(&item);
200 self.block_indent = self.block_indent.block_unindent(self.config);
202 // FIXME(#78): format traits.
203 ast::Item_::ItemTrait(_, _, _, ref trait_items) => {
204 self.format_missing_with_indent(item.span.lo);
205 self.block_indent = self.block_indent.block_indent(self.config);
206 for item in trait_items {
207 self.visit_trait_item(&item);
209 self.block_indent = self.block_indent.block_unindent(self.config);
211 ast::Item_::ItemExternCrate(_) => {
212 self.format_missing_with_indent(item.span.lo);
213 let new_str = self.snippet(item.span);
214 self.buffer.push_str(&new_str);
215 self.last_pos = item.span.hi;
217 ast::Item_::ItemStruct(ref def, ref generics) => {
218 let indent = self.block_indent;
219 let rewrite = self.format_struct("struct ",
228 ast::VariantData::Tuple(..) => s + ";",
232 self.push_rewrite(item.span, rewrite);
234 ast::Item_::ItemEnum(ref def, ref generics) => {
235 self.format_missing_with_indent(item.span.lo);
236 self.visit_enum(item.ident, item.vis, def, generics, item.span);
237 self.last_pos = item.span.hi;
239 ast::Item_::ItemMod(ref module) => {
240 self.format_missing_with_indent(item.span.lo);
241 self.format_mod(module, item.span, item.ident);
243 ast::Item_::ItemMac(..) => {
244 self.format_missing_with_indent(item.span.lo);
245 let snippet = self.snippet(item.span);
246 self.buffer.push_str(&snippet);
247 self.last_pos = item.span.hi;
248 // FIXME: we cannot format these yet, because of a bad span.
249 // See rust lang issue #28424.
251 ast::Item_::ItemForeignMod(ref foreign_mod) => {
252 self.format_missing_with_indent(item.span.lo);
253 self.format_foreign_mod(foreign_mod, item.span);
255 ast::Item_::ItemStatic(ref ty, mutability, ref expr) => {
256 let rewrite = rewrite_static("static",
262 &self.get_context());
263 self.push_rewrite(item.span, rewrite);
265 ast::Item_::ItemConst(ref ty, ref expr) => {
266 let rewrite = rewrite_static("const",
270 ast::Mutability::MutImmutable,
272 &self.get_context());
273 self.push_rewrite(item.span, rewrite);
275 ast::Item_::ItemDefaultImpl(..) => {
276 // FIXME(#78): format impl definitions.
278 ast::ItemFn(ref declaration, unsafety, constness, abi, ref generics, ref body) => {
279 self.visit_fn(visit::FnKind::ItemFn(item.ident,
290 ast::Item_::ItemTy(..) => {
291 // FIXME(#486): format type aliases.
296 fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
297 if self.visit_attrs(&ti.attrs) {
302 ast::ConstTraitItem(..) => {
305 ast::MethodTraitItem(ref sig, None) => {
306 let indent = self.block_indent;
307 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
308 self.push_rewrite(ti.span, rewrite);
310 ast::MethodTraitItem(ref sig, Some(ref body)) => {
311 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
317 ast::TypeTraitItem(..) => {
323 fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
324 if self.visit_attrs(&ii.attrs) {
329 ast::MethodImplItem(ref sig, ref body) => {
330 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(ii.vis)),
336 ast::ConstImplItem(..) => {
339 ast::TypeImplItem(_) => {
342 ast::MacImplItem(ref mac) => {
348 fn visit_mac(&mut self, mac: &ast::Mac) {
350 let width = self.config.max_width - self.block_indent.width() - 1;
351 let rewrite = rewrite_macro(mac, &self.get_context(), width, self.block_indent);
353 if let Some(res) = rewrite {
354 self.buffer.push_str(&res);
355 self.last_pos = mac.span.hi;
359 fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
360 self.format_missing_with_indent(span.lo);
362 if let Some(res) = rewrite {
363 self.buffer.push_str(&res);
364 self.last_pos = span.hi;
368 pub fn from_codemap(parse_session: &'a ParseSess,
370 mode: Option<WriteMode>)
373 parse_session: parse_session,
374 codemap: parse_session.codemap(),
375 buffer: StringBuffer::new(),
376 last_pos: BytePos(0),
377 block_indent: Indent {
386 pub fn snippet(&self, span: Span) -> String {
387 match self.codemap.span_to_snippet(span) {
390 println!("Couldn't make snippet for span {:?}->{:?}",
391 self.codemap.lookup_char_pos(span.lo),
392 self.codemap.lookup_char_pos(span.hi));
398 // Returns true if we should skip the following item.
399 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
400 if attrs.is_empty() {
404 if utils::contains_skip(attrs) {
408 let outers: Vec<_> = attrs.iter()
409 .filter(|a| a.node.style == ast::AttrStyle::Outer)
412 if outers.is_empty() {
416 let first = &outers[0];
417 self.format_missing_with_indent(first.span.lo);
419 let rewrite = outers.rewrite(&self.get_context(),
420 self.config.max_width - self.block_indent.width(),
423 self.buffer.push_str(&rewrite);
424 let last = outers.last().unwrap();
425 self.last_pos = last.span.hi;
429 fn walk_mod_items(&mut self, m: &ast::Mod) {
430 for item in &m.items {
431 self.visit_item(&item);
435 fn format_mod(&mut self, m: &ast::Mod, s: Span, ident: ast::Ident) {
436 debug!("FmtVisitor::format_mod: ident: {:?}, span: {:?}", ident, s);
438 // Decide whether this is an inline mod or an external mod.
439 let local_file_name = self.codemap.span_to_filename(s);
440 let is_internal = local_file_name == self.codemap.span_to_filename(m.inner);
442 // TODO: Should rewrite properly `mod X;`
445 self.block_indent = self.block_indent.block_indent(self.config);
446 self.walk_mod_items(m);
447 self.block_indent = self.block_indent.block_unindent(self.config);
449 self.format_missing_with_indent(m.inner.hi - BytePos(1));
450 self.buffer.push_str("}");
451 self.last_pos = m.inner.hi;
455 pub fn format_separate_mod(&mut self, m: &ast::Mod, filename: &str) {
456 let filemap = self.codemap.get_filemap(filename);
457 self.last_pos = filemap.start_pos;
458 self.block_indent = Indent::empty();
459 self.walk_mod_items(m);
460 self.format_missing(filemap.end_pos);
463 fn format_import(&mut self, vis: ast::Visibility, vp: &ast::ViewPath, span: Span) {
464 let vis = utils::format_visibility(vis);
465 let mut offset = self.block_indent;
466 offset.alignment += vis.len() + "use ".len();
468 match vp.rewrite(&self.get_context(),
469 self.config.max_width - offset.width() - 1,
471 Some(ref s) if s.is_empty() => {
472 // Format up to last newline
473 let prev_span = codemap::mk_sp(self.last_pos, span.lo);
474 let span_end = match self.snippet(prev_span).rfind('\n') {
475 Some(offset) => self.last_pos + BytePos(offset as u32),
478 self.format_missing(span_end);
479 self.last_pos = span.hi;
482 let s = format!("{}use {};", vis, s);
483 self.format_missing_with_indent(span.lo);
484 self.buffer.push_str(&s);
485 self.last_pos = span.hi;
488 self.format_missing_with_indent(span.lo);
489 self.format_missing(span.hi);
494 pub fn get_context(&self) -> RewriteContext {
496 parse_session: self.parse_session,
497 codemap: self.codemap,
499 block_indent: self.block_indent,
504 impl<'a> Rewrite for [ast::Attribute] {
505 fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
506 let mut result = String::new();
510 let indent = offset.to_string(context.config);
512 for (i, a) in self.iter().enumerate() {
513 let a_str = context.snippet(a.span);
516 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
517 // This particular horror show is to preserve line breaks in between doc
518 // comments. An alternative would be to force such line breaks to start
519 // with the usual doc comment token.
520 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
521 let comment = comment.trim();
522 if !comment.is_empty() {
523 let comment = try_opt!(rewrite_comment(comment,
525 context.config.max_width -
529 result.push_str(&indent);
530 result.push_str(&comment);
532 } else if multi_line {
535 result.push_str(&indent);
538 result.push_str(&a_str);
540 if i < self.len() - 1 {