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