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)]
23 #![allow(rustc::potential_query_instability)]
26 extern crate rustc_macros;
31 use rustc_data_structures::AtomicRef;
32 use rustc_macros::HashStable_Generic;
33 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
35 mod caching_source_map_view;
37 pub use self::caching_source_map_view::CachingSourceMapView;
38 use source_map::SourceMap;
43 use hygiene::Transparency;
44 pub use hygiene::{DesugaringKind, ExpnKind, MacroKind};
45 pub use hygiene::{ExpnData, ExpnHash, ExpnId, LocalExpnId, SyntaxContext};
46 use rustc_data_structures::stable_hasher::HashingControls;
48 use def_id::{CrateNum, DefId, DefPathHash, LocalDefId, LOCAL_CRATE};
51 pub use span_encoding::{Span, DUMMY_SP};
54 pub use symbol::{sym, Symbol};
56 mod analyze_source_file;
61 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
62 use rustc_data_structures::sync::{Lock, Lrc};
65 use std::cmp::{self, Ordering};
68 use std::ops::{Add, Range, Sub};
69 use std::path::{Path, PathBuf};
70 use std::str::FromStr;
83 // Per-session global variables: this struct is stored in thread-local storage
84 // in such a way that it is accessible without any kind of handle to all
85 // threads within the compilation session, but is not accessible outside the
87 pub struct SessionGlobals {
88 symbol_interner: symbol::Interner,
89 span_interner: Lock<span_encoding::SpanInterner>,
90 hygiene_data: Lock<hygiene::HygieneData>,
91 source_map: Lock<Option<Lrc<SourceMap>>>,
95 pub fn new(edition: Edition) -> SessionGlobals {
97 symbol_interner: symbol::Interner::fresh(),
98 span_interner: Lock::new(span_encoding::SpanInterner::default()),
99 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
100 source_map: Lock::new(None),
106 pub fn create_session_globals_then<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
108 !SESSION_GLOBALS.is_set(),
109 "SESSION_GLOBALS should never be overwritten! \
110 Use another thread if you need another SessionGlobals"
112 let session_globals = SessionGlobals::new(edition);
113 SESSION_GLOBALS.set(&session_globals, f)
117 pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R {
119 !SESSION_GLOBALS.is_set(),
120 "SESSION_GLOBALS should never be overwritten! \
121 Use another thread if you need another SessionGlobals"
123 SESSION_GLOBALS.set(session_globals, f)
127 pub fn create_default_session_if_not_set_then<R, F>(f: F) -> R
129 F: FnOnce(&SessionGlobals) -> R,
131 create_session_if_not_set_then(edition::DEFAULT_EDITION, f)
135 pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R
137 F: FnOnce(&SessionGlobals) -> R,
139 if !SESSION_GLOBALS.is_set() {
140 let session_globals = SessionGlobals::new(edition);
141 SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f))
143 SESSION_GLOBALS.with(f)
148 pub fn with_session_globals<R, F>(f: F) -> R
150 F: FnOnce(&SessionGlobals) -> R,
152 SESSION_GLOBALS.with(f)
156 pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R {
157 create_session_globals_then(edition::DEFAULT_EDITION, f)
160 // If this ever becomes non thread-local, `decode_syntax_context`
161 // and `decode_expn_id` will need to be updated to handle concurrent
163 scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals);
165 // FIXME: We should use this enum or something like it to get rid of the
166 // use of magic `/rust/1.x/...` paths across the board.
167 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)]
169 pub enum RealFileName {
171 /// For remapped paths (namely paths into libstd that have been mapped
172 /// to the appropriate spot on the local host's file system, and local file
173 /// system paths that have been remapped with `FilePathMapping`),
175 /// `local_path` is the (host-dependent) local path to the file. This is
176 /// None if the file was imported from another crate
177 local_path: Option<PathBuf>,
178 /// `virtual_name` is the stable path rustc will store internally within
180 virtual_name: PathBuf,
184 impl Hash for RealFileName {
185 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
186 // To prevent #70924 from happening again we should only hash the
187 // remapped (virtualized) path if that exists. This is because
188 // virtualized paths to sysroot crates (/rust/$hash or /rust/$version)
189 // remain stable even if the corresponding local_path changes
190 self.remapped_path_if_available().hash(state)
194 // This is functionally identical to #[derive(Encodable)], with the exception of
195 // an added assert statement
196 impl<S: Encoder> Encodable<S> for RealFileName {
197 fn encode(&self, encoder: &mut S) {
199 RealFileName::LocalPath(ref local_path) => encoder.emit_enum_variant(0, |encoder| {
200 local_path.encode(encoder);
203 RealFileName::Remapped { ref local_path, ref virtual_name } => encoder
204 .emit_enum_variant(1, |encoder| {
205 // For privacy and build reproducibility, we must not embed host-dependant path in artifacts
206 // if they have been remapped by --remap-path-prefix
207 assert!(local_path.is_none());
208 local_path.encode(encoder);
209 virtual_name.encode(encoder);
216 /// Returns the path suitable for reading from the file system on the local host,
217 /// if this information exists.
218 /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
219 pub fn local_path(&self) -> Option<&Path> {
221 RealFileName::LocalPath(p) => Some(p),
222 RealFileName::Remapped { local_path: p, virtual_name: _ } => {
223 p.as_ref().map(PathBuf::as_path)
228 /// Returns the path suitable for reading from the file system on the local host,
229 /// if this information exists.
230 /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
231 pub fn into_local_path(self) -> Option<PathBuf> {
233 RealFileName::LocalPath(p) => Some(p),
234 RealFileName::Remapped { local_path: p, virtual_name: _ } => p,
238 /// Returns the path suitable for embedding into build artifacts. This would still
239 /// be a local path if it has not been remapped. A remapped path will not correspond
240 /// to a valid file system path: see `local_path_if_available()` for something that
241 /// is more likely to return paths into the local host file system.
242 pub fn remapped_path_if_available(&self) -> &Path {
244 RealFileName::LocalPath(p)
245 | RealFileName::Remapped { local_path: _, virtual_name: p } => &p,
249 /// Returns the path suitable for reading from the file system on the local host,
250 /// if this information exists. Otherwise returns the remapped name.
251 /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
252 pub fn local_path_if_available(&self) -> &Path {
254 RealFileName::LocalPath(path)
255 | RealFileName::Remapped { local_path: None, virtual_name: path }
256 | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path,
260 pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> {
262 FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(),
263 FileNameDisplayPreference::Remapped => {
264 self.remapped_path_if_available().to_string_lossy()
270 /// Differentiates between real files and common virtual files.
271 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
272 #[derive(Decodable, Encodable)]
275 /// Call to `quote!`.
279 /// Hack in `src/librustc_ast/parse.rs`.
282 ProcMacroSourceCode(u64),
283 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
285 /// Strings provided as crate attributes in the CLI.
287 /// Custom sources for explicit parser calls from plugins and drivers.
289 DocTest(PathBuf, isize),
290 /// Post-substitution inline assembly from LLVM.
294 impl From<PathBuf> for FileName {
295 fn from(p: PathBuf) -> Self {
296 assert!(!p.to_string_lossy().ends_with('>'));
297 FileName::Real(RealFileName::LocalPath(p))
301 #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
302 pub enum FileNameDisplayPreference {
307 pub struct FileNameDisplay<'a> {
309 display_pref: FileNameDisplayPreference,
312 impl fmt::Display for FileNameDisplay<'_> {
313 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317 write!(fmt, "{}", name.to_string_lossy(self.display_pref))
319 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
320 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
321 Anon(_) => write!(fmt, "<anon>"),
322 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
323 CfgSpec(_) => write!(fmt, "<cfgspec>"),
324 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
325 Custom(ref s) => write!(fmt, "<{}>", s),
326 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
327 InlineAsm(_) => write!(fmt, "<inline asm>"),
332 impl<'a> FileNameDisplay<'a> {
333 pub fn to_string_lossy(&self) -> Cow<'a, str> {
335 FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref),
336 _ => Cow::from(self.to_string()),
342 pub fn is_real(&self) -> bool {
348 | ProcMacroSourceCode(_)
354 | InlineAsm(_) => false,
358 pub fn prefer_remapped(&self) -> FileNameDisplay<'_> {
359 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped }
362 // This may include transient local filesystem information.
363 // Must not be embedded in build outputs.
364 pub fn prefer_local(&self) -> FileNameDisplay<'_> {
365 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local }
368 pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> {
369 FileNameDisplay { inner: self, display_pref }
372 pub fn macro_expansion_source_code(src: &str) -> FileName {
373 let mut hasher = StableHasher::new();
374 src.hash(&mut hasher);
375 FileName::MacroExpansion(hasher.finish())
378 pub fn anon_source_code(src: &str) -> FileName {
379 let mut hasher = StableHasher::new();
380 src.hash(&mut hasher);
381 FileName::Anon(hasher.finish())
384 pub fn proc_macro_source_code(src: &str) -> FileName {
385 let mut hasher = StableHasher::new();
386 src.hash(&mut hasher);
387 FileName::ProcMacroSourceCode(hasher.finish())
390 pub fn cfg_spec_source_code(src: &str) -> FileName {
391 let mut hasher = StableHasher::new();
392 src.hash(&mut hasher);
393 FileName::QuoteExpansion(hasher.finish())
396 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
397 let mut hasher = StableHasher::new();
398 src.hash(&mut hasher);
399 FileName::CliCrateAttr(hasher.finish())
402 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
403 FileName::DocTest(path, line)
406 pub fn inline_asm_source_code(src: &str) -> FileName {
407 let mut hasher = StableHasher::new();
408 src.hash(&mut hasher);
409 FileName::InlineAsm(hasher.finish())
413 /// Represents a span.
415 /// Spans represent a region of code, used for error reporting. Positions in spans
416 /// are *absolute* positions from the beginning of the [`SourceMap`], not positions
417 /// relative to [`SourceFile`]s. Methods on the `SourceMap` can be used to relate spans back
418 /// to the original source.
420 /// You must be careful if the span crosses more than one file, since you will not be
421 /// able to use many of the functions on spans in source_map and you cannot assume
422 /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the
423 /// [`BytePos`] range between files.
425 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
426 /// sent to other threads, but some pieces of performance infra run in a separate thread.
427 /// Using `Span` is generally preferred.
428 #[derive(Clone, Copy, Hash, PartialEq, Eq)]
429 pub struct SpanData {
432 /// Information about where the macro came from, if this piece of
433 /// code was created by a macro expansion.
434 pub ctxt: SyntaxContext,
435 pub parent: Option<LocalDefId>,
438 // Order spans by position in the file.
439 impl Ord for SpanData {
440 fn cmp(&self, other: &Self) -> Ordering {
445 // `LocalDefId` does not implement `Ord`.
446 // The other fields are enough to determine in-file order.
453 // `LocalDefId` does not implement `Ord`.
454 // The other fields are enough to determine in-file order.
458 (s_lo, s_hi, s_ctxt).cmp(&(o_lo, o_hi, o_ctxt))
462 impl PartialOrd for SpanData {
463 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
464 Some(self.cmp(other))
470 pub fn span(&self) -> Span {
471 Span::new(self.lo, self.hi, self.ctxt, self.parent)
474 pub fn with_lo(&self, lo: BytePos) -> Span {
475 Span::new(lo, self.hi, self.ctxt, self.parent)
478 pub fn with_hi(&self, hi: BytePos) -> Span {
479 Span::new(self.lo, hi, self.ctxt, self.parent)
482 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
483 Span::new(self.lo, self.hi, ctxt, self.parent)
486 pub fn with_parent(&self, parent: Option<LocalDefId>) -> Span {
487 Span::new(self.lo, self.hi, self.ctxt, parent)
489 /// Returns `true` if this is a dummy span with any hygienic context.
491 pub fn is_dummy(self) -> bool {
492 self.lo.0 == 0 && self.hi.0 == 0
494 /// Returns `true` if `self` fully encloses `other`.
495 pub fn contains(self, other: Self) -> bool {
496 self.lo <= other.lo && other.hi <= self.hi
500 // The interner is pointed to by a thread local value which is only set on the main thread
501 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
502 // to avoid panics and other errors, even though it would be memory safe to do so.
503 #[cfg(not(parallel_compiler))]
504 impl !Send for Span {}
505 #[cfg(not(parallel_compiler))]
506 impl !Sync for Span {}
508 impl PartialOrd for Span {
509 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
510 PartialOrd::partial_cmp(&self.data(), &rhs.data())
514 fn cmp(&self, rhs: &Self) -> Ordering {
515 Ord::cmp(&self.data(), &rhs.data())
521 pub fn lo(self) -> BytePos {
525 pub fn with_lo(self, lo: BytePos) -> Span {
526 self.data().with_lo(lo)
529 pub fn hi(self) -> BytePos {
533 pub fn with_hi(self, hi: BytePos) -> Span {
534 self.data().with_hi(hi)
537 pub fn ctxt(self) -> SyntaxContext {
538 self.data_untracked().ctxt
540 pub fn eq_ctxt(self, other: Span) -> bool {
541 self.data_untracked().ctxt == other.data_untracked().ctxt
544 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
545 self.data_untracked().with_ctxt(ctxt)
548 pub fn parent(self) -> Option<LocalDefId> {
552 pub fn with_parent(self, ctxt: Option<LocalDefId>) -> Span {
553 self.data().with_parent(ctxt)
556 /// Returns `true` if this is a dummy span with any hygienic context.
558 pub fn is_dummy(self) -> bool {
559 self.data_untracked().is_dummy()
562 /// Returns `true` if this span comes from a macro or desugaring.
564 pub fn from_expansion(self) -> bool {
565 self.ctxt() != SyntaxContext::root()
568 /// Returns `true` if `span` originates in a derive-macro's expansion.
569 pub fn in_derive_expansion(self) -> bool {
570 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
573 /// Gate suggestions that would not be appropriate in a context the user didn't write.
574 pub fn can_be_used_for_suggestions(self) -> bool {
575 !self.from_expansion()
576 // FIXME: If this span comes from a `derive` macro but it points at code the user wrote,
577 // the callsite span and the span will be pointing at different places. It also means that
578 // we can safely provide suggestions on this span.
579 || (matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
580 && self.parent_callsite().map(|p| (p.lo(), p.hi())) != Some((self.lo(), self.hi())))
584 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
585 Span::new(lo, hi, SyntaxContext::root(), None)
588 /// Returns a new span representing an empty span at the beginning of this span.
590 pub fn shrink_to_lo(self) -> Span {
591 let span = self.data_untracked();
592 span.with_hi(span.lo)
594 /// Returns a new span representing an empty span at the end of this span.
596 pub fn shrink_to_hi(self) -> Span {
597 let span = self.data_untracked();
598 span.with_lo(span.hi)
602 /// Returns `true` if `hi == lo`.
603 pub fn is_empty(self) -> bool {
604 let span = self.data_untracked();
608 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
609 pub fn substitute_dummy(self, other: Span) -> Span {
610 if self.is_dummy() { other } else { self }
613 /// Returns `true` if `self` fully encloses `other`.
614 pub fn contains(self, other: Span) -> bool {
615 let span = self.data();
616 let other = other.data();
620 /// Returns `true` if `self` touches `other`.
621 pub fn overlaps(self, other: Span) -> bool {
622 let span = self.data();
623 let other = other.data();
624 span.lo < other.hi && other.lo < span.hi
627 /// Returns `true` if the spans are equal with regards to the source text.
629 /// Use this instead of `==` when either span could be generated code,
630 /// and you only care that they point to the same bytes of source text.
631 pub fn source_equal(self, other: Span) -> bool {
632 let span = self.data();
633 let other = other.data();
634 span.lo == other.lo && span.hi == other.hi
637 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
638 pub fn trim_start(self, other: Span) -> Option<Span> {
639 let span = self.data();
640 let other = other.data();
641 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
644 /// Returns the source span -- this is either the supplied span, or the span for
645 /// the macro callsite that expanded to it.
646 pub fn source_callsite(self) -> Span {
647 let expn_data = self.ctxt().outer_expn_data();
648 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
651 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
653 pub fn parent_callsite(self) -> Option<Span> {
654 let expn_data = self.ctxt().outer_expn_data();
655 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
658 /// Walk down the expansion ancestors to find a span that's contained within `outer`.
659 pub fn find_ancestor_inside(mut self, outer: Span) -> Option<Span> {
660 while !outer.contains(self) {
661 self = self.parent_callsite()?;
666 /// Edition of the crate from which this span came.
667 pub fn edition(self) -> edition::Edition {
668 self.ctxt().edition()
672 pub fn rust_2015(self) -> bool {
673 self.edition() == edition::Edition::Edition2015
677 pub fn rust_2018(self) -> bool {
678 self.edition() >= edition::Edition::Edition2018
682 pub fn rust_2021(self) -> bool {
683 self.edition() >= edition::Edition::Edition2021
687 pub fn rust_2024(self) -> bool {
688 self.edition() >= edition::Edition::Edition2024
691 /// Returns the source callee.
693 /// Returns `None` if the supplied span has no expansion trace,
694 /// else returns the `ExpnData` for the macro definition
695 /// corresponding to the source callsite.
696 pub fn source_callee(self) -> Option<ExpnData> {
697 fn source_callee(expn_data: ExpnData) -> ExpnData {
698 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
699 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
701 let expn_data = self.ctxt().outer_expn_data();
702 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
705 /// Checks if a span is "internal" to a macro in which `#[unstable]`
706 /// items can be used (that is, a macro marked with
707 /// `#[allow_internal_unstable]`).
708 pub fn allows_unstable(self, feature: Symbol) -> bool {
711 .allow_internal_unstable
712 .map_or(false, |features| features.iter().any(|&f| f == feature))
715 /// Checks if this span arises from a compiler desugaring of kind `kind`.
716 pub fn is_desugaring(self, kind: DesugaringKind) -> bool {
717 match self.ctxt().outer_expn_data().kind {
718 ExpnKind::Desugaring(k) => k == kind,
723 /// Returns the compiler desugaring that created this span, or `None`
724 /// if this span is not from a desugaring.
725 pub fn desugaring_kind(self) -> Option<DesugaringKind> {
726 match self.ctxt().outer_expn_data().kind {
727 ExpnKind::Desugaring(k) => Some(k),
732 /// Checks if a span is "internal" to a macro in which `unsafe`
733 /// can be used without triggering the `unsafe_code` lint.
734 // (that is, a macro marked with `#[allow_internal_unsafe]`).
735 pub fn allows_unsafe(self) -> bool {
736 self.ctxt().outer_expn_data().allow_internal_unsafe
739 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
740 let mut prev_span = DUMMY_SP;
741 std::iter::from_fn(move || {
743 let expn_data = self.ctxt().outer_expn_data();
744 if expn_data.is_root() {
748 let is_recursive = expn_data.call_site.source_equal(prev_span);
751 self = expn_data.call_site;
753 // Don't print recursive invocations.
755 return Some(expn_data);
761 /// Returns a `Span` that would enclose both `self` and `end`.
765 /// self lorem ipsum end
766 /// ^^^^^^^^^^^^^^^^^^^^
768 pub fn to(self, end: Span) -> Span {
769 let span_data = self.data();
770 let end_data = end.data();
771 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
772 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
773 // have an incomplete span than a completely nonsensical one.
774 if span_data.ctxt != end_data.ctxt {
775 if span_data.ctxt == SyntaxContext::root() {
777 } else if end_data.ctxt == SyntaxContext::root() {
780 // Both spans fall within a macro.
781 // FIXME(estebank): check if it is the *same* macro.
784 cmp::min(span_data.lo, end_data.lo),
785 cmp::max(span_data.hi, end_data.hi),
786 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
787 if span_data.parent == end_data.parent { span_data.parent } else { None },
791 /// Returns a `Span` between the end of `self` to the beginning of `end`.
795 /// self lorem ipsum end
798 pub fn between(self, end: Span) -> Span {
799 let span = self.data();
800 let end = end.data();
804 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
805 if span.parent == end.parent { span.parent } else { None },
809 /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
813 /// self lorem ipsum end
814 /// ^^^^^^^^^^^^^^^^^
816 pub fn until(self, end: Span) -> Span {
817 // Most of this function's body is copied from `to`.
818 // We can't just do `self.to(end.shrink_to_lo())`,
819 // because to also does some magic where it uses min/max so
820 // it can handle overlapping spans. Some advanced mis-use of
821 // `until` with different ctxts makes this visible.
822 let span_data = self.data();
823 let end_data = end.data();
824 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
825 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
826 // have an incomplete span than a completely nonsensical one.
827 if span_data.ctxt != end_data.ctxt {
828 if span_data.ctxt == SyntaxContext::root() {
830 } else if end_data.ctxt == SyntaxContext::root() {
833 // Both spans fall within a macro.
834 // FIXME(estebank): check if it is the *same* macro.
839 if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
840 if span_data.parent == end_data.parent { span_data.parent } else { None },
844 pub fn from_inner(self, inner: InnerSpan) -> Span {
845 let span = self.data();
847 span.lo + BytePos::from_usize(inner.start),
848 span.lo + BytePos::from_usize(inner.end),
854 /// Equivalent of `Span::def_site` from the proc macro API,
855 /// except that the location is taken from the `self` span.
856 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
857 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
860 /// Equivalent of `Span::call_site` from the proc macro API,
861 /// except that the location is taken from the `self` span.
862 pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span {
863 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
866 /// Equivalent of `Span::mixed_site` from the proc macro API,
867 /// except that the location is taken from the `self` span.
868 pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span {
869 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
872 /// Produces a span with the same location as `self` and context produced by a macro with the
873 /// given ID and transparency, assuming that macro was defined directly and not produced by
874 /// some other macro (which is the case for built-in and procedural macros).
875 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
876 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
880 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
881 let span = self.data();
882 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
886 pub fn remove_mark(&mut self) -> ExpnId {
887 let mut span = self.data();
888 let mark = span.ctxt.remove_mark();
889 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
894 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
895 let mut span = self.data();
896 let mark = span.ctxt.adjust(expn_id);
897 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
902 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
903 let mut span = self.data();
904 let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
905 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
910 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
911 let mut span = self.data();
912 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
913 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
918 pub fn reverse_glob_adjust(
922 ) -> Option<Option<ExpnId>> {
923 let mut span = self.data();
924 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
925 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
930 pub fn normalize_to_macros_2_0(self) -> Span {
931 let span = self.data();
932 span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
936 pub fn normalize_to_macro_rules(self) -> Span {
937 let span = self.data();
938 span.with_ctxt(span.ctxt.normalize_to_macro_rules())
942 impl Default for Span {
943 fn default() -> Self {
948 impl<E: Encoder> Encodable<E> for Span {
949 default fn encode(&self, s: &mut E) {
950 let span = self.data();
955 impl<D: Decoder> Decodable<D> for Span {
956 default fn decode(s: &mut D) -> Span {
957 let lo = Decodable::decode(s);
958 let hi = Decodable::decode(s);
960 Span::new(lo, hi, SyntaxContext::root(), None)
964 /// Calls the provided closure, using the provided `SourceMap` to format
965 /// any spans that are debug-printed during the closure's execution.
967 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
968 /// (see `rustc_interface::callbacks::span_debug1`). However, some parts
969 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
970 /// a `TyCtxt` is available. In this case, we fall back to
971 /// the `SourceMap` provided to this function. If that is not available,
972 /// we fall back to printing the raw `Span` field values.
973 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
974 with_session_globals(|session_globals| {
975 *session_globals.source_map.borrow_mut() = Some(source_map);
977 struct ClearSourceMap;
978 impl Drop for ClearSourceMap {
980 with_session_globals(|session_globals| {
981 session_globals.source_map.borrow_mut().take();
986 let _guard = ClearSourceMap;
990 impl fmt::Debug for Span {
991 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
992 with_session_globals(|session_globals| {
993 if let Some(source_map) = &*session_globals.source_map.borrow() {
994 write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(*self), self.ctxt())
996 f.debug_struct("Span")
997 .field("lo", &self.lo())
998 .field("hi", &self.hi())
999 .field("ctxt", &self.ctxt())
1006 impl fmt::Debug for SpanData {
1007 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1008 fmt::Debug::fmt(&Span::new(self.lo, self.hi, self.ctxt, self.parent), f)
1012 /// Identifies an offset of a multi-byte character in a `SourceFile`.
1013 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1014 pub struct MultiByteChar {
1015 /// The absolute offset of the character in the `SourceMap`.
1017 /// The number of bytes, `>= 2`.
1021 /// Identifies an offset of a non-narrow character in a `SourceFile`.
1022 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1023 pub enum NonNarrowChar {
1024 /// Represents a zero-width character.
1026 /// Represents a wide (full-width) character.
1028 /// Represents a tab character, represented visually with a width of 4 characters.
1032 impl NonNarrowChar {
1033 fn new(pos: BytePos, width: usize) -> Self {
1035 0 => NonNarrowChar::ZeroWidth(pos),
1036 2 => NonNarrowChar::Wide(pos),
1037 4 => NonNarrowChar::Tab(pos),
1038 _ => panic!("width {} given for non-narrow character", width),
1042 /// Returns the absolute offset of the character in the `SourceMap`.
1043 pub fn pos(&self) -> BytePos {
1045 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
1049 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
1050 pub fn width(&self) -> usize {
1052 NonNarrowChar::ZeroWidth(_) => 0,
1053 NonNarrowChar::Wide(_) => 2,
1054 NonNarrowChar::Tab(_) => 4,
1059 impl Add<BytePos> for NonNarrowChar {
1062 fn add(self, rhs: BytePos) -> Self {
1064 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
1065 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
1066 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
1071 impl Sub<BytePos> for NonNarrowChar {
1074 fn sub(self, rhs: BytePos) -> Self {
1076 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
1077 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
1078 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
1083 /// Identifies an offset of a character that was normalized away from `SourceFile`.
1084 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1085 pub struct NormalizedPos {
1086 /// The absolute offset of the character in the `SourceMap`.
1088 /// The difference between original and normalized string at position.
1092 #[derive(PartialEq, Eq, Clone, Debug)]
1093 pub enum ExternalSource {
1094 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
1097 kind: ExternalSourceKind,
1098 /// This SourceFile's byte-offset within the source_map of its original crate.
1099 original_start_pos: BytePos,
1100 /// The end of this SourceFile within the source_map of its original crate.
1101 original_end_pos: BytePos,
1105 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1106 #[derive(PartialEq, Eq, Clone, Debug)]
1107 pub enum ExternalSourceKind {
1108 /// The external source has been loaded already.
1109 Present(Lrc<String>),
1110 /// No attempt has been made to load the external source.
1112 /// A failed attempt has been made to load the external source.
1117 impl ExternalSource {
1118 pub fn get_source(&self) -> Option<&Lrc<String>> {
1120 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1127 pub struct OffsetOverflowError;
1129 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1130 #[derive(HashStable_Generic)]
1131 pub enum SourceFileHashAlgorithm {
1137 impl FromStr for SourceFileHashAlgorithm {
1140 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1142 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1143 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1144 "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1150 /// The hash of the on-disk source file used for debug info.
1151 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
1152 #[derive(HashStable_Generic, Encodable, Decodable)]
1153 pub struct SourceFileHash {
1154 pub kind: SourceFileHashAlgorithm,
1158 impl SourceFileHash {
1159 pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1160 let mut hash = SourceFileHash { kind, value: Default::default() };
1161 let len = hash.hash_len();
1162 let value = &mut hash.value[..len];
1163 let data = src.as_bytes();
1165 SourceFileHashAlgorithm::Md5 => {
1166 value.copy_from_slice(&Md5::digest(data));
1168 SourceFileHashAlgorithm::Sha1 => {
1169 value.copy_from_slice(&Sha1::digest(data));
1171 SourceFileHashAlgorithm::Sha256 => {
1172 value.copy_from_slice(&Sha256::digest(data));
1178 /// Check if the stored hash matches the hash of the string.
1179 pub fn matches(&self, src: &str) -> bool {
1180 Self::new(self.kind, src) == *self
1183 /// The bytes of the hash.
1184 pub fn hash_bytes(&self) -> &[u8] {
1185 let len = self.hash_len();
1189 fn hash_len(&self) -> usize {
1191 SourceFileHashAlgorithm::Md5 => 16,
1192 SourceFileHashAlgorithm::Sha1 => 20,
1193 SourceFileHashAlgorithm::Sha256 => 32,
1198 #[derive(HashStable_Generic)]
1199 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug, Encodable, Decodable)]
1200 pub enum DebuggerVisualizerType {
1205 /// A single debugger visualizer file.
1206 #[derive(HashStable_Generic)]
1207 #[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable)]
1208 pub struct DebuggerVisualizerFile {
1209 /// The complete debugger visualizer source.
1211 /// Indicates which visualizer type this targets.
1212 pub visualizer_type: DebuggerVisualizerType,
1215 impl DebuggerVisualizerFile {
1216 pub fn new(src: Arc<[u8]>, visualizer_type: DebuggerVisualizerType) -> Self {
1217 DebuggerVisualizerFile { src, visualizer_type }
1222 pub enum SourceFileLines {
1223 /// The source file lines, in decoded (random-access) form.
1224 Lines(Vec<BytePos>),
1226 /// The source file lines, in undecoded difference list form.
1227 Diffs(SourceFileDiffs),
1230 impl SourceFileLines {
1231 pub fn is_lines(&self) -> bool {
1232 matches!(self, SourceFileLines::Lines(_))
1236 /// The source file lines in difference list form. This matches the form
1237 /// used within metadata, which saves space by exploiting the fact that the
1238 /// lines list is sorted and individual lines are usually not that long.
1240 /// We read it directly from metadata and only decode it into `Lines` form
1241 /// when necessary. This is a significant performance win, especially for
1242 /// small crates where very little of `std`'s metadata is used.
1244 pub struct SourceFileDiffs {
1245 /// Position of the first line. Note that this is always encoded as a
1246 /// `BytePos` because it is often much larger than any of the
1248 line_start: BytePos,
1250 /// Always 1, 2, or 4. Always as small as possible, while being big
1251 /// enough to hold the length of the longest line in the source file.
1252 /// The 1 case is by far the most common.
1253 bytes_per_diff: usize,
1255 /// The number of diffs encoded in `raw_diffs`. Always one less than
1256 /// the number of lines in the source file.
1259 /// The diffs in "raw" form. Each segment of `bytes_per_diff` length
1260 /// encodes one little-endian diff. Note that they aren't LEB128
1261 /// encoded. This makes for much faster decoding. Besides, the
1262 /// bytes_per_diff==1 case is by far the most common, and LEB128
1263 /// encoding has no effect on that case.
1267 /// A single source in the [`SourceMap`].
1269 pub struct SourceFile {
1270 /// The name of the file that the source came from. Source that doesn't
1271 /// originate from files has names between angle brackets by convention
1272 /// (e.g., `<anon>`).
1274 /// The complete source code.
1275 pub src: Option<Lrc<String>>,
1276 /// The source code's hash.
1277 pub src_hash: SourceFileHash,
1278 /// The external source code (used for external crates, which will have a `None`
1279 /// value as `self.src`.
1280 pub external_src: Lock<ExternalSource>,
1281 /// The start position of this source in the `SourceMap`.
1282 pub start_pos: BytePos,
1283 /// The end position of this source in the `SourceMap`.
1284 pub end_pos: BytePos,
1285 /// Locations of lines beginnings in the source code.
1286 pub lines: Lock<SourceFileLines>,
1287 /// Locations of multi-byte characters in the source code.
1288 pub multibyte_chars: Vec<MultiByteChar>,
1289 /// Width of characters that are not narrow in the source code.
1290 pub non_narrow_chars: Vec<NonNarrowChar>,
1291 /// Locations of characters removed during normalization.
1292 pub normalized_pos: Vec<NormalizedPos>,
1293 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1294 pub name_hash: u128,
1295 /// Indicates which crate this `SourceFile` was imported from.
1299 impl<S: Encoder> Encodable<S> for SourceFile {
1300 fn encode(&self, s: &mut S) {
1301 self.name.encode(s);
1302 self.src_hash.encode(s);
1303 self.start_pos.encode(s);
1304 self.end_pos.encode(s);
1306 // We are always in `Lines` form by the time we reach here.
1307 assert!(self.lines.borrow().is_lines());
1308 self.lines(|lines| {
1309 // Store the length.
1310 s.emit_u32(lines.len() as u32);
1312 // Compute and store the difference list.
1313 if lines.len() != 0 {
1314 let max_line_length = if lines.len() == 1 {
1319 .map(|&[fst, snd]| snd - fst)
1320 .map(|bp| bp.to_usize())
1325 let bytes_per_diff: usize = match max_line_length {
1327 0x100..=0xFFFF => 2,
1331 // Encode the number of bytes used per diff.
1332 s.emit_u8(bytes_per_diff as u8);
1334 // Encode the first element.
1337 // Encode the difference list.
1338 let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst);
1339 let num_diffs = lines.len() - 1;
1341 match bytes_per_diff {
1343 raw_diffs = Vec::with_capacity(num_diffs);
1344 for diff in diff_iter {
1345 raw_diffs.push(diff.0 as u8);
1349 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
1350 for diff in diff_iter {
1351 raw_diffs.extend_from_slice(&(diff.0 as u16).to_le_bytes());
1355 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
1356 for diff in diff_iter {
1357 raw_diffs.extend_from_slice(&(diff.0 as u32).to_le_bytes());
1360 _ => unreachable!(),
1362 s.emit_raw_bytes(&raw_diffs);
1366 self.multibyte_chars.encode(s);
1367 self.non_narrow_chars.encode(s);
1368 self.name_hash.encode(s);
1369 self.normalized_pos.encode(s);
1370 self.cnum.encode(s);
1374 impl<D: Decoder> Decodable<D> for SourceFile {
1375 fn decode(d: &mut D) -> SourceFile {
1376 let name: FileName = Decodable::decode(d);
1377 let src_hash: SourceFileHash = Decodable::decode(d);
1378 let start_pos: BytePos = Decodable::decode(d);
1379 let end_pos: BytePos = Decodable::decode(d);
1381 let num_lines: u32 = Decodable::decode(d);
1383 // Read the number of bytes used per diff.
1384 let bytes_per_diff = d.read_u8() as usize;
1386 // Read the first element.
1387 let line_start: BytePos = Decodable::decode(d);
1389 // Read the difference list.
1390 let num_diffs = num_lines as usize - 1;
1391 let raw_diffs = d.read_raw_bytes(bytes_per_diff * num_diffs).to_vec();
1392 SourceFileLines::Diffs(SourceFileDiffs {
1399 SourceFileLines::Lines(vec![])
1402 let multibyte_chars: Vec<MultiByteChar> = Decodable::decode(d);
1403 let non_narrow_chars: Vec<NonNarrowChar> = Decodable::decode(d);
1404 let name_hash: u128 = Decodable::decode(d);
1405 let normalized_pos: Vec<NormalizedPos> = Decodable::decode(d);
1406 let cnum: CrateNum = Decodable::decode(d);
1413 // Unused - the metadata decoder will construct
1414 // a new SourceFile, filling in `external_src` properly
1415 external_src: Lock::new(ExternalSource::Unneeded),
1416 lines: Lock::new(lines),
1426 impl fmt::Debug for SourceFile {
1427 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1428 write!(fmt, "SourceFile({:?})", self.name)
1437 hash_kind: SourceFileHashAlgorithm,
1439 // Compute the file hash before any normalization.
1440 let src_hash = SourceFileHash::new(hash_kind, &src);
1441 let normalized_pos = normalize_src(&mut src, start_pos);
1444 let mut hasher: StableHasher = StableHasher::new();
1445 name.hash(&mut hasher);
1446 hasher.finish::<u128>()
1448 let end_pos = start_pos.to_usize() + src.len();
1449 assert!(end_pos <= u32::MAX as usize);
1451 let (lines, multibyte_chars, non_narrow_chars) =
1452 analyze_source_file::analyze_source_file(&src, start_pos);
1456 src: Some(Lrc::new(src)),
1458 external_src: Lock::new(ExternalSource::Unneeded),
1460 end_pos: Pos::from_usize(end_pos),
1461 lines: Lock::new(SourceFileLines::Lines(lines)),
1470 pub fn lines<F, R>(&self, f: F) -> R
1472 F: FnOnce(&[BytePos]) -> R,
1474 let mut guard = self.lines.borrow_mut();
1476 SourceFileLines::Lines(lines) => f(lines),
1477 SourceFileLines::Diffs(SourceFileDiffs {
1483 // Convert from "diffs" form to "lines" form.
1484 let num_lines = num_diffs + 1;
1485 let mut lines = Vec::with_capacity(num_lines);
1486 lines.push(line_start);
1488 assert_eq!(*num_diffs, raw_diffs.len() / bytes_per_diff);
1489 match bytes_per_diff {
1491 lines.extend(raw_diffs.into_iter().map(|&diff| {
1492 line_start = line_start + BytePos(diff as u32);
1497 lines.extend((0..*num_diffs).map(|i| {
1498 let pos = bytes_per_diff * i;
1499 let bytes = [raw_diffs[pos], raw_diffs[pos + 1]];
1500 let diff = u16::from_le_bytes(bytes);
1501 line_start = line_start + BytePos(diff as u32);
1506 lines.extend((0..*num_diffs).map(|i| {
1507 let pos = bytes_per_diff * i;
1514 let diff = u32::from_le_bytes(bytes);
1515 line_start = line_start + BytePos(diff);
1519 _ => unreachable!(),
1521 let res = f(&lines);
1522 *guard = SourceFileLines::Lines(lines);
1528 /// Returns the `BytePos` of the beginning of the current line.
1529 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1530 let line_index = self.lookup_line(pos).unwrap();
1531 self.lines(|lines| lines[line_index])
1534 /// Add externally loaded source.
1535 /// If the hash of the input doesn't match or no input is supplied via None,
1536 /// it is interpreted as an error and the corresponding enum variant is set.
1537 /// The return value signifies whether some kind of source is present.
1538 pub fn add_external_src<F>(&self, get_src: F) -> bool
1540 F: FnOnce() -> Option<String>,
1543 *self.external_src.borrow(),
1544 ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1546 let src = get_src();
1547 let mut external_src = self.external_src.borrow_mut();
1548 // Check that no-one else have provided the source while we were getting it
1549 if let ExternalSource::Foreign {
1550 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1551 } = &mut *external_src
1553 if let Some(mut src) = src {
1554 // The src_hash needs to be computed on the pre-normalized src.
1555 if self.src_hash.matches(&src) {
1556 normalize_src(&mut src, BytePos::from_usize(0));
1557 *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1561 *src_kind = ExternalSourceKind::AbsentErr;
1566 self.src.is_some() || external_src.get_source().is_some()
1569 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1573 /// Gets a line from the list of pre-computed line-beginnings.
1574 /// The line number here is 0-based.
1575 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1576 fn get_until_newline(src: &str, begin: usize) -> &str {
1577 // We can't use `lines.get(line_number+1)` because we might
1578 // be parsing when we call this function and thus the current
1579 // line is the last one we have line info for.
1580 let slice = &src[begin..];
1581 match slice.find('\n') {
1582 Some(e) => &slice[..e],
1588 let line = self.lines(|lines| lines.get(line_number).copied())?;
1589 let begin: BytePos = line - self.start_pos;
1593 if let Some(ref src) = self.src {
1594 Some(Cow::from(get_until_newline(src, begin)))
1595 } else if let Some(src) = self.external_src.borrow().get_source() {
1596 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1602 pub fn is_real_file(&self) -> bool {
1607 pub fn is_imported(&self) -> bool {
1611 pub fn count_lines(&self) -> usize {
1612 self.lines(|lines| lines.len())
1615 /// Finds the line containing the given position. The return value is the
1616 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1617 /// number. If the source_file is empty or the position is located before the
1618 /// first line, `None` is returned.
1619 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1620 self.lines(|lines| match lines.binary_search(&pos) {
1621 Ok(idx) => Some(idx),
1623 Err(idx) => Some(idx - 1),
1627 pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
1628 if self.is_empty() {
1629 return self.start_pos..self.end_pos;
1632 self.lines(|lines| {
1633 assert!(line_index < lines.len());
1634 if line_index == (lines.len() - 1) {
1635 lines[line_index]..self.end_pos
1637 lines[line_index]..lines[line_index + 1]
1642 /// Returns whether or not the file contains the given `SourceMap` byte
1643 /// position. The position one past the end of the file is considered to be
1644 /// contained by the file. This implies that files for which `is_empty`
1645 /// returns true still contain one byte position according to this function.
1647 pub fn contains(&self, byte_pos: BytePos) -> bool {
1648 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1652 pub fn is_empty(&self) -> bool {
1653 self.start_pos == self.end_pos
1656 /// Calculates the original byte position relative to the start of the file
1657 /// based on the given byte position.
1658 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1659 // Diff before any records is 0. Otherwise use the previously recorded
1660 // diff as that applies to the following characters until a new diff
1662 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1663 Ok(i) => self.normalized_pos[i].diff,
1664 Err(i) if i == 0 => 0,
1665 Err(i) => self.normalized_pos[i - 1].diff,
1668 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1671 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1672 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1673 // The number of extra bytes due to multibyte chars in the `SourceFile`.
1674 let mut total_extra_bytes = 0;
1676 for mbc in self.multibyte_chars.iter() {
1677 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1679 // Every character is at least one byte, so we only
1680 // count the actual extra bytes.
1681 total_extra_bytes += mbc.bytes as u32 - 1;
1682 // We should never see a byte position in the middle of a
1684 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1690 assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1691 CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1694 /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1695 /// given `BytePos`.
1696 pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1697 let chpos = self.bytepos_to_file_charpos(pos);
1698 match self.lookup_line(pos) {
1700 let line = a + 1; // Line numbers start at 1
1701 let linebpos = self.lines(|lines| lines[a]);
1702 let linechpos = self.bytepos_to_file_charpos(linebpos);
1703 let col = chpos - linechpos;
1704 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1705 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1706 debug!("byte is on line: {}", line);
1707 assert!(chpos >= linechpos);
1714 /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1715 /// column offset when displayed, for a given `BytePos`.
1716 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1717 let (line, col_or_chpos) = self.lookup_file_pos(pos);
1719 let col = col_or_chpos;
1720 let linebpos = self.lines(|lines| lines[line - 1]);
1722 let start_width_idx = self
1724 .binary_search_by_key(&linebpos, |x| x.pos())
1725 .unwrap_or_else(|x| x);
1726 let end_width_idx = self
1728 .binary_search_by_key(&pos, |x| x.pos())
1729 .unwrap_or_else(|x| x);
1730 let special_chars = end_width_idx - start_width_idx;
1731 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1735 col.0 - special_chars + non_narrow
1737 (line, col, col_display)
1739 let chpos = col_or_chpos;
1741 let end_width_idx = self
1743 .binary_search_by_key(&pos, |x| x.pos())
1744 .unwrap_or_else(|x| x);
1745 let non_narrow: usize =
1746 self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1747 chpos.0 - end_width_idx + non_narrow
1749 (0, chpos, col_display)
1754 /// Normalizes the source code and records the normalizations.
1755 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1756 let mut normalized_pos = vec![];
1757 remove_bom(src, &mut normalized_pos);
1758 normalize_newlines(src, &mut normalized_pos);
1760 // Offset all the positions by start_pos to match the final file positions.
1761 for np in &mut normalized_pos {
1762 np.pos.0 += start_pos.0;
1768 /// Removes UTF-8 BOM, if any.
1769 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1770 if src.starts_with('\u{feff}') {
1772 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1776 /// Replaces `\r\n` with `\n` in-place in `src`.
1778 /// Returns error if there's a lone `\r` in the string.
1779 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1780 if !src.as_bytes().contains(&b'\r') {
1784 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1785 // While we *can* call `as_mut_vec` and do surgery on the live string
1786 // directly, let's rather steal the contents of `src`. This makes the code
1787 // safe even if a panic occurs.
1789 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1790 let mut gap_len = 0;
1791 let mut tail = buf.as_mut_slice();
1793 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1795 let idx = match find_crlf(&tail[gap_len..]) {
1797 Some(idx) => idx + gap_len,
1799 tail.copy_within(gap_len..idx, 0);
1800 tail = &mut tail[idx - gap_len..];
1801 if tail.len() == gap_len {
1804 cursor += idx - gap_len;
1806 normalized_pos.push(NormalizedPos {
1807 pos: BytePos::from_usize(cursor + 1),
1808 diff: original_gap + gap_len as u32,
1812 // Account for removed `\r`.
1813 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1814 let new_len = buf.len() - gap_len;
1816 buf.set_len(new_len);
1817 *src = String::from_utf8_unchecked(buf);
1820 fn find_crlf(src: &[u8]) -> Option<usize> {
1821 let mut search_idx = 0;
1822 while let Some(idx) = find_cr(&src[search_idx..]) {
1823 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1824 search_idx += idx + 1;
1827 return Some(search_idx + idx);
1832 fn find_cr(src: &[u8]) -> Option<usize> {
1833 src.iter().position(|&b| b == b'\r')
1837 // _____________________________________________________________________________
1838 // Pos, BytePos, CharPos
1842 fn from_usize(n: usize) -> Self;
1843 fn to_usize(&self) -> usize;
1844 fn from_u32(n: u32) -> Self;
1845 fn to_u32(&self) -> u32;
1848 macro_rules! impl_pos {
1852 $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1857 $vis struct $ident($inner_vis $inner_ty);
1859 impl Pos for $ident {
1861 fn from_usize(n: usize) -> $ident {
1862 $ident(n as $inner_ty)
1866 fn to_usize(&self) -> usize {
1871 fn from_u32(n: u32) -> $ident {
1872 $ident(n as $inner_ty)
1876 fn to_u32(&self) -> u32 {
1881 impl Add for $ident {
1882 type Output = $ident;
1885 fn add(self, rhs: $ident) -> $ident {
1886 $ident(self.0 + rhs.0)
1890 impl Sub for $ident {
1891 type Output = $ident;
1894 fn sub(self, rhs: $ident) -> $ident {
1895 $ident(self.0 - rhs.0)
1905 /// Keep this small (currently 32-bits), as AST contains a lot of them.
1906 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1907 pub struct BytePos(pub u32);
1909 /// A character offset.
1911 /// Because of multibyte UTF-8 characters, a byte offset
1912 /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`]
1913 /// values to `CharPos` values as necessary.
1914 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1915 pub struct CharPos(pub usize);
1918 impl<S: Encoder> Encodable<S> for BytePos {
1919 fn encode(&self, s: &mut S) {
1924 impl<D: Decoder> Decodable<D> for BytePos {
1925 fn decode(d: &mut D) -> BytePos {
1926 BytePos(d.read_u32())
1930 // _____________________________________________________________________________
1931 // Loc, SourceFileAndLine, SourceFileAndBytePos
1934 /// A source code location used for error reporting.
1935 #[derive(Debug, Clone)]
1937 /// Information about the original source.
1938 pub file: Lrc<SourceFile>,
1939 /// The (1-based) line number.
1941 /// The (0-based) column offset.
1943 /// The (0-based) column offset when displayed.
1944 pub col_display: usize,
1947 // Used to be structural records.
1949 pub struct SourceFileAndLine {
1950 pub sf: Lrc<SourceFile>,
1951 /// Index of line, starting from 0.
1955 pub struct SourceFileAndBytePos {
1956 pub sf: Lrc<SourceFile>,
1960 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1961 pub struct LineInfo {
1962 /// Index of line, starting from 0.
1963 pub line_index: usize,
1965 /// Column in line where span begins, starting from 0.
1966 pub start_col: CharPos,
1968 /// Column in line where span ends, starting from 0, exclusive.
1969 pub end_col: CharPos,
1972 pub struct FileLines {
1973 pub file: Lrc<SourceFile>,
1974 pub lines: Vec<LineInfo>,
1977 pub static SPAN_TRACK: AtomicRef<fn(LocalDefId)> = AtomicRef::new(&((|_| {}) as fn(_)));
1979 // _____________________________________________________________________________
1980 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1983 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1985 #[derive(Clone, PartialEq, Eq, Debug)]
1986 pub enum SpanLinesError {
1987 DistinctSources(DistinctSources),
1990 #[derive(Clone, PartialEq, Eq, Debug)]
1991 pub enum SpanSnippetError {
1992 IllFormedSpan(Span),
1993 DistinctSources(DistinctSources),
1994 MalformedForSourcemap(MalformedSourceMapPositions),
1995 SourceNotAvailable { filename: FileName },
1998 #[derive(Clone, PartialEq, Eq, Debug)]
1999 pub struct DistinctSources {
2000 pub begin: (FileName, BytePos),
2001 pub end: (FileName, BytePos),
2004 #[derive(Clone, PartialEq, Eq, Debug)]
2005 pub struct MalformedSourceMapPositions {
2007 pub source_len: usize,
2008 pub begin_pos: BytePos,
2009 pub end_pos: BytePos,
2012 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
2013 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2014 pub struct InnerSpan {
2020 pub fn new(start: usize, end: usize) -> InnerSpan {
2021 InnerSpan { start, end }
2025 /// Requirements for a `StableHashingContext` to be used in this crate.
2027 /// This is a hack to allow using the [`HashStable_Generic`] derive macro
2028 /// instead of implementing everything in rustc_middle.
2029 pub trait HashStableContext {
2030 fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
2031 fn hash_spans(&self) -> bool;
2032 /// Accesses `sess.opts.unstable_opts.incremental_ignore_spans` since
2033 /// we don't have easy access to a `Session`
2034 fn unstable_opts_incremental_ignore_spans(&self) -> bool;
2035 fn def_span(&self, def_id: LocalDefId) -> Span;
2036 fn span_data_to_lines_and_cols(
2039 ) -> Option<(Lrc<SourceFile>, usize, BytePos, usize, BytePos)>;
2040 fn hashing_controls(&self) -> HashingControls;
2043 impl<CTX> HashStable<CTX> for Span
2045 CTX: HashStableContext,
2047 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
2048 /// fields (that would be similar to hashing pointers, since those are just
2049 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
2050 /// triple, which stays the same even if the containing `SourceFile` has moved
2051 /// within the `SourceMap`.
2053 /// Also note that we are hashing byte offsets for the column, not unicode
2054 /// codepoint offsets. For the purpose of the hash that's sufficient.
2055 /// Also, hashing filenames is expensive so we avoid doing it twice when the
2056 /// span starts and ends in the same file, which is almost always the case.
2057 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
2058 const TAG_VALID_SPAN: u8 = 0;
2059 const TAG_INVALID_SPAN: u8 = 1;
2060 const TAG_RELATIVE_SPAN: u8 = 2;
2062 if !ctx.hash_spans() {
2066 let span = self.data_untracked();
2067 span.ctxt.hash_stable(ctx, hasher);
2068 span.parent.hash_stable(ctx, hasher);
2070 if span.is_dummy() {
2071 Hash::hash(&TAG_INVALID_SPAN, hasher);
2075 if let Some(parent) = span.parent {
2076 let def_span = ctx.def_span(parent).data_untracked();
2077 if def_span.contains(span) {
2078 // This span is enclosed in a definition: only hash the relative position.
2079 Hash::hash(&TAG_RELATIVE_SPAN, hasher);
2080 (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher);
2081 (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher);
2086 // If this is not an empty or invalid span, we want to hash the last
2087 // position that belongs to it, as opposed to hashing the first
2088 // position past it.
2089 let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span) else {
2090 Hash::hash(&TAG_INVALID_SPAN, hasher);
2094 Hash::hash(&TAG_VALID_SPAN, hasher);
2095 // We truncate the stable ID hash and line and column numbers. The chances
2096 // of causing a collision this way should be minimal.
2097 Hash::hash(&(file.name_hash as u64), hasher);
2099 // Hash both the length and the end location (line/column) of a span. If we
2100 // hash only the length, for example, then two otherwise equal spans with
2101 // different end locations will have the same hash. This can cause a problem
2102 // during incremental compilation wherein a previous result for a query that
2103 // depends on the end location of a span will be incorrectly reused when the
2104 // end location of the span it depends on has changed (see issue #74890). A
2105 // similar analysis applies if some query depends specifically on the length
2106 // of the span, but we only hash the end location. So hash both.
2108 let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
2109 let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
2110 let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
2111 let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
2112 let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
2113 let len = (span.hi - span.lo).0;
2114 Hash::hash(&col_line, hasher);
2115 Hash::hash(&len, hasher);