1 //! Source positions and related helper functions.
3 //! Important concepts in this module include:
5 //! - the *span*, represented by [`SpanData`] and related types;
6 //! - source code as represented by a [`SourceMap`]; and
7 //! - interned strings, represented by [`Symbol`]s, with some common symbols available statically in the [`sym`] module.
9 //! Unlike most compilers, the span contains not only the position in the source code, but also various other metadata,
10 //! such as the edition and macro hygiene. This metadata is stored in [`SyntaxContext`] and [`ExpnData`].
14 //! This API is completely unstable and subject to change.
16 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
17 #![feature(array_windows)]
18 #![feature(crate_visibility_modifier)]
19 #![feature(negative_impls)]
21 #![feature(min_specialization)]
22 #![feature(thread_local_const_init)]
25 extern crate rustc_macros;
27 use rustc_data_structures::AtomicRef;
28 use rustc_macros::HashStable_Generic;
29 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
31 mod caching_source_map_view;
33 pub use self::caching_source_map_view::CachingSourceMapView;
34 use source_map::SourceMap;
39 use hygiene::Transparency;
40 pub use hygiene::{DesugaringKind, ExpnKind, ForLoopLoc, MacroKind};
41 pub use hygiene::{ExpnData, ExpnHash, ExpnId, SyntaxContext};
43 use def_id::{CrateNum, DefId, DefPathHash, LOCAL_CRATE};
46 pub use span_encoding::{Span, DUMMY_SP};
49 pub use symbol::{sym, Symbol};
51 mod analyze_source_file;
54 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
55 use rustc_data_structures::sync::{Lock, Lrc};
58 use std::cmp::{self, Ordering};
61 use std::ops::{Add, Range, Sub};
62 use std::path::{Path, PathBuf};
63 use std::str::FromStr;
75 // Per-session global variables: this struct is stored in thread-local storage
76 // in such a way that it is accessible without any kind of handle to all
77 // threads within the compilation session, but is not accessible outside the
79 pub struct SessionGlobals {
80 symbol_interner: Lock<symbol::Interner>,
81 span_interner: Lock<span_encoding::SpanInterner>,
82 hygiene_data: Lock<hygiene::HygieneData>,
83 source_map: Lock<Option<Lrc<SourceMap>>>,
87 pub fn new(edition: Edition) -> SessionGlobals {
89 symbol_interner: Lock::new(symbol::Interner::fresh()),
90 span_interner: Lock::new(span_encoding::SpanInterner::default()),
91 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
92 source_map: Lock::new(None),
98 pub fn create_session_globals_then<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
100 !SESSION_GLOBALS.is_set(),
101 "SESSION_GLOBALS should never be overwritten! \
102 Use another thread if you need another SessionGlobals"
104 let session_globals = SessionGlobals::new(edition);
105 SESSION_GLOBALS.set(&session_globals, f)
109 pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R {
111 !SESSION_GLOBALS.is_set(),
112 "SESSION_GLOBALS should never be overwritten! \
113 Use another thread if you need another SessionGlobals"
115 SESSION_GLOBALS.set(session_globals, f)
119 pub fn create_default_session_if_not_set_then<R, F>(f: F) -> R
121 F: FnOnce(&SessionGlobals) -> R,
123 create_session_if_not_set_then(edition::DEFAULT_EDITION, f)
127 pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R
129 F: FnOnce(&SessionGlobals) -> R,
131 if !SESSION_GLOBALS.is_set() {
132 let session_globals = SessionGlobals::new(edition);
133 SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f))
135 SESSION_GLOBALS.with(f)
140 pub fn with_session_globals<R, F>(f: F) -> R
142 F: FnOnce(&SessionGlobals) -> R,
144 SESSION_GLOBALS.with(f)
148 pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R {
149 create_session_globals_then(edition::DEFAULT_EDITION, f)
152 // If this ever becomes non thread-local, `decode_syntax_context`
153 // and `decode_expn_id` will need to be updated to handle concurrent
155 scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals);
157 // FIXME: We should use this enum or something like it to get rid of the
158 // use of magic `/rust/1.x/...` paths across the board.
159 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)]
160 #[derive(HashStable_Generic, Decodable)]
161 pub enum RealFileName {
163 /// For remapped paths (namely paths into libstd that have been mapped
164 /// to the appropriate spot on the local host's file system, and local file
165 /// system paths that have been remapped with `FilePathMapping`),
167 /// `local_path` is the (host-dependent) local path to the file. This is
168 /// None if the file was imported from another crate
169 local_path: Option<PathBuf>,
170 /// `virtual_name` is the stable path rustc will store internally within
172 virtual_name: PathBuf,
176 impl Hash for RealFileName {
177 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
178 // To prevent #70924 from happening again we should only hash the
179 // remapped (virtualized) path if that exists. This is because
180 // virtualized paths to sysroot crates (/rust/$hash or /rust/$version)
181 // remain stable even if the corresponding local_path changes
182 self.remapped_path_if_available().hash(state)
186 // This is functionally identical to #[derive(Encodable)], with the exception of
187 // an added assert statement
188 impl<S: Encoder> Encodable<S> for RealFileName {
189 fn encode(&self, encoder: &mut S) -> Result<(), S::Error> {
190 encoder.emit_enum(|encoder| match *self {
191 RealFileName::LocalPath(ref local_path) => {
192 encoder.emit_enum_variant("LocalPath", 0, 1, |encoder| {
195 .emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?;
200 RealFileName::Remapped { ref local_path, ref virtual_name } => encoder
201 .emit_enum_variant("Remapped", 1, 2, |encoder| {
202 // For privacy and build reproducibility, we must not embed host-dependant path in artifacts
203 // if they have been remapped by --remap-path-prefix
204 assert!(local_path.is_none());
207 .emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?;
209 .emit_enum_variant_arg(false, |encoder| virtual_name.encode(encoder))?;
217 /// Returns the path suitable for reading from the file system on the local host,
218 /// if this information exists.
219 /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
220 pub fn local_path(&self) -> Option<&Path> {
222 RealFileName::LocalPath(p) => Some(p),
223 RealFileName::Remapped { local_path: p, virtual_name: _ } => {
224 p.as_ref().map(PathBuf::as_path)
229 /// Returns the path suitable for reading from the file system on the local host,
230 /// if this information exists.
231 /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
232 pub fn into_local_path(self) -> Option<PathBuf> {
234 RealFileName::LocalPath(p) => Some(p),
235 RealFileName::Remapped { local_path: p, virtual_name: _ } => p,
239 /// Returns the path suitable for embedding into build artifacts. This would still
240 /// be a local path if it has not been remapped. A remapped path will not correspond
241 /// to a valid file system path: see `local_path_if_available()` for something that
242 /// is more likely to return paths into the local host file system.
243 pub fn remapped_path_if_available(&self) -> &Path {
245 RealFileName::LocalPath(p)
246 | RealFileName::Remapped { local_path: _, virtual_name: p } => &p,
250 /// Returns the path suitable for reading from the file system on the local host,
251 /// if this information exists. Otherwise returns the remapped name.
252 /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that.
253 pub fn local_path_if_available(&self) -> &Path {
255 RealFileName::LocalPath(path)
256 | RealFileName::Remapped { local_path: None, virtual_name: path }
257 | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path,
261 pub fn to_string_lossy(&self, prefer_local: bool) -> Cow<'_, str> {
263 self.local_path_if_available().to_string_lossy()
265 self.remapped_path_if_available().to_string_lossy()
270 /// Differentiates between real files and common virtual files.
271 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
272 #[derive(HashStable_Generic, Decodable, Encodable)]
275 /// Call to `quote!`.
279 /// Hack in `src/librustc_ast/parse.rs`.
282 ProcMacroSourceCode(u64),
283 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
285 /// Strings provided as crate attributes in the CLI.
287 /// Custom sources for explicit parser calls from plugins and drivers.
289 DocTest(PathBuf, isize),
290 /// Post-substitution inline assembly from LLVM.
294 impl From<PathBuf> for FileName {
295 fn from(p: PathBuf) -> Self {
296 assert!(!p.to_string_lossy().ends_with('>'));
297 FileName::Real(RealFileName::LocalPath(p))
301 pub struct FileNameDisplay<'a> {
306 impl fmt::Display for FileNameDisplay<'_> {
307 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311 write!(fmt, "{}", name.to_string_lossy(self.prefer_local))
313 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
314 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
315 Anon(_) => write!(fmt, "<anon>"),
316 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
317 CfgSpec(_) => write!(fmt, "<cfgspec>"),
318 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
319 Custom(ref s) => write!(fmt, "<{}>", s),
320 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
321 InlineAsm(_) => write!(fmt, "<inline asm>"),
326 impl FileNameDisplay<'_> {
327 pub fn to_string_lossy(&self) -> Cow<'_, str> {
329 FileName::Real(ref inner) => inner.to_string_lossy(self.prefer_local),
330 _ => Cow::from(format!("{}", self)),
336 pub fn is_real(&self) -> bool {
342 | ProcMacroSourceCode(_)
348 | InlineAsm(_) => false,
352 pub fn prefer_remapped(&self) -> FileNameDisplay<'_> {
353 FileNameDisplay { inner: self, prefer_local: false }
356 // This may include transient local filesystem information.
357 // Must not be embedded in build outputs.
358 pub fn prefer_local(&self) -> FileNameDisplay<'_> {
359 FileNameDisplay { inner: self, prefer_local: true }
362 pub fn macro_expansion_source_code(src: &str) -> FileName {
363 let mut hasher = StableHasher::new();
364 src.hash(&mut hasher);
365 FileName::MacroExpansion(hasher.finish())
368 pub fn anon_source_code(src: &str) -> FileName {
369 let mut hasher = StableHasher::new();
370 src.hash(&mut hasher);
371 FileName::Anon(hasher.finish())
374 pub fn proc_macro_source_code(src: &str) -> FileName {
375 let mut hasher = StableHasher::new();
376 src.hash(&mut hasher);
377 FileName::ProcMacroSourceCode(hasher.finish())
380 pub fn cfg_spec_source_code(src: &str) -> FileName {
381 let mut hasher = StableHasher::new();
382 src.hash(&mut hasher);
383 FileName::QuoteExpansion(hasher.finish())
386 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
387 let mut hasher = StableHasher::new();
388 src.hash(&mut hasher);
389 FileName::CliCrateAttr(hasher.finish())
392 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
393 FileName::DocTest(path, line)
396 pub fn inline_asm_source_code(src: &str) -> FileName {
397 let mut hasher = StableHasher::new();
398 src.hash(&mut hasher);
399 FileName::InlineAsm(hasher.finish())
403 /// Represents a span.
405 /// Spans represent a region of code, used for error reporting. Positions in spans
406 /// are *absolute* positions from the beginning of the [`SourceMap`], not positions
407 /// relative to [`SourceFile`]s. Methods on the `SourceMap` can be used to relate spans back
408 /// to the original source.
410 /// You must be careful if the span crosses more than one file, since you will not be
411 /// able to use many of the functions on spans in source_map and you cannot assume
412 /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the
413 /// [`BytePos`] range between files.
415 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
416 /// sent to other threads, but some pieces of performance infra run in a separate thread.
417 /// Using `Span` is generally preferred.
418 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
419 pub struct SpanData {
422 /// Information about where the macro came from, if this piece of
423 /// code was created by a macro expansion.
424 pub ctxt: SyntaxContext,
429 pub fn span(&self) -> Span {
430 Span::new(self.lo, self.hi, self.ctxt)
433 pub fn with_lo(&self, lo: BytePos) -> Span {
434 Span::new(lo, self.hi, self.ctxt)
437 pub fn with_hi(&self, hi: BytePos) -> Span {
438 Span::new(self.lo, hi, self.ctxt)
441 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
442 Span::new(self.lo, self.hi, ctxt)
446 // The interner is pointed to by a thread local value which is only set on the main thread
447 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
448 // to avoid panics and other errors, even though it would be memory safe to do so.
449 #[cfg(not(parallel_compiler))]
450 impl !Send for Span {}
451 #[cfg(not(parallel_compiler))]
452 impl !Sync for Span {}
454 impl PartialOrd for Span {
455 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
456 PartialOrd::partial_cmp(&self.data(), &rhs.data())
460 fn cmp(&self, rhs: &Self) -> Ordering {
461 Ord::cmp(&self.data(), &rhs.data())
465 /// A collection of `Span`s.
467 /// Spans have two orthogonal attributes:
469 /// - They can be *primary spans*. In this case they are the locus of
470 /// the error, and would be rendered with `^^^`.
471 /// - They can have a *label*. In this case, the label is written next
472 /// to the mark in the snippet when we render.
473 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
474 pub struct MultiSpan {
475 primary_spans: Vec<Span>,
476 span_labels: Vec<(Span, String)>,
481 pub fn lo(self) -> BytePos {
485 pub fn with_lo(self, lo: BytePos) -> Span {
486 self.data().with_lo(lo)
489 pub fn hi(self) -> BytePos {
493 pub fn with_hi(self, hi: BytePos) -> Span {
494 self.data().with_hi(hi)
497 pub fn ctxt(self) -> SyntaxContext {
501 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
502 self.data().with_ctxt(ctxt)
505 /// Returns `true` if this is a dummy span with any hygienic context.
507 pub fn is_dummy(self) -> bool {
508 let span = self.data();
509 span.lo.0 == 0 && span.hi.0 == 0
512 /// Returns `true` if this span comes from a macro or desugaring.
514 pub fn from_expansion(self) -> bool {
515 self.ctxt() != SyntaxContext::root()
518 /// Returns `true` if `span` originates in a derive-macro's expansion.
519 pub fn in_derive_expansion(self) -> bool {
520 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
524 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
525 Span::new(lo, hi, SyntaxContext::root())
528 /// Returns a new span representing an empty span at the beginning of this span.
530 pub fn shrink_to_lo(self) -> Span {
531 let span = self.data();
532 span.with_hi(span.lo)
534 /// Returns a new span representing an empty span at the end of this span.
536 pub fn shrink_to_hi(self) -> Span {
537 let span = self.data();
538 span.with_lo(span.hi)
542 /// Returns `true` if `hi == lo`.
543 pub fn is_empty(&self) -> bool {
544 let span = self.data();
548 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
549 pub fn substitute_dummy(self, other: Span) -> Span {
550 if self.is_dummy() { other } else { self }
553 /// Returns `true` if `self` fully encloses `other`.
554 pub fn contains(self, other: Span) -> bool {
555 let span = self.data();
556 let other = other.data();
557 span.lo <= other.lo && other.hi <= span.hi
560 /// Returns `true` if `self` touches `other`.
561 pub fn overlaps(self, other: Span) -> bool {
562 let span = self.data();
563 let other = other.data();
564 span.lo < other.hi && other.lo < span.hi
567 /// Returns `true` if the spans are equal with regards to the source text.
569 /// Use this instead of `==` when either span could be generated code,
570 /// and you only care that they point to the same bytes of source text.
571 pub fn source_equal(&self, other: &Span) -> bool {
572 let span = self.data();
573 let other = other.data();
574 span.lo == other.lo && span.hi == other.hi
577 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
578 pub fn trim_start(self, other: Span) -> Option<Span> {
579 let span = self.data();
580 let other = other.data();
581 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
584 /// Returns the source span -- this is either the supplied span, or the span for
585 /// the macro callsite that expanded to it.
586 pub fn source_callsite(self) -> Span {
587 let expn_data = self.ctxt().outer_expn_data();
588 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
591 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
593 pub fn parent(self) -> Option<Span> {
594 let expn_data = self.ctxt().outer_expn_data();
595 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
598 /// Edition of the crate from which this span came.
599 pub fn edition(self) -> edition::Edition {
600 self.ctxt().edition()
604 pub fn rust_2015(&self) -> bool {
605 self.edition() == edition::Edition::Edition2015
609 pub fn rust_2018(&self) -> bool {
610 self.edition() >= edition::Edition::Edition2018
614 pub fn rust_2021(&self) -> bool {
615 self.edition() >= edition::Edition::Edition2021
618 /// Returns the source callee.
620 /// Returns `None` if the supplied span has no expansion trace,
621 /// else returns the `ExpnData` for the macro definition
622 /// corresponding to the source callsite.
623 pub fn source_callee(self) -> Option<ExpnData> {
624 fn source_callee(expn_data: ExpnData) -> ExpnData {
625 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
626 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
628 let expn_data = self.ctxt().outer_expn_data();
629 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
632 /// Checks if a span is "internal" to a macro in which `#[unstable]`
633 /// items can be used (that is, a macro marked with
634 /// `#[allow_internal_unstable]`).
635 pub fn allows_unstable(&self, feature: Symbol) -> bool {
638 .allow_internal_unstable
639 .map_or(false, |features| features.iter().any(|&f| f == feature))
642 /// Checks if this span arises from a compiler desugaring of kind `kind`.
643 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
644 match self.ctxt().outer_expn_data().kind {
645 ExpnKind::Desugaring(k) => k == kind,
650 /// Returns the compiler desugaring that created this span, or `None`
651 /// if this span is not from a desugaring.
652 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
653 match self.ctxt().outer_expn_data().kind {
654 ExpnKind::Desugaring(k) => Some(k),
659 /// Checks if a span is "internal" to a macro in which `unsafe`
660 /// can be used without triggering the `unsafe_code` lint.
661 // (that is, a macro marked with `#[allow_internal_unsafe]`).
662 pub fn allows_unsafe(&self) -> bool {
663 self.ctxt().outer_expn_data().allow_internal_unsafe
666 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
667 let mut prev_span = DUMMY_SP;
668 std::iter::from_fn(move || {
670 let expn_data = self.ctxt().outer_expn_data();
671 if expn_data.is_root() {
675 let is_recursive = expn_data.call_site.source_equal(&prev_span);
678 self = expn_data.call_site;
680 // Don't print recursive invocations.
682 return Some(expn_data);
688 /// Returns a `Span` that would enclose both `self` and `end`.
692 /// self lorem ipsum end
693 /// ^^^^^^^^^^^^^^^^^^^^
695 pub fn to(self, end: Span) -> Span {
696 let span_data = self.data();
697 let end_data = end.data();
698 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
699 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
700 // have an incomplete span than a completely nonsensical one.
701 if span_data.ctxt != end_data.ctxt {
702 if span_data.ctxt == SyntaxContext::root() {
704 } else if end_data.ctxt == SyntaxContext::root() {
707 // Both spans fall within a macro.
708 // FIXME(estebank): check if it is the *same* macro.
711 cmp::min(span_data.lo, end_data.lo),
712 cmp::max(span_data.hi, end_data.hi),
713 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
717 /// Returns a `Span` between the end of `self` to the beginning of `end`.
721 /// self lorem ipsum end
724 pub fn between(self, end: Span) -> Span {
725 let span = self.data();
726 let end = end.data();
730 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
734 /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
738 /// self lorem ipsum end
739 /// ^^^^^^^^^^^^^^^^^
741 pub fn until(self, end: Span) -> Span {
742 let span = self.data();
743 let end = end.data();
747 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
751 pub fn from_inner(self, inner: InnerSpan) -> Span {
752 let span = self.data();
754 span.lo + BytePos::from_usize(inner.start),
755 span.lo + BytePos::from_usize(inner.end),
760 /// Equivalent of `Span::def_site` from the proc macro API,
761 /// except that the location is taken from the `self` span.
762 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
763 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
766 /// Equivalent of `Span::call_site` from the proc macro API,
767 /// except that the location is taken from the `self` span.
768 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
769 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
772 /// Equivalent of `Span::mixed_site` from the proc macro API,
773 /// except that the location is taken from the `self` span.
774 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
775 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
778 /// Produces a span with the same location as `self` and context produced by a macro with the
779 /// given ID and transparency, assuming that macro was defined directly and not produced by
780 /// some other macro (which is the case for built-in and procedural macros).
781 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
782 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
786 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
787 let span = self.data();
788 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
792 pub fn remove_mark(&mut self) -> ExpnId {
793 let mut span = self.data();
794 let mark = span.ctxt.remove_mark();
795 *self = Span::new(span.lo, span.hi, span.ctxt);
800 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
801 let mut span = self.data();
802 let mark = span.ctxt.adjust(expn_id);
803 *self = Span::new(span.lo, span.hi, span.ctxt);
808 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
809 let mut span = self.data();
810 let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
811 *self = Span::new(span.lo, span.hi, span.ctxt);
816 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
817 let mut span = self.data();
818 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
819 *self = Span::new(span.lo, span.hi, span.ctxt);
824 pub fn reverse_glob_adjust(
828 ) -> Option<Option<ExpnId>> {
829 let mut span = self.data();
830 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
831 *self = Span::new(span.lo, span.hi, span.ctxt);
836 pub fn normalize_to_macros_2_0(self) -> Span {
837 let span = self.data();
838 span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
842 pub fn normalize_to_macro_rules(self) -> Span {
843 let span = self.data();
844 span.with_ctxt(span.ctxt.normalize_to_macro_rules())
848 /// A span together with some additional data.
849 #[derive(Clone, Debug)]
850 pub struct SpanLabel {
851 /// The span we are going to include in the final snippet.
854 /// Is this a primary span? This is the "locus" of the message,
855 /// and is indicated with a `^^^^` underline, versus `----`.
856 pub is_primary: bool,
858 /// What label should we attach to this span (if any)?
859 pub label: Option<String>,
862 impl Default for Span {
863 fn default() -> Self {
868 impl<E: Encoder> Encodable<E> for Span {
869 default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
870 let span = self.data();
871 s.emit_struct(false, |s| {
872 s.emit_struct_field("lo", true, |s| span.lo.encode(s))?;
873 s.emit_struct_field("hi", false, |s| span.hi.encode(s))
877 impl<D: Decoder> Decodable<D> for Span {
878 default fn decode(s: &mut D) -> Result<Span, D::Error> {
880 let lo = d.read_struct_field("lo", Decodable::decode)?;
881 let hi = d.read_struct_field("hi", Decodable::decode)?;
883 Ok(Span::new(lo, hi, SyntaxContext::root()))
888 /// Calls the provided closure, using the provided `SourceMap` to format
889 /// any spans that are debug-printed during the closure's execution.
891 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
892 /// (see `rustc_interface::callbacks::span_debug1`). However, some parts
893 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
894 /// a `TyCtxt` is available. In this case, we fall back to
895 /// the `SourceMap` provided to this function. If that is not available,
896 /// we fall back to printing the raw `Span` field values.
897 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
898 with_session_globals(|session_globals| {
899 *session_globals.source_map.borrow_mut() = Some(source_map);
901 struct ClearSourceMap;
902 impl Drop for ClearSourceMap {
904 with_session_globals(|session_globals| {
905 session_globals.source_map.borrow_mut().take();
910 let _guard = ClearSourceMap;
914 pub fn debug_with_source_map(
916 f: &mut fmt::Formatter<'_>,
917 source_map: &SourceMap,
919 write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(span), span.ctxt())
922 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
923 with_session_globals(|session_globals| {
924 if let Some(source_map) = &*session_globals.source_map.borrow() {
925 debug_with_source_map(span, f, source_map)
927 f.debug_struct("Span")
928 .field("lo", &span.lo())
929 .field("hi", &span.hi())
930 .field("ctxt", &span.ctxt())
936 impl fmt::Debug for Span {
937 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
938 (*SPAN_DEBUG)(*self, f)
942 impl fmt::Debug for SpanData {
943 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
944 (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
950 pub fn new() -> MultiSpan {
951 MultiSpan { primary_spans: vec![], span_labels: vec![] }
954 pub fn from_span(primary_span: Span) -> MultiSpan {
955 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
958 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
960 MultiSpan { primary_spans: vec, span_labels: vec![] }
963 pub fn push_span_label(&mut self, span: Span, label: String) {
964 self.span_labels.push((span, label));
967 /// Selects the first primary span (if any).
968 pub fn primary_span(&self) -> Option<Span> {
969 self.primary_spans.first().cloned()
972 /// Returns all primary spans.
973 pub fn primary_spans(&self) -> &[Span] {
977 /// Returns `true` if any of the primary spans are displayable.
978 pub fn has_primary_spans(&self) -> bool {
979 self.primary_spans.iter().any(|sp| !sp.is_dummy())
982 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
983 pub fn is_dummy(&self) -> bool {
984 let mut is_dummy = true;
985 for span in &self.primary_spans {
986 if !span.is_dummy() {
993 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
994 /// display well (like std macros). Returns whether replacements occurred.
995 pub fn replace(&mut self, before: Span, after: Span) -> bool {
996 let mut replacements_occurred = false;
997 for primary_span in &mut self.primary_spans {
998 if *primary_span == before {
999 *primary_span = after;
1000 replacements_occurred = true;
1003 for span_label in &mut self.span_labels {
1004 if span_label.0 == before {
1005 span_label.0 = after;
1006 replacements_occurred = true;
1009 replacements_occurred
1012 /// Returns the strings to highlight. We always ensure that there
1013 /// is an entry for each of the primary spans -- for each primary
1014 /// span `P`, if there is at least one label with span `P`, we return
1015 /// those labels (marked as primary). But otherwise we return
1016 /// `SpanLabel` instances with empty labels.
1017 pub fn span_labels(&self) -> Vec<SpanLabel> {
1018 let is_primary = |span| self.primary_spans.contains(&span);
1020 let mut span_labels = self
1023 .map(|&(span, ref label)| SpanLabel {
1025 is_primary: is_primary(span),
1026 label: Some(label.clone()),
1028 .collect::<Vec<_>>();
1030 for &span in &self.primary_spans {
1031 if !span_labels.iter().any(|sl| sl.span == span) {
1032 span_labels.push(SpanLabel { span, is_primary: true, label: None });
1039 /// Returns `true` if any of the span labels is displayable.
1040 pub fn has_span_labels(&self) -> bool {
1041 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
1045 impl From<Span> for MultiSpan {
1046 fn from(span: Span) -> MultiSpan {
1047 MultiSpan::from_span(span)
1051 impl From<Vec<Span>> for MultiSpan {
1052 fn from(spans: Vec<Span>) -> MultiSpan {
1053 MultiSpan::from_spans(spans)
1057 /// Identifies an offset of a multi-byte character in a `SourceFile`.
1058 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1059 pub struct MultiByteChar {
1060 /// The absolute offset of the character in the `SourceMap`.
1062 /// The number of bytes, `>= 2`.
1066 /// Identifies an offset of a non-narrow character in a `SourceFile`.
1067 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1068 pub enum NonNarrowChar {
1069 /// Represents a zero-width character.
1071 /// Represents a wide (full-width) character.
1073 /// Represents a tab character, represented visually with a width of 4 characters.
1077 impl NonNarrowChar {
1078 fn new(pos: BytePos, width: usize) -> Self {
1080 0 => NonNarrowChar::ZeroWidth(pos),
1081 2 => NonNarrowChar::Wide(pos),
1082 4 => NonNarrowChar::Tab(pos),
1083 _ => panic!("width {} given for non-narrow character", width),
1087 /// Returns the absolute offset of the character in the `SourceMap`.
1088 pub fn pos(&self) -> BytePos {
1090 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
1094 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
1095 pub fn width(&self) -> usize {
1097 NonNarrowChar::ZeroWidth(_) => 0,
1098 NonNarrowChar::Wide(_) => 2,
1099 NonNarrowChar::Tab(_) => 4,
1104 impl Add<BytePos> for NonNarrowChar {
1107 fn add(self, rhs: BytePos) -> Self {
1109 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
1110 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
1111 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
1116 impl Sub<BytePos> for NonNarrowChar {
1119 fn sub(self, rhs: BytePos) -> Self {
1121 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
1122 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
1123 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
1128 /// Identifies an offset of a character that was normalized away from `SourceFile`.
1129 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1130 pub struct NormalizedPos {
1131 /// The absolute offset of the character in the `SourceMap`.
1133 /// The difference between original and normalized string at position.
1137 #[derive(PartialEq, Eq, Clone, Debug)]
1138 pub enum ExternalSource {
1139 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
1142 kind: ExternalSourceKind,
1143 /// This SourceFile's byte-offset within the source_map of its original crate.
1144 original_start_pos: BytePos,
1145 /// The end of this SourceFile within the source_map of its original crate.
1146 original_end_pos: BytePos,
1150 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1151 #[derive(PartialEq, Eq, Clone, Debug)]
1152 pub enum ExternalSourceKind {
1153 /// The external source has been loaded already.
1154 Present(Lrc<String>),
1155 /// No attempt has been made to load the external source.
1157 /// A failed attempt has been made to load the external source.
1162 impl ExternalSource {
1163 pub fn get_source(&self) -> Option<&Lrc<String>> {
1165 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1172 pub struct OffsetOverflowError;
1174 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1175 pub enum SourceFileHashAlgorithm {
1181 impl FromStr for SourceFileHashAlgorithm {
1184 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1186 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1187 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1188 "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1194 rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm);
1196 /// The hash of the on-disk source file used for debug info.
1197 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1198 #[derive(HashStable_Generic, Encodable, Decodable)]
1199 pub struct SourceFileHash {
1200 pub kind: SourceFileHashAlgorithm,
1204 impl SourceFileHash {
1205 pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1206 let mut hash = SourceFileHash { kind, value: Default::default() };
1207 let len = hash.hash_len();
1208 let value = &mut hash.value[..len];
1209 let data = src.as_bytes();
1211 SourceFileHashAlgorithm::Md5 => {
1212 value.copy_from_slice(&Md5::digest(data));
1214 SourceFileHashAlgorithm::Sha1 => {
1215 value.copy_from_slice(&Sha1::digest(data));
1217 SourceFileHashAlgorithm::Sha256 => {
1218 value.copy_from_slice(&Sha256::digest(data));
1224 /// Check if the stored hash matches the hash of the string.
1225 pub fn matches(&self, src: &str) -> bool {
1226 Self::new(self.kind, src) == *self
1229 /// The bytes of the hash.
1230 pub fn hash_bytes(&self) -> &[u8] {
1231 let len = self.hash_len();
1235 fn hash_len(&self) -> usize {
1237 SourceFileHashAlgorithm::Md5 => 16,
1238 SourceFileHashAlgorithm::Sha1 => 20,
1239 SourceFileHashAlgorithm::Sha256 => 32,
1244 /// A single source in the [`SourceMap`].
1246 pub struct SourceFile {
1247 /// The name of the file that the source came from. Source that doesn't
1248 /// originate from files has names between angle brackets by convention
1249 /// (e.g., `<anon>`).
1251 /// The complete source code.
1252 pub src: Option<Lrc<String>>,
1253 /// The source code's hash.
1254 pub src_hash: SourceFileHash,
1255 /// The external source code (used for external crates, which will have a `None`
1256 /// value as `self.src`.
1257 pub external_src: Lock<ExternalSource>,
1258 /// The start position of this source in the `SourceMap`.
1259 pub start_pos: BytePos,
1260 /// The end position of this source in the `SourceMap`.
1261 pub end_pos: BytePos,
1262 /// Locations of lines beginnings in the source code.
1263 pub lines: Vec<BytePos>,
1264 /// Locations of multi-byte characters in the source code.
1265 pub multibyte_chars: Vec<MultiByteChar>,
1266 /// Width of characters that are not narrow in the source code.
1267 pub non_narrow_chars: Vec<NonNarrowChar>,
1268 /// Locations of characters removed during normalization.
1269 pub normalized_pos: Vec<NormalizedPos>,
1270 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1271 pub name_hash: u128,
1272 /// Indicates which crate this `SourceFile` was imported from.
1276 impl<S: Encoder> Encodable<S> for SourceFile {
1277 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1278 s.emit_struct(false, |s| {
1279 s.emit_struct_field("name", true, |s| self.name.encode(s))?;
1280 s.emit_struct_field("src_hash", false, |s| self.src_hash.encode(s))?;
1281 s.emit_struct_field("start_pos", false, |s| self.start_pos.encode(s))?;
1282 s.emit_struct_field("end_pos", false, |s| self.end_pos.encode(s))?;
1283 s.emit_struct_field("lines", false, |s| {
1284 let lines = &self.lines[..];
1285 // Store the length.
1286 s.emit_u32(lines.len() as u32)?;
1288 if !lines.is_empty() {
1289 // In order to preserve some space, we exploit the fact that
1290 // the lines list is sorted and individual lines are
1291 // probably not that long. Because of that we can store lines
1292 // as a difference list, using as little space as possible
1293 // for the differences.
1294 let max_line_length = if lines.len() == 1 {
1299 .map(|&[fst, snd]| snd - fst)
1300 .map(|bp| bp.to_usize())
1305 let bytes_per_diff: u8 = match max_line_length {
1307 0x100..=0xFFFF => 2,
1311 // Encode the number of bytes used per diff.
1312 bytes_per_diff.encode(s)?;
1314 // Encode the first element.
1315 lines[0].encode(s)?;
1317 let diff_iter = lines[..].array_windows().map(|&[fst, snd]| snd - fst);
1319 match bytes_per_diff {
1321 for diff in diff_iter {
1322 (diff.0 as u8).encode(s)?
1326 for diff in diff_iter {
1327 (diff.0 as u16).encode(s)?
1331 for diff in diff_iter {
1335 _ => unreachable!(),
1341 s.emit_struct_field("multibyte_chars", false, |s| self.multibyte_chars.encode(s))?;
1342 s.emit_struct_field("non_narrow_chars", false, |s| self.non_narrow_chars.encode(s))?;
1343 s.emit_struct_field("name_hash", false, |s| self.name_hash.encode(s))?;
1344 s.emit_struct_field("normalized_pos", false, |s| self.normalized_pos.encode(s))?;
1345 s.emit_struct_field("cnum", false, |s| self.cnum.encode(s))
1350 impl<D: Decoder> Decodable<D> for SourceFile {
1351 fn decode(d: &mut D) -> Result<SourceFile, D::Error> {
1353 let name: FileName = d.read_struct_field("name", |d| Decodable::decode(d))?;
1354 let src_hash: SourceFileHash =
1355 d.read_struct_field("src_hash", |d| Decodable::decode(d))?;
1356 let start_pos: BytePos = d.read_struct_field("start_pos", |d| Decodable::decode(d))?;
1357 let end_pos: BytePos = d.read_struct_field("end_pos", |d| Decodable::decode(d))?;
1358 let lines: Vec<BytePos> = d.read_struct_field("lines", |d| {
1359 let num_lines: u32 = Decodable::decode(d)?;
1360 let mut lines = Vec::with_capacity(num_lines as usize);
1363 // Read the number of bytes used per diff.
1364 let bytes_per_diff: u8 = Decodable::decode(d)?;
1366 // Read the first element.
1367 let mut line_start: BytePos = Decodable::decode(d)?;
1368 lines.push(line_start);
1370 for _ in 1..num_lines {
1371 let diff = match bytes_per_diff {
1372 1 => d.read_u8()? as u32,
1373 2 => d.read_u16()? as u32,
1375 _ => unreachable!(),
1378 line_start = line_start + BytePos(diff);
1380 lines.push(line_start);
1386 let multibyte_chars: Vec<MultiByteChar> =
1387 d.read_struct_field("multibyte_chars", |d| Decodable::decode(d))?;
1388 let non_narrow_chars: Vec<NonNarrowChar> =
1389 d.read_struct_field("non_narrow_chars", |d| Decodable::decode(d))?;
1390 let name_hash: u128 = d.read_struct_field("name_hash", |d| Decodable::decode(d))?;
1391 let normalized_pos: Vec<NormalizedPos> =
1392 d.read_struct_field("normalized_pos", |d| Decodable::decode(d))?;
1393 let cnum: CrateNum = d.read_struct_field("cnum", |d| Decodable::decode(d))?;
1400 // Unused - the metadata decoder will construct
1401 // a new SourceFile, filling in `external_src` properly
1402 external_src: Lock::new(ExternalSource::Unneeded),
1414 impl fmt::Debug for SourceFile {
1415 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1416 write!(fmt, "SourceFile({:?})", self.name)
1425 hash_kind: SourceFileHashAlgorithm,
1427 // Compute the file hash before any normalization.
1428 let src_hash = SourceFileHash::new(hash_kind, &src);
1429 let normalized_pos = normalize_src(&mut src, start_pos);
1432 let mut hasher: StableHasher = StableHasher::new();
1433 name.hash(&mut hasher);
1434 hasher.finish::<u128>()
1436 let end_pos = start_pos.to_usize() + src.len();
1437 assert!(end_pos <= u32::MAX as usize);
1439 let (lines, multibyte_chars, non_narrow_chars) =
1440 analyze_source_file::analyze_source_file(&src[..], start_pos);
1444 src: Some(Lrc::new(src)),
1446 external_src: Lock::new(ExternalSource::Unneeded),
1448 end_pos: Pos::from_usize(end_pos),
1458 /// Returns the `BytePos` of the beginning of the current line.
1459 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1460 let line_index = self.lookup_line(pos).unwrap();
1461 self.lines[line_index]
1464 /// Add externally loaded source.
1465 /// If the hash of the input doesn't match or no input is supplied via None,
1466 /// it is interpreted as an error and the corresponding enum variant is set.
1467 /// The return value signifies whether some kind of source is present.
1468 pub fn add_external_src<F>(&self, get_src: F) -> bool
1470 F: FnOnce() -> Option<String>,
1473 *self.external_src.borrow(),
1474 ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1476 let src = get_src();
1477 let mut external_src = self.external_src.borrow_mut();
1478 // Check that no-one else have provided the source while we were getting it
1479 if let ExternalSource::Foreign {
1480 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1481 } = &mut *external_src
1483 if let Some(mut src) = src {
1484 // The src_hash needs to be computed on the pre-normalized src.
1485 if self.src_hash.matches(&src) {
1486 normalize_src(&mut src, BytePos::from_usize(0));
1487 *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1491 *src_kind = ExternalSourceKind::AbsentErr;
1496 self.src.is_some() || external_src.get_source().is_some()
1499 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1503 /// Gets a line from the list of pre-computed line-beginnings.
1504 /// The line number here is 0-based.
1505 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1506 fn get_until_newline(src: &str, begin: usize) -> &str {
1507 // We can't use `lines.get(line_number+1)` because we might
1508 // be parsing when we call this function and thus the current
1509 // line is the last one we have line info for.
1510 let slice = &src[begin..];
1511 match slice.find('\n') {
1512 Some(e) => &slice[..e],
1518 let line = self.lines.get(line_number)?;
1519 let begin: BytePos = *line - self.start_pos;
1523 if let Some(ref src) = self.src {
1524 Some(Cow::from(get_until_newline(src, begin)))
1525 } else if let Some(src) = self.external_src.borrow().get_source() {
1526 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1532 pub fn is_real_file(&self) -> bool {
1536 pub fn is_imported(&self) -> bool {
1540 pub fn count_lines(&self) -> usize {
1544 /// Finds the line containing the given position. The return value is the
1545 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1546 /// number. If the source_file is empty or the position is located before the
1547 /// first line, `None` is returned.
1548 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1549 match self.lines.binary_search(&pos) {
1550 Ok(idx) => Some(idx),
1552 Err(idx) => Some(idx - 1),
1556 pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
1557 if self.is_empty() {
1558 return self.start_pos..self.end_pos;
1561 assert!(line_index < self.lines.len());
1562 if line_index == (self.lines.len() - 1) {
1563 self.lines[line_index]..self.end_pos
1565 self.lines[line_index]..self.lines[line_index + 1]
1569 /// Returns whether or not the file contains the given `SourceMap` byte
1570 /// position. The position one past the end of the file is considered to be
1571 /// contained by the file. This implies that files for which `is_empty`
1572 /// returns true still contain one byte position according to this function.
1574 pub fn contains(&self, byte_pos: BytePos) -> bool {
1575 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1579 pub fn is_empty(&self) -> bool {
1580 self.start_pos == self.end_pos
1583 /// Calculates the original byte position relative to the start of the file
1584 /// based on the given byte position.
1585 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1586 // Diff before any records is 0. Otherwise use the previously recorded
1587 // diff as that applies to the following characters until a new diff
1589 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1590 Ok(i) => self.normalized_pos[i].diff,
1591 Err(i) if i == 0 => 0,
1592 Err(i) => self.normalized_pos[i - 1].diff,
1595 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1598 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1599 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1600 // The number of extra bytes due to multibyte chars in the `SourceFile`.
1601 let mut total_extra_bytes = 0;
1603 for mbc in self.multibyte_chars.iter() {
1604 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1606 // Every character is at least one byte, so we only
1607 // count the actual extra bytes.
1608 total_extra_bytes += mbc.bytes as u32 - 1;
1609 // We should never see a byte position in the middle of a
1611 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1617 assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1618 CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1621 /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1622 /// given `BytePos`.
1623 pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1624 let chpos = self.bytepos_to_file_charpos(pos);
1625 match self.lookup_line(pos) {
1627 let line = a + 1; // Line numbers start at 1
1628 let linebpos = self.lines[a];
1629 let linechpos = self.bytepos_to_file_charpos(linebpos);
1630 let col = chpos - linechpos;
1631 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1632 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1633 debug!("byte is on line: {}", line);
1634 assert!(chpos >= linechpos);
1641 /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1642 /// column offset when displayed, for a given `BytePos`.
1643 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1644 let (line, col_or_chpos) = self.lookup_file_pos(pos);
1646 let col = col_or_chpos;
1647 let linebpos = self.lines[line - 1];
1649 let start_width_idx = self
1651 .binary_search_by_key(&linebpos, |x| x.pos())
1652 .unwrap_or_else(|x| x);
1653 let end_width_idx = self
1655 .binary_search_by_key(&pos, |x| x.pos())
1656 .unwrap_or_else(|x| x);
1657 let special_chars = end_width_idx - start_width_idx;
1658 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1662 col.0 - special_chars + non_narrow
1664 (line, col, col_display)
1666 let chpos = col_or_chpos;
1668 let end_width_idx = self
1670 .binary_search_by_key(&pos, |x| x.pos())
1671 .unwrap_or_else(|x| x);
1672 let non_narrow: usize =
1673 self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1674 chpos.0 - end_width_idx + non_narrow
1676 (0, chpos, col_display)
1681 /// Normalizes the source code and records the normalizations.
1682 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1683 let mut normalized_pos = vec![];
1684 remove_bom(src, &mut normalized_pos);
1685 normalize_newlines(src, &mut normalized_pos);
1687 // Offset all the positions by start_pos to match the final file positions.
1688 for np in &mut normalized_pos {
1689 np.pos.0 += start_pos.0;
1695 /// Removes UTF-8 BOM, if any.
1696 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1697 if src.starts_with('\u{feff}') {
1699 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1703 /// Replaces `\r\n` with `\n` in-place in `src`.
1705 /// Returns error if there's a lone `\r` in the string.
1706 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1707 if !src.as_bytes().contains(&b'\r') {
1711 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1712 // While we *can* call `as_mut_vec` and do surgery on the live string
1713 // directly, let's rather steal the contents of `src`. This makes the code
1714 // safe even if a panic occurs.
1716 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1717 let mut gap_len = 0;
1718 let mut tail = buf.as_mut_slice();
1720 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1722 let idx = match find_crlf(&tail[gap_len..]) {
1724 Some(idx) => idx + gap_len,
1726 tail.copy_within(gap_len..idx, 0);
1727 tail = &mut tail[idx - gap_len..];
1728 if tail.len() == gap_len {
1731 cursor += idx - gap_len;
1733 normalized_pos.push(NormalizedPos {
1734 pos: BytePos::from_usize(cursor + 1),
1735 diff: original_gap + gap_len as u32,
1739 // Account for removed `\r`.
1740 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1741 let new_len = buf.len() - gap_len;
1743 buf.set_len(new_len);
1744 *src = String::from_utf8_unchecked(buf);
1747 fn find_crlf(src: &[u8]) -> Option<usize> {
1748 let mut search_idx = 0;
1749 while let Some(idx) = find_cr(&src[search_idx..]) {
1750 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1751 search_idx += idx + 1;
1754 return Some(search_idx + idx);
1759 fn find_cr(src: &[u8]) -> Option<usize> {
1760 src.iter().position(|&b| b == b'\r')
1764 // _____________________________________________________________________________
1765 // Pos, BytePos, CharPos
1769 fn from_usize(n: usize) -> Self;
1770 fn to_usize(&self) -> usize;
1771 fn from_u32(n: u32) -> Self;
1772 fn to_u32(&self) -> u32;
1775 macro_rules! impl_pos {
1779 $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1784 $vis struct $ident($inner_vis $inner_ty);
1786 impl Pos for $ident {
1788 fn from_usize(n: usize) -> $ident {
1789 $ident(n as $inner_ty)
1793 fn to_usize(&self) -> usize {
1798 fn from_u32(n: u32) -> $ident {
1799 $ident(n as $inner_ty)
1803 fn to_u32(&self) -> u32 {
1808 impl Add for $ident {
1809 type Output = $ident;
1812 fn add(self, rhs: $ident) -> $ident {
1813 $ident(self.0 + rhs.0)
1817 impl Sub for $ident {
1818 type Output = $ident;
1821 fn sub(self, rhs: $ident) -> $ident {
1822 $ident(self.0 - rhs.0)
1832 /// Keep this small (currently 32-bits), as AST contains a lot of them.
1833 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1834 pub struct BytePos(pub u32);
1836 /// A character offset.
1838 /// Because of multibyte UTF-8 characters, a byte offset
1839 /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`]
1840 /// values to `CharPos` values as necessary.
1841 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1842 pub struct CharPos(pub usize);
1845 impl<S: rustc_serialize::Encoder> Encodable<S> for BytePos {
1846 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1851 impl<D: rustc_serialize::Decoder> Decodable<D> for BytePos {
1852 fn decode(d: &mut D) -> Result<BytePos, D::Error> {
1853 Ok(BytePos(d.read_u32()?))
1857 // _____________________________________________________________________________
1858 // Loc, SourceFileAndLine, SourceFileAndBytePos
1861 /// A source code location used for error reporting.
1862 #[derive(Debug, Clone)]
1864 /// Information about the original source.
1865 pub file: Lrc<SourceFile>,
1866 /// The (1-based) line number.
1868 /// The (0-based) column offset.
1870 /// The (0-based) column offset when displayed.
1871 pub col_display: usize,
1874 // Used to be structural records.
1876 pub struct SourceFileAndLine {
1877 pub sf: Lrc<SourceFile>,
1881 pub struct SourceFileAndBytePos {
1882 pub sf: Lrc<SourceFile>,
1886 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1887 pub struct LineInfo {
1888 /// Index of line, starting from 0.
1889 pub line_index: usize,
1891 /// Column in line where span begins, starting from 0.
1892 pub start_col: CharPos,
1894 /// Column in line where span ends, starting from 0, exclusive.
1895 pub end_col: CharPos,
1898 pub struct FileLines {
1899 pub file: Lrc<SourceFile>,
1900 pub lines: Vec<LineInfo>,
1903 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1904 AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1906 // _____________________________________________________________________________
1907 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1910 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1912 #[derive(Clone, PartialEq, Eq, Debug)]
1913 pub enum SpanLinesError {
1914 DistinctSources(DistinctSources),
1917 #[derive(Clone, PartialEq, Eq, Debug)]
1918 pub enum SpanSnippetError {
1919 IllFormedSpan(Span),
1920 DistinctSources(DistinctSources),
1921 MalformedForSourcemap(MalformedSourceMapPositions),
1922 SourceNotAvailable { filename: FileName },
1925 #[derive(Clone, PartialEq, Eq, Debug)]
1926 pub struct DistinctSources {
1927 pub begin: (FileName, BytePos),
1928 pub end: (FileName, BytePos),
1931 #[derive(Clone, PartialEq, Eq, Debug)]
1932 pub struct MalformedSourceMapPositions {
1934 pub source_len: usize,
1935 pub begin_pos: BytePos,
1936 pub end_pos: BytePos,
1939 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1940 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1941 pub struct InnerSpan {
1947 pub fn new(start: usize, end: usize) -> InnerSpan {
1948 InnerSpan { start, end }
1952 /// Requirements for a `StableHashingContext` to be used in this crate.
1954 /// This is a hack to allow using the [`HashStable_Generic`] derive macro
1955 /// instead of implementing everything in rustc_middle.
1956 pub trait HashStableContext {
1957 fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
1958 fn hash_spans(&self) -> bool;
1959 fn span_data_to_lines_and_cols(
1962 ) -> Option<(Lrc<SourceFile>, usize, BytePos, usize, BytePos)>;
1965 impl<CTX> HashStable<CTX> for Span
1967 CTX: HashStableContext,
1969 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1970 /// fields (that would be similar to hashing pointers, since those are just
1971 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1972 /// triple, which stays the same even if the containing `SourceFile` has moved
1973 /// within the `SourceMap`.
1975 /// Also note that we are hashing byte offsets for the column, not unicode
1976 /// codepoint offsets. For the purpose of the hash that's sufficient.
1977 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1978 /// span starts and ends in the same file, which is almost always the case.
1979 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1980 const TAG_VALID_SPAN: u8 = 0;
1981 const TAG_INVALID_SPAN: u8 = 1;
1983 if !ctx.hash_spans() {
1987 self.ctxt().hash_stable(ctx, hasher);
1989 if self.is_dummy() {
1990 Hash::hash(&TAG_INVALID_SPAN, hasher);
1994 // If this is not an empty or invalid span, we want to hash the last
1995 // position that belongs to it, as opposed to hashing the first
1996 // position past it.
1997 let span = self.data();
1998 let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span)
2002 Hash::hash(&TAG_INVALID_SPAN, hasher);
2007 Hash::hash(&TAG_VALID_SPAN, hasher);
2008 // We truncate the stable ID hash and line and column numbers. The chances
2009 // of causing a collision this way should be minimal.
2010 Hash::hash(&(file.name_hash as u64), hasher);
2012 // Hash both the length and the end location (line/column) of a span. If we
2013 // hash only the length, for example, then two otherwise equal spans with
2014 // different end locations will have the same hash. This can cause a problem
2015 // during incremental compilation wherein a previous result for a query that
2016 // depends on the end location of a span will be incorrectly reused when the
2017 // end location of the span it depends on has changed (see issue #74890). A
2018 // similar analysis applies if some query depends specifically on the length
2019 // of the span, but we only hash the end location. So hash both.
2021 let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
2022 let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
2023 let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
2024 let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
2025 let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
2026 let len = (span.hi - span.lo).0;
2027 Hash::hash(&col_line, hasher);
2028 Hash::hash(&len, hasher);