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};
18 use rustc_macros::HashStable_Generic;
25 pub use hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind, MacroKind, DesugaringKind};
26 use hygiene::Transparency;
29 pub use span_encoding::{Span, DUMMY_SP};
32 pub use symbol::{Symbol, sym};
34 mod analyze_source_file;
37 use rustc_data_structures::stable_hasher::StableHasher;
38 use rustc_data_structures::sync::{Lrc, Lock};
42 use std::cmp::{self, Ordering};
44 use std::hash::{Hasher, Hash};
45 use std::ops::{Add, Sub};
46 use std::path::PathBuf;
52 symbol_interner: Lock<symbol::Interner>,
53 span_interner: Lock<span_encoding::SpanInterner>,
54 hygiene_data: Lock<hygiene::HygieneData>,
58 pub fn new(edition: Edition) -> Globals {
60 symbol_interner: Lock::new(symbol::Interner::fresh()),
61 span_interner: Lock::new(span_encoding::SpanInterner::default()),
62 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
67 scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
69 /// Differentiates between real files and common virtual files.
70 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash,
71 RustcDecodable, RustcEncodable, HashStable_Generic)]
74 /// A macro. This includes the full name of the macro, so that there are no clashes.
80 /// Hack in `src/libsyntax/parse.rs`.
83 ProcMacroSourceCode(u64),
84 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
86 /// Strings provided as crate attributes in the CLI.
88 /// Custom sources for explicit parser calls from plugins and drivers.
90 DocTest(PathBuf, isize),
93 impl std::fmt::Display for FileName {
94 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 Real(ref path) => write!(fmt, "{}", path.display()),
98 Macros(ref name) => write!(fmt, "<{} macros>", name),
99 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
100 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
101 Anon(_) => write!(fmt, "<anon>"),
102 ProcMacroSourceCode(_) =>
103 write!(fmt, "<proc-macro source code>"),
104 CfgSpec(_) => write!(fmt, "<cfgspec>"),
105 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
106 Custom(ref s) => write!(fmt, "<{}>", s),
107 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
112 impl From<PathBuf> for FileName {
113 fn from(p: PathBuf) -> Self {
114 assert!(!p.to_string_lossy().ends_with('>'));
120 pub fn is_real(&self) -> bool {
127 ProcMacroSourceCode(_) |
132 DocTest(_, _) => false,
136 pub fn is_macros(&self) -> bool {
142 ProcMacroSourceCode(_) |
147 DocTest(_, _) => false,
152 pub fn quote_expansion_source_code(src: &str) -> FileName {
153 let mut hasher = StableHasher::new();
154 src.hash(&mut hasher);
155 FileName::QuoteExpansion(hasher.finish())
158 pub fn macro_expansion_source_code(src: &str) -> FileName {
159 let mut hasher = StableHasher::new();
160 src.hash(&mut hasher);
161 FileName::MacroExpansion(hasher.finish())
164 pub fn anon_source_code(src: &str) -> FileName {
165 let mut hasher = StableHasher::new();
166 src.hash(&mut hasher);
167 FileName::Anon(hasher.finish())
170 pub fn proc_macro_source_code(src: &str) -> FileName {
171 let mut hasher = StableHasher::new();
172 src.hash(&mut hasher);
173 FileName::ProcMacroSourceCode(hasher.finish())
176 pub fn cfg_spec_source_code(src: &str) -> FileName {
177 let mut hasher = StableHasher::new();
178 src.hash(&mut hasher);
179 FileName::QuoteExpansion(hasher.finish())
182 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
183 let mut hasher = StableHasher::new();
184 src.hash(&mut hasher);
185 FileName::CliCrateAttr(hasher.finish())
188 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{
189 FileName::DocTest(path, line)
193 /// Spans represent a region of code, used for error reporting. Positions in spans
194 /// are *absolute* positions from the beginning of the source_map, not positions
195 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
196 /// to the original source.
197 /// You must be careful if the span crosses more than one file - you will not be
198 /// able to use many of the functions on spans in source_map and you cannot assume
199 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
200 /// range between files.
202 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
203 /// sent to other threads, but some pieces of performance infra run in a separate thread.
204 /// Using `Span` is generally preferred.
205 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
206 pub struct SpanData {
209 /// Information about where the macro came from, if this piece of
210 /// code was created by a macro expansion.
211 pub ctxt: SyntaxContext,
216 pub fn with_lo(&self, lo: BytePos) -> Span {
217 Span::new(lo, self.hi, self.ctxt)
220 pub fn with_hi(&self, hi: BytePos) -> Span {
221 Span::new(self.lo, hi, self.ctxt)
224 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
225 Span::new(self.lo, self.hi, ctxt)
229 // The interner is pointed to by a thread local value which is only set on the main thread
230 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
231 // to avoid panics and other errors, even though it would be memory safe to do so.
232 #[cfg(not(parallel_compiler))]
233 impl !Send for Span {}
234 #[cfg(not(parallel_compiler))]
235 impl !Sync for Span {}
237 impl PartialOrd for Span {
238 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
239 PartialOrd::partial_cmp(&self.data(), &rhs.data())
243 fn cmp(&self, rhs: &Self) -> Ordering {
244 Ord::cmp(&self.data(), &rhs.data())
248 /// A collection of spans. Spans have two orthogonal attributes:
250 /// - They can be *primary spans*. In this case they are the locus of
251 /// the error, and would be rendered with `^^^`.
252 /// - They can have a *label*. In this case, the label is written next
253 /// to the mark in the snippet when we render.
254 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
255 pub struct MultiSpan {
256 primary_spans: Vec<Span>,
257 span_labels: Vec<(Span, String)>,
262 pub fn lo(self) -> BytePos {
266 pub fn with_lo(self, lo: BytePos) -> Span {
267 self.data().with_lo(lo)
270 pub fn hi(self) -> BytePos {
274 pub fn with_hi(self, hi: BytePos) -> Span {
275 self.data().with_hi(hi)
278 pub fn ctxt(self) -> SyntaxContext {
282 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
283 self.data().with_ctxt(ctxt)
286 /// Returns `true` if this is a dummy span with any hygienic context.
288 pub fn is_dummy(self) -> bool {
289 let span = self.data();
290 span.lo.0 == 0 && span.hi.0 == 0
293 /// Returns `true` if this span comes from a macro or desugaring.
295 pub fn from_expansion(self) -> bool {
296 self.ctxt() != SyntaxContext::root()
300 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
301 Span::new(lo, hi, SyntaxContext::root())
304 /// Returns a new span representing an empty span at the beginning of this span
306 pub fn shrink_to_lo(self) -> Span {
307 let span = self.data();
308 span.with_hi(span.lo)
310 /// Returns a new span representing an empty span at the end of this span.
312 pub fn shrink_to_hi(self) -> Span {
313 let span = self.data();
314 span.with_lo(span.hi)
317 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
318 pub fn substitute_dummy(self, other: Span) -> Span {
319 if self.is_dummy() { other } else { self }
322 /// Returns `true` if `self` fully encloses `other`.
323 pub fn contains(self, other: Span) -> bool {
324 let span = self.data();
325 let other = other.data();
326 span.lo <= other.lo && other.hi <= span.hi
329 /// Returns `true` if `self` touches `other`.
330 pub fn overlaps(self, other: Span) -> bool {
331 let span = self.data();
332 let other = other.data();
333 span.lo < other.hi && other.lo < span.hi
336 /// Returns `true` if the spans are equal with regards to the source text.
338 /// Use this instead of `==` when either span could be generated code,
339 /// and you only care that they point to the same bytes of source text.
340 pub fn source_equal(&self, other: &Span) -> bool {
341 let span = self.data();
342 let other = other.data();
343 span.lo == other.lo && span.hi == other.hi
346 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
347 pub fn trim_start(self, other: Span) -> Option<Span> {
348 let span = self.data();
349 let other = other.data();
350 if span.hi > other.hi {
351 Some(span.with_lo(cmp::max(span.lo, other.hi)))
357 /// Returns the source span -- this is either the supplied span, or the span for
358 /// the macro callsite that expanded to it.
359 pub fn source_callsite(self) -> Span {
360 let expn_data = self.ctxt().outer_expn_data();
361 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
364 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
366 pub fn parent(self) -> Option<Span> {
367 let expn_data = self.ctxt().outer_expn_data();
368 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
371 /// Edition of the crate from which this span came.
372 pub fn edition(self) -> edition::Edition {
373 self.ctxt().outer_expn_data().edition
377 pub fn rust_2015(&self) -> bool {
378 self.edition() == edition::Edition::Edition2015
382 pub fn rust_2018(&self) -> bool {
383 self.edition() >= edition::Edition::Edition2018
386 /// Returns the source callee.
388 /// Returns `None` if the supplied span has no expansion trace,
389 /// else returns the `ExpnData` for the macro definition
390 /// corresponding to the source callsite.
391 pub fn source_callee(self) -> Option<ExpnData> {
392 fn source_callee(expn_data: ExpnData) -> ExpnData {
393 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
394 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
396 let expn_data = self.ctxt().outer_expn_data();
397 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
400 /// Checks if a span is "internal" to a macro in which `#[unstable]`
401 /// items can be used (that is, a macro marked with
402 /// `#[allow_internal_unstable]`).
403 pub fn allows_unstable(&self, feature: Symbol) -> bool {
404 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
405 features.iter().any(|&f| {
406 f == feature || f == sym::allow_internal_unstable_backcompat_hack
411 /// Checks if this span arises from a compiler desugaring of kind `kind`.
412 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
413 match self.ctxt().outer_expn_data().kind {
414 ExpnKind::Desugaring(k) => k == kind,
419 /// Returns the compiler desugaring that created this span, or `None`
420 /// if this span is not from a desugaring.
421 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
422 match self.ctxt().outer_expn_data().kind {
423 ExpnKind::Desugaring(k) => Some(k),
428 /// Checks if a span is "internal" to a macro in which `unsafe`
429 /// can be used without triggering the `unsafe_code` lint
430 // (that is, a macro marked with `#[allow_internal_unsafe]`).
431 pub fn allows_unsafe(&self) -> bool {
432 self.ctxt().outer_expn_data().allow_internal_unsafe
435 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
436 let mut prev_span = DUMMY_SP;
437 let mut result = vec![];
439 let expn_data = self.ctxt().outer_expn_data();
440 if expn_data.is_root() {
443 // Don't print recursive invocations.
444 if !expn_data.call_site.source_equal(&prev_span) {
445 let (pre, post) = match expn_data.kind {
446 ExpnKind::Root => break,
447 ExpnKind::Desugaring(..) => ("desugaring of ", ""),
448 ExpnKind::AstPass(..) => ("", ""),
449 ExpnKind::Macro(macro_kind, _) => match macro_kind {
450 MacroKind::Bang => ("", "!"),
451 MacroKind::Attr => ("#[", "]"),
452 MacroKind::Derive => ("#[derive(", ")]"),
455 result.push(MacroBacktrace {
456 call_site: expn_data.call_site,
457 macro_decl_name: format!("{}{}{}", pre, expn_data.kind.descr(), post),
458 def_site_span: expn_data.def_site,
463 self = expn_data.call_site;
468 /// Returns a `Span` that would enclose both `self` and `end`.
469 pub fn to(self, end: Span) -> Span {
470 let span_data = self.data();
471 let end_data = end.data();
472 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
473 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
474 // have an incomplete span than a completely nonsensical one.
475 if span_data.ctxt != end_data.ctxt {
476 if span_data.ctxt == SyntaxContext::root() {
478 } else if end_data.ctxt == SyntaxContext::root() {
481 // Both spans fall within a macro.
482 // FIXME(estebank): check if it is the *same* macro.
485 cmp::min(span_data.lo, end_data.lo),
486 cmp::max(span_data.hi, end_data.hi),
487 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
491 /// Returns a `Span` between the end of `self` to the beginning of `end`.
492 pub fn between(self, end: Span) -> Span {
493 let span = self.data();
494 let end = end.data();
498 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
502 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
503 pub fn until(self, end: Span) -> Span {
504 let span = self.data();
505 let end = end.data();
509 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
513 pub fn from_inner(self, inner: InnerSpan) -> Span {
514 let span = self.data();
515 Span::new(span.lo + BytePos::from_usize(inner.start),
516 span.lo + BytePos::from_usize(inner.end),
520 /// Equivalent of `Span::def_site` from the proc macro API,
521 /// except that the location is taken from the `self` span.
522 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
523 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
526 /// Equivalent of `Span::call_site` from the proc macro API,
527 /// except that the location is taken from the `self` span.
528 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
529 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
532 /// Equivalent of `Span::mixed_site` from the proc macro API,
533 /// except that the location is taken from the `self` span.
534 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
535 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
538 /// Produces a span with the same location as `self` and context produced by a macro with the
539 /// given ID and transparency, assuming that macro was defined directly and not produced by
540 /// some other macro (which is the case for built-in and procedural macros).
541 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
542 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
546 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
547 let span = self.data();
548 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
552 pub fn remove_mark(&mut self) -> ExpnId {
553 let mut span = self.data();
554 let mark = span.ctxt.remove_mark();
555 *self = Span::new(span.lo, span.hi, span.ctxt);
560 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
561 let mut span = self.data();
562 let mark = span.ctxt.adjust(expn_id);
563 *self = Span::new(span.lo, span.hi, span.ctxt);
568 pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
569 let mut span = self.data();
570 let mark = span.ctxt.modernize_and_adjust(expn_id);
571 *self = Span::new(span.lo, span.hi, span.ctxt);
576 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
577 let mut span = self.data();
578 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
579 *self = Span::new(span.lo, span.hi, span.ctxt);
584 pub fn reverse_glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span)
585 -> Option<Option<ExpnId>> {
586 let mut span = self.data();
587 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
588 *self = Span::new(span.lo, span.hi, span.ctxt);
593 pub fn modern(self) -> Span {
594 let span = self.data();
595 span.with_ctxt(span.ctxt.modern())
599 pub fn modern_and_legacy(self) -> Span {
600 let span = self.data();
601 span.with_ctxt(span.ctxt.modern_and_legacy())
605 #[derive(Clone, Debug)]
606 pub struct SpanLabel {
607 /// The span we are going to include in the final snippet.
610 /// Is this a primary span? This is the "locus" of the message,
611 /// and is indicated with a `^^^^` underline, versus `----`.
612 pub is_primary: bool,
614 /// What label should we attach to this span (if any)?
615 pub label: Option<String>,
618 impl Default for Span {
619 fn default() -> Self {
624 impl rustc_serialize::UseSpecializedEncodable for Span {
625 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
626 let span = self.data();
627 s.emit_struct("Span", 2, |s| {
628 s.emit_struct_field("lo", 0, |s| {
632 s.emit_struct_field("hi", 1, |s| {
639 impl rustc_serialize::UseSpecializedDecodable for Span {
640 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
641 d.read_struct("Span", 2, |d| {
642 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
643 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
644 Ok(Span::with_root_ctxt(lo, hi))
649 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
650 f.debug_struct("Span")
651 .field("lo", &span.lo())
652 .field("hi", &span.hi())
653 .field("ctxt", &span.ctxt())
657 impl fmt::Debug for Span {
658 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
663 impl fmt::Debug for SpanData {
664 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
665 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
671 pub fn new() -> MultiSpan {
673 primary_spans: vec![],
678 pub fn from_span(primary_span: Span) -> MultiSpan {
680 primary_spans: vec![primary_span],
685 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
692 pub fn push_span_label(&mut self, span: Span, label: String) {
693 self.span_labels.push((span, label));
696 /// Selects the first primary span (if any).
697 pub fn primary_span(&self) -> Option<Span> {
698 self.primary_spans.first().cloned()
701 /// Returns all primary spans.
702 pub fn primary_spans(&self) -> &[Span] {
706 /// Returns `true` if any of the primary spans are displayable.
707 pub fn has_primary_spans(&self) -> bool {
708 self.primary_spans.iter().any(|sp| !sp.is_dummy())
711 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
712 pub fn is_dummy(&self) -> bool {
713 let mut is_dummy = true;
714 for span in &self.primary_spans {
715 if !span.is_dummy() {
722 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
723 /// display well (like std macros). Returns whether replacements occurred.
724 pub fn replace(&mut self, before: Span, after: Span) -> bool {
725 let mut replacements_occurred = false;
726 for primary_span in &mut self.primary_spans {
727 if *primary_span == before {
728 *primary_span = after;
729 replacements_occurred = true;
732 for span_label in &mut self.span_labels {
733 if span_label.0 == before {
734 span_label.0 = after;
735 replacements_occurred = true;
738 replacements_occurred
741 /// Returns the strings to highlight. We always ensure that there
742 /// is an entry for each of the primary spans -- for each primary
743 /// span `P`, if there is at least one label with span `P`, we return
744 /// those labels (marked as primary). But otherwise we return
745 /// `SpanLabel` instances with empty labels.
746 pub fn span_labels(&self) -> Vec<SpanLabel> {
747 let is_primary = |span| self.primary_spans.contains(&span);
749 let mut span_labels = self.span_labels.iter().map(|&(span, ref label)|
752 is_primary: is_primary(span),
753 label: Some(label.clone())
755 ).collect::<Vec<_>>();
757 for &span in &self.primary_spans {
758 if !span_labels.iter().any(|sl| sl.span == span) {
759 span_labels.push(SpanLabel {
770 /// Returns `true` if any of the span labels is displayable.
771 pub fn has_span_labels(&self) -> bool {
772 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
776 impl From<Span> for MultiSpan {
777 fn from(span: Span) -> MultiSpan {
778 MultiSpan::from_span(span)
782 impl From<Vec<Span>> for MultiSpan {
783 fn from(spans: Vec<Span>) -> MultiSpan {
784 MultiSpan::from_spans(spans)
788 /// Identifies an offset of a multi-byte character in a `SourceFile`.
789 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
790 pub struct MultiByteChar {
791 /// The absolute offset of the character in the `SourceMap`.
793 /// The number of bytes, `>= 2`.
797 /// Identifies an offset of a non-narrow character in a `SourceFile`.
798 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
799 pub enum NonNarrowChar {
800 /// Represents a zero-width character.
802 /// Represents a wide (full-width) character.
804 /// Represents a tab character, represented visually with a width of 4 characters.
809 fn new(pos: BytePos, width: usize) -> Self {
811 0 => NonNarrowChar::ZeroWidth(pos),
812 2 => NonNarrowChar::Wide(pos),
813 4 => NonNarrowChar::Tab(pos),
814 _ => panic!("width {} given for non-narrow character", width),
818 /// Returns the absolute offset of the character in the `SourceMap`.
819 pub fn pos(&self) -> BytePos {
821 NonNarrowChar::ZeroWidth(p) |
822 NonNarrowChar::Wide(p) |
823 NonNarrowChar::Tab(p) => p,
827 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
828 pub fn width(&self) -> usize {
830 NonNarrowChar::ZeroWidth(_) => 0,
831 NonNarrowChar::Wide(_) => 2,
832 NonNarrowChar::Tab(_) => 4,
837 impl Add<BytePos> for NonNarrowChar {
840 fn add(self, rhs: BytePos) -> Self {
842 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
843 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
844 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
849 impl Sub<BytePos> for NonNarrowChar {
852 fn sub(self, rhs: BytePos) -> Self {
854 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
855 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
856 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
861 /// Identifies an offset of a character that was normalized away from `SourceFile`.
862 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
863 pub struct NormalizedPos {
864 /// The absolute offset of the character in the `SourceMap`.
866 /// The difference between original and normalized string at position.
870 /// The state of the lazy external source loading mechanism of a `SourceFile`.
871 #[derive(PartialEq, Eq, Clone)]
872 pub enum ExternalSource {
873 /// The external source has been loaded already.
875 /// No attempt has been made to load the external source.
877 /// A failed attempt has been made to load the external source.
879 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
883 impl ExternalSource {
884 pub fn is_absent(&self) -> bool {
886 ExternalSource::Present(_) => false,
891 pub fn get_source(&self) -> Option<&str> {
893 ExternalSource::Present(ref src) => Some(src),
900 pub struct OffsetOverflowError;
902 /// A single source in the `SourceMap`.
904 pub struct SourceFile {
905 /// The name of the file that the source came from. Source that doesn't
906 /// originate from files has names between angle brackets by convention
907 /// (e.g., `<anon>`).
909 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
910 pub name_was_remapped: bool,
911 /// The unmapped path of the file that the source came from.
912 /// Set to `None` if the `SourceFile` was imported from an external crate.
913 pub unmapped_path: Option<FileName>,
914 /// Indicates which crate this `SourceFile` was imported from.
915 pub crate_of_origin: u32,
916 /// The complete source code.
917 pub src: Option<Lrc<String>>,
918 /// The source code's hash.
920 /// The external source code (used for external crates, which will have a `None`
921 /// value as `self.src`.
922 pub external_src: Lock<ExternalSource>,
923 /// The start position of this source in the `SourceMap`.
924 pub start_pos: BytePos,
925 /// The end position of this source in the `SourceMap`.
926 pub end_pos: BytePos,
927 /// Locations of lines beginnings in the source code.
928 pub lines: Vec<BytePos>,
929 /// Locations of multi-byte characters in the source code.
930 pub multibyte_chars: Vec<MultiByteChar>,
931 /// Width of characters that are not narrow in the source code.
932 pub non_narrow_chars: Vec<NonNarrowChar>,
933 /// Locations of characters removed during normalization.
934 pub normalized_pos: Vec<NormalizedPos>,
935 /// A hash of the filename, used for speeding up hashing in incremental compilation.
939 impl Encodable for SourceFile {
940 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
941 s.emit_struct("SourceFile", 8, |s| {
942 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
943 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
944 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
945 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
946 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
947 s.emit_struct_field("lines", 5, |s| {
948 let lines = &self.lines[..];
950 s.emit_u32(lines.len() as u32)?;
952 if !lines.is_empty() {
953 // In order to preserve some space, we exploit the fact that
954 // the lines list is sorted and individual lines are
955 // probably not that long. Because of that we can store lines
956 // as a difference list, using as little space as possible
957 // for the differences.
958 let max_line_length = if lines.len() == 1 {
962 .map(|w| w[1] - w[0])
963 .map(|bp| bp.to_usize())
968 let bytes_per_diff: u8 = match max_line_length {
970 0x100 ..= 0xFFFF => 2,
974 // Encode the number of bytes used per diff.
975 bytes_per_diff.encode(s)?;
977 // Encode the first element.
980 let diff_iter = (&lines[..]).windows(2)
981 .map(|w| (w[1] - w[0]));
983 match bytes_per_diff {
984 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
985 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
986 4 => for diff in diff_iter { diff.0.encode(s)? },
993 s.emit_struct_field("multibyte_chars", 6, |s| {
994 self.multibyte_chars.encode(s)
996 s.emit_struct_field("non_narrow_chars", 7, |s| {
997 self.non_narrow_chars.encode(s)
999 s.emit_struct_field("name_hash", 8, |s| {
1000 self.name_hash.encode(s)
1002 s.emit_struct_field("normalized_pos", 9, |s| {
1003 self.normalized_pos.encode(s)
1009 impl Decodable for SourceFile {
1010 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
1011 d.read_struct("SourceFile", 8, |d| {
1012 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1013 let name_was_remapped: bool =
1014 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1015 let src_hash: u128 =
1016 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1017 let start_pos: BytePos =
1018 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1019 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1020 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1021 let num_lines: u32 = Decodable::decode(d)?;
1022 let mut lines = Vec::with_capacity(num_lines as usize);
1025 // Read the number of bytes used per diff.
1026 let bytes_per_diff: u8 = Decodable::decode(d)?;
1028 // Read the first element.
1029 let mut line_start: BytePos = Decodable::decode(d)?;
1030 lines.push(line_start);
1032 for _ in 1..num_lines {
1033 let diff = match bytes_per_diff {
1034 1 => d.read_u8()? as u32,
1035 2 => d.read_u16()? as u32,
1040 line_start = line_start + BytePos(diff);
1042 lines.push(line_start);
1048 let multibyte_chars: Vec<MultiByteChar> =
1049 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1050 let non_narrow_chars: Vec<NonNarrowChar> =
1051 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1052 let name_hash: u128 =
1053 d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1054 let normalized_pos: Vec<NormalizedPos> =
1055 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1059 unmapped_path: None,
1060 // `crate_of_origin` has to be set by the importer.
1061 // This value matches up with `rustc::hir::def_id::INVALID_CRATE`.
1062 // That constant is not available here, unfortunately.
1063 crate_of_origin: std::u32::MAX - 1,
1068 external_src: Lock::new(ExternalSource::AbsentOk),
1079 impl fmt::Debug for SourceFile {
1080 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1081 write!(fmt, "SourceFile({})", self.name)
1086 pub fn new(name: FileName,
1087 name_was_remapped: bool,
1088 unmapped_path: FileName,
1090 start_pos: BytePos) -> Result<SourceFile, OffsetOverflowError> {
1091 let normalized_pos = normalize_src(&mut src, start_pos);
1094 let mut hasher: StableHasher = StableHasher::new();
1095 hasher.write(src.as_bytes());
1096 hasher.finish::<u128>()
1099 let mut hasher: StableHasher = StableHasher::new();
1100 name.hash(&mut hasher);
1101 hasher.finish::<u128>()
1103 let end_pos = start_pos.to_usize() + src.len();
1104 if end_pos > u32::max_value() as usize {
1105 return Err(OffsetOverflowError);
1108 let (lines, multibyte_chars, non_narrow_chars) =
1109 analyze_source_file::analyze_source_file(&src[..], start_pos);
1114 unmapped_path: Some(unmapped_path),
1116 src: Some(Lrc::new(src)),
1118 external_src: Lock::new(ExternalSource::Unneeded),
1120 end_pos: Pos::from_usize(end_pos),
1129 /// Returns the `BytePos` of the beginning of the current line.
1130 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1131 let line_index = self.lookup_line(pos).unwrap();
1132 self.lines[line_index]
1135 /// Add externally loaded source.
1136 /// If the hash of the input doesn't match or no input is supplied via None,
1137 /// it is interpreted as an error and the corresponding enum variant is set.
1138 /// The return value signifies whether some kind of source is present.
1139 pub fn add_external_src<F>(&self, get_src: F) -> bool
1140 where F: FnOnce() -> Option<String>
1142 if *self.external_src.borrow() == ExternalSource::AbsentOk {
1143 let src = get_src();
1144 let mut external_src = self.external_src.borrow_mut();
1145 // Check that no-one else have provided the source while we were getting it
1146 if *external_src == ExternalSource::AbsentOk {
1147 if let Some(src) = src {
1148 let mut hasher: StableHasher = StableHasher::new();
1149 hasher.write(src.as_bytes());
1151 if hasher.finish::<u128>() == self.src_hash {
1152 *external_src = ExternalSource::Present(src);
1156 *external_src = ExternalSource::AbsentErr;
1161 self.src.is_some() || external_src.get_source().is_some()
1164 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1168 /// Gets a line from the list of pre-computed line-beginnings.
1169 /// The line number here is 0-based.
1170 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1171 fn get_until_newline(src: &str, begin: usize) -> &str {
1172 // We can't use `lines.get(line_number+1)` because we might
1173 // be parsing when we call this function and thus the current
1174 // line is the last one we have line info for.
1175 let slice = &src[begin..];
1176 match slice.find('\n') {
1177 Some(e) => &slice[..e],
1183 let line = if let Some(line) = self.lines.get(line_number) {
1188 let begin: BytePos = *line - self.start_pos;
1192 if let Some(ref src) = self.src {
1193 Some(Cow::from(get_until_newline(src, begin)))
1194 } else if let Some(src) = self.external_src.borrow().get_source() {
1195 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1201 pub fn is_real_file(&self) -> bool {
1205 pub fn is_imported(&self) -> bool {
1209 pub fn byte_length(&self) -> u32 {
1210 self.end_pos.0 - self.start_pos.0
1212 pub fn count_lines(&self) -> usize {
1216 /// Finds the line containing the given position. The return value is the
1217 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1218 /// number. If the source_file is empty or the position is located before the
1219 /// first line, `None` is returned.
1220 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1221 if self.lines.len() == 0 {
1225 let line_index = lookup_line(&self.lines[..], pos);
1226 assert!(line_index < self.lines.len() as isize);
1227 if line_index >= 0 {
1228 Some(line_index as usize)
1234 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1235 if self.start_pos == self.end_pos {
1236 return (self.start_pos, self.end_pos);
1239 assert!(line_index < self.lines.len());
1240 if line_index == (self.lines.len() - 1) {
1241 (self.lines[line_index], self.end_pos)
1243 (self.lines[line_index], self.lines[line_index + 1])
1248 pub fn contains(&self, byte_pos: BytePos) -> bool {
1249 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1252 /// Calculates the original byte position relative to the start of the file
1253 /// based on the given byte position.
1254 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1256 // Diff before any records is 0. Otherwise use the previously recorded
1257 // diff as that applies to the following characters until a new diff
1259 let diff = match self.normalized_pos.binary_search_by(
1260 |np| np.pos.cmp(&pos)) {
1261 Ok(i) => self.normalized_pos[i].diff,
1262 Err(i) if i == 0 => 0,
1263 Err(i) => self.normalized_pos[i-1].diff,
1266 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1270 /// Normalizes the source code and records the normalizations.
1271 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1272 let mut normalized_pos = vec![];
1273 remove_bom(src, &mut normalized_pos);
1274 normalize_newlines(src, &mut normalized_pos);
1276 // Offset all the positions by start_pos to match the final file positions.
1277 for np in &mut normalized_pos {
1278 np.pos.0 += start_pos.0;
1284 /// Removes UTF-8 BOM, if any.
1285 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1286 if src.starts_with("\u{feff}") {
1288 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1293 /// Replaces `\r\n` with `\n` in-place in `src`.
1295 /// Returns error if there's a lone `\r` in the string
1296 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1297 if !src.as_bytes().contains(&b'\r') {
1301 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1302 // While we *can* call `as_mut_vec` and do surgery on the live string
1303 // directly, let's rather steal the contents of `src`. This makes the code
1304 // safe even if a panic occurs.
1306 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1307 let mut gap_len = 0;
1308 let mut tail = buf.as_mut_slice();
1310 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1312 let idx = match find_crlf(&tail[gap_len..]) {
1314 Some(idx) => idx + gap_len,
1316 tail.copy_within(gap_len..idx, 0);
1317 tail = &mut tail[idx - gap_len..];
1318 if tail.len() == gap_len {
1321 cursor += idx - gap_len;
1323 normalized_pos.push(NormalizedPos {
1324 pos: BytePos::from_usize(cursor + 1),
1325 diff: original_gap + gap_len as u32,
1329 // Account for removed `\r`.
1330 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1331 let new_len = buf.len() - gap_len;
1333 buf.set_len(new_len);
1334 *src = String::from_utf8_unchecked(buf);
1337 fn find_crlf(src: &[u8]) -> Option<usize> {
1338 let mut search_idx = 0;
1339 while let Some(idx) = find_cr(&src[search_idx..]) {
1340 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1341 search_idx += idx + 1;
1344 return Some(search_idx + idx);
1349 fn find_cr(src: &[u8]) -> Option<usize> {
1350 src.iter().position(|&b| b == b'\r')
1354 // _____________________________________________________________________________
1355 // Pos, BytePos, CharPos
1359 fn from_usize(n: usize) -> Self;
1360 fn to_usize(&self) -> usize;
1361 fn from_u32(n: u32) -> Self;
1362 fn to_u32(&self) -> u32;
1365 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1367 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1368 pub struct BytePos(pub u32);
1370 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1371 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1372 /// values to `CharPos` values as necessary.
1373 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1374 pub struct CharPos(pub usize);
1376 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1377 // have been unsuccessful.
1379 impl Pos for BytePos {
1381 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1384 fn to_usize(&self) -> usize { self.0 as usize }
1387 fn from_u32(n: u32) -> BytePos { BytePos(n) }
1390 fn to_u32(&self) -> u32 { self.0 }
1393 impl Add for BytePos {
1394 type Output = BytePos;
1397 fn add(self, rhs: BytePos) -> BytePos {
1398 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1402 impl Sub for BytePos {
1403 type Output = BytePos;
1406 fn sub(self, rhs: BytePos) -> BytePos {
1407 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1411 impl Encodable for BytePos {
1412 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1417 impl Decodable for BytePos {
1418 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1419 Ok(BytePos(d.read_u32()?))
1423 impl Pos for CharPos {
1425 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1428 fn to_usize(&self) -> usize { self.0 }
1431 fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1434 fn to_u32(&self) -> u32 { self.0 as u32}
1437 impl Add for CharPos {
1438 type Output = CharPos;
1441 fn add(self, rhs: CharPos) -> CharPos {
1442 CharPos(self.to_usize() + rhs.to_usize())
1446 impl Sub for CharPos {
1447 type Output = CharPos;
1450 fn sub(self, rhs: CharPos) -> CharPos {
1451 CharPos(self.to_usize() - rhs.to_usize())
1455 // _____________________________________________________________________________
1456 // Loc, SourceFileAndLine, SourceFileAndBytePos
1459 /// A source code location used for error reporting.
1460 #[derive(Debug, Clone)]
1462 /// Information about the original source.
1463 pub file: Lrc<SourceFile>,
1464 /// The (1-based) line number.
1466 /// The (0-based) column offset.
1468 /// The (0-based) column offset when displayed.
1469 pub col_display: usize,
1472 // Used to be structural records.
1474 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1476 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1478 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1479 pub struct LineInfo {
1480 /// Index of line, starting from 0.
1481 pub line_index: usize,
1483 /// Column in line where span begins, starting from 0.
1484 pub start_col: CharPos,
1486 /// Column in line where span ends, starting from 0, exclusive.
1487 pub end_col: CharPos,
1490 pub struct FileLines {
1491 pub file: Lrc<SourceFile>,
1492 pub lines: Vec<LineInfo>
1495 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1496 Cell::new(default_span_debug));
1499 pub struct MacroBacktrace {
1500 /// span where macro was applied to generate this code
1501 pub call_site: Span,
1503 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1504 pub macro_decl_name: String,
1506 /// span where macro was defined (possibly dummy)
1507 pub def_site_span: Span,
1510 // _____________________________________________________________________________
1511 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1514 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1516 #[derive(Clone, PartialEq, Eq, Debug)]
1517 pub enum SpanLinesError {
1518 DistinctSources(DistinctSources),
1521 #[derive(Clone, PartialEq, Eq, Debug)]
1522 pub enum SpanSnippetError {
1523 IllFormedSpan(Span),
1524 DistinctSources(DistinctSources),
1525 MalformedForSourcemap(MalformedSourceMapPositions),
1526 SourceNotAvailable { filename: FileName }
1529 #[derive(Clone, PartialEq, Eq, Debug)]
1530 pub struct DistinctSources {
1531 pub begin: (FileName, BytePos),
1532 pub end: (FileName, BytePos)
1535 #[derive(Clone, PartialEq, Eq, Debug)]
1536 pub struct MalformedSourceMapPositions {
1538 pub source_len: usize,
1539 pub begin_pos: BytePos,
1540 pub end_pos: BytePos
1543 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1544 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1545 pub struct InnerSpan {
1551 pub fn new(start: usize, end: usize) -> InnerSpan {
1552 InnerSpan { start, end }
1556 // Given a slice of line start positions and a position, returns the index of
1557 // the line the position is on. Returns -1 if the position is located before
1559 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1560 match lines.binary_search(&pos) {
1561 Ok(line) => line as isize,
1562 Err(line) => line as isize - 1