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