]> git.lizzy.rs Git - rust.git/blob - src/missed_spans.rs
Implement closing-block procedure without relying on missed_span module (#3691)
[rust.git] / src / missed_spans.rs
1 use syntax::source_map::{BytePos, Pos, Span};
2
3 use crate::comment::{is_last_comment_block, rewrite_comment, CodeCharKind, CommentCodeSlices};
4 use crate::config::file_lines::FileLines;
5 use crate::config::FileName;
6 use crate::coverage::transform_missing_snippet;
7 use crate::shape::{Indent, Shape};
8 use crate::source_map::LineRangeUtils;
9 use crate::utils::{count_lf_crlf, count_newlines, last_line_width, mk_sp};
10 use crate::visitor::FmtVisitor;
11
12 struct SnippetStatus {
13     /// An offset to the current line from the beginning of the original snippet.
14     line_start: usize,
15     /// A length of trailing whitespaces on the current line.
16     last_wspace: Option<usize>,
17     /// The current line number.
18     cur_line: usize,
19 }
20
21 impl SnippetStatus {
22     fn new(cur_line: usize) -> Self {
23         SnippetStatus {
24             line_start: 0,
25             last_wspace: None,
26             cur_line,
27         }
28     }
29 }
30
31 impl<'a> FmtVisitor<'a> {
32     fn output_at_start(&self) -> bool {
33         self.buffer.is_empty()
34     }
35
36     pub(crate) fn format_missing(&mut self, end: BytePos) {
37         // HACK(topecongiro): we use `format_missing()` to extract a missing comment between
38         // a macro (or similar) and a trailing semicolon. Here we just try to avoid calling
39         // `format_missing_inner` in the common case where there is no such comment.
40         // This is a hack, ideally we should fix a possible bug in `format_missing_inner`
41         // or refactor `visit_mac` and `rewrite_macro`, but this should suffice to fix the
42         // issue (#2727).
43         let missing_snippet = self.snippet(mk_sp(self.last_pos, end));
44         if missing_snippet.trim() == ";" {
45             self.push_str(";");
46             self.last_pos = end;
47             return;
48         }
49         self.format_missing_inner(end, |this, last_snippet, _| this.push_str(last_snippet))
50     }
51
52     pub(crate) 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_end());
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(crate) 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_end());
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.source_map.lookup_char_pos(start),
90             self.source_map.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.buffer.chars().rev().take_while(|c| *c == '\n').count();
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 write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
135     where
136         F: Fn(&mut FmtVisitor<'_>, &str, &str),
137     {
138         // Get a snippet from the file start to the span's hi without allocating.
139         // We need it to determine what precedes the current comment. If the comment
140         // follows code on the same line, we won't touch it.
141         let big_span_lo = self.source_map.lookup_char_pos(span.lo()).file.start_pos;
142         let local_begin = self.source_map.lookup_byte_offset(big_span_lo);
143         let local_end = self.source_map.lookup_byte_offset(span.hi());
144         let start_index = local_begin.pos.to_usize();
145         let end_index = local_end.pos.to_usize();
146         let big_snippet = &local_begin.sf.src.as_ref().unwrap()[start_index..end_index];
147
148         let big_diff = (span.lo() - big_span_lo).to_usize();
149         let snippet = self.snippet(span);
150
151         debug!("write_snippet `{}`", snippet);
152
153         self.write_snippet_inner(big_snippet, big_diff, snippet, span, process_last_snippet);
154     }
155
156     fn write_snippet_inner<F>(
157         &mut self,
158         big_snippet: &str,
159         big_diff: usize,
160         old_snippet: &str,
161         span: Span,
162         process_last_snippet: F,
163     ) where
164         F: Fn(&mut FmtVisitor<'_>, &str, &str),
165     {
166         // Trim whitespace from the right hand side of each line.
167         // Annoyingly, the library functions for splitting by lines etc. are not
168         // quite right, so we must do it ourselves.
169         let char_pos = self.source_map.lookup_char_pos(span.lo());
170         let file_name = &char_pos.file.name.clone().into();
171         let mut status = SnippetStatus::new(char_pos.line);
172
173         let snippet = &*transform_missing_snippet(self.config, old_snippet);
174
175         let slice_within_file_lines_range =
176             |file_lines: FileLines, cur_line, s| -> (usize, usize, bool) {
177                 let (lf_count, crlf_count) = count_lf_crlf(s);
178                 let newline_count = lf_count + crlf_count;
179                 let within_file_lines_range = file_lines.contains_range(
180                     file_name,
181                     cur_line,
182                     // if a newline character is at the end of the slice, then the number of
183                     // newlines needs to be decreased by 1 so that the range checked against
184                     // the file_lines is the visual range one would expect.
185                     cur_line + newline_count - if s.ends_with('\n') { 1 } else { 0 },
186                 );
187                 (lf_count, crlf_count, within_file_lines_range)
188             };
189         for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
190             debug!("{:?}: {:?}", kind, subslice);
191
192             let (lf_count, crlf_count, within_file_lines_range) =
193                 slice_within_file_lines_range(self.config.file_lines(), status.cur_line, subslice);
194             let newline_count = lf_count + crlf_count;
195             if CodeCharKind::Comment == kind && within_file_lines_range {
196                 // 1: comment.
197                 self.process_comment(
198                     &mut status,
199                     snippet,
200                     &big_snippet[..(offset + big_diff)],
201                     offset,
202                     subslice,
203                 );
204             } else if subslice.trim().is_empty() && newline_count > 0 && within_file_lines_range {
205                 // 2: blank lines.
206                 self.push_vertical_spaces(newline_count);
207                 status.cur_line += newline_count;
208                 status.line_start = offset + lf_count + crlf_count * 2;
209             } else {
210                 // 3: code which we failed to format or which is not within file-lines range.
211                 self.process_missing_code(&mut status, snippet, subslice, offset, file_name);
212             }
213         }
214
215         let last_snippet = &snippet[status.line_start..];
216         let (_, _, within_file_lines_range) =
217             slice_within_file_lines_range(self.config.file_lines(), status.cur_line, last_snippet);
218         if within_file_lines_range {
219             process_last_snippet(self, last_snippet, snippet);
220         } else {
221             // just append what's left
222             self.push_str(last_snippet);
223         }
224     }
225
226     fn process_comment(
227         &mut self,
228         status: &mut SnippetStatus,
229         snippet: &str,
230         big_snippet: &str,
231         offset: usize,
232         subslice: &str,
233     ) {
234         let last_char = big_snippet
235             .chars()
236             .rev()
237             .skip_while(|rev_c| [' ', '\t'].contains(rev_c))
238             .next();
239
240         let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
241
242         let comment_indent = if fix_indent {
243             if let Some('{') = last_char {
244                 self.push_str("\n");
245             }
246             let indent_str = self.block_indent.to_string(self.config);
247             self.push_str(&indent_str);
248             self.block_indent
249         } else {
250             self.push_str(" ");
251             Indent::from_width(self.config, last_line_width(&self.buffer))
252         };
253
254         let comment_width = ::std::cmp::min(
255             self.config.comment_width(),
256             self.config.max_width() - self.block_indent.width(),
257         );
258         let comment_shape = Shape::legacy(comment_width, comment_indent);
259         let comment_str = rewrite_comment(subslice, false, comment_shape, self.config)
260             .unwrap_or_else(|| String::from(subslice));
261         self.push_str(&comment_str);
262
263         status.last_wspace = None;
264         status.line_start = offset + subslice.len();
265
266         // Add a newline:
267         // - if there isn't one already
268         // - otherwise, only if the last line is a line comment
269         if status.line_start <= snippet.len() {
270             match snippet[status.line_start..]
271                 .chars()
272                 // skip trailing whitespaces
273                 .skip_while(|c| *c == ' ' || *c == '\t')
274                 .next()
275             {
276                 Some('\n') | Some('\r') => {
277                     if !is_last_comment_block(subslice) {
278                         self.push_str("\n");
279                     }
280                 }
281                 _ => self.push_str("\n"),
282             }
283         }
284
285         status.cur_line += count_newlines(subslice);
286     }
287
288     fn process_missing_code(
289         &mut self,
290         status: &mut SnippetStatus,
291         snippet: &str,
292         subslice: &str,
293         offset: usize,
294         file_name: &FileName,
295     ) {
296         for (mut i, c) in subslice.char_indices() {
297             i += offset;
298
299             if c == '\n' {
300                 let skip_this_line = !self
301                     .config
302                     .file_lines()
303                     .contains_line(file_name, status.cur_line);
304                 if skip_this_line {
305                     status.last_wspace = None;
306                 }
307
308                 if let Some(lw) = status.last_wspace {
309                     self.push_str(&snippet[status.line_start..lw]);
310                     self.push_str("\n");
311                     status.last_wspace = None;
312                 } else {
313                     self.push_str(&snippet[status.line_start..=i]);
314                 }
315
316                 status.cur_line += 1;
317                 status.line_start = i + 1;
318             } else if c.is_whitespace() && status.last_wspace.is_none() {
319                 status.last_wspace = Some(i);
320             } else {
321                 status.last_wspace = None;
322             }
323         }
324
325         let remaining = snippet[status.line_start..subslice.len() + offset].trim();
326         if !remaining.is_empty() {
327             self.push_str(remaining);
328             status.line_start = subslice.len() + offset;
329         }
330     }
331 }