]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Tweak chain rules
[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, ptr, 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, Shape};
18 use utils;
19 use codemap::{LineRangeUtils, SpanUtils};
20 use config::Config;
21 use rewrite::{Rewrite, RewriteContext};
22 use comment::rewrite_comment;
23 use macros::{rewrite_macro, MacroPosition};
24 use items::{rewrite_static, rewrite_associated_type, rewrite_type_alias, format_impl, format_trait};
25
26 fn is_use_item(item: &ast::Item) -> bool {
27     match item.node {
28         ast::ItemKind::Use(_) => true,
29         _ => false,
30     }
31 }
32
33 pub struct FmtVisitor<'a> {
34     pub parse_session: &'a ParseSess,
35     pub codemap: &'a CodeMap,
36     pub buffer: StringBuffer,
37     pub last_pos: BytePos,
38     // FIXME: use an RAII util or closure for indenting
39     pub block_indent: Indent,
40     pub config: &'a Config,
41 }
42
43 impl<'a> FmtVisitor<'a> {
44     fn visit_stmt(&mut self, stmt: &ast::Stmt) {
45         debug!("visit_stmt: {:?} {:?}",
46                self.codemap.lookup_char_pos(stmt.span.lo),
47                self.codemap.lookup_char_pos(stmt.span.hi));
48
49         // FIXME(#434): Move this check to somewhere more central, eg Rewrite.
50         if !self.config.file_lines.contains(&self.codemap.lookup_line_range(stmt.span)) {
51             return;
52         }
53
54         match stmt.node {
55             ast::StmtKind::Item(ref item) => {
56                 self.visit_item(item);
57             }
58             ast::StmtKind::Local(..) |
59             ast::StmtKind::Expr(..) |
60             ast::StmtKind::Semi(..) => {
61                 let rewrite = stmt.rewrite(&self.get_context(),
62                                            Shape::legacy(self.config.max_width -
63                                                          self.block_indent.width(),
64                                                          self.block_indent));
65                 self.push_rewrite(stmt.span, rewrite);
66             }
67             ast::StmtKind::Mac(ref mac) => {
68                 let (ref mac, _macro_style, _) = **mac;
69                 self.visit_mac(mac, None, MacroPosition::Statement);
70                 self.format_missing(stmt.span.hi);
71             }
72         }
73     }
74
75     pub fn visit_block(&mut self, b: &ast::Block) {
76         debug!("visit_block: {:?} {:?}",
77                self.codemap.lookup_char_pos(b.span.lo),
78                self.codemap.lookup_char_pos(b.span.hi));
79
80         // Check if this block has braces.
81         let snippet = self.snippet(b.span);
82         let has_braces = snippet.starts_with('{') || snippet.starts_with("unsafe");
83         let brace_compensation = if has_braces { BytePos(1) } else { BytePos(0) };
84
85         self.last_pos = self.last_pos + brace_compensation;
86         self.block_indent = self.block_indent.block_indent(self.config);
87         self.buffer.push_str("{");
88
89         for stmt in &b.stmts {
90             self.visit_stmt(stmt)
91         }
92
93         if !b.stmts.is_empty() {
94             if let Some(expr) = utils::stmt_expr(&b.stmts[b.stmts.len() - 1]) {
95                 if utils::semicolon_for_expr(expr) {
96                     self.buffer.push_str(";");
97                 }
98             }
99         }
100
101         // FIXME: we should compress any newlines here to just one
102         self.format_missing_with_indent(source!(self, b.span).hi - brace_compensation);
103         self.close_block();
104         self.last_pos = source!(self, 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                 s: Span,
129                 _: ast::NodeId,
130                 defaultness: ast::Defaultness) {
131         let indent = self.block_indent;
132         let block;
133         let rewrite = match fk {
134             visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis, b) => {
135                 block = b;
136                 self.rewrite_fn(indent,
137                                 ident,
138                                 fd,
139                                 generics,
140                                 unsafety,
141                                 constness.node,
142                                 defaultness,
143                                 abi,
144                                 vis,
145                                 codemap::mk_sp(s.lo, b.span.lo),
146                                 &b)
147             }
148             visit::FnKind::Method(ident, sig, vis, b) => {
149                 block = b;
150                 self.rewrite_fn(indent,
151                                 ident,
152                                 fd,
153                                 &sig.generics,
154                                 sig.unsafety,
155                                 sig.constness.node,
156                                 defaultness,
157                                 sig.abi,
158                                 vis.unwrap_or(&ast::Visibility::Inherited),
159                                 codemap::mk_sp(s.lo, b.span.lo),
160                                 &b)
161             }
162             visit::FnKind::Closure(_) => unreachable!(),
163         };
164
165         if let Some(fn_str) = rewrite {
166             self.format_missing_with_indent(source!(self, s).lo);
167             self.buffer.push_str(&fn_str);
168             if let Some(c) = fn_str.chars().last() {
169                 if c == '}' {
170                     self.last_pos = source!(self, block.span).hi;
171                     return;
172                 }
173             }
174         } else {
175             self.format_missing(source!(self, block.span).lo);
176         }
177
178         self.last_pos = source!(self, block.span).lo;
179         self.visit_block(block)
180     }
181
182     pub fn visit_item(&mut self, item: &ast::Item) {
183         // This is where we bail out if there is a skip attribute. This is only
184         // complex in the module case. It is complex because the module could be
185         // in a separate file and there might be attributes in both files, but
186         // the AST lumps them all together.
187         match item.node {
188             ast::ItemKind::Mod(ref m) => {
189                 let outer_file = self.codemap.lookup_char_pos(item.span.lo).file;
190                 let inner_file = self.codemap.lookup_char_pos(m.inner.lo).file;
191                 if outer_file.name == inner_file.name {
192                     // Module is inline, in this case we treat modules like any
193                     // other item.
194                     if self.visit_attrs(&item.attrs) {
195                         self.push_rewrite(item.span, None);
196                         return;
197                     }
198                 } else if utils::contains_skip(&item.attrs) {
199                     // Module is not inline, but should be skipped.
200                     return;
201                 } else {
202                     // Module is not inline and should not be skipped. We want
203                     // to process only the attributes in the current file.
204                     let attrs = item.attrs
205                         .iter()
206                         .filter_map(|a| {
207                             let attr_file = self.codemap.lookup_char_pos(a.span.lo).file;
208                             if attr_file.name == outer_file.name {
209                                 Some(a.clone())
210                             } else {
211                                 None
212                             }
213                         })
214                         .collect::<Vec<_>>();
215                     // Assert because if we should skip it should be caught by
216                     // the above case.
217                     assert!(!self.visit_attrs(&attrs));
218                 }
219             }
220             _ => {
221                 if self.visit_attrs(&item.attrs) {
222                     self.push_rewrite(item.span, None);
223                     return;
224                 }
225             }
226         }
227
228         match item.node {
229             ast::ItemKind::Use(ref vp) => {
230                 self.format_import(&item.vis, vp, item.span);
231             }
232             ast::ItemKind::Impl(..) => {
233                 self.format_missing_with_indent(source!(self, item.span).lo);
234                 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
235                     self.buffer.push_str(&impl_str);
236                     self.last_pos = source!(self, item.span).hi;
237                 }
238             }
239             ast::ItemKind::Trait(..) => {
240                 self.format_missing_with_indent(item.span.lo);
241                 if let Some(trait_str) = format_trait(&self.get_context(),
242                                                       item,
243                                                       self.block_indent) {
244                     self.buffer.push_str(&trait_str);
245                     self.last_pos = source!(self, item.span).hi;
246                 }
247             }
248             ast::ItemKind::ExternCrate(_) => {
249                 self.format_missing_with_indent(source!(self, item.span).lo);
250                 let new_str = self.snippet(item.span);
251                 self.buffer.push_str(&new_str);
252                 self.last_pos = source!(self, item.span).hi;
253             }
254             ast::ItemKind::Struct(ref def, ref generics) => {
255                 let rewrite = {
256                     let indent = self.block_indent;
257                     let context = self.get_context();
258                     ::items::format_struct(&context,
259                                            "struct ",
260                                            item.ident,
261                                            &item.vis,
262                                            def,
263                                            Some(generics),
264                                            item.span,
265                                            indent,
266                                            None)
267                             .map(|s| match *def {
268                                      ast::VariantData::Tuple(..) => s + ";",
269                                      _ => s,
270                                  })
271                 };
272                 self.push_rewrite(item.span, rewrite);
273             }
274             ast::ItemKind::Enum(ref def, ref generics) => {
275                 self.format_missing_with_indent(source!(self, item.span).lo);
276                 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
277                 self.last_pos = source!(self, item.span).hi;
278             }
279             ast::ItemKind::Mod(ref module) => {
280                 self.format_missing_with_indent(source!(self, item.span).lo);
281                 self.format_mod(module, &item.vis, item.span, item.ident);
282             }
283             ast::ItemKind::Mac(ref mac) => {
284                 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
285             }
286             ast::ItemKind::ForeignMod(ref foreign_mod) => {
287                 self.format_missing_with_indent(source!(self, item.span).lo);
288                 self.format_foreign_mod(foreign_mod, item.span);
289             }
290             ast::ItemKind::Static(ref ty, mutability, ref expr) => {
291                 let rewrite = rewrite_static("static",
292                                              &item.vis,
293                                              item.ident,
294                                              ty,
295                                              mutability,
296                                              Some(expr),
297                                              self.block_indent,
298                                              &self.get_context());
299                 self.push_rewrite(item.span, rewrite);
300             }
301             ast::ItemKind::Const(ref ty, ref expr) => {
302                 let rewrite = rewrite_static("const",
303                                              &item.vis,
304                                              item.ident,
305                                              ty,
306                                              ast::Mutability::Immutable,
307                                              Some(expr),
308                                              self.block_indent,
309                                              &self.get_context());
310                 self.push_rewrite(item.span, rewrite);
311             }
312             ast::ItemKind::DefaultImpl(..) => {
313                 // FIXME(#78): format impl definitions.
314             }
315             ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
316                 self.visit_fn(visit::FnKind::ItemFn(item.ident,
317                                                     generics,
318                                                     unsafety,
319                                                     constness,
320                                                     abi,
321                                                     &item.vis,
322                                                     body),
323                               decl,
324                               item.span,
325                               item.id,
326                               ast::Defaultness::Final)
327             }
328             ast::ItemKind::Ty(ref ty, ref generics) => {
329                 let rewrite = rewrite_type_alias(&self.get_context(),
330                                                  self.block_indent,
331                                                  item.ident,
332                                                  ty,
333                                                  generics,
334                                                  &item.vis,
335                                                  item.span);
336                 self.push_rewrite(item.span, rewrite);
337             }
338             ast::ItemKind::Union(..) => {
339                 // FIXME(#1157): format union definitions.
340             }
341         }
342     }
343
344     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
345         if self.visit_attrs(&ti.attrs) {
346             self.push_rewrite(ti.span, None);
347             return;
348         }
349
350         match ti.node {
351             ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
352                 let rewrite = rewrite_static("const",
353                                              &ast::Visibility::Inherited,
354                                              ti.ident,
355                                              ty,
356                                              ast::Mutability::Immutable,
357                                              expr_opt.as_ref(),
358                                              self.block_indent,
359                                              &self.get_context());
360                 self.push_rewrite(ti.span, rewrite);
361             }
362             ast::TraitItemKind::Method(ref sig, None) => {
363                 let indent = self.block_indent;
364                 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
365                 self.push_rewrite(ti.span, rewrite);
366             }
367             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
368                 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None, body),
369                               &sig.decl,
370                               ti.span,
371                               ti.id,
372                               ast::Defaultness::Final);
373             }
374             ast::TraitItemKind::Type(ref type_param_bounds, _) => {
375                 let rewrite = rewrite_associated_type(ti.ident,
376                                                       None,
377                                                       Some(type_param_bounds),
378                                                       &self.get_context(),
379                                                       self.block_indent);
380                 self.push_rewrite(ti.span, rewrite);
381             }
382             ast::TraitItemKind::Macro(..) => {
383                 // FIXME(#1158) Macros in trait item position
384             }
385         }
386     }
387
388     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
389         if self.visit_attrs(&ii.attrs) {
390             self.push_rewrite(ii.span, None);
391             return;
392         }
393
394         match ii.node {
395             ast::ImplItemKind::Method(ref sig, ref body) => {
396                 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
397                               &sig.decl,
398                               ii.span,
399                               ii.id,
400                               ii.defaultness);
401             }
402             ast::ImplItemKind::Const(ref ty, ref expr) => {
403                 let rewrite = rewrite_static("const",
404                                              &ii.vis,
405                                              ii.ident,
406                                              ty,
407                                              ast::Mutability::Immutable,
408                                              Some(expr),
409                                              self.block_indent,
410                                              &self.get_context());
411                 self.push_rewrite(ii.span, rewrite);
412             }
413             ast::ImplItemKind::Type(ref ty) => {
414                 let rewrite = rewrite_associated_type(ii.ident,
415                                                       Some(ty),
416                                                       None,
417                                                       &self.get_context(),
418                                                       self.block_indent);
419                 self.push_rewrite(ii.span, rewrite);
420             }
421             ast::ImplItemKind::Macro(ref mac) => {
422                 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
423             }
424         }
425     }
426
427     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
428         // 1 = ;
429         let width = self.config.max_width - self.block_indent.width() - 1;
430         let rewrite = rewrite_macro(mac,
431                                     ident,
432                                     &self.get_context(),
433                                     Shape::legacy(width, self.block_indent),
434                                     pos);
435         self.push_rewrite(mac.span, rewrite);
436     }
437
438     fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
439         self.format_missing_with_indent(source!(self, span).lo);
440         let result = rewrite.unwrap_or_else(|| self.snippet(span));
441         self.buffer.push_str(&result);
442         self.last_pos = source!(self, span).hi;
443     }
444
445     pub fn from_codemap(parse_session: &'a ParseSess, config: &'a Config) -> FmtVisitor<'a> {
446         FmtVisitor {
447             parse_session: parse_session,
448             codemap: parse_session.codemap(),
449             buffer: StringBuffer::new(),
450             last_pos: BytePos(0),
451             block_indent: Indent {
452                 block_indent: 0,
453                 alignment: 0,
454             },
455             config: config,
456         }
457     }
458
459     pub fn snippet(&self, span: Span) -> String {
460         match self.codemap.span_to_snippet(span) {
461             Ok(s) => s,
462             Err(_) => {
463                 println!("Couldn't make snippet for span {:?}->{:?}",
464                          self.codemap.lookup_char_pos(span.lo),
465                          self.codemap.lookup_char_pos(span.hi));
466                 "".to_owned()
467             }
468         }
469     }
470
471     // Returns true if we should skip the following item.
472     pub fn visit_attrs(&mut self, attrs: &[ast::Attribute]) -> bool {
473         if utils::contains_skip(attrs) {
474             return true;
475         }
476
477         let outers: Vec<_> = attrs.iter()
478             .filter(|a| a.style == ast::AttrStyle::Outer)
479             .cloned()
480             .collect();
481         if outers.is_empty() {
482             return false;
483         }
484
485         let first = &outers[0];
486         self.format_missing_with_indent(source!(self, first.span).lo);
487
488         let rewrite = outers.rewrite(&self.get_context(),
489                                      Shape::legacy(self.config.max_width -
490                                                    self.block_indent.width(),
491                                                    self.block_indent))
492             .unwrap();
493         self.buffer.push_str(&rewrite);
494         let last = outers.last().unwrap();
495         self.last_pos = source!(self, last.span).hi;
496         false
497     }
498
499     fn walk_mod_items(&mut self, m: &ast::Mod) {
500         let mut items_left: &[ptr::P<ast::Item>] = &m.items;
501         while !items_left.is_empty() {
502             // If the next item is a `use` declaration, then extract it and any subsequent `use`s
503             // to be potentially reordered within `format_imports`. Otherwise, just format the
504             // next item for output.
505             if self.config.reorder_imports && is_use_item(&*items_left[0]) {
506                 let use_item_length =
507                     items_left.iter().take_while(|ppi| is_use_item(&***ppi)).count();
508                 let (use_items, rest) = items_left.split_at(use_item_length);
509                 self.format_imports(use_items);
510                 items_left = rest;
511             } else {
512                 // `unwrap()` is safe here because we know `items_left`
513                 // has elements from the loop condition
514                 let (item, rest) = items_left.split_first().unwrap();
515                 self.visit_item(item);
516                 items_left = rest;
517             }
518         }
519     }
520
521     fn format_mod(&mut self, m: &ast::Mod, vis: &ast::Visibility, s: Span, ident: ast::Ident) {
522         // Decide whether this is an inline mod or an external mod.
523         let local_file_name = self.codemap.span_to_filename(s);
524         let inner_span = source!(self, m.inner);
525         let is_internal = !(inner_span.lo.0 == 0 && inner_span.hi.0 == 0) &&
526                           local_file_name == self.codemap.span_to_filename(inner_span);
527
528         self.buffer.push_str(&*utils::format_visibility(vis));
529         self.buffer.push_str("mod ");
530         self.buffer.push_str(&ident.to_string());
531
532         if is_internal {
533             self.buffer.push_str(" {");
534             // Hackery to account for the closing }.
535             let mod_lo = self.codemap.span_after(source!(self, s), "{");
536             let body_snippet =
537                 self.snippet(codemap::mk_sp(mod_lo, source!(self, m.inner).hi - BytePos(1)));
538             let body_snippet = body_snippet.trim();
539             if body_snippet.is_empty() {
540                 self.buffer.push_str("}");
541             } else {
542                 self.last_pos = mod_lo;
543                 self.block_indent = self.block_indent.block_indent(self.config);
544                 self.walk_mod_items(m);
545                 self.format_missing_with_indent(source!(self, m.inner).hi - BytePos(1));
546                 self.close_block();
547             }
548             self.last_pos = source!(self, m.inner).hi;
549         } else {
550             self.buffer.push_str(";");
551             self.last_pos = source!(self, s).hi;
552         }
553     }
554
555     pub fn format_separate_mod(&mut self, m: &ast::Mod) {
556         let filemap = self.codemap.lookup_char_pos(m.inner.lo).file;
557         self.last_pos = filemap.start_pos;
558         self.block_indent = Indent::empty();
559         self.walk_mod_items(m);
560         self.format_missing_with_indent(filemap.end_pos);
561     }
562
563     pub fn get_context(&self) -> RewriteContext {
564         RewriteContext {
565             parse_session: self.parse_session,
566             codemap: self.codemap,
567             config: self.config,
568         }
569     }
570 }
571
572 impl<'a> Rewrite for [ast::Attribute] {
573     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
574         let mut result = String::new();
575         if self.is_empty() {
576             return Some(result);
577         }
578         let indent = shape.indent.to_string(context.config);
579
580         for (i, a) in self.iter().enumerate() {
581             let mut a_str = context.snippet(a.span);
582
583             // Write comments and blank lines between attributes.
584             if i > 0 {
585                 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
586                 // This particular horror show is to preserve line breaks in between doc
587                 // comments. An alternative would be to force such line breaks to start
588                 // with the usual doc comment token.
589                 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
590                 let comment = comment.trim();
591                 if !comment.is_empty() {
592                     let comment = try_opt!(rewrite_comment(comment,
593                                                            false,
594                                                            Shape::legacy(context.config
595                                                                              .ideal_width -
596                                                                          shape.indent.width(),
597                                                                          shape.indent),
598                                                            context.config));
599                     result.push_str(&indent);
600                     result.push_str(&comment);
601                     result.push('\n');
602                 } else if multi_line {
603                     result.push('\n');
604                 }
605                 result.push_str(&indent);
606             }
607
608             if a_str.starts_with("//") {
609                 a_str = try_opt!(rewrite_comment(&a_str,
610                                                  false,
611                                                  Shape::legacy(context.config.ideal_width -
612                                                                shape.indent.width(),
613                                                                shape.indent),
614                                                  context.config));
615             }
616
617             // Write the attribute itself.
618             result.push_str(&a_str);
619
620             if i < self.len() - 1 {
621                 result.push('\n');
622             }
623         }
624
625         Some(result)
626     }
627 }