1 //! This module contains utilities that work with the `SourceMap` from `libsyntax`/`syntex_syntax`.
2 //! This includes extension traits and methods for looking up spans and line ranges for AST nodes.
4 use syntax::source_map::{BytePos, SourceMap, Span};
6 use crate::comment::FindUncommented;
7 use crate::config::file_lines::LineRange;
8 use crate::visitor::SnippetProvider;
11 fn span_after(&self, original: Span, needle: &str) -> BytePos;
12 fn span_after_last(&self, original: Span, needle: &str) -> BytePos;
13 fn span_before(&self, original: Span, needle: &str) -> BytePos;
14 fn opt_span_after(&self, original: Span, needle: &str) -> Option<BytePos>;
15 fn opt_span_before(&self, original: Span, needle: &str) -> Option<BytePos>;
18 pub trait LineRangeUtils {
19 /// Returns the `LineRange` that corresponds to `span` in `self`.
23 /// Panics if `span` crosses a file boundary, which shouldn't happen.
24 fn lookup_line_range(&self, span: Span) -> LineRange;
27 impl<'a> SpanUtils for SnippetProvider<'a> {
28 fn span_after(&self, original: Span, needle: &str) -> BytePos {
29 self.opt_span_after(original, needle).expect("bad span")
32 fn span_after_last(&self, original: Span, needle: &str) -> BytePos {
33 let snippet = self.span_to_snippet(original).unwrap();
36 while let Some(additional_offset) = snippet[offset..].find_uncommented(needle) {
37 offset += additional_offset + needle.len();
40 original.lo() + BytePos(offset as u32)
43 fn span_before(&self, original: Span, needle: &str) -> BytePos {
44 self.opt_span_before(original, needle).unwrap_or_else(|| {
48 self.span_to_snippet(original).unwrap()
53 fn opt_span_after(&self, original: Span, needle: &str) -> Option<BytePos> {
54 self.opt_span_before(original, needle)
55 .map(|bytepos| bytepos + BytePos(needle.len() as u32))
58 fn opt_span_before(&self, original: Span, needle: &str) -> Option<BytePos> {
59 let snippet = self.span_to_snippet(original)?;
60 let offset = snippet.find_uncommented(needle)?;
62 Some(original.lo() + BytePos(offset as u32))
66 impl LineRangeUtils for SourceMap {
67 fn lookup_line_range(&self, span: Span) -> LineRange {
68 let lo = self.lookup_line(span.lo()).unwrap();
69 let hi = self.lookup_line(span.hi()).unwrap();
72 lo.sf.name, hi.sf.name,
73 "span crossed file boundary: lo: {:?}, hi: {:?}",
77 // Line numbers start at 1