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)]
18 #![feature(if_let_guard)]
19 #![feature(negative_impls)]
20 #![feature(min_specialization)]
21 #![feature(rustc_attrs)]
22 #![deny(rustc::untranslatable_diagnostic)]
23 #![deny(rustc::diagnostic_outside_of_impl)]
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;
81 /// Per-session global variables: this struct is stored in thread-local storage
82 /// in such a way that it is accessible without any kind of handle to all
83 /// threads within the compilation session, but is not accessible outside the
85 pub struct SessionGlobals {
86 symbol_interner: symbol::Interner,
87 span_interner: Lock<span_encoding::SpanInterner>,
88 hygiene_data: Lock<hygiene::HygieneData>,
89 source_map: Lock<Option<Lrc<SourceMap>>>,
93 pub fn new(edition: Edition) -> SessionGlobals {
95 symbol_interner: symbol::Interner::fresh(),
96 span_interner: Lock::new(span_encoding::SpanInterner::default()),
97 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
98 source_map: Lock::new(None),
104 pub fn create_session_globals_then<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
106 !SESSION_GLOBALS.is_set(),
107 "SESSION_GLOBALS should never be overwritten! \
108 Use another thread if you need another SessionGlobals"
110 let session_globals = SessionGlobals::new(edition);
111 SESSION_GLOBALS.set(&session_globals, f)
115 pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R {
117 !SESSION_GLOBALS.is_set(),
118 "SESSION_GLOBALS should never be overwritten! \
119 Use another thread if you need another SessionGlobals"
121 SESSION_GLOBALS.set(session_globals, f)
125 pub fn create_default_session_if_not_set_then<R, F>(f: F) -> R
127 F: FnOnce(&SessionGlobals) -> R,
129 create_session_if_not_set_then(edition::DEFAULT_EDITION, f)
133 pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R
135 F: FnOnce(&SessionGlobals) -> R,
137 if !SESSION_GLOBALS.is_set() {
138 let session_globals = SessionGlobals::new(edition);
139 SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f))
141 SESSION_GLOBALS.with(f)
146 pub fn with_session_globals<R, F>(f: F) -> R
148 F: FnOnce(&SessionGlobals) -> R,
150 SESSION_GLOBALS.with(f)
154 pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R {
155 create_session_globals_then(edition::DEFAULT_EDITION, f)
158 // If this ever becomes non thread-local, `decode_syntax_context`
159 // and `decode_expn_id` will need to be updated to handle concurrent
161 scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals);
163 // FIXME: We should use this enum or something like it to get rid of the
164 // use of magic `/rust/1.x/...` paths across the board.
165 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)]
167 pub enum RealFileName {
169 /// For remapped paths (namely paths into libstd that have been mapped
170 /// to the appropriate spot on the local host's file system, and local file
171 /// system paths that have been remapped with `FilePathMapping`),
173 /// `local_path` is the (host-dependent) local path to the file. This is
174 /// None if the file was imported from another crate
175 local_path: Option<PathBuf>,
176 /// `virtual_name` is the stable path rustc will store internally within
178 virtual_name: PathBuf,
182 impl Hash for RealFileName {
183 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
184 // To prevent #70924 from happening again we should only hash the
185 // remapped (virtualized) path if that exists. This is because
186 // virtualized paths to sysroot crates (/rust/$hash or /rust/$version)
187 // remain stable even if the corresponding local_path changes
188 self.remapped_path_if_available().hash(state)
192 // This is functionally identical to #[derive(Encodable)], with the exception of
193 // an added assert statement
194 impl<S: Encoder> Encodable<S> for RealFileName {
195 fn encode(&self, encoder: &mut S) {
197 RealFileName::LocalPath(ref local_path) => encoder.emit_enum_variant(0, |encoder| {
198 local_path.encode(encoder);
201 RealFileName::Remapped { ref local_path, ref virtual_name } => encoder
202 .emit_enum_variant(1, |encoder| {
203 // For privacy and build reproducibility, we must not embed host-dependant path in artifacts
204 // if they have been remapped by --remap-path-prefix
205 assert!(local_path.is_none());
206 local_path.encode(encoder);
207 virtual_name.encode(encoder);
214 /// Returns the path suitable for reading from the file system on the local host,
215 /// if this information exists.
216 /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
217 pub fn local_path(&self) -> Option<&Path> {
219 RealFileName::LocalPath(p) => Some(p),
220 RealFileName::Remapped { local_path, virtual_name: _ } => local_path.as_deref(),
224 /// Returns the path suitable for reading from the file system on the local host,
225 /// if this information exists.
226 /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
227 pub fn into_local_path(self) -> Option<PathBuf> {
229 RealFileName::LocalPath(p) => Some(p),
230 RealFileName::Remapped { local_path: p, virtual_name: _ } => p,
234 /// Returns the path suitable for embedding into build artifacts. This would still
235 /// be a local path if it has not been remapped. A remapped path will not correspond
236 /// to a valid file system path: see `local_path_if_available()` for something that
237 /// is more likely to return paths into the local host file system.
238 pub fn remapped_path_if_available(&self) -> &Path {
240 RealFileName::LocalPath(p)
241 | RealFileName::Remapped { local_path: _, virtual_name: p } => p,
245 /// Returns the path suitable for reading from the file system on the local host,
246 /// if this information exists. Otherwise returns the remapped name.
247 /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
248 pub fn local_path_if_available(&self) -> &Path {
250 RealFileName::LocalPath(path)
251 | RealFileName::Remapped { local_path: None, virtual_name: path }
252 | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path,
256 pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> {
258 FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(),
259 FileNameDisplayPreference::Remapped => {
260 self.remapped_path_if_available().to_string_lossy()
262 FileNameDisplayPreference::Short => self
263 .local_path_if_available()
265 .map_or_else(|| "".into(), |f| f.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 {
303 /// Display the path after the application of rewrite rules provided via `--remap-path-prefix`.
304 /// This is appropriate for paths that get embedded into files produced by the compiler.
306 /// Display the path before the application of rewrite rules provided via `--remap-path-prefix`.
307 /// This is appropriate for use in user-facing output (such as diagnostics).
309 /// Display only the filename, as a way to reduce the verbosity of the output.
310 /// This is appropriate for use in user-facing output (such as diagnostics).
314 pub struct FileNameDisplay<'a> {
316 display_pref: FileNameDisplayPreference,
319 impl fmt::Display for FileNameDisplay<'_> {
320 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324 write!(fmt, "{}", name.to_string_lossy(self.display_pref))
326 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
327 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
328 Anon(_) => write!(fmt, "<anon>"),
329 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
330 CfgSpec(_) => write!(fmt, "<cfgspec>"),
331 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
332 Custom(ref s) => write!(fmt, "<{}>", s),
333 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
334 InlineAsm(_) => write!(fmt, "<inline asm>"),
339 impl<'a> FileNameDisplay<'a> {
340 pub fn to_string_lossy(&self) -> Cow<'a, str> {
342 FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref),
343 _ => Cow::from(self.to_string()),
349 pub fn is_real(&self) -> bool {
355 | ProcMacroSourceCode(_)
361 | InlineAsm(_) => false,
365 pub fn prefer_remapped(&self) -> FileNameDisplay<'_> {
366 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped }
369 /// This may include transient local filesystem information.
370 /// Must not be embedded in build outputs.
371 pub fn prefer_local(&self) -> FileNameDisplay<'_> {
372 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local }
375 pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> {
376 FileNameDisplay { inner: self, display_pref }
379 pub fn macro_expansion_source_code(src: &str) -> FileName {
380 let mut hasher = StableHasher::new();
381 src.hash(&mut hasher);
382 FileName::MacroExpansion(hasher.finish())
385 pub fn anon_source_code(src: &str) -> FileName {
386 let mut hasher = StableHasher::new();
387 src.hash(&mut hasher);
388 FileName::Anon(hasher.finish())
391 pub fn proc_macro_source_code(src: &str) -> FileName {
392 let mut hasher = StableHasher::new();
393 src.hash(&mut hasher);
394 FileName::ProcMacroSourceCode(hasher.finish())
397 pub fn cfg_spec_source_code(src: &str) -> FileName {
398 let mut hasher = StableHasher::new();
399 src.hash(&mut hasher);
400 FileName::QuoteExpansion(hasher.finish())
403 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
404 let mut hasher = StableHasher::new();
405 src.hash(&mut hasher);
406 FileName::CliCrateAttr(hasher.finish())
409 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
410 FileName::DocTest(path, line)
413 pub fn inline_asm_source_code(src: &str) -> FileName {
414 let mut hasher = StableHasher::new();
415 src.hash(&mut hasher);
416 FileName::InlineAsm(hasher.finish())
420 /// Represents a span.
422 /// Spans represent a region of code, used for error reporting. Positions in spans
423 /// are *absolute* positions from the beginning of the [`SourceMap`], not positions
424 /// relative to [`SourceFile`]s. Methods on the `SourceMap` can be used to relate spans back
425 /// to the original source.
427 /// You must be careful if the span crosses more than one file, since you will not be
428 /// able to use many of the functions on spans in source_map and you cannot assume
429 /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the
430 /// [`BytePos`] range between files.
432 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
433 /// sent to other threads, but some pieces of performance infra run in a separate thread.
434 /// Using `Span` is generally preferred.
435 #[derive(Clone, Copy, Hash, PartialEq, Eq)]
436 pub struct SpanData {
439 /// Information about where the macro came from, if this piece of
440 /// code was created by a macro expansion.
441 pub ctxt: SyntaxContext,
442 pub parent: Option<LocalDefId>,
445 // Order spans by position in the file.
446 impl Ord for SpanData {
447 fn cmp(&self, other: &Self) -> Ordering {
452 // `LocalDefId` does not implement `Ord`.
453 // The other fields are enough to determine in-file order.
460 // `LocalDefId` does not implement `Ord`.
461 // The other fields are enough to determine in-file order.
465 (s_lo, s_hi, s_ctxt).cmp(&(o_lo, o_hi, o_ctxt))
469 impl PartialOrd for SpanData {
470 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
471 Some(self.cmp(other))
477 pub fn span(&self) -> Span {
478 Span::new(self.lo, self.hi, self.ctxt, self.parent)
481 pub fn with_lo(&self, lo: BytePos) -> Span {
482 Span::new(lo, self.hi, self.ctxt, self.parent)
485 pub fn with_hi(&self, hi: BytePos) -> Span {
486 Span::new(self.lo, hi, self.ctxt, self.parent)
489 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
490 Span::new(self.lo, self.hi, ctxt, self.parent)
493 pub fn with_parent(&self, parent: Option<LocalDefId>) -> Span {
494 Span::new(self.lo, self.hi, self.ctxt, parent)
496 /// Returns `true` if this is a dummy span with any hygienic context.
498 pub fn is_dummy(self) -> bool {
499 self.lo.0 == 0 && self.hi.0 == 0
502 pub fn is_visible(self, sm: &SourceMap) -> bool {
503 !self.is_dummy() && sm.is_span_accessible(self.span())
505 /// Returns `true` if `self` fully encloses `other`.
506 pub fn contains(self, other: Self) -> bool {
507 self.lo <= other.lo && other.hi <= self.hi
511 // The interner is pointed to by a thread local value which is only set on the main thread
512 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
513 // to avoid panics and other errors, even though it would be memory safe to do so.
514 #[cfg(not(parallel_compiler))]
515 impl !Send for Span {}
516 #[cfg(not(parallel_compiler))]
517 impl !Sync for Span {}
519 impl PartialOrd for Span {
520 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
521 PartialOrd::partial_cmp(&self.data(), &rhs.data())
525 fn cmp(&self, rhs: &Self) -> Ordering {
526 Ord::cmp(&self.data(), &rhs.data())
532 pub fn lo(self) -> BytePos {
536 pub fn with_lo(self, lo: BytePos) -> Span {
537 self.data().with_lo(lo)
540 pub fn hi(self) -> BytePos {
544 pub fn with_hi(self, hi: BytePos) -> Span {
545 self.data().with_hi(hi)
548 pub fn eq_ctxt(self, other: Span) -> bool {
549 self.data_untracked().ctxt == other.data_untracked().ctxt
552 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
553 self.data_untracked().with_ctxt(ctxt)
556 pub fn parent(self) -> Option<LocalDefId> {
560 pub fn with_parent(self, ctxt: Option<LocalDefId>) -> Span {
561 self.data().with_parent(ctxt)
564 /// Returns `true` if this is a dummy span with any hygienic context.
566 pub fn is_dummy(self) -> bool {
567 self.data_untracked().is_dummy()
571 pub fn is_visible(self, sm: &SourceMap) -> bool {
572 self.data_untracked().is_visible(sm)
575 /// Returns `true` if this span comes from any kind of macro, desugaring or inlining.
577 pub fn from_expansion(self) -> bool {
578 self.ctxt() != SyntaxContext::root()
581 /// Returns `true` if `span` originates in a macro's expansion where debuginfo should be
583 pub fn in_macro_expansion_with_collapse_debuginfo(self) -> bool {
584 let outer_expn = self.ctxt().outer_expn_data();
585 matches!(outer_expn.kind, ExpnKind::Macro(..)) && outer_expn.collapse_debuginfo
588 /// Returns `true` if this span comes from MIR inlining.
589 pub fn is_inlined(self) -> bool {
590 let outer_expn = self.ctxt().outer_expn_data();
591 matches!(outer_expn.kind, ExpnKind::Inlined)
594 /// Returns `true` if `span` originates in a derive-macro's expansion.
595 pub fn in_derive_expansion(self) -> bool {
596 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
599 /// Gate suggestions that would not be appropriate in a context the user didn't write.
600 pub fn can_be_used_for_suggestions(self) -> bool {
601 !self.from_expansion()
602 // FIXME: If this span comes from a `derive` macro but it points at code the user wrote,
603 // the callsite span and the span will be pointing at different places. It also means that
604 // we can safely provide suggestions on this span.
605 || (matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
606 && self.parent_callsite().map(|p| (p.lo(), p.hi())) != Some((self.lo(), self.hi())))
610 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
611 Span::new(lo, hi, SyntaxContext::root(), None)
614 /// Returns a new span representing an empty span at the beginning of this span.
616 pub fn shrink_to_lo(self) -> Span {
617 let span = self.data_untracked();
618 span.with_hi(span.lo)
620 /// Returns a new span representing an empty span at the end of this span.
622 pub fn shrink_to_hi(self) -> Span {
623 let span = self.data_untracked();
624 span.with_lo(span.hi)
628 /// Returns `true` if `hi == lo`.
629 pub fn is_empty(self) -> bool {
630 let span = self.data_untracked();
634 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
635 pub fn substitute_dummy(self, other: Span) -> Span {
636 if self.is_dummy() { other } else { self }
639 /// Returns `true` if `self` fully encloses `other`.
640 pub fn contains(self, other: Span) -> bool {
641 let span = self.data();
642 let other = other.data();
646 /// Returns `true` if `self` touches `other`.
647 pub fn overlaps(self, other: Span) -> bool {
648 let span = self.data();
649 let other = other.data();
650 span.lo < other.hi && other.lo < span.hi
653 /// Returns `true` if the spans are equal with regards to the source text.
655 /// Use this instead of `==` when either span could be generated code,
656 /// and you only care that they point to the same bytes of source text.
657 pub fn source_equal(self, other: Span) -> bool {
658 let span = self.data();
659 let other = other.data();
660 span.lo == other.lo && span.hi == other.hi
663 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
664 pub fn trim_start(self, other: Span) -> Option<Span> {
665 let span = self.data();
666 let other = other.data();
667 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
670 /// Returns the source span -- this is either the supplied span, or the span for
671 /// the macro callsite that expanded to it.
672 pub fn source_callsite(self) -> Span {
673 let expn_data = self.ctxt().outer_expn_data();
674 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
677 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
679 pub fn parent_callsite(self) -> Option<Span> {
680 let expn_data = self.ctxt().outer_expn_data();
681 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
684 /// Walk down the expansion ancestors to find a span that's contained within `outer`.
685 pub fn find_ancestor_inside(mut self, outer: Span) -> Option<Span> {
686 while !outer.contains(self) {
687 self = self.parent_callsite()?;
692 /// Like `find_ancestor_inside`, but specifically for when spans might not
693 /// overlaps. Take care when using this, and prefer `find_ancestor_inside`
694 /// when you know that the spans are nested (modulo macro expansion).
695 pub fn find_ancestor_in_same_ctxt(mut self, other: Span) -> Option<Span> {
696 while !Span::eq_ctxt(self, other) {
697 self = self.parent_callsite()?;
702 /// Edition of the crate from which this span came.
703 pub fn edition(self) -> edition::Edition {
704 self.ctxt().edition()
708 pub fn rust_2015(self) -> bool {
709 self.edition() == edition::Edition::Edition2015
713 pub fn rust_2018(self) -> bool {
714 self.edition() >= edition::Edition::Edition2018
718 pub fn rust_2021(self) -> bool {
719 self.edition() >= edition::Edition::Edition2021
723 pub fn rust_2024(self) -> bool {
724 self.edition() >= edition::Edition::Edition2024
727 /// Returns the source callee.
729 /// Returns `None` if the supplied span has no expansion trace,
730 /// else returns the `ExpnData` for the macro definition
731 /// corresponding to the source callsite.
732 pub fn source_callee(self) -> Option<ExpnData> {
733 fn source_callee(expn_data: ExpnData) -> ExpnData {
734 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
735 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
737 let expn_data = self.ctxt().outer_expn_data();
738 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
741 /// Checks if a span is "internal" to a macro in which `#[unstable]`
742 /// items can be used (that is, a macro marked with
743 /// `#[allow_internal_unstable]`).
744 pub fn allows_unstable(self, feature: Symbol) -> bool {
747 .allow_internal_unstable
748 .map_or(false, |features| features.iter().any(|&f| f == feature))
751 /// Checks if this span arises from a compiler desugaring of kind `kind`.
752 pub fn is_desugaring(self, kind: DesugaringKind) -> bool {
753 match self.ctxt().outer_expn_data().kind {
754 ExpnKind::Desugaring(k) => k == kind,
759 /// Returns the compiler desugaring that created this span, or `None`
760 /// if this span is not from a desugaring.
761 pub fn desugaring_kind(self) -> Option<DesugaringKind> {
762 match self.ctxt().outer_expn_data().kind {
763 ExpnKind::Desugaring(k) => Some(k),
768 /// Checks if a span is "internal" to a macro in which `unsafe`
769 /// can be used without triggering the `unsafe_code` lint.
770 /// (that is, a macro marked with `#[allow_internal_unsafe]`).
771 pub fn allows_unsafe(self) -> bool {
772 self.ctxt().outer_expn_data().allow_internal_unsafe
775 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
776 let mut prev_span = DUMMY_SP;
777 std::iter::from_fn(move || {
779 let expn_data = self.ctxt().outer_expn_data();
780 if expn_data.is_root() {
784 let is_recursive = expn_data.call_site.source_equal(prev_span);
787 self = expn_data.call_site;
789 // Don't print recursive invocations.
791 return Some(expn_data);
797 /// Returns a `Span` that would enclose both `self` and `end`.
799 /// Note that this can also be used to extend the span "backwards":
800 /// `start.to(end)` and `end.to(start)` return the same `Span`.
804 /// self lorem ipsum end
805 /// ^^^^^^^^^^^^^^^^^^^^
807 pub fn to(self, end: Span) -> Span {
808 let span_data = self.data();
809 let end_data = end.data();
810 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
811 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
812 // have an incomplete span than a completely nonsensical one.
813 if span_data.ctxt != end_data.ctxt {
814 if span_data.ctxt == SyntaxContext::root() {
816 } else if end_data.ctxt == SyntaxContext::root() {
819 // Both spans fall within a macro.
820 // FIXME(estebank): check if it is the *same* macro.
823 cmp::min(span_data.lo, end_data.lo),
824 cmp::max(span_data.hi, end_data.hi),
825 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
826 if span_data.parent == end_data.parent { span_data.parent } else { None },
830 /// Returns a `Span` between the end of `self` to the beginning of `end`.
834 /// self lorem ipsum end
837 pub fn between(self, end: Span) -> Span {
838 let span = self.data();
839 let end = end.data();
843 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
844 if span.parent == end.parent { span.parent } else { None },
848 /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
852 /// self lorem ipsum end
853 /// ^^^^^^^^^^^^^^^^^
855 pub fn until(self, end: Span) -> Span {
856 // Most of this function's body is copied from `to`.
857 // We can't just do `self.to(end.shrink_to_lo())`,
858 // because to also does some magic where it uses min/max so
859 // it can handle overlapping spans. Some advanced mis-use of
860 // `until` with different ctxts makes this visible.
861 let span_data = self.data();
862 let end_data = end.data();
863 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
864 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
865 // have an incomplete span than a completely nonsensical one.
866 if span_data.ctxt != end_data.ctxt {
867 if span_data.ctxt == SyntaxContext::root() {
869 } else if end_data.ctxt == SyntaxContext::root() {
872 // Both spans fall within a macro.
873 // FIXME(estebank): check if it is the *same* macro.
878 if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
879 if span_data.parent == end_data.parent { span_data.parent } else { None },
883 pub fn from_inner(self, inner: InnerSpan) -> Span {
884 let span = self.data();
886 span.lo + BytePos::from_usize(inner.start),
887 span.lo + BytePos::from_usize(inner.end),
893 /// Equivalent of `Span::def_site` from the proc macro API,
894 /// except that the location is taken from the `self` span.
895 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
896 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
899 /// Equivalent of `Span::call_site` from the proc macro API,
900 /// except that the location is taken from the `self` span.
901 pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span {
902 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
905 /// Equivalent of `Span::mixed_site` from the proc macro API,
906 /// except that the location is taken from the `self` span.
907 pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span {
908 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
911 /// Produces a span with the same location as `self` and context produced by a macro with the
912 /// given ID and transparency, assuming that macro was defined directly and not produced by
913 /// some other macro (which is the case for built-in and procedural macros).
914 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
915 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
919 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
920 let span = self.data();
921 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
925 pub fn remove_mark(&mut self) -> ExpnId {
926 let mut span = self.data();
927 let mark = span.ctxt.remove_mark();
928 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
933 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
934 let mut span = self.data();
935 let mark = span.ctxt.adjust(expn_id);
936 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
941 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
942 let mut span = self.data();
943 let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
944 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
949 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
950 let mut span = self.data();
951 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
952 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
957 pub fn reverse_glob_adjust(
961 ) -> Option<Option<ExpnId>> {
962 let mut span = self.data();
963 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
964 *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
969 pub fn normalize_to_macros_2_0(self) -> Span {
970 let span = self.data();
971 span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
975 pub fn normalize_to_macro_rules(self) -> Span {
976 let span = self.data();
977 span.with_ctxt(span.ctxt.normalize_to_macro_rules())
981 impl Default for Span {
982 fn default() -> Self {
987 impl<E: Encoder> Encodable<E> for Span {
988 default fn encode(&self, s: &mut E) {
989 let span = self.data();
994 impl<D: Decoder> Decodable<D> for Span {
995 default fn decode(s: &mut D) -> Span {
996 let lo = Decodable::decode(s);
997 let hi = Decodable::decode(s);
999 Span::new(lo, hi, SyntaxContext::root(), None)
1003 /// Calls the provided closure, using the provided `SourceMap` to format
1004 /// any spans that are debug-printed during the closure's execution.
1006 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
1007 /// (see `rustc_interface::callbacks::span_debug1`). However, some parts
1008 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
1009 /// a `TyCtxt` is available. In this case, we fall back to
1010 /// the `SourceMap` provided to this function. If that is not available,
1011 /// we fall back to printing the raw `Span` field values.
1012 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
1013 with_session_globals(|session_globals| {
1014 *session_globals.source_map.borrow_mut() = Some(source_map);
1016 struct ClearSourceMap;
1017 impl Drop for ClearSourceMap {
1018 fn drop(&mut self) {
1019 with_session_globals(|session_globals| {
1020 session_globals.source_map.borrow_mut().take();
1025 let _guard = ClearSourceMap;
1029 impl fmt::Debug for Span {
1030 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1031 with_session_globals(|session_globals| {
1032 if let Some(source_map) = &*session_globals.source_map.borrow() {
1033 write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(*self), self.ctxt())
1035 f.debug_struct("Span")
1036 .field("lo", &self.lo())
1037 .field("hi", &self.hi())
1038 .field("ctxt", &self.ctxt())
1045 impl fmt::Debug for SpanData {
1046 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1047 fmt::Debug::fmt(&Span::new(self.lo, self.hi, self.ctxt, self.parent), f)
1051 /// Identifies an offset of a multi-byte character in a `SourceFile`.
1052 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1053 pub struct MultiByteChar {
1054 /// The absolute offset of the character in the `SourceMap`.
1056 /// The number of bytes, `>= 2`.
1060 /// Identifies an offset of a non-narrow character in a `SourceFile`.
1061 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1062 pub enum NonNarrowChar {
1063 /// Represents a zero-width character.
1065 /// Represents a wide (full-width) character.
1067 /// Represents a tab character, represented visually with a width of 4 characters.
1071 impl NonNarrowChar {
1072 fn new(pos: BytePos, width: usize) -> Self {
1074 0 => NonNarrowChar::ZeroWidth(pos),
1075 2 => NonNarrowChar::Wide(pos),
1076 4 => NonNarrowChar::Tab(pos),
1077 _ => panic!("width {} given for non-narrow character", width),
1081 /// Returns the absolute offset of the character in the `SourceMap`.
1082 pub fn pos(&self) -> BytePos {
1084 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
1088 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
1089 pub fn width(&self) -> usize {
1091 NonNarrowChar::ZeroWidth(_) => 0,
1092 NonNarrowChar::Wide(_) => 2,
1093 NonNarrowChar::Tab(_) => 4,
1098 impl Add<BytePos> for NonNarrowChar {
1101 fn add(self, rhs: BytePos) -> Self {
1103 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
1104 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
1105 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
1110 impl Sub<BytePos> for NonNarrowChar {
1113 fn sub(self, rhs: BytePos) -> Self {
1115 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
1116 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
1117 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
1122 /// Identifies an offset of a character that was normalized away from `SourceFile`.
1123 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1124 pub struct NormalizedPos {
1125 /// The absolute offset of the character in the `SourceMap`.
1127 /// The difference between original and normalized string at position.
1131 #[derive(PartialEq, Eq, Clone, Debug)]
1132 pub enum ExternalSource {
1133 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
1136 kind: ExternalSourceKind,
1137 /// Index of the file inside metadata.
1138 metadata_index: u32,
1142 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1143 #[derive(PartialEq, Eq, Clone, Debug)]
1144 pub enum ExternalSourceKind {
1145 /// The external source has been loaded already.
1146 Present(Lrc<String>),
1147 /// No attempt has been made to load the external source.
1149 /// A failed attempt has been made to load the external source.
1154 impl ExternalSource {
1155 pub fn get_source(&self) -> Option<&Lrc<String>> {
1157 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1164 pub struct OffsetOverflowError;
1166 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1167 #[derive(HashStable_Generic)]
1168 pub enum SourceFileHashAlgorithm {
1174 impl FromStr for SourceFileHashAlgorithm {
1177 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1179 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1180 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1181 "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1187 /// The hash of the on-disk source file used for debug info.
1188 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
1189 #[derive(HashStable_Generic, Encodable, Decodable)]
1190 pub struct SourceFileHash {
1191 pub kind: SourceFileHashAlgorithm,
1195 impl SourceFileHash {
1196 pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1197 let mut hash = SourceFileHash { kind, value: Default::default() };
1198 let len = hash.hash_len();
1199 let value = &mut hash.value[..len];
1200 let data = src.as_bytes();
1202 SourceFileHashAlgorithm::Md5 => {
1203 value.copy_from_slice(&Md5::digest(data));
1205 SourceFileHashAlgorithm::Sha1 => {
1206 value.copy_from_slice(&Sha1::digest(data));
1208 SourceFileHashAlgorithm::Sha256 => {
1209 value.copy_from_slice(&Sha256::digest(data));
1215 /// Check if the stored hash matches the hash of the string.
1216 pub fn matches(&self, src: &str) -> bool {
1217 Self::new(self.kind, src) == *self
1220 /// The bytes of the hash.
1221 pub fn hash_bytes(&self) -> &[u8] {
1222 let len = self.hash_len();
1226 fn hash_len(&self) -> usize {
1228 SourceFileHashAlgorithm::Md5 => 16,
1229 SourceFileHashAlgorithm::Sha1 => 20,
1230 SourceFileHashAlgorithm::Sha256 => 32,
1235 #[derive(HashStable_Generic)]
1236 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug, Encodable, Decodable)]
1237 pub enum DebuggerVisualizerType {
1242 /// A single debugger visualizer file.
1243 #[derive(HashStable_Generic)]
1244 #[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable)]
1245 pub struct DebuggerVisualizerFile {
1246 /// The complete debugger visualizer source.
1248 /// Indicates which visualizer type this targets.
1249 pub visualizer_type: DebuggerVisualizerType,
1252 impl DebuggerVisualizerFile {
1253 pub fn new(src: Arc<[u8]>, visualizer_type: DebuggerVisualizerType) -> Self {
1254 DebuggerVisualizerFile { src, visualizer_type }
1259 pub enum SourceFileLines {
1260 /// The source file lines, in decoded (random-access) form.
1261 Lines(Vec<BytePos>),
1263 /// The source file lines, in undecoded difference list form.
1264 Diffs(SourceFileDiffs),
1267 impl SourceFileLines {
1268 pub fn is_lines(&self) -> bool {
1269 matches!(self, SourceFileLines::Lines(_))
1273 /// The source file lines in difference list form. This matches the form
1274 /// used within metadata, which saves space by exploiting the fact that the
1275 /// lines list is sorted and individual lines are usually not that long.
1277 /// We read it directly from metadata and only decode it into `Lines` form
1278 /// when necessary. This is a significant performance win, especially for
1279 /// small crates where very little of `std`'s metadata is used.
1281 pub struct SourceFileDiffs {
1282 /// Position of the first line. Note that this is always encoded as a
1283 /// `BytePos` because it is often much larger than any of the
1285 line_start: BytePos,
1287 /// Always 1, 2, or 4. Always as small as possible, while being big
1288 /// enough to hold the length of the longest line in the source file.
1289 /// The 1 case is by far the most common.
1290 bytes_per_diff: usize,
1292 /// The number of diffs encoded in `raw_diffs`. Always one less than
1293 /// the number of lines in the source file.
1296 /// The diffs in "raw" form. Each segment of `bytes_per_diff` length
1297 /// encodes one little-endian diff. Note that they aren't LEB128
1298 /// encoded. This makes for much faster decoding. Besides, the
1299 /// bytes_per_diff==1 case is by far the most common, and LEB128
1300 /// encoding has no effect on that case.
1304 /// A single source in the [`SourceMap`].
1306 pub struct SourceFile {
1307 /// The name of the file that the source came from. Source that doesn't
1308 /// originate from files has names between angle brackets by convention
1309 /// (e.g., `<anon>`).
1311 /// The complete source code.
1312 pub src: Option<Lrc<String>>,
1313 /// The source code's hash.
1314 pub src_hash: SourceFileHash,
1315 /// The external source code (used for external crates, which will have a `None`
1316 /// value as `self.src`.
1317 pub external_src: Lock<ExternalSource>,
1318 /// The start position of this source in the `SourceMap`.
1319 pub start_pos: BytePos,
1320 /// The end position of this source in the `SourceMap`.
1321 pub end_pos: BytePos,
1322 /// Locations of lines beginnings in the source code.
1323 pub lines: Lock<SourceFileLines>,
1324 /// Locations of multi-byte characters in the source code.
1325 pub multibyte_chars: Vec<MultiByteChar>,
1326 /// Width of characters that are not narrow in the source code.
1327 pub non_narrow_chars: Vec<NonNarrowChar>,
1328 /// Locations of characters removed during normalization.
1329 pub normalized_pos: Vec<NormalizedPos>,
1330 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1331 pub name_hash: u128,
1332 /// Indicates which crate this `SourceFile` was imported from.
1336 impl<S: Encoder> Encodable<S> for SourceFile {
1337 fn encode(&self, s: &mut S) {
1338 self.name.encode(s);
1339 self.src_hash.encode(s);
1340 self.start_pos.encode(s);
1341 self.end_pos.encode(s);
1343 // We are always in `Lines` form by the time we reach here.
1344 assert!(self.lines.borrow().is_lines());
1345 self.lines(|lines| {
1346 // Store the length.
1347 s.emit_u32(lines.len() as u32);
1349 // Compute and store the difference list.
1350 if lines.len() != 0 {
1351 let max_line_length = if lines.len() == 1 {
1356 .map(|&[fst, snd]| snd - fst)
1357 .map(|bp| bp.to_usize())
1362 let bytes_per_diff: usize = match max_line_length {
1364 0x100..=0xFFFF => 2,
1368 // Encode the number of bytes used per diff.
1369 s.emit_u8(bytes_per_diff as u8);
1371 // Encode the first element.
1374 // Encode the difference list.
1375 let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst);
1376 let num_diffs = lines.len() - 1;
1378 match bytes_per_diff {
1380 raw_diffs = Vec::with_capacity(num_diffs);
1381 for diff in diff_iter {
1382 raw_diffs.push(diff.0 as u8);
1386 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
1387 for diff in diff_iter {
1388 raw_diffs.extend_from_slice(&(diff.0 as u16).to_le_bytes());
1392 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
1393 for diff in diff_iter {
1394 raw_diffs.extend_from_slice(&(diff.0).to_le_bytes());
1397 _ => unreachable!(),
1399 s.emit_raw_bytes(&raw_diffs);
1403 self.multibyte_chars.encode(s);
1404 self.non_narrow_chars.encode(s);
1405 self.name_hash.encode(s);
1406 self.normalized_pos.encode(s);
1407 self.cnum.encode(s);
1411 impl<D: Decoder> Decodable<D> for SourceFile {
1412 fn decode(d: &mut D) -> SourceFile {
1413 let name: FileName = Decodable::decode(d);
1414 let src_hash: SourceFileHash = Decodable::decode(d);
1415 let start_pos: BytePos = Decodable::decode(d);
1416 let end_pos: BytePos = Decodable::decode(d);
1418 let num_lines: u32 = Decodable::decode(d);
1420 // Read the number of bytes used per diff.
1421 let bytes_per_diff = d.read_u8() as usize;
1423 // Read the first element.
1424 let line_start: BytePos = Decodable::decode(d);
1426 // Read the difference list.
1427 let num_diffs = num_lines as usize - 1;
1428 let raw_diffs = d.read_raw_bytes(bytes_per_diff * num_diffs).to_vec();
1429 SourceFileLines::Diffs(SourceFileDiffs {
1436 SourceFileLines::Lines(vec![])
1439 let multibyte_chars: Vec<MultiByteChar> = Decodable::decode(d);
1440 let non_narrow_chars: Vec<NonNarrowChar> = Decodable::decode(d);
1441 let name_hash: u128 = Decodable::decode(d);
1442 let normalized_pos: Vec<NormalizedPos> = Decodable::decode(d);
1443 let cnum: CrateNum = Decodable::decode(d);
1450 // Unused - the metadata decoder will construct
1451 // a new SourceFile, filling in `external_src` properly
1452 external_src: Lock::new(ExternalSource::Unneeded),
1453 lines: Lock::new(lines),
1463 impl fmt::Debug for SourceFile {
1464 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1465 write!(fmt, "SourceFile({:?})", self.name)
1474 hash_kind: SourceFileHashAlgorithm,
1476 // Compute the file hash before any normalization.
1477 let src_hash = SourceFileHash::new(hash_kind, &src);
1478 let normalized_pos = normalize_src(&mut src, start_pos);
1481 let mut hasher: StableHasher = StableHasher::new();
1482 name.hash(&mut hasher);
1483 hasher.finish::<u128>()
1485 let end_pos = start_pos.to_usize() + src.len();
1486 assert!(end_pos <= u32::MAX as usize);
1488 let (lines, multibyte_chars, non_narrow_chars) =
1489 analyze_source_file::analyze_source_file(&src, start_pos);
1493 src: Some(Lrc::new(src)),
1495 external_src: Lock::new(ExternalSource::Unneeded),
1497 end_pos: Pos::from_usize(end_pos),
1498 lines: Lock::new(SourceFileLines::Lines(lines)),
1507 pub fn lines<F, R>(&self, f: F) -> R
1509 F: FnOnce(&[BytePos]) -> R,
1511 let mut guard = self.lines.borrow_mut();
1513 SourceFileLines::Lines(lines) => f(lines),
1514 SourceFileLines::Diffs(SourceFileDiffs {
1520 // Convert from "diffs" form to "lines" form.
1521 let num_lines = num_diffs + 1;
1522 let mut lines = Vec::with_capacity(num_lines);
1523 lines.push(line_start);
1525 assert_eq!(*num_diffs, raw_diffs.len() / bytes_per_diff);
1526 match bytes_per_diff {
1528 lines.extend(raw_diffs.into_iter().map(|&diff| {
1529 line_start = line_start + BytePos(diff as u32);
1534 lines.extend((0..*num_diffs).map(|i| {
1535 let pos = bytes_per_diff * i;
1536 let bytes = [raw_diffs[pos], raw_diffs[pos + 1]];
1537 let diff = u16::from_le_bytes(bytes);
1538 line_start = line_start + BytePos(diff as u32);
1543 lines.extend((0..*num_diffs).map(|i| {
1544 let pos = bytes_per_diff * i;
1551 let diff = u32::from_le_bytes(bytes);
1552 line_start = line_start + BytePos(diff);
1556 _ => unreachable!(),
1558 let res = f(&lines);
1559 *guard = SourceFileLines::Lines(lines);
1565 /// Returns the `BytePos` of the beginning of the current line.
1566 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1567 let line_index = self.lookup_line(pos).unwrap();
1568 self.lines(|lines| lines[line_index])
1571 /// Add externally loaded source.
1572 /// If the hash of the input doesn't match or no input is supplied via None,
1573 /// it is interpreted as an error and the corresponding enum variant is set.
1574 /// The return value signifies whether some kind of source is present.
1575 pub fn add_external_src<F>(&self, get_src: F) -> bool
1577 F: FnOnce() -> Option<String>,
1580 *self.external_src.borrow(),
1581 ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1583 let src = get_src();
1584 let mut external_src = self.external_src.borrow_mut();
1585 // Check that no-one else have provided the source while we were getting it
1586 if let ExternalSource::Foreign {
1587 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1588 } = &mut *external_src
1590 if let Some(mut src) = src {
1591 // The src_hash needs to be computed on the pre-normalized src.
1592 if self.src_hash.matches(&src) {
1593 normalize_src(&mut src, BytePos::from_usize(0));
1594 *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1598 *src_kind = ExternalSourceKind::AbsentErr;
1603 self.src.is_some() || external_src.get_source().is_some()
1606 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1610 /// Gets a line from the list of pre-computed line-beginnings.
1611 /// The line number here is 0-based.
1612 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1613 fn get_until_newline(src: &str, begin: usize) -> &str {
1614 // We can't use `lines.get(line_number+1)` because we might
1615 // be parsing when we call this function and thus the current
1616 // line is the last one we have line info for.
1617 let slice = &src[begin..];
1618 match slice.find('\n') {
1619 Some(e) => &slice[..e],
1625 let line = self.lines(|lines| lines.get(line_number).copied())?;
1626 let begin: BytePos = line - self.start_pos;
1630 if let Some(ref src) = self.src {
1631 Some(Cow::from(get_until_newline(src, begin)))
1632 } else if let Some(src) = self.external_src.borrow().get_source() {
1633 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1639 pub fn is_real_file(&self) -> bool {
1644 pub fn is_imported(&self) -> bool {
1648 pub fn count_lines(&self) -> usize {
1649 self.lines(|lines| lines.len())
1652 /// Finds the line containing the given position. The return value is the
1653 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1654 /// number. If the source_file is empty or the position is located before the
1655 /// first line, `None` is returned.
1656 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1657 self.lines(|lines| lines.partition_point(|x| x <= &pos).checked_sub(1))
1660 pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
1661 if self.is_empty() {
1662 return self.start_pos..self.end_pos;
1665 self.lines(|lines| {
1666 assert!(line_index < lines.len());
1667 if line_index == (lines.len() - 1) {
1668 lines[line_index]..self.end_pos
1670 lines[line_index]..lines[line_index + 1]
1675 /// Returns whether or not the file contains the given `SourceMap` byte
1676 /// position. The position one past the end of the file is considered to be
1677 /// contained by the file. This implies that files for which `is_empty`
1678 /// returns true still contain one byte position according to this function.
1680 pub fn contains(&self, byte_pos: BytePos) -> bool {
1681 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1685 pub fn is_empty(&self) -> bool {
1686 self.start_pos == self.end_pos
1689 /// Calculates the original byte position relative to the start of the file
1690 /// based on the given byte position.
1691 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1692 // Diff before any records is 0. Otherwise use the previously recorded
1693 // diff as that applies to the following characters until a new diff
1695 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1696 Ok(i) => self.normalized_pos[i].diff,
1697 Err(i) if i == 0 => 0,
1698 Err(i) => self.normalized_pos[i - 1].diff,
1701 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1704 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1705 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1706 // The number of extra bytes due to multibyte chars in the `SourceFile`.
1707 let mut total_extra_bytes = 0;
1709 for mbc in self.multibyte_chars.iter() {
1710 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1712 // Every character is at least one byte, so we only
1713 // count the actual extra bytes.
1714 total_extra_bytes += mbc.bytes as u32 - 1;
1715 // We should never see a byte position in the middle of a
1717 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1723 assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1724 CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1727 /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1728 /// given `BytePos`.
1729 pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1730 let chpos = self.bytepos_to_file_charpos(pos);
1731 match self.lookup_line(pos) {
1733 let line = a + 1; // Line numbers start at 1
1734 let linebpos = self.lines(|lines| lines[a]);
1735 let linechpos = self.bytepos_to_file_charpos(linebpos);
1736 let col = chpos - linechpos;
1737 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1738 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1739 debug!("byte is on line: {}", line);
1740 assert!(chpos >= linechpos);
1747 /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1748 /// column offset when displayed, for a given `BytePos`.
1749 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1750 let (line, col_or_chpos) = self.lookup_file_pos(pos);
1752 let col = col_or_chpos;
1753 let linebpos = self.lines(|lines| lines[line - 1]);
1755 let start_width_idx = self
1757 .binary_search_by_key(&linebpos, |x| x.pos())
1758 .unwrap_or_else(|x| x);
1759 let end_width_idx = self
1761 .binary_search_by_key(&pos, |x| x.pos())
1762 .unwrap_or_else(|x| x);
1763 let special_chars = end_width_idx - start_width_idx;
1764 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1768 col.0 - special_chars + non_narrow
1770 (line, col, col_display)
1772 let chpos = col_or_chpos;
1774 let end_width_idx = self
1776 .binary_search_by_key(&pos, |x| x.pos())
1777 .unwrap_or_else(|x| x);
1778 let non_narrow: usize =
1779 self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1780 chpos.0 - end_width_idx + non_narrow
1782 (0, chpos, col_display)
1787 /// Normalizes the source code and records the normalizations.
1788 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1789 let mut normalized_pos = vec![];
1790 remove_bom(src, &mut normalized_pos);
1791 normalize_newlines(src, &mut normalized_pos);
1793 // Offset all the positions by start_pos to match the final file positions.
1794 for np in &mut normalized_pos {
1795 np.pos.0 += start_pos.0;
1801 /// Removes UTF-8 BOM, if any.
1802 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1803 if src.starts_with('\u{feff}') {
1805 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1809 /// Replaces `\r\n` with `\n` in-place in `src`.
1811 /// Returns error if there's a lone `\r` in the string.
1812 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1813 if !src.as_bytes().contains(&b'\r') {
1817 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1818 // While we *can* call `as_mut_vec` and do surgery on the live string
1819 // directly, let's rather steal the contents of `src`. This makes the code
1820 // safe even if a panic occurs.
1822 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1823 let mut gap_len = 0;
1824 let mut tail = buf.as_mut_slice();
1826 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1828 let idx = match find_crlf(&tail[gap_len..]) {
1830 Some(idx) => idx + gap_len,
1832 tail.copy_within(gap_len..idx, 0);
1833 tail = &mut tail[idx - gap_len..];
1834 if tail.len() == gap_len {
1837 cursor += idx - gap_len;
1839 normalized_pos.push(NormalizedPos {
1840 pos: BytePos::from_usize(cursor + 1),
1841 diff: original_gap + gap_len as u32,
1845 // Account for removed `\r`.
1846 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1847 let new_len = buf.len() - gap_len;
1849 buf.set_len(new_len);
1850 *src = String::from_utf8_unchecked(buf);
1853 fn find_crlf(src: &[u8]) -> Option<usize> {
1854 let mut search_idx = 0;
1855 while let Some(idx) = find_cr(&src[search_idx..]) {
1856 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1857 search_idx += idx + 1;
1860 return Some(search_idx + idx);
1865 fn find_cr(src: &[u8]) -> Option<usize> {
1866 src.iter().position(|&b| b == b'\r')
1870 // _____________________________________________________________________________
1871 // Pos, BytePos, CharPos
1875 fn from_usize(n: usize) -> Self;
1876 fn to_usize(&self) -> usize;
1877 fn from_u32(n: u32) -> Self;
1878 fn to_u32(&self) -> u32;
1881 macro_rules! impl_pos {
1885 $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1890 $vis struct $ident($inner_vis $inner_ty);
1892 impl Pos for $ident {
1894 fn from_usize(n: usize) -> $ident {
1895 $ident(n as $inner_ty)
1899 fn to_usize(&self) -> usize {
1904 fn from_u32(n: u32) -> $ident {
1905 $ident(n as $inner_ty)
1909 fn to_u32(&self) -> u32 {
1914 impl Add for $ident {
1915 type Output = $ident;
1918 fn add(self, rhs: $ident) -> $ident {
1919 $ident(self.0 + rhs.0)
1923 impl Sub for $ident {
1924 type Output = $ident;
1927 fn sub(self, rhs: $ident) -> $ident {
1928 $ident(self.0 - rhs.0)
1938 /// Keep this small (currently 32-bits), as AST contains a lot of them.
1939 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1940 pub struct BytePos(pub u32);
1942 /// A character offset.
1944 /// Because of multibyte UTF-8 characters, a byte offset
1945 /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`]
1946 /// values to `CharPos` values as necessary.
1947 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1948 pub struct CharPos(pub usize);
1951 impl<S: Encoder> Encodable<S> for BytePos {
1952 fn encode(&self, s: &mut S) {
1957 impl<D: Decoder> Decodable<D> for BytePos {
1958 fn decode(d: &mut D) -> BytePos {
1959 BytePos(d.read_u32())
1963 // _____________________________________________________________________________
1964 // Loc, SourceFileAndLine, SourceFileAndBytePos
1967 /// A source code location used for error reporting.
1968 #[derive(Debug, Clone)]
1970 /// Information about the original source.
1971 pub file: Lrc<SourceFile>,
1972 /// The (1-based) line number.
1974 /// The (0-based) column offset.
1976 /// The (0-based) column offset when displayed.
1977 pub col_display: usize,
1980 // Used to be structural records.
1982 pub struct SourceFileAndLine {
1983 pub sf: Lrc<SourceFile>,
1984 /// Index of line, starting from 0.
1988 pub struct SourceFileAndBytePos {
1989 pub sf: Lrc<SourceFile>,
1993 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1994 pub struct LineInfo {
1995 /// Index of line, starting from 0.
1996 pub line_index: usize,
1998 /// Column in line where span begins, starting from 0.
1999 pub start_col: CharPos,
2001 /// Column in line where span ends, starting from 0, exclusive.
2002 pub end_col: CharPos,
2005 pub struct FileLines {
2006 pub file: Lrc<SourceFile>,
2007 pub lines: Vec<LineInfo>,
2010 pub static SPAN_TRACK: AtomicRef<fn(LocalDefId)> = AtomicRef::new(&((|_| {}) as fn(_)));
2012 // _____________________________________________________________________________
2013 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
2016 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
2018 #[derive(Clone, PartialEq, Eq, Debug)]
2019 pub enum SpanLinesError {
2020 DistinctSources(DistinctSources),
2023 #[derive(Clone, PartialEq, Eq, Debug)]
2024 pub enum SpanSnippetError {
2025 IllFormedSpan(Span),
2026 DistinctSources(DistinctSources),
2027 MalformedForSourcemap(MalformedSourceMapPositions),
2028 SourceNotAvailable { filename: FileName },
2031 #[derive(Clone, PartialEq, Eq, Debug)]
2032 pub struct DistinctSources {
2033 pub begin: (FileName, BytePos),
2034 pub end: (FileName, BytePos),
2037 #[derive(Clone, PartialEq, Eq, Debug)]
2038 pub struct MalformedSourceMapPositions {
2040 pub source_len: usize,
2041 pub begin_pos: BytePos,
2042 pub end_pos: BytePos,
2045 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
2046 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2047 pub struct InnerSpan {
2053 pub fn new(start: usize, end: usize) -> InnerSpan {
2054 InnerSpan { start, end }
2058 /// Requirements for a `StableHashingContext` to be used in this crate.
2060 /// This is a hack to allow using the [`HashStable_Generic`] derive macro
2061 /// instead of implementing everything in rustc_middle.
2062 pub trait HashStableContext {
2063 fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
2064 fn hash_spans(&self) -> bool;
2065 /// Accesses `sess.opts.unstable_opts.incremental_ignore_spans` since
2066 /// we don't have easy access to a `Session`
2067 fn unstable_opts_incremental_ignore_spans(&self) -> bool;
2068 fn def_span(&self, def_id: LocalDefId) -> Span;
2069 fn span_data_to_lines_and_cols(
2072 ) -> Option<(Lrc<SourceFile>, usize, BytePos, usize, BytePos)>;
2073 fn hashing_controls(&self) -> HashingControls;
2076 impl<CTX> HashStable<CTX> for Span
2078 CTX: HashStableContext,
2080 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
2081 /// fields (that would be similar to hashing pointers, since those are just
2082 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
2083 /// triple, which stays the same even if the containing `SourceFile` has moved
2084 /// within the `SourceMap`.
2086 /// Also note that we are hashing byte offsets for the column, not unicode
2087 /// codepoint offsets. For the purpose of the hash that's sufficient.
2088 /// Also, hashing filenames is expensive so we avoid doing it twice when the
2089 /// span starts and ends in the same file, which is almost always the case.
2090 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
2091 const TAG_VALID_SPAN: u8 = 0;
2092 const TAG_INVALID_SPAN: u8 = 1;
2093 const TAG_RELATIVE_SPAN: u8 = 2;
2095 if !ctx.hash_spans() {
2099 let span = self.data_untracked();
2100 span.ctxt.hash_stable(ctx, hasher);
2101 span.parent.hash_stable(ctx, hasher);
2103 if span.is_dummy() {
2104 Hash::hash(&TAG_INVALID_SPAN, hasher);
2108 if let Some(parent) = span.parent {
2109 let def_span = ctx.def_span(parent).data_untracked();
2110 if def_span.contains(span) {
2111 // This span is enclosed in a definition: only hash the relative position.
2112 Hash::hash(&TAG_RELATIVE_SPAN, hasher);
2113 (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher);
2114 (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher);
2119 // If this is not an empty or invalid span, we want to hash the last
2120 // position that belongs to it, as opposed to hashing the first
2121 // position past it.
2122 let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span) else {
2123 Hash::hash(&TAG_INVALID_SPAN, hasher);
2127 Hash::hash(&TAG_VALID_SPAN, hasher);
2128 // We truncate the stable ID hash and line and column numbers. The chances
2129 // of causing a collision this way should be minimal.
2130 Hash::hash(&(file.name_hash as u64), hasher);
2132 // Hash both the length and the end location (line/column) of a span. If we
2133 // hash only the length, for example, then two otherwise equal spans with
2134 // different end locations will have the same hash. This can cause a problem
2135 // during incremental compilation wherein a previous result for a query that
2136 // depends on the end location of a span will be incorrectly reused when the
2137 // end location of the span it depends on has changed (see issue #74890). A
2138 // similar analysis applies if some query depends specifically on the length
2139 // of the span, but we only hash the end location. So hash both.
2141 let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
2142 let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
2143 let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
2144 let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
2145 let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
2146 let len = (span.hi - span.lo).0;
2147 Hash::hash(&col_line, hasher);
2148 Hash::hash(&len, hasher);