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/")]
22 #![feature(custom_attribute)]
23 #![feature(optin_builtin_traits)]
24 #![allow(unused_attributes)]
25 #![feature(specialization)]
29 use std::cmp::{self, Ordering};
31 use std::hash::{Hasher, Hash};
32 use std::ops::{Add, Sub};
33 use std::path::PathBuf;
35 use rustc_data_structures::stable_hasher::StableHasher;
36 use rustc_data_structures::sync::{Lrc, Lock};
38 extern crate rustc_data_structures;
41 extern crate scoped_tls;
43 use serialize::{Encodable, Decodable, Encoder, Decoder};
45 extern crate serialize;
46 extern crate serialize as rustc_serialize; // used by deriving
48 extern crate unicode_width;
51 pub use hygiene::{Mark, SyntaxContext, ExpnInfo, ExpnFormat, NameAndSpan, CompilerDesugaringKind};
54 pub use span_encoding::{Span, DUMMY_SP};
59 symbol_interner: Lock<symbol::Interner>,
60 span_interner: Lock<span_encoding::SpanInterner>,
61 hygiene_data: Lock<hygiene::HygieneData>,
65 pub fn new() -> Globals {
67 symbol_interner: Lock::new(symbol::Interner::fresh()),
68 span_interner: Lock::new(span_encoding::SpanInterner::default()),
69 hygiene_data: Lock::new(hygiene::HygieneData::new()),
74 scoped_thread_local!(pub static GLOBALS: Globals);
76 /// Differentiates between real files and common virtual files
77 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
86 /// Hack in src/libsyntax/parse.rs
90 /// Strings provided as --cfg [cfgspec] stored in a crate_cfg
92 /// Custom sources for explicit parser calls from plugins and drivers
96 impl std::fmt::Display for FileName {
97 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
98 use self::FileName::*;
100 Real(ref path) => write!(fmt, "{}", path.display()),
101 Macros(ref name) => write!(fmt, "<{} macros>", name),
102 QuoteExpansion => write!(fmt, "<quote expansion>"),
103 MacroExpansion => write!(fmt, "<macro expansion>"),
104 Anon => write!(fmt, "<anon>"),
105 ProcMacroSourceCode => write!(fmt, "<proc-macro source code>"),
106 CfgSpec => write!(fmt, "cfgspec"),
107 Custom(ref s) => write!(fmt, "<{}>", s),
112 impl From<PathBuf> for FileName {
113 fn from(p: PathBuf) -> Self {
114 assert!(!p.to_string_lossy().ends_with('>'));
120 pub fn is_real(&self) -> bool {
121 use self::FileName::*;
127 ProcMacroSourceCode |
130 QuoteExpansion => false,
134 pub fn is_macros(&self) -> bool {
135 use self::FileName::*;
140 ProcMacroSourceCode |
143 QuoteExpansion => false,
149 /// Spans represent a region of code, used for error reporting. Positions in spans
150 /// are *absolute* positions from the beginning of the codemap, not positions
151 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
152 /// to the original source.
153 /// You must be careful if the span crosses more than one file - you will not be
154 /// able to use many of the functions on spans in codemap and you cannot assume
155 /// that the length of the span = hi - lo; there may be space in the BytePos
156 /// range between files.
158 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
159 /// sent to other threads, but some pieces of performance infra run in a separate thread.
160 /// Using `Span` is generally preferred.
161 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
162 pub struct SpanData {
165 /// Information about where the macro came from, if this piece of
166 /// code was created by a macro expansion.
167 pub ctxt: SyntaxContext,
172 pub fn with_lo(&self, lo: BytePos) -> Span {
173 Span::new(lo, self.hi, self.ctxt)
176 pub fn with_hi(&self, hi: BytePos) -> Span {
177 Span::new(self.lo, hi, self.ctxt)
180 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
181 Span::new(self.lo, self.hi, ctxt)
185 // The interner is pointed to by a thread local value which is only set on the main thread
186 // with parallelization is disabled. So we don't allow Span to transfer between threads
187 // to avoid panics and other errors, even though it would be memory safe to do so.
188 #[cfg(not(parallel_queries))]
189 impl !Send for Span {}
190 #[cfg(not(parallel_queries))]
191 impl !Sync for Span {}
193 impl PartialOrd for Span {
194 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
195 PartialOrd::partial_cmp(&self.data(), &rhs.data())
199 fn cmp(&self, rhs: &Self) -> Ordering {
200 Ord::cmp(&self.data(), &rhs.data())
204 /// A collection of spans. Spans have two orthogonal attributes:
206 /// - they can be *primary spans*. In this case they are the locus of
207 /// the error, and would be rendered with `^^^`.
208 /// - they can have a *label*. In this case, the label is written next
209 /// to the mark in the snippet when we render.
210 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
211 pub struct MultiSpan {
212 primary_spans: Vec<Span>,
213 span_labels: Vec<(Span, String)>,
218 pub fn lo(self) -> BytePos {
222 pub fn with_lo(self, lo: BytePos) -> Span {
223 self.data().with_lo(lo)
226 pub fn hi(self) -> BytePos {
230 pub fn with_hi(self, hi: BytePos) -> Span {
231 self.data().with_hi(hi)
234 pub fn ctxt(self) -> SyntaxContext {
238 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
239 self.data().with_ctxt(ctxt)
242 /// Returns a new span representing an empty span at the beginning of this span
244 pub fn shrink_to_lo(self) -> Span {
245 let span = self.data();
246 span.with_hi(span.lo)
248 /// Returns a new span representing an empty span at the end of this span
250 pub fn shrink_to_hi(self) -> Span {
251 let span = self.data();
252 span.with_lo(span.hi)
255 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
256 pub fn substitute_dummy(self, other: Span) -> Span {
257 if self.source_equal(&DUMMY_SP) { other } else { self }
260 /// Return true if `self` fully encloses `other`.
261 pub fn contains(self, other: Span) -> bool {
262 let span = self.data();
263 let other = other.data();
264 span.lo <= other.lo && other.hi <= span.hi
267 /// Return true if the spans are equal with regards to the source text.
269 /// Use this instead of `==` when either span could be generated code,
270 /// and you only care that they point to the same bytes of source text.
271 pub fn source_equal(&self, other: &Span) -> bool {
272 let span = self.data();
273 let other = other.data();
274 span.lo == other.lo && span.hi == other.hi
277 /// Returns `Some(span)`, where the start is trimmed by the end of `other`
278 pub fn trim_start(self, other: Span) -> Option<Span> {
279 let span = self.data();
280 let other = other.data();
281 if span.hi > other.hi {
282 Some(span.with_lo(cmp::max(span.lo, other.hi)))
288 /// Return the source span - this is either the supplied span, or the span for
289 /// the macro callsite that expanded to it.
290 pub fn source_callsite(self) -> Span {
291 self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
294 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
296 pub fn parent(self) -> Option<Span> {
297 self.ctxt().outer().expn_info().map(|i| i.call_site)
300 /// Return the source callee.
302 /// Returns None if the supplied span has no expansion trace,
303 /// else returns the NameAndSpan for the macro definition
304 /// corresponding to the source callsite.
305 pub fn source_callee(self) -> Option<NameAndSpan> {
306 fn source_callee(info: ExpnInfo) -> NameAndSpan {
307 match info.call_site.ctxt().outer().expn_info() {
308 Some(info) => source_callee(info),
312 self.ctxt().outer().expn_info().map(source_callee)
315 /// Check if a span is "internal" to a macro in which #[unstable]
316 /// items can be used (that is, a macro marked with
317 /// `#[allow_internal_unstable]`).
318 pub fn allows_unstable(&self) -> bool {
319 match self.ctxt().outer().expn_info() {
320 Some(info) => info.callee.allow_internal_unstable,
325 /// Check if this span arises from a compiler desugaring of kind `kind`.
326 pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
327 match self.ctxt().outer().expn_info() {
328 Some(info) => match info.callee.format {
329 ExpnFormat::CompilerDesugaring(k) => k == kind,
336 /// Return the compiler desugaring that created this span, or None
337 /// if this span is not from a desugaring.
338 pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
339 match self.ctxt().outer().expn_info() {
340 Some(info) => match info.callee.format {
341 ExpnFormat::CompilerDesugaring(k) => Some(k),
348 /// Check if a span is "internal" to a macro in which `unsafe`
349 /// can be used without triggering the `unsafe_code` lint
350 // (that is, a macro marked with `#[allow_internal_unsafe]`).
351 pub fn allows_unsafe(&self) -> bool {
352 match self.ctxt().outer().expn_info() {
353 Some(info) => info.callee.allow_internal_unsafe,
358 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
359 let mut prev_span = DUMMY_SP;
360 let mut result = vec![];
361 while let Some(info) = self.ctxt().outer().expn_info() {
362 let (pre, post) = match info.callee.format {
363 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
364 ExpnFormat::MacroBang(..) => ("", "!"),
365 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
367 let macro_decl_name = format!("{}{}{}", pre, info.callee.name(), post);
368 let def_site_span = info.callee.span;
370 // Don't print recursive invocations
371 if !info.call_site.source_equal(&prev_span) {
372 result.push(MacroBacktrace {
373 call_site: info.call_site,
380 self = info.call_site;
385 /// Return a `Span` that would enclose both `self` and `end`.
386 pub fn to(self, end: Span) -> Span {
387 let span_data = self.data();
388 let end_data = end.data();
389 // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480)
390 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
391 // have an incomplete span than a completely nonsensical one.
392 if span_data.ctxt != end_data.ctxt {
393 if span_data.ctxt == SyntaxContext::empty() {
395 } else if end_data.ctxt == SyntaxContext::empty() {
398 // both span fall within a macro
399 // FIXME(estebank) check if it is the *same* macro
402 cmp::min(span_data.lo, end_data.lo),
403 cmp::max(span_data.hi, end_data.hi),
404 if span_data.ctxt == SyntaxContext::empty() { end_data.ctxt } else { span_data.ctxt },
408 /// Return a `Span` between the end of `self` to the beginning of `end`.
409 pub fn between(self, end: Span) -> Span {
410 let span = self.data();
411 let end = end.data();
415 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
419 /// Return a `Span` between the beginning of `self` to the beginning of `end`.
420 pub fn until(self, end: Span) -> Span {
421 let span = self.data();
422 let end = end.data();
426 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
431 pub fn apply_mark(self, mark: Mark) -> Span {
432 let span = self.data();
433 span.with_ctxt(span.ctxt.apply_mark(mark))
437 pub fn remove_mark(&mut self) -> Mark {
438 let mut span = self.data();
439 let mark = span.ctxt.remove_mark();
440 *self = Span::new(span.lo, span.hi, span.ctxt);
445 pub fn adjust(&mut self, expansion: Mark) -> Option<Mark> {
446 let mut span = self.data();
447 let mark = span.ctxt.adjust(expansion);
448 *self = Span::new(span.lo, span.hi, span.ctxt);
453 pub fn glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
454 -> Option<Option<Mark>> {
455 let mut span = self.data();
456 let mark = span.ctxt.glob_adjust(expansion, glob_ctxt);
457 *self = Span::new(span.lo, span.hi, span.ctxt);
462 pub fn reverse_glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
463 -> Option<Option<Mark>> {
464 let mut span = self.data();
465 let mark = span.ctxt.reverse_glob_adjust(expansion, glob_ctxt);
466 *self = Span::new(span.lo, span.hi, span.ctxt);
471 pub fn modern(self) -> Span {
472 let span = self.data();
473 span.with_ctxt(span.ctxt.modern())
477 #[derive(Clone, Debug)]
478 pub struct SpanLabel {
479 /// The span we are going to include in the final snippet.
482 /// Is this a primary span? This is the "locus" of the message,
483 /// and is indicated with a `^^^^` underline, versus `----`.
484 pub is_primary: bool,
486 /// What label should we attach to this span (if any)?
487 pub label: Option<String>,
490 impl Default for Span {
491 fn default() -> Self {
496 impl serialize::UseSpecializedEncodable for Span {
497 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
498 let span = self.data();
499 s.emit_struct("Span", 2, |s| {
500 s.emit_struct_field("lo", 0, |s| {
504 s.emit_struct_field("hi", 1, |s| {
511 impl serialize::UseSpecializedDecodable for Span {
512 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
513 d.read_struct("Span", 2, |d| {
514 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
515 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
516 Ok(Span::new(lo, hi, NO_EXPANSION))
521 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
522 f.debug_struct("Span")
523 .field("lo", &span.lo())
524 .field("hi", &span.hi())
525 .field("ctxt", &span.ctxt())
529 impl fmt::Debug for Span {
530 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
531 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
535 impl fmt::Debug for SpanData {
536 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
537 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
542 pub fn new() -> MultiSpan {
544 primary_spans: vec![],
549 pub fn from_span(primary_span: Span) -> MultiSpan {
551 primary_spans: vec![primary_span],
556 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
563 pub fn push_span_label(&mut self, span: Span, label: String) {
564 self.span_labels.push((span, label));
567 /// Selects the first primary span (if any)
568 pub fn primary_span(&self) -> Option<Span> {
569 self.primary_spans.first().cloned()
572 /// Returns all primary spans.
573 pub fn primary_spans(&self) -> &[Span] {
577 /// Replaces all occurrences of one Span with another. Used to move Spans in areas that don't
578 /// display well (like std macros). Returns true if replacements occurred.
579 pub fn replace(&mut self, before: Span, after: Span) -> bool {
580 let mut replacements_occurred = false;
581 for primary_span in &mut self.primary_spans {
582 if *primary_span == before {
583 *primary_span = after;
584 replacements_occurred = true;
587 for span_label in &mut self.span_labels {
588 if span_label.0 == before {
589 span_label.0 = after;
590 replacements_occurred = true;
593 replacements_occurred
596 /// Returns the strings to highlight. We always ensure that there
597 /// is an entry for each of the primary spans -- for each primary
598 /// span P, if there is at least one label with span P, we return
599 /// those labels (marked as primary). But otherwise we return
600 /// `SpanLabel` instances with empty labels.
601 pub fn span_labels(&self) -> Vec<SpanLabel> {
602 let is_primary = |span| self.primary_spans.contains(&span);
603 let mut span_labels = vec![];
605 for &(span, ref label) in &self.span_labels {
606 span_labels.push(SpanLabel {
608 is_primary: is_primary(span),
609 label: Some(label.clone())
613 for &span in &self.primary_spans {
614 if !span_labels.iter().any(|sl| sl.span == span) {
615 span_labels.push(SpanLabel {
627 impl From<Span> for MultiSpan {
628 fn from(span: Span) -> MultiSpan {
629 MultiSpan::from_span(span)
633 impl From<Vec<Span>> for MultiSpan {
634 fn from(spans: Vec<Span>) -> MultiSpan {
635 MultiSpan::from_spans(spans)
639 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
641 /// Identifies an offset of a multi-byte character in a FileMap
642 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
643 pub struct MultiByteChar {
644 /// The absolute offset of the character in the CodeMap
646 /// The number of bytes, >=2
650 /// Identifies an offset of a non-narrow character in a FileMap
651 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
652 pub enum NonNarrowChar {
653 /// Represents a zero-width character
655 /// Represents a wide (fullwidth) character
657 /// Represents a tab character, represented visually with a width of 4 characters
662 fn new(pos: BytePos, width: usize) -> Self {
664 0 => NonNarrowChar::ZeroWidth(pos),
665 2 => NonNarrowChar::Wide(pos),
666 4 => NonNarrowChar::Tab(pos),
667 _ => panic!("width {} given for non-narrow character", width),
671 /// Returns the absolute offset of the character in the CodeMap
672 pub fn pos(&self) -> BytePos {
674 NonNarrowChar::ZeroWidth(p) |
675 NonNarrowChar::Wide(p) |
676 NonNarrowChar::Tab(p) => p,
680 /// Returns the width of the character, 0 (zero-width) or 2 (wide)
681 pub fn width(&self) -> usize {
683 NonNarrowChar::ZeroWidth(_) => 0,
684 NonNarrowChar::Wide(_) => 2,
685 NonNarrowChar::Tab(_) => 4,
690 impl Add<BytePos> for NonNarrowChar {
693 fn add(self, rhs: BytePos) -> Self {
695 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
696 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
697 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
702 impl Sub<BytePos> for NonNarrowChar {
705 fn sub(self, rhs: BytePos) -> Self {
707 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
708 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
709 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
714 /// The state of the lazy external source loading mechanism of a FileMap.
715 #[derive(PartialEq, Eq, Clone)]
716 pub enum ExternalSource {
717 /// The external source has been loaded already.
719 /// No attempt has been made to load the external source.
721 /// A failed attempt has been made to load the external source.
723 /// No external source has to be loaded, since the FileMap represents a local crate.
727 impl ExternalSource {
728 pub fn is_absent(&self) -> bool {
730 ExternalSource::Present(_) => false,
735 pub fn get_source(&self) -> Option<&str> {
737 ExternalSource::Present(ref src) => Some(src),
743 /// A single source in the CodeMap.
746 /// The name of the file that the source came from, source that doesn't
747 /// originate from files has names between angle brackets by convention,
750 /// True if the `name` field above has been modified by --remap-path-prefix
751 pub name_was_remapped: bool,
752 /// The unmapped path of the file that the source came from.
753 /// Set to `None` if the FileMap was imported from an external crate.
754 pub unmapped_path: Option<FileName>,
755 /// Indicates which crate this FileMap was imported from.
756 pub crate_of_origin: u32,
757 /// The complete source code
758 pub src: Option<Lrc<String>>,
759 /// The source code's hash
761 /// The external source code (used for external crates, which will have a `None`
762 /// value as `self.src`.
763 pub external_src: Lock<ExternalSource>,
764 /// The start position of this source in the CodeMap
765 pub start_pos: BytePos,
766 /// The end position of this source in the CodeMap
767 pub end_pos: BytePos,
768 /// Locations of lines beginnings in the source code
769 pub lines: Lock<Vec<BytePos>>,
770 /// Locations of multi-byte characters in the source code
771 pub multibyte_chars: Lock<Vec<MultiByteChar>>,
772 /// Width of characters that are not narrow in the source code
773 pub non_narrow_chars: Lock<Vec<NonNarrowChar>>,
774 /// A hash of the filename, used for speeding up the incr. comp. hashing.
778 impl Encodable for FileMap {
779 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
780 s.emit_struct("FileMap", 8, |s| {
781 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
782 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
783 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
784 s.emit_struct_field("start_pos", 4, |s| self.start_pos.encode(s))?;
785 s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
786 s.emit_struct_field("lines", 6, |s| {
787 let lines = self.lines.borrow();
789 s.emit_u32(lines.len() as u32)?;
791 if !lines.is_empty() {
792 // In order to preserve some space, we exploit the fact that
793 // the lines list is sorted and individual lines are
794 // probably not that long. Because of that we can store lines
795 // as a difference list, using as little space as possible
796 // for the differences.
797 let max_line_length = if lines.len() == 1 {
801 .map(|w| w[1] - w[0])
802 .map(|bp| bp.to_usize())
807 let bytes_per_diff: u8 = match max_line_length {
809 0x100 ... 0xFFFF => 2,
813 // Encode the number of bytes used per diff.
814 bytes_per_diff.encode(s)?;
816 // Encode the first element.
819 let diff_iter = (&lines[..]).windows(2)
820 .map(|w| (w[1] - w[0]));
822 match bytes_per_diff {
823 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
824 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
825 4 => for diff in diff_iter { diff.0.encode(s)? },
832 s.emit_struct_field("multibyte_chars", 7, |s| {
833 (*self.multibyte_chars.borrow()).encode(s)
835 s.emit_struct_field("non_narrow_chars", 8, |s| {
836 (*self.non_narrow_chars.borrow()).encode(s)
838 s.emit_struct_field("name_hash", 9, |s| {
839 self.name_hash.encode(s)
845 impl Decodable for FileMap {
846 fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
848 d.read_struct("FileMap", 8, |d| {
849 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
850 let name_was_remapped: bool =
851 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
853 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
854 let start_pos: BytePos =
855 d.read_struct_field("start_pos", 4, |d| Decodable::decode(d))?;
856 let end_pos: BytePos = d.read_struct_field("end_pos", 5, |d| Decodable::decode(d))?;
857 let lines: Vec<BytePos> = d.read_struct_field("lines", 6, |d| {
858 let num_lines: u32 = Decodable::decode(d)?;
859 let mut lines = Vec::with_capacity(num_lines as usize);
862 // Read the number of bytes used per diff.
863 let bytes_per_diff: u8 = Decodable::decode(d)?;
865 // Read the first element.
866 let mut line_start: BytePos = Decodable::decode(d)?;
867 lines.push(line_start);
869 for _ in 1..num_lines {
870 let diff = match bytes_per_diff {
871 1 => d.read_u8()? as u32,
872 2 => d.read_u16()? as u32,
877 line_start = line_start + BytePos(diff);
879 lines.push(line_start);
885 let multibyte_chars: Vec<MultiByteChar> =
886 d.read_struct_field("multibyte_chars", 7, |d| Decodable::decode(d))?;
887 let non_narrow_chars: Vec<NonNarrowChar> =
888 d.read_struct_field("non_narrow_chars", 8, |d| Decodable::decode(d))?;
889 let name_hash: u128 =
890 d.read_struct_field("name_hash", 9, |d| Decodable::decode(d))?;
895 // `crate_of_origin` has to be set by the importer.
896 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
897 // That constant is not available here unfortunately :(
898 crate_of_origin: ::std::u32::MAX - 1,
903 external_src: Lock::new(ExternalSource::AbsentOk),
904 lines: Lock::new(lines),
905 multibyte_chars: Lock::new(multibyte_chars),
906 non_narrow_chars: Lock::new(non_narrow_chars),
913 impl fmt::Debug for FileMap {
914 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
915 write!(fmt, "FileMap({})", self.name)
920 pub fn new(name: FileName,
921 name_was_remapped: bool,
922 unmapped_path: FileName,
924 start_pos: BytePos) -> FileMap {
925 remove_bom(&mut src);
928 let mut hasher: StableHasher<u128> = StableHasher::new();
929 hasher.write(src.as_bytes());
933 let mut hasher: StableHasher<u128> = StableHasher::new();
934 name.hash(&mut hasher);
937 let end_pos = start_pos.to_usize() + src.len();
942 unmapped_path: Some(unmapped_path),
944 src: Some(Lrc::new(src)),
946 external_src: Lock::new(ExternalSource::Unneeded),
948 end_pos: Pos::from_usize(end_pos),
949 lines: Lock::new(Vec::new()),
950 multibyte_chars: Lock::new(Vec::new()),
951 non_narrow_chars: Lock::new(Vec::new()),
956 /// EFFECT: register a start-of-line offset in the
957 /// table of line-beginnings.
958 /// UNCHECKED INVARIANT: these offsets must be added in the right
959 /// order and must be in the right places; there is shared knowledge
960 /// about what ends a line between this file and parse.rs
961 /// WARNING: pos param here is the offset relative to start of CodeMap,
962 /// and CodeMap will append a newline when adding a filemap without a newline at the end,
963 /// so the safe way to call this is with value calculated as
964 /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
965 pub fn next_line(&self, pos: BytePos) {
966 // the new charpos must be > the last one (or it's the first one).
967 let mut lines = self.lines.borrow_mut();
968 let line_len = lines.len();
969 assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
973 /// Add externally loaded source.
974 /// If the hash of the input doesn't match or no input is supplied via None,
975 /// it is interpreted as an error and the corresponding enum variant is set.
976 /// The return value signifies whether some kind of source is present.
977 pub fn add_external_src<F>(&self, get_src: F) -> bool
978 where F: FnOnce() -> Option<String>
980 if *self.external_src.borrow() == ExternalSource::AbsentOk {
982 let mut external_src = self.external_src.borrow_mut();
983 // Check that no-one else have provided the source while we were getting it
984 if *external_src == ExternalSource::AbsentOk {
985 if let Some(src) = src {
986 let mut hasher: StableHasher<u128> = StableHasher::new();
987 hasher.write(src.as_bytes());
989 if hasher.finish() == self.src_hash {
990 *external_src = ExternalSource::Present(src);
994 *external_src = ExternalSource::AbsentErr;
999 self.src.is_some() || external_src.get_source().is_some()
1002 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1006 /// Get a line from the list of pre-computed line-beginnings.
1007 /// The line number here is 0-based.
1008 pub fn get_line(&self, line_number: usize) -> Option<Cow<str>> {
1009 fn get_until_newline(src: &str, begin: usize) -> &str {
1010 // We can't use `lines.get(line_number+1)` because we might
1011 // be parsing when we call this function and thus the current
1012 // line is the last one we have line info for.
1013 let slice = &src[begin..];
1014 match slice.find('\n') {
1015 Some(e) => &slice[..e],
1021 let lines = self.lines.borrow();
1022 let line = if let Some(line) = lines.get(line_number) {
1027 let begin: BytePos = *line - self.start_pos;
1031 if let Some(ref src) = self.src {
1032 Some(Cow::from(get_until_newline(src, begin)))
1033 } else if let Some(src) = self.external_src.borrow().get_source() {
1034 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1040 pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
1041 assert!(bytes >=2 && bytes <= 4);
1042 let mbc = MultiByteChar {
1046 self.multibyte_chars.borrow_mut().push(mbc);
1049 pub fn record_width(&self, pos: BytePos, ch: char) {
1050 let width = match ch {
1052 // Tabs will consume 4 columns.
1055 // Make newlines take one column so that displayed spans can point them.
1058 // Assume control characters are zero width.
1059 // FIXME: How can we decide between `width` and `width_cjk`?
1060 unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0),
1062 // Only record non-narrow characters.
1064 self.non_narrow_chars.borrow_mut().push(NonNarrowChar::new(pos, width));
1068 pub fn is_real_file(&self) -> bool {
1072 pub fn is_imported(&self) -> bool {
1076 pub fn byte_length(&self) -> u32 {
1077 self.end_pos.0 - self.start_pos.0
1079 pub fn count_lines(&self) -> usize {
1080 self.lines.borrow().len()
1083 /// Find the line containing the given position. The return value is the
1084 /// index into the `lines` array of this FileMap, not the 1-based line
1085 /// number. If the filemap is empty or the position is located before the
1086 /// first line, None is returned.
1087 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1088 let lines = self.lines.borrow();
1089 if lines.len() == 0 {
1093 let line_index = lookup_line(&lines[..], pos);
1094 assert!(line_index < lines.len() as isize);
1095 if line_index >= 0 {
1096 Some(line_index as usize)
1102 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1103 if self.start_pos == self.end_pos {
1104 return (self.start_pos, self.end_pos);
1107 let lines = self.lines.borrow();
1108 assert!(line_index < lines.len());
1109 if line_index == (lines.len() - 1) {
1110 (lines[line_index], self.end_pos)
1112 (lines[line_index], lines[line_index + 1])
1117 pub fn contains(&self, byte_pos: BytePos) -> bool {
1118 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1122 /// Remove utf-8 BOM if any.
1123 fn remove_bom(src: &mut String) {
1124 if src.starts_with("\u{feff}") {
1129 // _____________________________________________________________________________
1130 // Pos, BytePos, CharPos
1134 fn from_usize(n: usize) -> Self;
1135 fn to_usize(&self) -> usize;
1138 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1140 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1141 pub struct BytePos(pub u32);
1143 /// A character offset. Because of multibyte utf8 characters, a byte offset
1144 /// is not equivalent to a character offset. The CodeMap will convert BytePos
1145 /// values to CharPos values as necessary.
1146 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1147 pub struct CharPos(pub usize);
1149 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
1150 // have been unsuccessful
1152 impl Pos for BytePos {
1153 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1154 fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
1157 impl Add for BytePos {
1158 type Output = BytePos;
1160 fn add(self, rhs: BytePos) -> BytePos {
1161 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1165 impl Sub for BytePos {
1166 type Output = BytePos;
1168 fn sub(self, rhs: BytePos) -> BytePos {
1169 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1173 impl Encodable for BytePos {
1174 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1179 impl Decodable for BytePos {
1180 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1181 Ok(BytePos(d.read_u32()?))
1185 impl Pos for CharPos {
1186 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1187 fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
1190 impl Add for CharPos {
1191 type Output = CharPos;
1193 fn add(self, rhs: CharPos) -> CharPos {
1194 CharPos(self.to_usize() + rhs.to_usize())
1198 impl Sub for CharPos {
1199 type Output = CharPos;
1201 fn sub(self, rhs: CharPos) -> CharPos {
1202 CharPos(self.to_usize() - rhs.to_usize())
1206 // _____________________________________________________________________________
1207 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
1210 /// A source code location used for error reporting
1211 #[derive(Debug, Clone)]
1213 /// Information about the original source
1214 pub file: Lrc<FileMap>,
1215 /// The (1-based) line number
1217 /// The (0-based) column offset
1219 /// The (0-based) column offset when displayed
1220 pub col_display: usize,
1223 /// A source code location used as the result of lookup_char_pos_adj
1224 // Actually, *none* of the clients use the filename *or* file field;
1225 // perhaps they should just be removed.
1227 pub struct LocWithOpt {
1228 pub filename: FileName,
1231 pub file: Option<Lrc<FileMap>>,
1234 // used to be structural records. Better names, anyone?
1236 pub struct FileMapAndLine { pub fm: Lrc<FileMap>, pub line: usize }
1238 pub struct FileMapAndBytePos { pub fm: Lrc<FileMap>, pub pos: BytePos }
1240 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1241 pub struct LineInfo {
1242 /// Index of line, starting from 0.
1243 pub line_index: usize,
1245 /// Column in line where span begins, starting from 0.
1246 pub start_col: CharPos,
1248 /// Column in line where span ends, starting from 0, exclusive.
1249 pub end_col: CharPos,
1252 pub struct FileLines {
1253 pub file: Lrc<FileMap>,
1254 pub lines: Vec<LineInfo>
1257 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
1258 Cell::new(default_span_debug));
1261 pub struct MacroBacktrace {
1262 /// span where macro was applied to generate this code
1263 pub call_site: Span,
1265 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1266 pub macro_decl_name: String,
1268 /// span where macro was defined (if known)
1269 pub def_site_span: Option<Span>,
1272 // _____________________________________________________________________________
1273 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
1276 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1278 #[derive(Clone, PartialEq, Eq, Debug)]
1279 pub enum SpanLinesError {
1280 IllFormedSpan(Span),
1281 DistinctSources(DistinctSources),
1284 #[derive(Clone, PartialEq, Eq, Debug)]
1285 pub enum SpanSnippetError {
1286 IllFormedSpan(Span),
1287 DistinctSources(DistinctSources),
1288 MalformedForCodemap(MalformedCodemapPositions),
1289 SourceNotAvailable { filename: FileName }
1292 #[derive(Clone, PartialEq, Eq, Debug)]
1293 pub struct DistinctSources {
1294 pub begin: (FileName, BytePos),
1295 pub end: (FileName, BytePos)
1298 #[derive(Clone, PartialEq, Eq, Debug)]
1299 pub struct MalformedCodemapPositions {
1301 pub source_len: usize,
1302 pub begin_pos: BytePos,
1303 pub end_pos: BytePos
1306 // Given a slice of line start positions and a position, returns the index of
1307 // the line the position is on. Returns -1 if the position is located before
1309 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1310 match lines.binary_search(&pos) {
1311 Ok(line) => line as isize,
1312 Err(line) => line as isize - 1
1318 use super::{lookup_line, BytePos};
1321 fn test_lookup_line() {
1323 let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1325 assert_eq!(lookup_line(lines, BytePos(0)), -1);
1326 assert_eq!(lookup_line(lines, BytePos(3)), 0);
1327 assert_eq!(lookup_line(lines, BytePos(4)), 0);
1329 assert_eq!(lookup_line(lines, BytePos(16)), 0);
1330 assert_eq!(lookup_line(lines, BytePos(17)), 1);
1331 assert_eq!(lookup_line(lines, BytePos(18)), 1);
1333 assert_eq!(lookup_line(lines, BytePos(28)), 2);
1334 assert_eq!(lookup_line(lines, BytePos(29)), 2);