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};
14 use syntax::parse::token;
16 use std::path::PathBuf;
20 use comment::FindUncommented;
22 use changes::ChangeSet;
23 use rewrite::{Rewrite, RewriteContext};
25 pub struct FmtVisitor<'a> {
26 pub codemap: &'a CodeMap,
27 pub changes: ChangeSet<'a>,
28 pub last_pos: BytePos,
29 // TODO RAII util for indenting
30 pub block_indent: usize,
31 pub config: &'a Config,
34 impl<'a, 'v> visit::Visitor<'v> for FmtVisitor<'a> {
35 fn visit_expr(&mut self, ex: &'v ast::Expr) {
36 debug!("visit_expr: {:?} {:?}",
37 self.codemap.lookup_char_pos(ex.span.lo),
38 self.codemap.lookup_char_pos(ex.span.hi));
39 self.format_missing(ex.span.lo);
40 let offset = self.changes.cur_offset_span(ex.span);
41 let context = RewriteContext { codemap: self.codemap,
43 block_indent: self.block_indent, };
44 let rewrite = ex.rewrite(&context, self.config.max_width - offset, offset);
46 if let Some(new_str) = rewrite {
47 self.changes.push_str_span(ex.span, &new_str);
48 self.last_pos = ex.span.hi;
52 fn visit_stmt(&mut self, stmt: &'v ast::Stmt) {
53 // If the stmt is actually an item, then we'll handle any missing spans
54 // there. This is important because of annotations.
55 // Although it might make more sense for the statement span to include
56 // any annotations on the item.
57 let skip_missing = match stmt.node {
58 ast::Stmt_::StmtDecl(ref decl, _) => {
60 ast::Decl_::DeclItem(_) => true,
67 self.format_missing_with_indent(stmt.span.lo);
69 visit::walk_stmt(self, stmt);
72 fn visit_block(&mut self, b: &'v ast::Block) {
73 debug!("visit_block: {:?} {:?}",
74 self.codemap.lookup_char_pos(b.span.lo),
75 self.codemap.lookup_char_pos(b.span.hi));
76 self.format_missing(b.span.lo);
78 self.changes.push_str_span(b.span, "{");
79 self.last_pos = self.last_pos + BytePos(1);
80 self.block_indent += self.config.tab_spaces;
82 for stmt in &b.stmts {
83 self.visit_stmt(&stmt)
87 self.format_missing_with_indent(e.span.lo);
93 self.block_indent -= self.config.tab_spaces;
94 // TODO we should compress any newlines here to just one
95 self.format_missing_with_indent(b.span.hi - BytePos(1));
96 self.changes.push_str_span(b.span, "}");
97 self.last_pos = b.span.hi;
100 // Note that this only gets called for function definitions. Required methods
101 // on traits do not get handled here.
102 fn visit_fn(&mut self,
103 fk: visit::FnKind<'v>,
108 self.format_missing_with_indent(s.lo);
109 self.last_pos = s.lo;
111 let indent = self.block_indent;
113 visit::FkItemFn(ident,
119 let new_fn = self.rewrite_fn(indent,
128 codemap::mk_sp(s.lo, b.span.lo));
129 self.changes.push_str_span(s, &new_fn);
131 visit::FkMethod(ident, ref sig, vis) => {
132 let new_fn = self.rewrite_fn(indent,
135 Some(&sig.explicit_self),
140 vis.unwrap_or(ast::Visibility::Inherited),
141 codemap::mk_sp(s.lo, b.span.lo));
142 self.changes.push_str_span(s, &new_fn);
144 visit::FkFnBlock(..) => {}
147 self.last_pos = b.span.lo;
151 fn visit_item(&mut self, item: &'v ast::Item) {
152 // Don't look at attributes for modules.
153 // We want to avoid looking at attributes in another file, which the AST
154 // doesn't distinguish. FIXME This is overly conservative and means we miss
155 // attributes on inline modules.
157 ast::Item_::ItemMod(_) => {}
159 if self.visit_attrs(&item.attrs) {
166 ast::Item_::ItemUse(ref vp) => {
168 ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
169 let block_indent = self.block_indent;
170 let one_line_budget = self.config.max_width - block_indent;
171 let multi_line_budget = self.config.ideal_width - block_indent;
172 let formatted = self.rewrite_use_list(block_indent,
180 if let Some(new_str) = formatted {
181 self.format_missing_with_indent(item.span.lo);
182 self.changes.push_str_span(item.span, &new_str);
184 // Format up to last newline
185 let span = codemap::mk_sp(self.last_pos, item.span.lo);
186 let span_end = match self.snippet(span).rfind('\n') {
187 Some(offset) => self.last_pos + BytePos(offset as u32),
190 self.format_missing(span_end);
193 self.last_pos = item.span.hi;
195 ast::ViewPath_::ViewPathGlob(_) => {
196 self.format_missing_with_indent(item.span.lo);
197 // FIXME convert to list?
199 ast::ViewPath_::ViewPathSimple(_,_) => {
200 self.format_missing_with_indent(item.span.lo);
203 visit::walk_item(self, item);
205 ast::Item_::ItemImpl(..) |
206 ast::Item_::ItemTrait(..) => {
207 self.block_indent += self.config.tab_spaces;
208 visit::walk_item(self, item);
209 self.block_indent -= self.config.tab_spaces;
211 ast::Item_::ItemExternCrate(_) => {
212 self.format_missing_with_indent(item.span.lo);
213 let new_str = self.snippet(item.span);
214 self.changes.push_str_span(item.span, &new_str);
215 self.last_pos = item.span.hi;
217 ast::Item_::ItemStruct(ref def, ref generics) => {
218 self.format_missing_with_indent(item.span.lo);
219 self.visit_struct(item.ident,
224 self.last_pos = item.span.hi;
226 ast::Item_::ItemEnum(ref def, ref generics) => {
227 self.format_missing_with_indent(item.span.lo);
228 self.visit_enum(item.ident,
233 self.last_pos = item.span.hi;
235 ast::Item_::ItemMod(ref module) => {
236 self.format_missing_with_indent(item.span.lo);
237 self.format_mod(module, item.span, item.ident, &item.attrs);
240 visit::walk_item(self, item);
245 fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
246 if self.visit_attrs(&ti.attrs) {
250 if let ast::TraitItem_::MethodTraitItem(ref sig, None) = ti.node {
251 self.format_missing_with_indent(ti.span.lo);
253 let indent = self.block_indent;
254 let new_fn = self.rewrite_required_fn(indent,
259 self.changes.push_str_span(ti.span, &new_fn);
260 self.last_pos = ti.span.hi;
262 // TODO format trait types
264 visit::walk_trait_item(self, ti)
267 fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
268 if self.visit_attrs(&ii.attrs) {
271 visit::walk_impl_item(self, ii)
274 fn visit_mac(&mut self, mac: &'v ast::Mac) {
275 visit::walk_mac(self, mac)
278 fn visit_mod(&mut self, m: &'v ast::Mod, s: Span, _: ast::NodeId) {
279 // This is only called for the root module
280 let filename = self.codemap.span_to_filename(s);
281 self.format_separate_mod(m, &filename);
285 impl<'a> FmtVisitor<'a> {
286 pub fn from_codemap<'b>(codemap: &'b CodeMap, config: &'b Config) -> FmtVisitor<'b> {
287 FmtVisitor { codemap: codemap,
288 changes: ChangeSet::from_codemap(codemap),
289 last_pos: BytePos(0),
294 pub fn snippet(&self, span: Span) -> String {
295 match self.codemap.span_to_snippet(span) {
298 println!("Couldn't make snippet for span {:?}->{:?}",
299 self.codemap.lookup_char_pos(span.lo),
300 self.codemap.lookup_char_pos(span.hi));
306 // Returns true if we should skip the following item.
307 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
308 if attrs.len() == 0 {
312 let first = &attrs[0];
313 self.format_missing_with_indent(first.span.lo);
315 if utils::contains_skip(attrs) {
318 let rewrite = self.rewrite_attrs(attrs, self.block_indent);
319 self.changes.push_str_span(first.span, &rewrite);
320 let last = attrs.last().unwrap();
321 self.last_pos = last.span.hi;
326 pub fn rewrite_attrs(&self, attrs: &[ast::Attribute], indent: usize) -> String {
327 let mut result = String::new();
328 let indent = utils::make_indent(indent);
330 for (i, a) in attrs.iter().enumerate() {
331 let a_str = self.snippet(a.span);
334 let comment = self.snippet(codemap::mk_sp(attrs[i-1].span.hi, a.span.lo));
335 // This particular horror show is to preserve line breaks in between doc
336 // comments. An alternative would be to force such line breaks to start
337 // with the usual doc comment token.
338 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
339 let comment = comment.trim();
340 if comment.len() > 0 {
341 result.push_str(&indent);
342 result.push_str(comment);
344 } else if multi_line {
347 result.push_str(&indent);
350 result.push_str(&a_str);
352 if i < attrs.len() -1 {
360 fn format_mod(&mut self, m: &ast::Mod, s: Span, ident: ast::Ident, attrs: &[ast::Attribute]) {
361 debug!("FmtVisitor::format_mod: ident: {:?}, span: {:?}", ident, s);
362 // Decide whether this is an inline mod or an external mod.
363 // There isn't any difference between inline and external mod in AST,
364 // so we use the trick of searching for an opening brace.
365 // We can't use the inner span of the mod since it is weird when it
366 // is empty (no items).
367 // FIXME Use the inner span once rust-lang/rust#26755 is fixed.
368 let open_brace = self.codemap.span_to_snippet(s).unwrap().find_uncommented("{");
371 debug!("FmtVisitor::format_mod: external mod");
372 let file_path = self.module_file(ident, attrs, s);
373 let filename = file_path.to_str().unwrap();
374 if self.changes.is_changed(filename) {
375 // The file has already been reformatted, do nothing
377 self.format_separate_mod(m, filename);
379 // TODO Should rewrite properly `mod X;`
381 Some(open_brace) => {
382 debug!("FmtVisitor::format_mod: internal mod");
383 debug!("... open_brace: {}, str: {:?}", open_brace, self.codemap.span_to_snippet(s));
384 // Format everything until opening brace
385 // TODO Shoud rewrite properly
386 self.format_missing(s.lo + BytePos(open_brace as u32));
387 self.block_indent += self.config.tab_spaces;
388 visit::walk_mod(self, m);
389 debug!("... last_pos after: {:?}", self.last_pos);
390 self.block_indent -= self.config.tab_spaces;
393 self.format_missing(s.hi);
394 debug!("FmtVisitor::format_mod: exit");
397 /// Find the file corresponding to an external mod
398 /// Same algorithm as syntax::parse::eval_src_mod
399 fn module_file(&self, id: ast::Ident, outer_attrs: &[ast::Attribute], id_sp: Span) -> PathBuf {
400 // FIXME use libsyntax once rust-lang/rust#26750 is merged
401 let mut prefix = PathBuf::from(&self.codemap.span_to_filename(id_sp));
403 let mod_string = token::get_ident(id);
404 match attr::first_attr_value_str_by_name(outer_attrs, "path") {
405 Some(d) => prefix.join(&*d),
407 let default_path_str = format!("{}.rs", mod_string);
408 let secondary_path_str = format!("{}/mod.rs", mod_string);
409 let default_path = prefix.join(&default_path_str);
410 let secondary_path = prefix.join(&secondary_path_str);
411 let default_exists = self.codemap.file_exists(&default_path);
412 let secondary_exists = self.codemap.file_exists(&secondary_path);
415 } else if secondary_exists {
418 // Should never appens since rustc parsed everything sucessfully
419 panic!("Didn't found module {}", mod_string);
425 /// Format the content of a module into a separate file
426 fn format_separate_mod(&mut self, m: &ast::Mod, filename: &str) {
427 let last_pos = self.last_pos;
428 let block_indent = self.block_indent;
429 let filemap = self.codemap.get_filemap(filename);
430 self.last_pos = filemap.start_pos;
431 self.block_indent = 0;
432 visit::walk_mod(self, m);
433 self.format_missing(filemap.end_pos);
434 self.last_pos = last_pos;
435 self.block_indent = block_indent;