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