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)]
20 #![feature(const_panic)]
21 #![feature(negative_impls)]
23 #![feature(min_specialization)]
26 extern crate rustc_macros;
28 use rustc_data_structures::AtomicRef;
29 use rustc_macros::HashStable_Generic;
30 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
32 mod caching_source_map_view;
34 pub use self::caching_source_map_view::CachingSourceMapView;
35 use source_map::SourceMap;
40 pub use hygiene::SyntaxContext;
41 use hygiene::Transparency;
42 pub use hygiene::{DesugaringKind, ExpnData, ExpnId, ExpnKind, ForLoopLoc, MacroKind};
44 use def_id::{CrateNum, DefId, LOCAL_CRATE};
47 pub use span_encoding::{Span, DUMMY_SP};
49 pub mod crate_disambiguator;
52 pub use symbol::{sym, Symbol};
54 mod analyze_source_file;
57 use rustc_data_structures::fingerprint::Fingerprint;
58 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
59 use rustc_data_structures::sync::{Lock, Lrc};
62 use std::cell::RefCell;
63 use std::cmp::{self, Ordering};
66 use std::ops::{Add, Range, Sub};
67 use std::path::{Path, PathBuf};
68 use std::str::FromStr;
69 use std::thread::LocalKey;
81 // Per-session global variables: this struct is stored in thread-local storage
82 // in such a way that it is accessible without any kind of handle to all
83 // threads within the compilation session, but is not accessible outside the
85 pub struct SessionGlobals {
86 symbol_interner: Lock<symbol::Interner>,
87 span_interner: Lock<span_encoding::SpanInterner>,
88 hygiene_data: Lock<hygiene::HygieneData>,
89 source_map: Lock<Option<Lrc<SourceMap>>>,
93 pub fn new(edition: Edition) -> SessionGlobals {
95 symbol_interner: Lock::new(symbol::Interner::fresh()),
96 span_interner: Lock::new(span_encoding::SpanInterner::default()),
97 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
98 source_map: Lock::new(None),
103 pub fn with_session_globals<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
104 let session_globals = SessionGlobals::new(edition);
105 SESSION_GLOBALS.set(&session_globals, f)
108 pub fn with_default_session_globals<R>(f: impl FnOnce() -> R) -> R {
109 with_session_globals(edition::DEFAULT_EDITION, f)
112 // If this ever becomes non thread-local, `decode_syntax_context`
113 // and `decode_expn_id` will need to be updated to handle concurrent
115 scoped_tls::scoped_thread_local!(pub static SESSION_GLOBALS: SessionGlobals);
117 // FIXME: Perhaps this should not implement Rustc{Decodable, Encodable}
119 // FIXME: We should use this enum or something like it to get rid of the
120 // use of magic `/rust/1.x/...` paths across the board.
121 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
122 #[derive(HashStable_Generic, Decodable, Encodable)]
123 pub enum RealFileName {
125 /// For de-virtualized paths (namely paths into libstd that have been mapped
126 /// to the appropriate spot on the local host's file system),
128 /// `local_path` is the (host-dependent) local path to the file.
130 /// `virtual_name` is the stable path rustc will store internally within
132 virtual_name: PathBuf,
137 /// Returns the path suitable for reading from the file system on the local host.
138 /// Avoid embedding this in build artifacts; see `stable_name()` for that.
139 pub fn local_path(&self) -> &Path {
141 RealFileName::Named(p)
142 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => &p,
146 /// Returns the path suitable for reading from the file system on the local host.
147 /// Avoid embedding this in build artifacts; see `stable_name()` for that.
148 pub fn into_local_path(self) -> PathBuf {
150 RealFileName::Named(p)
151 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => p,
155 /// Returns the path suitable for embedding into build artifacts. Note that
156 /// a virtualized path will not correspond to a valid file system path; see
157 /// `local_path()` for something that is more likely to return paths into the
158 /// local host file system.
159 pub fn stable_name(&self) -> &Path {
161 RealFileName::Named(p)
162 | RealFileName::Devirtualized { local_path: _, virtual_name: p } => &p,
167 /// Differentiates between real files and common virtual files.
168 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
169 #[derive(HashStable_Generic, Decodable, Encodable)]
172 /// Call to `quote!`.
176 /// Hack in `src/librustc_ast/parse.rs`.
179 ProcMacroSourceCode(u64),
180 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
182 /// Strings provided as crate attributes in the CLI.
184 /// Custom sources for explicit parser calls from plugins and drivers.
186 DocTest(PathBuf, isize),
187 /// Post-substitution inline assembly from LLVM.
191 impl std::fmt::Display for FileName {
192 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195 Real(RealFileName::Named(ref path)) => write!(fmt, "{}", path.display()),
196 // FIXME: might be nice to display both components of Devirtualized.
197 // But for now (to backport fix for issue #70924), best to not
198 // perturb diagnostics so its obvious test suite still works.
199 Real(RealFileName::Devirtualized { ref local_path, virtual_name: _ }) => {
200 write!(fmt, "{}", local_path.display())
202 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
203 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
204 Anon(_) => write!(fmt, "<anon>"),
205 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
206 CfgSpec(_) => write!(fmt, "<cfgspec>"),
207 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
208 Custom(ref s) => write!(fmt, "<{}>", s),
209 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
210 InlineAsm(_) => write!(fmt, "<inline asm>"),
215 impl From<PathBuf> for FileName {
216 fn from(p: PathBuf) -> Self {
217 assert!(!p.to_string_lossy().ends_with('>'));
218 FileName::Real(RealFileName::Named(p))
223 pub fn is_real(&self) -> bool {
229 | ProcMacroSourceCode(_)
235 | InlineAsm(_) => false,
239 pub fn macro_expansion_source_code(src: &str) -> FileName {
240 let mut hasher = StableHasher::new();
241 src.hash(&mut hasher);
242 FileName::MacroExpansion(hasher.finish())
245 pub fn anon_source_code(src: &str) -> FileName {
246 let mut hasher = StableHasher::new();
247 src.hash(&mut hasher);
248 FileName::Anon(hasher.finish())
251 pub fn proc_macro_source_code(src: &str) -> FileName {
252 let mut hasher = StableHasher::new();
253 src.hash(&mut hasher);
254 FileName::ProcMacroSourceCode(hasher.finish())
257 pub fn cfg_spec_source_code(src: &str) -> FileName {
258 let mut hasher = StableHasher::new();
259 src.hash(&mut hasher);
260 FileName::QuoteExpansion(hasher.finish())
263 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
264 let mut hasher = StableHasher::new();
265 src.hash(&mut hasher);
266 FileName::CliCrateAttr(hasher.finish())
269 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
270 FileName::DocTest(path, line)
273 pub fn inline_asm_source_code(src: &str) -> FileName {
274 let mut hasher = StableHasher::new();
275 src.hash(&mut hasher);
276 FileName::InlineAsm(hasher.finish())
280 /// Represents a span.
282 /// Spans represent a region of code, used for error reporting. Positions in spans
283 /// are *absolute* positions from the beginning of the [`SourceMap`], not positions
284 /// relative to [`SourceFile`]s. Methods on the `SourceMap` can be used to relate spans back
285 /// to the original source.
287 /// You must be careful if the span crosses more than one file, since you will not be
288 /// able to use many of the functions on spans in source_map and you cannot assume
289 /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the
290 /// [`BytePos`] range between files.
292 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
293 /// sent to other threads, but some pieces of performance infra run in a separate thread.
294 /// Using `Span` is generally preferred.
295 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
296 pub struct SpanData {
299 /// Information about where the macro came from, if this piece of
300 /// code was created by a macro expansion.
301 pub ctxt: SyntaxContext,
306 pub fn span(&self) -> Span {
307 Span::new(self.lo, self.hi, self.ctxt)
310 pub fn with_lo(&self, lo: BytePos) -> Span {
311 Span::new(lo, self.hi, self.ctxt)
314 pub fn with_hi(&self, hi: BytePos) -> Span {
315 Span::new(self.lo, hi, self.ctxt)
318 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
319 Span::new(self.lo, self.hi, ctxt)
323 // The interner is pointed to by a thread local value which is only set on the main thread
324 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
325 // to avoid panics and other errors, even though it would be memory safe to do so.
326 #[cfg(not(parallel_compiler))]
327 impl !Send for Span {}
328 #[cfg(not(parallel_compiler))]
329 impl !Sync for Span {}
331 impl PartialOrd for Span {
332 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
333 PartialOrd::partial_cmp(&self.data(), &rhs.data())
337 fn cmp(&self, rhs: &Self) -> Ordering {
338 Ord::cmp(&self.data(), &rhs.data())
342 /// A collection of `Span`s.
344 /// Spans have two orthogonal attributes:
346 /// - They can be *primary spans*. In this case they are the locus of
347 /// the error, and would be rendered with `^^^`.
348 /// - They can have a *label*. In this case, the label is written next
349 /// to the mark in the snippet when we render.
350 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
351 pub struct MultiSpan {
352 primary_spans: Vec<Span>,
353 span_labels: Vec<(Span, String)>,
358 pub fn lo(self) -> BytePos {
362 pub fn with_lo(self, lo: BytePos) -> Span {
363 self.data().with_lo(lo)
366 pub fn hi(self) -> BytePos {
370 pub fn with_hi(self, hi: BytePos) -> Span {
371 self.data().with_hi(hi)
374 pub fn ctxt(self) -> SyntaxContext {
378 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
379 self.data().with_ctxt(ctxt)
382 /// Returns `true` if this is a dummy span with any hygienic context.
384 pub fn is_dummy(self) -> bool {
385 let span = self.data();
386 span.lo.0 == 0 && span.hi.0 == 0
389 /// Returns `true` if this span comes from a macro or desugaring.
391 pub fn from_expansion(self) -> bool {
392 self.ctxt() != SyntaxContext::root()
395 /// Returns `true` if `span` originates in a derive-macro's expansion.
396 pub fn in_derive_expansion(self) -> bool {
397 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
401 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
402 Span::new(lo, hi, SyntaxContext::root())
405 /// Returns a new span representing an empty span at the beginning of this span.
407 pub fn shrink_to_lo(self) -> Span {
408 let span = self.data();
409 span.with_hi(span.lo)
411 /// Returns a new span representing an empty span at the end of this span.
413 pub fn shrink_to_hi(self) -> Span {
414 let span = self.data();
415 span.with_lo(span.hi)
419 /// Returns `true` if `hi == lo`.
420 pub fn is_empty(&self) -> bool {
421 let span = self.data();
425 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
426 pub fn substitute_dummy(self, other: Span) -> Span {
427 if self.is_dummy() { other } else { self }
430 /// Returns `true` if `self` fully encloses `other`.
431 pub fn contains(self, other: Span) -> bool {
432 let span = self.data();
433 let other = other.data();
434 span.lo <= other.lo && other.hi <= span.hi
437 /// Returns `true` if `self` touches `other`.
438 pub fn overlaps(self, other: Span) -> bool {
439 let span = self.data();
440 let other = other.data();
441 span.lo < other.hi && other.lo < span.hi
444 /// Returns `true` if the spans are equal with regards to the source text.
446 /// Use this instead of `==` when either span could be generated code,
447 /// and you only care that they point to the same bytes of source text.
448 pub fn source_equal(&self, other: &Span) -> bool {
449 let span = self.data();
450 let other = other.data();
451 span.lo == other.lo && span.hi == other.hi
454 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
455 pub fn trim_start(self, other: Span) -> Option<Span> {
456 let span = self.data();
457 let other = other.data();
458 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
461 /// Returns the source span -- this is either the supplied span, or the span for
462 /// the macro callsite that expanded to it.
463 pub fn source_callsite(self) -> Span {
464 let expn_data = self.ctxt().outer_expn_data();
465 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
468 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
470 pub fn parent(self) -> Option<Span> {
471 let expn_data = self.ctxt().outer_expn_data();
472 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
475 /// Edition of the crate from which this span came.
476 pub fn edition(self) -> edition::Edition {
477 self.ctxt().edition()
481 pub fn rust_2015(&self) -> bool {
482 self.edition() == edition::Edition::Edition2015
486 pub fn rust_2018(&self) -> bool {
487 self.edition() >= edition::Edition::Edition2018
491 pub fn rust_2021(&self) -> bool {
492 self.edition() >= edition::Edition::Edition2021
495 /// Returns the source callee.
497 /// Returns `None` if the supplied span has no expansion trace,
498 /// else returns the `ExpnData` for the macro definition
499 /// corresponding to the source callsite.
500 pub fn source_callee(self) -> Option<ExpnData> {
501 fn source_callee(expn_data: ExpnData) -> ExpnData {
502 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
503 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
505 let expn_data = self.ctxt().outer_expn_data();
506 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
509 /// Checks if a span is "internal" to a macro in which `#[unstable]`
510 /// items can be used (that is, a macro marked with
511 /// `#[allow_internal_unstable]`).
512 pub fn allows_unstable(&self, feature: Symbol) -> bool {
515 .allow_internal_unstable
516 .map_or(false, |features| features.iter().any(|&f| f == feature))
519 /// Checks if this span arises from a compiler desugaring of kind `kind`.
520 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
521 match self.ctxt().outer_expn_data().kind {
522 ExpnKind::Desugaring(k) => k == kind,
527 /// Returns the compiler desugaring that created this span, or `None`
528 /// if this span is not from a desugaring.
529 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
530 match self.ctxt().outer_expn_data().kind {
531 ExpnKind::Desugaring(k) => Some(k),
536 /// Checks if a span is "internal" to a macro in which `unsafe`
537 /// can be used without triggering the `unsafe_code` lint.
538 // (that is, a macro marked with `#[allow_internal_unsafe]`).
539 pub fn allows_unsafe(&self) -> bool {
540 self.ctxt().outer_expn_data().allow_internal_unsafe
543 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
544 let mut prev_span = DUMMY_SP;
545 std::iter::from_fn(move || {
547 let expn_data = self.ctxt().outer_expn_data();
548 if expn_data.is_root() {
552 let is_recursive = expn_data.call_site.source_equal(&prev_span);
555 self = expn_data.call_site;
557 // Don't print recursive invocations.
559 return Some(expn_data);
565 /// Returns a `Span` that would enclose both `self` and `end`.
569 /// self lorem ipsum end
570 /// ^^^^^^^^^^^^^^^^^^^^
572 pub fn to(self, end: Span) -> Span {
573 let span_data = self.data();
574 let end_data = end.data();
575 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
576 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
577 // have an incomplete span than a completely nonsensical one.
578 if span_data.ctxt != end_data.ctxt {
579 if span_data.ctxt == SyntaxContext::root() {
581 } else if end_data.ctxt == SyntaxContext::root() {
584 // Both spans fall within a macro.
585 // FIXME(estebank): check if it is the *same* macro.
588 cmp::min(span_data.lo, end_data.lo),
589 cmp::max(span_data.hi, end_data.hi),
590 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
594 /// Returns a `Span` between the end of `self` to the beginning of `end`.
598 /// self lorem ipsum end
601 pub fn between(self, end: Span) -> Span {
602 let span = self.data();
603 let end = end.data();
607 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
611 /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
615 /// self lorem ipsum end
616 /// ^^^^^^^^^^^^^^^^^
618 pub fn until(self, end: Span) -> Span {
619 let span = self.data();
620 let end = end.data();
624 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
628 pub fn from_inner(self, inner: InnerSpan) -> Span {
629 let span = self.data();
631 span.lo + BytePos::from_usize(inner.start),
632 span.lo + BytePos::from_usize(inner.end),
637 /// Equivalent of `Span::def_site` from the proc macro API,
638 /// except that the location is taken from the `self` span.
639 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
640 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
643 /// Equivalent of `Span::call_site` from the proc macro API,
644 /// except that the location is taken from the `self` span.
645 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
646 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
649 /// Equivalent of `Span::mixed_site` from the proc macro API,
650 /// except that the location is taken from the `self` span.
651 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
652 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
655 /// Produces a span with the same location as `self` and context produced by a macro with the
656 /// given ID and transparency, assuming that macro was defined directly and not produced by
657 /// some other macro (which is the case for built-in and procedural macros).
658 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
659 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
663 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
664 let span = self.data();
665 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
669 pub fn remove_mark(&mut self) -> ExpnId {
670 let mut span = self.data();
671 let mark = span.ctxt.remove_mark();
672 *self = Span::new(span.lo, span.hi, span.ctxt);
677 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
678 let mut span = self.data();
679 let mark = span.ctxt.adjust(expn_id);
680 *self = Span::new(span.lo, span.hi, span.ctxt);
685 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
686 let mut span = self.data();
687 let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
688 *self = Span::new(span.lo, span.hi, span.ctxt);
693 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
694 let mut span = self.data();
695 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
696 *self = Span::new(span.lo, span.hi, span.ctxt);
701 pub fn reverse_glob_adjust(
705 ) -> Option<Option<ExpnId>> {
706 let mut span = self.data();
707 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
708 *self = Span::new(span.lo, span.hi, span.ctxt);
713 pub fn normalize_to_macros_2_0(self) -> Span {
714 let span = self.data();
715 span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
719 pub fn normalize_to_macro_rules(self) -> Span {
720 let span = self.data();
721 span.with_ctxt(span.ctxt.normalize_to_macro_rules())
725 /// A span together with some additional data.
726 #[derive(Clone, Debug)]
727 pub struct SpanLabel {
728 /// The span we are going to include in the final snippet.
731 /// Is this a primary span? This is the "locus" of the message,
732 /// and is indicated with a `^^^^` underline, versus `----`.
733 pub is_primary: bool,
735 /// What label should we attach to this span (if any)?
736 pub label: Option<String>,
739 impl Default for Span {
740 fn default() -> Self {
745 impl<E: Encoder> Encodable<E> for Span {
746 default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
747 let span = self.data();
748 s.emit_struct("Span", 2, |s| {
749 s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?;
750 s.emit_struct_field("hi", 1, |s| span.hi.encode(s))
754 impl<D: Decoder> Decodable<D> for Span {
755 default fn decode(s: &mut D) -> Result<Span, D::Error> {
756 s.read_struct("Span", 2, |d| {
757 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
758 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
760 Ok(Span::new(lo, hi, SyntaxContext::root()))
765 /// Calls the provided closure, using the provided `SourceMap` to format
766 /// any spans that are debug-printed during the closure's execution.
768 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
769 /// (see `rustc_interface::callbacks::span_debug1`). However, some parts
770 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
771 /// a `TyCtxt` is available. In this case, we fall back to
772 /// the `SourceMap` provided to this function. If that is not available,
773 /// we fall back to printing the raw `Span` field values.
774 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
775 SESSION_GLOBALS.with(|session_globals| {
776 *session_globals.source_map.borrow_mut() = Some(source_map);
778 struct ClearSourceMap;
779 impl Drop for ClearSourceMap {
781 SESSION_GLOBALS.with(|session_globals| {
782 session_globals.source_map.borrow_mut().take();
787 let _guard = ClearSourceMap;
791 pub fn debug_with_source_map(
793 f: &mut fmt::Formatter<'_>,
794 source_map: &SourceMap,
796 write!(f, "{} ({:?})", source_map.span_to_string(span), span.ctxt())
799 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
800 SESSION_GLOBALS.with(|session_globals| {
801 if let Some(source_map) = &*session_globals.source_map.borrow() {
802 debug_with_source_map(span, f, source_map)
804 f.debug_struct("Span")
805 .field("lo", &span.lo())
806 .field("hi", &span.hi())
807 .field("ctxt", &span.ctxt())
813 impl fmt::Debug for Span {
814 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
815 (*SPAN_DEBUG)(*self, f)
819 impl fmt::Debug for SpanData {
820 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
821 (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
827 pub fn new() -> MultiSpan {
828 MultiSpan { primary_spans: vec![], span_labels: vec![] }
831 pub fn from_span(primary_span: Span) -> MultiSpan {
832 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
835 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
837 MultiSpan { primary_spans: vec, span_labels: vec![] }
840 pub fn push_span_label(&mut self, span: Span, label: String) {
841 self.span_labels.push((span, label));
844 /// Selects the first primary span (if any).
845 pub fn primary_span(&self) -> Option<Span> {
846 self.primary_spans.first().cloned()
849 /// Returns all primary spans.
850 pub fn primary_spans(&self) -> &[Span] {
854 /// Returns `true` if any of the primary spans are displayable.
855 pub fn has_primary_spans(&self) -> bool {
856 self.primary_spans.iter().any(|sp| !sp.is_dummy())
859 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
860 pub fn is_dummy(&self) -> bool {
861 let mut is_dummy = true;
862 for span in &self.primary_spans {
863 if !span.is_dummy() {
870 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
871 /// display well (like std macros). Returns whether replacements occurred.
872 pub fn replace(&mut self, before: Span, after: Span) -> bool {
873 let mut replacements_occurred = false;
874 for primary_span in &mut self.primary_spans {
875 if *primary_span == before {
876 *primary_span = after;
877 replacements_occurred = true;
880 for span_label in &mut self.span_labels {
881 if span_label.0 == before {
882 span_label.0 = after;
883 replacements_occurred = true;
886 replacements_occurred
889 /// Returns the strings to highlight. We always ensure that there
890 /// is an entry for each of the primary spans -- for each primary
891 /// span `P`, if there is at least one label with span `P`, we return
892 /// those labels (marked as primary). But otherwise we return
893 /// `SpanLabel` instances with empty labels.
894 pub fn span_labels(&self) -> Vec<SpanLabel> {
895 let is_primary = |span| self.primary_spans.contains(&span);
897 let mut span_labels = self
900 .map(|&(span, ref label)| SpanLabel {
902 is_primary: is_primary(span),
903 label: Some(label.clone()),
905 .collect::<Vec<_>>();
907 for &span in &self.primary_spans {
908 if !span_labels.iter().any(|sl| sl.span == span) {
909 span_labels.push(SpanLabel { span, is_primary: true, label: None });
916 /// Returns `true` if any of the span labels is displayable.
917 pub fn has_span_labels(&self) -> bool {
918 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
922 impl From<Span> for MultiSpan {
923 fn from(span: Span) -> MultiSpan {
924 MultiSpan::from_span(span)
928 impl From<Vec<Span>> for MultiSpan {
929 fn from(spans: Vec<Span>) -> MultiSpan {
930 MultiSpan::from_spans(spans)
934 /// Identifies an offset of a multi-byte character in a `SourceFile`.
935 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
936 pub struct MultiByteChar {
937 /// The absolute offset of the character in the `SourceMap`.
939 /// The number of bytes, `>= 2`.
943 /// Identifies an offset of a non-narrow character in a `SourceFile`.
944 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
945 pub enum NonNarrowChar {
946 /// Represents a zero-width character.
948 /// Represents a wide (full-width) character.
950 /// Represents a tab character, represented visually with a width of 4 characters.
955 fn new(pos: BytePos, width: usize) -> Self {
957 0 => NonNarrowChar::ZeroWidth(pos),
958 2 => NonNarrowChar::Wide(pos),
959 4 => NonNarrowChar::Tab(pos),
960 _ => panic!("width {} given for non-narrow character", width),
964 /// Returns the absolute offset of the character in the `SourceMap`.
965 pub fn pos(&self) -> BytePos {
967 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
971 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
972 pub fn width(&self) -> usize {
974 NonNarrowChar::ZeroWidth(_) => 0,
975 NonNarrowChar::Wide(_) => 2,
976 NonNarrowChar::Tab(_) => 4,
981 impl Add<BytePos> for NonNarrowChar {
984 fn add(self, rhs: BytePos) -> Self {
986 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
987 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
988 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
993 impl Sub<BytePos> for NonNarrowChar {
996 fn sub(self, rhs: BytePos) -> Self {
998 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
999 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
1000 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
1005 /// Identifies an offset of a character that was normalized away from `SourceFile`.
1006 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
1007 pub struct NormalizedPos {
1008 /// The absolute offset of the character in the `SourceMap`.
1010 /// The difference between original and normalized string at position.
1014 #[derive(PartialEq, Eq, Clone, Debug)]
1015 pub enum ExternalSource {
1016 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
1019 kind: ExternalSourceKind,
1020 /// This SourceFile's byte-offset within the source_map of its original crate.
1021 original_start_pos: BytePos,
1022 /// The end of this SourceFile within the source_map of its original crate.
1023 original_end_pos: BytePos,
1027 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1028 #[derive(PartialEq, Eq, Clone, Debug)]
1029 pub enum ExternalSourceKind {
1030 /// The external source has been loaded already.
1031 Present(Lrc<String>),
1032 /// No attempt has been made to load the external source.
1034 /// A failed attempt has been made to load the external source.
1039 impl ExternalSource {
1040 pub fn get_source(&self) -> Option<&Lrc<String>> {
1042 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1049 pub struct OffsetOverflowError;
1051 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1052 pub enum SourceFileHashAlgorithm {
1058 impl FromStr for SourceFileHashAlgorithm {
1061 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1063 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1064 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1065 "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1071 rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm);
1073 /// The hash of the on-disk source file used for debug info.
1074 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1075 #[derive(HashStable_Generic, Encodable, Decodable)]
1076 pub struct SourceFileHash {
1077 pub kind: SourceFileHashAlgorithm,
1081 impl SourceFileHash {
1082 pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1083 let mut hash = SourceFileHash { kind, value: Default::default() };
1084 let len = hash.hash_len();
1085 let value = &mut hash.value[..len];
1086 let data = src.as_bytes();
1088 SourceFileHashAlgorithm::Md5 => {
1089 value.copy_from_slice(&Md5::digest(data));
1091 SourceFileHashAlgorithm::Sha1 => {
1092 value.copy_from_slice(&Sha1::digest(data));
1094 SourceFileHashAlgorithm::Sha256 => {
1095 value.copy_from_slice(&Sha256::digest(data));
1101 /// Check if the stored hash matches the hash of the string.
1102 pub fn matches(&self, src: &str) -> bool {
1103 Self::new(self.kind, src) == *self
1106 /// The bytes of the hash.
1107 pub fn hash_bytes(&self) -> &[u8] {
1108 let len = self.hash_len();
1112 fn hash_len(&self) -> usize {
1114 SourceFileHashAlgorithm::Md5 => 16,
1115 SourceFileHashAlgorithm::Sha1 => 20,
1116 SourceFileHashAlgorithm::Sha256 => 32,
1121 /// A single source in the [`SourceMap`].
1123 pub struct SourceFile {
1124 /// The name of the file that the source came from. Source that doesn't
1125 /// originate from files has names between angle brackets by convention
1126 /// (e.g., `<anon>`).
1128 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
1129 pub name_was_remapped: bool,
1130 /// The unmapped path of the file that the source came from.
1131 /// Set to `None` if the `SourceFile` was imported from an external crate.
1132 pub unmapped_path: Option<FileName>,
1133 /// The complete source code.
1134 pub src: Option<Lrc<String>>,
1135 /// The source code's hash.
1136 pub src_hash: SourceFileHash,
1137 /// The external source code (used for external crates, which will have a `None`
1138 /// value as `self.src`.
1139 pub external_src: Lock<ExternalSource>,
1140 /// The start position of this source in the `SourceMap`.
1141 pub start_pos: BytePos,
1142 /// The end position of this source in the `SourceMap`.
1143 pub end_pos: BytePos,
1144 /// Locations of lines beginnings in the source code.
1145 pub lines: Vec<BytePos>,
1146 /// Locations of multi-byte characters in the source code.
1147 pub multibyte_chars: Vec<MultiByteChar>,
1148 /// Width of characters that are not narrow in the source code.
1149 pub non_narrow_chars: Vec<NonNarrowChar>,
1150 /// Locations of characters removed during normalization.
1151 pub normalized_pos: Vec<NormalizedPos>,
1152 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1153 pub name_hash: u128,
1154 /// Indicates which crate this `SourceFile` was imported from.
1158 impl<S: Encoder> Encodable<S> for SourceFile {
1159 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1160 s.emit_struct("SourceFile", 8, |s| {
1161 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
1162 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
1163 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
1164 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
1165 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
1166 s.emit_struct_field("lines", 5, |s| {
1167 let lines = &self.lines[..];
1168 // Store the length.
1169 s.emit_u32(lines.len() as u32)?;
1171 if !lines.is_empty() {
1172 // In order to preserve some space, we exploit the fact that
1173 // the lines list is sorted and individual lines are
1174 // probably not that long. Because of that we can store lines
1175 // as a difference list, using as little space as possible
1176 // for the differences.
1177 let max_line_length = if lines.len() == 1 {
1182 .map(|&[fst, snd]| snd - fst)
1183 .map(|bp| bp.to_usize())
1188 let bytes_per_diff: u8 = match max_line_length {
1190 0x100..=0xFFFF => 2,
1194 // Encode the number of bytes used per diff.
1195 bytes_per_diff.encode(s)?;
1197 // Encode the first element.
1198 lines[0].encode(s)?;
1200 let diff_iter = lines[..].array_windows().map(|&[fst, snd]| snd - fst);
1202 match bytes_per_diff {
1204 for diff in diff_iter {
1205 (diff.0 as u8).encode(s)?
1209 for diff in diff_iter {
1210 (diff.0 as u16).encode(s)?
1214 for diff in diff_iter {
1218 _ => unreachable!(),
1224 s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
1225 s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
1226 s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
1227 s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))?;
1228 s.emit_struct_field("cnum", 10, |s| self.cnum.encode(s))
1233 impl<D: Decoder> Decodable<D> for SourceFile {
1234 fn decode(d: &mut D) -> Result<SourceFile, D::Error> {
1235 d.read_struct("SourceFile", 8, |d| {
1236 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1237 let name_was_remapped: bool =
1238 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1239 let src_hash: SourceFileHash =
1240 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1241 let start_pos: BytePos =
1242 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1243 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1244 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1245 let num_lines: u32 = Decodable::decode(d)?;
1246 let mut lines = Vec::with_capacity(num_lines as usize);
1249 // Read the number of bytes used per diff.
1250 let bytes_per_diff: u8 = Decodable::decode(d)?;
1252 // Read the first element.
1253 let mut line_start: BytePos = Decodable::decode(d)?;
1254 lines.push(line_start);
1256 for _ in 1..num_lines {
1257 let diff = match bytes_per_diff {
1258 1 => d.read_u8()? as u32,
1259 2 => d.read_u16()? as u32,
1261 _ => unreachable!(),
1264 line_start = line_start + BytePos(diff);
1266 lines.push(line_start);
1272 let multibyte_chars: Vec<MultiByteChar> =
1273 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1274 let non_narrow_chars: Vec<NonNarrowChar> =
1275 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1276 let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1277 let normalized_pos: Vec<NormalizedPos> =
1278 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1279 let cnum: CrateNum = d.read_struct_field("cnum", 10, |d| Decodable::decode(d))?;
1283 unmapped_path: None,
1288 // Unused - the metadata decoder will construct
1289 // a new SourceFile, filling in `external_src` properly
1290 external_src: Lock::new(ExternalSource::Unneeded),
1302 impl fmt::Debug for SourceFile {
1303 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1304 write!(fmt, "SourceFile({})", self.name)
1311 name_was_remapped: bool,
1312 unmapped_path: FileName,
1315 hash_kind: SourceFileHashAlgorithm,
1317 // Compute the file hash before any normalization.
1318 let src_hash = SourceFileHash::new(hash_kind, &src);
1319 let normalized_pos = normalize_src(&mut src, start_pos);
1322 let mut hasher: StableHasher = StableHasher::new();
1323 name.hash(&mut hasher);
1324 hasher.finish::<u128>()
1326 let end_pos = start_pos.to_usize() + src.len();
1327 assert!(end_pos <= u32::MAX as usize);
1329 let (lines, multibyte_chars, non_narrow_chars) =
1330 analyze_source_file::analyze_source_file(&src[..], start_pos);
1335 unmapped_path: Some(unmapped_path),
1336 src: Some(Lrc::new(src)),
1338 external_src: Lock::new(ExternalSource::Unneeded),
1340 end_pos: Pos::from_usize(end_pos),
1350 /// Returns the `BytePos` of the beginning of the current line.
1351 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1352 let line_index = self.lookup_line(pos).unwrap();
1353 self.lines[line_index]
1356 /// Add externally loaded source.
1357 /// If the hash of the input doesn't match or no input is supplied via None,
1358 /// it is interpreted as an error and the corresponding enum variant is set.
1359 /// The return value signifies whether some kind of source is present.
1360 pub fn add_external_src<F>(&self, get_src: F) -> bool
1362 F: FnOnce() -> Option<String>,
1365 *self.external_src.borrow(),
1366 ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1368 let src = get_src();
1369 let mut external_src = self.external_src.borrow_mut();
1370 // Check that no-one else have provided the source while we were getting it
1371 if let ExternalSource::Foreign {
1372 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1373 } = &mut *external_src
1375 if let Some(mut src) = src {
1376 // The src_hash needs to be computed on the pre-normalized src.
1377 if self.src_hash.matches(&src) {
1378 normalize_src(&mut src, BytePos::from_usize(0));
1379 *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1383 *src_kind = ExternalSourceKind::AbsentErr;
1388 self.src.is_some() || external_src.get_source().is_some()
1391 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1395 /// Gets a line from the list of pre-computed line-beginnings.
1396 /// The line number here is 0-based.
1397 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1398 fn get_until_newline(src: &str, begin: usize) -> &str {
1399 // We can't use `lines.get(line_number+1)` because we might
1400 // be parsing when we call this function and thus the current
1401 // line is the last one we have line info for.
1402 let slice = &src[begin..];
1403 match slice.find('\n') {
1404 Some(e) => &slice[..e],
1410 let line = self.lines.get(line_number)?;
1411 let begin: BytePos = *line - self.start_pos;
1415 if let Some(ref src) = self.src {
1416 Some(Cow::from(get_until_newline(src, begin)))
1417 } else if let Some(src) = self.external_src.borrow().get_source() {
1418 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1424 pub fn is_real_file(&self) -> bool {
1428 pub fn is_imported(&self) -> bool {
1432 pub fn count_lines(&self) -> usize {
1436 /// Finds the line containing the given position. The return value is the
1437 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1438 /// number. If the source_file is empty or the position is located before the
1439 /// first line, `None` is returned.
1440 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1441 if self.lines.is_empty() {
1445 let line_index = lookup_line(&self.lines[..], pos);
1446 assert!(line_index < self.lines.len() as isize);
1447 if line_index >= 0 { Some(line_index as usize) } else { None }
1450 pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
1451 if self.is_empty() {
1452 return self.start_pos..self.end_pos;
1455 assert!(line_index < self.lines.len());
1456 if line_index == (self.lines.len() - 1) {
1457 self.lines[line_index]..self.end_pos
1459 self.lines[line_index]..self.lines[line_index + 1]
1463 /// Returns whether or not the file contains the given `SourceMap` byte
1464 /// position. The position one past the end of the file is considered to be
1465 /// contained by the file. This implies that files for which `is_empty`
1466 /// returns true still contain one byte position according to this function.
1468 pub fn contains(&self, byte_pos: BytePos) -> bool {
1469 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1473 pub fn is_empty(&self) -> bool {
1474 self.start_pos == self.end_pos
1477 /// Calculates the original byte position relative to the start of the file
1478 /// based on the given byte position.
1479 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1480 // Diff before any records is 0. Otherwise use the previously recorded
1481 // diff as that applies to the following characters until a new diff
1483 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1484 Ok(i) => self.normalized_pos[i].diff,
1485 Err(i) if i == 0 => 0,
1486 Err(i) => self.normalized_pos[i - 1].diff,
1489 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1492 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1493 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1494 // The number of extra bytes due to multibyte chars in the `SourceFile`.
1495 let mut total_extra_bytes = 0;
1497 for mbc in self.multibyte_chars.iter() {
1498 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1500 // Every character is at least one byte, so we only
1501 // count the actual extra bytes.
1502 total_extra_bytes += mbc.bytes as u32 - 1;
1503 // We should never see a byte position in the middle of a
1505 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1511 assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1512 CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1515 /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1516 /// given `BytePos`.
1517 pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1518 let chpos = self.bytepos_to_file_charpos(pos);
1519 match self.lookup_line(pos) {
1521 let line = a + 1; // Line numbers start at 1
1522 let linebpos = self.lines[a];
1523 let linechpos = self.bytepos_to_file_charpos(linebpos);
1524 let col = chpos - linechpos;
1525 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1526 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1527 debug!("byte is on line: {}", line);
1528 assert!(chpos >= linechpos);
1535 /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1536 /// column offset when displayed, for a given `BytePos`.
1537 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1538 let (line, col_or_chpos) = self.lookup_file_pos(pos);
1540 let col = col_or_chpos;
1541 let linebpos = self.lines[line - 1];
1543 let start_width_idx = self
1545 .binary_search_by_key(&linebpos, |x| x.pos())
1546 .unwrap_or_else(|x| x);
1547 let end_width_idx = self
1549 .binary_search_by_key(&pos, |x| x.pos())
1550 .unwrap_or_else(|x| x);
1551 let special_chars = end_width_idx - start_width_idx;
1552 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1556 col.0 - special_chars + non_narrow
1558 (line, col, col_display)
1560 let chpos = col_or_chpos;
1562 let end_width_idx = self
1564 .binary_search_by_key(&pos, |x| x.pos())
1565 .unwrap_or_else(|x| x);
1566 let non_narrow: usize =
1567 self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1568 chpos.0 - end_width_idx + non_narrow
1570 (0, chpos, col_display)
1575 /// Normalizes the source code and records the normalizations.
1576 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1577 let mut normalized_pos = vec![];
1578 remove_bom(src, &mut normalized_pos);
1579 normalize_newlines(src, &mut normalized_pos);
1581 // Offset all the positions by start_pos to match the final file positions.
1582 for np in &mut normalized_pos {
1583 np.pos.0 += start_pos.0;
1589 /// Removes UTF-8 BOM, if any.
1590 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1591 if src.starts_with('\u{feff}') {
1593 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1597 /// Replaces `\r\n` with `\n` in-place in `src`.
1599 /// Returns error if there's a lone `\r` in the string.
1600 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1601 if !src.as_bytes().contains(&b'\r') {
1605 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1606 // While we *can* call `as_mut_vec` and do surgery on the live string
1607 // directly, let's rather steal the contents of `src`. This makes the code
1608 // safe even if a panic occurs.
1610 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1611 let mut gap_len = 0;
1612 let mut tail = buf.as_mut_slice();
1614 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1616 let idx = match find_crlf(&tail[gap_len..]) {
1618 Some(idx) => idx + gap_len,
1620 tail.copy_within(gap_len..idx, 0);
1621 tail = &mut tail[idx - gap_len..];
1622 if tail.len() == gap_len {
1625 cursor += idx - gap_len;
1627 normalized_pos.push(NormalizedPos {
1628 pos: BytePos::from_usize(cursor + 1),
1629 diff: original_gap + gap_len as u32,
1633 // Account for removed `\r`.
1634 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1635 let new_len = buf.len() - gap_len;
1637 buf.set_len(new_len);
1638 *src = String::from_utf8_unchecked(buf);
1641 fn find_crlf(src: &[u8]) -> Option<usize> {
1642 let mut search_idx = 0;
1643 while let Some(idx) = find_cr(&src[search_idx..]) {
1644 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1645 search_idx += idx + 1;
1648 return Some(search_idx + idx);
1653 fn find_cr(src: &[u8]) -> Option<usize> {
1654 src.iter().position(|&b| b == b'\r')
1658 // _____________________________________________________________________________
1659 // Pos, BytePos, CharPos
1663 fn from_usize(n: usize) -> Self;
1664 fn to_usize(&self) -> usize;
1665 fn from_u32(n: u32) -> Self;
1666 fn to_u32(&self) -> u32;
1669 macro_rules! impl_pos {
1673 $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1678 $vis struct $ident($inner_vis $inner_ty);
1680 impl Pos for $ident {
1682 fn from_usize(n: usize) -> $ident {
1683 $ident(n as $inner_ty)
1687 fn to_usize(&self) -> usize {
1692 fn from_u32(n: u32) -> $ident {
1693 $ident(n as $inner_ty)
1697 fn to_u32(&self) -> u32 {
1702 impl Add for $ident {
1703 type Output = $ident;
1706 fn add(self, rhs: $ident) -> $ident {
1707 $ident(self.0 + rhs.0)
1711 impl Sub for $ident {
1712 type Output = $ident;
1715 fn sub(self, rhs: $ident) -> $ident {
1716 $ident(self.0 - rhs.0)
1726 /// Keep this small (currently 32-bits), as AST contains a lot of them.
1727 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1728 pub struct BytePos(pub u32);
1730 /// A character offset.
1732 /// Because of multibyte UTF-8 characters, a byte offset
1733 /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`]
1734 /// values to `CharPos` values as necessary.
1735 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1736 pub struct CharPos(pub usize);
1739 impl<S: rustc_serialize::Encoder> Encodable<S> for BytePos {
1740 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1745 impl<D: rustc_serialize::Decoder> Decodable<D> for BytePos {
1746 fn decode(d: &mut D) -> Result<BytePos, D::Error> {
1747 Ok(BytePos(d.read_u32()?))
1751 // _____________________________________________________________________________
1752 // Loc, SourceFileAndLine, SourceFileAndBytePos
1755 /// A source code location used for error reporting.
1756 #[derive(Debug, Clone)]
1758 /// Information about the original source.
1759 pub file: Lrc<SourceFile>,
1760 /// The (1-based) line number.
1762 /// The (0-based) column offset.
1764 /// The (0-based) column offset when displayed.
1765 pub col_display: usize,
1768 // Used to be structural records.
1770 pub struct SourceFileAndLine {
1771 pub sf: Lrc<SourceFile>,
1775 pub struct SourceFileAndBytePos {
1776 pub sf: Lrc<SourceFile>,
1780 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1781 pub struct LineInfo {
1782 /// Index of line, starting from 0.
1783 pub line_index: usize,
1785 /// Column in line where span begins, starting from 0.
1786 pub start_col: CharPos,
1788 /// Column in line where span ends, starting from 0, exclusive.
1789 pub end_col: CharPos,
1792 pub struct FileLines {
1793 pub file: Lrc<SourceFile>,
1794 pub lines: Vec<LineInfo>,
1797 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1798 AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1800 // _____________________________________________________________________________
1801 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1804 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1806 #[derive(Clone, PartialEq, Eq, Debug)]
1807 pub enum SpanLinesError {
1808 DistinctSources(DistinctSources),
1811 #[derive(Clone, PartialEq, Eq, Debug)]
1812 pub enum SpanSnippetError {
1813 IllFormedSpan(Span),
1814 DistinctSources(DistinctSources),
1815 MalformedForSourcemap(MalformedSourceMapPositions),
1816 SourceNotAvailable { filename: FileName },
1819 #[derive(Clone, PartialEq, Eq, Debug)]
1820 pub struct DistinctSources {
1821 pub begin: (FileName, BytePos),
1822 pub end: (FileName, BytePos),
1825 #[derive(Clone, PartialEq, Eq, Debug)]
1826 pub struct MalformedSourceMapPositions {
1828 pub source_len: usize,
1829 pub begin_pos: BytePos,
1830 pub end_pos: BytePos,
1833 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1834 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1835 pub struct InnerSpan {
1841 pub fn new(start: usize, end: usize) -> InnerSpan {
1842 InnerSpan { start, end }
1846 // Given a slice of line start positions and a position, returns the index of
1847 // the line the position is on. Returns -1 if the position is located before
1849 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1850 match lines.binary_search(&pos) {
1851 Ok(line) => line as isize,
1852 Err(line) => line as isize - 1,
1856 /// Requirements for a `StableHashingContext` to be used in this crate.
1858 /// This is a hack to allow using the [`HashStable_Generic`] derive macro
1859 /// instead of implementing everything in rustc_middle.
1860 pub trait HashStableContext {
1861 fn hash_def_id(&mut self, _: DefId, hasher: &mut StableHasher);
1862 /// Obtains a cache for storing the `Fingerprint` of an `ExpnId`.
1863 /// This method allows us to have multiple `HashStableContext` implementations
1864 /// that hash things in a different way, without the results of one polluting
1865 /// the cache of the other.
1866 fn expn_id_cache() -> &'static LocalKey<ExpnIdCache>;
1867 fn hash_crate_num(&mut self, _: CrateNum, hasher: &mut StableHasher);
1868 fn hash_spans(&self) -> bool;
1869 fn span_data_to_lines_and_cols(
1872 ) -> Option<(Lrc<SourceFile>, usize, BytePos, usize, BytePos)>;
1875 impl<CTX> HashStable<CTX> for Span
1877 CTX: HashStableContext,
1879 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1880 /// fields (that would be similar to hashing pointers, since those are just
1881 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1882 /// triple, which stays the same even if the containing `SourceFile` has moved
1883 /// within the `SourceMap`.
1885 /// Also note that we are hashing byte offsets for the column, not unicode
1886 /// codepoint offsets. For the purpose of the hash that's sufficient.
1887 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1888 /// span starts and ends in the same file, which is almost always the case.
1889 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1890 const TAG_VALID_SPAN: u8 = 0;
1891 const TAG_INVALID_SPAN: u8 = 1;
1893 if !ctx.hash_spans() {
1897 self.ctxt().hash_stable(ctx, hasher);
1899 if self.is_dummy() {
1900 Hash::hash(&TAG_INVALID_SPAN, hasher);
1904 // If this is not an empty or invalid span, we want to hash the last
1905 // position that belongs to it, as opposed to hashing the first
1906 // position past it.
1907 let span = self.data();
1908 let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span)
1912 Hash::hash(&TAG_INVALID_SPAN, hasher);
1917 Hash::hash(&TAG_VALID_SPAN, hasher);
1918 // We truncate the stable ID hash and line and column numbers. The chances
1919 // of causing a collision this way should be minimal.
1920 Hash::hash(&(file.name_hash as u64), hasher);
1922 // Hash both the length and the end location (line/column) of a span. If we
1923 // hash only the length, for example, then two otherwise equal spans with
1924 // different end locations will have the same hash. This can cause a problem
1925 // during incremental compilation wherein a previous result for a query that
1926 // depends on the end location of a span will be incorrectly reused when the
1927 // end location of the span it depends on has changed (see issue #74890). A
1928 // similar analysis applies if some query depends specifically on the length
1929 // of the span, but we only hash the end location. So hash both.
1931 let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
1932 let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1933 let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
1934 let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
1935 let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
1936 let len = (span.hi - span.lo).0;
1937 Hash::hash(&col_line, hasher);
1938 Hash::hash(&len, hasher);
1942 impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1943 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1944 const TAG_EXPANSION: u8 = 0;
1945 const TAG_NO_EXPANSION: u8 = 1;
1947 if *self == SyntaxContext::root() {
1948 TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1950 TAG_EXPANSION.hash_stable(ctx, hasher);
1951 let (expn_id, transparency) = self.outer_mark();
1952 expn_id.hash_stable(ctx, hasher);
1953 transparency.hash_stable(ctx, hasher);
1958 pub type ExpnIdCache = RefCell<Vec<Option<Fingerprint>>>;
1960 impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
1961 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1962 const TAG_ROOT: u8 = 0;
1963 const TAG_NOT_ROOT: u8 = 1;
1965 if *self == ExpnId::root() {
1966 TAG_ROOT.hash_stable(ctx, hasher);
1970 // Since the same expansion context is usually referenced many
1971 // times, we cache a stable hash of it and hash that instead of
1972 // recursing every time.
1973 let index = self.as_u32() as usize;
1974 let res = CTX::expn_id_cache().with(|cache| cache.borrow().get(index).copied().flatten());
1976 if let Some(res) = res {
1977 res.hash_stable(ctx, hasher);
1979 let new_len = index + 1;
1981 let mut sub_hasher = StableHasher::new();
1982 TAG_NOT_ROOT.hash_stable(ctx, &mut sub_hasher);
1983 self.expn_data().hash_stable(ctx, &mut sub_hasher);
1984 let sub_hash: Fingerprint = sub_hasher.finish();
1986 CTX::expn_id_cache().with(|cache| {
1987 let mut cache = cache.borrow_mut();
1988 if cache.len() < new_len {
1989 cache.resize(new_len, None);
1991 let prev = cache[index].replace(sub_hash);
1992 assert_eq!(prev, None, "Cache slot was filled");
1994 sub_hash.hash_stable(ctx, hasher);