]> git.lizzy.rs Git - rust.git/blob - src/missed_spans.rs
Merge pull request #3240 from Xanewok/parser-panic
[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 beginning 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_end());
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_end());
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.buffer.chars().rev().take_while(|c| *c == '\n').count();
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 write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
146     where
147         F: Fn(&mut FmtVisitor, &str, &str),
148     {
149         // Get a snippet from the file start to the span's hi without allocating.
150         // We need it to determine what precedes the current comment. If the comment
151         // follows code on the same line, we won't touch it.
152         let big_span_lo = self.source_map.lookup_char_pos(span.lo()).file.start_pos;
153         let local_begin = self.source_map.lookup_byte_offset(big_span_lo);
154         let local_end = self.source_map.lookup_byte_offset(span.hi());
155         let start_index = local_begin.pos.to_usize();
156         let end_index = local_end.pos.to_usize();
157         let big_snippet = &local_begin.sf.src.as_ref().unwrap()[start_index..end_index];
158
159         let big_diff = (span.lo() - big_span_lo).to_usize();
160         let snippet = self.snippet(span);
161
162         debug!("write_snippet `{}`", snippet);
163
164         self.write_snippet_inner(big_snippet, big_diff, snippet, span, process_last_snippet);
165     }
166
167     fn write_snippet_inner<F>(
168         &mut self,
169         big_snippet: &str,
170         big_diff: usize,
171         old_snippet: &str,
172         span: Span,
173         process_last_snippet: F,
174     ) where
175         F: Fn(&mut FmtVisitor, &str, &str),
176     {
177         // Trim whitespace from the right hand side of each line.
178         // Annoyingly, the library functions for splitting by lines etc. are not
179         // quite right, so we must do it ourselves.
180         let char_pos = self.source_map.lookup_char_pos(span.lo());
181         let file_name = &char_pos.file.name.clone().into();
182         let mut status = SnippetStatus::new(char_pos.line);
183
184         let snippet = &*match self.config.emit_mode() {
185             EmitMode::Coverage => Cow::from(replace_chars(old_snippet)),
186             _ => Cow::from(old_snippet),
187         };
188
189         for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
190             debug!("{:?}: {:?}", kind, subslice);
191
192             let newline_count = count_newlines(subslice);
193             let within_file_lines_range = self.config.file_lines().contains_range(
194                 file_name,
195                 status.cur_line,
196                 status.cur_line + newline_count,
197             );
198
199             if CodeCharKind::Comment == kind && within_file_lines_range {
200                 // 1: comment.
201                 self.process_comment(
202                     &mut status,
203                     snippet,
204                     &big_snippet[..(offset + big_diff)],
205                     offset,
206                     subslice,
207                 );
208             } else if subslice.trim().is_empty() && newline_count > 0 && within_file_lines_range {
209                 // 2: blank lines.
210                 self.push_vertical_spaces(newline_count);
211                 status.cur_line += newline_count;
212                 status.line_start = offset + newline_count;
213             } else {
214                 // 3: code which we failed to format or which is not within file-lines range.
215                 self.process_missing_code(&mut status, snippet, subslice, offset, file_name);
216             }
217         }
218
219         process_last_snippet(self, &snippet[status.line_start..], snippet);
220     }
221
222     fn process_comment(
223         &mut self,
224         status: &mut SnippetStatus,
225         snippet: &str,
226         big_snippet: &str,
227         offset: usize,
228         subslice: &str,
229     ) {
230         let last_char = big_snippet
231             .chars()
232             .rev()
233             .skip_while(|rev_c| [' ', '\t'].contains(rev_c))
234             .next();
235
236         let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
237
238         let comment_indent = if fix_indent {
239             if let Some('{') = last_char {
240                 self.push_str("\n");
241             }
242             let indent_str = self.block_indent.to_string(self.config);
243             self.push_str(&indent_str);
244             self.block_indent
245         } else {
246             self.push_str(" ");
247             Indent::from_width(self.config, last_line_width(&self.buffer))
248         };
249
250         let comment_width = ::std::cmp::min(
251             self.config.comment_width(),
252             self.config.max_width() - self.block_indent.width(),
253         );
254         let comment_shape = Shape::legacy(comment_width, comment_indent);
255         let comment_str = rewrite_comment(subslice, false, comment_shape, self.config)
256             .unwrap_or_else(|| String::from(subslice));
257         self.push_str(&comment_str);
258
259         status.last_wspace = None;
260         status.line_start = offset + subslice.len();
261
262         // Add a newline:
263         // - if there isn't one already
264         // - otherwise, only if the last line is a line comment
265         if status.line_start <= snippet.len() {
266             match snippet[status.line_start..].chars().next() {
267                 Some('\n') | Some('\r') => {
268                     if !subslice.trim_end().ends_with("*/") {
269                         self.push_str("\n");
270                     }
271                 }
272                 _ => self.push_str("\n"),
273             }
274         }
275
276         status.cur_line += count_newlines(subslice);
277     }
278
279     fn process_missing_code(
280         &mut self,
281         status: &mut SnippetStatus,
282         snippet: &str,
283         subslice: &str,
284         offset: usize,
285         file_name: &FileName,
286     ) {
287         for (mut i, c) in subslice.char_indices() {
288             i += offset;
289
290             if c == '\n' {
291                 let skip_this_line = !self
292                     .config
293                     .file_lines()
294                     .contains_line(file_name, status.cur_line);
295                 if skip_this_line {
296                     status.last_wspace = None;
297                 }
298
299                 if let Some(lw) = status.last_wspace {
300                     self.push_str(&snippet[status.line_start..lw]);
301                     self.push_str("\n");
302                     status.last_wspace = None;
303                 } else {
304                     self.push_str(&snippet[status.line_start..=i]);
305                 }
306
307                 status.cur_line += 1;
308                 status.line_start = i + 1;
309             } else if c.is_whitespace() && status.last_wspace.is_none() {
310                 status.last_wspace = Some(i);
311             } else {
312                 status.last_wspace = None;
313             }
314         }
315
316         let remaining = snippet[status.line_start..subslice.len() + offset].trim();
317         if !remaining.is_empty() {
318             self.push_str(remaining);
319             status.line_start = subslice.len() + offset;
320         }
321     }
322 }
323
324 fn replace_chars(string: &str) -> String {
325     string
326         .chars()
327         .map(|ch| if ch.is_whitespace() { ch } else { 'X' })
328         .collect()
329 }