]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/lib.rs
Auto merge of #85832 - kornelski:raw_arg, r=yaahc
[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!(
524             self.ctxt().outer_expn_data().kind,
525             ExpnKind::Macro { kind: MacroKind::Derive, name: _, proc_macro: _ }
526         )
527     }
528
529     #[inline]
530     pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
531         Span::new(lo, hi, SyntaxContext::root())
532     }
533
534     /// Returns a new span representing an empty span at the beginning of this span.
535     #[inline]
536     pub fn shrink_to_lo(self) -> Span {
537         let span = self.data();
538         span.with_hi(span.lo)
539     }
540     /// Returns a new span representing an empty span at the end of this span.
541     #[inline]
542     pub fn shrink_to_hi(self) -> Span {
543         let span = self.data();
544         span.with_lo(span.hi)
545     }
546
547     #[inline]
548     /// Returns `true` if `hi == lo`.
549     pub fn is_empty(&self) -> bool {
550         let span = self.data();
551         span.hi == span.lo
552     }
553
554     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
555     pub fn substitute_dummy(self, other: Span) -> Span {
556         if self.is_dummy() { other } else { self }
557     }
558
559     /// Returns `true` if `self` fully encloses `other`.
560     pub fn contains(self, other: Span) -> bool {
561         let span = self.data();
562         let other = other.data();
563         span.lo <= other.lo && other.hi <= span.hi
564     }
565
566     /// Returns `true` if `self` touches `other`.
567     pub fn overlaps(self, other: Span) -> bool {
568         let span = self.data();
569         let other = other.data();
570         span.lo < other.hi && other.lo < span.hi
571     }
572
573     /// Returns `true` if the spans are equal with regards to the source text.
574     ///
575     /// Use this instead of `==` when either span could be generated code,
576     /// and you only care that they point to the same bytes of source text.
577     pub fn source_equal(&self, other: &Span) -> bool {
578         let span = self.data();
579         let other = other.data();
580         span.lo == other.lo && span.hi == other.hi
581     }
582
583     /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
584     pub fn trim_start(self, other: Span) -> Option<Span> {
585         let span = self.data();
586         let other = other.data();
587         if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
588     }
589
590     /// Returns the source span -- this is either the supplied span, or the span for
591     /// the macro callsite that expanded to it.
592     pub fn source_callsite(self) -> Span {
593         let expn_data = self.ctxt().outer_expn_data();
594         if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
595     }
596
597     /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
598     /// if any.
599     pub fn parent(self) -> Option<Span> {
600         let expn_data = self.ctxt().outer_expn_data();
601         if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
602     }
603
604     /// Edition of the crate from which this span came.
605     pub fn edition(self) -> edition::Edition {
606         self.ctxt().edition()
607     }
608
609     #[inline]
610     pub fn rust_2015(&self) -> bool {
611         self.edition() == edition::Edition::Edition2015
612     }
613
614     #[inline]
615     pub fn rust_2018(&self) -> bool {
616         self.edition() >= edition::Edition::Edition2018
617     }
618
619     #[inline]
620     pub fn rust_2021(&self) -> bool {
621         self.edition() >= edition::Edition::Edition2021
622     }
623
624     /// Returns the source callee.
625     ///
626     /// Returns `None` if the supplied span has no expansion trace,
627     /// else returns the `ExpnData` for the macro definition
628     /// corresponding to the source callsite.
629     pub fn source_callee(self) -> Option<ExpnData> {
630         fn source_callee(expn_data: ExpnData) -> ExpnData {
631             let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
632             if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
633         }
634         let expn_data = self.ctxt().outer_expn_data();
635         if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
636     }
637
638     /// Checks if a span is "internal" to a macro in which `#[unstable]`
639     /// items can be used (that is, a macro marked with
640     /// `#[allow_internal_unstable]`).
641     pub fn allows_unstable(&self, feature: Symbol) -> bool {
642         self.ctxt()
643             .outer_expn_data()
644             .allow_internal_unstable
645             .map_or(false, |features| features.iter().any(|&f| f == feature))
646     }
647
648     /// Checks if this span arises from a compiler desugaring of kind `kind`.
649     pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
650         match self.ctxt().outer_expn_data().kind {
651             ExpnKind::Desugaring(k) => k == kind,
652             _ => false,
653         }
654     }
655
656     /// Returns the compiler desugaring that created this span, or `None`
657     /// if this span is not from a desugaring.
658     pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
659         match self.ctxt().outer_expn_data().kind {
660             ExpnKind::Desugaring(k) => Some(k),
661             _ => None,
662         }
663     }
664
665     /// Checks if a span is "internal" to a macro in which `unsafe`
666     /// can be used without triggering the `unsafe_code` lint.
667     //  (that is, a macro marked with `#[allow_internal_unsafe]`).
668     pub fn allows_unsafe(&self) -> bool {
669         self.ctxt().outer_expn_data().allow_internal_unsafe
670     }
671
672     pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
673         let mut prev_span = DUMMY_SP;
674         std::iter::from_fn(move || {
675             loop {
676                 let expn_data = self.ctxt().outer_expn_data();
677                 if expn_data.is_root() {
678                     return None;
679                 }
680
681                 let is_recursive = expn_data.call_site.source_equal(&prev_span);
682
683                 prev_span = self;
684                 self = expn_data.call_site;
685
686                 // Don't print recursive invocations.
687                 if !is_recursive {
688                     return Some(expn_data);
689                 }
690             }
691         })
692     }
693
694     /// Returns a `Span` that would enclose both `self` and `end`.
695     ///
696     /// ```text
697     ///     ____             ___
698     ///     self lorem ipsum end
699     ///     ^^^^^^^^^^^^^^^^^^^^
700     /// ```
701     pub fn to(self, end: Span) -> Span {
702         let span_data = self.data();
703         let end_data = end.data();
704         // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
705         // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
706         // have an incomplete span than a completely nonsensical one.
707         if span_data.ctxt != end_data.ctxt {
708             if span_data.ctxt == SyntaxContext::root() {
709                 return end;
710             } else if end_data.ctxt == SyntaxContext::root() {
711                 return self;
712             }
713             // Both spans fall within a macro.
714             // FIXME(estebank): check if it is the *same* macro.
715         }
716         Span::new(
717             cmp::min(span_data.lo, end_data.lo),
718             cmp::max(span_data.hi, end_data.hi),
719             if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
720         )
721     }
722
723     /// Returns a `Span` between the end of `self` to the beginning of `end`.
724     ///
725     /// ```text
726     ///     ____             ___
727     ///     self lorem ipsum end
728     ///         ^^^^^^^^^^^^^
729     /// ```
730     pub fn between(self, end: Span) -> Span {
731         let span = self.data();
732         let end = end.data();
733         Span::new(
734             span.hi,
735             end.lo,
736             if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
737         )
738     }
739
740     /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
741     ///
742     /// ```text
743     ///     ____             ___
744     ///     self lorem ipsum end
745     ///     ^^^^^^^^^^^^^^^^^
746     /// ```
747     pub fn until(self, end: Span) -> Span {
748         let span = self.data();
749         let end = end.data();
750         Span::new(
751             span.lo,
752             end.lo,
753             if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
754         )
755     }
756
757     pub fn from_inner(self, inner: InnerSpan) -> Span {
758         let span = self.data();
759         Span::new(
760             span.lo + BytePos::from_usize(inner.start),
761             span.lo + BytePos::from_usize(inner.end),
762             span.ctxt,
763         )
764     }
765
766     /// Equivalent of `Span::def_site` from the proc macro API,
767     /// except that the location is taken from the `self` span.
768     pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
769         self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
770     }
771
772     /// Equivalent of `Span::call_site` from the proc macro API,
773     /// except that the location is taken from the `self` span.
774     pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
775         self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
776     }
777
778     /// Equivalent of `Span::mixed_site` from the proc macro API,
779     /// except that the location is taken from the `self` span.
780     pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
781         self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
782     }
783
784     /// Produces a span with the same location as `self` and context produced by a macro with the
785     /// given ID and transparency, assuming that macro was defined directly and not produced by
786     /// some other macro (which is the case for built-in and procedural macros).
787     pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
788         self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
789     }
790
791     #[inline]
792     pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
793         let span = self.data();
794         span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
795     }
796
797     #[inline]
798     pub fn remove_mark(&mut self) -> ExpnId {
799         let mut span = self.data();
800         let mark = span.ctxt.remove_mark();
801         *self = Span::new(span.lo, span.hi, span.ctxt);
802         mark
803     }
804
805     #[inline]
806     pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
807         let mut span = self.data();
808         let mark = span.ctxt.adjust(expn_id);
809         *self = Span::new(span.lo, span.hi, span.ctxt);
810         mark
811     }
812
813     #[inline]
814     pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
815         let mut span = self.data();
816         let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
817         *self = Span::new(span.lo, span.hi, span.ctxt);
818         mark
819     }
820
821     #[inline]
822     pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
823         let mut span = self.data();
824         let mark = span.ctxt.glob_adjust(expn_id, glob_span);
825         *self = Span::new(span.lo, span.hi, span.ctxt);
826         mark
827     }
828
829     #[inline]
830     pub fn reverse_glob_adjust(
831         &mut self,
832         expn_id: ExpnId,
833         glob_span: Span,
834     ) -> Option<Option<ExpnId>> {
835         let mut span = self.data();
836         let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
837         *self = Span::new(span.lo, span.hi, span.ctxt);
838         mark
839     }
840
841     #[inline]
842     pub fn normalize_to_macros_2_0(self) -> Span {
843         let span = self.data();
844         span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
845     }
846
847     #[inline]
848     pub fn normalize_to_macro_rules(self) -> Span {
849         let span = self.data();
850         span.with_ctxt(span.ctxt.normalize_to_macro_rules())
851     }
852 }
853
854 /// A span together with some additional data.
855 #[derive(Clone, Debug)]
856 pub struct SpanLabel {
857     /// The span we are going to include in the final snippet.
858     pub span: Span,
859
860     /// Is this a primary span? This is the "locus" of the message,
861     /// and is indicated with a `^^^^` underline, versus `----`.
862     pub is_primary: bool,
863
864     /// What label should we attach to this span (if any)?
865     pub label: Option<String>,
866 }
867
868 impl Default for Span {
869     fn default() -> Self {
870         DUMMY_SP
871     }
872 }
873
874 impl<E: Encoder> Encodable<E> for Span {
875     default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
876         let span = self.data();
877         s.emit_struct(false, |s| {
878             s.emit_struct_field("lo", true, |s| span.lo.encode(s))?;
879             s.emit_struct_field("hi", false, |s| span.hi.encode(s))
880         })
881     }
882 }
883 impl<D: Decoder> Decodable<D> for Span {
884     default fn decode(s: &mut D) -> Result<Span, D::Error> {
885         s.read_struct(|d| {
886             let lo = d.read_struct_field("lo", Decodable::decode)?;
887             let hi = d.read_struct_field("hi", Decodable::decode)?;
888
889             Ok(Span::new(lo, hi, SyntaxContext::root()))
890         })
891     }
892 }
893
894 /// Calls the provided closure, using the provided `SourceMap` to format
895 /// any spans that are debug-printed during the closure's execution.
896 ///
897 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
898 /// (see `rustc_interface::callbacks::span_debug1`). However, some parts
899 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
900 /// a `TyCtxt` is available. In this case, we fall back to
901 /// the `SourceMap` provided to this function. If that is not available,
902 /// we fall back to printing the raw `Span` field values.
903 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
904     with_session_globals(|session_globals| {
905         *session_globals.source_map.borrow_mut() = Some(source_map);
906     });
907     struct ClearSourceMap;
908     impl Drop for ClearSourceMap {
909         fn drop(&mut self) {
910             with_session_globals(|session_globals| {
911                 session_globals.source_map.borrow_mut().take();
912             });
913         }
914     }
915
916     let _guard = ClearSourceMap;
917     f()
918 }
919
920 pub fn debug_with_source_map(
921     span: Span,
922     f: &mut fmt::Formatter<'_>,
923     source_map: &SourceMap,
924 ) -> fmt::Result {
925     write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(span), span.ctxt())
926 }
927
928 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
929     with_session_globals(|session_globals| {
930         if let Some(source_map) = &*session_globals.source_map.borrow() {
931             debug_with_source_map(span, f, source_map)
932         } else {
933             f.debug_struct("Span")
934                 .field("lo", &span.lo())
935                 .field("hi", &span.hi())
936                 .field("ctxt", &span.ctxt())
937                 .finish()
938         }
939     })
940 }
941
942 impl fmt::Debug for Span {
943     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
944         (*SPAN_DEBUG)(*self, f)
945     }
946 }
947
948 impl fmt::Debug for SpanData {
949     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
950         (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
951     }
952 }
953
954 impl MultiSpan {
955     #[inline]
956     pub fn new() -> MultiSpan {
957         MultiSpan { primary_spans: vec![], span_labels: vec![] }
958     }
959
960     pub fn from_span(primary_span: Span) -> MultiSpan {
961         MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
962     }
963
964     pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
965         vec.sort();
966         MultiSpan { primary_spans: vec, span_labels: vec![] }
967     }
968
969     pub fn push_span_label(&mut self, span: Span, label: String) {
970         self.span_labels.push((span, label));
971     }
972
973     /// Selects the first primary span (if any).
974     pub fn primary_span(&self) -> Option<Span> {
975         self.primary_spans.first().cloned()
976     }
977
978     /// Returns all primary spans.
979     pub fn primary_spans(&self) -> &[Span] {
980         &self.primary_spans
981     }
982
983     /// Returns `true` if any of the primary spans are displayable.
984     pub fn has_primary_spans(&self) -> bool {
985         self.primary_spans.iter().any(|sp| !sp.is_dummy())
986     }
987
988     /// Returns `true` if this contains only a dummy primary span with any hygienic context.
989     pub fn is_dummy(&self) -> bool {
990         let mut is_dummy = true;
991         for span in &self.primary_spans {
992             if !span.is_dummy() {
993                 is_dummy = false;
994             }
995         }
996         is_dummy
997     }
998
999     /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
1000     /// display well (like std macros). Returns whether replacements occurred.
1001     pub fn replace(&mut self, before: Span, after: Span) -> bool {
1002         let mut replacements_occurred = false;
1003         for primary_span in &mut self.primary_spans {
1004             if *primary_span == before {
1005                 *primary_span = after;
1006                 replacements_occurred = true;
1007             }
1008         }
1009         for span_label in &mut self.span_labels {
1010             if span_label.0 == before {
1011                 span_label.0 = after;
1012                 replacements_occurred = true;
1013             }
1014         }
1015         replacements_occurred
1016     }
1017
1018     /// Returns the strings to highlight. We always ensure that there
1019     /// is an entry for each of the primary spans -- for each primary
1020     /// span `P`, if there is at least one label with span `P`, we return
1021     /// those labels (marked as primary). But otherwise we return
1022     /// `SpanLabel` instances with empty labels.
1023     pub fn span_labels(&self) -> Vec<SpanLabel> {
1024         let is_primary = |span| self.primary_spans.contains(&span);
1025
1026         let mut span_labels = self
1027             .span_labels
1028             .iter()
1029             .map(|&(span, ref label)| SpanLabel {
1030                 span,
1031                 is_primary: is_primary(span),
1032                 label: Some(label.clone()),
1033             })
1034             .collect::<Vec<_>>();
1035
1036         for &span in &self.primary_spans {
1037             if !span_labels.iter().any(|sl| sl.span == span) {
1038                 span_labels.push(SpanLabel { span, is_primary: true, label: None });
1039             }
1040         }
1041
1042         span_labels
1043     }
1044
1045     /// Returns `true` if any of the span labels is displayable.
1046     pub fn has_span_labels(&self) -> bool {
1047         self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
1048     }
1049 }
1050
1051 impl From<Span> for MultiSpan {
1052     fn from(span: Span) -> MultiSpan {
1053         MultiSpan::from_span(span)
1054     }
1055 }
1056
1057 impl From<Vec<Span>> for MultiSpan {
1058     fn from(spans: Vec<Span>) -> MultiSpan {
1059         MultiSpan::from_spans(spans)
1060     }
1061 }
1062
1063 /// Identifies an offset of a multi-byte character in a `SourceFile`.
1064 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1065 pub struct MultiByteChar {
1066     /// The absolute offset of the character in the `SourceMap`.
1067     pub pos: BytePos,
1068     /// The number of bytes, `>= 2`.
1069     pub bytes: u8,
1070 }
1071
1072 /// Identifies an offset of a non-narrow character in a `SourceFile`.
1073 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1074 pub enum NonNarrowChar {
1075     /// Represents a zero-width character.
1076     ZeroWidth(BytePos),
1077     /// Represents a wide (full-width) character.
1078     Wide(BytePos),
1079     /// Represents a tab character, represented visually with a width of 4 characters.
1080     Tab(BytePos),
1081 }
1082
1083 impl NonNarrowChar {
1084     fn new(pos: BytePos, width: usize) -> Self {
1085         match width {
1086             0 => NonNarrowChar::ZeroWidth(pos),
1087             2 => NonNarrowChar::Wide(pos),
1088             4 => NonNarrowChar::Tab(pos),
1089             _ => panic!("width {} given for non-narrow character", width),
1090         }
1091     }
1092
1093     /// Returns the absolute offset of the character in the `SourceMap`.
1094     pub fn pos(&self) -> BytePos {
1095         match *self {
1096             NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
1097         }
1098     }
1099
1100     /// Returns the width of the character, 0 (zero-width) or 2 (wide).
1101     pub fn width(&self) -> usize {
1102         match *self {
1103             NonNarrowChar::ZeroWidth(_) => 0,
1104             NonNarrowChar::Wide(_) => 2,
1105             NonNarrowChar::Tab(_) => 4,
1106         }
1107     }
1108 }
1109
1110 impl Add<BytePos> for NonNarrowChar {
1111     type Output = Self;
1112
1113     fn add(self, rhs: BytePos) -> Self {
1114         match self {
1115             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
1116             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
1117             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
1118         }
1119     }
1120 }
1121
1122 impl Sub<BytePos> for NonNarrowChar {
1123     type Output = Self;
1124
1125     fn sub(self, rhs: BytePos) -> Self {
1126         match self {
1127             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
1128             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
1129             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
1130         }
1131     }
1132 }
1133
1134 /// Identifies an offset of a character that was normalized away from `SourceFile`.
1135 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1136 pub struct NormalizedPos {
1137     /// The absolute offset of the character in the `SourceMap`.
1138     pub pos: BytePos,
1139     /// The difference between original and normalized string at position.
1140     pub diff: u32,
1141 }
1142
1143 #[derive(PartialEq, Eq, Clone, Debug)]
1144 pub enum ExternalSource {
1145     /// No external source has to be loaded, since the `SourceFile` represents a local crate.
1146     Unneeded,
1147     Foreign {
1148         kind: ExternalSourceKind,
1149         /// This SourceFile's byte-offset within the source_map of its original crate.
1150         original_start_pos: BytePos,
1151         /// The end of this SourceFile within the source_map of its original crate.
1152         original_end_pos: BytePos,
1153     },
1154 }
1155
1156 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1157 #[derive(PartialEq, Eq, Clone, Debug)]
1158 pub enum ExternalSourceKind {
1159     /// The external source has been loaded already.
1160     Present(Lrc<String>),
1161     /// No attempt has been made to load the external source.
1162     AbsentOk,
1163     /// A failed attempt has been made to load the external source.
1164     AbsentErr,
1165     Unneeded,
1166 }
1167
1168 impl ExternalSource {
1169     pub fn get_source(&self) -> Option<&Lrc<String>> {
1170         match self {
1171             ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1172             _ => None,
1173         }
1174     }
1175 }
1176
1177 #[derive(Debug)]
1178 pub struct OffsetOverflowError;
1179
1180 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1181 pub enum SourceFileHashAlgorithm {
1182     Md5,
1183     Sha1,
1184     Sha256,
1185 }
1186
1187 impl FromStr for SourceFileHashAlgorithm {
1188     type Err = ();
1189
1190     fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1191         match s {
1192             "md5" => Ok(SourceFileHashAlgorithm::Md5),
1193             "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1194             "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1195             _ => Err(()),
1196         }
1197     }
1198 }
1199
1200 rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm);
1201
1202 /// The hash of the on-disk source file used for debug info.
1203 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1204 #[derive(HashStable_Generic, Encodable, Decodable)]
1205 pub struct SourceFileHash {
1206     pub kind: SourceFileHashAlgorithm,
1207     value: [u8; 32],
1208 }
1209
1210 impl SourceFileHash {
1211     pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1212         let mut hash = SourceFileHash { kind, value: Default::default() };
1213         let len = hash.hash_len();
1214         let value = &mut hash.value[..len];
1215         let data = src.as_bytes();
1216         match kind {
1217             SourceFileHashAlgorithm::Md5 => {
1218                 value.copy_from_slice(&Md5::digest(data));
1219             }
1220             SourceFileHashAlgorithm::Sha1 => {
1221                 value.copy_from_slice(&Sha1::digest(data));
1222             }
1223             SourceFileHashAlgorithm::Sha256 => {
1224                 value.copy_from_slice(&Sha256::digest(data));
1225             }
1226         }
1227         hash
1228     }
1229
1230     /// Check if the stored hash matches the hash of the string.
1231     pub fn matches(&self, src: &str) -> bool {
1232         Self::new(self.kind, src) == *self
1233     }
1234
1235     /// The bytes of the hash.
1236     pub fn hash_bytes(&self) -> &[u8] {
1237         let len = self.hash_len();
1238         &self.value[..len]
1239     }
1240
1241     fn hash_len(&self) -> usize {
1242         match self.kind {
1243             SourceFileHashAlgorithm::Md5 => 16,
1244             SourceFileHashAlgorithm::Sha1 => 20,
1245             SourceFileHashAlgorithm::Sha256 => 32,
1246         }
1247     }
1248 }
1249
1250 /// A single source in the [`SourceMap`].
1251 #[derive(Clone)]
1252 pub struct SourceFile {
1253     /// The name of the file that the source came from. Source that doesn't
1254     /// originate from files has names between angle brackets by convention
1255     /// (e.g., `<anon>`).
1256     pub name: FileName,
1257     /// The complete source code.
1258     pub src: Option<Lrc<String>>,
1259     /// The source code's hash.
1260     pub src_hash: SourceFileHash,
1261     /// The external source code (used for external crates, which will have a `None`
1262     /// value as `self.src`.
1263     pub external_src: Lock<ExternalSource>,
1264     /// The start position of this source in the `SourceMap`.
1265     pub start_pos: BytePos,
1266     /// The end position of this source in the `SourceMap`.
1267     pub end_pos: BytePos,
1268     /// Locations of lines beginnings in the source code.
1269     pub lines: Vec<BytePos>,
1270     /// Locations of multi-byte characters in the source code.
1271     pub multibyte_chars: Vec<MultiByteChar>,
1272     /// Width of characters that are not narrow in the source code.
1273     pub non_narrow_chars: Vec<NonNarrowChar>,
1274     /// Locations of characters removed during normalization.
1275     pub normalized_pos: Vec<NormalizedPos>,
1276     /// A hash of the filename, used for speeding up hashing in incremental compilation.
1277     pub name_hash: u128,
1278     /// Indicates which crate this `SourceFile` was imported from.
1279     pub cnum: CrateNum,
1280 }
1281
1282 impl<S: Encoder> Encodable<S> for SourceFile {
1283     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1284         s.emit_struct(false, |s| {
1285             s.emit_struct_field("name", true, |s| self.name.encode(s))?;
1286             s.emit_struct_field("src_hash", false, |s| self.src_hash.encode(s))?;
1287             s.emit_struct_field("start_pos", false, |s| self.start_pos.encode(s))?;
1288             s.emit_struct_field("end_pos", false, |s| self.end_pos.encode(s))?;
1289             s.emit_struct_field("lines", false, |s| {
1290                 let lines = &self.lines[..];
1291                 // Store the length.
1292                 s.emit_u32(lines.len() as u32)?;
1293
1294                 if !lines.is_empty() {
1295                     // In order to preserve some space, we exploit the fact that
1296                     // the lines list is sorted and individual lines are
1297                     // probably not that long. Because of that we can store lines
1298                     // as a difference list, using as little space as possible
1299                     // for the differences.
1300                     let max_line_length = if lines.len() == 1 {
1301                         0
1302                     } else {
1303                         lines
1304                             .array_windows()
1305                             .map(|&[fst, snd]| snd - fst)
1306                             .map(|bp| bp.to_usize())
1307                             .max()
1308                             .unwrap()
1309                     };
1310
1311                     let bytes_per_diff: u8 = match max_line_length {
1312                         0..=0xFF => 1,
1313                         0x100..=0xFFFF => 2,
1314                         _ => 4,
1315                     };
1316
1317                     // Encode the number of bytes used per diff.
1318                     bytes_per_diff.encode(s)?;
1319
1320                     // Encode the first element.
1321                     lines[0].encode(s)?;
1322
1323                     let diff_iter = lines[..].array_windows().map(|&[fst, snd]| snd - fst);
1324
1325                     match bytes_per_diff {
1326                         1 => {
1327                             for diff in diff_iter {
1328                                 (diff.0 as u8).encode(s)?
1329                             }
1330                         }
1331                         2 => {
1332                             for diff in diff_iter {
1333                                 (diff.0 as u16).encode(s)?
1334                             }
1335                         }
1336                         4 => {
1337                             for diff in diff_iter {
1338                                 diff.0.encode(s)?
1339                             }
1340                         }
1341                         _ => unreachable!(),
1342                     }
1343                 }
1344
1345                 Ok(())
1346             })?;
1347             s.emit_struct_field("multibyte_chars", false, |s| self.multibyte_chars.encode(s))?;
1348             s.emit_struct_field("non_narrow_chars", false, |s| self.non_narrow_chars.encode(s))?;
1349             s.emit_struct_field("name_hash", false, |s| self.name_hash.encode(s))?;
1350             s.emit_struct_field("normalized_pos", false, |s| self.normalized_pos.encode(s))?;
1351             s.emit_struct_field("cnum", false, |s| self.cnum.encode(s))
1352         })
1353     }
1354 }
1355
1356 impl<D: Decoder> Decodable<D> for SourceFile {
1357     fn decode(d: &mut D) -> Result<SourceFile, D::Error> {
1358         d.read_struct(|d| {
1359             let name: FileName = d.read_struct_field("name", |d| Decodable::decode(d))?;
1360             let src_hash: SourceFileHash =
1361                 d.read_struct_field("src_hash", |d| Decodable::decode(d))?;
1362             let start_pos: BytePos = d.read_struct_field("start_pos", |d| Decodable::decode(d))?;
1363             let end_pos: BytePos = d.read_struct_field("end_pos", |d| Decodable::decode(d))?;
1364             let lines: Vec<BytePos> = d.read_struct_field("lines", |d| {
1365                 let num_lines: u32 = Decodable::decode(d)?;
1366                 let mut lines = Vec::with_capacity(num_lines as usize);
1367
1368                 if num_lines > 0 {
1369                     // Read the number of bytes used per diff.
1370                     let bytes_per_diff: u8 = Decodable::decode(d)?;
1371
1372                     // Read the first element.
1373                     let mut line_start: BytePos = Decodable::decode(d)?;
1374                     lines.push(line_start);
1375
1376                     for _ in 1..num_lines {
1377                         let diff = match bytes_per_diff {
1378                             1 => d.read_u8()? as u32,
1379                             2 => d.read_u16()? as u32,
1380                             4 => d.read_u32()?,
1381                             _ => unreachable!(),
1382                         };
1383
1384                         line_start = line_start + BytePos(diff);
1385
1386                         lines.push(line_start);
1387                     }
1388                 }
1389
1390                 Ok(lines)
1391             })?;
1392             let multibyte_chars: Vec<MultiByteChar> =
1393                 d.read_struct_field("multibyte_chars", |d| Decodable::decode(d))?;
1394             let non_narrow_chars: Vec<NonNarrowChar> =
1395                 d.read_struct_field("non_narrow_chars", |d| Decodable::decode(d))?;
1396             let name_hash: u128 = d.read_struct_field("name_hash", |d| Decodable::decode(d))?;
1397             let normalized_pos: Vec<NormalizedPos> =
1398                 d.read_struct_field("normalized_pos", |d| Decodable::decode(d))?;
1399             let cnum: CrateNum = d.read_struct_field("cnum", |d| Decodable::decode(d))?;
1400             Ok(SourceFile {
1401                 name,
1402                 start_pos,
1403                 end_pos,
1404                 src: None,
1405                 src_hash,
1406                 // Unused - the metadata decoder will construct
1407                 // a new SourceFile, filling in `external_src` properly
1408                 external_src: Lock::new(ExternalSource::Unneeded),
1409                 lines,
1410                 multibyte_chars,
1411                 non_narrow_chars,
1412                 normalized_pos,
1413                 name_hash,
1414                 cnum,
1415             })
1416         })
1417     }
1418 }
1419
1420 impl fmt::Debug for SourceFile {
1421     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1422         write!(fmt, "SourceFile({:?})", self.name)
1423     }
1424 }
1425
1426 impl SourceFile {
1427     pub fn new(
1428         name: FileName,
1429         mut src: String,
1430         start_pos: BytePos,
1431         hash_kind: SourceFileHashAlgorithm,
1432     ) -> Self {
1433         // Compute the file hash before any normalization.
1434         let src_hash = SourceFileHash::new(hash_kind, &src);
1435         let normalized_pos = normalize_src(&mut src, start_pos);
1436
1437         let name_hash = {
1438             let mut hasher: StableHasher = StableHasher::new();
1439             name.hash(&mut hasher);
1440             hasher.finish::<u128>()
1441         };
1442         let end_pos = start_pos.to_usize() + src.len();
1443         assert!(end_pos <= u32::MAX as usize);
1444
1445         let (lines, multibyte_chars, non_narrow_chars) =
1446             analyze_source_file::analyze_source_file(&src[..], start_pos);
1447
1448         SourceFile {
1449             name,
1450             src: Some(Lrc::new(src)),
1451             src_hash,
1452             external_src: Lock::new(ExternalSource::Unneeded),
1453             start_pos,
1454             end_pos: Pos::from_usize(end_pos),
1455             lines,
1456             multibyte_chars,
1457             non_narrow_chars,
1458             normalized_pos,
1459             name_hash,
1460             cnum: LOCAL_CRATE,
1461         }
1462     }
1463
1464     /// Returns the `BytePos` of the beginning of the current line.
1465     pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1466         let line_index = self.lookup_line(pos).unwrap();
1467         self.lines[line_index]
1468     }
1469
1470     /// Add externally loaded source.
1471     /// If the hash of the input doesn't match or no input is supplied via None,
1472     /// it is interpreted as an error and the corresponding enum variant is set.
1473     /// The return value signifies whether some kind of source is present.
1474     pub fn add_external_src<F>(&self, get_src: F) -> bool
1475     where
1476         F: FnOnce() -> Option<String>,
1477     {
1478         if matches!(
1479             *self.external_src.borrow(),
1480             ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1481         ) {
1482             let src = get_src();
1483             let mut external_src = self.external_src.borrow_mut();
1484             // Check that no-one else have provided the source while we were getting it
1485             if let ExternalSource::Foreign {
1486                 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1487             } = &mut *external_src
1488             {
1489                 if let Some(mut src) = src {
1490                     // The src_hash needs to be computed on the pre-normalized src.
1491                     if self.src_hash.matches(&src) {
1492                         normalize_src(&mut src, BytePos::from_usize(0));
1493                         *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1494                         return true;
1495                     }
1496                 } else {
1497                     *src_kind = ExternalSourceKind::AbsentErr;
1498                 }
1499
1500                 false
1501             } else {
1502                 self.src.is_some() || external_src.get_source().is_some()
1503             }
1504         } else {
1505             self.src.is_some() || self.external_src.borrow().get_source().is_some()
1506         }
1507     }
1508
1509     /// Gets a line from the list of pre-computed line-beginnings.
1510     /// The line number here is 0-based.
1511     pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1512         fn get_until_newline(src: &str, begin: usize) -> &str {
1513             // We can't use `lines.get(line_number+1)` because we might
1514             // be parsing when we call this function and thus the current
1515             // line is the last one we have line info for.
1516             let slice = &src[begin..];
1517             match slice.find('\n') {
1518                 Some(e) => &slice[..e],
1519                 None => slice,
1520             }
1521         }
1522
1523         let begin = {
1524             let line = self.lines.get(line_number)?;
1525             let begin: BytePos = *line - self.start_pos;
1526             begin.to_usize()
1527         };
1528
1529         if let Some(ref src) = self.src {
1530             Some(Cow::from(get_until_newline(src, begin)))
1531         } else if let Some(src) = self.external_src.borrow().get_source() {
1532             Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1533         } else {
1534             None
1535         }
1536     }
1537
1538     pub fn is_real_file(&self) -> bool {
1539         self.name.is_real()
1540     }
1541
1542     pub fn is_imported(&self) -> bool {
1543         self.src.is_none()
1544     }
1545
1546     pub fn count_lines(&self) -> usize {
1547         self.lines.len()
1548     }
1549
1550     /// Finds the line containing the given position. The return value is the
1551     /// index into the `lines` array of this `SourceFile`, not the 1-based line
1552     /// number. If the source_file is empty or the position is located before the
1553     /// first line, `None` is returned.
1554     pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1555         match self.lines.binary_search(&pos) {
1556             Ok(idx) => Some(idx),
1557             Err(0) => None,
1558             Err(idx) => Some(idx - 1),
1559         }
1560     }
1561
1562     pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
1563         if self.is_empty() {
1564             return self.start_pos..self.end_pos;
1565         }
1566
1567         assert!(line_index < self.lines.len());
1568         if line_index == (self.lines.len() - 1) {
1569             self.lines[line_index]..self.end_pos
1570         } else {
1571             self.lines[line_index]..self.lines[line_index + 1]
1572         }
1573     }
1574
1575     /// Returns whether or not the file contains the given `SourceMap` byte
1576     /// position. The position one past the end of the file is considered to be
1577     /// contained by the file. This implies that files for which `is_empty`
1578     /// returns true still contain one byte position according to this function.
1579     #[inline]
1580     pub fn contains(&self, byte_pos: BytePos) -> bool {
1581         byte_pos >= self.start_pos && byte_pos <= self.end_pos
1582     }
1583
1584     #[inline]
1585     pub fn is_empty(&self) -> bool {
1586         self.start_pos == self.end_pos
1587     }
1588
1589     /// Calculates the original byte position relative to the start of the file
1590     /// based on the given byte position.
1591     pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1592         // Diff before any records is 0. Otherwise use the previously recorded
1593         // diff as that applies to the following characters until a new diff
1594         // is recorded.
1595         let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1596             Ok(i) => self.normalized_pos[i].diff,
1597             Err(i) if i == 0 => 0,
1598             Err(i) => self.normalized_pos[i - 1].diff,
1599         };
1600
1601         BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1602     }
1603
1604     /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1605     pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1606         // The number of extra bytes due to multibyte chars in the `SourceFile`.
1607         let mut total_extra_bytes = 0;
1608
1609         for mbc in self.multibyte_chars.iter() {
1610             debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1611             if mbc.pos < bpos {
1612                 // Every character is at least one byte, so we only
1613                 // count the actual extra bytes.
1614                 total_extra_bytes += mbc.bytes as u32 - 1;
1615                 // We should never see a byte position in the middle of a
1616                 // character.
1617                 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1618             } else {
1619                 break;
1620             }
1621         }
1622
1623         assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1624         CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1625     }
1626
1627     /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1628     /// given `BytePos`.
1629     pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1630         let chpos = self.bytepos_to_file_charpos(pos);
1631         match self.lookup_line(pos) {
1632             Some(a) => {
1633                 let line = a + 1; // Line numbers start at 1
1634                 let linebpos = self.lines[a];
1635                 let linechpos = self.bytepos_to_file_charpos(linebpos);
1636                 let col = chpos - linechpos;
1637                 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1638                 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1639                 debug!("byte is on line: {}", line);
1640                 assert!(chpos >= linechpos);
1641                 (line, col)
1642             }
1643             None => (0, chpos),
1644         }
1645     }
1646
1647     /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1648     /// column offset when displayed, for a given `BytePos`.
1649     pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1650         let (line, col_or_chpos) = self.lookup_file_pos(pos);
1651         if line > 0 {
1652             let col = col_or_chpos;
1653             let linebpos = self.lines[line - 1];
1654             let col_display = {
1655                 let start_width_idx = self
1656                     .non_narrow_chars
1657                     .binary_search_by_key(&linebpos, |x| x.pos())
1658                     .unwrap_or_else(|x| x);
1659                 let end_width_idx = self
1660                     .non_narrow_chars
1661                     .binary_search_by_key(&pos, |x| x.pos())
1662                     .unwrap_or_else(|x| x);
1663                 let special_chars = end_width_idx - start_width_idx;
1664                 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1665                     .iter()
1666                     .map(|x| x.width())
1667                     .sum();
1668                 col.0 - special_chars + non_narrow
1669             };
1670             (line, col, col_display)
1671         } else {
1672             let chpos = col_or_chpos;
1673             let col_display = {
1674                 let end_width_idx = self
1675                     .non_narrow_chars
1676                     .binary_search_by_key(&pos, |x| x.pos())
1677                     .unwrap_or_else(|x| x);
1678                 let non_narrow: usize =
1679                     self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1680                 chpos.0 - end_width_idx + non_narrow
1681             };
1682             (0, chpos, col_display)
1683         }
1684     }
1685 }
1686
1687 /// Normalizes the source code and records the normalizations.
1688 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1689     let mut normalized_pos = vec![];
1690     remove_bom(src, &mut normalized_pos);
1691     normalize_newlines(src, &mut normalized_pos);
1692
1693     // Offset all the positions by start_pos to match the final file positions.
1694     for np in &mut normalized_pos {
1695         np.pos.0 += start_pos.0;
1696     }
1697
1698     normalized_pos
1699 }
1700
1701 /// Removes UTF-8 BOM, if any.
1702 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1703     if src.starts_with('\u{feff}') {
1704         src.drain(..3);
1705         normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1706     }
1707 }
1708
1709 /// Replaces `\r\n` with `\n` in-place in `src`.
1710 ///
1711 /// Returns error if there's a lone `\r` in the string.
1712 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1713     if !src.as_bytes().contains(&b'\r') {
1714         return;
1715     }
1716
1717     // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1718     // While we *can* call `as_mut_vec` and do surgery on the live string
1719     // directly, let's rather steal the contents of `src`. This makes the code
1720     // safe even if a panic occurs.
1721
1722     let mut buf = std::mem::replace(src, String::new()).into_bytes();
1723     let mut gap_len = 0;
1724     let mut tail = buf.as_mut_slice();
1725     let mut cursor = 0;
1726     let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1727     loop {
1728         let idx = match find_crlf(&tail[gap_len..]) {
1729             None => tail.len(),
1730             Some(idx) => idx + gap_len,
1731         };
1732         tail.copy_within(gap_len..idx, 0);
1733         tail = &mut tail[idx - gap_len..];
1734         if tail.len() == gap_len {
1735             break;
1736         }
1737         cursor += idx - gap_len;
1738         gap_len += 1;
1739         normalized_pos.push(NormalizedPos {
1740             pos: BytePos::from_usize(cursor + 1),
1741             diff: original_gap + gap_len as u32,
1742         });
1743     }
1744
1745     // Account for removed `\r`.
1746     // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1747     let new_len = buf.len() - gap_len;
1748     unsafe {
1749         buf.set_len(new_len);
1750         *src = String::from_utf8_unchecked(buf);
1751     }
1752
1753     fn find_crlf(src: &[u8]) -> Option<usize> {
1754         let mut search_idx = 0;
1755         while let Some(idx) = find_cr(&src[search_idx..]) {
1756             if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1757                 search_idx += idx + 1;
1758                 continue;
1759             }
1760             return Some(search_idx + idx);
1761         }
1762         None
1763     }
1764
1765     fn find_cr(src: &[u8]) -> Option<usize> {
1766         src.iter().position(|&b| b == b'\r')
1767     }
1768 }
1769
1770 // _____________________________________________________________________________
1771 // Pos, BytePos, CharPos
1772 //
1773
1774 pub trait Pos {
1775     fn from_usize(n: usize) -> Self;
1776     fn to_usize(&self) -> usize;
1777     fn from_u32(n: u32) -> Self;
1778     fn to_u32(&self) -> u32;
1779 }
1780
1781 macro_rules! impl_pos {
1782     (
1783         $(
1784             $(#[$attr:meta])*
1785             $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1786         )*
1787     ) => {
1788         $(
1789             $(#[$attr])*
1790             $vis struct $ident($inner_vis $inner_ty);
1791
1792             impl Pos for $ident {
1793                 #[inline(always)]
1794                 fn from_usize(n: usize) -> $ident {
1795                     $ident(n as $inner_ty)
1796                 }
1797
1798                 #[inline(always)]
1799                 fn to_usize(&self) -> usize {
1800                     self.0 as usize
1801                 }
1802
1803                 #[inline(always)]
1804                 fn from_u32(n: u32) -> $ident {
1805                     $ident(n as $inner_ty)
1806                 }
1807
1808                 #[inline(always)]
1809                 fn to_u32(&self) -> u32 {
1810                     self.0 as u32
1811                 }
1812             }
1813
1814             impl Add for $ident {
1815                 type Output = $ident;
1816
1817                 #[inline(always)]
1818                 fn add(self, rhs: $ident) -> $ident {
1819                     $ident(self.0 + rhs.0)
1820                 }
1821             }
1822
1823             impl Sub for $ident {
1824                 type Output = $ident;
1825
1826                 #[inline(always)]
1827                 fn sub(self, rhs: $ident) -> $ident {
1828                     $ident(self.0 - rhs.0)
1829                 }
1830             }
1831         )*
1832     };
1833 }
1834
1835 impl_pos! {
1836     /// A byte offset.
1837     ///
1838     /// Keep this small (currently 32-bits), as AST contains a lot of them.
1839     #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1840     pub struct BytePos(pub u32);
1841
1842     /// A character offset.
1843     ///
1844     /// Because of multibyte UTF-8 characters, a byte offset
1845     /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`]
1846     /// values to `CharPos` values as necessary.
1847     #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1848     pub struct CharPos(pub usize);
1849 }
1850
1851 impl<S: rustc_serialize::Encoder> Encodable<S> for BytePos {
1852     fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1853         s.emit_u32(self.0)
1854     }
1855 }
1856
1857 impl<D: rustc_serialize::Decoder> Decodable<D> for BytePos {
1858     fn decode(d: &mut D) -> Result<BytePos, D::Error> {
1859         Ok(BytePos(d.read_u32()?))
1860     }
1861 }
1862
1863 // _____________________________________________________________________________
1864 // Loc, SourceFileAndLine, SourceFileAndBytePos
1865 //
1866
1867 /// A source code location used for error reporting.
1868 #[derive(Debug, Clone)]
1869 pub struct Loc {
1870     /// Information about the original source.
1871     pub file: Lrc<SourceFile>,
1872     /// The (1-based) line number.
1873     pub line: usize,
1874     /// The (0-based) column offset.
1875     pub col: CharPos,
1876     /// The (0-based) column offset when displayed.
1877     pub col_display: usize,
1878 }
1879
1880 // Used to be structural records.
1881 #[derive(Debug)]
1882 pub struct SourceFileAndLine {
1883     pub sf: Lrc<SourceFile>,
1884     pub line: usize,
1885 }
1886 #[derive(Debug)]
1887 pub struct SourceFileAndBytePos {
1888     pub sf: Lrc<SourceFile>,
1889     pub pos: BytePos,
1890 }
1891
1892 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1893 pub struct LineInfo {
1894     /// Index of line, starting from 0.
1895     pub line_index: usize,
1896
1897     /// Column in line where span begins, starting from 0.
1898     pub start_col: CharPos,
1899
1900     /// Column in line where span ends, starting from 0, exclusive.
1901     pub end_col: CharPos,
1902 }
1903
1904 pub struct FileLines {
1905     pub file: Lrc<SourceFile>,
1906     pub lines: Vec<LineInfo>,
1907 }
1908
1909 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1910     AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1911
1912 // _____________________________________________________________________________
1913 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1914 //
1915
1916 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1917
1918 #[derive(Clone, PartialEq, Eq, Debug)]
1919 pub enum SpanLinesError {
1920     DistinctSources(DistinctSources),
1921 }
1922
1923 #[derive(Clone, PartialEq, Eq, Debug)]
1924 pub enum SpanSnippetError {
1925     IllFormedSpan(Span),
1926     DistinctSources(DistinctSources),
1927     MalformedForSourcemap(MalformedSourceMapPositions),
1928     SourceNotAvailable { filename: FileName },
1929 }
1930
1931 #[derive(Clone, PartialEq, Eq, Debug)]
1932 pub struct DistinctSources {
1933     pub begin: (FileName, BytePos),
1934     pub end: (FileName, BytePos),
1935 }
1936
1937 #[derive(Clone, PartialEq, Eq, Debug)]
1938 pub struct MalformedSourceMapPositions {
1939     pub name: FileName,
1940     pub source_len: usize,
1941     pub begin_pos: BytePos,
1942     pub end_pos: BytePos,
1943 }
1944
1945 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1946 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1947 pub struct InnerSpan {
1948     pub start: usize,
1949     pub end: usize,
1950 }
1951
1952 impl InnerSpan {
1953     pub fn new(start: usize, end: usize) -> InnerSpan {
1954         InnerSpan { start, end }
1955     }
1956 }
1957
1958 /// Requirements for a `StableHashingContext` to be used in this crate.
1959 ///
1960 /// This is a hack to allow using the [`HashStable_Generic`] derive macro
1961 /// instead of implementing everything in rustc_middle.
1962 pub trait HashStableContext {
1963     fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
1964     /// Obtains a cache for storing the `Fingerprint` of an `ExpnId`.
1965     /// This method allows us to have multiple `HashStableContext` implementations
1966     /// that hash things in a different way, without the results of one polluting
1967     /// the cache of the other.
1968     fn expn_id_cache() -> &'static LocalKey<ExpnIdCache>;
1969     fn hash_spans(&self) -> bool;
1970     fn span_data_to_lines_and_cols(
1971         &mut self,
1972         span: &SpanData,
1973     ) -> Option<(Lrc<SourceFile>, usize, BytePos, usize, BytePos)>;
1974 }
1975
1976 impl<CTX> HashStable<CTX> for Span
1977 where
1978     CTX: HashStableContext,
1979 {
1980     /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1981     /// fields (that would be similar to hashing pointers, since those are just
1982     /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1983     /// triple, which stays the same even if the containing `SourceFile` has moved
1984     /// within the `SourceMap`.
1985     ///
1986     /// Also note that we are hashing byte offsets for the column, not unicode
1987     /// codepoint offsets. For the purpose of the hash that's sufficient.
1988     /// Also, hashing filenames is expensive so we avoid doing it twice when the
1989     /// span starts and ends in the same file, which is almost always the case.
1990     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1991         const TAG_VALID_SPAN: u8 = 0;
1992         const TAG_INVALID_SPAN: u8 = 1;
1993
1994         if !ctx.hash_spans() {
1995             return;
1996         }
1997
1998         self.ctxt().hash_stable(ctx, hasher);
1999
2000         if self.is_dummy() {
2001             Hash::hash(&TAG_INVALID_SPAN, hasher);
2002             return;
2003         }
2004
2005         // If this is not an empty or invalid span, we want to hash the last
2006         // position that belongs to it, as opposed to hashing the first
2007         // position past it.
2008         let span = self.data();
2009         let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span)
2010         {
2011             Some(pos) => pos,
2012             None => {
2013                 Hash::hash(&TAG_INVALID_SPAN, hasher);
2014                 return;
2015             }
2016         };
2017
2018         Hash::hash(&TAG_VALID_SPAN, hasher);
2019         // We truncate the stable ID hash and line and column numbers. The chances
2020         // of causing a collision this way should be minimal.
2021         Hash::hash(&(file.name_hash as u64), hasher);
2022
2023         // Hash both the length and the end location (line/column) of a span. If we
2024         // hash only the length, for example, then two otherwise equal spans with
2025         // different end locations will have the same hash. This can cause a problem
2026         // during incremental compilation wherein a previous result for a query that
2027         // depends on the end location of a span will be incorrectly reused when the
2028         // end location of the span it depends on has changed (see issue #74890). A
2029         // similar analysis applies if some query depends specifically on the length
2030         // of the span, but we only hash the end location. So hash both.
2031
2032         let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
2033         let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
2034         let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
2035         let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
2036         let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
2037         let len = (span.hi - span.lo).0;
2038         Hash::hash(&col_line, hasher);
2039         Hash::hash(&len, hasher);
2040     }
2041 }
2042
2043 impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
2044     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
2045         const TAG_EXPANSION: u8 = 0;
2046         const TAG_NO_EXPANSION: u8 = 1;
2047
2048         if *self == SyntaxContext::root() {
2049             TAG_NO_EXPANSION.hash_stable(ctx, hasher);
2050         } else {
2051             TAG_EXPANSION.hash_stable(ctx, hasher);
2052             let (expn_id, transparency) = self.outer_mark();
2053             expn_id.hash_stable(ctx, hasher);
2054             transparency.hash_stable(ctx, hasher);
2055         }
2056     }
2057 }
2058
2059 pub type ExpnIdCache = RefCell<Vec<Option<Fingerprint>>>;
2060
2061 impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
2062     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
2063         const TAG_ROOT: u8 = 0;
2064         const TAG_NOT_ROOT: u8 = 1;
2065
2066         if *self == ExpnId::root() {
2067             TAG_ROOT.hash_stable(ctx, hasher);
2068             return;
2069         }
2070
2071         // Since the same expansion context is usually referenced many
2072         // times, we cache a stable hash of it and hash that instead of
2073         // recursing every time.
2074         let index = self.as_u32() as usize;
2075         let res = CTX::expn_id_cache().with(|cache| cache.borrow().get(index).copied().flatten());
2076
2077         if let Some(res) = res {
2078             res.hash_stable(ctx, hasher);
2079         } else {
2080             let new_len = index + 1;
2081
2082             let mut sub_hasher = StableHasher::new();
2083             TAG_NOT_ROOT.hash_stable(ctx, &mut sub_hasher);
2084             self.expn_data().hash_stable(ctx, &mut sub_hasher);
2085             let sub_hash: Fingerprint = sub_hasher.finish();
2086
2087             CTX::expn_id_cache().with(|cache| {
2088                 let mut cache = cache.borrow_mut();
2089                 if cache.len() < new_len {
2090                     cache.resize(new_len, None);
2091                 }
2092                 let prev = cache[index].replace(sub_hash);
2093                 assert_eq!(prev, None, "Cache slot was filled");
2094             });
2095             sub_hash.hash_stable(ctx, hasher);
2096         }
2097     }
2098 }