1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use syntax::source_map::{BytePos, Pos, Span};
15 use comment::{rewrite_comment, CodeCharKind, CommentCodeSlices};
16 use config::{EmitMode, FileName};
17 use shape::{Indent, Shape};
18 use source_map::LineRangeUtils;
19 use utils::{count_newlines, last_line_width, mk_sp};
20 use visitor::FmtVisitor;
22 struct SnippetStatus {
23 /// An offset to the current line from the beginning of the original snippet.
25 /// A length of trailing whitespaces on the current line.
26 last_wspace: Option<usize>,
27 /// The current line number.
32 fn new(cur_line: usize) -> Self {
41 impl<'a> FmtVisitor<'a> {
42 fn output_at_start(&self) -> bool {
43 self.buffer.is_empty()
46 pub fn format_missing(&mut self, end: BytePos) {
48 // We use `format_missing()` to extract a missing comment between a macro
49 // (or alike) and a trailing semicolon. Here we just try to avoid calling
50 // `format_missing_inner` in the common case where there is no such comment.
51 // This is a hack, ideally we should fix a possible bug in `format_missing_inner`
52 // or refactor `visit_mac` and `rewrite_macro`, but this should suffice to fix the
54 let missing_snippet = self.snippet(mk_sp(self.last_pos, end));
55 if missing_snippet.trim() == ";" {
60 self.format_missing_inner(end, |this, last_snippet, _| this.push_str(last_snippet))
63 pub fn format_missing_with_indent(&mut self, end: BytePos) {
64 let config = self.config;
65 self.format_missing_inner(end, |this, last_snippet, snippet| {
66 this.push_str(last_snippet.trim_end());
67 if last_snippet == snippet && !this.output_at_start() {
68 // No new lines in the snippet.
71 let indent = this.block_indent.to_string(config);
72 this.push_str(&indent);
76 pub fn format_missing_no_indent(&mut self, end: BytePos) {
77 self.format_missing_inner(end, |this, last_snippet, _| {
78 this.push_str(last_snippet.trim_end());
82 fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, &str)>(
85 process_last_snippet: F,
87 let start = self.last_pos;
90 // Do nothing if this is the beginning of the file.
91 if !self.output_at_start() {
92 process_last_snippet(self, "", "");
99 "Request to format inverted span: {:?} to {:?}",
100 self.source_map.lookup_char_pos(start),
101 self.source_map.lookup_char_pos(end)
105 let span = mk_sp(start, end);
106 let snippet = self.snippet(span);
108 // Do nothing for spaces in the beginning of the file
109 if start == BytePos(0) && end.0 as usize == snippet.len() && snippet.trim().is_empty() {
113 if snippet.trim().is_empty() && !out_of_file_lines_range!(self, span) {
114 // Keep vertical spaces within range.
115 self.push_vertical_spaces(count_newlines(snippet));
116 process_last_snippet(self, "", snippet);
118 self.write_snippet(span, &process_last_snippet);
122 fn push_vertical_spaces(&mut self, mut newline_count: usize) {
123 let offset = self.buffer.chars().rev().take_while(|c| *c == '\n').count();
124 let newline_upper_bound = self.config.blank_lines_upper_bound() + 1;
125 let newline_lower_bound = self.config.blank_lines_lower_bound() + 1;
127 if newline_count + offset > newline_upper_bound {
128 if offset >= newline_upper_bound {
131 newline_count = newline_upper_bound - offset;
133 } else if newline_count + offset < newline_lower_bound {
134 if offset >= newline_lower_bound {
137 newline_count = newline_lower_bound - offset;
141 let blank_lines = "\n".repeat(newline_count);
142 self.push_str(&blank_lines);
145 fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
147 F: Fn(&mut FmtVisitor, &str, &str),
149 // Get a snippet from the file start to the span's hi without allocating.
150 // We need it to determine what precedes the current comment. If the comment
151 // follows code on the same line, we won't touch it.
152 let big_span_lo = self.source_map.lookup_char_pos(span.lo()).file.start_pos;
153 let local_begin = self.source_map.lookup_byte_offset(big_span_lo);
154 let local_end = self.source_map.lookup_byte_offset(span.hi());
155 let start_index = local_begin.pos.to_usize();
156 let end_index = local_end.pos.to_usize();
157 let big_snippet = &local_begin.sf.src.as_ref().unwrap()[start_index..end_index];
159 let big_diff = (span.lo() - big_span_lo).to_usize();
160 let snippet = self.snippet(span);
162 debug!("write_snippet `{}`", snippet);
164 self.write_snippet_inner(big_snippet, big_diff, snippet, span, process_last_snippet);
167 fn write_snippet_inner<F>(
173 process_last_snippet: F,
175 F: Fn(&mut FmtVisitor, &str, &str),
177 // Trim whitespace from the right hand side of each line.
178 // Annoyingly, the library functions for splitting by lines etc. are not
179 // quite right, so we must do it ourselves.
180 let char_pos = self.source_map.lookup_char_pos(span.lo());
181 let file_name = &char_pos.file.name.clone().into();
182 let mut status = SnippetStatus::new(char_pos.line);
184 let snippet = &*match self.config.emit_mode() {
185 EmitMode::Coverage => Cow::from(replace_chars(old_snippet)),
186 _ => Cow::from(old_snippet),
189 for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
190 debug!("{:?}: {:?}", kind, subslice);
192 let newline_count = count_newlines(subslice);
193 let within_file_lines_range = self.config.file_lines().contains_range(
196 status.cur_line + newline_count,
199 if CodeCharKind::Comment == kind && within_file_lines_range {
201 self.process_comment(
204 &big_snippet[..(offset + big_diff)],
208 } else if subslice.trim().is_empty() && newline_count > 0 && within_file_lines_range {
210 self.push_vertical_spaces(newline_count);
211 status.cur_line += newline_count;
212 status.line_start = offset + newline_count;
214 // 3: code which we failed to format or which is not within file-lines range.
215 self.process_missing_code(&mut status, snippet, subslice, offset, file_name);
219 process_last_snippet(self, &snippet[status.line_start..], 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));
238 let comment_indent = if fix_indent {
239 if let Some('{') = last_char {
242 let indent_str = self.block_indent.to_string(self.config);
243 self.push_str(&indent_str);
247 Indent::from_width(self.config, last_line_width(&self.buffer))
250 let comment_width = ::std::cmp::min(
251 self.config.comment_width(),
252 self.config.max_width() - self.block_indent.width(),
254 let comment_shape = Shape::legacy(comment_width, comment_indent);
255 let comment_str = rewrite_comment(subslice, false, comment_shape, self.config)
256 .unwrap_or_else(|| String::from(subslice));
257 self.push_str(&comment_str);
259 status.last_wspace = None;
260 status.line_start = offset + subslice.len();
263 // - if there isn't one already
264 // - otherwise, only if the last line is a line comment
265 if status.line_start <= snippet.len() {
266 match snippet[status.line_start..].chars().next() {
267 Some('\n') | Some('\r') => {
268 if !subslice.trim_end().ends_with("*/") {
272 _ => self.push_str("\n"),
276 status.cur_line += count_newlines(subslice);
279 fn process_missing_code(
281 status: &mut SnippetStatus,
285 file_name: &FileName,
287 for (mut i, c) in subslice.char_indices() {
291 let skip_this_line = !self
294 .contains_line(file_name, status.cur_line);
296 status.last_wspace = None;
299 if let Some(lw) = status.last_wspace {
300 self.push_str(&snippet[status.line_start..lw]);
302 status.last_wspace = None;
304 self.push_str(&snippet[status.line_start..=i]);
307 status.cur_line += 1;
308 status.line_start = i + 1;
309 } else if c.is_whitespace() && status.last_wspace.is_none() {
310 status.last_wspace = Some(i);
312 status.last_wspace = None;
316 let remaining = snippet[status.line_start..subslice.len() + offset].trim();
317 if !remaining.is_empty() {
318 self.push_str(remaining);
319 status.line_start = subslice.len() + offset;
324 fn replace_chars(string: &str) -> String {
327 .map(|ch| if ch.is_whitespace() { ch } else { 'X' })