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