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, ptr, visit};
12 use syntax::codemap::{self, CodeMap, Span, BytePos};
13 use syntax::parse::ParseSess;
15 use strings::string_buffer::StringBuffer;
19 use codemap::{LineRangeUtils, SpanUtils};
21 use rewrite::{Rewrite, RewriteContext};
22 use comment::rewrite_comment;
23 use macros::rewrite_macro;
24 use items::{rewrite_static, rewrite_associated_type, rewrite_type_alias, format_impl, format_trait};
26 fn is_use_item(item: &ast::Item) -> bool {
28 ast::ItemKind::Use(_) => true,
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) {
45 debug!("visit_stmt: {:?} {:?}",
46 self.codemap.lookup_char_pos(stmt.span.lo),
47 self.codemap.lookup_char_pos(stmt.span.hi));
49 // FIXME(#434): Move this check to somewhere more central, eg Rewrite.
50 if !self.config.file_lines.contains(&self.codemap.lookup_line_range(stmt.span)) {
55 ast::StmtKind::Item(ref item) => {
56 self.visit_item(item);
58 ast::StmtKind::Local(..) |
59 ast::StmtKind::Expr(..) |
60 ast::StmtKind::Semi(..) => {
61 let rewrite = stmt.rewrite(&self.get_context(),
62 self.config.max_width - self.block_indent.width(),
65 self.push_rewrite(stmt.span, rewrite);
67 ast::StmtKind::Mac(ref mac) => {
68 let (ref mac, _macro_style, _) = **mac;
69 self.visit_mac(mac, None);
74 pub fn visit_block(&mut self, b: &ast::Block) {
75 debug!("visit_block: {:?} {:?}",
76 self.codemap.lookup_char_pos(b.span.lo),
77 self.codemap.lookup_char_pos(b.span.hi));
79 // Check if this block has braces.
80 let snippet = self.snippet(b.span);
81 let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
82 let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
84 self.last_pos = self.last_pos + brace_compensation;
85 self.block_indent = self.block_indent.block_indent(self.config);
86 self.buffer.push_str("{");
88 for stmt in &b.stmts {
92 if !b.stmts.is_empty() {
93 if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
94 if utils::semicolon_for_expr(expr) {
95 self.buffer.push_str(";");
100 // FIXME: we should compress any newlines here to just one
101 self.format_missing_with_indent(source!(self, b.span).hi - brace_compensation);
103 self.last_pos = source!(self, 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 defaultness: ast::Defaultness) {
131 let indent = self.block_indent;
132 let rewrite = match fk {
133 visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis) => {
134 self.rewrite_fn(indent,
143 codemap::mk_sp(s.lo, b.span.lo),
146 visit::FnKind::Method(ident, sig, vis) => {
147 self.rewrite_fn(indent,
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(source!(self, s).lo);
164 self.buffer.push_str(&fn_str);
165 if let Some(c) = fn_str.chars().last() {
167 self.last_pos = source!(self, b.span).hi;
172 self.format_missing(source!(self, b.span).lo);
175 self.last_pos = source!(self, b.span).lo;
179 pub fn visit_item(&mut self, item: &ast::Item) {
180 // This is where we bail out if there is a skip attribute. This is only
181 // complex in the module case. It is complex because the module could be
182 // in a seperate file and there might be attributes in both files, but
183 // the AST lumps them all together.
185 ast::ItemKind::Mod(ref m) => {
186 let outer_file = self.codemap.lookup_char_pos(item.span.lo).file;
187 let inner_file = self.codemap.lookup_char_pos(m.inner.lo).file;
188 if outer_file.name == inner_file.name {
189 // Module is inline, in this case we treat modules like any
191 if self.visit_attrs(&item.attrs) {
192 self.push_rewrite(item.span, None);
195 } else if utils::contains_skip(&item.attrs) {
196 // Module is not inline, but should be skipped.
199 // Module is not inline and should not be skipped. We want
200 // to process only the attributes in the current file.
201 let attrs = item.attrs
204 let attr_file = self.codemap.lookup_char_pos(a.span.lo).file;
205 if attr_file.name == outer_file.name {
211 .collect::<Vec<_>>();
212 // Assert because if we should skip it should be caught by
214 assert!(!self.visit_attrs(&attrs));
218 if self.visit_attrs(&item.attrs) {
219 self.push_rewrite(item.span, None);
226 ast::ItemKind::Use(ref vp) => {
227 self.format_import(&item.vis, vp, item.span);
229 ast::ItemKind::Impl(..) => {
230 self.format_missing_with_indent(source!(self, item.span).lo);
231 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
232 self.buffer.push_str(&impl_str);
233 self.last_pos = source!(self, item.span).hi;
236 ast::ItemKind::Trait(..) => {
237 self.format_missing_with_indent(item.span.lo);
238 if let Some(trait_str) = format_trait(&self.get_context(),
241 self.buffer.push_str(&trait_str);
242 self.last_pos = source!(self, item.span).hi;
245 ast::ItemKind::ExternCrate(_) => {
246 self.format_missing_with_indent(source!(self, item.span).lo);
247 let new_str = self.snippet(item.span);
248 self.buffer.push_str(&new_str);
249 self.last_pos = source!(self, item.span).hi;
251 ast::ItemKind::Struct(ref def, ref generics) => {
253 let indent = self.block_indent;
254 let context = self.get_context();
255 ::items::format_struct(&context,
266 ast::VariantData::Tuple(..) => s + ";",
271 self.push_rewrite(item.span, rewrite);
273 ast::ItemKind::Enum(ref def, ref generics) => {
274 self.format_missing_with_indent(source!(self, item.span).lo);
275 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
276 self.last_pos = source!(self, item.span).hi;
278 ast::ItemKind::Mod(ref module) => {
279 self.format_missing_with_indent(source!(self, item.span).lo);
280 self.format_mod(module, &item.vis, item.span, item.ident);
282 ast::ItemKind::Mac(ref mac) => {
283 self.visit_mac(mac, Some(item.ident));
285 ast::ItemKind::ForeignMod(ref foreign_mod) => {
286 self.format_missing_with_indent(source!(self, item.span).lo);
287 self.format_foreign_mod(foreign_mod, item.span);
289 ast::ItemKind::Static(ref ty, mutability, ref expr) => {
290 let rewrite = rewrite_static("static",
296 &self.get_context());
297 self.push_rewrite(item.span, rewrite);
299 ast::ItemKind::Const(ref ty, ref expr) => {
300 let rewrite = rewrite_static("const",
304 ast::Mutability::Immutable,
306 &self.get_context());
307 self.push_rewrite(item.span, rewrite);
309 ast::ItemKind::DefaultImpl(..) => {
310 // FIXME(#78): format impl definitions.
312 ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
313 self.visit_fn(visit::FnKind::ItemFn(item.ident,
323 ast::Defaultness::Final)
325 ast::ItemKind::Ty(ref ty, ref generics) => {
326 let rewrite = rewrite_type_alias(&self.get_context(),
333 self.push_rewrite(item.span, rewrite);
335 ast::ItemKind::Union(..) => {
336 // FIXME(#1157): format union definitions.
341 pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
342 if self.visit_attrs(&ti.attrs) {
343 self.push_rewrite(ti.span, None);
348 ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
349 let rewrite = rewrite_static("const",
350 &ast::Visibility::Inherited,
353 ast::Mutability::Immutable,
355 &self.get_context());
356 self.push_rewrite(ti.span, rewrite);
358 ast::TraitItemKind::Method(ref sig, None) => {
359 let indent = self.block_indent;
360 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
361 self.push_rewrite(ti.span, rewrite);
363 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
364 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
369 ast::Defaultness::Final);
371 ast::TraitItemKind::Type(ref type_param_bounds, _) => {
372 let rewrite = rewrite_associated_type(ti.ident,
374 Some(type_param_bounds),
377 self.push_rewrite(ti.span, rewrite);
379 ast::TraitItemKind::Macro(..) => {
380 // FIXME(#1158) Macros in trait item position
385 pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
386 if self.visit_attrs(&ii.attrs) {
387 self.push_rewrite(ii.span, None);
392 ast::ImplItemKind::Method(ref sig, ref body) => {
393 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(&ii.vis)),
400 ast::ImplItemKind::Const(ref ty, ref expr) => {
401 let rewrite = rewrite_static("const",
405 ast::Mutability::Immutable,
407 &self.get_context());
408 self.push_rewrite(ii.span, rewrite);
410 ast::ImplItemKind::Type(ref ty) => {
411 let rewrite = rewrite_associated_type(ii.ident,
416 self.push_rewrite(ii.span, rewrite);
418 ast::ImplItemKind::Macro(ref mac) => {
419 self.visit_mac(mac, Some(ii.ident));
424 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>) {
426 let width = self.config.max_width - self.block_indent.width() - 1;
427 let rewrite = rewrite_macro(mac, ident, &self.get_context(), width, self.block_indent);
428 self.push_rewrite(mac.span, rewrite);
431 fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
432 self.format_missing_with_indent(source!(self, span).lo);
433 let result = rewrite.unwrap_or_else(|| self.snippet(span));
434 self.buffer.push_str(&result);
435 self.last_pos = source!(self, span).hi;
438 pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
440 parse_session: parse_session,
441 codemap: parse_session.codemap(),
442 buffer: StringBuffer::new(),
443 last_pos: BytePos(0),
444 block_indent: Indent {
452 pub fn snippet(&self, span: Span) -> String {
453 match self.codemap.span_to_snippet(span) {
456 println!("Couldn't make snippet for span {:?}->{:?}",
457 self.codemap.lookup_char_pos(span.lo),
458 self.codemap.lookup_char_pos(span.hi));
464 // Returns true if we should skip the following item.
465 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
466 if utils::contains_skip(attrs) {
470 let outers: Vec<_> = attrs.iter()
471 .filter(|a| a.node.style == ast::AttrStyle::Outer)
474 if outers.is_empty() {
478 let first = &outers[0];
479 self.format_missing_with_indent(source!(self, first.span).lo);
481 let rewrite = outers.rewrite(&self.get_context(),
482 self.config.max_width - self.block_indent.width(),
485 self.buffer.push_str(&rewrite);
486 let last = outers.last().unwrap();
487 self.last_pos = source!(self, last.span).hi;
491 fn walk_mod_items(&mut self, m: &ast::Mod) {
492 let mut items_left: &[ptr::P<ast::Item>] = &m.items;
493 while !items_left.is_empty() {
494 // If the next item is a `use` declaration, then extract it and any subsequent `use`s
495 // to be potentially reordered within `format_imports`. Otherwise, just format the
496 // next item for output.
497 if self.config.reorder_imports && is_use_item(&*items_left[0]) {
498 let use_item_length =
499 items_left.iter().take_while(|ppi| is_use_item(&***ppi)).count();
500 let (use_items, rest) = items_left.split_at(use_item_length);
501 self.format_imports(use_items);
504 // `unwrap()` is safe here because we know `items_left`
505 // has elements from the loop condition
506 let (item, rest) = items_left.split_first().unwrap();
507 self.visit_item(item);
513 fn format_mod(&mut self, m: &ast::Mod, vis: &ast::Visibility, s: Span, ident: ast::Ident) {
514 // Decide whether this is an inline mod or an external mod.
515 let local_file_name = self.codemap.span_to_filename(s);
516 let is_internal = local_file_name == self.codemap.span_to_filename(source!(self, m.inner));
518 self.buffer.push_str(&*utils::format_visibility(vis));
519 self.buffer.push_str("mod ");
520 self.buffer.push_str(&ident.to_string());
523 self.buffer.push_str(" {");
524 // Hackery to account for the closing }.
525 let mod_lo = self.codemap.span_after(source!(self, s), "{");
527 self.snippet(codemap::mk_sp(mod_lo, source!(self, m.inner).hi - BytePos(1)));
528 let body_snippet = body_snippet.trim();
529 if body_snippet.is_empty() {
530 self.buffer.push_str("}");
532 self.last_pos = mod_lo;
533 self.block_indent = self.block_indent.block_indent(self.config);
534 self.walk_mod_items(m);
535 self.format_missing_with_indent(source!(self, m.inner).hi - BytePos(1));
538 self.last_pos = source!(self, m.inner).hi;
540 self.buffer.push_str(";");
541 self.last_pos = source!(self, s).hi;
545 pub fn format_separate_mod(&mut self, m: &ast::Mod) {
546 let filemap = self.codemap.lookup_char_pos(source!(self, m.inner).lo).file;
547 self.last_pos = filemap.start_pos;
548 self.block_indent = Indent::empty();
549 self.walk_mod_items(m);
550 self.format_missing_with_indent(filemap.end_pos);
553 pub fn get_context(&self) -> RewriteContext {
555 parse_session: self.parse_session,
556 codemap: self.codemap,
558 block_indent: self.block_indent,
563 impl<'a> Rewrite for [ast::Attribute] {
564 fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
565 let mut result = String::new();
569 let indent = offset.to_string(context.config);
571 for (i, a) in self.iter().enumerate() {
572 let mut a_str = context.snippet(a.span);
574 // Write comments and blank lines between attributes.
576 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
577 // This particular horror show is to preserve line breaks in between doc
578 // comments. An alternative would be to force such line breaks to start
579 // with the usual doc comment token.
580 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
581 let comment = comment.trim();
582 if !comment.is_empty() {
583 let comment = try_opt!(rewrite_comment(comment,
585 context.config.ideal_width -
589 result.push_str(&indent);
590 result.push_str(&comment);
592 } else if multi_line {
595 result.push_str(&indent);
598 if a_str.starts_with("//") {
599 a_str = try_opt!(rewrite_comment(&a_str,
601 context.config.ideal_width - offset.width(),
606 // Write the attribute itself.
607 result.push_str(&a_str);
609 if i < self.len() - 1 {