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),
223 /// Returns true if `self` includes all lines in all files. Otherwise runs `f` on all ranges in
224 /// the designated file (if any) and returns true if `f` ever does.
225 fn file_range_matches<F>(&self, file_name: &FileName, f: F) -> bool
227 F: FnMut(&Range) -> bool,
229 let map = match self.0 {
230 // `None` means "all lines in all files".
232 Some(ref map) => map,
235 match canonicalize_path_string(file_name).and_then(|file| map.get(&file)) {
236 Some(ranges) => ranges.iter().any(f),
241 /// Returns true if `range` is fully contained in `self`.
243 pub(crate) fn contains(&self, range: &LineRange) -> bool {
244 self.file_range_matches(&range.file_name(), |r| r.contains(Range::from(range)))
247 /// Returns true if any lines in `range` are in `self`.
248 pub(crate) fn intersects(&self, range: &LineRange) -> bool {
249 self.file_range_matches(&range.file_name(), |r| r.intersects(Range::from(range)))
252 /// Returns true if `line` from `file_name` is in `self`.
253 pub(crate) fn contains_line(&self, file_name: &FileName, line: usize) -> bool {
254 self.file_range_matches(file_name, |r| r.lo <= line && r.hi >= line)
257 /// Returns true if all the lines between `lo` and `hi` from `file_name` are in `self`.
258 pub(crate) fn contains_range(&self, file_name: &FileName, lo: usize, hi: usize) -> bool {
259 self.file_range_matches(file_name, |r| r.contains(Range::new(lo, hi)))
263 /// `FileLines` files iterator.
264 pub struct Files<'a>(Option<::std::collections::hash_map::Keys<'a, FileName, Vec<Range>>>);
266 impl<'a> iter::Iterator for Files<'a> {
267 type Item = &'a FileName;
269 fn next(&mut self) -> Option<&'a FileName> {
270 self.0.as_mut().and_then(Iterator::next)
274 fn canonicalize_path_string(file: &FileName) -> Option<FileName> {
276 FileName::Real(ref path) => path.canonicalize().ok().map(FileName::Real),
277 _ => Some(file.clone()),
281 // This impl is needed for `Config::override_value` to work for use in tests.
282 impl str::FromStr for FileLines {
285 fn from_str(s: &str) -> Result<FileLines, String> {
286 let v: Vec<JsonSpan> = json::from_str(s).map_err(|e| e.to_string())?;
287 let mut m = HashMap::new();
289 let (s, r) = JsonSpan::into_tuple(js)?;
290 m.entry(s).or_insert_with(|| vec![]).push(r);
292 Ok(FileLines::from_ranges(m))
296 // For JSON decoding.
297 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
298 pub struct JsonSpan {
300 range: (usize, usize),
304 fn into_tuple(self) -> Result<(FileName, Range), String> {
305 let (lo, hi) = self.range;
306 let canonical = canonicalize_path_string(&self.file)
307 .ok_or_else(|| format!("Can't canonicalize {}", &self.file))?;
308 Ok((canonical, Range::new(lo, hi)))
312 // This impl is needed for inclusion in the `Config` struct. We don't have a toml representation
313 // for `FileLines`, so it will just panic instead.
314 impl<'de> ::serde::de::Deserialize<'de> for FileLines {
315 fn deserialize<D>(_: D) -> Result<Self, D::Error>
317 D: ::serde::de::Deserializer<'de>,
320 "FileLines cannot be deserialized from a project rustfmt.toml file: please \
321 specify it via the `--file-lines` option instead"
326 // We also want to avoid attempting to serialize a FileLines to toml. The
327 // `Config` struct should ensure this impl is never reached.
328 impl ::serde::ser::Serialize for FileLines {
329 fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error>
331 S: ::serde::ser::Serializer,
333 unreachable!("FileLines cannot be serialized. This is a rustfmt bug.");
342 fn test_range_intersects() {
343 assert!(Range::new(1, 2).intersects(Range::new(1, 1)));
344 assert!(Range::new(1, 2).intersects(Range::new(2, 2)));
345 assert!(!Range::new(1, 2).intersects(Range::new(0, 0)));
346 assert!(!Range::new(1, 2).intersects(Range::new(3, 10)));
347 assert!(!Range::new(1, 3).intersects(Range::new(5, 5)));
351 fn test_range_adjacent_to() {
352 assert!(!Range::new(1, 2).adjacent_to(Range::new(1, 1)));
353 assert!(!Range::new(1, 2).adjacent_to(Range::new(2, 2)));
354 assert!(Range::new(1, 2).adjacent_to(Range::new(0, 0)));
355 assert!(Range::new(1, 2).adjacent_to(Range::new(3, 10)));
356 assert!(!Range::new(1, 3).adjacent_to(Range::new(5, 5)));
360 fn test_range_contains() {
361 assert!(Range::new(1, 2).contains(Range::new(1, 1)));
362 assert!(Range::new(1, 2).contains(Range::new(2, 2)));
363 assert!(!Range::new(1, 2).contains(Range::new(0, 0)));
364 assert!(!Range::new(1, 2).contains(Range::new(3, 10)));
368 fn test_range_merge() {
369 assert_eq!(None, Range::new(1, 3).merge(Range::new(5, 5)));
370 assert_eq!(None, Range::new(4, 7).merge(Range::new(0, 1)));
372 Some(Range::new(3, 7)),
373 Range::new(3, 5).merge(Range::new(4, 7))
376 Some(Range::new(3, 7)),
377 Range::new(3, 5).merge(Range::new(5, 7))
380 Some(Range::new(3, 7)),
381 Range::new(3, 5).merge(Range::new(6, 7))
384 Some(Range::new(3, 7)),
385 Range::new(3, 7).merge(Range::new(4, 5))
389 use super::json::{self, json, json_internal};
390 use super::{FileLines, FileName};
391 use std::{collections::HashMap, path::PathBuf};
394 fn file_lines_to_json() {
395 let ranges: HashMap<FileName, Vec<Range>> = [
397 FileName::Real(PathBuf::from("src/main.rs")),
398 vec![Range::new(1, 3), Range::new(5, 7)],
401 FileName::Real(PathBuf::from("src/lib.rs")),
402 vec![Range::new(1, 7)],
409 let file_lines = FileLines::from_ranges(ranges);
410 let mut spans = file_lines.to_json_spans();
412 let json = json::to_value(&spans).unwrap();
416 {"file": "src/lib.rs", "range": [1, 7]},
417 {"file": "src/main.rs", "range": [1, 3]},
418 {"file": "src/main.rs", "range": [5, 7]},