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)]
19 extern crate rustc_macros;
21 use rustc_data_structures::AtomicRef;
22 use rustc_macros::HashStable_Generic;
23 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
25 mod caching_source_map_view;
27 pub use self::caching_source_map_view::CachingSourceMapView;
28 use source_map::SourceMap;
33 pub use hygiene::SyntaxContext;
34 use hygiene::Transparency;
35 pub use hygiene::{DesugaringKind, ExpnData, ExpnId, ExpnKind, ForLoopLoc, MacroKind};
37 use def_id::{CrateNum, DefId, LOCAL_CRATE};
39 pub use span_encoding::{Span, DUMMY_SP};
42 pub use symbol::{sym, Symbol};
44 mod analyze_source_file;
47 use rustc_data_structures::fingerprint::Fingerprint;
48 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
49 use rustc_data_structures::sync::{Lock, Lrc};
52 use std::cell::RefCell;
53 use std::cmp::{self, Ordering};
56 use std::ops::{Add, Sub};
57 use std::path::{Path, PathBuf};
58 use std::str::FromStr;
67 // Per-session global variables: this struct is stored in thread-local storage
68 // in such a way that it is accessible without any kind of handle to all
69 // threads within the compilation session, but is not accessible outside the
71 pub struct SessionGlobals {
72 symbol_interner: Lock<symbol::Interner>,
73 span_interner: Lock<span_encoding::SpanInterner>,
74 hygiene_data: Lock<hygiene::HygieneData>,
75 source_map: Lock<Option<Lrc<SourceMap>>>,
79 pub fn new(edition: Edition) -> SessionGlobals {
81 symbol_interner: Lock::new(symbol::Interner::fresh()),
82 span_interner: Lock::new(span_encoding::SpanInterner::default()),
83 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
84 source_map: Lock::new(None),
89 pub fn with_session_globals<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
90 let session_globals = SessionGlobals::new(edition);
91 SESSION_GLOBALS.set(&session_globals, f)
94 pub fn with_default_session_globals<R>(f: impl FnOnce() -> R) -> R {
95 with_session_globals(edition::DEFAULT_EDITION, f)
98 // If this ever becomes non thread-local, `decode_syntax_context`
99 // and `decode_expn_id` will need to be updated to handle concurrent
101 scoped_tls::scoped_thread_local!(pub static SESSION_GLOBALS: SessionGlobals);
103 // FIXME: Perhaps this should not implement Rustc{Decodable, Encodable}
105 // FIXME: We should use this enum or something like it to get rid of the
106 // use of magic `/rust/1.x/...` paths across the board.
107 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
108 #[derive(HashStable_Generic, Decodable, Encodable)]
109 pub enum RealFileName {
111 /// For de-virtualized paths (namely paths into libstd that have been mapped
112 /// to the appropriate spot on the local host's file system),
114 /// `local_path` is the (host-dependent) local path to the file.
116 /// `virtual_name` is the stable path rustc will store internally within
118 virtual_name: PathBuf,
123 /// Returns the path suitable for reading from the file system on the local host.
124 /// Avoid embedding this in build artifacts; see `stable_name` for that.
125 pub fn local_path(&self) -> &Path {
127 RealFileName::Named(p)
128 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => &p,
132 /// Returns the path suitable for reading from the file system on the local host.
133 /// Avoid embedding this in build artifacts; see `stable_name` for that.
134 pub fn into_local_path(self) -> PathBuf {
136 RealFileName::Named(p)
137 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => p,
141 /// Returns the path suitable for embedding into build artifacts. Note that
142 /// a virtualized path will not correspond to a valid file system path; see
143 /// `local_path` for something that is more likely to return paths into the
144 /// local host file system.
145 pub fn stable_name(&self) -> &Path {
147 RealFileName::Named(p)
148 | RealFileName::Devirtualized { local_path: _, virtual_name: p } => &p,
153 /// Differentiates between real files and common virtual files.
154 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
155 #[derive(HashStable_Generic, Decodable, Encodable)]
158 /// Call to `quote!`.
162 /// Hack in `src/librustc_ast/parse.rs`.
165 ProcMacroSourceCode(u64),
166 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
168 /// Strings provided as crate attributes in the CLI.
170 /// Custom sources for explicit parser calls from plugins and drivers.
172 DocTest(PathBuf, isize),
173 /// Post-substitution inline assembly from LLVM
177 impl std::fmt::Display for FileName {
178 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181 Real(RealFileName::Named(ref path)) => write!(fmt, "{}", path.display()),
182 // FIXME: might be nice to display both compoments of Devirtualized.
183 // But for now (to backport fix for issue #70924), best to not
184 // perturb diagnostics so its obvious test suite still works.
185 Real(RealFileName::Devirtualized { ref local_path, virtual_name: _ }) => {
186 write!(fmt, "{}", local_path.display())
188 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
189 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
190 Anon(_) => write!(fmt, "<anon>"),
191 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
192 CfgSpec(_) => write!(fmt, "<cfgspec>"),
193 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
194 Custom(ref s) => write!(fmt, "<{}>", s),
195 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
196 InlineAsm(_) => write!(fmt, "<inline asm>"),
201 impl From<PathBuf> for FileName {
202 fn from(p: PathBuf) -> Self {
203 assert!(!p.to_string_lossy().ends_with('>'));
204 FileName::Real(RealFileName::Named(p))
209 pub fn is_real(&self) -> bool {
215 | ProcMacroSourceCode(_)
221 | InlineAsm(_) => false,
225 pub fn quote_expansion_source_code(src: &str) -> FileName {
226 let mut hasher = StableHasher::new();
227 src.hash(&mut hasher);
228 FileName::QuoteExpansion(hasher.finish())
231 pub fn macro_expansion_source_code(src: &str) -> FileName {
232 let mut hasher = StableHasher::new();
233 src.hash(&mut hasher);
234 FileName::MacroExpansion(hasher.finish())
237 pub fn anon_source_code(src: &str) -> FileName {
238 let mut hasher = StableHasher::new();
239 src.hash(&mut hasher);
240 FileName::Anon(hasher.finish())
243 pub fn proc_macro_source_code(src: &str) -> FileName {
244 let mut hasher = StableHasher::new();
245 src.hash(&mut hasher);
246 FileName::ProcMacroSourceCode(hasher.finish())
249 pub fn cfg_spec_source_code(src: &str) -> FileName {
250 let mut hasher = StableHasher::new();
251 src.hash(&mut hasher);
252 FileName::QuoteExpansion(hasher.finish())
255 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
256 let mut hasher = StableHasher::new();
257 src.hash(&mut hasher);
258 FileName::CliCrateAttr(hasher.finish())
261 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
262 FileName::DocTest(path, line)
265 pub fn inline_asm_source_code(src: &str) -> FileName {
266 let mut hasher = StableHasher::new();
267 src.hash(&mut hasher);
268 FileName::InlineAsm(hasher.finish())
272 /// Spans represent a region of code, used for error reporting. Positions in spans
273 /// are *absolute* positions from the beginning of the source_map, not positions
274 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
275 /// to the original source.
276 /// You must be careful if the span crosses more than one file - you will not be
277 /// able to use many of the functions on spans in source_map and you cannot assume
278 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
279 /// range between files.
281 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
282 /// sent to other threads, but some pieces of performance infra run in a separate thread.
283 /// Using `Span` is generally preferred.
284 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
285 pub struct SpanData {
288 /// Information about where the macro came from, if this piece of
289 /// code was created by a macro expansion.
290 pub ctxt: SyntaxContext,
295 pub fn with_lo(&self, lo: BytePos) -> Span {
296 Span::new(lo, self.hi, self.ctxt)
299 pub fn with_hi(&self, hi: BytePos) -> Span {
300 Span::new(self.lo, hi, self.ctxt)
303 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
304 Span::new(self.lo, self.hi, ctxt)
308 // The interner is pointed to by a thread local value which is only set on the main thread
309 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
310 // to avoid panics and other errors, even though it would be memory safe to do so.
311 #[cfg(not(parallel_compiler))]
312 impl !Send for Span {}
313 #[cfg(not(parallel_compiler))]
314 impl !Sync for Span {}
316 impl PartialOrd for Span {
317 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
318 PartialOrd::partial_cmp(&self.data(), &rhs.data())
322 fn cmp(&self, rhs: &Self) -> Ordering {
323 Ord::cmp(&self.data(), &rhs.data())
327 /// A collection of `Span`s.
329 /// Spans have two orthogonal attributes:
331 /// - They can be *primary spans*. In this case they are the locus of
332 /// the error, and would be rendered with `^^^`.
333 /// - They can have a *label*. In this case, the label is written next
334 /// to the mark in the snippet when we render.
335 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
336 pub struct MultiSpan {
337 primary_spans: Vec<Span>,
338 span_labels: Vec<(Span, String)>,
343 pub fn lo(self) -> BytePos {
347 pub fn with_lo(self, lo: BytePos) -> Span {
348 self.data().with_lo(lo)
351 pub fn hi(self) -> BytePos {
355 pub fn with_hi(self, hi: BytePos) -> Span {
356 self.data().with_hi(hi)
359 pub fn ctxt(self) -> SyntaxContext {
363 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
364 self.data().with_ctxt(ctxt)
367 /// Returns `true` if this is a dummy span with any hygienic context.
369 pub fn is_dummy(self) -> bool {
370 let span = self.data();
371 span.lo.0 == 0 && span.hi.0 == 0
374 /// Returns `true` if this span comes from a macro or desugaring.
376 pub fn from_expansion(self) -> bool {
377 self.ctxt() != SyntaxContext::root()
380 /// Returns `true` if `span` originates in a derive-macro's expansion.
381 pub fn in_derive_expansion(self) -> bool {
382 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
386 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
387 Span::new(lo, hi, SyntaxContext::root())
390 /// Returns a new span representing an empty span at the beginning of this span
392 pub fn shrink_to_lo(self) -> Span {
393 let span = self.data();
394 span.with_hi(span.lo)
396 /// Returns a new span representing an empty span at the end of this span.
398 pub fn shrink_to_hi(self) -> Span {
399 let span = self.data();
400 span.with_lo(span.hi)
403 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
404 pub fn substitute_dummy(self, other: Span) -> Span {
405 if self.is_dummy() { other } else { self }
408 /// Returns `true` if `self` fully encloses `other`.
409 pub fn contains(self, other: Span) -> bool {
410 let span = self.data();
411 let other = other.data();
412 span.lo <= other.lo && other.hi <= span.hi
415 /// Returns `true` if `self` touches `other`.
416 pub fn overlaps(self, other: Span) -> bool {
417 let span = self.data();
418 let other = other.data();
419 span.lo < other.hi && other.lo < span.hi
422 /// Returns `true` if the spans are equal with regards to the source text.
424 /// Use this instead of `==` when either span could be generated code,
425 /// and you only care that they point to the same bytes of source text.
426 pub fn source_equal(&self, other: &Span) -> bool {
427 let span = self.data();
428 let other = other.data();
429 span.lo == other.lo && span.hi == other.hi
432 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
433 pub fn trim_start(self, other: Span) -> Option<Span> {
434 let span = self.data();
435 let other = other.data();
436 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
439 /// Returns the source span -- this is either the supplied span, or the span for
440 /// the macro callsite that expanded to it.
441 pub fn source_callsite(self) -> Span {
442 let expn_data = self.ctxt().outer_expn_data();
443 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
446 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
448 pub fn parent(self) -> Option<Span> {
449 let expn_data = self.ctxt().outer_expn_data();
450 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
453 /// Edition of the crate from which this span came.
454 pub fn edition(self) -> edition::Edition {
455 self.ctxt().outer_expn_data().edition
459 pub fn rust_2015(&self) -> bool {
460 self.edition() == edition::Edition::Edition2015
464 pub fn rust_2018(&self) -> bool {
465 self.edition() >= edition::Edition::Edition2018
468 /// Returns the source callee.
470 /// Returns `None` if the supplied span has no expansion trace,
471 /// else returns the `ExpnData` for the macro definition
472 /// corresponding to the source callsite.
473 pub fn source_callee(self) -> Option<ExpnData> {
474 fn source_callee(expn_data: ExpnData) -> ExpnData {
475 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
476 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
478 let expn_data = self.ctxt().outer_expn_data();
479 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
482 /// Checks if a span is "internal" to a macro in which `#[unstable]`
483 /// items can be used (that is, a macro marked with
484 /// `#[allow_internal_unstable]`).
485 pub fn allows_unstable(&self, feature: Symbol) -> bool {
486 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
489 .any(|&f| f == feature || f == sym::allow_internal_unstable_backcompat_hack)
493 /// Checks if this span arises from a compiler desugaring of kind `kind`.
494 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
495 match self.ctxt().outer_expn_data().kind {
496 ExpnKind::Desugaring(k) => k == kind,
501 /// Returns the compiler desugaring that created this span, or `None`
502 /// if this span is not from a desugaring.
503 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
504 match self.ctxt().outer_expn_data().kind {
505 ExpnKind::Desugaring(k) => Some(k),
510 /// Checks if a span is "internal" to a macro in which `unsafe`
511 /// can be used without triggering the `unsafe_code` lint
512 // (that is, a macro marked with `#[allow_internal_unsafe]`).
513 pub fn allows_unsafe(&self) -> bool {
514 self.ctxt().outer_expn_data().allow_internal_unsafe
517 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
518 let mut prev_span = DUMMY_SP;
519 std::iter::from_fn(move || {
521 let expn_data = self.ctxt().outer_expn_data();
522 if expn_data.is_root() {
526 let is_recursive = expn_data.call_site.source_equal(&prev_span);
529 self = expn_data.call_site;
531 // Don't print recursive invocations.
533 return Some(expn_data);
539 /// Returns a `Span` that would enclose both `self` and `end`.
540 pub fn to(self, end: Span) -> Span {
541 let span_data = self.data();
542 let end_data = end.data();
543 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
544 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
545 // have an incomplete span than a completely nonsensical one.
546 if span_data.ctxt != end_data.ctxt {
547 if span_data.ctxt == SyntaxContext::root() {
549 } else if end_data.ctxt == SyntaxContext::root() {
552 // Both spans fall within a macro.
553 // FIXME(estebank): check if it is the *same* macro.
556 cmp::min(span_data.lo, end_data.lo),
557 cmp::max(span_data.hi, end_data.hi),
558 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
562 /// Returns a `Span` between the end of `self` to the beginning of `end`.
563 pub fn between(self, end: Span) -> Span {
564 let span = self.data();
565 let end = end.data();
569 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
573 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
574 pub fn until(self, end: Span) -> Span {
575 let span = self.data();
576 let end = end.data();
580 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
584 pub fn from_inner(self, inner: InnerSpan) -> Span {
585 let span = self.data();
587 span.lo + BytePos::from_usize(inner.start),
588 span.lo + BytePos::from_usize(inner.end),
593 /// Equivalent of `Span::def_site` from the proc macro API,
594 /// except that the location is taken from the `self` span.
595 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
596 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
599 /// Equivalent of `Span::call_site` from the proc macro API,
600 /// except that the location is taken from the `self` span.
601 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
602 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
605 /// Equivalent of `Span::mixed_site` from the proc macro API,
606 /// except that the location is taken from the `self` span.
607 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
608 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
611 /// Produces a span with the same location as `self` and context produced by a macro with the
612 /// given ID and transparency, assuming that macro was defined directly and not produced by
613 /// some other macro (which is the case for built-in and procedural macros).
614 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
615 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
619 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
620 let span = self.data();
621 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
625 pub fn remove_mark(&mut self) -> ExpnId {
626 let mut span = self.data();
627 let mark = span.ctxt.remove_mark();
628 *self = Span::new(span.lo, span.hi, span.ctxt);
633 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
634 let mut span = self.data();
635 let mark = span.ctxt.adjust(expn_id);
636 *self = Span::new(span.lo, span.hi, span.ctxt);
641 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
642 let mut span = self.data();
643 let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
644 *self = Span::new(span.lo, span.hi, span.ctxt);
649 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
650 let mut span = self.data();
651 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
652 *self = Span::new(span.lo, span.hi, span.ctxt);
657 pub fn reverse_glob_adjust(
661 ) -> Option<Option<ExpnId>> {
662 let mut span = self.data();
663 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
664 *self = Span::new(span.lo, span.hi, span.ctxt);
669 pub fn normalize_to_macros_2_0(self) -> Span {
670 let span = self.data();
671 span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
675 pub fn normalize_to_macro_rules(self) -> Span {
676 let span = self.data();
677 span.with_ctxt(span.ctxt.normalize_to_macro_rules())
681 #[derive(Clone, Debug)]
682 pub struct SpanLabel {
683 /// The span we are going to include in the final snippet.
686 /// Is this a primary span? This is the "locus" of the message,
687 /// and is indicated with a `^^^^` underline, versus `----`.
688 pub is_primary: bool,
690 /// What label should we attach to this span (if any)?
691 pub label: Option<String>,
694 impl Default for Span {
695 fn default() -> Self {
700 impl<E: Encoder> Encodable<E> for Span {
701 default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
702 let span = self.data();
703 s.emit_struct("Span", 2, |s| {
704 s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?;
705 s.emit_struct_field("hi", 1, |s| span.hi.encode(s))
709 impl<D: Decoder> Decodable<D> for Span {
710 default fn decode(s: &mut D) -> Result<Span, D::Error> {
711 s.read_struct("Span", 2, |d| {
712 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
713 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
715 Ok(Span::new(lo, hi, SyntaxContext::root()))
720 /// Calls the provided closure, using the provided `SourceMap` to format
721 /// any spans that are debug-printed during the closure'e exectuino.
723 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
724 /// (see `rustc_interface::callbacks::span_debug1). However, some parts
725 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
726 /// a `TyCtxt` is available. In this case, we fall back to
727 /// the `SourceMap` provided to this function. If that is not available,
728 /// we fall back to printing the raw `Span` field values
729 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
730 SESSION_GLOBALS.with(|session_globals| {
731 *session_globals.source_map.borrow_mut() = Some(source_map);
733 struct ClearSourceMap;
734 impl Drop for ClearSourceMap {
736 SESSION_GLOBALS.with(|session_globals| {
737 session_globals.source_map.borrow_mut().take();
742 let _guard = ClearSourceMap;
746 pub fn debug_with_source_map(
748 f: &mut fmt::Formatter<'_>,
749 source_map: &SourceMap,
751 write!(f, "{} ({:?})", source_map.span_to_string(span), span.ctxt())
754 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
755 SESSION_GLOBALS.with(|session_globals| {
756 if let Some(source_map) = &*session_globals.source_map.borrow() {
757 debug_with_source_map(span, f, source_map)
759 f.debug_struct("Span")
760 .field("lo", &span.lo())
761 .field("hi", &span.hi())
762 .field("ctxt", &span.ctxt())
768 impl fmt::Debug for Span {
769 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
770 (*SPAN_DEBUG)(*self, f)
774 impl fmt::Debug for SpanData {
775 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
776 (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
782 pub fn new() -> MultiSpan {
783 MultiSpan { primary_spans: vec![], span_labels: vec![] }
786 pub fn from_span(primary_span: Span) -> MultiSpan {
787 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
790 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
792 MultiSpan { primary_spans: vec, span_labels: vec![] }
795 pub fn push_span_label(&mut self, span: Span, label: String) {
796 self.span_labels.push((span, label));
799 /// Selects the first primary span (if any).
800 pub fn primary_span(&self) -> Option<Span> {
801 self.primary_spans.first().cloned()
804 /// Returns all primary spans.
805 pub fn primary_spans(&self) -> &[Span] {
809 /// Returns `true` if any of the primary spans are displayable.
810 pub fn has_primary_spans(&self) -> bool {
811 self.primary_spans.iter().any(|sp| !sp.is_dummy())
814 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
815 pub fn is_dummy(&self) -> bool {
816 let mut is_dummy = true;
817 for span in &self.primary_spans {
818 if !span.is_dummy() {
825 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
826 /// display well (like std macros). Returns whether replacements occurred.
827 pub fn replace(&mut self, before: Span, after: Span) -> bool {
828 let mut replacements_occurred = false;
829 for primary_span in &mut self.primary_spans {
830 if *primary_span == before {
831 *primary_span = after;
832 replacements_occurred = true;
835 for span_label in &mut self.span_labels {
836 if span_label.0 == before {
837 span_label.0 = after;
838 replacements_occurred = true;
841 replacements_occurred
844 /// Returns the strings to highlight. We always ensure that there
845 /// is an entry for each of the primary spans -- for each primary
846 /// span `P`, if there is at least one label with span `P`, we return
847 /// those labels (marked as primary). But otherwise we return
848 /// `SpanLabel` instances with empty labels.
849 pub fn span_labels(&self) -> Vec<SpanLabel> {
850 let is_primary = |span| self.primary_spans.contains(&span);
852 let mut span_labels = self
855 .map(|&(span, ref label)| SpanLabel {
857 is_primary: is_primary(span),
858 label: Some(label.clone()),
860 .collect::<Vec<_>>();
862 for &span in &self.primary_spans {
863 if !span_labels.iter().any(|sl| sl.span == span) {
864 span_labels.push(SpanLabel { span, is_primary: true, label: None });
871 /// Returns `true` if any of the span labels is displayable.
872 pub fn has_span_labels(&self) -> bool {
873 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
877 impl From<Span> for MultiSpan {
878 fn from(span: Span) -> MultiSpan {
879 MultiSpan::from_span(span)
883 impl From<Vec<Span>> for MultiSpan {
884 fn from(spans: Vec<Span>) -> MultiSpan {
885 MultiSpan::from_spans(spans)
889 /// Identifies an offset of a multi-byte character in a `SourceFile`.
890 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
891 pub struct MultiByteChar {
892 /// The absolute offset of the character in the `SourceMap`.
894 /// The number of bytes, `>= 2`.
898 /// Identifies an offset of a non-narrow character in a `SourceFile`.
899 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
900 pub enum NonNarrowChar {
901 /// Represents a zero-width character.
903 /// Represents a wide (full-width) character.
905 /// Represents a tab character, represented visually with a width of 4 characters.
910 fn new(pos: BytePos, width: usize) -> Self {
912 0 => NonNarrowChar::ZeroWidth(pos),
913 2 => NonNarrowChar::Wide(pos),
914 4 => NonNarrowChar::Tab(pos),
915 _ => panic!("width {} given for non-narrow character", width),
919 /// Returns the absolute offset of the character in the `SourceMap`.
920 pub fn pos(&self) -> BytePos {
922 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
926 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
927 pub fn width(&self) -> usize {
929 NonNarrowChar::ZeroWidth(_) => 0,
930 NonNarrowChar::Wide(_) => 2,
931 NonNarrowChar::Tab(_) => 4,
936 impl Add<BytePos> for NonNarrowChar {
939 fn add(self, rhs: BytePos) -> Self {
941 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
942 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
943 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
948 impl Sub<BytePos> for NonNarrowChar {
951 fn sub(self, rhs: BytePos) -> Self {
953 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
954 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
955 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
960 /// Identifies an offset of a character that was normalized away from `SourceFile`.
961 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
962 pub struct NormalizedPos {
963 /// The absolute offset of the character in the `SourceMap`.
965 /// The difference between original and normalized string at position.
969 #[derive(PartialEq, Eq, Clone, Debug)]
970 pub enum ExternalSource {
971 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
974 kind: ExternalSourceKind,
975 /// This SourceFile's byte-offset within the source_map of its original crate
976 original_start_pos: BytePos,
977 /// The end of this SourceFile within the source_map of its original crate
978 original_end_pos: BytePos,
982 /// The state of the lazy external source loading mechanism of a `SourceFile`.
983 #[derive(PartialEq, Eq, Clone, Debug)]
984 pub enum ExternalSourceKind {
985 /// The external source has been loaded already.
986 Present(Lrc<String>),
987 /// No attempt has been made to load the external source.
989 /// A failed attempt has been made to load the external source.
994 impl ExternalSource {
995 pub fn is_absent(&self) -> bool {
997 ExternalSource::Foreign { kind: ExternalSourceKind::Present(_), .. } => false,
1002 pub fn get_source(&self) -> Option<&Lrc<String>> {
1004 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1011 pub struct OffsetOverflowError;
1013 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1014 pub enum SourceFileHashAlgorithm {
1019 impl FromStr for SourceFileHashAlgorithm {
1022 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1024 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1025 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1031 rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm);
1033 /// The hash of the on-disk source file used for debug info.
1034 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1035 #[derive(HashStable_Generic, Encodable, Decodable)]
1036 pub struct SourceFileHash {
1037 pub kind: SourceFileHashAlgorithm,
1041 impl SourceFileHash {
1042 pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1043 let mut hash = SourceFileHash { kind, value: Default::default() };
1044 let len = hash.hash_len();
1045 let value = &mut hash.value[..len];
1046 let data = src.as_bytes();
1048 SourceFileHashAlgorithm::Md5 => {
1049 value.copy_from_slice(&Md5::digest(data));
1051 SourceFileHashAlgorithm::Sha1 => {
1052 value.copy_from_slice(&Sha1::digest(data));
1058 /// Check if the stored hash matches the hash of the string.
1059 pub fn matches(&self, src: &str) -> bool {
1060 Self::new(self.kind, src) == *self
1063 /// The bytes of the hash.
1064 pub fn hash_bytes(&self) -> &[u8] {
1065 let len = self.hash_len();
1069 fn hash_len(&self) -> usize {
1071 SourceFileHashAlgorithm::Md5 => 16,
1072 SourceFileHashAlgorithm::Sha1 => 20,
1077 /// A single source in the `SourceMap`.
1079 pub struct SourceFile {
1080 /// The name of the file that the source came from. Source that doesn't
1081 /// originate from files has names between angle brackets by convention
1082 /// (e.g., `<anon>`).
1084 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
1085 pub name_was_remapped: bool,
1086 /// The unmapped path of the file that the source came from.
1087 /// Set to `None` if the `SourceFile` was imported from an external crate.
1088 pub unmapped_path: Option<FileName>,
1089 /// The complete source code.
1090 pub src: Option<Lrc<String>>,
1091 /// The source code's hash.
1092 pub src_hash: SourceFileHash,
1093 /// The external source code (used for external crates, which will have a `None`
1094 /// value as `self.src`.
1095 pub external_src: Lock<ExternalSource>,
1096 /// The start position of this source in the `SourceMap`.
1097 pub start_pos: BytePos,
1098 /// The end position of this source in the `SourceMap`.
1099 pub end_pos: BytePos,
1100 /// Locations of lines beginnings in the source code.
1101 pub lines: Vec<BytePos>,
1102 /// Locations of multi-byte characters in the source code.
1103 pub multibyte_chars: Vec<MultiByteChar>,
1104 /// Width of characters that are not narrow in the source code.
1105 pub non_narrow_chars: Vec<NonNarrowChar>,
1106 /// Locations of characters removed during normalization.
1107 pub normalized_pos: Vec<NormalizedPos>,
1108 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1109 pub name_hash: u128,
1110 /// Indicates which crate this `SourceFile` was imported from.
1114 impl<S: Encoder> Encodable<S> for SourceFile {
1115 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1116 s.emit_struct("SourceFile", 8, |s| {
1117 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
1118 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
1119 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
1120 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
1121 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
1122 s.emit_struct_field("lines", 5, |s| {
1123 let lines = &self.lines[..];
1124 // Store the length.
1125 s.emit_u32(lines.len() as u32)?;
1127 if !lines.is_empty() {
1128 // In order to preserve some space, we exploit the fact that
1129 // the lines list is sorted and individual lines are
1130 // probably not that long. Because of that we can store lines
1131 // as a difference list, using as little space as possible
1132 // for the differences.
1133 let max_line_length = if lines.len() == 1 {
1136 lines.windows(2).map(|w| w[1] - w[0]).map(|bp| bp.to_usize()).max().unwrap()
1139 let bytes_per_diff: u8 = match max_line_length {
1141 0x100..=0xFFFF => 2,
1145 // Encode the number of bytes used per diff.
1146 bytes_per_diff.encode(s)?;
1148 // Encode the first element.
1149 lines[0].encode(s)?;
1151 let diff_iter = (&lines[..]).windows(2).map(|w| (w[1] - w[0]));
1153 match bytes_per_diff {
1155 for diff in diff_iter {
1156 (diff.0 as u8).encode(s)?
1160 for diff in diff_iter {
1161 (diff.0 as u16).encode(s)?
1165 for diff in diff_iter {
1169 _ => unreachable!(),
1175 s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
1176 s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
1177 s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
1178 s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))?;
1179 s.emit_struct_field("cnum", 10, |s| self.cnum.encode(s))
1184 impl<D: Decoder> Decodable<D> for SourceFile {
1185 fn decode(d: &mut D) -> Result<SourceFile, D::Error> {
1186 d.read_struct("SourceFile", 8, |d| {
1187 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1188 let name_was_remapped: bool =
1189 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1190 let src_hash: SourceFileHash =
1191 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1192 let start_pos: BytePos =
1193 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1194 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1195 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1196 let num_lines: u32 = Decodable::decode(d)?;
1197 let mut lines = Vec::with_capacity(num_lines as usize);
1200 // Read the number of bytes used per diff.
1201 let bytes_per_diff: u8 = Decodable::decode(d)?;
1203 // Read the first element.
1204 let mut line_start: BytePos = Decodable::decode(d)?;
1205 lines.push(line_start);
1207 for _ in 1..num_lines {
1208 let diff = match bytes_per_diff {
1209 1 => d.read_u8()? as u32,
1210 2 => d.read_u16()? as u32,
1212 _ => unreachable!(),
1215 line_start = line_start + BytePos(diff);
1217 lines.push(line_start);
1223 let multibyte_chars: Vec<MultiByteChar> =
1224 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1225 let non_narrow_chars: Vec<NonNarrowChar> =
1226 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1227 let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1228 let normalized_pos: Vec<NormalizedPos> =
1229 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1230 let cnum: CrateNum = d.read_struct_field("cnum", 10, |d| Decodable::decode(d))?;
1234 unmapped_path: None,
1239 // Unused - the metadata decoder will construct
1240 // a new SourceFile, filling in `external_src` properly
1241 external_src: Lock::new(ExternalSource::Unneeded),
1253 impl fmt::Debug for SourceFile {
1254 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1255 write!(fmt, "SourceFile({})", self.name)
1262 name_was_remapped: bool,
1263 unmapped_path: FileName,
1266 hash_kind: SourceFileHashAlgorithm,
1268 // Compute the file hash before any normalization.
1269 let src_hash = SourceFileHash::new(hash_kind, &src);
1270 let normalized_pos = normalize_src(&mut src, start_pos);
1273 let mut hasher: StableHasher = StableHasher::new();
1274 name.hash(&mut hasher);
1275 hasher.finish::<u128>()
1277 let end_pos = start_pos.to_usize() + src.len();
1278 assert!(end_pos <= u32::MAX as usize);
1280 let (lines, multibyte_chars, non_narrow_chars) =
1281 analyze_source_file::analyze_source_file(&src[..], start_pos);
1286 unmapped_path: Some(unmapped_path),
1287 src: Some(Lrc::new(src)),
1289 external_src: Lock::new(ExternalSource::Unneeded),
1291 end_pos: Pos::from_usize(end_pos),
1301 /// Returns the `BytePos` of the beginning of the current line.
1302 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1303 let line_index = self.lookup_line(pos).unwrap();
1304 self.lines[line_index]
1307 /// Add externally loaded source.
1308 /// If the hash of the input doesn't match or no input is supplied via None,
1309 /// it is interpreted as an error and the corresponding enum variant is set.
1310 /// The return value signifies whether some kind of source is present.
1311 pub fn add_external_src<F>(&self, get_src: F) -> bool
1313 F: FnOnce() -> Option<String>,
1316 *self.external_src.borrow(),
1317 ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1319 let src = get_src();
1320 let mut external_src = self.external_src.borrow_mut();
1321 // Check that no-one else have provided the source while we were getting it
1322 if let ExternalSource::Foreign {
1323 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1324 } = &mut *external_src
1326 if let Some(mut src) = src {
1327 // The src_hash needs to be computed on the pre-normalized src.
1328 if self.src_hash.matches(&src) {
1329 normalize_src(&mut src, BytePos::from_usize(0));
1330 *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1334 *src_kind = ExternalSourceKind::AbsentErr;
1339 self.src.is_some() || external_src.get_source().is_some()
1342 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1346 /// Gets a line from the list of pre-computed line-beginnings.
1347 /// The line number here is 0-based.
1348 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1349 fn get_until_newline(src: &str, begin: usize) -> &str {
1350 // We can't use `lines.get(line_number+1)` because we might
1351 // be parsing when we call this function and thus the current
1352 // line is the last one we have line info for.
1353 let slice = &src[begin..];
1354 match slice.find('\n') {
1355 Some(e) => &slice[..e],
1361 let line = self.lines.get(line_number)?;
1362 let begin: BytePos = *line - self.start_pos;
1366 if let Some(ref src) = self.src {
1367 Some(Cow::from(get_until_newline(src, begin)))
1368 } else if let Some(src) = self.external_src.borrow().get_source() {
1369 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1375 pub fn is_real_file(&self) -> bool {
1379 pub fn is_imported(&self) -> bool {
1383 pub fn byte_length(&self) -> u32 {
1384 self.end_pos.0 - self.start_pos.0
1386 pub fn count_lines(&self) -> usize {
1390 /// Finds the line containing the given position. The return value is the
1391 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1392 /// number. If the source_file is empty or the position is located before the
1393 /// first line, `None` is returned.
1394 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1395 if self.lines.is_empty() {
1399 let line_index = lookup_line(&self.lines[..], pos);
1400 assert!(line_index < self.lines.len() as isize);
1401 if line_index >= 0 { Some(line_index as usize) } else { None }
1404 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1405 if self.start_pos == self.end_pos {
1406 return (self.start_pos, self.end_pos);
1409 assert!(line_index < self.lines.len());
1410 if line_index == (self.lines.len() - 1) {
1411 (self.lines[line_index], self.end_pos)
1413 (self.lines[line_index], self.lines[line_index + 1])
1418 pub fn contains(&self, byte_pos: BytePos) -> bool {
1419 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1422 /// Calculates the original byte position relative to the start of the file
1423 /// based on the given byte position.
1424 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1425 // Diff before any records is 0. Otherwise use the previously recorded
1426 // diff as that applies to the following characters until a new diff
1428 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1429 Ok(i) => self.normalized_pos[i].diff,
1430 Err(i) if i == 0 => 0,
1431 Err(i) => self.normalized_pos[i - 1].diff,
1434 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1438 /// Normalizes the source code and records the normalizations.
1439 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1440 let mut normalized_pos = vec![];
1441 remove_bom(src, &mut normalized_pos);
1442 normalize_newlines(src, &mut normalized_pos);
1444 // Offset all the positions by start_pos to match the final file positions.
1445 for np in &mut normalized_pos {
1446 np.pos.0 += start_pos.0;
1452 /// Removes UTF-8 BOM, if any.
1453 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1454 if src.starts_with("\u{feff}") {
1456 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1460 /// Replaces `\r\n` with `\n` in-place in `src`.
1462 /// Returns error if there's a lone `\r` in the string
1463 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1464 if !src.as_bytes().contains(&b'\r') {
1468 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1469 // While we *can* call `as_mut_vec` and do surgery on the live string
1470 // directly, let's rather steal the contents of `src`. This makes the code
1471 // safe even if a panic occurs.
1473 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1474 let mut gap_len = 0;
1475 let mut tail = buf.as_mut_slice();
1477 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1479 let idx = match find_crlf(&tail[gap_len..]) {
1481 Some(idx) => idx + gap_len,
1483 tail.copy_within(gap_len..idx, 0);
1484 tail = &mut tail[idx - gap_len..];
1485 if tail.len() == gap_len {
1488 cursor += idx - gap_len;
1490 normalized_pos.push(NormalizedPos {
1491 pos: BytePos::from_usize(cursor + 1),
1492 diff: original_gap + gap_len as u32,
1496 // Account for removed `\r`.
1497 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1498 let new_len = buf.len() - gap_len;
1500 buf.set_len(new_len);
1501 *src = String::from_utf8_unchecked(buf);
1504 fn find_crlf(src: &[u8]) -> Option<usize> {
1505 let mut search_idx = 0;
1506 while let Some(idx) = find_cr(&src[search_idx..]) {
1507 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1508 search_idx += idx + 1;
1511 return Some(search_idx + idx);
1516 fn find_cr(src: &[u8]) -> Option<usize> {
1517 src.iter().position(|&b| b == b'\r')
1521 // _____________________________________________________________________________
1522 // Pos, BytePos, CharPos
1526 fn from_usize(n: usize) -> Self;
1527 fn to_usize(&self) -> usize;
1528 fn from_u32(n: u32) -> Self;
1529 fn to_u32(&self) -> u32;
1532 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1534 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1535 pub struct BytePos(pub u32);
1537 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1538 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1539 /// values to `CharPos` values as necessary.
1540 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1541 pub struct CharPos(pub usize);
1543 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1544 // have been unsuccessful.
1546 impl Pos for BytePos {
1548 fn from_usize(n: usize) -> BytePos {
1553 fn to_usize(&self) -> usize {
1558 fn from_u32(n: u32) -> BytePos {
1563 fn to_u32(&self) -> u32 {
1568 impl Add for BytePos {
1569 type Output = BytePos;
1572 fn add(self, rhs: BytePos) -> BytePos {
1573 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1577 impl Sub for BytePos {
1578 type Output = BytePos;
1581 fn sub(self, rhs: BytePos) -> BytePos {
1582 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1586 impl<S: rustc_serialize::Encoder> Encodable<S> for BytePos {
1587 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1592 impl<D: rustc_serialize::Decoder> Decodable<D> for BytePos {
1593 fn decode(d: &mut D) -> Result<BytePos, D::Error> {
1594 Ok(BytePos(d.read_u32()?))
1598 impl Pos for CharPos {
1600 fn from_usize(n: usize) -> CharPos {
1605 fn to_usize(&self) -> usize {
1610 fn from_u32(n: u32) -> CharPos {
1615 fn to_u32(&self) -> u32 {
1620 impl Add for CharPos {
1621 type Output = CharPos;
1624 fn add(self, rhs: CharPos) -> CharPos {
1625 CharPos(self.to_usize() + rhs.to_usize())
1629 impl Sub for CharPos {
1630 type Output = CharPos;
1633 fn sub(self, rhs: CharPos) -> CharPos {
1634 CharPos(self.to_usize() - rhs.to_usize())
1638 // _____________________________________________________________________________
1639 // Loc, SourceFileAndLine, SourceFileAndBytePos
1642 /// A source code location used for error reporting.
1643 #[derive(Debug, Clone)]
1645 /// Information about the original source.
1646 pub file: Lrc<SourceFile>,
1647 /// The (1-based) line number.
1649 /// The (0-based) column offset.
1651 /// The (0-based) column offset when displayed.
1652 pub col_display: usize,
1655 // Used to be structural records.
1657 pub struct SourceFileAndLine {
1658 pub sf: Lrc<SourceFile>,
1662 pub struct SourceFileAndBytePos {
1663 pub sf: Lrc<SourceFile>,
1667 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1668 pub struct LineInfo {
1669 /// Index of line, starting from 0.
1670 pub line_index: usize,
1672 /// Column in line where span begins, starting from 0.
1673 pub start_col: CharPos,
1675 /// Column in line where span ends, starting from 0, exclusive.
1676 pub end_col: CharPos,
1679 pub struct FileLines {
1680 pub file: Lrc<SourceFile>,
1681 pub lines: Vec<LineInfo>,
1684 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1685 AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1687 // _____________________________________________________________________________
1688 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1691 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1693 #[derive(Clone, PartialEq, Eq, Debug)]
1694 pub enum SpanLinesError {
1695 DistinctSources(DistinctSources),
1698 #[derive(Clone, PartialEq, Eq, Debug)]
1699 pub enum SpanSnippetError {
1700 IllFormedSpan(Span),
1701 DistinctSources(DistinctSources),
1702 MalformedForSourcemap(MalformedSourceMapPositions),
1703 SourceNotAvailable { filename: FileName },
1706 #[derive(Clone, PartialEq, Eq, Debug)]
1707 pub struct DistinctSources {
1708 pub begin: (FileName, BytePos),
1709 pub end: (FileName, BytePos),
1712 #[derive(Clone, PartialEq, Eq, Debug)]
1713 pub struct MalformedSourceMapPositions {
1715 pub source_len: usize,
1716 pub begin_pos: BytePos,
1717 pub end_pos: BytePos,
1720 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1721 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1722 pub struct InnerSpan {
1728 pub fn new(start: usize, end: usize) -> InnerSpan {
1729 InnerSpan { start, end }
1733 // Given a slice of line start positions and a position, returns the index of
1734 // the line the position is on. Returns -1 if the position is located before
1736 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1737 match lines.binary_search(&pos) {
1738 Ok(line) => line as isize,
1739 Err(line) => line as isize - 1,
1743 /// Requirements for a `StableHashingContext` to be used in this crate.
1744 /// This is a hack to allow using the `HashStable_Generic` derive macro
1745 /// instead of implementing everything in librustc_middle.
1746 pub trait HashStableContext {
1747 fn hash_def_id(&mut self, _: DefId, hasher: &mut StableHasher);
1748 fn hash_crate_num(&mut self, _: CrateNum, hasher: &mut StableHasher);
1749 fn hash_spans(&self) -> bool;
1750 fn byte_pos_to_line_and_col(
1753 ) -> Option<(Lrc<SourceFile>, usize, BytePos)>;
1756 impl<CTX> HashStable<CTX> for Span
1758 CTX: HashStableContext,
1760 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1761 /// fields (that would be similar to hashing pointers, since those are just
1762 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1763 /// triple, which stays the same even if the containing `SourceFile` has moved
1764 /// within the `SourceMap`.
1765 /// Also note that we are hashing byte offsets for the column, not unicode
1766 /// codepoint offsets. For the purpose of the hash that's sufficient.
1767 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1768 /// span starts and ends in the same file, which is almost always the case.
1769 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1770 const TAG_VALID_SPAN: u8 = 0;
1771 const TAG_INVALID_SPAN: u8 = 1;
1773 if !ctx.hash_spans() {
1777 if *self == DUMMY_SP {
1778 std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1782 // If this is not an empty or invalid span, we want to hash the last
1783 // position that belongs to it, as opposed to hashing the first
1784 // position past it.
1785 let span = self.data();
1786 let (file_lo, line_lo, col_lo) = match ctx.byte_pos_to_line_and_col(span.lo) {
1789 std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1790 span.ctxt.hash_stable(ctx, hasher);
1795 if !file_lo.contains(span.hi) {
1796 std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1797 span.ctxt.hash_stable(ctx, hasher);
1801 std::hash::Hash::hash(&TAG_VALID_SPAN, hasher);
1802 // We truncate the stable ID hash and line and column numbers. The chances
1803 // of causing a collision this way should be minimal.
1804 std::hash::Hash::hash(&(file_lo.name_hash as u64), hasher);
1806 let col = (col_lo.0 as u64) & 0xFF;
1807 let line = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1808 let len = ((span.hi - span.lo).0 as u64) << 32;
1809 let line_col_len = col | line | len;
1810 std::hash::Hash::hash(&line_col_len, hasher);
1811 span.ctxt.hash_stable(ctx, hasher);
1815 impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1816 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1817 const TAG_EXPANSION: u8 = 0;
1818 const TAG_NO_EXPANSION: u8 = 1;
1820 if *self == SyntaxContext::root() {
1821 TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1823 TAG_EXPANSION.hash_stable(ctx, hasher);
1824 let (expn_id, transparency) = self.outer_mark();
1825 expn_id.hash_stable(ctx, hasher);
1826 transparency.hash_stable(ctx, hasher);
1831 impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
1832 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1833 // Since the same expansion context is usually referenced many
1834 // times, we cache a stable hash of it and hash that instead of
1835 // recursing every time.
1837 static CACHE: RefCell<Vec<Option<Fingerprint>>> = Default::default();
1840 const TAG_ROOT: u8 = 0;
1841 const TAG_NOT_ROOT: u8 = 1;
1843 if *self == ExpnId::root() {
1844 TAG_ROOT.hash_stable(ctx, hasher);
1848 TAG_NOT_ROOT.hash_stable(ctx, hasher);
1849 let index = self.as_u32() as usize;
1851 let res = CACHE.with(|cache| cache.borrow().get(index).copied().flatten());
1853 if let Some(res) = res {
1854 res.hash_stable(ctx, hasher);
1856 let new_len = index + 1;
1858 let mut sub_hasher = StableHasher::new();
1859 self.expn_data().hash_stable(ctx, &mut sub_hasher);
1860 let sub_hash: Fingerprint = sub_hasher.finish();
1862 CACHE.with(|cache| {
1863 let mut cache = cache.borrow_mut();
1864 if cache.len() < new_len {
1865 cache.resize(new_len, None);
1867 cache[index].replace(sub_hash).expect_none("Cache slot was filled");
1869 sub_hash.hash_stable(ctx, hasher);