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