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/")]
8 #![feature(crate_visibility_modifier)]
10 #![feature(const_panic)]
11 #![feature(negative_impls)]
13 #![feature(optin_builtin_traits)]
14 #![feature(min_specialization)]
15 #![feature(option_expect_none)]
16 #![feature(refcell_take)]
18 // FIXME(#56935): Work around ICEs during cross-compilation.
20 extern crate rustc_macros;
22 use rustc_data_structures::AtomicRef;
23 use rustc_macros::HashStable_Generic;
24 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
26 mod caching_source_map_view;
28 pub use self::caching_source_map_view::CachingSourceMapView;
29 use source_map::SourceMap;
34 pub use hygiene::SyntaxContext;
35 pub use hygiene::{DesugaringKind, ExpnData, ExpnId, ExpnKind, ForLoopLoc, MacroKind};
36 use hygiene::{Transparency, NUM_TRANSPARENCIES};
38 use def_id::{CrateNum, DefId, LOCAL_CRATE};
40 pub use span_encoding::{Span, DUMMY_SP};
43 pub use symbol::{sym, Symbol};
45 mod analyze_source_file;
48 use rustc_data_structures::fingerprint::Fingerprint;
49 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
50 use rustc_data_structures::sync::{Lock, Lrc};
53 use std::cell::RefCell;
54 use std::cmp::{self, Ordering};
57 use std::ops::{Add, Sub};
58 use std::path::{Path, PathBuf};
59 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 // If this ever becomes non thread-local, `decode_syntax_context`
91 // and `decode_expn_id` will need to be updated to handle concurrent
93 scoped_tls::scoped_thread_local!(pub static SESSION_GLOBALS: SessionGlobals);
95 // FIXME: Perhaps this should not implement Rustc{Decodable, Encodable}
97 // FIXME: We should use this enum or something like it to get rid of the
98 // use of magic `/rust/1.x/...` paths across the board.
99 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
100 #[derive(HashStable_Generic)]
101 pub enum RealFileName {
103 /// For de-virtualized paths (namely paths into libstd that have been mapped
104 /// to the appropriate spot on the local host's file system),
106 /// `local_path` is the (host-dependent) local path to the file.
108 /// `virtual_name` is the stable path rustc will store internally within
110 virtual_name: PathBuf,
115 /// Returns the path suitable for reading from the file system on the local host.
116 /// Avoid embedding this in build artifacts; see `stable_name` for that.
117 pub fn local_path(&self) -> &Path {
119 RealFileName::Named(p)
120 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => &p,
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 into_local_path(self) -> PathBuf {
128 RealFileName::Named(p)
129 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => p,
133 /// Returns the path suitable for embedding into build artifacts. Note that
134 /// a virtualized path will not correspond to a valid file system path; see
135 /// `local_path` for something that is more likely to return paths into the
136 /// local host file system.
137 pub fn stable_name(&self) -> &Path {
139 RealFileName::Named(p)
140 | RealFileName::Devirtualized { local_path: _, virtual_name: p } => &p,
145 /// Differentiates between real files and common virtual files.
146 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
147 #[derive(HashStable_Generic)]
150 /// Call to `quote!`.
154 /// Hack in `src/librustc_ast/parse.rs`.
157 ProcMacroSourceCode(u64),
158 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
160 /// Strings provided as crate attributes in the CLI.
162 /// Custom sources for explicit parser calls from plugins and drivers.
164 DocTest(PathBuf, isize),
165 /// Post-substitution inline assembly from LLVM
169 impl std::fmt::Display for FileName {
170 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173 Real(RealFileName::Named(ref path)) => write!(fmt, "{}", path.display()),
174 // FIXME: might be nice to display both compoments of Devirtualized.
175 // But for now (to backport fix for issue #70924), best to not
176 // perturb diagnostics so its obvious test suite still works.
177 Real(RealFileName::Devirtualized { ref local_path, virtual_name: _ }) => {
178 write!(fmt, "{}", local_path.display())
180 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
181 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
182 Anon(_) => write!(fmt, "<anon>"),
183 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
184 CfgSpec(_) => write!(fmt, "<cfgspec>"),
185 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
186 Custom(ref s) => write!(fmt, "<{}>", s),
187 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
188 InlineAsm(_) => write!(fmt, "<inline asm>"),
193 impl From<PathBuf> for FileName {
194 fn from(p: PathBuf) -> Self {
195 assert!(!p.to_string_lossy().ends_with('>'));
196 FileName::Real(RealFileName::Named(p))
201 pub fn is_real(&self) -> bool {
207 | ProcMacroSourceCode(_)
213 | InlineAsm(_) => false,
217 pub fn quote_expansion_source_code(src: &str) -> FileName {
218 let mut hasher = StableHasher::new();
219 src.hash(&mut hasher);
220 FileName::QuoteExpansion(hasher.finish())
223 pub fn macro_expansion_source_code(src: &str) -> FileName {
224 let mut hasher = StableHasher::new();
225 src.hash(&mut hasher);
226 FileName::MacroExpansion(hasher.finish())
229 pub fn anon_source_code(src: &str) -> FileName {
230 let mut hasher = StableHasher::new();
231 src.hash(&mut hasher);
232 FileName::Anon(hasher.finish())
235 pub fn proc_macro_source_code(src: &str) -> FileName {
236 let mut hasher = StableHasher::new();
237 src.hash(&mut hasher);
238 FileName::ProcMacroSourceCode(hasher.finish())
241 pub fn cfg_spec_source_code(src: &str) -> FileName {
242 let mut hasher = StableHasher::new();
243 src.hash(&mut hasher);
244 FileName::QuoteExpansion(hasher.finish())
247 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
248 let mut hasher = StableHasher::new();
249 src.hash(&mut hasher);
250 FileName::CliCrateAttr(hasher.finish())
253 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
254 FileName::DocTest(path, line)
257 pub fn inline_asm_source_code(src: &str) -> FileName {
258 let mut hasher = StableHasher::new();
259 src.hash(&mut hasher);
260 FileName::InlineAsm(hasher.finish())
264 /// Spans represent a region of code, used for error reporting. Positions in spans
265 /// are *absolute* positions from the beginning of the source_map, not positions
266 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
267 /// to the original source.
268 /// You must be careful if the span crosses more than one file - you will not be
269 /// able to use many of the functions on spans in source_map and you cannot assume
270 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
271 /// range between files.
273 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
274 /// sent to other threads, but some pieces of performance infra run in a separate thread.
275 /// Using `Span` is generally preferred.
276 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
277 pub struct SpanData {
280 /// Information about where the macro came from, if this piece of
281 /// code was created by a macro expansion.
282 pub ctxt: SyntaxContext,
287 pub fn with_lo(&self, lo: BytePos) -> Span {
288 Span::new(lo, self.hi, self.ctxt)
291 pub fn with_hi(&self, hi: BytePos) -> Span {
292 Span::new(self.lo, hi, self.ctxt)
295 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
296 Span::new(self.lo, self.hi, ctxt)
300 // The interner is pointed to by a thread local value which is only set on the main thread
301 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
302 // to avoid panics and other errors, even though it would be memory safe to do so.
303 #[cfg(not(parallel_compiler))]
304 impl !Send for Span {}
305 #[cfg(not(parallel_compiler))]
306 impl !Sync for Span {}
308 impl PartialOrd for Span {
309 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
310 PartialOrd::partial_cmp(&self.data(), &rhs.data())
314 fn cmp(&self, rhs: &Self) -> Ordering {
315 Ord::cmp(&self.data(), &rhs.data())
319 /// A collection of `Span`s.
321 /// Spans have two orthogonal attributes:
323 /// - They can be *primary spans*. In this case they are the locus of
324 /// the error, and would be rendered with `^^^`.
325 /// - They can have a *label*. In this case, the label is written next
326 /// to the mark in the snippet when we render.
327 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
328 pub struct MultiSpan {
329 primary_spans: Vec<Span>,
330 span_labels: Vec<(Span, String)>,
335 pub fn lo(self) -> BytePos {
339 pub fn with_lo(self, lo: BytePos) -> Span {
340 self.data().with_lo(lo)
343 pub fn hi(self) -> BytePos {
347 pub fn with_hi(self, hi: BytePos) -> Span {
348 self.data().with_hi(hi)
351 pub fn ctxt(self) -> SyntaxContext {
355 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
356 self.data().with_ctxt(ctxt)
359 /// Returns `true` if this is a dummy span with any hygienic context.
361 pub fn is_dummy(self) -> bool {
362 let span = self.data();
363 span.lo.0 == 0 && span.hi.0 == 0
366 /// Returns `true` if this span comes from a macro or desugaring.
368 pub fn from_expansion(self) -> bool {
369 self.ctxt() != SyntaxContext::root()
372 /// Returns `true` if `span` originates in a derive-macro's expansion.
373 pub fn in_derive_expansion(self) -> bool {
374 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
378 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
379 Span::new(lo, hi, SyntaxContext::root())
382 /// Returns a new span representing an empty span at the beginning of this span
384 pub fn shrink_to_lo(self) -> Span {
385 let span = self.data();
386 span.with_hi(span.lo)
388 /// Returns a new span representing an empty span at the end of this span.
390 pub fn shrink_to_hi(self) -> Span {
391 let span = self.data();
392 span.with_lo(span.hi)
395 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
396 pub fn substitute_dummy(self, other: Span) -> Span {
397 if self.is_dummy() { other } else { self }
400 /// Returns `true` if `self` fully encloses `other`.
401 pub fn contains(self, other: Span) -> bool {
402 let span = self.data();
403 let other = other.data();
404 span.lo <= other.lo && other.hi <= span.hi
407 /// Returns `true` if `self` touches `other`.
408 pub fn overlaps(self, other: Span) -> bool {
409 let span = self.data();
410 let other = other.data();
411 span.lo < other.hi && other.lo < span.hi
414 /// Returns `true` if the spans are equal with regards to the source text.
416 /// Use this instead of `==` when either span could be generated code,
417 /// and you only care that they point to the same bytes of source text.
418 pub fn source_equal(&self, other: &Span) -> bool {
419 let span = self.data();
420 let other = other.data();
421 span.lo == other.lo && span.hi == other.hi
424 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
425 pub fn trim_start(self, other: Span) -> Option<Span> {
426 let span = self.data();
427 let other = other.data();
428 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
431 /// Returns the source span -- this is either the supplied span, or the span for
432 /// the macro callsite that expanded to it.
433 pub fn source_callsite(self) -> Span {
434 let expn_data = self.ctxt().outer_expn_data();
435 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
438 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
440 pub fn parent(self) -> Option<Span> {
441 let expn_data = self.ctxt().outer_expn_data();
442 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
445 /// Edition of the crate from which this span came.
446 pub fn edition(self) -> edition::Edition {
447 self.ctxt().outer_expn_data().edition
451 pub fn rust_2015(&self) -> bool {
452 self.edition() == edition::Edition::Edition2015
456 pub fn rust_2018(&self) -> bool {
457 self.edition() >= edition::Edition::Edition2018
460 /// Returns the source callee.
462 /// Returns `None` if the supplied span has no expansion trace,
463 /// else returns the `ExpnData` for the macro definition
464 /// corresponding to the source callsite.
465 pub fn source_callee(self) -> Option<ExpnData> {
466 fn source_callee(expn_data: ExpnData) -> ExpnData {
467 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
468 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
470 let expn_data = self.ctxt().outer_expn_data();
471 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
474 /// Checks if a span is "internal" to a macro in which `#[unstable]`
475 /// items can be used (that is, a macro marked with
476 /// `#[allow_internal_unstable]`).
477 pub fn allows_unstable(&self, feature: Symbol) -> bool {
478 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
481 .any(|&f| f == feature || f == sym::allow_internal_unstable_backcompat_hack)
485 /// Checks if this span arises from a compiler desugaring of kind `kind`.
486 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
487 match self.ctxt().outer_expn_data().kind {
488 ExpnKind::Desugaring(k) => k == kind,
493 /// Returns the compiler desugaring that created this span, or `None`
494 /// if this span is not from a desugaring.
495 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
496 match self.ctxt().outer_expn_data().kind {
497 ExpnKind::Desugaring(k) => Some(k),
502 /// Checks if a span is "internal" to a macro in which `unsafe`
503 /// can be used without triggering the `unsafe_code` lint
504 // (that is, a macro marked with `#[allow_internal_unsafe]`).
505 pub fn allows_unsafe(&self) -> bool {
506 self.ctxt().outer_expn_data().allow_internal_unsafe
509 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
510 let mut prev_span = DUMMY_SP;
511 std::iter::from_fn(move || {
513 let expn_data = self.ctxt().outer_expn_data();
514 if expn_data.is_root() {
518 let is_recursive = expn_data.call_site.source_equal(&prev_span);
521 self = expn_data.call_site;
523 // Don't print recursive invocations.
525 return Some(expn_data);
531 /// Returns a `Span` that would enclose both `self` and `end`.
532 pub fn to(self, end: Span) -> Span {
533 let span_data = self.data();
534 let end_data = end.data();
535 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
536 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
537 // have an incomplete span than a completely nonsensical one.
538 if span_data.ctxt != end_data.ctxt {
539 if span_data.ctxt == SyntaxContext::root() {
541 } else if end_data.ctxt == SyntaxContext::root() {
544 // Both spans fall within a macro.
545 // FIXME(estebank): check if it is the *same* macro.
548 cmp::min(span_data.lo, end_data.lo),
549 cmp::max(span_data.hi, end_data.hi),
550 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
554 /// Returns a `Span` between the end of `self` to the beginning of `end`.
555 pub fn between(self, end: Span) -> Span {
556 let span = self.data();
557 let end = end.data();
561 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
565 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
566 pub fn until(self, end: Span) -> Span {
567 let span = self.data();
568 let end = end.data();
572 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
576 pub fn from_inner(self, inner: InnerSpan) -> Span {
577 let span = self.data();
579 span.lo + BytePos::from_usize(inner.start),
580 span.lo + BytePos::from_usize(inner.end),
585 /// Equivalent of `Span::def_site` from the proc macro API,
586 /// except that the location is taken from the `self` span.
587 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
588 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
591 /// Equivalent of `Span::call_site` from the proc macro API,
592 /// except that the location is taken from the `self` span.
593 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
594 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
597 /// Equivalent of `Span::mixed_site` from the proc macro API,
598 /// except that the location is taken from the `self` span.
599 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
600 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
603 /// Produces a span with the same location as `self` and context produced by a macro with the
604 /// given ID and transparency, assuming that macro was defined directly and not produced by
605 /// some other macro (which is the case for built-in and procedural macros).
606 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
607 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
611 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
612 let span = self.data();
613 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
617 pub fn remove_mark(&mut self) -> ExpnId {
618 let mut span = self.data();
619 let mark = span.ctxt.remove_mark();
620 *self = Span::new(span.lo, span.hi, span.ctxt);
625 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
626 let mut span = self.data();
627 let mark = span.ctxt.adjust(expn_id);
628 *self = Span::new(span.lo, span.hi, span.ctxt);
633 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
634 let mut span = self.data();
635 let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
636 *self = Span::new(span.lo, span.hi, span.ctxt);
641 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
642 let mut span = self.data();
643 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
644 *self = Span::new(span.lo, span.hi, span.ctxt);
649 pub fn reverse_glob_adjust(
653 ) -> Option<Option<ExpnId>> {
654 let mut span = self.data();
655 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
656 *self = Span::new(span.lo, span.hi, span.ctxt);
661 pub fn normalize_to_macros_2_0(self) -> Span {
662 let span = self.data();
663 span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
667 pub fn normalize_to_macro_rules(self) -> Span {
668 let span = self.data();
669 span.with_ctxt(span.ctxt.normalize_to_macro_rules())
673 #[derive(Clone, Debug)]
674 pub struct SpanLabel {
675 /// The span we are going to include in the final snippet.
678 /// Is this a primary span? This is the "locus" of the message,
679 /// and is indicated with a `^^^^` underline, versus `----`.
680 pub is_primary: bool,
682 /// What label should we attach to this span (if any)?
683 pub label: Option<String>,
686 impl Default for Span {
687 fn default() -> Self {
692 impl rustc_serialize::UseSpecializedEncodable for Span {
693 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
694 let span = self.data();
695 s.emit_struct("Span", 2, |s| {
696 s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?;
698 s.emit_struct_field("hi", 1, |s| span.hi.encode(s))
703 impl rustc_serialize::UseSpecializedDecodable for Span {
704 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
705 d.read_struct("Span", 2, |d| {
706 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
707 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
708 Ok(Span::with_root_ctxt(lo, hi))
713 /// Calls the provided closure, using the provided `SourceMap` to format
714 /// any spans that are debug-printed during the closure'e exectuino.
716 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
717 /// (see `rustc_interface::callbacks::span_debug1). However, some parts
718 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
719 /// a `TyCtxt` is available. In this case, we fall back to
720 /// the `SourceMap` provided to this function. If that is not available,
721 /// we fall back to printing the raw `Span` field values
722 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
723 SESSION_GLOBALS.with(|session_globals| {
724 *session_globals.source_map.borrow_mut() = Some(source_map);
726 struct ClearSourceMap;
727 impl Drop for ClearSourceMap {
729 SESSION_GLOBALS.with(|session_globals| {
730 session_globals.source_map.borrow_mut().take();
735 let _guard = ClearSourceMap;
739 pub fn debug_with_source_map(
741 f: &mut fmt::Formatter<'_>,
742 source_map: &SourceMap,
744 write!(f, "{} ({:?})", source_map.span_to_string(span), span.ctxt())
747 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
748 SESSION_GLOBALS.with(|session_globals| {
749 if let Some(source_map) = &*session_globals.source_map.borrow() {
750 debug_with_source_map(span, f, source_map)
752 f.debug_struct("Span")
753 .field("lo", &span.lo())
754 .field("hi", &span.hi())
755 .field("ctxt", &span.ctxt())
761 impl fmt::Debug for Span {
762 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
763 (*SPAN_DEBUG)(*self, f)
767 impl fmt::Debug for SpanData {
768 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
769 (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
775 pub fn new() -> MultiSpan {
776 MultiSpan { primary_spans: vec![], span_labels: vec![] }
779 pub fn from_span(primary_span: Span) -> MultiSpan {
780 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
783 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
785 MultiSpan { primary_spans: vec, span_labels: vec![] }
788 pub fn push_span_label(&mut self, span: Span, label: String) {
789 self.span_labels.push((span, label));
792 /// Selects the first primary span (if any).
793 pub fn primary_span(&self) -> Option<Span> {
794 self.primary_spans.first().cloned()
797 /// Returns all primary spans.
798 pub fn primary_spans(&self) -> &[Span] {
802 /// Returns `true` if any of the primary spans are displayable.
803 pub fn has_primary_spans(&self) -> bool {
804 self.primary_spans.iter().any(|sp| !sp.is_dummy())
807 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
808 pub fn is_dummy(&self) -> bool {
809 let mut is_dummy = true;
810 for span in &self.primary_spans {
811 if !span.is_dummy() {
818 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
819 /// display well (like std macros). Returns whether replacements occurred.
820 pub fn replace(&mut self, before: Span, after: Span) -> bool {
821 let mut replacements_occurred = false;
822 for primary_span in &mut self.primary_spans {
823 if *primary_span == before {
824 *primary_span = after;
825 replacements_occurred = true;
828 for span_label in &mut self.span_labels {
829 if span_label.0 == before {
830 span_label.0 = after;
831 replacements_occurred = true;
834 replacements_occurred
837 /// Returns the strings to highlight. We always ensure that there
838 /// is an entry for each of the primary spans -- for each primary
839 /// span `P`, if there is at least one label with span `P`, we return
840 /// those labels (marked as primary). But otherwise we return
841 /// `SpanLabel` instances with empty labels.
842 pub fn span_labels(&self) -> Vec<SpanLabel> {
843 let is_primary = |span| self.primary_spans.contains(&span);
845 let mut span_labels = self
848 .map(|&(span, ref label)| SpanLabel {
850 is_primary: is_primary(span),
851 label: Some(label.clone()),
853 .collect::<Vec<_>>();
855 for &span in &self.primary_spans {
856 if !span_labels.iter().any(|sl| sl.span == span) {
857 span_labels.push(SpanLabel { span, is_primary: true, label: None });
864 /// Returns `true` if any of the span labels is displayable.
865 pub fn has_span_labels(&self) -> bool {
866 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
870 impl From<Span> for MultiSpan {
871 fn from(span: Span) -> MultiSpan {
872 MultiSpan::from_span(span)
876 impl From<Vec<Span>> for MultiSpan {
877 fn from(spans: Vec<Span>) -> MultiSpan {
878 MultiSpan::from_spans(spans)
882 /// Identifies an offset of a multi-byte character in a `SourceFile`.
883 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
884 pub struct MultiByteChar {
885 /// The absolute offset of the character in the `SourceMap`.
887 /// The number of bytes, `>= 2`.
891 /// Identifies an offset of a non-narrow character in a `SourceFile`.
892 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
893 pub enum NonNarrowChar {
894 /// Represents a zero-width character.
896 /// Represents a wide (full-width) character.
898 /// Represents a tab character, represented visually with a width of 4 characters.
903 fn new(pos: BytePos, width: usize) -> Self {
905 0 => NonNarrowChar::ZeroWidth(pos),
906 2 => NonNarrowChar::Wide(pos),
907 4 => NonNarrowChar::Tab(pos),
908 _ => panic!("width {} given for non-narrow character", width),
912 /// Returns the absolute offset of the character in the `SourceMap`.
913 pub fn pos(&self) -> BytePos {
915 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
919 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
920 pub fn width(&self) -> usize {
922 NonNarrowChar::ZeroWidth(_) => 0,
923 NonNarrowChar::Wide(_) => 2,
924 NonNarrowChar::Tab(_) => 4,
929 impl Add<BytePos> for NonNarrowChar {
932 fn add(self, rhs: BytePos) -> Self {
934 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
935 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
936 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
941 impl Sub<BytePos> for NonNarrowChar {
944 fn sub(self, rhs: BytePos) -> Self {
946 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
947 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
948 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
953 /// Identifies an offset of a character that was normalized away from `SourceFile`.
954 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
955 pub struct NormalizedPos {
956 /// The absolute offset of the character in the `SourceMap`.
958 /// The difference between original and normalized string at position.
962 #[derive(PartialEq, Eq, Clone, Debug)]
963 pub enum ExternalSource {
964 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
967 kind: ExternalSourceKind,
968 /// This SourceFile's byte-offset within the source_map of its original crate
969 original_start_pos: BytePos,
970 /// The end of this SourceFile within the source_map of its original crate
971 original_end_pos: BytePos,
975 /// The state of the lazy external source loading mechanism of a `SourceFile`.
976 #[derive(PartialEq, Eq, Clone, Debug)]
977 pub enum ExternalSourceKind {
978 /// The external source has been loaded already.
979 Present(Lrc<String>),
980 /// No attempt has been made to load the external source.
982 /// A failed attempt has been made to load the external source.
987 impl ExternalSource {
988 pub fn is_absent(&self) -> bool {
990 ExternalSource::Foreign { kind: ExternalSourceKind::Present(_), .. } => false,
995 pub fn get_source(&self) -> Option<&Lrc<String>> {
997 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1004 pub struct OffsetOverflowError;
1006 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1007 pub enum SourceFileHashAlgorithm {
1012 impl FromStr for SourceFileHashAlgorithm {
1015 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1017 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1018 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1024 rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm);
1026 /// The hash of the on-disk source file used for debug info.
1027 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
1028 #[derive(HashStable_Generic)]
1029 pub struct SourceFileHash {
1030 pub kind: SourceFileHashAlgorithm,
1034 impl SourceFileHash {
1035 pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1036 let mut hash = SourceFileHash { kind, value: Default::default() };
1037 let len = hash.hash_len();
1038 let value = &mut hash.value[..len];
1039 let data = src.as_bytes();
1041 SourceFileHashAlgorithm::Md5 => {
1042 value.copy_from_slice(&Md5::digest(data));
1044 SourceFileHashAlgorithm::Sha1 => {
1045 value.copy_from_slice(&Sha1::digest(data));
1051 /// Check if the stored hash matches the hash of the string.
1052 pub fn matches(&self, src: &str) -> bool {
1053 Self::new(self.kind, src) == *self
1056 /// The bytes of the hash.
1057 pub fn hash_bytes(&self) -> &[u8] {
1058 let len = self.hash_len();
1062 fn hash_len(&self) -> usize {
1064 SourceFileHashAlgorithm::Md5 => 16,
1065 SourceFileHashAlgorithm::Sha1 => 20,
1070 /// A single source in the `SourceMap`.
1072 pub struct SourceFile {
1073 /// The name of the file that the source came from. Source that doesn't
1074 /// originate from files has names between angle brackets by convention
1075 /// (e.g., `<anon>`).
1077 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
1078 pub name_was_remapped: bool,
1079 /// The unmapped path of the file that the source came from.
1080 /// Set to `None` if the `SourceFile` was imported from an external crate.
1081 pub unmapped_path: Option<FileName>,
1082 /// The complete source code.
1083 pub src: Option<Lrc<String>>,
1084 /// The source code's hash.
1085 pub src_hash: SourceFileHash,
1086 /// The external source code (used for external crates, which will have a `None`
1087 /// value as `self.src`.
1088 pub external_src: Lock<ExternalSource>,
1089 /// The start position of this source in the `SourceMap`.
1090 pub start_pos: BytePos,
1091 /// The end position of this source in the `SourceMap`.
1092 pub end_pos: BytePos,
1093 /// Locations of lines beginnings in the source code.
1094 pub lines: Vec<BytePos>,
1095 /// Locations of multi-byte characters in the source code.
1096 pub multibyte_chars: Vec<MultiByteChar>,
1097 /// Width of characters that are not narrow in the source code.
1098 pub non_narrow_chars: Vec<NonNarrowChar>,
1099 /// Locations of characters removed during normalization.
1100 pub normalized_pos: Vec<NormalizedPos>,
1101 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1102 pub name_hash: u128,
1103 /// Indicates which crate this `SourceFile` was imported from.
1107 impl Encodable for SourceFile {
1108 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1109 s.emit_struct("SourceFile", 8, |s| {
1110 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
1111 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
1112 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
1113 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
1114 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
1115 s.emit_struct_field("lines", 5, |s| {
1116 let lines = &self.lines[..];
1117 // Store the length.
1118 s.emit_u32(lines.len() as u32)?;
1120 if !lines.is_empty() {
1121 // In order to preserve some space, we exploit the fact that
1122 // the lines list is sorted and individual lines are
1123 // probably not that long. Because of that we can store lines
1124 // as a difference list, using as little space as possible
1125 // for the differences.
1126 let max_line_length = if lines.len() == 1 {
1129 lines.windows(2).map(|w| w[1] - w[0]).map(|bp| bp.to_usize()).max().unwrap()
1132 let bytes_per_diff: u8 = match max_line_length {
1134 0x100..=0xFFFF => 2,
1138 // Encode the number of bytes used per diff.
1139 bytes_per_diff.encode(s)?;
1141 // Encode the first element.
1142 lines[0].encode(s)?;
1144 let diff_iter = (&lines[..]).windows(2).map(|w| (w[1] - w[0]));
1146 match bytes_per_diff {
1148 for diff in diff_iter {
1149 (diff.0 as u8).encode(s)?
1153 for diff in diff_iter {
1154 (diff.0 as u16).encode(s)?
1158 for diff in diff_iter {
1162 _ => unreachable!(),
1168 s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
1169 s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
1170 s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
1171 s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))?;
1172 s.emit_struct_field("cnum", 10, |s| self.cnum.encode(s))
1177 impl Decodable for SourceFile {
1178 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
1179 d.read_struct("SourceFile", 8, |d| {
1180 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1181 let name_was_remapped: bool =
1182 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1183 let src_hash: SourceFileHash =
1184 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1185 let start_pos: BytePos =
1186 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1187 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1188 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1189 let num_lines: u32 = Decodable::decode(d)?;
1190 let mut lines = Vec::with_capacity(num_lines as usize);
1193 // Read the number of bytes used per diff.
1194 let bytes_per_diff: u8 = Decodable::decode(d)?;
1196 // Read the first element.
1197 let mut line_start: BytePos = Decodable::decode(d)?;
1198 lines.push(line_start);
1200 for _ in 1..num_lines {
1201 let diff = match bytes_per_diff {
1202 1 => d.read_u8()? as u32,
1203 2 => d.read_u16()? as u32,
1205 _ => unreachable!(),
1208 line_start = line_start + BytePos(diff);
1210 lines.push(line_start);
1216 let multibyte_chars: Vec<MultiByteChar> =
1217 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1218 let non_narrow_chars: Vec<NonNarrowChar> =
1219 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1220 let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1221 let normalized_pos: Vec<NormalizedPos> =
1222 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1223 let cnum: CrateNum = d.read_struct_field("cnum", 10, |d| Decodable::decode(d))?;
1227 unmapped_path: None,
1232 // Unused - the metadata decoder will construct
1233 // a new SourceFile, filling in `external_src` properly
1234 external_src: Lock::new(ExternalSource::Unneeded),
1246 impl fmt::Debug for SourceFile {
1247 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1248 write!(fmt, "SourceFile({})", self.name)
1255 name_was_remapped: bool,
1256 unmapped_path: FileName,
1259 hash_kind: SourceFileHashAlgorithm,
1261 // Compute the file hash before any normalization.
1262 let src_hash = SourceFileHash::new(hash_kind, &src);
1263 let normalized_pos = normalize_src(&mut src, start_pos);
1266 let mut hasher: StableHasher = StableHasher::new();
1267 name.hash(&mut hasher);
1268 hasher.finish::<u128>()
1270 let end_pos = start_pos.to_usize() + src.len();
1271 assert!(end_pos <= u32::MAX as usize);
1273 let (lines, multibyte_chars, non_narrow_chars) =
1274 analyze_source_file::analyze_source_file(&src[..], start_pos);
1279 unmapped_path: Some(unmapped_path),
1280 src: Some(Lrc::new(src)),
1282 external_src: Lock::new(ExternalSource::Unneeded),
1284 end_pos: Pos::from_usize(end_pos),
1294 /// Returns the `BytePos` of the beginning of the current line.
1295 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1296 let line_index = self.lookup_line(pos).unwrap();
1297 self.lines[line_index]
1300 /// Add externally loaded source.
1301 /// If the hash of the input doesn't match or no input is supplied via None,
1302 /// it is interpreted as an error and the corresponding enum variant is set.
1303 /// The return value signifies whether some kind of source is present.
1304 pub fn add_external_src<F>(&self, get_src: F) -> bool
1306 F: FnOnce() -> Option<String>,
1309 *self.external_src.borrow(),
1310 ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1312 let src = get_src();
1313 let mut external_src = self.external_src.borrow_mut();
1314 // Check that no-one else have provided the source while we were getting it
1315 if let ExternalSource::Foreign {
1316 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1317 } = &mut *external_src
1319 if let Some(mut src) = src {
1320 // The src_hash needs to be computed on the pre-normalized src.
1321 if self.src_hash.matches(&src) {
1322 normalize_src(&mut src, BytePos::from_usize(0));
1323 *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1327 *src_kind = ExternalSourceKind::AbsentErr;
1332 self.src.is_some() || external_src.get_source().is_some()
1335 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1339 /// Gets a line from the list of pre-computed line-beginnings.
1340 /// The line number here is 0-based.
1341 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1342 fn get_until_newline(src: &str, begin: usize) -> &str {
1343 // We can't use `lines.get(line_number+1)` because we might
1344 // be parsing when we call this function and thus the current
1345 // line is the last one we have line info for.
1346 let slice = &src[begin..];
1347 match slice.find('\n') {
1348 Some(e) => &slice[..e],
1354 let line = self.lines.get(line_number)?;
1355 let begin: BytePos = *line - self.start_pos;
1359 if let Some(ref src) = self.src {
1360 Some(Cow::from(get_until_newline(src, begin)))
1361 } else if let Some(src) = self.external_src.borrow().get_source() {
1362 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1368 pub fn is_real_file(&self) -> bool {
1372 pub fn is_imported(&self) -> bool {
1376 pub fn byte_length(&self) -> u32 {
1377 self.end_pos.0 - self.start_pos.0
1379 pub fn count_lines(&self) -> usize {
1383 /// Finds the line containing the given position. The return value is the
1384 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1385 /// number. If the source_file is empty or the position is located before the
1386 /// first line, `None` is returned.
1387 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1388 if self.lines.is_empty() {
1392 let line_index = lookup_line(&self.lines[..], pos);
1393 assert!(line_index < self.lines.len() as isize);
1394 if line_index >= 0 { Some(line_index as usize) } else { None }
1397 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1398 if self.start_pos == self.end_pos {
1399 return (self.start_pos, self.end_pos);
1402 assert!(line_index < self.lines.len());
1403 if line_index == (self.lines.len() - 1) {
1404 (self.lines[line_index], self.end_pos)
1406 (self.lines[line_index], self.lines[line_index + 1])
1411 pub fn contains(&self, byte_pos: BytePos) -> bool {
1412 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1415 /// Calculates the original byte position relative to the start of the file
1416 /// based on the given byte position.
1417 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1418 // Diff before any records is 0. Otherwise use the previously recorded
1419 // diff as that applies to the following characters until a new diff
1421 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1422 Ok(i) => self.normalized_pos[i].diff,
1423 Err(i) if i == 0 => 0,
1424 Err(i) => self.normalized_pos[i - 1].diff,
1427 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1431 /// Normalizes the source code and records the normalizations.
1432 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1433 let mut normalized_pos = vec![];
1434 remove_bom(src, &mut normalized_pos);
1435 normalize_newlines(src, &mut normalized_pos);
1437 // Offset all the positions by start_pos to match the final file positions.
1438 for np in &mut normalized_pos {
1439 np.pos.0 += start_pos.0;
1445 /// Removes UTF-8 BOM, if any.
1446 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1447 if src.starts_with("\u{feff}") {
1449 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1453 /// Replaces `\r\n` with `\n` in-place in `src`.
1455 /// Returns error if there's a lone `\r` in the string
1456 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1457 if !src.as_bytes().contains(&b'\r') {
1461 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1462 // While we *can* call `as_mut_vec` and do surgery on the live string
1463 // directly, let's rather steal the contents of `src`. This makes the code
1464 // safe even if a panic occurs.
1466 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1467 let mut gap_len = 0;
1468 let mut tail = buf.as_mut_slice();
1470 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1472 let idx = match find_crlf(&tail[gap_len..]) {
1474 Some(idx) => idx + gap_len,
1476 tail.copy_within(gap_len..idx, 0);
1477 tail = &mut tail[idx - gap_len..];
1478 if tail.len() == gap_len {
1481 cursor += idx - gap_len;
1483 normalized_pos.push(NormalizedPos {
1484 pos: BytePos::from_usize(cursor + 1),
1485 diff: original_gap + gap_len as u32,
1489 // Account for removed `\r`.
1490 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1491 let new_len = buf.len() - gap_len;
1493 buf.set_len(new_len);
1494 *src = String::from_utf8_unchecked(buf);
1497 fn find_crlf(src: &[u8]) -> Option<usize> {
1498 let mut search_idx = 0;
1499 while let Some(idx) = find_cr(&src[search_idx..]) {
1500 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1501 search_idx += idx + 1;
1504 return Some(search_idx + idx);
1509 fn find_cr(src: &[u8]) -> Option<usize> {
1510 src.iter().position(|&b| b == b'\r')
1514 // _____________________________________________________________________________
1515 // Pos, BytePos, CharPos
1519 fn from_usize(n: usize) -> Self;
1520 fn to_usize(&self) -> usize;
1521 fn from_u32(n: u32) -> Self;
1522 fn to_u32(&self) -> u32;
1525 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1527 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1528 pub struct BytePos(pub u32);
1530 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1531 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1532 /// values to `CharPos` values as necessary.
1533 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1534 pub struct CharPos(pub usize);
1536 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1537 // have been unsuccessful.
1539 impl Pos for BytePos {
1541 fn from_usize(n: usize) -> BytePos {
1546 fn to_usize(&self) -> usize {
1551 fn from_u32(n: u32) -> BytePos {
1556 fn to_u32(&self) -> u32 {
1561 impl Add for BytePos {
1562 type Output = BytePos;
1565 fn add(self, rhs: BytePos) -> BytePos {
1566 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1570 impl Sub for BytePos {
1571 type Output = BytePos;
1574 fn sub(self, rhs: BytePos) -> BytePos {
1575 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1579 impl Encodable for BytePos {
1580 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1585 impl Decodable for BytePos {
1586 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1587 Ok(BytePos(d.read_u32()?))
1591 impl Pos for CharPos {
1593 fn from_usize(n: usize) -> CharPos {
1598 fn to_usize(&self) -> usize {
1603 fn from_u32(n: u32) -> CharPos {
1608 fn to_u32(&self) -> u32 {
1613 impl Add for CharPos {
1614 type Output = CharPos;
1617 fn add(self, rhs: CharPos) -> CharPos {
1618 CharPos(self.to_usize() + rhs.to_usize())
1622 impl Sub for CharPos {
1623 type Output = CharPos;
1626 fn sub(self, rhs: CharPos) -> CharPos {
1627 CharPos(self.to_usize() - rhs.to_usize())
1631 // _____________________________________________________________________________
1632 // Loc, SourceFileAndLine, SourceFileAndBytePos
1635 /// A source code location used for error reporting.
1636 #[derive(Debug, Clone)]
1638 /// Information about the original source.
1639 pub file: Lrc<SourceFile>,
1640 /// The (1-based) line number.
1642 /// The (0-based) column offset.
1644 /// The (0-based) column offset when displayed.
1645 pub col_display: usize,
1648 // Used to be structural records.
1650 pub struct SourceFileAndLine {
1651 pub sf: Lrc<SourceFile>,
1655 pub struct SourceFileAndBytePos {
1656 pub sf: Lrc<SourceFile>,
1660 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1661 pub struct LineInfo {
1662 /// Index of line, starting from 0.
1663 pub line_index: usize,
1665 /// Column in line where span begins, starting from 0.
1666 pub start_col: CharPos,
1668 /// Column in line where span ends, starting from 0, exclusive.
1669 pub end_col: CharPos,
1672 pub struct FileLines {
1673 pub file: Lrc<SourceFile>,
1674 pub lines: Vec<LineInfo>,
1677 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1678 AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1680 // _____________________________________________________________________________
1681 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1684 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1686 #[derive(Clone, PartialEq, Eq, Debug)]
1687 pub enum SpanLinesError {
1688 DistinctSources(DistinctSources),
1691 #[derive(Clone, PartialEq, Eq, Debug)]
1692 pub enum SpanSnippetError {
1693 IllFormedSpan(Span),
1694 DistinctSources(DistinctSources),
1695 MalformedForSourcemap(MalformedSourceMapPositions),
1696 SourceNotAvailable { filename: FileName },
1699 #[derive(Clone, PartialEq, Eq, Debug)]
1700 pub struct DistinctSources {
1701 pub begin: (FileName, BytePos),
1702 pub end: (FileName, BytePos),
1705 #[derive(Clone, PartialEq, Eq, Debug)]
1706 pub struct MalformedSourceMapPositions {
1708 pub source_len: usize,
1709 pub begin_pos: BytePos,
1710 pub end_pos: BytePos,
1713 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1714 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1715 pub struct InnerSpan {
1721 pub fn new(start: usize, end: usize) -> InnerSpan {
1722 InnerSpan { start, end }
1726 // Given a slice of line start positions and a position, returns the index of
1727 // the line the position is on. Returns -1 if the position is located before
1729 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1730 match lines.binary_search(&pos) {
1731 Ok(line) => line as isize,
1732 Err(line) => line as isize - 1,
1736 /// Requirements for a `StableHashingContext` to be used in this crate.
1737 /// This is a hack to allow using the `HashStable_Generic` derive macro
1738 /// instead of implementing everything in librustc_middle.
1739 pub trait HashStableContext {
1740 fn hash_def_id(&mut self, _: DefId, hasher: &mut StableHasher);
1741 fn hash_crate_num(&mut self, _: CrateNum, hasher: &mut StableHasher);
1742 fn hash_spans(&self) -> bool;
1743 fn byte_pos_to_line_and_col(
1746 ) -> Option<(Lrc<SourceFile>, usize, BytePos)>;
1749 impl<CTX> HashStable<CTX> for Span
1751 CTX: HashStableContext,
1753 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1754 /// fields (that would be similar to hashing pointers, since those are just
1755 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1756 /// triple, which stays the same even if the containing `SourceFile` has moved
1757 /// within the `SourceMap`.
1758 /// Also note that we are hashing byte offsets for the column, not unicode
1759 /// codepoint offsets. For the purpose of the hash that's sufficient.
1760 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1761 /// span starts and ends in the same file, which is almost always the case.
1762 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1763 const TAG_VALID_SPAN: u8 = 0;
1764 const TAG_INVALID_SPAN: u8 = 1;
1766 if !ctx.hash_spans() {
1770 if *self == DUMMY_SP {
1771 std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1775 // If this is not an empty or invalid span, we want to hash the last
1776 // position that belongs to it, as opposed to hashing the first
1777 // position past it.
1778 let span = self.data();
1779 let (file_lo, line_lo, col_lo) = match ctx.byte_pos_to_line_and_col(span.lo) {
1782 std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1783 span.ctxt.hash_stable(ctx, hasher);
1788 if !file_lo.contains(span.hi) {
1789 std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1790 span.ctxt.hash_stable(ctx, hasher);
1794 std::hash::Hash::hash(&TAG_VALID_SPAN, hasher);
1795 // We truncate the stable ID hash and line and column numbers. The chances
1796 // of causing a collision this way should be minimal.
1797 std::hash::Hash::hash(&(file_lo.name_hash as u64), hasher);
1799 let col = (col_lo.0 as u64) & 0xFF;
1800 let line = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1801 let len = ((span.hi - span.lo).0 as u64) << 32;
1802 let line_col_len = col | line | len;
1803 std::hash::Hash::hash(&line_col_len, hasher);
1804 span.ctxt.hash_stable(ctx, hasher);
1808 impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1809 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1810 const TAG_EXPANSION: u8 = 0;
1811 const TAG_NO_EXPANSION: u8 = 1;
1813 if *self == SyntaxContext::root() {
1814 TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1816 TAG_EXPANSION.hash_stable(ctx, hasher);
1818 // Since the same expansion context is usually referenced many
1819 // times, we cache a stable hash of it and hash that instead of
1820 // recursing every time.
1822 static CACHE: RefCell<Vec<Option<[Option<u64>; NUM_TRANSPARENCIES]>>> = Default::default();
1825 let sub_hash: u64 = CACHE.with(|cache| {
1826 let (expn_id, transparency, _) = self.outer_mark_with_data();
1827 let index = expn_id.as_u32() as usize;
1829 if let Some(sub_hash_cache) = cache.borrow().get(index).copied().flatten() {
1830 if let Some(sub_hash) = sub_hash_cache[transparency as usize] {
1835 let new_len = index + 1;
1837 let mut hasher = StableHasher::new();
1838 expn_id.expn_data().hash_stable(ctx, &mut hasher);
1839 transparency.hash_stable(ctx, &mut hasher);
1841 let sub_hash: Fingerprint = hasher.finish();
1842 let sub_hash = sub_hash.to_smaller_hash();
1844 let mut cache = cache.borrow_mut();
1845 if cache.len() < new_len {
1846 cache.resize(new_len, None);
1848 if let Some(mut sub_hash_cache) = cache[index] {
1849 sub_hash_cache[transparency as usize] = Some(sub_hash);
1851 let mut sub_hash_cache = [None; NUM_TRANSPARENCIES];
1852 sub_hash_cache[transparency as usize] = Some(sub_hash);
1853 cache[index] = Some(sub_hash_cache);
1858 sub_hash.hash_stable(ctx, hasher);