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 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19 html_root_url = "https://doc.rust-lang.org/nightly/")]
23 #![feature(custom_attribute)]
24 #![feature(i128_type)]
25 #![feature(optin_builtin_traits)]
26 #![allow(unused_attributes)]
27 #![feature(specialization)]
28 #![feature(staged_api)]
31 use std::cell::{Cell, RefCell};
34 use std::hash::Hasher;
35 use std::ops::{Add, Sub};
38 use rustc_data_structures::stable_hasher::StableHasher;
40 extern crate rustc_data_structures;
42 use serialize::{Encodable, Decodable, Encoder, Decoder};
44 extern crate serialize;
45 extern crate serialize as rustc_serialize; // used by deriving
48 pub use hygiene::{SyntaxContext, ExpnInfo, ExpnFormat, NameAndSpan, CompilerDesugaringKind};
52 pub type FileName = String;
54 /// Spans represent a region of code, used for error reporting. Positions in spans
55 /// are *absolute* positions from the beginning of the codemap, not positions
56 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
57 /// to the original source.
58 /// You must be careful if the span crosses more than one file - you will not be
59 /// able to use many of the functions on spans in codemap and you cannot assume
60 /// that the length of the span = hi - lo; there may be space in the BytePos
61 /// range between files.
62 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
64 #[unstable(feature = "rustc_private", issue = "27812")]
65 #[rustc_deprecated(since = "1.21", reason = "use getters/setters instead")]
67 #[unstable(feature = "rustc_private", issue = "27812")]
68 #[rustc_deprecated(since = "1.21", reason = "use getters/setters instead")]
70 /// Information about where the macro came from, if this piece of
71 /// code was created by a macro expansion.
72 #[unstable(feature = "rustc_private", issue = "27812")]
73 #[rustc_deprecated(since = "1.21", reason = "use getters/setters instead")]
74 pub ctxt: SyntaxContext,
78 pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), ctxt: NO_EXPANSION };
80 /// A collection of spans. Spans have two orthogonal attributes:
82 /// - they can be *primary spans*. In this case they are the locus of
83 /// the error, and would be rendered with `^^^`.
84 /// - they can have a *label*. In this case, the label is written next
85 /// to the mark in the snippet when we render.
86 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
87 pub struct MultiSpan {
88 primary_spans: Vec<Span>,
89 span_labels: Vec<(Span, String)>,
95 pub fn new(lo: BytePos, hi: BytePos, ctxt: SyntaxContext) -> Self {
96 if lo <= hi { Span { lo, hi, ctxt } } else { Span { lo: hi, hi: lo, ctxt } }
101 pub fn lo(self) -> BytePos {
105 pub fn with_lo(self, lo: BytePos) -> Span {
106 Span::new(lo, self.hi(), self.ctxt())
110 pub fn hi(self) -> BytePos {
114 pub fn with_hi(self, hi: BytePos) -> Span {
115 Span::new(self.lo(), hi, self.ctxt())
119 pub fn ctxt(self) -> SyntaxContext {
123 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
124 Span::new(self.lo(), self.hi(), ctxt)
127 /// Returns a new span representing just the end-point of this span
128 pub fn end_point(self) -> Span {
129 let lo = cmp::max(self.hi().0 - 1, self.lo().0);
130 self.with_lo(BytePos(lo))
133 /// Returns a new span representing the next character after the end-point of this span
134 pub fn next_point(self) -> Span {
135 let lo = cmp::max(self.hi().0, self.lo().0 + 1);
136 Span::new(BytePos(lo), BytePos(lo), self.ctxt())
139 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
140 pub fn substitute_dummy(self, other: Span) -> Span {
141 if self.source_equal(&DUMMY_SP) { other } else { self }
144 /// Return true if `self` fully encloses `other`.
145 pub fn contains(self, other: Span) -> bool {
146 self.lo() <= other.lo() && other.hi() <= self.hi()
149 /// Return true if the spans are equal with regards to the source text.
151 /// Use this instead of `==` when either span could be generated code,
152 /// and you only care that they point to the same bytes of source text.
153 pub fn source_equal(&self, other: &Span) -> bool {
154 self.lo() == other.lo() && self.hi() == other.hi()
157 /// Returns `Some(span)`, where the start is trimmed by the end of `other`
158 pub fn trim_start(self, other: Span) -> Option<Span> {
159 if self.hi() > other.hi() {
160 Some(self.with_lo(cmp::max(self.lo(), other.hi())))
166 /// Return the source span - this is either the supplied span, or the span for
167 /// the macro callsite that expanded to it.
168 pub fn source_callsite(self) -> Span {
169 self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
172 /// Return the source callee.
174 /// Returns None if the supplied span has no expansion trace,
175 /// else returns the NameAndSpan for the macro definition
176 /// corresponding to the source callsite.
177 pub fn source_callee(self) -> Option<NameAndSpan> {
178 fn source_callee(info: ExpnInfo) -> NameAndSpan {
179 match info.call_site.ctxt().outer().expn_info() {
180 Some(info) => source_callee(info),
184 self.ctxt().outer().expn_info().map(source_callee)
187 /// Check if a span is "internal" to a macro in which #[unstable]
188 /// items can be used (that is, a macro marked with
189 /// `#[allow_internal_unstable]`).
190 pub fn allows_unstable(&self) -> bool {
191 match self.ctxt().outer().expn_info() {
192 Some(info) => info.callee.allow_internal_unstable,
197 /// Check if this span arises from a compiler desugaring of kind `kind`.
198 pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
199 match self.ctxt().outer().expn_info() {
200 Some(info) => match info.callee.format {
201 ExpnFormat::CompilerDesugaring(k) => k == kind,
208 /// Return the compiler desugaring that created this span, or None
209 /// if this span is not from a desugaring.
210 pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
211 match self.ctxt().outer().expn_info() {
212 Some(info) => match info.callee.format {
213 ExpnFormat::CompilerDesugaring(k) => Some(k),
220 /// Check if a span is "internal" to a macro in which `unsafe`
221 /// can be used without triggering the `unsafe_code` lint
222 // (that is, a macro marked with `#[allow_internal_unsafe]`).
223 pub fn allows_unsafe(&self) -> bool {
224 match self.ctxt().outer().expn_info() {
225 Some(info) => info.callee.allow_internal_unsafe,
230 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
231 let mut prev_span = DUMMY_SP;
232 let mut result = vec![];
234 let info = match self.ctxt().outer().expn_info() {
239 let (pre, post) = match info.callee.format {
240 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
241 ExpnFormat::MacroBang(..) => ("", "!"),
242 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
244 let macro_decl_name = format!("{}{}{}", pre, info.callee.name(), post);
245 let def_site_span = info.callee.span;
247 // Don't print recursive invocations
248 if !info.call_site.source_equal(&prev_span) {
249 result.push(MacroBacktrace {
250 call_site: info.call_site,
257 self = info.call_site;
262 /// Return a `Span` that would enclose both `self` and `end`.
263 pub fn to(self, end: Span) -> Span {
265 cmp::min(self.lo(), end.lo()),
266 cmp::max(self.hi(), end.hi()),
267 // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480)
268 if self.ctxt() == SyntaxContext::empty() { end.ctxt() } else { self.ctxt() },
272 /// Return a `Span` between the end of `self` to the beginning of `end`.
273 pub fn between(self, end: Span) -> Span {
277 if end.ctxt() == SyntaxContext::empty() { end.ctxt() } else { self.ctxt() },
281 /// Return a `Span` between the beginning of `self` to the beginning of `end`.
282 pub fn until(self, end: Span) -> Span {
286 if end.ctxt() == SyntaxContext::empty() { end.ctxt() } else { self.ctxt() },
291 #[derive(Clone, Debug)]
292 pub struct SpanLabel {
293 /// The span we are going to include in the final snippet.
296 /// Is this a primary span? This is the "locus" of the message,
297 /// and is indicated with a `^^^^` underline, versus `----`.
298 pub is_primary: bool,
300 /// What label should we attach to this span (if any)?
301 pub label: Option<String>,
304 impl Default for Span {
305 fn default() -> Self {
310 impl serialize::UseSpecializedEncodable for Span {
311 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
312 s.emit_struct("Span", 2, |s| {
313 s.emit_struct_field("lo", 0, |s| {
317 s.emit_struct_field("hi", 1, |s| {
324 impl serialize::UseSpecializedDecodable for Span {
325 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
326 d.read_struct("Span", 2, |d| {
327 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
328 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
329 Ok(Span::new(lo, hi, NO_EXPANSION))
334 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
335 write!(f, "Span {{ lo: {:?}, hi: {:?}, ctxt: {:?} }}",
336 span.lo(), span.hi(), span.ctxt())
339 impl fmt::Debug for Span {
340 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
341 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
346 pub fn new() -> MultiSpan {
348 primary_spans: vec![],
353 pub fn from_span(primary_span: Span) -> MultiSpan {
355 primary_spans: vec![primary_span],
360 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
367 pub fn push_span_label(&mut self, span: Span, label: String) {
368 self.span_labels.push((span, label));
371 /// Selects the first primary span (if any)
372 pub fn primary_span(&self) -> Option<Span> {
373 self.primary_spans.first().cloned()
376 /// Returns all primary spans.
377 pub fn primary_spans(&self) -> &[Span] {
381 /// Replaces all occurrences of one Span with another. Used to move Spans in areas that don't
382 /// display well (like std macros). Returns true if replacements occurred.
383 pub fn replace(&mut self, before: Span, after: Span) -> bool {
384 let mut replacements_occurred = false;
385 for primary_span in &mut self.primary_spans {
386 if *primary_span == before {
387 *primary_span = after;
388 replacements_occurred = true;
391 for span_label in &mut self.span_labels {
392 if span_label.0 == before {
393 span_label.0 = after;
394 replacements_occurred = true;
397 replacements_occurred
400 /// Returns the strings to highlight. We always ensure that there
401 /// is an entry for each of the primary spans -- for each primary
402 /// span P, if there is at least one label with span P, we return
403 /// those labels (marked as primary). But otherwise we return
404 /// `SpanLabel` instances with empty labels.
405 pub fn span_labels(&self) -> Vec<SpanLabel> {
406 let is_primary = |span| self.primary_spans.contains(&span);
407 let mut span_labels = vec![];
409 for &(span, ref label) in &self.span_labels {
410 span_labels.push(SpanLabel {
412 is_primary: is_primary(span),
413 label: Some(label.clone())
417 for &span in &self.primary_spans {
418 if !span_labels.iter().any(|sl| sl.span == span) {
419 span_labels.push(SpanLabel {
431 impl From<Span> for MultiSpan {
432 fn from(span: Span) -> MultiSpan {
433 MultiSpan::from_span(span)
437 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
439 /// Identifies an offset of a multi-byte character in a FileMap
440 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
441 pub struct MultiByteChar {
442 /// The absolute offset of the character in the CodeMap
444 /// The number of bytes, >=2
448 /// The state of the lazy external source loading mechanism of a FileMap.
449 #[derive(PartialEq, Eq, Clone)]
450 pub enum ExternalSource {
451 /// The external source has been loaded already.
453 /// No attempt has been made to load the external source.
455 /// A failed attempt has been made to load the external source.
457 /// No external source has to be loaded, since the FileMap represents a local crate.
461 impl ExternalSource {
462 pub fn is_absent(&self) -> bool {
464 ExternalSource::Present(_) => false,
469 pub fn get_source(&self) -> Option<&str> {
471 ExternalSource::Present(ref src) => Some(src),
477 /// A single source in the CodeMap.
480 /// The name of the file that the source came from, source that doesn't
481 /// originate from files has names between angle brackets by convention,
484 /// True if the `name` field above has been modified by -Zremap-path-prefix
485 pub name_was_remapped: bool,
486 /// Indicates which crate this FileMap was imported from.
487 pub crate_of_origin: u32,
488 /// The complete source code
489 pub src: Option<Rc<String>>,
490 /// The source code's hash
492 /// The external source code (used for external crates, which will have a `None`
493 /// value as `self.src`.
494 pub external_src: RefCell<ExternalSource>,
495 /// The start position of this source in the CodeMap
496 pub start_pos: BytePos,
497 /// The end position of this source in the CodeMap
498 pub end_pos: BytePos,
499 /// Locations of lines beginnings in the source code
500 pub lines: RefCell<Vec<BytePos>>,
501 /// Locations of multi-byte characters in the source code
502 pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
505 impl Encodable for FileMap {
506 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
507 s.emit_struct("FileMap", 7, |s| {
508 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
509 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
510 s.emit_struct_field("src_hash", 6, |s| self.src_hash.encode(s))?;
511 s.emit_struct_field("start_pos", 2, |s| self.start_pos.encode(s))?;
512 s.emit_struct_field("end_pos", 3, |s| self.end_pos.encode(s))?;
513 s.emit_struct_field("lines", 4, |s| {
514 let lines = self.lines.borrow();
516 s.emit_u32(lines.len() as u32)?;
518 if !lines.is_empty() {
519 // In order to preserve some space, we exploit the fact that
520 // the lines list is sorted and individual lines are
521 // probably not that long. Because of that we can store lines
522 // as a difference list, using as little space as possible
523 // for the differences.
524 let max_line_length = if lines.len() == 1 {
528 .map(|w| w[1] - w[0])
529 .map(|bp| bp.to_usize())
534 let bytes_per_diff: u8 = match max_line_length {
536 0x100 ... 0xFFFF => 2,
540 // Encode the number of bytes used per diff.
541 bytes_per_diff.encode(s)?;
543 // Encode the first element.
546 let diff_iter = (&lines[..]).windows(2)
547 .map(|w| (w[1] - w[0]));
549 match bytes_per_diff {
550 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
551 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
552 4 => for diff in diff_iter { diff.0.encode(s)? },
559 s.emit_struct_field("multibyte_chars", 5, |s| {
560 (*self.multibyte_chars.borrow()).encode(s)
566 impl Decodable for FileMap {
567 fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
569 d.read_struct("FileMap", 6, |d| {
570 let name: String = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
571 let name_was_remapped: bool =
572 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
574 d.read_struct_field("src_hash", 6, |d| Decodable::decode(d))?;
575 let start_pos: BytePos =
576 d.read_struct_field("start_pos", 2, |d| Decodable::decode(d))?;
577 let end_pos: BytePos = d.read_struct_field("end_pos", 3, |d| Decodable::decode(d))?;
578 let lines: Vec<BytePos> = d.read_struct_field("lines", 4, |d| {
579 let num_lines: u32 = Decodable::decode(d)?;
580 let mut lines = Vec::with_capacity(num_lines as usize);
583 // Read the number of bytes used per diff.
584 let bytes_per_diff: u8 = Decodable::decode(d)?;
586 // Read the first element.
587 let mut line_start: BytePos = Decodable::decode(d)?;
588 lines.push(line_start);
590 for _ in 1..num_lines {
591 let diff = match bytes_per_diff {
592 1 => d.read_u8()? as u32,
593 2 => d.read_u16()? as u32,
598 line_start = line_start + BytePos(diff);
600 lines.push(line_start);
606 let multibyte_chars: Vec<MultiByteChar> =
607 d.read_struct_field("multibyte_chars", 5, |d| Decodable::decode(d))?;
611 // `crate_of_origin` has to be set by the importer.
612 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
613 // That constant is not available here unfortunately :(
614 crate_of_origin: ::std::u32::MAX - 1,
619 external_src: RefCell::new(ExternalSource::AbsentOk),
620 lines: RefCell::new(lines),
621 multibyte_chars: RefCell::new(multibyte_chars)
627 impl fmt::Debug for FileMap {
628 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
629 write!(fmt, "FileMap({})", self.name)
634 pub fn new(name: FileName,
635 name_was_remapped: bool,
637 start_pos: BytePos) -> FileMap {
638 remove_bom(&mut src);
640 let mut hasher: StableHasher<u128> = StableHasher::new();
641 hasher.write(src.as_bytes());
642 let src_hash = hasher.finish();
644 let end_pos = start_pos.to_usize() + src.len();
650 src: Some(Rc::new(src)),
652 external_src: RefCell::new(ExternalSource::Unneeded),
654 end_pos: Pos::from_usize(end_pos),
655 lines: RefCell::new(Vec::new()),
656 multibyte_chars: RefCell::new(Vec::new()),
660 /// EFFECT: register a start-of-line offset in the
661 /// table of line-beginnings.
662 /// UNCHECKED INVARIANT: these offsets must be added in the right
663 /// order and must be in the right places; there is shared knowledge
664 /// about what ends a line between this file and parse.rs
665 /// WARNING: pos param here is the offset relative to start of CodeMap,
666 /// and CodeMap will append a newline when adding a filemap without a newline at the end,
667 /// so the safe way to call this is with value calculated as
668 /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
669 pub fn next_line(&self, pos: BytePos) {
670 // the new charpos must be > the last one (or it's the first one).
671 let mut lines = self.lines.borrow_mut();
672 let line_len = lines.len();
673 assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
677 /// Add externally loaded source.
678 /// If the hash of the input doesn't match or no input is supplied via None,
679 /// it is interpreted as an error and the corresponding enum variant is set.
680 /// The return value signifies whether some kind of source is present.
681 pub fn add_external_src<F>(&self, get_src: F) -> bool
682 where F: FnOnce() -> Option<String>
684 if *self.external_src.borrow() == ExternalSource::AbsentOk {
686 let mut external_src = self.external_src.borrow_mut();
687 if let Some(src) = src {
688 let mut hasher: StableHasher<u128> = StableHasher::new();
689 hasher.write(src.as_bytes());
691 if hasher.finish() == self.src_hash {
692 *external_src = ExternalSource::Present(src);
696 *external_src = ExternalSource::AbsentErr;
701 self.src.is_some() || self.external_src.borrow().get_source().is_some()
705 /// Get a line from the list of pre-computed line-beginnings.
706 /// The line number here is 0-based.
707 pub fn get_line(&self, line_number: usize) -> Option<Cow<str>> {
708 fn get_until_newline(src: &str, begin: usize) -> &str {
709 // We can't use `lines.get(line_number+1)` because we might
710 // be parsing when we call this function and thus the current
711 // line is the last one we have line info for.
712 let slice = &src[begin..];
713 match slice.find('\n') {
714 Some(e) => &slice[..e],
719 let lines = self.lines.borrow();
720 let line = if let Some(line) = lines.get(line_number) {
725 let begin: BytePos = *line - self.start_pos;
726 let begin = begin.to_usize();
728 if let Some(ref src) = self.src {
729 Some(Cow::from(get_until_newline(src, begin)))
730 } else if let Some(src) = self.external_src.borrow().get_source() {
731 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
737 pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
738 assert!(bytes >=2 && bytes <= 4);
739 let mbc = MultiByteChar {
743 self.multibyte_chars.borrow_mut().push(mbc);
746 pub fn is_real_file(&self) -> bool {
747 !(self.name.starts_with("<") &&
748 self.name.ends_with(">"))
751 pub fn is_imported(&self) -> bool {
755 pub fn byte_length(&self) -> u32 {
756 self.end_pos.0 - self.start_pos.0
758 pub fn count_lines(&self) -> usize {
759 self.lines.borrow().len()
762 /// Find the line containing the given position. The return value is the
763 /// index into the `lines` array of this FileMap, not the 1-based line
764 /// number. If the filemap is empty or the position is located before the
765 /// first line, None is returned.
766 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
767 let lines = self.lines.borrow();
768 if lines.len() == 0 {
772 let line_index = lookup_line(&lines[..], pos);
773 assert!(line_index < lines.len() as isize);
775 Some(line_index as usize)
781 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
782 if self.start_pos == self.end_pos {
783 return (self.start_pos, self.end_pos);
786 let lines = self.lines.borrow();
787 assert!(line_index < lines.len());
788 if line_index == (lines.len() - 1) {
789 (lines[line_index], self.end_pos)
791 (lines[line_index], lines[line_index + 1])
796 /// Remove utf-8 BOM if any.
797 fn remove_bom(src: &mut String) {
798 if src.starts_with("\u{feff}") {
803 // _____________________________________________________________________________
804 // Pos, BytePos, CharPos
808 fn from_usize(n: usize) -> Self;
809 fn to_usize(&self) -> usize;
812 /// A byte offset. Keep this small (currently 32-bits), as AST contains
814 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
815 pub struct BytePos(pub u32);
817 /// A character offset. Because of multibyte utf8 characters, a byte offset
818 /// is not equivalent to a character offset. The CodeMap will convert BytePos
819 /// values to CharPos values as necessary.
820 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
821 pub struct CharPos(pub usize);
823 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
824 // have been unsuccessful
826 impl Pos for BytePos {
827 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
828 fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
831 impl Add for BytePos {
832 type Output = BytePos;
834 fn add(self, rhs: BytePos) -> BytePos {
835 BytePos((self.to_usize() + rhs.to_usize()) as u32)
839 impl Sub for BytePos {
840 type Output = BytePos;
842 fn sub(self, rhs: BytePos) -> BytePos {
843 BytePos((self.to_usize() - rhs.to_usize()) as u32)
847 impl Encodable for BytePos {
848 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
853 impl Decodable for BytePos {
854 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
855 Ok(BytePos(d.read_u32()?))
859 impl Pos for CharPos {
860 fn from_usize(n: usize) -> CharPos { CharPos(n) }
861 fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
864 impl Add for CharPos {
865 type Output = CharPos;
867 fn add(self, rhs: CharPos) -> CharPos {
868 CharPos(self.to_usize() + rhs.to_usize())
872 impl Sub for CharPos {
873 type Output = CharPos;
875 fn sub(self, rhs: CharPos) -> CharPos {
876 CharPos(self.to_usize() - rhs.to_usize())
880 // _____________________________________________________________________________
881 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
884 /// A source code location used for error reporting
885 #[derive(Debug, Clone)]
887 /// Information about the original source
888 pub file: Rc<FileMap>,
889 /// The (1-based) line number
891 /// The (0-based) column offset
895 /// A source code location used as the result of lookup_char_pos_adj
896 // Actually, *none* of the clients use the filename *or* file field;
897 // perhaps they should just be removed.
899 pub struct LocWithOpt {
900 pub filename: FileName,
903 pub file: Option<Rc<FileMap>>,
906 // used to be structural records. Better names, anyone?
908 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
910 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
912 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
913 pub struct LineInfo {
914 /// Index of line, starting from 0.
915 pub line_index: usize,
917 /// Column in line where span begins, starting from 0.
918 pub start_col: CharPos,
920 /// Column in line where span ends, starting from 0, exclusive.
921 pub end_col: CharPos,
924 pub struct FileLines {
925 pub file: Rc<FileMap>,
926 pub lines: Vec<LineInfo>
929 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
930 Cell::new(default_span_debug));
933 pub struct MacroBacktrace {
934 /// span where macro was applied to generate this code
937 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
938 pub macro_decl_name: String,
940 /// span where macro was defined (if known)
941 pub def_site_span: Option<Span>,
944 // _____________________________________________________________________________
945 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
948 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
950 #[derive(Clone, PartialEq, Eq, Debug)]
951 pub enum SpanLinesError {
953 DistinctSources(DistinctSources),
956 #[derive(Clone, PartialEq, Eq, Debug)]
957 pub enum SpanSnippetError {
959 DistinctSources(DistinctSources),
960 MalformedForCodemap(MalformedCodemapPositions),
961 SourceNotAvailable { filename: String }
964 #[derive(Clone, PartialEq, Eq, Debug)]
965 pub struct DistinctSources {
966 pub begin: (String, BytePos),
967 pub end: (String, BytePos)
970 #[derive(Clone, PartialEq, Eq, Debug)]
971 pub struct MalformedCodemapPositions {
973 pub source_len: usize,
974 pub begin_pos: BytePos,
978 // Given a slice of line start positions and a position, returns the index of
979 // the line the position is on. Returns -1 if the position is located before
981 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
982 match lines.binary_search(&pos) {
983 Ok(line) => line as isize,
984 Err(line) => line as isize - 1
990 use super::{lookup_line, BytePos};
993 fn test_lookup_line() {
995 let lines = &[BytePos(3), BytePos(17), BytePos(28)];
997 assert_eq!(lookup_line(lines, BytePos(0)), -1);
998 assert_eq!(lookup_line(lines, BytePos(3)), 0);
999 assert_eq!(lookup_line(lines, BytePos(4)), 0);
1001 assert_eq!(lookup_line(lines, BytePos(16)), 0);
1002 assert_eq!(lookup_line(lines, BytePos(17)), 1);
1003 assert_eq!(lookup_line(lines, BytePos(18)), 1);
1005 assert_eq!(lookup_line(lines, BytePos(28)), 2);
1006 assert_eq!(lookup_line(lines, BytePos(29)), 2);