]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Merge pull request #883 from marcusklaas/macro-with-name
[rust.git] / src / visitor.rs
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.
4 //
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.
10
11 use syntax::{ast, visit};
12 use syntax::codemap::{self, CodeMap, Span, BytePos};
13 use syntax::parse::ParseSess;
14
15 use strings::string_buffer::StringBuffer;
16
17 use Indent;
18 use utils::{self, CodeMapSpanUtils};
19 use config::Config;
20 use rewrite::{Rewrite, RewriteContext};
21 use comment::rewrite_comment;
22 use macros::rewrite_macro;
23 use items::{rewrite_static, rewrite_associated_type, rewrite_type_alias, format_impl, format_trait};
24
25 pub struct FmtVisitor<'a> {
26     pub parse_session: &'a ParseSess,
27     pub codemap: &'a CodeMap,
28     pub buffer: StringBuffer,
29     pub last_pos: BytePos,
30     // FIXME: use an RAII util or closure for indenting
31     pub block_indent: Indent,
32     pub config: &'a Config,
33 }
34
35 impl<'a> FmtVisitor<'a> {
36     fn visit_stmt(&mut self, stmt: &ast::Stmt) {
37         match stmt.node {
38             ast::StmtKind::Decl(ref decl, _) => {
39                 if let ast::DeclKind::Item(ref item) = decl.node {
40                     self.visit_item(item);
41                 } else {
42                     let rewrite = stmt.rewrite(&self.get_context(),
43                                                self.config.max_width - self.block_indent.width(),
44                                                self.block_indent);
45
46                     self.push_rewrite(stmt.span, rewrite);
47                 }
48             }
49             ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
50                 let rewrite = stmt.rewrite(&self.get_context(),
51                                            self.config.max_width - self.block_indent.width(),
52                                            self.block_indent);
53
54                 self.push_rewrite(stmt.span, rewrite);
55             }
56             ast::StmtKind::Mac(ref mac, _macro_style, _) => {
57                 self.format_missing_with_indent(stmt.span.lo);
58                 self.visit_mac(mac, None);
59             }
60         }
61     }
62
63     pub fn visit_block(&mut self, b: &ast::Block) {
64         debug!("visit_block: {:?} {:?}",
65                self.codemap.lookup_char_pos(b.span.lo),
66                self.codemap.lookup_char_pos(b.span.hi));
67
68         // Check if this block has braces.
69         let snippet = self.snippet(b.span);
70         let has_braces = snippet.starts_with("{") || snippet.starts_with("unsafe");
71         let brace_compensation = if has_braces {
72             BytePos(1)
73         } else {
74             BytePos(0)
75         };
76
77         self.last_pos = self.last_pos + brace_compensation;
78         self.block_indent = self.block_indent.block_indent(self.config);
79         self.buffer.push_str("{");
80
81         for stmt in &b.stmts {
82             self.visit_stmt(&stmt)
83         }
84
85         if let Some(ref e) = b.expr {
86             self.format_missing_with_indent(e.span.lo);
87             let rewrite = e.rewrite(&self.get_context(),
88                                     self.config.max_width - self.block_indent.width(),
89                                     self.block_indent)
90                            .unwrap_or_else(|| self.snippet(e.span));
91
92             self.buffer.push_str(&rewrite);
93             self.last_pos = e.span.hi;
94
95             if utils::semicolon_for_expr(e) {
96                 self.buffer.push_str(";");
97             }
98         }
99
100         // FIXME: we should compress any newlines here to just one
101         self.format_missing_with_indent(b.span.hi - brace_compensation);
102         self.close_block();
103         self.last_pos = b.span.hi;
104     }
105
106     // FIXME: this is a terrible hack to indent the comments between the last
107     // item in the block and the closing brace to the block's level.
108     // The closing brace itself, however, should be indented at a shallower
109     // level.
110     fn close_block(&mut self) {
111         let total_len = self.buffer.len;
112         let chars_too_many = if self.config.hard_tabs {
113             1
114         } else {
115             self.config.tab_spaces
116         };
117         self.buffer.truncate(total_len - chars_too_many);
118         self.buffer.push_str("}");
119         self.block_indent = self.block_indent.block_unindent(self.config);
120     }
121
122     // Note that this only gets called for function definitions. Required methods
123     // on traits do not get handled here.
124     fn visit_fn(&mut self,
125                 fk: visit::FnKind,
126                 fd: &ast::FnDecl,
127                 b: &ast::Block,
128                 s: Span,
129                 _: ast::NodeId) {
130         let indent = self.block_indent;
131         let rewrite = match fk {
132             visit::FnKind::ItemFn(ident, ref generics, unsafety, constness, abi, vis) => {
133                 self.rewrite_fn(indent,
134                                 ident,
135                                 fd,
136                                 None,
137                                 generics,
138                                 unsafety,
139                                 constness,
140                                 abi,
141                                 vis,
142                                 codemap::mk_sp(s.lo, b.span.lo),
143                                 &b)
144             }
145             visit::FnKind::Method(ident, ref sig, vis) => {
146                 self.rewrite_fn(indent,
147                                 ident,
148                                 fd,
149                                 Some(&sig.explicit_self),
150                                 &sig.generics,
151                                 sig.unsafety,
152                                 sig.constness,
153                                 sig.abi,
154                                 vis.unwrap_or(ast::Visibility::Inherited),
155                                 codemap::mk_sp(s.lo, b.span.lo),
156                                 &b)
157             }
158             visit::FnKind::Closure => None,
159         };
160
161         if let Some(fn_str) = rewrite {
162             self.format_missing_with_indent(s.lo);
163             self.buffer.push_str(&fn_str);
164             if let Some(c) = fn_str.chars().last() {
165                 if c == '}' {
166                     self.last_pos = b.span.hi;
167                     return;
168                 }
169             }
170         } else {
171             self.format_missing(b.span.lo);
172         }
173
174         self.last_pos = b.span.lo;
175         self.visit_block(b)
176     }
177
178     fn visit_item(&mut self, item: &ast::Item) {
179         // Don't look at attributes for modules (except for rustfmt_skip).
180         // We want to avoid looking at attributes in another file, which the AST
181         // doesn't distinguish.
182         // FIXME This is overly conservative and means we miss attributes on
183         // inline modules.
184         match item.node {
185             ast::ItemKind::Mod(_) => {
186                 if utils::contains_skip(&item.attrs) {
187                     return;
188                 }
189             }
190             _ => {
191                 if self.visit_attrs(&item.attrs) {
192                     self.push_rewrite(item.span, None);
193                     return;
194                 }
195             }
196         }
197
198         match item.node {
199             ast::ItemKind::Use(ref vp) => {
200                 self.format_import(item.vis, vp, item.span);
201             }
202             ast::ItemKind::Impl(..) => {
203                 self.format_missing_with_indent(item.span.lo);
204                 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
205                     self.buffer.push_str(&impl_str);
206                     self.last_pos = item.span.hi;
207                 }
208             }
209             ast::ItemKind::Trait(..) => {
210                 self.format_missing_with_indent(item.span.lo);
211                 if let Some(trait_str) = format_trait(&self.get_context(),
212                                                       item,
213                                                       self.block_indent) {
214                     self.buffer.push_str(&trait_str);
215                     self.last_pos = item.span.hi;
216                 }
217             }
218             ast::ItemKind::ExternCrate(_) => {
219                 self.format_missing_with_indent(item.span.lo);
220                 let new_str = self.snippet(item.span);
221                 self.buffer.push_str(&new_str);
222                 self.last_pos = item.span.hi;
223             }
224             ast::ItemKind::Struct(ref def, ref generics) => {
225                 let rewrite = {
226                     let indent = self.block_indent;
227                     let context = self.get_context();
228                     ::items::format_struct(&context,
229                                            "struct ",
230                                            item.ident,
231                                            item.vis,
232                                            def,
233                                            Some(generics),
234                                            item.span,
235                                            indent)
236                         .map(|s| {
237                             match *def {
238                                 ast::VariantData::Tuple(..) => s + ";",
239                                 _ => s,
240                             }
241                         })
242                 };
243                 self.push_rewrite(item.span, rewrite);
244             }
245             ast::ItemKind::Enum(ref def, ref generics) => {
246                 self.format_missing_with_indent(item.span.lo);
247                 self.visit_enum(item.ident, item.vis, def, generics, item.span);
248                 self.last_pos = item.span.hi;
249             }
250             ast::ItemKind::Mod(ref module) => {
251                 self.format_missing_with_indent(item.span.lo);
252                 self.format_mod(module, item.vis, item.span, item.ident);
253             }
254             ast::ItemKind::Mac(ref mac) => {
255                 self.format_missing_with_indent(item.span.lo);
256                 self.visit_mac(mac, Some(item.ident));
257             }
258             ast::ItemKind::ForeignMod(ref foreign_mod) => {
259                 self.format_missing_with_indent(item.span.lo);
260                 self.format_foreign_mod(foreign_mod, item.span);
261             }
262             ast::ItemKind::Static(ref ty, mutability, ref expr) => {
263                 let rewrite = rewrite_static("static",
264                                              item.vis,
265                                              item.ident,
266                                              ty,
267                                              mutability,
268                                              Some(expr),
269                                              &self.get_context());
270                 self.push_rewrite(item.span, rewrite);
271             }
272             ast::ItemKind::Const(ref ty, ref expr) => {
273                 let rewrite = rewrite_static("const",
274                                              item.vis,
275                                              item.ident,
276                                              ty,
277                                              ast::Mutability::Immutable,
278                                              Some(expr),
279                                              &self.get_context());
280                 self.push_rewrite(item.span, rewrite);
281             }
282             ast::ItemKind::DefaultImpl(..) => {
283                 // FIXME(#78): format impl definitions.
284             }
285             ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
286                 self.visit_fn(visit::FnKind::ItemFn(item.ident,
287                                                     generics,
288                                                     unsafety,
289                                                     constness,
290                                                     abi,
291                                                     item.vis),
292                               decl,
293                               body,
294                               item.span,
295                               item.id)
296             }
297             ast::ItemKind::Ty(ref ty, ref generics) => {
298                 let rewrite = rewrite_type_alias(&self.get_context(),
299                                                  self.block_indent,
300                                                  item.ident,
301                                                  ty,
302                                                  generics,
303                                                  item.vis,
304                                                  item.span);
305                 self.push_rewrite(item.span, rewrite);
306             }
307         }
308     }
309
310     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
311         if self.visit_attrs(&ti.attrs) {
312             return;
313         }
314
315         match ti.node {
316             ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
317                 let rewrite = rewrite_static("const",
318                                              ast::Visibility::Inherited,
319                                              ti.ident,
320                                              ty,
321                                              ast::Mutability::Immutable,
322                                              expr_opt.as_ref(),
323                                              &self.get_context());
324                 self.push_rewrite(ti.span, rewrite);
325             }
326             ast::TraitItemKind::Method(ref sig, None) => {
327                 let indent = self.block_indent;
328                 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
329                 self.push_rewrite(ti.span, rewrite);
330             }
331             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
332                 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
333                               &sig.decl,
334                               &body,
335                               ti.span,
336                               ti.id);
337             }
338             ast::TraitItemKind::Type(ref type_param_bounds, _) => {
339                 let rewrite = rewrite_associated_type(ti.ident,
340                                                       None,
341                                                       Some(type_param_bounds),
342                                                       &self.get_context(),
343                                                       self.block_indent);
344                 self.push_rewrite(ti.span, rewrite);
345             }
346         }
347     }
348
349     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
350         if self.visit_attrs(&ii.attrs) {
351             return;
352         }
353
354         match ii.node {
355             ast::ImplItemKind::Method(ref sig, ref body) => {
356                 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(ii.vis)),
357                               &sig.decl,
358                               body,
359                               ii.span,
360                               ii.id);
361             }
362             ast::ImplItemKind::Const(ref ty, ref expr) => {
363                 let rewrite = rewrite_static("const",
364                                              ast::Visibility::Inherited,
365                                              ii.ident,
366                                              ty,
367                                              ast::Mutability::Immutable,
368                                              Some(expr),
369                                              &self.get_context());
370                 self.push_rewrite(ii.span, rewrite);
371             }
372             ast::ImplItemKind::Type(ref ty) => {
373                 let rewrite = rewrite_associated_type(ii.ident,
374                                                       Some(ty),
375                                                       None,
376                                                       &self.get_context(),
377                                                       self.block_indent);
378                 self.push_rewrite(ii.span, rewrite);
379             }
380             ast::ImplItemKind::Macro(ref mac) => {
381                 self.format_missing_with_indent(ii.span.lo);
382                 self.visit_mac(mac, Some(ii.ident));
383             }
384         }
385     }
386
387     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>) {
388         // 1 = ;
389         let width = self.config.max_width - self.block_indent.width() - 1;
390         let rewrite = rewrite_macro(mac, ident, &self.get_context(), width, self.block_indent);
391
392         if let Some(res) = rewrite {
393             self.buffer.push_str(&res);
394             self.last_pos = mac.span.hi;
395         }
396     }
397
398     fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
399         self.format_missing_with_indent(span.lo);
400         let result = rewrite.unwrap_or_else(|| self.snippet(span));
401         self.buffer.push_str(&result);
402         self.last_pos = span.hi;
403     }
404
405     pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
406         FmtVisitor {
407             parse_session: parse_session,
408             codemap: parse_session.codemap(),
409             buffer: StringBuffer::new(),
410             last_pos: BytePos(0),
411             block_indent: Indent {
412                 block_indent: 0,
413                 alignment: 0,
414             },
415             config: config,
416         }
417     }
418
419     pub fn snippet(&self, span: Span) -> String {
420         match self.codemap.span_to_snippet(span) {
421             Ok(s) => s,
422             Err(_) => {
423                 println!("Couldn't make snippet for span {:?}->{:?}",
424                          self.codemap.lookup_char_pos(span.lo),
425                          self.codemap.lookup_char_pos(span.hi));
426                 "".to_owned()
427             }
428         }
429     }
430
431     // Returns true if we should skip the following item.
432     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
433         if utils::contains_skip(attrs) {
434             return true;
435         }
436
437         let outers: Vec<_> = attrs.iter()
438                                   .filter(|a| a.node.style == ast::AttrStyle::Outer)
439                                   .cloned()
440                                   .collect();
441         if outers.is_empty() {
442             return false;
443         }
444
445         let first = &outers[0];
446         self.format_missing_with_indent(first.span.lo);
447
448         let rewrite = outers.rewrite(&self.get_context(),
449                                      self.config.max_width - self.block_indent.width(),
450                                      self.block_indent)
451                             .unwrap();
452         self.buffer.push_str(&rewrite);
453         let last = outers.last().unwrap();
454         self.last_pos = last.span.hi;
455         false
456     }
457
458     fn walk_mod_items(&mut self, m: &ast::Mod) {
459         for item in &m.items {
460             self.visit_item(&item);
461         }
462     }
463
464     fn format_mod(&mut self, m: &ast::Mod, vis: ast::Visibility, s: Span, ident: ast::Ident) {
465         // Decide whether this is an inline mod or an external mod.
466         let local_file_name = self.codemap.span_to_filename(s);
467         let is_internal = local_file_name == self.codemap.span_to_filename(m.inner);
468
469         self.buffer.push_str(utils::format_visibility(vis));
470         self.buffer.push_str("mod ");
471         self.buffer.push_str(&ident.to_string());
472
473         if is_internal {
474             self.buffer.push_str(" {");
475             // Hackery to account for the closing }.
476             let mod_lo = self.codemap.span_after(s, "{");
477             let body_snippet = self.snippet(codemap::mk_sp(mod_lo, m.inner.hi - BytePos(1)));
478             let body_snippet = body_snippet.trim();
479             if body_snippet.is_empty() {
480                 self.buffer.push_str("}");
481             } else {
482                 self.last_pos = mod_lo;
483                 self.block_indent = self.block_indent.block_indent(self.config);
484                 self.walk_mod_items(m);
485                 self.format_missing_with_indent(m.inner.hi - BytePos(1));
486                 self.close_block();
487             }
488             self.last_pos = m.inner.hi;
489         } else {
490             self.buffer.push_str(";");
491             self.last_pos = s.hi;
492         }
493     }
494
495     pub fn format_separate_mod(&mut self, m: &ast::Mod) {
496         let filemap = self.codemap.lookup_char_pos(m.inner.lo).file;
497         self.last_pos = filemap.start_pos;
498         self.block_indent = Indent::empty();
499         self.walk_mod_items(m);
500         self.format_missing(filemap.end_pos);
501     }
502
503     fn format_import(&mut self, vis: ast::Visibility, vp: &ast::ViewPath, span: Span) {
504         let vis = utils::format_visibility(vis);
505         let mut offset = self.block_indent;
506         offset.alignment += vis.len() + "use ".len();
507         // 1 = ";"
508         match vp.rewrite(&self.get_context(),
509                          self.config.max_width - offset.width() - 1,
510                          offset) {
511             Some(ref s) if s.is_empty() => {
512                 // Format up to last newline
513                 let prev_span = codemap::mk_sp(self.last_pos, span.lo);
514                 let span_end = match self.snippet(prev_span).rfind('\n') {
515                     Some(offset) => self.last_pos + BytePos(offset as u32),
516                     None => span.lo,
517                 };
518                 self.format_missing(span_end);
519                 self.last_pos = span.hi;
520             }
521             Some(ref s) => {
522                 let s = format!("{}use {};", vis, s);
523                 self.format_missing_with_indent(span.lo);
524                 self.buffer.push_str(&s);
525                 self.last_pos = span.hi;
526             }
527             None => {
528                 self.format_missing_with_indent(span.lo);
529                 self.format_missing(span.hi);
530             }
531         }
532     }
533
534     pub fn get_context(&self) -> RewriteContext {
535         RewriteContext {
536             parse_session: self.parse_session,
537             codemap: self.codemap,
538             config: self.config,
539             block_indent: self.block_indent,
540         }
541     }
542 }
543
544 impl<'a> Rewrite for [ast::Attribute] {
545     fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
546         let mut result = String::new();
547         if self.is_empty() {
548             return Some(result);
549         }
550         let indent = offset.to_string(context.config);
551
552         for (i, a) in self.iter().enumerate() {
553             let a_str = context.snippet(a.span);
554
555             // Write comments and blank lines between attributes.
556             if i > 0 {
557                 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
558                 // This particular horror show is to preserve line breaks in between doc
559                 // comments. An alternative would be to force such line breaks to start
560                 // with the usual doc comment token.
561                 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
562                 let comment = comment.trim();
563                 if !comment.is_empty() {
564                     let comment = try_opt!(rewrite_comment(comment,
565                                                            false,
566                                                            context.config.max_width -
567                                                            offset.width(),
568                                                            offset,
569                                                            context.config));
570                     result.push_str(&indent);
571                     result.push_str(&comment);
572                     result.push('\n');
573                 } else if multi_line {
574                     result.push('\n');
575                 }
576                 result.push_str(&indent);
577             }
578
579             // Write the attribute itself.
580             result.push_str(&a_str);
581
582             if i < self.len() - 1 {
583                 result.push('\n');
584             }
585         }
586
587         Some(result)
588     }
589 }