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};
18 use changes::ChangeSet;
19 use rewrite::{Rewrite, RewriteContext};
21 pub struct FmtVisitor<'a> {
22 pub codemap: &'a CodeMap,
23 pub changes: ChangeSet<'a>,
24 pub last_pos: BytePos,
25 // TODO RAII util for indenting
26 pub block_indent: usize,
27 pub config: &'a Config,
30 impl<'a, 'v> visit::Visitor<'v> for FmtVisitor<'a> {
31 fn visit_expr(&mut self, ex: &'v ast::Expr) {
32 debug!("visit_expr: {:?} {:?}",
33 self.codemap.lookup_char_pos(ex.span.lo),
34 self.codemap.lookup_char_pos(ex.span.hi));
35 self.format_missing(ex.span.lo);
36 let offset = self.changes.cur_offset_span(ex.span);
37 let context = RewriteContext { codemap: self.codemap, config: self.config };
38 let rewrite = ex.rewrite(&context, self.config.max_width - offset, offset);
40 if let Some(new_str) = rewrite {
41 self.changes.push_str_span(ex.span, &new_str);
42 self.last_pos = ex.span.hi;
46 fn visit_stmt(&mut self, stmt: &'v ast::Stmt) {
47 // If the stmt is actually an item, then we'll handle any missing spans
48 // there. This is important because of annotations.
49 // Although it might make more sense for the statement span to include
50 // any annotations on the item.
51 let skip_missing = match stmt.node {
52 ast::Stmt_::StmtDecl(ref decl, _) => {
54 ast::Decl_::DeclItem(_) => true,
61 self.format_missing_with_indent(stmt.span.lo);
63 visit::walk_stmt(self, stmt);
66 fn visit_block(&mut self, b: &'v ast::Block) {
67 debug!("visit_block: {:?} {:?}",
68 self.codemap.lookup_char_pos(b.span.lo),
69 self.codemap.lookup_char_pos(b.span.hi));
70 self.format_missing(b.span.lo);
72 self.changes.push_str_span(b.span, "{");
73 self.last_pos = self.last_pos + BytePos(1);
74 self.block_indent += self.config.tab_spaces;
76 for stmt in &b.stmts {
77 self.visit_stmt(&stmt)
81 self.format_missing_with_indent(e.span.lo);
87 self.block_indent -= self.config.tab_spaces;
88 // TODO we should compress any newlines here to just one
89 self.format_missing_with_indent(b.span.hi - BytePos(1));
90 self.changes.push_str_span(b.span, "}");
91 self.last_pos = b.span.hi;
94 // Note that this only gets called for function definitions. Required methods
95 // on traits do not get handled here.
96 fn visit_fn(&mut self,
97 fk: visit::FnKind<'v>,
102 self.format_missing_with_indent(s.lo);
103 self.last_pos = s.lo;
105 let indent = self.block_indent;
107 visit::FkItemFn(ident,
113 let new_fn = self.rewrite_fn(indent,
122 codemap::mk_sp(s.lo, b.span.lo));
123 self.changes.push_str_span(s, &new_fn);
125 visit::FkMethod(ident, ref sig, vis) => {
126 let new_fn = self.rewrite_fn(indent,
129 Some(&sig.explicit_self),
134 vis.unwrap_or(ast::Visibility::Inherited),
135 codemap::mk_sp(s.lo, b.span.lo));
136 self.changes.push_str_span(s, &new_fn);
138 visit::FkFnBlock(..) => {}
141 self.last_pos = b.span.lo;
145 fn visit_item(&mut self, item: &'v ast::Item) {
146 // Don't look at attributes for modules.
147 // We want to avoid looking at attributes in another file, which the AST
148 // doesn't distinguish. FIXME This is overly conservative and means we miss
149 // attributes on inline modules.
151 ast::Item_::ItemMod(_) => {}
153 if self.visit_attrs(&item.attrs) {
160 ast::Item_::ItemUse(ref vp) => {
162 ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
163 let block_indent = self.block_indent;
164 let one_line_budget = self.config.max_width - block_indent;
165 let multi_line_budget = self.config.ideal_width - block_indent;
166 let formatted = self.rewrite_use_list(block_indent,
173 if let Some(new_str) = formatted {
174 self.format_missing_with_indent(item.span.lo);
175 self.changes.push_str_span(item.span, &new_str);
177 // Format up to last newline
178 let span = codemap::mk_sp(self.last_pos, item.span.lo);
179 let span_end = match self.snippet(span).rfind('\n') {
180 Some(offset) => self.last_pos + BytePos(offset as u32),
183 self.format_missing(span_end);
186 self.last_pos = item.span.hi;
188 ast::ViewPath_::ViewPathGlob(_) => {
189 // FIXME convert to list?
191 ast::ViewPath_::ViewPathSimple(_,_) => {}
193 visit::walk_item(self, item);
195 ast::Item_::ItemImpl(..) |
196 ast::Item_::ItemMod(_) |
197 ast::Item_::ItemTrait(..) => {
198 self.block_indent += self.config.tab_spaces;
199 visit::walk_item(self, item);
200 self.block_indent -= self.config.tab_spaces;
202 ast::Item_::ItemExternCrate(_) => {
203 self.format_missing_with_indent(item.span.lo);
204 let new_str = self.snippet(item.span);
205 self.changes.push_str_span(item.span, &new_str);
206 self.last_pos = item.span.hi;
208 ast::Item_::ItemStruct(ref def, ref generics) => {
209 self.format_missing_with_indent(item.span.lo);
210 self.visit_struct(item.ident,
215 self.last_pos = item.span.hi;
217 ast::Item_::ItemEnum(ref def, ref generics) => {
218 self.format_missing_with_indent(item.span.lo);
219 self.visit_enum(item.ident,
224 self.last_pos = item.span.hi;
227 visit::walk_item(self, item);
232 fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
233 if self.visit_attrs(&ti.attrs) {
237 if let ast::TraitItem_::MethodTraitItem(ref sig, None) = ti.node {
238 self.format_missing_with_indent(ti.span.lo);
240 let indent = self.block_indent;
241 let new_fn = self.rewrite_required_fn(indent,
246 self.changes.push_str_span(ti.span, &new_fn);
247 self.last_pos = ti.span.hi;
249 // TODO format trait types
251 visit::walk_trait_item(self, ti)
254 fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
255 if self.visit_attrs(&ii.attrs) {
258 visit::walk_impl_item(self, ii)
261 fn visit_mac(&mut self, mac: &'v ast::Mac) {
262 visit::walk_mac(self, mac)
265 fn visit_mod(&mut self, m: &'v ast::Mod, s: Span, _: ast::NodeId) {
266 // Only visit inline mods here.
267 if self.codemap.lookup_char_pos(s.lo).file.name !=
268 self.codemap.lookup_char_pos(m.inner.lo).file.name {
271 visit::walk_mod(self, m);
275 impl<'a> FmtVisitor<'a> {
276 pub fn from_codemap<'b>(codemap: &'b CodeMap, config: &'b Config) -> FmtVisitor<'b> {
279 changes: ChangeSet::from_codemap(codemap),
280 last_pos: BytePos(0),
286 pub fn snippet(&self, span: Span) -> String {
287 match self.codemap.span_to_snippet(span) {
290 println!("Couldn't make snippet for span {:?}->{:?}",
291 self.codemap.lookup_char_pos(span.lo),
292 self.codemap.lookup_char_pos(span.hi));
298 // Returns true if we should skip the following item.
299 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
300 if attrs.len() == 0 {
304 let first = &attrs[0];
305 self.format_missing_with_indent(first.span.lo);
307 if utils::contains_skip(attrs) {
310 let rewrite = self.rewrite_attrs(attrs, self.block_indent);
311 self.changes.push_str_span(first.span, &rewrite);
312 let last = attrs.last().unwrap();
313 self.last_pos = last.span.hi;
318 pub fn rewrite_attrs(&self, attrs: &[ast::Attribute], indent: usize) -> String {
319 let mut result = String::new();
320 let indent = utils::make_indent(indent);
322 for (i, a) in attrs.iter().enumerate() {
323 let a_str = self.snippet(a.span);
326 let comment = self.snippet(codemap::mk_sp(attrs[i-1].span.hi, a.span.lo));
327 // This particular horror show is to preserve line breaks in between doc
328 // comments. An alternative would be to force such line breaks to start
329 // with the usual doc comment token.
330 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
331 let comment = comment.trim();
332 if comment.len() > 0 {
333 result.push_str(&indent);
334 result.push_str(comment);
336 } else if multi_line {
339 result.push_str(&indent);
342 result.push_str(&a_str);
344 if i < attrs.len() -1 {