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