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