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