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