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