1 //! The source positions and related helper functions.
5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
8 #![feature(array_windows)]
9 #![feature(crate_visibility_modifier)]
11 #![feature(const_panic)]
12 #![feature(negative_impls)]
14 #![feature(min_specialization)]
15 #![feature(option_expect_none)]
18 extern crate rustc_macros;
20 use rustc_data_structures::AtomicRef;
21 use rustc_macros::HashStable_Generic;
22 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
24 mod caching_source_map_view;
26 pub use self::caching_source_map_view::CachingSourceMapView;
27 use source_map::SourceMap;
32 pub use hygiene::SyntaxContext;
33 use hygiene::Transparency;
34 pub use hygiene::{DesugaringKind, ExpnData, ExpnId, ExpnKind, ForLoopLoc, MacroKind};
36 use def_id::{CrateNum, DefId, LOCAL_CRATE};
38 pub use span_encoding::{Span, DUMMY_SP};
41 pub use symbol::{sym, Symbol};
43 mod analyze_source_file;
46 use rustc_data_structures::fingerprint::Fingerprint;
47 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
48 use rustc_data_structures::sync::{Lock, Lrc};
51 use std::cell::RefCell;
52 use std::cmp::{self, Ordering};
55 use std::ops::{Add, Range, Sub};
56 use std::path::{Path, PathBuf};
57 use std::str::FromStr;
68 // Per-session global variables: this struct is stored in thread-local storage
69 // in such a way that it is accessible without any kind of handle to all
70 // threads within the compilation session, but is not accessible outside the
72 pub struct SessionGlobals {
73 symbol_interner: Lock<symbol::Interner>,
74 span_interner: Lock<span_encoding::SpanInterner>,
75 hygiene_data: Lock<hygiene::HygieneData>,
76 source_map: Lock<Option<Lrc<SourceMap>>>,
80 pub fn new(edition: Edition) -> SessionGlobals {
82 symbol_interner: Lock::new(symbol::Interner::fresh()),
83 span_interner: Lock::new(span_encoding::SpanInterner::default()),
84 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
85 source_map: Lock::new(None),
90 pub fn with_session_globals<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
91 let session_globals = SessionGlobals::new(edition);
92 SESSION_GLOBALS.set(&session_globals, f)
95 pub fn with_default_session_globals<R>(f: impl FnOnce() -> R) -> R {
96 with_session_globals(edition::DEFAULT_EDITION, f)
99 // If this ever becomes non thread-local, `decode_syntax_context`
100 // and `decode_expn_id` will need to be updated to handle concurrent
102 scoped_tls::scoped_thread_local!(pub static SESSION_GLOBALS: SessionGlobals);
104 // FIXME: Perhaps this should not implement Rustc{Decodable, Encodable}
106 // FIXME: We should use this enum or something like it to get rid of the
107 // use of magic `/rust/1.x/...` paths across the board.
108 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
109 #[derive(HashStable_Generic, Decodable, Encodable)]
110 pub enum RealFileName {
112 /// For de-virtualized paths (namely paths into libstd that have been mapped
113 /// to the appropriate spot on the local host's file system),
115 /// `local_path` is the (host-dependent) local path to the file.
117 /// `virtual_name` is the stable path rustc will store internally within
119 virtual_name: PathBuf,
124 /// Returns the path suitable for reading from the file system on the local host.
125 /// Avoid embedding this in build artifacts; see `stable_name` for that.
126 pub fn local_path(&self) -> &Path {
128 RealFileName::Named(p)
129 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => &p,
133 /// Returns the path suitable for reading from the file system on the local host.
134 /// Avoid embedding this in build artifacts; see `stable_name` for that.
135 pub fn into_local_path(self) -> PathBuf {
137 RealFileName::Named(p)
138 | RealFileName::Devirtualized { local_path: p, virtual_name: _ } => p,
142 /// Returns the path suitable for embedding into build artifacts. Note that
143 /// a virtualized path will not correspond to a valid file system path; see
144 /// `local_path` for something that is more likely to return paths into the
145 /// local host file system.
146 pub fn stable_name(&self) -> &Path {
148 RealFileName::Named(p)
149 | RealFileName::Devirtualized { local_path: _, virtual_name: p } => &p,
154 /// Differentiates between real files and common virtual files.
155 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
156 #[derive(HashStable_Generic, Decodable, Encodable)]
159 /// Call to `quote!`.
163 /// Hack in `src/librustc_ast/parse.rs`.
166 ProcMacroSourceCode(u64),
167 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
169 /// Strings provided as crate attributes in the CLI.
171 /// Custom sources for explicit parser calls from plugins and drivers.
173 DocTest(PathBuf, isize),
174 /// Post-substitution inline assembly from LLVM
178 impl std::fmt::Display for FileName {
179 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182 Real(RealFileName::Named(ref path)) => write!(fmt, "{}", path.display()),
183 // FIXME: might be nice to display both compoments of Devirtualized.
184 // But for now (to backport fix for issue #70924), best to not
185 // perturb diagnostics so its obvious test suite still works.
186 Real(RealFileName::Devirtualized { ref local_path, virtual_name: _ }) => {
187 write!(fmt, "{}", local_path.display())
189 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
190 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
191 Anon(_) => write!(fmt, "<anon>"),
192 ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
193 CfgSpec(_) => write!(fmt, "<cfgspec>"),
194 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
195 Custom(ref s) => write!(fmt, "<{}>", s),
196 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
197 InlineAsm(_) => write!(fmt, "<inline asm>"),
202 impl From<PathBuf> for FileName {
203 fn from(p: PathBuf) -> Self {
204 assert!(!p.to_string_lossy().ends_with('>'));
205 FileName::Real(RealFileName::Named(p))
210 pub fn is_real(&self) -> bool {
216 | ProcMacroSourceCode(_)
222 | InlineAsm(_) => false,
226 pub fn macro_expansion_source_code(src: &str) -> FileName {
227 let mut hasher = StableHasher::new();
228 src.hash(&mut hasher);
229 FileName::MacroExpansion(hasher.finish())
232 pub fn anon_source_code(src: &str) -> FileName {
233 let mut hasher = StableHasher::new();
234 src.hash(&mut hasher);
235 FileName::Anon(hasher.finish())
238 pub fn proc_macro_source_code(src: &str) -> FileName {
239 let mut hasher = StableHasher::new();
240 src.hash(&mut hasher);
241 FileName::ProcMacroSourceCode(hasher.finish())
244 pub fn cfg_spec_source_code(src: &str) -> FileName {
245 let mut hasher = StableHasher::new();
246 src.hash(&mut hasher);
247 FileName::QuoteExpansion(hasher.finish())
250 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
251 let mut hasher = StableHasher::new();
252 src.hash(&mut hasher);
253 FileName::CliCrateAttr(hasher.finish())
256 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
257 FileName::DocTest(path, line)
260 pub fn inline_asm_source_code(src: &str) -> FileName {
261 let mut hasher = StableHasher::new();
262 src.hash(&mut hasher);
263 FileName::InlineAsm(hasher.finish())
267 /// Spans represent a region of code, used for error reporting. Positions in spans
268 /// are *absolute* positions from the beginning of the source_map, not positions
269 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
270 /// to the original source.
271 /// You must be careful if the span crosses more than one file - you will not be
272 /// able to use many of the functions on spans in source_map and you cannot assume
273 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
274 /// range between files.
276 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
277 /// sent to other threads, but some pieces of performance infra run in a separate thread.
278 /// Using `Span` is generally preferred.
279 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
280 pub struct SpanData {
283 /// Information about where the macro came from, if this piece of
284 /// code was created by a macro expansion.
285 pub ctxt: SyntaxContext,
290 pub fn with_lo(&self, lo: BytePos) -> Span {
291 Span::new(lo, self.hi, self.ctxt)
294 pub fn with_hi(&self, hi: BytePos) -> Span {
295 Span::new(self.lo, hi, self.ctxt)
298 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
299 Span::new(self.lo, self.hi, ctxt)
303 // The interner is pointed to by a thread local value which is only set on the main thread
304 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
305 // to avoid panics and other errors, even though it would be memory safe to do so.
306 #[cfg(not(parallel_compiler))]
307 impl !Send for Span {}
308 #[cfg(not(parallel_compiler))]
309 impl !Sync for Span {}
311 impl PartialOrd for Span {
312 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
313 PartialOrd::partial_cmp(&self.data(), &rhs.data())
317 fn cmp(&self, rhs: &Self) -> Ordering {
318 Ord::cmp(&self.data(), &rhs.data())
322 /// A collection of `Span`s.
324 /// Spans have two orthogonal attributes:
326 /// - They can be *primary spans*. In this case they are the locus of
327 /// the error, and would be rendered with `^^^`.
328 /// - They can have a *label*. In this case, the label is written next
329 /// to the mark in the snippet when we render.
330 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
331 pub struct MultiSpan {
332 primary_spans: Vec<Span>,
333 span_labels: Vec<(Span, String)>,
338 pub fn lo(self) -> BytePos {
342 pub fn with_lo(self, lo: BytePos) -> Span {
343 self.data().with_lo(lo)
346 pub fn hi(self) -> BytePos {
350 pub fn with_hi(self, hi: BytePos) -> Span {
351 self.data().with_hi(hi)
354 pub fn ctxt(self) -> SyntaxContext {
358 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
359 self.data().with_ctxt(ctxt)
362 /// Returns `true` if this is a dummy span with any hygienic context.
364 pub fn is_dummy(self) -> bool {
365 let span = self.data();
366 span.lo.0 == 0 && span.hi.0 == 0
369 /// Returns `true` if this span comes from a macro or desugaring.
371 pub fn from_expansion(self) -> bool {
372 self.ctxt() != SyntaxContext::root()
375 /// Returns `true` if `span` originates in a derive-macro's expansion.
376 pub fn in_derive_expansion(self) -> bool {
377 matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
381 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
382 Span::new(lo, hi, SyntaxContext::root())
385 /// Returns a new span representing an empty span at the beginning of this span
387 pub fn shrink_to_lo(self) -> Span {
388 let span = self.data();
389 span.with_hi(span.lo)
391 /// Returns a new span representing an empty span at the end of this span.
393 pub fn shrink_to_hi(self) -> Span {
394 let span = self.data();
395 span.with_lo(span.hi)
399 /// Returns true if hi == lo
400 pub fn is_empty(&self) -> bool {
401 let span = self.data();
405 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
406 pub fn substitute_dummy(self, other: Span) -> Span {
407 if self.is_dummy() { other } else { self }
410 /// Returns `true` if `self` fully encloses `other`.
411 pub fn contains(self, other: Span) -> bool {
412 let span = self.data();
413 let other = other.data();
414 span.lo <= other.lo && other.hi <= span.hi
417 /// Returns `true` if `self` touches `other`.
418 pub fn overlaps(self, other: Span) -> bool {
419 let span = self.data();
420 let other = other.data();
421 span.lo < other.hi && other.lo < span.hi
424 /// Returns `true` if the spans are equal with regards to the source text.
426 /// Use this instead of `==` when either span could be generated code,
427 /// and you only care that they point to the same bytes of source text.
428 pub fn source_equal(&self, other: &Span) -> bool {
429 let span = self.data();
430 let other = other.data();
431 span.lo == other.lo && span.hi == other.hi
434 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
435 pub fn trim_start(self, other: Span) -> Option<Span> {
436 let span = self.data();
437 let other = other.data();
438 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
441 /// Returns the source span -- this is either the supplied span, or the span for
442 /// the macro callsite that expanded to it.
443 pub fn source_callsite(self) -> Span {
444 let expn_data = self.ctxt().outer_expn_data();
445 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
448 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
450 pub fn parent(self) -> Option<Span> {
451 let expn_data = self.ctxt().outer_expn_data();
452 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
455 /// Edition of the crate from which this span came.
456 pub fn edition(self) -> edition::Edition {
457 self.ctxt().outer_expn_data().edition
461 pub fn rust_2015(&self) -> bool {
462 self.edition() == edition::Edition::Edition2015
466 pub fn rust_2018(&self) -> bool {
467 self.edition() >= edition::Edition::Edition2018
470 /// Returns the source callee.
472 /// Returns `None` if the supplied span has no expansion trace,
473 /// else returns the `ExpnData` for the macro definition
474 /// corresponding to the source callsite.
475 pub fn source_callee(self) -> Option<ExpnData> {
476 fn source_callee(expn_data: ExpnData) -> ExpnData {
477 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
478 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
480 let expn_data = self.ctxt().outer_expn_data();
481 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
484 /// Checks if a span is "internal" to a macro in which `#[unstable]`
485 /// items can be used (that is, a macro marked with
486 /// `#[allow_internal_unstable]`).
487 pub fn allows_unstable(&self, feature: Symbol) -> bool {
488 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
491 .any(|&f| f == feature || f == sym::allow_internal_unstable_backcompat_hack)
495 /// Checks if this span arises from a compiler desugaring of kind `kind`.
496 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
497 match self.ctxt().outer_expn_data().kind {
498 ExpnKind::Desugaring(k) => k == kind,
503 /// Returns the compiler desugaring that created this span, or `None`
504 /// if this span is not from a desugaring.
505 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
506 match self.ctxt().outer_expn_data().kind {
507 ExpnKind::Desugaring(k) => Some(k),
512 /// Checks if a span is "internal" to a macro in which `unsafe`
513 /// can be used without triggering the `unsafe_code` lint
514 // (that is, a macro marked with `#[allow_internal_unsafe]`).
515 pub fn allows_unsafe(&self) -> bool {
516 self.ctxt().outer_expn_data().allow_internal_unsafe
519 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
520 let mut prev_span = DUMMY_SP;
521 std::iter::from_fn(move || {
523 let expn_data = self.ctxt().outer_expn_data();
524 if expn_data.is_root() {
528 let is_recursive = expn_data.call_site.source_equal(&prev_span);
531 self = expn_data.call_site;
533 // Don't print recursive invocations.
535 return Some(expn_data);
541 /// Returns a `Span` that would enclose both `self` and `end`.
545 /// self lorem ipsum end
546 /// ^^^^^^^^^^^^^^^^^^^^
548 pub fn to(self, end: Span) -> Span {
549 let span_data = self.data();
550 let end_data = end.data();
551 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
552 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
553 // have an incomplete span than a completely nonsensical one.
554 if span_data.ctxt != end_data.ctxt {
555 if span_data.ctxt == SyntaxContext::root() {
557 } else if end_data.ctxt == SyntaxContext::root() {
560 // Both spans fall within a macro.
561 // FIXME(estebank): check if it is the *same* macro.
564 cmp::min(span_data.lo, end_data.lo),
565 cmp::max(span_data.hi, end_data.hi),
566 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
570 /// Returns a `Span` between the end of `self` to the beginning of `end`.
574 /// self lorem ipsum end
577 pub fn between(self, end: Span) -> Span {
578 let span = self.data();
579 let end = end.data();
583 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
587 /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
591 /// self lorem ipsum end
592 /// ^^^^^^^^^^^^^^^^^
594 pub fn until(self, end: Span) -> Span {
595 let span = self.data();
596 let end = end.data();
600 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
604 pub fn from_inner(self, inner: InnerSpan) -> Span {
605 let span = self.data();
607 span.lo + BytePos::from_usize(inner.start),
608 span.lo + BytePos::from_usize(inner.end),
613 /// Equivalent of `Span::def_site` from the proc macro API,
614 /// except that the location is taken from the `self` span.
615 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
616 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
619 /// Equivalent of `Span::call_site` from the proc macro API,
620 /// except that the location is taken from the `self` span.
621 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
622 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
625 /// Equivalent of `Span::mixed_site` from the proc macro API,
626 /// except that the location is taken from the `self` span.
627 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
628 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
631 /// Produces a span with the same location as `self` and context produced by a macro with the
632 /// given ID and transparency, assuming that macro was defined directly and not produced by
633 /// some other macro (which is the case for built-in and procedural macros).
634 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
635 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
639 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
640 let span = self.data();
641 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
645 pub fn remove_mark(&mut self) -> ExpnId {
646 let mut span = self.data();
647 let mark = span.ctxt.remove_mark();
648 *self = Span::new(span.lo, span.hi, span.ctxt);
653 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
654 let mut span = self.data();
655 let mark = span.ctxt.adjust(expn_id);
656 *self = Span::new(span.lo, span.hi, span.ctxt);
661 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
662 let mut span = self.data();
663 let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
664 *self = Span::new(span.lo, span.hi, span.ctxt);
669 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
670 let mut span = self.data();
671 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
672 *self = Span::new(span.lo, span.hi, span.ctxt);
677 pub fn reverse_glob_adjust(
681 ) -> Option<Option<ExpnId>> {
682 let mut span = self.data();
683 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
684 *self = Span::new(span.lo, span.hi, span.ctxt);
689 pub fn normalize_to_macros_2_0(self) -> Span {
690 let span = self.data();
691 span.with_ctxt(span.ctxt.normalize_to_macros_2_0())
695 pub fn normalize_to_macro_rules(self) -> Span {
696 let span = self.data();
697 span.with_ctxt(span.ctxt.normalize_to_macro_rules())
701 #[derive(Clone, Debug)]
702 pub struct SpanLabel {
703 /// The span we are going to include in the final snippet.
706 /// Is this a primary span? This is the "locus" of the message,
707 /// and is indicated with a `^^^^` underline, versus `----`.
708 pub is_primary: bool,
710 /// What label should we attach to this span (if any)?
711 pub label: Option<String>,
714 impl Default for Span {
715 fn default() -> Self {
720 impl<E: Encoder> Encodable<E> for Span {
721 default fn encode(&self, s: &mut E) -> Result<(), E::Error> {
722 let span = self.data();
723 s.emit_struct("Span", 2, |s| {
724 s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?;
725 s.emit_struct_field("hi", 1, |s| span.hi.encode(s))
729 impl<D: Decoder> Decodable<D> for Span {
730 default fn decode(s: &mut D) -> Result<Span, D::Error> {
731 s.read_struct("Span", 2, |d| {
732 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
733 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
735 Ok(Span::new(lo, hi, SyntaxContext::root()))
740 /// Calls the provided closure, using the provided `SourceMap` to format
741 /// any spans that are debug-printed during the closure'e exectuino.
743 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
744 /// (see `rustc_interface::callbacks::span_debug1). However, some parts
745 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
746 /// a `TyCtxt` is available. In this case, we fall back to
747 /// the `SourceMap` provided to this function. If that is not available,
748 /// we fall back to printing the raw `Span` field values
749 pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
750 SESSION_GLOBALS.with(|session_globals| {
751 *session_globals.source_map.borrow_mut() = Some(source_map);
753 struct ClearSourceMap;
754 impl Drop for ClearSourceMap {
756 SESSION_GLOBALS.with(|session_globals| {
757 session_globals.source_map.borrow_mut().take();
762 let _guard = ClearSourceMap;
766 pub fn debug_with_source_map(
768 f: &mut fmt::Formatter<'_>,
769 source_map: &SourceMap,
771 write!(f, "{} ({:?})", source_map.span_to_string(span), span.ctxt())
774 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
775 SESSION_GLOBALS.with(|session_globals| {
776 if let Some(source_map) = &*session_globals.source_map.borrow() {
777 debug_with_source_map(span, f, source_map)
779 f.debug_struct("Span")
780 .field("lo", &span.lo())
781 .field("hi", &span.hi())
782 .field("ctxt", &span.ctxt())
788 impl fmt::Debug for Span {
789 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
790 (*SPAN_DEBUG)(*self, f)
794 impl fmt::Debug for SpanData {
795 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
796 (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
802 pub fn new() -> MultiSpan {
803 MultiSpan { primary_spans: vec![], span_labels: vec![] }
806 pub fn from_span(primary_span: Span) -> MultiSpan {
807 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
810 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
812 MultiSpan { primary_spans: vec, span_labels: vec![] }
815 pub fn push_span_label(&mut self, span: Span, label: String) {
816 self.span_labels.push((span, label));
819 /// Selects the first primary span (if any).
820 pub fn primary_span(&self) -> Option<Span> {
821 self.primary_spans.first().cloned()
824 /// Returns all primary spans.
825 pub fn primary_spans(&self) -> &[Span] {
829 /// Returns `true` if any of the primary spans are displayable.
830 pub fn has_primary_spans(&self) -> bool {
831 self.primary_spans.iter().any(|sp| !sp.is_dummy())
834 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
835 pub fn is_dummy(&self) -> bool {
836 let mut is_dummy = true;
837 for span in &self.primary_spans {
838 if !span.is_dummy() {
845 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
846 /// display well (like std macros). Returns whether replacements occurred.
847 pub fn replace(&mut self, before: Span, after: Span) -> bool {
848 let mut replacements_occurred = false;
849 for primary_span in &mut self.primary_spans {
850 if *primary_span == before {
851 *primary_span = after;
852 replacements_occurred = true;
855 for span_label in &mut self.span_labels {
856 if span_label.0 == before {
857 span_label.0 = after;
858 replacements_occurred = true;
861 replacements_occurred
864 /// Returns the strings to highlight. We always ensure that there
865 /// is an entry for each of the primary spans -- for each primary
866 /// span `P`, if there is at least one label with span `P`, we return
867 /// those labels (marked as primary). But otherwise we return
868 /// `SpanLabel` instances with empty labels.
869 pub fn span_labels(&self) -> Vec<SpanLabel> {
870 let is_primary = |span| self.primary_spans.contains(&span);
872 let mut span_labels = self
875 .map(|&(span, ref label)| SpanLabel {
877 is_primary: is_primary(span),
878 label: Some(label.clone()),
880 .collect::<Vec<_>>();
882 for &span in &self.primary_spans {
883 if !span_labels.iter().any(|sl| sl.span == span) {
884 span_labels.push(SpanLabel { span, is_primary: true, label: None });
891 /// Returns `true` if any of the span labels is displayable.
892 pub fn has_span_labels(&self) -> bool {
893 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
897 impl From<Span> for MultiSpan {
898 fn from(span: Span) -> MultiSpan {
899 MultiSpan::from_span(span)
903 impl From<Vec<Span>> for MultiSpan {
904 fn from(spans: Vec<Span>) -> MultiSpan {
905 MultiSpan::from_spans(spans)
909 /// Identifies an offset of a multi-byte character in a `SourceFile`.
910 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
911 pub struct MultiByteChar {
912 /// The absolute offset of the character in the `SourceMap`.
914 /// The number of bytes, `>= 2`.
918 /// Identifies an offset of a non-narrow character in a `SourceFile`.
919 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
920 pub enum NonNarrowChar {
921 /// Represents a zero-width character.
923 /// Represents a wide (full-width) character.
925 /// Represents a tab character, represented visually with a width of 4 characters.
930 fn new(pos: BytePos, width: usize) -> Self {
932 0 => NonNarrowChar::ZeroWidth(pos),
933 2 => NonNarrowChar::Wide(pos),
934 4 => NonNarrowChar::Tab(pos),
935 _ => panic!("width {} given for non-narrow character", width),
939 /// Returns the absolute offset of the character in the `SourceMap`.
940 pub fn pos(&self) -> BytePos {
942 NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
946 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
947 pub fn width(&self) -> usize {
949 NonNarrowChar::ZeroWidth(_) => 0,
950 NonNarrowChar::Wide(_) => 2,
951 NonNarrowChar::Tab(_) => 4,
956 impl Add<BytePos> for NonNarrowChar {
959 fn add(self, rhs: BytePos) -> Self {
961 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
962 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
963 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
968 impl Sub<BytePos> for NonNarrowChar {
971 fn sub(self, rhs: BytePos) -> Self {
973 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
974 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
975 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
980 /// Identifies an offset of a character that was normalized away from `SourceFile`.
981 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
982 pub struct NormalizedPos {
983 /// The absolute offset of the character in the `SourceMap`.
985 /// The difference between original and normalized string at position.
989 #[derive(PartialEq, Eq, Clone, Debug)]
990 pub enum ExternalSource {
991 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
994 kind: ExternalSourceKind,
995 /// This SourceFile's byte-offset within the source_map of its original crate
996 original_start_pos: BytePos,
997 /// The end of this SourceFile within the source_map of its original crate
998 original_end_pos: BytePos,
1002 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1003 #[derive(PartialEq, Eq, Clone, Debug)]
1004 pub enum ExternalSourceKind {
1005 /// The external source has been loaded already.
1006 Present(Lrc<String>),
1007 /// No attempt has been made to load the external source.
1009 /// A failed attempt has been made to load the external source.
1014 impl ExternalSource {
1015 pub fn is_absent(&self) -> bool {
1017 ExternalSource::Foreign { kind: ExternalSourceKind::Present(_), .. } => false,
1022 pub fn get_source(&self) -> Option<&Lrc<String>> {
1024 ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src),
1031 pub struct OffsetOverflowError;
1033 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1034 pub enum SourceFileHashAlgorithm {
1039 impl FromStr for SourceFileHashAlgorithm {
1042 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1044 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1045 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1051 rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm);
1053 /// The hash of the on-disk source file used for debug info.
1054 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1055 #[derive(HashStable_Generic, Encodable, Decodable)]
1056 pub struct SourceFileHash {
1057 pub kind: SourceFileHashAlgorithm,
1061 impl SourceFileHash {
1062 pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash {
1063 let mut hash = SourceFileHash { kind, value: Default::default() };
1064 let len = hash.hash_len();
1065 let value = &mut hash.value[..len];
1066 let data = src.as_bytes();
1068 SourceFileHashAlgorithm::Md5 => {
1069 value.copy_from_slice(&Md5::digest(data));
1071 SourceFileHashAlgorithm::Sha1 => {
1072 value.copy_from_slice(&Sha1::digest(data));
1078 /// Check if the stored hash matches the hash of the string.
1079 pub fn matches(&self, src: &str) -> bool {
1080 Self::new(self.kind, src) == *self
1083 /// The bytes of the hash.
1084 pub fn hash_bytes(&self) -> &[u8] {
1085 let len = self.hash_len();
1089 fn hash_len(&self) -> usize {
1091 SourceFileHashAlgorithm::Md5 => 16,
1092 SourceFileHashAlgorithm::Sha1 => 20,
1097 /// A single source in the `SourceMap`.
1099 pub struct SourceFile {
1100 /// The name of the file that the source came from. Source that doesn't
1101 /// originate from files has names between angle brackets by convention
1102 /// (e.g., `<anon>`).
1104 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
1105 pub name_was_remapped: bool,
1106 /// The unmapped path of the file that the source came from.
1107 /// Set to `None` if the `SourceFile` was imported from an external crate.
1108 pub unmapped_path: Option<FileName>,
1109 /// The complete source code.
1110 pub src: Option<Lrc<String>>,
1111 /// The source code's hash.
1112 pub src_hash: SourceFileHash,
1113 /// The external source code (used for external crates, which will have a `None`
1114 /// value as `self.src`.
1115 pub external_src: Lock<ExternalSource>,
1116 /// The start position of this source in the `SourceMap`.
1117 pub start_pos: BytePos,
1118 /// The end position of this source in the `SourceMap`.
1119 pub end_pos: BytePos,
1120 /// Locations of lines beginnings in the source code.
1121 pub lines: Vec<BytePos>,
1122 /// Locations of multi-byte characters in the source code.
1123 pub multibyte_chars: Vec<MultiByteChar>,
1124 /// Width of characters that are not narrow in the source code.
1125 pub non_narrow_chars: Vec<NonNarrowChar>,
1126 /// Locations of characters removed during normalization.
1127 pub normalized_pos: Vec<NormalizedPos>,
1128 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1129 pub name_hash: u128,
1130 /// Indicates which crate this `SourceFile` was imported from.
1134 impl<S: Encoder> Encodable<S> for SourceFile {
1135 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1136 s.emit_struct("SourceFile", 8, |s| {
1137 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
1138 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
1139 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
1140 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
1141 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
1142 s.emit_struct_field("lines", 5, |s| {
1143 let lines = &self.lines[..];
1144 // Store the length.
1145 s.emit_u32(lines.len() as u32)?;
1147 if !lines.is_empty() {
1148 // In order to preserve some space, we exploit the fact that
1149 // the lines list is sorted and individual lines are
1150 // probably not that long. Because of that we can store lines
1151 // as a difference list, using as little space as possible
1152 // for the differences.
1153 let max_line_length = if lines.len() == 1 {
1158 .map(|&[fst, snd]| snd - fst)
1159 .map(|bp| bp.to_usize())
1164 let bytes_per_diff: u8 = match max_line_length {
1166 0x100..=0xFFFF => 2,
1170 // Encode the number of bytes used per diff.
1171 bytes_per_diff.encode(s)?;
1173 // Encode the first element.
1174 lines[0].encode(s)?;
1176 let diff_iter = lines[..].array_windows().map(|&[fst, snd]| snd - fst);
1178 match bytes_per_diff {
1180 for diff in diff_iter {
1181 (diff.0 as u8).encode(s)?
1185 for diff in diff_iter {
1186 (diff.0 as u16).encode(s)?
1190 for diff in diff_iter {
1194 _ => unreachable!(),
1200 s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
1201 s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
1202 s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
1203 s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))?;
1204 s.emit_struct_field("cnum", 10, |s| self.cnum.encode(s))
1209 impl<D: Decoder> Decodable<D> for SourceFile {
1210 fn decode(d: &mut D) -> Result<SourceFile, D::Error> {
1211 d.read_struct("SourceFile", 8, |d| {
1212 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1213 let name_was_remapped: bool =
1214 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1215 let src_hash: SourceFileHash =
1216 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1217 let start_pos: BytePos =
1218 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1219 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1220 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1221 let num_lines: u32 = Decodable::decode(d)?;
1222 let mut lines = Vec::with_capacity(num_lines as usize);
1225 // Read the number of bytes used per diff.
1226 let bytes_per_diff: u8 = Decodable::decode(d)?;
1228 // Read the first element.
1229 let mut line_start: BytePos = Decodable::decode(d)?;
1230 lines.push(line_start);
1232 for _ in 1..num_lines {
1233 let diff = match bytes_per_diff {
1234 1 => d.read_u8()? as u32,
1235 2 => d.read_u16()? as u32,
1237 _ => unreachable!(),
1240 line_start = line_start + BytePos(diff);
1242 lines.push(line_start);
1248 let multibyte_chars: Vec<MultiByteChar> =
1249 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1250 let non_narrow_chars: Vec<NonNarrowChar> =
1251 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1252 let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1253 let normalized_pos: Vec<NormalizedPos> =
1254 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1255 let cnum: CrateNum = d.read_struct_field("cnum", 10, |d| Decodable::decode(d))?;
1259 unmapped_path: None,
1264 // Unused - the metadata decoder will construct
1265 // a new SourceFile, filling in `external_src` properly
1266 external_src: Lock::new(ExternalSource::Unneeded),
1278 impl fmt::Debug for SourceFile {
1279 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1280 write!(fmt, "SourceFile({})", self.name)
1287 name_was_remapped: bool,
1288 unmapped_path: FileName,
1291 hash_kind: SourceFileHashAlgorithm,
1293 // Compute the file hash before any normalization.
1294 let src_hash = SourceFileHash::new(hash_kind, &src);
1295 let normalized_pos = normalize_src(&mut src, start_pos);
1298 let mut hasher: StableHasher = StableHasher::new();
1299 name.hash(&mut hasher);
1300 hasher.finish::<u128>()
1302 let end_pos = start_pos.to_usize() + src.len();
1303 assert!(end_pos <= u32::MAX as usize);
1305 let (lines, multibyte_chars, non_narrow_chars) =
1306 analyze_source_file::analyze_source_file(&src[..], start_pos);
1311 unmapped_path: Some(unmapped_path),
1312 src: Some(Lrc::new(src)),
1314 external_src: Lock::new(ExternalSource::Unneeded),
1316 end_pos: Pos::from_usize(end_pos),
1326 /// Returns the `BytePos` of the beginning of the current line.
1327 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1328 let line_index = self.lookup_line(pos).unwrap();
1329 self.lines[line_index]
1332 /// Add externally loaded source.
1333 /// If the hash of the input doesn't match or no input is supplied via None,
1334 /// it is interpreted as an error and the corresponding enum variant is set.
1335 /// The return value signifies whether some kind of source is present.
1336 pub fn add_external_src<F>(&self, get_src: F) -> bool
1338 F: FnOnce() -> Option<String>,
1341 *self.external_src.borrow(),
1342 ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1344 let src = get_src();
1345 let mut external_src = self.external_src.borrow_mut();
1346 // Check that no-one else have provided the source while we were getting it
1347 if let ExternalSource::Foreign {
1348 kind: src_kind @ ExternalSourceKind::AbsentOk, ..
1349 } = &mut *external_src
1351 if let Some(mut src) = src {
1352 // The src_hash needs to be computed on the pre-normalized src.
1353 if self.src_hash.matches(&src) {
1354 normalize_src(&mut src, BytePos::from_usize(0));
1355 *src_kind = ExternalSourceKind::Present(Lrc::new(src));
1359 *src_kind = ExternalSourceKind::AbsentErr;
1364 self.src.is_some() || external_src.get_source().is_some()
1367 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1371 /// Gets a line from the list of pre-computed line-beginnings.
1372 /// The line number here is 0-based.
1373 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1374 fn get_until_newline(src: &str, begin: usize) -> &str {
1375 // We can't use `lines.get(line_number+1)` because we might
1376 // be parsing when we call this function and thus the current
1377 // line is the last one we have line info for.
1378 let slice = &src[begin..];
1379 match slice.find('\n') {
1380 Some(e) => &slice[..e],
1386 let line = self.lines.get(line_number)?;
1387 let begin: BytePos = *line - self.start_pos;
1391 if let Some(ref src) = self.src {
1392 Some(Cow::from(get_until_newline(src, begin)))
1393 } else if let Some(src) = self.external_src.borrow().get_source() {
1394 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1400 pub fn is_real_file(&self) -> bool {
1404 pub fn is_imported(&self) -> bool {
1408 pub fn byte_length(&self) -> u32 {
1409 self.end_pos.0 - self.start_pos.0
1411 pub fn count_lines(&self) -> usize {
1415 /// Finds the line containing the given position. The return value is the
1416 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1417 /// number. If the source_file is empty or the position is located before the
1418 /// first line, `None` is returned.
1419 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1420 if self.lines.is_empty() {
1424 let line_index = lookup_line(&self.lines[..], pos);
1425 assert!(line_index < self.lines.len() as isize);
1426 if line_index >= 0 { Some(line_index as usize) } else { None }
1429 pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
1430 if self.is_empty() {
1431 return self.start_pos..self.end_pos;
1434 assert!(line_index < self.lines.len());
1435 if line_index == (self.lines.len() - 1) {
1436 self.lines[line_index]..self.end_pos
1438 self.lines[line_index]..self.lines[line_index + 1]
1442 /// Returns whether or not the file contains the given `SourceMap` byte
1443 /// position. The position one past the end of the file is considered to be
1444 /// contained by the file. This implies that files for which `is_empty`
1445 /// returns true still contain one byte position according to this function.
1447 pub fn contains(&self, byte_pos: BytePos) -> bool {
1448 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1452 pub fn is_empty(&self) -> bool {
1453 self.start_pos == self.end_pos
1456 /// Calculates the original byte position relative to the start of the file
1457 /// based on the given byte position.
1458 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1459 // Diff before any records is 0. Otherwise use the previously recorded
1460 // diff as that applies to the following characters until a new diff
1462 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1463 Ok(i) => self.normalized_pos[i].diff,
1464 Err(i) if i == 0 => 0,
1465 Err(i) => self.normalized_pos[i - 1].diff,
1468 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1471 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1472 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
1473 // The number of extra bytes due to multibyte chars in the `SourceFile`.
1474 let mut total_extra_bytes = 0;
1476 for mbc in self.multibyte_chars.iter() {
1477 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
1479 // Every character is at least one byte, so we only
1480 // count the actual extra bytes.
1481 total_extra_bytes += mbc.bytes as u32 - 1;
1482 // We should never see a byte position in the middle of a
1484 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
1490 assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32());
1491 CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize)
1494 /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1495 /// given `BytePos`.
1496 pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) {
1497 let chpos = self.bytepos_to_file_charpos(pos);
1498 match self.lookup_line(pos) {
1500 let line = a + 1; // Line numbers start at 1
1501 let linebpos = self.lines[a];
1502 let linechpos = self.bytepos_to_file_charpos(linebpos);
1503 let col = chpos - linechpos;
1504 debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
1505 debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
1506 debug!("byte is on line: {}", line);
1507 assert!(chpos >= linechpos);
1514 /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1515 /// column offset when displayed, for a given `BytePos`.
1516 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
1517 let (line, col_or_chpos) = self.lookup_file_pos(pos);
1519 let col = col_or_chpos;
1520 let linebpos = self.lines[line - 1];
1522 let start_width_idx = self
1524 .binary_search_by_key(&linebpos, |x| x.pos())
1525 .unwrap_or_else(|x| x);
1526 let end_width_idx = self
1528 .binary_search_by_key(&pos, |x| x.pos())
1529 .unwrap_or_else(|x| x);
1530 let special_chars = end_width_idx - start_width_idx;
1531 let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx]
1535 col.0 - special_chars + non_narrow
1537 (line, col, col_display)
1539 let chpos = col_or_chpos;
1541 let end_width_idx = self
1543 .binary_search_by_key(&pos, |x| x.pos())
1544 .unwrap_or_else(|x| x);
1545 let non_narrow: usize =
1546 self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum();
1547 chpos.0 - end_width_idx + non_narrow
1549 (0, chpos, col_display)
1554 /// Normalizes the source code and records the normalizations.
1555 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1556 let mut normalized_pos = vec![];
1557 remove_bom(src, &mut normalized_pos);
1558 normalize_newlines(src, &mut normalized_pos);
1560 // Offset all the positions by start_pos to match the final file positions.
1561 for np in &mut normalized_pos {
1562 np.pos.0 += start_pos.0;
1568 /// Removes UTF-8 BOM, if any.
1569 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1570 if src.starts_with("\u{feff}") {
1572 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1576 /// Replaces `\r\n` with `\n` in-place in `src`.
1578 /// Returns error if there's a lone `\r` in the string
1579 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1580 if !src.as_bytes().contains(&b'\r') {
1584 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1585 // While we *can* call `as_mut_vec` and do surgery on the live string
1586 // directly, let's rather steal the contents of `src`. This makes the code
1587 // safe even if a panic occurs.
1589 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1590 let mut gap_len = 0;
1591 let mut tail = buf.as_mut_slice();
1593 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1595 let idx = match find_crlf(&tail[gap_len..]) {
1597 Some(idx) => idx + gap_len,
1599 tail.copy_within(gap_len..idx, 0);
1600 tail = &mut tail[idx - gap_len..];
1601 if tail.len() == gap_len {
1604 cursor += idx - gap_len;
1606 normalized_pos.push(NormalizedPos {
1607 pos: BytePos::from_usize(cursor + 1),
1608 diff: original_gap + gap_len as u32,
1612 // Account for removed `\r`.
1613 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1614 let new_len = buf.len() - gap_len;
1616 buf.set_len(new_len);
1617 *src = String::from_utf8_unchecked(buf);
1620 fn find_crlf(src: &[u8]) -> Option<usize> {
1621 let mut search_idx = 0;
1622 while let Some(idx) = find_cr(&src[search_idx..]) {
1623 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1624 search_idx += idx + 1;
1627 return Some(search_idx + idx);
1632 fn find_cr(src: &[u8]) -> Option<usize> {
1633 src.iter().position(|&b| b == b'\r')
1637 // _____________________________________________________________________________
1638 // Pos, BytePos, CharPos
1642 fn from_usize(n: usize) -> Self;
1643 fn to_usize(&self) -> usize;
1644 fn from_u32(n: u32) -> Self;
1645 fn to_u32(&self) -> u32;
1648 macro_rules! impl_pos {
1652 $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
1657 $vis struct $ident($inner_vis $inner_ty);
1659 impl Pos for $ident {
1661 fn from_usize(n: usize) -> $ident {
1662 $ident(n as $inner_ty)
1666 fn to_usize(&self) -> usize {
1671 fn from_u32(n: u32) -> $ident {
1672 $ident(n as $inner_ty)
1676 fn to_u32(&self) -> u32 {
1681 impl Add for $ident {
1682 type Output = $ident;
1685 fn add(self, rhs: $ident) -> $ident {
1686 $ident(self.0 + rhs.0)
1690 impl Sub for $ident {
1691 type Output = $ident;
1694 fn sub(self, rhs: $ident) -> $ident {
1695 $ident(self.0 - rhs.0)
1703 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1705 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1706 pub struct BytePos(pub u32);
1708 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1709 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1710 /// values to `CharPos` values as necessary.
1711 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1712 pub struct CharPos(pub usize);
1715 impl<S: rustc_serialize::Encoder> Encodable<S> for BytePos {
1716 fn encode(&self, s: &mut S) -> Result<(), S::Error> {
1721 impl<D: rustc_serialize::Decoder> Decodable<D> for BytePos {
1722 fn decode(d: &mut D) -> Result<BytePos, D::Error> {
1723 Ok(BytePos(d.read_u32()?))
1727 // _____________________________________________________________________________
1728 // Loc, SourceFileAndLine, SourceFileAndBytePos
1731 /// A source code location used for error reporting.
1732 #[derive(Debug, Clone)]
1734 /// Information about the original source.
1735 pub file: Lrc<SourceFile>,
1736 /// The (1-based) line number.
1738 /// The (0-based) column offset.
1740 /// The (0-based) column offset when displayed.
1741 pub col_display: usize,
1744 // Used to be structural records.
1746 pub struct SourceFileAndLine {
1747 pub sf: Lrc<SourceFile>,
1751 pub struct SourceFileAndBytePos {
1752 pub sf: Lrc<SourceFile>,
1756 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1757 pub struct LineInfo {
1758 /// Index of line, starting from 0.
1759 pub line_index: usize,
1761 /// Column in line where span begins, starting from 0.
1762 pub start_col: CharPos,
1764 /// Column in line where span ends, starting from 0, exclusive.
1765 pub end_col: CharPos,
1768 pub struct FileLines {
1769 pub file: Lrc<SourceFile>,
1770 pub lines: Vec<LineInfo>,
1773 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1774 AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1776 // _____________________________________________________________________________
1777 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1780 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1782 #[derive(Clone, PartialEq, Eq, Debug)]
1783 pub enum SpanLinesError {
1784 DistinctSources(DistinctSources),
1787 #[derive(Clone, PartialEq, Eq, Debug)]
1788 pub enum SpanSnippetError {
1789 IllFormedSpan(Span),
1790 DistinctSources(DistinctSources),
1791 MalformedForSourcemap(MalformedSourceMapPositions),
1792 SourceNotAvailable { filename: FileName },
1795 #[derive(Clone, PartialEq, Eq, Debug)]
1796 pub struct DistinctSources {
1797 pub begin: (FileName, BytePos),
1798 pub end: (FileName, BytePos),
1801 #[derive(Clone, PartialEq, Eq, Debug)]
1802 pub struct MalformedSourceMapPositions {
1804 pub source_len: usize,
1805 pub begin_pos: BytePos,
1806 pub end_pos: BytePos,
1809 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1810 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1811 pub struct InnerSpan {
1817 pub fn new(start: usize, end: usize) -> InnerSpan {
1818 InnerSpan { start, end }
1822 // Given a slice of line start positions and a position, returns the index of
1823 // the line the position is on. Returns -1 if the position is located before
1825 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1826 match lines.binary_search(&pos) {
1827 Ok(line) => line as isize,
1828 Err(line) => line as isize - 1,
1832 /// Requirements for a `StableHashingContext` to be used in this crate.
1833 /// This is a hack to allow using the `HashStable_Generic` derive macro
1834 /// instead of implementing everything in librustc_middle.
1835 pub trait HashStableContext {
1836 fn hash_def_id(&mut self, _: DefId, hasher: &mut StableHasher);
1837 fn hash_crate_num(&mut self, _: CrateNum, hasher: &mut StableHasher);
1838 fn hash_spans(&self) -> bool;
1839 fn byte_pos_to_line_and_col(
1842 ) -> Option<(Lrc<SourceFile>, usize, BytePos)>;
1845 impl<CTX> HashStable<CTX> for Span
1847 CTX: HashStableContext,
1849 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1850 /// fields (that would be similar to hashing pointers, since those are just
1851 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1852 /// triple, which stays the same even if the containing `SourceFile` has moved
1853 /// within the `SourceMap`.
1854 /// Also note that we are hashing byte offsets for the column, not unicode
1855 /// codepoint offsets. For the purpose of the hash that's sufficient.
1856 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1857 /// span starts and ends in the same file, which is almost always the case.
1858 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1859 const TAG_VALID_SPAN: u8 = 0;
1860 const TAG_INVALID_SPAN: u8 = 1;
1862 if !ctx.hash_spans() {
1866 if *self == DUMMY_SP {
1867 Hash::hash(&TAG_INVALID_SPAN, hasher);
1871 // If this is not an empty or invalid span, we want to hash the last
1872 // position that belongs to it, as opposed to hashing the first
1873 // position past it.
1874 let span = self.data();
1875 let (file_lo, line_lo, col_lo) = match ctx.byte_pos_to_line_and_col(span.lo) {
1878 Hash::hash(&TAG_INVALID_SPAN, hasher);
1879 span.ctxt.hash_stable(ctx, hasher);
1884 if !file_lo.contains(span.hi) {
1885 Hash::hash(&TAG_INVALID_SPAN, hasher);
1886 span.ctxt.hash_stable(ctx, hasher);
1890 Hash::hash(&TAG_VALID_SPAN, hasher);
1891 // We truncate the stable ID hash and line and column numbers. The chances
1892 // of causing a collision this way should be minimal.
1893 Hash::hash(&(file_lo.name_hash as u64), hasher);
1895 let col = (col_lo.0 as u64) & 0xFF;
1896 let line = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1897 let len = ((span.hi - span.lo).0 as u64) << 32;
1898 let line_col_len = col | line | len;
1899 Hash::hash(&line_col_len, hasher);
1900 span.ctxt.hash_stable(ctx, hasher);
1904 impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1905 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1906 const TAG_EXPANSION: u8 = 0;
1907 const TAG_NO_EXPANSION: u8 = 1;
1909 if *self == SyntaxContext::root() {
1910 TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1912 TAG_EXPANSION.hash_stable(ctx, hasher);
1913 let (expn_id, transparency) = self.outer_mark();
1914 expn_id.hash_stable(ctx, hasher);
1915 transparency.hash_stable(ctx, hasher);
1920 impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
1921 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1922 // Since the same expansion context is usually referenced many
1923 // times, we cache a stable hash of it and hash that instead of
1924 // recursing every time.
1926 static CACHE: RefCell<Vec<Option<Fingerprint>>> = Default::default();
1929 const TAG_ROOT: u8 = 0;
1930 const TAG_NOT_ROOT: u8 = 1;
1932 if *self == ExpnId::root() {
1933 TAG_ROOT.hash_stable(ctx, hasher);
1937 TAG_NOT_ROOT.hash_stable(ctx, hasher);
1938 let index = self.as_u32() as usize;
1940 let res = CACHE.with(|cache| cache.borrow().get(index).copied().flatten());
1942 if let Some(res) = res {
1943 res.hash_stable(ctx, hasher);
1945 let new_len = index + 1;
1947 let mut sub_hasher = StableHasher::new();
1948 self.expn_data().hash_stable(ctx, &mut sub_hasher);
1949 let sub_hash: Fingerprint = sub_hasher.finish();
1951 CACHE.with(|cache| {
1952 let mut cache = cache.borrow_mut();
1953 if cache.len() < new_len {
1954 cache.resize(new_len, None);
1956 cache[index].replace(sub_hash).expect_none("Cache slot was filled");
1958 sub_hash.hash_stable(ctx, hasher);