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)]
13 #![feature(crate_visibility_modifier)]
15 #![feature(non_exhaustive)]
16 #![feature(optin_builtin_traits)]
17 #![feature(rustc_attrs)]
18 #![feature(proc_macro_hygiene)]
19 #![feature(specialization)]
20 #![feature(step_trait)]
22 use serialize::{Encodable, Decodable, Encoder, Decoder};
24 #[allow(unused_extern_crates)]
25 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::{Symbol, sym};
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>,
59 pub fn new(edition: Edition) -> Globals {
61 symbol_interner: Lock::new(symbol::Interner::fresh()),
62 span_interner: Lock::new(span_encoding::SpanInterner::default()),
63 hygiene_data: Lock::new(hygiene::HygieneData::new()),
69 scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
71 /// Differentiates between real files and common virtual files.
72 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
75 /// A macro. This includes the full name of the macro, so that there are no clashes.
81 /// Hack in `src/libsyntax/parse.rs`.
84 ProcMacroSourceCode(u64),
85 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
87 /// Strings provided as crate attributes in the CLI.
89 /// Custom sources for explicit parser calls from plugins and drivers.
91 DocTest(PathBuf, isize),
94 impl std::fmt::Display for FileName {
95 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 Real(ref path) => write!(fmt, "{}", path.display()),
99 Macros(ref name) => write!(fmt, "<{} macros>", name),
100 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
101 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
102 Anon(_) => write!(fmt, "<anon>"),
103 ProcMacroSourceCode(_) =>
104 write!(fmt, "<proc-macro source code>"),
105 CfgSpec(_) => write!(fmt, "<cfgspec>"),
106 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
107 Custom(ref s) => write!(fmt, "<{}>", s),
108 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
113 impl From<PathBuf> for FileName {
114 fn from(p: PathBuf) -> Self {
115 assert!(!p.to_string_lossy().ends_with('>'));
121 pub fn is_real(&self) -> bool {
128 ProcMacroSourceCode(_) |
133 DocTest(_, _) => false,
137 pub fn is_macros(&self) -> bool {
143 ProcMacroSourceCode(_) |
148 DocTest(_, _) => false,
153 pub fn quote_expansion_source_code(src: &str) -> FileName {
154 let mut hasher = StableHasher::new();
155 src.hash(&mut hasher);
156 FileName::QuoteExpansion(hasher.finish())
159 pub fn macro_expansion_source_code(src: &str) -> FileName {
160 let mut hasher = StableHasher::new();
161 src.hash(&mut hasher);
162 FileName::MacroExpansion(hasher.finish())
165 pub fn anon_source_code(src: &str) -> FileName {
166 let mut hasher = StableHasher::new();
167 src.hash(&mut hasher);
168 FileName::Anon(hasher.finish())
171 pub fn proc_macro_source_code(src: &str) -> FileName {
172 let mut hasher = StableHasher::new();
173 src.hash(&mut hasher);
174 FileName::ProcMacroSourceCode(hasher.finish())
177 pub fn cfg_spec_source_code(src: &str) -> FileName {
178 let mut hasher = StableHasher::new();
179 src.hash(&mut hasher);
180 FileName::QuoteExpansion(hasher.finish())
183 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
184 let mut hasher = StableHasher::new();
185 src.hash(&mut hasher);
186 FileName::CliCrateAttr(hasher.finish())
189 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{
190 FileName::DocTest(path, line)
194 /// Spans represent a region of code, used for error reporting. Positions in spans
195 /// are *absolute* positions from the beginning of the source_map, not positions
196 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
197 /// to the original source.
198 /// You must be careful if the span crosses more than one file - you will not be
199 /// able to use many of the functions on spans in source_map and you cannot assume
200 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
201 /// range between files.
203 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
204 /// sent to other threads, but some pieces of performance infra run in a separate thread.
205 /// Using `Span` is generally preferred.
206 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
207 pub struct SpanData {
210 /// Information about where the macro came from, if this piece of
211 /// code was created by a macro expansion.
212 pub ctxt: SyntaxContext,
217 pub fn with_lo(&self, lo: BytePos) -> Span {
218 Span::new(lo, self.hi, self.ctxt)
221 pub fn with_hi(&self, hi: BytePos) -> Span {
222 Span::new(self.lo, hi, self.ctxt)
225 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
226 Span::new(self.lo, self.hi, ctxt)
230 // The interner is pointed to by a thread local value which is only set on the main thread
231 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
232 // to avoid panics and other errors, even though it would be memory safe to do so.
233 #[cfg(not(parallel_compiler))]
234 impl !Send for Span {}
235 #[cfg(not(parallel_compiler))]
236 impl !Sync for Span {}
238 impl PartialOrd for Span {
239 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
240 PartialOrd::partial_cmp(&self.data(), &rhs.data())
244 fn cmp(&self, rhs: &Self) -> Ordering {
245 Ord::cmp(&self.data(), &rhs.data())
249 /// A collection of spans. Spans have two orthogonal attributes:
251 /// - They can be *primary spans*. In this case they are the locus of
252 /// the error, and would be rendered with `^^^`.
253 /// - They can have a *label*. In this case, the label is written next
254 /// to the mark in the snippet when we render.
255 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
256 pub struct MultiSpan {
257 primary_spans: Vec<Span>,
258 span_labels: Vec<(Span, String)>,
263 pub fn lo(self) -> BytePos {
267 pub fn with_lo(self, lo: BytePos) -> Span {
268 self.data().with_lo(lo)
271 pub fn hi(self) -> BytePos {
275 pub fn with_hi(self, hi: BytePos) -> Span {
276 self.data().with_hi(hi)
279 pub fn ctxt(self) -> SyntaxContext {
283 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
284 self.data().with_ctxt(ctxt)
287 /// Returns `true` if this is a dummy span with any hygienic context.
289 pub fn is_dummy(self) -> bool {
290 let span = self.data();
291 span.lo.0 == 0 && span.hi.0 == 0
294 /// Returns a new span representing an empty span at the beginning of this span
296 pub fn shrink_to_lo(self) -> Span {
297 let span = self.data();
298 span.with_hi(span.lo)
300 /// Returns a new span representing an empty span at the end of this span.
302 pub fn shrink_to_hi(self) -> Span {
303 let span = self.data();
304 span.with_lo(span.hi)
307 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
308 pub fn substitute_dummy(self, other: Span) -> Span {
309 if self.is_dummy() { other } else { self }
312 /// Returns `true` if `self` fully encloses `other`.
313 pub fn contains(self, other: Span) -> bool {
314 let span = self.data();
315 let other = other.data();
316 span.lo <= other.lo && other.hi <= span.hi
319 /// Returns `true` if `self` touches `other`.
320 pub fn overlaps(self, other: Span) -> bool {
321 let span = self.data();
322 let other = other.data();
323 span.lo < other.hi && other.lo < span.hi
326 /// Returns `true` if the spans are equal with regards to the source text.
328 /// Use this instead of `==` when either span could be generated code,
329 /// and you only care that they point to the same bytes of source text.
330 pub fn source_equal(&self, other: &Span) -> bool {
331 let span = self.data();
332 let other = other.data();
333 span.lo == other.lo && span.hi == other.hi
336 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
337 pub fn trim_start(self, other: Span) -> Option<Span> {
338 let span = self.data();
339 let other = other.data();
340 if span.hi > other.hi {
341 Some(span.with_lo(cmp::max(span.lo, other.hi)))
347 /// Returns the source span -- this is either the supplied span, or the span for
348 /// the macro callsite that expanded to it.
349 pub fn source_callsite(self) -> Span {
350 self.ctxt().outer_expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
353 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
355 pub fn parent(self) -> Option<Span> {
356 self.ctxt().outer_expn_info().map(|i| i.call_site)
359 /// Edition of the crate from which this span came.
360 pub fn edition(self) -> edition::Edition {
361 self.ctxt().outer_expn_info().map_or_else(|| {
362 Edition::from_session()
363 }, |einfo| einfo.edition)
367 pub fn rust_2015(&self) -> bool {
368 self.edition() == edition::Edition::Edition2015
372 pub fn rust_2018(&self) -> bool {
373 self.edition() >= edition::Edition::Edition2018
376 /// Returns the source callee.
378 /// Returns `None` if the supplied span has no expansion trace,
379 /// else returns the `ExpnInfo` for the macro definition
380 /// corresponding to the source callsite.
381 pub fn source_callee(self) -> Option<ExpnInfo> {
382 fn source_callee(info: ExpnInfo) -> ExpnInfo {
383 match info.call_site.ctxt().outer_expn_info() {
384 Some(info) => source_callee(info),
388 self.ctxt().outer_expn_info().map(source_callee)
391 /// Checks if a span is "internal" to a macro in which `#[unstable]`
392 /// items can be used (that is, a macro marked with
393 /// `#[allow_internal_unstable]`).
394 pub fn allows_unstable(&self, feature: Symbol) -> bool {
395 match self.ctxt().outer_expn_info() {
397 .allow_internal_unstable
398 .map_or(false, |features| features.iter().any(|&f|
399 f == feature || f == sym::allow_internal_unstable_backcompat_hack
405 /// Checks if this span arises from a compiler desugaring of kind `kind`.
406 pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
407 match self.ctxt().outer_expn_info() {
408 Some(info) => match info.format {
409 ExpnFormat::CompilerDesugaring(k) => k == kind,
416 /// Returns the compiler desugaring that created this span, or `None`
417 /// if this span is not from a desugaring.
418 pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
419 match self.ctxt().outer_expn_info() {
420 Some(info) => match info.format {
421 ExpnFormat::CompilerDesugaring(k) => Some(k),
428 /// Checks if a span is "internal" to a macro in which `unsafe`
429 /// can be used without triggering the `unsafe_code` lint
430 // (that is, a macro marked with `#[allow_internal_unsafe]`).
431 pub fn allows_unsafe(&self) -> bool {
432 match self.ctxt().outer_expn_info() {
433 Some(info) => info.allow_internal_unsafe,
438 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
439 let mut prev_span = DUMMY_SP;
440 let mut result = vec![];
441 while let Some(info) = self.ctxt().outer_expn_info() {
442 // Don't print recursive invocations.
443 if !info.call_site.source_equal(&prev_span) {
444 let (pre, post) = match info.format {
445 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
446 ExpnFormat::MacroBang(..) => ("", "!"),
447 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
449 result.push(MacroBacktrace {
450 call_site: info.call_site,
451 macro_decl_name: format!("{}{}{}", pre, info.format.name(), post),
452 def_site_span: info.def_site,
457 self = info.call_site;
462 /// Returns a `Span` that would enclose both `self` and `end`.
463 pub fn to(self, end: Span) -> Span {
464 let span_data = self.data();
465 let end_data = end.data();
466 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
467 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
468 // have an incomplete span than a completely nonsensical one.
469 if span_data.ctxt != end_data.ctxt {
470 if span_data.ctxt == SyntaxContext::empty() {
472 } else if end_data.ctxt == SyntaxContext::empty() {
475 // Both spans fall within a macro.
476 // FIXME(estebank): check if it is the *same* macro.
479 cmp::min(span_data.lo, end_data.lo),
480 cmp::max(span_data.hi, end_data.hi),
481 if span_data.ctxt == SyntaxContext::empty() { end_data.ctxt } else { span_data.ctxt },
485 /// Returns a `Span` between the end of `self` to the beginning of `end`.
486 pub fn between(self, end: Span) -> Span {
487 let span = self.data();
488 let end = end.data();
492 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
496 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
497 pub fn until(self, end: Span) -> Span {
498 let span = self.data();
499 let end = end.data();
503 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
507 pub fn from_inner(self, inner: InnerSpan) -> Span {
508 let span = self.data();
509 Span::new(span.lo + BytePos::from_usize(inner.start),
510 span.lo + BytePos::from_usize(inner.end),
515 pub fn apply_mark(self, mark: Mark) -> Span {
516 let span = self.data();
517 span.with_ctxt(span.ctxt.apply_mark(mark))
521 pub fn remove_mark(&mut self) -> Mark {
522 let mut span = self.data();
523 let mark = span.ctxt.remove_mark();
524 *self = Span::new(span.lo, span.hi, span.ctxt);
529 pub fn adjust(&mut self, expansion: Mark) -> Option<Mark> {
530 let mut span = self.data();
531 let mark = span.ctxt.adjust(expansion);
532 *self = Span::new(span.lo, span.hi, span.ctxt);
537 pub fn modernize_and_adjust(&mut self, expansion: Mark) -> Option<Mark> {
538 let mut span = self.data();
539 let mark = span.ctxt.modernize_and_adjust(expansion);
540 *self = Span::new(span.lo, span.hi, span.ctxt);
545 pub fn glob_adjust(&mut self, expansion: Mark, glob_span: Span) -> Option<Option<Mark>> {
546 let mut span = self.data();
547 let mark = span.ctxt.glob_adjust(expansion, glob_span);
548 *self = Span::new(span.lo, span.hi, span.ctxt);
553 pub fn reverse_glob_adjust(&mut self, expansion: Mark, glob_span: Span)
554 -> Option<Option<Mark>> {
555 let mut span = self.data();
556 let mark = span.ctxt.reverse_glob_adjust(expansion, glob_span);
557 *self = Span::new(span.lo, span.hi, span.ctxt);
562 pub fn modern(self) -> Span {
563 let span = self.data();
564 span.with_ctxt(span.ctxt.modern())
568 pub fn modern_and_legacy(self) -> Span {
569 let span = self.data();
570 span.with_ctxt(span.ctxt.modern_and_legacy())
574 #[derive(Clone, Debug)]
575 pub struct SpanLabel {
576 /// The span we are going to include in the final snippet.
579 /// Is this a primary span? This is the "locus" of the message,
580 /// and is indicated with a `^^^^` underline, versus `----`.
581 pub is_primary: bool,
583 /// What label should we attach to this span (if any)?
584 pub label: Option<String>,
587 impl Default for Span {
588 fn default() -> Self {
593 impl serialize::UseSpecializedEncodable for Span {
594 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
595 let span = self.data();
596 s.emit_struct("Span", 2, |s| {
597 s.emit_struct_field("lo", 0, |s| {
601 s.emit_struct_field("hi", 1, |s| {
608 impl serialize::UseSpecializedDecodable for Span {
609 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
610 d.read_struct("Span", 2, |d| {
611 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
612 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
613 Ok(Span::new(lo, hi, NO_EXPANSION))
618 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
619 f.debug_struct("Span")
620 .field("lo", &span.lo())
621 .field("hi", &span.hi())
622 .field("ctxt", &span.ctxt())
626 impl fmt::Debug for Span {
627 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
632 impl fmt::Debug for SpanData {
633 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
634 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
640 pub fn new() -> MultiSpan {
642 primary_spans: vec![],
647 pub fn from_span(primary_span: Span) -> MultiSpan {
649 primary_spans: vec![primary_span],
654 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
661 pub fn push_span_label(&mut self, span: Span, label: String) {
662 self.span_labels.push((span, label));
665 /// Selects the first primary span (if any).
666 pub fn primary_span(&self) -> Option<Span> {
667 self.primary_spans.first().cloned()
670 /// Returns all primary spans.
671 pub fn primary_spans(&self) -> &[Span] {
675 /// Returns `true` if any of the primary spans are displayable.
676 pub fn has_primary_spans(&self) -> bool {
677 self.primary_spans.iter().any(|sp| !sp.is_dummy())
680 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
681 pub fn is_dummy(&self) -> bool {
682 let mut is_dummy = true;
683 for span in &self.primary_spans {
684 if !span.is_dummy() {
691 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
692 /// display well (like std macros). Returns whether replacements occurred.
693 pub fn replace(&mut self, before: Span, after: Span) -> bool {
694 let mut replacements_occurred = false;
695 for primary_span in &mut self.primary_spans {
696 if *primary_span == before {
697 *primary_span = after;
698 replacements_occurred = true;
701 for span_label in &mut self.span_labels {
702 if span_label.0 == before {
703 span_label.0 = after;
704 replacements_occurred = true;
707 replacements_occurred
710 /// Returns the strings to highlight. We always ensure that there
711 /// is an entry for each of the primary spans -- for each primary
712 /// span `P`, if there is at least one label with span `P`, we return
713 /// those labels (marked as primary). But otherwise we return
714 /// `SpanLabel` instances with empty labels.
715 pub fn span_labels(&self) -> Vec<SpanLabel> {
716 let is_primary = |span| self.primary_spans.contains(&span);
718 let mut span_labels = self.span_labels.iter().map(|&(span, ref label)|
721 is_primary: is_primary(span),
722 label: Some(label.clone())
724 ).collect::<Vec<_>>();
726 for &span in &self.primary_spans {
727 if !span_labels.iter().any(|sl| sl.span == span) {
728 span_labels.push(SpanLabel {
739 /// Returns `true` if any of the span labels is displayable.
740 pub fn has_span_labels(&self) -> bool {
741 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
745 impl From<Span> for MultiSpan {
746 fn from(span: Span) -> MultiSpan {
747 MultiSpan::from_span(span)
751 impl From<Vec<Span>> for MultiSpan {
752 fn from(spans: Vec<Span>) -> MultiSpan {
753 MultiSpan::from_spans(spans)
757 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
759 /// Identifies an offset of a multi-byte character in a `SourceFile`.
760 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
761 pub struct MultiByteChar {
762 /// The absolute offset of the character in the `SourceMap`.
764 /// The number of bytes, `>= 2`.
768 /// Identifies an offset of a non-narrow character in a `SourceFile`.
769 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
770 pub enum NonNarrowChar {
771 /// Represents a zero-width character.
773 /// Represents a wide (full-width) character.
775 /// Represents a tab character, represented visually with a width of 4 characters.
780 fn new(pos: BytePos, width: usize) -> Self {
782 0 => NonNarrowChar::ZeroWidth(pos),
783 2 => NonNarrowChar::Wide(pos),
784 4 => NonNarrowChar::Tab(pos),
785 _ => panic!("width {} given for non-narrow character", width),
789 /// Returns the absolute offset of the character in the `SourceMap`.
790 pub fn pos(&self) -> BytePos {
792 NonNarrowChar::ZeroWidth(p) |
793 NonNarrowChar::Wide(p) |
794 NonNarrowChar::Tab(p) => p,
798 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
799 pub fn width(&self) -> usize {
801 NonNarrowChar::ZeroWidth(_) => 0,
802 NonNarrowChar::Wide(_) => 2,
803 NonNarrowChar::Tab(_) => 4,
808 impl Add<BytePos> for NonNarrowChar {
811 fn add(self, rhs: BytePos) -> Self {
813 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
814 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
815 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
820 impl Sub<BytePos> for NonNarrowChar {
823 fn sub(self, rhs: BytePos) -> Self {
825 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
826 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
827 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
832 /// The state of the lazy external source loading mechanism of a `SourceFile`.
833 #[derive(PartialEq, Eq, Clone)]
834 pub enum ExternalSource {
835 /// The external source has been loaded already.
837 /// No attempt has been made to load the external source.
839 /// A failed attempt has been made to load the external source.
841 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
845 impl ExternalSource {
846 pub fn is_absent(&self) -> bool {
848 ExternalSource::Present(_) => false,
853 pub fn get_source(&self) -> Option<&str> {
855 ExternalSource::Present(ref src) => Some(src),
861 /// A single source in the `SourceMap`.
863 pub struct SourceFile {
864 /// The name of the file that the source came from, source that doesn't
865 /// originate from files has names between angle brackets by convention
866 /// (e.g., `<anon>`).
868 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
869 pub name_was_remapped: bool,
870 /// The unmapped path of the file that the source came from.
871 /// Set to `None` if the `SourceFile` was imported from an external crate.
872 pub unmapped_path: Option<FileName>,
873 /// Indicates which crate this `SourceFile` was imported from.
874 pub crate_of_origin: u32,
875 /// The complete source code.
876 pub src: Option<Lrc<String>>,
877 /// The source code's hash.
879 /// The external source code (used for external crates, which will have a `None`
880 /// value as `self.src`.
881 pub external_src: Lock<ExternalSource>,
882 /// The start position of this source in the `SourceMap`.
883 pub start_pos: BytePos,
884 /// The end position of this source in the `SourceMap`.
885 pub end_pos: BytePos,
886 /// Locations of lines beginnings in the source code.
887 pub lines: Vec<BytePos>,
888 /// Locations of multi-byte characters in the source code.
889 pub multibyte_chars: Vec<MultiByteChar>,
890 /// Width of characters that are not narrow in the source code.
891 pub non_narrow_chars: Vec<NonNarrowChar>,
892 /// A hash of the filename, used for speeding up hashing in incremental compilation.
896 impl Encodable for SourceFile {
897 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
898 s.emit_struct("SourceFile", 8, |s| {
899 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
900 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
901 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
902 s.emit_struct_field("start_pos", 4, |s| self.start_pos.encode(s))?;
903 s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
904 s.emit_struct_field("lines", 6, |s| {
905 let lines = &self.lines[..];
907 s.emit_u32(lines.len() as u32)?;
909 if !lines.is_empty() {
910 // In order to preserve some space, we exploit the fact that
911 // the lines list is sorted and individual lines are
912 // probably not that long. Because of that we can store lines
913 // as a difference list, using as little space as possible
914 // for the differences.
915 let max_line_length = if lines.len() == 1 {
919 .map(|w| w[1] - w[0])
920 .map(|bp| bp.to_usize())
925 let bytes_per_diff: u8 = match max_line_length {
927 0x100 ..= 0xFFFF => 2,
931 // Encode the number of bytes used per diff.
932 bytes_per_diff.encode(s)?;
934 // Encode the first element.
937 let diff_iter = (&lines[..]).windows(2)
938 .map(|w| (w[1] - w[0]));
940 match bytes_per_diff {
941 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
942 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
943 4 => for diff in diff_iter { diff.0.encode(s)? },
950 s.emit_struct_field("multibyte_chars", 7, |s| {
951 self.multibyte_chars.encode(s)
953 s.emit_struct_field("non_narrow_chars", 8, |s| {
954 self.non_narrow_chars.encode(s)
956 s.emit_struct_field("name_hash", 9, |s| {
957 self.name_hash.encode(s)
963 impl Decodable for SourceFile {
964 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
966 d.read_struct("SourceFile", 8, |d| {
967 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
968 let name_was_remapped: bool =
969 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
971 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
972 let start_pos: BytePos =
973 d.read_struct_field("start_pos", 4, |d| Decodable::decode(d))?;
974 let end_pos: BytePos = d.read_struct_field("end_pos", 5, |d| Decodable::decode(d))?;
975 let lines: Vec<BytePos> = d.read_struct_field("lines", 6, |d| {
976 let num_lines: u32 = Decodable::decode(d)?;
977 let mut lines = Vec::with_capacity(num_lines as usize);
980 // Read the number of bytes used per diff.
981 let bytes_per_diff: u8 = Decodable::decode(d)?;
983 // Read the first element.
984 let mut line_start: BytePos = Decodable::decode(d)?;
985 lines.push(line_start);
987 for _ in 1..num_lines {
988 let diff = match bytes_per_diff {
989 1 => d.read_u8()? as u32,
990 2 => d.read_u16()? as u32,
995 line_start = line_start + BytePos(diff);
997 lines.push(line_start);
1003 let multibyte_chars: Vec<MultiByteChar> =
1004 d.read_struct_field("multibyte_chars", 7, |d| Decodable::decode(d))?;
1005 let non_narrow_chars: Vec<NonNarrowChar> =
1006 d.read_struct_field("non_narrow_chars", 8, |d| Decodable::decode(d))?;
1007 let name_hash: u128 =
1008 d.read_struct_field("name_hash", 9, |d| Decodable::decode(d))?;
1012 unmapped_path: None,
1013 // `crate_of_origin` has to be set by the importer.
1014 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
1015 // That constant is not available here unfortunately :(
1016 crate_of_origin: std::u32::MAX - 1,
1021 external_src: Lock::new(ExternalSource::AbsentOk),
1031 impl fmt::Debug for SourceFile {
1032 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1033 write!(fmt, "SourceFile({})", self.name)
1038 pub fn new(name: FileName,
1039 name_was_remapped: bool,
1040 unmapped_path: FileName,
1042 start_pos: BytePos) -> SourceFile {
1043 remove_bom(&mut src);
1046 let mut hasher: StableHasher<u128> = StableHasher::new();
1047 hasher.write(src.as_bytes());
1051 let mut hasher: StableHasher<u128> = StableHasher::new();
1052 name.hash(&mut hasher);
1055 let end_pos = start_pos.to_usize() + src.len();
1057 let (lines, multibyte_chars, non_narrow_chars) =
1058 analyze_source_file::analyze_source_file(&src[..], start_pos);
1063 unmapped_path: Some(unmapped_path),
1065 src: Some(Lrc::new(src)),
1067 external_src: Lock::new(ExternalSource::Unneeded),
1069 end_pos: Pos::from_usize(end_pos),
1077 /// Returns the `BytePos` of the beginning of the current line.
1078 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1079 let line_index = self.lookup_line(pos).unwrap();
1080 self.lines[line_index]
1083 /// Add externally loaded source.
1084 /// If the hash of the input doesn't match or no input is supplied via None,
1085 /// it is interpreted as an error and the corresponding enum variant is set.
1086 /// The return value signifies whether some kind of source is present.
1087 pub fn add_external_src<F>(&self, get_src: F) -> bool
1088 where F: FnOnce() -> Option<String>
1090 if *self.external_src.borrow() == ExternalSource::AbsentOk {
1091 let src = get_src();
1092 let mut external_src = self.external_src.borrow_mut();
1093 // Check that no-one else have provided the source while we were getting it
1094 if *external_src == ExternalSource::AbsentOk {
1095 if let Some(src) = src {
1096 let mut hasher: StableHasher<u128> = StableHasher::new();
1097 hasher.write(src.as_bytes());
1099 if hasher.finish() == self.src_hash {
1100 *external_src = ExternalSource::Present(src);
1104 *external_src = ExternalSource::AbsentErr;
1109 self.src.is_some() || external_src.get_source().is_some()
1112 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1116 /// Gets a line from the list of pre-computed line-beginnings.
1117 /// The line number here is 0-based.
1118 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1119 fn get_until_newline(src: &str, begin: usize) -> &str {
1120 // We can't use `lines.get(line_number+1)` because we might
1121 // be parsing when we call this function and thus the current
1122 // line is the last one we have line info for.
1123 let slice = &src[begin..];
1124 match slice.find('\n') {
1125 Some(e) => &slice[..e],
1131 let line = if let Some(line) = self.lines.get(line_number) {
1136 let begin: BytePos = *line - self.start_pos;
1140 if let Some(ref src) = self.src {
1141 Some(Cow::from(get_until_newline(src, begin)))
1142 } else if let Some(src) = self.external_src.borrow().get_source() {
1143 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1149 pub fn is_real_file(&self) -> bool {
1153 pub fn is_imported(&self) -> bool {
1157 pub fn byte_length(&self) -> u32 {
1158 self.end_pos.0 - self.start_pos.0
1160 pub fn count_lines(&self) -> usize {
1164 /// Finds the line containing the given position. The return value is the
1165 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1166 /// number. If the source_file is empty or the position is located before the
1167 /// first line, `None` is returned.
1168 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1169 if self.lines.len() == 0 {
1173 let line_index = lookup_line(&self.lines[..], pos);
1174 assert!(line_index < self.lines.len() as isize);
1175 if line_index >= 0 {
1176 Some(line_index as usize)
1182 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1183 if self.start_pos == self.end_pos {
1184 return (self.start_pos, self.end_pos);
1187 assert!(line_index < self.lines.len());
1188 if line_index == (self.lines.len() - 1) {
1189 (self.lines[line_index], self.end_pos)
1191 (self.lines[line_index], self.lines[line_index + 1])
1196 pub fn contains(&self, byte_pos: BytePos) -> bool {
1197 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1201 /// Removes UTF-8 BOM, if any.
1202 fn remove_bom(src: &mut String) {
1203 if src.starts_with("\u{feff}") {
1208 // _____________________________________________________________________________
1209 // Pos, BytePos, CharPos
1213 fn from_usize(n: usize) -> Self;
1214 fn to_usize(&self) -> usize;
1215 fn from_u32(n: u32) -> Self;
1216 fn to_u32(&self) -> u32;
1219 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1221 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1222 pub struct BytePos(pub u32);
1224 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1225 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1226 /// values to `CharPos` values as necessary.
1227 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1228 pub struct CharPos(pub usize);
1230 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1231 // have been unsuccessful.
1233 impl Pos for BytePos {
1235 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1238 fn to_usize(&self) -> usize { self.0 as usize }
1241 fn from_u32(n: u32) -> BytePos { BytePos(n) }
1244 fn to_u32(&self) -> u32 { self.0 }
1247 impl Add for BytePos {
1248 type Output = BytePos;
1251 fn add(self, rhs: BytePos) -> BytePos {
1252 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1256 impl Sub for BytePos {
1257 type Output = BytePos;
1260 fn sub(self, rhs: BytePos) -> BytePos {
1261 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1265 impl Encodable for BytePos {
1266 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1271 impl Decodable for BytePos {
1272 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1273 Ok(BytePos(d.read_u32()?))
1277 impl Pos for CharPos {
1279 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1282 fn to_usize(&self) -> usize { self.0 }
1285 fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1288 fn to_u32(&self) -> u32 { self.0 as u32}
1291 impl Add for CharPos {
1292 type Output = CharPos;
1295 fn add(self, rhs: CharPos) -> CharPos {
1296 CharPos(self.to_usize() + rhs.to_usize())
1300 impl Sub for CharPos {
1301 type Output = CharPos;
1304 fn sub(self, rhs: CharPos) -> CharPos {
1305 CharPos(self.to_usize() - rhs.to_usize())
1309 // _____________________________________________________________________________
1310 // Loc, SourceFileAndLine, SourceFileAndBytePos
1313 /// A source code location used for error reporting.
1314 #[derive(Debug, Clone)]
1316 /// Information about the original source.
1317 pub file: Lrc<SourceFile>,
1318 /// The (1-based) line number.
1320 /// The (0-based) column offset.
1322 /// The (0-based) column offset when displayed.
1323 pub col_display: usize,
1326 // Used to be structural records.
1328 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1330 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1332 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1333 pub struct LineInfo {
1334 /// Index of line, starting from 0.
1335 pub line_index: usize,
1337 /// Column in line where span begins, starting from 0.
1338 pub start_col: CharPos,
1340 /// Column in line where span ends, starting from 0, exclusive.
1341 pub end_col: CharPos,
1344 pub struct FileLines {
1345 pub file: Lrc<SourceFile>,
1346 pub lines: Vec<LineInfo>
1349 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1350 Cell::new(default_span_debug));
1353 pub struct MacroBacktrace {
1354 /// span where macro was applied to generate this code
1355 pub call_site: Span,
1357 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1358 pub macro_decl_name: String,
1360 /// span where macro was defined (if known)
1361 pub def_site_span: Option<Span>,
1364 // _____________________________________________________________________________
1365 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1368 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1370 #[derive(Clone, PartialEq, Eq, Debug)]
1371 pub enum SpanLinesError {
1372 IllFormedSpan(Span),
1373 DistinctSources(DistinctSources),
1376 #[derive(Clone, PartialEq, Eq, Debug)]
1377 pub enum SpanSnippetError {
1378 IllFormedSpan(Span),
1379 DistinctSources(DistinctSources),
1380 MalformedForSourcemap(MalformedSourceMapPositions),
1381 SourceNotAvailable { filename: FileName }
1384 #[derive(Clone, PartialEq, Eq, Debug)]
1385 pub struct DistinctSources {
1386 pub begin: (FileName, BytePos),
1387 pub end: (FileName, BytePos)
1390 #[derive(Clone, PartialEq, Eq, Debug)]
1391 pub struct MalformedSourceMapPositions {
1393 pub source_len: usize,
1394 pub begin_pos: BytePos,
1395 pub end_pos: BytePos
1398 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1399 pub struct InnerSpan {
1405 pub fn new(start: usize, end: usize) -> InnerSpan {
1406 InnerSpan { start, end }
1410 // Given a slice of line start positions and a position, returns the index of
1411 // the line the position is on. Returns -1 if the position is located before
1413 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1414 match lines.binary_search(&pos) {
1415 Ok(line) => line as isize,
1416 Err(line) => line as isize - 1
1422 use super::{lookup_line, BytePos};
1425 fn test_lookup_line() {
1427 let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1429 assert_eq!(lookup_line(lines, BytePos(0)), -1);
1430 assert_eq!(lookup_line(lines, BytePos(3)), 0);
1431 assert_eq!(lookup_line(lines, BytePos(4)), 0);
1433 assert_eq!(lookup_line(lines, BytePos(16)), 0);
1434 assert_eq!(lookup_line(lines, BytePos(17)), 1);
1435 assert_eq!(lookup_line(lines, BytePos(18)), 1);
1437 assert_eq!(lookup_line(lines, BytePos(28)), 2);
1438 assert_eq!(lookup_line(lines, BytePos(29)), 2);