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::codemap::{BytePos, Pos, Span};
15 use codemap::LineRangeUtils;
16 use comment::{rewrite_comment, CodeCharKind, CommentCodeSlices};
17 use config::{EmitMode, FileName};
18 use shape::{Indent, Shape};
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 beginnig 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 // TODO these format_missing methods are ugly. Refactor and add unit tests
47 // for the central whitespace stripping loop.
48 pub fn format_missing(&mut self, end: BytePos) {
50 // We use `format_missing()` to extract a missing comment between a macro
51 // (or alike) and a trailing semicolon. Here we just try to avoid calling
52 // `format_missing_inner` in the common case where there is no such comment.
53 // This is a hack, ideally we should fix a possible bug in `format_missing_inner`
54 // or refactor `visit_mac` and `rewrite_macro`, but this should suffice to fix the
56 let missing_snippet = self.snippet(mk_sp(self.last_pos, end));
57 if missing_snippet.trim() == ";" {
62 self.format_missing_inner(end, |this, last_snippet, _| this.push_str(last_snippet))
65 pub fn format_missing_with_indent(&mut self, end: BytePos) {
66 let config = self.config;
67 self.format_missing_inner(end, |this, last_snippet, snippet| {
68 this.push_str(last_snippet.trim_right());
69 if last_snippet == snippet && !this.output_at_start() {
70 // No new lines in the snippet.
73 let indent = this.block_indent.to_string(config);
74 this.push_str(&indent);
78 pub fn format_missing_no_indent(&mut self, end: BytePos) {
79 self.format_missing_inner(end, |this, last_snippet, _| {
80 this.push_str(last_snippet.trim_right());
84 fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, &str)>(
87 process_last_snippet: F,
89 let start = self.last_pos;
92 // Do nothing if this is the beginning of the file.
93 if !self.output_at_start() {
94 process_last_snippet(self, "", "");
101 "Request to format inverted span: {:?} to {:?}",
102 self.codemap.lookup_char_pos(start),
103 self.codemap.lookup_char_pos(end)
107 let span = mk_sp(start, end);
108 let snippet = self.snippet(span);
110 // Do nothing for spaces in the beginning of the file
111 if start == BytePos(0) && end.0 as usize == snippet.len() && snippet.trim().is_empty() {
115 if snippet.trim().is_empty() && !out_of_file_lines_range!(self, span) {
116 // Keep vertical spaces within range.
117 self.push_vertical_spaces(count_newlines(snippet));
118 process_last_snippet(self, "", snippet);
120 self.write_snippet(span, &process_last_snippet);
124 fn push_vertical_spaces(&mut self, mut newline_count: usize) {
125 let offset = self.count_trailing_newlines();
126 let newline_upper_bound = self.config.blank_lines_upper_bound() + 1;
127 let newline_lower_bound = self.config.blank_lines_lower_bound() + 1;
129 if newline_count + offset > newline_upper_bound {
130 if offset >= newline_upper_bound {
133 newline_count = newline_upper_bound - offset;
135 } else if newline_count + offset < newline_lower_bound {
136 if offset >= newline_lower_bound {
139 newline_count = newline_lower_bound - offset;
143 let blank_lines = "\n".repeat(newline_count);
144 self.push_str(&blank_lines);
147 fn count_trailing_newlines(&self) -> usize {
148 let mut buf = &*self.buffer;
150 while buf.ends_with('\n') {
151 buf = &buf[..buf.len() - 1];
157 fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
159 F: Fn(&mut FmtVisitor, &str, &str),
161 // Get a snippet from the file start to the span's hi without allocating.
162 // We need it to determine what precedes the current comment. If the comment
163 // follows code on the same line, we won't touch it.
164 let big_span_lo = self.codemap.lookup_char_pos(span.lo()).file.start_pos;
165 let local_begin = self.codemap.lookup_byte_offset(big_span_lo);
166 let local_end = self.codemap.lookup_byte_offset(span.hi());
167 let start_index = local_begin.pos.to_usize();
168 let end_index = local_end.pos.to_usize();
169 let big_snippet = &local_begin.fm.src.as_ref().unwrap()[start_index..end_index];
171 let big_diff = (span.lo() - big_span_lo).to_usize();
172 let snippet = self.snippet(span);
174 debug!("write_snippet `{}`", snippet);
176 self.write_snippet_inner(big_snippet, big_diff, snippet, span, process_last_snippet);
179 fn write_snippet_inner<F>(
185 process_last_snippet: F,
187 F: Fn(&mut FmtVisitor, &str, &str),
189 // Trim whitespace from the right hand side of each line.
190 // Annoyingly, the library functions for splitting by lines etc. are not
191 // quite right, so we must do it ourselves.
192 let char_pos = self.codemap.lookup_char_pos(span.lo());
193 let file_name = &char_pos.file.name.clone().into();
194 let mut status = SnippetStatus::new(char_pos.line);
196 let snippet = &*match self.config.emit_mode() {
197 EmitMode::Coverage => Cow::from(replace_chars(old_snippet)),
198 _ => Cow::from(old_snippet),
201 for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
202 debug!("{:?}: {:?}", kind, subslice);
204 let newline_count = count_newlines(subslice);
205 let within_file_lines_range = self.config.file_lines().contains_range(
208 status.cur_line + newline_count,
211 if CodeCharKind::Comment == kind && within_file_lines_range {
213 self.process_comment(
216 &big_snippet[..(offset + big_diff)],
220 } else if subslice.trim().is_empty() && newline_count > 0 && within_file_lines_range {
222 self.push_vertical_spaces(newline_count);
223 status.cur_line += newline_count;
224 status.line_start = offset + newline_count;
226 // 3: code which we failed to format or which is not within file-lines range.
227 self.process_missing_code(&mut status, snippet, subslice, offset, file_name);
231 process_last_snippet(self, &snippet[status.line_start..], snippet);
236 status: &mut SnippetStatus,
242 let last_char = big_snippet
245 .skip_while(|rev_c| [' ', '\t'].contains(rev_c))
248 let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
250 let comment_indent = if fix_indent {
251 if let Some('{') = last_char {
254 let indent_str = self.block_indent.to_string(self.config);
255 self.push_str(&indent_str);
259 Indent::from_width(self.config, last_line_width(&self.buffer))
262 let comment_width = ::std::cmp::min(
263 self.config.comment_width(),
264 self.config.max_width() - self.block_indent.width(),
266 let comment_shape = Shape::legacy(comment_width, comment_indent);
267 let comment_str = rewrite_comment(subslice, false, comment_shape, self.config)
268 .unwrap_or_else(|| String::from(subslice));
269 self.push_str(&comment_str);
271 status.last_wspace = None;
272 status.line_start = offset + subslice.len();
274 if let Some('/') = subslice.chars().nth(1) {
275 // check that there are no contained block comments
278 .map(|s| s.trim_left())
279 .any(|s| s.len() >= 2 && &s[0..2] == "/*")
281 // Add a newline after line comments
284 } else if status.line_start <= snippet.len() {
285 // For other comments add a newline if there isn't one at the end already
286 match snippet[status.line_start..].chars().next() {
287 Some('\n') | Some('\r') => (),
288 _ => self.push_str("\n"),
292 status.cur_line += count_newlines(subslice);
295 fn process_missing_code(
297 status: &mut SnippetStatus,
301 file_name: &FileName,
303 for (mut i, c) in subslice.char_indices() {
307 let skip_this_line = !self
310 .contains_line(file_name, status.cur_line);
312 status.last_wspace = None;
315 if let Some(lw) = status.last_wspace {
316 self.push_str(&snippet[status.line_start..lw]);
318 status.last_wspace = None;
320 self.push_str(&snippet[status.line_start..i + 1]);
323 status.cur_line += 1;
324 status.line_start = i + 1;
325 } else if c.is_whitespace() && status.last_wspace.is_none() {
326 status.last_wspace = Some(i);
327 } else if c == ';' && status.last_wspace.is_some() {
328 status.line_start = i;
329 status.last_wspace = None;
331 status.last_wspace = None;
335 let remaining = snippet[status.line_start..subslice.len() + offset].trim();
336 if !remaining.is_empty() {
337 self.push_str(remaining);
338 status.line_start = subslice.len() + offset;
343 fn replace_chars(string: &str) -> String {
346 .map(|ch| if ch.is_whitespace() { ch } else { 'X' })