1 //! The source positions and related helper functions.
5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
9 #![deny(rust_2018_idioms)]
10 #![cfg_attr(not(stage0), deny(internal))]
13 #![feature(crate_visibility_modifier)]
14 #![feature(custom_attribute)]
16 #![feature(non_exhaustive)]
17 #![feature(optin_builtin_traits)]
18 #![feature(rustc_attrs)]
19 #![feature(proc_macro_hygiene)]
20 #![feature(specialization)]
21 #![feature(step_trait)]
23 use serialize::{Encodable, Decodable, Encoder, Decoder};
25 #[allow(unused_extern_crates)]
26 extern crate serialize as rustc_serialize; // used by deriving
30 pub use hygiene::{Mark, SyntaxContext, ExpnInfo, ExpnFormat, CompilerDesugaringKind};
33 pub use span_encoding::{Span, DUMMY_SP};
36 pub use symbol::symbols;
38 mod analyze_source_file;
40 use rustc_data_structures::stable_hasher::StableHasher;
41 use rustc_data_structures::sync::{Lrc, Lock};
45 use std::cmp::{self, Ordering};
47 use std::hash::{Hasher, Hash};
48 use std::ops::{Add, Sub};
49 use std::path::PathBuf;
52 symbol_interner: Lock<symbol::Interner>,
53 span_interner: Lock<span_encoding::SpanInterner>,
54 hygiene_data: Lock<hygiene::HygieneData>,
58 pub fn new() -> Globals {
60 symbol_interner: Lock::new(symbol::Interner::fresh()),
61 span_interner: Lock::new(span_encoding::SpanInterner::default()),
62 hygiene_data: Lock::new(hygiene::HygieneData::new()),
67 scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
69 /// Differentiates between real files and common virtual files.
70 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
73 /// A macro. This includes the full name of the macro, so that there are no clashes.
79 /// Hack in `src/libsyntax/parse.rs`.
82 ProcMacroSourceCode(u64),
83 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
85 /// Strings provided as crate attributes in the CLI.
87 /// Custom sources for explicit parser calls from plugins and drivers.
89 DocTest(PathBuf, isize),
92 impl std::fmt::Display for FileName {
93 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 Real(ref path) => write!(fmt, "{}", path.display()),
97 Macros(ref name) => write!(fmt, "<{} macros>", name),
98 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
99 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
100 Anon(_) => write!(fmt, "<anon>"),
101 ProcMacroSourceCode(_) =>
102 write!(fmt, "<proc-macro source code>"),
103 CfgSpec(_) => write!(fmt, "<cfgspec>"),
104 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
105 Custom(ref s) => write!(fmt, "<{}>", s),
106 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
111 impl From<PathBuf> for FileName {
112 fn from(p: PathBuf) -> Self {
113 assert!(!p.to_string_lossy().ends_with('>'));
119 pub fn is_real(&self) -> bool {
126 ProcMacroSourceCode(_) |
131 DocTest(_, _) => false,
135 pub fn is_macros(&self) -> bool {
141 ProcMacroSourceCode(_) |
146 DocTest(_, _) => false,
151 pub fn quote_expansion_source_code(src: &str) -> FileName {
152 let mut hasher = StableHasher::new();
153 src.hash(&mut hasher);
154 FileName::QuoteExpansion(hasher.finish())
157 pub fn macro_expansion_source_code(src: &str) -> FileName {
158 let mut hasher = StableHasher::new();
159 src.hash(&mut hasher);
160 FileName::MacroExpansion(hasher.finish())
163 pub fn anon_source_code(src: &str) -> FileName {
164 let mut hasher = StableHasher::new();
165 src.hash(&mut hasher);
166 FileName::Anon(hasher.finish())
169 pub fn proc_macro_source_code(src: &str) -> FileName {
170 let mut hasher = StableHasher::new();
171 src.hash(&mut hasher);
172 FileName::ProcMacroSourceCode(hasher.finish())
175 pub fn cfg_spec_source_code(src: &str) -> FileName {
176 let mut hasher = StableHasher::new();
177 src.hash(&mut hasher);
178 FileName::QuoteExpansion(hasher.finish())
181 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
182 let mut hasher = StableHasher::new();
183 src.hash(&mut hasher);
184 FileName::CliCrateAttr(hasher.finish())
187 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{
188 FileName::DocTest(path, line)
192 /// Spans represent a region of code, used for error reporting. Positions in spans
193 /// are *absolute* positions from the beginning of the source_map, not positions
194 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
195 /// to the original source.
196 /// You must be careful if the span crosses more than one file - you will not be
197 /// able to use many of the functions on spans in source_map and you cannot assume
198 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
199 /// range between files.
201 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
202 /// sent to other threads, but some pieces of performance infra run in a separate thread.
203 /// Using `Span` is generally preferred.
204 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
205 pub struct SpanData {
208 /// Information about where the macro came from, if this piece of
209 /// code was created by a macro expansion.
210 pub ctxt: SyntaxContext,
215 pub fn with_lo(&self, lo: BytePos) -> Span {
216 Span::new(lo, self.hi, self.ctxt)
219 pub fn with_hi(&self, hi: BytePos) -> Span {
220 Span::new(self.lo, hi, self.ctxt)
223 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
224 Span::new(self.lo, self.hi, ctxt)
228 // The interner is pointed to by a thread local value which is only set on the main thread
229 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
230 // to avoid panics and other errors, even though it would be memory safe to do so.
231 #[cfg(not(parallel_compiler))]
232 impl !Send for Span {}
233 #[cfg(not(parallel_compiler))]
234 impl !Sync for Span {}
236 impl PartialOrd for Span {
237 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
238 PartialOrd::partial_cmp(&self.data(), &rhs.data())
242 fn cmp(&self, rhs: &Self) -> Ordering {
243 Ord::cmp(&self.data(), &rhs.data())
247 /// A collection of spans. Spans have two orthogonal attributes:
249 /// - They can be *primary spans*. In this case they are the locus of
250 /// the error, and would be rendered with `^^^`.
251 /// - They can have a *label*. In this case, the label is written next
252 /// to the mark in the snippet when we render.
253 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
254 pub struct MultiSpan {
255 primary_spans: Vec<Span>,
256 span_labels: Vec<(Span, String)>,
261 pub fn lo(self) -> BytePos {
265 pub fn with_lo(self, lo: BytePos) -> Span {
266 self.data().with_lo(lo)
269 pub fn hi(self) -> BytePos {
273 pub fn with_hi(self, hi: BytePos) -> Span {
274 self.data().with_hi(hi)
277 pub fn ctxt(self) -> SyntaxContext {
281 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
282 self.data().with_ctxt(ctxt)
285 /// Returns `true` if this is a dummy span with any hygienic context.
287 pub fn is_dummy(self) -> bool {
288 let span = self.data();
289 span.lo.0 == 0 && span.hi.0 == 0
292 /// Returns a new span representing an empty span at the beginning of this span
294 pub fn shrink_to_lo(self) -> Span {
295 let span = self.data();
296 span.with_hi(span.lo)
298 /// Returns a new span representing an empty span at the end of this span.
300 pub fn shrink_to_hi(self) -> Span {
301 let span = self.data();
302 span.with_lo(span.hi)
305 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
306 pub fn substitute_dummy(self, other: Span) -> Span {
307 if self.is_dummy() { other } else { self }
310 /// Returns `true` if `self` fully encloses `other`.
311 pub fn contains(self, other: Span) -> bool {
312 let span = self.data();
313 let other = other.data();
314 span.lo <= other.lo && other.hi <= span.hi
317 /// Returns `true` if `self` touches `other`.
318 pub fn overlaps(self, other: Span) -> bool {
319 let span = self.data();
320 let other = other.data();
321 span.lo < other.hi && other.lo < span.hi
324 /// Returns `true` if the spans are equal with regards to the source text.
326 /// Use this instead of `==` when either span could be generated code,
327 /// and you only care that they point to the same bytes of source text.
328 pub fn source_equal(&self, other: &Span) -> bool {
329 let span = self.data();
330 let other = other.data();
331 span.lo == other.lo && span.hi == other.hi
334 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
335 pub fn trim_start(self, other: Span) -> Option<Span> {
336 let span = self.data();
337 let other = other.data();
338 if span.hi > other.hi {
339 Some(span.with_lo(cmp::max(span.lo, other.hi)))
345 /// Returns the source span -- this is either the supplied span, or the span for
346 /// the macro callsite that expanded to it.
347 pub fn source_callsite(self) -> Span {
348 self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
351 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
353 pub fn parent(self) -> Option<Span> {
354 self.ctxt().outer().expn_info().map(|i| i.call_site)
357 /// Edition of the crate from which this span came.
358 pub fn edition(self) -> edition::Edition {
359 self.ctxt().outer().expn_info().map_or_else(|| hygiene::default_edition(),
360 |einfo| einfo.edition)
364 pub fn rust_2015(&self) -> bool {
365 self.edition() == edition::Edition::Edition2015
369 pub fn rust_2018(&self) -> bool {
370 self.edition() >= edition::Edition::Edition2018
373 /// Returns the source callee.
375 /// Returns `None` if the supplied span has no expansion trace,
376 /// else returns the `ExpnInfo` for the macro definition
377 /// corresponding to the source callsite.
378 pub fn source_callee(self) -> Option<ExpnInfo> {
379 fn source_callee(info: ExpnInfo) -> ExpnInfo {
380 match info.call_site.ctxt().outer().expn_info() {
381 Some(info) => source_callee(info),
385 self.ctxt().outer().expn_info().map(source_callee)
388 /// Checks if a span is "internal" to a macro in which `#[unstable]`
389 /// items can be used (that is, a macro marked with
390 /// `#[allow_internal_unstable]`).
391 pub fn allows_unstable(&self, feature: &str) -> bool {
392 match self.ctxt().outer().expn_info() {
394 .allow_internal_unstable
395 .map_or(false, |features| features.iter().any(|&f|
396 f == feature || f == "allow_internal_unstable_backcompat_hack"
402 /// Checks if this span arises from a compiler desugaring of kind `kind`.
403 pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
404 match self.ctxt().outer().expn_info() {
405 Some(info) => match info.format {
406 ExpnFormat::CompilerDesugaring(k) => k == kind,
413 /// Returns the compiler desugaring that created this span, or `None`
414 /// if this span is not from a desugaring.
415 pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
416 match self.ctxt().outer().expn_info() {
417 Some(info) => match info.format {
418 ExpnFormat::CompilerDesugaring(k) => Some(k),
425 /// Checks if a span is "internal" to a macro in which `unsafe`
426 /// can be used without triggering the `unsafe_code` lint
427 // (that is, a macro marked with `#[allow_internal_unsafe]`).
428 pub fn allows_unsafe(&self) -> bool {
429 match self.ctxt().outer().expn_info() {
430 Some(info) => info.allow_internal_unsafe,
435 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
436 let mut prev_span = DUMMY_SP;
437 let mut result = vec![];
438 while let Some(info) = self.ctxt().outer().expn_info() {
439 // Don't print recursive invocations.
440 if !info.call_site.source_equal(&prev_span) {
441 let (pre, post) = match info.format {
442 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
443 ExpnFormat::MacroBang(..) => ("", "!"),
444 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
446 result.push(MacroBacktrace {
447 call_site: info.call_site,
448 macro_decl_name: format!("{}{}{}", pre, info.format.name(), post),
449 def_site_span: info.def_site,
454 self = info.call_site;
459 /// Returns a `Span` that would enclose both `self` and `end`.
460 pub fn to(self, end: Span) -> Span {
461 let span_data = self.data();
462 let end_data = end.data();
463 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
464 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
465 // have an incomplete span than a completely nonsensical one.
466 if span_data.ctxt != end_data.ctxt {
467 if span_data.ctxt == SyntaxContext::empty() {
469 } else if end_data.ctxt == SyntaxContext::empty() {
472 // Both spans fall within a macro.
473 // FIXME(estebank): check if it is the *same* macro.
476 cmp::min(span_data.lo, end_data.lo),
477 cmp::max(span_data.hi, end_data.hi),
478 if span_data.ctxt == SyntaxContext::empty() { end_data.ctxt } else { span_data.ctxt },
482 /// Returns a `Span` between the end of `self` to the beginning of `end`.
483 pub fn between(self, end: Span) -> Span {
484 let span = self.data();
485 let end = end.data();
489 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
493 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
494 pub fn until(self, end: Span) -> Span {
495 let span = self.data();
496 let end = end.data();
500 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
504 pub fn from_inner_byte_pos(self, start: usize, end: usize) -> Span {
505 let span = self.data();
506 Span::new(span.lo + BytePos::from_usize(start),
507 span.lo + BytePos::from_usize(end),
512 pub fn apply_mark(self, mark: Mark) -> Span {
513 let span = self.data();
514 span.with_ctxt(span.ctxt.apply_mark(mark))
518 pub fn remove_mark(&mut self) -> Mark {
519 let mut span = self.data();
520 let mark = span.ctxt.remove_mark();
521 *self = Span::new(span.lo, span.hi, span.ctxt);
526 pub fn adjust(&mut self, expansion: Mark) -> Option<Mark> {
527 let mut span = self.data();
528 let mark = span.ctxt.adjust(expansion);
529 *self = Span::new(span.lo, span.hi, span.ctxt);
534 pub fn glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
535 -> Option<Option<Mark>> {
536 let mut span = self.data();
537 let mark = span.ctxt.glob_adjust(expansion, glob_ctxt);
538 *self = Span::new(span.lo, span.hi, span.ctxt);
543 pub fn reverse_glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
544 -> Option<Option<Mark>> {
545 let mut span = self.data();
546 let mark = span.ctxt.reverse_glob_adjust(expansion, glob_ctxt);
547 *self = Span::new(span.lo, span.hi, span.ctxt);
552 pub fn modern(self) -> Span {
553 let span = self.data();
554 span.with_ctxt(span.ctxt.modern())
558 pub fn modern_and_legacy(self) -> Span {
559 let span = self.data();
560 span.with_ctxt(span.ctxt.modern_and_legacy())
564 #[derive(Clone, Debug)]
565 pub struct SpanLabel {
566 /// The span we are going to include in the final snippet.
569 /// Is this a primary span? This is the "locus" of the message,
570 /// and is indicated with a `^^^^` underline, versus `----`.
571 pub is_primary: bool,
573 /// What label should we attach to this span (if any)?
574 pub label: Option<String>,
577 impl Default for Span {
578 fn default() -> Self {
583 impl serialize::UseSpecializedEncodable for Span {
584 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
585 let span = self.data();
586 s.emit_struct("Span", 2, |s| {
587 s.emit_struct_field("lo", 0, |s| {
591 s.emit_struct_field("hi", 1, |s| {
598 impl serialize::UseSpecializedDecodable for Span {
599 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
600 d.read_struct("Span", 2, |d| {
601 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
602 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
603 Ok(Span::new(lo, hi, NO_EXPANSION))
608 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
609 f.debug_struct("Span")
610 .field("lo", &span.lo())
611 .field("hi", &span.hi())
612 .field("ctxt", &span.ctxt())
616 impl fmt::Debug for Span {
617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
622 impl fmt::Debug for SpanData {
623 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
624 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
630 pub fn new() -> MultiSpan {
632 primary_spans: vec![],
637 pub fn from_span(primary_span: Span) -> MultiSpan {
639 primary_spans: vec![primary_span],
644 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
651 pub fn push_span_label(&mut self, span: Span, label: String) {
652 self.span_labels.push((span, label));
655 /// Selects the first primary span (if any).
656 pub fn primary_span(&self) -> Option<Span> {
657 self.primary_spans.first().cloned()
660 /// Returns all primary spans.
661 pub fn primary_spans(&self) -> &[Span] {
665 /// Returns `true` if any of the primary spans are displayable.
666 pub fn has_primary_spans(&self) -> bool {
667 self.primary_spans.iter().any(|sp| !sp.is_dummy())
670 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
671 pub fn is_dummy(&self) -> bool {
672 let mut is_dummy = true;
673 for span in &self.primary_spans {
674 if !span.is_dummy() {
681 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
682 /// display well (like std macros). Returns whether replacements occurred.
683 pub fn replace(&mut self, before: Span, after: Span) -> bool {
684 let mut replacements_occurred = false;
685 for primary_span in &mut self.primary_spans {
686 if *primary_span == before {
687 *primary_span = after;
688 replacements_occurred = true;
691 for span_label in &mut self.span_labels {
692 if span_label.0 == before {
693 span_label.0 = after;
694 replacements_occurred = true;
697 replacements_occurred
700 /// Returns the strings to highlight. We always ensure that there
701 /// is an entry for each of the primary spans -- for each primary
702 /// span `P`, if there is at least one label with span `P`, we return
703 /// those labels (marked as primary). But otherwise we return
704 /// `SpanLabel` instances with empty labels.
705 pub fn span_labels(&self) -> Vec<SpanLabel> {
706 let is_primary = |span| self.primary_spans.contains(&span);
708 let mut span_labels = self.span_labels.iter().map(|&(span, ref label)|
711 is_primary: is_primary(span),
712 label: Some(label.clone())
714 ).collect::<Vec<_>>();
716 for &span in &self.primary_spans {
717 if !span_labels.iter().any(|sl| sl.span == span) {
718 span_labels.push(SpanLabel {
729 /// Returns `true` if any of the span labels is displayable.
730 pub fn has_span_labels(&self) -> bool {
731 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
735 impl From<Span> for MultiSpan {
736 fn from(span: Span) -> MultiSpan {
737 MultiSpan::from_span(span)
741 impl From<Vec<Span>> for MultiSpan {
742 fn from(spans: Vec<Span>) -> MultiSpan {
743 MultiSpan::from_spans(spans)
747 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
749 /// Identifies an offset of a multi-byte character in a `SourceFile`.
750 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
751 pub struct MultiByteChar {
752 /// The absolute offset of the character in the `SourceMap`.
754 /// The number of bytes, `>= 2`.
758 /// Identifies an offset of a non-narrow character in a `SourceFile`.
759 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
760 pub enum NonNarrowChar {
761 /// Represents a zero-width character.
763 /// Represents a wide (full-width) character.
765 /// Represents a tab character, represented visually with a width of 4 characters.
770 fn new(pos: BytePos, width: usize) -> Self {
772 0 => NonNarrowChar::ZeroWidth(pos),
773 2 => NonNarrowChar::Wide(pos),
774 4 => NonNarrowChar::Tab(pos),
775 _ => panic!("width {} given for non-narrow character", width),
779 /// Returns the absolute offset of the character in the `SourceMap`.
780 pub fn pos(&self) -> BytePos {
782 NonNarrowChar::ZeroWidth(p) |
783 NonNarrowChar::Wide(p) |
784 NonNarrowChar::Tab(p) => p,
788 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
789 pub fn width(&self) -> usize {
791 NonNarrowChar::ZeroWidth(_) => 0,
792 NonNarrowChar::Wide(_) => 2,
793 NonNarrowChar::Tab(_) => 4,
798 impl Add<BytePos> for NonNarrowChar {
801 fn add(self, rhs: BytePos) -> Self {
803 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
804 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
805 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
810 impl Sub<BytePos> for NonNarrowChar {
813 fn sub(self, rhs: BytePos) -> Self {
815 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
816 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
817 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
822 /// The state of the lazy external source loading mechanism of a `SourceFile`.
823 #[derive(PartialEq, Eq, Clone)]
824 pub enum ExternalSource {
825 /// The external source has been loaded already.
827 /// No attempt has been made to load the external source.
829 /// A failed attempt has been made to load the external source.
831 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
835 impl ExternalSource {
836 pub fn is_absent(&self) -> bool {
838 ExternalSource::Present(_) => false,
843 pub fn get_source(&self) -> Option<&str> {
845 ExternalSource::Present(ref src) => Some(src),
851 /// A single source in the `SourceMap`.
853 pub struct SourceFile {
854 /// The name of the file that the source came from, source that doesn't
855 /// originate from files has names between angle brackets by convention
856 /// (e.g., `<anon>`).
858 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
859 pub name_was_remapped: bool,
860 /// The unmapped path of the file that the source came from.
861 /// Set to `None` if the `SourceFile` was imported from an external crate.
862 pub unmapped_path: Option<FileName>,
863 /// Indicates which crate this `SourceFile` was imported from.
864 pub crate_of_origin: u32,
865 /// The complete source code.
866 pub src: Option<Lrc<String>>,
867 /// The source code's hash.
869 /// The external source code (used for external crates, which will have a `None`
870 /// value as `self.src`.
871 pub external_src: Lock<ExternalSource>,
872 /// The start position of this source in the `SourceMap`.
873 pub start_pos: BytePos,
874 /// The end position of this source in the `SourceMap`.
875 pub end_pos: BytePos,
876 /// Locations of lines beginnings in the source code.
877 pub lines: Vec<BytePos>,
878 /// Locations of multi-byte characters in the source code.
879 pub multibyte_chars: Vec<MultiByteChar>,
880 /// Width of characters that are not narrow in the source code.
881 pub non_narrow_chars: Vec<NonNarrowChar>,
882 /// A hash of the filename, used for speeding up hashing in incremental compilation.
886 impl Encodable for SourceFile {
887 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
888 s.emit_struct("SourceFile", 8, |s| {
889 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
890 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
891 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
892 s.emit_struct_field("start_pos", 4, |s| self.start_pos.encode(s))?;
893 s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
894 s.emit_struct_field("lines", 6, |s| {
895 let lines = &self.lines[..];
897 s.emit_u32(lines.len() as u32)?;
899 if !lines.is_empty() {
900 // In order to preserve some space, we exploit the fact that
901 // the lines list is sorted and individual lines are
902 // probably not that long. Because of that we can store lines
903 // as a difference list, using as little space as possible
904 // for the differences.
905 let max_line_length = if lines.len() == 1 {
909 .map(|w| w[1] - w[0])
910 .map(|bp| bp.to_usize())
915 let bytes_per_diff: u8 = match max_line_length {
917 0x100 ..= 0xFFFF => 2,
921 // Encode the number of bytes used per diff.
922 bytes_per_diff.encode(s)?;
924 // Encode the first element.
927 let diff_iter = (&lines[..]).windows(2)
928 .map(|w| (w[1] - w[0]));
930 match bytes_per_diff {
931 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
932 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
933 4 => for diff in diff_iter { diff.0.encode(s)? },
940 s.emit_struct_field("multibyte_chars", 7, |s| {
941 self.multibyte_chars.encode(s)
943 s.emit_struct_field("non_narrow_chars", 8, |s| {
944 self.non_narrow_chars.encode(s)
946 s.emit_struct_field("name_hash", 9, |s| {
947 self.name_hash.encode(s)
953 impl Decodable for SourceFile {
954 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
956 d.read_struct("SourceFile", 8, |d| {
957 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
958 let name_was_remapped: bool =
959 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
961 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
962 let start_pos: BytePos =
963 d.read_struct_field("start_pos", 4, |d| Decodable::decode(d))?;
964 let end_pos: BytePos = d.read_struct_field("end_pos", 5, |d| Decodable::decode(d))?;
965 let lines: Vec<BytePos> = d.read_struct_field("lines", 6, |d| {
966 let num_lines: u32 = Decodable::decode(d)?;
967 let mut lines = Vec::with_capacity(num_lines as usize);
970 // Read the number of bytes used per diff.
971 let bytes_per_diff: u8 = Decodable::decode(d)?;
973 // Read the first element.
974 let mut line_start: BytePos = Decodable::decode(d)?;
975 lines.push(line_start);
977 for _ in 1..num_lines {
978 let diff = match bytes_per_diff {
979 1 => d.read_u8()? as u32,
980 2 => d.read_u16()? as u32,
985 line_start = line_start + BytePos(diff);
987 lines.push(line_start);
993 let multibyte_chars: Vec<MultiByteChar> =
994 d.read_struct_field("multibyte_chars", 7, |d| Decodable::decode(d))?;
995 let non_narrow_chars: Vec<NonNarrowChar> =
996 d.read_struct_field("non_narrow_chars", 8, |d| Decodable::decode(d))?;
997 let name_hash: u128 =
998 d.read_struct_field("name_hash", 9, |d| Decodable::decode(d))?;
1002 unmapped_path: None,
1003 // `crate_of_origin` has to be set by the importer.
1004 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
1005 // That constant is not available here unfortunately :(
1006 crate_of_origin: std::u32::MAX - 1,
1011 external_src: Lock::new(ExternalSource::AbsentOk),
1021 impl fmt::Debug for SourceFile {
1022 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1023 write!(fmt, "SourceFile({})", self.name)
1028 pub fn new(name: FileName,
1029 name_was_remapped: bool,
1030 unmapped_path: FileName,
1032 start_pos: BytePos) -> SourceFile {
1033 remove_bom(&mut src);
1036 let mut hasher: StableHasher<u128> = StableHasher::new();
1037 hasher.write(src.as_bytes());
1041 let mut hasher: StableHasher<u128> = StableHasher::new();
1042 name.hash(&mut hasher);
1045 let end_pos = start_pos.to_usize() + src.len();
1047 let (lines, multibyte_chars, non_narrow_chars) =
1048 analyze_source_file::analyze_source_file(&src[..], start_pos);
1053 unmapped_path: Some(unmapped_path),
1055 src: Some(Lrc::new(src)),
1057 external_src: Lock::new(ExternalSource::Unneeded),
1059 end_pos: Pos::from_usize(end_pos),
1067 /// Returns the `BytePos` of the beginning of the current line.
1068 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1069 let line_index = self.lookup_line(pos).unwrap();
1070 self.lines[line_index]
1073 /// Add externally loaded source.
1074 /// If the hash of the input doesn't match or no input is supplied via None,
1075 /// it is interpreted as an error and the corresponding enum variant is set.
1076 /// The return value signifies whether some kind of source is present.
1077 pub fn add_external_src<F>(&self, get_src: F) -> bool
1078 where F: FnOnce() -> Option<String>
1080 if *self.external_src.borrow() == ExternalSource::AbsentOk {
1081 let src = get_src();
1082 let mut external_src = self.external_src.borrow_mut();
1083 // Check that no-one else have provided the source while we were getting it
1084 if *external_src == ExternalSource::AbsentOk {
1085 if let Some(src) = src {
1086 let mut hasher: StableHasher<u128> = StableHasher::new();
1087 hasher.write(src.as_bytes());
1089 if hasher.finish() == self.src_hash {
1090 *external_src = ExternalSource::Present(src);
1094 *external_src = ExternalSource::AbsentErr;
1099 self.src.is_some() || external_src.get_source().is_some()
1102 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1106 /// Gets a line from the list of pre-computed line-beginnings.
1107 /// The line number here is 0-based.
1108 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1109 fn get_until_newline(src: &str, begin: usize) -> &str {
1110 // We can't use `lines.get(line_number+1)` because we might
1111 // be parsing when we call this function and thus the current
1112 // line is the last one we have line info for.
1113 let slice = &src[begin..];
1114 match slice.find('\n') {
1115 Some(e) => &slice[..e],
1121 let line = if let Some(line) = self.lines.get(line_number) {
1126 let begin: BytePos = *line - self.start_pos;
1130 if let Some(ref src) = self.src {
1131 Some(Cow::from(get_until_newline(src, begin)))
1132 } else if let Some(src) = self.external_src.borrow().get_source() {
1133 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1139 pub fn is_real_file(&self) -> bool {
1143 pub fn is_imported(&self) -> bool {
1147 pub fn byte_length(&self) -> u32 {
1148 self.end_pos.0 - self.start_pos.0
1150 pub fn count_lines(&self) -> usize {
1154 /// Finds the line containing the given position. The return value is the
1155 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1156 /// number. If the source_file is empty or the position is located before the
1157 /// first line, `None` is returned.
1158 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1159 if self.lines.len() == 0 {
1163 let line_index = lookup_line(&self.lines[..], pos);
1164 assert!(line_index < self.lines.len() as isize);
1165 if line_index >= 0 {
1166 Some(line_index as usize)
1172 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1173 if self.start_pos == self.end_pos {
1174 return (self.start_pos, self.end_pos);
1177 assert!(line_index < self.lines.len());
1178 if line_index == (self.lines.len() - 1) {
1179 (self.lines[line_index], self.end_pos)
1181 (self.lines[line_index], self.lines[line_index + 1])
1186 pub fn contains(&self, byte_pos: BytePos) -> bool {
1187 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1191 /// Removes UTF-8 BOM, if any.
1192 fn remove_bom(src: &mut String) {
1193 if src.starts_with("\u{feff}") {
1198 // _____________________________________________________________________________
1199 // Pos, BytePos, CharPos
1203 fn from_usize(n: usize) -> Self;
1204 fn to_usize(&self) -> usize;
1205 fn from_u32(n: u32) -> Self;
1206 fn to_u32(&self) -> u32;
1209 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1211 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1212 pub struct BytePos(pub u32);
1214 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1215 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1216 /// values to `CharPos` values as necessary.
1217 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1218 pub struct CharPos(pub usize);
1220 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1221 // have been unsuccessful.
1223 impl Pos for BytePos {
1225 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1228 fn to_usize(&self) -> usize { self.0 as usize }
1231 fn from_u32(n: u32) -> BytePos { BytePos(n) }
1234 fn to_u32(&self) -> u32 { self.0 }
1237 impl Add for BytePos {
1238 type Output = BytePos;
1241 fn add(self, rhs: BytePos) -> BytePos {
1242 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1246 impl Sub for BytePos {
1247 type Output = BytePos;
1250 fn sub(self, rhs: BytePos) -> BytePos {
1251 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1255 impl Encodable for BytePos {
1256 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1261 impl Decodable for BytePos {
1262 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1263 Ok(BytePos(d.read_u32()?))
1267 impl Pos for CharPos {
1269 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1272 fn to_usize(&self) -> usize { self.0 }
1275 fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1278 fn to_u32(&self) -> u32 { self.0 as u32}
1281 impl Add for CharPos {
1282 type Output = CharPos;
1285 fn add(self, rhs: CharPos) -> CharPos {
1286 CharPos(self.to_usize() + rhs.to_usize())
1290 impl Sub for CharPos {
1291 type Output = CharPos;
1294 fn sub(self, rhs: CharPos) -> CharPos {
1295 CharPos(self.to_usize() - rhs.to_usize())
1299 // _____________________________________________________________________________
1300 // Loc, SourceFileAndLine, SourceFileAndBytePos
1303 /// A source code location used for error reporting.
1304 #[derive(Debug, Clone)]
1306 /// Information about the original source.
1307 pub file: Lrc<SourceFile>,
1308 /// The (1-based) line number.
1310 /// The (0-based) column offset.
1312 /// The (0-based) column offset when displayed.
1313 pub col_display: usize,
1316 // Used to be structural records.
1318 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1320 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1322 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1323 pub struct LineInfo {
1324 /// Index of line, starting from 0.
1325 pub line_index: usize,
1327 /// Column in line where span begins, starting from 0.
1328 pub start_col: CharPos,
1330 /// Column in line where span ends, starting from 0, exclusive.
1331 pub end_col: CharPos,
1334 pub struct FileLines {
1335 pub file: Lrc<SourceFile>,
1336 pub lines: Vec<LineInfo>
1339 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1340 Cell::new(default_span_debug));
1343 pub struct MacroBacktrace {
1344 /// span where macro was applied to generate this code
1345 pub call_site: Span,
1347 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1348 pub macro_decl_name: String,
1350 /// span where macro was defined (if known)
1351 pub def_site_span: Option<Span>,
1354 // _____________________________________________________________________________
1355 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1358 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1360 #[derive(Clone, PartialEq, Eq, Debug)]
1361 pub enum SpanLinesError {
1362 IllFormedSpan(Span),
1363 DistinctSources(DistinctSources),
1366 #[derive(Clone, PartialEq, Eq, Debug)]
1367 pub enum SpanSnippetError {
1368 IllFormedSpan(Span),
1369 DistinctSources(DistinctSources),
1370 MalformedForSourcemap(MalformedSourceMapPositions),
1371 SourceNotAvailable { filename: FileName }
1374 #[derive(Clone, PartialEq, Eq, Debug)]
1375 pub struct DistinctSources {
1376 pub begin: (FileName, BytePos),
1377 pub end: (FileName, BytePos)
1380 #[derive(Clone, PartialEq, Eq, Debug)]
1381 pub struct MalformedSourceMapPositions {
1383 pub source_len: usize,
1384 pub begin_pos: BytePos,
1385 pub end_pos: BytePos
1388 // Given a slice of line start positions and a position, returns the index of
1389 // the line the position is on. Returns -1 if the position is located before
1391 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1392 match lines.binary_search(&pos) {
1393 Ok(line) => line as isize,
1394 Err(line) => line as isize - 1
1400 use super::{lookup_line, BytePos};
1403 fn test_lookup_line() {
1405 let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1407 assert_eq!(lookup_line(lines, BytePos(0)), -1);
1408 assert_eq!(lookup_line(lines, BytePos(3)), 0);
1409 assert_eq!(lookup_line(lines, BytePos(4)), 0);
1411 assert_eq!(lookup_line(lines, BytePos(16)), 0);
1412 assert_eq!(lookup_line(lines, BytePos(17)), 1);
1413 assert_eq!(lookup_line(lines, BytePos(18)), 1);
1415 assert_eq!(lookup_line(lines, BytePos(28)), 2);
1416 assert_eq!(lookup_line(lines, BytePos(29)), 2);