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.
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.
11 //! This module contains types and functions to support formatting specific line ranges.
13 use std::collections::HashMap;
14 use std::path::PathBuf;
16 use std::{cmp, fmt, iter, str};
18 use serde::de::{Deserialize, Deserializer};
19 use serde::ser::{self, Serialize, Serializer};
20 use serde_json as json;
22 use syntax::source_map::{self, SourceFile};
24 /// A range of lines in a file, inclusive of both ends.
25 pub struct LineRange {
26 pub file: Rc<SourceFile>,
31 /// Defines the name of an input - either a file or stdin.
32 #[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
38 impl From<source_map::FileName> for FileName {
39 fn from(name: source_map::FileName) -> FileName {
41 source_map::FileName::Real(p) => FileName::Real(p),
42 source_map::FileName::Custom(ref f) if f == "stdin" => FileName::Stdin,
48 impl fmt::Display for FileName {
49 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51 FileName::Real(p) => write!(f, "{}", p.to_str().unwrap()),
52 FileName::Stdin => write!(f, "stdin"),
57 impl<'de> Deserialize<'de> for FileName {
58 fn deserialize<D>(deserializer: D) -> Result<FileName, D::Error>
62 let s = String::deserialize(deserializer)?;
66 Ok(FileName::Real(s.into()))
71 impl Serialize for FileName {
72 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
77 FileName::Stdin => Ok("stdin"),
78 FileName::Real(path) => path
80 .ok_or_else(|| ser::Error::custom("path can't be serialized as UTF-8 string")),
83 s.and_then(|s| serializer.serialize_str(s))
88 pub fn file_name(&self) -> FileName {
89 self.file.name.clone().into()
93 /// A range that is inclusive of both ends.
94 #[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Deserialize)]
100 impl<'a> From<&'a LineRange> for Range {
101 fn from(range: &'a LineRange) -> Range {
102 Range::new(range.lo, range.hi)
107 pub fn new(lo: usize, hi: usize) -> Range {
111 fn is_empty(self) -> bool {
116 fn contains(self, other: Range) -> bool {
117 if other.is_empty() {
120 !self.is_empty() && self.lo <= other.lo && self.hi >= other.hi
124 fn intersects(self, other: Range) -> bool {
125 if self.is_empty() || other.is_empty() {
128 (self.lo <= other.hi && other.hi <= self.hi)
129 || (other.lo <= self.hi && self.hi <= other.hi)
133 fn adjacent_to(self, other: Range) -> bool {
134 if self.is_empty() || other.is_empty() {
137 self.hi + 1 == other.lo || other.hi + 1 == self.lo
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) {
146 cmp::min(self.lo, other.lo),
147 cmp::max(self.hi, other.hi),
155 /// A set of lines in files.
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>>>);
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() {
168 let mut result = vec![];
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();
189 /// Creates a `FileLines` that contains all lines in all files.
190 pub(crate) fn all() -> FileLines {
194 /// Returns true if this `FileLines` contains all lines in all files.
195 pub(crate) fn is_all(&self) -> bool {
199 pub fn from_ranges(mut ranges: HashMap<FileName, Vec<Range>>) -> FileLines {
200 normalize_ranges(&mut ranges);
201 FileLines(Some(ranges))
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()))
209 /// Returns JSON representation as accepted by the `--file-lines JSON` arg.
210 pub fn to_json_spans(&self) -> Vec<JsonSpan> {
213 Some(file_ranges) => file_ranges
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),
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
228 F: FnMut(&Range) -> bool,
230 let map = match self.0 {
231 // `None` means "all lines in all files".
233 Some(ref map) => map,
236 match canonicalize_path_string(file_name).and_then(|file| map.get(&file)) {
237 Some(ranges) => ranges.iter().any(f),
242 /// Returns true if `range` is fully contained in `self`.
244 pub(crate) fn contains(&self, range: &LineRange) -> bool {
245 self.file_range_matches(&range.file_name(), |r| r.contains(Range::from(range)))
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)))
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)
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)))
264 /// `FileLines` files iterator.
265 pub struct Files<'a>(Option<::std::collections::hash_map::Keys<'a, FileName, Vec<Range>>>);
267 impl<'a> iter::Iterator for Files<'a> {
268 type Item = &'a FileName;
270 fn next(&mut self) -> Option<&'a FileName> {
271 self.0.as_mut().and_then(Iterator::next)
275 fn canonicalize_path_string(file: &FileName) -> Option<FileName> {
277 FileName::Real(ref path) => path.canonicalize().ok().map(FileName::Real),
278 _ => Some(file.clone()),
282 // This impl is needed for `Config::override_value` to work for use in tests.
283 impl str::FromStr for FileLines {
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();
290 let (s, r) = JsonSpan::into_tuple(js)?;
291 m.entry(s).or_insert_with(|| vec![]).push(r);
293 Ok(FileLines::from_ranges(m))
297 // For JSON decoding.
298 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
299 pub struct JsonSpan {
301 range: (usize, usize),
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)))
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>
318 D: ::serde::de::Deserializer<'de>,
321 "FileLines cannot be deserialized from a project rustfmt.toml file: please \
322 specify it via the `--file-lines` option instead"
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>
332 S: ::serde::ser::Serializer,
334 unreachable!("FileLines cannot be serialized. This is a rustfmt bug.");
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)));
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)));
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)));
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)));
373 Some(Range::new(3, 7)),
374 Range::new(3, 5).merge(Range::new(4, 7))
377 Some(Range::new(3, 7)),
378 Range::new(3, 5).merge(Range::new(5, 7))
381 Some(Range::new(3, 7)),
382 Range::new(3, 5).merge(Range::new(6, 7))
385 Some(Range::new(3, 7)),
386 Range::new(3, 7).merge(Range::new(4, 5))
390 use super::json::{self, json};
391 use super::{FileLines, FileName};
392 use std::{collections::HashMap, path::PathBuf};
395 fn file_lines_to_json() {
396 let ranges: HashMap<FileName, Vec<Range>> = [
398 FileName::Real(PathBuf::from("src/main.rs")),
399 vec![Range::new(1, 3), Range::new(5, 7)],
402 FileName::Real(PathBuf::from("src/lib.rs")),
403 vec![Range::new(1, 7)],
410 let file_lines = FileLines::from_ranges(ranges);
411 let mut spans = file_lines.to_json_spans();
413 let json = json::to_value(&spans).unwrap();
417 {"file": "src/lib.rs", "range": [1, 7]},
418 {"file": "src/main.rs", "range": [1, 3]},
419 {"file": "src/main.rs", "range": [5, 7]},