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