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