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, Sub}
;
56 use std
::path
::{Path, PathBuf}
;
57 use std
::str::FromStr
;
66 // Per-session global variables: this struct is stored in thread-local storage
67 // in such a way that it is accessible without any kind of handle to all
68 // threads within the compilation session, but is not accessible outside the
70 pub struct SessionGlobals
{
71 symbol_interner
: Lock
<symbol
::Interner
>,
72 span_interner
: Lock
<span_encoding
::SpanInterner
>,
73 hygiene_data
: Lock
<hygiene
::HygieneData
>,
74 source_map
: Lock
<Option
<Lrc
<SourceMap
>>>,
78 pub fn new(edition
: Edition
) -> SessionGlobals
{
80 symbol_interner
: Lock
::new(symbol
::Interner
::fresh()),
81 span_interner
: Lock
::new(span_encoding
::SpanInterner
::default()),
82 hygiene_data
: Lock
::new(hygiene
::HygieneData
::new(edition
)),
83 source_map
: Lock
::new(None
),
88 pub fn with_session_globals
<R
>(edition
: Edition
, f
: impl FnOnce() -> R
) -> R
{
89 let session_globals
= SessionGlobals
::new(edition
);
90 SESSION_GLOBALS
.set(&session_globals
, f
)
93 pub fn with_default_session_globals
<R
>(f
: impl FnOnce() -> R
) -> R
{
94 with_session_globals(edition
::DEFAULT_EDITION
, f
)
97 // If this ever becomes non thread-local, `decode_syntax_context`
98 // and `decode_expn_id` will need to be updated to handle concurrent
100 scoped_tls
::scoped_thread_local
!(pub static SESSION_GLOBALS
: SessionGlobals
);
102 // FIXME: Perhaps this should not implement Rustc{Decodable, Encodable}
104 // FIXME: We should use this enum or something like it to get rid of the
105 // use of magic `/rust/1.x/...` paths across the board.
106 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
107 #[derive(HashStable_Generic, Decodable, Encodable)]
108 pub enum RealFileName
{
110 /// For de-virtualized paths (namely paths into libstd that have been mapped
111 /// to the appropriate spot on the local host's file system),
113 /// `local_path` is the (host-dependent) local path to the file.
115 /// `virtual_name` is the stable path rustc will store internally within
117 virtual_name
: PathBuf
,
122 /// Returns the path suitable for reading from the file system on the local host.
123 /// Avoid embedding this in build artifacts; see `stable_name` for that.
124 pub fn local_path(&self) -> &Path
{
126 RealFileName
::Named(p
)
127 | RealFileName
::Devirtualized { local_path: p, virtual_name: _ }
=> &p
,
131 /// Returns the path suitable for reading from the file system on the local host.
132 /// Avoid embedding this in build artifacts; see `stable_name` for that.
133 pub fn into_local_path(self) -> PathBuf
{
135 RealFileName
::Named(p
)
136 | RealFileName
::Devirtualized { local_path: p, virtual_name: _ }
=> p
,
140 /// Returns the path suitable for embedding into build artifacts. Note that
141 /// a virtualized path will not correspond to a valid file system path; see
142 /// `local_path` for something that is more likely to return paths into the
143 /// local host file system.
144 pub fn stable_name(&self) -> &Path
{
146 RealFileName
::Named(p
)
147 | RealFileName
::Devirtualized { local_path: _, virtual_name: p }
=> &p
,
152 /// Differentiates between real files and common virtual files.
153 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
154 #[derive(HashStable_Generic, Decodable, Encodable)]
157 /// Call to `quote!`.
161 /// Hack in `src/librustc_ast/parse.rs`.
164 ProcMacroSourceCode(u64),
165 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
167 /// Strings provided as crate attributes in the CLI.
169 /// Custom sources for explicit parser calls from plugins and drivers.
171 DocTest(PathBuf
, isize),
172 /// Post-substitution inline assembly from LLVM
176 impl std
::fmt
::Display
for FileName
{
177 fn fmt(&self, fmt
: &mut std
::fmt
::Formatter
<'_
>) -> std
::fmt
::Result
{
180 Real(RealFileName
::Named(ref path
)) => write
!(fmt
, "{}", path
.display()),
181 // FIXME: might be nice to display both compoments of Devirtualized.
182 // But for now (to backport fix for issue #70924), best to not
183 // perturb diagnostics so its obvious test suite still works.
184 Real(RealFileName
::Devirtualized { ref local_path, virtual_name: _ }
) => {
185 write
!(fmt
, "{}", local_path
.display())
187 QuoteExpansion(_
) => write
!(fmt
, "<quote expansion>"),
188 MacroExpansion(_
) => write
!(fmt
, "<macro expansion>"),
189 Anon(_
) => write
!(fmt
, "<anon>"),
190 ProcMacroSourceCode(_
) => write
!(fmt
, "<proc-macro source code>"),
191 CfgSpec(_
) => write
!(fmt
, "<cfgspec>"),
192 CliCrateAttr(_
) => write
!(fmt
, "<crate attribute>"),
193 Custom(ref s
) => write
!(fmt
, "<{}>", s
),
194 DocTest(ref path
, _
) => write
!(fmt
, "{}", path
.display()),
195 InlineAsm(_
) => write
!(fmt
, "<inline asm>"),
200 impl From
<PathBuf
> for FileName
{
201 fn from(p
: PathBuf
) -> Self {
202 assert
!(!p
.to_string_lossy().ends_with('
>'
));
203 FileName
::Real(RealFileName
::Named(p
))
208 pub fn is_real(&self) -> bool
{
214 | ProcMacroSourceCode(_
)
220 | InlineAsm(_
) => false,
224 pub fn quote_expansion_source_code(src
: &str) -> FileName
{
225 let mut hasher
= StableHasher
::new();
226 src
.hash(&mut hasher
);
227 FileName
::QuoteExpansion(hasher
.finish())
230 pub fn macro_expansion_source_code(src
: &str) -> FileName
{
231 let mut hasher
= StableHasher
::new();
232 src
.hash(&mut hasher
);
233 FileName
::MacroExpansion(hasher
.finish())
236 pub fn anon_source_code(src
: &str) -> FileName
{
237 let mut hasher
= StableHasher
::new();
238 src
.hash(&mut hasher
);
239 FileName
::Anon(hasher
.finish())
242 pub fn proc_macro_source_code(src
: &str) -> FileName
{
243 let mut hasher
= StableHasher
::new();
244 src
.hash(&mut hasher
);
245 FileName
::ProcMacroSourceCode(hasher
.finish())
248 pub fn cfg_spec_source_code(src
: &str) -> FileName
{
249 let mut hasher
= StableHasher
::new();
250 src
.hash(&mut hasher
);
251 FileName
::QuoteExpansion(hasher
.finish())
254 pub fn cli_crate_attr_source_code(src
: &str) -> FileName
{
255 let mut hasher
= StableHasher
::new();
256 src
.hash(&mut hasher
);
257 FileName
::CliCrateAttr(hasher
.finish())
260 pub fn doc_test_source_code(path
: PathBuf
, line
: isize) -> FileName
{
261 FileName
::DocTest(path
, line
)
264 pub fn inline_asm_source_code(src
: &str) -> FileName
{
265 let mut hasher
= StableHasher
::new();
266 src
.hash(&mut hasher
);
267 FileName
::InlineAsm(hasher
.finish())
271 /// Spans represent a region of code, used for error reporting. Positions in spans
272 /// are *absolute* positions from the beginning of the source_map, not positions
273 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
274 /// to the original source.
275 /// You must be careful if the span crosses more than one file - you will not be
276 /// able to use many of the functions on spans in source_map and you cannot assume
277 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
278 /// range between files.
280 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
281 /// sent to other threads, but some pieces of performance infra run in a separate thread.
282 /// Using `Span` is generally preferred.
283 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
284 pub struct SpanData
{
287 /// Information about where the macro came from, if this piece of
288 /// code was created by a macro expansion.
289 pub ctxt
: SyntaxContext
,
294 pub fn with_lo(&self, lo
: BytePos
) -> Span
{
295 Span
::new(lo
, self.hi
, self.ctxt
)
298 pub fn with_hi(&self, hi
: BytePos
) -> Span
{
299 Span
::new(self.lo
, hi
, self.ctxt
)
302 pub fn with_ctxt(&self, ctxt
: SyntaxContext
) -> Span
{
303 Span
::new(self.lo
, self.hi
, ctxt
)
307 // The interner is pointed to by a thread local value which is only set on the main thread
308 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
309 // to avoid panics and other errors, even though it would be memory safe to do so.
310 #[cfg(not(parallel_compiler))]
311 impl !Send
for Span {}
312 #[cfg(not(parallel_compiler))]
313 impl !Sync
for Span {}
315 impl PartialOrd
for Span
{
316 fn partial_cmp(&self, rhs
: &Self) -> Option
<Ordering
> {
317 PartialOrd
::partial_cmp(&self.data(), &rhs
.data())
321 fn cmp(&self, rhs
: &Self) -> Ordering
{
322 Ord
::cmp(&self.data(), &rhs
.data())
326 /// A collection of `Span`s.
328 /// Spans have two orthogonal attributes:
330 /// - They can be *primary spans*. In this case they are the locus of
331 /// the error, and would be rendered with `^^^`.
332 /// - They can have a *label*. In this case, the label is written next
333 /// to the mark in the snippet when we render.
334 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
335 pub struct MultiSpan
{
336 primary_spans
: Vec
<Span
>,
337 span_labels
: Vec
<(Span
, String
)>,
342 pub fn lo(self) -> BytePos
{
346 pub fn with_lo(self, lo
: BytePos
) -> Span
{
347 self.data().with_lo(lo
)
350 pub fn hi(self) -> BytePos
{
354 pub fn with_hi(self, hi
: BytePos
) -> Span
{
355 self.data().with_hi(hi
)
358 pub fn ctxt(self) -> SyntaxContext
{
362 pub fn with_ctxt(self, ctxt
: SyntaxContext
) -> Span
{
363 self.data().with_ctxt(ctxt
)
366 /// Returns `true` if this is a dummy span with any hygienic context.
368 pub fn is_dummy(self) -> bool
{
369 let span
= self.data();
370 span
.lo
.0 == 0 && span
.hi
.0 == 0
373 /// Returns `true` if this span comes from a macro or desugaring.
375 pub fn from_expansion(self) -> bool
{
376 self.ctxt() != SyntaxContext
::root()
379 /// Returns `true` if `span` originates in a derive-macro's expansion.
380 pub fn in_derive_expansion(self) -> bool
{
381 matches
!(self.ctxt().outer_expn_data().kind
, ExpnKind
::Macro(MacroKind
::Derive
, _
))
385 pub fn with_root_ctxt(lo
: BytePos
, hi
: BytePos
) -> Span
{
386 Span
::new(lo
, hi
, SyntaxContext
::root())
389 /// Returns a new span representing an empty span at the beginning of this span
391 pub fn shrink_to_lo(self) -> Span
{
392 let span
= self.data();
393 span
.with_hi(span
.lo
)
395 /// Returns a new span representing an empty span at the end of this span.
397 pub fn shrink_to_hi(self) -> Span
{
398 let span
= self.data();
399 span
.with_lo(span
.hi
)
403 /// Returns true if hi == lo
404 pub fn is_empty(&self) -> bool
{
405 let span
= self.data();
409 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
410 pub fn substitute_dummy(self, other
: Span
) -> Span
{
411 if self.is_dummy() { other }
else { self }
414 /// Returns `true` if `self` fully encloses `other`.
415 pub fn contains(self, other
: Span
) -> bool
{
416 let span
= self.data();
417 let other
= other
.data();
418 span
.lo
<= other
.lo
&& other
.hi
<= span
.hi
421 /// Returns `true` if `self` touches `other`.
422 pub fn overlaps(self, other
: Span
) -> bool
{
423 let span
= self.data();
424 let other
= other
.data();
425 span
.lo
< other
.hi
&& other
.lo
< span
.hi
428 /// Returns `true` if the spans are equal with regards to the source text.
430 /// Use this instead of `==` when either span could be generated code,
431 /// and you only care that they point to the same bytes of source text.
432 pub fn source_equal(&self, other
: &Span
) -> bool
{
433 let span
= self.data();
434 let other
= other
.data();
435 span
.lo
== other
.lo
&& span
.hi
== other
.hi
438 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
439 pub fn trim_start(self, other
: Span
) -> Option
<Span
> {
440 let span
= self.data();
441 let other
= other
.data();
442 if span
.hi
> other
.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) }
else { None }
445 /// Returns the source span -- this is either the supplied span, or the span for
446 /// the macro callsite that expanded to it.
447 pub fn source_callsite(self) -> Span
{
448 let expn_data
= self.ctxt().outer_expn_data();
449 if !expn_data
.is_root() { expn_data.call_site.source_callsite() }
else { self }
452 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
454 pub fn parent(self) -> Option
<Span
> {
455 let expn_data
= self.ctxt().outer_expn_data();
456 if !expn_data
.is_root() { Some(expn_data.call_site) }
else { None }
459 /// Edition of the crate from which this span came.
460 pub fn edition(self) -> edition
::Edition
{
461 self.ctxt().outer_expn_data().edition
465 pub fn rust_2015(&self) -> bool
{
466 self.edition() == edition
::Edition
::Edition2015
470 pub fn rust_2018(&self) -> bool
{
471 self.edition() >= edition
::Edition
::Edition2018
474 /// Returns the source callee.
476 /// Returns `None` if the supplied span has no expansion trace,
477 /// else returns the `ExpnData` for the macro definition
478 /// corresponding to the source callsite.
479 pub fn source_callee(self) -> Option
<ExpnData
> {
480 fn source_callee(expn_data
: ExpnData
) -> ExpnData
{
481 let next_expn_data
= expn_data
.call_site
.ctxt().outer_expn_data();
482 if !next_expn_data
.is_root() { source_callee(next_expn_data) }
else { expn_data }
484 let expn_data
= self.ctxt().outer_expn_data();
485 if !expn_data
.is_root() { Some(source_callee(expn_data)) }
else { None }
488 /// Checks if a span is "internal" to a macro in which `#[unstable]`
489 /// items can be used (that is, a macro marked with
490 /// `#[allow_internal_unstable]`).
491 pub fn allows_unstable(&self, feature
: Symbol
) -> bool
{
492 self.ctxt().outer_expn_data().allow_internal_unstable
.map_or(false, |features
| {
495 .any(|&f
| f
== feature
|| f
== sym
::allow_internal_unstable_backcompat_hack
)
499 /// Checks if this span arises from a compiler desugaring of kind `kind`.
500 pub fn is_desugaring(&self, kind
: DesugaringKind
) -> bool
{
501 match self.ctxt().outer_expn_data().kind
{
502 ExpnKind
::Desugaring(k
) => k
== kind
,
507 /// Returns the compiler desugaring that created this span, or `None`
508 /// if this span is not from a desugaring.
509 pub fn desugaring_kind(&self) -> Option
<DesugaringKind
> {
510 match self.ctxt().outer_expn_data().kind
{
511 ExpnKind
::Desugaring(k
) => Some(k
),
516 /// Checks if a span is "internal" to a macro in which `unsafe`
517 /// can be used without triggering the `unsafe_code` lint
518 // (that is, a macro marked with `#[allow_internal_unsafe]`).
519 pub fn allows_unsafe(&self) -> bool
{
520 self.ctxt().outer_expn_data().allow_internal_unsafe
523 pub fn macro_backtrace(mut self) -> impl Iterator
<Item
= ExpnData
> {
524 let mut prev_span
= DUMMY_SP
;
525 std
::iter
::from_fn(move || {
527 let expn_data
= self.ctxt().outer_expn_data();
528 if expn_data
.is_root() {
532 let is_recursive
= expn_data
.call_site
.source_equal(&prev_span
);
535 self = expn_data
.call_site
;
537 // Don't print recursive invocations.
539 return Some(expn_data
);
545 /// Returns a `Span` that would enclose both `self` and `end`.
549 /// self lorem ipsum end
550 /// ^^^^^^^^^^^^^^^^^^^^
552 pub fn to(self, end
: Span
) -> Span
{
553 let span_data
= self.data();
554 let end_data
= end
.data();
555 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
556 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
557 // have an incomplete span than a completely nonsensical one.
558 if span_data
.ctxt
!= end_data
.ctxt
{
559 if span_data
.ctxt
== SyntaxContext
::root() {
561 } else if end_data
.ctxt
== SyntaxContext
::root() {
564 // Both spans fall within a macro.
565 // FIXME(estebank): check if it is the *same* macro.
568 cmp
::min(span_data
.lo
, end_data
.lo
),
569 cmp
::max(span_data
.hi
, end_data
.hi
),
570 if span_data
.ctxt
== SyntaxContext
::root() { end_data.ctxt }
else { span_data.ctxt }
,
574 /// Returns a `Span` between the end of `self` to the beginning of `end`.
578 /// self lorem ipsum end
581 pub fn between(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 /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
595 /// self lorem ipsum end
596 /// ^^^^^^^^^^^^^^^^^
598 pub fn until(self, end
: Span
) -> Span
{
599 let span
= self.data();
600 let end
= end
.data();
604 if end
.ctxt
== SyntaxContext
::root() { end.ctxt }
else { span.ctxt }
,
608 pub fn from_inner(self, inner
: InnerSpan
) -> Span
{
609 let span
= self.data();
611 span
.lo
+ BytePos
::from_usize(inner
.start
),
612 span
.lo
+ BytePos
::from_usize(inner
.end
),
617 /// Equivalent of `Span::def_site` from the proc macro API,
618 /// except that the location is taken from the `self` span.
619 pub fn with_def_site_ctxt(self, expn_id
: ExpnId
) -> Span
{
620 self.with_ctxt_from_mark(expn_id
, Transparency
::Opaque
)
623 /// Equivalent of `Span::call_site` from the proc macro API,
624 /// except that the location is taken from the `self` span.
625 pub fn with_call_site_ctxt(&self, expn_id
: ExpnId
) -> Span
{
626 self.with_ctxt_from_mark(expn_id
, Transparency
::Transparent
)
629 /// Equivalent of `Span::mixed_site` from the proc macro API,
630 /// except that the location is taken from the `self` span.
631 pub fn with_mixed_site_ctxt(&self, expn_id
: ExpnId
) -> Span
{
632 self.with_ctxt_from_mark(expn_id
, Transparency
::SemiTransparent
)
635 /// Produces a span with the same location as `self` and context produced by a macro with the
636 /// given ID and transparency, assuming that macro was defined directly and not produced by
637 /// some other macro (which is the case for built-in and procedural macros).
638 pub fn with_ctxt_from_mark(self, expn_id
: ExpnId
, transparency
: Transparency
) -> Span
{
639 self.with_ctxt(SyntaxContext
::root().apply_mark(expn_id
, transparency
))
643 pub fn apply_mark(self, expn_id
: ExpnId
, transparency
: Transparency
) -> Span
{
644 let span
= self.data();
645 span
.with_ctxt(span
.ctxt
.apply_mark(expn_id
, transparency
))
649 pub fn remove_mark(&mut self) -> ExpnId
{
650 let mut span
= self.data();
651 let mark
= span
.ctxt
.remove_mark();
652 *self = Span
::new(span
.lo
, span
.hi
, span
.ctxt
);
657 pub fn adjust(&mut self, expn_id
: ExpnId
) -> Option
<ExpnId
> {
658 let mut span
= self.data();
659 let mark
= span
.ctxt
.adjust(expn_id
);
660 *self = Span
::new(span
.lo
, span
.hi
, span
.ctxt
);
665 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id
: ExpnId
) -> Option
<ExpnId
> {
666 let mut span
= self.data();
667 let mark
= span
.ctxt
.normalize_to_macros_2_0_and_adjust(expn_id
);
668 *self = Span
::new(span
.lo
, span
.hi
, span
.ctxt
);
673 pub fn glob_adjust(&mut self, expn_id
: ExpnId
, glob_span
: Span
) -> Option
<Option
<ExpnId
>> {
674 let mut span
= self.data();
675 let mark
= span
.ctxt
.glob_adjust(expn_id
, glob_span
);
676 *self = Span
::new(span
.lo
, span
.hi
, span
.ctxt
);
681 pub fn reverse_glob_adjust(
685 ) -> Option
<Option
<ExpnId
>> {
686 let mut span
= self.data();
687 let mark
= span
.ctxt
.reverse_glob_adjust(expn_id
, glob_span
);
688 *self = Span
::new(span
.lo
, span
.hi
, span
.ctxt
);
693 pub fn normalize_to_macros_2_0(self) -> Span
{
694 let span
= self.data();
695 span
.with_ctxt(span
.ctxt
.normalize_to_macros_2_0())
699 pub fn normalize_to_macro_rules(self) -> Span
{
700 let span
= self.data();
701 span
.with_ctxt(span
.ctxt
.normalize_to_macro_rules())
705 #[derive(Clone, Debug)]
706 pub struct SpanLabel
{
707 /// The span we are going to include in the final snippet.
710 /// Is this a primary span? This is the "locus" of the message,
711 /// and is indicated with a `^^^^` underline, versus `----`.
712 pub is_primary
: bool
,
714 /// What label should we attach to this span (if any)?
715 pub label
: Option
<String
>,
718 impl Default
for Span
{
719 fn default() -> Self {
724 impl<E
: Encoder
> Encodable
<E
> for Span
{
725 default fn encode(&self, s
: &mut E
) -> Result
<(), E
::Error
> {
726 let span
= self.data();
727 s
.emit_struct("Span", 2, |s
| {
728 s
.emit_struct_field("lo", 0, |s
| span
.lo
.encode(s
))?
;
729 s
.emit_struct_field("hi", 1, |s
| span
.hi
.encode(s
))
733 impl<D
: Decoder
> Decodable
<D
> for Span
{
734 default fn decode(s
: &mut D
) -> Result
<Span
, D
::Error
> {
735 s
.read_struct("Span", 2, |d
| {
736 let lo
= d
.read_struct_field("lo", 0, Decodable
::decode
)?
;
737 let hi
= d
.read_struct_field("hi", 1, Decodable
::decode
)?
;
739 Ok(Span
::new(lo
, hi
, SyntaxContext
::root()))
744 /// Calls the provided closure, using the provided `SourceMap` to format
745 /// any spans that are debug-printed during the closure'e exectuino.
747 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
748 /// (see `rustc_interface::callbacks::span_debug1). However, some parts
749 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
750 /// a `TyCtxt` is available. In this case, we fall back to
751 /// the `SourceMap` provided to this function. If that is not available,
752 /// we fall back to printing the raw `Span` field values
753 pub fn with_source_map
<T
, F
: FnOnce() -> T
>(source_map
: Lrc
<SourceMap
>, f
: F
) -> T
{
754 SESSION_GLOBALS
.with(|session_globals
| {
755 *session_globals
.source_map
.borrow_mut() = Some(source_map
);
757 struct ClearSourceMap
;
758 impl Drop
for ClearSourceMap
{
760 SESSION_GLOBALS
.with(|session_globals
| {
761 session_globals
.source_map
.borrow_mut().take();
766 let _guard
= ClearSourceMap
;
770 pub fn debug_with_source_map(
772 f
: &mut fmt
::Formatter
<'_
>,
773 source_map
: &SourceMap
,
775 write
!(f
, "{} ({:?})", source_map
.span_to_string(span
), span
.ctxt())
778 pub fn default_span_debug(span
: Span
, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
779 SESSION_GLOBALS
.with(|session_globals
| {
780 if let Some(source_map
) = &*session_globals
.source_map
.borrow() {
781 debug_with_source_map(span
, f
, source_map
)
783 f
.debug_struct("Span")
784 .field("lo", &span
.lo())
785 .field("hi", &span
.hi())
786 .field("ctxt", &span
.ctxt())
792 impl fmt
::Debug
for Span
{
793 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
794 (*SPAN_DEBUG
)(*self, f
)
798 impl fmt
::Debug
for SpanData
{
799 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
800 (*SPAN_DEBUG
)(Span
::new(self.lo
, self.hi
, self.ctxt
), f
)
806 pub fn new() -> MultiSpan
{
807 MultiSpan { primary_spans: vec![], span_labels: vec![] }
810 pub fn from_span(primary_span
: Span
) -> MultiSpan
{
811 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
814 pub fn from_spans(mut vec
: Vec
<Span
>) -> MultiSpan
{
816 MultiSpan { primary_spans: vec, span_labels: vec![] }
819 pub fn push_span_label(&mut self, span
: Span
, label
: String
) {
820 self.span_labels
.push((span
, label
));
823 /// Selects the first primary span (if any).
824 pub fn primary_span(&self) -> Option
<Span
> {
825 self.primary_spans
.first().cloned()
828 /// Returns all primary spans.
829 pub fn primary_spans(&self) -> &[Span
] {
833 /// Returns `true` if any of the primary spans are displayable.
834 pub fn has_primary_spans(&self) -> bool
{
835 self.primary_spans
.iter().any(|sp
| !sp
.is_dummy())
838 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
839 pub fn is_dummy(&self) -> bool
{
840 let mut is_dummy
= true;
841 for span
in &self.primary_spans
{
842 if !span
.is_dummy() {
849 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
850 /// display well (like std macros). Returns whether replacements occurred.
851 pub fn replace(&mut self, before
: Span
, after
: Span
) -> bool
{
852 let mut replacements_occurred
= false;
853 for primary_span
in &mut self.primary_spans
{
854 if *primary_span
== before
{
855 *primary_span
= after
;
856 replacements_occurred
= true;
859 for span_label
in &mut self.span_labels
{
860 if span_label
.0 == before
{
861 span_label
.0 = after
;
862 replacements_occurred
= true;
865 replacements_occurred
868 /// Returns the strings to highlight. We always ensure that there
869 /// is an entry for each of the primary spans -- for each primary
870 /// span `P`, if there is at least one label with span `P`, we return
871 /// those labels (marked as primary). But otherwise we return
872 /// `SpanLabel` instances with empty labels.
873 pub fn span_labels(&self) -> Vec
<SpanLabel
> {
874 let is_primary
= |span
| self.primary_spans
.contains(&span
);
876 let mut span_labels
= self
879 .map(|&(span
, ref label
)| SpanLabel
{
881 is_primary
: is_primary(span
),
882 label
: Some(label
.clone()),
884 .collect
::<Vec
<_
>>();
886 for &span
in &self.primary_spans
{
887 if !span_labels
.iter().any(|sl
| sl
.span
== span
) {
888 span_labels
.push(SpanLabel { span, is_primary: true, label: None }
);
895 /// Returns `true` if any of the span labels is displayable.
896 pub fn has_span_labels(&self) -> bool
{
897 self.span_labels
.iter().any(|(sp
, _
)| !sp
.is_dummy())
901 impl From
<Span
> for MultiSpan
{
902 fn from(span
: Span
) -> MultiSpan
{
903 MultiSpan
::from_span(span
)
907 impl From
<Vec
<Span
>> for MultiSpan
{
908 fn from(spans
: Vec
<Span
>) -> MultiSpan
{
909 MultiSpan
::from_spans(spans
)
913 /// Identifies an offset of a multi-byte character in a `SourceFile`.
914 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
915 pub struct MultiByteChar
{
916 /// The absolute offset of the character in the `SourceMap`.
918 /// The number of bytes, `>= 2`.
922 /// Identifies an offset of a non-narrow character in a `SourceFile`.
923 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
924 pub enum NonNarrowChar
{
925 /// Represents a zero-width character.
927 /// Represents a wide (full-width) character.
929 /// Represents a tab character, represented visually with a width of 4 characters.
934 fn new(pos
: BytePos
, width
: usize) -> Self {
936 0 => NonNarrowChar
::ZeroWidth(pos
),
937 2 => NonNarrowChar
::Wide(pos
),
938 4 => NonNarrowChar
::Tab(pos
),
939 _
=> panic
!("width {} given for non-narrow character", width
),
943 /// Returns the absolute offset of the character in the `SourceMap`.
944 pub fn pos(&self) -> BytePos
{
946 NonNarrowChar
::ZeroWidth(p
) | NonNarrowChar
::Wide(p
) | NonNarrowChar
::Tab(p
) => p
,
950 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
951 pub fn width(&self) -> usize {
953 NonNarrowChar
::ZeroWidth(_
) => 0,
954 NonNarrowChar
::Wide(_
) => 2,
955 NonNarrowChar
::Tab(_
) => 4,
960 impl Add
<BytePos
> for NonNarrowChar
{
963 fn add(self, rhs
: BytePos
) -> Self {
965 NonNarrowChar
::ZeroWidth(pos
) => NonNarrowChar
::ZeroWidth(pos
+ rhs
),
966 NonNarrowChar
::Wide(pos
) => NonNarrowChar
::Wide(pos
+ rhs
),
967 NonNarrowChar
::Tab(pos
) => NonNarrowChar
::Tab(pos
+ rhs
),
972 impl Sub
<BytePos
> for NonNarrowChar
{
975 fn sub(self, rhs
: BytePos
) -> Self {
977 NonNarrowChar
::ZeroWidth(pos
) => NonNarrowChar
::ZeroWidth(pos
- rhs
),
978 NonNarrowChar
::Wide(pos
) => NonNarrowChar
::Wide(pos
- rhs
),
979 NonNarrowChar
::Tab(pos
) => NonNarrowChar
::Tab(pos
- rhs
),
984 /// Identifies an offset of a character that was normalized away from `SourceFile`.
985 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
986 pub struct NormalizedPos
{
987 /// The absolute offset of the character in the `SourceMap`.
989 /// The difference between original and normalized string at position.
993 #[derive(PartialEq, Eq, Clone, Debug)]
994 pub enum ExternalSource
{
995 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
998 kind
: ExternalSourceKind
,
999 /// This SourceFile's byte-offset within the source_map of its original crate
1000 original_start_pos
: BytePos
,
1001 /// The end of this SourceFile within the source_map of its original crate
1002 original_end_pos
: BytePos
,
1006 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1007 #[derive(PartialEq, Eq, Clone, Debug)]
1008 pub enum ExternalSourceKind
{
1009 /// The external source has been loaded already.
1010 Present(Lrc
<String
>),
1011 /// No attempt has been made to load the external source.
1013 /// A failed attempt has been made to load the external source.
1018 impl ExternalSource
{
1019 pub fn is_absent(&self) -> bool
{
1021 ExternalSource
::Foreign { kind: ExternalSourceKind::Present(_), .. }
=> false,
1026 pub fn get_source(&self) -> Option
<&Lrc
<String
>> {
1028 ExternalSource
::Foreign { kind: ExternalSourceKind::Present(ref src), .. }
=> Some(src
),
1035 pub struct OffsetOverflowError
;
1037 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1038 pub enum SourceFileHashAlgorithm
{
1043 impl FromStr
for SourceFileHashAlgorithm
{
1046 fn from_str(s
: &str) -> Result
<SourceFileHashAlgorithm
, ()> {
1048 "md5" => Ok(SourceFileHashAlgorithm
::Md5
),
1049 "sha1" => Ok(SourceFileHashAlgorithm
::Sha1
),
1055 rustc_data_structures
::impl_stable_hash_via_hash
!(SourceFileHashAlgorithm
);
1057 /// The hash of the on-disk source file used for debug info.
1058 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1059 #[derive(HashStable_Generic, Encodable, Decodable)]
1060 pub struct SourceFileHash
{
1061 pub kind
: SourceFileHashAlgorithm
,
1065 impl SourceFileHash
{
1066 pub fn new(kind
: SourceFileHashAlgorithm
, src
: &str) -> SourceFileHash
{
1067 let mut hash
= SourceFileHash { kind, value: Default::default() }
;
1068 let len
= hash
.hash_len();
1069 let value
= &mut hash
.value
[..len
];
1070 let data
= src
.as_bytes();
1072 SourceFileHashAlgorithm
::Md5
=> {
1073 value
.copy_from_slice(&Md5
::digest(data
));
1075 SourceFileHashAlgorithm
::Sha1
=> {
1076 value
.copy_from_slice(&Sha1
::digest(data
));
1082 /// Check if the stored hash matches the hash of the string.
1083 pub fn matches(&self, src
: &str) -> bool
{
1084 Self::new(self.kind
, src
) == *self
1087 /// The bytes of the hash.
1088 pub fn hash_bytes(&self) -> &[u8] {
1089 let len
= self.hash_len();
1093 fn hash_len(&self) -> usize {
1095 SourceFileHashAlgorithm
::Md5
=> 16,
1096 SourceFileHashAlgorithm
::Sha1
=> 20,
1101 /// A single source in the `SourceMap`.
1103 pub struct SourceFile
{
1104 /// The name of the file that the source came from. Source that doesn't
1105 /// originate from files has names between angle brackets by convention
1106 /// (e.g., `<anon>`).
1108 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
1109 pub name_was_remapped
: bool
,
1110 /// The unmapped path of the file that the source came from.
1111 /// Set to `None` if the `SourceFile` was imported from an external crate.
1112 pub unmapped_path
: Option
<FileName
>,
1113 /// The complete source code.
1114 pub src
: Option
<Lrc
<String
>>,
1115 /// The source code's hash.
1116 pub src_hash
: SourceFileHash
,
1117 /// The external source code (used for external crates, which will have a `None`
1118 /// value as `self.src`.
1119 pub external_src
: Lock
<ExternalSource
>,
1120 /// The start position of this source in the `SourceMap`.
1121 pub start_pos
: BytePos
,
1122 /// The end position of this source in the `SourceMap`.
1123 pub end_pos
: BytePos
,
1124 /// Locations of lines beginnings in the source code.
1125 pub lines
: Vec
<BytePos
>,
1126 /// Locations of multi-byte characters in the source code.
1127 pub multibyte_chars
: Vec
<MultiByteChar
>,
1128 /// Width of characters that are not narrow in the source code.
1129 pub non_narrow_chars
: Vec
<NonNarrowChar
>,
1130 /// Locations of characters removed during normalization.
1131 pub normalized_pos
: Vec
<NormalizedPos
>,
1132 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1133 pub name_hash
: u128
,
1134 /// Indicates which crate this `SourceFile` was imported from.
1138 impl<S
: Encoder
> Encodable
<S
> for SourceFile
{
1139 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
1140 s
.emit_struct("SourceFile", 8, |s
| {
1141 s
.emit_struct_field("name", 0, |s
| self.name
.encode(s
))?
;
1142 s
.emit_struct_field("name_was_remapped", 1, |s
| self.name_was_remapped
.encode(s
))?
;
1143 s
.emit_struct_field("src_hash", 2, |s
| self.src_hash
.encode(s
))?
;
1144 s
.emit_struct_field("start_pos", 3, |s
| self.start_pos
.encode(s
))?
;
1145 s
.emit_struct_field("end_pos", 4, |s
| self.end_pos
.encode(s
))?
;
1146 s
.emit_struct_field("lines", 5, |s
| {
1147 let lines
= &self.lines
[..];
1148 // Store the length.
1149 s
.emit_u32(lines
.len() as u32)?
;
1151 if !lines
.is_empty() {
1152 // In order to preserve some space, we exploit the fact that
1153 // the lines list is sorted and individual lines are
1154 // probably not that long. Because of that we can store lines
1155 // as a difference list, using as little space as possible
1156 // for the differences.
1157 let max_line_length
= if lines
.len() == 1 {
1162 .map(|&[fst
, snd
]| snd
- fst
)
1163 .map(|bp
| bp
.to_usize())
1168 let bytes_per_diff
: u8 = match max_line_length
{
1170 0x100..=0xFFFF => 2,
1174 // Encode the number of bytes used per diff.
1175 bytes_per_diff
.encode(s
)?
;
1177 // Encode the first element.
1178 lines
[0].encode(s
)?
;
1180 let diff_iter
= lines
[..].array_windows().map(|&[fst
, snd
]| snd
- fst
);
1182 match bytes_per_diff
{
1184 for diff
in diff_iter
{
1185 (diff
.0 as u8).encode(s
)?
1189 for diff
in diff_iter
{
1190 (diff
.0 as u16).encode(s
)?
1194 for diff
in diff_iter
{
1198 _
=> unreachable
!(),
1204 s
.emit_struct_field("multibyte_chars", 6, |s
| self.multibyte_chars
.encode(s
))?
;
1205 s
.emit_struct_field("non_narrow_chars", 7, |s
| self.non_narrow_chars
.encode(s
))?
;
1206 s
.emit_struct_field("name_hash", 8, |s
| self.name_hash
.encode(s
))?
;
1207 s
.emit_struct_field("normalized_pos", 9, |s
| self.normalized_pos
.encode(s
))?
;
1208 s
.emit_struct_field("cnum", 10, |s
| self.cnum
.encode(s
))
1213 impl<D
: Decoder
> Decodable
<D
> for SourceFile
{
1214 fn decode(d
: &mut D
) -> Result
<SourceFile
, D
::Error
> {
1215 d
.read_struct("SourceFile", 8, |d
| {
1216 let name
: FileName
= d
.read_struct_field("name", 0, |d
| Decodable
::decode(d
))?
;
1217 let name_was_remapped
: bool
=
1218 d
.read_struct_field("name_was_remapped", 1, |d
| Decodable
::decode(d
))?
;
1219 let src_hash
: SourceFileHash
=
1220 d
.read_struct_field("src_hash", 2, |d
| Decodable
::decode(d
))?
;
1221 let start_pos
: BytePos
=
1222 d
.read_struct_field("start_pos", 3, |d
| Decodable
::decode(d
))?
;
1223 let end_pos
: BytePos
= d
.read_struct_field("end_pos", 4, |d
| Decodable
::decode(d
))?
;
1224 let lines
: Vec
<BytePos
> = d
.read_struct_field("lines", 5, |d
| {
1225 let num_lines
: u32 = Decodable
::decode(d
)?
;
1226 let mut lines
= Vec
::with_capacity(num_lines
as usize);
1229 // Read the number of bytes used per diff.
1230 let bytes_per_diff
: u8 = Decodable
::decode(d
)?
;
1232 // Read the first element.
1233 let mut line_start
: BytePos
= Decodable
::decode(d
)?
;
1234 lines
.push(line_start
);
1236 for _
in 1..num_lines
{
1237 let diff
= match bytes_per_diff
{
1238 1 => d
.read_u8()?
as u32,
1239 2 => d
.read_u16()?
as u32,
1241 _
=> unreachable
!(),
1244 line_start
= line_start
+ BytePos(diff
);
1246 lines
.push(line_start
);
1252 let multibyte_chars
: Vec
<MultiByteChar
> =
1253 d
.read_struct_field("multibyte_chars", 6, |d
| Decodable
::decode(d
))?
;
1254 let non_narrow_chars
: Vec
<NonNarrowChar
> =
1255 d
.read_struct_field("non_narrow_chars", 7, |d
| Decodable
::decode(d
))?
;
1256 let name_hash
: u128
= d
.read_struct_field("name_hash", 8, |d
| Decodable
::decode(d
))?
;
1257 let normalized_pos
: Vec
<NormalizedPos
> =
1258 d
.read_struct_field("normalized_pos", 9, |d
| Decodable
::decode(d
))?
;
1259 let cnum
: CrateNum
= d
.read_struct_field("cnum", 10, |d
| Decodable
::decode(d
))?
;
1263 unmapped_path
: None
,
1268 // Unused - the metadata decoder will construct
1269 // a new SourceFile, filling in `external_src` properly
1270 external_src
: Lock
::new(ExternalSource
::Unneeded
),
1282 impl fmt
::Debug
for SourceFile
{
1283 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1284 write
!(fmt
, "SourceFile({})", self.name
)
1291 name_was_remapped
: bool
,
1292 unmapped_path
: FileName
,
1295 hash_kind
: SourceFileHashAlgorithm
,
1297 // Compute the file hash before any normalization.
1298 let src_hash
= SourceFileHash
::new(hash_kind
, &src
);
1299 let normalized_pos
= normalize_src(&mut src
, start_pos
);
1302 let mut hasher
: StableHasher
= StableHasher
::new();
1303 name
.hash(&mut hasher
);
1304 hasher
.finish
::<u128
>()
1306 let end_pos
= start_pos
.to_usize() + src
.len();
1307 assert
!(end_pos
<= u32::MAX
as usize);
1309 let (lines
, multibyte_chars
, non_narrow_chars
) =
1310 analyze_source_file
::analyze_source_file(&src
[..], start_pos
);
1315 unmapped_path
: Some(unmapped_path
),
1316 src
: Some(Lrc
::new(src
)),
1318 external_src
: Lock
::new(ExternalSource
::Unneeded
),
1320 end_pos
: Pos
::from_usize(end_pos
),
1330 /// Returns the `BytePos` of the beginning of the current line.
1331 pub fn line_begin_pos(&self, pos
: BytePos
) -> BytePos
{
1332 let line_index
= self.lookup_line(pos
).unwrap();
1333 self.lines
[line_index
]
1336 /// Add externally loaded source.
1337 /// If the hash of the input doesn't match or no input is supplied via None,
1338 /// it is interpreted as an error and the corresponding enum variant is set.
1339 /// The return value signifies whether some kind of source is present.
1340 pub fn add_external_src
<F
>(&self, get_src
: F
) -> bool
1342 F
: FnOnce() -> Option
<String
>,
1345 *self.external_src
.borrow(),
1346 ExternalSource
::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1348 let src
= get_src();
1349 let mut external_src
= self.external_src
.borrow_mut();
1350 // Check that no-one else have provided the source while we were getting it
1351 if let ExternalSource
::Foreign
{
1352 kind
: src_kind @ ExternalSourceKind
::AbsentOk
, ..
1353 } = &mut *external_src
1355 if let Some(mut src
) = src
{
1356 // The src_hash needs to be computed on the pre-normalized src.
1357 if self.src_hash
.matches(&src
) {
1358 normalize_src(&mut src
, BytePos
::from_usize(0));
1359 *src_kind
= ExternalSourceKind
::Present(Lrc
::new(src
));
1363 *src_kind
= ExternalSourceKind
::AbsentErr
;
1368 self.src
.is_some() || external_src
.get_source().is_some()
1371 self.src
.is_some() || self.external_src
.borrow().get_source().is_some()
1375 /// Gets a line from the list of pre-computed line-beginnings.
1376 /// The line number here is 0-based.
1377 pub fn get_line(&self, line_number
: usize) -> Option
<Cow
<'_
, str>> {
1378 fn get_until_newline(src
: &str, begin
: usize) -> &str {
1379 // We can't use `lines.get(line_number+1)` because we might
1380 // be parsing when we call this function and thus the current
1381 // line is the last one we have line info for.
1382 let slice
= &src
[begin
..];
1383 match slice
.find('
\n'
) {
1384 Some(e
) => &slice
[..e
],
1390 let line
= self.lines
.get(line_number
)?
;
1391 let begin
: BytePos
= *line
- self.start_pos
;
1395 if let Some(ref src
) = self.src
{
1396 Some(Cow
::from(get_until_newline(src
, begin
)))
1397 } else if let Some(src
) = self.external_src
.borrow().get_source() {
1398 Some(Cow
::Owned(String
::from(get_until_newline(src
, begin
))))
1404 pub fn is_real_file(&self) -> bool
{
1408 pub fn is_imported(&self) -> bool
{
1412 pub fn byte_length(&self) -> u32 {
1413 self.end_pos
.0 - self.start_pos
.0
1415 pub fn count_lines(&self) -> usize {
1419 /// Finds the line containing the given position. The return value is the
1420 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1421 /// number. If the source_file is empty or the position is located before the
1422 /// first line, `None` is returned.
1423 pub fn lookup_line(&self, pos
: BytePos
) -> Option
<usize> {
1424 if self.lines
.is_empty() {
1428 let line_index
= lookup_line(&self.lines
[..], pos
);
1429 assert
!(line_index
< self.lines
.len() as isize);
1430 if line_index
>= 0 { Some(line_index as usize) }
else { None }
1433 pub fn line_bounds(&self, line_index
: usize) -> (BytePos
, BytePos
) {
1434 if self.start_pos
== self.end_pos
{
1435 return (self.start_pos
, self.end_pos
);
1438 assert
!(line_index
< self.lines
.len());
1439 if line_index
== (self.lines
.len() - 1) {
1440 (self.lines
[line_index
], self.end_pos
)
1442 (self.lines
[line_index
], self.lines
[line_index
+ 1])
1447 pub fn contains(&self, byte_pos
: BytePos
) -> bool
{
1448 byte_pos
>= self.start_pos
&& byte_pos
<= self.end_pos
1451 /// Calculates the original byte position relative to the start of the file
1452 /// based on the given byte position.
1453 pub fn original_relative_byte_pos(&self, pos
: BytePos
) -> BytePos
{
1454 // Diff before any records is 0. Otherwise use the previously recorded
1455 // diff as that applies to the following characters until a new diff
1457 let diff
= match self.normalized_pos
.binary_search_by(|np
| np
.pos
.cmp(&pos
)) {
1458 Ok(i
) => self.normalized_pos
[i
].diff
,
1459 Err(i
) if i
== 0 => 0,
1460 Err(i
) => self.normalized_pos
[i
- 1].diff
,
1463 BytePos
::from_u32(pos
.0 - self.start_pos
.0 + diff
)
1467 /// Normalizes the source code and records the normalizations.
1468 fn normalize_src(src
: &mut String
, start_pos
: BytePos
) -> Vec
<NormalizedPos
> {
1469 let mut normalized_pos
= vec
![];
1470 remove_bom(src
, &mut normalized_pos
);
1471 normalize_newlines(src
, &mut normalized_pos
);
1473 // Offset all the positions by start_pos to match the final file positions.
1474 for np
in &mut normalized_pos
{
1475 np
.pos
.0 += start_pos
.0;
1481 /// Removes UTF-8 BOM, if any.
1482 fn remove_bom(src
: &mut String
, normalized_pos
: &mut Vec
<NormalizedPos
>) {
1483 if src
.starts_with("\u{feff}") {
1485 normalized_pos
.push(NormalizedPos { pos: BytePos(0), diff: 3 }
);
1489 /// Replaces `\r\n` with `\n` in-place in `src`.
1491 /// Returns error if there's a lone `\r` in the string
1492 fn normalize_newlines(src
: &mut String
, normalized_pos
: &mut Vec
<NormalizedPos
>) {
1493 if !src
.as_bytes().contains(&b'
\r'
) {
1497 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1498 // While we *can* call `as_mut_vec` and do surgery on the live string
1499 // directly, let's rather steal the contents of `src`. This makes the code
1500 // safe even if a panic occurs.
1502 let mut buf
= std
::mem
::replace(src
, String
::new()).into_bytes();
1503 let mut gap_len
= 0;
1504 let mut tail
= buf
.as_mut_slice();
1506 let original_gap
= normalized_pos
.last().map_or(0, |l
| l
.diff
);
1508 let idx
= match find_crlf(&tail
[gap_len
..]) {
1510 Some(idx
) => idx
+ gap_len
,
1512 tail
.copy_within(gap_len
..idx
, 0);
1513 tail
= &mut tail
[idx
- gap_len
..];
1514 if tail
.len() == gap_len
{
1517 cursor
+= idx
- gap_len
;
1519 normalized_pos
.push(NormalizedPos
{
1520 pos
: BytePos
::from_usize(cursor
+ 1),
1521 diff
: original_gap
+ gap_len
as u32,
1525 // Account for removed `\r`.
1526 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1527 let new_len
= buf
.len() - gap_len
;
1529 buf
.set_len(new_len
);
1530 *src
= String
::from_utf8_unchecked(buf
);
1533 fn find_crlf(src
: &[u8]) -> Option
<usize> {
1534 let mut search_idx
= 0;
1535 while let Some(idx
) = find_cr(&src
[search_idx
..]) {
1536 if src
[search_idx
..].get(idx
+ 1) != Some(&b'
\n'
) {
1537 search_idx
+= idx
+ 1;
1540 return Some(search_idx
+ idx
);
1545 fn find_cr(src
: &[u8]) -> Option
<usize> {
1546 src
.iter().position(|&b
| b
== b'
\r'
)
1550 // _____________________________________________________________________________
1551 // Pos, BytePos, CharPos
1555 fn from_usize(n
: usize) -> Self;
1556 fn to_usize(&self) -> usize;
1557 fn from_u32(n
: u32) -> Self;
1558 fn to_u32(&self) -> u32;
1561 macro_rules
! impl_pos
{
1565 $vis
:vis
struct $ident
:ident($inner_vis
:vis $inner_ty
:ty
);
1570 $vis
struct $
ident($inner_vis $inner_ty
);
1572 impl Pos
for $ident
{
1574 fn from_usize(n
: usize) -> $ident
{
1575 $
ident(n
as $inner_ty
)
1579 fn to_usize(&self) -> usize {
1584 fn from_u32(n
: u32) -> $ident
{
1585 $
ident(n
as $inner_ty
)
1589 fn to_u32(&self) -> u32 {
1594 impl Add
for $ident
{
1595 type Output
= $ident
;
1598 fn add(self, rhs
: $ident
) -> $ident
{
1599 $
ident(self.0 + rhs
.0)
1603 impl Sub
for $ident
{
1604 type Output
= $ident
;
1607 fn sub(self, rhs
: $ident
) -> $ident
{
1608 $
ident(self.0 - rhs
.0)
1616 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1618 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1619 pub struct BytePos(pub u32);
1621 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1622 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1623 /// values to `CharPos` values as necessary.
1624 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1625 pub struct CharPos(pub usize);
1628 impl<S
: rustc_serialize
::Encoder
> Encodable
<S
> for BytePos
{
1629 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
1634 impl<D
: rustc_serialize
::Decoder
> Decodable
<D
> for BytePos
{
1635 fn decode(d
: &mut D
) -> Result
<BytePos
, D
::Error
> {
1636 Ok(BytePos(d
.read_u32()?
))
1640 // _____________________________________________________________________________
1641 // Loc, SourceFileAndLine, SourceFileAndBytePos
1644 /// A source code location used for error reporting.
1645 #[derive(Debug, Clone)]
1647 /// Information about the original source.
1648 pub file
: Lrc
<SourceFile
>,
1649 /// The (1-based) line number.
1651 /// The (0-based) column offset.
1653 /// The (0-based) column offset when displayed.
1654 pub col_display
: usize,
1657 // Used to be structural records.
1659 pub struct SourceFileAndLine
{
1660 pub sf
: Lrc
<SourceFile
>,
1664 pub struct SourceFileAndBytePos
{
1665 pub sf
: Lrc
<SourceFile
>,
1669 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1670 pub struct LineInfo
{
1671 /// Index of line, starting from 0.
1672 pub line_index
: usize,
1674 /// Column in line where span begins, starting from 0.
1675 pub start_col
: CharPos
,
1677 /// Column in line where span ends, starting from 0, exclusive.
1678 pub end_col
: CharPos
,
1681 pub struct FileLines
{
1682 pub file
: Lrc
<SourceFile
>,
1683 pub lines
: Vec
<LineInfo
>,
1686 pub static SPAN_DEBUG
: AtomicRef
<fn(Span
, &mut fmt
::Formatter
<'_
>) -> fmt
::Result
> =
1687 AtomicRef
::new(&(default_span_debug
as fn(_
, &mut fmt
::Formatter
<'_
>) -> _
));
1689 // _____________________________________________________________________________
1690 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1693 pub type FileLinesResult
= Result
<FileLines
, SpanLinesError
>;
1695 #[derive(Clone, PartialEq, Eq, Debug)]
1696 pub enum SpanLinesError
{
1697 DistinctSources(DistinctSources
),
1700 #[derive(Clone, PartialEq, Eq, Debug)]
1701 pub enum SpanSnippetError
{
1702 IllFormedSpan(Span
),
1703 DistinctSources(DistinctSources
),
1704 MalformedForSourcemap(MalformedSourceMapPositions
),
1705 SourceNotAvailable { filename: FileName }
,
1708 #[derive(Clone, PartialEq, Eq, Debug)]
1709 pub struct DistinctSources
{
1710 pub begin
: (FileName
, BytePos
),
1711 pub end
: (FileName
, BytePos
),
1714 #[derive(Clone, PartialEq, Eq, Debug)]
1715 pub struct MalformedSourceMapPositions
{
1717 pub source_len
: usize,
1718 pub begin_pos
: BytePos
,
1719 pub end_pos
: BytePos
,
1722 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1723 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1724 pub struct InnerSpan
{
1730 pub fn new(start
: usize, end
: usize) -> InnerSpan
{
1731 InnerSpan { start, end }
1735 // Given a slice of line start positions and a position, returns the index of
1736 // the line the position is on. Returns -1 if the position is located before
1738 fn lookup_line(lines
: &[BytePos
], pos
: BytePos
) -> isize {
1739 match lines
.binary_search(&pos
) {
1740 Ok(line
) => line
as isize,
1741 Err(line
) => line
as isize - 1,
1745 /// Requirements for a `StableHashingContext` to be used in this crate.
1746 /// This is a hack to allow using the `HashStable_Generic` derive macro
1747 /// instead of implementing everything in librustc_middle.
1748 pub trait HashStableContext
{
1749 fn hash_def_id(&mut self, _
: DefId
, hasher
: &mut StableHasher
);
1750 fn hash_crate_num(&mut self, _
: CrateNum
, hasher
: &mut StableHasher
);
1751 fn hash_spans(&self) -> bool
;
1752 fn byte_pos_to_line_and_col(
1755 ) -> Option
<(Lrc
<SourceFile
>, usize, BytePos
)>;
1758 impl<CTX
> HashStable
<CTX
> for Span
1760 CTX
: HashStableContext
,
1762 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1763 /// fields (that would be similar to hashing pointers, since those are just
1764 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1765 /// triple, which stays the same even if the containing `SourceFile` has moved
1766 /// within the `SourceMap`.
1767 /// Also note that we are hashing byte offsets for the column, not unicode
1768 /// codepoint offsets. For the purpose of the hash that's sufficient.
1769 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1770 /// span starts and ends in the same file, which is almost always the case.
1771 fn hash_stable(&self, ctx
: &mut CTX
, hasher
: &mut StableHasher
) {
1772 const TAG_VALID_SPAN
: u8 = 0;
1773 const TAG_INVALID_SPAN
: u8 = 1;
1775 if !ctx
.hash_spans() {
1779 if *self == DUMMY_SP
{
1780 std
::hash
::Hash
::hash(&TAG_INVALID_SPAN
, hasher
);
1784 // If this is not an empty or invalid span, we want to hash the last
1785 // position that belongs to it, as opposed to hashing the first
1786 // position past it.
1787 let span
= self.data();
1788 let (file_lo
, line_lo
, col_lo
) = match ctx
.byte_pos_to_line_and_col(span
.lo
) {
1791 std
::hash
::Hash
::hash(&TAG_INVALID_SPAN
, hasher
);
1792 span
.ctxt
.hash_stable(ctx
, hasher
);
1797 if !file_lo
.contains(span
.hi
) {
1798 std
::hash
::Hash
::hash(&TAG_INVALID_SPAN
, hasher
);
1799 span
.ctxt
.hash_stable(ctx
, hasher
);
1803 std
::hash
::Hash
::hash(&TAG_VALID_SPAN
, hasher
);
1804 // We truncate the stable ID hash and line and column numbers. The chances
1805 // of causing a collision this way should be minimal.
1806 std
::hash
::Hash
::hash(&(file_lo
.name_hash
as u64), hasher
);
1808 let col
= (col_lo
.0 as u64) & 0xFF;
1809 let line
= ((line_lo
as u64) & 0xFF_FF_FF) << 8;
1810 let len
= ((span
.hi
- span
.lo
).0 as u64) << 32;
1811 let line_col_len
= col
| line
| len
;
1812 std
::hash
::Hash
::hash(&line_col_len
, hasher
);
1813 span
.ctxt
.hash_stable(ctx
, hasher
);
1817 impl<CTX
: HashStableContext
> HashStable
<CTX
> for SyntaxContext
{
1818 fn hash_stable(&self, ctx
: &mut CTX
, hasher
: &mut StableHasher
) {
1819 const TAG_EXPANSION
: u8 = 0;
1820 const TAG_NO_EXPANSION
: u8 = 1;
1822 if *self == SyntaxContext
::root() {
1823 TAG_NO_EXPANSION
.hash_stable(ctx
, hasher
);
1825 TAG_EXPANSION
.hash_stable(ctx
, hasher
);
1826 let (expn_id
, transparency
) = self.outer_mark();
1827 expn_id
.hash_stable(ctx
, hasher
);
1828 transparency
.hash_stable(ctx
, hasher
);
1833 impl<CTX
: HashStableContext
> HashStable
<CTX
> for ExpnId
{
1834 fn hash_stable(&self, ctx
: &mut CTX
, hasher
: &mut StableHasher
) {
1835 // Since the same expansion context is usually referenced many
1836 // times, we cache a stable hash of it and hash that instead of
1837 // recursing every time.
1839 static CACHE
: RefCell
<Vec
<Option
<Fingerprint
>>> = Default
::default();
1842 const TAG_ROOT
: u8 = 0;
1843 const TAG_NOT_ROOT
: u8 = 1;
1845 if *self == ExpnId
::root() {
1846 TAG_ROOT
.hash_stable(ctx
, hasher
);
1850 TAG_NOT_ROOT
.hash_stable(ctx
, hasher
);
1851 let index
= self.as_u32() as usize;
1853 let res
= CACHE
.with(|cache
| cache
.borrow().get(index
).copied().flatten());
1855 if let Some(res
) = res
{
1856 res
.hash_stable(ctx
, hasher
);
1858 let new_len
= index
+ 1;
1860 let mut sub_hasher
= StableHasher
::new();
1861 self.expn_data().hash_stable(ctx
, &mut sub_hasher
);
1862 let sub_hash
: Fingerprint
= sub_hasher
.finish();
1864 CACHE
.with(|cache
| {
1865 let mut cache
= cache
.borrow_mut();
1866 if cache
.len() < new_len
{
1867 cache
.resize(new_len
, None
);
1869 cache
[index
].replace(sub_hash
).expect_none("Cache slot was filled");
1871 sub_hash
.hash_stable(ctx
, hasher
);