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.
11 use config::WriteMode;
12 use visitor::FmtVisitor;
13 use syntax::codemap::{self, BytePos, Span, Pos};
14 use comment::{CodeCharKind, CommentCodeSlices, rewrite_comment};
17 impl<'a> FmtVisitor<'a> {
18 fn output_at_start(&self) -> bool {
22 // TODO these format_missing methods are ugly. Refactor and add unit tests
23 // for the central whitespace stripping loop.
24 pub fn format_missing(&mut self, end: BytePos) {
25 self.format_missing_inner(end,
26 |this, last_snippet, _| this.buffer.push_str(last_snippet))
29 pub fn format_missing_with_indent(&mut self, end: BytePos) {
30 let config = self.config;
31 self.format_missing_inner(end, |this, last_snippet, snippet| {
32 this.buffer.push_str(last_snippet.trim_right());
33 if last_snippet == snippet && !this.output_at_start() {
34 // No new lines in the snippet.
35 this.buffer.push_str("\n");
37 let indent = this.block_indent.to_string(config);
38 this.buffer.push_str(&indent);
42 pub fn format_missing_no_indent(&mut self, end: BytePos) {
43 self.format_missing_inner(end, |this, last_snippet, _| {
44 this.buffer.push_str(last_snippet.trim_right());
48 fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, &str)>(&mut self,
50 process_last_snippet: F) {
51 let start = self.last_pos;
54 // Do nothing if this is the beginning of the file.
55 if !self.output_at_start() {
56 process_last_snippet(self, "", "");
62 "Request to format inverted span: {:?} to {:?}",
63 self.codemap.lookup_char_pos(start),
64 self.codemap.lookup_char_pos(end));
67 let span = codemap::mk_sp(start, end);
69 self.write_snippet(span, &process_last_snippet);
72 fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
73 where F: Fn(&mut FmtVisitor, &str, &str)
75 // Get a snippet from the file start to the span's hi without allocating.
76 // We need it to determine what precedes the current comment. If the comment
77 // follows code on the same line, we won't touch it.
78 let big_span_lo = self.codemap
79 .lookup_char_pos(span.lo)
82 let local_begin = self.codemap.lookup_byte_offset(big_span_lo);
83 let local_end = self.codemap.lookup_byte_offset(span.hi);
84 let start_index = local_begin.pos.to_usize();
85 let end_index = local_end.pos.to_usize();
86 let big_snippet = &local_begin.fm
90 [start_index..end_index];
92 let big_diff = (span.lo - big_span_lo).to_usize();
93 let snippet = self.snippet(span);
95 debug!("write_snippet `{}`", snippet);
97 self.write_snippet_inner(big_snippet, big_diff, &snippet, process_last_snippet);
100 fn write_snippet_inner<F>(&mut self,
104 process_last_snippet: F)
105 where F: Fn(&mut FmtVisitor, &str, &str)
107 // Trim whitespace from the right hand side of each line.
108 // Annoyingly, the library functions for splitting by lines etc. are not
109 // quite right, so we must do it ourselves.
110 let mut line_start = 0;
111 let mut last_wspace = None;
112 let mut rewrite_next_comment = true;
114 fn replace_chars(string: &str) -> String {
115 string.chars().map(|ch| if ch.is_whitespace() { ch } else { 'X' }).collect()
118 let replaced = match self.config.write_mode {
119 WriteMode::Coverage => replace_chars(old_snippet),
120 _ => old_snippet.to_owned(),
122 let snippet = &*replaced;
124 for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
125 debug!("{:?}: {:?}", kind, subslice);
127 if let CodeCharKind::Comment = kind {
128 let last_char = big_snippet[..(offset + big_diff)]
131 .skip_while(|rev_c| [' ', '\t'].contains(rev_c))
134 let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
136 if rewrite_next_comment {
138 if let Some('{') = last_char {
139 self.buffer.push_str("\n");
141 self.buffer.push_str(&self.block_indent.to_string(self.config));
143 self.buffer.push_str(" ");
146 let comment_width = ::std::cmp::min(self.config.ideal_width,
147 self.config.max_width -
148 self.block_indent.width());
150 self.buffer.push_str(&rewrite_comment(subslice,
152 Shape::legacy(comment_width,
158 line_start = offset + subslice.len();
160 if let Some('/') = subslice.chars().skip(1).next() {
161 // check that there are no contained block comments
162 if !subslice.split('\n').map(|s| s.trim_left()).any(|s| {
166 // Add a newline after line comments
167 self.buffer.push_str("\n");
169 } else if line_start <= snippet.len() {
170 // For other comments add a newline if there isn't one at the end already
171 match snippet[line_start..].chars().next() {
172 Some('\n') | Some('\r') => (),
173 _ => self.buffer.push_str("\n"),
179 rewrite_next_comment = false;
183 for (mut i, c) in subslice.char_indices() {
187 if let Some(lw) = last_wspace {
188 self.buffer.push_str(&snippet[line_start..lw]);
189 self.buffer.push_str("\n");
191 self.buffer.push_str(&snippet[line_start..i + 1]);
196 rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
197 } else if c.is_whitespace() {
198 if last_wspace.is_none() {
199 last_wspace = Some(i);
202 if last_wspace.is_some() {
206 rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
209 rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
214 let remaining = snippet[line_start..subslice.len() + offset].trim();
215 if !remaining.is_empty() {
216 self.buffer.push_str(remaining);
217 line_start = subslice.len() + offset;
218 rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
222 process_last_snippet(self, &snippet[line_start..], snippet);