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