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 utilities that work with the `CodeMap` from `libsyntax` / `syntex_syntax`.
12 //! This includes extension traits and methods for looking up spans and line ranges for AST nodes.
14 use config::file_lines::LineRange;
15 use visitor::SnippetProvider;
16 use syntax::codemap::{BytePos, CodeMap, Span};
18 use comment::FindUncommented;
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 fn opt_span_after(&self, original: Span, needle: &str) -> Option<BytePos>;
27 pub trait LineRangeUtils {
28 /// Returns the `LineRange` that corresponds to `span` in `self`.
32 /// Panics if `span` crosses a file boundary, which shouldn't happen.
33 fn lookup_line_range(&self, span: Span) -> LineRange;
36 impl<'a> SpanUtils for SnippetProvider<'a> {
37 fn span_after(&self, original: Span, needle: &str) -> BytePos {
38 let snippet = self.span_to_snippet(original).expect("Bad snippet");
39 let offset = snippet.find_uncommented(needle).expect("Bad offset") + needle.len();
41 original.lo() + BytePos(offset as u32)
44 fn span_after_last(&self, original: Span, needle: &str) -> BytePos {
45 let snippet = self.span_to_snippet(original).unwrap();
48 while let Some(additional_offset) = snippet[offset..].find_uncommented(needle) {
49 offset += additional_offset + needle.len();
52 original.lo() + BytePos(offset as u32)
55 fn span_before(&self, original: Span, needle: &str) -> BytePos {
56 let snippet = self.span_to_snippet(original).unwrap();
57 let offset = snippet.find_uncommented(needle).unwrap();
59 original.lo() + BytePos(offset as u32)
62 fn opt_span_after(&self, original: Span, needle: &str) -> Option<BytePos> {
63 let snippet = self.span_to_snippet(original)?;
64 let offset = snippet.find_uncommented(needle)? + needle.len();
66 Some(original.lo() + BytePos(offset as u32))
70 impl LineRangeUtils for CodeMap {
71 fn lookup_line_range(&self, span: Span) -> LineRange {
72 let lo = self.lookup_line(span.lo()).unwrap();
73 let hi = self.lookup_line(span.hi()).unwrap();
76 lo.fm.name, hi.fm.name,
77 "span crossed file boundary: lo: {:?}, hi: {:?}",
81 // Line numbers start at 1