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