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