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