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