1#![allow(internal_features)]
20#![cfg_attr(bootstrap, feature(array_windows))]
21#![cfg_attr(target_arch = "loongarch64", feature(stdarch_loongarch))]
22#![feature(cfg_select)]
23#![feature(core_io_borrowed_buf)]
24#![feature(if_let_guard)]
25#![feature(map_try_insert)]
26#![feature(negative_impls)]
27#![feature(read_buf)]
28#![feature(rustc_attrs)]
29extern crate self as rustc_span;
35
36use derive_where::derive_where;
37use rustc_data_structures::{AtomicRef, outline};
38use rustc_macros::{Decodable, Encodable, HashStable_Generic};
39use rustc_serialize::opaque::{FileEncoder, MemDecoder};
40use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
41use tracing::debug;
42
43mod caching_source_map_view;
44pub mod source_map;
45use source_map::{SourceMap, SourceMapInputs};
46
47pub use self::caching_source_map_view::CachingSourceMapView;
48use crate::fatal_error::FatalError;
49
50pub mod edition;
51use edition::Edition;
52pub mod hygiene;
53use hygiene::Transparency;
54pub use hygiene::{
55 DesugaringKind, ExpnData, ExpnHash, ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext,
56};
57use rustc_data_structures::stable_hasher::HashingControls;
58pub mod def_id;
59use def_id::{CrateNum, DefId, DefIndex, DefPathHash, LOCAL_CRATE, LocalDefId, StableCrateId};
60pub mod edit_distance;
61mod span_encoding;
62pub use span_encoding::{DUMMY_SP, Span};
63
64pub mod symbol;
65pub use symbol::{
66 ByteSymbol, Ident, MacroRulesNormalizedIdent, Macros20NormalizedIdent, STDLIB_STABLE_CRATES,
67 Symbol, kw, sym,
68};
69
70mod analyze_source_file;
71pub mod fatal_error;
72
73pub mod profiling;
74
75use std::borrow::Cow;
76use std::cmp::{self, Ordering};
77use std::fmt::Display;
78use std::hash::Hash;
79use std::io::{self, Read};
80use std::ops::{Add, Range, Sub};
81use std::path::{Path, PathBuf};
82use std::str::FromStr;
83use std::sync::Arc;
84use std::{fmt, iter};
85
86use md5::{Digest, Md5};
87use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
88use rustc_data_structures::sync::{FreezeLock, FreezeWriteGuard, Lock};
89use rustc_data_structures::unord::UnordMap;
90use rustc_hashes::{Hash64, Hash128};
91use sha1::Sha1;
92use sha2::Sha256;
93
94#[cfg(test)]
95mod tests;
96
97pub struct SessionGlobals {
102 symbol_interner: symbol::Interner,
103 span_interner: Lock<span_encoding::SpanInterner>,
104 metavar_spans: MetavarSpansMap,
107 hygiene_data: Lock<hygiene::HygieneData>,
108
109 source_map: Option<Arc<SourceMap>>,
113}
114
115impl SessionGlobals {
116 pub fn new(
117 edition: Edition,
118 extra_symbols: &[&'static str],
119 sm_inputs: Option<SourceMapInputs>,
120 ) -> SessionGlobals {
121 SessionGlobals {
122 symbol_interner: symbol::Interner::with_extra_symbols(extra_symbols),
123 span_interner: Lock::new(span_encoding::SpanInterner::default()),
124 metavar_spans: Default::default(),
125 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
126 source_map: sm_inputs.map(|inputs| Arc::new(SourceMap::with_inputs(inputs))),
127 }
128 }
129}
130
131pub fn create_session_globals_then<R>(
132 edition: Edition,
133 extra_symbols: &[&'static str],
134 sm_inputs: Option<SourceMapInputs>,
135 f: impl FnOnce() -> R,
136) -> R {
137 assert!(
138 !SESSION_GLOBALS.is_set(),
139 "SESSION_GLOBALS should never be overwritten! \
140 Use another thread if you need another SessionGlobals"
141 );
142 let session_globals = SessionGlobals::new(edition, extra_symbols, sm_inputs);
143 SESSION_GLOBALS.set(&session_globals, f)
144}
145
146pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R {
147 assert!(
148 !SESSION_GLOBALS.is_set(),
149 "SESSION_GLOBALS should never be overwritten! \
150 Use another thread if you need another SessionGlobals"
151 );
152 SESSION_GLOBALS.set(session_globals, f)
153}
154
155pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R
157where
158 F: FnOnce(&SessionGlobals) -> R,
159{
160 if !SESSION_GLOBALS.is_set() {
161 let session_globals = SessionGlobals::new(edition, &[], None);
162 SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f))
163 } else {
164 SESSION_GLOBALS.with(f)
165 }
166}
167
168#[inline]
169pub fn with_session_globals<R, F>(f: F) -> R
170where
171 F: FnOnce(&SessionGlobals) -> R,
172{
173 SESSION_GLOBALS.with(f)
174}
175
176pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R {
178 create_session_globals_then(edition::DEFAULT_EDITION, &[], None, f)
179}
180
181scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals);
185
186#[derive(Default)]
187pub struct MetavarSpansMap(FreezeLock<UnordMap<Span, (Span, bool)>>);
188
189impl MetavarSpansMap {
190 pub fn insert(&self, span: Span, var_span: Span) -> bool {
191 match self.0.write().try_insert(span, (var_span, false)) {
192 Ok(_) => true,
193 Err(entry) => entry.entry.get().0 == var_span,
194 }
195 }
196
197 pub fn get(&self, span: Span) -> Option<Span> {
199 if let Some(mut mspans) = self.0.try_write() {
200 if let Some((var_span, read)) = mspans.get_mut(&span) {
201 *read = true;
202 Some(*var_span)
203 } else {
204 None
205 }
206 } else {
207 if let Some((span, true)) = self.0.read().get(&span) { Some(*span) } else { None }
208 }
209 }
210
211 pub fn freeze_and_get_read_spans(&self) -> UnordMap<Span, Span> {
215 self.0.freeze().items().filter(|(_, (_, b))| *b).map(|(s1, (s2, _))| (*s1, *s2)).collect()
216 }
217}
218
219#[inline]
220pub fn with_metavar_spans<R>(f: impl FnOnce(&MetavarSpansMap) -> R) -> R {
221 with_session_globals(|session_globals| f(&session_globals.metavar_spans))
222}
223
224bitflags::bitflags! {
225 #[derive(Debug, Eq, PartialEq, Clone, Copy, Ord, PartialOrd, Hash)]
227 pub struct RemapPathScopeComponents: u8 {
228 const MACRO = 1 << 0;
230 const DIAGNOSTICS = 1 << 1;
232 const DEBUGINFO = 1 << 3;
234 const COVERAGE = 1 << 4;
236
237 const OBJECT = Self::MACRO.bits() | Self::DEBUGINFO.bits() | Self::COVERAGE.bits();
240 }
241}
242
243impl<E: Encoder> Encodable<E> for RemapPathScopeComponents {
244 #[inline]
245 fn encode(&self, s: &mut E) {
246 s.emit_u8(self.bits());
247 }
248}
249
250impl<D: Decoder> Decodable<D> for RemapPathScopeComponents {
251 #[inline]
252 fn decode(s: &mut D) -> RemapPathScopeComponents {
253 RemapPathScopeComponents::from_bits(s.read_u8())
254 .expect("invalid bits for RemapPathScopeComponents")
255 }
256}
257
258#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Decodable, Encodable)]
290pub struct RealFileName {
291 local: Option<InnerRealFileName>,
293 maybe_remapped: InnerRealFileName,
295 scopes: RemapPathScopeComponents,
297}
298
299#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Decodable, Encodable, Hash)]
303struct InnerRealFileName {
304 name: PathBuf,
306 working_directory: PathBuf,
308 embeddable_name: PathBuf,
310}
311
312impl Hash for RealFileName {
313 #[inline]
314 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
315 if !self.was_fully_remapped() {
320 self.local.hash(state);
321 }
322 self.maybe_remapped.hash(state);
323 self.scopes.bits().hash(state);
324 }
325}
326
327impl RealFileName {
328 #[inline]
334 pub fn path(&self, scope: RemapPathScopeComponents) -> &Path {
335 assert!(
336 scope.bits().count_ones() == 1,
337 "one and only one scope should be passed to `RealFileName::path`: {scope:?}"
338 );
339 if !self.scopes.contains(scope)
340 && let Some(local_name) = &self.local
341 {
342 local_name.name.as_path()
343 } else {
344 self.maybe_remapped.name.as_path()
345 }
346 }
347
348 #[inline]
359 pub fn embeddable_name(&self, scope: RemapPathScopeComponents) -> (&Path, &Path) {
360 assert!(
361 scope.bits().count_ones() == 1,
362 "one and only one scope should be passed to `RealFileName::embeddable_path`: {scope:?}"
363 );
364 if !self.scopes.contains(scope)
365 && let Some(local_name) = &self.local
366 {
367 (&local_name.working_directory, &local_name.embeddable_name)
368 } else {
369 (&self.maybe_remapped.working_directory, &self.maybe_remapped.embeddable_name)
370 }
371 }
372
373 #[inline]
380 pub fn local_path(&self) -> Option<&Path> {
381 if self.was_not_remapped() {
382 Some(&self.maybe_remapped.name)
383 } else if let Some(local) = &self.local {
384 Some(&local.name)
385 } else {
386 None
387 }
388 }
389
390 #[inline]
397 pub fn into_local_path(self) -> Option<PathBuf> {
398 if self.was_not_remapped() {
399 Some(self.maybe_remapped.name)
400 } else if let Some(local) = self.local {
401 Some(local.name)
402 } else {
403 None
404 }
405 }
406
407 #[inline]
409 pub(crate) fn was_remapped(&self) -> bool {
410 !self.scopes.is_empty()
411 }
412
413 #[inline]
415 fn was_fully_remapped(&self) -> bool {
416 self.scopes.is_all()
417 }
418
419 #[inline]
421 fn was_not_remapped(&self) -> bool {
422 self.scopes.is_empty()
423 }
424
425 #[inline]
429 pub fn empty() -> RealFileName {
430 RealFileName {
431 local: Some(InnerRealFileName {
432 name: PathBuf::new(),
433 working_directory: PathBuf::new(),
434 embeddable_name: PathBuf::new(),
435 }),
436 maybe_remapped: InnerRealFileName {
437 name: PathBuf::new(),
438 working_directory: PathBuf::new(),
439 embeddable_name: PathBuf::new(),
440 },
441 scopes: RemapPathScopeComponents::empty(),
442 }
443 }
444
445 pub fn from_virtual_path(path: &Path) -> RealFileName {
449 let name = InnerRealFileName {
450 name: path.to_owned(),
451 embeddable_name: path.to_owned(),
452 working_directory: PathBuf::new(),
453 };
454 RealFileName { local: None, maybe_remapped: name, scopes: RemapPathScopeComponents::all() }
455 }
456
457 #[inline]
462 pub fn update_for_crate_metadata(&mut self) {
463 if self.was_fully_remapped() || self.was_not_remapped() {
464 self.local = None;
469 }
470 }
471
472 fn to_string_lossy<'a>(&'a self, display_pref: FileNameDisplayPreference) -> Cow<'a, str> {
476 match display_pref {
477 FileNameDisplayPreference::Remapped => self.maybe_remapped.name.to_string_lossy(),
478 FileNameDisplayPreference::Local => {
479 self.local.as_ref().unwrap_or(&self.maybe_remapped).name.to_string_lossy()
480 }
481 FileNameDisplayPreference::Short => self
482 .maybe_remapped
483 .name
484 .file_name()
485 .map_or_else(|| "".into(), |f| f.to_string_lossy()),
486 FileNameDisplayPreference::Scope(scope) => self.path(scope).to_string_lossy(),
487 }
488 }
489}
490
491#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, Decodable, Encodable)]
493pub enum FileName {
494 Real(RealFileName),
495 CfgSpec(Hash64),
497 Anon(Hash64),
499 MacroExpansion(Hash64),
502 ProcMacroSourceCode(Hash64),
503 CliCrateAttr(Hash64),
505 Custom(String),
507 DocTest(PathBuf, isize),
508 InlineAsm(Hash64),
510}
511
512pub struct FileNameDisplay<'a> {
513 inner: &'a FileName,
514 display_pref: FileNameDisplayPreference,
515}
516
517#[derive(Clone, Copy)]
519enum FileNameDisplayPreference {
520 Remapped,
521 Local,
522 Short,
523 Scope(RemapPathScopeComponents),
524}
525
526impl fmt::Display for FileNameDisplay<'_> {
527 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
528 use FileName::*;
529 match *self.inner {
530 Real(ref name) => {
531 write!(fmt, "{}", name.to_string_lossy(self.display_pref))
532 }
533 CfgSpec(_) => write!(fmt, "<cfgspec>"),
534 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
535 Anon(_) => write!(fmt, "<anon>"),
536 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
537 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
538 Custom(ref s) => write!(fmt, "<{s}>"),
539 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
540 InlineAsm(_) => write!(fmt, "<inline asm>"),
541 }
542 }
543}
544
545impl<'a> FileNameDisplay<'a> {
546 pub fn to_string_lossy(&self) -> Cow<'a, str> {
547 match self.inner {
548 FileName::Real(inner) => inner.to_string_lossy(self.display_pref),
549 _ => Cow::from(self.to_string()),
550 }
551 }
552}
553
554impl FileName {
555 pub fn is_real(&self) -> bool {
556 use FileName::*;
557 match *self {
558 Real(_) => true,
559 Anon(_)
560 | MacroExpansion(_)
561 | ProcMacroSourceCode(_)
562 | CliCrateAttr(_)
563 | Custom(_)
564 | CfgSpec(_)
565 | DocTest(_, _)
566 | InlineAsm(_) => false,
567 }
568 }
569
570 #[inline]
575 pub fn prefer_remapped_unconditionally(&self) -> FileNameDisplay<'_> {
576 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped }
577 }
578
579 #[inline]
584 pub fn prefer_local_unconditionally(&self) -> FileNameDisplay<'_> {
585 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local }
586 }
587
588 #[inline]
590 pub fn short(&self) -> FileNameDisplay<'_> {
591 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Short }
592 }
593
594 #[inline]
596 pub fn display(&self, scope: RemapPathScopeComponents) -> FileNameDisplay<'_> {
597 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Scope(scope) }
598 }
599
600 pub fn macro_expansion_source_code(src: &str) -> FileName {
601 let mut hasher = StableHasher::new();
602 src.hash(&mut hasher);
603 FileName::MacroExpansion(hasher.finish())
604 }
605
606 pub fn anon_source_code(src: &str) -> FileName {
607 let mut hasher = StableHasher::new();
608 src.hash(&mut hasher);
609 FileName::Anon(hasher.finish())
610 }
611
612 pub fn proc_macro_source_code(src: &str) -> FileName {
613 let mut hasher = StableHasher::new();
614 src.hash(&mut hasher);
615 FileName::ProcMacroSourceCode(hasher.finish())
616 }
617
618 pub fn cfg_spec_source_code(src: &str) -> FileName {
619 let mut hasher = StableHasher::new();
620 src.hash(&mut hasher);
621 FileName::CfgSpec(hasher.finish())
622 }
623
624 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
625 let mut hasher = StableHasher::new();
626 src.hash(&mut hasher);
627 FileName::CliCrateAttr(hasher.finish())
628 }
629
630 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
631 FileName::DocTest(path, line)
632 }
633
634 pub fn inline_asm_source_code(src: &str) -> FileName {
635 let mut hasher = StableHasher::new();
636 src.hash(&mut hasher);
637 FileName::InlineAsm(hasher.finish())
638 }
639
640 pub fn into_local_path(self) -> Option<PathBuf> {
645 match self {
646 FileName::Real(path) => path.into_local_path(),
647 FileName::DocTest(path, _) => Some(path),
648 _ => None,
649 }
650 }
651}
652
653#[derive(Clone, Copy, Hash, PartialEq, Eq)]
669#[derive_where(PartialOrd, Ord)]
670pub struct SpanData {
671 pub lo: BytePos,
672 pub hi: BytePos,
673 #[derive_where(skip)]
676 pub ctxt: SyntaxContext,
679 #[derive_where(skip)]
680 pub parent: Option<LocalDefId>,
683}
684
685impl SpanData {
686 #[inline]
687 pub fn span(&self) -> Span {
688 Span::new(self.lo, self.hi, self.ctxt, self.parent)
689 }
690 #[inline]
691 pub fn with_lo(&self, lo: BytePos) -> Span {
692 Span::new(lo, self.hi, self.ctxt, self.parent)
693 }
694 #[inline]
695 pub fn with_hi(&self, hi: BytePos) -> Span {
696 Span::new(self.lo, hi, self.ctxt, self.parent)
697 }
698 #[inline]
700 fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
701 Span::new(self.lo, self.hi, ctxt, self.parent)
702 }
703 #[inline]
705 fn with_parent(&self, parent: Option<LocalDefId>) -> Span {
706 Span::new(self.lo, self.hi, self.ctxt, parent)
707 }
708 #[inline]
710 pub fn is_dummy(self) -> bool {
711 self.lo.0 == 0 && self.hi.0 == 0
712 }
713 pub fn contains(self, other: Self) -> bool {
715 self.lo <= other.lo && other.hi <= self.hi
716 }
717}
718
719impl Default for SpanData {
720 fn default() -> Self {
721 Self { lo: BytePos(0), hi: BytePos(0), ctxt: SyntaxContext::root(), parent: None }
722 }
723}
724
725impl PartialOrd for Span {
726 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
727 PartialOrd::partial_cmp(&self.data(), &rhs.data())
728 }
729}
730impl Ord for Span {
731 fn cmp(&self, rhs: &Self) -> Ordering {
732 Ord::cmp(&self.data(), &rhs.data())
733 }
734}
735
736impl Span {
737 #[inline]
738 pub fn lo(self) -> BytePos {
739 self.data().lo
740 }
741 #[inline]
742 pub fn with_lo(self, lo: BytePos) -> Span {
743 self.data().with_lo(lo)
744 }
745 #[inline]
746 pub fn hi(self) -> BytePos {
747 self.data().hi
748 }
749 #[inline]
750 pub fn with_hi(self, hi: BytePos) -> Span {
751 self.data().with_hi(hi)
752 }
753 #[inline]
754 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
755 self.map_ctxt(|_| ctxt)
756 }
757
758 #[inline]
759 pub fn is_visible(self, sm: &SourceMap) -> bool {
760 !self.is_dummy() && sm.is_span_accessible(self)
761 }
762
763 #[inline]
768 pub fn in_external_macro(self, sm: &SourceMap) -> bool {
769 self.ctxt().in_external_macro(sm)
770 }
771
772 pub fn in_derive_expansion(self) -> bool {
774 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
775 }
776
777 pub fn is_from_async_await(self) -> bool {
779 matches!(
780 self.ctxt().outer_expn_data().kind,
781 ExpnKind::Desugaring(DesugaringKind::Async | DesugaringKind::Await),
782 )
783 }
784
785 pub fn can_be_used_for_suggestions(self) -> bool {
787 !self.from_expansion()
788 || (self.in_derive_expansion()
792 && self.parent_callsite().map(|p| (p.lo(), p.hi())) != Some((self.lo(), self.hi())))
793 }
794
795 #[inline]
796 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
797 Span::new(lo, hi, SyntaxContext::root(), None)
798 }
799
800 #[inline]
802 pub fn shrink_to_lo(self) -> Span {
803 let span = self.data_untracked();
804 span.with_hi(span.lo)
805 }
806 #[inline]
808 pub fn shrink_to_hi(self) -> Span {
809 let span = self.data_untracked();
810 span.with_lo(span.hi)
811 }
812
813 #[inline]
814 pub fn is_empty(self) -> bool {
816 let span = self.data_untracked();
817 span.hi == span.lo
818 }
819
820 pub fn substitute_dummy(self, other: Span) -> Span {
822 if self.is_dummy() { other } else { self }
823 }
824
825 pub fn contains(self, other: Span) -> bool {
827 let span = self.data();
828 let other = other.data();
829 span.contains(other)
830 }
831
832 pub fn overlaps(self, other: Span) -> bool {
834 let span = self.data();
835 let other = other.data();
836 span.lo < other.hi && other.lo < span.hi
837 }
838
839 pub fn overlaps_or_adjacent(self, other: Span) -> bool {
841 let span = self.data();
842 let other = other.data();
843 span.lo <= other.hi && other.lo <= span.hi
844 }
845
846 pub fn source_equal(self, other: Span) -> bool {
851 let span = self.data();
852 let other = other.data();
853 span.lo == other.lo && span.hi == other.hi
854 }
855
856 pub fn trim_start(self, other: Span) -> Option<Span> {
858 let span = self.data();
859 let other = other.data();
860 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
861 }
862
863 pub fn trim_end(self, other: Span) -> Option<Span> {
865 let span = self.data();
866 let other = other.data();
867 if span.lo < other.lo { Some(span.with_hi(cmp::min(span.hi, other.lo))) } else { None }
868 }
869
870 pub fn source_callsite(self) -> Span {
873 let ctxt = self.ctxt();
874 if !ctxt.is_root() { ctxt.outer_expn_data().call_site.source_callsite() } else { self }
875 }
876
877 pub fn parent_callsite(self) -> Option<Span> {
880 let ctxt = self.ctxt();
881 (!ctxt.is_root()).then(|| ctxt.outer_expn_data().call_site)
882 }
883
884 pub fn find_ancestor_inside(mut self, outer: Span) -> Option<Span> {
897 while !outer.contains(self) {
898 self = self.parent_callsite()?;
899 }
900 Some(self)
901 }
902
903 pub fn find_ancestor_in_same_ctxt(mut self, other: Span) -> Option<Span> {
916 while !self.eq_ctxt(other) {
917 self = self.parent_callsite()?;
918 }
919 Some(self)
920 }
921
922 pub fn find_ancestor_inside_same_ctxt(mut self, outer: Span) -> Option<Span> {
935 while !outer.contains(self) || !self.eq_ctxt(outer) {
936 self = self.parent_callsite()?;
937 }
938 Some(self)
939 }
940
941 pub fn find_ancestor_not_from_extern_macro(mut self, sm: &SourceMap) -> Option<Span> {
955 while self.in_external_macro(sm) {
956 self = self.parent_callsite()?;
957 }
958 Some(self)
959 }
960
961 pub fn find_ancestor_not_from_macro(mut self) -> Option<Span> {
974 while self.from_expansion() {
975 self = self.parent_callsite()?;
976 }
977 Some(self)
978 }
979
980 pub fn edition(self) -> edition::Edition {
982 self.ctxt().edition()
983 }
984
985 #[inline]
987 pub fn is_rust_2015(self) -> bool {
988 self.edition().is_rust_2015()
989 }
990
991 #[inline]
993 pub fn at_least_rust_2018(self) -> bool {
994 self.edition().at_least_rust_2018()
995 }
996
997 #[inline]
999 pub fn at_least_rust_2021(self) -> bool {
1000 self.edition().at_least_rust_2021()
1001 }
1002
1003 #[inline]
1005 pub fn at_least_rust_2024(self) -> bool {
1006 self.edition().at_least_rust_2024()
1007 }
1008
1009 pub fn source_callee(self) -> Option<ExpnData> {
1015 let mut ctxt = self.ctxt();
1016 let mut opt_expn_data = None;
1017 while !ctxt.is_root() {
1018 let expn_data = ctxt.outer_expn_data();
1019 ctxt = expn_data.call_site.ctxt();
1020 opt_expn_data = Some(expn_data);
1021 }
1022 opt_expn_data
1023 }
1024
1025 pub fn allows_unstable(self, feature: Symbol) -> bool {
1029 self.ctxt()
1030 .outer_expn_data()
1031 .allow_internal_unstable
1032 .is_some_and(|features| features.contains(&feature))
1033 }
1034
1035 pub fn is_desugaring(self, kind: DesugaringKind) -> bool {
1037 match self.ctxt().outer_expn_data().kind {
1038 ExpnKind::Desugaring(k) => k == kind,
1039 _ => false,
1040 }
1041 }
1042
1043 pub fn desugaring_kind(self) -> Option<DesugaringKind> {
1046 match self.ctxt().outer_expn_data().kind {
1047 ExpnKind::Desugaring(k) => Some(k),
1048 _ => None,
1049 }
1050 }
1051
1052 pub fn allows_unsafe(self) -> bool {
1056 self.ctxt().outer_expn_data().allow_internal_unsafe
1057 }
1058
1059 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
1060 let mut prev_span = DUMMY_SP;
1061 iter::from_fn(move || {
1062 loop {
1063 let ctxt = self.ctxt();
1064 if ctxt.is_root() {
1065 return None;
1066 }
1067
1068 let expn_data = ctxt.outer_expn_data();
1069 let is_recursive = expn_data.call_site.source_equal(prev_span);
1070
1071 prev_span = self;
1072 self = expn_data.call_site;
1073
1074 if !is_recursive {
1076 return Some(expn_data);
1077 }
1078 }
1079 })
1080 }
1081
1082 pub fn split_at(self, pos: u32) -> (Span, Span) {
1084 let len = self.hi().0 - self.lo().0;
1085 debug_assert!(pos <= len);
1086
1087 let split_pos = BytePos(self.lo().0 + pos);
1088 (
1089 Span::new(self.lo(), split_pos, self.ctxt(), self.parent()),
1090 Span::new(split_pos, self.hi(), self.ctxt(), self.parent()),
1091 )
1092 }
1093
1094 fn try_metavars(a: SpanData, b: SpanData, a_orig: Span, b_orig: Span) -> (SpanData, SpanData) {
1096 match with_metavar_spans(|mspans| (mspans.get(a_orig), mspans.get(b_orig))) {
1097 (None, None) => {}
1098 (Some(meta_a), None) => {
1099 let meta_a = meta_a.data();
1100 if meta_a.ctxt == b.ctxt {
1101 return (meta_a, b);
1102 }
1103 }
1104 (None, Some(meta_b)) => {
1105 let meta_b = meta_b.data();
1106 if a.ctxt == meta_b.ctxt {
1107 return (a, meta_b);
1108 }
1109 }
1110 (Some(meta_a), Some(meta_b)) => {
1111 let meta_b = meta_b.data();
1112 if a.ctxt == meta_b.ctxt {
1113 return (a, meta_b);
1114 }
1115 let meta_a = meta_a.data();
1116 if meta_a.ctxt == b.ctxt {
1117 return (meta_a, b);
1118 } else if meta_a.ctxt == meta_b.ctxt {
1119 return (meta_a, meta_b);
1120 }
1121 }
1122 }
1123
1124 (a, b)
1125 }
1126
1127 fn prepare_to_combine(
1129 a_orig: Span,
1130 b_orig: Span,
1131 ) -> Result<(SpanData, SpanData, Option<LocalDefId>), Span> {
1132 let (a, b) = (a_orig.data(), b_orig.data());
1133 if a.ctxt == b.ctxt {
1134 return Ok((a, b, if a.parent == b.parent { a.parent } else { None }));
1135 }
1136
1137 let (a, b) = Span::try_metavars(a, b, a_orig, b_orig);
1138 if a.ctxt == b.ctxt {
1139 return Ok((a, b, if a.parent == b.parent { a.parent } else { None }));
1140 }
1141
1142 let a_is_callsite = a.ctxt.is_root() || a.ctxt == b.span().source_callsite().ctxt();
1150 Err(if a_is_callsite { b_orig } else { a_orig })
1151 }
1152
1153 pub fn with_neighbor(self, neighbor: Span) -> Span {
1155 match Span::prepare_to_combine(self, neighbor) {
1156 Ok((this, ..)) => this.span(),
1157 Err(_) => self,
1158 }
1159 }
1160
1161 pub fn to(self, end: Span) -> Span {
1172 match Span::prepare_to_combine(self, end) {
1173 Ok((from, to, parent)) => {
1174 Span::new(cmp::min(from.lo, to.lo), cmp::max(from.hi, to.hi), from.ctxt, parent)
1175 }
1176 Err(fallback) => fallback,
1177 }
1178 }
1179
1180 pub fn between(self, end: Span) -> Span {
1188 match Span::prepare_to_combine(self, end) {
1189 Ok((from, to, parent)) => {
1190 Span::new(cmp::min(from.hi, to.hi), cmp::max(from.lo, to.lo), from.ctxt, parent)
1191 }
1192 Err(fallback) => fallback,
1193 }
1194 }
1195
1196 pub fn until(self, end: Span) -> Span {
1204 match Span::prepare_to_combine(self, end) {
1205 Ok((from, to, parent)) => {
1206 Span::new(cmp::min(from.lo, to.lo), cmp::max(from.lo, to.lo), from.ctxt, parent)
1207 }
1208 Err(fallback) => fallback,
1209 }
1210 }
1211
1212 pub fn within_macro(self, within: Span, sm: &SourceMap) -> Option<Span> {
1227 match Span::prepare_to_combine(self, within) {
1228 Ok((self_, _, parent))
1235 if self_.hi < self.lo() || self.hi() < self_.lo && !sm.is_imported(within) =>
1236 {
1237 Some(Span::new(self_.lo, self_.hi, self_.ctxt, parent))
1238 }
1239 _ => None,
1240 }
1241 }
1242
1243 pub fn from_inner(self, inner: InnerSpan) -> Span {
1244 let span = self.data();
1245 Span::new(
1246 span.lo + BytePos::from_usize(inner.start),
1247 span.lo + BytePos::from_usize(inner.end),
1248 span.ctxt,
1249 span.parent,
1250 )
1251 }
1252
1253 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
1256 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
1257 }
1258
1259 pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span {
1262 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
1263 }
1264
1265 pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span {
1268 self.with_ctxt_from_mark(expn_id, Transparency::SemiOpaque)
1269 }
1270
1271 fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
1275 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
1276 }
1277
1278 #[inline]
1279 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
1280 self.map_ctxt(|ctxt| ctxt.apply_mark(expn_id, transparency))
1281 }
1282
1283 #[inline]
1284 pub fn remove_mark(&mut self) -> ExpnId {
1285 let mut mark = ExpnId::root();
1286 *self = self.map_ctxt(|mut ctxt| {
1287 mark = ctxt.remove_mark();
1288 ctxt
1289 });
1290 mark
1291 }
1292
1293 #[inline]
1294 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
1295 let mut mark = None;
1296 *self = self.map_ctxt(|mut ctxt| {
1297 mark = ctxt.adjust(expn_id);
1298 ctxt
1299 });
1300 mark
1301 }
1302
1303 #[inline]
1304 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
1305 let mut mark = None;
1306 *self = self.map_ctxt(|mut ctxt| {
1307 mark = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
1308 ctxt
1309 });
1310 mark
1311 }
1312
1313 #[inline]
1314 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
1315 let mut mark = None;
1316 *self = self.map_ctxt(|mut ctxt| {
1317 mark = ctxt.glob_adjust(expn_id, glob_span);
1318 ctxt
1319 });
1320 mark
1321 }
1322
1323 #[inline]
1324 pub fn reverse_glob_adjust(
1325 &mut self,
1326 expn_id: ExpnId,
1327 glob_span: Span,
1328 ) -> Option<Option<ExpnId>> {
1329 let mut mark = None;
1330 *self = self.map_ctxt(|mut ctxt| {
1331 mark = ctxt.reverse_glob_adjust(expn_id, glob_span);
1332 ctxt
1333 });
1334 mark
1335 }
1336
1337 #[inline]
1338 pub fn normalize_to_macros_2_0(self) -> Span {
1339 self.map_ctxt(|ctxt| ctxt.normalize_to_macros_2_0())
1340 }
1341
1342 #[inline]
1343 pub fn normalize_to_macro_rules(self) -> Span {
1344 self.map_ctxt(|ctxt| ctxt.normalize_to_macro_rules())
1345 }
1346}
1347
1348impl Default for Span {
1349 fn default() -> Self {
1350 DUMMY_SP
1351 }
1352}
1353
1354rustc_index::newtype_index! {
1355 #[orderable]
1356 #[debug_format = "AttrId({})"]
1357 pub struct AttrId {}
1358}
1359
1360pub trait SpanEncoder: Encoder {
1363 fn encode_span(&mut self, span: Span);
1364 fn encode_symbol(&mut self, sym: Symbol);
1365 fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol);
1366 fn encode_expn_id(&mut self, expn_id: ExpnId);
1367 fn encode_syntax_context(&mut self, syntax_context: SyntaxContext);
1368 fn encode_crate_num(&mut self, crate_num: CrateNum);
1371 fn encode_def_index(&mut self, def_index: DefIndex);
1372 fn encode_def_id(&mut self, def_id: DefId);
1373}
1374
1375impl SpanEncoder for FileEncoder {
1376 fn encode_span(&mut self, span: Span) {
1377 let span = span.data();
1378 span.lo.encode(self);
1379 span.hi.encode(self);
1380 }
1381
1382 fn encode_symbol(&mut self, sym: Symbol) {
1383 self.emit_str(sym.as_str());
1384 }
1385
1386 fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
1387 self.emit_byte_str(byte_sym.as_byte_str());
1388 }
1389
1390 fn encode_expn_id(&mut self, _expn_id: ExpnId) {
1391 panic!("cannot encode `ExpnId` with `FileEncoder`");
1392 }
1393
1394 fn encode_syntax_context(&mut self, _syntax_context: SyntaxContext) {
1395 panic!("cannot encode `SyntaxContext` with `FileEncoder`");
1396 }
1397
1398 fn encode_crate_num(&mut self, crate_num: CrateNum) {
1399 self.emit_u32(crate_num.as_u32());
1400 }
1401
1402 fn encode_def_index(&mut self, _def_index: DefIndex) {
1403 panic!("cannot encode `DefIndex` with `FileEncoder`");
1404 }
1405
1406 fn encode_def_id(&mut self, def_id: DefId) {
1407 def_id.krate.encode(self);
1408 def_id.index.encode(self);
1409 }
1410}
1411
1412impl<E: SpanEncoder> Encodable<E> for Span {
1413 fn encode(&self, s: &mut E) {
1414 s.encode_span(*self);
1415 }
1416}
1417
1418impl<E: SpanEncoder> Encodable<E> for Symbol {
1419 fn encode(&self, s: &mut E) {
1420 s.encode_symbol(*self);
1421 }
1422}
1423
1424impl<E: SpanEncoder> Encodable<E> for ByteSymbol {
1425 fn encode(&self, s: &mut E) {
1426 s.encode_byte_symbol(*self);
1427 }
1428}
1429
1430impl<E: SpanEncoder> Encodable<E> for ExpnId {
1431 fn encode(&self, s: &mut E) {
1432 s.encode_expn_id(*self)
1433 }
1434}
1435
1436impl<E: SpanEncoder> Encodable<E> for SyntaxContext {
1437 fn encode(&self, s: &mut E) {
1438 s.encode_syntax_context(*self)
1439 }
1440}
1441
1442impl<E: SpanEncoder> Encodable<E> for CrateNum {
1443 fn encode(&self, s: &mut E) {
1444 s.encode_crate_num(*self)
1445 }
1446}
1447
1448impl<E: SpanEncoder> Encodable<E> for DefIndex {
1449 fn encode(&self, s: &mut E) {
1450 s.encode_def_index(*self)
1451 }
1452}
1453
1454impl<E: SpanEncoder> Encodable<E> for DefId {
1455 fn encode(&self, s: &mut E) {
1456 s.encode_def_id(*self)
1457 }
1458}
1459
1460impl<E: SpanEncoder> Encodable<E> for AttrId {
1461 fn encode(&self, _s: &mut E) {
1462 }
1464}
1465
1466pub trait BlobDecoder: Decoder {
1467 fn decode_symbol(&mut self) -> Symbol;
1468 fn decode_byte_symbol(&mut self) -> ByteSymbol;
1469 fn decode_def_index(&mut self) -> DefIndex;
1470}
1471
1472pub trait SpanDecoder: BlobDecoder {
1489 fn decode_span(&mut self) -> Span;
1490 fn decode_expn_id(&mut self) -> ExpnId;
1491 fn decode_syntax_context(&mut self) -> SyntaxContext;
1492 fn decode_crate_num(&mut self) -> CrateNum;
1493 fn decode_def_id(&mut self) -> DefId;
1494 fn decode_attr_id(&mut self) -> AttrId;
1495}
1496
1497impl BlobDecoder for MemDecoder<'_> {
1498 fn decode_symbol(&mut self) -> Symbol {
1499 Symbol::intern(self.read_str())
1500 }
1501
1502 fn decode_byte_symbol(&mut self) -> ByteSymbol {
1503 ByteSymbol::intern(self.read_byte_str())
1504 }
1505
1506 fn decode_def_index(&mut self) -> DefIndex {
1507 panic!("cannot decode `DefIndex` with `MemDecoder`");
1508 }
1509}
1510
1511impl SpanDecoder for MemDecoder<'_> {
1512 fn decode_span(&mut self) -> Span {
1513 let lo = Decodable::decode(self);
1514 let hi = Decodable::decode(self);
1515
1516 Span::new(lo, hi, SyntaxContext::root(), None)
1517 }
1518
1519 fn decode_expn_id(&mut self) -> ExpnId {
1520 panic!("cannot decode `ExpnId` with `MemDecoder`");
1521 }
1522
1523 fn decode_syntax_context(&mut self) -> SyntaxContext {
1524 panic!("cannot decode `SyntaxContext` with `MemDecoder`");
1525 }
1526
1527 fn decode_crate_num(&mut self) -> CrateNum {
1528 CrateNum::from_u32(self.read_u32())
1529 }
1530
1531 fn decode_def_id(&mut self) -> DefId {
1532 DefId { krate: Decodable::decode(self), index: Decodable::decode(self) }
1533 }
1534
1535 fn decode_attr_id(&mut self) -> AttrId {
1536 panic!("cannot decode `AttrId` with `MemDecoder`");
1537 }
1538}
1539
1540impl<D: SpanDecoder> Decodable<D> for Span {
1541 fn decode(s: &mut D) -> Span {
1542 s.decode_span()
1543 }
1544}
1545
1546impl<D: BlobDecoder> Decodable<D> for Symbol {
1547 fn decode(s: &mut D) -> Symbol {
1548 s.decode_symbol()
1549 }
1550}
1551
1552impl<D: BlobDecoder> Decodable<D> for ByteSymbol {
1553 fn decode(s: &mut D) -> ByteSymbol {
1554 s.decode_byte_symbol()
1555 }
1556}
1557
1558impl<D: SpanDecoder> Decodable<D> for ExpnId {
1559 fn decode(s: &mut D) -> ExpnId {
1560 s.decode_expn_id()
1561 }
1562}
1563
1564impl<D: SpanDecoder> Decodable<D> for SyntaxContext {
1565 fn decode(s: &mut D) -> SyntaxContext {
1566 s.decode_syntax_context()
1567 }
1568}
1569
1570impl<D: SpanDecoder> Decodable<D> for CrateNum {
1571 fn decode(s: &mut D) -> CrateNum {
1572 s.decode_crate_num()
1573 }
1574}
1575
1576impl<D: BlobDecoder> Decodable<D> for DefIndex {
1577 fn decode(s: &mut D) -> DefIndex {
1578 s.decode_def_index()
1579 }
1580}
1581
1582impl<D: SpanDecoder> Decodable<D> for DefId {
1583 fn decode(s: &mut D) -> DefId {
1584 s.decode_def_id()
1585 }
1586}
1587
1588impl<D: SpanDecoder> Decodable<D> for AttrId {
1589 fn decode(s: &mut D) -> AttrId {
1590 s.decode_attr_id()
1591 }
1592}
1593
1594impl fmt::Debug for Span {
1595 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1596 fn fallback(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1600 f.debug_struct("Span")
1601 .field("lo", &span.lo())
1602 .field("hi", &span.hi())
1603 .field("ctxt", &span.ctxt())
1604 .finish()
1605 }
1606
1607 if SESSION_GLOBALS.is_set() {
1608 with_session_globals(|session_globals| {
1609 if let Some(source_map) = &session_globals.source_map {
1610 write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(*self), self.ctxt())
1611 } else {
1612 fallback(*self, f)
1613 }
1614 })
1615 } else {
1616 fallback(*self, f)
1617 }
1618 }
1619}
1620
1621impl fmt::Debug for SpanData {
1622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1623 fmt::Debug::fmt(&self.span(), f)
1624 }
1625}
1626
1627#[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug, HashStable_Generic)]
1629pub struct MultiByteChar {
1630 pub pos: RelativeBytePos,
1632 pub bytes: u8,
1634}
1635
1636#[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug, HashStable_Generic)]
1638pub struct NormalizedPos {
1639 pub pos: RelativeBytePos,
1641 pub diff: u32,
1643}
1644
1645#[derive(PartialEq, Eq, Clone, Debug)]
1646pub enum ExternalSource {
1647 Unneeded,
1649 Foreign {
1650 kind: ExternalSourceKind,
1651 metadata_index: u32,
1653 },
1654}
1655
1656#[derive(PartialEq, Eq, Clone, Debug)]
1658pub enum ExternalSourceKind {
1659 Present(Arc<String>),
1661 AbsentOk,
1663 AbsentErr,
1665}
1666
1667impl ExternalSource {
1668 pub fn get_source(&self) -> Option<&str> {
1669 match self {
1670 ExternalSource::Foreign { kind: ExternalSourceKind::Present(src), .. } => Some(src),
1671 _ => None,
1672 }
1673 }
1674}
1675
1676#[derive(Debug)]
1677pub struct OffsetOverflowError;
1678
1679#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1680#[derive(HashStable_Generic)]
1681pub enum SourceFileHashAlgorithm {
1682 Md5,
1683 Sha1,
1684 Sha256,
1685 Blake3,
1686}
1687
1688impl Display for SourceFileHashAlgorithm {
1689 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1690 f.write_str(match self {
1691 Self::Md5 => "md5",
1692 Self::Sha1 => "sha1",
1693 Self::Sha256 => "sha256",
1694 Self::Blake3 => "blake3",
1695 })
1696 }
1697}
1698
1699impl FromStr for SourceFileHashAlgorithm {
1700 type Err = ();
1701
1702 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1703 match s {
1704 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1705 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1706 "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1707 "blake3" => Ok(SourceFileHashAlgorithm::Blake3),
1708 _ => Err(()),
1709 }
1710 }
1711}
1712
1713#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
1715#[derive(HashStable_Generic, Encodable, Decodable)]
1716pub struct SourceFileHash {
1717 pub kind: SourceFileHashAlgorithm,
1718 value: [u8; 32],
1719}
1720
1721impl Display for SourceFileHash {
1722 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1723 write!(f, "{}=", self.kind)?;
1724 for byte in self.value[0..self.hash_len()].into_iter() {
1725 write!(f, "{byte:02x}")?;
1726 }
1727 Ok(())
1728 }
1729}
1730
1731impl SourceFileHash {
1732 pub fn new_in_memory(kind: SourceFileHashAlgorithm, src: impl AsRef<[u8]>) -> SourceFileHash {
1733 let mut hash = SourceFileHash { kind, value: Default::default() };
1734 let len = hash.hash_len();
1735 let value = &mut hash.value[..len];
1736 let data = src.as_ref();
1737 match kind {
1738 SourceFileHashAlgorithm::Md5 => {
1739 value.copy_from_slice(&Md5::digest(data));
1740 }
1741 SourceFileHashAlgorithm::Sha1 => {
1742 value.copy_from_slice(&Sha1::digest(data));
1743 }
1744 SourceFileHashAlgorithm::Sha256 => {
1745 value.copy_from_slice(&Sha256::digest(data));
1746 }
1747 SourceFileHashAlgorithm::Blake3 => value.copy_from_slice(blake3::hash(data).as_bytes()),
1748 };
1749 hash
1750 }
1751
1752 pub fn new(kind: SourceFileHashAlgorithm, src: impl Read) -> Result<SourceFileHash, io::Error> {
1753 let mut hash = SourceFileHash { kind, value: Default::default() };
1754 let len = hash.hash_len();
1755 let value = &mut hash.value[..len];
1756 let mut buf = vec![0; 16 * 1024];
1759
1760 fn digest<T>(
1761 mut hasher: T,
1762 mut update: impl FnMut(&mut T, &[u8]),
1763 finish: impl FnOnce(T, &mut [u8]),
1764 mut src: impl Read,
1765 buf: &mut [u8],
1766 value: &mut [u8],
1767 ) -> Result<(), io::Error> {
1768 loop {
1769 let bytes_read = src.read(buf)?;
1770 if bytes_read == 0 {
1771 break;
1772 }
1773 update(&mut hasher, &buf[0..bytes_read]);
1774 }
1775 finish(hasher, value);
1776 Ok(())
1777 }
1778
1779 match kind {
1780 SourceFileHashAlgorithm::Sha256 => {
1781 digest(
1782 Sha256::new(),
1783 |h, b| {
1784 h.update(b);
1785 },
1786 |h, out| out.copy_from_slice(&h.finalize()),
1787 src,
1788 &mut buf,
1789 value,
1790 )?;
1791 }
1792 SourceFileHashAlgorithm::Sha1 => {
1793 digest(
1794 Sha1::new(),
1795 |h, b| {
1796 h.update(b);
1797 },
1798 |h, out| out.copy_from_slice(&h.finalize()),
1799 src,
1800 &mut buf,
1801 value,
1802 )?;
1803 }
1804 SourceFileHashAlgorithm::Md5 => {
1805 digest(
1806 Md5::new(),
1807 |h, b| {
1808 h.update(b);
1809 },
1810 |h, out| out.copy_from_slice(&h.finalize()),
1811 src,
1812 &mut buf,
1813 value,
1814 )?;
1815 }
1816 SourceFileHashAlgorithm::Blake3 => {
1817 digest(
1818 blake3::Hasher::new(),
1819 |h, b| {
1820 h.update(b);
1821 },
1822 |h, out| out.copy_from_slice(h.finalize().as_bytes()),
1823 src,
1824 &mut buf,
1825 value,
1826 )?;
1827 }
1828 }
1829 Ok(hash)
1830 }
1831
1832 pub fn matches(&self, src: &str) -> bool {
1834 Self::new_in_memory(self.kind, src.as_bytes()) == *self
1835 }
1836
1837 pub fn hash_bytes(&self) -> &[u8] {
1839 let len = self.hash_len();
1840 &self.value[..len]
1841 }
1842
1843 fn hash_len(&self) -> usize {
1844 match self.kind {
1845 SourceFileHashAlgorithm::Md5 => 16,
1846 SourceFileHashAlgorithm::Sha1 => 20,
1847 SourceFileHashAlgorithm::Sha256 | SourceFileHashAlgorithm::Blake3 => 32,
1848 }
1849 }
1850}
1851
1852#[derive(Clone)]
1853pub enum SourceFileLines {
1854 Lines(Vec<RelativeBytePos>),
1856
1857 Diffs(SourceFileDiffs),
1859}
1860
1861impl SourceFileLines {
1862 pub fn is_lines(&self) -> bool {
1863 matches!(self, SourceFileLines::Lines(_))
1864 }
1865}
1866
1867#[derive(Clone)]
1875pub struct SourceFileDiffs {
1876 bytes_per_diff: usize,
1880
1881 num_diffs: usize,
1884
1885 raw_diffs: Vec<u8>,
1891}
1892
1893pub struct SourceFile {
1895 pub name: FileName,
1899 pub src: Option<Arc<String>>,
1901 pub src_hash: SourceFileHash,
1903 pub checksum_hash: Option<SourceFileHash>,
1907 pub external_src: FreezeLock<ExternalSource>,
1910 pub start_pos: BytePos,
1912 pub normalized_source_len: RelativeBytePos,
1914 pub unnormalized_source_len: u32,
1916 pub lines: FreezeLock<SourceFileLines>,
1918 pub multibyte_chars: Vec<MultiByteChar>,
1920 pub normalized_pos: Vec<NormalizedPos>,
1922 pub stable_id: StableSourceFileId,
1926 pub cnum: CrateNum,
1928}
1929
1930impl Clone for SourceFile {
1931 fn clone(&self) -> Self {
1932 Self {
1933 name: self.name.clone(),
1934 src: self.src.clone(),
1935 src_hash: self.src_hash,
1936 checksum_hash: self.checksum_hash,
1937 external_src: self.external_src.clone(),
1938 start_pos: self.start_pos,
1939 normalized_source_len: self.normalized_source_len,
1940 unnormalized_source_len: self.unnormalized_source_len,
1941 lines: self.lines.clone(),
1942 multibyte_chars: self.multibyte_chars.clone(),
1943 normalized_pos: self.normalized_pos.clone(),
1944 stable_id: self.stable_id,
1945 cnum: self.cnum,
1946 }
1947 }
1948}
1949
1950impl<S: SpanEncoder> Encodable<S> for SourceFile {
1951 fn encode(&self, s: &mut S) {
1952 self.name.encode(s);
1953 self.src_hash.encode(s);
1954 self.checksum_hash.encode(s);
1955 self.normalized_source_len.encode(s);
1957 self.unnormalized_source_len.encode(s);
1958
1959 assert!(self.lines.read().is_lines());
1961 let lines = self.lines();
1962 s.emit_u32(lines.len() as u32);
1964
1965 if lines.len() != 0 {
1967 let max_line_length = if lines.len() == 1 {
1968 0
1969 } else {
1970 lines
1971 .array_windows()
1972 .map(|&[fst, snd]| snd - fst)
1973 .map(|bp| bp.to_usize())
1974 .max()
1975 .unwrap()
1976 };
1977
1978 let bytes_per_diff: usize = match max_line_length {
1979 0..=0xFF => 1,
1980 0x100..=0xFFFF => 2,
1981 _ => 4,
1982 };
1983
1984 s.emit_u8(bytes_per_diff as u8);
1986
1987 assert_eq!(lines[0], RelativeBytePos(0));
1989
1990 let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst);
1992 let num_diffs = lines.len() - 1;
1993 let mut raw_diffs;
1994 match bytes_per_diff {
1995 1 => {
1996 raw_diffs = Vec::with_capacity(num_diffs);
1997 for diff in diff_iter {
1998 raw_diffs.push(diff.0 as u8);
1999 }
2000 }
2001 2 => {
2002 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
2003 for diff in diff_iter {
2004 raw_diffs.extend_from_slice(&(diff.0 as u16).to_le_bytes());
2005 }
2006 }
2007 4 => {
2008 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
2009 for diff in diff_iter {
2010 raw_diffs.extend_from_slice(&(diff.0).to_le_bytes());
2011 }
2012 }
2013 _ => unreachable!(),
2014 }
2015 s.emit_raw_bytes(&raw_diffs);
2016 }
2017
2018 self.multibyte_chars.encode(s);
2019 self.stable_id.encode(s);
2020 self.normalized_pos.encode(s);
2021 self.cnum.encode(s);
2022 }
2023}
2024
2025impl<D: SpanDecoder> Decodable<D> for SourceFile {
2026 fn decode(d: &mut D) -> SourceFile {
2027 let name: FileName = Decodable::decode(d);
2028 let src_hash: SourceFileHash = Decodable::decode(d);
2029 let checksum_hash: Option<SourceFileHash> = Decodable::decode(d);
2030 let normalized_source_len: RelativeBytePos = Decodable::decode(d);
2031 let unnormalized_source_len = Decodable::decode(d);
2032 let lines = {
2033 let num_lines: u32 = Decodable::decode(d);
2034 if num_lines > 0 {
2035 let bytes_per_diff = d.read_u8() as usize;
2037
2038 let num_diffs = num_lines as usize - 1;
2040 let raw_diffs = d.read_raw_bytes(bytes_per_diff * num_diffs).to_vec();
2041 SourceFileLines::Diffs(SourceFileDiffs { bytes_per_diff, num_diffs, raw_diffs })
2042 } else {
2043 SourceFileLines::Lines(vec![])
2044 }
2045 };
2046 let multibyte_chars: Vec<MultiByteChar> = Decodable::decode(d);
2047 let stable_id = Decodable::decode(d);
2048 let normalized_pos: Vec<NormalizedPos> = Decodable::decode(d);
2049 let cnum: CrateNum = Decodable::decode(d);
2050 SourceFile {
2051 name,
2052 start_pos: BytePos::from_u32(0),
2053 normalized_source_len,
2054 unnormalized_source_len,
2055 src: None,
2056 src_hash,
2057 checksum_hash,
2058 external_src: FreezeLock::frozen(ExternalSource::Unneeded),
2061 lines: FreezeLock::new(lines),
2062 multibyte_chars,
2063 normalized_pos,
2064 stable_id,
2065 cnum,
2066 }
2067 }
2068}
2069
2070impl fmt::Debug for SourceFile {
2071 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2072 write!(fmt, "SourceFile({:?})", self.name)
2073 }
2074}
2075
2076#[derive(
2098 Debug,
2099 Clone,
2100 Copy,
2101 Hash,
2102 PartialEq,
2103 Eq,
2104 HashStable_Generic,
2105 Encodable,
2106 Decodable,
2107 Default,
2108 PartialOrd,
2109 Ord
2110)]
2111pub struct StableSourceFileId(Hash128);
2112
2113impl StableSourceFileId {
2114 fn from_filename_in_current_crate(filename: &FileName) -> Self {
2115 Self::from_filename_and_stable_crate_id(filename, None)
2116 }
2117
2118 pub fn from_filename_for_export(
2119 filename: &FileName,
2120 local_crate_stable_crate_id: StableCrateId,
2121 ) -> Self {
2122 Self::from_filename_and_stable_crate_id(filename, Some(local_crate_stable_crate_id))
2123 }
2124
2125 fn from_filename_and_stable_crate_id(
2126 filename: &FileName,
2127 stable_crate_id: Option<StableCrateId>,
2128 ) -> Self {
2129 let mut hasher = StableHasher::new();
2130 filename.hash(&mut hasher);
2131 stable_crate_id.hash(&mut hasher);
2132 StableSourceFileId(hasher.finish())
2133 }
2134}
2135
2136impl SourceFile {
2137 const MAX_FILE_SIZE: u32 = u32::MAX - 1;
2138
2139 pub fn new(
2140 name: FileName,
2141 mut src: String,
2142 hash_kind: SourceFileHashAlgorithm,
2143 checksum_hash_kind: Option<SourceFileHashAlgorithm>,
2144 ) -> Result<Self, OffsetOverflowError> {
2145 let src_hash = SourceFileHash::new_in_memory(hash_kind, src.as_bytes());
2147 let checksum_hash = checksum_hash_kind.map(|checksum_hash_kind| {
2148 if checksum_hash_kind == hash_kind {
2149 src_hash
2150 } else {
2151 SourceFileHash::new_in_memory(checksum_hash_kind, src.as_bytes())
2152 }
2153 });
2154 let unnormalized_source_len = u32::try_from(src.len()).map_err(|_| OffsetOverflowError)?;
2156 if unnormalized_source_len > Self::MAX_FILE_SIZE {
2157 return Err(OffsetOverflowError);
2158 }
2159
2160 let normalized_pos = normalize_src(&mut src);
2161
2162 let stable_id = StableSourceFileId::from_filename_in_current_crate(&name);
2163 let normalized_source_len = u32::try_from(src.len()).map_err(|_| OffsetOverflowError)?;
2164 if normalized_source_len > Self::MAX_FILE_SIZE {
2165 return Err(OffsetOverflowError);
2166 }
2167
2168 let (lines, multibyte_chars) = analyze_source_file::analyze_source_file(&src);
2169
2170 Ok(SourceFile {
2171 name,
2172 src: Some(Arc::new(src)),
2173 src_hash,
2174 checksum_hash,
2175 external_src: FreezeLock::frozen(ExternalSource::Unneeded),
2176 start_pos: BytePos::from_u32(0),
2177 normalized_source_len: RelativeBytePos::from_u32(normalized_source_len),
2178 unnormalized_source_len,
2179 lines: FreezeLock::frozen(SourceFileLines::Lines(lines)),
2180 multibyte_chars,
2181 normalized_pos,
2182 stable_id,
2183 cnum: LOCAL_CRATE,
2184 })
2185 }
2186
2187 fn convert_diffs_to_lines_frozen(&self) {
2190 let mut guard = if let Some(guard) = self.lines.try_write() { guard } else { return };
2191
2192 let SourceFileDiffs { bytes_per_diff, num_diffs, raw_diffs } = match &*guard {
2193 SourceFileLines::Diffs(diffs) => diffs,
2194 SourceFileLines::Lines(..) => {
2195 FreezeWriteGuard::freeze(guard);
2196 return;
2197 }
2198 };
2199
2200 let num_lines = num_diffs + 1;
2202 let mut lines = Vec::with_capacity(num_lines);
2203 let mut line_start = RelativeBytePos(0);
2204 lines.push(line_start);
2205
2206 assert_eq!(*num_diffs, raw_diffs.len() / bytes_per_diff);
2207 match bytes_per_diff {
2208 1 => {
2209 lines.extend(raw_diffs.into_iter().map(|&diff| {
2210 line_start = line_start + RelativeBytePos(diff as u32);
2211 line_start
2212 }));
2213 }
2214 2 => {
2215 lines.extend((0..*num_diffs).map(|i| {
2216 let pos = bytes_per_diff * i;
2217 let bytes = [raw_diffs[pos], raw_diffs[pos + 1]];
2218 let diff = u16::from_le_bytes(bytes);
2219 line_start = line_start + RelativeBytePos(diff as u32);
2220 line_start
2221 }));
2222 }
2223 4 => {
2224 lines.extend((0..*num_diffs).map(|i| {
2225 let pos = bytes_per_diff * i;
2226 let bytes = [
2227 raw_diffs[pos],
2228 raw_diffs[pos + 1],
2229 raw_diffs[pos + 2],
2230 raw_diffs[pos + 3],
2231 ];
2232 let diff = u32::from_le_bytes(bytes);
2233 line_start = line_start + RelativeBytePos(diff);
2234 line_start
2235 }));
2236 }
2237 _ => unreachable!(),
2238 }
2239
2240 *guard = SourceFileLines::Lines(lines);
2241
2242 FreezeWriteGuard::freeze(guard);
2243 }
2244
2245 pub fn lines(&self) -> &[RelativeBytePos] {
2246 if let Some(SourceFileLines::Lines(lines)) = self.lines.get() {
2247 return &lines[..];
2248 }
2249
2250 outline(|| {
2251 self.convert_diffs_to_lines_frozen();
2252 if let Some(SourceFileLines::Lines(lines)) = self.lines.get() {
2253 return &lines[..];
2254 }
2255 unreachable!()
2256 })
2257 }
2258
2259 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
2261 let pos = self.relative_position(pos);
2262 let line_index = self.lookup_line(pos).unwrap();
2263 let line_start_pos = self.lines()[line_index];
2264 self.absolute_position(line_start_pos)
2265 }
2266
2267 pub fn add_external_src<F>(&self, get_src: F) -> bool
2272 where
2273 F: FnOnce() -> Option<String>,
2274 {
2275 if !self.external_src.is_frozen() {
2276 let src = get_src();
2277 let src = src.and_then(|mut src| {
2278 self.src_hash.matches(&src).then(|| {
2280 normalize_src(&mut src);
2281 src
2282 })
2283 });
2284
2285 self.external_src.try_write().map(|mut external_src| {
2286 if let ExternalSource::Foreign {
2287 kind: src_kind @ ExternalSourceKind::AbsentOk,
2288 ..
2289 } = &mut *external_src
2290 {
2291 *src_kind = if let Some(src) = src {
2292 ExternalSourceKind::Present(Arc::new(src))
2293 } else {
2294 ExternalSourceKind::AbsentErr
2295 };
2296 } else {
2297 panic!("unexpected state {:?}", *external_src)
2298 }
2299
2300 FreezeWriteGuard::freeze(external_src)
2302 });
2303 }
2304
2305 self.src.is_some() || self.external_src.read().get_source().is_some()
2306 }
2307
2308 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
2311 fn get_until_newline(src: &str, begin: usize) -> &str {
2312 let slice = &src[begin..];
2316 match slice.find('\n') {
2317 Some(e) => &slice[..e],
2318 None => slice,
2319 }
2320 }
2321
2322 let begin = {
2323 let line = self.lines().get(line_number).copied()?;
2324 line.to_usize()
2325 };
2326
2327 if let Some(ref src) = self.src {
2328 Some(Cow::from(get_until_newline(src, begin)))
2329 } else {
2330 self.external_src
2331 .borrow()
2332 .get_source()
2333 .map(|src| Cow::Owned(String::from(get_until_newline(src, begin))))
2334 }
2335 }
2336
2337 pub fn is_real_file(&self) -> bool {
2338 self.name.is_real()
2339 }
2340
2341 #[inline]
2342 pub fn is_imported(&self) -> bool {
2343 self.src.is_none()
2344 }
2345
2346 pub fn count_lines(&self) -> usize {
2347 self.lines().len()
2348 }
2349
2350 #[inline]
2351 pub fn absolute_position(&self, pos: RelativeBytePos) -> BytePos {
2352 BytePos::from_u32(pos.to_u32() + self.start_pos.to_u32())
2353 }
2354
2355 #[inline]
2356 pub fn relative_position(&self, pos: BytePos) -> RelativeBytePos {
2357 RelativeBytePos::from_u32(pos.to_u32() - self.start_pos.to_u32())
2358 }
2359
2360 #[inline]
2361 pub fn end_position(&self) -> BytePos {
2362 self.absolute_position(self.normalized_source_len)
2363 }
2364
2365 pub fn lookup_line(&self, pos: RelativeBytePos) -> Option<usize> {
2370 self.lines().partition_point(|x| x <= &pos).checked_sub(1)
2371 }
2372
2373 pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
2374 if self.is_empty() {
2375 return self.start_pos..self.start_pos;
2376 }
2377
2378 let lines = self.lines();
2379 assert!(line_index < lines.len());
2380 if line_index == (lines.len() - 1) {
2381 self.absolute_position(lines[line_index])..self.end_position()
2382 } else {
2383 self.absolute_position(lines[line_index])..self.absolute_position(lines[line_index + 1])
2384 }
2385 }
2386
2387 #[inline]
2392 pub fn contains(&self, byte_pos: BytePos) -> bool {
2393 byte_pos >= self.start_pos && byte_pos <= self.end_position()
2394 }
2395
2396 #[inline]
2397 pub fn is_empty(&self) -> bool {
2398 self.normalized_source_len.to_u32() == 0
2399 }
2400
2401 pub fn original_relative_byte_pos(&self, pos: BytePos) -> RelativeBytePos {
2404 let pos = self.relative_position(pos);
2405
2406 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
2410 Ok(i) => self.normalized_pos[i].diff,
2411 Err(0) => 0,
2412 Err(i) => self.normalized_pos[i - 1].diff,
2413 };
2414
2415 RelativeBytePos::from_u32(pos.0 + diff)
2416 }
2417
2418 pub fn normalized_byte_pos(&self, offset: u32) -> BytePos {
2428 let diff = match self
2429 .normalized_pos
2430 .binary_search_by(|np| (np.pos.0 + np.diff).cmp(&(self.start_pos.0 + offset)))
2431 {
2432 Ok(i) => self.normalized_pos[i].diff,
2433 Err(0) => 0,
2434 Err(i) => self.normalized_pos[i - 1].diff,
2435 };
2436
2437 BytePos::from_u32(self.start_pos.0 + offset - diff)
2438 }
2439
2440 fn bytepos_to_file_charpos(&self, bpos: RelativeBytePos) -> CharPos {
2442 let mut total_extra_bytes = 0;
2444
2445 for mbc in self.multibyte_chars.iter() {
2446 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
2447 if mbc.pos < bpos {
2448 total_extra_bytes += mbc.bytes as u32 - 1;
2451 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
2454 } else {
2455 break;
2456 }
2457 }
2458
2459 assert!(total_extra_bytes <= bpos.to_u32());
2460 CharPos(bpos.to_usize() - total_extra_bytes as usize)
2461 }
2462
2463 fn lookup_file_pos(&self, pos: RelativeBytePos) -> (usize, CharPos) {
2466 let chpos = self.bytepos_to_file_charpos(pos);
2467 match self.lookup_line(pos) {
2468 Some(a) => {
2469 let line = a + 1; let linebpos = self.lines()[a];
2471 let linechpos = self.bytepos_to_file_charpos(linebpos);
2472 let col = chpos - linechpos;
2473 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
2474 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
2475 debug!("byte is on line: {}", line);
2476 assert!(chpos >= linechpos);
2477 (line, col)
2478 }
2479 None => (0, chpos),
2480 }
2481 }
2482
2483 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
2486 let pos = self.relative_position(pos);
2487 let (line, col_or_chpos) = self.lookup_file_pos(pos);
2488 if line > 0 {
2489 let Some(code) = self.get_line(line - 1) else {
2490 tracing::info!("couldn't find line {line} {:?}", self.name);
2498 return (line, col_or_chpos, col_or_chpos.0);
2499 };
2500 let display_col = code.chars().take(col_or_chpos.0).map(|ch| char_width(ch)).sum();
2501 (line, col_or_chpos, display_col)
2502 } else {
2503 (0, col_or_chpos, col_or_chpos.0)
2505 }
2506 }
2507}
2508
2509pub fn char_width(ch: char) -> usize {
2510 match ch {
2513 '\t' => 4,
2514 '\u{0000}' | '\u{0001}' | '\u{0002}' | '\u{0003}' | '\u{0004}' | '\u{0005}'
2518 | '\u{0006}' | '\u{0007}' | '\u{0008}' | '\u{000B}' | '\u{000C}' | '\u{000D}'
2519 | '\u{000E}' | '\u{000F}' | '\u{0010}' | '\u{0011}' | '\u{0012}' | '\u{0013}'
2520 | '\u{0014}' | '\u{0015}' | '\u{0016}' | '\u{0017}' | '\u{0018}' | '\u{0019}'
2521 | '\u{001A}' | '\u{001B}' | '\u{001C}' | '\u{001D}' | '\u{001E}' | '\u{001F}'
2522 | '\u{007F}' | '\u{202A}' | '\u{202B}' | '\u{202D}' | '\u{202E}' | '\u{2066}'
2523 | '\u{2067}' | '\u{2068}' | '\u{202C}' | '\u{2069}' => 1,
2524 _ => unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1),
2525 }
2526}
2527
2528pub fn str_width(s: &str) -> usize {
2529 s.chars().map(char_width).sum()
2530}
2531
2532fn normalize_src(src: &mut String) -> Vec<NormalizedPos> {
2534 let mut normalized_pos = vec![];
2535 remove_bom(src, &mut normalized_pos);
2536 normalize_newlines(src, &mut normalized_pos);
2537 normalized_pos
2538}
2539
2540fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
2542 if src.starts_with('\u{feff}') {
2543 src.drain(..3);
2544 normalized_pos.push(NormalizedPos { pos: RelativeBytePos(0), diff: 3 });
2545 }
2546}
2547
2548fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
2552 if !src.as_bytes().contains(&b'\r') {
2553 return;
2554 }
2555
2556 let mut buf = std::mem::replace(src, String::new()).into_bytes();
2562 let mut gap_len = 0;
2563 let mut tail = buf.as_mut_slice();
2564 let mut cursor = 0;
2565 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
2566 loop {
2567 let idx = match find_crlf(&tail[gap_len..]) {
2568 None => tail.len(),
2569 Some(idx) => idx + gap_len,
2570 };
2571 tail.copy_within(gap_len..idx, 0);
2572 tail = &mut tail[idx - gap_len..];
2573 if tail.len() == gap_len {
2574 break;
2575 }
2576 cursor += idx - gap_len;
2577 gap_len += 1;
2578 normalized_pos.push(NormalizedPos {
2579 pos: RelativeBytePos::from_usize(cursor + 1),
2580 diff: original_gap + gap_len as u32,
2581 });
2582 }
2583
2584 let new_len = buf.len() - gap_len;
2587 unsafe {
2588 buf.set_len(new_len);
2589 *src = String::from_utf8_unchecked(buf);
2590 }
2591
2592 fn find_crlf(src: &[u8]) -> Option<usize> {
2593 let mut search_idx = 0;
2594 while let Some(idx) = find_cr(&src[search_idx..]) {
2595 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
2596 search_idx += idx + 1;
2597 continue;
2598 }
2599 return Some(search_idx + idx);
2600 }
2601 None
2602 }
2603
2604 fn find_cr(src: &[u8]) -> Option<usize> {
2605 src.iter().position(|&b| b == b'\r')
2606 }
2607}
2608
2609pub trait Pos {
2614 fn from_usize(n: usize) -> Self;
2615 fn to_usize(&self) -> usize;
2616 fn from_u32(n: u32) -> Self;
2617 fn to_u32(&self) -> u32;
2618}
2619
2620macro_rules! impl_pos {
2621 (
2622 $(
2623 $(#[$attr:meta])*
2624 $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
2625 )*
2626 ) => {
2627 $(
2628 $(#[$attr])*
2629 $vis struct $ident($inner_vis $inner_ty);
2630
2631 impl Pos for $ident {
2632 #[inline(always)]
2633 fn from_usize(n: usize) -> $ident {
2634 $ident(n as $inner_ty)
2635 }
2636
2637 #[inline(always)]
2638 fn to_usize(&self) -> usize {
2639 self.0 as usize
2640 }
2641
2642 #[inline(always)]
2643 fn from_u32(n: u32) -> $ident {
2644 $ident(n as $inner_ty)
2645 }
2646
2647 #[inline(always)]
2648 fn to_u32(&self) -> u32 {
2649 self.0 as u32
2650 }
2651 }
2652
2653 impl Add for $ident {
2654 type Output = $ident;
2655
2656 #[inline(always)]
2657 fn add(self, rhs: $ident) -> $ident {
2658 $ident(self.0 + rhs.0)
2659 }
2660 }
2661
2662 impl Sub for $ident {
2663 type Output = $ident;
2664
2665 #[inline(always)]
2666 fn sub(self, rhs: $ident) -> $ident {
2667 $ident(self.0 - rhs.0)
2668 }
2669 }
2670 )*
2671 };
2672}
2673
2674impl_pos! {
2675 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
2679 pub struct BytePos(pub u32);
2680
2681 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
2683 pub struct RelativeBytePos(pub u32);
2684
2685 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
2691 pub struct CharPos(pub usize);
2692}
2693
2694impl<S: Encoder> Encodable<S> for BytePos {
2695 fn encode(&self, s: &mut S) {
2696 s.emit_u32(self.0);
2697 }
2698}
2699
2700impl<D: Decoder> Decodable<D> for BytePos {
2701 fn decode(d: &mut D) -> BytePos {
2702 BytePos(d.read_u32())
2703 }
2704}
2705
2706impl<H: HashStableContext> HashStable<H> for RelativeBytePos {
2707 fn hash_stable(&self, hcx: &mut H, hasher: &mut StableHasher) {
2708 self.0.hash_stable(hcx, hasher);
2709 }
2710}
2711
2712impl<S: Encoder> Encodable<S> for RelativeBytePos {
2713 fn encode(&self, s: &mut S) {
2714 s.emit_u32(self.0);
2715 }
2716}
2717
2718impl<D: Decoder> Decodable<D> for RelativeBytePos {
2719 fn decode(d: &mut D) -> RelativeBytePos {
2720 RelativeBytePos(d.read_u32())
2721 }
2722}
2723
2724#[derive(Debug, Clone)]
2730pub struct Loc {
2731 pub file: Arc<SourceFile>,
2733 pub line: usize,
2735 pub col: CharPos,
2737 pub col_display: usize,
2739}
2740
2741#[derive(Debug)]
2743pub struct SourceFileAndLine {
2744 pub sf: Arc<SourceFile>,
2745 pub line: usize,
2747}
2748#[derive(Debug)]
2749pub struct SourceFileAndBytePos {
2750 pub sf: Arc<SourceFile>,
2751 pub pos: BytePos,
2752}
2753
2754#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2755pub struct LineInfo {
2756 pub line_index: usize,
2758
2759 pub start_col: CharPos,
2761
2762 pub end_col: CharPos,
2764}
2765
2766pub struct FileLines {
2767 pub file: Arc<SourceFile>,
2768 pub lines: Vec<LineInfo>,
2769}
2770
2771pub static SPAN_TRACK: AtomicRef<fn(LocalDefId)> = AtomicRef::new(&((|_| {}) as fn(_)));
2772
2773pub type FileLinesResult = Result<FileLines, SpanLinesError>;
2778
2779#[derive(Clone, PartialEq, Eq, Debug)]
2780pub enum SpanLinesError {
2781 DistinctSources(Box<DistinctSources>),
2782}
2783
2784#[derive(Clone, PartialEq, Eq, Debug)]
2785pub enum SpanSnippetError {
2786 IllFormedSpan(Span),
2787 DistinctSources(Box<DistinctSources>),
2788 MalformedForSourcemap(MalformedSourceMapPositions),
2789 SourceNotAvailable { filename: FileName },
2790}
2791
2792#[derive(Clone, PartialEq, Eq, Debug)]
2793pub struct DistinctSources {
2794 pub begin: (FileName, BytePos),
2795 pub end: (FileName, BytePos),
2796}
2797
2798#[derive(Clone, PartialEq, Eq, Debug)]
2799pub struct MalformedSourceMapPositions {
2800 pub name: FileName,
2801 pub source_len: usize,
2802 pub begin_pos: BytePos,
2803 pub end_pos: BytePos,
2804}
2805
2806#[derive(Copy, Clone, PartialEq, Eq, Debug)]
2808pub struct InnerSpan {
2809 pub start: usize,
2810 pub end: usize,
2811}
2812
2813impl InnerSpan {
2814 pub fn new(start: usize, end: usize) -> InnerSpan {
2815 InnerSpan { start, end }
2816 }
2817}
2818
2819pub trait HashStableContext {
2824 fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
2825 fn hash_spans(&self) -> bool;
2826 fn unstable_opts_incremental_ignore_spans(&self) -> bool;
2829 fn def_span(&self, def_id: LocalDefId) -> Span;
2830 fn span_data_to_lines_and_cols(
2831 &mut self,
2832 span: &SpanData,
2833 ) -> Option<(StableSourceFileId, usize, BytePos, usize, BytePos)>;
2834 fn hashing_controls(&self) -> HashingControls;
2835}
2836
2837impl<CTX> HashStable<CTX> for Span
2838where
2839 CTX: HashStableContext,
2840{
2841 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
2852 const TAG_VALID_SPAN: u8 = 0;
2853 const TAG_INVALID_SPAN: u8 = 1;
2854 const TAG_RELATIVE_SPAN: u8 = 2;
2855
2856 if !ctx.hash_spans() {
2857 return;
2858 }
2859
2860 let span = self.data_untracked();
2861 span.ctxt.hash_stable(ctx, hasher);
2862 span.parent.hash_stable(ctx, hasher);
2863
2864 if span.is_dummy() {
2865 Hash::hash(&TAG_INVALID_SPAN, hasher);
2866 return;
2867 }
2868
2869 if let Some(parent) = span.parent {
2870 let def_span = ctx.def_span(parent).data_untracked();
2871 if def_span.contains(span) {
2872 Hash::hash(&TAG_RELATIVE_SPAN, hasher);
2874 (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher);
2875 (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher);
2876 return;
2877 }
2878 }
2879
2880 let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span)
2884 else {
2885 Hash::hash(&TAG_INVALID_SPAN, hasher);
2886 return;
2887 };
2888
2889 Hash::hash(&TAG_VALID_SPAN, hasher);
2890 Hash::hash(&file, hasher);
2891
2892 let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
2902 let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
2903 let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
2904 let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
2905 let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
2906 let len = (span.hi - span.lo).0;
2907 Hash::hash(&col_line, hasher);
2908 Hash::hash(&len, hasher);
2909 }
2910}
2911
2912#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
2918#[derive(HashStable_Generic)]
2919pub struct ErrorGuaranteed(());
2920
2921impl ErrorGuaranteed {
2922 #[deprecated = "should only be used in `DiagCtxtInner::emit_diagnostic`"]
2924 pub fn unchecked_error_guaranteed() -> Self {
2925 ErrorGuaranteed(())
2926 }
2927
2928 pub fn raise_fatal(self) -> ! {
2929 FatalError.raise()
2930 }
2931}
2932
2933impl<E: rustc_serialize::Encoder> Encodable<E> for ErrorGuaranteed {
2934 #[inline]
2935 fn encode(&self, _e: &mut E) {
2936 panic!(
2937 "should never serialize an `ErrorGuaranteed`, as we do not write metadata or \
2938 incremental caches in case errors occurred"
2939 )
2940 }
2941}
2942impl<D: rustc_serialize::Decoder> Decodable<D> for ErrorGuaranteed {
2943 #[inline]
2944 fn decode(_d: &mut D) -> ErrorGuaranteed {
2945 panic!(
2946 "`ErrorGuaranteed` should never have been serialized to metadata or incremental caches"
2947 )
2948 }
2949}