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