Skip to main content

rustfmt_nightly/
missed_spans.rs

1use rustc_span::{BytePos, Pos, Span};
2use tracing::debug;
3
4use crate::comment::{CodeCharKind, CommentCodeSlices, is_last_comment_block, rewrite_comment};
5use crate::config::FileName;
6use crate::config::StyleEdition;
7use crate::config::file_lines::FileLines;
8use crate::coverage::transform_missing_snippet;
9use crate::shape::{Indent, Shape};
10use crate::source_map::LineRangeUtils;
11use crate::utils::{count_lf_crlf, count_newlines, last_line_width, mk_sp};
12use crate::visitor::FmtVisitor;
13
14struct SnippetStatus {
15    /// An offset to the current line from the beginning of the original snippet.
16    line_start: usize,
17    /// A length of trailing whitespaces on the current line.
18    last_wspace: Option<usize>,
19    /// The current line number.
20    cur_line: usize,
21}
22
23impl SnippetStatus {
24    fn new(cur_line: usize) -> Self {
25        SnippetStatus {
26            line_start: 0,
27            last_wspace: None,
28            cur_line,
29        }
30    }
31}
32
33impl<'a> FmtVisitor<'a> {
34    fn output_at_start(&self) -> bool {
35        self.buffer.is_empty()
36    }
37
38    pub(crate) fn format_missing(&mut self, end: BytePos) {
39        // HACK(topecongiro): we use `format_missing()` to extract a missing comment between
40        // a macro (or similar) and a trailing semicolon. Here we just try to avoid calling
41        // `format_missing_inner` in the common case where there is no such comment.
42        // This is a hack, ideally we should fix a possible bug in `format_missing_inner`
43        // or refactor `visit_mac` and `rewrite_macro`, but this should suffice to fix the
44        // issue (#2727).
45        let missing_snippet = self.snippet(mk_sp(self.last_pos, end));
46        if missing_snippet.trim() == ";" {
47            self.push_str(";");
48            self.last_pos = end;
49            return;
50        }
51        self.format_missing_inner(end, |this, last_snippet, _| this.push_str(last_snippet))
52    }
53
54    pub(crate) fn format_missing_with_indent(&mut self, end: BytePos) {
55        self.format_missing_indent(end, true)
56    }
57
58    pub(crate) fn format_missing_no_indent(&mut self, end: BytePos) {
59        self.format_missing_indent(end, false)
60    }
61
62    fn format_missing_indent(&mut self, end: BytePos, should_indent: bool) {
63        let config = self.config;
64        self.format_missing_inner(end, |this, last_snippet, snippet| {
65            this.push_str(last_snippet.trim_end());
66            if last_snippet == snippet && !this.output_at_start() {
67                // No new lines in the snippet.
68                this.push_str("\n");
69            }
70            if should_indent {
71                let indent = this.block_indent.to_string(config);
72                this.push_str(&indent);
73            }
74        })
75    }
76
77    fn format_missing_inner<F: Fn(&mut FmtVisitor<'_>, &str, &str)>(
78        &mut self,
79        end: BytePos,
80        process_last_snippet: F,
81    ) {
82        let start = self.last_pos;
83
84        if start == end {
85            // Do nothing if this is the beginning of the file.
86            if !self.output_at_start() {
87                process_last_snippet(self, "", "");
88            }
89            return;
90        }
91
92        assert!(
93            start < end,
94            "Request to format inverted span: {}",
95            self.psess.span_to_debug_info(mk_sp(start, end)),
96        );
97
98        self.last_pos = end;
99        let span = mk_sp(start, end);
100        let snippet = self.snippet(span);
101
102        // Do nothing for spaces in the beginning of the file
103        if start == BytePos(0) && end.0 as usize == snippet.len() && snippet.trim().is_empty() {
104            return;
105        }
106
107        if snippet.trim().is_empty() && !out_of_file_lines_range!(self, span) {
108            // Keep vertical spaces within range.
109            self.push_vertical_spaces(count_newlines(snippet));
110            process_last_snippet(self, "", snippet);
111        } else {
112            self.write_snippet(span, &process_last_snippet);
113        }
114    }
115
116    fn push_vertical_spaces(&mut self, mut newline_count: usize) {
117        let offset = self.buffer.chars().rev().take_while(|c| *c == '\n').count();
118        let newline_upper_bound = self.config.blank_lines_upper_bound() + 1;
119        let newline_lower_bound = self.config.blank_lines_lower_bound() + 1;
120
121        if newline_count + offset > newline_upper_bound {
122            if offset >= newline_upper_bound {
123                newline_count = 0;
124            } else {
125                newline_count = newline_upper_bound - offset;
126            }
127        } else if newline_count + offset < newline_lower_bound {
128            if offset >= newline_lower_bound {
129                newline_count = 0;
130            } else {
131                newline_count = newline_lower_bound - offset;
132            }
133        }
134
135        let blank_lines = "\n".repeat(newline_count);
136        self.push_str(&blank_lines);
137    }
138
139    fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
140    where
141        F: Fn(&mut FmtVisitor<'_>, &str, &str),
142    {
143        // Get a snippet from the file start to the span's hi without allocating.
144        // We need it to determine what precedes the current comment. If the comment
145        // follows code on the same line, we won't touch it.
146        let big_span_lo = self.snippet_provider.start_pos();
147        let big_snippet = self.snippet_provider.entire_snippet();
148        let big_diff = (span.lo() - big_span_lo).to_usize();
149
150        let snippet = self.snippet(span);
151
152        debug!("write_snippet `{}`", snippet);
153
154        self.write_snippet_inner(big_snippet, snippet, big_diff, span, process_last_snippet);
155    }
156
157    fn write_snippet_inner<F>(
158        &mut self,
159        big_snippet: &str,
160        old_snippet: &str,
161        big_diff: usize,
162        span: Span,
163        process_last_snippet: F,
164    ) where
165        F: Fn(&mut FmtVisitor<'_>, &str, &str),
166    {
167        // Trim whitespace from the right hand side of each line.
168        // Annoyingly, the library functions for splitting by lines etc. are not
169        // quite right, so we must do it ourselves.
170        let line = self.psess.line_of_byte_pos(span.lo());
171        let file_name = &self.psess.span_to_filename(span);
172        let mut status = SnippetStatus::new(line);
173
174        let snippet = &*transform_missing_snippet(self.config, old_snippet);
175
176        let slice_within_file_lines_range =
177            |file_lines: FileLines, cur_line, s| -> (usize, usize, bool) {
178                let (lf_count, crlf_count) = count_lf_crlf(s);
179                let newline_count = lf_count + crlf_count;
180                let within_file_lines_range = file_lines.contains_range(
181                    file_name,
182                    cur_line,
183                    // if a newline character is at the end of the slice, then the number of
184                    // newlines needs to be decreased by 1 so that the range checked against
185                    // the file_lines is the visual range one would expect.
186                    cur_line + newline_count - if s.ends_with('\n') { 1 } else { 0 },
187                );
188                (lf_count, crlf_count, within_file_lines_range)
189            };
190        for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
191            debug!("{:?}: {:?}", kind, subslice);
192
193            let (lf_count, crlf_count, within_file_lines_range) =
194                slice_within_file_lines_range(self.config.file_lines(), status.cur_line, subslice);
195            let newline_count = lf_count + crlf_count;
196            if CodeCharKind::Comment == kind && within_file_lines_range {
197                // 1: comment.
198                self.process_comment(
199                    &mut status,
200                    snippet,
201                    &big_snippet[..(offset + big_diff)],
202                    offset,
203                    subslice,
204                );
205            } else if subslice.trim().is_empty() && newline_count > 0 && within_file_lines_range {
206                // 2: blank lines.
207                self.push_vertical_spaces(newline_count);
208                status.cur_line += newline_count;
209                // To avoid any issues with whitespace unicode chars just add the len of the slice
210                status.line_start = offset + subslice.len()
211            } else {
212                // 3: code which we failed to format or which is not within file-lines range.
213                self.process_missing_code(&mut status, snippet, subslice, offset, file_name);
214            }
215        }
216
217        let last_snippet = &snippet[status.line_start..];
218        let (_, _, within_file_lines_range) =
219            slice_within_file_lines_range(self.config.file_lines(), status.cur_line, last_snippet);
220        if within_file_lines_range {
221            process_last_snippet(self, last_snippet, snippet);
222        } else {
223            // just append what's left
224            self.push_str(last_snippet);
225        }
226    }
227
228    fn process_comment(
229        &mut self,
230        status: &mut SnippetStatus,
231        snippet: &str,
232        big_snippet: &str,
233        offset: usize,
234        subslice: &str,
235    ) {
236        let last_char = big_snippet
237            .chars()
238            .rev()
239            .find(|rev_c| ![' ', '\t'].contains(rev_c));
240
241        let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
242        let mut on_same_line = false;
243
244        let comment_indent = if fix_indent {
245            if let Some('{') = last_char {
246                self.push_str("\n");
247            }
248            let indent_str = self.block_indent.to_string(self.config);
249            self.push_str(&indent_str);
250            self.block_indent
251        } else if self.config.style_edition() >= StyleEdition::Edition2024
252            && !snippet.starts_with('\n')
253        {
254            // The comment appears on the same line as the previous formatted code.
255            // Assuming that comment is logically associated with that code, we want to keep it on
256            // the same level and avoid mixing it with possible other comment.
257            on_same_line = true;
258            self.push_str(" ");
259            self.block_indent
260        } else {
261            self.push_str(" ");
262            Indent::from_width(self.config, last_line_width(&self.buffer))
263        };
264
265        let comment_width = ::std::cmp::min(
266            self.config.comment_width(),
267            self.config.max_width() - self.block_indent.width(),
268        );
269        let comment_shape = Shape::legacy(comment_width, comment_indent);
270
271        if on_same_line {
272            match subslice.find('\n') {
273                None => {
274                    self.push_str(subslice);
275                }
276                Some(offset) if offset + 1 == subslice.len() => {
277                    self.push_str(&subslice[..offset]);
278                }
279                Some(offset) => {
280                    // keep first line as is: if it were too long and wrapped, it may get mixed
281                    // with the other lines.
282                    let first_line = &subslice[..offset];
283                    self.push_str(first_line);
284                    self.push_str(&comment_indent.to_string_with_newline(self.config));
285
286                    let other_lines = &subslice[offset + 1..];
287                    let comment_str =
288                        rewrite_comment(other_lines, false, comment_shape, self.config)
289                            .unwrap_or_else(|_| String::from(other_lines));
290                    self.push_str(&comment_str);
291                }
292            }
293        } else {
294            let comment_str = rewrite_comment(subslice, false, comment_shape, self.config)
295                .unwrap_or_else(|_| String::from(subslice));
296            self.push_str(&comment_str);
297        }
298
299        status.last_wspace = None;
300        status.line_start = offset + subslice.len();
301
302        // Add a newline:
303        // - if there isn't one already
304        // - otherwise, only if the last line is a line comment
305        if status.line_start <= snippet.len() {
306            match snippet[status.line_start..]
307                .chars()
308                // skip trailing whitespaces
309                .find(|c| !(*c == ' ' || *c == '\t'))
310            {
311                Some('\n') | Some('\r') => {
312                    if !is_last_comment_block(subslice) {
313                        self.push_str("\n");
314                    }
315                }
316                _ => self.push_str("\n"),
317            }
318        }
319
320        status.cur_line += count_newlines(subslice);
321    }
322
323    fn process_missing_code(
324        &mut self,
325        status: &mut SnippetStatus,
326        snippet: &str,
327        subslice: &str,
328        offset: usize,
329        file_name: &FileName,
330    ) {
331        for (mut i, c) in subslice.char_indices() {
332            i += offset;
333
334            if c == '\n' {
335                let skip_this_line = !self
336                    .config
337                    .file_lines()
338                    .contains_line(file_name, status.cur_line);
339                if skip_this_line {
340                    status.last_wspace = None;
341                }
342
343                if let Some(lw) = status.last_wspace {
344                    self.push_str(&snippet[status.line_start..lw]);
345                    self.push_str("\n");
346                    status.last_wspace = None;
347                } else {
348                    self.push_str(&snippet[status.line_start..=i]);
349                }
350
351                status.cur_line += 1;
352                status.line_start = i + 1;
353            } else if c.is_whitespace() && status.last_wspace.is_none() {
354                status.last_wspace = Some(i);
355            } else {
356                status.last_wspace = None;
357            }
358        }
359
360        let remaining = snippet[status.line_start..subslice.len() + offset].trim();
361        if !remaining.is_empty() {
362            self.push_str(&self.block_indent.to_string(self.config));
363            self.push_str(remaining);
364            status.line_start = subslice.len() + offset;
365        }
366    }
367}