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