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 line_start: usize,
17 last_wspace: Option<usize>,
19 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 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 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 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 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 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 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 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 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 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 self.push_vertical_spaces(newline_count);
208 status.cur_line += newline_count;
209 status.line_start = offset + lf_count + crlf_count * 2;
210 } else {
211 self.process_missing_code(&mut status, snippet, subslice, offset, file_name);
213 }
214 }
215
216 let last_snippet = &snippet[status.line_start..];
217 let (_, _, within_file_lines_range) =
218 slice_within_file_lines_range(self.config.file_lines(), status.cur_line, last_snippet);
219 if within_file_lines_range {
220 process_last_snippet(self, last_snippet, snippet);
221 } else {
222 self.push_str(last_snippet);
224 }
225 }
226
227 fn process_comment(
228 &mut self,
229 status: &mut SnippetStatus,
230 snippet: &str,
231 big_snippet: &str,
232 offset: usize,
233 subslice: &str,
234 ) {
235 let last_char = big_snippet
236 .chars()
237 .rev()
238 .find(|rev_c| ![' ', '\t'].contains(rev_c));
239
240 let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
241 let mut on_same_line = false;
242
243 let comment_indent = if fix_indent {
244 if let Some('{') = last_char {
245 self.push_str("\n");
246 }
247 let indent_str = self.block_indent.to_string(self.config);
248 self.push_str(&indent_str);
249 self.block_indent
250 } else if self.config.style_edition() >= StyleEdition::Edition2024
251 && !snippet.starts_with('\n')
252 {
253 on_same_line = true;
257 self.push_str(" ");
258 self.block_indent
259 } else {
260 self.push_str(" ");
261 Indent::from_width(self.config, last_line_width(&self.buffer))
262 };
263
264 let comment_width = ::std::cmp::min(
265 self.config.comment_width(),
266 self.config.max_width() - self.block_indent.width(),
267 );
268 let comment_shape = Shape::legacy(comment_width, comment_indent);
269
270 if on_same_line {
271 match subslice.find('\n') {
272 None => {
273 self.push_str(subslice);
274 }
275 Some(offset) if offset + 1 == subslice.len() => {
276 self.push_str(&subslice[..offset]);
277 }
278 Some(offset) => {
279 let first_line = &subslice[..offset];
282 self.push_str(first_line);
283 self.push_str(&comment_indent.to_string_with_newline(self.config));
284
285 let other_lines = &subslice[offset + 1..];
286 let comment_str =
287 rewrite_comment(other_lines, false, comment_shape, self.config)
288 .unwrap_or_else(|_| String::from(other_lines));
289 self.push_str(&comment_str);
290 }
291 }
292 } else {
293 let comment_str = rewrite_comment(subslice, false, comment_shape, self.config)
294 .unwrap_or_else(|_| String::from(subslice));
295 self.push_str(&comment_str);
296 }
297
298 status.last_wspace = None;
299 status.line_start = offset + subslice.len();
300
301 if status.line_start <= snippet.len() {
305 match snippet[status.line_start..]
306 .chars()
307 .find(|c| !(*c == ' ' || *c == '\t'))
309 {
310 Some('\n') | Some('\r') => {
311 if !is_last_comment_block(subslice) {
312 self.push_str("\n");
313 }
314 }
315 _ => self.push_str("\n"),
316 }
317 }
318
319 status.cur_line += count_newlines(subslice);
320 }
321
322 fn process_missing_code(
323 &mut self,
324 status: &mut SnippetStatus,
325 snippet: &str,
326 subslice: &str,
327 offset: usize,
328 file_name: &FileName,
329 ) {
330 for (mut i, c) in subslice.char_indices() {
331 i += offset;
332
333 if c == '\n' {
334 let skip_this_line = !self
335 .config
336 .file_lines()
337 .contains_line(file_name, status.cur_line);
338 if skip_this_line {
339 status.last_wspace = None;
340 }
341
342 if let Some(lw) = status.last_wspace {
343 self.push_str(&snippet[status.line_start..lw]);
344 self.push_str("\n");
345 status.last_wspace = None;
346 } else {
347 self.push_str(&snippet[status.line_start..=i]);
348 }
349
350 status.cur_line += 1;
351 status.line_start = i + 1;
352 } else if c.is_whitespace() && status.last_wspace.is_none() {
353 status.last_wspace = Some(i);
354 } else {
355 status.last_wspace = None;
356 }
357 }
358
359 let remaining = snippet[status.line_start..subslice.len() + offset].trim();
360 if !remaining.is_empty() {
361 self.push_str(&self.block_indent.to_string(self.config));
362 self.push_str(remaining);
363 status.line_start = subslice.len() + offset;
364 }
365 }
366}