1 // Copyright 2012-2013 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 //! The source positions and related helper functions
15 //! This API is completely unstable and subject to change.
17 #![crate_name = "syntax_pos"]
18 #![crate_type = "dylib"]
19 #![crate_type = "rlib"]
20 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
21 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
22 html_root_url = "https://doc.rust-lang.org/nightly/")]
26 #![feature(custom_attribute)]
27 #![feature(i128_type)]
28 #![feature(optin_builtin_traits)]
29 #![allow(unused_attributes)]
30 #![feature(specialization)]
32 #![cfg_attr(stage0, unstable(feature = "rustc_private", issue = "27812"))]
33 #![cfg_attr(stage0, feature(rustc_private))]
34 #![cfg_attr(stage0, feature(staged_api))]
37 use std::cell::{Cell, RefCell};
38 use std::ops::{Add, Sub};
42 use std::hash::Hasher;
44 use rustc_data_structures::stable_hasher::StableHasher;
46 extern crate rustc_data_structures;
48 use serialize::{Encodable, Decodable, Encoder, Decoder};
50 extern crate serialize;
51 extern crate serialize as rustc_serialize; // used by deriving
54 pub use hygiene::{SyntaxContext, ExpnInfo, ExpnFormat, NameAndSpan};
58 pub type FileName = String;
60 /// Spans represent a region of code, used for error reporting. Positions in spans
61 /// are *absolute* positions from the beginning of the codemap, not positions
62 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
63 /// to the original source.
64 /// You must be careful if the span crosses more than one file - you will not be
65 /// able to use many of the functions on spans in codemap and you cannot assume
66 /// that the length of the span = hi - lo; there may be space in the BytePos
67 /// range between files.
68 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
72 /// Information about where the macro came from, if this piece of
73 /// code was created by a macro expansion.
74 pub ctxt: SyntaxContext,
77 /// A collection of spans. Spans have two orthogonal attributes:
79 /// - they can be *primary spans*. In this case they are the locus of
80 /// the error, and would be rendered with `^^^`.
81 /// - they can have a *label*. In this case, the label is written next
82 /// to the mark in the snippet when we render.
83 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
84 pub struct MultiSpan {
85 primary_spans: Vec<Span>,
86 span_labels: Vec<(Span, String)>,
90 /// Returns a new span representing just the end-point of this span
91 pub fn end_point(self) -> Span {
92 let lo = cmp::max(self.hi.0 - 1, self.lo.0);
93 Span { lo: BytePos(lo), ..self }
96 /// Returns a new span representing the next character after the end-point of this span
97 pub fn next_point(self) -> Span {
98 let lo = cmp::max(self.hi.0, self.lo.0 + 1);
99 Span { lo: BytePos(lo), hi: BytePos(lo), ..self }
102 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
103 pub fn substitute_dummy(self, other: Span) -> Span {
104 if self.source_equal(&DUMMY_SP) { other } else { self }
107 pub fn contains(self, other: Span) -> bool {
108 self.lo <= other.lo && other.hi <= self.hi
111 /// Return true if the spans are equal with regards to the source text.
113 /// Use this instead of `==` when either span could be generated code,
114 /// and you only care that they point to the same bytes of source text.
115 pub fn source_equal(&self, other: &Span) -> bool {
116 self.lo == other.lo && self.hi == other.hi
119 /// Returns `Some(span)`, where the start is trimmed by the end of `other`
120 pub fn trim_start(self, other: Span) -> Option<Span> {
121 if self.hi > other.hi {
122 Some(Span { lo: cmp::max(self.lo, other.hi), .. self })
128 /// Return the source span - this is either the supplied span, or the span for
129 /// the macro callsite that expanded to it.
130 pub fn source_callsite(self) -> Span {
131 self.ctxt.outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
134 /// Return the source callee.
136 /// Returns None if the supplied span has no expansion trace,
137 /// else returns the NameAndSpan for the macro definition
138 /// corresponding to the source callsite.
139 pub fn source_callee(self) -> Option<NameAndSpan> {
140 fn source_callee(info: ExpnInfo) -> NameAndSpan {
141 match info.call_site.ctxt.outer().expn_info() {
142 Some(info) => source_callee(info),
146 self.ctxt.outer().expn_info().map(source_callee)
149 /// Check if a span is "internal" to a macro in which #[unstable]
150 /// items can be used (that is, a macro marked with
151 /// `#[allow_internal_unstable]`).
152 pub fn allows_unstable(&self) -> bool {
153 match self.ctxt.outer().expn_info() {
154 Some(info) => info.callee.allow_internal_unstable,
159 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
160 let mut prev_span = DUMMY_SP;
161 let mut result = vec![];
163 let info = match self.ctxt.outer().expn_info() {
168 let (pre, post) = match info.callee.format {
169 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
170 ExpnFormat::MacroBang(..) => ("", "!"),
171 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
173 let macro_decl_name = format!("{}{}{}", pre, info.callee.name(), post);
174 let def_site_span = info.callee.span;
176 // Don't print recursive invocations
177 if !info.call_site.source_equal(&prev_span) {
178 result.push(MacroBacktrace {
179 call_site: info.call_site,
180 macro_decl_name: macro_decl_name,
181 def_site_span: def_site_span,
186 self = info.call_site;
191 pub fn to(self, end: Span) -> Span {
192 // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480)
193 if end.ctxt == SyntaxContext::empty() {
194 Span { lo: self.lo, ..end }
196 Span { hi: end.hi, ..self }
200 pub fn between(self, end: Span) -> Span {
204 ctxt: if end.ctxt == SyntaxContext::empty() {
212 pub fn until(self, end: Span) -> Span {
216 ctxt: if end.ctxt == SyntaxContext::empty() {
225 #[derive(Clone, Debug)]
226 pub struct SpanLabel {
227 /// The span we are going to include in the final snippet.
230 /// Is this a primary span? This is the "locus" of the message,
231 /// and is indicated with a `^^^^` underline, versus `----`.
232 pub is_primary: bool,
234 /// What label should we attach to this span (if any)?
235 pub label: Option<String>,
238 impl serialize::UseSpecializedEncodable for Span {
239 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
240 s.emit_struct("Span", 2, |s| {
241 s.emit_struct_field("lo", 0, |s| {
245 s.emit_struct_field("hi", 1, |s| {
252 impl serialize::UseSpecializedDecodable for Span {
253 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
254 d.read_struct("Span", 2, |d| {
255 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
256 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
257 Ok(Span { lo: lo, hi: hi, ctxt: NO_EXPANSION })
262 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
263 write!(f, "Span {{ lo: {:?}, hi: {:?}, ctxt: {:?} }}",
264 span.lo, span.hi, span.ctxt)
267 impl fmt::Debug for Span {
268 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
269 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
273 pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), ctxt: NO_EXPANSION };
276 pub fn new() -> MultiSpan {
278 primary_spans: vec![],
283 pub fn from_span(primary_span: Span) -> MultiSpan {
285 primary_spans: vec![primary_span],
290 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
297 pub fn push_span_label(&mut self, span: Span, label: String) {
298 self.span_labels.push((span, label));
301 /// Selects the first primary span (if any)
302 pub fn primary_span(&self) -> Option<Span> {
303 self.primary_spans.first().cloned()
306 /// Returns all primary spans.
307 pub fn primary_spans(&self) -> &[Span] {
311 /// Replaces all occurances of one Span with another. Used to move Spans in areas that don't
312 /// display well (like std macros). Returns true if replacements occurred.
313 pub fn replace(&mut self, before: Span, after: Span) -> bool {
314 let mut replacements_occurred = false;
315 for primary_span in &mut self.primary_spans {
316 if *primary_span == before {
317 *primary_span = after;
318 replacements_occurred = true;
321 for span_label in &mut self.span_labels {
322 if span_label.0 == before {
323 span_label.0 = after;
324 replacements_occurred = true;
327 replacements_occurred
330 /// Returns the strings to highlight. We always ensure that there
331 /// is an entry for each of the primary spans -- for each primary
332 /// span P, if there is at least one label with span P, we return
333 /// those labels (marked as primary). But otherwise we return
334 /// `SpanLabel` instances with empty labels.
335 pub fn span_labels(&self) -> Vec<SpanLabel> {
336 let is_primary = |span| self.primary_spans.contains(&span);
337 let mut span_labels = vec![];
339 for &(span, ref label) in &self.span_labels {
340 span_labels.push(SpanLabel {
342 is_primary: is_primary(span),
343 label: Some(label.clone())
347 for &span in &self.primary_spans {
348 if !span_labels.iter().any(|sl| sl.span == span) {
349 span_labels.push(SpanLabel {
361 impl From<Span> for MultiSpan {
362 fn from(span: Span) -> MultiSpan {
363 MultiSpan::from_span(span)
367 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
369 /// Identifies an offset of a multi-byte character in a FileMap
370 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
371 pub struct MultiByteChar {
372 /// The absolute offset of the character in the CodeMap
374 /// The number of bytes, >=2
378 /// The state of the lazy external source loading mechanism of a FileMap.
379 #[derive(PartialEq, Eq, Clone)]
380 pub enum ExternalSource {
381 /// The external source has been loaded already.
383 /// No attempt has been made to load the external source.
385 /// A failed attempt has been made to load the external source.
387 /// No external source has to be loaded, since the FileMap represents a local crate.
391 impl ExternalSource {
392 pub fn is_absent(&self) -> bool {
394 ExternalSource::Present(_) => false,
399 pub fn get_source(&self) -> Option<&str> {
401 ExternalSource::Present(ref src) => Some(src),
407 /// A single source in the CodeMap.
410 /// The name of the file that the source came from, source that doesn't
411 /// originate from files has names between angle brackets by convention,
414 /// True if the `name` field above has been modified by -Zremap-path-prefix
415 pub name_was_remapped: bool,
416 /// Indicates which crate this FileMap was imported from.
417 pub crate_of_origin: u32,
418 /// The complete source code
419 pub src: Option<Rc<String>>,
420 /// The source code's hash
422 /// The external source code (used for external crates, which will have a `None`
423 /// value as `self.src`.
424 pub external_src: RefCell<ExternalSource>,
425 /// The start position of this source in the CodeMap
426 pub start_pos: BytePos,
427 /// The end position of this source in the CodeMap
428 pub end_pos: BytePos,
429 /// Locations of lines beginnings in the source code
430 pub lines: RefCell<Vec<BytePos>>,
431 /// Locations of multi-byte characters in the source code
432 pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
435 impl Encodable for FileMap {
436 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
437 s.emit_struct("FileMap", 7, |s| {
438 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
439 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
440 s.emit_struct_field("src_hash", 6, |s| self.src_hash.encode(s))?;
441 s.emit_struct_field("start_pos", 2, |s| self.start_pos.encode(s))?;
442 s.emit_struct_field("end_pos", 3, |s| self.end_pos.encode(s))?;
443 s.emit_struct_field("lines", 4, |s| {
444 let lines = self.lines.borrow();
446 s.emit_u32(lines.len() as u32)?;
448 if !lines.is_empty() {
449 // In order to preserve some space, we exploit the fact that
450 // the lines list is sorted and individual lines are
451 // probably not that long. Because of that we can store lines
452 // as a difference list, using as little space as possible
453 // for the differences.
454 let max_line_length = if lines.len() == 1 {
458 .map(|w| w[1] - w[0])
459 .map(|bp| bp.to_usize())
464 let bytes_per_diff: u8 = match max_line_length {
466 0x100 ... 0xFFFF => 2,
470 // Encode the number of bytes used per diff.
471 bytes_per_diff.encode(s)?;
473 // Encode the first element.
476 let diff_iter = (&lines[..]).windows(2)
477 .map(|w| (w[1] - w[0]));
479 match bytes_per_diff {
480 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
481 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
482 4 => for diff in diff_iter { diff.0.encode(s)? },
489 s.emit_struct_field("multibyte_chars", 5, |s| {
490 (*self.multibyte_chars.borrow()).encode(s)
496 impl Decodable for FileMap {
497 fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
499 d.read_struct("FileMap", 6, |d| {
500 let name: String = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
501 let name_was_remapped: bool =
502 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
504 d.read_struct_field("src_hash", 6, |d| Decodable::decode(d))?;
505 let start_pos: BytePos =
506 d.read_struct_field("start_pos", 2, |d| Decodable::decode(d))?;
507 let end_pos: BytePos = d.read_struct_field("end_pos", 3, |d| Decodable::decode(d))?;
508 let lines: Vec<BytePos> = d.read_struct_field("lines", 4, |d| {
509 let num_lines: u32 = Decodable::decode(d)?;
510 let mut lines = Vec::with_capacity(num_lines as usize);
513 // Read the number of bytes used per diff.
514 let bytes_per_diff: u8 = Decodable::decode(d)?;
516 // Read the first element.
517 let mut line_start: BytePos = Decodable::decode(d)?;
518 lines.push(line_start);
520 for _ in 1..num_lines {
521 let diff = match bytes_per_diff {
522 1 => d.read_u8()? as u32,
523 2 => d.read_u16()? as u32,
528 line_start = line_start + BytePos(diff);
530 lines.push(line_start);
536 let multibyte_chars: Vec<MultiByteChar> =
537 d.read_struct_field("multibyte_chars", 5, |d| Decodable::decode(d))?;
540 name_was_remapped: name_was_remapped,
541 // `crate_of_origin` has to be set by the importer.
542 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
543 // That constant is not available here unfortunately :(
544 crate_of_origin: ::std::u32::MAX - 1,
545 start_pos: start_pos,
549 external_src: RefCell::new(ExternalSource::AbsentOk),
550 lines: RefCell::new(lines),
551 multibyte_chars: RefCell::new(multibyte_chars)
557 impl fmt::Debug for FileMap {
558 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
559 write!(fmt, "FileMap({})", self.name)
564 pub fn new(name: FileName,
565 name_was_remapped: bool,
567 start_pos: BytePos) -> FileMap {
568 remove_bom(&mut src);
570 let mut hasher: StableHasher<u128> = StableHasher::new();
571 hasher.write(src.as_bytes());
572 let src_hash = hasher.finish();
574 let end_pos = start_pos.to_usize() + src.len();
578 name_was_remapped: name_was_remapped,
580 src: Some(Rc::new(src)),
582 external_src: RefCell::new(ExternalSource::Unneeded),
583 start_pos: start_pos,
584 end_pos: Pos::from_usize(end_pos),
585 lines: RefCell::new(Vec::new()),
586 multibyte_chars: RefCell::new(Vec::new()),
590 /// EFFECT: register a start-of-line offset in the
591 /// table of line-beginnings.
592 /// UNCHECKED INVARIANT: these offsets must be added in the right
593 /// order and must be in the right places; there is shared knowledge
594 /// about what ends a line between this file and parse.rs
595 /// WARNING: pos param here is the offset relative to start of CodeMap,
596 /// and CodeMap will append a newline when adding a filemap without a newline at the end,
597 /// so the safe way to call this is with value calculated as
598 /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
599 pub fn next_line(&self, pos: BytePos) {
600 // the new charpos must be > the last one (or it's the first one).
601 let mut lines = self.lines.borrow_mut();
602 let line_len = lines.len();
603 assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
607 /// get a line from the list of pre-computed line-beginnings.
608 /// line-number here is 0-based.
609 pub fn get_line(&self, line_number: usize) -> Option<Cow<str>> {
610 fn get_until_newline(src: &str, begin: usize) -> &str {
611 // We can't use `lines.get(line_number+1)` because we might
612 // be parsing when we call this function and thus the current
613 // line is the last one we have line info for.
614 let slice = &src[begin..];
615 match slice.find('\n') {
616 Some(e) => &slice[..e],
621 let lines = self.lines.borrow();
622 let line = if let Some(line) = lines.get(line_number) {
627 let begin: BytePos = *line - self.start_pos;
628 let begin = begin.to_usize();
630 if let Some(ref src) = self.src {
631 Some(Cow::from(get_until_newline(src, begin)))
632 } else if let Some(src) = self.external_src.borrow().get_source() {
633 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
639 pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
640 assert!(bytes >=2 && bytes <= 4);
641 let mbc = MultiByteChar {
645 self.multibyte_chars.borrow_mut().push(mbc);
648 pub fn is_real_file(&self) -> bool {
649 !(self.name.starts_with("<") &&
650 self.name.ends_with(">"))
653 pub fn is_imported(&self) -> bool {
657 pub fn byte_length(&self) -> u32 {
658 self.end_pos.0 - self.start_pos.0
660 pub fn count_lines(&self) -> usize {
661 self.lines.borrow().len()
664 /// Find the line containing the given position. The return value is the
665 /// index into the `lines` array of this FileMap, not the 1-based line
666 /// number. If the filemap is empty or the position is located before the
667 /// first line, None is returned.
668 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
669 let lines = self.lines.borrow();
670 if lines.len() == 0 {
674 let line_index = lookup_line(&lines[..], pos);
675 assert!(line_index < lines.len() as isize);
677 Some(line_index as usize)
683 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
684 if self.start_pos == self.end_pos {
685 return (self.start_pos, self.end_pos);
688 let lines = self.lines.borrow();
689 assert!(line_index < lines.len());
690 if line_index == (lines.len() - 1) {
691 (lines[line_index], self.end_pos)
693 (lines[line_index], lines[line_index + 1])
698 /// Remove utf-8 BOM if any.
699 fn remove_bom(src: &mut String) {
700 if src.starts_with("\u{feff}") {
705 // _____________________________________________________________________________
706 // Pos, BytePos, CharPos
710 fn from_usize(n: usize) -> Self;
711 fn to_usize(&self) -> usize;
714 /// A byte offset. Keep this small (currently 32-bits), as AST contains
716 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
717 pub struct BytePos(pub u32);
719 /// A character offset. Because of multibyte utf8 characters, a byte offset
720 /// is not equivalent to a character offset. The CodeMap will convert BytePos
721 /// values to CharPos values as necessary.
722 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
723 pub struct CharPos(pub usize);
725 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
726 // have been unsuccessful
728 impl Pos for BytePos {
729 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
730 fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
733 impl Add for BytePos {
734 type Output = BytePos;
736 fn add(self, rhs: BytePos) -> BytePos {
737 BytePos((self.to_usize() + rhs.to_usize()) as u32)
741 impl Sub for BytePos {
742 type Output = BytePos;
744 fn sub(self, rhs: BytePos) -> BytePos {
745 BytePos((self.to_usize() - rhs.to_usize()) as u32)
749 impl Encodable for BytePos {
750 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
755 impl Decodable for BytePos {
756 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
757 Ok(BytePos(d.read_u32()?))
761 impl Pos for CharPos {
762 fn from_usize(n: usize) -> CharPos { CharPos(n) }
763 fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
766 impl Add for CharPos {
767 type Output = CharPos;
769 fn add(self, rhs: CharPos) -> CharPos {
770 CharPos(self.to_usize() + rhs.to_usize())
774 impl Sub for CharPos {
775 type Output = CharPos;
777 fn sub(self, rhs: CharPos) -> CharPos {
778 CharPos(self.to_usize() - rhs.to_usize())
782 // _____________________________________________________________________________
783 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
786 /// A source code location used for error reporting
787 #[derive(Debug, Clone)]
789 /// Information about the original source
790 pub file: Rc<FileMap>,
791 /// The (1-based) line number
793 /// The (0-based) column offset
797 /// A source code location used as the result of lookup_char_pos_adj
798 // Actually, *none* of the clients use the filename *or* file field;
799 // perhaps they should just be removed.
801 pub struct LocWithOpt {
802 pub filename: FileName,
805 pub file: Option<Rc<FileMap>>,
808 // used to be structural records. Better names, anyone?
810 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
812 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
814 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
815 pub struct LineInfo {
816 /// Index of line, starting from 0.
817 pub line_index: usize,
819 /// Column in line where span begins, starting from 0.
820 pub start_col: CharPos,
822 /// Column in line where span ends, starting from 0, exclusive.
823 pub end_col: CharPos,
826 pub struct FileLines {
827 pub file: Rc<FileMap>,
828 pub lines: Vec<LineInfo>
831 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
832 Cell::new(default_span_debug));
834 pub struct MacroBacktrace {
835 /// span where macro was applied to generate this code
838 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
839 pub macro_decl_name: String,
841 /// span where macro was defined (if known)
842 pub def_site_span: Option<Span>,
845 // _____________________________________________________________________________
846 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
849 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
851 #[derive(Clone, PartialEq, Eq, Debug)]
852 pub enum SpanLinesError {
854 DistinctSources(DistinctSources),
857 #[derive(Clone, PartialEq, Eq, Debug)]
858 pub enum SpanSnippetError {
860 DistinctSources(DistinctSources),
861 MalformedForCodemap(MalformedCodemapPositions),
862 SourceNotAvailable { filename: String }
865 #[derive(Clone, PartialEq, Eq, Debug)]
866 pub struct DistinctSources {
867 pub begin: (String, BytePos),
868 pub end: (String, BytePos)
871 #[derive(Clone, PartialEq, Eq, Debug)]
872 pub struct MalformedCodemapPositions {
874 pub source_len: usize,
875 pub begin_pos: BytePos,
879 // Given a slice of line start positions and a position, returns the index of
880 // the line the position is on. Returns -1 if the position is located before
882 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
883 match lines.binary_search(&pos) {
884 Ok(line) => line as isize,
885 Err(line) => line as isize - 1
891 use super::{lookup_line, BytePos};
894 fn test_lookup_line() {
896 let lines = &[BytePos(3), BytePos(17), BytePos(28)];
898 assert_eq!(lookup_line(lines, BytePos(0)), -1);
899 assert_eq!(lookup_line(lines, BytePos(3)), 0);
900 assert_eq!(lookup_line(lines, BytePos(4)), 0);
902 assert_eq!(lookup_line(lines, BytePos(16)), 0);
903 assert_eq!(lookup_line(lines, BytePos(17)), 1);
904 assert_eq!(lookup_line(lines, BytePos(18)), 1);
906 assert_eq!(lookup_line(lines, BytePos(28)), 2);
907 assert_eq!(lookup_line(lines, BytePos(29)), 2);