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