]> git.lizzy.rs Git - rust.git/blob - src/missed_spans.rs
Catch attributes before comments
[rust.git] / src / missed_spans.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 config::WriteMode;
12 use visitor::FmtVisitor;
13 use syntax::codemap::{self, BytePos, Span, Pos};
14 use comment::{CodeCharKind, CommentCodeSlices, rewrite_comment};
15
16 impl<'a> FmtVisitor<'a> {
17     fn output_at_start(&self) -> bool {
18         self.buffer.len == 0
19     }
20
21     // TODO these format_missing methods are ugly. Refactor and add unit tests
22     // for the central whitespace stripping loop.
23     pub fn format_missing(&mut self, end: BytePos) {
24         self.format_missing_inner(end,
25                                   |this, last_snippet, _| this.buffer.push_str(last_snippet))
26     }
27
28     pub fn format_missing_with_indent(&mut self, end: BytePos) {
29         let config = self.config;
30         self.format_missing_inner(end, |this, last_snippet, snippet| {
31             this.buffer.push_str(last_snippet.trim_right());
32             if last_snippet == snippet && !this.output_at_start() {
33                 // No new lines in the snippet.
34                 this.buffer.push_str("\n");
35             }
36             let indent = this.block_indent.to_string(config);
37             this.buffer.push_str(&indent);
38         })
39     }
40
41     pub fn format_missing_no_indent(&mut self, end: BytePos) {
42         self.format_missing_inner(end, |this, last_snippet, _| {
43             this.buffer.push_str(last_snippet.trim_right());
44         })
45     }
46
47     fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, &str)>(&mut self,
48                                                                 end: BytePos,
49                                                                 process_last_snippet: F) {
50         let start = self.last_pos;
51
52         if start == end {
53             // Do nothing if this is the beginning of the file.
54             if !self.output_at_start() {
55                 process_last_snippet(self, "", "");
56             }
57             return;
58         }
59
60         assert!(start < end,
61                 "Request to format inverted span: {:?} to {:?}",
62                 self.codemap.lookup_char_pos(start),
63                 self.codemap.lookup_char_pos(end));
64
65         self.last_pos = end;
66         let span = codemap::mk_sp(start, end);
67
68         self.write_snippet(span, &process_last_snippet);
69     }
70
71     fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
72         where F: Fn(&mut FmtVisitor, &str, &str)
73     {
74         // Get a snippet from the file start to the span's hi without allocating.
75         // We need it to determine what precedes the current comment. If the comment
76         // follows code on the same line, we won't touch it.
77         let big_span_lo = self.codemap.lookup_char_pos(span.lo).file.start_pos;
78         let local_begin = self.codemap.lookup_byte_offset(big_span_lo);
79         let local_end = self.codemap.lookup_byte_offset(span.hi);
80         let start_index = local_begin.pos.to_usize();
81         let end_index = local_end.pos.to_usize();
82         let big_snippet = &local_begin.fm.src.as_ref().unwrap()[start_index..end_index];
83
84         let big_diff = (span.lo - big_span_lo).to_usize();
85         let snippet = self.snippet(span);
86
87         debug!("write_snippet `{}`", snippet);
88
89         self.write_snippet_inner(big_snippet, big_diff, &snippet, process_last_snippet);
90     }
91
92     fn write_snippet_inner<F>(&mut self,
93                               big_snippet: &str,
94                               big_diff: usize,
95                               old_snippet: &str,
96                               process_last_snippet: F)
97         where F: Fn(&mut FmtVisitor, &str, &str)
98     {
99         // Trim whitespace from the right hand side of each line.
100         // Annoyingly, the library functions for splitting by lines etc. are not
101         // quite right, so we must do it ourselves.
102         let mut line_start = 0;
103         let mut last_wspace = None;
104         let mut rewrite_next_comment = true;
105
106         fn replace_chars(string: &str) -> String {
107             string.chars()
108                 .map(|ch| if ch.is_whitespace() { ch } else { 'X' })
109                 .collect()
110         }
111
112         let replaced = match self.config.write_mode {
113             WriteMode::Coverage => replace_chars(old_snippet),
114             _ => old_snippet.to_owned(),
115         };
116         let snippet = &*replaced;
117
118         for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
119             debug!("{:?}: {:?}", kind, subslice);
120
121             if let CodeCharKind::Comment = kind {
122                 let last_char = big_snippet[..(offset + big_diff)]
123                     .chars()
124                     .rev()
125                     .skip_while(|rev_c| [' ', '\t'].contains(rev_c))
126                     .next();
127
128                 let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
129
130                 if rewrite_next_comment {
131                     if fix_indent {
132                         if let Some('{') = last_char {
133                             self.buffer.push_str("\n");
134                         }
135                         self.buffer.push_str(&self.block_indent.to_string(self.config));
136                     } else {
137                         self.buffer.push_str(" ");
138                     }
139
140                     let comment_width = ::std::cmp::min(self.config.ideal_width,
141                                                         self.config.max_width -
142                                                         self.block_indent.width());
143
144                     self.buffer.push_str(&rewrite_comment(subslice,
145                                                           false,
146                                                           comment_width,
147                                                           self.block_indent,
148                                                           self.config)
149                         .unwrap());
150
151                     last_wspace = None;
152                     line_start = offset + subslice.len();
153
154                     if let Some('/') = subslice.chars().skip(1).next() {
155                         // check that there are no contained block comments
156                         if !subslice.split('\n')
157                             .map(|s| s.trim_left())
158                             .any(|s| s.len() > 2 && &s[0..2] == "/*") {
159                             // Add a newline after line comments
160                             self.buffer.push_str("\n");
161                         }
162                     } else if line_start <= snippet.len() {
163                         // For other comments add a newline if there isn't one at the end already
164                         match snippet[line_start..].chars().next() {
165                             Some('\n') | Some('\r') => (),
166                             _ => self.buffer.push_str("\n"),
167                         }
168                     }
169
170                     continue;
171                 } else {
172                     rewrite_next_comment = false;
173                 }
174             }
175
176             for (mut i, c) in subslice.char_indices() {
177                 i += offset;
178
179                 if c == '\n' {
180                     if let Some(lw) = last_wspace {
181                         self.buffer.push_str(&snippet[line_start..lw]);
182                         self.buffer.push_str("\n");
183                     } else {
184                         self.buffer.push_str(&snippet[line_start..i + 1]);
185                     }
186
187                     line_start = i + 1;
188                     last_wspace = None;
189                     rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
190                 } else if c.is_whitespace() {
191                     if last_wspace.is_none() {
192                         last_wspace = Some(i);
193                     }
194                 } else if c == ';' {
195                     if last_wspace.is_some() {
196                         line_start = i;
197                     }
198
199                     rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
200                     last_wspace = None;
201                 } else {
202                     rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
203                     last_wspace = None;
204                 }
205             }
206
207             let remaining = snippet[line_start..subslice.len() + offset].trim();
208             if !remaining.is_empty() {
209                 self.buffer.push_str(remaining);
210                 line_start = subslice.len() + offset;
211                 rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
212             }
213         }
214
215         process_last_snippet(self, &snippet[line_start..], snippet);
216     }
217 }