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
;
69 // Per-session global variables: this struct is stored in thread-local storage
70 // in such a way that it is accessible without any kind of handle to all
71 // threads within the compilation session, but is not accessible outside the
73 pub struct SessionGlobals
{
74 symbol_interner
: Lock
<symbol
::Interner
>,
75 span_interner
: Lock
<span_encoding
::SpanInterner
>,
76 hygiene_data
: Lock
<hygiene
::HygieneData
>,
77 source_map
: Lock
<Option
<Lrc
<SourceMap
>>>,
81 pub fn new(edition
: Edition
) -> SessionGlobals
{
83 symbol_interner
: Lock
::new(symbol
::Interner
::fresh()),
84 span_interner
: Lock
::new(span_encoding
::SpanInterner
::default()),
85 hygiene_data
: Lock
::new(hygiene
::HygieneData
::new(edition
)),
86 source_map
: Lock
::new(None
),
91 pub fn with_session_globals
<R
>(edition
: Edition
, f
: impl FnOnce() -> R
) -> R
{
92 let session_globals
= SessionGlobals
::new(edition
);
93 SESSION_GLOBALS
.set(&session_globals
, f
)
96 pub fn with_default_session_globals
<R
>(f
: impl FnOnce() -> R
) -> R
{
97 with_session_globals(edition
::DEFAULT_EDITION
, f
)
100 // If this ever becomes non thread-local, `decode_syntax_context`
101 // and `decode_expn_id` will need to be updated to handle concurrent
103 scoped_tls
::scoped_thread_local
!(pub static SESSION_GLOBALS
: SessionGlobals
);
105 // FIXME: Perhaps this should not implement Rustc{Decodable, Encodable}
107 // FIXME: We should use this enum or something like it to get rid of the
108 // use of magic `/rust/1.x/...` paths across the board.
109 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
110 #[derive(HashStable_Generic, Decodable, Encodable)]
111 pub enum RealFileName
{
113 /// For de-virtualized paths (namely paths into libstd that have been mapped
114 /// to the appropriate spot on the local host's file system),
116 /// `local_path` is the (host-dependent) local path to the file.
118 /// `virtual_name` is the stable path rustc will store internally within
120 virtual_name
: PathBuf
,
125 /// Returns the path suitable for reading from the file system on the local host.
126 /// Avoid embedding this in build artifacts; see `stable_name` for that.
127 pub fn local_path(&self) -> &Path
{
129 RealFileName
::Named(p
)
130 | RealFileName
::Devirtualized { local_path: p, virtual_name: _ }
=> &p
,
134 /// Returns the path suitable for reading from the file system on the local host.
135 /// Avoid embedding this in build artifacts; see `stable_name` for that.
136 pub fn into_local_path(self) -> PathBuf
{
138 RealFileName
::Named(p
)
139 | RealFileName
::Devirtualized { local_path: p, virtual_name: _ }
=> p
,
143 /// Returns the path suitable for embedding into build artifacts. Note that
144 /// a virtualized path will not correspond to a valid file system path; see
145 /// `local_path` for something that is more likely to return paths into the
146 /// local host file system.
147 pub fn stable_name(&self) -> &Path
{
149 RealFileName
::Named(p
)
150 | RealFileName
::Devirtualized { local_path: _, virtual_name: p }
=> &p
,
155 /// Differentiates between real files and common virtual files.
156 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)]
157 #[derive(HashStable_Generic, Decodable, Encodable)]
160 /// Call to `quote!`.
164 /// Hack in `src/librustc_ast/parse.rs`.
167 ProcMacroSourceCode(u64),
168 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
170 /// Strings provided as crate attributes in the CLI.
172 /// Custom sources for explicit parser calls from plugins and drivers.
174 DocTest(PathBuf
, isize),
175 /// Post-substitution inline assembly from LLVM
179 impl std
::fmt
::Display
for FileName
{
180 fn fmt(&self, fmt
: &mut std
::fmt
::Formatter
<'_
>) -> std
::fmt
::Result
{
183 Real(RealFileName
::Named(ref path
)) => write
!(fmt
, "{}", path
.display()),
184 // FIXME: might be nice to display both compoments of Devirtualized.
185 // But for now (to backport fix for issue #70924), best to not
186 // perturb diagnostics so its obvious test suite still works.
187 Real(RealFileName
::Devirtualized { ref local_path, virtual_name: _ }
) => {
188 write
!(fmt
, "{}", local_path
.display())
190 QuoteExpansion(_
) => write
!(fmt
, "<quote expansion>"),
191 MacroExpansion(_
) => write
!(fmt
, "<macro expansion>"),
192 Anon(_
) => write
!(fmt
, "<anon>"),
193 ProcMacroSourceCode(_
) => write
!(fmt
, "<proc-macro source code>"),
194 CfgSpec(_
) => write
!(fmt
, "<cfgspec>"),
195 CliCrateAttr(_
) => write
!(fmt
, "<crate attribute>"),
196 Custom(ref s
) => write
!(fmt
, "<{}>", s
),
197 DocTest(ref path
, _
) => write
!(fmt
, "{}", path
.display()),
198 InlineAsm(_
) => write
!(fmt
, "<inline asm>"),
203 impl From
<PathBuf
> for FileName
{
204 fn from(p
: PathBuf
) -> Self {
205 assert
!(!p
.to_string_lossy().ends_with('
>'
));
206 FileName
::Real(RealFileName
::Named(p
))
211 pub fn is_real(&self) -> bool
{
217 | ProcMacroSourceCode(_
)
223 | InlineAsm(_
) => false,
227 pub fn macro_expansion_source_code(src
: &str) -> FileName
{
228 let mut hasher
= StableHasher
::new();
229 src
.hash(&mut hasher
);
230 FileName
::MacroExpansion(hasher
.finish())
233 pub fn anon_source_code(src
: &str) -> FileName
{
234 let mut hasher
= StableHasher
::new();
235 src
.hash(&mut hasher
);
236 FileName
::Anon(hasher
.finish())
239 pub fn proc_macro_source_code(src
: &str) -> FileName
{
240 let mut hasher
= StableHasher
::new();
241 src
.hash(&mut hasher
);
242 FileName
::ProcMacroSourceCode(hasher
.finish())
245 pub fn cfg_spec_source_code(src
: &str) -> FileName
{
246 let mut hasher
= StableHasher
::new();
247 src
.hash(&mut hasher
);
248 FileName
::QuoteExpansion(hasher
.finish())
251 pub fn cli_crate_attr_source_code(src
: &str) -> FileName
{
252 let mut hasher
= StableHasher
::new();
253 src
.hash(&mut hasher
);
254 FileName
::CliCrateAttr(hasher
.finish())
257 pub fn doc_test_source_code(path
: PathBuf
, line
: isize) -> FileName
{
258 FileName
::DocTest(path
, line
)
261 pub fn inline_asm_source_code(src
: &str) -> FileName
{
262 let mut hasher
= StableHasher
::new();
263 src
.hash(&mut hasher
);
264 FileName
::InlineAsm(hasher
.finish())
268 /// Spans represent a region of code, used for error reporting. Positions in spans
269 /// are *absolute* positions from the beginning of the source_map, not positions
270 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
271 /// to the original source.
272 /// You must be careful if the span crosses more than one file - you will not be
273 /// able to use many of the functions on spans in source_map and you cannot assume
274 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
275 /// range between files.
277 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
278 /// sent to other threads, but some pieces of performance infra run in a separate thread.
279 /// Using `Span` is generally preferred.
280 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
281 pub struct SpanData
{
284 /// Information about where the macro came from, if this piece of
285 /// code was created by a macro expansion.
286 pub ctxt
: SyntaxContext
,
291 pub fn with_lo(&self, lo
: BytePos
) -> Span
{
292 Span
::new(lo
, self.hi
, self.ctxt
)
295 pub fn with_hi(&self, hi
: BytePos
) -> Span
{
296 Span
::new(self.lo
, hi
, self.ctxt
)
299 pub fn with_ctxt(&self, ctxt
: SyntaxContext
) -> Span
{
300 Span
::new(self.lo
, self.hi
, ctxt
)
304 // The interner is pointed to by a thread local value which is only set on the main thread
305 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
306 // to avoid panics and other errors, even though it would be memory safe to do so.
307 #[cfg(not(parallel_compiler))]
308 impl !Send
for Span {}
309 #[cfg(not(parallel_compiler))]
310 impl !Sync
for Span {}
312 impl PartialOrd
for Span
{
313 fn partial_cmp(&self, rhs
: &Self) -> Option
<Ordering
> {
314 PartialOrd
::partial_cmp(&self.data(), &rhs
.data())
318 fn cmp(&self, rhs
: &Self) -> Ordering
{
319 Ord
::cmp(&self.data(), &rhs
.data())
323 /// A collection of `Span`s.
325 /// Spans have two orthogonal attributes:
327 /// - They can be *primary spans*. In this case they are the locus of
328 /// the error, and would be rendered with `^^^`.
329 /// - They can have a *label*. In this case, the label is written next
330 /// to the mark in the snippet when we render.
331 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
332 pub struct MultiSpan
{
333 primary_spans
: Vec
<Span
>,
334 span_labels
: Vec
<(Span
, String
)>,
339 pub fn lo(self) -> BytePos
{
343 pub fn with_lo(self, lo
: BytePos
) -> Span
{
344 self.data().with_lo(lo
)
347 pub fn hi(self) -> BytePos
{
351 pub fn with_hi(self, hi
: BytePos
) -> Span
{
352 self.data().with_hi(hi
)
355 pub fn ctxt(self) -> SyntaxContext
{
359 pub fn with_ctxt(self, ctxt
: SyntaxContext
) -> Span
{
360 self.data().with_ctxt(ctxt
)
363 /// Returns `true` if this is a dummy span with any hygienic context.
365 pub fn is_dummy(self) -> bool
{
366 let span
= self.data();
367 span
.lo
.0 == 0 && span
.hi
.0 == 0
370 /// Returns `true` if this span comes from a macro or desugaring.
372 pub fn from_expansion(self) -> bool
{
373 self.ctxt() != SyntaxContext
::root()
376 /// Returns `true` if `span` originates in a derive-macro's expansion.
377 pub fn in_derive_expansion(self) -> bool
{
378 matches
!(self.ctxt().outer_expn_data().kind
, ExpnKind
::Macro(MacroKind
::Derive
, _
))
382 pub fn with_root_ctxt(lo
: BytePos
, hi
: BytePos
) -> Span
{
383 Span
::new(lo
, hi
, SyntaxContext
::root())
386 /// Returns a new span representing an empty span at the beginning of this span
388 pub fn shrink_to_lo(self) -> Span
{
389 let span
= self.data();
390 span
.with_hi(span
.lo
)
392 /// Returns a new span representing an empty span at the end of this span.
394 pub fn shrink_to_hi(self) -> Span
{
395 let span
= self.data();
396 span
.with_lo(span
.hi
)
400 /// Returns true if hi == lo
401 pub fn is_empty(&self) -> bool
{
402 let span
= self.data();
406 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
407 pub fn substitute_dummy(self, other
: Span
) -> Span
{
408 if self.is_dummy() { other }
else { self }
411 /// Returns `true` if `self` fully encloses `other`.
412 pub fn contains(self, other
: Span
) -> bool
{
413 let span
= self.data();
414 let other
= other
.data();
415 span
.lo
<= other
.lo
&& other
.hi
<= span
.hi
418 /// Returns `true` if `self` touches `other`.
419 pub fn overlaps(self, other
: Span
) -> bool
{
420 let span
= self.data();
421 let other
= other
.data();
422 span
.lo
< other
.hi
&& other
.lo
< span
.hi
425 /// Returns `true` if the spans are equal with regards to the source text.
427 /// Use this instead of `==` when either span could be generated code,
428 /// and you only care that they point to the same bytes of source text.
429 pub fn source_equal(&self, other
: &Span
) -> bool
{
430 let span
= self.data();
431 let other
= other
.data();
432 span
.lo
== other
.lo
&& span
.hi
== other
.hi
435 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
436 pub fn trim_start(self, other
: Span
) -> Option
<Span
> {
437 let span
= self.data();
438 let other
= other
.data();
439 if span
.hi
> other
.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) }
else { None }
442 /// Returns the source span -- this is either the supplied span, or the span for
443 /// the macro callsite that expanded to it.
444 pub fn source_callsite(self) -> Span
{
445 let expn_data
= self.ctxt().outer_expn_data();
446 if !expn_data
.is_root() { expn_data.call_site.source_callsite() }
else { self }
449 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
451 pub fn parent(self) -> Option
<Span
> {
452 let expn_data
= self.ctxt().outer_expn_data();
453 if !expn_data
.is_root() { Some(expn_data.call_site) }
else { None }
456 /// Edition of the crate from which this span came.
457 pub fn edition(self) -> edition
::Edition
{
458 self.ctxt().outer_expn_data().edition
462 pub fn rust_2015(&self) -> bool
{
463 self.edition() == edition
::Edition
::Edition2015
467 pub fn rust_2018(&self) -> bool
{
468 self.edition() >= edition
::Edition
::Edition2018
471 /// Returns the source callee.
473 /// Returns `None` if the supplied span has no expansion trace,
474 /// else returns the `ExpnData` for the macro definition
475 /// corresponding to the source callsite.
476 pub fn source_callee(self) -> Option
<ExpnData
> {
477 fn source_callee(expn_data
: ExpnData
) -> ExpnData
{
478 let next_expn_data
= expn_data
.call_site
.ctxt().outer_expn_data();
479 if !next_expn_data
.is_root() { source_callee(next_expn_data) }
else { expn_data }
481 let expn_data
= self.ctxt().outer_expn_data();
482 if !expn_data
.is_root() { Some(source_callee(expn_data)) }
else { None }
485 /// Checks if a span is "internal" to a macro in which `#[unstable]`
486 /// items can be used (that is, a macro marked with
487 /// `#[allow_internal_unstable]`).
488 pub fn allows_unstable(&self, feature
: Symbol
) -> bool
{
489 self.ctxt().outer_expn_data().allow_internal_unstable
.map_or(false, |features
| {
492 .any(|&f
| f
== feature
|| f
== sym
::allow_internal_unstable_backcompat_hack
)
496 /// Checks if this span arises from a compiler desugaring of kind `kind`.
497 pub fn is_desugaring(&self, kind
: DesugaringKind
) -> bool
{
498 match self.ctxt().outer_expn_data().kind
{
499 ExpnKind
::Desugaring(k
) => k
== kind
,
504 /// Returns the compiler desugaring that created this span, or `None`
505 /// if this span is not from a desugaring.
506 pub fn desugaring_kind(&self) -> Option
<DesugaringKind
> {
507 match self.ctxt().outer_expn_data().kind
{
508 ExpnKind
::Desugaring(k
) => Some(k
),
513 /// Checks if a span is "internal" to a macro in which `unsafe`
514 /// can be used without triggering the `unsafe_code` lint
515 // (that is, a macro marked with `#[allow_internal_unsafe]`).
516 pub fn allows_unsafe(&self) -> bool
{
517 self.ctxt().outer_expn_data().allow_internal_unsafe
520 pub fn macro_backtrace(mut self) -> impl Iterator
<Item
= ExpnData
> {
521 let mut prev_span
= DUMMY_SP
;
522 std
::iter
::from_fn(move || {
524 let expn_data
= self.ctxt().outer_expn_data();
525 if expn_data
.is_root() {
529 let is_recursive
= expn_data
.call_site
.source_equal(&prev_span
);
532 self = expn_data
.call_site
;
534 // Don't print recursive invocations.
536 return Some(expn_data
);
542 /// Returns a `Span` that would enclose both `self` and `end`.
546 /// self lorem ipsum end
547 /// ^^^^^^^^^^^^^^^^^^^^
549 pub fn to(self, end
: Span
) -> Span
{
550 let span_data
= self.data();
551 let end_data
= end
.data();
552 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
553 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
554 // have an incomplete span than a completely nonsensical one.
555 if span_data
.ctxt
!= end_data
.ctxt
{
556 if span_data
.ctxt
== SyntaxContext
::root() {
558 } else if end_data
.ctxt
== SyntaxContext
::root() {
561 // Both spans fall within a macro.
562 // FIXME(estebank): check if it is the *same* macro.
565 cmp
::min(span_data
.lo
, end_data
.lo
),
566 cmp
::max(span_data
.hi
, end_data
.hi
),
567 if span_data
.ctxt
== SyntaxContext
::root() { end_data.ctxt }
else { span_data.ctxt }
,
571 /// Returns a `Span` between the end of `self` to the beginning of `end`.
575 /// self lorem ipsum end
578 pub fn between(self, end
: Span
) -> Span
{
579 let span
= self.data();
580 let end
= end
.data();
584 if end
.ctxt
== SyntaxContext
::root() { end.ctxt }
else { span.ctxt }
,
588 /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
592 /// self lorem ipsum end
593 /// ^^^^^^^^^^^^^^^^^
595 pub fn until(self, end
: Span
) -> Span
{
596 let span
= self.data();
597 let end
= end
.data();
601 if end
.ctxt
== SyntaxContext
::root() { end.ctxt }
else { span.ctxt }
,
605 pub fn from_inner(self, inner
: InnerSpan
) -> Span
{
606 let span
= self.data();
608 span
.lo
+ BytePos
::from_usize(inner
.start
),
609 span
.lo
+ BytePos
::from_usize(inner
.end
),
614 /// Equivalent of `Span::def_site` from the proc macro API,
615 /// except that the location is taken from the `self` span.
616 pub fn with_def_site_ctxt(self, expn_id
: ExpnId
) -> Span
{
617 self.with_ctxt_from_mark(expn_id
, Transparency
::Opaque
)
620 /// Equivalent of `Span::call_site` from the proc macro API,
621 /// except that the location is taken from the `self` span.
622 pub fn with_call_site_ctxt(&self, expn_id
: ExpnId
) -> Span
{
623 self.with_ctxt_from_mark(expn_id
, Transparency
::Transparent
)
626 /// Equivalent of `Span::mixed_site` from the proc macro API,
627 /// except that the location is taken from the `self` span.
628 pub fn with_mixed_site_ctxt(&self, expn_id
: ExpnId
) -> Span
{
629 self.with_ctxt_from_mark(expn_id
, Transparency
::SemiTransparent
)
632 /// Produces a span with the same location as `self` and context produced by a macro with the
633 /// given ID and transparency, assuming that macro was defined directly and not produced by
634 /// some other macro (which is the case for built-in and procedural macros).
635 pub fn with_ctxt_from_mark(self, expn_id
: ExpnId
, transparency
: Transparency
) -> Span
{
636 self.with_ctxt(SyntaxContext
::root().apply_mark(expn_id
, transparency
))
640 pub fn apply_mark(self, expn_id
: ExpnId
, transparency
: Transparency
) -> Span
{
641 let span
= self.data();
642 span
.with_ctxt(span
.ctxt
.apply_mark(expn_id
, transparency
))
646 pub fn remove_mark(&mut self) -> ExpnId
{
647 let mut span
= self.data();
648 let mark
= span
.ctxt
.remove_mark();
649 *self = Span
::new(span
.lo
, span
.hi
, span
.ctxt
);
654 pub fn adjust(&mut self, expn_id
: ExpnId
) -> Option
<ExpnId
> {
655 let mut span
= self.data();
656 let mark
= span
.ctxt
.adjust(expn_id
);
657 *self = Span
::new(span
.lo
, span
.hi
, span
.ctxt
);
662 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id
: ExpnId
) -> Option
<ExpnId
> {
663 let mut span
= self.data();
664 let mark
= span
.ctxt
.normalize_to_macros_2_0_and_adjust(expn_id
);
665 *self = Span
::new(span
.lo
, span
.hi
, span
.ctxt
);
670 pub fn glob_adjust(&mut self, expn_id
: ExpnId
, glob_span
: Span
) -> Option
<Option
<ExpnId
>> {
671 let mut span
= self.data();
672 let mark
= span
.ctxt
.glob_adjust(expn_id
, glob_span
);
673 *self = Span
::new(span
.lo
, span
.hi
, span
.ctxt
);
678 pub fn reverse_glob_adjust(
682 ) -> Option
<Option
<ExpnId
>> {
683 let mut span
= self.data();
684 let mark
= span
.ctxt
.reverse_glob_adjust(expn_id
, glob_span
);
685 *self = Span
::new(span
.lo
, span
.hi
, span
.ctxt
);
690 pub fn normalize_to_macros_2_0(self) -> Span
{
691 let span
= self.data();
692 span
.with_ctxt(span
.ctxt
.normalize_to_macros_2_0())
696 pub fn normalize_to_macro_rules(self) -> Span
{
697 let span
= self.data();
698 span
.with_ctxt(span
.ctxt
.normalize_to_macro_rules())
702 #[derive(Clone, Debug)]
703 pub struct SpanLabel
{
704 /// The span we are going to include in the final snippet.
707 /// Is this a primary span? This is the "locus" of the message,
708 /// and is indicated with a `^^^^` underline, versus `----`.
709 pub is_primary
: bool
,
711 /// What label should we attach to this span (if any)?
712 pub label
: Option
<String
>,
715 impl Default
for Span
{
716 fn default() -> Self {
721 impl<E
: Encoder
> Encodable
<E
> for Span
{
722 default fn encode(&self, s
: &mut E
) -> Result
<(), E
::Error
> {
723 let span
= self.data();
724 s
.emit_struct("Span", 2, |s
| {
725 s
.emit_struct_field("lo", 0, |s
| span
.lo
.encode(s
))?
;
726 s
.emit_struct_field("hi", 1, |s
| span
.hi
.encode(s
))
730 impl<D
: Decoder
> Decodable
<D
> for Span
{
731 default fn decode(s
: &mut D
) -> Result
<Span
, D
::Error
> {
732 s
.read_struct("Span", 2, |d
| {
733 let lo
= d
.read_struct_field("lo", 0, Decodable
::decode
)?
;
734 let hi
= d
.read_struct_field("hi", 1, Decodable
::decode
)?
;
736 Ok(Span
::new(lo
, hi
, SyntaxContext
::root()))
741 /// Calls the provided closure, using the provided `SourceMap` to format
742 /// any spans that are debug-printed during the closure's execution.
744 /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap`
745 /// (see `rustc_interface::callbacks::span_debug1). However, some parts
746 /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before
747 /// a `TyCtxt` is available. In this case, we fall back to
748 /// the `SourceMap` provided to this function. If that is not available,
749 /// we fall back to printing the raw `Span` field values.
750 pub fn with_source_map
<T
, F
: FnOnce() -> T
>(source_map
: Lrc
<SourceMap
>, f
: F
) -> T
{
751 SESSION_GLOBALS
.with(|session_globals
| {
752 *session_globals
.source_map
.borrow_mut() = Some(source_map
);
754 struct ClearSourceMap
;
755 impl Drop
for ClearSourceMap
{
757 SESSION_GLOBALS
.with(|session_globals
| {
758 session_globals
.source_map
.borrow_mut().take();
763 let _guard
= ClearSourceMap
;
767 pub fn debug_with_source_map(
769 f
: &mut fmt
::Formatter
<'_
>,
770 source_map
: &SourceMap
,
772 write
!(f
, "{} ({:?})", source_map
.span_to_string(span
), span
.ctxt())
775 pub fn default_span_debug(span
: Span
, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
776 SESSION_GLOBALS
.with(|session_globals
| {
777 if let Some(source_map
) = &*session_globals
.source_map
.borrow() {
778 debug_with_source_map(span
, f
, source_map
)
780 f
.debug_struct("Span")
781 .field("lo", &span
.lo())
782 .field("hi", &span
.hi())
783 .field("ctxt", &span
.ctxt())
789 impl fmt
::Debug
for Span
{
790 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
791 (*SPAN_DEBUG
)(*self, f
)
795 impl fmt
::Debug
for SpanData
{
796 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
797 (*SPAN_DEBUG
)(Span
::new(self.lo
, self.hi
, self.ctxt
), f
)
803 pub fn new() -> MultiSpan
{
804 MultiSpan { primary_spans: vec![], span_labels: vec![] }
807 pub fn from_span(primary_span
: Span
) -> MultiSpan
{
808 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
811 pub fn from_spans(mut vec
: Vec
<Span
>) -> MultiSpan
{
813 MultiSpan { primary_spans: vec, span_labels: vec![] }
816 pub fn push_span_label(&mut self, span
: Span
, label
: String
) {
817 self.span_labels
.push((span
, label
));
820 /// Selects the first primary span (if any).
821 pub fn primary_span(&self) -> Option
<Span
> {
822 self.primary_spans
.first().cloned()
825 /// Returns all primary spans.
826 pub fn primary_spans(&self) -> &[Span
] {
830 /// Returns `true` if any of the primary spans are displayable.
831 pub fn has_primary_spans(&self) -> bool
{
832 self.primary_spans
.iter().any(|sp
| !sp
.is_dummy())
835 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
836 pub fn is_dummy(&self) -> bool
{
837 let mut is_dummy
= true;
838 for span
in &self.primary_spans
{
839 if !span
.is_dummy() {
846 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
847 /// display well (like std macros). Returns whether replacements occurred.
848 pub fn replace(&mut self, before
: Span
, after
: Span
) -> bool
{
849 let mut replacements_occurred
= false;
850 for primary_span
in &mut self.primary_spans
{
851 if *primary_span
== before
{
852 *primary_span
= after
;
853 replacements_occurred
= true;
856 for span_label
in &mut self.span_labels
{
857 if span_label
.0 == before
{
858 span_label
.0 = after
;
859 replacements_occurred
= true;
862 replacements_occurred
865 /// Returns the strings to highlight. We always ensure that there
866 /// is an entry for each of the primary spans -- for each primary
867 /// span `P`, if there is at least one label with span `P`, we return
868 /// those labels (marked as primary). But otherwise we return
869 /// `SpanLabel` instances with empty labels.
870 pub fn span_labels(&self) -> Vec
<SpanLabel
> {
871 let is_primary
= |span
| self.primary_spans
.contains(&span
);
873 let mut span_labels
= self
876 .map(|&(span
, ref label
)| SpanLabel
{
878 is_primary
: is_primary(span
),
879 label
: Some(label
.clone()),
881 .collect
::<Vec
<_
>>();
883 for &span
in &self.primary_spans
{
884 if !span_labels
.iter().any(|sl
| sl
.span
== span
) {
885 span_labels
.push(SpanLabel { span, is_primary: true, label: None }
);
892 /// Returns `true` if any of the span labels is displayable.
893 pub fn has_span_labels(&self) -> bool
{
894 self.span_labels
.iter().any(|(sp
, _
)| !sp
.is_dummy())
898 impl From
<Span
> for MultiSpan
{
899 fn from(span
: Span
) -> MultiSpan
{
900 MultiSpan
::from_span(span
)
904 impl From
<Vec
<Span
>> for MultiSpan
{
905 fn from(spans
: Vec
<Span
>) -> MultiSpan
{
906 MultiSpan
::from_spans(spans
)
910 /// Identifies an offset of a multi-byte character in a `SourceFile`.
911 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
912 pub struct MultiByteChar
{
913 /// The absolute offset of the character in the `SourceMap`.
915 /// The number of bytes, `>= 2`.
919 /// Identifies an offset of a non-narrow character in a `SourceFile`.
920 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
921 pub enum NonNarrowChar
{
922 /// Represents a zero-width character.
924 /// Represents a wide (full-width) character.
926 /// Represents a tab character, represented visually with a width of 4 characters.
931 fn new(pos
: BytePos
, width
: usize) -> Self {
933 0 => NonNarrowChar
::ZeroWidth(pos
),
934 2 => NonNarrowChar
::Wide(pos
),
935 4 => NonNarrowChar
::Tab(pos
),
936 _
=> panic
!("width {} given for non-narrow character", width
),
940 /// Returns the absolute offset of the character in the `SourceMap`.
941 pub fn pos(&self) -> BytePos
{
943 NonNarrowChar
::ZeroWidth(p
) | NonNarrowChar
::Wide(p
) | NonNarrowChar
::Tab(p
) => p
,
947 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
948 pub fn width(&self) -> usize {
950 NonNarrowChar
::ZeroWidth(_
) => 0,
951 NonNarrowChar
::Wide(_
) => 2,
952 NonNarrowChar
::Tab(_
) => 4,
957 impl Add
<BytePos
> for NonNarrowChar
{
960 fn add(self, rhs
: BytePos
) -> Self {
962 NonNarrowChar
::ZeroWidth(pos
) => NonNarrowChar
::ZeroWidth(pos
+ rhs
),
963 NonNarrowChar
::Wide(pos
) => NonNarrowChar
::Wide(pos
+ rhs
),
964 NonNarrowChar
::Tab(pos
) => NonNarrowChar
::Tab(pos
+ rhs
),
969 impl Sub
<BytePos
> for NonNarrowChar
{
972 fn sub(self, rhs
: BytePos
) -> Self {
974 NonNarrowChar
::ZeroWidth(pos
) => NonNarrowChar
::ZeroWidth(pos
- rhs
),
975 NonNarrowChar
::Wide(pos
) => NonNarrowChar
::Wide(pos
- rhs
),
976 NonNarrowChar
::Tab(pos
) => NonNarrowChar
::Tab(pos
- rhs
),
981 /// Identifies an offset of a character that was normalized away from `SourceFile`.
982 #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)]
983 pub struct NormalizedPos
{
984 /// The absolute offset of the character in the `SourceMap`.
986 /// The difference between original and normalized string at position.
990 #[derive(PartialEq, Eq, Clone, Debug)]
991 pub enum ExternalSource
{
992 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
995 kind
: ExternalSourceKind
,
996 /// This SourceFile's byte-offset within the source_map of its original crate
997 original_start_pos
: BytePos
,
998 /// The end of this SourceFile within the source_map of its original crate
999 original_end_pos
: BytePos
,
1003 /// The state of the lazy external source loading mechanism of a `SourceFile`.
1004 #[derive(PartialEq, Eq, Clone, Debug)]
1005 pub enum ExternalSourceKind
{
1006 /// The external source has been loaded already.
1007 Present(Lrc
<String
>),
1008 /// No attempt has been made to load the external source.
1010 /// A failed attempt has been made to load the external source.
1015 impl ExternalSource
{
1016 pub fn is_absent(&self) -> bool
{
1018 ExternalSource
::Foreign { kind: ExternalSourceKind::Present(_), .. }
=> false,
1023 pub fn get_source(&self) -> Option
<&Lrc
<String
>> {
1025 ExternalSource
::Foreign { kind: ExternalSourceKind::Present(ref src), .. }
=> Some(src
),
1032 pub struct OffsetOverflowError
;
1034 #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1035 pub enum SourceFileHashAlgorithm
{
1041 impl FromStr
for SourceFileHashAlgorithm
{
1044 fn from_str(s
: &str) -> Result
<SourceFileHashAlgorithm
, ()> {
1046 "md5" => Ok(SourceFileHashAlgorithm
::Md5
),
1047 "sha1" => Ok(SourceFileHashAlgorithm
::Sha1
),
1048 "sha256" => Ok(SourceFileHashAlgorithm
::Sha256
),
1054 rustc_data_structures
::impl_stable_hash_via_hash
!(SourceFileHashAlgorithm
);
1056 /// The hash of the on-disk source file used for debug info.
1057 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1058 #[derive(HashStable_Generic, Encodable, Decodable)]
1059 pub struct SourceFileHash
{
1060 pub kind
: SourceFileHashAlgorithm
,
1064 impl SourceFileHash
{
1065 pub fn new(kind
: SourceFileHashAlgorithm
, src
: &str) -> SourceFileHash
{
1066 let mut hash
= SourceFileHash { kind, value: Default::default() }
;
1067 let len
= hash
.hash_len();
1068 let value
= &mut hash
.value
[..len
];
1069 let data
= src
.as_bytes();
1071 SourceFileHashAlgorithm
::Md5
=> {
1072 value
.copy_from_slice(&Md5
::digest(data
));
1074 SourceFileHashAlgorithm
::Sha1
=> {
1075 value
.copy_from_slice(&Sha1
::digest(data
));
1077 SourceFileHashAlgorithm
::Sha256
=> {
1078 value
.copy_from_slice(&Sha256
::digest(data
));
1084 /// Check if the stored hash matches the hash of the string.
1085 pub fn matches(&self, src
: &str) -> bool
{
1086 Self::new(self.kind
, src
) == *self
1089 /// The bytes of the hash.
1090 pub fn hash_bytes(&self) -> &[u8] {
1091 let len
= self.hash_len();
1095 fn hash_len(&self) -> usize {
1097 SourceFileHashAlgorithm
::Md5
=> 16,
1098 SourceFileHashAlgorithm
::Sha1
=> 20,
1099 SourceFileHashAlgorithm
::Sha256
=> 32,
1104 /// A single source in the `SourceMap`.
1106 pub struct SourceFile
{
1107 /// The name of the file that the source came from. Source that doesn't
1108 /// originate from files has names between angle brackets by convention
1109 /// (e.g., `<anon>`).
1111 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
1112 pub name_was_remapped
: bool
,
1113 /// The unmapped path of the file that the source came from.
1114 /// Set to `None` if the `SourceFile` was imported from an external crate.
1115 pub unmapped_path
: Option
<FileName
>,
1116 /// The complete source code.
1117 pub src
: Option
<Lrc
<String
>>,
1118 /// The source code's hash.
1119 pub src_hash
: SourceFileHash
,
1120 /// The external source code (used for external crates, which will have a `None`
1121 /// value as `self.src`.
1122 pub external_src
: Lock
<ExternalSource
>,
1123 /// The start position of this source in the `SourceMap`.
1124 pub start_pos
: BytePos
,
1125 /// The end position of this source in the `SourceMap`.
1126 pub end_pos
: BytePos
,
1127 /// Locations of lines beginnings in the source code.
1128 pub lines
: Vec
<BytePos
>,
1129 /// Locations of multi-byte characters in the source code.
1130 pub multibyte_chars
: Vec
<MultiByteChar
>,
1131 /// Width of characters that are not narrow in the source code.
1132 pub non_narrow_chars
: Vec
<NonNarrowChar
>,
1133 /// Locations of characters removed during normalization.
1134 pub normalized_pos
: Vec
<NormalizedPos
>,
1135 /// A hash of the filename, used for speeding up hashing in incremental compilation.
1136 pub name_hash
: u128
,
1137 /// Indicates which crate this `SourceFile` was imported from.
1141 impl<S
: Encoder
> Encodable
<S
> for SourceFile
{
1142 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
1143 s
.emit_struct("SourceFile", 8, |s
| {
1144 s
.emit_struct_field("name", 0, |s
| self.name
.encode(s
))?
;
1145 s
.emit_struct_field("name_was_remapped", 1, |s
| self.name_was_remapped
.encode(s
))?
;
1146 s
.emit_struct_field("src_hash", 2, |s
| self.src_hash
.encode(s
))?
;
1147 s
.emit_struct_field("start_pos", 3, |s
| self.start_pos
.encode(s
))?
;
1148 s
.emit_struct_field("end_pos", 4, |s
| self.end_pos
.encode(s
))?
;
1149 s
.emit_struct_field("lines", 5, |s
| {
1150 let lines
= &self.lines
[..];
1151 // Store the length.
1152 s
.emit_u32(lines
.len() as u32)?
;
1154 if !lines
.is_empty() {
1155 // In order to preserve some space, we exploit the fact that
1156 // the lines list is sorted and individual lines are
1157 // probably not that long. Because of that we can store lines
1158 // as a difference list, using as little space as possible
1159 // for the differences.
1160 let max_line_length
= if lines
.len() == 1 {
1165 .map(|&[fst
, snd
]| snd
- fst
)
1166 .map(|bp
| bp
.to_usize())
1171 let bytes_per_diff
: u8 = match max_line_length
{
1173 0x100..=0xFFFF => 2,
1177 // Encode the number of bytes used per diff.
1178 bytes_per_diff
.encode(s
)?
;
1180 // Encode the first element.
1181 lines
[0].encode(s
)?
;
1183 let diff_iter
= lines
[..].array_windows().map(|&[fst
, snd
]| snd
- fst
);
1185 match bytes_per_diff
{
1187 for diff
in diff_iter
{
1188 (diff
.0 as u8).encode(s
)?
1192 for diff
in diff_iter
{
1193 (diff
.0 as u16).encode(s
)?
1197 for diff
in diff_iter
{
1201 _
=> unreachable
!(),
1207 s
.emit_struct_field("multibyte_chars", 6, |s
| self.multibyte_chars
.encode(s
))?
;
1208 s
.emit_struct_field("non_narrow_chars", 7, |s
| self.non_narrow_chars
.encode(s
))?
;
1209 s
.emit_struct_field("name_hash", 8, |s
| self.name_hash
.encode(s
))?
;
1210 s
.emit_struct_field("normalized_pos", 9, |s
| self.normalized_pos
.encode(s
))?
;
1211 s
.emit_struct_field("cnum", 10, |s
| self.cnum
.encode(s
))
1216 impl<D
: Decoder
> Decodable
<D
> for SourceFile
{
1217 fn decode(d
: &mut D
) -> Result
<SourceFile
, D
::Error
> {
1218 d
.read_struct("SourceFile", 8, |d
| {
1219 let name
: FileName
= d
.read_struct_field("name", 0, |d
| Decodable
::decode(d
))?
;
1220 let name_was_remapped
: bool
=
1221 d
.read_struct_field("name_was_remapped", 1, |d
| Decodable
::decode(d
))?
;
1222 let src_hash
: SourceFileHash
=
1223 d
.read_struct_field("src_hash", 2, |d
| Decodable
::decode(d
))?
;
1224 let start_pos
: BytePos
=
1225 d
.read_struct_field("start_pos", 3, |d
| Decodable
::decode(d
))?
;
1226 let end_pos
: BytePos
= d
.read_struct_field("end_pos", 4, |d
| Decodable
::decode(d
))?
;
1227 let lines
: Vec
<BytePos
> = d
.read_struct_field("lines", 5, |d
| {
1228 let num_lines
: u32 = Decodable
::decode(d
)?
;
1229 let mut lines
= Vec
::with_capacity(num_lines
as usize);
1232 // Read the number of bytes used per diff.
1233 let bytes_per_diff
: u8 = Decodable
::decode(d
)?
;
1235 // Read the first element.
1236 let mut line_start
: BytePos
= Decodable
::decode(d
)?
;
1237 lines
.push(line_start
);
1239 for _
in 1..num_lines
{
1240 let diff
= match bytes_per_diff
{
1241 1 => d
.read_u8()?
as u32,
1242 2 => d
.read_u16()?
as u32,
1244 _
=> unreachable
!(),
1247 line_start
= line_start
+ BytePos(diff
);
1249 lines
.push(line_start
);
1255 let multibyte_chars
: Vec
<MultiByteChar
> =
1256 d
.read_struct_field("multibyte_chars", 6, |d
| Decodable
::decode(d
))?
;
1257 let non_narrow_chars
: Vec
<NonNarrowChar
> =
1258 d
.read_struct_field("non_narrow_chars", 7, |d
| Decodable
::decode(d
))?
;
1259 let name_hash
: u128
= d
.read_struct_field("name_hash", 8, |d
| Decodable
::decode(d
))?
;
1260 let normalized_pos
: Vec
<NormalizedPos
> =
1261 d
.read_struct_field("normalized_pos", 9, |d
| Decodable
::decode(d
))?
;
1262 let cnum
: CrateNum
= d
.read_struct_field("cnum", 10, |d
| Decodable
::decode(d
))?
;
1266 unmapped_path
: None
,
1271 // Unused - the metadata decoder will construct
1272 // a new SourceFile, filling in `external_src` properly
1273 external_src
: Lock
::new(ExternalSource
::Unneeded
),
1285 impl fmt
::Debug
for SourceFile
{
1286 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1287 write
!(fmt
, "SourceFile({})", self.name
)
1294 name_was_remapped
: bool
,
1295 unmapped_path
: FileName
,
1298 hash_kind
: SourceFileHashAlgorithm
,
1300 // Compute the file hash before any normalization.
1301 let src_hash
= SourceFileHash
::new(hash_kind
, &src
);
1302 let normalized_pos
= normalize_src(&mut src
, start_pos
);
1305 let mut hasher
: StableHasher
= StableHasher
::new();
1306 name
.hash(&mut hasher
);
1307 hasher
.finish
::<u128
>()
1309 let end_pos
= start_pos
.to_usize() + src
.len();
1310 assert
!(end_pos
<= u32::MAX
as usize);
1312 let (lines
, multibyte_chars
, non_narrow_chars
) =
1313 analyze_source_file
::analyze_source_file(&src
[..], start_pos
);
1318 unmapped_path
: Some(unmapped_path
),
1319 src
: Some(Lrc
::new(src
)),
1321 external_src
: Lock
::new(ExternalSource
::Unneeded
),
1323 end_pos
: Pos
::from_usize(end_pos
),
1333 /// Returns the `BytePos` of the beginning of the current line.
1334 pub fn line_begin_pos(&self, pos
: BytePos
) -> BytePos
{
1335 let line_index
= self.lookup_line(pos
).unwrap();
1336 self.lines
[line_index
]
1339 /// Add externally loaded source.
1340 /// If the hash of the input doesn't match or no input is supplied via None,
1341 /// it is interpreted as an error and the corresponding enum variant is set.
1342 /// The return value signifies whether some kind of source is present.
1343 pub fn add_external_src
<F
>(&self, get_src
: F
) -> bool
1345 F
: FnOnce() -> Option
<String
>,
1348 *self.external_src
.borrow(),
1349 ExternalSource
::Foreign { kind: ExternalSourceKind::AbsentOk, .. }
1351 let src
= get_src();
1352 let mut external_src
= self.external_src
.borrow_mut();
1353 // Check that no-one else have provided the source while we were getting it
1354 if let ExternalSource
::Foreign
{
1355 kind
: src_kind @ ExternalSourceKind
::AbsentOk
, ..
1356 } = &mut *external_src
1358 if let Some(mut src
) = src
{
1359 // The src_hash needs to be computed on the pre-normalized src.
1360 if self.src_hash
.matches(&src
) {
1361 normalize_src(&mut src
, BytePos
::from_usize(0));
1362 *src_kind
= ExternalSourceKind
::Present(Lrc
::new(src
));
1366 *src_kind
= ExternalSourceKind
::AbsentErr
;
1371 self.src
.is_some() || external_src
.get_source().is_some()
1374 self.src
.is_some() || self.external_src
.borrow().get_source().is_some()
1378 /// Gets a line from the list of pre-computed line-beginnings.
1379 /// The line number here is 0-based.
1380 pub fn get_line(&self, line_number
: usize) -> Option
<Cow
<'_
, str>> {
1381 fn get_until_newline(src
: &str, begin
: usize) -> &str {
1382 // We can't use `lines.get(line_number+1)` because we might
1383 // be parsing when we call this function and thus the current
1384 // line is the last one we have line info for.
1385 let slice
= &src
[begin
..];
1386 match slice
.find('
\n'
) {
1387 Some(e
) => &slice
[..e
],
1393 let line
= self.lines
.get(line_number
)?
;
1394 let begin
: BytePos
= *line
- self.start_pos
;
1398 if let Some(ref src
) = self.src
{
1399 Some(Cow
::from(get_until_newline(src
, begin
)))
1400 } else if let Some(src
) = self.external_src
.borrow().get_source() {
1401 Some(Cow
::Owned(String
::from(get_until_newline(src
, begin
))))
1407 pub fn is_real_file(&self) -> bool
{
1411 pub fn is_imported(&self) -> bool
{
1415 pub fn byte_length(&self) -> u32 {
1416 self.end_pos
.0 - self.start_pos
.0
1418 pub fn count_lines(&self) -> usize {
1422 /// Finds the line containing the given position. The return value is the
1423 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1424 /// number. If the source_file is empty or the position is located before the
1425 /// first line, `None` is returned.
1426 pub fn lookup_line(&self, pos
: BytePos
) -> Option
<usize> {
1427 if self.lines
.is_empty() {
1431 let line_index
= lookup_line(&self.lines
[..], pos
);
1432 assert
!(line_index
< self.lines
.len() as isize);
1433 if line_index
>= 0 { Some(line_index as usize) }
else { None }
1436 pub fn line_bounds(&self, line_index
: usize) -> Range
<BytePos
> {
1437 if self.is_empty() {
1438 return self.start_pos
..self.end_pos
;
1441 assert
!(line_index
< self.lines
.len());
1442 if line_index
== (self.lines
.len() - 1) {
1443 self.lines
[line_index
]..self.end_pos
1445 self.lines
[line_index
]..self.lines
[line_index
+ 1]
1449 /// Returns whether or not the file contains the given `SourceMap` byte
1450 /// position. The position one past the end of the file is considered to be
1451 /// contained by the file. This implies that files for which `is_empty`
1452 /// returns true still contain one byte position according to this function.
1454 pub fn contains(&self, byte_pos
: BytePos
) -> bool
{
1455 byte_pos
>= self.start_pos
&& byte_pos
<= self.end_pos
1459 pub fn is_empty(&self) -> bool
{
1460 self.start_pos
== self.end_pos
1463 /// Calculates the original byte position relative to the start of the file
1464 /// based on the given byte position.
1465 pub fn original_relative_byte_pos(&self, pos
: BytePos
) -> BytePos
{
1466 // Diff before any records is 0. Otherwise use the previously recorded
1467 // diff as that applies to the following characters until a new diff
1469 let diff
= match self.normalized_pos
.binary_search_by(|np
| np
.pos
.cmp(&pos
)) {
1470 Ok(i
) => self.normalized_pos
[i
].diff
,
1471 Err(i
) if i
== 0 => 0,
1472 Err(i
) => self.normalized_pos
[i
- 1].diff
,
1475 BytePos
::from_u32(pos
.0 - self.start_pos
.0 + diff
)
1478 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
1479 pub fn bytepos_to_file_charpos(&self, bpos
: BytePos
) -> CharPos
{
1480 // The number of extra bytes due to multibyte chars in the `SourceFile`.
1481 let mut total_extra_bytes
= 0;
1483 for mbc
in self.multibyte_chars
.iter() {
1484 debug
!("{}-byte char at {:?}", mbc
.bytes
, mbc
.pos
);
1486 // Every character is at least one byte, so we only
1487 // count the actual extra bytes.
1488 total_extra_bytes
+= mbc
.bytes
as u32 - 1;
1489 // We should never see a byte position in the middle of a
1491 assert
!(bpos
.to_u32() >= mbc
.pos
.to_u32() + mbc
.bytes
as u32);
1497 assert
!(self.start_pos
.to_u32() + total_extra_bytes
<= bpos
.to_u32());
1498 CharPos(bpos
.to_usize() - self.start_pos
.to_usize() - total_extra_bytes
as usize)
1501 /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
1502 /// given `BytePos`.
1503 pub fn lookup_file_pos(&self, pos
: BytePos
) -> (usize, CharPos
) {
1504 let chpos
= self.bytepos_to_file_charpos(pos
);
1505 match self.lookup_line(pos
) {
1507 let line
= a
+ 1; // Line numbers start at 1
1508 let linebpos
= self.lines
[a
];
1509 let linechpos
= self.bytepos_to_file_charpos(linebpos
);
1510 let col
= chpos
- linechpos
;
1511 debug
!("byte pos {:?} is on the line at byte pos {:?}", pos
, linebpos
);
1512 debug
!("char pos {:?} is on the line at char pos {:?}", chpos
, linechpos
);
1513 debug
!("byte is on line: {}", line
);
1514 assert
!(chpos
>= linechpos
);
1521 /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
1522 /// column offset when displayed, for a given `BytePos`.
1523 pub fn lookup_file_pos_with_col_display(&self, pos
: BytePos
) -> (usize, CharPos
, usize) {
1524 let (line
, col_or_chpos
) = self.lookup_file_pos(pos
);
1526 let col
= col_or_chpos
;
1527 let linebpos
= self.lines
[line
- 1];
1529 let start_width_idx
= self
1531 .binary_search_by_key(&linebpos
, |x
| x
.pos())
1532 .unwrap_or_else(|x
| x
);
1533 let end_width_idx
= self
1535 .binary_search_by_key(&pos
, |x
| x
.pos())
1536 .unwrap_or_else(|x
| x
);
1537 let special_chars
= end_width_idx
- start_width_idx
;
1538 let non_narrow
: usize = self.non_narrow_chars
[start_width_idx
..end_width_idx
]
1542 col
.0 - special_chars
+ non_narrow
1544 (line
, col
, col_display
)
1546 let chpos
= col_or_chpos
;
1548 let end_width_idx
= self
1550 .binary_search_by_key(&pos
, |x
| x
.pos())
1551 .unwrap_or_else(|x
| x
);
1552 let non_narrow
: usize =
1553 self.non_narrow_chars
[0..end_width_idx
].iter().map(|x
| x
.width()).sum();
1554 chpos
.0 - end_width_idx
+ non_narrow
1556 (0, chpos
, col_display
)
1561 /// Normalizes the source code and records the normalizations.
1562 fn normalize_src(src
: &mut String
, start_pos
: BytePos
) -> Vec
<NormalizedPos
> {
1563 let mut normalized_pos
= vec
![];
1564 remove_bom(src
, &mut normalized_pos
);
1565 normalize_newlines(src
, &mut normalized_pos
);
1567 // Offset all the positions by start_pos to match the final file positions.
1568 for np
in &mut normalized_pos
{
1569 np
.pos
.0 += start_pos
.0;
1575 /// Removes UTF-8 BOM, if any.
1576 fn remove_bom(src
: &mut String
, normalized_pos
: &mut Vec
<NormalizedPos
>) {
1577 if src
.starts_with('
\u{feff}'
) {
1579 normalized_pos
.push(NormalizedPos { pos: BytePos(0), diff: 3 }
);
1583 /// Replaces `\r\n` with `\n` in-place in `src`.
1585 /// Returns error if there's a lone `\r` in the string
1586 fn normalize_newlines(src
: &mut String
, normalized_pos
: &mut Vec
<NormalizedPos
>) {
1587 if !src
.as_bytes().contains(&b'
\r'
) {
1591 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1592 // While we *can* call `as_mut_vec` and do surgery on the live string
1593 // directly, let's rather steal the contents of `src`. This makes the code
1594 // safe even if a panic occurs.
1596 let mut buf
= std
::mem
::replace(src
, String
::new()).into_bytes();
1597 let mut gap_len
= 0;
1598 let mut tail
= buf
.as_mut_slice();
1600 let original_gap
= normalized_pos
.last().map_or(0, |l
| l
.diff
);
1602 let idx
= match find_crlf(&tail
[gap_len
..]) {
1604 Some(idx
) => idx
+ gap_len
,
1606 tail
.copy_within(gap_len
..idx
, 0);
1607 tail
= &mut tail
[idx
- gap_len
..];
1608 if tail
.len() == gap_len
{
1611 cursor
+= idx
- gap_len
;
1613 normalized_pos
.push(NormalizedPos
{
1614 pos
: BytePos
::from_usize(cursor
+ 1),
1615 diff
: original_gap
+ gap_len
as u32,
1619 // Account for removed `\r`.
1620 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1621 let new_len
= buf
.len() - gap_len
;
1623 buf
.set_len(new_len
);
1624 *src
= String
::from_utf8_unchecked(buf
);
1627 fn find_crlf(src
: &[u8]) -> Option
<usize> {
1628 let mut search_idx
= 0;
1629 while let Some(idx
) = find_cr(&src
[search_idx
..]) {
1630 if src
[search_idx
..].get(idx
+ 1) != Some(&b'
\n'
) {
1631 search_idx
+= idx
+ 1;
1634 return Some(search_idx
+ idx
);
1639 fn find_cr(src
: &[u8]) -> Option
<usize> {
1640 src
.iter().position(|&b
| b
== b'
\r'
)
1644 // _____________________________________________________________________________
1645 // Pos, BytePos, CharPos
1649 fn from_usize(n
: usize) -> Self;
1650 fn to_usize(&self) -> usize;
1651 fn from_u32(n
: u32) -> Self;
1652 fn to_u32(&self) -> u32;
1655 macro_rules
! impl_pos
{
1659 $vis
:vis
struct $ident
:ident($inner_vis
:vis $inner_ty
:ty
);
1664 $vis
struct $
ident($inner_vis $inner_ty
);
1666 impl Pos
for $ident
{
1668 fn from_usize(n
: usize) -> $ident
{
1669 $
ident(n
as $inner_ty
)
1673 fn to_usize(&self) -> usize {
1678 fn from_u32(n
: u32) -> $ident
{
1679 $
ident(n
as $inner_ty
)
1683 fn to_u32(&self) -> u32 {
1688 impl Add
for $ident
{
1689 type Output
= $ident
;
1692 fn add(self, rhs
: $ident
) -> $ident
{
1693 $
ident(self.0 + rhs
.0)
1697 impl Sub
for $ident
{
1698 type Output
= $ident
;
1701 fn sub(self, rhs
: $ident
) -> $ident
{
1702 $
ident(self.0 - rhs
.0)
1710 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1712 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1713 pub struct BytePos(pub u32);
1715 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1716 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1717 /// values to `CharPos` values as necessary.
1718 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
1719 pub struct CharPos(pub usize);
1722 impl<S
: rustc_serialize
::Encoder
> Encodable
<S
> for BytePos
{
1723 fn encode(&self, s
: &mut S
) -> Result
<(), S
::Error
> {
1728 impl<D
: rustc_serialize
::Decoder
> Decodable
<D
> for BytePos
{
1729 fn decode(d
: &mut D
) -> Result
<BytePos
, D
::Error
> {
1730 Ok(BytePos(d
.read_u32()?
))
1734 // _____________________________________________________________________________
1735 // Loc, SourceFileAndLine, SourceFileAndBytePos
1738 /// A source code location used for error reporting.
1739 #[derive(Debug, Clone)]
1741 /// Information about the original source.
1742 pub file
: Lrc
<SourceFile
>,
1743 /// The (1-based) line number.
1745 /// The (0-based) column offset.
1747 /// The (0-based) column offset when displayed.
1748 pub col_display
: usize,
1751 // Used to be structural records.
1753 pub struct SourceFileAndLine
{
1754 pub sf
: Lrc
<SourceFile
>,
1758 pub struct SourceFileAndBytePos
{
1759 pub sf
: Lrc
<SourceFile
>,
1763 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1764 pub struct LineInfo
{
1765 /// Index of line, starting from 0.
1766 pub line_index
: usize,
1768 /// Column in line where span begins, starting from 0.
1769 pub start_col
: CharPos
,
1771 /// Column in line where span ends, starting from 0, exclusive.
1772 pub end_col
: CharPos
,
1775 pub struct FileLines
{
1776 pub file
: Lrc
<SourceFile
>,
1777 pub lines
: Vec
<LineInfo
>,
1780 pub static SPAN_DEBUG
: AtomicRef
<fn(Span
, &mut fmt
::Formatter
<'_
>) -> fmt
::Result
> =
1781 AtomicRef
::new(&(default_span_debug
as fn(_
, &mut fmt
::Formatter
<'_
>) -> _
));
1783 // _____________________________________________________________________________
1784 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1787 pub type FileLinesResult
= Result
<FileLines
, SpanLinesError
>;
1789 #[derive(Clone, PartialEq, Eq, Debug)]
1790 pub enum SpanLinesError
{
1791 DistinctSources(DistinctSources
),
1794 #[derive(Clone, PartialEq, Eq, Debug)]
1795 pub enum SpanSnippetError
{
1796 IllFormedSpan(Span
),
1797 DistinctSources(DistinctSources
),
1798 MalformedForSourcemap(MalformedSourceMapPositions
),
1799 SourceNotAvailable { filename: FileName }
,
1802 #[derive(Clone, PartialEq, Eq, Debug)]
1803 pub struct DistinctSources
{
1804 pub begin
: (FileName
, BytePos
),
1805 pub end
: (FileName
, BytePos
),
1808 #[derive(Clone, PartialEq, Eq, Debug)]
1809 pub struct MalformedSourceMapPositions
{
1811 pub source_len
: usize,
1812 pub begin_pos
: BytePos
,
1813 pub end_pos
: BytePos
,
1816 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1817 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1818 pub struct InnerSpan
{
1824 pub fn new(start
: usize, end
: usize) -> InnerSpan
{
1825 InnerSpan { start, end }
1829 // Given a slice of line start positions and a position, returns the index of
1830 // the line the position is on. Returns -1 if the position is located before
1832 fn lookup_line(lines
: &[BytePos
], pos
: BytePos
) -> isize {
1833 match lines
.binary_search(&pos
) {
1834 Ok(line
) => line
as isize,
1835 Err(line
) => line
as isize - 1,
1839 /// Requirements for a `StableHashingContext` to be used in this crate.
1840 /// This is a hack to allow using the `HashStable_Generic` derive macro
1841 /// instead of implementing everything in librustc_middle.
1842 pub trait HashStableContext
{
1843 fn hash_def_id(&mut self, _
: DefId
, hasher
: &mut StableHasher
);
1844 fn hash_crate_num(&mut self, _
: CrateNum
, hasher
: &mut StableHasher
);
1845 fn hash_spans(&self) -> bool
;
1846 fn byte_pos_to_line_and_col(
1849 ) -> Option
<(Lrc
<SourceFile
>, usize, BytePos
)>;
1852 impl<CTX
> HashStable
<CTX
> for Span
1854 CTX
: HashStableContext
,
1856 /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1857 /// fields (that would be similar to hashing pointers, since those are just
1858 /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1859 /// triple, which stays the same even if the containing `SourceFile` has moved
1860 /// within the `SourceMap`.
1861 /// Also note that we are hashing byte offsets for the column, not unicode
1862 /// codepoint offsets. For the purpose of the hash that's sufficient.
1863 /// Also, hashing filenames is expensive so we avoid doing it twice when the
1864 /// span starts and ends in the same file, which is almost always the case.
1865 fn hash_stable(&self, ctx
: &mut CTX
, hasher
: &mut StableHasher
) {
1866 const TAG_VALID_SPAN
: u8 = 0;
1867 const TAG_INVALID_SPAN
: u8 = 1;
1869 if !ctx
.hash_spans() {
1873 if *self == DUMMY_SP
{
1874 Hash
::hash(&TAG_INVALID_SPAN
, hasher
);
1878 // If this is not an empty or invalid span, we want to hash the last
1879 // position that belongs to it, as opposed to hashing the first
1880 // position past it.
1881 let span
= self.data();
1882 let (file_lo
, line_lo
, col_lo
) = match ctx
.byte_pos_to_line_and_col(span
.lo
) {
1885 Hash
::hash(&TAG_INVALID_SPAN
, hasher
);
1886 span
.ctxt
.hash_stable(ctx
, hasher
);
1891 if !file_lo
.contains(span
.hi
) {
1892 Hash
::hash(&TAG_INVALID_SPAN
, hasher
);
1893 span
.ctxt
.hash_stable(ctx
, hasher
);
1897 let (_
, line_hi
, col_hi
) = match ctx
.byte_pos_to_line_and_col(span
.hi
) {
1900 Hash
::hash(&TAG_INVALID_SPAN
, hasher
);
1901 span
.ctxt
.hash_stable(ctx
, hasher
);
1906 Hash
::hash(&TAG_VALID_SPAN
, hasher
);
1907 // We truncate the stable ID hash and line and column numbers. The chances
1908 // of causing a collision this way should be minimal.
1909 Hash
::hash(&(file_lo
.name_hash
as u64), hasher
);
1911 // Hash both the length and the end location (line/column) of a span. If we
1912 // hash only the length, for example, then two otherwise equal spans with
1913 // different end locations will have the same hash. This can cause a problem
1914 // during incremental compilation wherein a previous result for a query that
1915 // depends on the end location of a span will be incorrectly reused when the
1916 // end location of the span it depends on has changed (see issue #74890). A
1917 // similar analysis applies if some query depends specifically on the length
1918 // of the span, but we only hash the end location. So hash both.
1920 let col_lo_trunc
= (col_lo
.0 as u64) & 0xFF;
1921 let line_lo_trunc
= ((line_lo
as u64) & 0xFF_FF_FF) << 8;
1922 let col_hi_trunc
= (col_hi
.0 as u64) & 0xFF << 32;
1923 let line_hi_trunc
= ((line_hi
as u64) & 0xFF_FF_FF) << 40;
1924 let col_line
= col_lo_trunc
| line_lo_trunc
| col_hi_trunc
| line_hi_trunc
;
1925 let len
= (span
.hi
- span
.lo
).0;
1926 Hash
::hash(&col_line
, hasher
);
1927 Hash
::hash(&len
, hasher
);
1928 span
.ctxt
.hash_stable(ctx
, hasher
);
1932 impl<CTX
: HashStableContext
> HashStable
<CTX
> for SyntaxContext
{
1933 fn hash_stable(&self, ctx
: &mut CTX
, hasher
: &mut StableHasher
) {
1934 const TAG_EXPANSION
: u8 = 0;
1935 const TAG_NO_EXPANSION
: u8 = 1;
1937 if *self == SyntaxContext
::root() {
1938 TAG_NO_EXPANSION
.hash_stable(ctx
, hasher
);
1940 TAG_EXPANSION
.hash_stable(ctx
, hasher
);
1941 let (expn_id
, transparency
) = self.outer_mark();
1942 expn_id
.hash_stable(ctx
, hasher
);
1943 transparency
.hash_stable(ctx
, hasher
);
1948 impl<CTX
: HashStableContext
> HashStable
<CTX
> for ExpnId
{
1949 fn hash_stable(&self, ctx
: &mut CTX
, hasher
: &mut StableHasher
) {
1950 // Since the same expansion context is usually referenced many
1951 // times, we cache a stable hash of it and hash that instead of
1952 // recursing every time.
1954 static CACHE
: RefCell
<Vec
<Option
<Fingerprint
>>> = Default
::default();
1957 const TAG_ROOT
: u8 = 0;
1958 const TAG_NOT_ROOT
: u8 = 1;
1960 if *self == ExpnId
::root() {
1961 TAG_ROOT
.hash_stable(ctx
, hasher
);
1965 let index
= self.as_u32() as usize;
1966 let res
= CACHE
.with(|cache
| cache
.borrow().get(index
).copied().flatten());
1968 if let Some(res
) = res
{
1969 res
.hash_stable(ctx
, hasher
);
1971 let new_len
= index
+ 1;
1973 let mut sub_hasher
= StableHasher
::new();
1974 TAG_NOT_ROOT
.hash_stable(ctx
, &mut sub_hasher
);
1975 self.expn_data().hash_stable(ctx
, &mut sub_hasher
);
1976 let sub_hash
: Fingerprint
= sub_hasher
.finish();
1978 CACHE
.with(|cache
| {
1979 let mut cache
= cache
.borrow_mut();
1980 if cache
.len() < new_len
{
1981 cache
.resize(new_len
, None
);
1983 cache
[index
].replace(sub_hash
).expect_none("Cache slot was filled");
1985 sub_hash
.hash_stable(ctx
, hasher
);