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