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, config: self.config };
42 let rewrite = ex.rewrite(&context, self.config.max_width - offset, offset);
44 if let Some(new_str) = rewrite {
45 self.changes.push_str_span(ex.span, &new_str);
46 self.last_pos = ex.span.hi;
50 fn visit_stmt(&mut self, stmt: &'v ast::Stmt) {
51 // If the stmt is actually an item, then we'll handle any missing spans
52 // there. This is important because of annotations.
53 // Although it might make more sense for the statement span to include
54 // any annotations on the item.
55 let skip_missing = match stmt.node {
56 ast::Stmt_::StmtDecl(ref decl, _) => {
58 ast::Decl_::DeclItem(_) => true,
65 self.format_missing_with_indent(stmt.span.lo);
67 visit::walk_stmt(self, stmt);
70 fn visit_block(&mut self, b: &'v ast::Block) {
71 debug!("visit_block: {:?} {:?}",
72 self.codemap.lookup_char_pos(b.span.lo),
73 self.codemap.lookup_char_pos(b.span.hi));
74 self.format_missing(b.span.lo);
76 self.changes.push_str_span(b.span, "{");
77 self.last_pos = self.last_pos + BytePos(1);
78 self.block_indent += self.config.tab_spaces;
80 for stmt in &b.stmts {
81 self.visit_stmt(&stmt)
85 self.format_missing_with_indent(e.span.lo);
91 self.block_indent -= self.config.tab_spaces;
92 // TODO we should compress any newlines here to just one
93 self.format_missing_with_indent(b.span.hi - BytePos(1));
94 self.changes.push_str_span(b.span, "}");
95 self.last_pos = b.span.hi;
98 // Note that this only gets called for function definitions. Required methods
99 // on traits do not get handled here.
100 fn visit_fn(&mut self,
101 fk: visit::FnKind<'v>,
106 self.format_missing_with_indent(s.lo);
107 self.last_pos = s.lo;
109 let indent = self.block_indent;
111 visit::FkItemFn(ident,
117 let new_fn = self.rewrite_fn(indent,
126 codemap::mk_sp(s.lo, b.span.lo));
127 self.changes.push_str_span(s, &new_fn);
129 visit::FkMethod(ident, ref sig, vis) => {
130 let new_fn = self.rewrite_fn(indent,
133 Some(&sig.explicit_self),
138 vis.unwrap_or(ast::Visibility::Inherited),
139 codemap::mk_sp(s.lo, b.span.lo));
140 self.changes.push_str_span(s, &new_fn);
142 visit::FkFnBlock(..) => {}
145 self.last_pos = b.span.lo;
149 fn visit_item(&mut self, item: &'v ast::Item) {
150 // Don't look at attributes for modules.
151 // We want to avoid looking at attributes in another file, which the AST
152 // doesn't distinguish. FIXME This is overly conservative and means we miss
153 // attributes on inline modules.
155 ast::Item_::ItemMod(_) => {}
157 if self.visit_attrs(&item.attrs) {
164 ast::Item_::ItemUse(ref vp) => {
166 ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
167 let block_indent = self.block_indent;
168 let one_line_budget = self.config.max_width - block_indent;
169 let multi_line_budget = self.config.ideal_width - block_indent;
170 let formatted = self.rewrite_use_list(block_indent,
178 if let Some(new_str) = formatted {
179 self.format_missing_with_indent(item.span.lo);
180 self.changes.push_str_span(item.span, &new_str);
182 // Format up to last newline
183 let span = codemap::mk_sp(self.last_pos, item.span.lo);
184 let span_end = match self.snippet(span).rfind('\n') {
185 Some(offset) => self.last_pos + BytePos(offset as u32),
188 self.format_missing(span_end);
191 self.last_pos = item.span.hi;
193 ast::ViewPath_::ViewPathGlob(_) => {
194 self.format_missing_with_indent(item.span.lo);
195 // FIXME convert to list?
197 ast::ViewPath_::ViewPathSimple(_,_) => {
198 self.format_missing_with_indent(item.span.lo);
201 visit::walk_item(self, item);
203 ast::Item_::ItemImpl(..) |
204 ast::Item_::ItemTrait(..) => {
205 self.block_indent += self.config.tab_spaces;
206 visit::walk_item(self, item);
207 self.block_indent -= self.config.tab_spaces;
209 ast::Item_::ItemExternCrate(_) => {
210 self.format_missing_with_indent(item.span.lo);
211 let new_str = self.snippet(item.span);
212 self.changes.push_str_span(item.span, &new_str);
213 self.last_pos = item.span.hi;
215 ast::Item_::ItemStruct(ref def, ref generics) => {
216 self.format_missing_with_indent(item.span.lo);
217 self.visit_struct(item.ident,
222 self.last_pos = item.span.hi;
224 ast::Item_::ItemEnum(ref def, ref generics) => {
225 self.format_missing_with_indent(item.span.lo);
226 self.visit_enum(item.ident,
231 self.last_pos = item.span.hi;
233 ast::Item_::ItemMod(ref module) => {
234 self.format_missing_with_indent(item.span.lo);
235 self.format_mod(module, item.span, item.ident, &item.attrs);
238 visit::walk_item(self, item);
243 fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
244 if self.visit_attrs(&ti.attrs) {
248 if let ast::TraitItem_::MethodTraitItem(ref sig, None) = ti.node {
249 self.format_missing_with_indent(ti.span.lo);
251 let indent = self.block_indent;
252 let new_fn = self.rewrite_required_fn(indent,
257 self.changes.push_str_span(ti.span, &new_fn);
258 self.last_pos = ti.span.hi;
260 // TODO format trait types
262 visit::walk_trait_item(self, ti)
265 fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
266 if self.visit_attrs(&ii.attrs) {
269 visit::walk_impl_item(self, ii)
272 fn visit_mac(&mut self, mac: &'v ast::Mac) {
273 visit::walk_mac(self, mac)
276 fn visit_mod(&mut self, m: &'v ast::Mod, s: Span, _: ast::NodeId) {
277 // This is only called for the root module
278 let filename = self.codemap.span_to_filename(s);
279 self.format_separate_mod(m, &filename);
283 impl<'a> FmtVisitor<'a> {
284 pub fn from_codemap<'b>(codemap: &'b CodeMap, config: &'b Config) -> FmtVisitor<'b> {
285 FmtVisitor { codemap: codemap,
286 changes: ChangeSet::from_codemap(codemap),
287 last_pos: BytePos(0),
292 pub fn snippet(&self, span: Span) -> String {
293 match self.codemap.span_to_snippet(span) {
296 println!("Couldn't make snippet for span {:?}->{:?}",
297 self.codemap.lookup_char_pos(span.lo),
298 self.codemap.lookup_char_pos(span.hi));
304 // Returns true if we should skip the following item.
305 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
306 if attrs.len() == 0 {
310 let first = &attrs[0];
311 self.format_missing_with_indent(first.span.lo);
313 if utils::contains_skip(attrs) {
316 let rewrite = self.rewrite_attrs(attrs, self.block_indent);
317 self.changes.push_str_span(first.span, &rewrite);
318 let last = attrs.last().unwrap();
319 self.last_pos = last.span.hi;
324 pub fn rewrite_attrs(&self, attrs: &[ast::Attribute], indent: usize) -> String {
325 let mut result = String::new();
326 let indent = utils::make_indent(indent);
328 for (i, a) in attrs.iter().enumerate() {
329 let a_str = self.snippet(a.span);
332 let comment = self.snippet(codemap::mk_sp(attrs[i-1].span.hi, a.span.lo));
333 // This particular horror show is to preserve line breaks in between doc
334 // comments. An alternative would be to force such line breaks to start
335 // with the usual doc comment token.
336 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
337 let comment = comment.trim();
338 if comment.len() > 0 {
339 result.push_str(&indent);
340 result.push_str(comment);
342 } else if multi_line {
345 result.push_str(&indent);
348 result.push_str(&a_str);
350 if i < attrs.len() -1 {
358 fn format_mod(&mut self, m: &ast::Mod, s: Span, ident: ast::Ident, attrs: &[ast::Attribute]) {
359 debug!("FmtVisitor::format_mod: ident: {:?}, span: {:?}", ident, s);
360 // Decide whether this is an inline mod or an external mod.
361 // There isn't any difference between inline and external mod in AST,
362 // so we use the trick of searching for an opening brace.
363 // We can't use the inner span of the mod since it is weird when it
364 // is empty (no items).
365 // FIXME Use the inner span once rust-lang/rust#26755 is fixed.
366 let open_brace = self.codemap.span_to_snippet(s).unwrap().find_uncommented("{");
369 debug!("FmtVisitor::format_mod: external mod");
370 let file_path = self.module_file(ident, attrs, s);
371 let filename = file_path.to_str().unwrap();
372 if self.changes.is_changed(filename) {
373 // The file has already been reformatted, do nothing
375 self.format_separate_mod(m, filename);
377 // TODO Should rewrite properly `mod X;`
379 Some(open_brace) => {
380 debug!("FmtVisitor::format_mod: internal mod");
381 debug!("... open_brace: {}, str: {:?}", open_brace, self.codemap.span_to_snippet(s));
382 // Format everything until opening brace
383 // TODO Shoud rewrite properly
384 self.format_missing(s.lo + BytePos(open_brace as u32));
385 self.block_indent += self.config.tab_spaces;
386 visit::walk_mod(self, m);
387 debug!("... last_pos after: {:?}", self.last_pos);
388 self.block_indent -= self.config.tab_spaces;
391 self.format_missing(s.hi);
392 debug!("FmtVisitor::format_mod: exit");
395 /// Find the file corresponding to an external mod
396 /// Same algorithm as syntax::parse::eval_src_mod
397 fn module_file(&self, id: ast::Ident, outer_attrs: &[ast::Attribute], id_sp: Span) -> PathBuf {
398 // FIXME use libsyntax once rust-lang/rust#26750 is merged
399 let mut prefix = PathBuf::from(&self.codemap.span_to_filename(id_sp));
401 let mod_string = token::get_ident(id);
402 match attr::first_attr_value_str_by_name(outer_attrs, "path") {
403 Some(d) => prefix.join(&*d),
405 let default_path_str = format!("{}.rs", mod_string);
406 let secondary_path_str = format!("{}/mod.rs", mod_string);
407 let default_path = prefix.join(&default_path_str);
408 let secondary_path = prefix.join(&secondary_path_str);
409 let default_exists = self.codemap.file_exists(&default_path);
410 let secondary_exists = self.codemap.file_exists(&secondary_path);
413 } else if secondary_exists {
416 // Should never appens since rustc parsed everything sucessfully
417 panic!("Didn't found module {}", mod_string);
423 /// Format the content of a module into a separate file
424 fn format_separate_mod(&mut self, m: &ast::Mod, filename: &str) {
425 let last_pos = self.last_pos;
426 let block_indent = self.block_indent;
427 let filemap = self.codemap.get_filemap(filename);
428 self.last_pos = filemap.start_pos;
429 self.block_indent = 0;
430 visit::walk_mod(self, m);
431 self.format_missing(filemap.end_pos);
432 self.last_pos = last_pos;
433 self.block_indent = block_indent;