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