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};
15 use strings::string_buffer::StringBuffer;
19 use rewrite::{Rewrite, RewriteContext};
20 use comment::rewrite_comment;
22 pub struct FmtVisitor<'a> {
23 pub codemap: &'a CodeMap,
24 pub buffer: StringBuffer,
25 pub last_pos: BytePos,
26 // TODO RAII util for indenting
27 pub block_indent: usize,
28 pub config: &'a Config,
31 impl<'a, 'v> visit::Visitor<'v> for FmtVisitor<'a> {
32 // FIXME: We'd rather not format expressions here, as we have little
33 // context. How are we still reaching this?
34 fn visit_expr(&mut self, ex: &'v ast::Expr) {
35 debug!("visit_expr: {:?} {:?}",
36 self.codemap.lookup_char_pos(ex.span.lo),
37 self.codemap.lookup_char_pos(ex.span.hi));
38 self.format_missing(ex.span.lo);
40 let offset = self.buffer.cur_offset();
41 let rewrite = ex.rewrite(&self.get_context(), self.config.max_width - offset, offset);
43 if let Some(new_str) = rewrite {
44 self.buffer.push_str(&new_str);
45 self.last_pos = ex.span.hi;
49 fn visit_stmt(&mut self, stmt: &'v ast::Stmt) {
51 ast::Stmt_::StmtDecl(ref decl, _) => {
53 ast::Decl_::DeclLocal(ref local) => self.visit_let(local, stmt.span),
54 ast::Decl_::DeclItem(..) => visit::walk_stmt(self, stmt),
57 ast::Stmt_::StmtExpr(ref ex, _) | ast::Stmt_::StmtSemi(ref ex, _) => {
58 self.format_missing_with_indent(stmt.span.lo);
59 let suffix = if let ast::Stmt_::StmtExpr(..) = stmt.node {
65 // 1 = trailing semicolon;
66 let rewrite = ex.rewrite(&self.get_context(),
67 self.config.max_width - self.block_indent - suffix.len(),
70 if let Some(new_str) = rewrite {
71 self.buffer.push_str(&new_str);
72 self.buffer.push_str(suffix);
73 self.last_pos = stmt.span.hi;
76 ast::Stmt_::StmtMac(..) => {
77 self.format_missing_with_indent(stmt.span.lo);
78 visit::walk_stmt(self, stmt);
83 fn visit_block(&mut self, b: &'v ast::Block) {
84 debug!("visit_block: {:?} {:?}",
85 self.codemap.lookup_char_pos(b.span.lo),
86 self.codemap.lookup_char_pos(b.span.hi));
88 // Check if this block has braces.
89 let snippet = self.snippet(b.span);
90 let has_braces = &snippet[..1] == "{" || &snippet[..6] == "unsafe";
91 let brace_compensation = if has_braces {
97 self.last_pos = self.last_pos + brace_compensation;
98 self.block_indent += self.config.tab_spaces;
99 self.buffer.push_str("{");
101 for stmt in &b.stmts {
102 self.visit_stmt(&stmt)
107 self.format_missing_with_indent(e.span.lo);
113 self.block_indent -= self.config.tab_spaces;
114 // TODO we should compress any newlines here to just one
115 self.format_missing_with_indent(b.span.hi - brace_compensation);
116 self.buffer.push_str("}");
117 self.last_pos = b.span.hi;
120 // Note that this only gets called for function definitions. Required methods
121 // on traits do not get handled here.
122 fn visit_fn(&mut self,
123 fk: visit::FnKind<'v>,
128 let indent = self.block_indent;
129 let rewrite = match fk {
130 visit::FnKind::ItemFn(ident,
136 self.rewrite_fn(indent,
145 codemap::mk_sp(s.lo, b.span.lo))
147 visit::FnKind::Method(ident, ref sig, vis) => {
148 self.rewrite_fn(indent,
151 Some(&sig.explicit_self),
156 vis.unwrap_or(ast::Visibility::Inherited),
157 codemap::mk_sp(s.lo, b.span.lo))
159 visit::FnKind::Closure => None,
162 if let Some(fn_str) = rewrite {
163 self.format_missing_with_indent(s.lo);
164 self.buffer.push_str(&fn_str);
166 self.format_missing(b.span.lo);
169 self.last_pos = b.span.lo;
173 fn visit_item(&mut self, item: &'v ast::Item) {
174 // Don't look at attributes for modules.
175 // We want to avoid looking at attributes in another file, which the AST
176 // doesn't distinguish. FIXME This is overly conservative and means we miss
177 // attributes on inline modules.
179 ast::Item_::ItemMod(_) => {}
181 if self.visit_attrs(&item.attrs) {
188 ast::Item_::ItemUse(ref vp) => {
189 self.format_import(item.vis, vp, item.span);
191 ast::Item_::ItemImpl(..) |
192 ast::Item_::ItemTrait(..) => {
193 self.block_indent += self.config.tab_spaces;
194 visit::walk_item(self, item);
195 self.block_indent -= self.config.tab_spaces;
197 ast::Item_::ItemExternCrate(_) => {
198 self.format_missing_with_indent(item.span.lo);
199 let new_str = self.snippet(item.span);
200 self.buffer.push_str(&new_str);
201 self.last_pos = item.span.hi;
203 ast::Item_::ItemStruct(ref def, ref generics) => {
204 self.format_missing_with_indent(item.span.lo);
205 self.visit_struct(item.ident, item.vis, def, generics, item.span);
207 ast::Item_::ItemEnum(ref def, ref generics) => {
208 self.format_missing_with_indent(item.span.lo);
209 self.visit_enum(item.ident, item.vis, def, generics, item.span);
210 self.last_pos = item.span.hi;
212 ast::Item_::ItemMod(ref module) => {
213 self.format_missing_with_indent(item.span.lo);
214 self.format_mod(module, item.span, item.ident);
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, ti.ident, sig, ti.span);
234 if let Some(fn_str) = new_fn {
235 self.buffer.push_str(&fn_str);
236 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)
256 impl<'a> FmtVisitor<'a> {
257 pub fn from_codemap<'b>(codemap: &'b CodeMap, config: &'b Config) -> FmtVisitor<'b> {
260 buffer: StringBuffer::new(),
261 last_pos: BytePos(0),
267 pub fn snippet(&self, span: Span) -> String {
268 match self.codemap.span_to_snippet(span) {
271 println!("Couldn't make snippet for span {:?}->{:?}",
272 self.codemap.lookup_char_pos(span.lo),
273 self.codemap.lookup_char_pos(span.hi));
279 // Returns true if we should skip the following item.
280 pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
281 if attrs.is_empty() {
285 let first = &attrs[0];
286 self.format_missing_with_indent(first.span.lo);
288 if utils::contains_skip(attrs) {
291 let rewrite = attrs.rewrite(&self.get_context(),
292 self.config.max_width - self.block_indent,
295 self.buffer.push_str(&rewrite);
296 let last = attrs.last().unwrap();
297 self.last_pos = last.span.hi;
302 fn format_mod(&mut self, m: &ast::Mod, s: Span, ident: ast::Ident) {
303 debug!("FmtVisitor::format_mod: ident: {:?}, span: {:?}", ident, s);
305 // Decide whether this is an inline mod or an external mod.
306 let local_file_name = self.codemap.span_to_filename(s);
307 let is_internal = local_file_name == self.codemap.span_to_filename(m.inner);
309 // TODO Should rewrite properly `mod X;`
312 debug!("FmtVisitor::format_mod: internal mod");
313 self.block_indent += self.config.tab_spaces;
314 visit::walk_mod(self, m);
315 debug!("... last_pos after: {:?}", self.last_pos);
316 self.block_indent -= self.config.tab_spaces;
320 pub fn format_separate_mod(&mut self, m: &ast::Mod, filename: &str) {
321 let filemap = self.codemap.get_filemap(filename);
322 self.last_pos = filemap.start_pos;
323 self.block_indent = 0;
324 visit::walk_mod(self, m);
325 self.format_missing(filemap.end_pos);
328 fn format_import(&mut self, vis: ast::Visibility, vp: &ast::ViewPath, span: Span) {
329 let vis = utils::format_visibility(vis);
330 let offset = self.block_indent + vis.len() + "use ".len();
331 let context = RewriteContext {
332 codemap: self.codemap,
334 block_indent: self.block_indent,
338 match vp.rewrite(&context, self.config.max_width - offset - 1, offset) {
339 Some(ref s) if s.is_empty() => {
340 // Format up to last newline
341 let prev_span = codemap::mk_sp(self.last_pos, span.lo);
342 let span_end = match self.snippet(prev_span).rfind('\n') {
343 Some(offset) => self.last_pos + BytePos(offset as u32),
346 self.format_missing(span_end);
347 self.last_pos = span.hi;
350 let s = format!("{}use {};", vis, s);
351 self.format_missing_with_indent(span.lo);
352 self.buffer.push_str(&s);
353 self.last_pos = span.hi;
356 self.format_missing_with_indent(span.lo);
357 self.format_missing(span.hi);
362 pub fn get_context(&self) -> RewriteContext {
364 codemap: self.codemap,
366 block_indent: self.block_indent,
372 impl<'a> Rewrite for [ast::Attribute] {
373 fn rewrite(&self, context: &RewriteContext, _: usize, offset: usize) -> Option<String> {
374 let mut result = String::new();
378 let indent = utils::make_indent(offset);
380 for (i, a) in self.iter().enumerate() {
381 let a_str = context.snippet(a.span);
384 let comment = context.snippet(codemap::mk_sp(self[i-1].span.hi, a.span.lo));
385 // This particular horror show is to preserve line breaks in between doc
386 // comments. An alternative would be to force such line breaks to start
387 // with the usual doc comment token.
388 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
389 let comment = comment.trim();
390 if !comment.is_empty() {
391 let comment = rewrite_comment(comment,
393 context.config.max_width - offset,
395 result.push_str(&indent);
396 result.push_str(&comment);
398 } else if multi_line {
401 result.push_str(&indent);
404 result.push_str(&a_str);
406 if i < self.len() - 1 {