]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/lib.rs
merge rustc history
[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 #![cfg_attr(bootstrap, 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 eq_ctxt(self, other: Span) -> bool {
537         self.data_untracked().ctxt == other.data_untracked().ctxt
538     }
539     #[inline]
540     pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
541         self.data_untracked().with_ctxt(ctxt)
542     }
543     #[inline]
544     pub fn parent(self) -> Option<LocalDefId> {
545         self.data().parent
546     }
547     #[inline]
548     pub fn with_parent(self, ctxt: Option<LocalDefId>) -> Span {
549         self.data().with_parent(ctxt)
550     }
551
552     /// Returns `true` if this is a dummy span with any hygienic context.
553     #[inline]
554     pub fn is_dummy(self) -> bool {
555         self.data_untracked().is_dummy()
556     }
557
558     /// Returns `true` if this span comes from a macro or desugaring.
559     #[inline]
560     pub fn from_expansion(self) -> bool {
561         self.ctxt() != SyntaxContext::root()
562     }
563
564     /// Returns `true` if `span` originates in a macro's expansion where debuginfo should be
565     /// collapsed.
566     pub fn in_macro_expansion_with_collapse_debuginfo(self) -> bool {
567         let outer_expn = self.ctxt().outer_expn_data();
568         matches!(outer_expn.kind, ExpnKind::Macro(..)) && outer_expn.collapse_debuginfo
569     }
570
571     /// Returns `true` if `span` originates in a derive-macro's expansion.
572     pub fn in_derive_expansion(self) -> bool {
573         matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
574     }
575
576     /// Gate suggestions that would not be appropriate in a context the user didn't write.
577     pub fn can_be_used_for_suggestions(self) -> bool {
578         !self.from_expansion()
579         // FIXME: If this span comes from a `derive` macro but it points at code the user wrote,
580         // the callsite span and the span will be pointing at different places. It also means that
581         // we can safely provide suggestions on this span.
582             || (matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
583                 && self.parent_callsite().map(|p| (p.lo(), p.hi())) != Some((self.lo(), self.hi())))
584     }
585
586     #[inline]
587     pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
588         Span::new(lo, hi, SyntaxContext::root(), None)
589     }
590
591     /// Returns a new span representing an empty span at the beginning of this span.
592     #[inline]
593     pub fn shrink_to_lo(self) -> Span {
594         let span = self.data_untracked();
595         span.with_hi(span.lo)
596     }
597     /// Returns a new span representing an empty span at the end of this span.
598     #[inline]
599     pub fn shrink_to_hi(self) -> Span {
600         let span = self.data_untracked();
601         span.with_lo(span.hi)
602     }
603
604     #[inline]
605     /// Returns `true` if `hi == lo`.
606     pub fn is_empty(self) -> bool {
607         let span = self.data_untracked();
608         span.hi == span.lo
609     }
610
611     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
612     pub fn substitute_dummy(self, other: Span) -> Span {
613         if self.is_dummy() { other } else { self }
614     }
615
616     /// Returns `true` if `self` fully encloses `other`.
617     pub fn contains(self, other: Span) -> bool {
618         let span = self.data();
619         let other = other.data();
620         span.contains(other)
621     }
622
623     /// Returns `true` if `self` touches `other`.
624     pub fn overlaps(self, other: Span) -> bool {
625         let span = self.data();
626         let other = other.data();
627         span.lo < other.hi && other.lo < span.hi
628     }
629
630     /// Returns `true` if the spans are equal with regards to the source text.
631     ///
632     /// Use this instead of `==` when either span could be generated code,
633     /// and you only care that they point to the same bytes of source text.
634     pub fn source_equal(self, other: Span) -> bool {
635         let span = self.data();
636         let other = other.data();
637         span.lo == other.lo && span.hi == other.hi
638     }
639
640     /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
641     pub fn trim_start(self, other: Span) -> Option<Span> {
642         let span = self.data();
643         let other = other.data();
644         if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
645     }
646
647     /// Returns the source span -- this is either the supplied span, or the span for
648     /// the macro callsite that expanded to it.
649     pub fn source_callsite(self) -> Span {
650         let expn_data = self.ctxt().outer_expn_data();
651         if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
652     }
653
654     /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
655     /// if any.
656     pub fn parent_callsite(self) -> Option<Span> {
657         let expn_data = self.ctxt().outer_expn_data();
658         if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
659     }
660
661     /// Walk down the expansion ancestors to find a span that's contained within `outer`.
662     pub fn find_ancestor_inside(mut self, outer: Span) -> Option<Span> {
663         while !outer.contains(self) {
664             self = self.parent_callsite()?;
665         }
666         Some(self)
667     }
668
669     /// Like `find_ancestor_inside`, but specifically for when spans might not
670     /// overlaps. Take care when using this, and prefer `find_ancestor_inside`
671     /// when you know that the spans are nested (modulo macro expansion).
672     pub fn find_ancestor_in_same_ctxt(mut self, other: Span) -> Option<Span> {
673         while !Span::eq_ctxt(self, other) {
674             self = self.parent_callsite()?;
675         }
676         Some(self)
677     }
678
679     /// Edition of the crate from which this span came.
680     pub fn edition(self) -> edition::Edition {
681         self.ctxt().edition()
682     }
683
684     #[inline]
685     pub fn rust_2015(self) -> bool {
686         self.edition() == edition::Edition::Edition2015
687     }
688
689     #[inline]
690     pub fn rust_2018(self) -> bool {
691         self.edition() >= edition::Edition::Edition2018
692     }
693
694     #[inline]
695     pub fn rust_2021(self) -> bool {
696         self.edition() >= edition::Edition::Edition2021
697     }
698
699     #[inline]
700     pub fn rust_2024(self) -> bool {
701         self.edition() >= edition::Edition::Edition2024
702     }
703
704     /// Returns the source callee.
705     ///
706     /// Returns `None` if the supplied span has no expansion trace,
707     /// else returns the `ExpnData` for the macro definition
708     /// corresponding to the source callsite.
709     pub fn source_callee(self) -> Option<ExpnData> {
710         fn source_callee(expn_data: ExpnData) -> ExpnData {
711             let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
712             if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
713         }
714         let expn_data = self.ctxt().outer_expn_data();
715         if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
716     }
717
718     /// Checks if a span is "internal" to a macro in which `#[unstable]`
719     /// items can be used (that is, a macro marked with
720     /// `#[allow_internal_unstable]`).
721     pub fn allows_unstable(self, feature: Symbol) -> bool {
722         self.ctxt()
723             .outer_expn_data()
724             .allow_internal_unstable
725             .map_or(false, |features| features.iter().any(|&f| f == feature))
726     }
727
728     /// Checks if this span arises from a compiler desugaring of kind `kind`.
729     pub fn is_desugaring(self, kind: DesugaringKind) -> bool {
730         match self.ctxt().outer_expn_data().kind {
731             ExpnKind::Desugaring(k) => k == kind,
732             _ => false,
733         }
734     }
735
736     /// Returns the compiler desugaring that created this span, or `None`
737     /// if this span is not from a desugaring.
738     pub fn desugaring_kind(self) -> Option<DesugaringKind> {
739         match self.ctxt().outer_expn_data().kind {
740             ExpnKind::Desugaring(k) => Some(k),
741             _ => None,
742         }
743     }
744
745     /// Checks if a span is "internal" to a macro in which `unsafe`
746     /// can be used without triggering the `unsafe_code` lint.
747     //  (that is, a macro marked with `#[allow_internal_unsafe]`).
748     pub fn allows_unsafe(self) -> bool {
749         self.ctxt().outer_expn_data().allow_internal_unsafe
750     }
751
752     pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
753         let mut prev_span = DUMMY_SP;
754         std::iter::from_fn(move || {
755             loop {
756                 let expn_data = self.ctxt().outer_expn_data();
757                 if expn_data.is_root() {
758                     return None;
759                 }
760
761                 let is_recursive = expn_data.call_site.source_equal(prev_span);
762
763                 prev_span = self;
764                 self = expn_data.call_site;
765
766                 // Don't print recursive invocations.
767                 if !is_recursive {
768                     return Some(expn_data);
769                 }
770             }
771         })
772     }
773
774     /// Returns a `Span` that would enclose both `self` and `end`.
775     ///
776     /// ```text
777     ///     ____             ___
778     ///     self lorem ipsum end
779     ///     ^^^^^^^^^^^^^^^^^^^^
780     /// ```
781     pub fn to(self, end: Span) -> Span {
782         let span_data = self.data();
783         let end_data = end.data();
784         // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
785         // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
786         // have an incomplete span than a completely nonsensical one.
787         if span_data.ctxt != end_data.ctxt {
788             if span_data.ctxt == SyntaxContext::root() {
789                 return end;
790             } else if end_data.ctxt == SyntaxContext::root() {
791                 return self;
792             }
793             // Both spans fall within a macro.
794             // FIXME(estebank): check if it is the *same* macro.
795         }
796         Span::new(
797             cmp::min(span_data.lo, end_data.lo),
798             cmp::max(span_data.hi, end_data.hi),
799             if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
800             if span_data.parent == end_data.parent { span_data.parent } else { None },
801         )
802     }
803
804     /// Returns a `Span` between the end of `self` to the beginning of `end`.
805     ///
806     /// ```text
807     ///     ____             ___
808     ///     self lorem ipsum end
809     ///         ^^^^^^^^^^^^^
810     /// ```
811     pub fn between(self, end: Span) -> Span {
812         let span = self.data();
813         let end = end.data();
814         Span::new(
815             span.hi,
816             end.lo,
817             if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
818             if span.parent == end.parent { span.parent } else { None },
819         )
820     }
821
822     /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
823     ///
824     /// ```text
825     ///     ____             ___
826     ///     self lorem ipsum end
827     ///     ^^^^^^^^^^^^^^^^^
828     /// ```
829     pub fn until(self, end: Span) -> Span {
830         // Most of this function's body is copied from `to`.
831         // We can't just do `self.to(end.shrink_to_lo())`,
832         // because to also does some magic where it uses min/max so
833         // it can handle overlapping spans. Some advanced mis-use of
834         // `until` with different ctxts makes this visible.
835         let span_data = self.data();
836         let end_data = end.data();
837         // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
838         // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
839         // have an incomplete span than a completely nonsensical one.
840         if span_data.ctxt != end_data.ctxt {
841             if span_data.ctxt == SyntaxContext::root() {
842                 return end;
843             } else if end_data.ctxt == SyntaxContext::root() {
844                 return self;
845             }
846             // Both spans fall within a macro.
847             // FIXME(estebank): check if it is the *same* macro.
848         }
849         Span::new(
850             span_data.lo,
851             end_data.lo,
852             if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
853             if span_data.parent == end_data.parent { span_data.parent } else { None },
854         )
855     }
856
857     pub fn from_inner(self, inner: InnerSpan) -> Span {
858         let span = self.data();
859         Span::new(
860             span.lo + BytePos::from_usize(inner.start),
861             span.lo + BytePos::from_usize(inner.end),
862             span.ctxt,
863             span.parent,
864         )
865     }
866
867     /// Equivalent of `Span::def_site` from the proc macro API,
868     /// except that the location is taken from the `self` span.
869     pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
870         self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
871     }
872
873     /// Equivalent of `Span::call_site` from the proc macro API,
874     /// except that the location is taken from the `self` span.
875     pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span {
876         self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
877     }
878
879     /// Equivalent of `Span::mixed_site` from the proc macro API,
880     /// except that the location is taken from the `self` span.
881     pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span {
882         self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
883     }
884
885     /// Produces a span with the same location as `self` and context produced by a macro with the
886     /// given ID and transparency, assuming that macro was defined directly and not produced by
887     /// some other macro (which is the case for built-in and procedural macros).
888     pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
889         self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
890     }
891
892     #[inline]
893     pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
894         let span = self.data();
895         span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
896     }
897
898     #[inline]
899     pub fn remove_mark(&mut self) -> ExpnId {
900         let mut span = self.data();
901         let mark = span.ctxt.remove_mark();
902         *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
903         mark
904     }
905
906     #[inline]
907     pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
908         let mut span = self.data();
909         let mark = span.ctxt.adjust(expn_id);
910         *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
911         mark
912     }
913
914     #[inline]
915     pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
916         let mut span = self.data();
917         let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
918         *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
919         mark
920     }
921
922     #[inline]
923     pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
924         let mut span = self.data();
925         let mark = span.ctxt.glob_adjust(expn_id, glob_span);
926         *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
927         mark
928     }
929
930     #[inline]
931     pub fn reverse_glob_adjust(
932         &mut self,
933         expn_id: ExpnId,
934         glob_span: Span,
935     ) -> Option<Option<ExpnId>> {
936         let mut span = self.data();
937         let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
938         *self = Span::new(span.lo, span.hi, span.ctxt, span.parent);
939         mark
940     }
941
942     #[inline]
943     pub fn normalize_to_macros_2_0(self) -> Span {
944         let span = self.data();
945         span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
946     }
947
948     #[inline]
949     pub fn normalize_to_macro_rules(self) -> Span {
950         let span = self.data();
951         span.with_ctxt(span.ctxt.normalize_to_macro_rules())
952     }
953 }
954
955 impl Default for Span {
956     fn default() -> Self {
957         DUMMY_SP
958     }
959 }
960
961 impl<E: Encoder> Encodable<E> for Span {
962     default fn encode(&self, s: &mut E) {
963         let span = self.data();
964         span.lo.encode(s);
965         span.hi.encode(s);
966     }
967 }
968 impl<D: Decoder> Decodable<D> for Span {
969     default fn decode(s: &mut D) -> Span {
970         let lo = Decodable::decode(s);
971         let hi = Decodable::decode(s);
972
973         Span::new(lo, hi, SyntaxContext::root(), None)
974     }
975 }
976
977 /// Calls the provided closure, using the provided `SourceMap` to format
978 /// any spans that are debug-printed during the closure's execution.
979 ///
980 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
981 /// (see `rustc_interface::callbacks::span_debug1`). However, some parts
982 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
983 /// a `TyCtxt` is available. In this case, we fall back to
984 /// the `SourceMap` provided to this function. If that is not available,
985 /// we fall back to printing the raw `Span` field values.
986 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
987     with_session_globals(|session_globals| {
988         *session_globals.source_map.borrow_mut() = Some(source_map);
989     });
990     struct ClearSourceMap;
991     impl Drop for ClearSourceMap {
992         fn drop(&mut self) {
993             with_session_globals(|session_globals| {
994                 session_globals.source_map.borrow_mut().take();
995             });
996         }
997     }
998
999     let _guard = ClearSourceMap;
1000     f()
1001 }
1002
1003 impl fmt::Debug for Span {
1004     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1005         with_session_globals(|session_globals| {
1006             if let Some(source_map) = &*session_globals.source_map.borrow() {
1007                 write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(*self), self.ctxt())
1008             } else {
1009                 f.debug_struct("Span")
1010                     .field("lo", &self.lo())
1011                     .field("hi", &self.hi())
1012                     .field("ctxt", &self.ctxt())
1013                     .finish()
1014             }
1015         })
1016     }
1017 }
1018
1019 impl fmt::Debug for SpanData {
1020     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1021         fmt::Debug::fmt(&Span::new(self.lo, self.hi, self.ctxt, self.parent), f)
1022     }
1023 }
1024
1025 /// Identifies an offset of a multi-byte character in a `SourceFile`.
1026 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1027 pub struct MultiByteChar {
1028     /// The absolute offset of the character in the `SourceMap`.
1029     pub pos: BytePos,
1030     /// The number of bytes, `>= 2`.
1031     pub bytes: u8,
1032 }
1033
1034 /// Identifies an offset of a non-narrow character in a `SourceFile`.
1035 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1036 pub enum NonNarrowChar {
1037     /// Represents a zero-width character.
1038     ZeroWidth(BytePos),
1039     /// Represents a wide (full-width) character.
1040     Wide(BytePos),
1041     /// Represents a tab character, represented visually with a width of 4 characters.
1042     Tab(BytePos),
1043 }
1044
1045 impl NonNarrowChar {
1046     fn new(pos: BytePos, width: usize) -> Self {
1047         match width {
1048             0 => NonNarrowChar::ZeroWidth(pos),
1049             2 => NonNarrowChar::Wide(pos),
1050             4 => NonNarrowChar::Tab(pos),
1051             _ => panic!("width {} given for non-narrow character", width),
1052         }
1053     }
1054
1055     /// Returns the absolute offset of the character in the `SourceMap`.
1056     pub fn pos(&self) -> BytePos {
1057         match *self {
1058             NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
1059         }
1060     }
1061
1062     /// Returns the width of the character, 0 (zero-width) or 2 (wide).
1063     pub fn width(&self) -> usize {
1064         match *self {
1065             NonNarrowChar::ZeroWidth(_) => 0,
1066             NonNarrowChar::Wide(_) => 2,
1067             NonNarrowChar::Tab(_) => 4,
1068         }
1069     }
1070 }
1071
1072 impl Add<BytePos> for NonNarrowChar {
1073     type Output = Self;
1074
1075     fn add(self, rhs: BytePos) -> Self {
1076         match self {
1077             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
1078             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
1079             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
1080         }
1081     }
1082 }
1083
1084 impl Sub<BytePos> for NonNarrowChar {
1085     type Output = Self;
1086
1087     fn sub(self, rhs: BytePos) -> Self {
1088         match self {
1089             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
1090             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
1091             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
1092         }
1093     }
1094 }
1095
1096 /// Identifies an offset of a character that was normalized away from `SourceFile`.
1097 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1098 pub struct NormalizedPos {
1099     /// The absolute offset of the character in the `SourceMap`.
1100     pub pos: BytePos,
1101     /// The difference between original and normalized string at position.
1102     pub diff: u32,
1103 }
1104
1105 #[derive(PartialEq, Eq, Clone, Debug)]
1106 pub enum ExternalSource {
1107     /// No external source has to be loaded, since the `SourceFile` represents a local crate.
1108     Unneeded,
1109     Foreign {
1110         kind: ExternalSourceKind,
1111         /// Index of the file inside metadata.
1112         metadata_index: u32,
1113     },
1114 }
1115
1116 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1117 #[derive(PartialEq, Eq, Clone, Debug)]
1118 pub enum ExternalSourceKind {
1119     /// The external source has been loaded already.
1120     Present(Lrc<String>),
1121     /// No attempt has been made to load the external source.
1122     AbsentOk,
1123     /// A failed attempt has been made to load the external source.
1124     AbsentErr,
1125     Unneeded,
1126 }
1127
1128 impl ExternalSource {
1129     pub fn get_source(&self) -> Option<&Lrc<String>> {
1130         match self {
1131             ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1132             _ => None,
1133         }
1134     }
1135 }
1136
1137 #[derive(Debug)]
1138 pub struct OffsetOverflowError;
1139
1140 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1141 #[derive(HashStable_Generic)]
1142 pub enum SourceFileHashAlgorithm {
1143     Md5,
1144     Sha1,
1145     Sha256,
1146 }
1147
1148 impl FromStr for SourceFileHashAlgorithm {
1149     type Err = ();
1150
1151     fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1152         match s {
1153             "md5" => Ok(SourceFileHashAlgorithm::Md5),
1154             "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1155             "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1156             _ => Err(()),
1157         }
1158     }
1159 }
1160
1161 /// The hash of the on-disk source file used for debug info.
1162 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
1163 #[derive(HashStable_Generic, Encodable, Decodable)]
1164 pub struct SourceFileHash {
1165     pub kind: SourceFileHashAlgorithm,
1166     value: [u8; 32],
1167 }
1168
1169 impl SourceFileHash {
1170     pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1171         let mut hash = SourceFileHash { kind, value: Default::default() };
1172         let len = hash.hash_len();
1173         let value = &mut hash.value[..len];
1174         let data = src.as_bytes();
1175         match kind {
1176             SourceFileHashAlgorithm::Md5 => {
1177                 value.copy_from_slice(&Md5::digest(data));
1178             }
1179             SourceFileHashAlgorithm::Sha1 => {
1180                 value.copy_from_slice(&Sha1::digest(data));
1181             }
1182             SourceFileHashAlgorithm::Sha256 => {
1183                 value.copy_from_slice(&Sha256::digest(data));
1184             }
1185         }
1186         hash
1187     }
1188
1189     /// Check if the stored hash matches the hash of the string.
1190     pub fn matches(&self, src: &str) -> bool {
1191         Self::new(self.kind, src) == *self
1192     }
1193
1194     /// The bytes of the hash.
1195     pub fn hash_bytes(&self) -> &[u8] {
1196         let len = self.hash_len();
1197         &self.value[..len]
1198     }
1199
1200     fn hash_len(&self) -> usize {
1201         match self.kind {
1202             SourceFileHashAlgorithm::Md5 => 16,
1203             SourceFileHashAlgorithm::Sha1 => 20,
1204             SourceFileHashAlgorithm::Sha256 => 32,
1205         }
1206     }
1207 }
1208
1209 #[derive(HashStable_Generic)]
1210 #[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug, Encodable, Decodable)]
1211 pub enum DebuggerVisualizerType {
1212     Natvis,
1213     GdbPrettyPrinter,
1214 }
1215
1216 /// A single debugger visualizer file.
1217 #[derive(HashStable_Generic)]
1218 #[derive(Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable)]
1219 pub struct DebuggerVisualizerFile {
1220     /// The complete debugger visualizer source.
1221     pub src: Arc<[u8]>,
1222     /// Indicates which visualizer type this targets.
1223     pub visualizer_type: DebuggerVisualizerType,
1224 }
1225
1226 impl DebuggerVisualizerFile {
1227     pub fn new(src: Arc<[u8]>, visualizer_type: DebuggerVisualizerType) -> Self {
1228         DebuggerVisualizerFile { src, visualizer_type }
1229     }
1230 }
1231
1232 #[derive(Clone)]
1233 pub enum SourceFileLines {
1234     /// The source file lines, in decoded (random-access) form.
1235     Lines(Vec<BytePos>),
1236
1237     /// The source file lines, in undecoded difference list form.
1238     Diffs(SourceFileDiffs),
1239 }
1240
1241 impl SourceFileLines {
1242     pub fn is_lines(&self) -> bool {
1243         matches!(self, SourceFileLines::Lines(_))
1244     }
1245 }
1246
1247 /// The source file lines in difference list form. This matches the form
1248 /// used within metadata, which saves space by exploiting the fact that the
1249 /// lines list is sorted and individual lines are usually not that long.
1250 ///
1251 /// We read it directly from metadata and only decode it into `Lines` form
1252 /// when necessary. This is a significant performance win, especially for
1253 /// small crates where very little of `std`'s metadata is used.
1254 #[derive(Clone)]
1255 pub struct SourceFileDiffs {
1256     /// Position of the first line. Note that this is always encoded as a
1257     /// `BytePos` because it is often much larger than any of the
1258     /// differences.
1259     line_start: BytePos,
1260
1261     /// Always 1, 2, or 4. Always as small as possible, while being big
1262     /// enough to hold the length of the longest line in the source file.
1263     /// The 1 case is by far the most common.
1264     bytes_per_diff: usize,
1265
1266     /// The number of diffs encoded in `raw_diffs`. Always one less than
1267     /// the number of lines in the source file.
1268     num_diffs: usize,
1269
1270     /// The diffs in "raw" form. Each segment of `bytes_per_diff` length
1271     /// encodes one little-endian diff. Note that they aren't LEB128
1272     /// encoded. This makes for much faster decoding. Besides, the
1273     /// bytes_per_diff==1 case is by far the most common, and LEB128
1274     /// encoding has no effect on that case.
1275     raw_diffs: Vec<u8>,
1276 }
1277
1278 /// A single source in the [`SourceMap`].
1279 #[derive(Clone)]
1280 pub struct SourceFile {
1281     /// The name of the file that the source came from. Source that doesn't
1282     /// originate from files has names between angle brackets by convention
1283     /// (e.g., `<anon>`).
1284     pub name: FileName,
1285     /// The complete source code.
1286     pub src: Option<Lrc<String>>,
1287     /// The source code's hash.
1288     pub src_hash: SourceFileHash,
1289     /// The external source code (used for external crates, which will have a `None`
1290     /// value as `self.src`.
1291     pub external_src: Lock<ExternalSource>,
1292     /// The start position of this source in the `SourceMap`.
1293     pub start_pos: BytePos,
1294     /// The end position of this source in the `SourceMap`.
1295     pub end_pos: BytePos,
1296     /// Locations of lines beginnings in the source code.
1297     pub lines: Lock<SourceFileLines>,
1298     /// Locations of multi-byte characters in the source code.
1299     pub multibyte_chars: Vec<MultiByteChar>,
1300     /// Width of characters that are not narrow in the source code.
1301     pub non_narrow_chars: Vec<NonNarrowChar>,
1302     /// Locations of characters removed during normalization.
1303     pub normalized_pos: Vec<NormalizedPos>,
1304     /// A hash of the filename, used for speeding up hashing in incremental compilation.
1305     pub name_hash: u128,
1306     /// Indicates which crate this `SourceFile` was imported from.
1307     pub cnum: CrateNum,
1308 }
1309
1310 impl<S: Encoder> Encodable<S> for SourceFile {
1311     fn encode(&self, s: &mut S) {
1312         self.name.encode(s);
1313         self.src_hash.encode(s);
1314         self.start_pos.encode(s);
1315         self.end_pos.encode(s);
1316
1317         // We are always in `Lines` form by the time we reach here.
1318         assert!(self.lines.borrow().is_lines());
1319         self.lines(|lines| {
1320             // Store the length.
1321             s.emit_u32(lines.len() as u32);
1322
1323             // Compute and store the difference list.
1324             if lines.len() != 0 {
1325                 let max_line_length = if lines.len() == 1 {
1326                     0
1327                 } else {
1328                     lines
1329                         .array_windows()
1330                         .map(|&[fst, snd]| snd - fst)
1331                         .map(|bp| bp.to_usize())
1332                         .max()
1333                         .unwrap()
1334                 };
1335
1336                 let bytes_per_diff: usize = match max_line_length {
1337                     0..=0xFF => 1,
1338                     0x100..=0xFFFF => 2,
1339                     _ => 4,
1340                 };
1341
1342                 // Encode the number of bytes used per diff.
1343                 s.emit_u8(bytes_per_diff as u8);
1344
1345                 // Encode the first element.
1346                 lines[0].encode(s);
1347
1348                 // Encode the difference list.
1349                 let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst);
1350                 let num_diffs = lines.len() - 1;
1351                 let mut raw_diffs;
1352                 match bytes_per_diff {
1353                     1 => {
1354                         raw_diffs = Vec::with_capacity(num_diffs);
1355                         for diff in diff_iter {
1356                             raw_diffs.push(diff.0 as u8);
1357                         }
1358                     }
1359                     2 => {
1360                         raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
1361                         for diff in diff_iter {
1362                             raw_diffs.extend_from_slice(&(diff.0 as u16).to_le_bytes());
1363                         }
1364                     }
1365                     4 => {
1366                         raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
1367                         for diff in diff_iter {
1368                             raw_diffs.extend_from_slice(&(diff.0 as u32).to_le_bytes());
1369                         }
1370                     }
1371                     _ => unreachable!(),
1372                 }
1373                 s.emit_raw_bytes(&raw_diffs);
1374             }
1375         });
1376
1377         self.multibyte_chars.encode(s);
1378         self.non_narrow_chars.encode(s);
1379         self.name_hash.encode(s);
1380         self.normalized_pos.encode(s);
1381         self.cnum.encode(s);
1382     }
1383 }
1384
1385 impl<D: Decoder> Decodable<D> for SourceFile {
1386     fn decode(d: &mut D) -> SourceFile {
1387         let name: FileName = Decodable::decode(d);
1388         let src_hash: SourceFileHash = Decodable::decode(d);
1389         let start_pos: BytePos = Decodable::decode(d);
1390         let end_pos: BytePos = Decodable::decode(d);
1391         let lines = {
1392             let num_lines: u32 = Decodable::decode(d);
1393             if num_lines > 0 {
1394                 // Read the number of bytes used per diff.
1395                 let bytes_per_diff = d.read_u8() as usize;
1396
1397                 // Read the first element.
1398                 let line_start: BytePos = Decodable::decode(d);
1399
1400                 // Read the difference list.
1401                 let num_diffs = num_lines as usize - 1;
1402                 let raw_diffs = d.read_raw_bytes(bytes_per_diff * num_diffs).to_vec();
1403                 SourceFileLines::Diffs(SourceFileDiffs {
1404                     line_start,
1405                     bytes_per_diff,
1406                     num_diffs,
1407                     raw_diffs,
1408                 })
1409             } else {
1410                 SourceFileLines::Lines(vec![])
1411             }
1412         };
1413         let multibyte_chars: Vec<MultiByteChar> = Decodable::decode(d);
1414         let non_narrow_chars: Vec<NonNarrowChar> = Decodable::decode(d);
1415         let name_hash: u128 = Decodable::decode(d);
1416         let normalized_pos: Vec<NormalizedPos> = Decodable::decode(d);
1417         let cnum: CrateNum = Decodable::decode(d);
1418         SourceFile {
1419             name,
1420             start_pos,
1421             end_pos,
1422             src: None,
1423             src_hash,
1424             // Unused - the metadata decoder will construct
1425             // a new SourceFile, filling in `external_src` properly
1426             external_src: Lock::new(ExternalSource::Unneeded),
1427             lines: Lock::new(lines),
1428             multibyte_chars,
1429             non_narrow_chars,
1430             normalized_pos,
1431             name_hash,
1432             cnum,
1433         }
1434     }
1435 }
1436
1437 impl fmt::Debug for SourceFile {
1438     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1439         write!(fmt, "SourceFile({:?})", self.name)
1440     }
1441 }
1442
1443 impl SourceFile {
1444     pub fn new(
1445         name: FileName,
1446         mut src: String,
1447         start_pos: BytePos,
1448         hash_kind: SourceFileHashAlgorithm,
1449     ) -> Self {
1450         // Compute the file hash before any normalization.
1451         let src_hash = SourceFileHash::new(hash_kind, &src);
1452         let normalized_pos = normalize_src(&mut src, start_pos);
1453
1454         let name_hash = {
1455             let mut hasher: StableHasher = StableHasher::new();
1456             name.hash(&mut hasher);
1457             hasher.finish::<u128>()
1458         };
1459         let end_pos = start_pos.to_usize() + src.len();
1460         assert!(end_pos <= u32::MAX as usize);
1461
1462         let (lines, multibyte_chars, non_narrow_chars) =
1463             analyze_source_file::analyze_source_file(&src, start_pos);
1464
1465         SourceFile {
1466             name,
1467             src: Some(Lrc::new(src)),
1468             src_hash,
1469             external_src: Lock::new(ExternalSource::Unneeded),
1470             start_pos,
1471             end_pos: Pos::from_usize(end_pos),
1472             lines: Lock::new(SourceFileLines::Lines(lines)),
1473             multibyte_chars,
1474             non_narrow_chars,
1475             normalized_pos,
1476             name_hash,
1477             cnum: LOCAL_CRATE,
1478         }
1479     }
1480
1481     pub fn lines<F, R>(&self, f: F) -> R
1482     where
1483         F: FnOnce(&[BytePos]) -> R,
1484     {
1485         let mut guard = self.lines.borrow_mut();
1486         match &*guard {
1487             SourceFileLines::Lines(lines) => f(lines),
1488             SourceFileLines::Diffs(SourceFileDiffs {
1489                 mut line_start,
1490                 bytes_per_diff,
1491                 num_diffs,
1492                 raw_diffs,
1493             }) => {
1494                 // Convert from "diffs" form to "lines" form.
1495                 let num_lines = num_diffs + 1;
1496                 let mut lines = Vec::with_capacity(num_lines);
1497                 lines.push(line_start);
1498
1499                 assert_eq!(*num_diffs, raw_diffs.len() / bytes_per_diff);
1500                 match bytes_per_diff {
1501                     1 => {
1502                         lines.extend(raw_diffs.into_iter().map(|&diff| {
1503                             line_start = line_start + BytePos(diff as u32);
1504                             line_start
1505                         }));
1506                     }
1507                     2 => {
1508                         lines.extend((0..*num_diffs).map(|i| {
1509                             let pos = bytes_per_diff * i;
1510                             let bytes = [raw_diffs[pos], raw_diffs[pos + 1]];
1511                             let diff = u16::from_le_bytes(bytes);
1512                             line_start = line_start + BytePos(diff as u32);
1513                             line_start
1514                         }));
1515                     }
1516                     4 => {
1517                         lines.extend((0..*num_diffs).map(|i| {
1518                             let pos = bytes_per_diff * i;
1519                             let bytes = [
1520                                 raw_diffs[pos],
1521                                 raw_diffs[pos + 1],
1522                                 raw_diffs[pos + 2],
1523                                 raw_diffs[pos + 3],
1524                             ];
1525                             let diff = u32::from_le_bytes(bytes);
1526                             line_start = line_start + BytePos(diff);
1527                             line_start
1528                         }));
1529                     }
1530                     _ => unreachable!(),
1531                 }
1532                 let res = f(&lines);
1533                 *guard = SourceFileLines::Lines(lines);
1534                 res
1535             }
1536         }
1537     }
1538
1539     /// Returns the `BytePos` of the beginning of the current line.
1540     pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1541         let line_index = self.lookup_line(pos).unwrap();
1542         self.lines(|lines| lines[line_index])
1543     }
1544
1545     /// Add externally loaded source.
1546     /// If the hash of the input doesn't match or no input is supplied via None,
1547     /// it is interpreted as an error and the corresponding enum variant is set.
1548     /// The return value signifies whether some kind of source is present.
1549     pub fn add_external_src<F>(&self, get_src: F) -> bool
1550     where
1551         F: FnOnce() -> Option<String>,
1552     {
1553         if matches!(
1554             *self.external_src.borrow(),
1555             ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1556         ) {
1557             let src = get_src();
1558             let mut external_src = self.external_src.borrow_mut();
1559             // Check that no-one else have provided the source while we were getting it
1560             if let ExternalSource::Foreign {
1561                 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1562             } = &mut *external_src
1563             {
1564                 if let Some(mut src) = src {
1565                     // The src_hash needs to be computed on the pre-normalized src.
1566                     if self.src_hash.matches(&src) {
1567                         normalize_src(&mut src, BytePos::from_usize(0));
1568                         *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1569                         return true;
1570                     }
1571                 } else {
1572                     *src_kind = ExternalSourceKind::AbsentErr;
1573                 }
1574
1575                 false
1576             } else {
1577                 self.src.is_some() || external_src.get_source().is_some()
1578             }
1579         } else {
1580             self.src.is_some() || self.external_src.borrow().get_source().is_some()
1581         }
1582     }
1583
1584     /// Gets a line from the list of pre-computed line-beginnings.
1585     /// The line number here is 0-based.
1586     pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1587         fn get_until_newline(src: &str, begin: usize) -> &str {
1588             // We can't use `lines.get(line_number+1)` because we might
1589             // be parsing when we call this function and thus the current
1590             // line is the last one we have line info for.
1591             let slice = &src[begin..];
1592             match slice.find('\n') {
1593                 Some(e) => &slice[..e],
1594                 None => slice,
1595             }
1596         }
1597
1598         let begin = {
1599             let line = self.lines(|lines| lines.get(line_number).copied())?;
1600             let begin: BytePos = line - self.start_pos;
1601             begin.to_usize()
1602         };
1603
1604         if let Some(ref src) = self.src {
1605             Some(Cow::from(get_until_newline(src, begin)))
1606         } else if let Some(src) = self.external_src.borrow().get_source() {
1607             Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1608         } else {
1609             None
1610         }
1611     }
1612
1613     pub fn is_real_file(&self) -> bool {
1614         self.name.is_real()
1615     }
1616
1617     #[inline]
1618     pub fn is_imported(&self) -> bool {
1619         self.src.is_none()
1620     }
1621
1622     pub fn count_lines(&self) -> usize {
1623         self.lines(|lines| lines.len())
1624     }
1625
1626     /// Finds the line containing the given position. The return value is the
1627     /// index into the `lines` array of this `SourceFile`, not the 1-based line
1628     /// number. If the source_file is empty or the position is located before the
1629     /// first line, `None` is returned.
1630     pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1631         self.lines(|lines| match lines.partition_point(|x| x <= &pos) {
1632             0 => None,
1633             i => Some(i - 1),
1634         })
1635     }
1636
1637     pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
1638         if self.is_empty() {
1639             return self.start_pos..self.end_pos;
1640         }
1641
1642         self.lines(|lines| {
1643             assert!(line_index < lines.len());
1644             if line_index == (lines.len() - 1) {
1645                 lines[line_index]..self.end_pos
1646             } else {
1647                 lines[line_index]..lines[line_index + 1]
1648             }
1649         })
1650     }
1651
1652     /// Returns whether or not the file contains the given `SourceMap` byte
1653     /// position. The position one past the end of the file is considered to be
1654     /// contained by the file. This implies that files for which `is_empty`
1655     /// returns true still contain one byte position according to this function.
1656     #[inline]
1657     pub fn contains(&self, byte_pos: BytePos) -> bool {
1658         byte_pos >= self.start_pos && byte_pos <= self.end_pos
1659     }
1660
1661     #[inline]
1662     pub fn is_empty(&self) -> bool {
1663         self.start_pos == self.end_pos
1664     }
1665
1666     /// Calculates the original byte position relative to the start of the file
1667     /// based on the given byte position.
1668     pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1669         // Diff before any records is 0. Otherwise use the previously recorded
1670         // diff as that applies to the following characters until a new diff
1671         // is recorded.
1672         let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1673             Ok(i) => self.normalized_pos[i].diff,
1674             Err(i) if i == 0 => 0,
1675             Err(i) => self.normalized_pos[i - 1].diff,
1676         };
1677
1678         BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1679     }
1680
1681     /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1682     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1683         // The number of extra bytes due to multibyte chars in the `SourceFile`.
1684         let mut total_extra_bytes = 0;
1685
1686         for mbc in self.multibyte_chars.iter() {
1687             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1688             if mbc.pos < bpos {
1689                 // Every character is at least one byte, so we only
1690                 // count the actual extra bytes.
1691                 total_extra_bytes += mbc.bytes as u32 - 1;
1692                 // We should never see a byte position in the middle of a
1693                 // character.
1694                 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1695             } else {
1696                 break;
1697             }
1698         }
1699
1700         assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1701         CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1702     }
1703
1704     /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1705     /// given `BytePos`.
1706     pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1707         let chpos = self.bytepos_to_file_charpos(pos);
1708         match self.lookup_line(pos) {
1709             Some(a) => {
1710                 let line = a + 1; // Line numbers start at 1
1711                 let linebpos = self.lines(|lines| lines[a]);
1712                 let linechpos = self.bytepos_to_file_charpos(linebpos);
1713                 let col = chpos - linechpos;
1714                 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1715                 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1716                 debug!("byte is on line: {}", line);
1717                 assert!(chpos >= linechpos);
1718                 (line, col)
1719             }
1720             None => (0, chpos),
1721         }
1722     }
1723
1724     /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1725     /// column offset when displayed, for a given `BytePos`.
1726     pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1727         let (line, col_or_chpos) = self.lookup_file_pos(pos);
1728         if line > 0 {
1729             let col = col_or_chpos;
1730             let linebpos = self.lines(|lines| lines[line - 1]);
1731             let col_display = {
1732                 let start_width_idx = self
1733                     .non_narrow_chars
1734                     .binary_search_by_key(&linebpos, |x| x.pos())
1735                     .unwrap_or_else(|x| x);
1736                 let end_width_idx = self
1737                     .non_narrow_chars
1738                     .binary_search_by_key(&pos, |x| x.pos())
1739                     .unwrap_or_else(|x| x);
1740                 let special_chars = end_width_idx - start_width_idx;
1741                 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1742                     .iter()
1743                     .map(|x| x.width())
1744                     .sum();
1745                 col.0 - special_chars + non_narrow
1746             };
1747             (line, col, col_display)
1748         } else {
1749             let chpos = col_or_chpos;
1750             let col_display = {
1751                 let end_width_idx = self
1752                     .non_narrow_chars
1753                     .binary_search_by_key(&pos, |x| x.pos())
1754                     .unwrap_or_else(|x| x);
1755                 let non_narrow: usize =
1756                     self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1757                 chpos.0 - end_width_idx + non_narrow
1758             };
1759             (0, chpos, col_display)
1760         }
1761     }
1762 }
1763
1764 /// Normalizes the source code and records the normalizations.
1765 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1766     let mut normalized_pos = vec![];
1767     remove_bom(src, &mut normalized_pos);
1768     normalize_newlines(src, &mut normalized_pos);
1769
1770     // Offset all the positions by start_pos to match the final file positions.
1771     for np in &mut normalized_pos {
1772         np.pos.0 += start_pos.0;
1773     }
1774
1775     normalized_pos
1776 }
1777
1778 /// Removes UTF-8 BOM, if any.
1779 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1780     if src.starts_with('\u{feff}') {
1781         src.drain(..3);
1782         normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1783     }
1784 }
1785
1786 /// Replaces `\r\n` with `\n` in-place in `src`.
1787 ///
1788 /// Returns error if there's a lone `\r` in the string.
1789 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1790     if !src.as_bytes().contains(&b'\r') {
1791         return;
1792     }
1793
1794     // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1795     // While we *can* call `as_mut_vec` and do surgery on the live string
1796     // directly, let's rather steal the contents of `src`. This makes the code
1797     // safe even if a panic occurs.
1798
1799     let mut buf = std::mem::replace(src, String::new()).into_bytes();
1800     let mut gap_len = 0;
1801     let mut tail = buf.as_mut_slice();
1802     let mut cursor = 0;
1803     let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1804     loop {
1805         let idx = match find_crlf(&tail[gap_len..]) {
1806             None => tail.len(),
1807             Some(idx) => idx + gap_len,
1808         };
1809         tail.copy_within(gap_len..idx, 0);
1810         tail = &mut tail[idx - gap_len..];
1811         if tail.len() == gap_len {
1812             break;
1813         }
1814         cursor += idx - gap_len;
1815         gap_len += 1;
1816         normalized_pos.push(NormalizedPos {
1817             pos: BytePos::from_usize(cursor + 1),
1818             diff: original_gap + gap_len as u32,
1819         });
1820     }
1821
1822     // Account for removed `\r`.
1823     // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1824     let new_len = buf.len() - gap_len;
1825     unsafe {
1826         buf.set_len(new_len);
1827         *src = String::from_utf8_unchecked(buf);
1828     }
1829
1830     fn find_crlf(src: &[u8]) -> Option<usize> {
1831         let mut search_idx = 0;
1832         while let Some(idx) = find_cr(&src[search_idx..]) {
1833             if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1834                 search_idx += idx + 1;
1835                 continue;
1836             }
1837             return Some(search_idx + idx);
1838         }
1839         None
1840     }
1841
1842     fn find_cr(src: &[u8]) -> Option<usize> {
1843         src.iter().position(|&b| b == b'\r')
1844     }
1845 }
1846
1847 // _____________________________________________________________________________
1848 // Pos, BytePos, CharPos
1849 //
1850
1851 pub trait Pos {
1852     fn from_usize(n: usize) -> Self;
1853     fn to_usize(&self) -> usize;
1854     fn from_u32(n: u32) -> Self;
1855     fn to_u32(&self) -> u32;
1856 }
1857
1858 macro_rules! impl_pos {
1859     (
1860         $(
1861             $(#[$attr:meta])*
1862             $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1863         )*
1864     ) => {
1865         $(
1866             $(#[$attr])*
1867             $vis struct $ident($inner_vis $inner_ty);
1868
1869             impl Pos for $ident {
1870                 #[inline(always)]
1871                 fn from_usize(n: usize) -> $ident {
1872                     $ident(n as $inner_ty)
1873                 }
1874
1875                 #[inline(always)]
1876                 fn to_usize(&self) -> usize {
1877                     self.0 as usize
1878                 }
1879
1880                 #[inline(always)]
1881                 fn from_u32(n: u32) -> $ident {
1882                     $ident(n as $inner_ty)
1883                 }
1884
1885                 #[inline(always)]
1886                 fn to_u32(&self) -> u32 {
1887                     self.0 as u32
1888                 }
1889             }
1890
1891             impl Add for $ident {
1892                 type Output = $ident;
1893
1894                 #[inline(always)]
1895                 fn add(self, rhs: $ident) -> $ident {
1896                     $ident(self.0 + rhs.0)
1897                 }
1898             }
1899
1900             impl Sub for $ident {
1901                 type Output = $ident;
1902
1903                 #[inline(always)]
1904                 fn sub(self, rhs: $ident) -> $ident {
1905                     $ident(self.0 - rhs.0)
1906                 }
1907             }
1908         )*
1909     };
1910 }
1911
1912 impl_pos! {
1913     /// A byte offset.
1914     ///
1915     /// Keep this small (currently 32-bits), as AST contains a lot of them.
1916     #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1917     pub struct BytePos(pub u32);
1918
1919     /// A character offset.
1920     ///
1921     /// Because of multibyte UTF-8 characters, a byte offset
1922     /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`]
1923     /// values to `CharPos` values as necessary.
1924     #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1925     pub struct CharPos(pub usize);
1926 }
1927
1928 impl<S: Encoder> Encodable<S> for BytePos {
1929     fn encode(&self, s: &mut S) {
1930         s.emit_u32(self.0);
1931     }
1932 }
1933
1934 impl<D: Decoder> Decodable<D> for BytePos {
1935     fn decode(d: &mut D) -> BytePos {
1936         BytePos(d.read_u32())
1937     }
1938 }
1939
1940 // _____________________________________________________________________________
1941 // Loc, SourceFileAndLine, SourceFileAndBytePos
1942 //
1943
1944 /// A source code location used for error reporting.
1945 #[derive(Debug, Clone)]
1946 pub struct Loc {
1947     /// Information about the original source.
1948     pub file: Lrc<SourceFile>,
1949     /// The (1-based) line number.
1950     pub line: usize,
1951     /// The (0-based) column offset.
1952     pub col: CharPos,
1953     /// The (0-based) column offset when displayed.
1954     pub col_display: usize,
1955 }
1956
1957 // Used to be structural records.
1958 #[derive(Debug)]
1959 pub struct SourceFileAndLine {
1960     pub sf: Lrc<SourceFile>,
1961     /// Index of line, starting from 0.
1962     pub line: usize,
1963 }
1964 #[derive(Debug)]
1965 pub struct SourceFileAndBytePos {
1966     pub sf: Lrc<SourceFile>,
1967     pub pos: BytePos,
1968 }
1969
1970 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1971 pub struct LineInfo {
1972     /// Index of line, starting from 0.
1973     pub line_index: usize,
1974
1975     /// Column in line where span begins, starting from 0.
1976     pub start_col: CharPos,
1977
1978     /// Column in line where span ends, starting from 0, exclusive.
1979     pub end_col: CharPos,
1980 }
1981
1982 pub struct FileLines {
1983     pub file: Lrc<SourceFile>,
1984     pub lines: Vec<LineInfo>,
1985 }
1986
1987 pub static SPAN_TRACK: AtomicRef<fn(LocalDefId)> = AtomicRef::new(&((|_| {}) as fn(_)));
1988
1989 // _____________________________________________________________________________
1990 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1991 //
1992
1993 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1994
1995 #[derive(Clone, PartialEq, Eq, Debug)]
1996 pub enum SpanLinesError {
1997     DistinctSources(DistinctSources),
1998 }
1999
2000 #[derive(Clone, PartialEq, Eq, Debug)]
2001 pub enum SpanSnippetError {
2002     IllFormedSpan(Span),
2003     DistinctSources(DistinctSources),
2004     MalformedForSourcemap(MalformedSourceMapPositions),
2005     SourceNotAvailable { filename: FileName },
2006 }
2007
2008 #[derive(Clone, PartialEq, Eq, Debug)]
2009 pub struct DistinctSources {
2010     pub begin: (FileName, BytePos),
2011     pub end: (FileName, BytePos),
2012 }
2013
2014 #[derive(Clone, PartialEq, Eq, Debug)]
2015 pub struct MalformedSourceMapPositions {
2016     pub name: FileName,
2017     pub source_len: usize,
2018     pub begin_pos: BytePos,
2019     pub end_pos: BytePos,
2020 }
2021
2022 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
2023 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2024 pub struct InnerSpan {
2025     pub start: usize,
2026     pub end: usize,
2027 }
2028
2029 impl InnerSpan {
2030     pub fn new(start: usize, end: usize) -> InnerSpan {
2031         InnerSpan { start, end }
2032     }
2033 }
2034
2035 /// Requirements for a `StableHashingContext` to be used in this crate.
2036 ///
2037 /// This is a hack to allow using the [`HashStable_Generic`] derive macro
2038 /// instead of implementing everything in rustc_middle.
2039 pub trait HashStableContext {
2040     fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
2041     fn hash_spans(&self) -> bool;
2042     /// Accesses `sess.opts.unstable_opts.incremental_ignore_spans` since
2043     /// we don't have easy access to a `Session`
2044     fn unstable_opts_incremental_ignore_spans(&self) -> bool;
2045     fn def_span(&self, def_id: LocalDefId) -> Span;
2046     fn span_data_to_lines_and_cols(
2047         &mut self,
2048         span: &SpanData,
2049     ) -> Option<(Lrc<SourceFile>, usize, BytePos, usize, BytePos)>;
2050     fn hashing_controls(&self) -> HashingControls;
2051 }
2052
2053 impl<CTX> HashStable<CTX> for Span
2054 where
2055     CTX: HashStableContext,
2056 {
2057     /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
2058     /// fields (that would be similar to hashing pointers, since those are just
2059     /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
2060     /// triple, which stays the same even if the containing `SourceFile` has moved
2061     /// within the `SourceMap`.
2062     ///
2063     /// Also note that we are hashing byte offsets for the column, not unicode
2064     /// codepoint offsets. For the purpose of the hash that's sufficient.
2065     /// Also, hashing filenames is expensive so we avoid doing it twice when the
2066     /// span starts and ends in the same file, which is almost always the case.
2067     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
2068         const TAG_VALID_SPAN: u8 = 0;
2069         const TAG_INVALID_SPAN: u8 = 1;
2070         const TAG_RELATIVE_SPAN: u8 = 2;
2071
2072         if !ctx.hash_spans() {
2073             return;
2074         }
2075
2076         let span = self.data_untracked();
2077         span.ctxt.hash_stable(ctx, hasher);
2078         span.parent.hash_stable(ctx, hasher);
2079
2080         if span.is_dummy() {
2081             Hash::hash(&TAG_INVALID_SPAN, hasher);
2082             return;
2083         }
2084
2085         if let Some(parent) = span.parent {
2086             let def_span = ctx.def_span(parent).data_untracked();
2087             if def_span.contains(span) {
2088                 // This span is enclosed in a definition: only hash the relative position.
2089                 Hash::hash(&TAG_RELATIVE_SPAN, hasher);
2090                 (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher);
2091                 (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher);
2092                 return;
2093             }
2094         }
2095
2096         // If this is not an empty or invalid span, we want to hash the last
2097         // position that belongs to it, as opposed to hashing the first
2098         // position past it.
2099         let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span) else {
2100             Hash::hash(&TAG_INVALID_SPAN, hasher);
2101             return;
2102         };
2103
2104         Hash::hash(&TAG_VALID_SPAN, hasher);
2105         // We truncate the stable ID hash and line and column numbers. The chances
2106         // of causing a collision this way should be minimal.
2107         Hash::hash(&(file.name_hash as u64), hasher);
2108
2109         // Hash both the length and the end location (line/column) of a span. If we
2110         // hash only the length, for example, then two otherwise equal spans with
2111         // different end locations will have the same hash. This can cause a problem
2112         // during incremental compilation wherein a previous result for a query that
2113         // depends on the end location of a span will be incorrectly reused when the
2114         // end location of the span it depends on has changed (see issue #74890). A
2115         // similar analysis applies if some query depends specifically on the length
2116         // of the span, but we only hash the end location. So hash both.
2117
2118         let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
2119         let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
2120         let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
2121         let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
2122         let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
2123         let len = (span.hi - span.lo).0;
2124         Hash::hash(&col_line, hasher);
2125         Hash::hash(&len, hasher);
2126     }
2127 }