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.
16 use syntax::codemap::{BytePos, CodeMap, FileMap, FileName, Span};
18 use comment::FindUncommented;
20 /// A range of lines in a file, inclusive of both ends.
21 pub struct LineRange {
22 pub file: Rc<FileMap>,
28 pub fn file_name(&self) -> &FileName {
34 fn span_after(&self, original: Span, needle: &str) -> BytePos;
35 fn span_after_last(&self, original: Span, needle: &str) -> BytePos;
36 fn span_before(&self, original: Span, needle: &str) -> BytePos;
37 fn opt_span_after(&self, original: Span, needle: &str) -> Option<BytePos>;
40 pub trait LineRangeUtils {
41 /// Returns the `LineRange` that corresponds to `span` in `self`.
45 /// Panics if `span` crosses a file boundary, which shouldn't happen.
46 fn lookup_line_range(&self, span: Span) -> LineRange;
49 impl SpanUtils for CodeMap {
50 fn span_after(&self, original: Span, needle: &str) -> BytePos {
51 let snippet = self.span_to_snippet(original).unwrap();
52 let offset = snippet.find_uncommented(needle).unwrap() + needle.len();
54 original.lo() + BytePos(offset as u32)
57 fn span_after_last(&self, original: Span, needle: &str) -> BytePos {
58 let snippet = self.span_to_snippet(original).unwrap();
61 while let Some(additional_offset) = snippet[offset..].find_uncommented(needle) {
62 offset += additional_offset + needle.len();
65 original.lo() + BytePos(offset as u32)
68 fn span_before(&self, original: Span, needle: &str) -> BytePos {
69 let snippet = self.span_to_snippet(original).unwrap();
70 let offset = snippet.find_uncommented(needle).unwrap();
72 original.lo() + BytePos(offset as u32)
75 fn opt_span_after(&self, original: Span, needle: &str) -> Option<BytePos> {
76 let snippet = self.span_to_snippet(original).ok()?;
77 let offset = snippet.find_uncommented(needle)? + needle.len();
79 Some(original.lo() + BytePos(offset as u32))
83 impl LineRangeUtils for CodeMap {
84 fn lookup_line_range(&self, span: Span) -> LineRange {
85 let lo = self.lookup_char_pos(span.lo());
86 let hi = self.lookup_char_pos(span.hi());
89 lo.file.name, hi.file.name,
90 "span crossed file boundary: lo: {:?}, hi: {:?}",
95 file: lo.file.clone(),