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,
29 impl<'a, 'v> visit::Visitor<'v> for FmtVisitor<'a> {
30 fn visit_expr(&mut self, ex: &'v ast::Expr) {
31 debug!("visit_expr: {:?} {:?}",
32 self.codemap.lookup_char_pos(ex.span.lo),
33 self.codemap.lookup_char_pos(ex.span.hi));
34 self.format_missing(ex.span.lo);
35 let offset = self.changes.cur_offset_span(ex.span);
36 match ex.rewrite(&RewriteContext { codemap: self.codemap },
37 config!(max_width) - offset,
40 //let new_str = self.rewrite_expr(ex, config!(max_width) - offset, offset);
41 self.changes.push_str_span(ex.span, &new_str);
42 self.last_pos = ex.span.hi;
44 None => { self.last_pos = ex.span.lo; }
48 fn visit_stmt(&mut self, stmt: &'v ast::Stmt) {
49 // If the stmt is actually an item, then we'll handle any missing spans
50 // there. This is important because of annotations.
51 // Although it might make more sense for the statement span to include
52 // any annotations on the item.
53 let skip_missing = match stmt.node {
54 ast::Stmt_::StmtDecl(ref decl, _) => {
56 ast::Decl_::DeclItem(_) => true,
63 self.format_missing_with_indent(stmt.span.lo);
65 visit::walk_stmt(self, stmt);
68 fn visit_block(&mut self, b: &'v ast::Block) {
69 debug!("visit_block: {:?} {:?}",
70 self.codemap.lookup_char_pos(b.span.lo),
71 self.codemap.lookup_char_pos(b.span.hi));
72 self.format_missing(b.span.lo);
74 self.changes.push_str_span(b.span, "{");
75 self.last_pos = self.last_pos + BytePos(1);
76 self.block_indent += config!(tab_spaces);
78 for stmt in &b.stmts {
79 self.visit_stmt(&stmt)
83 self.format_missing_with_indent(e.span.lo);
89 self.block_indent -= config!(tab_spaces);
90 // TODO we should compress any newlines here to just one
91 self.format_missing_with_indent(b.span.hi - BytePos(1));
92 self.changes.push_str_span(b.span, "}");
93 self.last_pos = b.span.hi;
96 // Note that this only gets called for function definitions. Required methods
97 // on traits do not get handled here.
98 fn visit_fn(&mut self,
99 fk: visit::FnKind<'v>,
104 self.format_missing_with_indent(s.lo);
105 self.last_pos = s.lo;
107 let indent = self.block_indent;
109 visit::FkItemFn(ident,
115 let new_fn = self.rewrite_fn(indent,
125 self.changes.push_str_span(s, &new_fn);
127 visit::FkMethod(ident, ref sig, vis) => {
128 let new_fn = self.rewrite_fn(indent,
131 Some(&sig.explicit_self),
136 vis.unwrap_or(ast::Visibility::Inherited),
138 self.changes.push_str_span(s, &new_fn);
140 visit::FkFnBlock(..) => {}
143 self.last_pos = b.span.lo;
147 fn visit_item(&mut self, item: &'v ast::Item) {
148 // Don't look at attributes for modules.
149 // We want to avoid looking at attributes in another file, which the AST
150 // doesn't distinguish. FIXME This is overly conservative and means we miss
151 // attributes on inline modules.
153 ast::Item_::ItemMod(_) => {}
155 if self.visit_attrs(&item.attrs) {
162 ast::Item_::ItemUse(ref vp) => {
163 self.format_missing_with_indent(item.span.lo);
165 ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
166 let block_indent = self.block_indent;
167 let one_line_budget = config!(max_width) - block_indent;
168 let multi_line_budget = config!(ideal_width) - block_indent;
169 let new_str = self.rewrite_use_list(block_indent,
175 self.changes.push_str_span(item.span, &new_str);
176 self.last_pos = item.span.hi;
178 ast::ViewPath_::ViewPathGlob(_) => {
179 // FIXME convert to list?
181 ast::ViewPath_::ViewPathSimple(_,_) => {}
183 visit::walk_item(self, item);
185 ast::Item_::ItemImpl(..) |
186 ast::Item_::ItemMod(_) |
187 ast::Item_::ItemTrait(..) => {
188 self.block_indent += config!(tab_spaces);
189 visit::walk_item(self, item);
190 self.block_indent -= config!(tab_spaces);
192 ast::Item_::ItemExternCrate(_) => {
193 self.format_missing_with_indent(item.span.lo);
194 let new_str = self.snippet(item.span);
195 self.changes.push_str_span(item.span, &new_str);
196 self.last_pos = item.span.hi;
198 ast::Item_::ItemStruct(ref def, ref generics) => {
199 self.format_missing_with_indent(item.span.lo);
200 self.visit_struct(item.ident,
205 self.last_pos = item.span.hi;
207 ast::Item_::ItemEnum(ref def, ref generics) => {
208 self.format_missing_with_indent(item.span.lo);
209 self.visit_enum(item.ident,
214 self.last_pos = item.span.hi;
217 visit::walk_item(self, item);
222 fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
223 if self.visit_attrs(&ti.attrs) {
227 if let ast::TraitItem_::MethodTraitItem(ref sig, None) = ti.node {
228 self.format_missing_with_indent(ti.span.lo);
230 let indent = self.block_indent;
231 let new_fn = self.rewrite_required_fn(indent,
236 self.changes.push_str_span(ti.span, &new_fn);
237 self.last_pos = ti.span.hi;
239 // TODO format trait types
241 visit::walk_trait_item(self, ti)
244 fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
245 if self.visit_attrs(&ii.attrs) {
248 visit::walk_impl_item(self, ii)
251 fn visit_mac(&mut self, mac: &'v ast::Mac) {
252 visit::walk_mac(self, mac)
255 fn visit_mod(&mut self, m: &'v ast::Mod, s: Span, _: ast::NodeId) {
256 // Only visit inline mods here.
257 if self.codemap.lookup_char_pos(s.lo).file.name !=
258 self.codemap.lookup_char_pos(m.inner.lo).file.name {
261 visit::walk_mod(self, m);
265 impl<'a> FmtVisitor<'a> {
266 pub fn from_codemap<'b>(codemap: &'b CodeMap) -> FmtVisitor<'b> {
269 changes: ChangeSet::from_codemap(codemap),
270 last_pos: BytePos(0),
275 pub fn snippet(&self, span: Span) -> String {
276 match self.codemap.span_to_snippet(span) {
279 println!("Couldn't make snippet for span {:?}->{:?}",
280 self.codemap.lookup_char_pos(span.lo),
281 self.codemap.lookup_char_pos(span.hi));
287 // Returns true if we should skip the following item.
288 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
289 if attrs.len() == 0 {
293 let first = &attrs[0];
294 self.format_missing_with_indent(first.span.lo);
296 match self.rewrite_attrs(attrs, self.block_indent) {
298 self.changes.push_str_span(first.span, &s);
299 let last = attrs.last().unwrap();
300 self.last_pos = last.span.hi;
307 fn rewrite_attrs(&self, attrs: &[ast::Attribute], indent: usize) -> Option<String> {
308 let mut result = String::new();
309 let indent = utils::make_indent(indent);
311 for (i, a) in attrs.iter().enumerate() {
312 if is_skip(&a.node.value) {
316 let a_str = self.snippet(a.span);
319 let comment = self.snippet(codemap::mk_sp(attrs[i-1].span.hi, a.span.lo));
320 // This particular horror show is to preserve line breaks in between doc
321 // comments. An alternative would be to force such line breaks to start
322 // with the usual doc comment token.
323 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
324 let comment = comment.trim();
325 if comment.len() > 0 {
326 result.push_str(&indent);
327 result.push_str(comment);
329 } else if multi_line {
332 result.push_str(&indent);
335 result.push_str(&a_str);
337 if i < attrs.len() -1 {
346 fn is_skip(meta_item: &ast::MetaItem) -> bool {
347 match meta_item.node {
348 ast::MetaItem_::MetaWord(ref s) => *s == SKIP_ANNOTATION,