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/")]
10 #![feature(crate_visibility_modifier)]
12 #![feature(optin_builtin_traits)]
13 #![feature(rustc_attrs)]
14 #![feature(specialization)]
15 #![feature(step_trait)]
17 use rustc_serialize::{Encodable, Decodable, Encoder, Decoder};
24 pub use hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind, MacroKind, DesugaringKind};
25 use hygiene::Transparency;
28 pub use span_encoding::{Span, DUMMY_SP};
31 pub use symbol::{Symbol, sym};
33 mod analyze_source_file;
36 use rustc_data_structures::stable_hasher::StableHasher;
37 use rustc_data_structures::sync::{Lrc, Lock};
41 use std::cmp::{self, Ordering};
43 use std::hash::{Hasher, Hash};
44 use std::ops::{Add, Sub};
45 use std::path::PathBuf;
51 symbol_interner: Lock<symbol::Interner>,
52 span_interner: Lock<span_encoding::SpanInterner>,
53 hygiene_data: Lock<hygiene::HygieneData>,
57 pub fn new(edition: Edition) -> Globals {
59 symbol_interner: Lock::new(symbol::Interner::fresh()),
60 span_interner: Lock::new(span_encoding::SpanInterner::default()),
61 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
66 scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
68 /// Differentiates between real files and common virtual files.
69 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
72 /// A macro. This includes the full name of the macro, so that there are no clashes.
78 /// Hack in `src/libsyntax/parse.rs`.
81 ProcMacroSourceCode(u64),
82 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
84 /// Strings provided as crate attributes in the CLI.
86 /// Custom sources for explicit parser calls from plugins and drivers.
88 DocTest(PathBuf, isize),
91 impl std::fmt::Display for FileName {
92 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 Real(ref path) => write!(fmt, "{}", path.display()),
96 Macros(ref name) => write!(fmt, "<{} macros>", name),
97 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
98 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
99 Anon(_) => write!(fmt, "<anon>"),
100 ProcMacroSourceCode(_) =>
101 write!(fmt, "<proc-macro source code>"),
102 CfgSpec(_) => write!(fmt, "<cfgspec>"),
103 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
104 Custom(ref s) => write!(fmt, "<{}>", s),
105 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
110 impl From<PathBuf> for FileName {
111 fn from(p: PathBuf) -> Self {
112 assert!(!p.to_string_lossy().ends_with('>'));
118 pub fn is_real(&self) -> bool {
125 ProcMacroSourceCode(_) |
130 DocTest(_, _) => false,
134 pub fn is_macros(&self) -> bool {
140 ProcMacroSourceCode(_) |
145 DocTest(_, _) => false,
150 pub fn quote_expansion_source_code(src: &str) -> FileName {
151 let mut hasher = StableHasher::new();
152 src.hash(&mut hasher);
153 FileName::QuoteExpansion(hasher.finish())
156 pub fn macro_expansion_source_code(src: &str) -> FileName {
157 let mut hasher = StableHasher::new();
158 src.hash(&mut hasher);
159 FileName::MacroExpansion(hasher.finish())
162 pub fn anon_source_code(src: &str) -> FileName {
163 let mut hasher = StableHasher::new();
164 src.hash(&mut hasher);
165 FileName::Anon(hasher.finish())
168 pub fn proc_macro_source_code(src: &str) -> FileName {
169 let mut hasher = StableHasher::new();
170 src.hash(&mut hasher);
171 FileName::ProcMacroSourceCode(hasher.finish())
174 pub fn cfg_spec_source_code(src: &str) -> FileName {
175 let mut hasher = StableHasher::new();
176 src.hash(&mut hasher);
177 FileName::QuoteExpansion(hasher.finish())
180 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
181 let mut hasher = StableHasher::new();
182 src.hash(&mut hasher);
183 FileName::CliCrateAttr(hasher.finish())
186 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{
187 FileName::DocTest(path, line)
191 /// Spans represent a region of code, used for error reporting. Positions in spans
192 /// are *absolute* positions from the beginning of the source_map, not positions
193 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
194 /// to the original source.
195 /// You must be careful if the span crosses more than one file - you will not be
196 /// able to use many of the functions on spans in source_map and you cannot assume
197 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
198 /// range between files.
200 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
201 /// sent to other threads, but some pieces of performance infra run in a separate thread.
202 /// Using `Span` is generally preferred.
203 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
204 pub struct SpanData {
207 /// Information about where the macro came from, if this piece of
208 /// code was created by a macro expansion.
209 pub ctxt: SyntaxContext,
214 pub fn with_lo(&self, lo: BytePos) -> Span {
215 Span::new(lo, self.hi, self.ctxt)
218 pub fn with_hi(&self, hi: BytePos) -> Span {
219 Span::new(self.lo, hi, self.ctxt)
222 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
223 Span::new(self.lo, self.hi, ctxt)
227 // The interner is pointed to by a thread local value which is only set on the main thread
228 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
229 // to avoid panics and other errors, even though it would be memory safe to do so.
230 #[cfg(not(parallel_compiler))]
231 impl !Send for Span {}
232 #[cfg(not(parallel_compiler))]
233 impl !Sync for Span {}
235 impl PartialOrd for Span {
236 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
237 PartialOrd::partial_cmp(&self.data(), &rhs.data())
241 fn cmp(&self, rhs: &Self) -> Ordering {
242 Ord::cmp(&self.data(), &rhs.data())
246 /// A collection of spans. Spans have two orthogonal attributes:
248 /// - They can be *primary spans*. In this case they are the locus of
249 /// the error, and would be rendered with `^^^`.
250 /// - They can have a *label*. In this case, the label is written next
251 /// to the mark in the snippet when we render.
252 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
253 pub struct MultiSpan {
254 primary_spans: Vec<Span>,
255 span_labels: Vec<(Span, String)>,
260 pub fn lo(self) -> BytePos {
264 pub fn with_lo(self, lo: BytePos) -> Span {
265 self.data().with_lo(lo)
268 pub fn hi(self) -> BytePos {
272 pub fn with_hi(self, hi: BytePos) -> Span {
273 self.data().with_hi(hi)
276 pub fn ctxt(self) -> SyntaxContext {
280 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
281 self.data().with_ctxt(ctxt)
284 /// Returns `true` if this is a dummy span with any hygienic context.
286 pub fn is_dummy(self) -> bool {
287 let span = self.data();
288 span.lo.0 == 0 && span.hi.0 == 0
291 /// Returns `true` if this span comes from a macro or desugaring.
293 pub fn from_expansion(self) -> bool {
294 self.ctxt() != SyntaxContext::root()
298 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
299 Span::new(lo, hi, SyntaxContext::root())
302 /// Returns a new span representing an empty span at the beginning of this span
304 pub fn shrink_to_lo(self) -> Span {
305 let span = self.data();
306 span.with_hi(span.lo)
308 /// Returns a new span representing an empty span at the end of this span.
310 pub fn shrink_to_hi(self) -> Span {
311 let span = self.data();
312 span.with_lo(span.hi)
315 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
316 pub fn substitute_dummy(self, other: Span) -> Span {
317 if self.is_dummy() { other } else { self }
320 /// Returns `true` if `self` fully encloses `other`.
321 pub fn contains(self, other: Span) -> bool {
322 let span = self.data();
323 let other = other.data();
324 span.lo <= other.lo && other.hi <= span.hi
327 /// Returns `true` if `self` touches `other`.
328 pub fn overlaps(self, other: Span) -> bool {
329 let span = self.data();
330 let other = other.data();
331 span.lo < other.hi && other.lo < span.hi
334 /// Returns `true` if the spans are equal with regards to the source text.
336 /// Use this instead of `==` when either span could be generated code,
337 /// and you only care that they point to the same bytes of source text.
338 pub fn source_equal(&self, other: &Span) -> bool {
339 let span = self.data();
340 let other = other.data();
341 span.lo == other.lo && span.hi == other.hi
344 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
345 pub fn trim_start(self, other: Span) -> Option<Span> {
346 let span = self.data();
347 let other = other.data();
348 if span.hi > other.hi {
349 Some(span.with_lo(cmp::max(span.lo, other.hi)))
355 /// Returns the source span -- this is either the supplied span, or the span for
356 /// the macro callsite that expanded to it.
357 pub fn source_callsite(self) -> Span {
358 let expn_data = self.ctxt().outer_expn_data();
359 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
362 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
364 pub fn parent(self) -> Option<Span> {
365 let expn_data = self.ctxt().outer_expn_data();
366 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
369 /// Edition of the crate from which this span came.
370 pub fn edition(self) -> edition::Edition {
371 self.ctxt().outer_expn_data().edition
375 pub fn rust_2015(&self) -> bool {
376 self.edition() == edition::Edition::Edition2015
380 pub fn rust_2018(&self) -> bool {
381 self.edition() >= edition::Edition::Edition2018
384 /// Returns the source callee.
386 /// Returns `None` if the supplied span has no expansion trace,
387 /// else returns the `ExpnData` for the macro definition
388 /// corresponding to the source callsite.
389 pub fn source_callee(self) -> Option<ExpnData> {
390 fn source_callee(expn_data: ExpnData) -> ExpnData {
391 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
392 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
394 let expn_data = self.ctxt().outer_expn_data();
395 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
398 /// Checks if a span is "internal" to a macro in which `#[unstable]`
399 /// items can be used (that is, a macro marked with
400 /// `#[allow_internal_unstable]`).
401 pub fn allows_unstable(&self, feature: Symbol) -> bool {
402 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
403 features.iter().any(|&f| {
404 f == feature || f == sym::allow_internal_unstable_backcompat_hack
409 /// Checks if this span arises from a compiler desugaring of kind `kind`.
410 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
411 match self.ctxt().outer_expn_data().kind {
412 ExpnKind::Desugaring(k) => k == kind,
417 /// Returns the compiler desugaring that created this span, or `None`
418 /// if this span is not from a desugaring.
419 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
420 match self.ctxt().outer_expn_data().kind {
421 ExpnKind::Desugaring(k) => Some(k),
426 /// Checks if a span is "internal" to a macro in which `unsafe`
427 /// can be used without triggering the `unsafe_code` lint
428 // (that is, a macro marked with `#[allow_internal_unsafe]`).
429 pub fn allows_unsafe(&self) -> bool {
430 self.ctxt().outer_expn_data().allow_internal_unsafe
433 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
434 let mut prev_span = DUMMY_SP;
435 let mut result = vec![];
437 let expn_data = self.ctxt().outer_expn_data();
438 if expn_data.is_root() {
441 // Don't print recursive invocations.
442 if !expn_data.call_site.source_equal(&prev_span) {
443 let (pre, post) = match expn_data.kind {
444 ExpnKind::Root => break,
445 ExpnKind::Desugaring(..) => ("desugaring of ", ""),
446 ExpnKind::AstPass(..) => ("", ""),
447 ExpnKind::Macro(macro_kind, _) => match macro_kind {
448 MacroKind::Bang => ("", "!"),
449 MacroKind::Attr => ("#[", "]"),
450 MacroKind::Derive => ("#[derive(", ")]"),
453 result.push(MacroBacktrace {
454 call_site: expn_data.call_site,
455 macro_decl_name: format!("{}{}{}", pre, expn_data.kind.descr(), post),
456 def_site_span: expn_data.def_site,
461 self = expn_data.call_site;
466 /// Returns a `Span` that would enclose both `self` and `end`.
467 pub fn to(self, end: Span) -> Span {
468 let span_data = self.data();
469 let end_data = end.data();
470 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
471 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
472 // have an incomplete span than a completely nonsensical one.
473 if span_data.ctxt != end_data.ctxt {
474 if span_data.ctxt == SyntaxContext::root() {
476 } else if end_data.ctxt == SyntaxContext::root() {
479 // Both spans fall within a macro.
480 // FIXME(estebank): check if it is the *same* macro.
483 cmp::min(span_data.lo, end_data.lo),
484 cmp::max(span_data.hi, end_data.hi),
485 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
489 /// Returns a `Span` between the end of `self` to the beginning of `end`.
490 pub fn between(self, end: Span) -> Span {
491 let span = self.data();
492 let end = end.data();
496 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
500 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
501 pub fn until(self, end: Span) -> Span {
502 let span = self.data();
503 let end = end.data();
507 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
511 pub fn from_inner(self, inner: InnerSpan) -> Span {
512 let span = self.data();
513 Span::new(span.lo + BytePos::from_usize(inner.start),
514 span.lo + BytePos::from_usize(inner.end),
518 /// Equivalent of `Span::def_site` from the proc macro API,
519 /// except that the location is taken from the `self` span.
520 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
521 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
524 /// Equivalent of `Span::call_site` from the proc macro API,
525 /// except that the location is taken from the `self` span.
526 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
527 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
530 /// Equivalent of `Span::mixed_site` from the proc macro API,
531 /// except that the location is taken from the `self` span.
532 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
533 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
536 /// Produces a span with the same location as `self` and context produced by a macro with the
537 /// given ID and transparency, assuming that macro was defined directly and not produced by
538 /// some other macro (which is the case for built-in and procedural macros).
539 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
540 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
544 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
545 let span = self.data();
546 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
550 pub fn remove_mark(&mut self) -> ExpnId {
551 let mut span = self.data();
552 let mark = span.ctxt.remove_mark();
553 *self = Span::new(span.lo, span.hi, span.ctxt);
558 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
559 let mut span = self.data();
560 let mark = span.ctxt.adjust(expn_id);
561 *self = Span::new(span.lo, span.hi, span.ctxt);
566 pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
567 let mut span = self.data();
568 let mark = span.ctxt.modernize_and_adjust(expn_id);
569 *self = Span::new(span.lo, span.hi, span.ctxt);
574 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
575 let mut span = self.data();
576 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
577 *self = Span::new(span.lo, span.hi, span.ctxt);
582 pub fn reverse_glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span)
583 -> Option<Option<ExpnId>> {
584 let mut span = self.data();
585 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
586 *self = Span::new(span.lo, span.hi, span.ctxt);
591 pub fn modern(self) -> Span {
592 let span = self.data();
593 span.with_ctxt(span.ctxt.modern())
597 pub fn modern_and_legacy(self) -> Span {
598 let span = self.data();
599 span.with_ctxt(span.ctxt.modern_and_legacy())
603 #[derive(Clone, Debug)]
604 pub struct SpanLabel {
605 /// The span we are going to include in the final snippet.
608 /// Is this a primary span? This is the "locus" of the message,
609 /// and is indicated with a `^^^^` underline, versus `----`.
610 pub is_primary: bool,
612 /// What label should we attach to this span (if any)?
613 pub label: Option<String>,
616 impl Default for Span {
617 fn default() -> Self {
622 impl rustc_serialize::UseSpecializedEncodable for Span {
623 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
624 let span = self.data();
625 s.emit_struct("Span", 2, |s| {
626 s.emit_struct_field("lo", 0, |s| {
630 s.emit_struct_field("hi", 1, |s| {
637 impl rustc_serialize::UseSpecializedDecodable for Span {
638 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
639 d.read_struct("Span", 2, |d| {
640 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
641 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
642 Ok(Span::with_root_ctxt(lo, hi))
647 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
648 f.debug_struct("Span")
649 .field("lo", &span.lo())
650 .field("hi", &span.hi())
651 .field("ctxt", &span.ctxt())
655 impl fmt::Debug for Span {
656 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
657 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
661 impl fmt::Debug for SpanData {
662 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
663 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
669 pub fn new() -> MultiSpan {
671 primary_spans: vec![],
676 pub fn from_span(primary_span: Span) -> MultiSpan {
678 primary_spans: vec![primary_span],
683 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
690 pub fn push_span_label(&mut self, span: Span, label: String) {
691 self.span_labels.push((span, label));
694 /// Selects the first primary span (if any).
695 pub fn primary_span(&self) -> Option<Span> {
696 self.primary_spans.first().cloned()
699 /// Returns all primary spans.
700 pub fn primary_spans(&self) -> &[Span] {
704 /// Returns `true` if any of the primary spans are displayable.
705 pub fn has_primary_spans(&self) -> bool {
706 self.primary_spans.iter().any(|sp| !sp.is_dummy())
709 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
710 pub fn is_dummy(&self) -> bool {
711 let mut is_dummy = true;
712 for span in &self.primary_spans {
713 if !span.is_dummy() {
720 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
721 /// display well (like std macros). Returns whether replacements occurred.
722 pub fn replace(&mut self, before: Span, after: Span) -> bool {
723 let mut replacements_occurred = false;
724 for primary_span in &mut self.primary_spans {
725 if *primary_span == before {
726 *primary_span = after;
727 replacements_occurred = true;
730 for span_label in &mut self.span_labels {
731 if span_label.0 == before {
732 span_label.0 = after;
733 replacements_occurred = true;
736 replacements_occurred
739 /// Returns the strings to highlight. We always ensure that there
740 /// is an entry for each of the primary spans -- for each primary
741 /// span `P`, if there is at least one label with span `P`, we return
742 /// those labels (marked as primary). But otherwise we return
743 /// `SpanLabel` instances with empty labels.
744 pub fn span_labels(&self) -> Vec<SpanLabel> {
745 let is_primary = |span| self.primary_spans.contains(&span);
747 let mut span_labels = self.span_labels.iter().map(|&(span, ref label)|
750 is_primary: is_primary(span),
751 label: Some(label.clone())
753 ).collect::<Vec<_>>();
755 for &span in &self.primary_spans {
756 if !span_labels.iter().any(|sl| sl.span == span) {
757 span_labels.push(SpanLabel {
768 /// Returns `true` if any of the span labels is displayable.
769 pub fn has_span_labels(&self) -> bool {
770 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
774 impl From<Span> for MultiSpan {
775 fn from(span: Span) -> MultiSpan {
776 MultiSpan::from_span(span)
780 impl From<Vec<Span>> for MultiSpan {
781 fn from(spans: Vec<Span>) -> MultiSpan {
782 MultiSpan::from_spans(spans)
786 /// Identifies an offset of a multi-byte character in a `SourceFile`.
787 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
788 pub struct MultiByteChar {
789 /// The absolute offset of the character in the `SourceMap`.
791 /// The number of bytes, `>= 2`.
795 /// Identifies an offset of a non-narrow character in a `SourceFile`.
796 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
797 pub enum NonNarrowChar {
798 /// Represents a zero-width character.
800 /// Represents a wide (full-width) character.
802 /// Represents a tab character, represented visually with a width of 4 characters.
807 fn new(pos: BytePos, width: usize) -> Self {
809 0 => NonNarrowChar::ZeroWidth(pos),
810 2 => NonNarrowChar::Wide(pos),
811 4 => NonNarrowChar::Tab(pos),
812 _ => panic!("width {} given for non-narrow character", width),
816 /// Returns the absolute offset of the character in the `SourceMap`.
817 pub fn pos(&self) -> BytePos {
819 NonNarrowChar::ZeroWidth(p) |
820 NonNarrowChar::Wide(p) |
821 NonNarrowChar::Tab(p) => p,
825 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
826 pub fn width(&self) -> usize {
828 NonNarrowChar::ZeroWidth(_) => 0,
829 NonNarrowChar::Wide(_) => 2,
830 NonNarrowChar::Tab(_) => 4,
835 impl Add<BytePos> for NonNarrowChar {
838 fn add(self, rhs: BytePos) -> Self {
840 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
841 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
842 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
847 impl Sub<BytePos> for NonNarrowChar {
850 fn sub(self, rhs: BytePos) -> Self {
852 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
853 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
854 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
859 /// Identifies an offset of a character that was normalized away from `SourceFile`.
860 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
861 pub struct NormalizedPos {
862 /// The absolute offset of the character in the `SourceMap`.
864 /// The difference between original and normalized string at position.
868 /// The state of the lazy external source loading mechanism of a `SourceFile`.
869 #[derive(PartialEq, Eq, Clone)]
870 pub enum ExternalSource {
871 /// The external source has been loaded already.
873 /// No attempt has been made to load the external source.
875 /// A failed attempt has been made to load the external source.
877 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
881 impl ExternalSource {
882 pub fn is_absent(&self) -> bool {
884 ExternalSource::Present(_) => false,
889 pub fn get_source(&self) -> Option<&str> {
891 ExternalSource::Present(ref src) => Some(src),
898 pub struct OffsetOverflowError;
900 /// A single source in the `SourceMap`.
902 pub struct SourceFile {
903 /// The name of the file that the source came from. Source that doesn't
904 /// originate from files has names between angle brackets by convention
905 /// (e.g., `<anon>`).
907 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
908 pub name_was_remapped: bool,
909 /// The unmapped path of the file that the source came from.
910 /// Set to `None` if the `SourceFile` was imported from an external crate.
911 pub unmapped_path: Option<FileName>,
912 /// Indicates which crate this `SourceFile` was imported from.
913 pub crate_of_origin: u32,
914 /// The complete source code.
915 pub src: Option<Lrc<String>>,
916 /// The source code's hash.
918 /// The external source code (used for external crates, which will have a `None`
919 /// value as `self.src`.
920 pub external_src: Lock<ExternalSource>,
921 /// The start position of this source in the `SourceMap`.
922 pub start_pos: BytePos,
923 /// The end position of this source in the `SourceMap`.
924 pub end_pos: BytePos,
925 /// Locations of lines beginnings in the source code.
926 pub lines: Vec<BytePos>,
927 /// Locations of multi-byte characters in the source code.
928 pub multibyte_chars: Vec<MultiByteChar>,
929 /// Width of characters that are not narrow in the source code.
930 pub non_narrow_chars: Vec<NonNarrowChar>,
931 /// Locations of characters removed during normalization.
932 pub normalized_pos: Vec<NormalizedPos>,
933 /// A hash of the filename, used for speeding up hashing in incremental compilation.
937 impl Encodable for SourceFile {
938 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
939 s.emit_struct("SourceFile", 8, |s| {
940 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
941 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
942 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
943 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
944 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
945 s.emit_struct_field("lines", 5, |s| {
946 let lines = &self.lines[..];
948 s.emit_u32(lines.len() as u32)?;
950 if !lines.is_empty() {
951 // In order to preserve some space, we exploit the fact that
952 // the lines list is sorted and individual lines are
953 // probably not that long. Because of that we can store lines
954 // as a difference list, using as little space as possible
955 // for the differences.
956 let max_line_length = if lines.len() == 1 {
960 .map(|w| w[1] - w[0])
961 .map(|bp| bp.to_usize())
966 let bytes_per_diff: u8 = match max_line_length {
968 0x100 ..= 0xFFFF => 2,
972 // Encode the number of bytes used per diff.
973 bytes_per_diff.encode(s)?;
975 // Encode the first element.
978 let diff_iter = (&lines[..]).windows(2)
979 .map(|w| (w[1] - w[0]));
981 match bytes_per_diff {
982 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
983 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
984 4 => for diff in diff_iter { diff.0.encode(s)? },
991 s.emit_struct_field("multibyte_chars", 6, |s| {
992 self.multibyte_chars.encode(s)
994 s.emit_struct_field("non_narrow_chars", 7, |s| {
995 self.non_narrow_chars.encode(s)
997 s.emit_struct_field("name_hash", 8, |s| {
998 self.name_hash.encode(s)
1000 s.emit_struct_field("normalized_pos", 9, |s| {
1001 self.normalized_pos.encode(s)
1007 impl Decodable for SourceFile {
1008 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
1009 d.read_struct("SourceFile", 8, |d| {
1010 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1011 let name_was_remapped: bool =
1012 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1013 let src_hash: u128 =
1014 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1015 let start_pos: BytePos =
1016 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1017 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1018 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1019 let num_lines: u32 = Decodable::decode(d)?;
1020 let mut lines = Vec::with_capacity(num_lines as usize);
1023 // Read the number of bytes used per diff.
1024 let bytes_per_diff: u8 = Decodable::decode(d)?;
1026 // Read the first element.
1027 let mut line_start: BytePos = Decodable::decode(d)?;
1028 lines.push(line_start);
1030 for _ in 1..num_lines {
1031 let diff = match bytes_per_diff {
1032 1 => d.read_u8()? as u32,
1033 2 => d.read_u16()? as u32,
1038 line_start = line_start + BytePos(diff);
1040 lines.push(line_start);
1046 let multibyte_chars: Vec<MultiByteChar> =
1047 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1048 let non_narrow_chars: Vec<NonNarrowChar> =
1049 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1050 let name_hash: u128 =
1051 d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1052 let normalized_pos: Vec<NormalizedPos> =
1053 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1057 unmapped_path: None,
1058 // `crate_of_origin` has to be set by the importer.
1059 // This value matches up with `rustc::hir::def_id::INVALID_CRATE`.
1060 // That constant is not available here, unfortunately.
1061 crate_of_origin: std::u32::MAX - 1,
1066 external_src: Lock::new(ExternalSource::AbsentOk),
1077 impl fmt::Debug for SourceFile {
1078 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1079 write!(fmt, "SourceFile({})", self.name)
1084 pub fn new(name: FileName,
1085 name_was_remapped: bool,
1086 unmapped_path: FileName,
1088 start_pos: BytePos) -> Result<SourceFile, OffsetOverflowError> {
1089 let normalized_pos = normalize_src(&mut src, start_pos);
1092 let mut hasher: StableHasher = StableHasher::new();
1093 hasher.write(src.as_bytes());
1094 hasher.finish::<u128>()
1097 let mut hasher: StableHasher = StableHasher::new();
1098 name.hash(&mut hasher);
1099 hasher.finish::<u128>()
1101 let end_pos = start_pos.to_usize() + src.len();
1102 if end_pos > u32::max_value() as usize {
1103 return Err(OffsetOverflowError);
1106 let (lines, multibyte_chars, non_narrow_chars) =
1107 analyze_source_file::analyze_source_file(&src[..], start_pos);
1112 unmapped_path: Some(unmapped_path),
1114 src: Some(Lrc::new(src)),
1116 external_src: Lock::new(ExternalSource::Unneeded),
1118 end_pos: Pos::from_usize(end_pos),
1127 /// Returns the `BytePos` of the beginning of the current line.
1128 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1129 let line_index = self.lookup_line(pos).unwrap();
1130 self.lines[line_index]
1133 /// Add externally loaded source.
1134 /// If the hash of the input doesn't match or no input is supplied via None,
1135 /// it is interpreted as an error and the corresponding enum variant is set.
1136 /// The return value signifies whether some kind of source is present.
1137 pub fn add_external_src<F>(&self, get_src: F) -> bool
1138 where F: FnOnce() -> Option<String>
1140 if *self.external_src.borrow() == ExternalSource::AbsentOk {
1141 let src = get_src();
1142 let mut external_src = self.external_src.borrow_mut();
1143 // Check that no-one else have provided the source while we were getting it
1144 if *external_src == ExternalSource::AbsentOk {
1145 if let Some(src) = src {
1146 let mut hasher: StableHasher = StableHasher::new();
1147 hasher.write(src.as_bytes());
1149 if hasher.finish::<u128>() == self.src_hash {
1150 *external_src = ExternalSource::Present(src);
1154 *external_src = ExternalSource::AbsentErr;
1159 self.src.is_some() || external_src.get_source().is_some()
1162 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1166 /// Gets a line from the list of pre-computed line-beginnings.
1167 /// The line number here is 0-based.
1168 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1169 fn get_until_newline(src: &str, begin: usize) -> &str {
1170 // We can't use `lines.get(line_number+1)` because we might
1171 // be parsing when we call this function and thus the current
1172 // line is the last one we have line info for.
1173 let slice = &src[begin..];
1174 match slice.find('\n') {
1175 Some(e) => &slice[..e],
1181 let line = if let Some(line) = self.lines.get(line_number) {
1186 let begin: BytePos = *line - self.start_pos;
1190 if let Some(ref src) = self.src {
1191 Some(Cow::from(get_until_newline(src, begin)))
1192 } else if let Some(src) = self.external_src.borrow().get_source() {
1193 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1199 pub fn is_real_file(&self) -> bool {
1203 pub fn is_imported(&self) -> bool {
1207 pub fn byte_length(&self) -> u32 {
1208 self.end_pos.0 - self.start_pos.0
1210 pub fn count_lines(&self) -> usize {
1214 /// Finds the line containing the given position. The return value is the
1215 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1216 /// number. If the source_file is empty or the position is located before the
1217 /// first line, `None` is returned.
1218 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1219 if self.lines.len() == 0 {
1223 let line_index = lookup_line(&self.lines[..], pos);
1224 assert!(line_index < self.lines.len() as isize);
1225 if line_index >= 0 {
1226 Some(line_index as usize)
1232 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1233 if self.start_pos == self.end_pos {
1234 return (self.start_pos, self.end_pos);
1237 assert!(line_index < self.lines.len());
1238 if line_index == (self.lines.len() - 1) {
1239 (self.lines[line_index], self.end_pos)
1241 (self.lines[line_index], self.lines[line_index + 1])
1246 pub fn contains(&self, byte_pos: BytePos) -> bool {
1247 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1250 /// Calculates the original byte position relative to the start of the file
1251 /// based on the given byte position.
1252 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1254 // Diff before any records is 0. Otherwise use the previously recorded
1255 // diff as that applies to the following characters until a new diff
1257 let diff = match self.normalized_pos.binary_search_by(
1258 |np| np.pos.cmp(&pos)) {
1259 Ok(i) => self.normalized_pos[i].diff,
1260 Err(i) if i == 0 => 0,
1261 Err(i) => self.normalized_pos[i-1].diff,
1264 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1268 /// Normalizes the source code and records the normalizations.
1269 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1270 let mut normalized_pos = vec![];
1271 remove_bom(src, &mut normalized_pos);
1272 normalize_newlines(src, &mut normalized_pos);
1274 // Offset all the positions by start_pos to match the final file positions.
1275 for np in &mut normalized_pos {
1276 np.pos.0 += start_pos.0;
1282 /// Removes UTF-8 BOM, if any.
1283 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1284 if src.starts_with("\u{feff}") {
1286 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1291 /// Replaces `\r\n` with `\n` in-place in `src`.
1293 /// Returns error if there's a lone `\r` in the string
1294 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1295 if !src.as_bytes().contains(&b'\r') {
1299 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1300 // While we *can* call `as_mut_vec` and do surgery on the live string
1301 // directly, let's rather steal the contents of `src`. This makes the code
1302 // safe even if a panic occurs.
1304 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1305 let mut gap_len = 0;
1306 let mut tail = buf.as_mut_slice();
1308 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1310 let idx = match find_crlf(&tail[gap_len..]) {
1312 Some(idx) => idx + gap_len,
1314 tail.copy_within(gap_len..idx, 0);
1315 tail = &mut tail[idx - gap_len..];
1316 if tail.len() == gap_len {
1319 cursor += idx - gap_len;
1321 normalized_pos.push(NormalizedPos {
1322 pos: BytePos::from_usize(cursor + 1),
1323 diff: original_gap + gap_len as u32,
1327 // Account for removed `\r`.
1328 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1329 let new_len = buf.len() - gap_len;
1331 buf.set_len(new_len);
1332 *src = String::from_utf8_unchecked(buf);
1335 fn find_crlf(src: &[u8]) -> Option<usize> {
1336 let mut search_idx = 0;
1337 while let Some(idx) = find_cr(&src[search_idx..]) {
1338 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1339 search_idx += idx + 1;
1342 return Some(search_idx + idx);
1347 fn find_cr(src: &[u8]) -> Option<usize> {
1348 src.iter().position(|&b| b == b'\r')
1352 // _____________________________________________________________________________
1353 // Pos, BytePos, CharPos
1357 fn from_usize(n: usize) -> Self;
1358 fn to_usize(&self) -> usize;
1359 fn from_u32(n: u32) -> Self;
1360 fn to_u32(&self) -> u32;
1363 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1365 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1366 pub struct BytePos(pub u32);
1368 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1369 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1370 /// values to `CharPos` values as necessary.
1371 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1372 pub struct CharPos(pub usize);
1374 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1375 // have been unsuccessful.
1377 impl Pos for BytePos {
1379 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1382 fn to_usize(&self) -> usize { self.0 as usize }
1385 fn from_u32(n: u32) -> BytePos { BytePos(n) }
1388 fn to_u32(&self) -> u32 { self.0 }
1391 impl Add for BytePos {
1392 type Output = BytePos;
1395 fn add(self, rhs: BytePos) -> BytePos {
1396 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1400 impl Sub for BytePos {
1401 type Output = BytePos;
1404 fn sub(self, rhs: BytePos) -> BytePos {
1405 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1409 impl Encodable for BytePos {
1410 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1415 impl Decodable for BytePos {
1416 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1417 Ok(BytePos(d.read_u32()?))
1421 impl Pos for CharPos {
1423 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1426 fn to_usize(&self) -> usize { self.0 }
1429 fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1432 fn to_u32(&self) -> u32 { self.0 as u32}
1435 impl Add for CharPos {
1436 type Output = CharPos;
1439 fn add(self, rhs: CharPos) -> CharPos {
1440 CharPos(self.to_usize() + rhs.to_usize())
1444 impl Sub for CharPos {
1445 type Output = CharPos;
1448 fn sub(self, rhs: CharPos) -> CharPos {
1449 CharPos(self.to_usize() - rhs.to_usize())
1453 // _____________________________________________________________________________
1454 // Loc, SourceFileAndLine, SourceFileAndBytePos
1457 /// A source code location used for error reporting.
1458 #[derive(Debug, Clone)]
1460 /// Information about the original source.
1461 pub file: Lrc<SourceFile>,
1462 /// The (1-based) line number.
1464 /// The (0-based) column offset.
1466 /// The (0-based) column offset when displayed.
1467 pub col_display: usize,
1470 // Used to be structural records.
1472 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1474 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1476 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1477 pub struct LineInfo {
1478 /// Index of line, starting from 0.
1479 pub line_index: usize,
1481 /// Column in line where span begins, starting from 0.
1482 pub start_col: CharPos,
1484 /// Column in line where span ends, starting from 0, exclusive.
1485 pub end_col: CharPos,
1488 pub struct FileLines {
1489 pub file: Lrc<SourceFile>,
1490 pub lines: Vec<LineInfo>
1493 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1494 Cell::new(default_span_debug));
1497 pub struct MacroBacktrace {
1498 /// span where macro was applied to generate this code
1499 pub call_site: Span,
1501 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1502 pub macro_decl_name: String,
1504 /// span where macro was defined (possibly dummy)
1505 pub def_site_span: Span,
1508 // _____________________________________________________________________________
1509 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1512 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1514 #[derive(Clone, PartialEq, Eq, Debug)]
1515 pub enum SpanLinesError {
1516 DistinctSources(DistinctSources),
1519 #[derive(Clone, PartialEq, Eq, Debug)]
1520 pub enum SpanSnippetError {
1521 IllFormedSpan(Span),
1522 DistinctSources(DistinctSources),
1523 MalformedForSourcemap(MalformedSourceMapPositions),
1524 SourceNotAvailable { filename: FileName }
1527 #[derive(Clone, PartialEq, Eq, Debug)]
1528 pub struct DistinctSources {
1529 pub begin: (FileName, BytePos),
1530 pub end: (FileName, BytePos)
1533 #[derive(Clone, PartialEq, Eq, Debug)]
1534 pub struct MalformedSourceMapPositions {
1536 pub source_len: usize,
1537 pub begin_pos: BytePos,
1538 pub end_pos: BytePos
1541 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1542 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1543 pub struct InnerSpan {
1549 pub fn new(start: usize, end: usize) -> InnerSpan {
1550 InnerSpan { start, end }
1554 // Given a slice of line start positions and a position, returns the index of
1555 // the line the position is on. Returns -1 if the position is located before
1557 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1558 match lines.binary_search(&pos) {
1559 Ok(line) => line as isize,
1560 Err(line) => line as isize - 1