1 //! The source positions and related helper functions.
5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
8 #![feature(array_windows)]
9 #![feature(crate_visibility_modifier)]
11 #![feature(const_panic)]
12 #![feature(negative_impls)]
14 #![feature(min_specialization)]
15 #![feature(option_expect_none)]
18 extern crate rustc_macros;
20 use rustc_data_structures::AtomicRef;
21 use rustc_macros::HashStable_Generic;
22 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
24 mod caching_source_map_view;
26 pub use self::caching_source_map_view::CachingSourceMapView;
27 use source_map::SourceMap;
32 pub use hygiene::SyntaxContext;
33 use hygiene::Transparency;
34 pub use hygiene::{DesugaringKind, ExpnData, ExpnId, ExpnKind, ForLoopLoc, MacroKind};
36 use def_id::{CrateNum, DefId, LOCAL_CRATE};
39 pub use span_encoding::{Span, DUMMY_SP};
42 pub use symbol::{sym, Symbol};
44 mod analyze_source_file;
47 use rustc_data_structures::fingerprint::Fingerprint;
48 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
49 use rustc_data_structures::sync::{Lock, Lrc};
52 use std::cell::RefCell;
53 use std::cmp::{self, Ordering};
56 use std::ops::{Add, Range, Sub};
57 use std::path::{Path, PathBuf};
58 use std::str::FromStr;
70 // Per-session global variables: this struct is stored in thread-local storage
71 // in such a way that it is accessible without any kind of handle to all
72 // threads within the compilation session, but is not accessible outside the
74 pub struct SessionGlobals {
75 symbol_interner: Lock<symbol::Interner>,
76 span_interner: Lock<span_encoding::SpanInterner>,
77 hygiene_data: Lock<hygiene::HygieneData>,
78 source_map: Lock<Option<Lrc<SourceMap>>>,
82 pub fn new(edition: Edition) -> SessionGlobals {
84 symbol_interner: Lock::new(symbol::Interner::fresh()),
85 span_interner: Lock::new(span_encoding::SpanInterner::default()),
86 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
87 source_map: Lock::new(None),
92 pub fn with_session_globals<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
93 let session_globals = SessionGlobals::new(edition);
94 SESSION_GLOBALS.set(&session_globals, f)
97 pub fn with_default_session_globals<R>(f: impl FnOnce() -> R) -> R {
98 with_session_globals(edition::DEFAULT_EDITION, f)
101 // If this ever becomes non thread-local, `decode_syntax_context`
102 // and `decode_expn_id` will need to be updated to handle concurrent
104 scoped_tls::scoped_thread_local!(pub static SESSION_GLOBALS: SessionGlobals);
106 // FIXME: Perhaps this should not implement Rustc{Decodable, Encodable}
108 // FIXME: We should use this enum or something like it to get rid of the
109 // use of magic `/rust/1.x/...` paths across the board.
110 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
111 #[derive(HashStable_Generic, Decodable, Encodable)]
112 pub enum RealFileName {
114 /// For de-virtualized paths (namely paths into libstd that have been mapped
115 /// to the appropriate spot on the local host's file system),
117 /// `local_path` is the (host-dependent) local path to the file.
119 /// `virtual_name` is the stable path rustc will store internally within
121 virtual_name: PathBuf,
126 /// Returns the path suitable for reading from the file system on the local host.
127 /// Avoid embedding this in build artifacts; see `stable_name` for that.
128 pub fn local_path(&self) -> &Path {
130 RealFileName::Named(p)
131 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => &p,
135 /// Returns the path suitable for reading from the file system on the local host.
136 /// Avoid embedding this in build artifacts; see `stable_name` for that.
137 pub fn into_local_path(self) -> PathBuf {
139 RealFileName::Named(p)
140 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => p,
144 /// Returns the path suitable for embedding into build artifacts. Note that
145 /// a virtualized path will not correspond to a valid file system path; see
146 /// `local_path` for something that is more likely to return paths into the
147 /// local host file system.
148 pub fn stable_name(&self) -> &Path {
150 RealFileName::Named(p)
151 | RealFileName::Devirtualized { local_path: _, virtual_name: p } => &p,
156 /// Differentiates between real files and common virtual files.
157 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
158 #[derive(HashStable_Generic, Decodable, Encodable)]
161 /// Call to `quote!`.
165 /// Hack in `src/librustc_ast/parse.rs`.
168 ProcMacroSourceCode(u64),
169 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
171 /// Strings provided as crate attributes in the CLI.
173 /// Custom sources for explicit parser calls from plugins and drivers.
175 DocTest(PathBuf, isize),
176 /// Post-substitution inline assembly from LLVM
180 impl std::fmt::Display for FileName {
181 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184 Real(RealFileName::Named(ref path)) => write!(fmt, "{}", path.display()),
185 // FIXME: might be nice to display both compoments of Devirtualized.
186 // But for now (to backport fix for issue #70924), best to not
187 // perturb diagnostics so its obvious test suite still works.
188 Real(RealFileName::Devirtualized { ref local_path, virtual_name: _ }) => {
189 write!(fmt, "{}", local_path.display())
191 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
192 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
193 Anon(_) => write!(fmt, "<anon>"),
194 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
195 CfgSpec(_) => write!(fmt, "<cfgspec>"),
196 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
197 Custom(ref s) => write!(fmt, "<{}>", s),
198 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
199 InlineAsm(_) => write!(fmt, "<inline asm>"),
204 impl From<PathBuf> for FileName {
205 fn from(p: PathBuf) -> Self {
206 assert!(!p.to_string_lossy().ends_with('>'));
207 FileName::Real(RealFileName::Named(p))
212 pub fn is_real(&self) -> bool {
218 | ProcMacroSourceCode(_)
224 | InlineAsm(_) => false,
228 pub fn macro_expansion_source_code(src: &str) -> FileName {
229 let mut hasher = StableHasher::new();
230 src.hash(&mut hasher);
231 FileName::MacroExpansion(hasher.finish())
234 pub fn anon_source_code(src: &str) -> FileName {
235 let mut hasher = StableHasher::new();
236 src.hash(&mut hasher);
237 FileName::Anon(hasher.finish())
240 pub fn proc_macro_source_code(src: &str) -> FileName {
241 let mut hasher = StableHasher::new();
242 src.hash(&mut hasher);
243 FileName::ProcMacroSourceCode(hasher.finish())
246 pub fn cfg_spec_source_code(src: &str) -> FileName {
247 let mut hasher = StableHasher::new();
248 src.hash(&mut hasher);
249 FileName::QuoteExpansion(hasher.finish())
252 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
253 let mut hasher = StableHasher::new();
254 src.hash(&mut hasher);
255 FileName::CliCrateAttr(hasher.finish())
258 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
259 FileName::DocTest(path, line)
262 pub fn inline_asm_source_code(src: &str) -> FileName {
263 let mut hasher = StableHasher::new();
264 src.hash(&mut hasher);
265 FileName::InlineAsm(hasher.finish())
269 /// Spans represent a region of code, used for error reporting. Positions in spans
270 /// are *absolute* positions from the beginning of the source_map, not positions
271 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
272 /// to the original source.
273 /// You must be careful if the span crosses more than one file - you will not be
274 /// able to use many of the functions on spans in source_map and you cannot assume
275 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
276 /// range between files.
278 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
279 /// sent to other threads, but some pieces of performance infra run in a separate thread.
280 /// Using `Span` is generally preferred.
281 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
282 pub struct SpanData {
285 /// Information about where the macro came from, if this piece of
286 /// code was created by a macro expansion.
287 pub ctxt: SyntaxContext,
292 pub fn with_lo(&self, lo: BytePos) -> Span {
293 Span::new(lo, self.hi, self.ctxt)
296 pub fn with_hi(&self, hi: BytePos) -> Span {
297 Span::new(self.lo, hi, self.ctxt)
300 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
301 Span::new(self.lo, self.hi, ctxt)
305 // The interner is pointed to by a thread local value which is only set on the main thread
306 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
307 // to avoid panics and other errors, even though it would be memory safe to do so.
308 #[cfg(not(parallel_compiler))]
309 impl !Send for Span {}
310 #[cfg(not(parallel_compiler))]
311 impl !Sync for Span {}
313 impl PartialOrd for Span {
314 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
315 PartialOrd::partial_cmp(&self.data(), &rhs.data())
319 fn cmp(&self, rhs: &Self) -> Ordering {
320 Ord::cmp(&self.data(), &rhs.data())
324 /// A collection of `Span`s.
326 /// Spans have two orthogonal attributes:
328 /// - They can be *primary spans*. In this case they are the locus of
329 /// the error, and would be rendered with `^^^`.
330 /// - They can have a *label*. In this case, the label is written next
331 /// to the mark in the snippet when we render.
332 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
333 pub struct MultiSpan {
334 primary_spans: Vec<Span>,
335 span_labels: Vec<(Span, String)>,
340 pub fn lo(self) -> BytePos {
344 pub fn with_lo(self, lo: BytePos) -> Span {
345 self.data().with_lo(lo)
348 pub fn hi(self) -> BytePos {
352 pub fn with_hi(self, hi: BytePos) -> Span {
353 self.data().with_hi(hi)
356 pub fn ctxt(self) -> SyntaxContext {
360 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
361 self.data().with_ctxt(ctxt)
364 /// Returns `true` if this is a dummy span with any hygienic context.
366 pub fn is_dummy(self) -> bool {
367 let span = self.data();
368 span.lo.0 == 0 && span.hi.0 == 0
371 /// Returns `true` if this span comes from a macro or desugaring.
373 pub fn from_expansion(self) -> bool {
374 self.ctxt() != SyntaxContext::root()
377 /// Returns `true` if `span` originates in a derive-macro's expansion.
378 pub fn in_derive_expansion(self) -> bool {
379 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
383 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
384 Span::new(lo, hi, SyntaxContext::root())
387 /// Returns a new span representing an empty span at the beginning of this span
389 pub fn shrink_to_lo(self) -> Span {
390 let span = self.data();
391 span.with_hi(span.lo)
393 /// Returns a new span representing an empty span at the end of this span.
395 pub fn shrink_to_hi(self) -> Span {
396 let span = self.data();
397 span.with_lo(span.hi)
401 /// Returns true if hi == lo
402 pub fn is_empty(&self) -> bool {
403 let span = self.data();
407 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
408 pub fn substitute_dummy(self, other: Span) -> Span {
409 if self.is_dummy() { other } else { self }
412 /// Returns `true` if `self` fully encloses `other`.
413 pub fn contains(self, other: Span) -> bool {
414 let span = self.data();
415 let other = other.data();
416 span.lo <= other.lo && other.hi <= span.hi
419 /// Returns `true` if `self` touches `other`.
420 pub fn overlaps(self, other: Span) -> bool {
421 let span = self.data();
422 let other = other.data();
423 span.lo < other.hi && other.lo < span.hi
426 /// Returns `true` if the spans are equal with regards to the source text.
428 /// Use this instead of `==` when either span could be generated code,
429 /// and you only care that they point to the same bytes of source text.
430 pub fn source_equal(&self, other: &Span) -> bool {
431 let span = self.data();
432 let other = other.data();
433 span.lo == other.lo && span.hi == other.hi
436 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
437 pub fn trim_start(self, other: Span) -> Option<Span> {
438 let span = self.data();
439 let other = other.data();
440 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
443 /// Returns the source span -- this is either the supplied span, or the span for
444 /// the macro callsite that expanded to it.
445 pub fn source_callsite(self) -> Span {
446 let expn_data = self.ctxt().outer_expn_data();
447 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
450 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
452 pub fn parent(self) -> Option<Span> {
453 let expn_data = self.ctxt().outer_expn_data();
454 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
457 /// Edition of the crate from which this span came.
458 pub fn edition(self) -> edition::Edition {
459 self.ctxt().outer_expn_data().edition
463 pub fn rust_2015(&self) -> bool {
464 self.edition() == edition::Edition::Edition2015
468 pub fn rust_2018(&self) -> bool {
469 self.edition() >= edition::Edition::Edition2018
472 /// Returns the source callee.
474 /// Returns `None` if the supplied span has no expansion trace,
475 /// else returns the `ExpnData` for the macro definition
476 /// corresponding to the source callsite.
477 pub fn source_callee(self) -> Option<ExpnData> {
478 fn source_callee(expn_data: ExpnData) -> ExpnData {
479 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
480 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
482 let expn_data = self.ctxt().outer_expn_data();
483 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
486 /// Checks if a span is "internal" to a macro in which `#[unstable]`
487 /// items can be used (that is, a macro marked with
488 /// `#[allow_internal_unstable]`).
489 pub fn allows_unstable(&self, feature: Symbol) -> bool {
490 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
493 .any(|&f| f == feature || f == sym::allow_internal_unstable_backcompat_hack)
497 /// Checks if this span arises from a compiler desugaring of kind `kind`.
498 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
499 match self.ctxt().outer_expn_data().kind {
500 ExpnKind::Desugaring(k) => k == kind,
505 /// Returns the compiler desugaring that created this span, or `None`
506 /// if this span is not from a desugaring.
507 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
508 match self.ctxt().outer_expn_data().kind {
509 ExpnKind::Desugaring(k) => Some(k),
514 /// Checks if a span is "internal" to a macro in which `unsafe`
515 /// can be used without triggering the `unsafe_code` lint
516 // (that is, a macro marked with `#[allow_internal_unsafe]`).
517 pub fn allows_unsafe(&self) -> bool {
518 self.ctxt().outer_expn_data().allow_internal_unsafe
521 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
522 let mut prev_span = DUMMY_SP;
523 std::iter::from_fn(move || {
525 let expn_data = self.ctxt().outer_expn_data();
526 if expn_data.is_root() {
530 let is_recursive = expn_data.call_site.source_equal(&prev_span);
533 self = expn_data.call_site;
535 // Don't print recursive invocations.
537 return Some(expn_data);
543 /// Returns a `Span` that would enclose both `self` and `end`.
547 /// self lorem ipsum end
548 /// ^^^^^^^^^^^^^^^^^^^^
550 pub fn to(self, end: Span) -> Span {
551 let span_data = self.data();
552 let end_data = end.data();
553 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
554 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
555 // have an incomplete span than a completely nonsensical one.
556 if span_data.ctxt != end_data.ctxt {
557 if span_data.ctxt == SyntaxContext::root() {
559 } else if end_data.ctxt == SyntaxContext::root() {
562 // Both spans fall within a macro.
563 // FIXME(estebank): check if it is the *same* macro.
566 cmp::min(span_data.lo, end_data.lo),
567 cmp::max(span_data.hi, end_data.hi),
568 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
572 /// Returns a `Span` between the end of `self` to the beginning of `end`.
576 /// self lorem ipsum end
579 pub fn between(self, end: Span) -> Span {
580 let span = self.data();
581 let end = end.data();
585 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
589 /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
593 /// self lorem ipsum end
594 /// ^^^^^^^^^^^^^^^^^
596 pub fn until(self, end: Span) -> Span {
597 let span = self.data();
598 let end = end.data();
602 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
606 pub fn from_inner(self, inner: InnerSpan) -> Span {
607 let span = self.data();
609 span.lo + BytePos::from_usize(inner.start),
610 span.lo + BytePos::from_usize(inner.end),
615 /// Equivalent of `Span::def_site` from the proc macro API,
616 /// except that the location is taken from the `self` span.
617 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
618 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
621 /// Equivalent of `Span::call_site` from the proc macro API,
622 /// except that the location is taken from the `self` span.
623 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
624 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
627 /// Equivalent of `Span::mixed_site` from the proc macro API,
628 /// except that the location is taken from the `self` span.
629 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
630 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
633 /// Produces a span with the same location as `self` and context produced by a macro with the
634 /// given ID and transparency, assuming that macro was defined directly and not produced by
635 /// some other macro (which is the case for built-in and procedural macros).
636 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
637 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
641 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
642 let span = self.data();
643 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
647 pub fn remove_mark(&mut self) -> ExpnId {
648 let mut span = self.data();
649 let mark = span.ctxt.remove_mark();
650 *self = Span::new(span.lo, span.hi, span.ctxt);
655 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
656 let mut span = self.data();
657 let mark = span.ctxt.adjust(expn_id);
658 *self = Span::new(span.lo, span.hi, span.ctxt);
663 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
664 let mut span = self.data();
665 let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
666 *self = Span::new(span.lo, span.hi, span.ctxt);
671 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
672 let mut span = self.data();
673 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
674 *self = Span::new(span.lo, span.hi, span.ctxt);
679 pub fn reverse_glob_adjust(
683 ) -> Option<Option<ExpnId>> {
684 let mut span = self.data();
685 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
686 *self = Span::new(span.lo, span.hi, span.ctxt);
691 pub fn normalize_to_macros_2_0(self) -> Span {
692 let span = self.data();
693 span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
697 pub fn normalize_to_macro_rules(self) -> Span {
698 let span = self.data();
699 span.with_ctxt(span.ctxt.normalize_to_macro_rules())
703 #[derive(Clone, Debug)]
704 pub struct SpanLabel {
705 /// The span we are going to include in the final snippet.
708 /// Is this a primary span? This is the "locus" of the message,
709 /// and is indicated with a `^^^^` underline, versus `----`.
710 pub is_primary: bool,
712 /// What label should we attach to this span (if any)?
713 pub label: Option<String>,
716 impl Default for Span {
717 fn default() -> Self {
722 impl<E: Encoder> Encodable<E> for Span {
723 default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
724 let span = self.data();
725 s.emit_struct("Span", 2, |s| {
726 s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?;
727 s.emit_struct_field("hi", 1, |s| span.hi.encode(s))
731 impl<D: Decoder> Decodable<D> for Span {
732 default fn decode(s: &mut D) -> Result<Span, D::Error> {
733 s.read_struct("Span", 2, |d| {
734 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
735 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
737 Ok(Span::new(lo, hi, SyntaxContext::root()))
742 /// Calls the provided closure, using the provided `SourceMap` to format
743 /// any spans that are debug-printed during the closure's execution.
745 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
746 /// (see `rustc_interface::callbacks::span_debug1). However, some parts
747 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
748 /// a `TyCtxt` is available. In this case, we fall back to
749 /// the `SourceMap` provided to this function. If that is not available,
750 /// we fall back to printing the raw `Span` field values.
751 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
752 SESSION_GLOBALS.with(|session_globals| {
753 *session_globals.source_map.borrow_mut() = Some(source_map);
755 struct ClearSourceMap;
756 impl Drop for ClearSourceMap {
758 SESSION_GLOBALS.with(|session_globals| {
759 session_globals.source_map.borrow_mut().take();
764 let _guard = ClearSourceMap;
768 pub fn debug_with_source_map(
770 f: &mut fmt::Formatter<'_>,
771 source_map: &SourceMap,
773 write!(f, "{} ({:?})", source_map.span_to_string(span), span.ctxt())
776 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
777 SESSION_GLOBALS.with(|session_globals| {
778 if let Some(source_map) = &*session_globals.source_map.borrow() {
779 debug_with_source_map(span, f, source_map)
781 f.debug_struct("Span")
782 .field("lo", &span.lo())
783 .field("hi", &span.hi())
784 .field("ctxt", &span.ctxt())
790 impl fmt::Debug for Span {
791 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
792 (*SPAN_DEBUG)(*self, f)
796 impl fmt::Debug for SpanData {
797 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
798 (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
804 pub fn new() -> MultiSpan {
805 MultiSpan { primary_spans: vec![], span_labels: vec![] }
808 pub fn from_span(primary_span: Span) -> MultiSpan {
809 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
812 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
814 MultiSpan { primary_spans: vec, span_labels: vec![] }
817 pub fn push_span_label(&mut self, span: Span, label: String) {
818 self.span_labels.push((span, label));
821 /// Selects the first primary span (if any).
822 pub fn primary_span(&self) -> Option<Span> {
823 self.primary_spans.first().cloned()
826 /// Returns all primary spans.
827 pub fn primary_spans(&self) -> &[Span] {
831 /// Returns `true` if any of the primary spans are displayable.
832 pub fn has_primary_spans(&self) -> bool {
833 self.primary_spans.iter().any(|sp| !sp.is_dummy())
836 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
837 pub fn is_dummy(&self) -> bool {
838 let mut is_dummy = true;
839 for span in &self.primary_spans {
840 if !span.is_dummy() {
847 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
848 /// display well (like std macros). Returns whether replacements occurred.
849 pub fn replace(&mut self, before: Span, after: Span) -> bool {
850 let mut replacements_occurred = false;
851 for primary_span in &mut self.primary_spans {
852 if *primary_span == before {
853 *primary_span = after;
854 replacements_occurred = true;
857 for span_label in &mut self.span_labels {
858 if span_label.0 == before {
859 span_label.0 = after;
860 replacements_occurred = true;
863 replacements_occurred
866 /// Returns the strings to highlight. We always ensure that there
867 /// is an entry for each of the primary spans -- for each primary
868 /// span `P`, if there is at least one label with span `P`, we return
869 /// those labels (marked as primary). But otherwise we return
870 /// `SpanLabel` instances with empty labels.
871 pub fn span_labels(&self) -> Vec<SpanLabel> {
872 let is_primary = |span| self.primary_spans.contains(&span);
874 let mut span_labels = self
877 .map(|&(span, ref label)| SpanLabel {
879 is_primary: is_primary(span),
880 label: Some(label.clone()),
882 .collect::<Vec<_>>();
884 for &span in &self.primary_spans {
885 if !span_labels.iter().any(|sl| sl.span == span) {
886 span_labels.push(SpanLabel { span, is_primary: true, label: None });
893 /// Returns `true` if any of the span labels is displayable.
894 pub fn has_span_labels(&self) -> bool {
895 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
899 impl From<Span> for MultiSpan {
900 fn from(span: Span) -> MultiSpan {
901 MultiSpan::from_span(span)
905 impl From<Vec<Span>> for MultiSpan {
906 fn from(spans: Vec<Span>) -> MultiSpan {
907 MultiSpan::from_spans(spans)
911 /// Identifies an offset of a multi-byte character in a `SourceFile`.
912 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
913 pub struct MultiByteChar {
914 /// The absolute offset of the character in the `SourceMap`.
916 /// The number of bytes, `>= 2`.
920 /// Identifies an offset of a non-narrow character in a `SourceFile`.
921 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
922 pub enum NonNarrowChar {
923 /// Represents a zero-width character.
925 /// Represents a wide (full-width) character.
927 /// Represents a tab character, represented visually with a width of 4 characters.
932 fn new(pos: BytePos, width: usize) -> Self {
934 0 => NonNarrowChar::ZeroWidth(pos),
935 2 => NonNarrowChar::Wide(pos),
936 4 => NonNarrowChar::Tab(pos),
937 _ => panic!("width {} given for non-narrow character", width),
941 /// Returns the absolute offset of the character in the `SourceMap`.
942 pub fn pos(&self) -> BytePos {
944 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
948 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
949 pub fn width(&self) -> usize {
951 NonNarrowChar::ZeroWidth(_) => 0,
952 NonNarrowChar::Wide(_) => 2,
953 NonNarrowChar::Tab(_) => 4,
958 impl Add<BytePos> for NonNarrowChar {
961 fn add(self, rhs: BytePos) -> Self {
963 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
964 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
965 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
970 impl Sub<BytePos> for NonNarrowChar {
973 fn sub(self, rhs: BytePos) -> Self {
975 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
976 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
977 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
982 /// Identifies an offset of a character that was normalized away from `SourceFile`.
983 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
984 pub struct NormalizedPos {
985 /// The absolute offset of the character in the `SourceMap`.
987 /// The difference between original and normalized string at position.
991 #[derive(PartialEq, Eq, Clone, Debug)]
992 pub enum ExternalSource {
993 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
996 kind: ExternalSourceKind,
997 /// This SourceFile's byte-offset within the source_map of its original crate
998 original_start_pos: BytePos,
999 /// The end of this SourceFile within the source_map of its original crate
1000 original_end_pos: BytePos,
1004 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1005 #[derive(PartialEq, Eq, Clone, Debug)]
1006 pub enum ExternalSourceKind {
1007 /// The external source has been loaded already.
1008 Present(Lrc<String>),
1009 /// No attempt has been made to load the external source.
1011 /// A failed attempt has been made to load the external source.
1016 impl ExternalSource {
1017 pub fn is_absent(&self) -> bool {
1019 ExternalSource::Foreign { kind: ExternalSourceKind::Present(_), .. } => false,
1024 pub fn get_source(&self) -> Option<&Lrc<String>> {
1026 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1033 pub struct OffsetOverflowError;
1035 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1036 pub enum SourceFileHashAlgorithm {
1042 impl FromStr for SourceFileHashAlgorithm {
1045 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1047 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1048 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1049 "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1055 rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm);
1057 /// The hash of the on-disk source file used for debug info.
1058 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1059 #[derive(HashStable_Generic, Encodable, Decodable)]
1060 pub struct SourceFileHash {
1061 pub kind: SourceFileHashAlgorithm,
1065 impl SourceFileHash {
1066 pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1067 let mut hash = SourceFileHash { kind, value: Default::default() };
1068 let len = hash.hash_len();
1069 let value = &mut hash.value[..len];
1070 let data = src.as_bytes();
1072 SourceFileHashAlgorithm::Md5 => {
1073 value.copy_from_slice(&Md5::digest(data));
1075 SourceFileHashAlgorithm::Sha1 => {
1076 value.copy_from_slice(&Sha1::digest(data));
1078 SourceFileHashAlgorithm::Sha256 => {
1079 value.copy_from_slice(&Sha256::digest(data));
1085 /// Check if the stored hash matches the hash of the string.
1086 pub fn matches(&self, src: &str) -> bool {
1087 Self::new(self.kind, src) == *self
1090 /// The bytes of the hash.
1091 pub fn hash_bytes(&self) -> &[u8] {
1092 let len = self.hash_len();
1096 fn hash_len(&self) -> usize {
1098 SourceFileHashAlgorithm::Md5 => 16,
1099 SourceFileHashAlgorithm::Sha1 => 20,
1100 SourceFileHashAlgorithm::Sha256 => 32,
1105 /// A single source in the `SourceMap`.
1107 pub struct SourceFile {
1108 /// The name of the file that the source came from. Source that doesn't
1109 /// originate from files has names between angle brackets by convention
1110 /// (e.g., `<anon>`).
1112 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
1113 pub name_was_remapped: bool,
1114 /// The unmapped path of the file that the source came from.
1115 /// Set to `None` if the `SourceFile` was imported from an external crate.
1116 pub unmapped_path: Option<FileName>,
1117 /// The complete source code.
1118 pub src: Option<Lrc<String>>,
1119 /// The source code's hash.
1120 pub src_hash: SourceFileHash,
1121 /// The external source code (used for external crates, which will have a `None`
1122 /// value as `self.src`.
1123 pub external_src: Lock<ExternalSource>,
1124 /// The start position of this source in the `SourceMap`.
1125 pub start_pos: BytePos,
1126 /// The end position of this source in the `SourceMap`.
1127 pub end_pos: BytePos,
1128 /// Locations of lines beginnings in the source code.
1129 pub lines: Vec<BytePos>,
1130 /// Locations of multi-byte characters in the source code.
1131 pub multibyte_chars: Vec<MultiByteChar>,
1132 /// Width of characters that are not narrow in the source code.
1133 pub non_narrow_chars: Vec<NonNarrowChar>,
1134 /// Locations of characters removed during normalization.
1135 pub normalized_pos: Vec<NormalizedPos>,
1136 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1137 pub name_hash: u128,
1138 /// Indicates which crate this `SourceFile` was imported from.
1142 impl<S: Encoder> Encodable<S> for SourceFile {
1143 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1144 s.emit_struct("SourceFile", 8, |s| {
1145 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
1146 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
1147 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
1148 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
1149 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
1150 s.emit_struct_field("lines", 5, |s| {
1151 let lines = &self.lines[..];
1152 // Store the length.
1153 s.emit_u32(lines.len() as u32)?;
1155 if !lines.is_empty() {
1156 // In order to preserve some space, we exploit the fact that
1157 // the lines list is sorted and individual lines are
1158 // probably not that long. Because of that we can store lines
1159 // as a difference list, using as little space as possible
1160 // for the differences.
1161 let max_line_length = if lines.len() == 1 {
1166 .map(|&[fst, snd]| snd - fst)
1167 .map(|bp| bp.to_usize())
1172 let bytes_per_diff: u8 = match max_line_length {
1174 0x100..=0xFFFF => 2,
1178 // Encode the number of bytes used per diff.
1179 bytes_per_diff.encode(s)?;
1181 // Encode the first element.
1182 lines[0].encode(s)?;
1184 let diff_iter = lines[..].array_windows().map(|&[fst, snd]| snd - fst);
1186 match bytes_per_diff {
1188 for diff in diff_iter {
1189 (diff.0 as u8).encode(s)?
1193 for diff in diff_iter {
1194 (diff.0 as u16).encode(s)?
1198 for diff in diff_iter {
1202 _ => unreachable!(),
1208 s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
1209 s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
1210 s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
1211 s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))?;
1212 s.emit_struct_field("cnum", 10, |s| self.cnum.encode(s))
1217 impl<D: Decoder> Decodable<D> for SourceFile {
1218 fn decode(d: &mut D) -> Result<SourceFile, D::Error> {
1219 d.read_struct("SourceFile", 8, |d| {
1220 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1221 let name_was_remapped: bool =
1222 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1223 let src_hash: SourceFileHash =
1224 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1225 let start_pos: BytePos =
1226 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1227 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1228 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1229 let num_lines: u32 = Decodable::decode(d)?;
1230 let mut lines = Vec::with_capacity(num_lines as usize);
1233 // Read the number of bytes used per diff.
1234 let bytes_per_diff: u8 = Decodable::decode(d)?;
1236 // Read the first element.
1237 let mut line_start: BytePos = Decodable::decode(d)?;
1238 lines.push(line_start);
1240 for _ in 1..num_lines {
1241 let diff = match bytes_per_diff {
1242 1 => d.read_u8()? as u32,
1243 2 => d.read_u16()? as u32,
1245 _ => unreachable!(),
1248 line_start = line_start + BytePos(diff);
1250 lines.push(line_start);
1256 let multibyte_chars: Vec<MultiByteChar> =
1257 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1258 let non_narrow_chars: Vec<NonNarrowChar> =
1259 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1260 let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1261 let normalized_pos: Vec<NormalizedPos> =
1262 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1263 let cnum: CrateNum = d.read_struct_field("cnum", 10, |d| Decodable::decode(d))?;
1267 unmapped_path: None,
1272 // Unused - the metadata decoder will construct
1273 // a new SourceFile, filling in `external_src` properly
1274 external_src: Lock::new(ExternalSource::Unneeded),
1286 impl fmt::Debug for SourceFile {
1287 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1288 write!(fmt, "SourceFile({})", self.name)
1295 name_was_remapped: bool,
1296 unmapped_path: FileName,
1299 hash_kind: SourceFileHashAlgorithm,
1301 // Compute the file hash before any normalization.
1302 let src_hash = SourceFileHash::new(hash_kind, &src);
1303 let normalized_pos = normalize_src(&mut src, start_pos);
1306 let mut hasher: StableHasher = StableHasher::new();
1307 name.hash(&mut hasher);
1308 hasher.finish::<u128>()
1310 let end_pos = start_pos.to_usize() + src.len();
1311 assert!(end_pos <= u32::MAX as usize);
1313 let (lines, multibyte_chars, non_narrow_chars) =
1314 analyze_source_file::analyze_source_file(&src[..], start_pos);
1319 unmapped_path: Some(unmapped_path),
1320 src: Some(Lrc::new(src)),
1322 external_src: Lock::new(ExternalSource::Unneeded),
1324 end_pos: Pos::from_usize(end_pos),
1334 /// Returns the `BytePos` of the beginning of the current line.
1335 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1336 let line_index = self.lookup_line(pos).unwrap();
1337 self.lines[line_index]
1340 /// Add externally loaded source.
1341 /// If the hash of the input doesn't match or no input is supplied via None,
1342 /// it is interpreted as an error and the corresponding enum variant is set.
1343 /// The return value signifies whether some kind of source is present.
1344 pub fn add_external_src<F>(&self, get_src: F) -> bool
1346 F: FnOnce() -> Option<String>,
1349 *self.external_src.borrow(),
1350 ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1352 let src = get_src();
1353 let mut external_src = self.external_src.borrow_mut();
1354 // Check that no-one else have provided the source while we were getting it
1355 if let ExternalSource::Foreign {
1356 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1357 } = &mut *external_src
1359 if let Some(mut src) = src {
1360 // The src_hash needs to be computed on the pre-normalized src.
1361 if self.src_hash.matches(&src) {
1362 normalize_src(&mut src, BytePos::from_usize(0));
1363 *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1367 *src_kind = ExternalSourceKind::AbsentErr;
1372 self.src.is_some() || external_src.get_source().is_some()
1375 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1379 /// Gets a line from the list of pre-computed line-beginnings.
1380 /// The line number here is 0-based.
1381 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1382 fn get_until_newline(src: &str, begin: usize) -> &str {
1383 // We can't use `lines.get(line_number+1)` because we might
1384 // be parsing when we call this function and thus the current
1385 // line is the last one we have line info for.
1386 let slice = &src[begin..];
1387 match slice.find('\n') {
1388 Some(e) => &slice[..e],
1394 let line = self.lines.get(line_number)?;
1395 let begin: BytePos = *line - self.start_pos;
1399 if let Some(ref src) = self.src {
1400 Some(Cow::from(get_until_newline(src, begin)))
1401 } else if let Some(src) = self.external_src.borrow().get_source() {
1402 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1408 pub fn is_real_file(&self) -> bool {
1412 pub fn is_imported(&self) -> bool {
1416 pub fn byte_length(&self) -> u32 {
1417 self.end_pos.0 - self.start_pos.0
1419 pub fn count_lines(&self) -> usize {
1423 /// Finds the line containing the given position. The return value is the
1424 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1425 /// number. If the source_file is empty or the position is located before the
1426 /// first line, `None` is returned.
1427 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1428 if self.lines.is_empty() {
1432 let line_index = lookup_line(&self.lines[..], pos);
1433 assert!(line_index < self.lines.len() as isize);
1434 if line_index >= 0 { Some(line_index as usize) } else { None }
1437 pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
1438 if self.is_empty() {
1439 return self.start_pos..self.end_pos;
1442 assert!(line_index < self.lines.len());
1443 if line_index == (self.lines.len() - 1) {
1444 self.lines[line_index]..self.end_pos
1446 self.lines[line_index]..self.lines[line_index + 1]
1450 /// Returns whether or not the file contains the given `SourceMap` byte
1451 /// position. The position one past the end of the file is considered to be
1452 /// contained by the file. This implies that files for which `is_empty`
1453 /// returns true still contain one byte position according to this function.
1455 pub fn contains(&self, byte_pos: BytePos) -> bool {
1456 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1460 pub fn is_empty(&self) -> bool {
1461 self.start_pos == self.end_pos
1464 /// Calculates the original byte position relative to the start of the file
1465 /// based on the given byte position.
1466 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1467 // Diff before any records is 0. Otherwise use the previously recorded
1468 // diff as that applies to the following characters until a new diff
1470 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1471 Ok(i) => self.normalized_pos[i].diff,
1472 Err(i) if i == 0 => 0,
1473 Err(i) => self.normalized_pos[i - 1].diff,
1476 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1479 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1480 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1481 // The number of extra bytes due to multibyte chars in the `SourceFile`.
1482 let mut total_extra_bytes = 0;
1484 for mbc in self.multibyte_chars.iter() {
1485 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1487 // Every character is at least one byte, so we only
1488 // count the actual extra bytes.
1489 total_extra_bytes += mbc.bytes as u32 - 1;
1490 // We should never see a byte position in the middle of a
1492 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1498 assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1499 CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1502 /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1503 /// given `BytePos`.
1504 pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1505 let chpos = self.bytepos_to_file_charpos(pos);
1506 match self.lookup_line(pos) {
1508 let line = a + 1; // Line numbers start at 1
1509 let linebpos = self.lines[a];
1510 let linechpos = self.bytepos_to_file_charpos(linebpos);
1511 let col = chpos - linechpos;
1512 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1513 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1514 debug!("byte is on line: {}", line);
1515 assert!(chpos >= linechpos);
1522 /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1523 /// column offset when displayed, for a given `BytePos`.
1524 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1525 let (line, col_or_chpos) = self.lookup_file_pos(pos);
1527 let col = col_or_chpos;
1528 let linebpos = self.lines[line - 1];
1530 let start_width_idx = self
1532 .binary_search_by_key(&linebpos, |x| x.pos())
1533 .unwrap_or_else(|x| x);
1534 let end_width_idx = self
1536 .binary_search_by_key(&pos, |x| x.pos())
1537 .unwrap_or_else(|x| x);
1538 let special_chars = end_width_idx - start_width_idx;
1539 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1543 col.0 - special_chars + non_narrow
1545 (line, col, col_display)
1547 let chpos = col_or_chpos;
1549 let end_width_idx = self
1551 .binary_search_by_key(&pos, |x| x.pos())
1552 .unwrap_or_else(|x| x);
1553 let non_narrow: usize =
1554 self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1555 chpos.0 - end_width_idx + non_narrow
1557 (0, chpos, col_display)
1562 /// Normalizes the source code and records the normalizations.
1563 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1564 let mut normalized_pos = vec![];
1565 remove_bom(src, &mut normalized_pos);
1566 normalize_newlines(src, &mut normalized_pos);
1568 // Offset all the positions by start_pos to match the final file positions.
1569 for np in &mut normalized_pos {
1570 np.pos.0 += start_pos.0;
1576 /// Removes UTF-8 BOM, if any.
1577 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1578 if src.starts_with('\u{feff}') {
1580 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1584 /// Replaces `\r\n` with `\n` in-place in `src`.
1586 /// Returns error if there's a lone `\r` in the string
1587 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1588 if !src.as_bytes().contains(&b'\r') {
1592 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1593 // While we *can* call `as_mut_vec` and do surgery on the live string
1594 // directly, let's rather steal the contents of `src`. This makes the code
1595 // safe even if a panic occurs.
1597 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1598 let mut gap_len = 0;
1599 let mut tail = buf.as_mut_slice();
1601 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1603 let idx = match find_crlf(&tail[gap_len..]) {
1605 Some(idx) => idx + gap_len,
1607 tail.copy_within(gap_len..idx, 0);
1608 tail = &mut tail[idx - gap_len..];
1609 if tail.len() == gap_len {
1612 cursor += idx - gap_len;
1614 normalized_pos.push(NormalizedPos {
1615 pos: BytePos::from_usize(cursor + 1),
1616 diff: original_gap + gap_len as u32,
1620 // Account for removed `\r`.
1621 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1622 let new_len = buf.len() - gap_len;
1624 buf.set_len(new_len);
1625 *src = String::from_utf8_unchecked(buf);
1628 fn find_crlf(src: &[u8]) -> Option<usize> {
1629 let mut search_idx = 0;
1630 while let Some(idx) = find_cr(&src[search_idx..]) {
1631 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1632 search_idx += idx + 1;
1635 return Some(search_idx + idx);
1640 fn find_cr(src: &[u8]) -> Option<usize> {
1641 src.iter().position(|&b| b == b'\r')
1645 // _____________________________________________________________________________
1646 // Pos, BytePos, CharPos
1650 fn from_usize(n: usize) -> Self;
1651 fn to_usize(&self) -> usize;
1652 fn from_u32(n: u32) -> Self;
1653 fn to_u32(&self) -> u32;
1656 macro_rules! impl_pos {
1660 $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1665 $vis struct $ident($inner_vis $inner_ty);
1667 impl Pos for $ident {
1669 fn from_usize(n: usize) -> $ident {
1670 $ident(n as $inner_ty)
1674 fn to_usize(&self) -> usize {
1679 fn from_u32(n: u32) -> $ident {
1680 $ident(n as $inner_ty)
1684 fn to_u32(&self) -> u32 {
1689 impl Add for $ident {
1690 type Output = $ident;
1693 fn add(self, rhs: $ident) -> $ident {
1694 $ident(self.0 + rhs.0)
1698 impl Sub for $ident {
1699 type Output = $ident;
1702 fn sub(self, rhs: $ident) -> $ident {
1703 $ident(self.0 - rhs.0)
1711 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1713 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1714 pub struct BytePos(pub u32);
1716 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1717 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1718 /// values to `CharPos` values as necessary.
1719 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1720 pub struct CharPos(pub usize);
1723 impl<S: rustc_serialize::Encoder> Encodable<S> for BytePos {
1724 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1729 impl<D: rustc_serialize::Decoder> Decodable<D> for BytePos {
1730 fn decode(d: &mut D) -> Result<BytePos, D::Error> {
1731 Ok(BytePos(d.read_u32()?))
1735 // _____________________________________________________________________________
1736 // Loc, SourceFileAndLine, SourceFileAndBytePos
1739 /// A source code location used for error reporting.
1740 #[derive(Debug, Clone)]
1742 /// Information about the original source.
1743 pub file: Lrc<SourceFile>,
1744 /// The (1-based) line number.
1746 /// The (0-based) column offset.
1748 /// The (0-based) column offset when displayed.
1749 pub col_display: usize,
1752 // Used to be structural records.
1754 pub struct SourceFileAndLine {
1755 pub sf: Lrc<SourceFile>,
1759 pub struct SourceFileAndBytePos {
1760 pub sf: Lrc<SourceFile>,
1764 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1765 pub struct LineInfo {
1766 /// Index of line, starting from 0.
1767 pub line_index: usize,
1769 /// Column in line where span begins, starting from 0.
1770 pub start_col: CharPos,
1772 /// Column in line where span ends, starting from 0, exclusive.
1773 pub end_col: CharPos,
1776 pub struct FileLines {
1777 pub file: Lrc<SourceFile>,
1778 pub lines: Vec<LineInfo>,
1781 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1782 AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1784 // _____________________________________________________________________________
1785 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1788 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1790 #[derive(Clone, PartialEq, Eq, Debug)]
1791 pub enum SpanLinesError {
1792 DistinctSources(DistinctSources),
1795 #[derive(Clone, PartialEq, Eq, Debug)]
1796 pub enum SpanSnippetError {
1797 IllFormedSpan(Span),
1798 DistinctSources(DistinctSources),
1799 MalformedForSourcemap(MalformedSourceMapPositions),
1800 SourceNotAvailable { filename: FileName },
1803 #[derive(Clone, PartialEq, Eq, Debug)]
1804 pub struct DistinctSources {
1805 pub begin: (FileName, BytePos),
1806 pub end: (FileName, BytePos),
1809 #[derive(Clone, PartialEq, Eq, Debug)]
1810 pub struct MalformedSourceMapPositions {
1812 pub source_len: usize,
1813 pub begin_pos: BytePos,
1814 pub end_pos: BytePos,
1817 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1818 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1819 pub struct InnerSpan {
1825 pub fn new(start: usize, end: usize) -> InnerSpan {
1826 InnerSpan { start, end }
1830 // Given a slice of line start positions and a position, returns the index of
1831 // the line the position is on. Returns -1 if the position is located before
1833 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1834 match lines.binary_search(&pos) {
1835 Ok(line) => line as isize,
1836 Err(line) => line as isize - 1,
1840 /// Requirements for a `StableHashingContext` to be used in this crate.
1841 /// This is a hack to allow using the `HashStable_Generic` derive macro
1842 /// instead of implementing everything in librustc_middle.
1843 pub trait HashStableContext {
1844 fn hash_def_id(&mut self, _: DefId, hasher: &mut StableHasher);
1845 fn hash_crate_num(&mut self, _: CrateNum, hasher: &mut StableHasher);
1846 fn hash_spans(&self) -> bool;
1847 fn byte_pos_to_line_and_col(
1850 ) -> Option<(Lrc<SourceFile>, usize, BytePos)>;
1853 impl<CTX> HashStable<CTX> for Span
1855 CTX: HashStableContext,
1857 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1858 /// fields (that would be similar to hashing pointers, since those are just
1859 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1860 /// triple, which stays the same even if the containing `SourceFile` has moved
1861 /// within the `SourceMap`.
1862 /// Also note that we are hashing byte offsets for the column, not unicode
1863 /// codepoint offsets. For the purpose of the hash that's sufficient.
1864 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1865 /// span starts and ends in the same file, which is almost always the case.
1866 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1867 const TAG_VALID_SPAN: u8 = 0;
1868 const TAG_INVALID_SPAN: u8 = 1;
1870 if !ctx.hash_spans() {
1874 if *self == DUMMY_SP {
1875 Hash::hash(&TAG_INVALID_SPAN, hasher);
1879 // If this is not an empty or invalid span, we want to hash the last
1880 // position that belongs to it, as opposed to hashing the first
1881 // position past it.
1882 let span = self.data();
1883 let (file_lo, line_lo, col_lo) = match ctx.byte_pos_to_line_and_col(span.lo) {
1886 Hash::hash(&TAG_INVALID_SPAN, hasher);
1887 span.ctxt.hash_stable(ctx, hasher);
1892 if !file_lo.contains(span.hi) {
1893 Hash::hash(&TAG_INVALID_SPAN, hasher);
1894 span.ctxt.hash_stable(ctx, hasher);
1898 let (_, line_hi, col_hi) = match ctx.byte_pos_to_line_and_col(span.hi) {
1901 Hash::hash(&TAG_INVALID_SPAN, hasher);
1902 span.ctxt.hash_stable(ctx, hasher);
1907 Hash::hash(&TAG_VALID_SPAN, hasher);
1908 // We truncate the stable ID hash and line and column numbers. The chances
1909 // of causing a collision this way should be minimal.
1910 Hash::hash(&(file_lo.name_hash as u64), hasher);
1912 // Hash both the length and the end location (line/column) of a span. If we
1913 // hash only the length, for example, then two otherwise equal spans with
1914 // different end locations will have the same hash. This can cause a problem
1915 // during incremental compilation wherein a previous result for a query that
1916 // depends on the end location of a span will be incorrectly reused when the
1917 // end location of the span it depends on has changed (see issue #74890). A
1918 // similar analysis applies if some query depends specifically on the length
1919 // of the span, but we only hash the end location. So hash both.
1921 let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
1922 let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1923 let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
1924 let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
1925 let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
1926 let len = (span.hi - span.lo).0;
1927 Hash::hash(&col_line, hasher);
1928 Hash::hash(&len, hasher);
1929 span.ctxt.hash_stable(ctx, hasher);
1933 impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1934 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1935 const TAG_EXPANSION: u8 = 0;
1936 const TAG_NO_EXPANSION: u8 = 1;
1938 if *self == SyntaxContext::root() {
1939 TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1941 TAG_EXPANSION.hash_stable(ctx, hasher);
1942 let (expn_id, transparency) = self.outer_mark();
1943 expn_id.hash_stable(ctx, hasher);
1944 transparency.hash_stable(ctx, hasher);
1949 impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
1950 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1951 // Since the same expansion context is usually referenced many
1952 // times, we cache a stable hash of it and hash that instead of
1953 // recursing every time.
1955 static CACHE: RefCell<Vec<Option<Fingerprint>>> = Default::default();
1958 const TAG_ROOT: u8 = 0;
1959 const TAG_NOT_ROOT: u8 = 1;
1961 if *self == ExpnId::root() {
1962 TAG_ROOT.hash_stable(ctx, hasher);
1966 let index = self.as_u32() as usize;
1967 let res = CACHE.with(|cache| cache.borrow().get(index).copied().flatten());
1969 if let Some(res) = res {
1970 res.hash_stable(ctx, hasher);
1972 let new_len = index + 1;
1974 let mut sub_hasher = StableHasher::new();
1975 TAG_NOT_ROOT.hash_stable(ctx, &mut sub_hasher);
1976 self.expn_data().hash_stable(ctx, &mut sub_hasher);
1977 let sub_hash: Fingerprint = sub_hasher.finish();
1979 CACHE.with(|cache| {
1980 let mut cache = cache.borrow_mut();
1981 if cache.len() < new_len {
1982 cache.resize(new_len, None);
1984 cache[index].replace(sub_hash).expect_none("Cache slot was filled");
1986 sub_hash.hash_stable(ctx, hasher);