]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/lib.rs
Auto merge of #96600 - c410-f3r:z-errors, r=petrochenkov
[rust.git] / compiler / rustc_span / src / lib.rs
1 //! Source positions and related helper functions.
2 //!
3 //! Important concepts in this module include:
4 //!
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.
8 //!
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`].
11 //!
12 //! ## Note
13 //!
14 //! This API is completely unstable and subject to change.
15
16 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
17 #![feature(array_windows)]
18 #![feature(bool_to_option)]
19 #![feature(crate_visibility_modifier)]
20 #![feature(let_else)]
21 #![feature(if_let_guard)]
22 #![feature(negative_impls)]
23 #![feature(nll)]
24 #![feature(min_specialization)]
25 #![feature(rustc_attrs)]
26 #![allow(rustc::potential_query_instability)]
27
28 #[macro_use]
29 extern crate rustc_macros;
30
31 #[macro_use]
32 extern crate tracing;
33
34 use rustc_data_structures::AtomicRef;
35 use rustc_macros::HashStable_Generic;
36 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
37
38 mod caching_source_map_view;
39 pub mod source_map;
40 pub use self::caching_source_map_view::CachingSourceMapView;
41 use source_map::SourceMap;
42
43 pub mod edition;
44 use edition::Edition;
45 pub mod hygiene;
46 use hygiene::Transparency;
47 pub use hygiene::{DesugaringKind, ExpnKind, MacroKind};
48 pub use hygiene::{ExpnData, ExpnHash, ExpnId, LocalExpnId, SyntaxContext};
49 use rustc_data_structures::stable_hasher::HashingControls;
50 pub mod def_id;
51 use def_id::{CrateNum, DefId, DefPathHash, LocalDefId, LOCAL_CRATE};
52 pub mod lev_distance;
53 mod span_encoding;
54 pub use span_encoding::{Span, DUMMY_SP};
55
56 pub mod symbol;
57 pub use symbol::{sym, Symbol};
58
59 mod analyze_source_file;
60 pub mod fatal_error;
61
62 pub mod profiling;
63
64 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
65 use rustc_data_structures::sync::{Lock, Lrc};
66
67 use std::borrow::Cow;
68 use std::cmp::{self, Ordering};
69 use std::fmt;
70 use std::hash::Hash;
71 use std::ops::{Add, Range, Sub};
72 use std::path::{Path, PathBuf};
73 use std::str::FromStr;
74
75 use md5::Digest;
76 use md5::Md5;
77 use sha1::Sha1;
78 use sha2::Sha256;
79
80 use tracing::debug;
81
82 #[cfg(test)]
83 mod tests;
84
85 // Per-session global variables: this struct is stored in thread-local storage
86 // in such a way that it is accessible without any kind of handle to all
87 // threads within the compilation session, but is not accessible outside the
88 // session.
89 pub struct SessionGlobals {
90     symbol_interner: symbol::Interner,
91     span_interner: Lock<span_encoding::SpanInterner>,
92     hygiene_data: Lock<hygiene::HygieneData>,
93     source_map: Lock<Option<Lrc<SourceMap>>>,
94 }
95
96 impl SessionGlobals {
97     pub fn new(edition: Edition) -> SessionGlobals {
98         SessionGlobals {
99             symbol_interner: symbol::Interner::fresh(),
100             span_interner: Lock::new(span_encoding::SpanInterner::default()),
101             hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
102             source_map: Lock::new(None),
103         }
104     }
105 }
106
107 #[inline]
108 pub fn create_session_globals_then<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
109     assert!(
110         !SESSION_GLOBALS.is_set(),
111         "SESSION_GLOBALS should never be overwritten! \
112          Use another thread if you need another SessionGlobals"
113     );
114     let session_globals = SessionGlobals::new(edition);
115     SESSION_GLOBALS.set(&session_globals, f)
116 }
117
118 #[inline]
119 pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R {
120     assert!(
121         !SESSION_GLOBALS.is_set(),
122         "SESSION_GLOBALS should never be overwritten! \
123          Use another thread if you need another SessionGlobals"
124     );
125     SESSION_GLOBALS.set(session_globals, f)
126 }
127
128 #[inline]
129 pub fn create_default_session_if_not_set_then<R, F>(f: F) -> R
130 where
131     F: FnOnce(&SessionGlobals) -> R,
132 {
133     create_session_if_not_set_then(edition::DEFAULT_EDITION, f)
134 }
135
136 #[inline]
137 pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R
138 where
139     F: FnOnce(&SessionGlobals) -> R,
140 {
141     if !SESSION_GLOBALS.is_set() {
142         let session_globals = SessionGlobals::new(edition);
143         SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f))
144     } else {
145         SESSION_GLOBALS.with(f)
146     }
147 }
148
149 #[inline]
150 pub fn with_session_globals<R, F>(f: F) -> R
151 where
152     F: FnOnce(&SessionGlobals) -> R,
153 {
154     SESSION_GLOBALS.with(f)
155 }
156
157 #[inline]
158 pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R {
159     create_session_globals_then(edition::DEFAULT_EDITION, f)
160 }
161
162 // If this ever becomes non thread-local, `decode_syntax_context`
163 // and `decode_expn_id` will need to be updated to handle concurrent
164 // deserialization.
165 scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals);
166
167 // FIXME: We should use this enum or something like it to get rid of the
168 // use of magic `/rust/1.x/...` paths across the board.
169 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)]
170 #[derive(Decodable)]
171 pub enum RealFileName {
172     LocalPath(PathBuf),
173     /// For remapped paths (namely paths into libstd that have been mapped
174     /// to the appropriate spot on the local host's file system, and local file
175     /// system paths that have been remapped with `FilePathMapping`),
176     Remapped {
177         /// `local_path` is the (host-dependent) local path to the file. This is
178         /// None if the file was imported from another crate
179         local_path: Option<PathBuf>,
180         /// `virtual_name` is the stable path rustc will store internally within
181         /// build artifacts.
182         virtual_name: PathBuf,
183     },
184 }
185
186 impl Hash for RealFileName {
187     fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
188         // To prevent #70924 from happening again we should only hash the
189         // remapped (virtualized) path if that exists. This is because
190         // virtualized paths to sysroot crates (/rust/$hash or /rust/$version)
191         // remain stable even if the corresponding local_path changes
192         self.remapped_path_if_available().hash(state)
193     }
194 }
195
196 // This is functionally identical to #[derive(Encodable)], with the exception of
197 // an added assert statement
198 impl<S: Encoder> Encodable<S> for RealFileName {
199     fn encode(&self, encoder: &mut S) -> Result<(), S::Error> {
200         encoder.emit_enum(|encoder| match *self {
201             RealFileName::LocalPath(ref local_path) => {
202                 encoder.emit_enum_variant("LocalPath", 0, 1, |encoder| {
203                     encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?;
204                     Ok(())
205                 })
206             }
207
208             RealFileName::Remapped { ref local_path, ref virtual_name } => encoder
209                 .emit_enum_variant("Remapped", 1, 2, |encoder| {
210                     // For privacy and build reproducibility, we must not embed host-dependant path in artifacts
211                     // if they have been remapped by --remap-path-prefix
212                     assert!(local_path.is_none());
213                     encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?;
214                     encoder.emit_enum_variant_arg(false, |encoder| virtual_name.encode(encoder))?;
215                     Ok(())
216                 }),
217         })
218     }
219 }
220
221 impl RealFileName {
222     /// Returns the path suitable for reading from the file system on the local host,
223     /// if this information exists.
224     /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
225     pub fn local_path(&self) -> Option<&Path> {
226         match self {
227             RealFileName::LocalPath(p) => Some(p),
228             RealFileName::Remapped { local_path: p, virtual_name: _ } => {
229                 p.as_ref().map(PathBuf::as_path)
230             }
231         }
232     }
233
234     /// Returns the path suitable for reading from the file system on the local host,
235     /// if this information exists.
236     /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
237     pub fn into_local_path(self) -> Option<PathBuf> {
238         match self {
239             RealFileName::LocalPath(p) => Some(p),
240             RealFileName::Remapped { local_path: p, virtual_name: _ } => p,
241         }
242     }
243
244     /// Returns the path suitable for embedding into build artifacts. This would still
245     /// be a local path if it has not been remapped. A remapped path will not correspond
246     /// to a valid file system path: see `local_path_if_available()` for something that
247     /// is more likely to return paths into the local host file system.
248     pub fn remapped_path_if_available(&self) -> &Path {
249         match self {
250             RealFileName::LocalPath(p)
251             | RealFileName::Remapped { local_path: _, virtual_name: p } => &p,
252         }
253     }
254
255     /// Returns the path suitable for reading from the file system on the local host,
256     /// if this information exists. Otherwise returns the remapped name.
257     /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
258     pub fn local_path_if_available(&self) -> &Path {
259         match self {
260             RealFileName::LocalPath(path)
261             | RealFileName::Remapped { local_path: None, virtual_name: path }
262             | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path,
263         }
264     }
265
266     pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> {
267         match display_pref {
268             FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(),
269             FileNameDisplayPreference::Remapped => {
270                 self.remapped_path_if_available().to_string_lossy()
271             }
272         }
273     }
274 }
275
276 /// Differentiates between real files and common virtual files.
277 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
278 #[derive(Decodable, Encodable)]
279 pub enum FileName {
280     Real(RealFileName),
281     /// Call to `quote!`.
282     QuoteExpansion(u64),
283     /// Command line.
284     Anon(u64),
285     /// Hack in `src/librustc_ast/parse.rs`.
286     // FIXME(jseyfried)
287     MacroExpansion(u64),
288     ProcMacroSourceCode(u64),
289     /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
290     CfgSpec(u64),
291     /// Strings provided as crate attributes in the CLI.
292     CliCrateAttr(u64),
293     /// Custom sources for explicit parser calls from plugins and drivers.
294     Custom(String),
295     DocTest(PathBuf, isize),
296     /// Post-substitution inline assembly from LLVM.
297     InlineAsm(u64),
298 }
299
300 impl From<PathBuf> for FileName {
301     fn from(p: PathBuf) -> Self {
302         assert!(!p.to_string_lossy().ends_with('>'));
303         FileName::Real(RealFileName::LocalPath(p))
304     }
305 }
306
307 #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
308 pub enum FileNameDisplayPreference {
309     Remapped,
310     Local,
311 }
312
313 pub struct FileNameDisplay<'a> {
314     inner: &'a FileName,
315     display_pref: FileNameDisplayPreference,
316 }
317
318 impl fmt::Display for FileNameDisplay<'_> {
319     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
320         use FileName::*;
321         match *self.inner {
322             Real(ref name) => {
323                 write!(fmt, "{}", name.to_string_lossy(self.display_pref))
324             }
325             QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
326             MacroExpansion(_) => write!(fmt, "<macro expansion>"),
327             Anon(_) => write!(fmt, "<anon>"),
328             ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
329             CfgSpec(_) => write!(fmt, "<cfgspec>"),
330             CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
331             Custom(ref s) => write!(fmt, "<{}>", s),
332             DocTest(ref path, _) => write!(fmt, "{}", path.display()),
333             InlineAsm(_) => write!(fmt, "<inline asm>"),
334         }
335     }
336 }
337
338 impl FileNameDisplay<'_> {
339     pub fn to_string_lossy(&self) -> Cow<'_, str> {
340         match self.inner {
341             FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref),
342             _ => Cow::from(format!("{}", self)),
343         }
344     }
345 }
346
347 impl FileName {
348     pub fn is_real(&self) -> bool {
349         use FileName::*;
350         match *self {
351             Real(_) => true,
352             Anon(_)
353             | MacroExpansion(_)
354             | ProcMacroSourceCode(_)
355             | CfgSpec(_)
356             | CliCrateAttr(_)
357             | Custom(_)
358             | QuoteExpansion(_)
359             | DocTest(_, _)
360             | InlineAsm(_) => false,
361         }
362     }
363
364     pub fn prefer_remapped(&self) -> FileNameDisplay<'_> {
365         FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped }
366     }
367
368     // This may include transient local filesystem information.
369     // Must not be embedded in build outputs.
370     pub fn prefer_local(&self) -> FileNameDisplay<'_> {
371         FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local }
372     }
373
374     pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> {
375         FileNameDisplay { inner: self, display_pref }
376     }
377
378     pub fn macro_expansion_source_code(src: &str) -> FileName {
379         let mut hasher = StableHasher::new();
380         src.hash(&mut hasher);
381         FileName::MacroExpansion(hasher.finish())
382     }
383
384     pub fn anon_source_code(src: &str) -> FileName {
385         let mut hasher = StableHasher::new();
386         src.hash(&mut hasher);
387         FileName::Anon(hasher.finish())
388     }
389
390     pub fn proc_macro_source_code(src: &str) -> FileName {
391         let mut hasher = StableHasher::new();
392         src.hash(&mut hasher);
393         FileName::ProcMacroSourceCode(hasher.finish())
394     }
395
396     pub fn cfg_spec_source_code(src: &str) -> FileName {
397         let mut hasher = StableHasher::new();
398         src.hash(&mut hasher);
399         FileName::QuoteExpansion(hasher.finish())
400     }
401
402     pub fn cli_crate_attr_source_code(src: &str) -> FileName {
403         let mut hasher = StableHasher::new();
404         src.hash(&mut hasher);
405         FileName::CliCrateAttr(hasher.finish())
406     }
407
408     pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
409         FileName::DocTest(path, line)
410     }
411
412     pub fn inline_asm_source_code(src: &str) -> FileName {
413         let mut hasher = StableHasher::new();
414         src.hash(&mut hasher);
415         FileName::InlineAsm(hasher.finish())
416     }
417 }
418
419 /// Represents a span.
420 ///
421 /// Spans represent a region of code, used for error reporting. Positions in spans
422 /// are *absolute* positions from the beginning of the [`SourceMap`], not positions
423 /// relative to [`SourceFile`]s. Methods on the `SourceMap` can be used to relate spans back
424 /// to the original source.
425 ///
426 /// You must be careful if the span crosses more than one file, since you will not be
427 /// able to use many of the functions on spans in source_map and you cannot assume
428 /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the
429 /// [`BytePos`] range between files.
430 ///
431 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
432 /// sent to other threads, but some pieces of performance infra run in a separate thread.
433 /// Using `Span` is generally preferred.
434 #[derive(Clone, Copy, Hash, PartialEq, Eq)]
435 pub struct SpanData {
436     pub lo: BytePos,
437     pub hi: BytePos,
438     /// Information about where the macro came from, if this piece of
439     /// code was created by a macro expansion.
440     pub ctxt: SyntaxContext,
441     pub parent: Option<LocalDefId>,
442 }
443
444 // Order spans by position in the file.
445 impl Ord for SpanData {
446     fn cmp(&self, other: &Self) -> Ordering {
447         let SpanData {
448             lo: s_lo,
449             hi: s_hi,
450             ctxt: s_ctxt,
451             // `LocalDefId` does not implement `Ord`.
452             // The other fields are enough to determine in-file order.
453             parent: _,
454         } = self;
455         let SpanData {
456             lo: o_lo,
457             hi: o_hi,
458             ctxt: o_ctxt,
459             // `LocalDefId` does not implement `Ord`.
460             // The other fields are enough to determine in-file order.
461             parent: _,
462         } = other;
463
464         (s_lo, s_hi, s_ctxt).cmp(&(o_lo, o_hi, o_ctxt))
465     }
466 }
467
468 impl PartialOrd for SpanData {
469     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
470         Some(self.cmp(other))
471     }
472 }
473
474 impl SpanData {
475     #[inline]
476     pub fn span(&self) -> Span {
477         Span::new(self.lo, self.hi, self.ctxt, self.parent)
478     }
479     #[inline]
480     pub fn with_lo(&self, lo: BytePos) -> Span {
481         Span::new(lo, self.hi, self.ctxt, self.parent)
482     }
483     #[inline]
484     pub fn with_hi(&self, hi: BytePos) -> Span {
485         Span::new(self.lo, hi, self.ctxt, self.parent)
486     }
487     #[inline]
488     pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
489         Span::new(self.lo, self.hi, ctxt, self.parent)
490     }
491     #[inline]
492     pub fn with_parent(&self, parent: Option<LocalDefId>) -> Span {
493         Span::new(self.lo, self.hi, self.ctxt, parent)
494     }
495     /// Returns `true` if this is a dummy span with any hygienic context.
496     #[inline]
497     pub fn is_dummy(self) -> bool {
498         self.lo.0 == 0 && self.hi.0 == 0
499     }
500     /// Returns `true` if `self` fully encloses `other`.
501     pub fn contains(self, other: Self) -> bool {
502         self.lo <= other.lo && other.hi <= self.hi
503     }
504 }
505
506 // The interner is pointed to by a thread local value which is only set on the main thread
507 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
508 // to avoid panics and other errors, even though it would be memory safe to do so.
509 #[cfg(not(parallel_compiler))]
510 impl !Send for Span {}
511 #[cfg(not(parallel_compiler))]
512 impl !Sync for Span {}
513
514 impl PartialOrd for Span {
515     fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
516         PartialOrd::partial_cmp(&self.data(), &rhs.data())
517     }
518 }
519 impl Ord for Span {
520     fn cmp(&self, rhs: &Self) -> Ordering {
521         Ord::cmp(&self.data(), &rhs.data())
522     }
523 }
524
525 impl Span {
526     #[inline]
527     pub fn lo(self) -> BytePos {
528         self.data().lo
529     }
530     #[inline]
531     pub fn with_lo(self, lo: BytePos) -> Span {
532         self.data().with_lo(lo)
533     }
534     #[inline]
535     pub fn hi(self) -> BytePos {
536         self.data().hi
537     }
538     #[inline]
539     pub fn with_hi(self, hi: BytePos) -> Span {
540         self.data().with_hi(hi)
541     }
542     #[inline]
543     pub fn ctxt(self) -> SyntaxContext {
544         self.data_untracked().ctxt
545     }
546     #[inline]
547     pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
548         self.data_untracked().with_ctxt(ctxt)
549     }
550     #[inline]
551     pub fn parent(self) -> Option<LocalDefId> {
552         self.data().parent
553     }
554     #[inline]
555     pub fn with_parent(self, ctxt: Option<LocalDefId>) -> Span {
556         self.data().with_parent(ctxt)
557     }
558
559     /// Returns `true` if this is a dummy span with any hygienic context.
560     #[inline]
561     pub fn is_dummy(self) -> bool {
562         self.data_untracked().is_dummy()
563     }
564
565     /// Returns `true` if this span comes from a macro or desugaring.
566     #[inline]
567     pub fn from_expansion(self) -> bool {
568         self.ctxt() != SyntaxContext::root()
569     }
570
571     /// Returns `true` if `span` originates in a derive-macro's expansion.
572     pub fn in_derive_expansion(self) -> bool {
573         matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
574     }
575
576     /// Gate suggestions that would not be appropriate in a context the user didn't write.
577     pub fn can_be_used_for_suggestions(self) -> bool {
578         !self.from_expansion()
579         // FIXME: If this span comes from a `derive` macro but it points at code the user wrote,
580         // the callsite span and the span will be pointing at different places. It also means that
581         // we can safely provide suggestions on this span.
582             || (matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
583                 && self.parent_callsite().map(|p| (p.lo(), p.hi())) != Some((self.lo(), self.hi())))
584     }
585
586     #[inline]
587     pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
588         Span::new(lo, hi, SyntaxContext::root(), None)
589     }
590
591     /// Returns a new span representing an empty span at the beginning of this span.
592     #[inline]
593     pub fn shrink_to_lo(self) -> Span {
594         let span = self.data_untracked();
595         span.with_hi(span.lo)
596     }
597     /// Returns a new span representing an empty span at the end of this span.
598     #[inline]
599     pub fn shrink_to_hi(self) -> Span {
600         let span = self.data_untracked();
601         span.with_lo(span.hi)
602     }
603
604     #[inline]
605     /// Returns `true` if `hi == lo`.
606     pub fn is_empty(self) -> bool {
607         let span = self.data_untracked();
608         span.hi == span.lo
609     }
610
611     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
612     pub fn substitute_dummy(self, other: Span) -> Span {
613         if self.is_dummy() { other } else { self }
614     }
615
616     /// Returns `true` if `self` fully encloses `other`.
617     pub fn contains(self, other: Span) -> bool {
618         let span = self.data();
619         let other = other.data();
620         span.contains(other)
621     }
622
623     /// Returns `true` if `self` touches `other`.
624     pub fn overlaps(self, other: Span) -> bool {
625         let span = self.data();
626         let other = other.data();
627         span.lo < other.hi && other.lo < span.hi
628     }
629
630     /// Returns `true` if the spans are equal with regards to the source text.
631     ///
632     /// Use this instead of `==` when either span could be generated code,
633     /// and you only care that they point to the same bytes of source text.
634     pub fn source_equal(self, other: Span) -> bool {
635         let span = self.data();
636         let other = other.data();
637         span.lo == other.lo && span.hi == other.hi
638     }
639
640     /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
641     pub fn trim_start(self, other: Span) -> Option<Span> {
642         let span = self.data();
643         let other = other.data();
644         if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
645     }
646
647     /// Returns the source span -- this is either the supplied span, or the span for
648     /// the macro callsite that expanded to it.
649     pub fn source_callsite(self) -> Span {
650         let expn_data = self.ctxt().outer_expn_data();
651         if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
652     }
653
654     /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
655     /// if any.
656     pub fn parent_callsite(self) -> Option<Span> {
657         let expn_data = self.ctxt().outer_expn_data();
658         if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
659     }
660
661     /// Walk down the expansion ancestors to find a span that's contained within `outer`.
662     pub fn find_ancestor_inside(mut self, outer: Span) -> Option<Span> {
663         while !outer.contains(self) {
664             self = self.parent_callsite()?;
665         }
666         Some(self)
667     }
668
669     /// Edition of the crate from which this span came.
670     pub fn edition(self) -> edition::Edition {
671         self.ctxt().edition()
672     }
673
674     #[inline]
675     pub fn rust_2015(self) -> bool {
676         self.edition() == edition::Edition::Edition2015
677     }
678
679     #[inline]
680     pub fn rust_2018(self) -> bool {
681         self.edition() >= edition::Edition::Edition2018
682     }
683
684     #[inline]
685     pub fn rust_2021(self) -> bool {
686         self.edition() >= edition::Edition::Edition2021
687     }
688
689     #[inline]
690     pub fn rust_2024(self) -> bool {
691         self.edition() >= edition::Edition::Edition2024
692     }
693
694     /// Returns the source callee.
695     ///
696     /// Returns `None` if the supplied span has no expansion trace,
697     /// else returns the `ExpnData` for the macro definition
698     /// corresponding to the source callsite.
699     pub fn source_callee(self) -> Option<ExpnData> {
700         fn source_callee(expn_data: ExpnData) -> ExpnData {
701             let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
702             if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
703         }
704         let expn_data = self.ctxt().outer_expn_data();
705         if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
706     }
707
708     /// Checks if a span is "internal" to a macro in which `#[unstable]`
709     /// items can be used (that is, a macro marked with
710     /// `#[allow_internal_unstable]`).
711     pub fn allows_unstable(self, feature: Symbol) -> bool {
712         self.ctxt()
713             .outer_expn_data()
714             .allow_internal_unstable
715             .map_or(false, |features| features.iter().any(|&f| f == feature))
716     }
717
718     /// Checks if this span arises from a compiler desugaring of kind `kind`.
719     pub fn is_desugaring(self, kind: DesugaringKind) -> bool {
720         match self.ctxt().outer_expn_data().kind {
721             ExpnKind::Desugaring(k) => k == kind,
722             _ => false,
723         }
724     }
725
726     /// Returns the compiler desugaring that created this span, or `None`
727     /// if this span is not from a desugaring.
728     pub fn desugaring_kind(self) -> Option<DesugaringKind> {
729         match self.ctxt().outer_expn_data().kind {
730             ExpnKind::Desugaring(k) => Some(k),
731             _ => None,
732         }
733     }
734
735     /// Checks if a span is "internal" to a macro in which `unsafe`
736     /// can be used without triggering the `unsafe_code` lint.
737     //  (that is, a macro marked with `#[allow_internal_unsafe]`).
738     pub fn allows_unsafe(self) -> bool {
739         self.ctxt().outer_expn_data().allow_internal_unsafe
740     }
741
742     pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
743         let mut prev_span = DUMMY_SP;
744         std::iter::from_fn(move || {
745             loop {
746                 let expn_data = self.ctxt().outer_expn_data();
747                 if expn_data.is_root() {
748                     return None;
749                 }
750
751                 let is_recursive = expn_data.call_site.source_equal(prev_span);
752
753                 prev_span = self;
754                 self = expn_data.call_site;
755
756                 // Don't print recursive invocations.
757                 if !is_recursive {
758                     return Some(expn_data);
759                 }
760             }
761         })
762     }
763
764     /// Returns a `Span` that would enclose both `self` and `end`.
765     ///
766     /// ```text
767     ///     ____             ___
768     ///     self lorem ipsum end
769     ///     ^^^^^^^^^^^^^^^^^^^^
770     /// ```
771     pub fn to(self, end: Span) -> Span {
772         let span_data = self.data();
773         let end_data = end.data();
774         // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
775         // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
776         // have an incomplete span than a completely nonsensical one.
777         if span_data.ctxt != end_data.ctxt {
778             if span_data.ctxt == SyntaxContext::root() {
779                 return end;
780             } else if end_data.ctxt == SyntaxContext::root() {
781                 return self;
782             }
783             // Both spans fall within a macro.
784             // FIXME(estebank): check if it is the *same* macro.
785         }
786         Span::new(
787             cmp::min(span_data.lo, end_data.lo),
788             cmp::max(span_data.hi, end_data.hi),
789             if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
790             if span_data.parent == end_data.parent { span_data.parent } else { None },
791         )
792     }
793
794     /// Returns a `Span` between the end of `self` to the beginning of `end`.
795     ///
796     /// ```text
797     ///     ____             ___
798     ///     self lorem ipsum end
799     ///         ^^^^^^^^^^^^^
800     /// ```
801     pub fn between(self, end: Span) -> Span {
802         let span = self.data();
803         let end = end.data();
804         Span::new(
805             span.hi,
806             end.lo,
807             if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
808             if span.parent == end.parent { span.parent } else { None },
809         )
810     }
811
812     /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
813     ///
814     /// ```text
815     ///     ____             ___
816     ///     self lorem ipsum end
817     ///     ^^^^^^^^^^^^^^^^^
818     /// ```
819     pub fn until(self, end: Span) -> Span {
820         // Most of this function's body is copied from `to`.
821         // We can't just do `self.to(end.shrink_to_lo())`,
822         // because to also does some magic where it uses min/max so
823         // it can handle overlapping spans. Some advanced mis-use of
824         // `until` with different ctxts makes this visible.
825         let span_data = self.data();
826         let end_data = end.data();
827         // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
828         // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
829         // have an incomplete span than a completely nonsensical one.
830         if span_data.ctxt != end_data.ctxt {
831             if span_data.ctxt == SyntaxContext::root() {
832                 return end;
833             } else if end_data.ctxt == SyntaxContext::root() {
834                 return self;
835             }
836             // Both spans fall within a macro.
837             // FIXME(estebank): check if it is the *same* macro.
838         }
839         Span::new(
840             span_data.lo,
841             end_data.lo,
842             if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
843             if span_data.parent == end_data.parent { span_data.parent } else { None },
844         )
845     }
846
847     pub fn from_inner(self, inner: InnerSpan) -> Span {
848         let span = self.data();
849         Span::new(
850             span.lo + BytePos::from_usize(inner.start),
851             span.lo + BytePos::from_usize(inner.end),
852             span.ctxt,
853             span.parent,
854         )
855     }
856
857     /// Equivalent of `Span::def_site` from the proc macro API,
858     /// except that the location is taken from the `self` span.
859     pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
860         self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
861     }
862
863     /// Equivalent of `Span::call_site` from the proc macro API,
864     /// except that the location is taken from the `self` span.
865     pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span {
866         self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
867     }
868
869     /// Equivalent of `Span::mixed_site` from the proc macro API,
870     /// except that the location is taken from the `self` span.
871     pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span {
872         self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
873     }
874
875     /// Produces a span with the same location as `self` and context produced by a macro with the
876     /// given ID and transparency, assuming that macro was defined directly and not produced by
877     /// some other macro (which is the case for built-in and procedural macros).
878     pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
879         self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
880     }
881
882     #[inline]
883     pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
884         let span = self.data();
885         span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
886     }
887
888     #[inline]
889     pub fn remove_mark(&mut self) -> ExpnId {
890         let mut span = self.data();
891         let mark = span.ctxt.remove_mark();
892         *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
893         mark
894     }
895
896     #[inline]
897     pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
898         let mut span = self.data();
899         let mark = span.ctxt.adjust(expn_id);
900         *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
901         mark
902     }
903
904     #[inline]
905     pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
906         let mut span = self.data();
907         let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
908         *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
909         mark
910     }
911
912     #[inline]
913     pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
914         let mut span = self.data();
915         let mark = span.ctxt.glob_adjust(expn_id, glob_span);
916         *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
917         mark
918     }
919
920     #[inline]
921     pub fn reverse_glob_adjust(
922         &mut self,
923         expn_id: ExpnId,
924         glob_span: Span,
925     ) -> Option<Option<ExpnId>> {
926         let mut span = self.data();
927         let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
928         *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
929         mark
930     }
931
932     #[inline]
933     pub fn normalize_to_macros_2_0(self) -> Span {
934         let span = self.data();
935         span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
936     }
937
938     #[inline]
939     pub fn normalize_to_macro_rules(self) -> Span {
940         let span = self.data();
941         span.with_ctxt(span.ctxt.normalize_to_macro_rules())
942     }
943 }
944
945 impl Default for Span {
946     fn default() -> Self {
947         DUMMY_SP
948     }
949 }
950
951 impl<E: Encoder> Encodable<E> for Span {
952     default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
953         let span = self.data();
954         s.emit_struct(false, |s| {
955             s.emit_struct_field("lo", true, |s| span.lo.encode(s))?;
956             s.emit_struct_field("hi", false, |s| span.hi.encode(s))
957         })
958     }
959 }
960 impl<D: Decoder> Decodable<D> for Span {
961     default fn decode(s: &mut D) -> Span {
962         let lo = Decodable::decode(s);
963         let hi = Decodable::decode(s);
964
965         Span::new(lo, hi, SyntaxContext::root(), None)
966     }
967 }
968
969 /// Calls the provided closure, using the provided `SourceMap` to format
970 /// any spans that are debug-printed during the closure's execution.
971 ///
972 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
973 /// (see `rustc_interface::callbacks::span_debug1`). However, some parts
974 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
975 /// a `TyCtxt` is available. In this case, we fall back to
976 /// the `SourceMap` provided to this function. If that is not available,
977 /// we fall back to printing the raw `Span` field values.
978 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
979     with_session_globals(|session_globals| {
980         *session_globals.source_map.borrow_mut() = Some(source_map);
981     });
982     struct ClearSourceMap;
983     impl Drop for ClearSourceMap {
984         fn drop(&mut self) {
985             with_session_globals(|session_globals| {
986                 session_globals.source_map.borrow_mut().take();
987             });
988         }
989     }
990
991     let _guard = ClearSourceMap;
992     f()
993 }
994
995 impl fmt::Debug for Span {
996     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
997         with_session_globals(|session_globals| {
998             if let Some(source_map) = &*session_globals.source_map.borrow() {
999                 write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(*self), self.ctxt())
1000             } else {
1001                 f.debug_struct("Span")
1002                     .field("lo", &self.lo())
1003                     .field("hi", &self.hi())
1004                     .field("ctxt", &self.ctxt())
1005                     .finish()
1006             }
1007         })
1008     }
1009 }
1010
1011 impl fmt::Debug for SpanData {
1012     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1013         fmt::Debug::fmt(&Span::new(self.lo, self.hi, self.ctxt, self.parent), f)
1014     }
1015 }
1016
1017 /// Identifies an offset of a multi-byte character in a `SourceFile`.
1018 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1019 pub struct MultiByteChar {
1020     /// The absolute offset of the character in the `SourceMap`.
1021     pub pos: BytePos,
1022     /// The number of bytes, `>= 2`.
1023     pub bytes: u8,
1024 }
1025
1026 /// Identifies an offset of a non-narrow character in a `SourceFile`.
1027 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1028 pub enum NonNarrowChar {
1029     /// Represents a zero-width character.
1030     ZeroWidth(BytePos),
1031     /// Represents a wide (full-width) character.
1032     Wide(BytePos),
1033     /// Represents a tab character, represented visually with a width of 4 characters.
1034     Tab(BytePos),
1035 }
1036
1037 impl NonNarrowChar {
1038     fn new(pos: BytePos, width: usize) -> Self {
1039         match width {
1040             0 => NonNarrowChar::ZeroWidth(pos),
1041             2 => NonNarrowChar::Wide(pos),
1042             4 => NonNarrowChar::Tab(pos),
1043             _ => panic!("width {} given for non-narrow character", width),
1044         }
1045     }
1046
1047     /// Returns the absolute offset of the character in the `SourceMap`.
1048     pub fn pos(&self) -> BytePos {
1049         match *self {
1050             NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
1051         }
1052     }
1053
1054     /// Returns the width of the character, 0 (zero-width) or 2 (wide).
1055     pub fn width(&self) -> usize {
1056         match *self {
1057             NonNarrowChar::ZeroWidth(_) => 0,
1058             NonNarrowChar::Wide(_) => 2,
1059             NonNarrowChar::Tab(_) => 4,
1060         }
1061     }
1062 }
1063
1064 impl Add<BytePos> for NonNarrowChar {
1065     type Output = Self;
1066
1067     fn add(self, rhs: BytePos) -> Self {
1068         match self {
1069             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
1070             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
1071             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
1072         }
1073     }
1074 }
1075
1076 impl Sub<BytePos> for NonNarrowChar {
1077     type Output = Self;
1078
1079     fn sub(self, rhs: BytePos) -> Self {
1080         match self {
1081             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
1082             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
1083             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
1084         }
1085     }
1086 }
1087
1088 /// Identifies an offset of a character that was normalized away from `SourceFile`.
1089 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1090 pub struct NormalizedPos {
1091     /// The absolute offset of the character in the `SourceMap`.
1092     pub pos: BytePos,
1093     /// The difference between original and normalized string at position.
1094     pub diff: u32,
1095 }
1096
1097 #[derive(PartialEq, Eq, Clone, Debug)]
1098 pub enum ExternalSource {
1099     /// No external source has to be loaded, since the `SourceFile` represents a local crate.
1100     Unneeded,
1101     Foreign {
1102         kind: ExternalSourceKind,
1103         /// This SourceFile's byte-offset within the source_map of its original crate.
1104         original_start_pos: BytePos,
1105         /// The end of this SourceFile within the source_map of its original crate.
1106         original_end_pos: BytePos,
1107     },
1108 }
1109
1110 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1111 #[derive(PartialEq, Eq, Clone, Debug)]
1112 pub enum ExternalSourceKind {
1113     /// The external source has been loaded already.
1114     Present(Lrc<String>),
1115     /// No attempt has been made to load the external source.
1116     AbsentOk,
1117     /// A failed attempt has been made to load the external source.
1118     AbsentErr,
1119     Unneeded,
1120 }
1121
1122 impl ExternalSource {
1123     pub fn get_source(&self) -> Option<&Lrc<String>> {
1124         match self {
1125             ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1126             _ => None,
1127         }
1128     }
1129 }
1130
1131 #[derive(Debug)]
1132 pub struct OffsetOverflowError;
1133
1134 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1135 #[derive(HashStable_Generic)]
1136 pub enum SourceFileHashAlgorithm {
1137     Md5,
1138     Sha1,
1139     Sha256,
1140 }
1141
1142 impl FromStr for SourceFileHashAlgorithm {
1143     type Err = ();
1144
1145     fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1146         match s {
1147             "md5" => Ok(SourceFileHashAlgorithm::Md5),
1148             "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1149             "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1150             _ => Err(()),
1151         }
1152     }
1153 }
1154
1155 /// The hash of the on-disk source file used for debug info.
1156 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1157 #[derive(HashStable_Generic, Encodable, Decodable)]
1158 pub struct SourceFileHash {
1159     pub kind: SourceFileHashAlgorithm,
1160     value: [u8; 32],
1161 }
1162
1163 impl SourceFileHash {
1164     pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1165         let mut hash = SourceFileHash { kind, value: Default::default() };
1166         let len = hash.hash_len();
1167         let value = &mut hash.value[..len];
1168         let data = src.as_bytes();
1169         match kind {
1170             SourceFileHashAlgorithm::Md5 => {
1171                 value.copy_from_slice(&Md5::digest(data));
1172             }
1173             SourceFileHashAlgorithm::Sha1 => {
1174                 value.copy_from_slice(&Sha1::digest(data));
1175             }
1176             SourceFileHashAlgorithm::Sha256 => {
1177                 value.copy_from_slice(&Sha256::digest(data));
1178             }
1179         }
1180         hash
1181     }
1182
1183     /// Check if the stored hash matches the hash of the string.
1184     pub fn matches(&self, src: &str) -> bool {
1185         Self::new(self.kind, src) == *self
1186     }
1187
1188     /// The bytes of the hash.
1189     pub fn hash_bytes(&self) -> &[u8] {
1190         let len = self.hash_len();
1191         &self.value[..len]
1192     }
1193
1194     fn hash_len(&self) -> usize {
1195         match self.kind {
1196             SourceFileHashAlgorithm::Md5 => 16,
1197             SourceFileHashAlgorithm::Sha1 => 20,
1198             SourceFileHashAlgorithm::Sha256 => 32,
1199         }
1200     }
1201 }
1202
1203 /// A single source in the [`SourceMap`].
1204 #[derive(Clone)]
1205 pub struct SourceFile {
1206     /// The name of the file that the source came from. Source that doesn't
1207     /// originate from files has names between angle brackets by convention
1208     /// (e.g., `<anon>`).
1209     pub name: FileName,
1210     /// The complete source code.
1211     pub src: Option<Lrc<String>>,
1212     /// The source code's hash.
1213     pub src_hash: SourceFileHash,
1214     /// The external source code (used for external crates, which will have a `None`
1215     /// value as `self.src`.
1216     pub external_src: Lock<ExternalSource>,
1217     /// The start position of this source in the `SourceMap`.
1218     pub start_pos: BytePos,
1219     /// The end position of this source in the `SourceMap`.
1220     pub end_pos: BytePos,
1221     /// Locations of lines beginnings in the source code.
1222     pub lines: Vec<BytePos>,
1223     /// Locations of multi-byte characters in the source code.
1224     pub multibyte_chars: Vec<MultiByteChar>,
1225     /// Width of characters that are not narrow in the source code.
1226     pub non_narrow_chars: Vec<NonNarrowChar>,
1227     /// Locations of characters removed during normalization.
1228     pub normalized_pos: Vec<NormalizedPos>,
1229     /// A hash of the filename, used for speeding up hashing in incremental compilation.
1230     pub name_hash: u128,
1231     /// Indicates which crate this `SourceFile` was imported from.
1232     pub cnum: CrateNum,
1233 }
1234
1235 impl<S: Encoder> Encodable<S> for SourceFile {
1236     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1237         s.emit_struct(false, |s| {
1238             s.emit_struct_field("name", true, |s| self.name.encode(s))?;
1239             s.emit_struct_field("src_hash", false, |s| self.src_hash.encode(s))?;
1240             s.emit_struct_field("start_pos", false, |s| self.start_pos.encode(s))?;
1241             s.emit_struct_field("end_pos", false, |s| self.end_pos.encode(s))?;
1242             s.emit_struct_field("lines", false, |s| {
1243                 let lines = &self.lines[..];
1244                 // Store the length.
1245                 s.emit_u32(lines.len() as u32)?;
1246
1247                 if !lines.is_empty() {
1248                     // In order to preserve some space, we exploit the fact that
1249                     // the lines list is sorted and individual lines are
1250                     // probably not that long. Because of that we can store lines
1251                     // as a difference list, using as little space as possible
1252                     // for the differences.
1253                     let max_line_length = if lines.len() == 1 {
1254                         0
1255                     } else {
1256                         lines
1257                             .array_windows()
1258                             .map(|&[fst, snd]| snd - fst)
1259                             .map(|bp| bp.to_usize())
1260                             .max()
1261                             .unwrap()
1262                     };
1263
1264                     let bytes_per_diff: u8 = match max_line_length {
1265                         0..=0xFF => 1,
1266                         0x100..=0xFFFF => 2,
1267                         _ => 4,
1268                     };
1269
1270                     // Encode the number of bytes used per diff.
1271                     bytes_per_diff.encode(s)?;
1272
1273                     // Encode the first element.
1274                     lines[0].encode(s)?;
1275
1276                     let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst);
1277
1278                     match bytes_per_diff {
1279                         1 => {
1280                             for diff in diff_iter {
1281                                 (diff.0 as u8).encode(s)?
1282                             }
1283                         }
1284                         2 => {
1285                             for diff in diff_iter {
1286                                 (diff.0 as u16).encode(s)?
1287                             }
1288                         }
1289                         4 => {
1290                             for diff in diff_iter {
1291                                 diff.0.encode(s)?
1292                             }
1293                         }
1294                         _ => unreachable!(),
1295                     }
1296                 }
1297
1298                 Ok(())
1299             })?;
1300             s.emit_struct_field("multibyte_chars", false, |s| self.multibyte_chars.encode(s))?;
1301             s.emit_struct_field("non_narrow_chars", false, |s| self.non_narrow_chars.encode(s))?;
1302             s.emit_struct_field("name_hash", false, |s| self.name_hash.encode(s))?;
1303             s.emit_struct_field("normalized_pos", false, |s| self.normalized_pos.encode(s))?;
1304             s.emit_struct_field("cnum", false, |s| self.cnum.encode(s))
1305         })
1306     }
1307 }
1308
1309 impl<D: Decoder> Decodable<D> for SourceFile {
1310     fn decode(d: &mut D) -> SourceFile {
1311         let name: FileName = Decodable::decode(d);
1312         let src_hash: SourceFileHash = Decodable::decode(d);
1313         let start_pos: BytePos = Decodable::decode(d);
1314         let end_pos: BytePos = Decodable::decode(d);
1315         let lines: Vec<BytePos> = {
1316             let num_lines: u32 = Decodable::decode(d);
1317             let mut lines = Vec::with_capacity(num_lines as usize);
1318
1319             if num_lines > 0 {
1320                 // Read the number of bytes used per diff.
1321                 let bytes_per_diff: u8 = Decodable::decode(d);
1322
1323                 // Read the first element.
1324                 let mut line_start: BytePos = Decodable::decode(d);
1325                 lines.push(line_start);
1326
1327                 match bytes_per_diff {
1328                     1 => lines.extend((1..num_lines).map(|_| {
1329                         line_start = line_start + BytePos(d.read_u8() as u32);
1330                         line_start
1331                     })),
1332                     2 => lines.extend((1..num_lines).map(|_| {
1333                         line_start = line_start + BytePos(d.read_u16() as u32);
1334                         line_start
1335                     })),
1336                     4 => lines.extend((1..num_lines).map(|_| {
1337                         line_start = line_start + BytePos(d.read_u32());
1338                         line_start
1339                     })),
1340                     _ => unreachable!(),
1341                 }
1342             }
1343
1344             lines
1345         };
1346         let multibyte_chars: Vec<MultiByteChar> = Decodable::decode(d);
1347         let non_narrow_chars: Vec<NonNarrowChar> = Decodable::decode(d);
1348         let name_hash: u128 = Decodable::decode(d);
1349         let normalized_pos: Vec<NormalizedPos> = Decodable::decode(d);
1350         let cnum: CrateNum = Decodable::decode(d);
1351         SourceFile {
1352             name,
1353             start_pos,
1354             end_pos,
1355             src: None,
1356             src_hash,
1357             // Unused - the metadata decoder will construct
1358             // a new SourceFile, filling in `external_src` properly
1359             external_src: Lock::new(ExternalSource::Unneeded),
1360             lines,
1361             multibyte_chars,
1362             non_narrow_chars,
1363             normalized_pos,
1364             name_hash,
1365             cnum,
1366         }
1367     }
1368 }
1369
1370 impl fmt::Debug for SourceFile {
1371     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1372         write!(fmt, "SourceFile({:?})", self.name)
1373     }
1374 }
1375
1376 impl SourceFile {
1377     pub fn new(
1378         name: FileName,
1379         mut src: String,
1380         start_pos: BytePos,
1381         hash_kind: SourceFileHashAlgorithm,
1382     ) -> Self {
1383         // Compute the file hash before any normalization.
1384         let src_hash = SourceFileHash::new(hash_kind, &src);
1385         let normalized_pos = normalize_src(&mut src, start_pos);
1386
1387         let name_hash = {
1388             let mut hasher: StableHasher = StableHasher::new();
1389             name.hash(&mut hasher);
1390             hasher.finish::<u128>()
1391         };
1392         let end_pos = start_pos.to_usize() + src.len();
1393         assert!(end_pos <= u32::MAX as usize);
1394
1395         let (lines, multibyte_chars, non_narrow_chars) =
1396             analyze_source_file::analyze_source_file(&src, start_pos);
1397
1398         SourceFile {
1399             name,
1400             src: Some(Lrc::new(src)),
1401             src_hash,
1402             external_src: Lock::new(ExternalSource::Unneeded),
1403             start_pos,
1404             end_pos: Pos::from_usize(end_pos),
1405             lines,
1406             multibyte_chars,
1407             non_narrow_chars,
1408             normalized_pos,
1409             name_hash,
1410             cnum: LOCAL_CRATE,
1411         }
1412     }
1413
1414     /// Returns the `BytePos` of the beginning of the current line.
1415     pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1416         let line_index = self.lookup_line(pos).unwrap();
1417         self.lines[line_index]
1418     }
1419
1420     /// Add externally loaded source.
1421     /// If the hash of the input doesn't match or no input is supplied via None,
1422     /// it is interpreted as an error and the corresponding enum variant is set.
1423     /// The return value signifies whether some kind of source is present.
1424     pub fn add_external_src<F>(&self, get_src: F) -> bool
1425     where
1426         F: FnOnce() -> Option<String>,
1427     {
1428         if matches!(
1429             *self.external_src.borrow(),
1430             ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1431         ) {
1432             let src = get_src();
1433             let mut external_src = self.external_src.borrow_mut();
1434             // Check that no-one else have provided the source while we were getting it
1435             if let ExternalSource::Foreign {
1436                 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1437             } = &mut *external_src
1438             {
1439                 if let Some(mut src) = src {
1440                     // The src_hash needs to be computed on the pre-normalized src.
1441                     if self.src_hash.matches(&src) {
1442                         normalize_src(&mut src, BytePos::from_usize(0));
1443                         *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1444                         return true;
1445                     }
1446                 } else {
1447                     *src_kind = ExternalSourceKind::AbsentErr;
1448                 }
1449
1450                 false
1451             } else {
1452                 self.src.is_some() || external_src.get_source().is_some()
1453             }
1454         } else {
1455             self.src.is_some() || self.external_src.borrow().get_source().is_some()
1456         }
1457     }
1458
1459     /// Gets a line from the list of pre-computed line-beginnings.
1460     /// The line number here is 0-based.
1461     pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1462         fn get_until_newline(src: &str, begin: usize) -> &str {
1463             // We can't use `lines.get(line_number+1)` because we might
1464             // be parsing when we call this function and thus the current
1465             // line is the last one we have line info for.
1466             let slice = &src[begin..];
1467             match slice.find('\n') {
1468                 Some(e) => &slice[..e],
1469                 None => slice,
1470             }
1471         }
1472
1473         let begin = {
1474             let line = self.lines.get(line_number)?;
1475             let begin: BytePos = *line - self.start_pos;
1476             begin.to_usize()
1477         };
1478
1479         if let Some(ref src) = self.src {
1480             Some(Cow::from(get_until_newline(src, begin)))
1481         } else if let Some(src) = self.external_src.borrow().get_source() {
1482             Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1483         } else {
1484             None
1485         }
1486     }
1487
1488     pub fn is_real_file(&self) -> bool {
1489         self.name.is_real()
1490     }
1491
1492     pub fn is_imported(&self) -> bool {
1493         self.src.is_none()
1494     }
1495
1496     pub fn count_lines(&self) -> usize {
1497         self.lines.len()
1498     }
1499
1500     /// Finds the line containing the given position. The return value is the
1501     /// index into the `lines` array of this `SourceFile`, not the 1-based line
1502     /// number. If the source_file is empty or the position is located before the
1503     /// first line, `None` is returned.
1504     pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1505         match self.lines.binary_search(&pos) {
1506             Ok(idx) => Some(idx),
1507             Err(0) => None,
1508             Err(idx) => Some(idx - 1),
1509         }
1510     }
1511
1512     pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
1513         if self.is_empty() {
1514             return self.start_pos..self.end_pos;
1515         }
1516
1517         assert!(line_index < self.lines.len());
1518         if line_index == (self.lines.len() - 1) {
1519             self.lines[line_index]..self.end_pos
1520         } else {
1521             self.lines[line_index]..self.lines[line_index + 1]
1522         }
1523     }
1524
1525     /// Returns whether or not the file contains the given `SourceMap` byte
1526     /// position. The position one past the end of the file is considered to be
1527     /// contained by the file. This implies that files for which `is_empty`
1528     /// returns true still contain one byte position according to this function.
1529     #[inline]
1530     pub fn contains(&self, byte_pos: BytePos) -> bool {
1531         byte_pos >= self.start_pos && byte_pos <= self.end_pos
1532     }
1533
1534     #[inline]
1535     pub fn is_empty(&self) -> bool {
1536         self.start_pos == self.end_pos
1537     }
1538
1539     /// Calculates the original byte position relative to the start of the file
1540     /// based on the given byte position.
1541     pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1542         // Diff before any records is 0. Otherwise use the previously recorded
1543         // diff as that applies to the following characters until a new diff
1544         // is recorded.
1545         let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1546             Ok(i) => self.normalized_pos[i].diff,
1547             Err(i) if i == 0 => 0,
1548             Err(i) => self.normalized_pos[i - 1].diff,
1549         };
1550
1551         BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1552     }
1553
1554     /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1555     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1556         // The number of extra bytes due to multibyte chars in the `SourceFile`.
1557         let mut total_extra_bytes = 0;
1558
1559         for mbc in self.multibyte_chars.iter() {
1560             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1561             if mbc.pos < bpos {
1562                 // Every character is at least one byte, so we only
1563                 // count the actual extra bytes.
1564                 total_extra_bytes += mbc.bytes as u32 - 1;
1565                 // We should never see a byte position in the middle of a
1566                 // character.
1567                 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1568             } else {
1569                 break;
1570             }
1571         }
1572
1573         assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1574         CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1575     }
1576
1577     /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1578     /// given `BytePos`.
1579     pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1580         let chpos = self.bytepos_to_file_charpos(pos);
1581         match self.lookup_line(pos) {
1582             Some(a) => {
1583                 let line = a + 1; // Line numbers start at 1
1584                 let linebpos = self.lines[a];
1585                 let linechpos = self.bytepos_to_file_charpos(linebpos);
1586                 let col = chpos - linechpos;
1587                 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1588                 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1589                 debug!("byte is on line: {}", line);
1590                 assert!(chpos >= linechpos);
1591                 (line, col)
1592             }
1593             None => (0, chpos),
1594         }
1595     }
1596
1597     /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1598     /// column offset when displayed, for a given `BytePos`.
1599     pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1600         let (line, col_or_chpos) = self.lookup_file_pos(pos);
1601         if line > 0 {
1602             let col = col_or_chpos;
1603             let linebpos = self.lines[line - 1];
1604             let col_display = {
1605                 let start_width_idx = self
1606                     .non_narrow_chars
1607                     .binary_search_by_key(&linebpos, |x| x.pos())
1608                     .unwrap_or_else(|x| x);
1609                 let end_width_idx = self
1610                     .non_narrow_chars
1611                     .binary_search_by_key(&pos, |x| x.pos())
1612                     .unwrap_or_else(|x| x);
1613                 let special_chars = end_width_idx - start_width_idx;
1614                 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1615                     .iter()
1616                     .map(|x| x.width())
1617                     .sum();
1618                 col.0 - special_chars + non_narrow
1619             };
1620             (line, col, col_display)
1621         } else {
1622             let chpos = col_or_chpos;
1623             let col_display = {
1624                 let end_width_idx = self
1625                     .non_narrow_chars
1626                     .binary_search_by_key(&pos, |x| x.pos())
1627                     .unwrap_or_else(|x| x);
1628                 let non_narrow: usize =
1629                     self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1630                 chpos.0 - end_width_idx + non_narrow
1631             };
1632             (0, chpos, col_display)
1633         }
1634     }
1635 }
1636
1637 /// Normalizes the source code and records the normalizations.
1638 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1639     let mut normalized_pos = vec![];
1640     remove_bom(src, &mut normalized_pos);
1641     normalize_newlines(src, &mut normalized_pos);
1642
1643     // Offset all the positions by start_pos to match the final file positions.
1644     for np in &mut normalized_pos {
1645         np.pos.0 += start_pos.0;
1646     }
1647
1648     normalized_pos
1649 }
1650
1651 /// Removes UTF-8 BOM, if any.
1652 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1653     if src.starts_with('\u{feff}') {
1654         src.drain(..3);
1655         normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1656     }
1657 }
1658
1659 /// Replaces `\r\n` with `\n` in-place in `src`.
1660 ///
1661 /// Returns error if there's a lone `\r` in the string.
1662 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1663     if !src.as_bytes().contains(&b'\r') {
1664         return;
1665     }
1666
1667     // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1668     // While we *can* call `as_mut_vec` and do surgery on the live string
1669     // directly, let's rather steal the contents of `src`. This makes the code
1670     // safe even if a panic occurs.
1671
1672     let mut buf = std::mem::replace(src, String::new()).into_bytes();
1673     let mut gap_len = 0;
1674     let mut tail = buf.as_mut_slice();
1675     let mut cursor = 0;
1676     let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1677     loop {
1678         let idx = match find_crlf(&tail[gap_len..]) {
1679             None => tail.len(),
1680             Some(idx) => idx + gap_len,
1681         };
1682         tail.copy_within(gap_len..idx, 0);
1683         tail = &mut tail[idx - gap_len..];
1684         if tail.len() == gap_len {
1685             break;
1686         }
1687         cursor += idx - gap_len;
1688         gap_len += 1;
1689         normalized_pos.push(NormalizedPos {
1690             pos: BytePos::from_usize(cursor + 1),
1691             diff: original_gap + gap_len as u32,
1692         });
1693     }
1694
1695     // Account for removed `\r`.
1696     // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1697     let new_len = buf.len() - gap_len;
1698     unsafe {
1699         buf.set_len(new_len);
1700         *src = String::from_utf8_unchecked(buf);
1701     }
1702
1703     fn find_crlf(src: &[u8]) -> Option<usize> {
1704         let mut search_idx = 0;
1705         while let Some(idx) = find_cr(&src[search_idx..]) {
1706             if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1707                 search_idx += idx + 1;
1708                 continue;
1709             }
1710             return Some(search_idx + idx);
1711         }
1712         None
1713     }
1714
1715     fn find_cr(src: &[u8]) -> Option<usize> {
1716         src.iter().position(|&b| b == b'\r')
1717     }
1718 }
1719
1720 // _____________________________________________________________________________
1721 // Pos, BytePos, CharPos
1722 //
1723
1724 pub trait Pos {
1725     fn from_usize(n: usize) -> Self;
1726     fn to_usize(&self) -> usize;
1727     fn from_u32(n: u32) -> Self;
1728     fn to_u32(&self) -> u32;
1729 }
1730
1731 macro_rules! impl_pos {
1732     (
1733         $(
1734             $(#[$attr:meta])*
1735             $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1736         )*
1737     ) => {
1738         $(
1739             $(#[$attr])*
1740             $vis struct $ident($inner_vis $inner_ty);
1741
1742             impl Pos for $ident {
1743                 #[inline(always)]
1744                 fn from_usize(n: usize) -> $ident {
1745                     $ident(n as $inner_ty)
1746                 }
1747
1748                 #[inline(always)]
1749                 fn to_usize(&self) -> usize {
1750                     self.0 as usize
1751                 }
1752
1753                 #[inline(always)]
1754                 fn from_u32(n: u32) -> $ident {
1755                     $ident(n as $inner_ty)
1756                 }
1757
1758                 #[inline(always)]
1759                 fn to_u32(&self) -> u32 {
1760                     self.0 as u32
1761                 }
1762             }
1763
1764             impl Add for $ident {
1765                 type Output = $ident;
1766
1767                 #[inline(always)]
1768                 fn add(self, rhs: $ident) -> $ident {
1769                     $ident(self.0 + rhs.0)
1770                 }
1771             }
1772
1773             impl Sub for $ident {
1774                 type Output = $ident;
1775
1776                 #[inline(always)]
1777                 fn sub(self, rhs: $ident) -> $ident {
1778                     $ident(self.0 - rhs.0)
1779                 }
1780             }
1781         )*
1782     };
1783 }
1784
1785 impl_pos! {
1786     /// A byte offset.
1787     ///
1788     /// Keep this small (currently 32-bits), as AST contains a lot of them.
1789     #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1790     pub struct BytePos(pub u32);
1791
1792     /// A character offset.
1793     ///
1794     /// Because of multibyte UTF-8 characters, a byte offset
1795     /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`]
1796     /// values to `CharPos` values as necessary.
1797     #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1798     pub struct CharPos(pub usize);
1799 }
1800
1801 impl<S: rustc_serialize::Encoder> Encodable<S> for BytePos {
1802     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1803         s.emit_u32(self.0)
1804     }
1805 }
1806
1807 impl<D: rustc_serialize::Decoder> Decodable<D> for BytePos {
1808     fn decode(d: &mut D) -> BytePos {
1809         BytePos(d.read_u32())
1810     }
1811 }
1812
1813 // _____________________________________________________________________________
1814 // Loc, SourceFileAndLine, SourceFileAndBytePos
1815 //
1816
1817 /// A source code location used for error reporting.
1818 #[derive(Debug, Clone)]
1819 pub struct Loc {
1820     /// Information about the original source.
1821     pub file: Lrc<SourceFile>,
1822     /// The (1-based) line number.
1823     pub line: usize,
1824     /// The (0-based) column offset.
1825     pub col: CharPos,
1826     /// The (0-based) column offset when displayed.
1827     pub col_display: usize,
1828 }
1829
1830 // Used to be structural records.
1831 #[derive(Debug)]
1832 pub struct SourceFileAndLine {
1833     pub sf: Lrc<SourceFile>,
1834     /// Index of line, starting from 0.
1835     pub line: usize,
1836 }
1837 #[derive(Debug)]
1838 pub struct SourceFileAndBytePos {
1839     pub sf: Lrc<SourceFile>,
1840     pub pos: BytePos,
1841 }
1842
1843 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1844 pub struct LineInfo {
1845     /// Index of line, starting from 0.
1846     pub line_index: usize,
1847
1848     /// Column in line where span begins, starting from 0.
1849     pub start_col: CharPos,
1850
1851     /// Column in line where span ends, starting from 0, exclusive.
1852     pub end_col: CharPos,
1853 }
1854
1855 pub struct FileLines {
1856     pub file: Lrc<SourceFile>,
1857     pub lines: Vec<LineInfo>,
1858 }
1859
1860 pub static SPAN_TRACK: AtomicRef<fn(LocalDefId)> = AtomicRef::new(&((|_| {}) as fn(_)));
1861
1862 // _____________________________________________________________________________
1863 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1864 //
1865
1866 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1867
1868 #[derive(Clone, PartialEq, Eq, Debug)]
1869 pub enum SpanLinesError {
1870     DistinctSources(DistinctSources),
1871 }
1872
1873 #[derive(Clone, PartialEq, Eq, Debug)]
1874 pub enum SpanSnippetError {
1875     IllFormedSpan(Span),
1876     DistinctSources(DistinctSources),
1877     MalformedForSourcemap(MalformedSourceMapPositions),
1878     SourceNotAvailable { filename: FileName },
1879 }
1880
1881 #[derive(Clone, PartialEq, Eq, Debug)]
1882 pub struct DistinctSources {
1883     pub begin: (FileName, BytePos),
1884     pub end: (FileName, BytePos),
1885 }
1886
1887 #[derive(Clone, PartialEq, Eq, Debug)]
1888 pub struct MalformedSourceMapPositions {
1889     pub name: FileName,
1890     pub source_len: usize,
1891     pub begin_pos: BytePos,
1892     pub end_pos: BytePos,
1893 }
1894
1895 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1896 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1897 pub struct InnerSpan {
1898     pub start: usize,
1899     pub end: usize,
1900 }
1901
1902 impl InnerSpan {
1903     pub fn new(start: usize, end: usize) -> InnerSpan {
1904         InnerSpan { start, end }
1905     }
1906 }
1907
1908 /// Requirements for a `StableHashingContext` to be used in this crate.
1909 ///
1910 /// This is a hack to allow using the [`HashStable_Generic`] derive macro
1911 /// instead of implementing everything in rustc_middle.
1912 pub trait HashStableContext {
1913     fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
1914     fn hash_spans(&self) -> bool;
1915     /// Accesses `sess.opts.debugging_opts.incremental_ignore_spans` since
1916     /// we don't have easy access to a `Session`
1917     fn debug_opts_incremental_ignore_spans(&self) -> bool;
1918     fn def_span(&self, def_id: LocalDefId) -> Span;
1919     fn span_data_to_lines_and_cols(
1920         &mut self,
1921         span: &SpanData,
1922     ) -> Option<(Lrc<SourceFile>, usize, BytePos, usize, BytePos)>;
1923     fn hashing_controls(&self) -> HashingControls;
1924 }
1925
1926 impl<CTX> HashStable<CTX> for Span
1927 where
1928     CTX: HashStableContext,
1929 {
1930     /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1931     /// fields (that would be similar to hashing pointers, since those are just
1932     /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1933     /// triple, which stays the same even if the containing `SourceFile` has moved
1934     /// within the `SourceMap`.
1935     ///
1936     /// Also note that we are hashing byte offsets for the column, not unicode
1937     /// codepoint offsets. For the purpose of the hash that's sufficient.
1938     /// Also, hashing filenames is expensive so we avoid doing it twice when the
1939     /// span starts and ends in the same file, which is almost always the case.
1940     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1941         const TAG_VALID_SPAN: u8 = 0;
1942         const TAG_INVALID_SPAN: u8 = 1;
1943         const TAG_RELATIVE_SPAN: u8 = 2;
1944
1945         if !ctx.hash_spans() {
1946             return;
1947         }
1948
1949         let span = self.data_untracked();
1950         span.ctxt.hash_stable(ctx, hasher);
1951         span.parent.hash_stable(ctx, hasher);
1952
1953         if span.is_dummy() {
1954             Hash::hash(&TAG_INVALID_SPAN, hasher);
1955             return;
1956         }
1957
1958         if let Some(parent) = span.parent {
1959             let def_span = ctx.def_span(parent).data_untracked();
1960             if def_span.contains(span) {
1961                 // This span is enclosed in a definition: only hash the relative position.
1962                 Hash::hash(&TAG_RELATIVE_SPAN, hasher);
1963                 (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher);
1964                 (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher);
1965                 return;
1966             }
1967         }
1968
1969         // If this is not an empty or invalid span, we want to hash the last
1970         // position that belongs to it, as opposed to hashing the first
1971         // position past it.
1972         let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span) else {
1973             Hash::hash(&TAG_INVALID_SPAN, hasher);
1974             return;
1975         };
1976
1977         Hash::hash(&TAG_VALID_SPAN, hasher);
1978         // We truncate the stable ID hash and line and column numbers. The chances
1979         // of causing a collision this way should be minimal.
1980         Hash::hash(&(file.name_hash as u64), hasher);
1981
1982         // Hash both the length and the end location (line/column) of a span. If we
1983         // hash only the length, for example, then two otherwise equal spans with
1984         // different end locations will have the same hash. This can cause a problem
1985         // during incremental compilation wherein a previous result for a query that
1986         // depends on the end location of a span will be incorrectly reused when the
1987         // end location of the span it depends on has changed (see issue #74890). A
1988         // similar analysis applies if some query depends specifically on the length
1989         // of the span, but we only hash the end location. So hash both.
1990
1991         let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
1992         let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1993         let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
1994         let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
1995         let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
1996         let len = (span.hi - span.lo).0;
1997         Hash::hash(&col_line, hasher);
1998         Hash::hash(&len, hasher);
1999     }
2000 }