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