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, Pos, Span};
16 use comment::{rewrite_comment, CodeCharKind, CommentCodeSlices};
17 use config::WriteMode;
18 use shape::{Indent, Shape};
19 use utils::{count_newlines, mk_sp};
20 use visitor::FmtVisitor;
22 impl<'a> FmtVisitor<'a> {
23 fn output_at_start(&self) -> bool {
27 // TODO these format_missing methods are ugly. Refactor and add unit tests
28 // for the central whitespace stripping loop.
29 pub fn format_missing(&mut self, end: BytePos) {
30 self.format_missing_inner(end, |this, last_snippet, _| {
31 this.buffer.push_str(last_snippet)
35 pub fn format_missing_with_indent(&mut self, end: BytePos) {
36 let config = self.config;
37 self.format_missing_inner(end, |this, last_snippet, snippet| {
38 this.buffer.push_str(last_snippet.trim_right());
39 if last_snippet == snippet && !this.output_at_start() {
40 // No new lines in the snippet.
41 this.buffer.push_str("\n");
43 let indent = this.block_indent.to_string(config);
44 this.buffer.push_str(&indent);
48 pub fn format_missing_no_indent(&mut self, end: BytePos) {
49 self.format_missing_inner(end, |this, last_snippet, _| {
50 this.buffer.push_str(last_snippet.trim_right());
54 fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, &str)>(
57 process_last_snippet: F,
59 let start = self.last_pos;
62 // Do nothing if this is the beginning of the file.
63 if !self.output_at_start() {
64 process_last_snippet(self, "", "");
71 "Request to format inverted span: {:?} to {:?}",
72 self.codemap.lookup_char_pos(start),
73 self.codemap.lookup_char_pos(end)
77 let span = mk_sp(start, end);
78 let snippet = self.snippet(span);
79 if snippet.trim().is_empty() {
80 // Keep vertical spaces within range.
81 self.push_vertical_spaces(count_newlines(&snippet));
82 process_last_snippet(self, "", &snippet);
84 self.write_snippet(span, &process_last_snippet);
88 fn push_vertical_spaces(&mut self, mut newline_count: usize) {
89 let newline_upper_bound = self.config.blank_lines_upper_bound() + 1;
90 let newline_lower_bound = self.config.blank_lines_lower_bound() + 1;
91 if newline_count > newline_upper_bound {
92 newline_count = newline_upper_bound;
93 } else if newline_count < newline_lower_bound {
94 newline_count = newline_lower_bound;
96 let blank_lines: String = repeat('\n').take(newline_count).collect();
97 self.buffer.push_str(&blank_lines);
100 fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
102 F: Fn(&mut FmtVisitor, &str, &str),
104 // Get a snippet from the file start to the span's hi without allocating.
105 // We need it to determine what precedes the current comment. If the comment
106 // follows code on the same line, we won't touch it.
107 let big_span_lo = self.codemap.lookup_char_pos(span.lo()).file.start_pos;
108 let local_begin = self.codemap.lookup_byte_offset(big_span_lo);
109 let local_end = self.codemap.lookup_byte_offset(span.hi());
110 let start_index = local_begin.pos.to_usize();
111 let end_index = local_end.pos.to_usize();
112 let big_snippet = &local_begin.fm.src.as_ref().unwrap()[start_index..end_index];
114 let big_diff = (span.lo() - big_span_lo).to_usize();
115 let snippet = self.snippet(span);
117 debug!("write_snippet `{}`", snippet);
119 self.write_snippet_inner(big_snippet, big_diff, &snippet, span, process_last_snippet);
124 status: &mut SnippetStatus,
132 let last_char = big_snippet[..(offset + big_diff)]
135 .skip_while(|rev_c| [' ', '\t'].contains(rev_c))
138 let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
140 let subslice_num_lines = count_newlines(subslice);
141 let skip_this_range = !self.config.file_lines().intersects_range(
144 status.cur_line + subslice_num_lines,
147 if status.rewrite_next_comment && skip_this_range {
148 status.rewrite_next_comment = false;
151 if status.rewrite_next_comment {
153 if let Some('{') = last_char {
154 self.buffer.push_str("\n");
157 .push_str(&self.block_indent.to_string(self.config));
159 self.buffer.push_str(" ");
162 let comment_width = ::std::cmp::min(
163 self.config.comment_width(),
164 self.config.max_width() - self.block_indent.width(),
166 let comment_indent = Indent::from_width(self.config, self.buffer.cur_offset());
167 let comment_shape = Shape::legacy(comment_width, comment_indent);
168 let comment_str = rewrite_comment(subslice, false, comment_shape, self.config)
169 .unwrap_or_else(|| String::from(subslice));
170 self.buffer.push_str(&comment_str);
172 status.last_wspace = None;
173 status.line_start = offset + subslice.len();
175 if let Some('/') = subslice.chars().nth(1) {
176 // check that there are no contained block comments
179 .map(|s| s.trim_left())
180 .any(|s| s.len() >= 2 && &s[0..2] == "/*")
182 // Add a newline after line comments
183 self.buffer.push_str("\n");
185 } else if status.line_start <= snippet.len() {
186 // For other comments add a newline if there isn't one at the end already
187 match snippet[status.line_start..].chars().next() {
188 Some('\n') | Some('\r') => (),
189 _ => self.buffer.push_str("\n"),
193 status.cur_line += subslice_num_lines;
196 status.rewrite_next_comment = false;
201 fn write_snippet_inner<F>(
207 process_last_snippet: F,
209 F: Fn(&mut FmtVisitor, &str, &str),
211 // Trim whitespace from the right hand side of each line.
212 // Annoyingly, the library functions for splitting by lines etc. are not
213 // quite right, so we must do it ourselves.
214 let char_pos = self.codemap.lookup_char_pos(span.lo());
215 let file_name = &char_pos.file.name;
216 let mut status = SnippetStatus::new(char_pos.line);
218 fn replace_chars<'a>(string: &'a str) -> Cow<'a, str> {
219 if string.contains(char::is_whitespace) {
223 .map(|ch| if ch.is_whitespace() { ch } else { 'X' })
224 .collect::<String>(),
231 let snippet = &*match self.config.write_mode() {
232 WriteMode::Coverage => replace_chars(old_snippet),
233 _ => Cow::from(old_snippet),
236 for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
237 debug!("{:?}: {:?}", kind, subslice);
239 if let CodeCharKind::Comment = kind {
240 if self.process_comment(
253 // cur_line += newline_count;
254 // rewirte_next_comment = true;
256 for (mut i, c) in subslice.char_indices() {
262 .contains_line(file_name, status.cur_line)
264 status.last_wspace = None;
267 if let Some(lw) = status.last_wspace {
268 self.buffer.push_str(&snippet[status.line_start..lw]);
269 self.buffer.push_str("\n");
271 self.buffer.push_str(&snippet[status.line_start..i + 1]);
274 status.cur_line += 1;
275 status.line_start = i + 1;
276 status.last_wspace = None;
277 status.rewrite_next_comment = true;
278 } else if c.is_whitespace() {
279 if status.last_wspace.is_none() {
280 status.last_wspace = Some(i);
283 if status.last_wspace.is_some() {
284 status.line_start = i;
287 status.rewrite_next_comment = true;
288 status.last_wspace = None;
290 status.rewrite_next_comment = true;
291 status.last_wspace = None;
295 let remaining = snippet[status.line_start..subslice.len() + offset].trim();
296 if !remaining.is_empty() {
297 self.buffer.push_str(remaining);
298 status.line_start = subslice.len() + offset;
299 status.rewrite_next_comment = true;
303 process_last_snippet(self, &snippet[status.line_start..], snippet);
307 struct SnippetStatus {
309 last_wspace: Option<usize>,
310 rewrite_next_comment: bool,
315 fn new(cur_line: usize) -> Self {
319 rewrite_next_comment: true,