1 //! Source positions and related helper functions.
3 //! Important concepts in this module include:
5 //! - the *span*, represented by [`SpanData`] and related types;
6 //! - source code as represented by a [`SourceMap`]; and
7 //! - interned strings, represented by [`Symbol`]s, with some common symbols available statically in the [`sym`] module.
9 //! Unlike most compilers, the span contains not only the position in the source code, but also various other metadata,
10 //! such as the edition and macro hygiene. This metadata is stored in [`SyntaxContext`] and [`ExpnData`].
14 //! This API is completely unstable and subject to change.
16 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
17 #![feature(array_windows)]
19 #![feature(if_let_guard)]
20 #![feature(negative_impls)]
21 #![feature(min_specialization)]
22 #![feature(rustc_attrs)]
25 extern crate rustc_macros;
30 use rustc_data_structures::AtomicRef;
31 use rustc_macros::HashStable_Generic;
32 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
34 mod caching_source_map_view;
36 pub use self::caching_source_map_view::CachingSourceMapView;
37 use source_map::SourceMap;
42 use hygiene::Transparency;
43 pub use hygiene::{DesugaringKind, ExpnKind, MacroKind};
44 pub use hygiene::{ExpnData, ExpnHash, ExpnId, LocalExpnId, SyntaxContext};
45 use rustc_data_structures::stable_hasher::HashingControls;
47 use def_id::{CrateNum, DefId, DefPathHash, LocalDefId, LOCAL_CRATE};
50 pub use span_encoding::{Span, DUMMY_SP};
53 pub use symbol::{sym, Symbol};
55 mod analyze_source_file;
60 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
61 use rustc_data_structures::sync::{Lock, Lrc};
64 use std::cmp::{self, Ordering};
67 use std::ops::{Add, Range, Sub};
68 use std::path::{Path, PathBuf};
69 use std::str::FromStr;
82 // Per-session global variables: this struct is stored in thread-local storage
83 // in such a way that it is accessible without any kind of handle to all
84 // threads within the compilation session, but is not accessible outside the
86 pub struct SessionGlobals {
87 symbol_interner: symbol::Interner,
88 span_interner: Lock<span_encoding::SpanInterner>,
89 hygiene_data: Lock<hygiene::HygieneData>,
90 source_map: Lock<Option<Lrc<SourceMap>>>,
94 pub fn new(edition: Edition) -> SessionGlobals {
96 symbol_interner: symbol::Interner::fresh(),
97 span_interner: Lock::new(span_encoding::SpanInterner::default()),
98 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
99 source_map: Lock::new(None),
105 pub fn create_session_globals_then<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
107 !SESSION_GLOBALS.is_set(),
108 "SESSION_GLOBALS should never be overwritten! \
109 Use another thread if you need another SessionGlobals"
111 let session_globals = SessionGlobals::new(edition);
112 SESSION_GLOBALS.set(&session_globals, f)
116 pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R {
118 !SESSION_GLOBALS.is_set(),
119 "SESSION_GLOBALS should never be overwritten! \
120 Use another thread if you need another SessionGlobals"
122 SESSION_GLOBALS.set(session_globals, f)
126 pub fn create_default_session_if_not_set_then<R, F>(f: F) -> R
128 F: FnOnce(&SessionGlobals) -> R,
130 create_session_if_not_set_then(edition::DEFAULT_EDITION, f)
134 pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R
136 F: FnOnce(&SessionGlobals) -> R,
138 if !SESSION_GLOBALS.is_set() {
139 let session_globals = SessionGlobals::new(edition);
140 SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f))
142 SESSION_GLOBALS.with(f)
147 pub fn with_session_globals<R, F>(f: F) -> R
149 F: FnOnce(&SessionGlobals) -> R,
151 SESSION_GLOBALS.with(f)
155 pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R {
156 create_session_globals_then(edition::DEFAULT_EDITION, f)
159 // If this ever becomes non thread-local, `decode_syntax_context`
160 // and `decode_expn_id` will need to be updated to handle concurrent
162 scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals);
164 // FIXME: We should use this enum or something like it to get rid of the
165 // use of magic `/rust/1.x/...` paths across the board.
166 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)]
168 pub enum RealFileName {
170 /// For remapped paths (namely paths into libstd that have been mapped
171 /// to the appropriate spot on the local host's file system, and local file
172 /// system paths that have been remapped with `FilePathMapping`),
174 /// `local_path` is the (host-dependent) local path to the file. This is
175 /// None if the file was imported from another crate
176 local_path: Option<PathBuf>,
177 /// `virtual_name` is the stable path rustc will store internally within
179 virtual_name: PathBuf,
183 impl Hash for RealFileName {
184 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
185 // To prevent #70924 from happening again we should only hash the
186 // remapped (virtualized) path if that exists. This is because
187 // virtualized paths to sysroot crates (/rust/$hash or /rust/$version)
188 // remain stable even if the corresponding local_path changes
189 self.remapped_path_if_available().hash(state)
193 // This is functionally identical to #[derive(Encodable)], with the exception of
194 // an added assert statement
195 impl<S: Encoder> Encodable<S> for RealFileName {
196 fn encode(&self, encoder: &mut S) {
198 RealFileName::LocalPath(ref local_path) => encoder.emit_enum_variant(0, |encoder| {
199 local_path.encode(encoder);
202 RealFileName::Remapped { ref local_path, ref virtual_name } => encoder
203 .emit_enum_variant(1, |encoder| {
204 // For privacy and build reproducibility, we must not embed host-dependant path in artifacts
205 // if they have been remapped by --remap-path-prefix
206 assert!(local_path.is_none());
207 local_path.encode(encoder);
208 virtual_name.encode(encoder);
215 /// Returns the path suitable for reading from the file system on the local host,
216 /// if this information exists.
217 /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
218 pub fn local_path(&self) -> Option<&Path> {
220 RealFileName::LocalPath(p) => Some(p),
221 RealFileName::Remapped { local_path: p, virtual_name: _ } => {
222 p.as_ref().map(PathBuf::as_path)
227 /// Returns the path suitable for reading from the file system on the local host,
228 /// if this information exists.
229 /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
230 pub fn into_local_path(self) -> Option<PathBuf> {
232 RealFileName::LocalPath(p) => Some(p),
233 RealFileName::Remapped { local_path: p, virtual_name: _ } => p,
237 /// Returns the path suitable for embedding into build artifacts. This would still
238 /// be a local path if it has not been remapped. A remapped path will not correspond
239 /// to a valid file system path: see `local_path_if_available()` for something that
240 /// is more likely to return paths into the local host file system.
241 pub fn remapped_path_if_available(&self) -> &Path {
243 RealFileName::LocalPath(p)
244 | RealFileName::Remapped { local_path: _, virtual_name: p } => &p,
248 /// Returns the path suitable for reading from the file system on the local host,
249 /// if this information exists. Otherwise returns the remapped name.
250 /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
251 pub fn local_path_if_available(&self) -> &Path {
253 RealFileName::LocalPath(path)
254 | RealFileName::Remapped { local_path: None, virtual_name: path }
255 | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path,
259 pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> {
261 FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(),
262 FileNameDisplayPreference::Remapped => {
263 self.remapped_path_if_available().to_string_lossy()
269 /// Differentiates between real files and common virtual files.
270 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
271 #[derive(Decodable, Encodable)]
274 /// Call to `quote!`.
278 /// Hack in `src/librustc_ast/parse.rs`.
281 ProcMacroSourceCode(u64),
282 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
284 /// Strings provided as crate attributes in the CLI.
286 /// Custom sources for explicit parser calls from plugins and drivers.
288 DocTest(PathBuf, isize),
289 /// Post-substitution inline assembly from LLVM.
293 impl From<PathBuf> for FileName {
294 fn from(p: PathBuf) -> Self {
295 assert!(!p.to_string_lossy().ends_with('>'));
296 FileName::Real(RealFileName::LocalPath(p))
300 #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
301 pub enum FileNameDisplayPreference {
306 pub struct FileNameDisplay<'a> {
308 display_pref: FileNameDisplayPreference,
311 impl fmt::Display for FileNameDisplay<'_> {
312 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
316 write!(fmt, "{}", name.to_string_lossy(self.display_pref))
318 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
319 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
320 Anon(_) => write!(fmt, "<anon>"),
321 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
322 CfgSpec(_) => write!(fmt, "<cfgspec>"),
323 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
324 Custom(ref s) => write!(fmt, "<{}>", s),
325 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
326 InlineAsm(_) => write!(fmt, "<inline asm>"),
331 impl<'a> FileNameDisplay<'a> {
332 pub fn to_string_lossy(&self) -> Cow<'a, str> {
334 FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref),
335 _ => Cow::from(self.to_string()),
341 pub fn is_real(&self) -> bool {
347 | ProcMacroSourceCode(_)
353 | InlineAsm(_) => false,
357 pub fn prefer_remapped(&self) -> FileNameDisplay<'_> {
358 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped }
361 // This may include transient local filesystem information.
362 // Must not be embedded in build outputs.
363 pub fn prefer_local(&self) -> FileNameDisplay<'_> {
364 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local }
367 pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> {
368 FileNameDisplay { inner: self, display_pref }
371 pub fn macro_expansion_source_code(src: &str) -> FileName {
372 let mut hasher = StableHasher::new();
373 src.hash(&mut hasher);
374 FileName::MacroExpansion(hasher.finish())
377 pub fn anon_source_code(src: &str) -> FileName {
378 let mut hasher = StableHasher::new();
379 src.hash(&mut hasher);
380 FileName::Anon(hasher.finish())
383 pub fn proc_macro_source_code(src: &str) -> FileName {
384 let mut hasher = StableHasher::new();
385 src.hash(&mut hasher);
386 FileName::ProcMacroSourceCode(hasher.finish())
389 pub fn cfg_spec_source_code(src: &str) -> FileName {
390 let mut hasher = StableHasher::new();
391 src.hash(&mut hasher);
392 FileName::QuoteExpansion(hasher.finish())
395 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
396 let mut hasher = StableHasher::new();
397 src.hash(&mut hasher);
398 FileName::CliCrateAttr(hasher.finish())
401 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
402 FileName::DocTest(path, line)
405 pub fn inline_asm_source_code(src: &str) -> FileName {
406 let mut hasher = StableHasher::new();
407 src.hash(&mut hasher);
408 FileName::InlineAsm(hasher.finish())
412 /// Represents a span.
414 /// Spans represent a region of code, used for error reporting. Positions in spans
415 /// are *absolute* positions from the beginning of the [`SourceMap`], not positions
416 /// relative to [`SourceFile`]s. Methods on the `SourceMap` can be used to relate spans back
417 /// to the original source.
419 /// You must be careful if the span crosses more than one file, since you will not be
420 /// able to use many of the functions on spans in source_map and you cannot assume
421 /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the
422 /// [`BytePos`] range between files.
424 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
425 /// sent to other threads, but some pieces of performance infra run in a separate thread.
426 /// Using `Span` is generally preferred.
427 #[derive(Clone, Copy, Hash, PartialEq, Eq)]
428 pub struct SpanData {
431 /// Information about where the macro came from, if this piece of
432 /// code was created by a macro expansion.
433 pub ctxt: SyntaxContext,
434 pub parent: Option<LocalDefId>,
437 // Order spans by position in the file.
438 impl Ord for SpanData {
439 fn cmp(&self, other: &Self) -> Ordering {
444 // `LocalDefId` does not implement `Ord`.
445 // The other fields are enough to determine in-file order.
452 // `LocalDefId` does not implement `Ord`.
453 // The other fields are enough to determine in-file order.
457 (s_lo, s_hi, s_ctxt).cmp(&(o_lo, o_hi, o_ctxt))
461 impl PartialOrd for SpanData {
462 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
463 Some(self.cmp(other))
469 pub fn span(&self) -> Span {
470 Span::new(self.lo, self.hi, self.ctxt, self.parent)
473 pub fn with_lo(&self, lo: BytePos) -> Span {
474 Span::new(lo, self.hi, self.ctxt, self.parent)
477 pub fn with_hi(&self, hi: BytePos) -> Span {
478 Span::new(self.lo, hi, self.ctxt, self.parent)
481 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
482 Span::new(self.lo, self.hi, ctxt, self.parent)
485 pub fn with_parent(&self, parent: Option<LocalDefId>) -> Span {
486 Span::new(self.lo, self.hi, self.ctxt, parent)
488 /// Returns `true` if this is a dummy span with any hygienic context.
490 pub fn is_dummy(self) -> bool {
491 self.lo.0 == 0 && self.hi.0 == 0
493 /// Returns `true` if `self` fully encloses `other`.
494 pub fn contains(self, other: Self) -> bool {
495 self.lo <= other.lo && other.hi <= self.hi
499 // The interner is pointed to by a thread local value which is only set on the main thread
500 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
501 // to avoid panics and other errors, even though it would be memory safe to do so.
502 #[cfg(not(parallel_compiler))]
503 impl !Send for Span {}
504 #[cfg(not(parallel_compiler))]
505 impl !Sync for Span {}
507 impl PartialOrd for Span {
508 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
509 PartialOrd::partial_cmp(&self.data(), &rhs.data())
513 fn cmp(&self, rhs: &Self) -> Ordering {
514 Ord::cmp(&self.data(), &rhs.data())
520 pub fn lo(self) -> BytePos {
524 pub fn with_lo(self, lo: BytePos) -> Span {
525 self.data().with_lo(lo)
528 pub fn hi(self) -> BytePos {
532 pub fn with_hi(self, hi: BytePos) -> Span {
533 self.data().with_hi(hi)
536 pub fn ctxt(self) -> SyntaxContext {
537 self.data_untracked().ctxt
539 pub fn eq_ctxt(self, other: Span) -> bool {
540 self.data_untracked().ctxt == other.data_untracked().ctxt
543 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
544 self.data_untracked().with_ctxt(ctxt)
547 pub fn parent(self) -> Option<LocalDefId> {
551 pub fn with_parent(self, ctxt: Option<LocalDefId>) -> Span {
552 self.data().with_parent(ctxt)
555 /// Returns `true` if this is a dummy span with any hygienic context.
557 pub fn is_dummy(self) -> bool {
558 self.data_untracked().is_dummy()
561 /// Returns `true` if this span comes from a macro or desugaring.
563 pub fn from_expansion(self) -> bool {
564 self.ctxt() != SyntaxContext::root()
567 /// Returns `true` if `span` originates in a derive-macro's expansion.
568 pub fn in_derive_expansion(self) -> bool {
569 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
572 /// Gate suggestions that would not be appropriate in a context the user didn't write.
573 pub fn can_be_used_for_suggestions(self) -> bool {
574 !self.from_expansion()
575 // FIXME: If this span comes from a `derive` macro but it points at code the user wrote,
576 // the callsite span and the span will be pointing at different places. It also means that
577 // we can safely provide suggestions on this span.
578 || (matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
579 && self.parent_callsite().map(|p| (p.lo(), p.hi())) != Some((self.lo(), self.hi())))
583 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
584 Span::new(lo, hi, SyntaxContext::root(), None)
587 /// Returns a new span representing an empty span at the beginning of this span.
589 pub fn shrink_to_lo(self) -> Span {
590 let span = self.data_untracked();
591 span.with_hi(span.lo)
593 /// Returns a new span representing an empty span at the end of this span.
595 pub fn shrink_to_hi(self) -> Span {
596 let span = self.data_untracked();
597 span.with_lo(span.hi)
601 /// Returns `true` if `hi == lo`.
602 pub fn is_empty(self) -> bool {
603 let span = self.data_untracked();
607 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
608 pub fn substitute_dummy(self, other: Span) -> Span {
609 if self.is_dummy() { other } else { self }
612 /// Returns `true` if `self` fully encloses `other`.
613 pub fn contains(self, other: Span) -> bool {
614 let span = self.data();
615 let other = other.data();
619 /// Returns `true` if `self` touches `other`.
620 pub fn overlaps(self, other: Span) -> bool {
621 let span = self.data();
622 let other = other.data();
623 span.lo < other.hi && other.lo < span.hi
626 /// Returns `true` if the spans are equal with regards to the source text.
628 /// Use this instead of `==` when either span could be generated code,
629 /// and you only care that they point to the same bytes of source text.
630 pub fn source_equal(self, other: Span) -> bool {
631 let span = self.data();
632 let other = other.data();
633 span.lo == other.lo && span.hi == other.hi
636 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
637 pub fn trim_start(self, other: Span) -> Option<Span> {
638 let span = self.data();
639 let other = other.data();
640 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
643 /// Returns the source span -- this is either the supplied span, or the span for
644 /// the macro callsite that expanded to it.
645 pub fn source_callsite(self) -> Span {
646 let expn_data = self.ctxt().outer_expn_data();
647 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
650 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
652 pub fn parent_callsite(self) -> Option<Span> {
653 let expn_data = self.ctxt().outer_expn_data();
654 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
657 /// Walk down the expansion ancestors to find a span that's contained within `outer`.
658 pub fn find_ancestor_inside(mut self, outer: Span) -> Option<Span> {
659 while !outer.contains(self) {
660 self = self.parent_callsite()?;
665 /// Edition of the crate from which this span came.
666 pub fn edition(self) -> edition::Edition {
667 self.ctxt().edition()
671 pub fn rust_2015(self) -> bool {
672 self.edition() == edition::Edition::Edition2015
676 pub fn rust_2018(self) -> bool {
677 self.edition() >= edition::Edition::Edition2018
681 pub fn rust_2021(self) -> bool {
682 self.edition() >= edition::Edition::Edition2021
686 pub fn rust_2024(self) -> bool {
687 self.edition() >= edition::Edition::Edition2024
690 /// Returns the source callee.
692 /// Returns `None` if the supplied span has no expansion trace,
693 /// else returns the `ExpnData` for the macro definition
694 /// corresponding to the source callsite.
695 pub fn source_callee(self) -> Option<ExpnData> {
696 fn source_callee(expn_data: ExpnData) -> ExpnData {
697 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
698 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
700 let expn_data = self.ctxt().outer_expn_data();
701 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
704 /// Checks if a span is "internal" to a macro in which `#[unstable]`
705 /// items can be used (that is, a macro marked with
706 /// `#[allow_internal_unstable]`).
707 pub fn allows_unstable(self, feature: Symbol) -> bool {
710 .allow_internal_unstable
711 .map_or(false, |features| features.iter().any(|&f| f == feature))
714 /// Checks if this span arises from a compiler desugaring of kind `kind`.
715 pub fn is_desugaring(self, kind: DesugaringKind) -> bool {
716 match self.ctxt().outer_expn_data().kind {
717 ExpnKind::Desugaring(k) => k == kind,
722 /// Returns the compiler desugaring that created this span, or `None`
723 /// if this span is not from a desugaring.
724 pub fn desugaring_kind(self) -> Option<DesugaringKind> {
725 match self.ctxt().outer_expn_data().kind {
726 ExpnKind::Desugaring(k) => Some(k),
731 /// Checks if a span is "internal" to a macro in which `unsafe`
732 /// can be used without triggering the `unsafe_code` lint.
733 // (that is, a macro marked with `#[allow_internal_unsafe]`).
734 pub fn allows_unsafe(self) -> bool {
735 self.ctxt().outer_expn_data().allow_internal_unsafe
738 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
739 let mut prev_span = DUMMY_SP;
740 std::iter::from_fn(move || {
742 let expn_data = self.ctxt().outer_expn_data();
743 if expn_data.is_root() {
747 let is_recursive = expn_data.call_site.source_equal(prev_span);
750 self = expn_data.call_site;
752 // Don't print recursive invocations.
754 return Some(expn_data);
760 /// Returns a `Span` that would enclose both `self` and `end`.
764 /// self lorem ipsum end
765 /// ^^^^^^^^^^^^^^^^^^^^
767 pub fn to(self, end: Span) -> Span {
768 let span_data = self.data();
769 let end_data = end.data();
770 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
771 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
772 // have an incomplete span than a completely nonsensical one.
773 if span_data.ctxt != end_data.ctxt {
774 if span_data.ctxt == SyntaxContext::root() {
776 } else if end_data.ctxt == SyntaxContext::root() {
779 // Both spans fall within a macro.
780 // FIXME(estebank): check if it is the *same* macro.
783 cmp::min(span_data.lo, end_data.lo),
784 cmp::max(span_data.hi, end_data.hi),
785 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
786 if span_data.parent == end_data.parent { span_data.parent } else { None },
790 /// Returns a `Span` between the end of `self` to the beginning of `end`.
794 /// self lorem ipsum end
797 pub fn between(self, end: Span) -> Span {
798 let span = self.data();
799 let end = end.data();
803 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
804 if span.parent == end.parent { span.parent } else { None },
808 /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
812 /// self lorem ipsum end
813 /// ^^^^^^^^^^^^^^^^^
815 pub fn until(self, end: Span) -> Span {
816 // Most of this function's body is copied from `to`.
817 // We can't just do `self.to(end.shrink_to_lo())`,
818 // because to also does some magic where it uses min/max so
819 // it can handle overlapping spans. Some advanced mis-use of
820 // `until` with different ctxts makes this visible.
821 let span_data = self.data();
822 let end_data = end.data();
823 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
824 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
825 // have an incomplete span than a completely nonsensical one.
826 if span_data.ctxt != end_data.ctxt {
827 if span_data.ctxt == SyntaxContext::root() {
829 } else if end_data.ctxt == SyntaxContext::root() {
832 // Both spans fall within a macro.
833 // FIXME(estebank): check if it is the *same* macro.
838 if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
839 if span_data.parent == end_data.parent { span_data.parent } else { None },
843 pub fn from_inner(self, inner: InnerSpan) -> Span {
844 let span = self.data();
846 span.lo + BytePos::from_usize(inner.start),
847 span.lo + BytePos::from_usize(inner.end),
853 /// Equivalent of `Span::def_site` from the proc macro API,
854 /// except that the location is taken from the `self` span.
855 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
856 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
859 /// Equivalent of `Span::call_site` from the proc macro API,
860 /// except that the location is taken from the `self` span.
861 pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span {
862 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
865 /// Equivalent of `Span::mixed_site` from the proc macro API,
866 /// except that the location is taken from the `self` span.
867 pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span {
868 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
871 /// Produces a span with the same location as `self` and context produced by a macro with the
872 /// given ID and transparency, assuming that macro was defined directly and not produced by
873 /// some other macro (which is the case for built-in and procedural macros).
874 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
875 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
879 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
880 let span = self.data();
881 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
885 pub fn remove_mark(&mut self) -> ExpnId {
886 let mut span = self.data();
887 let mark = span.ctxt.remove_mark();
888 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
893 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
894 let mut span = self.data();
895 let mark = span.ctxt.adjust(expn_id);
896 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
901 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
902 let mut span = self.data();
903 let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
904 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
909 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
910 let mut span = self.data();
911 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
912 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
917 pub fn reverse_glob_adjust(
921 ) -> Option<Option<ExpnId>> {
922 let mut span = self.data();
923 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
924 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
929 pub fn normalize_to_macros_2_0(self) -> Span {
930 let span = self.data();
931 span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
935 pub fn normalize_to_macro_rules(self) -> Span {
936 let span = self.data();
937 span.with_ctxt(span.ctxt.normalize_to_macro_rules())
941 impl Default for Span {
942 fn default() -> Self {
947 impl<E: Encoder> Encodable<E> for Span {
948 default fn encode(&self, s: &mut E) {
949 let span = self.data();
954 impl<D: Decoder> Decodable<D> for Span {
955 default fn decode(s: &mut D) -> Span {
956 let lo = Decodable::decode(s);
957 let hi = Decodable::decode(s);
959 Span::new(lo, hi, SyntaxContext::root(), None)
963 /// Calls the provided closure, using the provided `SourceMap` to format
964 /// any spans that are debug-printed during the closure's execution.
966 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
967 /// (see `rustc_interface::callbacks::span_debug1`). However, some parts
968 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
969 /// a `TyCtxt` is available. In this case, we fall back to
970 /// the `SourceMap` provided to this function. If that is not available,
971 /// we fall back to printing the raw `Span` field values.
972 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
973 with_session_globals(|session_globals| {
974 *session_globals.source_map.borrow_mut() = Some(source_map);
976 struct ClearSourceMap;
977 impl Drop for ClearSourceMap {
979 with_session_globals(|session_globals| {
980 session_globals.source_map.borrow_mut().take();
985 let _guard = ClearSourceMap;
989 impl fmt::Debug for Span {
990 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
991 with_session_globals(|session_globals| {
992 if let Some(source_map) = &*session_globals.source_map.borrow() {
993 write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(*self), self.ctxt())
995 f.debug_struct("Span")
996 .field("lo", &self.lo())
997 .field("hi", &self.hi())
998 .field("ctxt", &self.ctxt())
1005 impl fmt::Debug for SpanData {
1006 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1007 fmt::Debug::fmt(&Span::new(self.lo, self.hi, self.ctxt, self.parent), f)
1011 /// Identifies an offset of a multi-byte character in a `SourceFile`.
1012 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1013 pub struct MultiByteChar {
1014 /// The absolute offset of the character in the `SourceMap`.
1016 /// The number of bytes, `>= 2`.
1020 /// Identifies an offset of a non-narrow character in a `SourceFile`.
1021 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1022 pub enum NonNarrowChar {
1023 /// Represents a zero-width character.
1025 /// Represents a wide (full-width) character.
1027 /// Represents a tab character, represented visually with a width of 4 characters.
1031 impl NonNarrowChar {
1032 fn new(pos: BytePos, width: usize) -> Self {
1034 0 => NonNarrowChar::ZeroWidth(pos),
1035 2 => NonNarrowChar::Wide(pos),
1036 4 => NonNarrowChar::Tab(pos),
1037 _ => panic!("width {} given for non-narrow character", width),
1041 /// Returns the absolute offset of the character in the `SourceMap`.
1042 pub fn pos(&self) -> BytePos {
1044 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
1048 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
1049 pub fn width(&self) -> usize {
1051 NonNarrowChar::ZeroWidth(_) => 0,
1052 NonNarrowChar::Wide(_) => 2,
1053 NonNarrowChar::Tab(_) => 4,
1058 impl Add<BytePos> for NonNarrowChar {
1061 fn add(self, rhs: BytePos) -> Self {
1063 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
1064 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
1065 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
1070 impl Sub<BytePos> for NonNarrowChar {
1073 fn sub(self, rhs: BytePos) -> Self {
1075 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
1076 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
1077 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
1082 /// Identifies an offset of a character that was normalized away from `SourceFile`.
1083 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1084 pub struct NormalizedPos {
1085 /// The absolute offset of the character in the `SourceMap`.
1087 /// The difference between original and normalized string at position.
1091 #[derive(PartialEq, Eq, Clone, Debug)]
1092 pub enum ExternalSource {
1093 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
1096 kind: ExternalSourceKind,
1097 /// This SourceFile's byte-offset within the source_map of its original crate.
1098 original_start_pos: BytePos,
1099 /// The end of this SourceFile within the source_map of its original crate.
1100 original_end_pos: BytePos,
1104 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1105 #[derive(PartialEq, Eq, Clone, Debug)]
1106 pub enum ExternalSourceKind {
1107 /// The external source has been loaded already.
1108 Present(Lrc<String>),
1109 /// No attempt has been made to load the external source.
1111 /// A failed attempt has been made to load the external source.
1116 impl ExternalSource {
1117 pub fn get_source(&self) -> Option<&Lrc<String>> {
1119 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1126 pub struct OffsetOverflowError;
1128 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1129 #[derive(HashStable_Generic)]
1130 pub enum SourceFileHashAlgorithm {
1136 impl FromStr for SourceFileHashAlgorithm {
1139 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1141 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1142 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1143 "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1149 /// The hash of the on-disk source file used for debug info.
1150 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
1151 #[derive(HashStable_Generic, Encodable, Decodable)]
1152 pub struct SourceFileHash {
1153 pub kind: SourceFileHashAlgorithm,
1157 impl SourceFileHash {
1158 pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1159 let mut hash = SourceFileHash { kind, value: Default::default() };
1160 let len = hash.hash_len();
1161 let value = &mut hash.value[..len];
1162 let data = src.as_bytes();
1164 SourceFileHashAlgorithm::Md5 => {
1165 value.copy_from_slice(&Md5::digest(data));
1167 SourceFileHashAlgorithm::Sha1 => {
1168 value.copy_from_slice(&Sha1::digest(data));
1170 SourceFileHashAlgorithm::Sha256 => {
1171 value.copy_from_slice(&Sha256::digest(data));
1177 /// Check if the stored hash matches the hash of the string.
1178 pub fn matches(&self, src: &str) -> bool {
1179 Self::new(self.kind, src) == *self
1182 /// The bytes of the hash.
1183 pub fn hash_bytes(&self) -> &[u8] {
1184 let len = self.hash_len();
1188 fn hash_len(&self) -> usize {
1190 SourceFileHashAlgorithm::Md5 => 16,
1191 SourceFileHashAlgorithm::Sha1 => 20,
1192 SourceFileHashAlgorithm::Sha256 => 32,
1197 #[derive(HashStable_Generic)]
1198 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug, Encodable, Decodable)]
1199 pub enum DebuggerVisualizerType {
1204 /// A single debugger visualizer file.
1205 #[derive(HashStable_Generic)]
1206 #[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable)]
1207 pub struct DebuggerVisualizerFile {
1208 /// The complete debugger visualizer source.
1210 /// Indicates which visualizer type this targets.
1211 pub visualizer_type: DebuggerVisualizerType,
1214 impl DebuggerVisualizerFile {
1215 pub fn new(src: Arc<[u8]>, visualizer_type: DebuggerVisualizerType) -> Self {
1216 DebuggerVisualizerFile { src, visualizer_type }
1221 pub enum SourceFileLines {
1222 /// The source file lines, in decoded (random-access) form.
1223 Lines(Vec<BytePos>),
1225 /// The source file lines, in undecoded difference list form.
1226 Diffs(SourceFileDiffs),
1229 impl SourceFileLines {
1230 pub fn is_lines(&self) -> bool {
1231 matches!(self, SourceFileLines::Lines(_))
1235 /// The source file lines in difference list form. This matches the form
1236 /// used within metadata, which saves space by exploiting the fact that the
1237 /// lines list is sorted and individual lines are usually not that long.
1239 /// We read it directly from metadata and only decode it into `Lines` form
1240 /// when necessary. This is a significant performance win, especially for
1241 /// small crates where very little of `std`'s metadata is used.
1243 pub struct SourceFileDiffs {
1244 /// Position of the first line. Note that this is always encoded as a
1245 /// `BytePos` because it is often much larger than any of the
1247 line_start: BytePos,
1249 /// Always 1, 2, or 4. Always as small as possible, while being big
1250 /// enough to hold the length of the longest line in the source file.
1251 /// The 1 case is by far the most common.
1252 bytes_per_diff: usize,
1254 /// The number of diffs encoded in `raw_diffs`. Always one less than
1255 /// the number of lines in the source file.
1258 /// The diffs in "raw" form. Each segment of `bytes_per_diff` length
1259 /// encodes one little-endian diff. Note that they aren't LEB128
1260 /// encoded. This makes for much faster decoding. Besides, the
1261 /// bytes_per_diff==1 case is by far the most common, and LEB128
1262 /// encoding has no effect on that case.
1266 /// A single source in the [`SourceMap`].
1268 pub struct SourceFile {
1269 /// The name of the file that the source came from. Source that doesn't
1270 /// originate from files has names between angle brackets by convention
1271 /// (e.g., `<anon>`).
1273 /// The complete source code.
1274 pub src: Option<Lrc<String>>,
1275 /// The source code's hash.
1276 pub src_hash: SourceFileHash,
1277 /// The external source code (used for external crates, which will have a `None`
1278 /// value as `self.src`.
1279 pub external_src: Lock<ExternalSource>,
1280 /// The start position of this source in the `SourceMap`.
1281 pub start_pos: BytePos,
1282 /// The end position of this source in the `SourceMap`.
1283 pub end_pos: BytePos,
1284 /// Locations of lines beginnings in the source code.
1285 pub lines: Lock<SourceFileLines>,
1286 /// Locations of multi-byte characters in the source code.
1287 pub multibyte_chars: Vec<MultiByteChar>,
1288 /// Width of characters that are not narrow in the source code.
1289 pub non_narrow_chars: Vec<NonNarrowChar>,
1290 /// Locations of characters removed during normalization.
1291 pub normalized_pos: Vec<NormalizedPos>,
1292 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1293 pub name_hash: u128,
1294 /// Indicates which crate this `SourceFile` was imported from.
1298 impl<S: Encoder> Encodable<S> for SourceFile {
1299 fn encode(&self, s: &mut S) {
1300 self.name.encode(s);
1301 self.src_hash.encode(s);
1302 self.start_pos.encode(s);
1303 self.end_pos.encode(s);
1305 // We are always in `Lines` form by the time we reach here.
1306 assert!(self.lines.borrow().is_lines());
1307 self.lines(|lines| {
1308 // Store the length.
1309 s.emit_u32(lines.len() as u32);
1311 // Compute and store the difference list.
1312 if lines.len() != 0 {
1313 let max_line_length = if lines.len() == 1 {
1318 .map(|&[fst, snd]| snd - fst)
1319 .map(|bp| bp.to_usize())
1324 let bytes_per_diff: usize = match max_line_length {
1326 0x100..=0xFFFF => 2,
1330 // Encode the number of bytes used per diff.
1331 s.emit_u8(bytes_per_diff as u8);
1333 // Encode the first element.
1336 // Encode the difference list.
1337 let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst);
1338 let num_diffs = lines.len() - 1;
1340 match bytes_per_diff {
1342 raw_diffs = Vec::with_capacity(num_diffs);
1343 for diff in diff_iter {
1344 raw_diffs.push(diff.0 as u8);
1348 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
1349 for diff in diff_iter {
1350 raw_diffs.extend_from_slice(&(diff.0 as u16).to_le_bytes());
1354 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
1355 for diff in diff_iter {
1356 raw_diffs.extend_from_slice(&(diff.0 as u32).to_le_bytes());
1359 _ => unreachable!(),
1361 s.emit_raw_bytes(&raw_diffs);
1365 self.multibyte_chars.encode(s);
1366 self.non_narrow_chars.encode(s);
1367 self.name_hash.encode(s);
1368 self.normalized_pos.encode(s);
1369 self.cnum.encode(s);
1373 impl<D: Decoder> Decodable<D> for SourceFile {
1374 fn decode(d: &mut D) -> SourceFile {
1375 let name: FileName = Decodable::decode(d);
1376 let src_hash: SourceFileHash = Decodable::decode(d);
1377 let start_pos: BytePos = Decodable::decode(d);
1378 let end_pos: BytePos = Decodable::decode(d);
1380 let num_lines: u32 = Decodable::decode(d);
1382 // Read the number of bytes used per diff.
1383 let bytes_per_diff = d.read_u8() as usize;
1385 // Read the first element.
1386 let line_start: BytePos = Decodable::decode(d);
1388 // Read the difference list.
1389 let num_diffs = num_lines as usize - 1;
1390 let raw_diffs = d.read_raw_bytes(bytes_per_diff * num_diffs).to_vec();
1391 SourceFileLines::Diffs(SourceFileDiffs {
1398 SourceFileLines::Lines(vec![])
1401 let multibyte_chars: Vec<MultiByteChar> = Decodable::decode(d);
1402 let non_narrow_chars: Vec<NonNarrowChar> = Decodable::decode(d);
1403 let name_hash: u128 = Decodable::decode(d);
1404 let normalized_pos: Vec<NormalizedPos> = Decodable::decode(d);
1405 let cnum: CrateNum = Decodable::decode(d);
1412 // Unused - the metadata decoder will construct
1413 // a new SourceFile, filling in `external_src` properly
1414 external_src: Lock::new(ExternalSource::Unneeded),
1415 lines: Lock::new(lines),
1425 impl fmt::Debug for SourceFile {
1426 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1427 write!(fmt, "SourceFile({:?})", self.name)
1436 hash_kind: SourceFileHashAlgorithm,
1438 // Compute the file hash before any normalization.
1439 let src_hash = SourceFileHash::new(hash_kind, &src);
1440 let normalized_pos = normalize_src(&mut src, start_pos);
1443 let mut hasher: StableHasher = StableHasher::new();
1444 name.hash(&mut hasher);
1445 hasher.finish::<u128>()
1447 let end_pos = start_pos.to_usize() + src.len();
1448 assert!(end_pos <= u32::MAX as usize);
1450 let (lines, multibyte_chars, non_narrow_chars) =
1451 analyze_source_file::analyze_source_file(&src, start_pos);
1455 src: Some(Lrc::new(src)),
1457 external_src: Lock::new(ExternalSource::Unneeded),
1459 end_pos: Pos::from_usize(end_pos),
1460 lines: Lock::new(SourceFileLines::Lines(lines)),
1469 pub fn lines<F, R>(&self, f: F) -> R
1471 F: FnOnce(&[BytePos]) -> R,
1473 let mut guard = self.lines.borrow_mut();
1475 SourceFileLines::Lines(lines) => f(lines),
1476 SourceFileLines::Diffs(SourceFileDiffs {
1482 // Convert from "diffs" form to "lines" form.
1483 let num_lines = num_diffs + 1;
1484 let mut lines = Vec::with_capacity(num_lines);
1485 lines.push(line_start);
1487 assert_eq!(*num_diffs, raw_diffs.len() / bytes_per_diff);
1488 match bytes_per_diff {
1490 lines.extend(raw_diffs.into_iter().map(|&diff| {
1491 line_start = line_start + BytePos(diff as u32);
1496 lines.extend((0..*num_diffs).map(|i| {
1497 let pos = bytes_per_diff * i;
1498 let bytes = [raw_diffs[pos], raw_diffs[pos + 1]];
1499 let diff = u16::from_le_bytes(bytes);
1500 line_start = line_start + BytePos(diff as u32);
1505 lines.extend((0..*num_diffs).map(|i| {
1506 let pos = bytes_per_diff * i;
1513 let diff = u32::from_le_bytes(bytes);
1514 line_start = line_start + BytePos(diff);
1518 _ => unreachable!(),
1520 let res = f(&lines);
1521 *guard = SourceFileLines::Lines(lines);
1527 /// Returns the `BytePos` of the beginning of the current line.
1528 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1529 let line_index = self.lookup_line(pos).unwrap();
1530 self.lines(|lines| lines[line_index])
1533 /// Add externally loaded source.
1534 /// If the hash of the input doesn't match or no input is supplied via None,
1535 /// it is interpreted as an error and the corresponding enum variant is set.
1536 /// The return value signifies whether some kind of source is present.
1537 pub fn add_external_src<F>(&self, get_src: F) -> bool
1539 F: FnOnce() -> Option<String>,
1542 *self.external_src.borrow(),
1543 ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1545 let src = get_src();
1546 let mut external_src = self.external_src.borrow_mut();
1547 // Check that no-one else have provided the source while we were getting it
1548 if let ExternalSource::Foreign {
1549 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1550 } = &mut *external_src
1552 if let Some(mut src) = src {
1553 // The src_hash needs to be computed on the pre-normalized src.
1554 if self.src_hash.matches(&src) {
1555 normalize_src(&mut src, BytePos::from_usize(0));
1556 *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1560 *src_kind = ExternalSourceKind::AbsentErr;
1565 self.src.is_some() || external_src.get_source().is_some()
1568 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1572 /// Gets a line from the list of pre-computed line-beginnings.
1573 /// The line number here is 0-based.
1574 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1575 fn get_until_newline(src: &str, begin: usize) -> &str {
1576 // We can't use `lines.get(line_number+1)` because we might
1577 // be parsing when we call this function and thus the current
1578 // line is the last one we have line info for.
1579 let slice = &src[begin..];
1580 match slice.find('\n') {
1581 Some(e) => &slice[..e],
1587 let line = self.lines(|lines| lines.get(line_number).copied())?;
1588 let begin: BytePos = line - self.start_pos;
1592 if let Some(ref src) = self.src {
1593 Some(Cow::from(get_until_newline(src, begin)))
1594 } else if let Some(src) = self.external_src.borrow().get_source() {
1595 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1601 pub fn is_real_file(&self) -> bool {
1606 pub fn is_imported(&self) -> bool {
1610 pub fn count_lines(&self) -> usize {
1611 self.lines(|lines| lines.len())
1614 /// Finds the line containing the given position. The return value is the
1615 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1616 /// number. If the source_file is empty or the position is located before the
1617 /// first line, `None` is returned.
1618 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1619 self.lines(|lines| match lines.binary_search(&pos) {
1620 Ok(idx) => Some(idx),
1622 Err(idx) => Some(idx - 1),
1626 pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
1627 if self.is_empty() {
1628 return self.start_pos..self.end_pos;
1631 self.lines(|lines| {
1632 assert!(line_index < lines.len());
1633 if line_index == (lines.len() - 1) {
1634 lines[line_index]..self.end_pos
1636 lines[line_index]..lines[line_index + 1]
1641 /// Returns whether or not the file contains the given `SourceMap` byte
1642 /// position. The position one past the end of the file is considered to be
1643 /// contained by the file. This implies that files for which `is_empty`
1644 /// returns true still contain one byte position according to this function.
1646 pub fn contains(&self, byte_pos: BytePos) -> bool {
1647 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1651 pub fn is_empty(&self) -> bool {
1652 self.start_pos == self.end_pos
1655 /// Calculates the original byte position relative to the start of the file
1656 /// based on the given byte position.
1657 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1658 // Diff before any records is 0. Otherwise use the previously recorded
1659 // diff as that applies to the following characters until a new diff
1661 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1662 Ok(i) => self.normalized_pos[i].diff,
1663 Err(i) if i == 0 => 0,
1664 Err(i) => self.normalized_pos[i - 1].diff,
1667 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1670 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1671 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1672 // The number of extra bytes due to multibyte chars in the `SourceFile`.
1673 let mut total_extra_bytes = 0;
1675 for mbc in self.multibyte_chars.iter() {
1676 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1678 // Every character is at least one byte, so we only
1679 // count the actual extra bytes.
1680 total_extra_bytes += mbc.bytes as u32 - 1;
1681 // We should never see a byte position in the middle of a
1683 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1689 assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1690 CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1693 /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1694 /// given `BytePos`.
1695 pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1696 let chpos = self.bytepos_to_file_charpos(pos);
1697 match self.lookup_line(pos) {
1699 let line = a + 1; // Line numbers start at 1
1700 let linebpos = self.lines(|lines| lines[a]);
1701 let linechpos = self.bytepos_to_file_charpos(linebpos);
1702 let col = chpos - linechpos;
1703 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1704 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1705 debug!("byte is on line: {}", line);
1706 assert!(chpos >= linechpos);
1713 /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1714 /// column offset when displayed, for a given `BytePos`.
1715 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1716 let (line, col_or_chpos) = self.lookup_file_pos(pos);
1718 let col = col_or_chpos;
1719 let linebpos = self.lines(|lines| lines[line - 1]);
1721 let start_width_idx = self
1723 .binary_search_by_key(&linebpos, |x| x.pos())
1724 .unwrap_or_else(|x| x);
1725 let end_width_idx = self
1727 .binary_search_by_key(&pos, |x| x.pos())
1728 .unwrap_or_else(|x| x);
1729 let special_chars = end_width_idx - start_width_idx;
1730 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1734 col.0 - special_chars + non_narrow
1736 (line, col, col_display)
1738 let chpos = col_or_chpos;
1740 let end_width_idx = self
1742 .binary_search_by_key(&pos, |x| x.pos())
1743 .unwrap_or_else(|x| x);
1744 let non_narrow: usize =
1745 self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1746 chpos.0 - end_width_idx + non_narrow
1748 (0, chpos, col_display)
1753 /// Normalizes the source code and records the normalizations.
1754 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1755 let mut normalized_pos = vec![];
1756 remove_bom(src, &mut normalized_pos);
1757 normalize_newlines(src, &mut normalized_pos);
1759 // Offset all the positions by start_pos to match the final file positions.
1760 for np in &mut normalized_pos {
1761 np.pos.0 += start_pos.0;
1767 /// Removes UTF-8 BOM, if any.
1768 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1769 if src.starts_with('\u{feff}') {
1771 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1775 /// Replaces `\r\n` with `\n` in-place in `src`.
1777 /// Returns error if there's a lone `\r` in the string.
1778 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1779 if !src.as_bytes().contains(&b'\r') {
1783 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1784 // While we *can* call `as_mut_vec` and do surgery on the live string
1785 // directly, let's rather steal the contents of `src`. This makes the code
1786 // safe even if a panic occurs.
1788 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1789 let mut gap_len = 0;
1790 let mut tail = buf.as_mut_slice();
1792 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1794 let idx = match find_crlf(&tail[gap_len..]) {
1796 Some(idx) => idx + gap_len,
1798 tail.copy_within(gap_len..idx, 0);
1799 tail = &mut tail[idx - gap_len..];
1800 if tail.len() == gap_len {
1803 cursor += idx - gap_len;
1805 normalized_pos.push(NormalizedPos {
1806 pos: BytePos::from_usize(cursor + 1),
1807 diff: original_gap + gap_len as u32,
1811 // Account for removed `\r`.
1812 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1813 let new_len = buf.len() - gap_len;
1815 buf.set_len(new_len);
1816 *src = String::from_utf8_unchecked(buf);
1819 fn find_crlf(src: &[u8]) -> Option<usize> {
1820 let mut search_idx = 0;
1821 while let Some(idx) = find_cr(&src[search_idx..]) {
1822 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1823 search_idx += idx + 1;
1826 return Some(search_idx + idx);
1831 fn find_cr(src: &[u8]) -> Option<usize> {
1832 src.iter().position(|&b| b == b'\r')
1836 // _____________________________________________________________________________
1837 // Pos, BytePos, CharPos
1841 fn from_usize(n: usize) -> Self;
1842 fn to_usize(&self) -> usize;
1843 fn from_u32(n: u32) -> Self;
1844 fn to_u32(&self) -> u32;
1847 macro_rules! impl_pos {
1851 $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1856 $vis struct $ident($inner_vis $inner_ty);
1858 impl Pos for $ident {
1860 fn from_usize(n: usize) -> $ident {
1861 $ident(n as $inner_ty)
1865 fn to_usize(&self) -> usize {
1870 fn from_u32(n: u32) -> $ident {
1871 $ident(n as $inner_ty)
1875 fn to_u32(&self) -> u32 {
1880 impl Add for $ident {
1881 type Output = $ident;
1884 fn add(self, rhs: $ident) -> $ident {
1885 $ident(self.0 + rhs.0)
1889 impl Sub for $ident {
1890 type Output = $ident;
1893 fn sub(self, rhs: $ident) -> $ident {
1894 $ident(self.0 - rhs.0)
1904 /// Keep this small (currently 32-bits), as AST contains a lot of them.
1905 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1906 pub struct BytePos(pub u32);
1908 /// A character offset.
1910 /// Because of multibyte UTF-8 characters, a byte offset
1911 /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`]
1912 /// values to `CharPos` values as necessary.
1913 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1914 pub struct CharPos(pub usize);
1917 impl<S: Encoder> Encodable<S> for BytePos {
1918 fn encode(&self, s: &mut S) {
1923 impl<D: Decoder> Decodable<D> for BytePos {
1924 fn decode(d: &mut D) -> BytePos {
1925 BytePos(d.read_u32())
1929 // _____________________________________________________________________________
1930 // Loc, SourceFileAndLine, SourceFileAndBytePos
1933 /// A source code location used for error reporting.
1934 #[derive(Debug, Clone)]
1936 /// Information about the original source.
1937 pub file: Lrc<SourceFile>,
1938 /// The (1-based) line number.
1940 /// The (0-based) column offset.
1942 /// The (0-based) column offset when displayed.
1943 pub col_display: usize,
1946 // Used to be structural records.
1948 pub struct SourceFileAndLine {
1949 pub sf: Lrc<SourceFile>,
1950 /// Index of line, starting from 0.
1954 pub struct SourceFileAndBytePos {
1955 pub sf: Lrc<SourceFile>,
1959 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1960 pub struct LineInfo {
1961 /// Index of line, starting from 0.
1962 pub line_index: usize,
1964 /// Column in line where span begins, starting from 0.
1965 pub start_col: CharPos,
1967 /// Column in line where span ends, starting from 0, exclusive.
1968 pub end_col: CharPos,
1971 pub struct FileLines {
1972 pub file: Lrc<SourceFile>,
1973 pub lines: Vec<LineInfo>,
1976 pub static SPAN_TRACK: AtomicRef<fn(LocalDefId)> = AtomicRef::new(&((|_| {}) as fn(_)));
1978 // _____________________________________________________________________________
1979 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1982 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1984 #[derive(Clone, PartialEq, Eq, Debug)]
1985 pub enum SpanLinesError {
1986 DistinctSources(DistinctSources),
1989 #[derive(Clone, PartialEq, Eq, Debug)]
1990 pub enum SpanSnippetError {
1991 IllFormedSpan(Span),
1992 DistinctSources(DistinctSources),
1993 MalformedForSourcemap(MalformedSourceMapPositions),
1994 SourceNotAvailable { filename: FileName },
1997 #[derive(Clone, PartialEq, Eq, Debug)]
1998 pub struct DistinctSources {
1999 pub begin: (FileName, BytePos),
2000 pub end: (FileName, BytePos),
2003 #[derive(Clone, PartialEq, Eq, Debug)]
2004 pub struct MalformedSourceMapPositions {
2006 pub source_len: usize,
2007 pub begin_pos: BytePos,
2008 pub end_pos: BytePos,
2011 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
2012 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2013 pub struct InnerSpan {
2019 pub fn new(start: usize, end: usize) -> InnerSpan {
2020 InnerSpan { start, end }
2024 /// Requirements for a `StableHashingContext` to be used in this crate.
2026 /// This is a hack to allow using the [`HashStable_Generic`] derive macro
2027 /// instead of implementing everything in rustc_middle.
2028 pub trait HashStableContext {
2029 fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
2030 fn hash_spans(&self) -> bool;
2031 /// Accesses `sess.opts.unstable_opts.incremental_ignore_spans` since
2032 /// we don't have easy access to a `Session`
2033 fn unstable_opts_incremental_ignore_spans(&self) -> bool;
2034 fn def_span(&self, def_id: LocalDefId) -> Span;
2035 fn span_data_to_lines_and_cols(
2038 ) -> Option<(Lrc<SourceFile>, usize, BytePos, usize, BytePos)>;
2039 fn hashing_controls(&self) -> HashingControls;
2042 impl<CTX> HashStable<CTX> for Span
2044 CTX: HashStableContext,
2046 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
2047 /// fields (that would be similar to hashing pointers, since those are just
2048 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
2049 /// triple, which stays the same even if the containing `SourceFile` has moved
2050 /// within the `SourceMap`.
2052 /// Also note that we are hashing byte offsets for the column, not unicode
2053 /// codepoint offsets. For the purpose of the hash that's sufficient.
2054 /// Also, hashing filenames is expensive so we avoid doing it twice when the
2055 /// span starts and ends in the same file, which is almost always the case.
2056 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
2057 const TAG_VALID_SPAN: u8 = 0;
2058 const TAG_INVALID_SPAN: u8 = 1;
2059 const TAG_RELATIVE_SPAN: u8 = 2;
2061 if !ctx.hash_spans() {
2065 let span = self.data_untracked();
2066 span.ctxt.hash_stable(ctx, hasher);
2067 span.parent.hash_stable(ctx, hasher);
2069 if span.is_dummy() {
2070 Hash::hash(&TAG_INVALID_SPAN, hasher);
2074 if let Some(parent) = span.parent {
2075 let def_span = ctx.def_span(parent).data_untracked();
2076 if def_span.contains(span) {
2077 // This span is enclosed in a definition: only hash the relative position.
2078 Hash::hash(&TAG_RELATIVE_SPAN, hasher);
2079 (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher);
2080 (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher);
2085 // If this is not an empty or invalid span, we want to hash the last
2086 // position that belongs to it, as opposed to hashing the first
2087 // position past it.
2088 let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span) else {
2089 Hash::hash(&TAG_INVALID_SPAN, hasher);
2093 Hash::hash(&TAG_VALID_SPAN, hasher);
2094 // We truncate the stable ID hash and line and column numbers. The chances
2095 // of causing a collision this way should be minimal.
2096 Hash::hash(&(file.name_hash as u64), hasher);
2098 // Hash both the length and the end location (line/column) of a span. If we
2099 // hash only the length, for example, then two otherwise equal spans with
2100 // different end locations will have the same hash. This can cause a problem
2101 // during incremental compilation wherein a previous result for a query that
2102 // depends on the end location of a span will be incorrectly reused when the
2103 // end location of the span it depends on has changed (see issue #74890). A
2104 // similar analysis applies if some query depends specifically on the length
2105 // of the span, but we only hash the end location. So hash both.
2107 let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
2108 let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
2109 let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
2110 let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
2111 let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
2112 let len = (span.hi - span.lo).0;
2113 Hash::hash(&col_line, hasher);
2114 Hash::hash(&len, hasher);