]> git.lizzy.rs Git - rust.git/blob - src/codemap.rs
codemap: Add utilities for looking up line ranges of spans
[rust.git] / src / codemap.rs
1 use std::rc::Rc;
2
3 use syntax::codemap::{BytePos, CodeMap, FileMap, Span};
4
5 use comment::FindUncommented;
6
7 /// A range of lines in a file, inclusive of both ends.
8 pub struct LineRange {
9     pub file: Rc<FileMap>,
10     pub lo: usize,
11     pub hi: usize,
12 }
13
14 impl LineRange {
15     pub fn file_name(&self) -> &str {
16         self.file.as_ref().name.as_str()
17     }
18 }
19
20 pub trait SpanUtils {
21     fn span_after(&self, original: Span, needle: &str) -> BytePos;
22     fn span_after_last(&self, original: Span, needle: &str) -> BytePos;
23     fn span_before(&self, original: Span, needle: &str) -> BytePos;
24 }
25
26 pub trait LineRangeUtils {
27     /// Returns the `LineRange` that corresponds to `span` in `self`.
28     ///
29     /// # Panics
30     ///
31     /// Panics if `span` crosses a file boundary, which shouldn't happen.
32     fn lookup_line_range(&self, span: Span) -> LineRange;
33 }
34
35 impl SpanUtils for CodeMap {
36     #[inline]
37     fn span_after(&self, original: Span, needle: &str) -> BytePos {
38         let snippet = self.span_to_snippet(original).unwrap();
39         let offset = snippet.find_uncommented(needle).unwrap() + needle.len();
40
41         original.lo + BytePos(offset as u32)
42     }
43
44     #[inline]
45     fn span_after_last(&self, original: Span, needle: &str) -> BytePos {
46         let snippet = self.span_to_snippet(original).unwrap();
47         let mut offset = 0;
48
49         while let Some(additional_offset) = snippet[offset..].find_uncommented(needle) {
50             offset += additional_offset + needle.len();
51         }
52
53         original.lo + BytePos(offset as u32)
54     }
55
56     #[inline]
57     fn span_before(&self, original: Span, needle: &str) -> BytePos {
58         let snippet = self.span_to_snippet(original).unwrap();
59         let offset = snippet.find_uncommented(needle).unwrap();
60
61         original.lo + BytePos(offset as u32)
62     }
63 }
64
65 impl LineRangeUtils for CodeMap {
66     fn lookup_line_range(&self, span: Span) -> LineRange {
67         let lo = self.lookup_char_pos(span.lo);
68         let hi = self.lookup_char_pos(span.hi);
69
70         assert!(lo.file.name == hi.file.name,
71                 "span crossed file boundary: lo: {:?}, hi: {:?}",
72                 lo,
73                 hi);
74
75         LineRange {
76             file: lo.file.clone(),
77             lo: lo.line,
78             hi: hi.line,
79         }
80     }
81 }