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,
174 if let Some(new_str) = formatted {
175 self.format_missing_with_indent(item.span.lo);
176 self.changes.push_str_span(item.span, &new_str);
178 // Format up to last newline
179 let span = codemap::mk_sp(self.last_pos, item.span.lo);
180 let span_end = match self.snippet(span).rfind('\n') {
181 Some(offset) => self.last_pos + BytePos(offset as u32),
184 self.format_missing(span_end);
187 self.last_pos = item.span.hi;
189 ast::ViewPath_::ViewPathGlob(_) => {
190 self.format_missing_with_indent(item.span.lo);
191 // FIXME convert to list?
193 ast::ViewPath_::ViewPathSimple(_,_) => {
194 self.format_missing_with_indent(item.span.lo);
197 visit::walk_item(self, item);
199 ast::Item_::ItemImpl(..) |
200 ast::Item_::ItemMod(_) |
201 ast::Item_::ItemTrait(..) => {
202 self.block_indent += self.config.tab_spaces;
203 visit::walk_item(self, item);
204 self.block_indent -= self.config.tab_spaces;
206 ast::Item_::ItemExternCrate(_) => {
207 self.format_missing_with_indent(item.span.lo);
208 let new_str = self.snippet(item.span);
209 self.changes.push_str_span(item.span, &new_str);
210 self.last_pos = item.span.hi;
212 ast::Item_::ItemStruct(ref def, ref generics) => {
213 self.format_missing_with_indent(item.span.lo);
214 self.visit_struct(item.ident,
219 self.last_pos = item.span.hi;
221 ast::Item_::ItemEnum(ref def, ref generics) => {
222 self.format_missing_with_indent(item.span.lo);
223 self.visit_enum(item.ident,
228 self.last_pos = item.span.hi;
231 visit::walk_item(self, item);
236 fn visit_trait_item(&mut self, ti: &'v ast::TraitItem) {
237 if self.visit_attrs(&ti.attrs) {
241 if let ast::TraitItem_::MethodTraitItem(ref sig, None) = ti.node {
242 self.format_missing_with_indent(ti.span.lo);
244 let indent = self.block_indent;
245 let new_fn = self.rewrite_required_fn(indent,
250 self.changes.push_str_span(ti.span, &new_fn);
251 self.last_pos = ti.span.hi;
253 // TODO format trait types
255 visit::walk_trait_item(self, ti)
258 fn visit_impl_item(&mut self, ii: &'v ast::ImplItem) {
259 if self.visit_attrs(&ii.attrs) {
262 visit::walk_impl_item(self, ii)
265 fn visit_mac(&mut self, mac: &'v ast::Mac) {
266 visit::walk_mac(self, mac)
269 fn visit_mod(&mut self, m: &'v ast::Mod, s: Span, _: ast::NodeId) {
270 // Only visit inline mods here.
271 if self.codemap.lookup_char_pos(s.lo).file.name !=
272 self.codemap.lookup_char_pos(m.inner.lo).file.name {
275 visit::walk_mod(self, m);
279 impl<'a> FmtVisitor<'a> {
280 pub fn from_codemap<'b>(codemap: &'b CodeMap, config: &'b Config) -> FmtVisitor<'b> {
283 changes: ChangeSet::from_codemap(codemap),
284 last_pos: BytePos(0),
290 pub fn snippet(&self, span: Span) -> String {
291 match self.codemap.span_to_snippet(span) {
294 println!("Couldn't make snippet for span {:?}->{:?}",
295 self.codemap.lookup_char_pos(span.lo),
296 self.codemap.lookup_char_pos(span.hi));
302 // Returns true if we should skip the following item.
303 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
304 if attrs.len() == 0 {
308 let first = &attrs[0];
309 self.format_missing_with_indent(first.span.lo);
311 if utils::contains_skip(attrs) {
314 let rewrite = self.rewrite_attrs(attrs, self.block_indent);
315 self.changes.push_str_span(first.span, &rewrite);
316 let last = attrs.last().unwrap();
317 self.last_pos = last.span.hi;
322 pub fn rewrite_attrs(&self, attrs: &[ast::Attribute], indent: usize) -> String {
323 let mut result = String::new();
324 let indent = utils::make_indent(indent);
326 for (i, a) in attrs.iter().enumerate() {
327 let a_str = self.snippet(a.span);
330 let comment = self.snippet(codemap::mk_sp(attrs[i-1].span.hi, a.span.lo));
331 // This particular horror show is to preserve line breaks in between doc
332 // comments. An alternative would be to force such line breaks to start
333 // with the usual doc comment token.
334 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
335 let comment = comment.trim();
336 if comment.len() > 0 {
337 result.push_str(&indent);
338 result.push_str(comment);
340 } else if multi_line {
343 result.push_str(&indent);
346 result.push_str(&a_str);
348 if i < attrs.len() -1 {