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