]> git.lizzy.rs Git - rust.git/blob - src/missed_spans.rs
Use the last line's width for indent width in rewriting missed span
[rust.git] / src / missed_spans.rs
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.
4 //
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.
10
11 use {Indent, Shape};
12 use comment::{rewrite_comment, CodeCharKind, CommentCodeSlices};
13 use config::WriteMode;
14 use syntax::codemap::{BytePos, Pos, Span};
15 use utils::mk_sp;
16 use visitor::FmtVisitor;
17
18 impl<'a> FmtVisitor<'a> {
19     fn output_at_start(&self) -> bool {
20         self.buffer.len == 0
21     }
22
23     // TODO these format_missing methods are ugly. Refactor and add unit tests
24     // for the central whitespace stripping loop.
25     pub fn format_missing(&mut self, end: BytePos) {
26         self.format_missing_inner(end, |this, last_snippet, _| {
27             this.buffer.push_str(last_snippet)
28         })
29     }
30
31     pub fn format_missing_with_indent(&mut self, end: BytePos) {
32         let config = self.config;
33         self.format_missing_inner(end, |this, last_snippet, snippet| {
34             this.buffer.push_str(last_snippet.trim_right());
35             if last_snippet == snippet && !this.output_at_start() {
36                 // No new lines in the snippet.
37                 this.buffer.push_str("\n");
38             }
39             let indent = this.block_indent.to_string(config);
40             this.buffer.push_str(&indent);
41         })
42     }
43
44     pub fn format_missing_no_indent(&mut self, end: BytePos) {
45         self.format_missing_inner(end, |this, last_snippet, _| {
46             this.buffer.push_str(last_snippet.trim_right());
47         })
48     }
49
50     fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, &str)>(
51         &mut self,
52         end: BytePos,
53         process_last_snippet: F,
54     ) {
55         let start = self.last_pos;
56
57         if start == end {
58             // Do nothing if this is the beginning of the file.
59             if !self.output_at_start() {
60                 process_last_snippet(self, "", "");
61             }
62             return;
63         }
64
65         assert!(
66             start < end,
67             "Request to format inverted span: {:?} to {:?}",
68             self.codemap.lookup_char_pos(start),
69             self.codemap.lookup_char_pos(end)
70         );
71
72         self.last_pos = end;
73         let span = mk_sp(start, end);
74
75         self.write_snippet(span, &process_last_snippet);
76     }
77
78     fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
79     where
80         F: Fn(&mut FmtVisitor, &str, &str),
81     {
82         // Get a snippet from the file start to the span's hi without allocating.
83         // We need it to determine what precedes the current comment. If the comment
84         // follows code on the same line, we won't touch it.
85         let big_span_lo = self.codemap.lookup_char_pos(span.lo()).file.start_pos;
86         let local_begin = self.codemap.lookup_byte_offset(big_span_lo);
87         let local_end = self.codemap.lookup_byte_offset(span.hi());
88         let start_index = local_begin.pos.to_usize();
89         let end_index = local_end.pos.to_usize();
90         let big_snippet = &local_begin.fm.src.as_ref().unwrap()[start_index..end_index];
91
92         let big_diff = (span.lo() - big_span_lo).to_usize();
93         let snippet = self.snippet(span);
94
95         debug!("write_snippet `{}`", snippet);
96
97         self.write_snippet_inner(big_snippet, big_diff, &snippet, span, process_last_snippet);
98     }
99
100     fn write_snippet_inner<F>(
101         &mut self,
102         big_snippet: &str,
103         big_diff: usize,
104         old_snippet: &str,
105         span: Span,
106         process_last_snippet: F,
107     ) where
108         F: Fn(&mut FmtVisitor, &str, &str),
109     {
110         // Trim whitespace from the right hand side of each line.
111         // Annoyingly, the library functions for splitting by lines etc. are not
112         // quite right, so we must do it ourselves.
113         let mut line_start = 0;
114         let mut last_wspace = None;
115         let mut rewrite_next_comment = true;
116
117         let char_pos = self.codemap.lookup_char_pos(span.lo());
118         let file_name = &char_pos.file.name;
119         let mut cur_line = char_pos.line;
120
121         fn replace_chars(string: &str) -> String {
122             string
123                 .chars()
124                 .map(|ch| if ch.is_whitespace() { ch } else { 'X' })
125                 .collect()
126         }
127
128         let replaced = match self.config.write_mode() {
129             WriteMode::Coverage => replace_chars(old_snippet),
130             _ => old_snippet.to_owned(),
131         };
132         let snippet = &*replaced;
133
134         for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
135             debug!("{:?}: {:?}", kind, subslice);
136
137             if let CodeCharKind::Comment = kind {
138                 let last_char = big_snippet[..(offset + big_diff)]
139                     .chars()
140                     .rev()
141                     .skip_while(|rev_c| [' ', '\t'].contains(rev_c))
142                     .next();
143
144                 let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
145
146                 let subslice_num_lines = subslice.chars().filter(|c| *c == '\n').count();
147
148                 if rewrite_next_comment &&
149                     !self.config.file_lines().intersects_range(
150                         file_name,
151                         cur_line,
152                         cur_line + subslice_num_lines,
153                     ) {
154                     rewrite_next_comment = false;
155                 }
156
157                 if rewrite_next_comment {
158                     if fix_indent {
159                         if let Some('{') = last_char {
160                             self.buffer.push_str("\n");
161                         }
162                         self.buffer
163                             .push_str(&self.block_indent.to_string(self.config));
164                     } else {
165                         self.buffer.push_str(" ");
166                     }
167
168                     let comment_width = ::std::cmp::min(
169                         self.config.comment_width(),
170                         self.config.max_width() - self.block_indent.width(),
171                     );
172                     let comment_indent = Indent::from_width(self.config, self.buffer.cur_offset());
173
174                     self.buffer.push_str(&rewrite_comment(
175                         subslice,
176                         false,
177                         Shape::legacy(comment_width, comment_indent),
178                         self.config,
179                     ).unwrap());
180
181                     last_wspace = None;
182                     line_start = offset + subslice.len();
183
184                     if let Some('/') = subslice.chars().nth(1) {
185                         // check that there are no contained block comments
186                         if !subslice
187                             .split('\n')
188                             .map(|s| s.trim_left())
189                             .any(|s| s.len() >= 2 && &s[0..2] == "/*")
190                         {
191                             // Add a newline after line comments
192                             self.buffer.push_str("\n");
193                         }
194                     } else if line_start <= snippet.len() {
195                         // For other comments add a newline if there isn't one at the end already
196                         match snippet[line_start..].chars().next() {
197                             Some('\n') | Some('\r') => (),
198                             _ => self.buffer.push_str("\n"),
199                         }
200                     }
201
202                     cur_line += subslice_num_lines;
203                     continue;
204                 } else {
205                     rewrite_next_comment = false;
206                 }
207             }
208
209             for (mut i, c) in subslice.char_indices() {
210                 i += offset;
211
212                 if c == '\n' {
213                     if !self.config.file_lines().contains_line(file_name, cur_line) {
214                         last_wspace = None;
215                     }
216
217                     if let Some(lw) = last_wspace {
218                         self.buffer.push_str(&snippet[line_start..lw]);
219                         self.buffer.push_str("\n");
220                     } else {
221                         self.buffer.push_str(&snippet[line_start..i + 1]);
222                     }
223
224                     cur_line += 1;
225                     line_start = i + 1;
226                     last_wspace = None;
227                     rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
228                 } else if c.is_whitespace() {
229                     if last_wspace.is_none() {
230                         last_wspace = Some(i);
231                     }
232                 } else if c == ';' {
233                     if last_wspace.is_some() {
234                         line_start = i;
235                     }
236
237                     rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
238                     last_wspace = None;
239                 } else {
240                     rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
241                     last_wspace = None;
242                 }
243             }
244
245             let remaining = snippet[line_start..subslice.len() + offset].trim();
246             if !remaining.is_empty() {
247                 self.buffer.push_str(remaining);
248                 line_start = subslice.len() + offset;
249                 rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
250             }
251         }
252
253         process_last_snippet(self, &snippet[line_start..], snippet);
254     }
255 }