]> git.lizzy.rs Git - rust.git/blob - src/missed_spans.rs
Merge pull request #2298 from davidalber/fix-2269
[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 std::borrow::Cow;
12 use std::iter::repeat;
13
14 use syntax::codemap::{BytePos, FileName, Pos, Span};
15
16 use codemap::LineRangeUtils;
17 use comment::{rewrite_comment, CodeCharKind, CommentCodeSlices};
18 use config::WriteMode;
19 use shape::{Indent, Shape};
20 use utils::{count_newlines, last_line_width, mk_sp};
21 use visitor::FmtVisitor;
22
23 struct SnippetStatus {
24     /// An offset to the current line from the beginnig of the original snippet.
25     line_start: usize,
26     /// A length of trailing whitespaces on the current line.
27     last_wspace: Option<usize>,
28     /// The current line number.
29     cur_line: usize,
30 }
31
32 impl SnippetStatus {
33     fn new(cur_line: usize) -> Self {
34         SnippetStatus {
35             line_start: 0,
36             last_wspace: None,
37             cur_line,
38         }
39     }
40 }
41
42 impl<'a> FmtVisitor<'a> {
43     fn output_at_start(&self) -> bool {
44         self.buffer.is_empty()
45     }
46
47     // TODO these format_missing methods are ugly. Refactor and add unit tests
48     // for the central whitespace stripping loop.
49     pub fn format_missing(&mut self, end: BytePos) {
50         self.format_missing_inner(end, |this, last_snippet, _| this.push_str(last_snippet))
51     }
52
53     pub fn format_missing_with_indent(&mut self, end: BytePos) {
54         let config = self.config;
55         self.format_missing_inner(end, |this, last_snippet, snippet| {
56             this.push_str(last_snippet.trim_right());
57             if last_snippet == snippet && !this.output_at_start() {
58                 // No new lines in the snippet.
59                 this.push_str("\n");
60             }
61             let indent = this.block_indent.to_string(config);
62             this.push_str(&indent);
63         })
64     }
65
66     pub fn format_missing_no_indent(&mut self, end: BytePos) {
67         self.format_missing_inner(end, |this, last_snippet, _| {
68             this.push_str(last_snippet.trim_right());
69         })
70     }
71
72     fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, &str)>(
73         &mut self,
74         end: BytePos,
75         process_last_snippet: F,
76     ) {
77         let start = self.last_pos;
78
79         if start == end {
80             // Do nothing if this is the beginning of the file.
81             if !self.output_at_start() {
82                 process_last_snippet(self, "", "");
83             }
84             return;
85         }
86
87         assert!(
88             start < end,
89             "Request to format inverted span: {:?} to {:?}",
90             self.codemap.lookup_char_pos(start),
91             self.codemap.lookup_char_pos(end)
92         );
93
94         self.last_pos = end;
95         let span = mk_sp(start, end);
96         let snippet = self.snippet(span);
97         if snippet.trim().is_empty() && !out_of_file_lines_range!(self, span) {
98             // Keep vertical spaces within range.
99             self.push_vertical_spaces(count_newlines(snippet));
100             process_last_snippet(self, "", snippet);
101         } else {
102             self.write_snippet(span, &process_last_snippet);
103         }
104     }
105
106     fn push_vertical_spaces(&mut self, mut newline_count: usize) {
107         // The buffer already has a trailing newline.
108         let offset = if self.buffer.ends_with('\n') { 0 } else { 1 };
109         let newline_upper_bound = self.config.blank_lines_upper_bound() + offset;
110         let newline_lower_bound = self.config.blank_lines_lower_bound() + offset;
111         if newline_count > newline_upper_bound {
112             newline_count = newline_upper_bound;
113         } else if newline_count < newline_lower_bound {
114             newline_count = newline_lower_bound;
115         }
116         let blank_lines: String = repeat('\n').take(newline_count).collect();
117         self.push_str(&blank_lines);
118     }
119
120     fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
121     where
122         F: Fn(&mut FmtVisitor, &str, &str),
123     {
124         // Get a snippet from the file start to the span's hi without allocating.
125         // We need it to determine what precedes the current comment. If the comment
126         // follows code on the same line, we won't touch it.
127         let big_span_lo = self.codemap.lookup_char_pos(span.lo()).file.start_pos;
128         let local_begin = self.codemap.lookup_byte_offset(big_span_lo);
129         let local_end = self.codemap.lookup_byte_offset(span.hi());
130         let start_index = local_begin.pos.to_usize();
131         let end_index = local_end.pos.to_usize();
132         let big_snippet = &local_begin.fm.src.as_ref().unwrap()[start_index..end_index];
133
134         let big_diff = (span.lo() - big_span_lo).to_usize();
135         let snippet = self.snippet(span);
136
137         debug!("write_snippet `{}`", snippet);
138
139         self.write_snippet_inner(big_snippet, big_diff, snippet, span, process_last_snippet);
140     }
141
142     fn write_snippet_inner<F>(
143         &mut self,
144         big_snippet: &str,
145         big_diff: usize,
146         old_snippet: &str,
147         span: Span,
148         process_last_snippet: F,
149     ) where
150         F: Fn(&mut FmtVisitor, &str, &str),
151     {
152         // Trim whitespace from the right hand side of each line.
153         // Annoyingly, the library functions for splitting by lines etc. are not
154         // quite right, so we must do it ourselves.
155         let char_pos = self.codemap.lookup_char_pos(span.lo());
156         let file_name = &char_pos.file.name;
157         let mut status = SnippetStatus::new(char_pos.line);
158
159         let snippet = &*match self.config.write_mode() {
160             WriteMode::Coverage => replace_chars(old_snippet),
161             _ => Cow::from(old_snippet),
162         };
163
164         for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
165             debug!("{:?}: {:?}", kind, subslice);
166
167             let newline_count = count_newlines(subslice);
168             let within_file_lines_range = self.config.file_lines().intersects_range(
169                 file_name,
170                 status.cur_line,
171                 status.cur_line + newline_count,
172             );
173
174             if CodeCharKind::Comment == kind && within_file_lines_range {
175                 // 1: comment.
176                 self.process_comment(
177                     &mut status,
178                     snippet,
179                     &big_snippet[..(offset + big_diff)],
180                     offset,
181                     subslice,
182                 );
183             } else if subslice.trim().is_empty() && newline_count > 0 && within_file_lines_range {
184                 // 2: blank lines.
185                 self.push_vertical_spaces(newline_count);
186                 status.cur_line += newline_count;
187                 status.line_start = offset + newline_count;
188             } else {
189                 // 3: code which we failed to format or which is not within file-lines range.
190                 self.process_missing_code(&mut status, snippet, subslice, offset, file_name);
191             }
192         }
193
194         process_last_snippet(self, &snippet[status.line_start..], snippet);
195     }
196
197     fn process_comment(
198         &mut self,
199         status: &mut SnippetStatus,
200         snippet: &str,
201         big_snippet: &str,
202         offset: usize,
203         subslice: &str,
204     ) {
205         let last_char = big_snippet
206             .chars()
207             .rev()
208             .skip_while(|rev_c| [' ', '\t'].contains(rev_c))
209             .next();
210
211         let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
212
213         let comment_indent = if fix_indent {
214             if let Some('{') = last_char {
215                 self.push_str("\n");
216             }
217             let indent_str = self.block_indent.to_string(self.config);
218             self.push_str(&indent_str);
219             self.block_indent
220         } else {
221             self.push_str(" ");
222             Indent::from_width(self.config, last_line_width(&self.buffer))
223         };
224
225         let comment_width = ::std::cmp::min(
226             self.config.comment_width(),
227             self.config.max_width() - self.block_indent.width(),
228         );
229         let comment_shape = Shape::legacy(comment_width, comment_indent);
230         let comment_str = rewrite_comment(subslice, false, comment_shape, self.config)
231             .unwrap_or_else(|| String::from(subslice));
232         self.push_str(&comment_str);
233
234         status.last_wspace = None;
235         status.line_start = offset + subslice.len();
236
237         if let Some('/') = subslice.chars().nth(1) {
238             // check that there are no contained block comments
239             if !subslice
240                 .split('\n')
241                 .map(|s| s.trim_left())
242                 .any(|s| s.len() >= 2 && &s[0..2] == "/*")
243             {
244                 // Add a newline after line comments
245                 self.push_str("\n");
246             }
247         } else if status.line_start <= snippet.len() {
248             // For other comments add a newline if there isn't one at the end already
249             match snippet[status.line_start..].chars().next() {
250                 Some('\n') | Some('\r') => (),
251                 _ => self.push_str("\n"),
252             }
253         }
254
255         status.cur_line += count_newlines(subslice);
256     }
257
258     fn process_missing_code(
259         &mut self,
260         status: &mut SnippetStatus,
261         snippet: &str,
262         subslice: &str,
263         offset: usize,
264         file_name: &FileName,
265     ) {
266         for (mut i, c) in subslice.char_indices() {
267             i += offset;
268
269             if c == '\n' {
270                 let skip_this_line = !self.config
271                     .file_lines()
272                     .contains_line(file_name, status.cur_line);
273                 if skip_this_line {
274                     status.last_wspace = None;
275                 }
276
277                 if let Some(lw) = status.last_wspace {
278                     self.push_str(&snippet[status.line_start..lw]);
279                     self.push_str("\n");
280                     status.last_wspace = None;
281                 } else {
282                     self.push_str(&snippet[status.line_start..i + 1]);
283                 }
284
285                 status.cur_line += 1;
286                 status.line_start = i + 1;
287             } else if c.is_whitespace() && status.last_wspace.is_none() {
288                 status.last_wspace = Some(i);
289             } else if c == ';' && status.last_wspace.is_some() {
290                 status.line_start = i;
291                 status.last_wspace = None;
292             } else {
293                 status.last_wspace = None;
294             }
295         }
296
297         let remaining = snippet[status.line_start..subslice.len() + offset].trim();
298         if !remaining.is_empty() {
299             self.push_str(remaining);
300             status.line_start = subslice.len() + offset;
301         }
302     }
303 }
304
305 fn replace_chars(string: &str) -> Cow<str> {
306     Cow::from(
307         string
308             .chars()
309             .map(|ch| if ch.is_whitespace() { ch } else { 'X' })
310             .collect::<String>(),
311     )
312 }