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 self.changes.push_str_span(ex.span, &new_str);
41 self.last_pos = ex.span.hi;
43 None => { self.last_pos = ex.span.lo; }
47 fn visit_stmt(&mut self, stmt: &'v ast::Stmt) {
48 // If the stmt is actually an item, then we'll handle any missing spans
49 // there. This is important because of annotations.
50 // Although it might make more sense for the statement span to include
51 // any annotations on the item.
52 let skip_missing = match stmt.node {
53 ast::Stmt_::StmtDecl(ref decl, _) => {
55 ast::Decl_::DeclItem(_) => true,
62 self.format_missing_with_indent(stmt.span.lo);
64 visit::walk_stmt(self, stmt);
67 fn visit_block(&mut self, b: &'v ast::Block) {
68 debug!("visit_block: {:?} {:?}",
69 self.codemap.lookup_char_pos(b.span.lo),
70 self.codemap.lookup_char_pos(b.span.hi));
71 self.format_missing(b.span.lo);
73 self.changes.push_str_span(b.span, "{");
74 self.last_pos = self.last_pos + BytePos(1);
75 self.block_indent += config!(tab_spaces);
77 for stmt in &b.stmts {
78 self.visit_stmt(&stmt)
82 self.format_missing_with_indent(e.span.lo);
88 self.block_indent -= config!(tab_spaces);
89 // TODO we should compress any newlines here to just one
90 self.format_missing_with_indent(b.span.hi - BytePos(1));
91 self.changes.push_str_span(b.span, "}");
92 self.last_pos = b.span.hi;
95 // Note that this only gets called for function definitions. Required methods
96 // on traits do not get handled here.
97 fn visit_fn(&mut self,
98 fk: visit::FnKind<'v>,
103 self.format_missing_with_indent(s.lo);
104 self.last_pos = s.lo;
106 let indent = self.block_indent;
108 visit::FkItemFn(ident,
114 let new_fn = self.rewrite_fn(indent,
124 self.changes.push_str_span(s, &new_fn);
126 visit::FkMethod(ident, ref sig, vis) => {
127 let new_fn = self.rewrite_fn(indent,
130 Some(&sig.explicit_self),
135 vis.unwrap_or(ast::Visibility::Inherited),
137 self.changes.push_str_span(s, &new_fn);
139 visit::FkFnBlock(..) => {}
142 self.last_pos = b.span.lo;
146 fn visit_item(&mut self, item: &'v ast::Item) {
147 // Don't look at attributes for modules.
148 // We want to avoid looking at attributes in another file, which the AST
149 // doesn't distinguish. FIXME This is overly conservative and means we miss
150 // attributes on inline modules.
152 ast::Item_::ItemMod(_) => {}
154 if self.visit_attrs(&item.attrs) {
161 ast::Item_::ItemUse(ref vp) => {
162 self.format_missing_with_indent(item.span.lo);
164 ast::ViewPath_::ViewPathList(ref path, ref path_list) => {
165 let block_indent = self.block_indent;
166 let one_line_budget = config!(max_width) - block_indent;
167 let multi_line_budget = config!(ideal_width) - block_indent;
168 let new_str = self.rewrite_use_list(block_indent,
174 self.changes.push_str_span(item.span, &new_str);
175 self.last_pos = item.span.hi;
177 ast::ViewPath_::ViewPathGlob(_) => {
178 // FIXME convert to list?
180 ast::ViewPath_::ViewPathSimple(_,_) => {}
182 visit::walk_item(self, item);
184 ast::Item_::ItemImpl(..) |
185 ast::Item_::ItemMod(_) |
186 ast::Item_::ItemTrait(..) => {
187 self.block_indent += config!(tab_spaces);
188 visit::walk_item(self, item);
189 self.block_indent -= config!(tab_spaces);
191 ast::Item_::ItemExternCrate(_) => {
192 self.format_missing_with_indent(item.span.lo);
193 let new_str = self.snippet(item.span);
194 self.changes.push_str_span(item.span, &new_str);
195 self.last_pos = item.span.hi;
197 ast::Item_::ItemStruct(ref def, ref generics) => {
198 self.format_missing_with_indent(item.span.lo);
199 self.visit_struct(item.ident,
204 self.last_pos = item.span.hi;
206 ast::Item_::ItemEnum(ref def, ref generics) => {
207 self.format_missing_with_indent(item.span.lo);
208 self.visit_enum(item.ident,
213 self.last_pos = item.span.hi;
216 visit::walk_item(self, item);
221 fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
222 if self.visit_attrs(&ti.attrs) {
226 if let ast::TraitItem_::MethodTraitItem(ref sig, None) = ti.node {
227 self.format_missing_with_indent(ti.span.lo);
229 let indent = self.block_indent;
230 let new_fn = self.rewrite_required_fn(indent,
235 self.changes.push_str_span(ti.span, &new_fn);
236 self.last_pos = ti.span.hi;
238 // TODO format trait types
240 visit::walk_trait_item(self, ti)
243 fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
244 if self.visit_attrs(&ii.attrs) {
247 visit::walk_impl_item(self, ii)
250 fn visit_mac(&mut self, mac: &'v ast::Mac) {
251 visit::walk_mac(self, mac)
254 fn visit_mod(&mut self, m: &'v ast::Mod, s: Span, _: ast::NodeId) {
255 // Only visit inline mods here.
256 if self.codemap.lookup_char_pos(s.lo).file.name !=
257 self.codemap.lookup_char_pos(m.inner.lo).file.name {
260 visit::walk_mod(self, m);
264 impl<'a> FmtVisitor<'a> {
265 pub fn from_codemap<'b>(codemap: &'b CodeMap) -> FmtVisitor<'b> {
268 changes: ChangeSet::from_codemap(codemap),
269 last_pos: BytePos(0),
274 pub fn snippet(&self, span: Span) -> String {
275 match self.codemap.span_to_snippet(span) {
278 println!("Couldn't make snippet for span {:?}->{:?}",
279 self.codemap.lookup_char_pos(span.lo),
280 self.codemap.lookup_char_pos(span.hi));
286 // Returns true if we should skip the following item.
287 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
288 if attrs.len() == 0 {
292 let first = &attrs[0];
293 self.format_missing_with_indent(first.span.lo);
295 match self.rewrite_attrs(attrs, self.block_indent) {
297 self.changes.push_str_span(first.span, &s);
298 let last = attrs.last().unwrap();
299 self.last_pos = last.span.hi;
306 fn rewrite_attrs(&self, attrs: &[ast::Attribute], indent: usize) -> Option<String> {
307 let mut result = String::new();
308 let indent = utils::make_indent(indent);
310 for (i, a) in attrs.iter().enumerate() {
311 if is_skip(&a.node.value) {
315 let a_str = self.snippet(a.span);
318 let comment = self.snippet(codemap::mk_sp(attrs[i-1].span.hi, a.span.lo));
319 // This particular horror show is to preserve line breaks in between doc
320 // comments. An alternative would be to force such line breaks to start
321 // with the usual doc comment token.
322 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
323 let comment = comment.trim();
324 if comment.len() > 0 {
325 result.push_str(&indent);
326 result.push_str(comment);
328 } else if multi_line {
331 result.push_str(&indent);
334 result.push_str(&a_str);
336 if i < attrs.len() -1 {
345 fn is_skip(meta_item: &ast::MetaItem) -> bool {
346 match meta_item.node {
347 ast::MetaItem_::MetaWord(ref s) => *s == SKIP_ANNOTATION,