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