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(non_exhaustive)]
24 #![feature(optin_builtin_traits)]
25 #![allow(unused_attributes)]
26 #![feature(specialization)]
31 use std::cmp::{self, Ordering};
33 use std::hash::{Hasher, Hash};
34 use std::ops::{Add, Sub};
35 use std::path::PathBuf;
37 use rustc_data_structures::stable_hasher::StableHasher;
38 use rustc_data_structures::sync::{Lrc, Lock};
41 extern crate rustc_data_structures;
44 extern crate scoped_tls;
46 use serialize::{Encodable, Decodable, Encoder, Decoder};
48 extern crate serialize;
49 extern crate serialize as rustc_serialize; // used by deriving
54 extern crate unicode_width;
58 pub use hygiene::{Mark, SyntaxContext, ExpnInfo, ExpnFormat, CompilerDesugaringKind};
61 pub use span_encoding::{Span, DUMMY_SP};
68 symbol_interner: Lock<symbol::Interner>,
69 span_interner: Lock<span_encoding::SpanInterner>,
70 hygiene_data: Lock<hygiene::HygieneData>,
74 pub fn new() -> Globals {
76 symbol_interner: Lock::new(symbol::Interner::fresh()),
77 span_interner: Lock::new(span_encoding::SpanInterner::default()),
78 hygiene_data: Lock::new(hygiene::HygieneData::new()),
83 scoped_thread_local!(pub static GLOBALS: Globals);
85 /// Differentiates between real files and common virtual files
86 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
95 /// Hack in src/libsyntax/parse.rs
99 /// Strings provided as --cfg [cfgspec] stored in a crate_cfg
101 /// Custom sources for explicit parser calls from plugins and drivers
105 impl std::fmt::Display for FileName {
106 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
107 use self::FileName::*;
109 Real(ref path) => write!(fmt, "{}", path.display()),
110 Macros(ref name) => write!(fmt, "<{} macros>", name),
111 QuoteExpansion => write!(fmt, "<quote expansion>"),
112 MacroExpansion => write!(fmt, "<macro expansion>"),
113 Anon => write!(fmt, "<anon>"),
114 ProcMacroSourceCode => write!(fmt, "<proc-macro source code>"),
115 CfgSpec => write!(fmt, "cfgspec"),
116 Custom(ref s) => write!(fmt, "<{}>", s),
121 impl From<PathBuf> for FileName {
122 fn from(p: PathBuf) -> Self {
123 assert!(!p.to_string_lossy().ends_with('>'));
129 pub fn is_real(&self) -> bool {
130 use self::FileName::*;
136 ProcMacroSourceCode |
139 QuoteExpansion => false,
143 pub fn is_macros(&self) -> bool {
144 use self::FileName::*;
149 ProcMacroSourceCode |
152 QuoteExpansion => false,
158 /// Spans represent a region of code, used for error reporting. Positions in spans
159 /// are *absolute* positions from the beginning of the codemap, not positions
160 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
161 /// to the original source.
162 /// You must be careful if the span crosses more than one file - you will not be
163 /// able to use many of the functions on spans in codemap and you cannot assume
164 /// that the length of the span = hi - lo; there may be space in the BytePos
165 /// range between files.
167 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
168 /// sent to other threads, but some pieces of performance infra run in a separate thread.
169 /// Using `Span` is generally preferred.
170 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
171 pub struct SpanData {
174 /// Information about where the macro came from, if this piece of
175 /// code was created by a macro expansion.
176 pub ctxt: SyntaxContext,
181 pub fn with_lo(&self, lo: BytePos) -> Span {
182 Span::new(lo, self.hi, self.ctxt)
185 pub fn with_hi(&self, hi: BytePos) -> Span {
186 Span::new(self.lo, hi, self.ctxt)
189 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
190 Span::new(self.lo, self.hi, ctxt)
194 // The interner is pointed to by a thread local value which is only set on the main thread
195 // with parallelization is disabled. So we don't allow Span to transfer between threads
196 // to avoid panics and other errors, even though it would be memory safe to do so.
197 #[cfg(not(parallel_queries))]
198 impl !Send for Span {}
199 #[cfg(not(parallel_queries))]
200 impl !Sync for Span {}
202 impl PartialOrd for Span {
203 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
204 PartialOrd::partial_cmp(&self.data(), &rhs.data())
208 fn cmp(&self, rhs: &Self) -> Ordering {
209 Ord::cmp(&self.data(), &rhs.data())
213 /// A collection of spans. Spans have two orthogonal attributes:
215 /// - they can be *primary spans*. In this case they are the locus of
216 /// the error, and would be rendered with `^^^`.
217 /// - they can have a *label*. In this case, the label is written next
218 /// to the mark in the snippet when we render.
219 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
220 pub struct MultiSpan {
221 primary_spans: Vec<Span>,
222 span_labels: Vec<(Span, String)>,
227 pub fn lo(self) -> BytePos {
231 pub fn with_lo(self, lo: BytePos) -> Span {
232 self.data().with_lo(lo)
235 pub fn hi(self) -> BytePos {
239 pub fn with_hi(self, hi: BytePos) -> Span {
240 self.data().with_hi(hi)
243 pub fn ctxt(self) -> SyntaxContext {
247 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
248 self.data().with_ctxt(ctxt)
251 /// Returns a new span representing an empty span at the beginning of this span
253 pub fn shrink_to_lo(self) -> Span {
254 let span = self.data();
255 span.with_hi(span.lo)
257 /// Returns a new span representing an empty span at the end of this span
259 pub fn shrink_to_hi(self) -> Span {
260 let span = self.data();
261 span.with_lo(span.hi)
264 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
265 pub fn substitute_dummy(self, other: Span) -> Span {
266 if self.source_equal(&DUMMY_SP) { other } else { self }
269 /// Return true if `self` fully encloses `other`.
270 pub fn contains(self, other: Span) -> bool {
271 let span = self.data();
272 let other = other.data();
273 span.lo <= other.lo && other.hi <= span.hi
276 /// Return true if the spans are equal with regards to the source text.
278 /// Use this instead of `==` when either span could be generated code,
279 /// and you only care that they point to the same bytes of source text.
280 pub fn source_equal(&self, other: &Span) -> bool {
281 let span = self.data();
282 let other = other.data();
283 span.lo == other.lo && span.hi == other.hi
286 /// Returns `Some(span)`, where the start is trimmed by the end of `other`
287 pub fn trim_start(self, other: Span) -> Option<Span> {
288 let span = self.data();
289 let other = other.data();
290 if span.hi > other.hi {
291 Some(span.with_lo(cmp::max(span.lo, other.hi)))
297 /// Return the source span - this is either the supplied span, or the span for
298 /// the macro callsite that expanded to it.
299 pub fn source_callsite(self) -> Span {
300 self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
303 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
305 pub fn parent(self) -> Option<Span> {
306 self.ctxt().outer().expn_info().map(|i| i.call_site)
309 /// Edition of the crate from which this span came.
310 pub fn edition(self) -> edition::Edition {
311 self.ctxt().outer().expn_info().map_or_else(|| hygiene::default_edition(),
312 |einfo| einfo.edition)
315 /// Return the source callee.
317 /// Returns `None` if the supplied span has no expansion trace,
318 /// else returns the `ExpnInfo` for the macro definition
319 /// corresponding to the source callsite.
320 pub fn source_callee(self) -> Option<ExpnInfo> {
321 fn source_callee(info: ExpnInfo) -> ExpnInfo {
322 match info.call_site.ctxt().outer().expn_info() {
323 Some(info) => source_callee(info),
327 self.ctxt().outer().expn_info().map(source_callee)
330 /// Check if a span is "internal" to a macro in which #[unstable]
331 /// items can be used (that is, a macro marked with
332 /// `#[allow_internal_unstable]`).
333 pub fn allows_unstable(&self) -> bool {
334 match self.ctxt().outer().expn_info() {
335 Some(info) => info.allow_internal_unstable,
340 /// Check if this span arises from a compiler desugaring of kind `kind`.
341 pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
342 match self.ctxt().outer().expn_info() {
343 Some(info) => match info.format {
344 ExpnFormat::CompilerDesugaring(k) => k == kind,
351 /// Return the compiler desugaring that created this span, or None
352 /// if this span is not from a desugaring.
353 pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
354 match self.ctxt().outer().expn_info() {
355 Some(info) => match info.format {
356 ExpnFormat::CompilerDesugaring(k) => Some(k),
363 /// Check if a span is "internal" to a macro in which `unsafe`
364 /// can be used without triggering the `unsafe_code` lint
365 // (that is, a macro marked with `#[allow_internal_unsafe]`).
366 pub fn allows_unsafe(&self) -> bool {
367 match self.ctxt().outer().expn_info() {
368 Some(info) => info.allow_internal_unsafe,
373 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
374 let mut prev_span = DUMMY_SP;
375 let mut result = vec![];
376 while let Some(info) = self.ctxt().outer().expn_info() {
377 // Don't print recursive invocations
378 if !info.call_site.source_equal(&prev_span) {
379 let (pre, post) = match info.format {
380 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
381 ExpnFormat::MacroBang(..) => ("", "!"),
382 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
384 result.push(MacroBacktrace {
385 call_site: info.call_site,
386 macro_decl_name: format!("{}{}{}", pre, info.format.name(), post),
387 def_site_span: info.def_site,
392 self = info.call_site;
397 /// Return a `Span` that would enclose both `self` and `end`.
398 pub fn to(self, end: Span) -> Span {
399 let span_data = self.data();
400 let end_data = end.data();
401 // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480)
402 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
403 // have an incomplete span than a completely nonsensical one.
404 if span_data.ctxt != end_data.ctxt {
405 if span_data.ctxt == SyntaxContext::empty() {
407 } else if end_data.ctxt == SyntaxContext::empty() {
410 // both span fall within a macro
411 // FIXME(estebank) check if it is the *same* macro
414 cmp::min(span_data.lo, end_data.lo),
415 cmp::max(span_data.hi, end_data.hi),
416 if span_data.ctxt == SyntaxContext::empty() { end_data.ctxt } else { span_data.ctxt },
420 /// Return a `Span` between the end of `self` to the beginning of `end`.
421 pub fn between(self, end: Span) -> Span {
422 let span = self.data();
423 let end = end.data();
427 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
431 /// Return a `Span` between the beginning of `self` to the beginning of `end`.
432 pub fn until(self, end: Span) -> Span {
433 let span = self.data();
434 let end = end.data();
438 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
442 pub fn from_inner_byte_pos(self, start: usize, end: usize) -> Span {
443 let span = self.data();
444 Span::new(span.lo + BytePos::from_usize(start),
445 span.lo + BytePos::from_usize(end),
450 pub fn apply_mark(self, mark: Mark) -> Span {
451 let span = self.data();
452 span.with_ctxt(span.ctxt.apply_mark(mark))
456 pub fn remove_mark(&mut self) -> Mark {
457 let mut span = self.data();
458 let mark = span.ctxt.remove_mark();
459 *self = Span::new(span.lo, span.hi, span.ctxt);
464 pub fn adjust(&mut self, expansion: Mark) -> Option<Mark> {
465 let mut span = self.data();
466 let mark = span.ctxt.adjust(expansion);
467 *self = Span::new(span.lo, span.hi, span.ctxt);
472 pub fn glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
473 -> Option<Option<Mark>> {
474 let mut span = self.data();
475 let mark = span.ctxt.glob_adjust(expansion, glob_ctxt);
476 *self = Span::new(span.lo, span.hi, span.ctxt);
481 pub fn reverse_glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
482 -> Option<Option<Mark>> {
483 let mut span = self.data();
484 let mark = span.ctxt.reverse_glob_adjust(expansion, glob_ctxt);
485 *self = Span::new(span.lo, span.hi, span.ctxt);
490 pub fn modern(self) -> Span {
491 let span = self.data();
492 span.with_ctxt(span.ctxt.modern())
496 #[derive(Clone, Debug)]
497 pub struct SpanLabel {
498 /// The span we are going to include in the final snippet.
501 /// Is this a primary span? This is the "locus" of the message,
502 /// and is indicated with a `^^^^` underline, versus `----`.
503 pub is_primary: bool,
505 /// What label should we attach to this span (if any)?
506 pub label: Option<String>,
509 impl Default for Span {
510 fn default() -> Self {
515 impl serialize::UseSpecializedEncodable for Span {
516 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
517 let span = self.data();
518 s.emit_struct("Span", 2, |s| {
519 s.emit_struct_field("lo", 0, |s| {
523 s.emit_struct_field("hi", 1, |s| {
530 impl serialize::UseSpecializedDecodable for Span {
531 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
532 d.read_struct("Span", 2, |d| {
533 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
534 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
535 Ok(Span::new(lo, hi, NO_EXPANSION))
540 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
541 f.debug_struct("Span")
542 .field("lo", &span.lo())
543 .field("hi", &span.hi())
544 .field("ctxt", &span.ctxt())
548 impl fmt::Debug for Span {
549 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
550 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
554 impl fmt::Debug for SpanData {
555 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
556 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
561 pub fn new() -> MultiSpan {
563 primary_spans: vec![],
568 pub fn from_span(primary_span: Span) -> MultiSpan {
570 primary_spans: vec![primary_span],
575 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
582 pub fn push_span_label(&mut self, span: Span, label: String) {
583 self.span_labels.push((span, label));
586 /// Selects the first primary span (if any)
587 pub fn primary_span(&self) -> Option<Span> {
588 self.primary_spans.first().cloned()
591 /// Returns all primary spans.
592 pub fn primary_spans(&self) -> &[Span] {
596 /// Replaces all occurrences of one Span with another. Used to move Spans in areas that don't
597 /// display well (like std macros). Returns true if replacements occurred.
598 pub fn replace(&mut self, before: Span, after: Span) -> bool {
599 let mut replacements_occurred = false;
600 for primary_span in &mut self.primary_spans {
601 if *primary_span == before {
602 *primary_span = after;
603 replacements_occurred = true;
606 for span_label in &mut self.span_labels {
607 if span_label.0 == before {
608 span_label.0 = after;
609 replacements_occurred = true;
612 replacements_occurred
615 /// Returns the strings to highlight. We always ensure that there
616 /// is an entry for each of the primary spans -- for each primary
617 /// span P, if there is at least one label with span P, we return
618 /// those labels (marked as primary). But otherwise we return
619 /// `SpanLabel` instances with empty labels.
620 pub fn span_labels(&self) -> Vec<SpanLabel> {
621 let is_primary = |span| self.primary_spans.contains(&span);
622 let mut span_labels = vec![];
624 for &(span, ref label) in &self.span_labels {
625 span_labels.push(SpanLabel {
627 is_primary: is_primary(span),
628 label: Some(label.clone())
632 for &span in &self.primary_spans {
633 if !span_labels.iter().any(|sl| sl.span == span) {
634 span_labels.push(SpanLabel {
646 impl From<Span> for MultiSpan {
647 fn from(span: Span) -> MultiSpan {
648 MultiSpan::from_span(span)
652 impl From<Vec<Span>> for MultiSpan {
653 fn from(spans: Vec<Span>) -> MultiSpan {
654 MultiSpan::from_spans(spans)
658 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
660 /// Identifies an offset of a multi-byte character in a FileMap
661 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
662 pub struct MultiByteChar {
663 /// The absolute offset of the character in the CodeMap
665 /// The number of bytes, >=2
669 /// Identifies an offset of a non-narrow character in a FileMap
670 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
671 pub enum NonNarrowChar {
672 /// Represents a zero-width character
674 /// Represents a wide (fullwidth) character
676 /// Represents a tab character, represented visually with a width of 4 characters
681 fn new(pos: BytePos, width: usize) -> Self {
683 0 => NonNarrowChar::ZeroWidth(pos),
684 2 => NonNarrowChar::Wide(pos),
685 4 => NonNarrowChar::Tab(pos),
686 _ => panic!("width {} given for non-narrow character", width),
690 /// Returns the absolute offset of the character in the CodeMap
691 pub fn pos(&self) -> BytePos {
693 NonNarrowChar::ZeroWidth(p) |
694 NonNarrowChar::Wide(p) |
695 NonNarrowChar::Tab(p) => p,
699 /// Returns the width of the character, 0 (zero-width) or 2 (wide)
700 pub fn width(&self) -> usize {
702 NonNarrowChar::ZeroWidth(_) => 0,
703 NonNarrowChar::Wide(_) => 2,
704 NonNarrowChar::Tab(_) => 4,
709 impl Add<BytePos> for NonNarrowChar {
712 fn add(self, rhs: BytePos) -> Self {
714 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
715 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
716 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
721 impl Sub<BytePos> for NonNarrowChar {
724 fn sub(self, rhs: BytePos) -> Self {
726 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
727 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
728 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
733 /// The state of the lazy external source loading mechanism of a FileMap.
734 #[derive(PartialEq, Eq, Clone)]
735 pub enum ExternalSource {
736 /// The external source has been loaded already.
738 /// No attempt has been made to load the external source.
740 /// A failed attempt has been made to load the external source.
742 /// No external source has to be loaded, since the FileMap represents a local crate.
746 impl ExternalSource {
747 pub fn is_absent(&self) -> bool {
749 ExternalSource::Present(_) => false,
754 pub fn get_source(&self) -> Option<&str> {
756 ExternalSource::Present(ref src) => Some(src),
762 /// A single source in the CodeMap.
765 /// The name of the file that the source came from, source that doesn't
766 /// originate from files has names between angle brackets by convention,
769 /// True if the `name` field above has been modified by --remap-path-prefix
770 pub name_was_remapped: bool,
771 /// The unmapped path of the file that the source came from.
772 /// Set to `None` if the FileMap was imported from an external crate.
773 pub unmapped_path: Option<FileName>,
774 /// Indicates which crate this FileMap was imported from.
775 pub crate_of_origin: u32,
776 /// The complete source code
777 pub src: Option<Lrc<String>>,
778 /// The source code's hash
780 /// The external source code (used for external crates, which will have a `None`
781 /// value as `self.src`.
782 pub external_src: Lock<ExternalSource>,
783 /// The start position of this source in the CodeMap
784 pub start_pos: BytePos,
785 /// The end position of this source in the CodeMap
786 pub end_pos: BytePos,
787 /// Locations of lines beginnings in the source code
788 pub lines: Vec<BytePos>,
789 /// Locations of multi-byte characters in the source code
790 pub multibyte_chars: Vec<MultiByteChar>,
791 /// Width of characters that are not narrow in the source code
792 pub non_narrow_chars: Vec<NonNarrowChar>,
793 /// A hash of the filename, used for speeding up the incr. comp. hashing.
797 impl Encodable for FileMap {
798 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
799 s.emit_struct("FileMap", 8, |s| {
800 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
801 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
802 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
803 s.emit_struct_field("start_pos", 4, |s| self.start_pos.encode(s))?;
804 s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
805 s.emit_struct_field("lines", 6, |s| {
806 let lines = &self.lines[..];
808 s.emit_u32(lines.len() as u32)?;
810 if !lines.is_empty() {
811 // In order to preserve some space, we exploit the fact that
812 // the lines list is sorted and individual lines are
813 // probably not that long. Because of that we can store lines
814 // as a difference list, using as little space as possible
815 // for the differences.
816 let max_line_length = if lines.len() == 1 {
820 .map(|w| w[1] - w[0])
821 .map(|bp| bp.to_usize())
826 let bytes_per_diff: u8 = match max_line_length {
828 0x100 ..= 0xFFFF => 2,
832 // Encode the number of bytes used per diff.
833 bytes_per_diff.encode(s)?;
835 // Encode the first element.
838 let diff_iter = (&lines[..]).windows(2)
839 .map(|w| (w[1] - w[0]));
841 match bytes_per_diff {
842 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
843 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
844 4 => for diff in diff_iter { diff.0.encode(s)? },
851 s.emit_struct_field("multibyte_chars", 7, |s| {
852 self.multibyte_chars.encode(s)
854 s.emit_struct_field("non_narrow_chars", 8, |s| {
855 self.non_narrow_chars.encode(s)
857 s.emit_struct_field("name_hash", 9, |s| {
858 self.name_hash.encode(s)
864 impl Decodable for FileMap {
865 fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
867 d.read_struct("FileMap", 8, |d| {
868 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
869 let name_was_remapped: bool =
870 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
872 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
873 let start_pos: BytePos =
874 d.read_struct_field("start_pos", 4, |d| Decodable::decode(d))?;
875 let end_pos: BytePos = d.read_struct_field("end_pos", 5, |d| Decodable::decode(d))?;
876 let lines: Vec<BytePos> = d.read_struct_field("lines", 6, |d| {
877 let num_lines: u32 = Decodable::decode(d)?;
878 let mut lines = Vec::with_capacity(num_lines as usize);
881 // Read the number of bytes used per diff.
882 let bytes_per_diff: u8 = Decodable::decode(d)?;
884 // Read the first element.
885 let mut line_start: BytePos = Decodable::decode(d)?;
886 lines.push(line_start);
888 for _ in 1..num_lines {
889 let diff = match bytes_per_diff {
890 1 => d.read_u8()? as u32,
891 2 => d.read_u16()? as u32,
896 line_start = line_start + BytePos(diff);
898 lines.push(line_start);
904 let multibyte_chars: Vec<MultiByteChar> =
905 d.read_struct_field("multibyte_chars", 7, |d| Decodable::decode(d))?;
906 let non_narrow_chars: Vec<NonNarrowChar> =
907 d.read_struct_field("non_narrow_chars", 8, |d| Decodable::decode(d))?;
908 let name_hash: u128 =
909 d.read_struct_field("name_hash", 9, |d| Decodable::decode(d))?;
914 // `crate_of_origin` has to be set by the importer.
915 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
916 // That constant is not available here unfortunately :(
917 crate_of_origin: ::std::u32::MAX - 1,
922 external_src: Lock::new(ExternalSource::AbsentOk),
932 impl fmt::Debug for FileMap {
933 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
934 write!(fmt, "FileMap({})", self.name)
939 pub fn new(name: FileName,
940 name_was_remapped: bool,
941 unmapped_path: FileName,
943 start_pos: BytePos) -> FileMap {
944 remove_bom(&mut src);
947 let mut hasher: StableHasher<u128> = StableHasher::new();
948 hasher.write(src.as_bytes());
952 let mut hasher: StableHasher<u128> = StableHasher::new();
953 name.hash(&mut hasher);
956 let end_pos = start_pos.to_usize() + src.len();
958 let (lines, multibyte_chars, non_narrow_chars) =
959 analyze_filemap::analyze_filemap(&src[..], start_pos);
964 unmapped_path: Some(unmapped_path),
966 src: Some(Lrc::new(src)),
968 external_src: Lock::new(ExternalSource::Unneeded),
970 end_pos: Pos::from_usize(end_pos),
978 /// Return the BytePos of the beginning of the current line.
979 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
980 let line_index = self.lookup_line(pos).unwrap();
981 self.lines[line_index]
984 /// Add externally loaded source.
985 /// If the hash of the input doesn't match or no input is supplied via None,
986 /// it is interpreted as an error and the corresponding enum variant is set.
987 /// The return value signifies whether some kind of source is present.
988 pub fn add_external_src<F>(&self, get_src: F) -> bool
989 where F: FnOnce() -> Option<String>
991 if *self.external_src.borrow() == ExternalSource::AbsentOk {
993 let mut external_src = self.external_src.borrow_mut();
994 // Check that no-one else have provided the source while we were getting it
995 if *external_src == ExternalSource::AbsentOk {
996 if let Some(src) = src {
997 let mut hasher: StableHasher<u128> = StableHasher::new();
998 hasher.write(src.as_bytes());
1000 if hasher.finish() == self.src_hash {
1001 *external_src = ExternalSource::Present(src);
1005 *external_src = ExternalSource::AbsentErr;
1010 self.src.is_some() || external_src.get_source().is_some()
1013 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1017 /// Get a line from the list of pre-computed line-beginnings.
1018 /// The line number here is 0-based.
1019 pub fn get_line(&self, line_number: usize) -> Option<Cow<str>> {
1020 fn get_until_newline(src: &str, begin: usize) -> &str {
1021 // We can't use `lines.get(line_number+1)` because we might
1022 // be parsing when we call this function and thus the current
1023 // line is the last one we have line info for.
1024 let slice = &src[begin..];
1025 match slice.find('\n') {
1026 Some(e) => &slice[..e],
1032 let line = if let Some(line) = self.lines.get(line_number) {
1037 let begin: BytePos = *line - self.start_pos;
1041 if let Some(ref src) = self.src {
1042 Some(Cow::from(get_until_newline(src, begin)))
1043 } else if let Some(src) = self.external_src.borrow().get_source() {
1044 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1050 pub fn is_real_file(&self) -> bool {
1054 pub fn is_imported(&self) -> bool {
1058 pub fn byte_length(&self) -> u32 {
1059 self.end_pos.0 - self.start_pos.0
1061 pub fn count_lines(&self) -> usize {
1065 /// Find the line containing the given position. The return value is the
1066 /// index into the `lines` array of this FileMap, not the 1-based line
1067 /// number. If the filemap is empty or the position is located before the
1068 /// first line, None is returned.
1069 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1070 if self.lines.len() == 0 {
1074 let line_index = lookup_line(&self.lines[..], pos);
1075 assert!(line_index < self.lines.len() as isize);
1076 if line_index >= 0 {
1077 Some(line_index as usize)
1083 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1084 if self.start_pos == self.end_pos {
1085 return (self.start_pos, self.end_pos);
1088 assert!(line_index < self.lines.len());
1089 if line_index == (self.lines.len() - 1) {
1090 (self.lines[line_index], self.end_pos)
1092 (self.lines[line_index], self.lines[line_index + 1])
1097 pub fn contains(&self, byte_pos: BytePos) -> bool {
1098 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1102 /// Remove utf-8 BOM if any.
1103 fn remove_bom(src: &mut String) {
1104 if src.starts_with("\u{feff}") {
1109 // _____________________________________________________________________________
1110 // Pos, BytePos, CharPos
1114 fn from_usize(n: usize) -> Self;
1115 fn to_usize(&self) -> usize;
1116 fn from_u32(n: u32) -> Self;
1117 fn to_u32(&self) -> u32;
1120 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1122 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1123 pub struct BytePos(pub u32);
1125 /// A character offset. Because of multibyte utf8 characters, a byte offset
1126 /// is not equivalent to a character offset. The CodeMap will convert BytePos
1127 /// values to CharPos values as necessary.
1128 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1129 pub struct CharPos(pub usize);
1131 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
1132 // have been unsuccessful
1134 impl Pos for BytePos {
1136 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1139 fn to_usize(&self) -> usize { self.0 as usize }
1142 fn from_u32(n: u32) -> BytePos { BytePos(n) }
1145 fn to_u32(&self) -> u32 { self.0 }
1148 impl Add for BytePos {
1149 type Output = BytePos;
1152 fn add(self, rhs: BytePos) -> BytePos {
1153 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1157 impl Sub for BytePos {
1158 type Output = BytePos;
1161 fn sub(self, rhs: BytePos) -> BytePos {
1162 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1166 impl Encodable for BytePos {
1167 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1172 impl Decodable for BytePos {
1173 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1174 Ok(BytePos(d.read_u32()?))
1178 impl Pos for CharPos {
1180 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1183 fn to_usize(&self) -> usize { self.0 }
1186 fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1189 fn to_u32(&self) -> u32 { self.0 as u32}
1192 impl Add for CharPos {
1193 type Output = CharPos;
1196 fn add(self, rhs: CharPos) -> CharPos {
1197 CharPos(self.to_usize() + rhs.to_usize())
1201 impl Sub for CharPos {
1202 type Output = CharPos;
1205 fn sub(self, rhs: CharPos) -> CharPos {
1206 CharPos(self.to_usize() - rhs.to_usize())
1210 // _____________________________________________________________________________
1211 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
1214 /// A source code location used for error reporting
1215 #[derive(Debug, Clone)]
1217 /// Information about the original source
1218 pub file: Lrc<FileMap>,
1219 /// The (1-based) line number
1221 /// The (0-based) column offset
1223 /// The (0-based) column offset when displayed
1224 pub col_display: usize,
1227 /// A source code location used as the result of lookup_char_pos_adj
1228 // Actually, *none* of the clients use the filename *or* file field;
1229 // perhaps they should just be removed.
1231 pub struct LocWithOpt {
1232 pub filename: FileName,
1235 pub file: Option<Lrc<FileMap>>,
1238 // used to be structural records. Better names, anyone?
1240 pub struct FileMapAndLine { pub fm: Lrc<FileMap>, pub line: usize }
1242 pub struct FileMapAndBytePos { pub fm: Lrc<FileMap>, pub pos: BytePos }
1244 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1245 pub struct LineInfo {
1246 /// Index of line, starting from 0.
1247 pub line_index: usize,
1249 /// Column in line where span begins, starting from 0.
1250 pub start_col: CharPos,
1252 /// Column in line where span ends, starting from 0, exclusive.
1253 pub end_col: CharPos,
1256 pub struct FileLines {
1257 pub file: Lrc<FileMap>,
1258 pub lines: Vec<LineInfo>
1261 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
1262 Cell::new(default_span_debug));
1265 pub struct MacroBacktrace {
1266 /// span where macro was applied to generate this code
1267 pub call_site: Span,
1269 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1270 pub macro_decl_name: String,
1272 /// span where macro was defined (if known)
1273 pub def_site_span: Option<Span>,
1276 // _____________________________________________________________________________
1277 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
1280 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1282 #[derive(Clone, PartialEq, Eq, Debug)]
1283 pub enum SpanLinesError {
1284 IllFormedSpan(Span),
1285 DistinctSources(DistinctSources),
1288 #[derive(Clone, PartialEq, Eq, Debug)]
1289 pub enum SpanSnippetError {
1290 IllFormedSpan(Span),
1291 DistinctSources(DistinctSources),
1292 MalformedForCodemap(MalformedCodemapPositions),
1293 SourceNotAvailable { filename: FileName }
1296 #[derive(Clone, PartialEq, Eq, Debug)]
1297 pub struct DistinctSources {
1298 pub begin: (FileName, BytePos),
1299 pub end: (FileName, BytePos)
1302 #[derive(Clone, PartialEq, Eq, Debug)]
1303 pub struct MalformedCodemapPositions {
1305 pub source_len: usize,
1306 pub begin_pos: BytePos,
1307 pub end_pos: BytePos
1310 // Given a slice of line start positions and a position, returns the index of
1311 // the line the position is on. Returns -1 if the position is located before
1313 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1314 match lines.binary_search(&pos) {
1315 Ok(line) => line as isize,
1316 Err(line) => line as isize - 1
1322 use super::{lookup_line, BytePos};
1325 fn test_lookup_line() {
1327 let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1329 assert_eq!(lookup_line(lines, BytePos(0)), -1);
1330 assert_eq!(lookup_line(lines, BytePos(3)), 0);
1331 assert_eq!(lookup_line(lines, BytePos(4)), 0);
1333 assert_eq!(lookup_line(lines, BytePos(16)), 0);
1334 assert_eq!(lookup_line(lines, BytePos(17)), 1);
1335 assert_eq!(lookup_line(lines, BytePos(18)), 1);
1337 assert_eq!(lookup_line(lines, BytePos(28)), 2);
1338 assert_eq!(lookup_line(lines, BytePos(29)), 2);