]> git.lizzy.rs Git - rust.git/blob - src/visitor.rs
Handle pub(restricted) (#1013)
[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                                            None)
272                         .map(|s| {
273                             match *def {
274                                 ast::VariantData::Tuple(..) => s + ";",
275                                 _ => s,
276                             }
277                         })
278                 };
279                 self.push_rewrite(item.span, rewrite);
280             }
281             ast::ItemKind::Enum(ref def, ref generics) => {
282                 self.format_missing_with_indent(source!(self, item.span).lo);
283                 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
284                 self.last_pos = source!(self, item.span).hi;
285             }
286             ast::ItemKind::Mod(ref module) => {
287                 self.format_missing_with_indent(source!(self, item.span).lo);
288                 self.format_mod(module, &item.vis, item.span, item.ident);
289             }
290             ast::ItemKind::Mac(ref mac) => {
291                 self.format_missing_with_indent(source!(self, item.span).lo);
292                 self.visit_mac(mac, Some(item.ident));
293             }
294             ast::ItemKind::ForeignMod(ref foreign_mod) => {
295                 self.format_missing_with_indent(source!(self, item.span).lo);
296                 self.format_foreign_mod(foreign_mod, item.span);
297             }
298             ast::ItemKind::Static(ref ty, mutability, ref expr) => {
299                 let rewrite = rewrite_static("static",
300                                              &item.vis,
301                                              item.ident,
302                                              ty,
303                                              mutability,
304                                              Some(expr),
305                                              &self.get_context());
306                 self.push_rewrite(item.span, rewrite);
307             }
308             ast::ItemKind::Const(ref ty, ref expr) => {
309                 let rewrite = rewrite_static("const",
310                                              &item.vis,
311                                              item.ident,
312                                              ty,
313                                              ast::Mutability::Immutable,
314                                              Some(expr),
315                                              &self.get_context());
316                 self.push_rewrite(item.span, rewrite);
317             }
318             ast::ItemKind::DefaultImpl(..) => {
319                 // FIXME(#78): format impl definitions.
320             }
321             ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
322                 self.visit_fn(visit::FnKind::ItemFn(item.ident,
323                                                     generics,
324                                                     unsafety,
325                                                     constness,
326                                                     abi,
327                                                     &item.vis),
328                               decl,
329                               body,
330                               item.span,
331                               item.id)
332             }
333             ast::ItemKind::Ty(ref ty, ref generics) => {
334                 let rewrite = rewrite_type_alias(&self.get_context(),
335                                                  self.block_indent,
336                                                  item.ident,
337                                                  ty,
338                                                  generics,
339                                                  &item.vis,
340                                                  item.span);
341                 self.push_rewrite(item.span, rewrite);
342             }
343         }
344     }
345
346     pub fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
347         if self.visit_attrs(&ti.attrs) {
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.get_context());
360                 self.push_rewrite(ti.span, rewrite);
361             }
362             ast::TraitItemKind::Method(ref sig, None) => {
363                 let indent = self.block_indent;
364                 let rewrite = self.rewrite_required_fn(indent, ti.ident, sig, ti.span);
365                 self.push_rewrite(ti.span, rewrite);
366             }
367             ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
368                 self.visit_fn(visit::FnKind::Method(ti.ident, sig, None),
369                               &sig.decl,
370                               &body,
371                               ti.span,
372                               ti.id);
373             }
374             ast::TraitItemKind::Type(ref type_param_bounds, _) => {
375                 let rewrite = rewrite_associated_type(ti.ident,
376                                                       None,
377                                                       Some(type_param_bounds),
378                                                       &self.get_context(),
379                                                       self.block_indent);
380                 self.push_rewrite(ti.span, rewrite);
381             }
382         }
383     }
384
385     pub fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
386         if self.visit_attrs(&ii.attrs) {
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)),
393                               &sig.decl,
394                               body,
395                               ii.span,
396                               ii.id);
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.format_missing_with_indent(source!(self, ii.span).lo);
418                 self.visit_mac(mac, Some(ii.ident));
419             }
420         }
421     }
422
423     fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>) {
424         // 1 = ;
425         let width = self.config.max_width - self.block_indent.width() - 1;
426         let rewrite = rewrite_macro(mac, ident, &self.get_context(), width, self.block_indent);
427
428         if let Some(res) = rewrite {
429             self.buffer.push_str(&res);
430             self.last_pos = source!(self, mac.span).hi;
431         }
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.node.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         for item in &m.items {
496             self.visit_item(&item);
497         }
498     }
499
500     fn format_mod(&mut self, m: &ast::Mod, vis: &ast::Visibility, s: Span, ident: ast::Ident) {
501         // Decide whether this is an inline mod or an external mod.
502         let local_file_name = self.codemap.span_to_filename(s);
503         let is_internal = local_file_name == self.codemap.span_to_filename(source!(self, m.inner));
504
505         self.buffer.push_str(&*utils::format_visibility(vis));
506         self.buffer.push_str("mod ");
507         self.buffer.push_str(&ident.to_string());
508
509         if is_internal {
510             self.buffer.push_str(" {");
511             // Hackery to account for the closing }.
512             let mod_lo = self.codemap.span_after(source!(self, s), "{");
513             let body_snippet =
514                 self.snippet(codemap::mk_sp(mod_lo, source!(self, m.inner).hi - BytePos(1)));
515             let body_snippet = body_snippet.trim();
516             if body_snippet.is_empty() {
517                 self.buffer.push_str("}");
518             } else {
519                 self.last_pos = mod_lo;
520                 self.block_indent = self.block_indent.block_indent(self.config);
521                 self.walk_mod_items(m);
522                 self.format_missing_with_indent(source!(self, m.inner).hi - BytePos(1));
523                 self.close_block();
524             }
525             self.last_pos = source!(self, m.inner).hi;
526         } else {
527             self.buffer.push_str(";");
528             self.last_pos = source!(self, s).hi;
529         }
530     }
531
532     pub fn format_separate_mod(&mut self, m: &ast::Mod) {
533         let filemap = self.codemap.lookup_char_pos(source!(self, m.inner).lo).file;
534         self.last_pos = filemap.start_pos;
535         self.block_indent = Indent::empty();
536         self.walk_mod_items(m);
537         self.format_missing(filemap.end_pos);
538     }
539
540     fn format_import(&mut self, vis: &ast::Visibility, vp: &ast::ViewPath, span: Span) {
541         let vis = utils::format_visibility(vis);
542         let mut offset = self.block_indent;
543         offset.alignment += vis.len() + "use ".len();
544         // 1 = ";"
545         match vp.rewrite(&self.get_context(),
546                          self.config.max_width - offset.width() - 1,
547                          offset) {
548             Some(ref s) if s.is_empty() => {
549                 // Format up to last newline
550                 let prev_span = codemap::mk_sp(self.last_pos, source!(self, span).lo);
551                 let span_end = match self.snippet(prev_span).rfind('\n') {
552                     Some(offset) => self.last_pos + BytePos(offset as u32),
553                     None => source!(self, span).lo,
554                 };
555                 self.format_missing(span_end);
556                 self.last_pos = source!(self, span).hi;
557             }
558             Some(ref s) => {
559                 let s = format!("{}use {};", vis, s);
560                 self.format_missing_with_indent(source!(self, span).lo);
561                 self.buffer.push_str(&s);
562                 self.last_pos = source!(self, span).hi;
563             }
564             None => {
565                 self.format_missing_with_indent(source!(self, span).lo);
566                 self.format_missing(source!(self, span).hi);
567             }
568         }
569     }
570
571     pub fn get_context(&self) -> RewriteContext {
572         RewriteContext {
573             parse_session: self.parse_session,
574             codemap: self.codemap,
575             config: self.config,
576             block_indent: self.block_indent,
577         }
578     }
579 }
580
581 impl<'a> Rewrite for [ast::Attribute] {
582     fn rewrite(&self, context: &RewriteContext, _: usize, offset: Indent) -> Option<String> {
583         let mut result = String::new();
584         if self.is_empty() {
585             return Some(result);
586         }
587         let indent = offset.to_string(context.config);
588
589         for (i, a) in self.iter().enumerate() {
590             let mut a_str = context.snippet(a.span);
591
592             // Write comments and blank lines between attributes.
593             if i > 0 {
594                 let comment = context.snippet(codemap::mk_sp(self[i - 1].span.hi, a.span.lo));
595                 // This particular horror show is to preserve line breaks in between doc
596                 // comments. An alternative would be to force such line breaks to start
597                 // with the usual doc comment token.
598                 let multi_line = a_str.starts_with("//") && comment.matches('\n').count() > 1;
599                 let comment = comment.trim();
600                 if !comment.is_empty() {
601                     let comment = try_opt!(rewrite_comment(comment,
602                                                            false,
603                                                            context.config.ideal_width -
604                                                            offset.width(),
605                                                            offset,
606                                                            context.config));
607                     result.push_str(&indent);
608                     result.push_str(&comment);
609                     result.push('\n');
610                 } else if multi_line {
611                     result.push('\n');
612                 }
613                 result.push_str(&indent);
614             }
615
616             if a_str.starts_with("//") {
617                 a_str = try_opt!(rewrite_comment(&a_str,
618                                                  false,
619                                                  context.config.ideal_width - offset.width(),
620                                                  offset,
621                                                  context.config));
622             }
623
624             // Write the attribute itself.
625             result.push_str(&a_str);
626
627             if i < self.len() - 1 {
628                 result.push('\n');
629             }
630         }
631
632         Some(result)
633     }
634 }