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