]> git.lizzy.rs Git - rust.git/blob - src/config/file_lines.rs
Merge pull request #3109 from scampi/issue-3038
[rust.git] / src / config / file_lines.rs
1 // Copyright 2016 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 //! This module contains types and functions to support formatting specific line ranges.
12
13 use std::collections::HashMap;
14 use std::path::PathBuf;
15 use std::rc::Rc;
16 use std::{cmp, fmt, iter, str};
17
18 use serde::de::{Deserialize, Deserializer};
19 use serde::ser::{self, Serialize, Serializer};
20 use serde_json as json;
21
22 use syntax::source_map::{self, SourceFile};
23
24 /// A range of lines in a file, inclusive of both ends.
25 pub struct LineRange {
26     pub file: Rc<SourceFile>,
27     pub lo: usize,
28     pub hi: usize,
29 }
30
31 /// Defines the name of an input - either a file or stdin.
32 #[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
33 pub enum FileName {
34     Real(PathBuf),
35     Stdin,
36 }
37
38 impl From<source_map::FileName> for FileName {
39     fn from(name: source_map::FileName) -> FileName {
40         match name {
41             source_map::FileName::Real(p) => FileName::Real(p),
42             source_map::FileName::Custom(ref f) if f == "stdin" => FileName::Stdin,
43             _ => unreachable!(),
44         }
45     }
46 }
47
48 impl fmt::Display for FileName {
49     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
50         match self {
51             FileName::Real(p) => write!(f, "{}", p.to_str().unwrap()),
52             FileName::Stdin => write!(f, "stdin"),
53         }
54     }
55 }
56
57 impl<'de> Deserialize<'de> for FileName {
58     fn deserialize<D>(deserializer: D) -> Result<FileName, D::Error>
59     where
60         D: Deserializer<'de>,
61     {
62         let s = String::deserialize(deserializer)?;
63         if s == "stdin" {
64             Ok(FileName::Stdin)
65         } else {
66             Ok(FileName::Real(s.into()))
67         }
68     }
69 }
70
71 impl Serialize for FileName {
72     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
73     where
74         S: Serializer,
75     {
76         let s = match self {
77             FileName::Stdin => Ok("stdin"),
78             FileName::Real(path) => path
79                 .to_str()
80                 .ok_or_else(|| ser::Error::custom("path can't be serialized as UTF-8 string")),
81         };
82
83         s.and_then(|s| serializer.serialize_str(s))
84     }
85 }
86
87 impl LineRange {
88     pub fn file_name(&self) -> FileName {
89         self.file.name.clone().into()
90     }
91 }
92
93 /// A range that is inclusive of both ends.
94 #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Deserialize)]
95 pub struct Range {
96     lo: usize,
97     hi: usize,
98 }
99
100 impl<'a> From<&'a LineRange> for Range {
101     fn from(range: &'a LineRange) -> Range {
102         Range::new(range.lo, range.hi)
103     }
104 }
105
106 impl Range {
107     pub fn new(lo: usize, hi: usize) -> Range {
108         Range { lo, hi }
109     }
110
111     fn is_empty(self) -> bool {
112         self.lo > self.hi
113     }
114
115     #[allow(dead_code)]
116     fn contains(self, other: Range) -> bool {
117         if other.is_empty() {
118             true
119         } else {
120             !self.is_empty() && self.lo <= other.lo && self.hi >= other.hi
121         }
122     }
123
124     fn intersects(self, other: Range) -> bool {
125         if self.is_empty() || other.is_empty() {
126             false
127         } else {
128             (self.lo <= other.hi && other.hi <= self.hi)
129                 || (other.lo <= self.hi && self.hi <= other.hi)
130         }
131     }
132
133     fn adjacent_to(self, other: Range) -> bool {
134         if self.is_empty() || other.is_empty() {
135             false
136         } else {
137             self.hi + 1 == other.lo || other.hi + 1 == self.lo
138         }
139     }
140
141     /// Returns a new `Range` with lines from `self` and `other` if they were adjacent or
142     /// intersect; returns `None` otherwise.
143     fn merge(self, other: Range) -> Option<Range> {
144         if self.adjacent_to(other) || self.intersects(other) {
145             Some(Range::new(
146                 cmp::min(self.lo, other.lo),
147                 cmp::max(self.hi, other.hi),
148             ))
149         } else {
150             None
151         }
152     }
153 }
154
155 /// A set of lines in files.
156 ///
157 /// It is represented as a multimap keyed on file names, with values a collection of
158 /// non-overlapping ranges sorted by their start point. An inner `None` is interpreted to mean all
159 /// lines in all files.
160 #[derive(Clone, Debug, Default, PartialEq)]
161 pub struct FileLines(Option<HashMap<FileName, Vec<Range>>>);
162
163 /// Normalizes the ranges so that the invariants for `FileLines` hold: ranges are non-overlapping,
164 /// and ordered by their start point.
165 fn normalize_ranges(ranges: &mut HashMap<FileName, Vec<Range>>) {
166     for ranges in ranges.values_mut() {
167         ranges.sort();
168         let mut result = vec![];
169         {
170             let mut iter = ranges.into_iter().peekable();
171             while let Some(next) = iter.next() {
172                 let mut next = *next;
173                 while let Some(&&mut peek) = iter.peek() {
174                     if let Some(merged) = next.merge(peek) {
175                         iter.next().unwrap();
176                         next = merged;
177                     } else {
178                         break;
179                     }
180                 }
181                 result.push(next)
182             }
183         }
184         *ranges = result;
185     }
186 }
187
188 impl FileLines {
189     /// Creates a `FileLines` that contains all lines in all files.
190     pub(crate) fn all() -> FileLines {
191         FileLines(None)
192     }
193
194     /// Returns true if this `FileLines` contains all lines in all files.
195     pub(crate) fn is_all(&self) -> bool {
196         self.0.is_none()
197     }
198
199     pub fn from_ranges(mut ranges: HashMap<FileName, Vec<Range>>) -> FileLines {
200         normalize_ranges(&mut ranges);
201         FileLines(Some(ranges))
202     }
203
204     /// Returns an iterator over the files contained in `self`.
205     pub fn files(&self) -> Files {
206         Files(self.0.as_ref().map(|m| m.keys()))
207     }
208
209     /// Returns JSON representation as accepted by the `--file-lines JSON` arg.
210     pub fn to_json_spans(&self) -> Vec<JsonSpan> {
211         match &self.0 {
212             None => vec![],
213             Some(file_ranges) => file_ranges
214                 .iter()
215                 .flat_map(|(file, ranges)| ranges.iter().map(move |r| (file, r)))
216                 .map(|(file, range)| JsonSpan {
217                     file: file.to_owned(),
218                     range: (range.lo, range.hi),
219                 })
220                 .collect(),
221         }
222     }
223
224     /// Returns true if `self` includes all lines in all files. Otherwise runs `f` on all ranges in
225     /// the designated file (if any) and returns true if `f` ever does.
226     fn file_range_matches<F>(&self, file_name: &FileName, f: F) -> bool
227     where
228         F: FnMut(&Range) -> bool,
229     {
230         let map = match self.0 {
231             // `None` means "all lines in all files".
232             None => return true,
233             Some(ref map) => map,
234         };
235
236         match canonicalize_path_string(file_name).and_then(|file| map.get(&file)) {
237             Some(ranges) => ranges.iter().any(f),
238             None => false,
239         }
240     }
241
242     /// Returns true if `range` is fully contained in `self`.
243     #[allow(dead_code)]
244     pub(crate) fn contains(&self, range: &LineRange) -> bool {
245         self.file_range_matches(&range.file_name(), |r| r.contains(Range::from(range)))
246     }
247
248     /// Returns true if any lines in `range` are in `self`.
249     pub(crate) fn intersects(&self, range: &LineRange) -> bool {
250         self.file_range_matches(&range.file_name(), |r| r.intersects(Range::from(range)))
251     }
252
253     /// Returns true if `line` from `file_name` is in `self`.
254     pub(crate) fn contains_line(&self, file_name: &FileName, line: usize) -> bool {
255         self.file_range_matches(file_name, |r| r.lo <= line && r.hi >= line)
256     }
257
258     /// Returns true if all the lines between `lo` and `hi` from `file_name` are in `self`.
259     pub(crate) fn contains_range(&self, file_name: &FileName, lo: usize, hi: usize) -> bool {
260         self.file_range_matches(file_name, |r| r.contains(Range::new(lo, hi)))
261     }
262 }
263
264 /// `FileLines` files iterator.
265 pub struct Files<'a>(Option<::std::collections::hash_map::Keys<'a, FileName, Vec<Range>>>);
266
267 impl<'a> iter::Iterator for Files<'a> {
268     type Item = &'a FileName;
269
270     fn next(&mut self) -> Option<&'a FileName> {
271         self.0.as_mut().and_then(Iterator::next)
272     }
273 }
274
275 fn canonicalize_path_string(file: &FileName) -> Option<FileName> {
276     match *file {
277         FileName::Real(ref path) => path.canonicalize().ok().map(FileName::Real),
278         _ => Some(file.clone()),
279     }
280 }
281
282 // This impl is needed for `Config::override_value` to work for use in tests.
283 impl str::FromStr for FileLines {
284     type Err = String;
285
286     fn from_str(s: &str) -> Result<FileLines, String> {
287         let v: Vec<JsonSpan> = json::from_str(s).map_err(|e| e.to_string())?;
288         let mut m = HashMap::new();
289         for js in v {
290             let (s, r) = JsonSpan::into_tuple(js)?;
291             m.entry(s).or_insert_with(|| vec![]).push(r);
292         }
293         Ok(FileLines::from_ranges(m))
294     }
295 }
296
297 // For JSON decoding.
298 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
299 pub struct JsonSpan {
300     file: FileName,
301     range: (usize, usize),
302 }
303
304 impl JsonSpan {
305     fn into_tuple(self) -> Result<(FileName, Range), String> {
306         let (lo, hi) = self.range;
307         let canonical = canonicalize_path_string(&self.file)
308             .ok_or_else(|| format!("Can't canonicalize {}", &self.file))?;
309         Ok((canonical, Range::new(lo, hi)))
310     }
311 }
312
313 // This impl is needed for inclusion in the `Config` struct. We don't have a toml representation
314 // for `FileLines`, so it will just panic instead.
315 impl<'de> ::serde::de::Deserialize<'de> for FileLines {
316     fn deserialize<D>(_: D) -> Result<Self, D::Error>
317     where
318         D: ::serde::de::Deserializer<'de>,
319     {
320         panic!(
321             "FileLines cannot be deserialized from a project rustfmt.toml file: please \
322              specify it via the `--file-lines` option instead"
323         );
324     }
325 }
326
327 // We also want to avoid attempting to serialize a FileLines to toml. The
328 // `Config` struct should ensure this impl is never reached.
329 impl ::serde::ser::Serialize for FileLines {
330     fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error>
331     where
332         S: ::serde::ser::Serializer,
333     {
334         unreachable!("FileLines cannot be serialized. This is a rustfmt bug.");
335     }
336 }
337
338 #[cfg(test)]
339 mod test {
340     use super::Range;
341
342     #[test]
343     fn test_range_intersects() {
344         assert!(Range::new(1, 2).intersects(Range::new(1, 1)));
345         assert!(Range::new(1, 2).intersects(Range::new(2, 2)));
346         assert!(!Range::new(1, 2).intersects(Range::new(0, 0)));
347         assert!(!Range::new(1, 2).intersects(Range::new(3, 10)));
348         assert!(!Range::new(1, 3).intersects(Range::new(5, 5)));
349     }
350
351     #[test]
352     fn test_range_adjacent_to() {
353         assert!(!Range::new(1, 2).adjacent_to(Range::new(1, 1)));
354         assert!(!Range::new(1, 2).adjacent_to(Range::new(2, 2)));
355         assert!(Range::new(1, 2).adjacent_to(Range::new(0, 0)));
356         assert!(Range::new(1, 2).adjacent_to(Range::new(3, 10)));
357         assert!(!Range::new(1, 3).adjacent_to(Range::new(5, 5)));
358     }
359
360     #[test]
361     fn test_range_contains() {
362         assert!(Range::new(1, 2).contains(Range::new(1, 1)));
363         assert!(Range::new(1, 2).contains(Range::new(2, 2)));
364         assert!(!Range::new(1, 2).contains(Range::new(0, 0)));
365         assert!(!Range::new(1, 2).contains(Range::new(3, 10)));
366     }
367
368     #[test]
369     fn test_range_merge() {
370         assert_eq!(None, Range::new(1, 3).merge(Range::new(5, 5)));
371         assert_eq!(None, Range::new(4, 7).merge(Range::new(0, 1)));
372         assert_eq!(
373             Some(Range::new(3, 7)),
374             Range::new(3, 5).merge(Range::new(4, 7))
375         );
376         assert_eq!(
377             Some(Range::new(3, 7)),
378             Range::new(3, 5).merge(Range::new(5, 7))
379         );
380         assert_eq!(
381             Some(Range::new(3, 7)),
382             Range::new(3, 5).merge(Range::new(6, 7))
383         );
384         assert_eq!(
385             Some(Range::new(3, 7)),
386             Range::new(3, 7).merge(Range::new(4, 5))
387         );
388     }
389
390     use super::json::{self, json};
391     use super::{FileLines, FileName};
392     use std::{collections::HashMap, path::PathBuf};
393
394     #[test]
395     fn file_lines_to_json() {
396         let ranges: HashMap<FileName, Vec<Range>> = [
397             (
398                 FileName::Real(PathBuf::from("src/main.rs")),
399                 vec![Range::new(1, 3), Range::new(5, 7)],
400             ),
401             (
402                 FileName::Real(PathBuf::from("src/lib.rs")),
403                 vec![Range::new(1, 7)],
404             ),
405         ]
406         .iter()
407         .cloned()
408         .collect();
409
410         let file_lines = FileLines::from_ranges(ranges);
411         let mut spans = file_lines.to_json_spans();
412         spans.sort();
413         let json = json::to_value(&spans).unwrap();
414         assert_eq!(
415             json,
416             json! {[
417                 {"file": "src/lib.rs",  "range": [1, 7]},
418                 {"file": "src/main.rs", "range": [1, 3]},
419                 {"file": "src/main.rs", "range": [5, 7]},
420             ]}
421         );
422     }
423 }