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