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, FileName, Pos, Span};
15 use codemap::LineRangeUtils;
16 use comment::{rewrite_comment, CodeCharKind, CommentCodeSlices};
17 use config::WriteMode;
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) {
49 self.format_missing_inner(end, |this, last_snippet, _| this.push_str(last_snippet))
52 pub 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_right());
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 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_right());
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.codemap.lookup_char_pos(start),
90 self.codemap.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.count_trailing_newlines();
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 count_trailing_newlines(&self) -> usize {
135 let mut buf = &*self.buffer;
137 while buf.ends_with('\n') {
138 buf = &buf[..buf.len() - 1];
144 fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
146 F: Fn(&mut FmtVisitor, &str, &str),
148 // Get a snippet from the file start to the span's hi without allocating.
149 // We need it to determine what precedes the current comment. If the comment
150 // follows code on the same line, we won't touch it.
151 let big_span_lo = self.codemap.lookup_char_pos(span.lo()).file.start_pos;
152 let local_begin = self.codemap.lookup_byte_offset(big_span_lo);
153 let local_end = self.codemap.lookup_byte_offset(span.hi());
154 let start_index = local_begin.pos.to_usize();
155 let end_index = local_end.pos.to_usize();
156 let big_snippet = &local_begin.fm.src.as_ref().unwrap()[start_index..end_index];
158 let big_diff = (span.lo() - big_span_lo).to_usize();
159 let snippet = self.snippet(span);
161 debug!("write_snippet `{}`", snippet);
163 self.write_snippet_inner(big_snippet, big_diff, snippet, span, process_last_snippet);
166 fn write_snippet_inner<F>(
172 process_last_snippet: F,
174 F: Fn(&mut FmtVisitor, &str, &str),
176 // Trim whitespace from the right hand side of each line.
177 // Annoyingly, the library functions for splitting by lines etc. are not
178 // quite right, so we must do it ourselves.
179 let char_pos = self.codemap.lookup_char_pos(span.lo());
180 let file_name = &char_pos.file.name;
181 let mut status = SnippetStatus::new(char_pos.line);
183 let snippet = &*match self.config.write_mode() {
184 WriteMode::Coverage => Cow::from(replace_chars(old_snippet)),
185 _ => Cow::from(old_snippet),
188 for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
189 debug!("{:?}: {:?}", kind, subslice);
191 let newline_count = count_newlines(subslice);
192 let within_file_lines_range = self.config.file_lines().intersects_range(
195 status.cur_line + newline_count,
198 if CodeCharKind::Comment == kind && within_file_lines_range {
200 self.process_comment(
203 &big_snippet[..(offset + big_diff)],
207 } else if subslice.trim().is_empty() && newline_count > 0 && within_file_lines_range {
209 self.push_vertical_spaces(newline_count);
210 status.cur_line += newline_count;
211 status.line_start = offset + newline_count;
213 // 3: code which we failed to format or which is not within file-lines range.
214 self.process_missing_code(&mut status, snippet, subslice, offset, file_name);
218 process_last_snippet(self, &snippet[status.line_start..], snippet);
223 status: &mut SnippetStatus,
229 let last_char = big_snippet
232 .skip_while(|rev_c| [' ', '\t'].contains(rev_c))
235 let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
237 let comment_indent = if fix_indent {
238 if let Some('{') = last_char {
241 let indent_str = self.block_indent.to_string(self.config);
242 self.push_str(&indent_str);
246 Indent::from_width(self.config, last_line_width(&self.buffer))
249 let comment_width = ::std::cmp::min(
250 self.config.comment_width(),
251 self.config.max_width() - self.block_indent.width(),
253 let comment_shape = Shape::legacy(comment_width, comment_indent);
254 let comment_str = rewrite_comment(subslice, false, comment_shape, self.config)
255 .unwrap_or_else(|| String::from(subslice));
256 self.push_str(&comment_str);
258 status.last_wspace = None;
259 status.line_start = offset + subslice.len();
261 if let Some('/') = subslice.chars().nth(1) {
262 // check that there are no contained block comments
265 .map(|s| s.trim_left())
266 .any(|s| s.len() >= 2 && &s[0..2] == "/*")
268 // Add a newline after line comments
271 } else if status.line_start <= snippet.len() {
272 // For other comments add a newline if there isn't one at the end already
273 match snippet[status.line_start..].chars().next() {
274 Some('\n') | Some('\r') => (),
275 _ => self.push_str("\n"),
279 status.cur_line += count_newlines(subslice);
282 fn process_missing_code(
284 status: &mut SnippetStatus,
288 file_name: &FileName,
290 for (mut i, c) in subslice.char_indices() {
294 let skip_this_line = !self.config
296 .contains_line(file_name, status.cur_line);
298 status.last_wspace = None;
301 if let Some(lw) = status.last_wspace {
302 self.push_str(&snippet[status.line_start..lw]);
304 status.last_wspace = None;
306 self.push_str(&snippet[status.line_start..i + 1]);
309 status.cur_line += 1;
310 status.line_start = i + 1;
311 } else if c.is_whitespace() && status.last_wspace.is_none() {
312 status.last_wspace = Some(i);
313 } else if c == ';' && status.last_wspace.is_some() {
314 status.line_start = i;
315 status.last_wspace = None;
317 status.last_wspace = None;
321 let remaining = snippet[status.line_start..subslice.len() + offset].trim();
322 if !remaining.is_empty() {
323 self.push_str(remaining);
324 status.line_start = subslice.len() + offset;
329 fn replace_chars(string: &str) -> String {
332 .map(|ch| if ch.is_whitespace() { ch } else { 'X' })