1 use syntax::source_map::{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::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;
12 struct SnippetStatus {
13 /// An offset to the current line from the beginning of the original snippet.
15 /// A length of trailing whitespaces on the current line.
16 last_wspace: Option<usize>,
17 /// The current line number.
22 fn new(cur_line: usize) -> Self {
31 impl<'a> FmtVisitor<'a> {
32 fn output_at_start(&self) -> bool {
33 self.buffer.is_empty()
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
43 let missing_snippet = self.snippet(mk_sp(self.last_pos, end));
44 if missing_snippet.trim() == ";" {
49 self.format_missing_inner(end, |this, last_snippet, _| this.push_str(last_snippet))
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.
60 let indent = this.block_indent.to_string(config);
61 this.push_str(&indent);
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());
71 fn format_missing_inner<F: Fn(&mut FmtVisitor<'_>, &str, &str)>(
74 process_last_snippet: F,
76 let start = self.last_pos;
79 // Do nothing if this is the beginning of the file.
80 if !self.output_at_start() {
81 process_last_snippet(self, "", "");
88 "Request to format inverted span: {:?} to {:?}",
89 self.source_map.lookup_char_pos(start),
90 self.source_map.lookup_char_pos(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.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];
148 let big_diff = (span.lo() - big_span_lo).to_usize();
149 let snippet = self.snippet(span);
151 debug!("write_snippet `{}`", snippet);
153 self.write_snippet_inner(big_snippet, big_diff, snippet, span, process_last_snippet);
156 fn write_snippet_inner<F>(
162 process_last_snippet: F,
164 F: Fn(&mut FmtVisitor<'_>, &str, &str),
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);
173 let snippet = &*transform_missing_snippet(self.config, old_snippet);
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(
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 },
187 (lf_count, crlf_count, within_file_lines_range)
189 for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
190 debug!("{:?}: {:?}", kind, subslice);
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 {
197 self.process_comment(
200 &big_snippet[..(offset + big_diff)],
204 } else if subslice.trim().is_empty() && newline_count > 0 && within_file_lines_range {
206 self.push_vertical_spaces(newline_count);
207 status.cur_line += newline_count;
208 status.line_start = offset + lf_count + crlf_count * 2;
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);
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);
221 // just append what's left
222 self.push_str(last_snippet);
228 status: &mut SnippetStatus,
234 let last_char = big_snippet
237 .skip_while(|rev_c| [' ', '\t'].contains(rev_c))
240 let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
242 let comment_indent = if fix_indent {
243 if let Some('{') = last_char {
246 let indent_str = self.block_indent.to_string(self.config);
247 self.push_str(&indent_str);
251 Indent::from_width(self.config, last_line_width(&self.buffer))
254 let comment_width = ::std::cmp::min(
255 self.config.comment_width(),
256 self.config.max_width() - self.block_indent.width(),
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);
263 status.last_wspace = None;
264 status.line_start = offset + subslice.len();
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..]
272 // skip trailing whitespaces
273 .skip_while(|c| *c == ' ' || *c == '\t')
276 Some('\n') | Some('\r') => {
277 if !is_last_comment_block(subslice) {
281 _ => self.push_str("\n"),
285 status.cur_line += count_newlines(subslice);
288 fn process_missing_code(
290 status: &mut SnippetStatus,
294 file_name: &FileName,
296 for (mut i, c) in subslice.char_indices() {
300 let skip_this_line = !self
303 .contains_line(file_name, status.cur_line);
305 status.last_wspace = None;
308 if let Some(lw) = status.last_wspace {
309 self.push_str(&snippet[status.line_start..lw]);
311 status.last_wspace = None;
313 self.push_str(&snippet[status.line_start..=i]);
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);
321 status.last_wspace = None;
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;