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