]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Merge pull request #1162 from sinkuu/fix1040
[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;
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;
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                                            self.config.max_width - self.block_indent.width(),
63                                            self.block_indent);
64
65                 self.push_rewrite(stmt.span, rewrite);
66             }
67             ast::StmtKind::Mac(ref mac) => {
68                 let (ref mac, _macro_style, _) = **mac;
69                 self.format_missing_with_indent(source!(self, stmt.span).lo);
70                 self.visit_mac(mac, None);
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                 b: &ast::Block,
129                 s: Span,
130                 _: ast::NodeId,
131                 defaultness: ast::Defaultness) {
132         let indent = self.block_indent;
133         let rewrite = match fk {
134             visit::FnKind::ItemFn(ident, generics, unsafety, constness, abi, vis) => {
135                 self.rewrite_fn(indent,
136                                 ident,
137                                 fd,
138                                 generics,
139                                 unsafety,
140                                 constness.node,
141                                 defaultness,
142                                 abi,
143                                 vis,
144                                 codemap::mk_sp(s.lo, b.span.lo),
145                                 b)
146             }
147             visit::FnKind::Method(ident, sig, vis) => {
148                 self.rewrite_fn(indent,
149                                 ident,
150                                 fd,
151                                 &sig.generics,
152                                 sig.unsafety,
153                                 sig.constness.node,
154                                 defaultness,
155                                 sig.abi,
156                                 vis.unwrap_or(&ast::Visibility::Inherited),
157                                 codemap::mk_sp(s.lo, b.span.lo),
158                                 b)
159             }
160             visit::FnKind::Closure => None,
161         };
162
163         if let Some(fn_str) = rewrite {
164             self.format_missing_with_indent(source!(self, s).lo);
165             self.buffer.push_str(&fn_str);
166             if let Some(c) = fn_str.chars().last() {
167                 if c == '}' {
168                     self.last_pos = source!(self, b.span).hi;
169                     return;
170                 }
171             }
172         } else {
173             self.format_missing(source!(self, b.span).lo);
174         }
175
176         self.last_pos = source!(self, b.span).lo;
177         self.visit_block(b)
178     }
179
180     pub fn visit_item(&mut self, item: &ast::Item) {
181         // This is where we bail out if there is a skip attribute. This is only
182         // complex in the module case. It is complex because the module could be
183         // in a seperate file and there might be attributes in both files, but
184         // the AST lumps them all together.
185         match item.node {
186             ast::ItemKind::Mod(ref m) => {
187                 let outer_file = self.codemap.lookup_char_pos(item.span.lo).file;
188                 let inner_file = self.codemap.lookup_char_pos(m.inner.lo).file;
189                 if outer_file.name == inner_file.name {
190                     // Module is inline, in this case we treat modules like any
191                     // other item.
192                     if self.visit_attrs(&item.attrs) {
193                         self.push_rewrite(item.span, None);
194                         return;
195                     }
196                 } else if utils::contains_skip(&item.attrs) {
197                     // Module is not inline, but should be skipped.
198                     return;
199                 } else {
200                     // Module is not inline and should not be skipped. We want
201                     // to process only the attributes in the current file.
202                     let attrs = item.attrs
203                         .iter()
204                         .filter_map(|a| {
205                             let attr_file = self.codemap.lookup_char_pos(a.span.lo).file;
206                             if attr_file.name == outer_file.name {
207                                 Some(a.clone())
208                             } else {
209                                 None
210                             }
211                         })
212                         .collect::<Vec<_>>();
213                     // Assert because if we should skip it should be caught by
214                     // the above case.
215                     assert!(!self.visit_attrs(&attrs));
216                 }
217             }
218             _ => {
219                 if self.visit_attrs(&item.attrs) {
220                     self.push_rewrite(item.span, None);
221                     return;
222                 }
223             }
224         }
225
226         match item.node {
227             ast::ItemKind::Use(ref vp) => {
228                 self.format_import(&item.vis, vp, item.span);
229             }
230             ast::ItemKind::Impl(..) => {
231                 self.format_missing_with_indent(source!(self, item.span).lo);
232                 if let Some(impl_str) = format_impl(&self.get_context(), item, self.block_indent) {
233                     self.buffer.push_str(&impl_str);
234                     self.last_pos = source!(self, item.span).hi;
235                 }
236             }
237             ast::ItemKind::Trait(..) => {
238                 self.format_missing_with_indent(item.span.lo);
239                 if let Some(trait_str) = format_trait(&self.get_context(),
240                                                       item,
241                                                       self.block_indent) {
242                     self.buffer.push_str(&trait_str);
243                     self.last_pos = source!(self, item.span).hi;
244                 }
245             }
246             ast::ItemKind::ExternCrate(_) => {
247                 self.format_missing_with_indent(source!(self, item.span).lo);
248                 let new_str = self.snippet(item.span);
249                 self.buffer.push_str(&new_str);
250                 self.last_pos = source!(self, item.span).hi;
251             }
252             ast::ItemKind::Struct(ref def, ref generics) => {
253                 let rewrite = {
254                     let indent = self.block_indent;
255                     let context = self.get_context();
256                     ::items::format_struct(&context,
257                                            "struct ",
258                                            item.ident,
259                                            &item.vis,
260                                            def,
261                                            Some(generics),
262                                            item.span,
263                                            indent,
264                                            None)
265                         .map(|s| {
266                             match *def {
267                                 ast::VariantData::Tuple(..) => s + ";",
268                                 _ => s,
269                             }
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.format_missing_with_indent(source!(self, item.span).lo);
285                 self.visit_mac(mac, Some(item.ident));
286             }
287             ast::ItemKind::ForeignMod(ref foreign_mod) => {
288                 self.format_missing_with_indent(source!(self, item.span).lo);
289                 self.format_foreign_mod(foreign_mod, item.span);
290             }
291             ast::ItemKind::Static(ref ty, mutability, ref expr) => {
292                 let rewrite = rewrite_static("static",
293                                              &item.vis,
294                                              item.ident,
295                                              ty,
296                                              mutability,
297                                              Some(expr),
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.get_context());
309                 self.push_rewrite(item.span, rewrite);
310             }
311             ast::ItemKind::DefaultImpl(..) => {
312                 // FIXME(#78): format impl definitions.
313             }
314             ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
315                 self.visit_fn(visit::FnKind::ItemFn(item.ident,
316                                                     generics,
317                                                     unsafety,
318                                                     constness,
319                                                     abi,
320                                                     &item.vis),
321                               decl,
322                               body,
323                               item.span,
324                               item.id,
325                               ast::Defaultness::Final)
326             }
327             ast::ItemKind::Ty(ref ty, ref generics) => {
328                 let rewrite = rewrite_type_alias(&self.get_context(),
329                                                  self.block_indent,
330                                                  item.ident,
331                                                  ty,
332                                                  generics,
333                                                  &item.vis,
334                                                  item.span);
335                 self.push_rewrite(item.span, rewrite);
336             }
337             ast::ItemKind::Union(..) => {
338                 // FIXME(#1157): format union definitions.
339             }
340         }
341     }
342
343     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
344         if self.visit_attrs(&ti.attrs) {
345             self.push_rewrite(ti.span, None);
346             return;
347         }
348
349         match ti.node {
350             ast::TraitItemKind::Const(ref ty, ref expr_opt) => {
351                 let rewrite = rewrite_static("const",
352                                              &ast::Visibility::Inherited,
353                                              ti.ident,
354                                              ty,
355                                              ast::Mutability::Immutable,
356                                              expr_opt.as_ref(),
357                                              &self.get_context());
358                 self.push_rewrite(ti.span, rewrite);
359             }
360             ast::TraitItemKind::Method(ref sig, None) => {
361                 let indent = self.block_indent;
362                 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
363                 self.push_rewrite(ti.span, rewrite);
364             }
365             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
366                 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
367                               &sig.decl,
368                               body,
369                               ti.span,
370                               ti.id,
371                               ast::Defaultness::Final);
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             ast::TraitItemKind::Macro(..) => {
382                 // FIXME(#1158) Macros in trait item position
383             }
384         }
385     }
386
387     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
388         if self.visit_attrs(&ii.attrs) {
389             self.push_rewrite(ii.span, None);
390             return;
391         }
392
393         match ii.node {
394             ast::ImplItemKind::Method(ref sig, ref body) => {
395                 self.visit_fn(visit::FnKind::Method(ii.ident, sig, Some(&ii.vis)),
396                               &sig.decl,
397                               body,
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.get_context());
410                 self.push_rewrite(ii.span, rewrite);
411             }
412             ast::ImplItemKind::Type(ref ty) => {
413                 let rewrite = rewrite_associated_type(ii.ident,
414                                                       Some(ty),
415                                                       None,
416                                                       &self.get_context(),
417                                                       self.block_indent);
418                 self.push_rewrite(ii.span, rewrite);
419             }
420             ast::ImplItemKind::Macro(ref mac) => {
421                 self.format_missing_with_indent(source!(self, ii.span).lo);
422                 self.visit_mac(mac, Some(ii.ident));
423             }
424         }
425     }
426
427     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>) {
428         // 1 = ;
429         let width = self.config.max_width - self.block_indent.width() - 1;
430         let rewrite = rewrite_macro(mac, ident, &self.get_context(), width, self.block_indent);
431
432         if let Some(res) = rewrite {
433             self.buffer.push_str(&res);
434             self.last_pos = source!(self, mac.span).hi;
435         }
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.node.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                      self.config.max_width - self.block_indent.width(),
490                      self.block_indent)
491             .unwrap();
492         self.buffer.push_str(&rewrite);
493         let last = outers.last().unwrap();
494         self.last_pos = source!(self, last.span).hi;
495         false
496     }
497
498     fn walk_mod_items(&mut self, m: &ast::Mod) {
499         let mut items_left: &[ptr::P<ast::Item>] = &m.items;
500         while !items_left.is_empty() {
501             // If the next item is a `use` declaration, then extract it and any subsequent `use`s
502             // to be potentially reordered within `format_imports`. Otherwise, just format the
503             // next item for output.
504             if self.config.reorder_imports && is_use_item(&*items_left[0]) {
505                 let use_item_length =
506                     items_left.iter().take_while(|ppi| is_use_item(&***ppi)).count();
507                 let (use_items, rest) = items_left.split_at(use_item_length);
508                 self.format_imports(use_items);
509                 items_left = rest;
510             } else {
511                 // `unwrap()` is safe here because we know `items_left`
512                 // has elements from the loop condition
513                 let (item, rest) = items_left.split_first().unwrap();
514                 self.visit_item(item);
515                 items_left = rest;
516             }
517         }
518     }
519
520     fn format_mod(&mut self, m: &ast::Mod, vis: &ast::Visibility, s: Span, ident: ast::Ident) {
521         // Decide whether this is an inline mod or an external mod.
522         let local_file_name = self.codemap.span_to_filename(s);
523         let is_internal = local_file_name == self.codemap.span_to_filename(source!(self, m.inner));
524
525         self.buffer.push_str(&*utils::format_visibility(vis));
526         self.buffer.push_str("mod ");
527         self.buffer.push_str(&ident.to_string());
528
529         if is_internal {
530             self.buffer.push_str(" {");
531             // Hackery to account for the closing }.
532             let mod_lo = self.codemap.span_after(source!(self, s), "{");
533             let body_snippet =
534                 self.snippet(codemap::mk_sp(mod_lo, source!(self, m.inner).hi - BytePos(1)));
535             let body_snippet = body_snippet.trim();
536             if body_snippet.is_empty() {
537                 self.buffer.push_str("}");
538             } else {
539                 self.last_pos = mod_lo;
540                 self.block_indent = self.block_indent.block_indent(self.config);
541                 self.walk_mod_items(m);
542                 self.format_missing_with_indent(source!(self, m.inner).hi - BytePos(1));
543                 self.close_block();
544             }
545             self.last_pos = source!(self, m.inner).hi;
546         } else {
547             self.buffer.push_str(";");
548             self.last_pos = source!(self, s).hi;
549         }
550     }
551
552     pub fn format_separate_mod(&mut self, m: &ast::Mod) {
553         let filemap = self.codemap.lookup_char_pos(source!(self, m.inner).lo).file;
554         self.last_pos = filemap.start_pos;
555         self.block_indent = Indent::empty();
556         self.walk_mod_items(m);
557         self.format_missing_with_indent(filemap.end_pos);
558     }
559
560     pub fn get_context(&self) -> RewriteContext {
561         RewriteContext {
562             parse_session: self.parse_session,
563             codemap: self.codemap,
564             config: self.config,
565             block_indent: self.block_indent,
566         }
567     }
568 }
569
570 impl<'a> Rewrite for [ast::Attribute] {
571     fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
572         let mut result = String::new();
573         if self.is_empty() {
574             return Some(result);
575         }
576         let indent = offset.to_string(context.config);
577
578         for (i, a) in self.iter().enumerate() {
579             let mut a_str = context.snippet(a.span);
580
581             // Write comments and blank lines between attributes.
582             if i > 0 {
583                 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
584                 // This particular horror show is to preserve line breaks in between doc
585                 // comments. An alternative would be to force such line breaks to start
586                 // with the usual doc comment token.
587                 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
588                 let comment = comment.trim();
589                 if !comment.is_empty() {
590                     let comment = try_opt!(rewrite_comment(comment,
591                                                            false,
592                                                            context.config.ideal_width -
593                                                            offset.width(),
594                                                            offset,
595                                                            context.config));
596                     result.push_str(&indent);
597                     result.push_str(&comment);
598                     result.push('\n');
599                 } else if multi_line {
600                     result.push('\n');
601                 }
602                 result.push_str(&indent);
603             }
604
605             if a_str.starts_with("//") {
606                 a_str = try_opt!(rewrite_comment(&a_str,
607                                                  false,
608                                                  context.config.ideal_width - offset.width(),
609                                                  offset,
610                                                  context.config));
611             }
612
613             // Write the attribute itself.
614             result.push_str(&a_str);
615
616             if i < self.len() - 1 {
617                 result.push('\n');
618             }
619         }
620
621         Some(result)
622     }
623 }