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