]> git.lizzy.rs Git - rust.git/blob - src/missed_spans.rs
Fix issue 1124 - detect start of output rather than start of input file when writing...
[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
16 impl<'a> FmtVisitor<'a> {
17     fn output_at_start(&self) -> bool {
18         self.buffer.len == 0
19     }
20
21     // TODO these format_missing methods are ugly. Refactor and add unit tests
22     // for the central whitespace stripping loop.
23     pub fn format_missing(&mut self, end: BytePos) {
24         self.format_missing_inner(end,
25                                   |this, last_snippet, _| this.buffer.push_str(last_snippet))
26     }
27
28     pub fn format_missing_with_indent(&mut self, end: BytePos) {
29         let config = self.config;
30         self.format_missing_inner(end, |this, last_snippet, snippet| {
31             this.buffer.push_str(last_snippet.trim_right());
32             if last_snippet == snippet && !this.output_at_start() {
33                 // No new lines in the snippet.
34                 this.buffer.push_str("\n");
35             }
36             let indent = this.block_indent.to_string(config);
37             this.buffer.push_str(&indent);
38         })
39     }
40
41     fn format_missing_inner<F: Fn(&mut FmtVisitor, &str, &str)>(&mut self,
42                                                                 end: BytePos,
43                                                                 process_last_snippet: F) {
44         let start = self.last_pos;
45
46         if start == end {
47             // Do nothing if this is the beginning of the file.
48             if !self.output_at_start() {
49                 process_last_snippet(self, "", "");
50             }
51             return;
52         }
53
54         assert!(start < end,
55                 "Request to format inverted span: {:?} to {:?}",
56                 self.codemap.lookup_char_pos(start),
57                 self.codemap.lookup_char_pos(end));
58
59         self.last_pos = end;
60         let span = codemap::mk_sp(start, end);
61
62         self.write_snippet(span, &process_last_snippet);
63     }
64
65     fn write_snippet<F>(&mut self, span: Span, process_last_snippet: F)
66         where F: Fn(&mut FmtVisitor, &str, &str)
67     {
68         // Get a snippet from the file start to the span's hi without allocating.
69         // We need it to determine what precedes the current comment. If the comment
70         // follows code on the same line, we won't touch it.
71         let big_span_lo = self.codemap.lookup_char_pos(span.lo).file.start_pos;
72         let local_begin = self.codemap.lookup_byte_offset(big_span_lo);
73         let local_end = self.codemap.lookup_byte_offset(span.hi);
74         let start_index = local_begin.pos.to_usize();
75         let end_index = local_end.pos.to_usize();
76         let big_snippet = &local_begin.fm.src.as_ref().unwrap()[start_index..end_index];
77
78         let big_diff = (span.lo - big_span_lo).to_usize();
79         let snippet = self.snippet(span);
80
81         self.write_snippet_inner(big_snippet, big_diff, &snippet, process_last_snippet);
82     }
83
84     fn write_snippet_inner<F>(&mut self,
85                               big_snippet: &str,
86                               big_diff: usize,
87                               old_snippet: &str,
88                               process_last_snippet: F)
89         where F: Fn(&mut FmtVisitor, &str, &str)
90     {
91         // Trim whitespace from the right hand side of each line.
92         // Annoyingly, the library functions for splitting by lines etc. are not
93         // quite right, so we must do it ourselves.
94         let mut line_start = 0;
95         let mut last_wspace = None;
96         let mut rewrite_next_comment = true;
97
98         fn replace_chars(string: &str) -> String {
99             string.chars()
100                 .map(|ch| { if ch.is_whitespace() { ch } else { 'X' } })
101                 .collect()
102         }
103
104         let replaced = match self.config.write_mode {
105             WriteMode::Coverage => replace_chars(old_snippet),
106             _ => old_snippet.to_owned(),
107         };
108         let snippet = &*replaced;
109
110         for (kind, offset, subslice) in CommentCodeSlices::new(snippet) {
111             if let CodeCharKind::Comment = kind {
112                 let last_char = big_snippet[..(offset + big_diff)]
113                     .chars()
114                     .rev()
115                     .skip_while(|rev_c| [' ', '\t'].contains(&rev_c))
116                     .next();
117
118                 let fix_indent = last_char.map_or(true, |rev_c| ['{', '\n'].contains(&rev_c));
119
120                 if rewrite_next_comment && fix_indent {
121                     if let Some('{') = last_char {
122                         self.buffer.push_str("\n");
123                     }
124
125                     let comment_width = ::std::cmp::min(self.config.ideal_width,
126                                                         self.config.max_width -
127                                                         self.block_indent.width());
128
129                     self.buffer.push_str(&self.block_indent.to_string(self.config));
130                     self.buffer.push_str(&rewrite_comment(subslice,
131                                                           false,
132                                                           comment_width,
133                                                           self.block_indent,
134                                                           self.config)
135                         .unwrap());
136
137                     last_wspace = None;
138                     line_start = offset + subslice.len();
139
140                     if let Some('/') = subslice.chars().skip(1).next() {
141                         // Add a newline after line comments
142                         self.buffer.push_str("\n");
143                     } else if line_start <= snippet.len() {
144                         // For other comments add a newline if there isn't one at the end already
145                         match snippet[line_start..].chars().next() {
146                             Some('\n') | Some('\r') => (),
147                             _ => self.buffer.push_str("\n"),
148                         }
149                     }
150
151                     continue;
152                 } else {
153                     rewrite_next_comment = false;
154                 }
155             }
156
157             for (mut i, c) in subslice.char_indices() {
158                 i += offset;
159
160                 if c == '\n' {
161                     if let Some(lw) = last_wspace {
162                         self.buffer.push_str(&snippet[line_start..lw]);
163                         self.buffer.push_str("\n");
164                     } else {
165                         self.buffer.push_str(&snippet[line_start..i + 1]);
166                     }
167
168                     line_start = i + 1;
169                     last_wspace = None;
170                     rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
171                 } else {
172                     if c.is_whitespace() {
173                         if last_wspace.is_none() {
174                             last_wspace = Some(i);
175                         }
176                     } else {
177                         rewrite_next_comment = rewrite_next_comment || kind == CodeCharKind::Normal;
178                         last_wspace = None;
179                     }
180                 }
181             }
182         }
183
184         process_last_snippet(self, &snippet[line_start..], &snippet);
185     }
186 }