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