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