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.
12 use std::iter::repeat;
14 use syntax::codemap::{BytePos, FileName, Pos, Span};
16 use codemap::LineRangeUtils;
17 use comment::{rewrite_comment, CodeCharKind, CommentCodeSlices};
18 use config::WriteMode;
19 use shape::{Indent, Shape};
20 use utils::{count_newlines, last_line_width, mk_sp};
21 use visitor::FmtVisitor;
23 struct SnippetStatus {
24 /// An offset to the current line from the beginnig of the original snippet.
26 /// A length of trailing whitespaces on the current line.
27 last_wspace: Option<usize>,
28 /// The current line number.
33 fn new(cur_line: usize) -> Self {
42 impl<'a> FmtVisitor<'a> {
43 fn output_at_start(&self) -> bool {
44 self.buffer.is_empty()
47 // TODO these format_missing methods are ugly. Refactor and add unit tests
48 // for the central whitespace stripping loop.
49 pub fn format_missing(&mut self, end: BytePos) {
50 self.format_missing_inner(end, |this, last_snippet, _| this.push_str(last_snippet))
53 pub fn format_missing_with_indent(&mut self, end: BytePos) {
54 let config = self.config;
55 self.format_missing_inner(end, |this, last_snippet, snippet| {
56 this.push_str(last_snippet.trim_right());
57 if last_snippet == snippet && !this.output_at_start() {
58 // No new lines in the snippet.
61 let indent = this.block_indent.to_string(config);
62 this.push_str(&indent);
66 pub fn format_missing_no_indent(&mut self, end: BytePos) {
67 self.format_missing_inner(end, |this, last_snippet, _| {
68 this.push_str(last_snippet.trim_right());
72 fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, &str)>(
75 process_last_snippet: F,
77 let start = self.last_pos;
80 // Do nothing if this is the beginning of the file.
81 if !self.output_at_start() {
82 process_last_snippet(self, "", "");
89 "Request to format inverted span: {:?} to {:?}",
90 self.codemap.lookup_char_pos(start),
91 self.codemap.lookup_char_pos(end)
95 let span = mk_sp(start, end);
96 let snippet = self.snippet(span);
97 if snippet.trim().is_empty() && !out_of_file_lines_range!(self, span) {
98 // Keep vertical spaces within range.
99 self.push_vertical_spaces(count_newlines(snippet));
100 process_last_snippet(self, "", snippet);
102 self.write_snippet(span, &process_last_snippet);
106 fn push_vertical_spaces(&mut self, mut newline_count: usize) {
107 // The buffer already has a trailing newline.
108 let offset = if self.buffer.ends_with('\n') { 0 } else { 1 };
109 let newline_upper_bound = self.config.blank_lines_upper_bound() + offset;
110 let newline_lower_bound = self.config.blank_lines_lower_bound() + offset;
111 if newline_count > newline_upper_bound {
112 newline_count = newline_upper_bound;
113 } else if newline_count < newline_lower_bound {
114 newline_count = newline_lower_bound;
116 let blank_lines: String = repeat('\n').take(newline_count).collect();
117 self.push_str(&blank_lines);
120 fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
122 F: Fn(&mut FmtVisitor, &str, &str),
124 // Get a snippet from the file start to the span's hi without allocating.
125 // We need it to determine what precedes the current comment. If the comment
126 // follows code on the same line, we won't touch it.
127 let big_span_lo = self.codemap.lookup_char_pos(span.lo()).file.start_pos;
128 let local_begin = self.codemap.lookup_byte_offset(big_span_lo);
129 let local_end = self.codemap.lookup_byte_offset(span.hi());
130 let start_index = local_begin.pos.to_usize();
131 let end_index = local_end.pos.to_usize();
132 let big_snippet = &local_begin.fm.src.as_ref().unwrap()[start_index..end_index];
134 let big_diff = (span.lo() - big_span_lo).to_usize();
135 let snippet = self.snippet(span);
137 debug!("write_snippet `{}`", snippet);
139 self.write_snippet_inner(big_snippet, big_diff, snippet, span, process_last_snippet);
142 fn write_snippet_inner<F>(
148 process_last_snippet: F,
150 F: Fn(&mut FmtVisitor, &str, &str),
152 // Trim whitespace from the right hand side of each line.
153 // Annoyingly, the library functions for splitting by lines etc. are not
154 // quite right, so we must do it ourselves.
155 let char_pos = self.codemap.lookup_char_pos(span.lo());
156 let file_name = &char_pos.file.name;
157 let mut status = SnippetStatus::new(char_pos.line);
159 let snippet = &*match self.config.write_mode() {
160 WriteMode::Coverage => replace_chars(old_snippet),
161 _ => Cow::from(old_snippet),
164 for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
165 debug!("{:?}: {:?}", kind, subslice);
167 let newline_count = count_newlines(subslice);
168 let within_file_lines_range = self.config.file_lines().intersects_range(
171 status.cur_line + newline_count,
174 if CodeCharKind::Comment == kind && within_file_lines_range {
176 self.process_comment(
179 &big_snippet[..(offset + big_diff)],
183 } else if subslice.trim().is_empty() && newline_count > 0 && within_file_lines_range {
185 self.push_vertical_spaces(newline_count);
186 status.cur_line += newline_count;
187 status.line_start = offset + newline_count;
189 // 3: code which we failed to format or which is not within file-lines range.
190 self.process_missing_code(&mut status, snippet, subslice, offset, file_name);
194 process_last_snippet(self, &snippet[status.line_start..], snippet);
199 status: &mut SnippetStatus,
205 let last_char = big_snippet
208 .skip_while(|rev_c| [' ', '\t'].contains(rev_c))
211 let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
213 let comment_indent = if fix_indent {
214 if let Some('{') = last_char {
217 let indent_str = self.block_indent.to_string(self.config);
218 self.push_str(&indent_str);
222 Indent::from_width(self.config, last_line_width(&self.buffer))
225 let comment_width = ::std::cmp::min(
226 self.config.comment_width(),
227 self.config.max_width() - self.block_indent.width(),
229 let comment_shape = Shape::legacy(comment_width, comment_indent);
230 let comment_str = rewrite_comment(subslice, false, comment_shape, self.config)
231 .unwrap_or_else(|| String::from(subslice));
232 self.push_str(&comment_str);
234 status.last_wspace = None;
235 status.line_start = offset + subslice.len();
237 if let Some('/') = subslice.chars().nth(1) {
238 // check that there are no contained block comments
241 .map(|s| s.trim_left())
242 .any(|s| s.len() >= 2 && &s[0..2] == "/*")
244 // Add a newline after line comments
247 } else if status.line_start <= snippet.len() {
248 // For other comments add a newline if there isn't one at the end already
249 match snippet[status.line_start..].chars().next() {
250 Some('\n') | Some('\r') => (),
251 _ => self.push_str("\n"),
255 status.cur_line += count_newlines(subslice);
258 fn process_missing_code(
260 status: &mut SnippetStatus,
264 file_name: &FileName,
266 for (mut i, c) in subslice.char_indices() {
270 let skip_this_line = !self.config
272 .contains_line(file_name, status.cur_line);
274 status.last_wspace = None;
277 if let Some(lw) = status.last_wspace {
278 self.push_str(&snippet[status.line_start..lw]);
280 status.last_wspace = None;
282 self.push_str(&snippet[status.line_start..i + 1]);
285 status.cur_line += 1;
286 status.line_start = i + 1;
287 } else if c.is_whitespace() && status.last_wspace.is_none() {
288 status.last_wspace = Some(i);
289 } else if c == ';' && status.last_wspace.is_some() {
290 status.line_start = i;
291 status.last_wspace = None;
293 status.last_wspace = None;
297 let remaining = snippet[status.line_start..subslice.len() + offset].trim();
298 if !remaining.is_empty() {
299 self.push_str(remaining);
300 status.line_start = subslice.len() + offset;
305 fn replace_chars(string: &str) -> Cow<str> {
309 .map(|ch| if ch.is_whitespace() { ch } else { 'X' })
310 .collect::<String>(),