1#![allow(internal_features)]
20#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
21#![doc(rust_logo)]
22#![feature(array_windows)]
23#![feature(cfg_match)]
24#![feature(core_io_borrowed_buf)]
25#![feature(hash_set_entry)]
26#![feature(if_let_guard)]
27#![feature(let_chains)]
28#![feature(map_try_insert)]
29#![feature(negative_impls)]
30#![feature(read_buf)]
31#![feature(round_char_boundary)]
32#![feature(rustc_attrs)]
33#![feature(rustdoc_internals)]
34#![warn(unreachable_pub)]
35extern crate self as rustc_span;
41
42use derive_where::derive_where;
43use rustc_data_structures::{AtomicRef, outline};
44use rustc_macros::{Decodable, Encodable, HashStable_Generic};
45use rustc_serialize::opaque::{FileEncoder, MemDecoder};
46use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
47use tracing::debug;
48
49mod caching_source_map_view;
50pub mod source_map;
51use source_map::{SourceMap, SourceMapInputs};
52
53pub use self::caching_source_map_view::CachingSourceMapView;
54use crate::fatal_error::FatalError;
55
56pub mod edition;
57use edition::Edition;
58pub mod hygiene;
59use hygiene::Transparency;
60pub use hygiene::{
61 DesugaringKind, ExpnData, ExpnHash, ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext,
62};
63use rustc_data_structures::stable_hasher::HashingControls;
64pub mod def_id;
65use def_id::{CrateNum, DefId, DefIndex, DefPathHash, LOCAL_CRATE, LocalDefId, StableCrateId};
66pub mod edit_distance;
67mod span_encoding;
68pub use span_encoding::{DUMMY_SP, Span};
69
70pub mod symbol;
71pub use symbol::{Ident, MacroRulesNormalizedIdent, STDLIB_STABLE_CRATES, Symbol, kw, sym};
72
73mod analyze_source_file;
74pub mod fatal_error;
75
76pub mod profiling;
77
78use std::borrow::Cow;
79use std::cmp::{self, Ordering};
80use std::fmt::Display;
81use std::hash::Hash;
82use std::io::{self, Read};
83use std::ops::{Add, Range, Sub};
84use std::path::{Path, PathBuf};
85use std::str::FromStr;
86use std::sync::Arc;
87use std::{fmt, iter};
88
89use md5::{Digest, Md5};
90use rustc_data_structures::stable_hasher::{Hash64, Hash128, HashStable, StableHasher};
91use rustc_data_structures::sync::{FreezeLock, FreezeWriteGuard, Lock};
92use rustc_data_structures::unord::UnordMap;
93use sha1::Sha1;
94use sha2::Sha256;
95
96#[cfg(test)]
97mod tests;
98
99pub struct SessionGlobals {
104 symbol_interner: symbol::Interner,
105 span_interner: Lock<span_encoding::SpanInterner>,
106 metavar_spans: MetavarSpansMap,
109 hygiene_data: Lock<hygiene::HygieneData>,
110
111 source_map: Option<Arc<SourceMap>>,
115}
116
117impl SessionGlobals {
118 pub fn new(edition: Edition, sm_inputs: Option<SourceMapInputs>) -> SessionGlobals {
119 SessionGlobals {
120 symbol_interner: symbol::Interner::fresh(),
121 span_interner: Lock::new(span_encoding::SpanInterner::default()),
122 metavar_spans: Default::default(),
123 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
124 source_map: sm_inputs.map(|inputs| Arc::new(SourceMap::with_inputs(inputs))),
125 }
126 }
127}
128
129pub fn create_session_globals_then<R>(
130 edition: Edition,
131 sm_inputs: Option<SourceMapInputs>,
132 f: impl FnOnce() -> R,
133) -> R {
134 assert!(
135 !SESSION_GLOBALS.is_set(),
136 "SESSION_GLOBALS should never be overwritten! \
137 Use another thread if you need another SessionGlobals"
138 );
139 let session_globals = SessionGlobals::new(edition, sm_inputs);
140 SESSION_GLOBALS.set(&session_globals, f)
141}
142
143pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R {
144 assert!(
145 !SESSION_GLOBALS.is_set(),
146 "SESSION_GLOBALS should never be overwritten! \
147 Use another thread if you need another SessionGlobals"
148 );
149 SESSION_GLOBALS.set(session_globals, f)
150}
151
152pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R
154where
155 F: FnOnce(&SessionGlobals) -> R,
156{
157 if !SESSION_GLOBALS.is_set() {
158 let session_globals = SessionGlobals::new(edition, None);
159 SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f))
160 } else {
161 SESSION_GLOBALS.with(f)
162 }
163}
164
165pub fn with_session_globals<R, F>(f: F) -> R
166where
167 F: FnOnce(&SessionGlobals) -> R,
168{
169 SESSION_GLOBALS.with(f)
170}
171
172pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R {
174 create_session_globals_then(edition::DEFAULT_EDITION, None, f)
175}
176
177scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals);
181
182#[derive(Default)]
183pub struct MetavarSpansMap(FreezeLock<UnordMap<Span, (Span, bool)>>);
184
185impl MetavarSpansMap {
186 pub fn insert(&self, span: Span, var_span: Span) -> bool {
187 match self.0.write().try_insert(span, (var_span, false)) {
188 Ok(_) => true,
189 Err(entry) => entry.entry.get().0 == var_span,
190 }
191 }
192
193 pub fn get(&self, span: Span) -> Option<Span> {
195 if let Some(mut mspans) = self.0.try_write() {
196 if let Some((var_span, read)) = mspans.get_mut(&span) {
197 *read = true;
198 Some(*var_span)
199 } else {
200 None
201 }
202 } else {
203 if let Some((span, true)) = self.0.read().get(&span) { Some(*span) } else { None }
204 }
205 }
206
207 pub fn freeze_and_get_read_spans(&self) -> UnordMap<Span, Span> {
211 self.0.freeze().items().filter(|(_, (_, b))| *b).map(|(s1, (s2, _))| (*s1, *s2)).collect()
212 }
213}
214
215#[inline]
216pub fn with_metavar_spans<R>(f: impl FnOnce(&MetavarSpansMap) -> R) -> R {
217 with_session_globals(|session_globals| f(&session_globals.metavar_spans))
218}
219
220#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Decodable)]
223pub enum RealFileName {
224 LocalPath(PathBuf),
225 Remapped {
229 local_path: Option<PathBuf>,
232 virtual_name: PathBuf,
235 },
236}
237
238impl Hash for RealFileName {
239 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
240 self.remapped_path_if_available().hash(state)
245 }
246}
247
248impl<S: Encoder> Encodable<S> for RealFileName {
251 fn encode(&self, encoder: &mut S) {
252 match *self {
253 RealFileName::LocalPath(ref local_path) => {
254 encoder.emit_u8(0);
255 local_path.encode(encoder);
256 }
257
258 RealFileName::Remapped { ref local_path, ref virtual_name } => {
259 encoder.emit_u8(1);
260 assert!(local_path.is_none());
263 local_path.encode(encoder);
264 virtual_name.encode(encoder);
265 }
266 }
267 }
268}
269
270impl RealFileName {
271 pub fn local_path(&self) -> Option<&Path> {
275 match self {
276 RealFileName::LocalPath(p) => Some(p),
277 RealFileName::Remapped { local_path, virtual_name: _ } => local_path.as_deref(),
278 }
279 }
280
281 pub fn into_local_path(self) -> Option<PathBuf> {
285 match self {
286 RealFileName::LocalPath(p) => Some(p),
287 RealFileName::Remapped { local_path: p, virtual_name: _ } => p,
288 }
289 }
290
291 pub fn remapped_path_if_available(&self) -> &Path {
296 match self {
297 RealFileName::LocalPath(p)
298 | RealFileName::Remapped { local_path: _, virtual_name: p } => p,
299 }
300 }
301
302 pub fn local_path_if_available(&self) -> &Path {
306 match self {
307 RealFileName::LocalPath(path)
308 | RealFileName::Remapped { local_path: None, virtual_name: path }
309 | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path,
310 }
311 }
312
313 pub fn to_path(&self, display_pref: FileNameDisplayPreference) -> &Path {
317 match display_pref {
318 FileNameDisplayPreference::Local | FileNameDisplayPreference::Short => {
319 self.local_path_if_available()
320 }
321 FileNameDisplayPreference::Remapped => self.remapped_path_if_available(),
322 }
323 }
324
325 pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> {
326 match display_pref {
327 FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(),
328 FileNameDisplayPreference::Remapped => {
329 self.remapped_path_if_available().to_string_lossy()
330 }
331 FileNameDisplayPreference::Short => self
332 .local_path_if_available()
333 .file_name()
334 .map_or_else(|| "".into(), |f| f.to_string_lossy()),
335 }
336 }
337}
338
339#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, Decodable, Encodable)]
341pub enum FileName {
342 Real(RealFileName),
343 CfgSpec(Hash64),
345 Anon(Hash64),
347 MacroExpansion(Hash64),
350 ProcMacroSourceCode(Hash64),
351 CliCrateAttr(Hash64),
353 Custom(String),
355 DocTest(PathBuf, isize),
356 InlineAsm(Hash64),
358}
359
360impl From<PathBuf> for FileName {
361 fn from(p: PathBuf) -> Self {
362 FileName::Real(RealFileName::LocalPath(p))
363 }
364}
365
366#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
367pub enum FileNameDisplayPreference {
368 Remapped,
371 Local,
374 Short,
377}
378
379pub struct FileNameDisplay<'a> {
380 inner: &'a FileName,
381 display_pref: FileNameDisplayPreference,
382}
383
384impl fmt::Display for FileNameDisplay<'_> {
385 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386 use FileName::*;
387 match *self.inner {
388 Real(ref name) => {
389 write!(fmt, "{}", name.to_string_lossy(self.display_pref))
390 }
391 CfgSpec(_) => write!(fmt, "<cfgspec>"),
392 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
393 Anon(_) => write!(fmt, "<anon>"),
394 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
395 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
396 Custom(ref s) => write!(fmt, "<{s}>"),
397 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
398 InlineAsm(_) => write!(fmt, "<inline asm>"),
399 }
400 }
401}
402
403impl<'a> FileNameDisplay<'a> {
404 pub fn to_string_lossy(&self) -> Cow<'a, str> {
405 match self.inner {
406 FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref),
407 _ => Cow::from(self.to_string()),
408 }
409 }
410}
411
412impl FileName {
413 pub fn is_real(&self) -> bool {
414 use FileName::*;
415 match *self {
416 Real(_) => true,
417 Anon(_)
418 | MacroExpansion(_)
419 | ProcMacroSourceCode(_)
420 | CliCrateAttr(_)
421 | Custom(_)
422 | CfgSpec(_)
423 | DocTest(_, _)
424 | InlineAsm(_) => false,
425 }
426 }
427
428 pub fn prefer_remapped_unconditionaly(&self) -> FileNameDisplay<'_> {
429 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped }
430 }
431
432 pub fn prefer_local(&self) -> FileNameDisplay<'_> {
435 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local }
436 }
437
438 pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> {
439 FileNameDisplay { inner: self, display_pref }
440 }
441
442 pub fn macro_expansion_source_code(src: &str) -> FileName {
443 let mut hasher = StableHasher::new();
444 src.hash(&mut hasher);
445 FileName::MacroExpansion(hasher.finish())
446 }
447
448 pub fn anon_source_code(src: &str) -> FileName {
449 let mut hasher = StableHasher::new();
450 src.hash(&mut hasher);
451 FileName::Anon(hasher.finish())
452 }
453
454 pub fn proc_macro_source_code(src: &str) -> FileName {
455 let mut hasher = StableHasher::new();
456 src.hash(&mut hasher);
457 FileName::ProcMacroSourceCode(hasher.finish())
458 }
459
460 pub fn cfg_spec_source_code(src: &str) -> FileName {
461 let mut hasher = StableHasher::new();
462 src.hash(&mut hasher);
463 FileName::CfgSpec(hasher.finish())
464 }
465
466 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
467 let mut hasher = StableHasher::new();
468 src.hash(&mut hasher);
469 FileName::CliCrateAttr(hasher.finish())
470 }
471
472 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
473 FileName::DocTest(path, line)
474 }
475
476 pub fn inline_asm_source_code(src: &str) -> FileName {
477 let mut hasher = StableHasher::new();
478 src.hash(&mut hasher);
479 FileName::InlineAsm(hasher.finish())
480 }
481
482 pub fn into_local_path(self) -> Option<PathBuf> {
486 match self {
487 FileName::Real(path) => path.into_local_path(),
488 FileName::DocTest(path, _) => Some(path),
489 _ => None,
490 }
491 }
492}
493
494#[derive(Clone, Copy, Hash, PartialEq, Eq)]
510#[derive_where(PartialOrd, Ord)]
511pub struct SpanData {
512 pub lo: BytePos,
513 pub hi: BytePos,
514 #[derive_where(skip)]
517 pub ctxt: SyntaxContext,
520 #[derive_where(skip)]
521 pub parent: Option<LocalDefId>,
524}
525
526impl SpanData {
527 #[inline]
528 pub fn span(&self) -> Span {
529 Span::new(self.lo, self.hi, self.ctxt, self.parent)
530 }
531 #[inline]
532 pub fn with_lo(&self, lo: BytePos) -> Span {
533 Span::new(lo, self.hi, self.ctxt, self.parent)
534 }
535 #[inline]
536 pub fn with_hi(&self, hi: BytePos) -> Span {
537 Span::new(self.lo, hi, self.ctxt, self.parent)
538 }
539 #[inline]
541 fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
542 Span::new(self.lo, self.hi, ctxt, self.parent)
543 }
544 #[inline]
546 fn with_parent(&self, parent: Option<LocalDefId>) -> Span {
547 Span::new(self.lo, self.hi, self.ctxt, parent)
548 }
549 #[inline]
551 pub fn is_dummy(self) -> bool {
552 self.lo.0 == 0 && self.hi.0 == 0
553 }
554 pub fn contains(self, other: Self) -> bool {
556 self.lo <= other.lo && other.hi <= self.hi
557 }
558}
559
560impl Default for SpanData {
561 fn default() -> Self {
562 Self { lo: BytePos(0), hi: BytePos(0), ctxt: SyntaxContext::root(), parent: None }
563 }
564}
565
566impl PartialOrd for Span {
567 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
568 PartialOrd::partial_cmp(&self.data(), &rhs.data())
569 }
570}
571impl Ord for Span {
572 fn cmp(&self, rhs: &Self) -> Ordering {
573 Ord::cmp(&self.data(), &rhs.data())
574 }
575}
576
577impl Span {
578 #[inline]
579 pub fn lo(self) -> BytePos {
580 self.data().lo
581 }
582 #[inline]
583 pub fn with_lo(self, lo: BytePos) -> Span {
584 self.data().with_lo(lo)
585 }
586 #[inline]
587 pub fn hi(self) -> BytePos {
588 self.data().hi
589 }
590 #[inline]
591 pub fn with_hi(self, hi: BytePos) -> Span {
592 self.data().with_hi(hi)
593 }
594 #[inline]
595 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
596 self.map_ctxt(|_| ctxt)
597 }
598
599 #[inline]
600 pub fn is_visible(self, sm: &SourceMap) -> bool {
601 !self.is_dummy() && sm.is_span_accessible(self)
602 }
603
604 pub fn in_external_macro(self, sm: &SourceMap) -> bool {
609 let expn_data = self.ctxt().outer_expn_data();
610 match expn_data.kind {
611 ExpnKind::Root
612 | ExpnKind::Desugaring(
613 DesugaringKind::ForLoop
614 | DesugaringKind::WhileLoop
615 | DesugaringKind::OpaqueTy
616 | DesugaringKind::Async
617 | DesugaringKind::Await,
618 ) => false,
619 ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, ExpnKind::Macro(MacroKind::Bang, _) => {
621 expn_data.def_site.is_dummy() || sm.is_imported(expn_data.def_site)
623 }
624 ExpnKind::Macro { .. } => true, }
626 }
627
628 pub fn in_derive_expansion(self) -> bool {
630 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
631 }
632
633 pub fn is_from_async_await(self) -> bool {
635 matches!(
636 self.ctxt().outer_expn_data().kind,
637 ExpnKind::Desugaring(DesugaringKind::Async | DesugaringKind::Await),
638 )
639 }
640
641 pub fn can_be_used_for_suggestions(self) -> bool {
643 !self.from_expansion()
644 || (self.in_derive_expansion()
648 && self.parent_callsite().map(|p| (p.lo(), p.hi())) != Some((self.lo(), self.hi())))
649 }
650
651 #[inline]
652 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
653 Span::new(lo, hi, SyntaxContext::root(), None)
654 }
655
656 #[inline]
658 pub fn shrink_to_lo(self) -> Span {
659 let span = self.data_untracked();
660 span.with_hi(span.lo)
661 }
662 #[inline]
664 pub fn shrink_to_hi(self) -> Span {
665 let span = self.data_untracked();
666 span.with_lo(span.hi)
667 }
668
669 #[inline]
670 pub fn is_empty(self) -> bool {
672 let span = self.data_untracked();
673 span.hi == span.lo
674 }
675
676 pub fn substitute_dummy(self, other: Span) -> Span {
678 if self.is_dummy() { other } else { self }
679 }
680
681 pub fn contains(self, other: Span) -> bool {
683 let span = self.data();
684 let other = other.data();
685 span.contains(other)
686 }
687
688 pub fn overlaps(self, other: Span) -> bool {
690 let span = self.data();
691 let other = other.data();
692 span.lo < other.hi && other.lo < span.hi
693 }
694
695 pub fn overlaps_or_adjacent(self, other: Span) -> bool {
697 let span = self.data();
698 let other = other.data();
699 span.lo <= other.hi && other.lo <= span.hi
700 }
701
702 pub fn source_equal(self, other: Span) -> bool {
707 let span = self.data();
708 let other = other.data();
709 span.lo == other.lo && span.hi == other.hi
710 }
711
712 pub fn trim_start(self, other: Span) -> Option<Span> {
714 let span = self.data();
715 let other = other.data();
716 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
717 }
718
719 pub fn trim_end(self, other: Span) -> Option<Span> {
721 let span = self.data();
722 let other = other.data();
723 if span.lo < other.lo { Some(span.with_hi(cmp::min(span.hi, other.lo))) } else { None }
724 }
725
726 pub fn source_callsite(self) -> Span {
729 let ctxt = self.ctxt();
730 if !ctxt.is_root() { ctxt.outer_expn_data().call_site.source_callsite() } else { self }
731 }
732
733 pub fn parent_callsite(self) -> Option<Span> {
736 let ctxt = self.ctxt();
737 (!ctxt.is_root()).then(|| ctxt.outer_expn_data().call_site)
738 }
739
740 pub fn find_ancestor_inside(mut self, outer: Span) -> Option<Span> {
748 while !outer.contains(self) {
749 self = self.parent_callsite()?;
750 }
751 Some(self)
752 }
753
754 pub fn find_ancestor_in_same_ctxt(mut self, other: Span) -> Option<Span> {
765 while !self.eq_ctxt(other) {
766 self = self.parent_callsite()?;
767 }
768 Some(self)
769 }
770
771 pub fn find_ancestor_inside_same_ctxt(mut self, outer: Span) -> Option<Span> {
781 while !outer.contains(self) || !self.eq_ctxt(outer) {
782 self = self.parent_callsite()?;
783 }
784 Some(self)
785 }
786
787 pub fn find_oldest_ancestor_in_same_ctxt(self) -> Span {
817 let mut cur = self;
818 while cur.eq_ctxt(self)
819 && let Some(parent_callsite) = cur.parent_callsite()
820 {
821 cur = parent_callsite;
822 }
823 cur
824 }
825
826 pub fn edition(self) -> edition::Edition {
828 self.ctxt().edition()
829 }
830
831 #[inline]
833 pub fn is_rust_2015(self) -> bool {
834 self.edition().is_rust_2015()
835 }
836
837 #[inline]
839 pub fn at_least_rust_2018(self) -> bool {
840 self.edition().at_least_rust_2018()
841 }
842
843 #[inline]
845 pub fn at_least_rust_2021(self) -> bool {
846 self.edition().at_least_rust_2021()
847 }
848
849 #[inline]
851 pub fn at_least_rust_2024(self) -> bool {
852 self.edition().at_least_rust_2024()
853 }
854
855 pub fn source_callee(self) -> Option<ExpnData> {
861 let mut ctxt = self.ctxt();
862 let mut opt_expn_data = None;
863 while !ctxt.is_root() {
864 let expn_data = ctxt.outer_expn_data();
865 ctxt = expn_data.call_site.ctxt();
866 opt_expn_data = Some(expn_data);
867 }
868 opt_expn_data
869 }
870
871 pub fn allows_unstable(self, feature: Symbol) -> bool {
875 self.ctxt()
876 .outer_expn_data()
877 .allow_internal_unstable
878 .is_some_and(|features| features.iter().any(|&f| f == feature))
879 }
880
881 pub fn is_desugaring(self, kind: DesugaringKind) -> bool {
883 match self.ctxt().outer_expn_data().kind {
884 ExpnKind::Desugaring(k) => k == kind,
885 _ => false,
886 }
887 }
888
889 pub fn desugaring_kind(self) -> Option<DesugaringKind> {
892 match self.ctxt().outer_expn_data().kind {
893 ExpnKind::Desugaring(k) => Some(k),
894 _ => None,
895 }
896 }
897
898 pub fn allows_unsafe(self) -> bool {
902 self.ctxt().outer_expn_data().allow_internal_unsafe
903 }
904
905 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
906 let mut prev_span = DUMMY_SP;
907 iter::from_fn(move || {
908 loop {
909 let ctxt = self.ctxt();
910 if ctxt.is_root() {
911 return None;
912 }
913
914 let expn_data = ctxt.outer_expn_data();
915 let is_recursive = expn_data.call_site.source_equal(prev_span);
916
917 prev_span = self;
918 self = expn_data.call_site;
919
920 if !is_recursive {
922 return Some(expn_data);
923 }
924 }
925 })
926 }
927
928 pub fn split_at(self, pos: u32) -> (Span, Span) {
930 let len = self.hi().0 - self.lo().0;
931 debug_assert!(pos <= len);
932
933 let split_pos = BytePos(self.lo().0 + pos);
934 (
935 Span::new(self.lo(), split_pos, self.ctxt(), self.parent()),
936 Span::new(split_pos, self.hi(), self.ctxt(), self.parent()),
937 )
938 }
939
940 fn try_metavars(a: SpanData, b: SpanData, a_orig: Span, b_orig: Span) -> (SpanData, SpanData) {
942 match with_metavar_spans(|mspans| (mspans.get(a_orig), mspans.get(b_orig))) {
943 (None, None) => {}
944 (Some(meta_a), None) => {
945 let meta_a = meta_a.data();
946 if meta_a.ctxt == b.ctxt {
947 return (meta_a, b);
948 }
949 }
950 (None, Some(meta_b)) => {
951 let meta_b = meta_b.data();
952 if a.ctxt == meta_b.ctxt {
953 return (a, meta_b);
954 }
955 }
956 (Some(meta_a), Some(meta_b)) => {
957 let meta_b = meta_b.data();
958 if a.ctxt == meta_b.ctxt {
959 return (a, meta_b);
960 }
961 let meta_a = meta_a.data();
962 if meta_a.ctxt == b.ctxt {
963 return (meta_a, b);
964 } else if meta_a.ctxt == meta_b.ctxt {
965 return (meta_a, meta_b);
966 }
967 }
968 }
969
970 (a, b)
971 }
972
973 fn prepare_to_combine(
975 a_orig: Span,
976 b_orig: Span,
977 ) -> Result<(SpanData, SpanData, Option<LocalDefId>), Span> {
978 let (a, b) = (a_orig.data(), b_orig.data());
979 if a.ctxt == b.ctxt {
980 return Ok((a, b, if a.parent == b.parent { a.parent } else { None }));
981 }
982
983 let (a, b) = Span::try_metavars(a, b, a_orig, b_orig);
984 if a.ctxt == b.ctxt {
985 return Ok((a, b, if a.parent == b.parent { a.parent } else { None }));
986 }
987
988 let a_is_callsite = a.ctxt.is_root() || a.ctxt == b.span().source_callsite().ctxt();
996 Err(if a_is_callsite { b_orig } else { a_orig })
997 }
998
999 pub fn with_neighbor(self, neighbor: Span) -> Span {
1001 match Span::prepare_to_combine(self, neighbor) {
1002 Ok((this, ..)) => this.span(),
1003 Err(_) => self,
1004 }
1005 }
1006
1007 pub fn to(self, end: Span) -> Span {
1018 match Span::prepare_to_combine(self, end) {
1019 Ok((from, to, parent)) => {
1020 Span::new(cmp::min(from.lo, to.lo), cmp::max(from.hi, to.hi), from.ctxt, parent)
1021 }
1022 Err(fallback) => fallback,
1023 }
1024 }
1025
1026 pub fn between(self, end: Span) -> Span {
1034 match Span::prepare_to_combine(self, end) {
1035 Ok((from, to, parent)) => {
1036 Span::new(cmp::min(from.hi, to.hi), cmp::max(from.lo, to.lo), from.ctxt, parent)
1037 }
1038 Err(fallback) => fallback,
1039 }
1040 }
1041
1042 pub fn until(self, end: Span) -> Span {
1050 match Span::prepare_to_combine(self, end) {
1051 Ok((from, to, parent)) => {
1052 Span::new(cmp::min(from.lo, to.lo), cmp::max(from.lo, to.lo), from.ctxt, parent)
1053 }
1054 Err(fallback) => fallback,
1055 }
1056 }
1057
1058 pub fn from_inner(self, inner: InnerSpan) -> Span {
1059 let span = self.data();
1060 Span::new(
1061 span.lo + BytePos::from_usize(inner.start),
1062 span.lo + BytePos::from_usize(inner.end),
1063 span.ctxt,
1064 span.parent,
1065 )
1066 }
1067
1068 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
1071 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
1072 }
1073
1074 pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span {
1077 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
1078 }
1079
1080 pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span {
1083 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
1084 }
1085
1086 fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
1090 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
1091 }
1092
1093 #[inline]
1094 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
1095 self.map_ctxt(|ctxt| ctxt.apply_mark(expn_id, transparency))
1096 }
1097
1098 #[inline]
1099 pub fn remove_mark(&mut self) -> ExpnId {
1100 let mut mark = ExpnId::root();
1101 *self = self.map_ctxt(|mut ctxt| {
1102 mark = ctxt.remove_mark();
1103 ctxt
1104 });
1105 mark
1106 }
1107
1108 #[inline]
1109 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
1110 let mut mark = None;
1111 *self = self.map_ctxt(|mut ctxt| {
1112 mark = ctxt.adjust(expn_id);
1113 ctxt
1114 });
1115 mark
1116 }
1117
1118 #[inline]
1119 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
1120 let mut mark = None;
1121 *self = self.map_ctxt(|mut ctxt| {
1122 mark = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
1123 ctxt
1124 });
1125 mark
1126 }
1127
1128 #[inline]
1129 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
1130 let mut mark = None;
1131 *self = self.map_ctxt(|mut ctxt| {
1132 mark = ctxt.glob_adjust(expn_id, glob_span);
1133 ctxt
1134 });
1135 mark
1136 }
1137
1138 #[inline]
1139 pub fn reverse_glob_adjust(
1140 &mut self,
1141 expn_id: ExpnId,
1142 glob_span: Span,
1143 ) -> Option<Option<ExpnId>> {
1144 let mut mark = None;
1145 *self = self.map_ctxt(|mut ctxt| {
1146 mark = ctxt.reverse_glob_adjust(expn_id, glob_span);
1147 ctxt
1148 });
1149 mark
1150 }
1151
1152 #[inline]
1153 pub fn normalize_to_macros_2_0(self) -> Span {
1154 self.map_ctxt(|ctxt| ctxt.normalize_to_macros_2_0())
1155 }
1156
1157 #[inline]
1158 pub fn normalize_to_macro_rules(self) -> Span {
1159 self.map_ctxt(|ctxt| ctxt.normalize_to_macro_rules())
1160 }
1161}
1162
1163impl Default for Span {
1164 fn default() -> Self {
1165 DUMMY_SP
1166 }
1167}
1168
1169rustc_index::newtype_index! {
1170 #[orderable]
1171 #[debug_format = "AttrId({})"]
1172 pub struct AttrId {}
1173}
1174
1175pub trait SpanEncoder: Encoder {
1178 fn encode_span(&mut self, span: Span);
1179 fn encode_symbol(&mut self, symbol: Symbol);
1180 fn encode_expn_id(&mut self, expn_id: ExpnId);
1181 fn encode_syntax_context(&mut self, syntax_context: SyntaxContext);
1182 fn encode_crate_num(&mut self, crate_num: CrateNum);
1185 fn encode_def_index(&mut self, def_index: DefIndex);
1186 fn encode_def_id(&mut self, def_id: DefId);
1187}
1188
1189impl SpanEncoder for FileEncoder {
1190 fn encode_span(&mut self, span: Span) {
1191 let span = span.data();
1192 span.lo.encode(self);
1193 span.hi.encode(self);
1194 }
1195
1196 fn encode_symbol(&mut self, symbol: Symbol) {
1197 self.emit_str(symbol.as_str());
1198 }
1199
1200 fn encode_expn_id(&mut self, _expn_id: ExpnId) {
1201 panic!("cannot encode `ExpnId` with `FileEncoder`");
1202 }
1203
1204 fn encode_syntax_context(&mut self, _syntax_context: SyntaxContext) {
1205 panic!("cannot encode `SyntaxContext` with `FileEncoder`");
1206 }
1207
1208 fn encode_crate_num(&mut self, crate_num: CrateNum) {
1209 self.emit_u32(crate_num.as_u32());
1210 }
1211
1212 fn encode_def_index(&mut self, _def_index: DefIndex) {
1213 panic!("cannot encode `DefIndex` with `FileEncoder`");
1214 }
1215
1216 fn encode_def_id(&mut self, def_id: DefId) {
1217 def_id.krate.encode(self);
1218 def_id.index.encode(self);
1219 }
1220}
1221
1222impl<E: SpanEncoder> Encodable<E> for Span {
1223 fn encode(&self, s: &mut E) {
1224 s.encode_span(*self);
1225 }
1226}
1227
1228impl<E: SpanEncoder> Encodable<E> for Symbol {
1229 fn encode(&self, s: &mut E) {
1230 s.encode_symbol(*self);
1231 }
1232}
1233
1234impl<E: SpanEncoder> Encodable<E> for ExpnId {
1235 fn encode(&self, s: &mut E) {
1236 s.encode_expn_id(*self)
1237 }
1238}
1239
1240impl<E: SpanEncoder> Encodable<E> for SyntaxContext {
1241 fn encode(&self, s: &mut E) {
1242 s.encode_syntax_context(*self)
1243 }
1244}
1245
1246impl<E: SpanEncoder> Encodable<E> for CrateNum {
1247 fn encode(&self, s: &mut E) {
1248 s.encode_crate_num(*self)
1249 }
1250}
1251
1252impl<E: SpanEncoder> Encodable<E> for DefIndex {
1253 fn encode(&self, s: &mut E) {
1254 s.encode_def_index(*self)
1255 }
1256}
1257
1258impl<E: SpanEncoder> Encodable<E> for DefId {
1259 fn encode(&self, s: &mut E) {
1260 s.encode_def_id(*self)
1261 }
1262}
1263
1264impl<E: SpanEncoder> Encodable<E> for AttrId {
1265 fn encode(&self, _s: &mut E) {
1266 }
1268}
1269
1270pub trait SpanDecoder: Decoder {
1273 fn decode_span(&mut self) -> Span;
1274 fn decode_symbol(&mut self) -> Symbol;
1275 fn decode_expn_id(&mut self) -> ExpnId;
1276 fn decode_syntax_context(&mut self) -> SyntaxContext;
1277 fn decode_crate_num(&mut self) -> CrateNum;
1278 fn decode_def_index(&mut self) -> DefIndex;
1279 fn decode_def_id(&mut self) -> DefId;
1280 fn decode_attr_id(&mut self) -> AttrId;
1281}
1282
1283impl SpanDecoder for MemDecoder<'_> {
1284 fn decode_span(&mut self) -> Span {
1285 let lo = Decodable::decode(self);
1286 let hi = Decodable::decode(self);
1287
1288 Span::new(lo, hi, SyntaxContext::root(), None)
1289 }
1290
1291 fn decode_symbol(&mut self) -> Symbol {
1292 Symbol::intern(self.read_str())
1293 }
1294
1295 fn decode_expn_id(&mut self) -> ExpnId {
1296 panic!("cannot decode `ExpnId` with `MemDecoder`");
1297 }
1298
1299 fn decode_syntax_context(&mut self) -> SyntaxContext {
1300 panic!("cannot decode `SyntaxContext` with `MemDecoder`");
1301 }
1302
1303 fn decode_crate_num(&mut self) -> CrateNum {
1304 CrateNum::from_u32(self.read_u32())
1305 }
1306
1307 fn decode_def_index(&mut self) -> DefIndex {
1308 panic!("cannot decode `DefIndex` with `MemDecoder`");
1309 }
1310
1311 fn decode_def_id(&mut self) -> DefId {
1312 DefId { krate: Decodable::decode(self), index: Decodable::decode(self) }
1313 }
1314
1315 fn decode_attr_id(&mut self) -> AttrId {
1316 panic!("cannot decode `AttrId` with `MemDecoder`");
1317 }
1318}
1319
1320impl<D: SpanDecoder> Decodable<D> for Span {
1321 fn decode(s: &mut D) -> Span {
1322 s.decode_span()
1323 }
1324}
1325
1326impl<D: SpanDecoder> Decodable<D> for Symbol {
1327 fn decode(s: &mut D) -> Symbol {
1328 s.decode_symbol()
1329 }
1330}
1331
1332impl<D: SpanDecoder> Decodable<D> for ExpnId {
1333 fn decode(s: &mut D) -> ExpnId {
1334 s.decode_expn_id()
1335 }
1336}
1337
1338impl<D: SpanDecoder> Decodable<D> for SyntaxContext {
1339 fn decode(s: &mut D) -> SyntaxContext {
1340 s.decode_syntax_context()
1341 }
1342}
1343
1344impl<D: SpanDecoder> Decodable<D> for CrateNum {
1345 fn decode(s: &mut D) -> CrateNum {
1346 s.decode_crate_num()
1347 }
1348}
1349
1350impl<D: SpanDecoder> Decodable<D> for DefIndex {
1351 fn decode(s: &mut D) -> DefIndex {
1352 s.decode_def_index()
1353 }
1354}
1355
1356impl<D: SpanDecoder> Decodable<D> for DefId {
1357 fn decode(s: &mut D) -> DefId {
1358 s.decode_def_id()
1359 }
1360}
1361
1362impl<D: SpanDecoder> Decodable<D> for AttrId {
1363 fn decode(s: &mut D) -> AttrId {
1364 s.decode_attr_id()
1365 }
1366}
1367
1368impl fmt::Debug for Span {
1369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1370 fn fallback(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1374 f.debug_struct("Span")
1375 .field("lo", &span.lo())
1376 .field("hi", &span.hi())
1377 .field("ctxt", &span.ctxt())
1378 .finish()
1379 }
1380
1381 if SESSION_GLOBALS.is_set() {
1382 with_session_globals(|session_globals| {
1383 if let Some(source_map) = &session_globals.source_map {
1384 write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(*self), self.ctxt())
1385 } else {
1386 fallback(*self, f)
1387 }
1388 })
1389 } else {
1390 fallback(*self, f)
1391 }
1392 }
1393}
1394
1395impl fmt::Debug for SpanData {
1396 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1397 fmt::Debug::fmt(&self.span(), f)
1398 }
1399}
1400
1401#[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug, HashStable_Generic)]
1403pub struct MultiByteChar {
1404 pub pos: RelativeBytePos,
1406 pub bytes: u8,
1408}
1409
1410#[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug, HashStable_Generic)]
1412pub struct NormalizedPos {
1413 pub pos: RelativeBytePos,
1415 pub diff: u32,
1417}
1418
1419#[derive(PartialEq, Eq, Clone, Debug)]
1420pub enum ExternalSource {
1421 Unneeded,
1423 Foreign {
1424 kind: ExternalSourceKind,
1425 metadata_index: u32,
1427 },
1428}
1429
1430#[derive(PartialEq, Eq, Clone, Debug)]
1432pub enum ExternalSourceKind {
1433 Present(Arc<String>),
1435 AbsentOk,
1437 AbsentErr,
1439}
1440
1441impl ExternalSource {
1442 pub fn get_source(&self) -> Option<&str> {
1443 match self {
1444 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1445 _ => None,
1446 }
1447 }
1448}
1449
1450#[derive(Debug)]
1451pub struct OffsetOverflowError;
1452
1453#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1454#[derive(HashStable_Generic)]
1455pub enum SourceFileHashAlgorithm {
1456 Md5,
1457 Sha1,
1458 Sha256,
1459 Blake3,
1460}
1461
1462impl Display for SourceFileHashAlgorithm {
1463 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1464 f.write_str(match self {
1465 Self::Md5 => "md5",
1466 Self::Sha1 => "sha1",
1467 Self::Sha256 => "sha256",
1468 Self::Blake3 => "blake3",
1469 })
1470 }
1471}
1472
1473impl FromStr for SourceFileHashAlgorithm {
1474 type Err = ();
1475
1476 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1477 match s {
1478 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1479 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1480 "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1481 "blake3" => Ok(SourceFileHashAlgorithm::Blake3),
1482 _ => Err(()),
1483 }
1484 }
1485}
1486
1487#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
1489#[derive(HashStable_Generic, Encodable, Decodable)]
1490pub struct SourceFileHash {
1491 pub kind: SourceFileHashAlgorithm,
1492 value: [u8; 32],
1493}
1494
1495impl Display for SourceFileHash {
1496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1497 write!(f, "{}=", self.kind)?;
1498 for byte in self.value[0..self.hash_len()].into_iter() {
1499 write!(f, "{byte:02x}")?;
1500 }
1501 Ok(())
1502 }
1503}
1504
1505impl SourceFileHash {
1506 pub fn new_in_memory(kind: SourceFileHashAlgorithm, src: impl AsRef<[u8]>) -> SourceFileHash {
1507 let mut hash = SourceFileHash { kind, value: Default::default() };
1508 let len = hash.hash_len();
1509 let value = &mut hash.value[..len];
1510 let data = src.as_ref();
1511 match kind {
1512 SourceFileHashAlgorithm::Md5 => {
1513 value.copy_from_slice(&Md5::digest(data));
1514 }
1515 SourceFileHashAlgorithm::Sha1 => {
1516 value.copy_from_slice(&Sha1::digest(data));
1517 }
1518 SourceFileHashAlgorithm::Sha256 => {
1519 value.copy_from_slice(&Sha256::digest(data));
1520 }
1521 SourceFileHashAlgorithm::Blake3 => value.copy_from_slice(blake3::hash(data).as_bytes()),
1522 };
1523 hash
1524 }
1525
1526 pub fn new(kind: SourceFileHashAlgorithm, src: impl Read) -> Result<SourceFileHash, io::Error> {
1527 let mut hash = SourceFileHash { kind, value: Default::default() };
1528 let len = hash.hash_len();
1529 let value = &mut hash.value[..len];
1530 let mut buf = vec![0; 16 * 1024];
1533
1534 fn digest<T>(
1535 mut hasher: T,
1536 mut update: impl FnMut(&mut T, &[u8]),
1537 finish: impl FnOnce(T, &mut [u8]),
1538 mut src: impl Read,
1539 buf: &mut [u8],
1540 value: &mut [u8],
1541 ) -> Result<(), io::Error> {
1542 loop {
1543 let bytes_read = src.read(buf)?;
1544 if bytes_read == 0 {
1545 break;
1546 }
1547 update(&mut hasher, &buf[0..bytes_read]);
1548 }
1549 finish(hasher, value);
1550 Ok(())
1551 }
1552
1553 match kind {
1554 SourceFileHashAlgorithm::Sha256 => {
1555 digest(
1556 Sha256::new(),
1557 |h, b| {
1558 h.update(b);
1559 },
1560 |h, out| out.copy_from_slice(&h.finalize()),
1561 src,
1562 &mut buf,
1563 value,
1564 )?;
1565 }
1566 SourceFileHashAlgorithm::Sha1 => {
1567 digest(
1568 Sha1::new(),
1569 |h, b| {
1570 h.update(b);
1571 },
1572 |h, out| out.copy_from_slice(&h.finalize()),
1573 src,
1574 &mut buf,
1575 value,
1576 )?;
1577 }
1578 SourceFileHashAlgorithm::Md5 => {
1579 digest(
1580 Md5::new(),
1581 |h, b| {
1582 h.update(b);
1583 },
1584 |h, out| out.copy_from_slice(&h.finalize()),
1585 src,
1586 &mut buf,
1587 value,
1588 )?;
1589 }
1590 SourceFileHashAlgorithm::Blake3 => {
1591 digest(
1592 blake3::Hasher::new(),
1593 |h, b| {
1594 h.update(b);
1595 },
1596 |h, out| out.copy_from_slice(h.finalize().as_bytes()),
1597 src,
1598 &mut buf,
1599 value,
1600 )?;
1601 }
1602 }
1603 Ok(hash)
1604 }
1605
1606 pub fn matches(&self, src: &str) -> bool {
1608 Self::new_in_memory(self.kind, src.as_bytes()) == *self
1609 }
1610
1611 pub fn hash_bytes(&self) -> &[u8] {
1613 let len = self.hash_len();
1614 &self.value[..len]
1615 }
1616
1617 fn hash_len(&self) -> usize {
1618 match self.kind {
1619 SourceFileHashAlgorithm::Md5 => 16,
1620 SourceFileHashAlgorithm::Sha1 => 20,
1621 SourceFileHashAlgorithm::Sha256 | SourceFileHashAlgorithm::Blake3 => 32,
1622 }
1623 }
1624}
1625
1626#[derive(Clone)]
1627pub enum SourceFileLines {
1628 Lines(Vec<RelativeBytePos>),
1630
1631 Diffs(SourceFileDiffs),
1633}
1634
1635impl SourceFileLines {
1636 pub fn is_lines(&self) -> bool {
1637 matches!(self, SourceFileLines::Lines(_))
1638 }
1639}
1640
1641#[derive(Clone)]
1649pub struct SourceFileDiffs {
1650 bytes_per_diff: usize,
1654
1655 num_diffs: usize,
1658
1659 raw_diffs: Vec<u8>,
1665}
1666
1667pub struct SourceFile {
1669 pub name: FileName,
1673 pub src: Option<Arc<String>>,
1675 pub src_hash: SourceFileHash,
1677 pub checksum_hash: Option<SourceFileHash>,
1681 pub external_src: FreezeLock<ExternalSource>,
1684 pub start_pos: BytePos,
1686 pub source_len: RelativeBytePos,
1688 pub lines: FreezeLock<SourceFileLines>,
1690 pub multibyte_chars: Vec<MultiByteChar>,
1692 pub normalized_pos: Vec<NormalizedPos>,
1694 pub stable_id: StableSourceFileId,
1698 pub cnum: CrateNum,
1700}
1701
1702impl Clone for SourceFile {
1703 fn clone(&self) -> Self {
1704 Self {
1705 name: self.name.clone(),
1706 src: self.src.clone(),
1707 src_hash: self.src_hash,
1708 checksum_hash: self.checksum_hash,
1709 external_src: self.external_src.clone(),
1710 start_pos: self.start_pos,
1711 source_len: self.source_len,
1712 lines: self.lines.clone(),
1713 multibyte_chars: self.multibyte_chars.clone(),
1714 normalized_pos: self.normalized_pos.clone(),
1715 stable_id: self.stable_id,
1716 cnum: self.cnum,
1717 }
1718 }
1719}
1720
1721impl<S: SpanEncoder> Encodable<S> for SourceFile {
1722 fn encode(&self, s: &mut S) {
1723 self.name.encode(s);
1724 self.src_hash.encode(s);
1725 self.checksum_hash.encode(s);
1726 self.source_len.encode(s);
1728
1729 assert!(self.lines.read().is_lines());
1731 let lines = self.lines();
1732 s.emit_u32(lines.len() as u32);
1734
1735 if lines.len() != 0 {
1737 let max_line_length = if lines.len() == 1 {
1738 0
1739 } else {
1740 lines
1741 .array_windows()
1742 .map(|&[fst, snd]| snd - fst)
1743 .map(|bp| bp.to_usize())
1744 .max()
1745 .unwrap()
1746 };
1747
1748 let bytes_per_diff: usize = match max_line_length {
1749 0..=0xFF => 1,
1750 0x100..=0xFFFF => 2,
1751 _ => 4,
1752 };
1753
1754 s.emit_u8(bytes_per_diff as u8);
1756
1757 assert_eq!(lines[0], RelativeBytePos(0));
1759
1760 let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst);
1762 let num_diffs = lines.len() - 1;
1763 let mut raw_diffs;
1764 match bytes_per_diff {
1765 1 => {
1766 raw_diffs = Vec::with_capacity(num_diffs);
1767 for diff in diff_iter {
1768 raw_diffs.push(diff.0 as u8);
1769 }
1770 }
1771 2 => {
1772 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
1773 for diff in diff_iter {
1774 raw_diffs.extend_from_slice(&(diff.0 as u16).to_le_bytes());
1775 }
1776 }
1777 4 => {
1778 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
1779 for diff in diff_iter {
1780 raw_diffs.extend_from_slice(&(diff.0).to_le_bytes());
1781 }
1782 }
1783 _ => unreachable!(),
1784 }
1785 s.emit_raw_bytes(&raw_diffs);
1786 }
1787
1788 self.multibyte_chars.encode(s);
1789 self.stable_id.encode(s);
1790 self.normalized_pos.encode(s);
1791 self.cnum.encode(s);
1792 }
1793}
1794
1795impl<D: SpanDecoder> Decodable<D> for SourceFile {
1796 fn decode(d: &mut D) -> SourceFile {
1797 let name: FileName = Decodable::decode(d);
1798 let src_hash: SourceFileHash = Decodable::decode(d);
1799 let checksum_hash: Option<SourceFileHash> = Decodable::decode(d);
1800 let source_len: RelativeBytePos = Decodable::decode(d);
1801 let lines = {
1802 let num_lines: u32 = Decodable::decode(d);
1803 if num_lines > 0 {
1804 let bytes_per_diff = d.read_u8() as usize;
1806
1807 let num_diffs = num_lines as usize - 1;
1809 let raw_diffs = d.read_raw_bytes(bytes_per_diff * num_diffs).to_vec();
1810 SourceFileLines::Diffs(SourceFileDiffs { bytes_per_diff, num_diffs, raw_diffs })
1811 } else {
1812 SourceFileLines::Lines(vec![])
1813 }
1814 };
1815 let multibyte_chars: Vec<MultiByteChar> = Decodable::decode(d);
1816 let stable_id = Decodable::decode(d);
1817 let normalized_pos: Vec<NormalizedPos> = Decodable::decode(d);
1818 let cnum: CrateNum = Decodable::decode(d);
1819 SourceFile {
1820 name,
1821 start_pos: BytePos::from_u32(0),
1822 source_len,
1823 src: None,
1824 src_hash,
1825 checksum_hash,
1826 external_src: FreezeLock::frozen(ExternalSource::Unneeded),
1829 lines: FreezeLock::new(lines),
1830 multibyte_chars,
1831 normalized_pos,
1832 stable_id,
1833 cnum,
1834 }
1835 }
1836}
1837
1838impl fmt::Debug for SourceFile {
1839 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1840 write!(fmt, "SourceFile({:?})", self.name)
1841 }
1842}
1843
1844#[derive(
1866 Debug,
1867 Clone,
1868 Copy,
1869 Hash,
1870 PartialEq,
1871 Eq,
1872 HashStable_Generic,
1873 Encodable,
1874 Decodable,
1875 Default,
1876 PartialOrd,
1877 Ord
1878)]
1879pub struct StableSourceFileId(Hash128);
1880
1881impl StableSourceFileId {
1882 fn from_filename_in_current_crate(filename: &FileName) -> Self {
1883 Self::from_filename_and_stable_crate_id(filename, None)
1884 }
1885
1886 pub fn from_filename_for_export(
1887 filename: &FileName,
1888 local_crate_stable_crate_id: StableCrateId,
1889 ) -> Self {
1890 Self::from_filename_and_stable_crate_id(filename, Some(local_crate_stable_crate_id))
1891 }
1892
1893 fn from_filename_and_stable_crate_id(
1894 filename: &FileName,
1895 stable_crate_id: Option<StableCrateId>,
1896 ) -> Self {
1897 let mut hasher = StableHasher::new();
1898 filename.hash(&mut hasher);
1899 stable_crate_id.hash(&mut hasher);
1900 StableSourceFileId(hasher.finish())
1901 }
1902}
1903
1904impl SourceFile {
1905 const MAX_FILE_SIZE: u32 = u32::MAX - 1;
1906
1907 pub fn new(
1908 name: FileName,
1909 mut src: String,
1910 hash_kind: SourceFileHashAlgorithm,
1911 checksum_hash_kind: Option<SourceFileHashAlgorithm>,
1912 ) -> Result<Self, OffsetOverflowError> {
1913 let src_hash = SourceFileHash::new_in_memory(hash_kind, src.as_bytes());
1915 let checksum_hash = checksum_hash_kind.map(|checksum_hash_kind| {
1916 if checksum_hash_kind == hash_kind {
1917 src_hash
1918 } else {
1919 SourceFileHash::new_in_memory(checksum_hash_kind, src.as_bytes())
1920 }
1921 });
1922 let normalized_pos = normalize_src(&mut src);
1923
1924 let stable_id = StableSourceFileId::from_filename_in_current_crate(&name);
1925 let source_len = src.len();
1926 let source_len = u32::try_from(source_len).map_err(|_| OffsetOverflowError)?;
1927 if source_len > Self::MAX_FILE_SIZE {
1928 return Err(OffsetOverflowError);
1929 }
1930
1931 let (lines, multibyte_chars) = analyze_source_file::analyze_source_file(&src);
1932
1933 Ok(SourceFile {
1934 name,
1935 src: Some(Arc::new(src)),
1936 src_hash,
1937 checksum_hash,
1938 external_src: FreezeLock::frozen(ExternalSource::Unneeded),
1939 start_pos: BytePos::from_u32(0),
1940 source_len: RelativeBytePos::from_u32(source_len),
1941 lines: FreezeLock::frozen(SourceFileLines::Lines(lines)),
1942 multibyte_chars,
1943 normalized_pos,
1944 stable_id,
1945 cnum: LOCAL_CRATE,
1946 })
1947 }
1948
1949 fn convert_diffs_to_lines_frozen(&self) {
1952 let mut guard = if let Some(guard) = self.lines.try_write() { guard } else { return };
1953
1954 let SourceFileDiffs { bytes_per_diff, num_diffs, raw_diffs } = match &*guard {
1955 SourceFileLines::Diffs(diffs) => diffs,
1956 SourceFileLines::Lines(..) => {
1957 FreezeWriteGuard::freeze(guard);
1958 return;
1959 }
1960 };
1961
1962 let num_lines = num_diffs + 1;
1964 let mut lines = Vec::with_capacity(num_lines);
1965 let mut line_start = RelativeBytePos(0);
1966 lines.push(line_start);
1967
1968 assert_eq!(*num_diffs, raw_diffs.len() / bytes_per_diff);
1969 match bytes_per_diff {
1970 1 => {
1971 lines.extend(raw_diffs.into_iter().map(|&diff| {
1972 line_start = line_start + RelativeBytePos(diff as u32);
1973 line_start
1974 }));
1975 }
1976 2 => {
1977 lines.extend((0..*num_diffs).map(|i| {
1978 let pos = bytes_per_diff * i;
1979 let bytes = [raw_diffs[pos], raw_diffs[pos + 1]];
1980 let diff = u16::from_le_bytes(bytes);
1981 line_start = line_start + RelativeBytePos(diff as u32);
1982 line_start
1983 }));
1984 }
1985 4 => {
1986 lines.extend((0..*num_diffs).map(|i| {
1987 let pos = bytes_per_diff * i;
1988 let bytes = [
1989 raw_diffs[pos],
1990 raw_diffs[pos + 1],
1991 raw_diffs[pos + 2],
1992 raw_diffs[pos + 3],
1993 ];
1994 let diff = u32::from_le_bytes(bytes);
1995 line_start = line_start + RelativeBytePos(diff);
1996 line_start
1997 }));
1998 }
1999 _ => unreachable!(),
2000 }
2001
2002 *guard = SourceFileLines::Lines(lines);
2003
2004 FreezeWriteGuard::freeze(guard);
2005 }
2006
2007 pub fn lines(&self) -> &[RelativeBytePos] {
2008 if let Some(SourceFileLines::Lines(lines)) = self.lines.get() {
2009 return &lines[..];
2010 }
2011
2012 outline(|| {
2013 self.convert_diffs_to_lines_frozen();
2014 if let Some(SourceFileLines::Lines(lines)) = self.lines.get() {
2015 return &lines[..];
2016 }
2017 unreachable!()
2018 })
2019 }
2020
2021 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
2023 let pos = self.relative_position(pos);
2024 let line_index = self.lookup_line(pos).unwrap();
2025 let line_start_pos = self.lines()[line_index];
2026 self.absolute_position(line_start_pos)
2027 }
2028
2029 pub fn add_external_src<F>(&self, get_src: F) -> bool
2034 where
2035 F: FnOnce() -> Option<String>,
2036 {
2037 if !self.external_src.is_frozen() {
2038 let src = get_src();
2039 let src = src.and_then(|mut src| {
2040 self.src_hash.matches(&src).then(|| {
2042 normalize_src(&mut src);
2043 src
2044 })
2045 });
2046
2047 self.external_src.try_write().map(|mut external_src| {
2048 if let ExternalSource::Foreign {
2049 kind: src_kind @ ExternalSourceKind::AbsentOk,
2050 ..
2051 } = &mut *external_src
2052 {
2053 *src_kind = if let Some(src) = src {
2054 ExternalSourceKind::Present(Arc::new(src))
2055 } else {
2056 ExternalSourceKind::AbsentErr
2057 };
2058 } else {
2059 panic!("unexpected state {:?}", *external_src)
2060 }
2061
2062 FreezeWriteGuard::freeze(external_src)
2064 });
2065 }
2066
2067 self.src.is_some() || self.external_src.read().get_source().is_some()
2068 }
2069
2070 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
2073 fn get_until_newline(src: &str, begin: usize) -> &str {
2074 let slice = &src[begin..];
2078 match slice.find('\n') {
2079 Some(e) => &slice[..e],
2080 None => slice,
2081 }
2082 }
2083
2084 let begin = {
2085 let line = self.lines().get(line_number).copied()?;
2086 line.to_usize()
2087 };
2088
2089 if let Some(ref src) = self.src {
2090 Some(Cow::from(get_until_newline(src, begin)))
2091 } else {
2092 self.external_src
2093 .borrow()
2094 .get_source()
2095 .map(|src| Cow::Owned(String::from(get_until_newline(src, begin))))
2096 }
2097 }
2098
2099 pub fn is_real_file(&self) -> bool {
2100 self.name.is_real()
2101 }
2102
2103 #[inline]
2104 pub fn is_imported(&self) -> bool {
2105 self.src.is_none()
2106 }
2107
2108 pub fn count_lines(&self) -> usize {
2109 self.lines().len()
2110 }
2111
2112 #[inline]
2113 pub fn absolute_position(&self, pos: RelativeBytePos) -> BytePos {
2114 BytePos::from_u32(pos.to_u32() + self.start_pos.to_u32())
2115 }
2116
2117 #[inline]
2118 pub fn relative_position(&self, pos: BytePos) -> RelativeBytePos {
2119 RelativeBytePos::from_u32(pos.to_u32() - self.start_pos.to_u32())
2120 }
2121
2122 #[inline]
2123 pub fn end_position(&self) -> BytePos {
2124 self.absolute_position(self.source_len)
2125 }
2126
2127 pub fn lookup_line(&self, pos: RelativeBytePos) -> Option<usize> {
2132 self.lines().partition_point(|x| x <= &pos).checked_sub(1)
2133 }
2134
2135 pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
2136 if self.is_empty() {
2137 return self.start_pos..self.start_pos;
2138 }
2139
2140 let lines = self.lines();
2141 assert!(line_index < lines.len());
2142 if line_index == (lines.len() - 1) {
2143 self.absolute_position(lines[line_index])..self.end_position()
2144 } else {
2145 self.absolute_position(lines[line_index])..self.absolute_position(lines[line_index + 1])
2146 }
2147 }
2148
2149 #[inline]
2154 pub fn contains(&self, byte_pos: BytePos) -> bool {
2155 byte_pos >= self.start_pos && byte_pos <= self.end_position()
2156 }
2157
2158 #[inline]
2159 pub fn is_empty(&self) -> bool {
2160 self.source_len.to_u32() == 0
2161 }
2162
2163 pub fn original_relative_byte_pos(&self, pos: BytePos) -> RelativeBytePos {
2166 let pos = self.relative_position(pos);
2167
2168 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
2172 Ok(i) => self.normalized_pos[i].diff,
2173 Err(0) => 0,
2174 Err(i) => self.normalized_pos[i - 1].diff,
2175 };
2176
2177 RelativeBytePos::from_u32(pos.0 + diff)
2178 }
2179
2180 pub fn normalized_byte_pos(&self, offset: u32) -> BytePos {
2190 let diff = match self
2191 .normalized_pos
2192 .binary_search_by(|np| (np.pos.0 + np.diff).cmp(&(self.start_pos.0 + offset)))
2193 {
2194 Ok(i) => self.normalized_pos[i].diff,
2195 Err(0) => 0,
2196 Err(i) => self.normalized_pos[i - 1].diff,
2197 };
2198
2199 BytePos::from_u32(self.start_pos.0 + offset - diff)
2200 }
2201
2202 fn bytepos_to_file_charpos(&self, bpos: RelativeBytePos) -> CharPos {
2204 let mut total_extra_bytes = 0;
2206
2207 for mbc in self.multibyte_chars.iter() {
2208 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
2209 if mbc.pos < bpos {
2210 total_extra_bytes += mbc.bytes as u32 - 1;
2213 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
2216 } else {
2217 break;
2218 }
2219 }
2220
2221 assert!(total_extra_bytes <= bpos.to_u32());
2222 CharPos(bpos.to_usize() - total_extra_bytes as usize)
2223 }
2224
2225 fn lookup_file_pos(&self, pos: RelativeBytePos) -> (usize, CharPos) {
2228 let chpos = self.bytepos_to_file_charpos(pos);
2229 match self.lookup_line(pos) {
2230 Some(a) => {
2231 let line = a + 1; let linebpos = self.lines()[a];
2233 let linechpos = self.bytepos_to_file_charpos(linebpos);
2234 let col = chpos - linechpos;
2235 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
2236 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
2237 debug!("byte is on line: {}", line);
2238 assert!(chpos >= linechpos);
2239 (line, col)
2240 }
2241 None => (0, chpos),
2242 }
2243 }
2244
2245 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
2248 let pos = self.relative_position(pos);
2249 let (line, col_or_chpos) = self.lookup_file_pos(pos);
2250 if line > 0 {
2251 let Some(code) = self.get_line(line - 1) else {
2252 tracing::info!("couldn't find line {line} {:?}", self.name);
2260 return (line, col_or_chpos, col_or_chpos.0);
2261 };
2262 let display_col = code.chars().take(col_or_chpos.0).map(|ch| char_width(ch)).sum();
2263 (line, col_or_chpos, display_col)
2264 } else {
2265 (0, col_or_chpos, col_or_chpos.0)
2267 }
2268 }
2269}
2270
2271pub fn char_width(ch: char) -> usize {
2272 match ch {
2275 '\t' => 4,
2276 '\u{0000}' | '\u{0001}' | '\u{0002}' | '\u{0003}' | '\u{0004}' | '\u{0005}'
2280 | '\u{0006}' | '\u{0007}' | '\u{0008}' | '\u{000B}' | '\u{000C}' | '\u{000D}'
2281 | '\u{000E}' | '\u{000F}' | '\u{0010}' | '\u{0011}' | '\u{0012}' | '\u{0013}'
2282 | '\u{0014}' | '\u{0015}' | '\u{0016}' | '\u{0017}' | '\u{0018}' | '\u{0019}'
2283 | '\u{001A}' | '\u{001B}' | '\u{001C}' | '\u{001D}' | '\u{001E}' | '\u{001F}'
2284 | '\u{007F}' | '\u{202A}' | '\u{202B}' | '\u{202D}' | '\u{202E}' | '\u{2066}'
2285 | '\u{2067}' | '\u{2068}' | '\u{202C}' | '\u{2069}' => 1,
2286 _ => unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1),
2287 }
2288}
2289
2290pub fn str_width(s: &str) -> usize {
2291 s.chars().map(char_width).sum()
2292}
2293
2294fn normalize_src(src: &mut String) -> Vec<NormalizedPos> {
2296 let mut normalized_pos = vec![];
2297 remove_bom(src, &mut normalized_pos);
2298 normalize_newlines(src, &mut normalized_pos);
2299 normalized_pos
2300}
2301
2302fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
2304 if src.starts_with('\u{feff}') {
2305 src.drain(..3);
2306 normalized_pos.push(NormalizedPos { pos: RelativeBytePos(0), diff: 3 });
2307 }
2308}
2309
2310fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
2314 if !src.as_bytes().contains(&b'\r') {
2315 return;
2316 }
2317
2318 let mut buf = std::mem::replace(src, String::new()).into_bytes();
2324 let mut gap_len = 0;
2325 let mut tail = buf.as_mut_slice();
2326 let mut cursor = 0;
2327 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
2328 loop {
2329 let idx = match find_crlf(&tail[gap_len..]) {
2330 None => tail.len(),
2331 Some(idx) => idx + gap_len,
2332 };
2333 tail.copy_within(gap_len..idx, 0);
2334 tail = &mut tail[idx - gap_len..];
2335 if tail.len() == gap_len {
2336 break;
2337 }
2338 cursor += idx - gap_len;
2339 gap_len += 1;
2340 normalized_pos.push(NormalizedPos {
2341 pos: RelativeBytePos::from_usize(cursor + 1),
2342 diff: original_gap + gap_len as u32,
2343 });
2344 }
2345
2346 let new_len = buf.len() - gap_len;
2349 unsafe {
2350 buf.set_len(new_len);
2351 *src = String::from_utf8_unchecked(buf);
2352 }
2353
2354 fn find_crlf(src: &[u8]) -> Option<usize> {
2355 let mut search_idx = 0;
2356 while let Some(idx) = find_cr(&src[search_idx..]) {
2357 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
2358 search_idx += idx + 1;
2359 continue;
2360 }
2361 return Some(search_idx + idx);
2362 }
2363 None
2364 }
2365
2366 fn find_cr(src: &[u8]) -> Option<usize> {
2367 src.iter().position(|&b| b == b'\r')
2368 }
2369}
2370
2371pub trait Pos {
2376 fn from_usize(n: usize) -> Self;
2377 fn to_usize(&self) -> usize;
2378 fn from_u32(n: u32) -> Self;
2379 fn to_u32(&self) -> u32;
2380}
2381
2382macro_rules! impl_pos {
2383 (
2384 $(
2385 $(#[$attr:meta])*
2386 $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
2387 )*
2388 ) => {
2389 $(
2390 $(#[$attr])*
2391 $vis struct $ident($inner_vis $inner_ty);
2392
2393 impl Pos for $ident {
2394 #[inline(always)]
2395 fn from_usize(n: usize) -> $ident {
2396 $ident(n as $inner_ty)
2397 }
2398
2399 #[inline(always)]
2400 fn to_usize(&self) -> usize {
2401 self.0 as usize
2402 }
2403
2404 #[inline(always)]
2405 fn from_u32(n: u32) -> $ident {
2406 $ident(n as $inner_ty)
2407 }
2408
2409 #[inline(always)]
2410 fn to_u32(&self) -> u32 {
2411 self.0 as u32
2412 }
2413 }
2414
2415 impl Add for $ident {
2416 type Output = $ident;
2417
2418 #[inline(always)]
2419 fn add(self, rhs: $ident) -> $ident {
2420 $ident(self.0 + rhs.0)
2421 }
2422 }
2423
2424 impl Sub for $ident {
2425 type Output = $ident;
2426
2427 #[inline(always)]
2428 fn sub(self, rhs: $ident) -> $ident {
2429 $ident(self.0 - rhs.0)
2430 }
2431 }
2432 )*
2433 };
2434}
2435
2436impl_pos! {
2437 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
2441 pub struct BytePos(pub u32);
2442
2443 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
2445 pub struct RelativeBytePos(pub u32);
2446
2447 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
2453 pub struct CharPos(pub usize);
2454}
2455
2456impl<S: Encoder> Encodable<S> for BytePos {
2457 fn encode(&self, s: &mut S) {
2458 s.emit_u32(self.0);
2459 }
2460}
2461
2462impl<D: Decoder> Decodable<D> for BytePos {
2463 fn decode(d: &mut D) -> BytePos {
2464 BytePos(d.read_u32())
2465 }
2466}
2467
2468impl<H: HashStableContext> HashStable<H> for RelativeBytePos {
2469 fn hash_stable(&self, hcx: &mut H, hasher: &mut StableHasher) {
2470 self.0.hash_stable(hcx, hasher);
2471 }
2472}
2473
2474impl<S: Encoder> Encodable<S> for RelativeBytePos {
2475 fn encode(&self, s: &mut S) {
2476 s.emit_u32(self.0);
2477 }
2478}
2479
2480impl<D: Decoder> Decodable<D> for RelativeBytePos {
2481 fn decode(d: &mut D) -> RelativeBytePos {
2482 RelativeBytePos(d.read_u32())
2483 }
2484}
2485
2486#[derive(Debug, Clone)]
2492pub struct Loc {
2493 pub file: Arc<SourceFile>,
2495 pub line: usize,
2497 pub col: CharPos,
2499 pub col_display: usize,
2501}
2502
2503#[derive(Debug)]
2505pub struct SourceFileAndLine {
2506 pub sf: Arc<SourceFile>,
2507 pub line: usize,
2509}
2510#[derive(Debug)]
2511pub struct SourceFileAndBytePos {
2512 pub sf: Arc<SourceFile>,
2513 pub pos: BytePos,
2514}
2515
2516#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2517pub struct LineInfo {
2518 pub line_index: usize,
2520
2521 pub start_col: CharPos,
2523
2524 pub end_col: CharPos,
2526}
2527
2528pub struct FileLines {
2529 pub file: Arc<SourceFile>,
2530 pub lines: Vec<LineInfo>,
2531}
2532
2533pub static SPAN_TRACK: AtomicRef<fn(LocalDefId)> = AtomicRef::new(&((|_| {}) as fn(_)));
2534
2535pub type FileLinesResult = Result<FileLines, SpanLinesError>;
2540
2541#[derive(Clone, PartialEq, Eq, Debug)]
2542pub enum SpanLinesError {
2543 DistinctSources(Box<DistinctSources>),
2544}
2545
2546#[derive(Clone, PartialEq, Eq, Debug)]
2547pub enum SpanSnippetError {
2548 IllFormedSpan(Span),
2549 DistinctSources(Box<DistinctSources>),
2550 MalformedForSourcemap(MalformedSourceMapPositions),
2551 SourceNotAvailable { filename: FileName },
2552}
2553
2554#[derive(Clone, PartialEq, Eq, Debug)]
2555pub struct DistinctSources {
2556 pub begin: (FileName, BytePos),
2557 pub end: (FileName, BytePos),
2558}
2559
2560#[derive(Clone, PartialEq, Eq, Debug)]
2561pub struct MalformedSourceMapPositions {
2562 pub name: FileName,
2563 pub source_len: usize,
2564 pub begin_pos: BytePos,
2565 pub end_pos: BytePos,
2566}
2567
2568#[derive(Copy, Clone, PartialEq, Eq, Debug)]
2570pub struct InnerSpan {
2571 pub start: usize,
2572 pub end: usize,
2573}
2574
2575impl InnerSpan {
2576 pub fn new(start: usize, end: usize) -> InnerSpan {
2577 InnerSpan { start, end }
2578 }
2579}
2580
2581pub trait HashStableContext {
2586 fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
2587 fn hash_spans(&self) -> bool;
2588 fn unstable_opts_incremental_ignore_spans(&self) -> bool;
2591 fn def_span(&self, def_id: LocalDefId) -> Span;
2592 fn span_data_to_lines_and_cols(
2593 &mut self,
2594 span: &SpanData,
2595 ) -> Option<(Arc<SourceFile>, usize, BytePos, usize, BytePos)>;
2596 fn hashing_controls(&self) -> HashingControls;
2597}
2598
2599impl<CTX> HashStable<CTX> for Span
2600where
2601 CTX: HashStableContext,
2602{
2603 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
2614 const TAG_VALID_SPAN: u8 = 0;
2615 const TAG_INVALID_SPAN: u8 = 1;
2616 const TAG_RELATIVE_SPAN: u8 = 2;
2617
2618 if !ctx.hash_spans() {
2619 return;
2620 }
2621
2622 let span = self.data_untracked();
2623 span.ctxt.hash_stable(ctx, hasher);
2624 span.parent.hash_stable(ctx, hasher);
2625
2626 if span.is_dummy() {
2627 Hash::hash(&TAG_INVALID_SPAN, hasher);
2628 return;
2629 }
2630
2631 if let Some(parent) = span.parent {
2632 let def_span = ctx.def_span(parent).data_untracked();
2633 if def_span.contains(span) {
2634 Hash::hash(&TAG_RELATIVE_SPAN, hasher);
2636 (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher);
2637 (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher);
2638 return;
2639 }
2640 }
2641
2642 let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span)
2646 else {
2647 Hash::hash(&TAG_INVALID_SPAN, hasher);
2648 return;
2649 };
2650
2651 Hash::hash(&TAG_VALID_SPAN, hasher);
2652 Hash::hash(&file.stable_id, hasher);
2653
2654 let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
2664 let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
2665 let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
2666 let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
2667 let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
2668 let len = (span.hi - span.lo).0;
2669 Hash::hash(&col_line, hasher);
2670 Hash::hash(&len, hasher);
2671 }
2672}
2673
2674#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
2680#[derive(HashStable_Generic)]
2681pub struct ErrorGuaranteed(());
2682
2683impl ErrorGuaranteed {
2684 #[deprecated = "should only be used in `DiagCtxtInner::emit_diagnostic`"]
2686 pub fn unchecked_error_guaranteed() -> Self {
2687 ErrorGuaranteed(())
2688 }
2689
2690 pub fn raise_fatal(self) -> ! {
2691 FatalError.raise()
2692 }
2693}
2694
2695impl<E: rustc_serialize::Encoder> Encodable<E> for ErrorGuaranteed {
2696 #[inline]
2697 fn encode(&self, _e: &mut E) {
2698 panic!(
2699 "should never serialize an `ErrorGuaranteed`, as we do not write metadata or \
2700 incremental caches in case errors occurred"
2701 )
2702 }
2703}
2704impl<D: rustc_serialize::Decoder> Decodable<D> for ErrorGuaranteed {
2705 #[inline]
2706 fn decode(_d: &mut D) -> ErrorGuaranteed {
2707 panic!(
2708 "`ErrorGuaranteed` should never have been serialized to metadata or incremental caches"
2709 )
2710 }
2711}