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};
38 pub use span_encoding::{Span, DUMMY_SP};
41 pub use symbol::{sym, Symbol};
43 mod analyze_source_file;
46 use rustc_data_structures::fingerprint::Fingerprint;
47 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
48 use rustc_data_structures::sync::{Lock, Lrc};
51 use std::cell::RefCell;
52 use std::cmp::{self, Ordering};
55 use std::ops::{Add, Sub};
56 use std::path::{Path, PathBuf};
57 use std::str::FromStr;
68 // Per-session global variables: this struct is stored in thread-local storage
69 // in such a way that it is accessible without any kind of handle to all
70 // threads within the compilation session, but is not accessible outside the
72 pub struct SessionGlobals {
73 symbol_interner: Lock<symbol::Interner>,
74 span_interner: Lock<span_encoding::SpanInterner>,
75 hygiene_data: Lock<hygiene::HygieneData>,
76 source_map: Lock<Option<Lrc<SourceMap>>>,
80 pub fn new(edition: Edition) -> SessionGlobals {
82 symbol_interner: Lock::new(symbol::Interner::fresh()),
83 span_interner: Lock::new(span_encoding::SpanInterner::default()),
84 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
85 source_map: Lock::new(None),
90 pub fn with_session_globals<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
91 let session_globals = SessionGlobals::new(edition);
92 SESSION_GLOBALS.set(&session_globals, f)
95 pub fn with_default_session_globals<R>(f: impl FnOnce() -> R) -> R {
96 with_session_globals(edition::DEFAULT_EDITION, f)
99 // If this ever becomes non thread-local, `decode_syntax_context`
100 // and `decode_expn_id` will need to be updated to handle concurrent
102 scoped_tls::scoped_thread_local!(pub static SESSION_GLOBALS: SessionGlobals);
104 // FIXME: Perhaps this should not implement Rustc{Decodable, Encodable}
106 // FIXME: We should use this enum or something like it to get rid of the
107 // use of magic `/rust/1.x/...` paths across the board.
108 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
109 #[derive(HashStable_Generic, Decodable, Encodable)]
110 pub enum RealFileName {
112 /// For de-virtualized paths (namely paths into libstd that have been mapped
113 /// to the appropriate spot on the local host's file system),
115 /// `local_path` is the (host-dependent) local path to the file.
117 /// `virtual_name` is the stable path rustc will store internally within
119 virtual_name: PathBuf,
124 /// Returns the path suitable for reading from the file system on the local host.
125 /// Avoid embedding this in build artifacts; see `stable_name` for that.
126 pub fn local_path(&self) -> &Path {
128 RealFileName::Named(p)
129 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => &p,
133 /// Returns the path suitable for reading from the file system on the local host.
134 /// Avoid embedding this in build artifacts; see `stable_name` for that.
135 pub fn into_local_path(self) -> PathBuf {
137 RealFileName::Named(p)
138 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => p,
142 /// Returns the path suitable for embedding into build artifacts. Note that
143 /// a virtualized path will not correspond to a valid file system path; see
144 /// `local_path` for something that is more likely to return paths into the
145 /// local host file system.
146 pub fn stable_name(&self) -> &Path {
148 RealFileName::Named(p)
149 | RealFileName::Devirtualized { local_path: _, virtual_name: p } => &p,
154 /// Differentiates between real files and common virtual files.
155 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
156 #[derive(HashStable_Generic, Decodable, Encodable)]
159 /// Call to `quote!`.
163 /// Hack in `src/librustc_ast/parse.rs`.
166 ProcMacroSourceCode(u64),
167 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
169 /// Strings provided as crate attributes in the CLI.
171 /// Custom sources for explicit parser calls from plugins and drivers.
173 DocTest(PathBuf, isize),
174 /// Post-substitution inline assembly from LLVM
178 impl std::fmt::Display for FileName {
179 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182 Real(RealFileName::Named(ref path)) => write!(fmt, "{}", path.display()),
183 // FIXME: might be nice to display both compoments of Devirtualized.
184 // But for now (to backport fix for issue #70924), best to not
185 // perturb diagnostics so its obvious test suite still works.
186 Real(RealFileName::Devirtualized { ref local_path, virtual_name: _ }) => {
187 write!(fmt, "{}", local_path.display())
189 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
190 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
191 Anon(_) => write!(fmt, "<anon>"),
192 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
193 CfgSpec(_) => write!(fmt, "<cfgspec>"),
194 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
195 Custom(ref s) => write!(fmt, "<{}>", s),
196 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
197 InlineAsm(_) => write!(fmt, "<inline asm>"),
202 impl From<PathBuf> for FileName {
203 fn from(p: PathBuf) -> Self {
204 assert!(!p.to_string_lossy().ends_with('>'));
205 FileName::Real(RealFileName::Named(p))
210 pub fn is_real(&self) -> bool {
216 | ProcMacroSourceCode(_)
222 | InlineAsm(_) => false,
226 pub fn quote_expansion_source_code(src: &str) -> FileName {
227 let mut hasher = StableHasher::new();
228 src.hash(&mut hasher);
229 FileName::QuoteExpansion(hasher.finish())
232 pub fn macro_expansion_source_code(src: &str) -> FileName {
233 let mut hasher = StableHasher::new();
234 src.hash(&mut hasher);
235 FileName::MacroExpansion(hasher.finish())
238 pub fn anon_source_code(src: &str) -> FileName {
239 let mut hasher = StableHasher::new();
240 src.hash(&mut hasher);
241 FileName::Anon(hasher.finish())
244 pub fn proc_macro_source_code(src: &str) -> FileName {
245 let mut hasher = StableHasher::new();
246 src.hash(&mut hasher);
247 FileName::ProcMacroSourceCode(hasher.finish())
250 pub fn cfg_spec_source_code(src: &str) -> FileName {
251 let mut hasher = StableHasher::new();
252 src.hash(&mut hasher);
253 FileName::QuoteExpansion(hasher.finish())
256 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
257 let mut hasher = StableHasher::new();
258 src.hash(&mut hasher);
259 FileName::CliCrateAttr(hasher.finish())
262 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
263 FileName::DocTest(path, line)
266 pub fn inline_asm_source_code(src: &str) -> FileName {
267 let mut hasher = StableHasher::new();
268 src.hash(&mut hasher);
269 FileName::InlineAsm(hasher.finish())
273 /// Spans represent a region of code, used for error reporting. Positions in spans
274 /// are *absolute* positions from the beginning of the source_map, not positions
275 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
276 /// to the original source.
277 /// You must be careful if the span crosses more than one file - you will not be
278 /// able to use many of the functions on spans in source_map and you cannot assume
279 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
280 /// range between files.
282 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
283 /// sent to other threads, but some pieces of performance infra run in a separate thread.
284 /// Using `Span` is generally preferred.
285 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
286 pub struct SpanData {
289 /// Information about where the macro came from, if this piece of
290 /// code was created by a macro expansion.
291 pub ctxt: SyntaxContext,
296 pub fn with_lo(&self, lo: BytePos) -> Span {
297 Span::new(lo, self.hi, self.ctxt)
300 pub fn with_hi(&self, hi: BytePos) -> Span {
301 Span::new(self.lo, hi, self.ctxt)
304 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
305 Span::new(self.lo, self.hi, ctxt)
309 // The interner is pointed to by a thread local value which is only set on the main thread
310 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
311 // to avoid panics and other errors, even though it would be memory safe to do so.
312 #[cfg(not(parallel_compiler))]
313 impl !Send for Span {}
314 #[cfg(not(parallel_compiler))]
315 impl !Sync for Span {}
317 impl PartialOrd for Span {
318 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
319 PartialOrd::partial_cmp(&self.data(), &rhs.data())
323 fn cmp(&self, rhs: &Self) -> Ordering {
324 Ord::cmp(&self.data(), &rhs.data())
328 /// A collection of `Span`s.
330 /// Spans have two orthogonal attributes:
332 /// - They can be *primary spans*. In this case they are the locus of
333 /// the error, and would be rendered with `^^^`.
334 /// - They can have a *label*. In this case, the label is written next
335 /// to the mark in the snippet when we render.
336 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
337 pub struct MultiSpan {
338 primary_spans: Vec<Span>,
339 span_labels: Vec<(Span, String)>,
344 pub fn lo(self) -> BytePos {
348 pub fn with_lo(self, lo: BytePos) -> Span {
349 self.data().with_lo(lo)
352 pub fn hi(self) -> BytePos {
356 pub fn with_hi(self, hi: BytePos) -> Span {
357 self.data().with_hi(hi)
360 pub fn ctxt(self) -> SyntaxContext {
364 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
365 self.data().with_ctxt(ctxt)
368 /// Returns `true` if this is a dummy span with any hygienic context.
370 pub fn is_dummy(self) -> bool {
371 let span = self.data();
372 span.lo.0 == 0 && span.hi.0 == 0
375 /// Returns `true` if this span comes from a macro or desugaring.
377 pub fn from_expansion(self) -> bool {
378 self.ctxt() != SyntaxContext::root()
381 /// Returns `true` if `span` originates in a derive-macro's expansion.
382 pub fn in_derive_expansion(self) -> bool {
383 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
387 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
388 Span::new(lo, hi, SyntaxContext::root())
391 /// Returns a new span representing an empty span at the beginning of this span
393 pub fn shrink_to_lo(self) -> Span {
394 let span = self.data();
395 span.with_hi(span.lo)
397 /// Returns a new span representing an empty span at the end of this span.
399 pub fn shrink_to_hi(self) -> Span {
400 let span = self.data();
401 span.with_lo(span.hi)
405 /// Returns true if hi == lo
406 pub fn is_empty(&self) -> bool {
407 let span = self.data();
411 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
412 pub fn substitute_dummy(self, other: Span) -> Span {
413 if self.is_dummy() { other } else { self }
416 /// Returns `true` if `self` fully encloses `other`.
417 pub fn contains(self, other: Span) -> bool {
418 let span = self.data();
419 let other = other.data();
420 span.lo <= other.lo && other.hi <= span.hi
423 /// Returns `true` if `self` touches `other`.
424 pub fn overlaps(self, other: Span) -> bool {
425 let span = self.data();
426 let other = other.data();
427 span.lo < other.hi && other.lo < span.hi
430 /// Returns `true` if the spans are equal with regards to the source text.
432 /// Use this instead of `==` when either span could be generated code,
433 /// and you only care that they point to the same bytes of source text.
434 pub fn source_equal(&self, other: &Span) -> bool {
435 let span = self.data();
436 let other = other.data();
437 span.lo == other.lo && span.hi == other.hi
440 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
441 pub fn trim_start(self, other: Span) -> Option<Span> {
442 let span = self.data();
443 let other = other.data();
444 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
447 /// Returns the source span -- this is either the supplied span, or the span for
448 /// the macro callsite that expanded to it.
449 pub fn source_callsite(self) -> Span {
450 let expn_data = self.ctxt().outer_expn_data();
451 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
454 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
456 pub fn parent(self) -> Option<Span> {
457 let expn_data = self.ctxt().outer_expn_data();
458 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
461 /// Edition of the crate from which this span came.
462 pub fn edition(self) -> edition::Edition {
463 self.ctxt().outer_expn_data().edition
467 pub fn rust_2015(&self) -> bool {
468 self.edition() == edition::Edition::Edition2015
472 pub fn rust_2018(&self) -> bool {
473 self.edition() >= edition::Edition::Edition2018
476 /// Returns the source callee.
478 /// Returns `None` if the supplied span has no expansion trace,
479 /// else returns the `ExpnData` for the macro definition
480 /// corresponding to the source callsite.
481 pub fn source_callee(self) -> Option<ExpnData> {
482 fn source_callee(expn_data: ExpnData) -> ExpnData {
483 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
484 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
486 let expn_data = self.ctxt().outer_expn_data();
487 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
490 /// Checks if a span is "internal" to a macro in which `#[unstable]`
491 /// items can be used (that is, a macro marked with
492 /// `#[allow_internal_unstable]`).
493 pub fn allows_unstable(&self, feature: Symbol) -> bool {
494 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
497 .any(|&f| f == feature || f == sym::allow_internal_unstable_backcompat_hack)
501 /// Checks if this span arises from a compiler desugaring of kind `kind`.
502 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
503 match self.ctxt().outer_expn_data().kind {
504 ExpnKind::Desugaring(k) => k == kind,
509 /// Returns the compiler desugaring that created this span, or `None`
510 /// if this span is not from a desugaring.
511 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
512 match self.ctxt().outer_expn_data().kind {
513 ExpnKind::Desugaring(k) => Some(k),
518 /// Checks if a span is "internal" to a macro in which `unsafe`
519 /// can be used without triggering the `unsafe_code` lint
520 // (that is, a macro marked with `#[allow_internal_unsafe]`).
521 pub fn allows_unsafe(&self) -> bool {
522 self.ctxt().outer_expn_data().allow_internal_unsafe
525 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
526 let mut prev_span = DUMMY_SP;
527 std::iter::from_fn(move || {
529 let expn_data = self.ctxt().outer_expn_data();
530 if expn_data.is_root() {
534 let is_recursive = expn_data.call_site.source_equal(&prev_span);
537 self = expn_data.call_site;
539 // Don't print recursive invocations.
541 return Some(expn_data);
547 /// Returns a `Span` that would enclose both `self` and `end`.
551 /// self lorem ipsum end
552 /// ^^^^^^^^^^^^^^^^^^^^
554 pub fn to(self, end: Span) -> Span {
555 let span_data = self.data();
556 let end_data = end.data();
557 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
558 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
559 // have an incomplete span than a completely nonsensical one.
560 if span_data.ctxt != end_data.ctxt {
561 if span_data.ctxt == SyntaxContext::root() {
563 } else if end_data.ctxt == SyntaxContext::root() {
566 // Both spans fall within a macro.
567 // FIXME(estebank): check if it is the *same* macro.
570 cmp::min(span_data.lo, end_data.lo),
571 cmp::max(span_data.hi, end_data.hi),
572 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
576 /// Returns a `Span` between the end of `self` to the beginning of `end`.
580 /// self lorem ipsum end
583 pub fn between(self, end: Span) -> Span {
584 let span = self.data();
585 let end = end.data();
589 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
593 /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
597 /// self lorem ipsum end
598 /// ^^^^^^^^^^^^^^^^^
600 pub fn until(self, end: Span) -> Span {
601 let span = self.data();
602 let end = end.data();
606 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
610 pub fn from_inner(self, inner: InnerSpan) -> Span {
611 let span = self.data();
613 span.lo + BytePos::from_usize(inner.start),
614 span.lo + BytePos::from_usize(inner.end),
619 /// Equivalent of `Span::def_site` from the proc macro API,
620 /// except that the location is taken from the `self` span.
621 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
622 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
625 /// Equivalent of `Span::call_site` from the proc macro API,
626 /// except that the location is taken from the `self` span.
627 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
628 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
631 /// Equivalent of `Span::mixed_site` from the proc macro API,
632 /// except that the location is taken from the `self` span.
633 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
634 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
637 /// Produces a span with the same location as `self` and context produced by a macro with the
638 /// given ID and transparency, assuming that macro was defined directly and not produced by
639 /// some other macro (which is the case for built-in and procedural macros).
640 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
641 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
645 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
646 let span = self.data();
647 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
651 pub fn remove_mark(&mut self) -> ExpnId {
652 let mut span = self.data();
653 let mark = span.ctxt.remove_mark();
654 *self = Span::new(span.lo, span.hi, span.ctxt);
659 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
660 let mut span = self.data();
661 let mark = span.ctxt.adjust(expn_id);
662 *self = Span::new(span.lo, span.hi, span.ctxt);
667 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
668 let mut span = self.data();
669 let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
670 *self = Span::new(span.lo, span.hi, span.ctxt);
675 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
676 let mut span = self.data();
677 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
678 *self = Span::new(span.lo, span.hi, span.ctxt);
683 pub fn reverse_glob_adjust(
687 ) -> Option<Option<ExpnId>> {
688 let mut span = self.data();
689 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
690 *self = Span::new(span.lo, span.hi, span.ctxt);
695 pub fn normalize_to_macros_2_0(self) -> Span {
696 let span = self.data();
697 span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
701 pub fn normalize_to_macro_rules(self) -> Span {
702 let span = self.data();
703 span.with_ctxt(span.ctxt.normalize_to_macro_rules())
707 #[derive(Clone, Debug)]
708 pub struct SpanLabel {
709 /// The span we are going to include in the final snippet.
712 /// Is this a primary span? This is the "locus" of the message,
713 /// and is indicated with a `^^^^` underline, versus `----`.
714 pub is_primary: bool,
716 /// What label should we attach to this span (if any)?
717 pub label: Option<String>,
720 impl Default for Span {
721 fn default() -> Self {
726 impl<E: Encoder> Encodable<E> for Span {
727 default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
728 let span = self.data();
729 s.emit_struct("Span", 2, |s| {
730 s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?;
731 s.emit_struct_field("hi", 1, |s| span.hi.encode(s))
735 impl<D: Decoder> Decodable<D> for Span {
736 default fn decode(s: &mut D) -> Result<Span, D::Error> {
737 s.read_struct("Span", 2, |d| {
738 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
739 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
741 Ok(Span::new(lo, hi, SyntaxContext::root()))
746 /// Calls the provided closure, using the provided `SourceMap` to format
747 /// any spans that are debug-printed during the closure'e exectuino.
749 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
750 /// (see `rustc_interface::callbacks::span_debug1). However, some parts
751 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
752 /// a `TyCtxt` is available. In this case, we fall back to
753 /// the `SourceMap` provided to this function. If that is not available,
754 /// we fall back to printing the raw `Span` field values
755 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
756 SESSION_GLOBALS.with(|session_globals| {
757 *session_globals.source_map.borrow_mut() = Some(source_map);
759 struct ClearSourceMap;
760 impl Drop for ClearSourceMap {
762 SESSION_GLOBALS.with(|session_globals| {
763 session_globals.source_map.borrow_mut().take();
768 let _guard = ClearSourceMap;
772 pub fn debug_with_source_map(
774 f: &mut fmt::Formatter<'_>,
775 source_map: &SourceMap,
777 write!(f, "{} ({:?})", source_map.span_to_string(span), span.ctxt())
780 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
781 SESSION_GLOBALS.with(|session_globals| {
782 if let Some(source_map) = &*session_globals.source_map.borrow() {
783 debug_with_source_map(span, f, source_map)
785 f.debug_struct("Span")
786 .field("lo", &span.lo())
787 .field("hi", &span.hi())
788 .field("ctxt", &span.ctxt())
794 impl fmt::Debug for Span {
795 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
796 (*SPAN_DEBUG)(*self, f)
800 impl fmt::Debug for SpanData {
801 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802 (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
808 pub fn new() -> MultiSpan {
809 MultiSpan { primary_spans: vec![], span_labels: vec![] }
812 pub fn from_span(primary_span: Span) -> MultiSpan {
813 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
816 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
818 MultiSpan { primary_spans: vec, span_labels: vec![] }
821 pub fn push_span_label(&mut self, span: Span, label: String) {
822 self.span_labels.push((span, label));
825 /// Selects the first primary span (if any).
826 pub fn primary_span(&self) -> Option<Span> {
827 self.primary_spans.first().cloned()
830 /// Returns all primary spans.
831 pub fn primary_spans(&self) -> &[Span] {
835 /// Returns `true` if any of the primary spans are displayable.
836 pub fn has_primary_spans(&self) -> bool {
837 self.primary_spans.iter().any(|sp| !sp.is_dummy())
840 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
841 pub fn is_dummy(&self) -> bool {
842 let mut is_dummy = true;
843 for span in &self.primary_spans {
844 if !span.is_dummy() {
851 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
852 /// display well (like std macros). Returns whether replacements occurred.
853 pub fn replace(&mut self, before: Span, after: Span) -> bool {
854 let mut replacements_occurred = false;
855 for primary_span in &mut self.primary_spans {
856 if *primary_span == before {
857 *primary_span = after;
858 replacements_occurred = true;
861 for span_label in &mut self.span_labels {
862 if span_label.0 == before {
863 span_label.0 = after;
864 replacements_occurred = true;
867 replacements_occurred
870 /// Returns the strings to highlight. We always ensure that there
871 /// is an entry for each of the primary spans -- for each primary
872 /// span `P`, if there is at least one label with span `P`, we return
873 /// those labels (marked as primary). But otherwise we return
874 /// `SpanLabel` instances with empty labels.
875 pub fn span_labels(&self) -> Vec<SpanLabel> {
876 let is_primary = |span| self.primary_spans.contains(&span);
878 let mut span_labels = self
881 .map(|&(span, ref label)| SpanLabel {
883 is_primary: is_primary(span),
884 label: Some(label.clone()),
886 .collect::<Vec<_>>();
888 for &span in &self.primary_spans {
889 if !span_labels.iter().any(|sl| sl.span == span) {
890 span_labels.push(SpanLabel { span, is_primary: true, label: None });
897 /// Returns `true` if any of the span labels is displayable.
898 pub fn has_span_labels(&self) -> bool {
899 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
903 impl From<Span> for MultiSpan {
904 fn from(span: Span) -> MultiSpan {
905 MultiSpan::from_span(span)
909 impl From<Vec<Span>> for MultiSpan {
910 fn from(spans: Vec<Span>) -> MultiSpan {
911 MultiSpan::from_spans(spans)
915 /// Identifies an offset of a multi-byte character in a `SourceFile`.
916 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
917 pub struct MultiByteChar {
918 /// The absolute offset of the character in the `SourceMap`.
920 /// The number of bytes, `>= 2`.
924 /// Identifies an offset of a non-narrow character in a `SourceFile`.
925 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
926 pub enum NonNarrowChar {
927 /// Represents a zero-width character.
929 /// Represents a wide (full-width) character.
931 /// Represents a tab character, represented visually with a width of 4 characters.
936 fn new(pos: BytePos, width: usize) -> Self {
938 0 => NonNarrowChar::ZeroWidth(pos),
939 2 => NonNarrowChar::Wide(pos),
940 4 => NonNarrowChar::Tab(pos),
941 _ => panic!("width {} given for non-narrow character", width),
945 /// Returns the absolute offset of the character in the `SourceMap`.
946 pub fn pos(&self) -> BytePos {
948 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
952 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
953 pub fn width(&self) -> usize {
955 NonNarrowChar::ZeroWidth(_) => 0,
956 NonNarrowChar::Wide(_) => 2,
957 NonNarrowChar::Tab(_) => 4,
962 impl Add<BytePos> for NonNarrowChar {
965 fn add(self, rhs: BytePos) -> Self {
967 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
968 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
969 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
974 impl Sub<BytePos> for NonNarrowChar {
977 fn sub(self, rhs: BytePos) -> Self {
979 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
980 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
981 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
986 /// Identifies an offset of a character that was normalized away from `SourceFile`.
987 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
988 pub struct NormalizedPos {
989 /// The absolute offset of the character in the `SourceMap`.
991 /// The difference between original and normalized string at position.
995 #[derive(PartialEq, Eq, Clone, Debug)]
996 pub enum ExternalSource {
997 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
1000 kind: ExternalSourceKind,
1001 /// This SourceFile's byte-offset within the source_map of its original crate
1002 original_start_pos: BytePos,
1003 /// The end of this SourceFile within the source_map of its original crate
1004 original_end_pos: BytePos,
1008 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1009 #[derive(PartialEq, Eq, Clone, Debug)]
1010 pub enum ExternalSourceKind {
1011 /// The external source has been loaded already.
1012 Present(Lrc<String>),
1013 /// No attempt has been made to load the external source.
1015 /// A failed attempt has been made to load the external source.
1020 impl ExternalSource {
1021 pub fn is_absent(&self) -> bool {
1023 ExternalSource::Foreign { kind: ExternalSourceKind::Present(_), .. } => false,
1028 pub fn get_source(&self) -> Option<&Lrc<String>> {
1030 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1037 pub struct OffsetOverflowError;
1039 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1040 pub enum SourceFileHashAlgorithm {
1045 impl FromStr for SourceFileHashAlgorithm {
1048 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1050 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1051 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1057 rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm);
1059 /// The hash of the on-disk source file used for debug info.
1060 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1061 #[derive(HashStable_Generic, Encodable, Decodable)]
1062 pub struct SourceFileHash {
1063 pub kind: SourceFileHashAlgorithm,
1067 impl SourceFileHash {
1068 pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1069 let mut hash = SourceFileHash { kind, value: Default::default() };
1070 let len = hash.hash_len();
1071 let value = &mut hash.value[..len];
1072 let data = src.as_bytes();
1074 SourceFileHashAlgorithm::Md5 => {
1075 value.copy_from_slice(&Md5::digest(data));
1077 SourceFileHashAlgorithm::Sha1 => {
1078 value.copy_from_slice(&Sha1::digest(data));
1084 /// Check if the stored hash matches the hash of the string.
1085 pub fn matches(&self, src: &str) -> bool {
1086 Self::new(self.kind, src) == *self
1089 /// The bytes of the hash.
1090 pub fn hash_bytes(&self) -> &[u8] {
1091 let len = self.hash_len();
1095 fn hash_len(&self) -> usize {
1097 SourceFileHashAlgorithm::Md5 => 16,
1098 SourceFileHashAlgorithm::Sha1 => 20,
1103 /// A single source in the `SourceMap`.
1105 pub struct SourceFile {
1106 /// The name of the file that the source came from. Source that doesn't
1107 /// originate from files has names between angle brackets by convention
1108 /// (e.g., `<anon>`).
1110 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
1111 pub name_was_remapped: bool,
1112 /// The unmapped path of the file that the source came from.
1113 /// Set to `None` if the `SourceFile` was imported from an external crate.
1114 pub unmapped_path: Option<FileName>,
1115 /// The complete source code.
1116 pub src: Option<Lrc<String>>,
1117 /// The source code's hash.
1118 pub src_hash: SourceFileHash,
1119 /// The external source code (used for external crates, which will have a `None`
1120 /// value as `self.src`.
1121 pub external_src: Lock<ExternalSource>,
1122 /// The start position of this source in the `SourceMap`.
1123 pub start_pos: BytePos,
1124 /// The end position of this source in the `SourceMap`.
1125 pub end_pos: BytePos,
1126 /// Locations of lines beginnings in the source code.
1127 pub lines: Vec<BytePos>,
1128 /// Locations of multi-byte characters in the source code.
1129 pub multibyte_chars: Vec<MultiByteChar>,
1130 /// Width of characters that are not narrow in the source code.
1131 pub non_narrow_chars: Vec<NonNarrowChar>,
1132 /// Locations of characters removed during normalization.
1133 pub normalized_pos: Vec<NormalizedPos>,
1134 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1135 pub name_hash: u128,
1136 /// Indicates which crate this `SourceFile` was imported from.
1140 impl<S: Encoder> Encodable<S> for SourceFile {
1141 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1142 s.emit_struct("SourceFile", 8, |s| {
1143 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
1144 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
1145 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
1146 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
1147 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
1148 s.emit_struct_field("lines", 5, |s| {
1149 let lines = &self.lines[..];
1150 // Store the length.
1151 s.emit_u32(lines.len() as u32)?;
1153 if !lines.is_empty() {
1154 // In order to preserve some space, we exploit the fact that
1155 // the lines list is sorted and individual lines are
1156 // probably not that long. Because of that we can store lines
1157 // as a difference list, using as little space as possible
1158 // for the differences.
1159 let max_line_length = if lines.len() == 1 {
1164 .map(|&[fst, snd]| snd - fst)
1165 .map(|bp| bp.to_usize())
1170 let bytes_per_diff: u8 = match max_line_length {
1172 0x100..=0xFFFF => 2,
1176 // Encode the number of bytes used per diff.
1177 bytes_per_diff.encode(s)?;
1179 // Encode the first element.
1180 lines[0].encode(s)?;
1182 let diff_iter = lines[..].array_windows().map(|&[fst, snd]| snd - fst);
1184 match bytes_per_diff {
1186 for diff in diff_iter {
1187 (diff.0 as u8).encode(s)?
1191 for diff in diff_iter {
1192 (diff.0 as u16).encode(s)?
1196 for diff in diff_iter {
1200 _ => unreachable!(),
1206 s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
1207 s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
1208 s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
1209 s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))?;
1210 s.emit_struct_field("cnum", 10, |s| self.cnum.encode(s))
1215 impl<D: Decoder> Decodable<D> for SourceFile {
1216 fn decode(d: &mut D) -> Result<SourceFile, D::Error> {
1217 d.read_struct("SourceFile", 8, |d| {
1218 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1219 let name_was_remapped: bool =
1220 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1221 let src_hash: SourceFileHash =
1222 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1223 let start_pos: BytePos =
1224 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1225 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1226 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1227 let num_lines: u32 = Decodable::decode(d)?;
1228 let mut lines = Vec::with_capacity(num_lines as usize);
1231 // Read the number of bytes used per diff.
1232 let bytes_per_diff: u8 = Decodable::decode(d)?;
1234 // Read the first element.
1235 let mut line_start: BytePos = Decodable::decode(d)?;
1236 lines.push(line_start);
1238 for _ in 1..num_lines {
1239 let diff = match bytes_per_diff {
1240 1 => d.read_u8()? as u32,
1241 2 => d.read_u16()? as u32,
1243 _ => unreachable!(),
1246 line_start = line_start + BytePos(diff);
1248 lines.push(line_start);
1254 let multibyte_chars: Vec<MultiByteChar> =
1255 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1256 let non_narrow_chars: Vec<NonNarrowChar> =
1257 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1258 let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1259 let normalized_pos: Vec<NormalizedPos> =
1260 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1261 let cnum: CrateNum = d.read_struct_field("cnum", 10, |d| Decodable::decode(d))?;
1265 unmapped_path: None,
1270 // Unused - the metadata decoder will construct
1271 // a new SourceFile, filling in `external_src` properly
1272 external_src: Lock::new(ExternalSource::Unneeded),
1284 impl fmt::Debug for SourceFile {
1285 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1286 write!(fmt, "SourceFile({})", self.name)
1293 name_was_remapped: bool,
1294 unmapped_path: FileName,
1297 hash_kind: SourceFileHashAlgorithm,
1299 // Compute the file hash before any normalization.
1300 let src_hash = SourceFileHash::new(hash_kind, &src);
1301 let normalized_pos = normalize_src(&mut src, start_pos);
1304 let mut hasher: StableHasher = StableHasher::new();
1305 name.hash(&mut hasher);
1306 hasher.finish::<u128>()
1308 let end_pos = start_pos.to_usize() + src.len();
1309 assert!(end_pos <= u32::MAX as usize);
1311 let (lines, multibyte_chars, non_narrow_chars) =
1312 analyze_source_file::analyze_source_file(&src[..], start_pos);
1317 unmapped_path: Some(unmapped_path),
1318 src: Some(Lrc::new(src)),
1320 external_src: Lock::new(ExternalSource::Unneeded),
1322 end_pos: Pos::from_usize(end_pos),
1332 /// Returns the `BytePos` of the beginning of the current line.
1333 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1334 let line_index = self.lookup_line(pos).unwrap();
1335 self.lines[line_index]
1338 /// Add externally loaded source.
1339 /// If the hash of the input doesn't match or no input is supplied via None,
1340 /// it is interpreted as an error and the corresponding enum variant is set.
1341 /// The return value signifies whether some kind of source is present.
1342 pub fn add_external_src<F>(&self, get_src: F) -> bool
1344 F: FnOnce() -> Option<String>,
1347 *self.external_src.borrow(),
1348 ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1350 let src = get_src();
1351 let mut external_src = self.external_src.borrow_mut();
1352 // Check that no-one else have provided the source while we were getting it
1353 if let ExternalSource::Foreign {
1354 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1355 } = &mut *external_src
1357 if let Some(mut src) = src {
1358 // The src_hash needs to be computed on the pre-normalized src.
1359 if self.src_hash.matches(&src) {
1360 normalize_src(&mut src, BytePos::from_usize(0));
1361 *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1365 *src_kind = ExternalSourceKind::AbsentErr;
1370 self.src.is_some() || external_src.get_source().is_some()
1373 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1377 /// Gets a line from the list of pre-computed line-beginnings.
1378 /// The line number here is 0-based.
1379 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1380 fn get_until_newline(src: &str, begin: usize) -> &str {
1381 // We can't use `lines.get(line_number+1)` because we might
1382 // be parsing when we call this function and thus the current
1383 // line is the last one we have line info for.
1384 let slice = &src[begin..];
1385 match slice.find('\n') {
1386 Some(e) => &slice[..e],
1392 let line = self.lines.get(line_number)?;
1393 let begin: BytePos = *line - self.start_pos;
1397 if let Some(ref src) = self.src {
1398 Some(Cow::from(get_until_newline(src, begin)))
1399 } else if let Some(src) = self.external_src.borrow().get_source() {
1400 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1406 pub fn is_real_file(&self) -> bool {
1410 pub fn is_imported(&self) -> bool {
1414 pub fn byte_length(&self) -> u32 {
1415 self.end_pos.0 - self.start_pos.0
1417 pub fn count_lines(&self) -> usize {
1421 /// Finds the line containing the given position. The return value is the
1422 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1423 /// number. If the source_file is empty or the position is located before the
1424 /// first line, `None` is returned.
1425 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1426 if self.lines.is_empty() {
1430 let line_index = lookup_line(&self.lines[..], pos);
1431 assert!(line_index < self.lines.len() as isize);
1432 if line_index >= 0 { Some(line_index as usize) } else { None }
1435 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1436 if self.start_pos == self.end_pos {
1437 return (self.start_pos, self.end_pos);
1440 assert!(line_index < self.lines.len());
1441 if line_index == (self.lines.len() - 1) {
1442 (self.lines[line_index], self.end_pos)
1444 (self.lines[line_index], self.lines[line_index + 1])
1449 pub fn contains(&self, byte_pos: BytePos) -> bool {
1450 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1453 /// Calculates the original byte position relative to the start of the file
1454 /// based on the given byte position.
1455 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1456 // Diff before any records is 0. Otherwise use the previously recorded
1457 // diff as that applies to the following characters until a new diff
1459 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1460 Ok(i) => self.normalized_pos[i].diff,
1461 Err(i) if i == 0 => 0,
1462 Err(i) => self.normalized_pos[i - 1].diff,
1465 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1468 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1469 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1470 // The number of extra bytes due to multibyte chars in the `SourceFile`.
1471 let mut total_extra_bytes = 0;
1473 for mbc in self.multibyte_chars.iter() {
1474 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1476 // Every character is at least one byte, so we only
1477 // count the actual extra bytes.
1478 total_extra_bytes += mbc.bytes as u32 - 1;
1479 // We should never see a byte position in the middle of a
1481 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1487 assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1488 CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1491 /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1492 /// given `BytePos`.
1493 pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1494 let chpos = self.bytepos_to_file_charpos(pos);
1495 match self.lookup_line(pos) {
1497 let line = a + 1; // Line numbers start at 1
1498 let linebpos = self.lines[a];
1499 let linechpos = self.bytepos_to_file_charpos(linebpos);
1500 let col = chpos - linechpos;
1501 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1502 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1503 debug!("byte is on line: {}", line);
1504 assert!(chpos >= linechpos);
1511 /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1512 /// column offset when displayed, for a given `BytePos`.
1513 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1514 let (line, col_or_chpos) = self.lookup_file_pos(pos);
1516 let col = col_or_chpos;
1517 let linebpos = self.lines[line - 1];
1519 let start_width_idx = self
1521 .binary_search_by_key(&linebpos, |x| x.pos())
1522 .unwrap_or_else(|x| x);
1523 let end_width_idx = self
1525 .binary_search_by_key(&pos, |x| x.pos())
1526 .unwrap_or_else(|x| x);
1527 let special_chars = end_width_idx - start_width_idx;
1528 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1532 col.0 - special_chars + non_narrow
1534 (line, col, col_display)
1536 let chpos = col_or_chpos;
1538 let end_width_idx = self
1540 .binary_search_by_key(&pos, |x| x.pos())
1541 .unwrap_or_else(|x| x);
1542 let non_narrow: usize =
1543 self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1544 chpos.0 - end_width_idx + non_narrow
1546 (0, chpos, col_display)
1551 /// Normalizes the source code and records the normalizations.
1552 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1553 let mut normalized_pos = vec![];
1554 remove_bom(src, &mut normalized_pos);
1555 normalize_newlines(src, &mut normalized_pos);
1557 // Offset all the positions by start_pos to match the final file positions.
1558 for np in &mut normalized_pos {
1559 np.pos.0 += start_pos.0;
1565 /// Removes UTF-8 BOM, if any.
1566 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1567 if src.starts_with("\u{feff}") {
1569 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1573 /// Replaces `\r\n` with `\n` in-place in `src`.
1575 /// Returns error if there's a lone `\r` in the string
1576 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1577 if !src.as_bytes().contains(&b'\r') {
1581 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1582 // While we *can* call `as_mut_vec` and do surgery on the live string
1583 // directly, let's rather steal the contents of `src`. This makes the code
1584 // safe even if a panic occurs.
1586 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1587 let mut gap_len = 0;
1588 let mut tail = buf.as_mut_slice();
1590 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1592 let idx = match find_crlf(&tail[gap_len..]) {
1594 Some(idx) => idx + gap_len,
1596 tail.copy_within(gap_len..idx, 0);
1597 tail = &mut tail[idx - gap_len..];
1598 if tail.len() == gap_len {
1601 cursor += idx - gap_len;
1603 normalized_pos.push(NormalizedPos {
1604 pos: BytePos::from_usize(cursor + 1),
1605 diff: original_gap + gap_len as u32,
1609 // Account for removed `\r`.
1610 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1611 let new_len = buf.len() - gap_len;
1613 buf.set_len(new_len);
1614 *src = String::from_utf8_unchecked(buf);
1617 fn find_crlf(src: &[u8]) -> Option<usize> {
1618 let mut search_idx = 0;
1619 while let Some(idx) = find_cr(&src[search_idx..]) {
1620 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1621 search_idx += idx + 1;
1624 return Some(search_idx + idx);
1629 fn find_cr(src: &[u8]) -> Option<usize> {
1630 src.iter().position(|&b| b == b'\r')
1634 // _____________________________________________________________________________
1635 // Pos, BytePos, CharPos
1639 fn from_usize(n: usize) -> Self;
1640 fn to_usize(&self) -> usize;
1641 fn from_u32(n: u32) -> Self;
1642 fn to_u32(&self) -> u32;
1645 macro_rules! impl_pos {
1649 $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1654 $vis struct $ident($inner_vis $inner_ty);
1656 impl Pos for $ident {
1658 fn from_usize(n: usize) -> $ident {
1659 $ident(n as $inner_ty)
1663 fn to_usize(&self) -> usize {
1668 fn from_u32(n: u32) -> $ident {
1669 $ident(n as $inner_ty)
1673 fn to_u32(&self) -> u32 {
1678 impl Add for $ident {
1679 type Output = $ident;
1682 fn add(self, rhs: $ident) -> $ident {
1683 $ident(self.0 + rhs.0)
1687 impl Sub for $ident {
1688 type Output = $ident;
1691 fn sub(self, rhs: $ident) -> $ident {
1692 $ident(self.0 - rhs.0)
1700 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1702 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1703 pub struct BytePos(pub u32);
1705 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1706 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1707 /// values to `CharPos` values as necessary.
1708 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1709 pub struct CharPos(pub usize);
1712 impl<S: rustc_serialize::Encoder> Encodable<S> for BytePos {
1713 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1718 impl<D: rustc_serialize::Decoder> Decodable<D> for BytePos {
1719 fn decode(d: &mut D) -> Result<BytePos, D::Error> {
1720 Ok(BytePos(d.read_u32()?))
1724 // _____________________________________________________________________________
1725 // Loc, SourceFileAndLine, SourceFileAndBytePos
1728 /// A source code location used for error reporting.
1729 #[derive(Debug, Clone)]
1731 /// Information about the original source.
1732 pub file: Lrc<SourceFile>,
1733 /// The (1-based) line number.
1735 /// The (0-based) column offset.
1737 /// The (0-based) column offset when displayed.
1738 pub col_display: usize,
1741 // Used to be structural records.
1743 pub struct SourceFileAndLine {
1744 pub sf: Lrc<SourceFile>,
1748 pub struct SourceFileAndBytePos {
1749 pub sf: Lrc<SourceFile>,
1753 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1754 pub struct LineInfo {
1755 /// Index of line, starting from 0.
1756 pub line_index: usize,
1758 /// Column in line where span begins, starting from 0.
1759 pub start_col: CharPos,
1761 /// Column in line where span ends, starting from 0, exclusive.
1762 pub end_col: CharPos,
1765 pub struct FileLines {
1766 pub file: Lrc<SourceFile>,
1767 pub lines: Vec<LineInfo>,
1770 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1771 AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1773 // _____________________________________________________________________________
1774 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1777 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1779 #[derive(Clone, PartialEq, Eq, Debug)]
1780 pub enum SpanLinesError {
1781 DistinctSources(DistinctSources),
1784 #[derive(Clone, PartialEq, Eq, Debug)]
1785 pub enum SpanSnippetError {
1786 IllFormedSpan(Span),
1787 DistinctSources(DistinctSources),
1788 MalformedForSourcemap(MalformedSourceMapPositions),
1789 SourceNotAvailable { filename: FileName },
1792 #[derive(Clone, PartialEq, Eq, Debug)]
1793 pub struct DistinctSources {
1794 pub begin: (FileName, BytePos),
1795 pub end: (FileName, BytePos),
1798 #[derive(Clone, PartialEq, Eq, Debug)]
1799 pub struct MalformedSourceMapPositions {
1801 pub source_len: usize,
1802 pub begin_pos: BytePos,
1803 pub end_pos: BytePos,
1806 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1807 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1808 pub struct InnerSpan {
1814 pub fn new(start: usize, end: usize) -> InnerSpan {
1815 InnerSpan { start, end }
1819 // Given a slice of line start positions and a position, returns the index of
1820 // the line the position is on. Returns -1 if the position is located before
1822 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1823 match lines.binary_search(&pos) {
1824 Ok(line) => line as isize,
1825 Err(line) => line as isize - 1,
1829 /// Requirements for a `StableHashingContext` to be used in this crate.
1830 /// This is a hack to allow using the `HashStable_Generic` derive macro
1831 /// instead of implementing everything in librustc_middle.
1832 pub trait HashStableContext {
1833 fn hash_def_id(&mut self, _: DefId, hasher: &mut StableHasher);
1834 fn hash_crate_num(&mut self, _: CrateNum, hasher: &mut StableHasher);
1835 fn hash_spans(&self) -> bool;
1836 fn byte_pos_to_line_and_col(
1839 ) -> Option<(Lrc<SourceFile>, usize, BytePos)>;
1842 impl<CTX> HashStable<CTX> for Span
1844 CTX: HashStableContext,
1846 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1847 /// fields (that would be similar to hashing pointers, since those are just
1848 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1849 /// triple, which stays the same even if the containing `SourceFile` has moved
1850 /// within the `SourceMap`.
1851 /// Also note that we are hashing byte offsets for the column, not unicode
1852 /// codepoint offsets. For the purpose of the hash that's sufficient.
1853 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1854 /// span starts and ends in the same file, which is almost always the case.
1855 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1856 const TAG_VALID_SPAN: u8 = 0;
1857 const TAG_INVALID_SPAN: u8 = 1;
1859 if !ctx.hash_spans() {
1863 if *self == DUMMY_SP {
1864 Hash::hash(&TAG_INVALID_SPAN, hasher);
1868 // If this is not an empty or invalid span, we want to hash the last
1869 // position that belongs to it, as opposed to hashing the first
1870 // position past it.
1871 let span = self.data();
1872 let (file_lo, line_lo, col_lo) = match ctx.byte_pos_to_line_and_col(span.lo) {
1875 Hash::hash(&TAG_INVALID_SPAN, hasher);
1876 span.ctxt.hash_stable(ctx, hasher);
1881 if !file_lo.contains(span.hi) {
1882 Hash::hash(&TAG_INVALID_SPAN, hasher);
1883 span.ctxt.hash_stable(ctx, hasher);
1887 Hash::hash(&TAG_VALID_SPAN, hasher);
1888 // We truncate the stable ID hash and line and column numbers. The chances
1889 // of causing a collision this way should be minimal.
1890 Hash::hash(&(file_lo.name_hash as u64), hasher);
1892 let col = (col_lo.0 as u64) & 0xFF;
1893 let line = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1894 let len = ((span.hi - span.lo).0 as u64) << 32;
1895 let line_col_len = col | line | len;
1896 Hash::hash(&line_col_len, hasher);
1897 span.ctxt.hash_stable(ctx, hasher);
1901 impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1902 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1903 const TAG_EXPANSION: u8 = 0;
1904 const TAG_NO_EXPANSION: u8 = 1;
1906 if *self == SyntaxContext::root() {
1907 TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1909 TAG_EXPANSION.hash_stable(ctx, hasher);
1910 let (expn_id, transparency) = self.outer_mark();
1911 expn_id.hash_stable(ctx, hasher);
1912 transparency.hash_stable(ctx, hasher);
1917 impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
1918 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1919 // Since the same expansion context is usually referenced many
1920 // times, we cache a stable hash of it and hash that instead of
1921 // recursing every time.
1923 static CACHE: RefCell<Vec<Option<Fingerprint>>> = Default::default();
1926 const TAG_ROOT: u8 = 0;
1927 const TAG_NOT_ROOT: u8 = 1;
1929 if *self == ExpnId::root() {
1930 TAG_ROOT.hash_stable(ctx, hasher);
1934 TAG_NOT_ROOT.hash_stable(ctx, hasher);
1935 let index = self.as_u32() as usize;
1937 let res = CACHE.with(|cache| cache.borrow().get(index).copied().flatten());
1939 if let Some(res) = res {
1940 res.hash_stable(ctx, hasher);
1942 let new_len = index + 1;
1944 let mut sub_hasher = StableHasher::new();
1945 self.expn_data().hash_stable(ctx, &mut sub_hasher);
1946 let sub_hash: Fingerprint = sub_hasher.finish();
1948 CACHE.with(|cache| {
1949 let mut cache = cache.borrow_mut();
1950 if cache.len() < new_len {
1951 cache.resize(new_len, None);
1953 cache[index].replace(sub_hash).expect_none("Cache slot was filled");
1955 sub_hash.hash_stable(ctx, hasher);