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 use hygiene::Transparency;
36 pub use hygiene::{DesugaringKind, ExpnData, ExpnId, ExpnKind, ForLoopLoc, MacroKind};
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 pub fn with_session_globals<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
91 let session_globals = SessionGlobals::new(edition);
92 SESSION_GLOBALS.set(&session_globals, f)
95 pub fn with_default_session_globals<R>(f: impl FnOnce() -> R) -> R {
96 with_session_globals(edition::DEFAULT_EDITION, f)
99 // If this ever becomes non thread-local, `decode_syntax_context`
100 // and `decode_expn_id` will need to be updated to handle concurrent
102 scoped_tls::scoped_thread_local!(pub static SESSION_GLOBALS: SessionGlobals);
104 // FIXME: Perhaps this should not implement Rustc{Decodable, Encodable}
106 // FIXME: We should use this enum or something like it to get rid of the
107 // use of magic `/rust/1.x/...` paths across the board.
108 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
109 #[derive(HashStable_Generic)]
110 pub enum RealFileName {
112 /// For de-virtualized paths (namely paths into libstd that have been mapped
113 /// to the appropriate spot on the local host's file system),
115 /// `local_path` is the (host-dependent) local path to the file.
117 /// `virtual_name` is the stable path rustc will store internally within
119 virtual_name: PathBuf,
124 /// Returns the path suitable for reading from the file system on the local host.
125 /// Avoid embedding this in build artifacts; see `stable_name` for that.
126 pub fn local_path(&self) -> &Path {
128 RealFileName::Named(p)
129 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => &p,
133 /// Returns the path suitable for reading from the file system on the local host.
134 /// Avoid embedding this in build artifacts; see `stable_name` for that.
135 pub fn into_local_path(self) -> PathBuf {
137 RealFileName::Named(p)
138 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => p,
142 /// Returns the path suitable for embedding into build artifacts. Note that
143 /// a virtualized path will not correspond to a valid file system path; see
144 /// `local_path` for something that is more likely to return paths into the
145 /// local host file system.
146 pub fn stable_name(&self) -> &Path {
148 RealFileName::Named(p)
149 | RealFileName::Devirtualized { local_path: _, virtual_name: p } => &p,
154 /// Differentiates between real files and common virtual files.
155 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
156 #[derive(HashStable_Generic)]
159 /// Call to `quote!`.
163 /// Hack in `src/librustc_ast/parse.rs`.
166 ProcMacroSourceCode(u64),
167 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
169 /// Strings provided as crate attributes in the CLI.
171 /// Custom sources for explicit parser calls from plugins and drivers.
173 DocTest(PathBuf, isize),
174 /// Post-substitution inline assembly from LLVM
178 impl std::fmt::Display for FileName {
179 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182 Real(RealFileName::Named(ref path)) => write!(fmt, "{}", path.display()),
183 // FIXME: might be nice to display both compoments of Devirtualized.
184 // But for now (to backport fix for issue #70924), best to not
185 // perturb diagnostics so its obvious test suite still works.
186 Real(RealFileName::Devirtualized { ref local_path, virtual_name: _ }) => {
187 write!(fmt, "{}", local_path.display())
189 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
190 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
191 Anon(_) => write!(fmt, "<anon>"),
192 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
193 CfgSpec(_) => write!(fmt, "<cfgspec>"),
194 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
195 Custom(ref s) => write!(fmt, "<{}>", s),
196 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
197 InlineAsm(_) => write!(fmt, "<inline asm>"),
202 impl From<PathBuf> for FileName {
203 fn from(p: PathBuf) -> Self {
204 assert!(!p.to_string_lossy().ends_with('>'));
205 FileName::Real(RealFileName::Named(p))
210 pub fn is_real(&self) -> bool {
216 | ProcMacroSourceCode(_)
222 | InlineAsm(_) => false,
226 pub fn quote_expansion_source_code(src: &str) -> FileName {
227 let mut hasher = StableHasher::new();
228 src.hash(&mut hasher);
229 FileName::QuoteExpansion(hasher.finish())
232 pub fn macro_expansion_source_code(src: &str) -> FileName {
233 let mut hasher = StableHasher::new();
234 src.hash(&mut hasher);
235 FileName::MacroExpansion(hasher.finish())
238 pub fn anon_source_code(src: &str) -> FileName {
239 let mut hasher = StableHasher::new();
240 src.hash(&mut hasher);
241 FileName::Anon(hasher.finish())
244 pub fn proc_macro_source_code(src: &str) -> FileName {
245 let mut hasher = StableHasher::new();
246 src.hash(&mut hasher);
247 FileName::ProcMacroSourceCode(hasher.finish())
250 pub fn cfg_spec_source_code(src: &str) -> FileName {
251 let mut hasher = StableHasher::new();
252 src.hash(&mut hasher);
253 FileName::QuoteExpansion(hasher.finish())
256 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
257 let mut hasher = StableHasher::new();
258 src.hash(&mut hasher);
259 FileName::CliCrateAttr(hasher.finish())
262 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
263 FileName::DocTest(path, line)
266 pub fn inline_asm_source_code(src: &str) -> FileName {
267 let mut hasher = StableHasher::new();
268 src.hash(&mut hasher);
269 FileName::InlineAsm(hasher.finish())
273 /// Spans represent a region of code, used for error reporting. Positions in spans
274 /// are *absolute* positions from the beginning of the source_map, not positions
275 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
276 /// to the original source.
277 /// You must be careful if the span crosses more than one file - you will not be
278 /// able to use many of the functions on spans in source_map and you cannot assume
279 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
280 /// range between files.
282 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
283 /// sent to other threads, but some pieces of performance infra run in a separate thread.
284 /// Using `Span` is generally preferred.
285 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
286 pub struct SpanData {
289 /// Information about where the macro came from, if this piece of
290 /// code was created by a macro expansion.
291 pub ctxt: SyntaxContext,
296 pub fn with_lo(&self, lo: BytePos) -> Span {
297 Span::new(lo, self.hi, self.ctxt)
300 pub fn with_hi(&self, hi: BytePos) -> Span {
301 Span::new(self.lo, hi, self.ctxt)
304 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
305 Span::new(self.lo, self.hi, ctxt)
309 // The interner is pointed to by a thread local value which is only set on the main thread
310 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
311 // to avoid panics and other errors, even though it would be memory safe to do so.
312 #[cfg(not(parallel_compiler))]
313 impl !Send for Span {}
314 #[cfg(not(parallel_compiler))]
315 impl !Sync for Span {}
317 impl PartialOrd for Span {
318 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
319 PartialOrd::partial_cmp(&self.data(), &rhs.data())
323 fn cmp(&self, rhs: &Self) -> Ordering {
324 Ord::cmp(&self.data(), &rhs.data())
328 /// A collection of `Span`s.
330 /// Spans have two orthogonal attributes:
332 /// - They can be *primary spans*. In this case they are the locus of
333 /// the error, and would be rendered with `^^^`.
334 /// - They can have a *label*. In this case, the label is written next
335 /// to the mark in the snippet when we render.
336 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
337 pub struct MultiSpan {
338 primary_spans: Vec<Span>,
339 span_labels: Vec<(Span, String)>,
344 pub fn lo(self) -> BytePos {
348 pub fn with_lo(self, lo: BytePos) -> Span {
349 self.data().with_lo(lo)
352 pub fn hi(self) -> BytePos {
356 pub fn with_hi(self, hi: BytePos) -> Span {
357 self.data().with_hi(hi)
360 pub fn ctxt(self) -> SyntaxContext {
364 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
365 self.data().with_ctxt(ctxt)
368 /// Returns `true` if this is a dummy span with any hygienic context.
370 pub fn is_dummy(self) -> bool {
371 let span = self.data();
372 span.lo.0 == 0 && span.hi.0 == 0
375 /// Returns `true` if this span comes from a macro or desugaring.
377 pub fn from_expansion(self) -> bool {
378 self.ctxt() != SyntaxContext::root()
381 /// Returns `true` if `span` originates in a derive-macro's expansion.
382 pub fn in_derive_expansion(self) -> bool {
383 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
387 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
388 Span::new(lo, hi, SyntaxContext::root())
391 /// Returns a new span representing an empty span at the beginning of this span
393 pub fn shrink_to_lo(self) -> Span {
394 let span = self.data();
395 span.with_hi(span.lo)
397 /// Returns a new span representing an empty span at the end of this span.
399 pub fn shrink_to_hi(self) -> Span {
400 let span = self.data();
401 span.with_lo(span.hi)
404 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
405 pub fn substitute_dummy(self, other: Span) -> Span {
406 if self.is_dummy() { other } else { self }
409 /// Returns `true` if `self` fully encloses `other`.
410 pub fn contains(self, other: Span) -> bool {
411 let span = self.data();
412 let other = other.data();
413 span.lo <= other.lo && other.hi <= span.hi
416 /// Returns `true` if `self` touches `other`.
417 pub fn overlaps(self, other: Span) -> bool {
418 let span = self.data();
419 let other = other.data();
420 span.lo < other.hi && other.lo < span.hi
423 /// Returns `true` if the spans are equal with regards to the source text.
425 /// Use this instead of `==` when either span could be generated code,
426 /// and you only care that they point to the same bytes of source text.
427 pub fn source_equal(&self, other: &Span) -> bool {
428 let span = self.data();
429 let other = other.data();
430 span.lo == other.lo && span.hi == other.hi
433 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
434 pub fn trim_start(self, other: Span) -> Option<Span> {
435 let span = self.data();
436 let other = other.data();
437 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
440 /// Returns the source span -- this is either the supplied span, or the span for
441 /// the macro callsite that expanded to it.
442 pub fn source_callsite(self) -> Span {
443 let expn_data = self.ctxt().outer_expn_data();
444 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
447 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
449 pub fn parent(self) -> Option<Span> {
450 let expn_data = self.ctxt().outer_expn_data();
451 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
454 /// Edition of the crate from which this span came.
455 pub fn edition(self) -> edition::Edition {
456 self.ctxt().outer_expn_data().edition
460 pub fn rust_2015(&self) -> bool {
461 self.edition() == edition::Edition::Edition2015
465 pub fn rust_2018(&self) -> bool {
466 self.edition() >= edition::Edition::Edition2018
469 /// Returns the source callee.
471 /// Returns `None` if the supplied span has no expansion trace,
472 /// else returns the `ExpnData` for the macro definition
473 /// corresponding to the source callsite.
474 pub fn source_callee(self) -> Option<ExpnData> {
475 fn source_callee(expn_data: ExpnData) -> ExpnData {
476 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
477 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
479 let expn_data = self.ctxt().outer_expn_data();
480 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
483 /// Checks if a span is "internal" to a macro in which `#[unstable]`
484 /// items can be used (that is, a macro marked with
485 /// `#[allow_internal_unstable]`).
486 pub fn allows_unstable(&self, feature: Symbol) -> bool {
487 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
490 .any(|&f| f == feature || f == sym::allow_internal_unstable_backcompat_hack)
494 /// Checks if this span arises from a compiler desugaring of kind `kind`.
495 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
496 match self.ctxt().outer_expn_data().kind {
497 ExpnKind::Desugaring(k) => k == kind,
502 /// Returns the compiler desugaring that created this span, or `None`
503 /// if this span is not from a desugaring.
504 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
505 match self.ctxt().outer_expn_data().kind {
506 ExpnKind::Desugaring(k) => Some(k),
511 /// Checks if a span is "internal" to a macro in which `unsafe`
512 /// can be used without triggering the `unsafe_code` lint
513 // (that is, a macro marked with `#[allow_internal_unsafe]`).
514 pub fn allows_unsafe(&self) -> bool {
515 self.ctxt().outer_expn_data().allow_internal_unsafe
518 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
519 let mut prev_span = DUMMY_SP;
520 std::iter::from_fn(move || {
522 let expn_data = self.ctxt().outer_expn_data();
523 if expn_data.is_root() {
527 let is_recursive = expn_data.call_site.source_equal(&prev_span);
530 self = expn_data.call_site;
532 // Don't print recursive invocations.
534 return Some(expn_data);
540 /// Returns a `Span` that would enclose both `self` and `end`.
541 pub fn to(self, end: Span) -> Span {
542 let span_data = self.data();
543 let end_data = end.data();
544 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
545 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
546 // have an incomplete span than a completely nonsensical one.
547 if span_data.ctxt != end_data.ctxt {
548 if span_data.ctxt == SyntaxContext::root() {
550 } else if end_data.ctxt == SyntaxContext::root() {
553 // Both spans fall within a macro.
554 // FIXME(estebank): check if it is the *same* macro.
557 cmp::min(span_data.lo, end_data.lo),
558 cmp::max(span_data.hi, end_data.hi),
559 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
563 /// Returns a `Span` between the end of `self` to the beginning of `end`.
564 pub fn between(self, end: Span) -> Span {
565 let span = self.data();
566 let end = end.data();
570 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
574 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
575 pub fn until(self, end: Span) -> Span {
576 let span = self.data();
577 let end = end.data();
581 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
585 pub fn from_inner(self, inner: InnerSpan) -> Span {
586 let span = self.data();
588 span.lo + BytePos::from_usize(inner.start),
589 span.lo + BytePos::from_usize(inner.end),
594 /// Equivalent of `Span::def_site` from the proc macro API,
595 /// except that the location is taken from the `self` span.
596 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
597 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
600 /// Equivalent of `Span::call_site` from the proc macro API,
601 /// except that the location is taken from the `self` span.
602 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
603 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
606 /// Equivalent of `Span::mixed_site` from the proc macro API,
607 /// except that the location is taken from the `self` span.
608 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
609 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
612 /// Produces a span with the same location as `self` and context produced by a macro with the
613 /// given ID and transparency, assuming that macro was defined directly and not produced by
614 /// some other macro (which is the case for built-in and procedural macros).
615 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
616 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
620 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
621 let span = self.data();
622 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
626 pub fn remove_mark(&mut self) -> ExpnId {
627 let mut span = self.data();
628 let mark = span.ctxt.remove_mark();
629 *self = Span::new(span.lo, span.hi, span.ctxt);
634 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
635 let mut span = self.data();
636 let mark = span.ctxt.adjust(expn_id);
637 *self = Span::new(span.lo, span.hi, span.ctxt);
642 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
643 let mut span = self.data();
644 let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
645 *self = Span::new(span.lo, span.hi, span.ctxt);
650 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
651 let mut span = self.data();
652 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
653 *self = Span::new(span.lo, span.hi, span.ctxt);
658 pub fn reverse_glob_adjust(
662 ) -> Option<Option<ExpnId>> {
663 let mut span = self.data();
664 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
665 *self = Span::new(span.lo, span.hi, span.ctxt);
670 pub fn normalize_to_macros_2_0(self) -> Span {
671 let span = self.data();
672 span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
676 pub fn normalize_to_macro_rules(self) -> Span {
677 let span = self.data();
678 span.with_ctxt(span.ctxt.normalize_to_macro_rules())
682 #[derive(Clone, Debug)]
683 pub struct SpanLabel {
684 /// The span we are going to include in the final snippet.
687 /// Is this a primary span? This is the "locus" of the message,
688 /// and is indicated with a `^^^^` underline, versus `----`.
689 pub is_primary: bool,
691 /// What label should we attach to this span (if any)?
692 pub label: Option<String>,
695 impl Default for Span {
696 fn default() -> Self {
701 impl rustc_serialize::UseSpecializedEncodable for Span {
702 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
703 let span = self.data();
704 s.emit_struct("Span", 2, |s| {
705 s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?;
707 s.emit_struct_field("hi", 1, |s| span.hi.encode(s))
712 impl rustc_serialize::UseSpecializedDecodable for Span {
713 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
714 d.read_struct("Span", 2, |d| {
715 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
716 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
717 Ok(Span::with_root_ctxt(lo, hi))
722 /// Calls the provided closure, using the provided `SourceMap` to format
723 /// any spans that are debug-printed during the closure'e exectuino.
725 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
726 /// (see `rustc_interface::callbacks::span_debug1). However, some parts
727 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
728 /// a `TyCtxt` is available. In this case, we fall back to
729 /// the `SourceMap` provided to this function. If that is not available,
730 /// we fall back to printing the raw `Span` field values
731 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
732 SESSION_GLOBALS.with(|session_globals| {
733 *session_globals.source_map.borrow_mut() = Some(source_map);
735 struct ClearSourceMap;
736 impl Drop for ClearSourceMap {
738 SESSION_GLOBALS.with(|session_globals| {
739 session_globals.source_map.borrow_mut().take();
744 let _guard = ClearSourceMap;
748 pub fn debug_with_source_map(
750 f: &mut fmt::Formatter<'_>,
751 source_map: &SourceMap,
753 write!(f, "{} ({:?})", source_map.span_to_string(span), span.ctxt())
756 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
757 SESSION_GLOBALS.with(|session_globals| {
758 if let Some(source_map) = &*session_globals.source_map.borrow() {
759 debug_with_source_map(span, f, source_map)
761 f.debug_struct("Span")
762 .field("lo", &span.lo())
763 .field("hi", &span.hi())
764 .field("ctxt", &span.ctxt())
770 impl fmt::Debug for Span {
771 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
772 (*SPAN_DEBUG)(*self, f)
776 impl fmt::Debug for SpanData {
777 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
778 (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
784 pub fn new() -> MultiSpan {
785 MultiSpan { primary_spans: vec![], span_labels: vec![] }
788 pub fn from_span(primary_span: Span) -> MultiSpan {
789 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
792 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
794 MultiSpan { primary_spans: vec, span_labels: vec![] }
797 pub fn push_span_label(&mut self, span: Span, label: String) {
798 self.span_labels.push((span, label));
801 /// Selects the first primary span (if any).
802 pub fn primary_span(&self) -> Option<Span> {
803 self.primary_spans.first().cloned()
806 /// Returns all primary spans.
807 pub fn primary_spans(&self) -> &[Span] {
811 /// Returns `true` if any of the primary spans are displayable.
812 pub fn has_primary_spans(&self) -> bool {
813 self.primary_spans.iter().any(|sp| !sp.is_dummy())
816 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
817 pub fn is_dummy(&self) -> bool {
818 let mut is_dummy = true;
819 for span in &self.primary_spans {
820 if !span.is_dummy() {
827 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
828 /// display well (like std macros). Returns whether replacements occurred.
829 pub fn replace(&mut self, before: Span, after: Span) -> bool {
830 let mut replacements_occurred = false;
831 for primary_span in &mut self.primary_spans {
832 if *primary_span == before {
833 *primary_span = after;
834 replacements_occurred = true;
837 for span_label in &mut self.span_labels {
838 if span_label.0 == before {
839 span_label.0 = after;
840 replacements_occurred = true;
843 replacements_occurred
846 /// Returns the strings to highlight. We always ensure that there
847 /// is an entry for each of the primary spans -- for each primary
848 /// span `P`, if there is at least one label with span `P`, we return
849 /// those labels (marked as primary). But otherwise we return
850 /// `SpanLabel` instances with empty labels.
851 pub fn span_labels(&self) -> Vec<SpanLabel> {
852 let is_primary = |span| self.primary_spans.contains(&span);
854 let mut span_labels = self
857 .map(|&(span, ref label)| SpanLabel {
859 is_primary: is_primary(span),
860 label: Some(label.clone()),
862 .collect::<Vec<_>>();
864 for &span in &self.primary_spans {
865 if !span_labels.iter().any(|sl| sl.span == span) {
866 span_labels.push(SpanLabel { span, is_primary: true, label: None });
873 /// Returns `true` if any of the span labels is displayable.
874 pub fn has_span_labels(&self) -> bool {
875 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
879 impl From<Span> for MultiSpan {
880 fn from(span: Span) -> MultiSpan {
881 MultiSpan::from_span(span)
885 impl From<Vec<Span>> for MultiSpan {
886 fn from(spans: Vec<Span>) -> MultiSpan {
887 MultiSpan::from_spans(spans)
891 /// Identifies an offset of a multi-byte character in a `SourceFile`.
892 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
893 pub struct MultiByteChar {
894 /// The absolute offset of the character in the `SourceMap`.
896 /// The number of bytes, `>= 2`.
900 /// Identifies an offset of a non-narrow character in a `SourceFile`.
901 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
902 pub enum NonNarrowChar {
903 /// Represents a zero-width character.
905 /// Represents a wide (full-width) character.
907 /// Represents a tab character, represented visually with a width of 4 characters.
912 fn new(pos: BytePos, width: usize) -> Self {
914 0 => NonNarrowChar::ZeroWidth(pos),
915 2 => NonNarrowChar::Wide(pos),
916 4 => NonNarrowChar::Tab(pos),
917 _ => panic!("width {} given for non-narrow character", width),
921 /// Returns the absolute offset of the character in the `SourceMap`.
922 pub fn pos(&self) -> BytePos {
924 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
928 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
929 pub fn width(&self) -> usize {
931 NonNarrowChar::ZeroWidth(_) => 0,
932 NonNarrowChar::Wide(_) => 2,
933 NonNarrowChar::Tab(_) => 4,
938 impl Add<BytePos> for NonNarrowChar {
941 fn add(self, rhs: BytePos) -> Self {
943 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
944 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
945 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
950 impl Sub<BytePos> for NonNarrowChar {
953 fn sub(self, rhs: BytePos) -> Self {
955 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
956 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
957 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
962 /// Identifies an offset of a character that was normalized away from `SourceFile`.
963 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
964 pub struct NormalizedPos {
965 /// The absolute offset of the character in the `SourceMap`.
967 /// The difference between original and normalized string at position.
971 #[derive(PartialEq, Eq, Clone, Debug)]
972 pub enum ExternalSource {
973 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
976 kind: ExternalSourceKind,
977 /// This SourceFile's byte-offset within the source_map of its original crate
978 original_start_pos: BytePos,
979 /// The end of this SourceFile within the source_map of its original crate
980 original_end_pos: BytePos,
984 /// The state of the lazy external source loading mechanism of a `SourceFile`.
985 #[derive(PartialEq, Eq, Clone, Debug)]
986 pub enum ExternalSourceKind {
987 /// The external source has been loaded already.
988 Present(Lrc<String>),
989 /// No attempt has been made to load the external source.
991 /// A failed attempt has been made to load the external source.
996 impl ExternalSource {
997 pub fn is_absent(&self) -> bool {
999 ExternalSource::Foreign { kind: ExternalSourceKind::Present(_), .. } => false,
1004 pub fn get_source(&self) -> Option<&Lrc<String>> {
1006 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1013 pub struct OffsetOverflowError;
1015 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
1016 pub enum SourceFileHashAlgorithm {
1021 impl FromStr for SourceFileHashAlgorithm {
1024 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1026 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1027 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1033 rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm);
1035 /// The hash of the on-disk source file used for debug info.
1036 #[derive(Copy, Clone, PartialEq, Eq, Debug, RustcEncodable, RustcDecodable)]
1037 #[derive(HashStable_Generic)]
1038 pub struct SourceFileHash {
1039 pub kind: SourceFileHashAlgorithm,
1043 impl SourceFileHash {
1044 pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1045 let mut hash = SourceFileHash { kind, value: Default::default() };
1046 let len = hash.hash_len();
1047 let value = &mut hash.value[..len];
1048 let data = src.as_bytes();
1050 SourceFileHashAlgorithm::Md5 => {
1051 value.copy_from_slice(&Md5::digest(data));
1053 SourceFileHashAlgorithm::Sha1 => {
1054 value.copy_from_slice(&Sha1::digest(data));
1060 /// Check if the stored hash matches the hash of the string.
1061 pub fn matches(&self, src: &str) -> bool {
1062 Self::new(self.kind, src) == *self
1065 /// The bytes of the hash.
1066 pub fn hash_bytes(&self) -> &[u8] {
1067 let len = self.hash_len();
1071 fn hash_len(&self) -> usize {
1073 SourceFileHashAlgorithm::Md5 => 16,
1074 SourceFileHashAlgorithm::Sha1 => 20,
1079 /// A single source in the `SourceMap`.
1081 pub struct SourceFile {
1082 /// The name of the file that the source came from. Source that doesn't
1083 /// originate from files has names between angle brackets by convention
1084 /// (e.g., `<anon>`).
1086 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
1087 pub name_was_remapped: bool,
1088 /// The unmapped path of the file that the source came from.
1089 /// Set to `None` if the `SourceFile` was imported from an external crate.
1090 pub unmapped_path: Option<FileName>,
1091 /// The complete source code.
1092 pub src: Option<Lrc<String>>,
1093 /// The source code's hash.
1094 pub src_hash: SourceFileHash,
1095 /// The external source code (used for external crates, which will have a `None`
1096 /// value as `self.src`.
1097 pub external_src: Lock<ExternalSource>,
1098 /// The start position of this source in the `SourceMap`.
1099 pub start_pos: BytePos,
1100 /// The end position of this source in the `SourceMap`.
1101 pub end_pos: BytePos,
1102 /// Locations of lines beginnings in the source code.
1103 pub lines: Vec<BytePos>,
1104 /// Locations of multi-byte characters in the source code.
1105 pub multibyte_chars: Vec<MultiByteChar>,
1106 /// Width of characters that are not narrow in the source code.
1107 pub non_narrow_chars: Vec<NonNarrowChar>,
1108 /// Locations of characters removed during normalization.
1109 pub normalized_pos: Vec<NormalizedPos>,
1110 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1111 pub name_hash: u128,
1112 /// Indicates which crate this `SourceFile` was imported from.
1116 impl Encodable for SourceFile {
1117 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1118 s.emit_struct("SourceFile", 8, |s| {
1119 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
1120 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
1121 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
1122 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
1123 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
1124 s.emit_struct_field("lines", 5, |s| {
1125 let lines = &self.lines[..];
1126 // Store the length.
1127 s.emit_u32(lines.len() as u32)?;
1129 if !lines.is_empty() {
1130 // In order to preserve some space, we exploit the fact that
1131 // the lines list is sorted and individual lines are
1132 // probably not that long. Because of that we can store lines
1133 // as a difference list, using as little space as possible
1134 // for the differences.
1135 let max_line_length = if lines.len() == 1 {
1138 lines.windows(2).map(|w| w[1] - w[0]).map(|bp| bp.to_usize()).max().unwrap()
1141 let bytes_per_diff: u8 = match max_line_length {
1143 0x100..=0xFFFF => 2,
1147 // Encode the number of bytes used per diff.
1148 bytes_per_diff.encode(s)?;
1150 // Encode the first element.
1151 lines[0].encode(s)?;
1153 let diff_iter = (&lines[..]).windows(2).map(|w| (w[1] - w[0]));
1155 match bytes_per_diff {
1157 for diff in diff_iter {
1158 (diff.0 as u8).encode(s)?
1162 for diff in diff_iter {
1163 (diff.0 as u16).encode(s)?
1167 for diff in diff_iter {
1171 _ => unreachable!(),
1177 s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
1178 s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
1179 s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
1180 s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))?;
1181 s.emit_struct_field("cnum", 10, |s| self.cnum.encode(s))
1186 impl Decodable for SourceFile {
1187 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
1188 d.read_struct("SourceFile", 8, |d| {
1189 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1190 let name_was_remapped: bool =
1191 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1192 let src_hash: SourceFileHash =
1193 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1194 let start_pos: BytePos =
1195 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1196 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1197 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1198 let num_lines: u32 = Decodable::decode(d)?;
1199 let mut lines = Vec::with_capacity(num_lines as usize);
1202 // Read the number of bytes used per diff.
1203 let bytes_per_diff: u8 = Decodable::decode(d)?;
1205 // Read the first element.
1206 let mut line_start: BytePos = Decodable::decode(d)?;
1207 lines.push(line_start);
1209 for _ in 1..num_lines {
1210 let diff = match bytes_per_diff {
1211 1 => d.read_u8()? as u32,
1212 2 => d.read_u16()? as u32,
1214 _ => unreachable!(),
1217 line_start = line_start + BytePos(diff);
1219 lines.push(line_start);
1225 let multibyte_chars: Vec<MultiByteChar> =
1226 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1227 let non_narrow_chars: Vec<NonNarrowChar> =
1228 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1229 let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1230 let normalized_pos: Vec<NormalizedPos> =
1231 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1232 let cnum: CrateNum = d.read_struct_field("cnum", 10, |d| Decodable::decode(d))?;
1236 unmapped_path: None,
1241 // Unused - the metadata decoder will construct
1242 // a new SourceFile, filling in `external_src` properly
1243 external_src: Lock::new(ExternalSource::Unneeded),
1255 impl fmt::Debug for SourceFile {
1256 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1257 write!(fmt, "SourceFile({})", self.name)
1264 name_was_remapped: bool,
1265 unmapped_path: FileName,
1268 hash_kind: SourceFileHashAlgorithm,
1270 // Compute the file hash before any normalization.
1271 let src_hash = SourceFileHash::new(hash_kind, &src);
1272 let normalized_pos = normalize_src(&mut src, start_pos);
1275 let mut hasher: StableHasher = StableHasher::new();
1276 name.hash(&mut hasher);
1277 hasher.finish::<u128>()
1279 let end_pos = start_pos.to_usize() + src.len();
1280 assert!(end_pos <= u32::MAX as usize);
1282 let (lines, multibyte_chars, non_narrow_chars) =
1283 analyze_source_file::analyze_source_file(&src[..], start_pos);
1288 unmapped_path: Some(unmapped_path),
1289 src: Some(Lrc::new(src)),
1291 external_src: Lock::new(ExternalSource::Unneeded),
1293 end_pos: Pos::from_usize(end_pos),
1303 /// Returns the `BytePos` of the beginning of the current line.
1304 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1305 let line_index = self.lookup_line(pos).unwrap();
1306 self.lines[line_index]
1309 /// Add externally loaded source.
1310 /// If the hash of the input doesn't match or no input is supplied via None,
1311 /// it is interpreted as an error and the corresponding enum variant is set.
1312 /// The return value signifies whether some kind of source is present.
1313 pub fn add_external_src<F>(&self, get_src: F) -> bool
1315 F: FnOnce() -> Option<String>,
1318 *self.external_src.borrow(),
1319 ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1321 let src = get_src();
1322 let mut external_src = self.external_src.borrow_mut();
1323 // Check that no-one else have provided the source while we were getting it
1324 if let ExternalSource::Foreign {
1325 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1326 } = &mut *external_src
1328 if let Some(mut src) = src {
1329 // The src_hash needs to be computed on the pre-normalized src.
1330 if self.src_hash.matches(&src) {
1331 normalize_src(&mut src, BytePos::from_usize(0));
1332 *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1336 *src_kind = ExternalSourceKind::AbsentErr;
1341 self.src.is_some() || external_src.get_source().is_some()
1344 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1348 /// Gets a line from the list of pre-computed line-beginnings.
1349 /// The line number here is 0-based.
1350 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1351 fn get_until_newline(src: &str, begin: usize) -> &str {
1352 // We can't use `lines.get(line_number+1)` because we might
1353 // be parsing when we call this function and thus the current
1354 // line is the last one we have line info for.
1355 let slice = &src[begin..];
1356 match slice.find('\n') {
1357 Some(e) => &slice[..e],
1363 let line = self.lines.get(line_number)?;
1364 let begin: BytePos = *line - self.start_pos;
1368 if let Some(ref src) = self.src {
1369 Some(Cow::from(get_until_newline(src, begin)))
1370 } else if let Some(src) = self.external_src.borrow().get_source() {
1371 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1377 pub fn is_real_file(&self) -> bool {
1381 pub fn is_imported(&self) -> bool {
1385 pub fn byte_length(&self) -> u32 {
1386 self.end_pos.0 - self.start_pos.0
1388 pub fn count_lines(&self) -> usize {
1392 /// Finds the line containing the given position. The return value is the
1393 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1394 /// number. If the source_file is empty or the position is located before the
1395 /// first line, `None` is returned.
1396 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1397 if self.lines.is_empty() {
1401 let line_index = lookup_line(&self.lines[..], pos);
1402 assert!(line_index < self.lines.len() as isize);
1403 if line_index >= 0 { Some(line_index as usize) } else { None }
1406 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1407 if self.start_pos == self.end_pos {
1408 return (self.start_pos, self.end_pos);
1411 assert!(line_index < self.lines.len());
1412 if line_index == (self.lines.len() - 1) {
1413 (self.lines[line_index], self.end_pos)
1415 (self.lines[line_index], self.lines[line_index + 1])
1420 pub fn contains(&self, byte_pos: BytePos) -> bool {
1421 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1424 /// Calculates the original byte position relative to the start of the file
1425 /// based on the given byte position.
1426 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1427 // Diff before any records is 0. Otherwise use the previously recorded
1428 // diff as that applies to the following characters until a new diff
1430 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1431 Ok(i) => self.normalized_pos[i].diff,
1432 Err(i) if i == 0 => 0,
1433 Err(i) => self.normalized_pos[i - 1].diff,
1436 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1440 /// Normalizes the source code and records the normalizations.
1441 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1442 let mut normalized_pos = vec![];
1443 remove_bom(src, &mut normalized_pos);
1444 normalize_newlines(src, &mut normalized_pos);
1446 // Offset all the positions by start_pos to match the final file positions.
1447 for np in &mut normalized_pos {
1448 np.pos.0 += start_pos.0;
1454 /// Removes UTF-8 BOM, if any.
1455 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1456 if src.starts_with("\u{feff}") {
1458 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1462 /// Replaces `\r\n` with `\n` in-place in `src`.
1464 /// Returns error if there's a lone `\r` in the string
1465 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1466 if !src.as_bytes().contains(&b'\r') {
1470 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1471 // While we *can* call `as_mut_vec` and do surgery on the live string
1472 // directly, let's rather steal the contents of `src`. This makes the code
1473 // safe even if a panic occurs.
1475 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1476 let mut gap_len = 0;
1477 let mut tail = buf.as_mut_slice();
1479 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1481 let idx = match find_crlf(&tail[gap_len..]) {
1483 Some(idx) => idx + gap_len,
1485 tail.copy_within(gap_len..idx, 0);
1486 tail = &mut tail[idx - gap_len..];
1487 if tail.len() == gap_len {
1490 cursor += idx - gap_len;
1492 normalized_pos.push(NormalizedPos {
1493 pos: BytePos::from_usize(cursor + 1),
1494 diff: original_gap + gap_len as u32,
1498 // Account for removed `\r`.
1499 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1500 let new_len = buf.len() - gap_len;
1502 buf.set_len(new_len);
1503 *src = String::from_utf8_unchecked(buf);
1506 fn find_crlf(src: &[u8]) -> Option<usize> {
1507 let mut search_idx = 0;
1508 while let Some(idx) = find_cr(&src[search_idx..]) {
1509 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1510 search_idx += idx + 1;
1513 return Some(search_idx + idx);
1518 fn find_cr(src: &[u8]) -> Option<usize> {
1519 src.iter().position(|&b| b == b'\r')
1523 // _____________________________________________________________________________
1524 // Pos, BytePos, CharPos
1528 fn from_usize(n: usize) -> Self;
1529 fn to_usize(&self) -> usize;
1530 fn from_u32(n: u32) -> Self;
1531 fn to_u32(&self) -> u32;
1534 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1536 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1537 pub struct BytePos(pub u32);
1539 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1540 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1541 /// values to `CharPos` values as necessary.
1542 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1543 pub struct CharPos(pub usize);
1545 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1546 // have been unsuccessful.
1548 impl Pos for BytePos {
1550 fn from_usize(n: usize) -> BytePos {
1555 fn to_usize(&self) -> usize {
1560 fn from_u32(n: u32) -> BytePos {
1565 fn to_u32(&self) -> u32 {
1570 impl Add for BytePos {
1571 type Output = BytePos;
1574 fn add(self, rhs: BytePos) -> BytePos {
1575 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1579 impl Sub for BytePos {
1580 type Output = BytePos;
1583 fn sub(self, rhs: BytePos) -> BytePos {
1584 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1588 impl Encodable for BytePos {
1589 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1594 impl Decodable for BytePos {
1595 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1596 Ok(BytePos(d.read_u32()?))
1600 impl Pos for CharPos {
1602 fn from_usize(n: usize) -> CharPos {
1607 fn to_usize(&self) -> usize {
1612 fn from_u32(n: u32) -> CharPos {
1617 fn to_u32(&self) -> u32 {
1622 impl Add for CharPos {
1623 type Output = CharPos;
1626 fn add(self, rhs: CharPos) -> CharPos {
1627 CharPos(self.to_usize() + rhs.to_usize())
1631 impl Sub for CharPos {
1632 type Output = CharPos;
1635 fn sub(self, rhs: CharPos) -> CharPos {
1636 CharPos(self.to_usize() - rhs.to_usize())
1640 // _____________________________________________________________________________
1641 // Loc, SourceFileAndLine, SourceFileAndBytePos
1644 /// A source code location used for error reporting.
1645 #[derive(Debug, Clone)]
1647 /// Information about the original source.
1648 pub file: Lrc<SourceFile>,
1649 /// The (1-based) line number.
1651 /// The (0-based) column offset.
1653 /// The (0-based) column offset when displayed.
1654 pub col_display: usize,
1657 // Used to be structural records.
1659 pub struct SourceFileAndLine {
1660 pub sf: Lrc<SourceFile>,
1664 pub struct SourceFileAndBytePos {
1665 pub sf: Lrc<SourceFile>,
1669 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1670 pub struct LineInfo {
1671 /// Index of line, starting from 0.
1672 pub line_index: usize,
1674 /// Column in line where span begins, starting from 0.
1675 pub start_col: CharPos,
1677 /// Column in line where span ends, starting from 0, exclusive.
1678 pub end_col: CharPos,
1681 pub struct FileLines {
1682 pub file: Lrc<SourceFile>,
1683 pub lines: Vec<LineInfo>,
1686 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1687 AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1689 // _____________________________________________________________________________
1690 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1693 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1695 #[derive(Clone, PartialEq, Eq, Debug)]
1696 pub enum SpanLinesError {
1697 DistinctSources(DistinctSources),
1700 #[derive(Clone, PartialEq, Eq, Debug)]
1701 pub enum SpanSnippetError {
1702 IllFormedSpan(Span),
1703 DistinctSources(DistinctSources),
1704 MalformedForSourcemap(MalformedSourceMapPositions),
1705 SourceNotAvailable { filename: FileName },
1708 #[derive(Clone, PartialEq, Eq, Debug)]
1709 pub struct DistinctSources {
1710 pub begin: (FileName, BytePos),
1711 pub end: (FileName, BytePos),
1714 #[derive(Clone, PartialEq, Eq, Debug)]
1715 pub struct MalformedSourceMapPositions {
1717 pub source_len: usize,
1718 pub begin_pos: BytePos,
1719 pub end_pos: BytePos,
1722 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1723 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1724 pub struct InnerSpan {
1730 pub fn new(start: usize, end: usize) -> InnerSpan {
1731 InnerSpan { start, end }
1735 // Given a slice of line start positions and a position, returns the index of
1736 // the line the position is on. Returns -1 if the position is located before
1738 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1739 match lines.binary_search(&pos) {
1740 Ok(line) => line as isize,
1741 Err(line) => line as isize - 1,
1745 /// Requirements for a `StableHashingContext` to be used in this crate.
1746 /// This is a hack to allow using the `HashStable_Generic` derive macro
1747 /// instead of implementing everything in librustc_middle.
1748 pub trait HashStableContext {
1749 fn hash_def_id(&mut self, _: DefId, hasher: &mut StableHasher);
1750 fn hash_crate_num(&mut self, _: CrateNum, hasher: &mut StableHasher);
1751 fn hash_spans(&self) -> bool;
1752 fn byte_pos_to_line_and_col(
1755 ) -> Option<(Lrc<SourceFile>, usize, BytePos)>;
1758 impl<CTX> HashStable<CTX> for Span
1760 CTX: HashStableContext,
1762 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1763 /// fields (that would be similar to hashing pointers, since those are just
1764 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1765 /// triple, which stays the same even if the containing `SourceFile` has moved
1766 /// within the `SourceMap`.
1767 /// Also note that we are hashing byte offsets for the column, not unicode
1768 /// codepoint offsets. For the purpose of the hash that's sufficient.
1769 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1770 /// span starts and ends in the same file, which is almost always the case.
1771 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1772 const TAG_VALID_SPAN: u8 = 0;
1773 const TAG_INVALID_SPAN: u8 = 1;
1775 if !ctx.hash_spans() {
1779 if *self == DUMMY_SP {
1780 std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1784 // If this is not an empty or invalid span, we want to hash the last
1785 // position that belongs to it, as opposed to hashing the first
1786 // position past it.
1787 let span = self.data();
1788 let (file_lo, line_lo, col_lo) = match ctx.byte_pos_to_line_and_col(span.lo) {
1791 std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1792 span.ctxt.hash_stable(ctx, hasher);
1797 if !file_lo.contains(span.hi) {
1798 std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1799 span.ctxt.hash_stable(ctx, hasher);
1803 std::hash::Hash::hash(&TAG_VALID_SPAN, hasher);
1804 // We truncate the stable ID hash and line and column numbers. The chances
1805 // of causing a collision this way should be minimal.
1806 std::hash::Hash::hash(&(file_lo.name_hash as u64), hasher);
1808 let col = (col_lo.0 as u64) & 0xFF;
1809 let line = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1810 let len = ((span.hi - span.lo).0 as u64) << 32;
1811 let line_col_len = col | line | len;
1812 std::hash::Hash::hash(&line_col_len, hasher);
1813 span.ctxt.hash_stable(ctx, hasher);
1817 impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1818 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1819 const TAG_EXPANSION: u8 = 0;
1820 const TAG_NO_EXPANSION: u8 = 1;
1822 if *self == SyntaxContext::root() {
1823 TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1825 TAG_EXPANSION.hash_stable(ctx, hasher);
1826 let (expn_id, transparency) = self.outer_mark();
1827 expn_id.hash_stable(ctx, hasher);
1828 transparency.hash_stable(ctx, hasher);
1833 impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
1834 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1835 // Since the same expansion context is usually referenced many
1836 // times, we cache a stable hash of it and hash that instead of
1837 // recursing every time.
1839 static CACHE: RefCell<Vec<Option<Fingerprint>>> = Default::default();
1842 const TAG_ROOT: u8 = 0;
1843 const TAG_NOT_ROOT: u8 = 1;
1845 if *self == ExpnId::root() {
1846 TAG_ROOT.hash_stable(ctx, hasher);
1850 TAG_NOT_ROOT.hash_stable(ctx, hasher);
1851 let index = self.as_u32() as usize;
1853 let res = CACHE.with(|cache| cache.borrow().get(index).copied().flatten());
1855 if let Some(res) = res {
1856 res.hash_stable(ctx, hasher);
1858 let new_len = index + 1;
1860 let mut sub_hasher = StableHasher::new();
1861 self.expn_data().hash_stable(ctx, &mut sub_hasher);
1862 let sub_hash: Fingerprint = sub_hasher.finish();
1864 CACHE.with(|cache| {
1865 let mut cache = cache.borrow_mut();
1866 if cache.len() < new_len {
1867 cache.resize(new_len, None);
1869 cache[index].replace(sub_hash).expect_none("Cache slot was filled");
1871 sub_hash.hash_stable(ctx, hasher);