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)]
30 use std::cell::{Cell, RefCell};
31 use std::cmp::{self, Ordering};
33 use std::hash::{Hasher, Hash};
34 use std::ops::{Add, Sub};
35 use std::path::PathBuf;
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
47 extern crate unicode_width;
50 pub use hygiene::{SyntaxContext, ExpnInfo, ExpnFormat, NameAndSpan, CompilerDesugaringKind};
53 pub use span_encoding::{Span, DUMMY_SP};
57 /// Differentiates between real files and common virtual files
58 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
67 /// Hack in src/libsyntax/parse.rs
71 /// Strings provided as --cfg [cfgspec] stored in a crate_cfg
73 /// Custom sources for explicit parser calls from plugins and drivers
77 impl std::fmt::Display for FileName {
78 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
79 use self::FileName::*;
81 Real(ref path) => write!(fmt, "{}", path.display()),
82 Macros(ref name) => write!(fmt, "<{} macros>", name),
83 QuoteExpansion => write!(fmt, "<quote expansion>"),
84 MacroExpansion => write!(fmt, "<macro expansion>"),
85 Anon => write!(fmt, "<anon>"),
86 ProcMacroSourceCode => write!(fmt, "<proc-macro source code>"),
87 CfgSpec => write!(fmt, "cfgspec"),
88 Custom(ref s) => write!(fmt, "<{}>", s),
93 impl From<PathBuf> for FileName {
94 fn from(p: PathBuf) -> Self {
95 assert!(!p.to_string_lossy().ends_with('>'));
101 pub fn is_real(&self) -> bool {
102 use self::FileName::*;
108 ProcMacroSourceCode |
111 QuoteExpansion => false,
115 pub fn is_macros(&self) -> bool {
116 use self::FileName::*;
121 ProcMacroSourceCode |
124 QuoteExpansion => false,
130 /// Spans represent a region of code, used for error reporting. Positions in spans
131 /// are *absolute* positions from the beginning of the codemap, not positions
132 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
133 /// to the original source.
134 /// You must be careful if the span crosses more than one file - you will not be
135 /// able to use many of the functions on spans in codemap and you cannot assume
136 /// that the length of the span = hi - lo; there may be space in the BytePos
137 /// range between files.
139 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
140 /// sent to other threads, but some pieces of performance infra run in a separate thread.
141 /// Using `Span` is generally preferred.
142 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
143 pub struct SpanData {
146 /// Information about where the macro came from, if this piece of
147 /// code was created by a macro expansion.
148 pub ctxt: SyntaxContext,
153 pub fn with_lo(&self, lo: BytePos) -> Span {
154 Span::new(lo, self.hi, self.ctxt)
157 pub fn with_hi(&self, hi: BytePos) -> Span {
158 Span::new(self.lo, hi, self.ctxt)
161 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
162 Span::new(self.lo, self.hi, ctxt)
166 // The interner in thread-local, so `Span` shouldn't move between threads.
167 impl !Send for Span {}
168 impl !Sync for Span {}
170 impl PartialOrd for Span {
171 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
172 PartialOrd::partial_cmp(&self.data(), &rhs.data())
176 fn cmp(&self, rhs: &Self) -> Ordering {
177 Ord::cmp(&self.data(), &rhs.data())
181 /// A collection of spans. Spans have two orthogonal attributes:
183 /// - they can be *primary spans*. In this case they are the locus of
184 /// the error, and would be rendered with `^^^`.
185 /// - they can have a *label*. In this case, the label is written next
186 /// to the mark in the snippet when we render.
187 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
188 pub struct MultiSpan {
189 primary_spans: Vec<Span>,
190 span_labels: Vec<(Span, String)>,
195 pub fn lo(self) -> BytePos {
199 pub fn with_lo(self, lo: BytePos) -> Span {
200 self.data().with_lo(lo)
203 pub fn hi(self) -> BytePos {
207 pub fn with_hi(self, hi: BytePos) -> Span {
208 self.data().with_hi(hi)
211 pub fn ctxt(self) -> SyntaxContext {
215 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
216 self.data().with_ctxt(ctxt)
219 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
220 pub fn substitute_dummy(self, other: Span) -> Span {
221 if self.source_equal(&DUMMY_SP) { other } else { self }
224 /// Return true if `self` fully encloses `other`.
225 pub fn contains(self, other: Span) -> bool {
226 let span = self.data();
227 let other = other.data();
228 span.lo <= other.lo && other.hi <= span.hi
231 /// Return true if the spans are equal with regards to the source text.
233 /// Use this instead of `==` when either span could be generated code,
234 /// and you only care that they point to the same bytes of source text.
235 pub fn source_equal(&self, other: &Span) -> bool {
236 let span = self.data();
237 let other = other.data();
238 span.lo == other.lo && span.hi == other.hi
241 /// Returns `Some(span)`, where the start is trimmed by the end of `other`
242 pub fn trim_start(self, other: Span) -> Option<Span> {
243 let span = self.data();
244 let other = other.data();
245 if span.hi > other.hi {
246 Some(span.with_lo(cmp::max(span.lo, other.hi)))
252 /// Return the source span - this is either the supplied span, or the span for
253 /// the macro callsite that expanded to it.
254 pub fn source_callsite(self) -> Span {
255 self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
258 /// Return the source callee.
260 /// Returns None if the supplied span has no expansion trace,
261 /// else returns the NameAndSpan for the macro definition
262 /// corresponding to the source callsite.
263 pub fn source_callee(self) -> Option<NameAndSpan> {
264 fn source_callee(info: ExpnInfo) -> NameAndSpan {
265 match info.call_site.ctxt().outer().expn_info() {
266 Some(info) => source_callee(info),
270 self.ctxt().outer().expn_info().map(source_callee)
273 /// Check if a span is "internal" to a macro in which #[unstable]
274 /// items can be used (that is, a macro marked with
275 /// `#[allow_internal_unstable]`).
276 pub fn allows_unstable(&self) -> bool {
277 match self.ctxt().outer().expn_info() {
278 Some(info) => info.callee.allow_internal_unstable,
283 /// Check if this span arises from a compiler desugaring of kind `kind`.
284 pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
285 match self.ctxt().outer().expn_info() {
286 Some(info) => match info.callee.format {
287 ExpnFormat::CompilerDesugaring(k) => k == kind,
294 /// Return the compiler desugaring that created this span, or None
295 /// if this span is not from a desugaring.
296 pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
297 match self.ctxt().outer().expn_info() {
298 Some(info) => match info.callee.format {
299 ExpnFormat::CompilerDesugaring(k) => Some(k),
306 /// Check if a span is "internal" to a macro in which `unsafe`
307 /// can be used without triggering the `unsafe_code` lint
308 // (that is, a macro marked with `#[allow_internal_unsafe]`).
309 pub fn allows_unsafe(&self) -> bool {
310 match self.ctxt().outer().expn_info() {
311 Some(info) => info.callee.allow_internal_unsafe,
316 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
317 let mut prev_span = DUMMY_SP;
318 let mut result = vec![];
320 let info = match self.ctxt().outer().expn_info() {
325 let (pre, post) = match info.callee.format {
326 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
327 ExpnFormat::MacroBang(..) => ("", "!"),
328 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
330 let macro_decl_name = format!("{}{}{}", pre, info.callee.name(), post);
331 let def_site_span = info.callee.span;
333 // Don't print recursive invocations
334 if !info.call_site.source_equal(&prev_span) {
335 result.push(MacroBacktrace {
336 call_site: info.call_site,
343 self = info.call_site;
348 /// Return a `Span` that would enclose both `self` and `end`.
349 pub fn to(self, end: Span) -> Span {
350 let span_data = self.data();
351 let end_data = end.data();
352 // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480)
353 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
354 // have an incomplete span than a completely nonsensical one.
355 if span_data.ctxt != end_data.ctxt {
356 if span_data.ctxt == SyntaxContext::empty() {
358 } else if end_data.ctxt == SyntaxContext::empty() {
361 // both span fall within a macro
362 // FIXME(estebank) check if it is the *same* macro
365 cmp::min(span_data.lo, end_data.lo),
366 cmp::max(span_data.hi, end_data.hi),
367 if span_data.ctxt == SyntaxContext::empty() { end_data.ctxt } else { span_data.ctxt },
371 /// Return a `Span` between the end of `self` to the beginning of `end`.
372 pub fn between(self, end: Span) -> Span {
373 let span = self.data();
374 let end = end.data();
378 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
382 /// Return a `Span` between the beginning of `self` to the beginning of `end`.
383 pub fn until(self, end: Span) -> Span {
384 let span = self.data();
385 let end = end.data();
389 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
394 #[derive(Clone, Debug)]
395 pub struct SpanLabel {
396 /// The span we are going to include in the final snippet.
399 /// Is this a primary span? This is the "locus" of the message,
400 /// and is indicated with a `^^^^` underline, versus `----`.
401 pub is_primary: bool,
403 /// What label should we attach to this span (if any)?
404 pub label: Option<String>,
407 impl Default for Span {
408 fn default() -> Self {
413 impl serialize::UseSpecializedEncodable for Span {
414 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
415 let span = self.data();
416 s.emit_struct("Span", 2, |s| {
417 s.emit_struct_field("lo", 0, |s| {
421 s.emit_struct_field("hi", 1, |s| {
428 impl serialize::UseSpecializedDecodable for Span {
429 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
430 d.read_struct("Span", 2, |d| {
431 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
432 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
433 Ok(Span::new(lo, hi, NO_EXPANSION))
438 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
439 f.debug_struct("Span")
440 .field("lo", &span.lo())
441 .field("hi", &span.hi())
442 .field("ctxt", &span.ctxt())
446 impl fmt::Debug for Span {
447 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
448 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
452 impl fmt::Debug for SpanData {
453 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
454 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
459 pub fn new() -> MultiSpan {
461 primary_spans: vec![],
466 pub fn from_span(primary_span: Span) -> MultiSpan {
468 primary_spans: vec![primary_span],
473 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
480 pub fn push_span_label(&mut self, span: Span, label: String) {
481 self.span_labels.push((span, label));
484 /// Selects the first primary span (if any)
485 pub fn primary_span(&self) -> Option<Span> {
486 self.primary_spans.first().cloned()
489 /// Returns all primary spans.
490 pub fn primary_spans(&self) -> &[Span] {
494 /// Replaces all occurrences of one Span with another. Used to move Spans in areas that don't
495 /// display well (like std macros). Returns true if replacements occurred.
496 pub fn replace(&mut self, before: Span, after: Span) -> bool {
497 let mut replacements_occurred = false;
498 for primary_span in &mut self.primary_spans {
499 if *primary_span == before {
500 *primary_span = after;
501 replacements_occurred = true;
504 for span_label in &mut self.span_labels {
505 if span_label.0 == before {
506 span_label.0 = after;
507 replacements_occurred = true;
510 replacements_occurred
513 /// Returns the strings to highlight. We always ensure that there
514 /// is an entry for each of the primary spans -- for each primary
515 /// span P, if there is at least one label with span P, we return
516 /// those labels (marked as primary). But otherwise we return
517 /// `SpanLabel` instances with empty labels.
518 pub fn span_labels(&self) -> Vec<SpanLabel> {
519 let is_primary = |span| self.primary_spans.contains(&span);
520 let mut span_labels = vec![];
522 for &(span, ref label) in &self.span_labels {
523 span_labels.push(SpanLabel {
525 is_primary: is_primary(span),
526 label: Some(label.clone())
530 for &span in &self.primary_spans {
531 if !span_labels.iter().any(|sl| sl.span == span) {
532 span_labels.push(SpanLabel {
544 impl From<Span> for MultiSpan {
545 fn from(span: Span) -> MultiSpan {
546 MultiSpan::from_span(span)
550 impl From<Vec<Span>> for MultiSpan {
551 fn from(spans: Vec<Span>) -> MultiSpan {
552 MultiSpan::from_spans(spans)
556 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
558 /// Identifies an offset of a multi-byte character in a FileMap
559 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
560 pub struct MultiByteChar {
561 /// The absolute offset of the character in the CodeMap
563 /// The number of bytes, >=2
567 /// Identifies an offset of a non-narrow character in a FileMap
568 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
569 pub enum NonNarrowChar {
570 /// Represents a zero-width character
572 /// Represents a wide (fullwidth) character
574 /// Represents a tab character, represented visually with a width of 4 characters
579 fn new(pos: BytePos, width: usize) -> Self {
581 0 => NonNarrowChar::ZeroWidth(pos),
582 2 => NonNarrowChar::Wide(pos),
583 4 => NonNarrowChar::Tab(pos),
584 _ => panic!("width {} given for non-narrow character", width),
588 /// Returns the absolute offset of the character in the CodeMap
589 pub fn pos(&self) -> BytePos {
591 NonNarrowChar::ZeroWidth(p) |
592 NonNarrowChar::Wide(p) |
593 NonNarrowChar::Tab(p) => p,
597 /// Returns the width of the character, 0 (zero-width) or 2 (wide)
598 pub fn width(&self) -> usize {
600 NonNarrowChar::ZeroWidth(_) => 0,
601 NonNarrowChar::Wide(_) => 2,
602 NonNarrowChar::Tab(_) => 4,
607 impl Add<BytePos> for NonNarrowChar {
610 fn add(self, rhs: BytePos) -> Self {
612 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
613 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
614 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
619 impl Sub<BytePos> for NonNarrowChar {
622 fn sub(self, rhs: BytePos) -> Self {
624 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
625 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
626 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
631 /// The state of the lazy external source loading mechanism of a FileMap.
632 #[derive(PartialEq, Eq, Clone)]
633 pub enum ExternalSource {
634 /// The external source has been loaded already.
636 /// No attempt has been made to load the external source.
638 /// A failed attempt has been made to load the external source.
640 /// No external source has to be loaded, since the FileMap represents a local crate.
644 impl ExternalSource {
645 pub fn is_absent(&self) -> bool {
647 ExternalSource::Present(_) => false,
652 pub fn get_source(&self) -> Option<&str> {
654 ExternalSource::Present(ref src) => Some(src),
660 /// A single source in the CodeMap.
663 /// The name of the file that the source came from, source that doesn't
664 /// originate from files has names between angle brackets by convention,
667 /// True if the `name` field above has been modified by -Zremap-path-prefix
668 pub name_was_remapped: bool,
669 /// The unmapped path of the file that the source came from.
670 /// Set to `None` if the FileMap was imported from an external crate.
671 pub unmapped_path: Option<FileName>,
672 /// Indicates which crate this FileMap was imported from.
673 pub crate_of_origin: u32,
674 /// The complete source code
675 pub src: Option<Rc<String>>,
676 /// The source code's hash
678 /// The external source code (used for external crates, which will have a `None`
679 /// value as `self.src`.
680 pub external_src: RefCell<ExternalSource>,
681 /// The start position of this source in the CodeMap
682 pub start_pos: BytePos,
683 /// The end position of this source in the CodeMap
684 pub end_pos: BytePos,
685 /// Locations of lines beginnings in the source code
686 pub lines: RefCell<Vec<BytePos>>,
687 /// Locations of multi-byte characters in the source code
688 pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
689 /// Width of characters that are not narrow in the source code
690 pub non_narrow_chars: RefCell<Vec<NonNarrowChar>>,
691 /// A hash of the filename, used for speeding up the incr. comp. hashing.
695 impl Encodable for FileMap {
696 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
697 s.emit_struct("FileMap", 8, |s| {
698 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
699 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
700 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
701 s.emit_struct_field("start_pos", 4, |s| self.start_pos.encode(s))?;
702 s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
703 s.emit_struct_field("lines", 6, |s| {
704 let lines = self.lines.borrow();
706 s.emit_u32(lines.len() as u32)?;
708 if !lines.is_empty() {
709 // In order to preserve some space, we exploit the fact that
710 // the lines list is sorted and individual lines are
711 // probably not that long. Because of that we can store lines
712 // as a difference list, using as little space as possible
713 // for the differences.
714 let max_line_length = if lines.len() == 1 {
718 .map(|w| w[1] - w[0])
719 .map(|bp| bp.to_usize())
724 let bytes_per_diff: u8 = match max_line_length {
726 0x100 ... 0xFFFF => 2,
730 // Encode the number of bytes used per diff.
731 bytes_per_diff.encode(s)?;
733 // Encode the first element.
736 let diff_iter = (&lines[..]).windows(2)
737 .map(|w| (w[1] - w[0]));
739 match bytes_per_diff {
740 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
741 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
742 4 => for diff in diff_iter { diff.0.encode(s)? },
749 s.emit_struct_field("multibyte_chars", 7, |s| {
750 (*self.multibyte_chars.borrow()).encode(s)
752 s.emit_struct_field("non_narrow_chars", 8, |s| {
753 (*self.non_narrow_chars.borrow()).encode(s)
755 s.emit_struct_field("name_hash", 9, |s| {
756 self.name_hash.encode(s)
762 impl Decodable for FileMap {
763 fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
765 d.read_struct("FileMap", 8, |d| {
766 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
767 let name_was_remapped: bool =
768 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
770 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
771 let start_pos: BytePos =
772 d.read_struct_field("start_pos", 4, |d| Decodable::decode(d))?;
773 let end_pos: BytePos = d.read_struct_field("end_pos", 5, |d| Decodable::decode(d))?;
774 let lines: Vec<BytePos> = d.read_struct_field("lines", 6, |d| {
775 let num_lines: u32 = Decodable::decode(d)?;
776 let mut lines = Vec::with_capacity(num_lines as usize);
779 // Read the number of bytes used per diff.
780 let bytes_per_diff: u8 = Decodable::decode(d)?;
782 // Read the first element.
783 let mut line_start: BytePos = Decodable::decode(d)?;
784 lines.push(line_start);
786 for _ in 1..num_lines {
787 let diff = match bytes_per_diff {
788 1 => d.read_u8()? as u32,
789 2 => d.read_u16()? as u32,
794 line_start = line_start + BytePos(diff);
796 lines.push(line_start);
802 let multibyte_chars: Vec<MultiByteChar> =
803 d.read_struct_field("multibyte_chars", 7, |d| Decodable::decode(d))?;
804 let non_narrow_chars: Vec<NonNarrowChar> =
805 d.read_struct_field("non_narrow_chars", 8, |d| Decodable::decode(d))?;
806 let name_hash: u128 =
807 d.read_struct_field("name_hash", 9, |d| Decodable::decode(d))?;
812 // `crate_of_origin` has to be set by the importer.
813 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
814 // That constant is not available here unfortunately :(
815 crate_of_origin: ::std::u32::MAX - 1,
820 external_src: RefCell::new(ExternalSource::AbsentOk),
821 lines: RefCell::new(lines),
822 multibyte_chars: RefCell::new(multibyte_chars),
823 non_narrow_chars: RefCell::new(non_narrow_chars),
830 impl fmt::Debug for FileMap {
831 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
832 write!(fmt, "FileMap({})", self.name)
837 pub fn new(name: FileName,
838 name_was_remapped: bool,
839 unmapped_path: FileName,
841 start_pos: BytePos) -> FileMap {
842 remove_bom(&mut src);
845 let mut hasher: StableHasher<u128> = StableHasher::new();
846 hasher.write(src.as_bytes());
850 let mut hasher: StableHasher<u128> = StableHasher::new();
851 name.hash(&mut hasher);
854 let end_pos = start_pos.to_usize() + src.len();
859 unmapped_path: Some(unmapped_path),
861 src: Some(Rc::new(src)),
863 external_src: RefCell::new(ExternalSource::Unneeded),
865 end_pos: Pos::from_usize(end_pos),
866 lines: RefCell::new(Vec::new()),
867 multibyte_chars: RefCell::new(Vec::new()),
868 non_narrow_chars: RefCell::new(Vec::new()),
873 /// EFFECT: register a start-of-line offset in the
874 /// table of line-beginnings.
875 /// UNCHECKED INVARIANT: these offsets must be added in the right
876 /// order and must be in the right places; there is shared knowledge
877 /// about what ends a line between this file and parse.rs
878 /// WARNING: pos param here is the offset relative to start of CodeMap,
879 /// and CodeMap will append a newline when adding a filemap without a newline at the end,
880 /// so the safe way to call this is with value calculated as
881 /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
882 pub fn next_line(&self, pos: BytePos) {
883 // the new charpos must be > the last one (or it's the first one).
884 let mut lines = self.lines.borrow_mut();
885 let line_len = lines.len();
886 assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
890 /// Add externally loaded source.
891 /// If the hash of the input doesn't match or no input is supplied via None,
892 /// it is interpreted as an error and the corresponding enum variant is set.
893 /// The return value signifies whether some kind of source is present.
894 pub fn add_external_src<F>(&self, get_src: F) -> bool
895 where F: FnOnce() -> Option<String>
897 if *self.external_src.borrow() == ExternalSource::AbsentOk {
899 let mut external_src = self.external_src.borrow_mut();
900 if let Some(src) = src {
901 let mut hasher: StableHasher<u128> = StableHasher::new();
902 hasher.write(src.as_bytes());
904 if hasher.finish() == self.src_hash {
905 *external_src = ExternalSource::Present(src);
909 *external_src = ExternalSource::AbsentErr;
914 self.src.is_some() || self.external_src.borrow().get_source().is_some()
918 /// Get a line from the list of pre-computed line-beginnings.
919 /// The line number here is 0-based.
920 pub fn get_line(&self, line_number: usize) -> Option<Cow<str>> {
921 fn get_until_newline(src: &str, begin: usize) -> &str {
922 // We can't use `lines.get(line_number+1)` because we might
923 // be parsing when we call this function and thus the current
924 // line is the last one we have line info for.
925 let slice = &src[begin..];
926 match slice.find('\n') {
927 Some(e) => &slice[..e],
932 let lines = self.lines.borrow();
933 let line = if let Some(line) = lines.get(line_number) {
938 let begin: BytePos = *line - self.start_pos;
939 let begin = begin.to_usize();
941 if let Some(ref src) = self.src {
942 Some(Cow::from(get_until_newline(src, begin)))
943 } else if let Some(src) = self.external_src.borrow().get_source() {
944 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
950 pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
951 assert!(bytes >=2 && bytes <= 4);
952 let mbc = MultiByteChar {
956 self.multibyte_chars.borrow_mut().push(mbc);
959 pub fn record_width(&self, pos: BytePos, ch: char) {
960 let width = match ch {
962 // Tabs will consume 4 columns.
965 // Make newlines take one column so that displayed spans can point them.
968 // Assume control characters are zero width.
969 // FIXME: How can we decide between `width` and `width_cjk`?
970 unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0),
972 // Only record non-narrow characters.
974 self.non_narrow_chars.borrow_mut().push(NonNarrowChar::new(pos, width));
978 pub fn is_real_file(&self) -> bool {
982 pub fn is_imported(&self) -> bool {
986 pub fn byte_length(&self) -> u32 {
987 self.end_pos.0 - self.start_pos.0
989 pub fn count_lines(&self) -> usize {
990 self.lines.borrow().len()
993 /// Find the line containing the given position. The return value is the
994 /// index into the `lines` array of this FileMap, not the 1-based line
995 /// number. If the filemap is empty or the position is located before the
996 /// first line, None is returned.
997 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
998 let lines = self.lines.borrow();
999 if lines.len() == 0 {
1003 let line_index = lookup_line(&lines[..], pos);
1004 assert!(line_index < lines.len() as isize);
1005 if line_index >= 0 {
1006 Some(line_index as usize)
1012 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1013 if self.start_pos == self.end_pos {
1014 return (self.start_pos, self.end_pos);
1017 let lines = self.lines.borrow();
1018 assert!(line_index < lines.len());
1019 if line_index == (lines.len() - 1) {
1020 (lines[line_index], self.end_pos)
1022 (lines[line_index], lines[line_index + 1])
1027 pub fn contains(&self, byte_pos: BytePos) -> bool {
1028 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1032 /// Remove utf-8 BOM if any.
1033 fn remove_bom(src: &mut String) {
1034 if src.starts_with("\u{feff}") {
1039 // _____________________________________________________________________________
1040 // Pos, BytePos, CharPos
1044 fn from_usize(n: usize) -> Self;
1045 fn to_usize(&self) -> usize;
1048 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1050 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1051 pub struct BytePos(pub u32);
1053 /// A character offset. Because of multibyte utf8 characters, a byte offset
1054 /// is not equivalent to a character offset. The CodeMap will convert BytePos
1055 /// values to CharPos values as necessary.
1056 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1057 pub struct CharPos(pub usize);
1059 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
1060 // have been unsuccessful
1062 impl Pos for BytePos {
1063 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1064 fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
1067 impl Add for BytePos {
1068 type Output = BytePos;
1070 fn add(self, rhs: BytePos) -> BytePos {
1071 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1075 impl Sub for BytePos {
1076 type Output = BytePos;
1078 fn sub(self, rhs: BytePos) -> BytePos {
1079 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1083 impl Encodable for BytePos {
1084 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1089 impl Decodable for BytePos {
1090 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1091 Ok(BytePos(d.read_u32()?))
1095 impl Pos for CharPos {
1096 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1097 fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
1100 impl Add for CharPos {
1101 type Output = CharPos;
1103 fn add(self, rhs: CharPos) -> CharPos {
1104 CharPos(self.to_usize() + rhs.to_usize())
1108 impl Sub for CharPos {
1109 type Output = CharPos;
1111 fn sub(self, rhs: CharPos) -> CharPos {
1112 CharPos(self.to_usize() - rhs.to_usize())
1116 // _____________________________________________________________________________
1117 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
1120 /// A source code location used for error reporting
1121 #[derive(Debug, Clone)]
1123 /// Information about the original source
1124 pub file: Rc<FileMap>,
1125 /// The (1-based) line number
1127 /// The (0-based) column offset
1129 /// The (0-based) column offset when displayed
1130 pub col_display: usize,
1133 /// A source code location used as the result of lookup_char_pos_adj
1134 // Actually, *none* of the clients use the filename *or* file field;
1135 // perhaps they should just be removed.
1137 pub struct LocWithOpt {
1138 pub filename: FileName,
1141 pub file: Option<Rc<FileMap>>,
1144 // used to be structural records. Better names, anyone?
1146 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
1148 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
1150 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1151 pub struct LineInfo {
1152 /// Index of line, starting from 0.
1153 pub line_index: usize,
1155 /// Column in line where span begins, starting from 0.
1156 pub start_col: CharPos,
1158 /// Column in line where span ends, starting from 0, exclusive.
1159 pub end_col: CharPos,
1162 pub struct FileLines {
1163 pub file: Rc<FileMap>,
1164 pub lines: Vec<LineInfo>
1167 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
1168 Cell::new(default_span_debug));
1171 pub struct MacroBacktrace {
1172 /// span where macro was applied to generate this code
1173 pub call_site: Span,
1175 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1176 pub macro_decl_name: String,
1178 /// span where macro was defined (if known)
1179 pub def_site_span: Option<Span>,
1182 // _____________________________________________________________________________
1183 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
1186 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1188 #[derive(Clone, PartialEq, Eq, Debug)]
1189 pub enum SpanLinesError {
1190 IllFormedSpan(Span),
1191 DistinctSources(DistinctSources),
1194 #[derive(Clone, PartialEq, Eq, Debug)]
1195 pub enum SpanSnippetError {
1196 IllFormedSpan(Span),
1197 DistinctSources(DistinctSources),
1198 MalformedForCodemap(MalformedCodemapPositions),
1199 SourceNotAvailable { filename: FileName }
1202 #[derive(Clone, PartialEq, Eq, Debug)]
1203 pub struct DistinctSources {
1204 pub begin: (FileName, BytePos),
1205 pub end: (FileName, BytePos)
1208 #[derive(Clone, PartialEq, Eq, Debug)]
1209 pub struct MalformedCodemapPositions {
1211 pub source_len: usize,
1212 pub begin_pos: BytePos,
1213 pub end_pos: BytePos
1216 // Given a slice of line start positions and a position, returns the index of
1217 // the line the position is on. Returns -1 if the position is located before
1219 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1220 match lines.binary_search(&pos) {
1221 Ok(line) => line as isize,
1222 Err(line) => line as isize - 1
1228 use super::{lookup_line, BytePos};
1231 fn test_lookup_line() {
1233 let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1235 assert_eq!(lookup_line(lines, BytePos(0)), -1);
1236 assert_eq!(lookup_line(lines, BytePos(3)), 0);
1237 assert_eq!(lookup_line(lines, BytePos(4)), 0);
1239 assert_eq!(lookup_line(lines, BytePos(16)), 0);
1240 assert_eq!(lookup_line(lines, BytePos(17)), 1);
1241 assert_eq!(lookup_line(lines, BytePos(18)), 1);
1243 assert_eq!(lookup_line(lines, BytePos(28)), 2);
1244 assert_eq!(lookup_line(lines, BytePos(29)), 2);