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,
151 codemap::mk_sp(s.lo, b.span.lo),
154 visit::FnKind::Method(ident, ref sig, vis) => {
155 self.rewrite_fn(indent,
158 Some(&sig.explicit_self),
163 vis.unwrap_or(&ast::Visibility::Inherited),
164 codemap::mk_sp(s.lo, b.span.lo),
167 visit::FnKind::Closure => None,
170 if let Some(fn_str) = rewrite {
171 self.format_missing_with_indent(source!(self, s).lo);
172 self.buffer.push_str(&fn_str);
173 if let Some(c) = fn_str.chars().last() {
175 self.last_pos = source!(self, b.span).hi;
180 self.format_missing(source!(self, b.span).lo);
183 self.last_pos = source!(self, b.span).lo;
187 fn visit_item(&mut self, item: &ast::Item) {
188 // This is where we bail out if there is a skip attribute. This is only
189 // complex in the module case. It is complex because the module could be
190 // in a seperate file and there might be attributes in both files, but
191 // the AST lumps them all together.
193 ast::ItemKind::Mod(ref m) => {
194 let outer_file = self.codemap.lookup_char_pos(item.span.lo).file;
195 let inner_file = self.codemap.lookup_char_pos(m.inner.lo).file;
196 if outer_file.name == inner_file.name {
197 // Module is inline, in this case we treat modules like any
199 if self.visit_attrs(&item.attrs) {
200 self.push_rewrite(item.span, None);
203 } else if utils::contains_skip(&item.attrs) {
204 // Module is not inline, but should be skipped.
207 // Module is not inline and should not be skipped. We want
208 // to process only the attributes in the current file.
209 let attrs = item.attrs
212 let attr_file = self.codemap.lookup_char_pos(a.span.lo).file;
213 if attr_file.name == outer_file.name {
219 .collect::<Vec<_>>();
220 // Assert because if we should skip it should be caught by
222 assert!(!self.visit_attrs(&attrs));
226 if self.visit_attrs(&item.attrs) {
227 self.push_rewrite(item.span, None);
234 ast::ItemKind::Use(ref vp) => {
235 self.format_import(&item.vis, vp, item.span);
237 ast::ItemKind::Impl(..) => {
238 self.format_missing_with_indent(source!(self, item.span).lo);
239 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
240 self.buffer.push_str(&impl_str);
241 self.last_pos = source!(self, item.span).hi;
244 ast::ItemKind::Trait(..) => {
245 self.format_missing_with_indent(item.span.lo);
246 if let Some(trait_str) = format_trait(&self.get_context(),
249 self.buffer.push_str(&trait_str);
250 self.last_pos = source!(self, item.span).hi;
253 ast::ItemKind::ExternCrate(_) => {
254 self.format_missing_with_indent(source!(self, item.span).lo);
255 let new_str = self.snippet(item.span);
256 self.buffer.push_str(&new_str);
257 self.last_pos = source!(self, item.span).hi;
259 ast::ItemKind::Struct(ref def, ref generics) => {
261 let indent = self.block_indent;
262 let context = self.get_context();
263 ::items::format_struct(&context,
273 ast::VariantData::Tuple(..) => s + ";",
278 self.push_rewrite(item.span, rewrite);
280 ast::ItemKind::Enum(ref def, ref generics) => {
281 self.format_missing_with_indent(source!(self, item.span).lo);
282 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
283 self.last_pos = source!(self, item.span).hi;
285 ast::ItemKind::Mod(ref module) => {
286 self.format_missing_with_indent(source!(self, item.span).lo);
287 self.format_mod(module, &item.vis, item.span, item.ident);
289 ast::ItemKind::Mac(ref mac) => {
290 self.format_missing_with_indent(source!(self, item.span).lo);
291 self.visit_mac(mac, Some(item.ident));
293 ast::ItemKind::ForeignMod(ref foreign_mod) => {
294 self.format_missing_with_indent(source!(self, item.span).lo);
295 self.format_foreign_mod(foreign_mod, item.span);
297 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
298 let rewrite = rewrite_static("static",
304 &self.get_context());
305 self.push_rewrite(item.span, rewrite);
307 ast::ItemKind::Const(ref ty, ref expr) => {
308 let rewrite = rewrite_static("const",
312 ast::Mutability::Immutable,
314 &self.get_context());
315 self.push_rewrite(item.span, rewrite);
317 ast::ItemKind::DefaultImpl(..) => {
318 // FIXME(#78): format impl definitions.
320 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
321 self.visit_fn(visit::FnKind::ItemFn(item.ident,
332 ast::ItemKind::Ty(ref ty, ref generics) => {
333 let rewrite = rewrite_type_alias(&self.get_context(),
340 self.push_rewrite(item.span, rewrite);
345 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
346 if self.visit_attrs(&ti.attrs) {
351 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
352 let rewrite = rewrite_static("const",
353 &ast::Visibility::Inherited,
356 ast::Mutability::Immutable,
358 &self.get_context());
359 self.push_rewrite(ti.span, rewrite);
361 ast::TraitItemKind::Method(ref sig, None) => {
362 let indent = self.block_indent;
363 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
364 self.push_rewrite(ti.span, rewrite);
366 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
367 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
373 ast::TraitItemKind::Type(ref type_param_bounds, _) => {
374 let rewrite = rewrite_associated_type(ti.ident,
376 Some(type_param_bounds),
379 self.push_rewrite(ti.span, rewrite);
384 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
385 if self.visit_attrs(&ii.attrs) {
390 ast::ImplItemKind::Method(ref sig, ref body) => {
391 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(&ii.vis)),
397 ast::ImplItemKind::Const(ref ty, ref expr) => {
398 let rewrite = rewrite_static("const",
402 ast::Mutability::Immutable,
404 &self.get_context());
405 self.push_rewrite(ii.span, rewrite);
407 ast::ImplItemKind::Type(ref ty) => {
408 let rewrite = rewrite_associated_type(ii.ident,
413 self.push_rewrite(ii.span, rewrite);
415 ast::ImplItemKind::Macro(ref mac) => {
416 self.format_missing_with_indent(source!(self, ii.span).lo);
417 self.visit_mac(mac, Some(ii.ident));
422 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>) {
424 let width = self.config.max_width - self.block_indent.width() - 1;
425 let rewrite = rewrite_macro(mac, ident, &self.get_context(), width, self.block_indent);
427 if let Some(res) = rewrite {
428 self.buffer.push_str(&res);
429 self.last_pos = source!(self, mac.span).hi;
433 fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
434 self.format_missing_with_indent(source!(self, span).lo);
435 let result = rewrite.unwrap_or_else(|| self.snippet(span));
436 self.buffer.push_str(&result);
437 self.last_pos = source!(self, span).hi;
440 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
442 parse_session: parse_session,
443 codemap: parse_session.codemap(),
444 buffer: StringBuffer::new(),
445 last_pos: BytePos(0),
446 block_indent: Indent {
454 pub fn snippet(&self, span: Span) -> String {
455 match self.codemap.span_to_snippet(span) {
458 println!("Couldn't make snippet for span {:?}->{:?}",
459 self.codemap.lookup_char_pos(span.lo),
460 self.codemap.lookup_char_pos(span.hi));
466 // Returns true if we should skip the following item.
467 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
468 if utils::contains_skip(attrs) {
472 let outers: Vec<_> = attrs.iter()
473 .filter(|a| a.node.style == ast::AttrStyle::Outer)
476 if outers.is_empty() {
480 let first = &outers[0];
481 self.format_missing_with_indent(source!(self, first.span).lo);
483 let rewrite = outers.rewrite(&self.get_context(),
484 self.config.max_width - self.block_indent.width(),
487 self.buffer.push_str(&rewrite);
488 let last = outers.last().unwrap();
489 self.last_pos = source!(self, last.span).hi;
493 fn walk_mod_items(&mut self, m: &ast::Mod) {
494 for item in &m.items {
495 self.visit_item(&item);
499 fn format_mod(&mut self, m: &ast::Mod, vis: &ast::Visibility, s: Span, ident: ast::Ident) {
500 // Decide whether this is an inline mod or an external mod.
501 let local_file_name = self.codemap.span_to_filename(s);
502 let is_internal = local_file_name == self.codemap.span_to_filename(source!(self, m.inner));
504 if let Some(vis) = utils::format_visibility(vis) {
505 self.buffer.push_str(vis);
507 self.buffer.push_str("mod ");
508 self.buffer.push_str(&ident.to_string());
511 self.buffer.push_str(" {");
512 // Hackery to account for the closing }.
513 let mod_lo = self.codemap.span_after(source!(self, s), "{");
515 self.snippet(codemap::mk_sp(mod_lo, source!(self, m.inner).hi - BytePos(1)));
516 let body_snippet = body_snippet.trim();
517 if body_snippet.is_empty() {
518 self.buffer.push_str("}");
520 self.last_pos = mod_lo;
521 self.block_indent = self.block_indent.block_indent(self.config);
522 self.walk_mod_items(m);
523 self.format_missing_with_indent(source!(self, m.inner).hi - BytePos(1));
526 self.last_pos = source!(self, m.inner).hi;
528 self.buffer.push_str(";");
529 self.last_pos = source!(self, s).hi;
533 pub fn format_separate_mod(&mut self, m: &ast::Mod) {
534 let filemap = self.codemap.lookup_char_pos(source!(self, m.inner).lo).file;
535 self.last_pos = filemap.start_pos;
536 self.block_indent = Indent::empty();
537 self.walk_mod_items(m);
538 self.format_missing(filemap.end_pos);
541 fn format_import(&mut self, vis: &ast::Visibility, vp: &ast::ViewPath, span: Span) {
542 let vis = match utils::format_visibility(vis) {
546 let mut offset = self.block_indent;
547 offset.alignment += vis.len() + "use ".len();
549 match vp.rewrite(&self.get_context(),
550 self.config.max_width - offset.width() - 1,
552 Some(ref s) if s.is_empty() => {
553 // Format up to last newline
554 let prev_span = codemap::mk_sp(self.last_pos, source!(self, span).lo);
555 let span_end = match self.snippet(prev_span).rfind('\n') {
556 Some(offset) => self.last_pos + BytePos(offset as u32),
557 None => source!(self, span).lo,
559 self.format_missing(span_end);
560 self.last_pos = source!(self, span).hi;
563 let s = format!("{}use {};", vis, s);
564 self.format_missing_with_indent(source!(self, span).lo);
565 self.buffer.push_str(&s);
566 self.last_pos = source!(self, span).hi;
569 self.format_missing_with_indent(source!(self, span).lo);
570 self.format_missing(source!(self, span).hi);
575 pub fn get_context(&self) -> RewriteContext {
577 parse_session: self.parse_session,
578 codemap: self.codemap,
580 block_indent: self.block_indent,
585 impl<'a> Rewrite for [ast::Attribute] {
586 fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
587 let mut result = String::new();
591 let indent = offset.to_string(context.config);
593 for (i, a) in self.iter().enumerate() {
594 let mut a_str = context.snippet(a.span);
596 // Write comments and blank lines between attributes.
598 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
599 // This particular horror show is to preserve line breaks in between doc
600 // comments. An alternative would be to force such line breaks to start
601 // with the usual doc comment token.
602 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
603 let comment = comment.trim();
604 if !comment.is_empty() {
605 let comment = try_opt!(rewrite_comment(comment,
607 context.config.ideal_width -
611 result.push_str(&indent);
612 result.push_str(&comment);
614 } else if multi_line {
617 result.push_str(&indent);
620 if a_str.starts_with("//") {
621 a_str = try_opt!(rewrite_comment(&a_str,
623 context.config.ideal_width - offset.width(),
628 // Write the attribute itself.
629 result.push_str(&a_str);
631 if i < self.len() - 1 {