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 // For format_missing and last_pos, need to use the source callsite (if applicable).
26 // Required as generated code spans aren't guaranteed to follow on from the last span.
28 ($this:ident, $sp: expr) => {
29 $this.codemap.source_callsite($sp)
33 pub struct FmtVisitor<'a> {
34 pub parse_session: &'a ParseSess,
35 pub codemap: &'a CodeMap,
36 pub buffer: StringBuffer,
37 pub last_pos: BytePos,
38 // FIXME: use an RAII util or closure for indenting
39 pub block_indent: Indent,
40 pub config: &'a Config,
43 impl<'a> FmtVisitor<'a> {
44 fn visit_stmt(&mut self, stmt: &ast::Stmt) {
46 ast::StmtKind::Decl(ref decl, _) => {
47 if let ast::DeclKind::Item(ref item) = decl.node {
48 self.visit_item(item);
50 let rewrite = stmt.rewrite(&self.get_context(),
51 self.config.max_width - self.block_indent.width(),
54 self.push_rewrite(stmt.span, rewrite);
57 ast::StmtKind::Expr(..) |
58 ast::StmtKind::Semi(..) => {
59 let rewrite = stmt.rewrite(&self.get_context(),
60 self.config.max_width - self.block_indent.width(),
63 self.push_rewrite(stmt.span, rewrite);
65 ast::StmtKind::Mac(ref mac, _macro_style, _) => {
66 self.format_missing_with_indent(source!(self, stmt.span).lo);
67 self.visit_mac(mac, None);
72 pub fn visit_block(&mut self, b: &ast::Block) {
73 debug!("visit_block: {:?} {:?}",
74 self.codemap.lookup_char_pos(b.span.lo),
75 self.codemap.lookup_char_pos(b.span.hi));
77 // Check if this block has braces.
78 let snippet = self.snippet(b.span);
79 let has_braces = snippet.starts_with("{") || snippet.starts_with("unsafe");
80 let brace_compensation = if has_braces {
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 {
91 self.visit_stmt(&stmt)
94 if let Some(ref e) = b.expr {
95 self.format_missing_with_indent(source!(self, e.span).lo);
96 let rewrite = e.rewrite(&self.get_context(),
97 self.config.max_width - self.block_indent.width(),
99 .unwrap_or_else(|| self.snippet(e.span));
101 self.buffer.push_str(&rewrite);
102 self.last_pos = source!(self, e.span).hi;
104 if utils::semicolon_for_expr(e) {
105 self.buffer.push_str(";");
109 // FIXME: we should compress any newlines here to just one
110 self.format_missing_with_indent(source!(self, b.span).hi - brace_compensation);
112 self.last_pos = source!(self, b.span).hi;
115 // FIXME: this is a terrible hack to indent the comments between the last
116 // item in the block and the closing brace to the block's level.
117 // The closing brace itself, however, should be indented at a shallower
119 fn close_block(&mut self) {
120 let total_len = self.buffer.len;
121 let chars_too_many = if self.config.hard_tabs {
124 self.config.tab_spaces
126 self.buffer.truncate(total_len - chars_too_many);
127 self.buffer.push_str("}");
128 self.block_indent = self.block_indent.block_unindent(self.config);
131 // Note that this only gets called for function definitions. Required methods
132 // on traits do not get handled here.
133 fn visit_fn(&mut self,
139 let indent = self.block_indent;
140 let rewrite = match fk {
141 visit::FnKind::ItemFn(ident, ref generics, unsafety, constness, abi, vis) => {
142 self.rewrite_fn(indent,
150 codemap::mk_sp(s.lo, b.span.lo),
153 visit::FnKind::Method(ident, ref sig, vis) => {
154 self.rewrite_fn(indent,
161 vis.unwrap_or(&ast::Visibility::Inherited),
162 codemap::mk_sp(s.lo, b.span.lo),
165 visit::FnKind::Closure => None,
168 if let Some(fn_str) = rewrite {
169 self.format_missing_with_indent(source!(self, s).lo);
170 self.buffer.push_str(&fn_str);
171 if let Some(c) = fn_str.chars().last() {
173 self.last_pos = source!(self, b.span).hi;
178 self.format_missing(source!(self, b.span).lo);
181 self.last_pos = source!(self, b.span).lo;
185 fn visit_item(&mut self, item: &ast::Item) {
186 // This is where we bail out if there is a skip attribute. This is only
187 // complex in the module case. It is complex because the module could be
188 // in a seperate file and there might be attributes in both files, but
189 // the AST lumps them all together.
191 ast::ItemKind::Mod(ref m) => {
192 let outer_file = self.codemap.lookup_char_pos(item.span.lo).file;
193 let inner_file = self.codemap.lookup_char_pos(m.inner.lo).file;
194 if outer_file.name == inner_file.name {
195 // Module is inline, in this case we treat modules like any
197 if self.visit_attrs(&item.attrs) {
198 self.push_rewrite(item.span, None);
201 } else if utils::contains_skip(&item.attrs) {
202 // Module is not inline, but should be skipped.
205 // Module is not inline and should not be skipped. We want
206 // to process only the attributes in the current file.
207 let attrs = item.attrs
210 let attr_file = self.codemap.lookup_char_pos(a.span.lo).file;
211 if attr_file.name == outer_file.name {
217 .collect::<Vec<_>>();
218 // Assert because if we should skip it should be caught by
220 assert!(!self.visit_attrs(&attrs));
224 if self.visit_attrs(&item.attrs) {
225 self.push_rewrite(item.span, None);
232 ast::ItemKind::Use(ref vp) => {
233 self.format_import(&item.vis, vp, item.span);
235 ast::ItemKind::Impl(..) => {
236 self.format_missing_with_indent(source!(self, item.span).lo);
237 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
238 self.buffer.push_str(&impl_str);
239 self.last_pos = source!(self, item.span).hi;
242 ast::ItemKind::Trait(..) => {
243 self.format_missing_with_indent(item.span.lo);
244 if let Some(trait_str) = format_trait(&self.get_context(),
247 self.buffer.push_str(&trait_str);
248 self.last_pos = source!(self, item.span).hi;
251 ast::ItemKind::ExternCrate(_) => {
252 self.format_missing_with_indent(source!(self, item.span).lo);
253 let new_str = self.snippet(item.span);
254 self.buffer.push_str(&new_str);
255 self.last_pos = source!(self, item.span).hi;
257 ast::ItemKind::Struct(ref def, ref generics) => {
259 let indent = self.block_indent;
260 let context = self.get_context();
261 ::items::format_struct(&context,
272 ast::VariantData::Tuple(..) => s + ";",
277 self.push_rewrite(item.span, rewrite);
279 ast::ItemKind::Enum(ref def, ref generics) => {
280 self.format_missing_with_indent(source!(self, item.span).lo);
281 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
282 self.last_pos = source!(self, item.span).hi;
284 ast::ItemKind::Mod(ref module) => {
285 self.format_missing_with_indent(source!(self, item.span).lo);
286 self.format_mod(module, &item.vis, item.span, item.ident);
288 ast::ItemKind::Mac(ref mac) => {
289 self.format_missing_with_indent(source!(self, item.span).lo);
290 self.visit_mac(mac, Some(item.ident));
292 ast::ItemKind::ForeignMod(ref foreign_mod) => {
293 self.format_missing_with_indent(source!(self, item.span).lo);
294 self.format_foreign_mod(foreign_mod, item.span);
296 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
297 let rewrite = rewrite_static("static",
303 &self.get_context());
304 self.push_rewrite(item.span, rewrite);
306 ast::ItemKind::Const(ref ty, ref expr) => {
307 let rewrite = rewrite_static("const",
311 ast::Mutability::Immutable,
313 &self.get_context());
314 self.push_rewrite(item.span, rewrite);
316 ast::ItemKind::DefaultImpl(..) => {
317 // FIXME(#78): format impl definitions.
319 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
320 self.visit_fn(visit::FnKind::ItemFn(item.ident,
331 ast::ItemKind::Ty(ref ty, ref generics) => {
332 let rewrite = rewrite_type_alias(&self.get_context(),
339 self.push_rewrite(item.span, rewrite);
344 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
345 if self.visit_attrs(&ti.attrs) {
350 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
351 let rewrite = rewrite_static("const",
352 &ast::Visibility::Inherited,
355 ast::Mutability::Immutable,
357 &self.get_context());
358 self.push_rewrite(ti.span, rewrite);
360 ast::TraitItemKind::Method(ref sig, None) => {
361 let indent = self.block_indent;
362 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
363 self.push_rewrite(ti.span, rewrite);
365 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
366 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
372 ast::TraitItemKind::Type(ref type_param_bounds, _) => {
373 let rewrite = rewrite_associated_type(ti.ident,
375 Some(type_param_bounds),
378 self.push_rewrite(ti.span, rewrite);
383 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
384 if self.visit_attrs(&ii.attrs) {
389 ast::ImplItemKind::Method(ref sig, ref body) => {
390 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(&ii.vis)),
396 ast::ImplItemKind::Const(ref ty, ref expr) => {
397 let rewrite = rewrite_static("const",
401 ast::Mutability::Immutable,
403 &self.get_context());
404 self.push_rewrite(ii.span, rewrite);
406 ast::ImplItemKind::Type(ref ty) => {
407 let rewrite = rewrite_associated_type(ii.ident,
412 self.push_rewrite(ii.span, rewrite);
414 ast::ImplItemKind::Macro(ref mac) => {
415 self.format_missing_with_indent(source!(self, ii.span).lo);
416 self.visit_mac(mac, Some(ii.ident));
421 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>) {
423 let width = self.config.max_width - self.block_indent.width() - 1;
424 let rewrite = rewrite_macro(mac, ident, &self.get_context(), width, self.block_indent);
426 if let Some(res) = rewrite {
427 self.buffer.push_str(&res);
428 self.last_pos = source!(self, mac.span).hi;
432 fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
433 self.format_missing_with_indent(source!(self, span).lo);
434 let result = rewrite.unwrap_or_else(|| self.snippet(span));
435 self.buffer.push_str(&result);
436 self.last_pos = source!(self, span).hi;
439 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
441 parse_session: parse_session,
442 codemap: parse_session.codemap(),
443 buffer: StringBuffer::new(),
444 last_pos: BytePos(0),
445 block_indent: Indent {
453 pub fn snippet(&self, span: Span) -> String {
454 match self.codemap.span_to_snippet(span) {
457 println!("Couldn't make snippet for span {:?}->{:?}",
458 self.codemap.lookup_char_pos(span.lo),
459 self.codemap.lookup_char_pos(span.hi));
465 // Returns true if we should skip the following item.
466 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
467 if utils::contains_skip(attrs) {
471 let outers: Vec<_> = attrs.iter()
472 .filter(|a| a.node.style == ast::AttrStyle::Outer)
475 if outers.is_empty() {
479 let first = &outers[0];
480 self.format_missing_with_indent(source!(self, first.span).lo);
482 let rewrite = outers.rewrite(&self.get_context(),
483 self.config.max_width - self.block_indent.width(),
486 self.buffer.push_str(&rewrite);
487 let last = outers.last().unwrap();
488 self.last_pos = source!(self, last.span).hi;
492 fn walk_mod_items(&mut self, m: &ast::Mod) {
493 for item in &m.items {
494 self.visit_item(&item);
498 fn format_mod(&mut self, m: &ast::Mod, vis: &ast::Visibility, s: Span, ident: ast::Ident) {
499 // Decide whether this is an inline mod or an external mod.
500 let local_file_name = self.codemap.span_to_filename(s);
501 let is_internal = local_file_name == self.codemap.span_to_filename(source!(self, m.inner));
503 self.buffer.push_str(&*utils::format_visibility(vis));
504 self.buffer.push_str("mod ");
505 self.buffer.push_str(&ident.to_string());
508 self.buffer.push_str(" {");
509 // Hackery to account for the closing }.
510 let mod_lo = self.codemap.span_after(source!(self, s), "{");
512 self.snippet(codemap::mk_sp(mod_lo, source!(self, m.inner).hi - BytePos(1)));
513 let body_snippet = body_snippet.trim();
514 if body_snippet.is_empty() {
515 self.buffer.push_str("}");
517 self.last_pos = mod_lo;
518 self.block_indent = self.block_indent.block_indent(self.config);
519 self.walk_mod_items(m);
520 self.format_missing_with_indent(source!(self, m.inner).hi - BytePos(1));
523 self.last_pos = source!(self, m.inner).hi;
525 self.buffer.push_str(";");
526 self.last_pos = source!(self, s).hi;
530 pub fn format_separate_mod(&mut self, m: &ast::Mod) {
531 let filemap = self.codemap.lookup_char_pos(source!(self, m.inner).lo).file;
532 self.last_pos = filemap.start_pos;
533 self.block_indent = Indent::empty();
534 self.walk_mod_items(m);
535 self.format_missing(filemap.end_pos);
538 fn format_import(&mut self, vis: &ast::Visibility, vp: &ast::ViewPath, span: Span) {
539 let vis = utils::format_visibility(vis);
540 let mut offset = self.block_indent;
541 offset.alignment += vis.len() + "use ".len();
543 match vp.rewrite(&self.get_context(),
544 self.config.max_width - offset.width() - 1,
546 Some(ref s) if s.is_empty() => {
547 // Format up to last newline
548 let prev_span = codemap::mk_sp(self.last_pos, source!(self, span).lo);
549 let span_end = match self.snippet(prev_span).rfind('\n') {
550 Some(offset) => self.last_pos + BytePos(offset as u32),
551 None => source!(self, span).lo,
553 self.format_missing(span_end);
554 self.last_pos = source!(self, span).hi;
557 let s = format!("{}use {};", vis, s);
558 self.format_missing_with_indent(source!(self, span).lo);
559 self.buffer.push_str(&s);
560 self.last_pos = source!(self, span).hi;
563 self.format_missing_with_indent(source!(self, span).lo);
564 self.format_missing(source!(self, span).hi);
569 pub fn get_context(&self) -> RewriteContext {
571 parse_session: self.parse_session,
572 codemap: self.codemap,
574 block_indent: self.block_indent,
579 impl<'a> Rewrite for [ast::Attribute] {
580 fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
581 let mut result = String::new();
585 let indent = offset.to_string(context.config);
587 for (i, a) in self.iter().enumerate() {
588 let mut a_str = context.snippet(a.span);
590 // Write comments and blank lines between attributes.
592 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
593 // This particular horror show is to preserve line breaks in between doc
594 // comments. An alternative would be to force such line breaks to start
595 // with the usual doc comment token.
596 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
597 let comment = comment.trim();
598 if !comment.is_empty() {
599 let comment = try_opt!(rewrite_comment(comment,
601 context.config.ideal_width -
605 result.push_str(&indent);
606 result.push_str(&comment);
608 } else if multi_line {
611 result.push_str(&indent);
614 if a_str.starts_with("//") {
615 a_str = try_opt!(rewrite_comment(&a_str,
617 context.config.ideal_width - offset.width(),
622 // Write the attribute itself.
623 result.push_str(&a_str);
625 if i < self.len() - 1 {