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)
404 /// Returns true if hi == lo
405 pub fn is_empty(&self) -> bool {
406 let span = self.data();
410 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
411 pub fn substitute_dummy(self, other: Span) -> Span {
412 if self.is_dummy() { other } else { self }
415 /// Returns `true` if `self` fully encloses `other`.
416 pub fn contains(self, other: Span) -> bool {
417 let span = self.data();
418 let other = other.data();
419 span.lo <= other.lo && other.hi <= span.hi
422 /// Returns `true` if `self` touches `other`.
423 pub fn overlaps(self, other: Span) -> bool {
424 let span = self.data();
425 let other = other.data();
426 span.lo < other.hi && other.lo < span.hi
429 /// Returns `true` if the spans are equal with regards to the source text.
431 /// Use this instead of `==` when either span could be generated code,
432 /// and you only care that they point to the same bytes of source text.
433 pub fn source_equal(&self, other: &Span) -> bool {
434 let span = self.data();
435 let other = other.data();
436 span.lo == other.lo && span.hi == other.hi
439 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
440 pub fn trim_start(self, other: Span) -> Option<Span> {
441 let span = self.data();
442 let other = other.data();
443 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
446 /// Returns the source span -- this is either the supplied span, or the span for
447 /// the macro callsite that expanded to it.
448 pub fn source_callsite(self) -> Span {
449 let expn_data = self.ctxt().outer_expn_data();
450 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
453 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
455 pub fn parent(self) -> Option<Span> {
456 let expn_data = self.ctxt().outer_expn_data();
457 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
460 /// Edition of the crate from which this span came.
461 pub fn edition(self) -> edition::Edition {
462 self.ctxt().outer_expn_data().edition
466 pub fn rust_2015(&self) -> bool {
467 self.edition() == edition::Edition::Edition2015
471 pub fn rust_2018(&self) -> bool {
472 self.edition() >= edition::Edition::Edition2018
475 /// Returns the source callee.
477 /// Returns `None` if the supplied span has no expansion trace,
478 /// else returns the `ExpnData` for the macro definition
479 /// corresponding to the source callsite.
480 pub fn source_callee(self) -> Option<ExpnData> {
481 fn source_callee(expn_data: ExpnData) -> ExpnData {
482 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
483 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
485 let expn_data = self.ctxt().outer_expn_data();
486 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
489 /// Checks if a span is "internal" to a macro in which `#[unstable]`
490 /// items can be used (that is, a macro marked with
491 /// `#[allow_internal_unstable]`).
492 pub fn allows_unstable(&self, feature: Symbol) -> bool {
493 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
496 .any(|&f| f == feature || f == sym::allow_internal_unstable_backcompat_hack)
500 /// Checks if this span arises from a compiler desugaring of kind `kind`.
501 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
502 match self.ctxt().outer_expn_data().kind {
503 ExpnKind::Desugaring(k) => k == kind,
508 /// Returns the compiler desugaring that created this span, or `None`
509 /// if this span is not from a desugaring.
510 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
511 match self.ctxt().outer_expn_data().kind {
512 ExpnKind::Desugaring(k) => Some(k),
517 /// Checks if a span is "internal" to a macro in which `unsafe`
518 /// can be used without triggering the `unsafe_code` lint
519 // (that is, a macro marked with `#[allow_internal_unsafe]`).
520 pub fn allows_unsafe(&self) -> bool {
521 self.ctxt().outer_expn_data().allow_internal_unsafe
524 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
525 let mut prev_span = DUMMY_SP;
526 std::iter::from_fn(move || {
528 let expn_data = self.ctxt().outer_expn_data();
529 if expn_data.is_root() {
533 let is_recursive = expn_data.call_site.source_equal(&prev_span);
536 self = expn_data.call_site;
538 // Don't print recursive invocations.
540 return Some(expn_data);
546 /// Returns a `Span` that would enclose both `self` and `end`.
547 pub fn to(self, end: Span) -> Span {
548 let span_data = self.data();
549 let end_data = end.data();
550 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
551 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
552 // have an incomplete span than a completely nonsensical one.
553 if span_data.ctxt != end_data.ctxt {
554 if span_data.ctxt == SyntaxContext::root() {
556 } else if end_data.ctxt == SyntaxContext::root() {
559 // Both spans fall within a macro.
560 // FIXME(estebank): check if it is the *same* macro.
563 cmp::min(span_data.lo, end_data.lo),
564 cmp::max(span_data.hi, end_data.hi),
565 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
569 /// Returns a `Span` between the end of `self` to the beginning of `end`.
570 pub fn between(self, end: Span) -> Span {
571 let span = self.data();
572 let end = end.data();
576 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
580 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
581 pub fn until(self, end: Span) -> Span {
582 let span = self.data();
583 let end = end.data();
587 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
591 pub fn from_inner(self, inner: InnerSpan) -> Span {
592 let span = self.data();
594 span.lo + BytePos::from_usize(inner.start),
595 span.lo + BytePos::from_usize(inner.end),
600 /// Equivalent of `Span::def_site` from the proc macro API,
601 /// except that the location is taken from the `self` span.
602 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
603 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
606 /// Equivalent of `Span::call_site` from the proc macro API,
607 /// except that the location is taken from the `self` span.
608 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
609 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
612 /// Equivalent of `Span::mixed_site` from the proc macro API,
613 /// except that the location is taken from the `self` span.
614 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
615 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
618 /// Produces a span with the same location as `self` and context produced by a macro with the
619 /// given ID and transparency, assuming that macro was defined directly and not produced by
620 /// some other macro (which is the case for built-in and procedural macros).
621 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
622 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
626 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
627 let span = self.data();
628 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
632 pub fn remove_mark(&mut self) -> ExpnId {
633 let mut span = self.data();
634 let mark = span.ctxt.remove_mark();
635 *self = Span::new(span.lo, span.hi, span.ctxt);
640 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
641 let mut span = self.data();
642 let mark = span.ctxt.adjust(expn_id);
643 *self = Span::new(span.lo, span.hi, span.ctxt);
648 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
649 let mut span = self.data();
650 let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
651 *self = Span::new(span.lo, span.hi, span.ctxt);
656 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
657 let mut span = self.data();
658 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
659 *self = Span::new(span.lo, span.hi, span.ctxt);
664 pub fn reverse_glob_adjust(
668 ) -> Option<Option<ExpnId>> {
669 let mut span = self.data();
670 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
671 *self = Span::new(span.lo, span.hi, span.ctxt);
676 pub fn normalize_to_macros_2_0(self) -> Span {
677 let span = self.data();
678 span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
682 pub fn normalize_to_macro_rules(self) -> Span {
683 let span = self.data();
684 span.with_ctxt(span.ctxt.normalize_to_macro_rules())
688 #[derive(Clone, Debug)]
689 pub struct SpanLabel {
690 /// The span we are going to include in the final snippet.
693 /// Is this a primary span? This is the "locus" of the message,
694 /// and is indicated with a `^^^^` underline, versus `----`.
695 pub is_primary: bool,
697 /// What label should we attach to this span (if any)?
698 pub label: Option<String>,
701 impl Default for Span {
702 fn default() -> Self {
707 impl<E: Encoder> Encodable<E> for Span {
708 default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
709 let span = self.data();
710 s.emit_struct("Span", 2, |s| {
711 s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?;
712 s.emit_struct_field("hi", 1, |s| span.hi.encode(s))
716 impl<D: Decoder> Decodable<D> for Span {
717 default fn decode(s: &mut D) -> Result<Span, D::Error> {
718 s.read_struct("Span", 2, |d| {
719 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
720 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
722 Ok(Span::new(lo, hi, SyntaxContext::root()))
727 /// Calls the provided closure, using the provided `SourceMap` to format
728 /// any spans that are debug-printed during the closure'e exectuino.
730 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
731 /// (see `rustc_interface::callbacks::span_debug1). However, some parts
732 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
733 /// a `TyCtxt` is available. In this case, we fall back to
734 /// the `SourceMap` provided to this function. If that is not available,
735 /// we fall back to printing the raw `Span` field values
736 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
737 SESSION_GLOBALS.with(|session_globals| {
738 *session_globals.source_map.borrow_mut() = Some(source_map);
740 struct ClearSourceMap;
741 impl Drop for ClearSourceMap {
743 SESSION_GLOBALS.with(|session_globals| {
744 session_globals.source_map.borrow_mut().take();
749 let _guard = ClearSourceMap;
753 pub fn debug_with_source_map(
755 f: &mut fmt::Formatter<'_>,
756 source_map: &SourceMap,
758 write!(f, "{} ({:?})", source_map.span_to_string(span), span.ctxt())
761 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
762 SESSION_GLOBALS.with(|session_globals| {
763 if let Some(source_map) = &*session_globals.source_map.borrow() {
764 debug_with_source_map(span, f, source_map)
766 f.debug_struct("Span")
767 .field("lo", &span.lo())
768 .field("hi", &span.hi())
769 .field("ctxt", &span.ctxt())
775 impl fmt::Debug for Span {
776 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
777 (*SPAN_DEBUG)(*self, f)
781 impl fmt::Debug for SpanData {
782 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
783 (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
789 pub fn new() -> MultiSpan {
790 MultiSpan { primary_spans: vec![], span_labels: vec![] }
793 pub fn from_span(primary_span: Span) -> MultiSpan {
794 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
797 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
799 MultiSpan { primary_spans: vec, span_labels: vec![] }
802 pub fn push_span_label(&mut self, span: Span, label: String) {
803 self.span_labels.push((span, label));
806 /// Selects the first primary span (if any).
807 pub fn primary_span(&self) -> Option<Span> {
808 self.primary_spans.first().cloned()
811 /// Returns all primary spans.
812 pub fn primary_spans(&self) -> &[Span] {
816 /// Returns `true` if any of the primary spans are displayable.
817 pub fn has_primary_spans(&self) -> bool {
818 self.primary_spans.iter().any(|sp| !sp.is_dummy())
821 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
822 pub fn is_dummy(&self) -> bool {
823 let mut is_dummy = true;
824 for span in &self.primary_spans {
825 if !span.is_dummy() {
832 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
833 /// display well (like std macros). Returns whether replacements occurred.
834 pub fn replace(&mut self, before: Span, after: Span) -> bool {
835 let mut replacements_occurred = false;
836 for primary_span in &mut self.primary_spans {
837 if *primary_span == before {
838 *primary_span = after;
839 replacements_occurred = true;
842 for span_label in &mut self.span_labels {
843 if span_label.0 == before {
844 span_label.0 = after;
845 replacements_occurred = true;
848 replacements_occurred
851 /// Returns the strings to highlight. We always ensure that there
852 /// is an entry for each of the primary spans -- for each primary
853 /// span `P`, if there is at least one label with span `P`, we return
854 /// those labels (marked as primary). But otherwise we return
855 /// `SpanLabel` instances with empty labels.
856 pub fn span_labels(&self) -> Vec<SpanLabel> {
857 let is_primary = |span| self.primary_spans.contains(&span);
859 let mut span_labels = self
862 .map(|&(span, ref label)| SpanLabel {
864 is_primary: is_primary(span),
865 label: Some(label.clone()),
867 .collect::<Vec<_>>();
869 for &span in &self.primary_spans {
870 if !span_labels.iter().any(|sl| sl.span == span) {
871 span_labels.push(SpanLabel { span, is_primary: true, label: None });
878 /// Returns `true` if any of the span labels is displayable.
879 pub fn has_span_labels(&self) -> bool {
880 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
884 impl From<Span> for MultiSpan {
885 fn from(span: Span) -> MultiSpan {
886 MultiSpan::from_span(span)
890 impl From<Vec<Span>> for MultiSpan {
891 fn from(spans: Vec<Span>) -> MultiSpan {
892 MultiSpan::from_spans(spans)
896 /// Identifies an offset of a multi-byte character in a `SourceFile`.
897 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
898 pub struct MultiByteChar {
899 /// The absolute offset of the character in the `SourceMap`.
901 /// The number of bytes, `>= 2`.
905 /// Identifies an offset of a non-narrow character in a `SourceFile`.
906 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
907 pub enum NonNarrowChar {
908 /// Represents a zero-width character.
910 /// Represents a wide (full-width) character.
912 /// Represents a tab character, represented visually with a width of 4 characters.
917 fn new(pos: BytePos, width: usize) -> Self {
919 0 => NonNarrowChar::ZeroWidth(pos),
920 2 => NonNarrowChar::Wide(pos),
921 4 => NonNarrowChar::Tab(pos),
922 _ => panic!("width {} given for non-narrow character", width),
926 /// Returns the absolute offset of the character in the `SourceMap`.
927 pub fn pos(&self) -> BytePos {
929 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
933 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
934 pub fn width(&self) -> usize {
936 NonNarrowChar::ZeroWidth(_) => 0,
937 NonNarrowChar::Wide(_) => 2,
938 NonNarrowChar::Tab(_) => 4,
943 impl Add<BytePos> for NonNarrowChar {
946 fn add(self, rhs: BytePos) -> Self {
948 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
949 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
950 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
955 impl Sub<BytePos> for NonNarrowChar {
958 fn sub(self, rhs: BytePos) -> Self {
960 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
961 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
962 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
967 /// Identifies an offset of a character that was normalized away from `SourceFile`.
968 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
969 pub struct NormalizedPos {
970 /// The absolute offset of the character in the `SourceMap`.
972 /// The difference between original and normalized string at position.
976 #[derive(PartialEq, Eq, Clone, Debug)]
977 pub enum ExternalSource {
978 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
981 kind: ExternalSourceKind,
982 /// This SourceFile's byte-offset within the source_map of its original crate
983 original_start_pos: BytePos,
984 /// The end of this SourceFile within the source_map of its original crate
985 original_end_pos: BytePos,
989 /// The state of the lazy external source loading mechanism of a `SourceFile`.
990 #[derive(PartialEq, Eq, Clone, Debug)]
991 pub enum ExternalSourceKind {
992 /// The external source has been loaded already.
993 Present(Lrc<String>),
994 /// No attempt has been made to load the external source.
996 /// A failed attempt has been made to load the external source.
1001 impl ExternalSource {
1002 pub fn is_absent(&self) -> bool {
1004 ExternalSource::Foreign { kind: ExternalSourceKind::Present(_), .. } => false,
1009 pub fn get_source(&self) -> Option<&Lrc<String>> {
1011 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1018 pub struct OffsetOverflowError;
1020 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1021 pub enum SourceFileHashAlgorithm {
1026 impl FromStr for SourceFileHashAlgorithm {
1029 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1031 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1032 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1038 rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm);
1040 /// The hash of the on-disk source file used for debug info.
1041 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1042 #[derive(HashStable_Generic, Encodable, Decodable)]
1043 pub struct SourceFileHash {
1044 pub kind: SourceFileHashAlgorithm,
1048 impl SourceFileHash {
1049 pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1050 let mut hash = SourceFileHash { kind, value: Default::default() };
1051 let len = hash.hash_len();
1052 let value = &mut hash.value[..len];
1053 let data = src.as_bytes();
1055 SourceFileHashAlgorithm::Md5 => {
1056 value.copy_from_slice(&Md5::digest(data));
1058 SourceFileHashAlgorithm::Sha1 => {
1059 value.copy_from_slice(&Sha1::digest(data));
1065 /// Check if the stored hash matches the hash of the string.
1066 pub fn matches(&self, src: &str) -> bool {
1067 Self::new(self.kind, src) == *self
1070 /// The bytes of the hash.
1071 pub fn hash_bytes(&self) -> &[u8] {
1072 let len = self.hash_len();
1076 fn hash_len(&self) -> usize {
1078 SourceFileHashAlgorithm::Md5 => 16,
1079 SourceFileHashAlgorithm::Sha1 => 20,
1084 /// A single source in the `SourceMap`.
1086 pub struct SourceFile {
1087 /// The name of the file that the source came from. Source that doesn't
1088 /// originate from files has names between angle brackets by convention
1089 /// (e.g., `<anon>`).
1091 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
1092 pub name_was_remapped: bool,
1093 /// The unmapped path of the file that the source came from.
1094 /// Set to `None` if the `SourceFile` was imported from an external crate.
1095 pub unmapped_path: Option<FileName>,
1096 /// The complete source code.
1097 pub src: Option<Lrc<String>>,
1098 /// The source code's hash.
1099 pub src_hash: SourceFileHash,
1100 /// The external source code (used for external crates, which will have a `None`
1101 /// value as `self.src`.
1102 pub external_src: Lock<ExternalSource>,
1103 /// The start position of this source in the `SourceMap`.
1104 pub start_pos: BytePos,
1105 /// The end position of this source in the `SourceMap`.
1106 pub end_pos: BytePos,
1107 /// Locations of lines beginnings in the source code.
1108 pub lines: Vec<BytePos>,
1109 /// Locations of multi-byte characters in the source code.
1110 pub multibyte_chars: Vec<MultiByteChar>,
1111 /// Width of characters that are not narrow in the source code.
1112 pub non_narrow_chars: Vec<NonNarrowChar>,
1113 /// Locations of characters removed during normalization.
1114 pub normalized_pos: Vec<NormalizedPos>,
1115 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1116 pub name_hash: u128,
1117 /// Indicates which crate this `SourceFile` was imported from.
1121 impl<S: Encoder> Encodable<S> for SourceFile {
1122 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1123 s.emit_struct("SourceFile", 8, |s| {
1124 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
1125 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
1126 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
1127 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
1128 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
1129 s.emit_struct_field("lines", 5, |s| {
1130 let lines = &self.lines[..];
1131 // Store the length.
1132 s.emit_u32(lines.len() as u32)?;
1134 if !lines.is_empty() {
1135 // In order to preserve some space, we exploit the fact that
1136 // the lines list is sorted and individual lines are
1137 // probably not that long. Because of that we can store lines
1138 // as a difference list, using as little space as possible
1139 // for the differences.
1140 let max_line_length = if lines.len() == 1 {
1143 lines.windows(2).map(|w| w[1] - w[0]).map(|bp| bp.to_usize()).max().unwrap()
1146 let bytes_per_diff: u8 = match max_line_length {
1148 0x100..=0xFFFF => 2,
1152 // Encode the number of bytes used per diff.
1153 bytes_per_diff.encode(s)?;
1155 // Encode the first element.
1156 lines[0].encode(s)?;
1158 let diff_iter = (&lines[..]).windows(2).map(|w| (w[1] - w[0]));
1160 match bytes_per_diff {
1162 for diff in diff_iter {
1163 (diff.0 as u8).encode(s)?
1167 for diff in diff_iter {
1168 (diff.0 as u16).encode(s)?
1172 for diff in diff_iter {
1176 _ => unreachable!(),
1182 s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
1183 s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
1184 s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
1185 s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))?;
1186 s.emit_struct_field("cnum", 10, |s| self.cnum.encode(s))
1191 impl<D: Decoder> Decodable<D> for SourceFile {
1192 fn decode(d: &mut D) -> Result<SourceFile, D::Error> {
1193 d.read_struct("SourceFile", 8, |d| {
1194 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1195 let name_was_remapped: bool =
1196 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1197 let src_hash: SourceFileHash =
1198 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1199 let start_pos: BytePos =
1200 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1201 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1202 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1203 let num_lines: u32 = Decodable::decode(d)?;
1204 let mut lines = Vec::with_capacity(num_lines as usize);
1207 // Read the number of bytes used per diff.
1208 let bytes_per_diff: u8 = Decodable::decode(d)?;
1210 // Read the first element.
1211 let mut line_start: BytePos = Decodable::decode(d)?;
1212 lines.push(line_start);
1214 for _ in 1..num_lines {
1215 let diff = match bytes_per_diff {
1216 1 => d.read_u8()? as u32,
1217 2 => d.read_u16()? as u32,
1219 _ => unreachable!(),
1222 line_start = line_start + BytePos(diff);
1224 lines.push(line_start);
1230 let multibyte_chars: Vec<MultiByteChar> =
1231 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1232 let non_narrow_chars: Vec<NonNarrowChar> =
1233 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1234 let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1235 let normalized_pos: Vec<NormalizedPos> =
1236 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1237 let cnum: CrateNum = d.read_struct_field("cnum", 10, |d| Decodable::decode(d))?;
1241 unmapped_path: None,
1246 // Unused - the metadata decoder will construct
1247 // a new SourceFile, filling in `external_src` properly
1248 external_src: Lock::new(ExternalSource::Unneeded),
1260 impl fmt::Debug for SourceFile {
1261 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1262 write!(fmt, "SourceFile({})", self.name)
1269 name_was_remapped: bool,
1270 unmapped_path: FileName,
1273 hash_kind: SourceFileHashAlgorithm,
1275 // Compute the file hash before any normalization.
1276 let src_hash = SourceFileHash::new(hash_kind, &src);
1277 let normalized_pos = normalize_src(&mut src, start_pos);
1280 let mut hasher: StableHasher = StableHasher::new();
1281 name.hash(&mut hasher);
1282 hasher.finish::<u128>()
1284 let end_pos = start_pos.to_usize() + src.len();
1285 assert!(end_pos <= u32::MAX as usize);
1287 let (lines, multibyte_chars, non_narrow_chars) =
1288 analyze_source_file::analyze_source_file(&src[..], start_pos);
1293 unmapped_path: Some(unmapped_path),
1294 src: Some(Lrc::new(src)),
1296 external_src: Lock::new(ExternalSource::Unneeded),
1298 end_pos: Pos::from_usize(end_pos),
1308 /// Returns the `BytePos` of the beginning of the current line.
1309 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1310 let line_index = self.lookup_line(pos).unwrap();
1311 self.lines[line_index]
1314 /// Add externally loaded source.
1315 /// If the hash of the input doesn't match or no input is supplied via None,
1316 /// it is interpreted as an error and the corresponding enum variant is set.
1317 /// The return value signifies whether some kind of source is present.
1318 pub fn add_external_src<F>(&self, get_src: F) -> bool
1320 F: FnOnce() -> Option<String>,
1323 *self.external_src.borrow(),
1324 ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1326 let src = get_src();
1327 let mut external_src = self.external_src.borrow_mut();
1328 // Check that no-one else have provided the source while we were getting it
1329 if let ExternalSource::Foreign {
1330 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1331 } = &mut *external_src
1333 if let Some(mut src) = src {
1334 // The src_hash needs to be computed on the pre-normalized src.
1335 if self.src_hash.matches(&src) {
1336 normalize_src(&mut src, BytePos::from_usize(0));
1337 *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1341 *src_kind = ExternalSourceKind::AbsentErr;
1346 self.src.is_some() || external_src.get_source().is_some()
1349 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1353 /// Gets a line from the list of pre-computed line-beginnings.
1354 /// The line number here is 0-based.
1355 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1356 fn get_until_newline(src: &str, begin: usize) -> &str {
1357 // We can't use `lines.get(line_number+1)` because we might
1358 // be parsing when we call this function and thus the current
1359 // line is the last one we have line info for.
1360 let slice = &src[begin..];
1361 match slice.find('\n') {
1362 Some(e) => &slice[..e],
1368 let line = self.lines.get(line_number)?;
1369 let begin: BytePos = *line - self.start_pos;
1373 if let Some(ref src) = self.src {
1374 Some(Cow::from(get_until_newline(src, begin)))
1375 } else if let Some(src) = self.external_src.borrow().get_source() {
1376 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1382 pub fn is_real_file(&self) -> bool {
1386 pub fn is_imported(&self) -> bool {
1390 pub fn byte_length(&self) -> u32 {
1391 self.end_pos.0 - self.start_pos.0
1393 pub fn count_lines(&self) -> usize {
1397 /// Finds the line containing the given position. The return value is the
1398 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1399 /// number. If the source_file is empty or the position is located before the
1400 /// first line, `None` is returned.
1401 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1402 if self.lines.is_empty() {
1406 let line_index = lookup_line(&self.lines[..], pos);
1407 assert!(line_index < self.lines.len() as isize);
1408 if line_index >= 0 { Some(line_index as usize) } else { None }
1411 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1412 if self.start_pos == self.end_pos {
1413 return (self.start_pos, self.end_pos);
1416 assert!(line_index < self.lines.len());
1417 if line_index == (self.lines.len() - 1) {
1418 (self.lines[line_index], self.end_pos)
1420 (self.lines[line_index], self.lines[line_index + 1])
1425 pub fn contains(&self, byte_pos: BytePos) -> bool {
1426 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1429 /// Calculates the original byte position relative to the start of the file
1430 /// based on the given byte position.
1431 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1432 // Diff before any records is 0. Otherwise use the previously recorded
1433 // diff as that applies to the following characters until a new diff
1435 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1436 Ok(i) => self.normalized_pos[i].diff,
1437 Err(i) if i == 0 => 0,
1438 Err(i) => self.normalized_pos[i - 1].diff,
1441 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1445 /// Normalizes the source code and records the normalizations.
1446 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1447 let mut normalized_pos = vec![];
1448 remove_bom(src, &mut normalized_pos);
1449 normalize_newlines(src, &mut normalized_pos);
1451 // Offset all the positions by start_pos to match the final file positions.
1452 for np in &mut normalized_pos {
1453 np.pos.0 += start_pos.0;
1459 /// Removes UTF-8 BOM, if any.
1460 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1461 if src.starts_with("\u{feff}") {
1463 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1467 /// Replaces `\r\n` with `\n` in-place in `src`.
1469 /// Returns error if there's a lone `\r` in the string
1470 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1471 if !src.as_bytes().contains(&b'\r') {
1475 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1476 // While we *can* call `as_mut_vec` and do surgery on the live string
1477 // directly, let's rather steal the contents of `src`. This makes the code
1478 // safe even if a panic occurs.
1480 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1481 let mut gap_len = 0;
1482 let mut tail = buf.as_mut_slice();
1484 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1486 let idx = match find_crlf(&tail[gap_len..]) {
1488 Some(idx) => idx + gap_len,
1490 tail.copy_within(gap_len..idx, 0);
1491 tail = &mut tail[idx - gap_len..];
1492 if tail.len() == gap_len {
1495 cursor += idx - gap_len;
1497 normalized_pos.push(NormalizedPos {
1498 pos: BytePos::from_usize(cursor + 1),
1499 diff: original_gap + gap_len as u32,
1503 // Account for removed `\r`.
1504 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1505 let new_len = buf.len() - gap_len;
1507 buf.set_len(new_len);
1508 *src = String::from_utf8_unchecked(buf);
1511 fn find_crlf(src: &[u8]) -> Option<usize> {
1512 let mut search_idx = 0;
1513 while let Some(idx) = find_cr(&src[search_idx..]) {
1514 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1515 search_idx += idx + 1;
1518 return Some(search_idx + idx);
1523 fn find_cr(src: &[u8]) -> Option<usize> {
1524 src.iter().position(|&b| b == b'\r')
1528 // _____________________________________________________________________________
1529 // Pos, BytePos, CharPos
1533 fn from_usize(n: usize) -> Self;
1534 fn to_usize(&self) -> usize;
1535 fn from_u32(n: u32) -> Self;
1536 fn to_u32(&self) -> u32;
1539 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1541 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1542 pub struct BytePos(pub u32);
1544 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1545 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1546 /// values to `CharPos` values as necessary.
1547 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1548 pub struct CharPos(pub usize);
1550 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1551 // have been unsuccessful.
1553 impl Pos for BytePos {
1555 fn from_usize(n: usize) -> BytePos {
1560 fn to_usize(&self) -> usize {
1565 fn from_u32(n: u32) -> BytePos {
1570 fn to_u32(&self) -> u32 {
1575 impl Add for BytePos {
1576 type Output = BytePos;
1579 fn add(self, rhs: BytePos) -> BytePos {
1580 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1584 impl Sub for BytePos {
1585 type Output = BytePos;
1588 fn sub(self, rhs: BytePos) -> BytePos {
1589 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1593 impl<S: rustc_serialize::Encoder> Encodable<S> for BytePos {
1594 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1599 impl<D: rustc_serialize::Decoder> Decodable<D> for BytePos {
1600 fn decode(d: &mut D) -> Result<BytePos, D::Error> {
1601 Ok(BytePos(d.read_u32()?))
1605 impl Pos for CharPos {
1607 fn from_usize(n: usize) -> CharPos {
1612 fn to_usize(&self) -> usize {
1617 fn from_u32(n: u32) -> CharPos {
1622 fn to_u32(&self) -> u32 {
1627 impl Add for CharPos {
1628 type Output = CharPos;
1631 fn add(self, rhs: CharPos) -> CharPos {
1632 CharPos(self.to_usize() + rhs.to_usize())
1636 impl Sub for CharPos {
1637 type Output = CharPos;
1640 fn sub(self, rhs: CharPos) -> CharPos {
1641 CharPos(self.to_usize() - rhs.to_usize())
1645 // _____________________________________________________________________________
1646 // Loc, SourceFileAndLine, SourceFileAndBytePos
1649 /// A source code location used for error reporting.
1650 #[derive(Debug, Clone)]
1652 /// Information about the original source.
1653 pub file: Lrc<SourceFile>,
1654 /// The (1-based) line number.
1656 /// The (0-based) column offset.
1658 /// The (0-based) column offset when displayed.
1659 pub col_display: usize,
1662 // Used to be structural records.
1664 pub struct SourceFileAndLine {
1665 pub sf: Lrc<SourceFile>,
1669 pub struct SourceFileAndBytePos {
1670 pub sf: Lrc<SourceFile>,
1674 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1675 pub struct LineInfo {
1676 /// Index of line, starting from 0.
1677 pub line_index: usize,
1679 /// Column in line where span begins, starting from 0.
1680 pub start_col: CharPos,
1682 /// Column in line where span ends, starting from 0, exclusive.
1683 pub end_col: CharPos,
1686 pub struct FileLines {
1687 pub file: Lrc<SourceFile>,
1688 pub lines: Vec<LineInfo>,
1691 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1692 AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1694 // _____________________________________________________________________________
1695 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1698 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1700 #[derive(Clone, PartialEq, Eq, Debug)]
1701 pub enum SpanLinesError {
1702 DistinctSources(DistinctSources),
1705 #[derive(Clone, PartialEq, Eq, Debug)]
1706 pub enum SpanSnippetError {
1707 IllFormedSpan(Span),
1708 DistinctSources(DistinctSources),
1709 MalformedForSourcemap(MalformedSourceMapPositions),
1710 SourceNotAvailable { filename: FileName },
1713 #[derive(Clone, PartialEq, Eq, Debug)]
1714 pub struct DistinctSources {
1715 pub begin: (FileName, BytePos),
1716 pub end: (FileName, BytePos),
1719 #[derive(Clone, PartialEq, Eq, Debug)]
1720 pub struct MalformedSourceMapPositions {
1722 pub source_len: usize,
1723 pub begin_pos: BytePos,
1724 pub end_pos: BytePos,
1727 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1728 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1729 pub struct InnerSpan {
1735 pub fn new(start: usize, end: usize) -> InnerSpan {
1736 InnerSpan { start, end }
1740 // Given a slice of line start positions and a position, returns the index of
1741 // the line the position is on. Returns -1 if the position is located before
1743 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1744 match lines.binary_search(&pos) {
1745 Ok(line) => line as isize,
1746 Err(line) => line as isize - 1,
1750 /// Requirements for a `StableHashingContext` to be used in this crate.
1751 /// This is a hack to allow using the `HashStable_Generic` derive macro
1752 /// instead of implementing everything in librustc_middle.
1753 pub trait HashStableContext {
1754 fn hash_def_id(&mut self, _: DefId, hasher: &mut StableHasher);
1755 fn hash_crate_num(&mut self, _: CrateNum, hasher: &mut StableHasher);
1756 fn hash_spans(&self) -> bool;
1757 fn byte_pos_to_line_and_col(
1760 ) -> Option<(Lrc<SourceFile>, usize, BytePos)>;
1763 impl<CTX> HashStable<CTX> for Span
1765 CTX: HashStableContext,
1767 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1768 /// fields (that would be similar to hashing pointers, since those are just
1769 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1770 /// triple, which stays the same even if the containing `SourceFile` has moved
1771 /// within the `SourceMap`.
1772 /// Also note that we are hashing byte offsets for the column, not unicode
1773 /// codepoint offsets. For the purpose of the hash that's sufficient.
1774 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1775 /// span starts and ends in the same file, which is almost always the case.
1776 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1777 const TAG_VALID_SPAN: u8 = 0;
1778 const TAG_INVALID_SPAN: u8 = 1;
1780 if !ctx.hash_spans() {
1784 if *self == DUMMY_SP {
1785 std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1789 // If this is not an empty or invalid span, we want to hash the last
1790 // position that belongs to it, as opposed to hashing the first
1791 // position past it.
1792 let span = self.data();
1793 let (file_lo, line_lo, col_lo) = match ctx.byte_pos_to_line_and_col(span.lo) {
1796 std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1797 span.ctxt.hash_stable(ctx, hasher);
1802 if !file_lo.contains(span.hi) {
1803 std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1804 span.ctxt.hash_stable(ctx, hasher);
1808 std::hash::Hash::hash(&TAG_VALID_SPAN, hasher);
1809 // We truncate the stable ID hash and line and column numbers. The chances
1810 // of causing a collision this way should be minimal.
1811 std::hash::Hash::hash(&(file_lo.name_hash as u64), hasher);
1813 let col = (col_lo.0 as u64) & 0xFF;
1814 let line = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1815 let len = ((span.hi - span.lo).0 as u64) << 32;
1816 let line_col_len = col | line | len;
1817 std::hash::Hash::hash(&line_col_len, hasher);
1818 span.ctxt.hash_stable(ctx, hasher);
1822 impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1823 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1824 const TAG_EXPANSION: u8 = 0;
1825 const TAG_NO_EXPANSION: u8 = 1;
1827 if *self == SyntaxContext::root() {
1828 TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1830 TAG_EXPANSION.hash_stable(ctx, hasher);
1831 let (expn_id, transparency) = self.outer_mark();
1832 expn_id.hash_stable(ctx, hasher);
1833 transparency.hash_stable(ctx, hasher);
1838 impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
1839 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1840 // Since the same expansion context is usually referenced many
1841 // times, we cache a stable hash of it and hash that instead of
1842 // recursing every time.
1844 static CACHE: RefCell<Vec<Option<Fingerprint>>> = Default::default();
1847 const TAG_ROOT: u8 = 0;
1848 const TAG_NOT_ROOT: u8 = 1;
1850 if *self == ExpnId::root() {
1851 TAG_ROOT.hash_stable(ctx, hasher);
1855 TAG_NOT_ROOT.hash_stable(ctx, hasher);
1856 let index = self.as_u32() as usize;
1858 let res = CACHE.with(|cache| cache.borrow().get(index).copied().flatten());
1860 if let Some(res) = res {
1861 res.hash_stable(ctx, hasher);
1863 let new_len = index + 1;
1865 let mut sub_hasher = StableHasher::new();
1866 self.expn_data().hash_stable(ctx, &mut sub_hasher);
1867 let sub_hash: Fingerprint = sub_hasher.finish();
1869 CACHE.with(|cache| {
1870 let mut cache = cache.borrow_mut();
1871 if cache.len() < new_len {
1872 cache.resize(new_len, None);
1874 cache[index].replace(sub_hash).expect_none("Cache slot was filled");
1876 sub_hash.hash_stable(ctx, hasher);