1 use rustc_span::{BytePos, Pos, Span};
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::config::Version;
7 use crate::coverage::transform_missing_snippet;
8 use crate::shape::{Indent, Shape};
9 use crate::source_map::LineRangeUtils;
10 use crate::utils::{count_lf_crlf, count_newlines, last_line_width, mk_sp};
11 use crate::visitor::FmtVisitor;
13 struct SnippetStatus {
14 /// An offset to the current line from the beginning of the original snippet.
16 /// A length of trailing whitespaces on the current line.
17 last_wspace: Option<usize>,
18 /// The current line number.
23 fn new(cur_line: usize) -> Self {
32 impl<'a> FmtVisitor<'a> {
33 fn output_at_start(&self) -> bool {
34 self.buffer.is_empty()
37 pub(crate) fn format_missing(&mut self, end: BytePos) {
38 // HACK(topecongiro): we use `format_missing()` to extract a missing comment between
39 // a macro (or similar) and a trailing semicolon. Here we just try to avoid calling
40 // `format_missing_inner` in the common case where there is no such comment.
41 // This is a hack, ideally we should fix a possible bug in `format_missing_inner`
42 // or refactor `visit_mac` and `rewrite_macro`, but this should suffice to fix the
44 let missing_snippet = self.snippet(mk_sp(self.last_pos, end));
45 if missing_snippet.trim() == ";" {
50 self.format_missing_inner(end, |this, last_snippet, _| this.push_str(last_snippet))
53 pub(crate) fn format_missing_with_indent(&mut self, end: BytePos) {
54 let config = self.config;
55 self.format_missing_inner(end, |this, last_snippet, snippet| {
56 this.push_str(last_snippet.trim_end());
57 if last_snippet == snippet && !this.output_at_start() {
58 // No new lines in the snippet.
61 let indent = this.block_indent.to_string(config);
62 this.push_str(&indent);
66 pub(crate) fn format_missing_no_indent(&mut self, end: BytePos) {
67 self.format_missing_inner(end, |this, last_snippet, _| {
68 this.push_str(last_snippet.trim_end());
72 fn format_missing_inner<F: Fn(&mut FmtVisitor<'_>, &str, &str)>(
75 process_last_snippet: F,
77 let start = self.last_pos;
80 // Do nothing if this is the beginning of the file.
81 if !self.output_at_start() {
82 process_last_snippet(self, "", "");
89 "Request to format inverted span: {}",
90 self.parse_sess.span_to_debug_info(mk_sp(start, end)),
94 let span = mk_sp(start, end);
95 let snippet = self.snippet(span);
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() {
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);
107 self.write_snippet(span, &process_last_snippet);
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;
116 if newline_count + offset > newline_upper_bound {
117 if offset >= newline_upper_bound {
120 newline_count = newline_upper_bound - offset;
122 } else if newline_count + offset < newline_lower_bound {
123 if offset >= newline_lower_bound {
126 newline_count = newline_lower_bound - offset;
130 let blank_lines = "\n".repeat(newline_count);
131 self.push_str(&blank_lines);
134 fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
136 F: Fn(&mut FmtVisitor<'_>, &str, &str),
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.snippet_provider.start_pos();
142 let big_snippet = self.snippet_provider.entire_snippet();
143 let big_diff = (span.lo() - big_span_lo).to_usize();
145 let snippet = self.snippet(span);
147 debug!("write_snippet `{}`", snippet);
149 self.write_snippet_inner(big_snippet, snippet, big_diff, span, process_last_snippet);
152 fn write_snippet_inner<F>(
158 process_last_snippet: F,
160 F: Fn(&mut FmtVisitor<'_>, &str, &str),
162 // Trim whitespace from the right hand side of each line.
163 // Annoyingly, the library functions for splitting by lines etc. are not
164 // quite right, so we must do it ourselves.
165 let line = self.parse_sess.line_of_byte_pos(span.lo());
166 let file_name = &self.parse_sess.span_to_filename(span);
167 let mut status = SnippetStatus::new(line);
169 let snippet = &*transform_missing_snippet(self.config, old_snippet);
171 let slice_within_file_lines_range =
172 |file_lines: FileLines, cur_line, s| -> (usize, usize, bool) {
173 let (lf_count, crlf_count) = count_lf_crlf(s);
174 let newline_count = lf_count + crlf_count;
175 let within_file_lines_range = file_lines.contains_range(
178 // if a newline character is at the end of the slice, then the number of
179 // newlines needs to be decreased by 1 so that the range checked against
180 // the file_lines is the visual range one would expect.
181 cur_line + newline_count - if s.ends_with('\n') { 1 } else { 0 },
183 (lf_count, crlf_count, within_file_lines_range)
185 for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
186 debug!("{:?}: {:?}", kind, subslice);
188 let (lf_count, crlf_count, within_file_lines_range) =
189 slice_within_file_lines_range(self.config.file_lines(), status.cur_line, subslice);
190 let newline_count = lf_count + crlf_count;
191 if CodeCharKind::Comment == kind && within_file_lines_range {
193 self.process_comment(
196 &big_snippet[..(offset + big_diff)],
200 } else if subslice.trim().is_empty() && newline_count > 0 && within_file_lines_range {
202 self.push_vertical_spaces(newline_count);
203 status.cur_line += newline_count;
204 status.line_start = offset + lf_count + crlf_count * 2;
206 // 3: code which we failed to format or which is not within file-lines range.
207 self.process_missing_code(&mut status, snippet, subslice, offset, file_name);
211 let last_snippet = &snippet[status.line_start..];
212 let (_, _, within_file_lines_range) =
213 slice_within_file_lines_range(self.config.file_lines(), status.cur_line, last_snippet);
214 if within_file_lines_range {
215 process_last_snippet(self, last_snippet, snippet);
217 // just append what's left
218 self.push_str(last_snippet);
224 status: &mut SnippetStatus,
230 let last_char = big_snippet
233 .skip_while(|rev_c| [' ', '\t'].contains(rev_c))
236 let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
237 let mut on_same_line = false;
239 let comment_indent = if fix_indent {
240 if let Some('{') = last_char {
243 let indent_str = self.block_indent.to_string(self.config);
244 self.push_str(&indent_str);
246 } else if self.config.version() == Version::Two && !snippet.starts_with('\n') {
247 // The comment appears on the same line as the previous formatted code.
248 // Assuming that comment is logically associated with that code, we want to keep it on
249 // the same level and avoid mixing it with possible other comment.
255 Indent::from_width(self.config, last_line_width(&self.buffer))
258 let comment_width = ::std::cmp::min(
259 self.config.comment_width(),
260 self.config.max_width() - self.block_indent.width(),
262 let comment_shape = Shape::legacy(comment_width, comment_indent);
265 match subslice.find("\n") {
267 self.push_str(subslice);
269 Some(offset) if offset + 1 == subslice.len() => {
270 self.push_str(&subslice[..offset]);
273 // keep first line as is: if it were too long and wrapped, it may get mixed
274 // with the other lines.
275 let first_line = &subslice[..offset];
276 self.push_str(first_line);
277 self.push_str(&comment_indent.to_string_with_newline(self.config));
279 let other_lines = &subslice[offset + 1..];
281 rewrite_comment(other_lines, false, comment_shape, self.config)
282 .unwrap_or_else(|| String::from(other_lines));
283 self.push_str(&comment_str);
287 let comment_str = rewrite_comment(subslice, false, comment_shape, self.config)
288 .unwrap_or_else(|| String::from(subslice));
289 self.push_str(&comment_str);
292 status.last_wspace = None;
293 status.line_start = offset + subslice.len();
296 // - if there isn't one already
297 // - otherwise, only if the last line is a line comment
298 if status.line_start <= snippet.len() {
299 match snippet[status.line_start..]
301 // skip trailing whitespaces
302 .skip_while(|c| *c == ' ' || *c == '\t')
305 Some('\n') | Some('\r') => {
306 if !is_last_comment_block(subslice) {
310 _ => self.push_str("\n"),
314 status.cur_line += count_newlines(subslice);
317 fn process_missing_code(
319 status: &mut SnippetStatus,
323 file_name: &FileName,
325 for (mut i, c) in subslice.char_indices() {
329 let skip_this_line = !self
332 .contains_line(file_name, status.cur_line);
334 status.last_wspace = None;
337 if let Some(lw) = status.last_wspace {
338 self.push_str(&snippet[status.line_start..lw]);
340 status.last_wspace = None;
342 self.push_str(&snippet[status.line_start..=i]);
345 status.cur_line += 1;
346 status.line_start = i + 1;
347 } else if c.is_whitespace() && status.last_wspace.is_none() {
348 status.last_wspace = Some(i);
350 status.last_wspace = None;
354 let remaining = snippet[status.line_start..subslice.len() + offset].trim();
355 if !remaining.is_empty() {
356 self.push_str(&self.block_indent.to_string(self.config));
357 self.push_str(remaining);
358 status.line_start = subslice.len() + offset;