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};
22 pub use hygiene::{ExpnId, SyntaxContext, ExpnData, ExpnKind, MacroKind, DesugaringKind};
23 use hygiene::Transparency;
26 pub use span_encoding::{Span, DUMMY_SP};
29 pub use symbol::{Symbol, sym};
31 mod analyze_source_file;
33 use rustc_data_structures::stable_hasher::StableHasher;
34 use rustc_data_structures::sync::{Lrc, Lock};
38 use std::cmp::{self, Ordering};
40 use std::hash::{Hasher, Hash};
41 use std::ops::{Add, Sub};
42 use std::path::PathBuf;
48 symbol_interner: Lock<symbol::Interner>,
49 span_interner: Lock<span_encoding::SpanInterner>,
50 hygiene_data: Lock<hygiene::HygieneData>,
54 pub fn new(edition: Edition) -> Globals {
56 symbol_interner: Lock::new(symbol::Interner::fresh()),
57 span_interner: Lock::new(span_encoding::SpanInterner::default()),
58 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
63 scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
65 /// Differentiates between real files and common virtual files.
66 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
69 /// A macro. This includes the full name of the macro, so that there are no clashes.
75 /// Hack in `src/libsyntax/parse.rs`.
78 ProcMacroSourceCode(u64),
79 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
81 /// Strings provided as crate attributes in the CLI.
83 /// Custom sources for explicit parser calls from plugins and drivers.
85 DocTest(PathBuf, isize),
88 impl std::fmt::Display for FileName {
89 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 Real(ref path) => write!(fmt, "{}", path.display()),
93 Macros(ref name) => write!(fmt, "<{} macros>", name),
94 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
95 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
96 Anon(_) => write!(fmt, "<anon>"),
97 ProcMacroSourceCode(_) =>
98 write!(fmt, "<proc-macro source code>"),
99 CfgSpec(_) => write!(fmt, "<cfgspec>"),
100 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
101 Custom(ref s) => write!(fmt, "<{}>", s),
102 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
107 impl From<PathBuf> for FileName {
108 fn from(p: PathBuf) -> Self {
109 assert!(!p.to_string_lossy().ends_with('>'));
115 pub fn is_real(&self) -> bool {
122 ProcMacroSourceCode(_) |
127 DocTest(_, _) => false,
131 pub fn is_macros(&self) -> bool {
137 ProcMacroSourceCode(_) |
142 DocTest(_, _) => false,
147 pub fn quote_expansion_source_code(src: &str) -> FileName {
148 let mut hasher = StableHasher::new();
149 src.hash(&mut hasher);
150 FileName::QuoteExpansion(hasher.finish())
153 pub fn macro_expansion_source_code(src: &str) -> FileName {
154 let mut hasher = StableHasher::new();
155 src.hash(&mut hasher);
156 FileName::MacroExpansion(hasher.finish())
159 pub fn anon_source_code(src: &str) -> FileName {
160 let mut hasher = StableHasher::new();
161 src.hash(&mut hasher);
162 FileName::Anon(hasher.finish())
165 pub fn proc_macro_source_code(src: &str) -> FileName {
166 let mut hasher = StableHasher::new();
167 src.hash(&mut hasher);
168 FileName::ProcMacroSourceCode(hasher.finish())
171 pub fn cfg_spec_source_code(src: &str) -> FileName {
172 let mut hasher = StableHasher::new();
173 src.hash(&mut hasher);
174 FileName::QuoteExpansion(hasher.finish())
177 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
178 let mut hasher = StableHasher::new();
179 src.hash(&mut hasher);
180 FileName::CliCrateAttr(hasher.finish())
183 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{
184 FileName::DocTest(path, line)
188 /// Spans represent a region of code, used for error reporting. Positions in spans
189 /// are *absolute* positions from the beginning of the source_map, not positions
190 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
191 /// to the original source.
192 /// You must be careful if the span crosses more than one file - you will not be
193 /// able to use many of the functions on spans in source_map and you cannot assume
194 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
195 /// range between files.
197 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
198 /// sent to other threads, but some pieces of performance infra run in a separate thread.
199 /// Using `Span` is generally preferred.
200 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
201 pub struct SpanData {
204 /// Information about where the macro came from, if this piece of
205 /// code was created by a macro expansion.
206 pub ctxt: SyntaxContext,
211 pub fn with_lo(&self, lo: BytePos) -> Span {
212 Span::new(lo, self.hi, self.ctxt)
215 pub fn with_hi(&self, hi: BytePos) -> Span {
216 Span::new(self.lo, hi, self.ctxt)
219 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
220 Span::new(self.lo, self.hi, ctxt)
224 // The interner is pointed to by a thread local value which is only set on the main thread
225 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
226 // to avoid panics and other errors, even though it would be memory safe to do so.
227 #[cfg(not(parallel_compiler))]
228 impl !Send for Span {}
229 #[cfg(not(parallel_compiler))]
230 impl !Sync for Span {}
232 impl PartialOrd for Span {
233 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
234 PartialOrd::partial_cmp(&self.data(), &rhs.data())
238 fn cmp(&self, rhs: &Self) -> Ordering {
239 Ord::cmp(&self.data(), &rhs.data())
243 /// A collection of spans. Spans have two orthogonal attributes:
245 /// - They can be *primary spans*. In this case they are the locus of
246 /// the error, and would be rendered with `^^^`.
247 /// - They can have a *label*. In this case, the label is written next
248 /// to the mark in the snippet when we render.
249 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
250 pub struct MultiSpan {
251 primary_spans: Vec<Span>,
252 span_labels: Vec<(Span, String)>,
257 pub fn lo(self) -> BytePos {
261 pub fn with_lo(self, lo: BytePos) -> Span {
262 self.data().with_lo(lo)
265 pub fn hi(self) -> BytePos {
269 pub fn with_hi(self, hi: BytePos) -> Span {
270 self.data().with_hi(hi)
273 pub fn ctxt(self) -> SyntaxContext {
277 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
278 self.data().with_ctxt(ctxt)
281 /// Returns `true` if this is a dummy span with any hygienic context.
283 pub fn is_dummy(self) -> bool {
284 let span = self.data();
285 span.lo.0 == 0 && span.hi.0 == 0
288 /// Returns `true` if this span comes from a macro or desugaring.
290 pub fn from_expansion(self) -> bool {
291 self.ctxt() != SyntaxContext::root()
295 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
296 Span::new(lo, hi, SyntaxContext::root())
299 /// Returns a new span representing an empty span at the beginning of this span
301 pub fn shrink_to_lo(self) -> Span {
302 let span = self.data();
303 span.with_hi(span.lo)
305 /// Returns a new span representing an empty span at the end of this span.
307 pub fn shrink_to_hi(self) -> Span {
308 let span = self.data();
309 span.with_lo(span.hi)
312 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
313 pub fn substitute_dummy(self, other: Span) -> Span {
314 if self.is_dummy() { other } else { self }
317 /// Returns `true` if `self` fully encloses `other`.
318 pub fn contains(self, other: Span) -> bool {
319 let span = self.data();
320 let other = other.data();
321 span.lo <= other.lo && other.hi <= span.hi
324 /// Returns `true` if `self` touches `other`.
325 pub fn overlaps(self, other: Span) -> bool {
326 let span = self.data();
327 let other = other.data();
328 span.lo < other.hi && other.lo < span.hi
331 /// Returns `true` if the spans are equal with regards to the source text.
333 /// Use this instead of `==` when either span could be generated code,
334 /// and you only care that they point to the same bytes of source text.
335 pub fn source_equal(&self, other: &Span) -> bool {
336 let span = self.data();
337 let other = other.data();
338 span.lo == other.lo && span.hi == other.hi
341 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
342 pub fn trim_start(self, other: Span) -> Option<Span> {
343 let span = self.data();
344 let other = other.data();
345 if span.hi > other.hi {
346 Some(span.with_lo(cmp::max(span.lo, other.hi)))
352 /// Returns the source span -- this is either the supplied span, or the span for
353 /// the macro callsite that expanded to it.
354 pub fn source_callsite(self) -> Span {
355 let expn_data = self.ctxt().outer_expn_data();
356 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
359 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
361 pub fn parent(self) -> Option<Span> {
362 let expn_data = self.ctxt().outer_expn_data();
363 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
366 /// Edition of the crate from which this span came.
367 pub fn edition(self) -> edition::Edition {
368 self.ctxt().outer_expn_data().edition
372 pub fn rust_2015(&self) -> bool {
373 self.edition() == edition::Edition::Edition2015
377 pub fn rust_2018(&self) -> bool {
378 self.edition() >= edition::Edition::Edition2018
381 /// Returns the source callee.
383 /// Returns `None` if the supplied span has no expansion trace,
384 /// else returns the `ExpnData` for the macro definition
385 /// corresponding to the source callsite.
386 pub fn source_callee(self) -> Option<ExpnData> {
387 fn source_callee(expn_data: ExpnData) -> ExpnData {
388 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
389 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
391 let expn_data = self.ctxt().outer_expn_data();
392 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
395 /// Checks if a span is "internal" to a macro in which `#[unstable]`
396 /// items can be used (that is, a macro marked with
397 /// `#[allow_internal_unstable]`).
398 pub fn allows_unstable(&self, feature: Symbol) -> bool {
399 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
400 features.iter().any(|&f| {
401 f == feature || f == sym::allow_internal_unstable_backcompat_hack
406 /// Checks if this span arises from a compiler desugaring of kind `kind`.
407 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
408 match self.ctxt().outer_expn_data().kind {
409 ExpnKind::Desugaring(k) => k == kind,
414 /// Returns the compiler desugaring that created this span, or `None`
415 /// if this span is not from a desugaring.
416 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
417 match self.ctxt().outer_expn_data().kind {
418 ExpnKind::Desugaring(k) => Some(k),
423 /// Checks if a span is "internal" to a macro in which `unsafe`
424 /// can be used without triggering the `unsafe_code` lint
425 // (that is, a macro marked with `#[allow_internal_unsafe]`).
426 pub fn allows_unsafe(&self) -> bool {
427 self.ctxt().outer_expn_data().allow_internal_unsafe
430 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
431 let mut prev_span = DUMMY_SP;
432 let mut result = vec![];
434 let expn_data = self.ctxt().outer_expn_data();
435 if expn_data.is_root() {
438 // Don't print recursive invocations.
439 if !expn_data.call_site.source_equal(&prev_span) {
440 let (pre, post) = match expn_data.kind {
441 ExpnKind::Root => break,
442 ExpnKind::Desugaring(..) => ("desugaring of ", ""),
443 ExpnKind::AstPass(..) => ("", ""),
444 ExpnKind::Macro(macro_kind, _) => match macro_kind {
445 MacroKind::Bang => ("", "!"),
446 MacroKind::Attr => ("#[", "]"),
447 MacroKind::Derive => ("#[derive(", ")]"),
450 result.push(MacroBacktrace {
451 call_site: expn_data.call_site,
452 macro_decl_name: format!("{}{}{}", pre, expn_data.kind.descr(), post),
453 def_site_span: expn_data.def_site,
458 self = expn_data.call_site;
463 /// Returns a `Span` that would enclose both `self` and `end`.
464 pub fn to(self, end: Span) -> Span {
465 let span_data = self.data();
466 let end_data = end.data();
467 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
468 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
469 // have an incomplete span than a completely nonsensical one.
470 if span_data.ctxt != end_data.ctxt {
471 if span_data.ctxt == SyntaxContext::root() {
473 } else if end_data.ctxt == SyntaxContext::root() {
476 // Both spans fall within a macro.
477 // FIXME(estebank): check if it is the *same* macro.
480 cmp::min(span_data.lo, end_data.lo),
481 cmp::max(span_data.hi, end_data.hi),
482 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
486 /// Returns a `Span` between the end of `self` to the beginning of `end`.
487 pub fn between(self, end: Span) -> Span {
488 let span = self.data();
489 let end = end.data();
493 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
497 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
498 pub fn until(self, end: Span) -> Span {
499 let span = self.data();
500 let end = end.data();
504 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
508 pub fn from_inner(self, inner: InnerSpan) -> Span {
509 let span = self.data();
510 Span::new(span.lo + BytePos::from_usize(inner.start),
511 span.lo + BytePos::from_usize(inner.end),
515 /// Equivalent of `Span::def_site` from the proc macro API,
516 /// except that the location is taken from the `self` span.
517 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
518 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
521 /// Equivalent of `Span::call_site` from the proc macro API,
522 /// except that the location is taken from the `self` span.
523 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
524 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
527 /// Equivalent of `Span::mixed_site` from the proc macro API,
528 /// except that the location is taken from the `self` span.
529 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
530 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
533 /// Produces a span with the same location as `self` and context produced by a macro with the
534 /// given ID and transparency, assuming that macro was defined directly and not produced by
535 /// some other macro (which is the case for built-in and procedural macros).
536 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
537 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
541 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
542 let span = self.data();
543 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
547 pub fn remove_mark(&mut self) -> ExpnId {
548 let mut span = self.data();
549 let mark = span.ctxt.remove_mark();
550 *self = Span::new(span.lo, span.hi, span.ctxt);
555 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
556 let mut span = self.data();
557 let mark = span.ctxt.adjust(expn_id);
558 *self = Span::new(span.lo, span.hi, span.ctxt);
563 pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
564 let mut span = self.data();
565 let mark = span.ctxt.modernize_and_adjust(expn_id);
566 *self = Span::new(span.lo, span.hi, span.ctxt);
571 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
572 let mut span = self.data();
573 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
574 *self = Span::new(span.lo, span.hi, span.ctxt);
579 pub fn reverse_glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span)
580 -> Option<Option<ExpnId>> {
581 let mut span = self.data();
582 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
583 *self = Span::new(span.lo, span.hi, span.ctxt);
588 pub fn modern(self) -> Span {
589 let span = self.data();
590 span.with_ctxt(span.ctxt.modern())
594 pub fn modern_and_legacy(self) -> Span {
595 let span = self.data();
596 span.with_ctxt(span.ctxt.modern_and_legacy())
600 #[derive(Clone, Debug)]
601 pub struct SpanLabel {
602 /// The span we are going to include in the final snippet.
605 /// Is this a primary span? This is the "locus" of the message,
606 /// and is indicated with a `^^^^` underline, versus `----`.
607 pub is_primary: bool,
609 /// What label should we attach to this span (if any)?
610 pub label: Option<String>,
613 impl Default for Span {
614 fn default() -> Self {
619 impl rustc_serialize::UseSpecializedEncodable for Span {
620 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
621 let span = self.data();
622 s.emit_struct("Span", 2, |s| {
623 s.emit_struct_field("lo", 0, |s| {
627 s.emit_struct_field("hi", 1, |s| {
634 impl rustc_serialize::UseSpecializedDecodable for Span {
635 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
636 d.read_struct("Span", 2, |d| {
637 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
638 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
639 Ok(Span::with_root_ctxt(lo, hi))
644 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
645 f.debug_struct("Span")
646 .field("lo", &span.lo())
647 .field("hi", &span.hi())
648 .field("ctxt", &span.ctxt())
652 impl fmt::Debug for Span {
653 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
654 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
658 impl fmt::Debug for SpanData {
659 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
660 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
666 pub fn new() -> MultiSpan {
668 primary_spans: vec![],
673 pub fn from_span(primary_span: Span) -> MultiSpan {
675 primary_spans: vec![primary_span],
680 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
687 pub fn push_span_label(&mut self, span: Span, label: String) {
688 self.span_labels.push((span, label));
691 /// Selects the first primary span (if any).
692 pub fn primary_span(&self) -> Option<Span> {
693 self.primary_spans.first().cloned()
696 /// Returns all primary spans.
697 pub fn primary_spans(&self) -> &[Span] {
701 /// Returns `true` if any of the primary spans are displayable.
702 pub fn has_primary_spans(&self) -> bool {
703 self.primary_spans.iter().any(|sp| !sp.is_dummy())
706 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
707 pub fn is_dummy(&self) -> bool {
708 let mut is_dummy = true;
709 for span in &self.primary_spans {
710 if !span.is_dummy() {
717 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
718 /// display well (like std macros). Returns whether replacements occurred.
719 pub fn replace(&mut self, before: Span, after: Span) -> bool {
720 let mut replacements_occurred = false;
721 for primary_span in &mut self.primary_spans {
722 if *primary_span == before {
723 *primary_span = after;
724 replacements_occurred = true;
727 for span_label in &mut self.span_labels {
728 if span_label.0 == before {
729 span_label.0 = after;
730 replacements_occurred = true;
733 replacements_occurred
736 /// Returns the strings to highlight. We always ensure that there
737 /// is an entry for each of the primary spans -- for each primary
738 /// span `P`, if there is at least one label with span `P`, we return
739 /// those labels (marked as primary). But otherwise we return
740 /// `SpanLabel` instances with empty labels.
741 pub fn span_labels(&self) -> Vec<SpanLabel> {
742 let is_primary = |span| self.primary_spans.contains(&span);
744 let mut span_labels = self.span_labels.iter().map(|&(span, ref label)|
747 is_primary: is_primary(span),
748 label: Some(label.clone())
750 ).collect::<Vec<_>>();
752 for &span in &self.primary_spans {
753 if !span_labels.iter().any(|sl| sl.span == span) {
754 span_labels.push(SpanLabel {
765 /// Returns `true` if any of the span labels is displayable.
766 pub fn has_span_labels(&self) -> bool {
767 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
771 impl From<Span> for MultiSpan {
772 fn from(span: Span) -> MultiSpan {
773 MultiSpan::from_span(span)
777 impl From<Vec<Span>> for MultiSpan {
778 fn from(spans: Vec<Span>) -> MultiSpan {
779 MultiSpan::from_spans(spans)
783 /// Identifies an offset of a multi-byte character in a `SourceFile`.
784 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
785 pub struct MultiByteChar {
786 /// The absolute offset of the character in the `SourceMap`.
788 /// The number of bytes, `>= 2`.
792 /// Identifies an offset of a non-narrow character in a `SourceFile`.
793 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
794 pub enum NonNarrowChar {
795 /// Represents a zero-width character.
797 /// Represents a wide (full-width) character.
799 /// Represents a tab character, represented visually with a width of 4 characters.
804 fn new(pos: BytePos, width: usize) -> Self {
806 0 => NonNarrowChar::ZeroWidth(pos),
807 2 => NonNarrowChar::Wide(pos),
808 4 => NonNarrowChar::Tab(pos),
809 _ => panic!("width {} given for non-narrow character", width),
813 /// Returns the absolute offset of the character in the `SourceMap`.
814 pub fn pos(&self) -> BytePos {
816 NonNarrowChar::ZeroWidth(p) |
817 NonNarrowChar::Wide(p) |
818 NonNarrowChar::Tab(p) => p,
822 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
823 pub fn width(&self) -> usize {
825 NonNarrowChar::ZeroWidth(_) => 0,
826 NonNarrowChar::Wide(_) => 2,
827 NonNarrowChar::Tab(_) => 4,
832 impl Add<BytePos> for NonNarrowChar {
835 fn add(self, rhs: BytePos) -> Self {
837 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
838 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
839 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
844 impl Sub<BytePos> for NonNarrowChar {
847 fn sub(self, rhs: BytePos) -> Self {
849 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
850 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
851 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
856 /// Identifies an offset of a character that was normalized away from `SourceFile`.
857 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
858 pub struct NormalizedPos {
859 /// The absolute offset of the character in the `SourceMap`.
861 /// The difference between original and normalized string at position.
865 /// The state of the lazy external source loading mechanism of a `SourceFile`.
866 #[derive(PartialEq, Eq, Clone)]
867 pub enum ExternalSource {
868 /// The external source has been loaded already.
870 /// No attempt has been made to load the external source.
872 /// A failed attempt has been made to load the external source.
874 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
878 impl ExternalSource {
879 pub fn is_absent(&self) -> bool {
881 ExternalSource::Present(_) => false,
886 pub fn get_source(&self) -> Option<&str> {
888 ExternalSource::Present(ref src) => Some(src),
895 pub struct OffsetOverflowError;
897 /// A single source in the `SourceMap`.
899 pub struct SourceFile {
900 /// The name of the file that the source came from. Source that doesn't
901 /// originate from files has names between angle brackets by convention
902 /// (e.g., `<anon>`).
904 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
905 pub name_was_remapped: bool,
906 /// The unmapped path of the file that the source came from.
907 /// Set to `None` if the `SourceFile` was imported from an external crate.
908 pub unmapped_path: Option<FileName>,
909 /// Indicates which crate this `SourceFile` was imported from.
910 pub crate_of_origin: u32,
911 /// The complete source code.
912 pub src: Option<Lrc<String>>,
913 /// The source code's hash.
915 /// The external source code (used for external crates, which will have a `None`
916 /// value as `self.src`.
917 pub external_src: Lock<ExternalSource>,
918 /// The start position of this source in the `SourceMap`.
919 pub start_pos: BytePos,
920 /// The end position of this source in the `SourceMap`.
921 pub end_pos: BytePos,
922 /// Locations of lines beginnings in the source code.
923 pub lines: Vec<BytePos>,
924 /// Locations of multi-byte characters in the source code.
925 pub multibyte_chars: Vec<MultiByteChar>,
926 /// Width of characters that are not narrow in the source code.
927 pub non_narrow_chars: Vec<NonNarrowChar>,
928 /// Locations of characters removed during normalization.
929 pub normalized_pos: Vec<NormalizedPos>,
930 /// A hash of the filename, used for speeding up hashing in incremental compilation.
934 impl Encodable for SourceFile {
935 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
936 s.emit_struct("SourceFile", 8, |s| {
937 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
938 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
939 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
940 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
941 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
942 s.emit_struct_field("lines", 5, |s| {
943 let lines = &self.lines[..];
945 s.emit_u32(lines.len() as u32)?;
947 if !lines.is_empty() {
948 // In order to preserve some space, we exploit the fact that
949 // the lines list is sorted and individual lines are
950 // probably not that long. Because of that we can store lines
951 // as a difference list, using as little space as possible
952 // for the differences.
953 let max_line_length = if lines.len() == 1 {
957 .map(|w| w[1] - w[0])
958 .map(|bp| bp.to_usize())
963 let bytes_per_diff: u8 = match max_line_length {
965 0x100 ..= 0xFFFF => 2,
969 // Encode the number of bytes used per diff.
970 bytes_per_diff.encode(s)?;
972 // Encode the first element.
975 let diff_iter = (&lines[..]).windows(2)
976 .map(|w| (w[1] - w[0]));
978 match bytes_per_diff {
979 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
980 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
981 4 => for diff in diff_iter { diff.0.encode(s)? },
988 s.emit_struct_field("multibyte_chars", 6, |s| {
989 self.multibyte_chars.encode(s)
991 s.emit_struct_field("non_narrow_chars", 7, |s| {
992 self.non_narrow_chars.encode(s)
994 s.emit_struct_field("name_hash", 8, |s| {
995 self.name_hash.encode(s)
997 s.emit_struct_field("normalized_pos", 9, |s| {
998 self.normalized_pos.encode(s)
1004 impl Decodable for SourceFile {
1005 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
1006 d.read_struct("SourceFile", 8, |d| {
1007 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1008 let name_was_remapped: bool =
1009 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1010 let src_hash: u128 =
1011 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1012 let start_pos: BytePos =
1013 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1014 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1015 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1016 let num_lines: u32 = Decodable::decode(d)?;
1017 let mut lines = Vec::with_capacity(num_lines as usize);
1020 // Read the number of bytes used per diff.
1021 let bytes_per_diff: u8 = Decodable::decode(d)?;
1023 // Read the first element.
1024 let mut line_start: BytePos = Decodable::decode(d)?;
1025 lines.push(line_start);
1027 for _ in 1..num_lines {
1028 let diff = match bytes_per_diff {
1029 1 => d.read_u8()? as u32,
1030 2 => d.read_u16()? as u32,
1035 line_start = line_start + BytePos(diff);
1037 lines.push(line_start);
1043 let multibyte_chars: Vec<MultiByteChar> =
1044 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1045 let non_narrow_chars: Vec<NonNarrowChar> =
1046 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1047 let name_hash: u128 =
1048 d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1049 let normalized_pos: Vec<NormalizedPos> =
1050 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1054 unmapped_path: None,
1055 // `crate_of_origin` has to be set by the importer.
1056 // This value matches up with `rustc::hir::def_id::INVALID_CRATE`.
1057 // That constant is not available here, unfortunately.
1058 crate_of_origin: std::u32::MAX - 1,
1063 external_src: Lock::new(ExternalSource::AbsentOk),
1074 impl fmt::Debug for SourceFile {
1075 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1076 write!(fmt, "SourceFile({})", self.name)
1081 pub fn new(name: FileName,
1082 name_was_remapped: bool,
1083 unmapped_path: FileName,
1085 start_pos: BytePos) -> Result<SourceFile, OffsetOverflowError> {
1086 let normalized_pos = normalize_src(&mut src, start_pos);
1089 let mut hasher: StableHasher = StableHasher::new();
1090 hasher.write(src.as_bytes());
1091 hasher.finish::<u128>()
1094 let mut hasher: StableHasher = StableHasher::new();
1095 name.hash(&mut hasher);
1096 hasher.finish::<u128>()
1098 let end_pos = start_pos.to_usize() + src.len();
1099 if end_pos > u32::max_value() as usize {
1100 return Err(OffsetOverflowError);
1103 let (lines, multibyte_chars, non_narrow_chars) =
1104 analyze_source_file::analyze_source_file(&src[..], start_pos);
1109 unmapped_path: Some(unmapped_path),
1111 src: Some(Lrc::new(src)),
1113 external_src: Lock::new(ExternalSource::Unneeded),
1115 end_pos: Pos::from_usize(end_pos),
1124 /// Returns the `BytePos` of the beginning of the current line.
1125 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1126 let line_index = self.lookup_line(pos).unwrap();
1127 self.lines[line_index]
1130 /// Add externally loaded source.
1131 /// If the hash of the input doesn't match or no input is supplied via None,
1132 /// it is interpreted as an error and the corresponding enum variant is set.
1133 /// The return value signifies whether some kind of source is present.
1134 pub fn add_external_src<F>(&self, get_src: F) -> bool
1135 where F: FnOnce() -> Option<String>
1137 if *self.external_src.borrow() == ExternalSource::AbsentOk {
1138 let src = get_src();
1139 let mut external_src = self.external_src.borrow_mut();
1140 // Check that no-one else have provided the source while we were getting it
1141 if *external_src == ExternalSource::AbsentOk {
1142 if let Some(src) = src {
1143 let mut hasher: StableHasher = StableHasher::new();
1144 hasher.write(src.as_bytes());
1146 if hasher.finish::<u128>() == self.src_hash {
1147 *external_src = ExternalSource::Present(src);
1151 *external_src = ExternalSource::AbsentErr;
1156 self.src.is_some() || external_src.get_source().is_some()
1159 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1163 /// Gets a line from the list of pre-computed line-beginnings.
1164 /// The line number here is 0-based.
1165 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1166 fn get_until_newline(src: &str, begin: usize) -> &str {
1167 // We can't use `lines.get(line_number+1)` because we might
1168 // be parsing when we call this function and thus the current
1169 // line is the last one we have line info for.
1170 let slice = &src[begin..];
1171 match slice.find('\n') {
1172 Some(e) => &slice[..e],
1178 let line = if let Some(line) = self.lines.get(line_number) {
1183 let begin: BytePos = *line - self.start_pos;
1187 if let Some(ref src) = self.src {
1188 Some(Cow::from(get_until_newline(src, begin)))
1189 } else if let Some(src) = self.external_src.borrow().get_source() {
1190 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1196 pub fn is_real_file(&self) -> bool {
1200 pub fn is_imported(&self) -> bool {
1204 pub fn byte_length(&self) -> u32 {
1205 self.end_pos.0 - self.start_pos.0
1207 pub fn count_lines(&self) -> usize {
1211 /// Finds the line containing the given position. The return value is the
1212 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1213 /// number. If the source_file is empty or the position is located before the
1214 /// first line, `None` is returned.
1215 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1216 if self.lines.len() == 0 {
1220 let line_index = lookup_line(&self.lines[..], pos);
1221 assert!(line_index < self.lines.len() as isize);
1222 if line_index >= 0 {
1223 Some(line_index as usize)
1229 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1230 if self.start_pos == self.end_pos {
1231 return (self.start_pos, self.end_pos);
1234 assert!(line_index < self.lines.len());
1235 if line_index == (self.lines.len() - 1) {
1236 (self.lines[line_index], self.end_pos)
1238 (self.lines[line_index], self.lines[line_index + 1])
1243 pub fn contains(&self, byte_pos: BytePos) -> bool {
1244 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1247 /// Calculates the original byte position relative to the start of the file
1248 /// based on the given byte position.
1249 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1251 // Diff before any records is 0. Otherwise use the previously recorded
1252 // diff as that applies to the following characters until a new diff
1254 let diff = match self.normalized_pos.binary_search_by(
1255 |np| np.pos.cmp(&pos)) {
1256 Ok(i) => self.normalized_pos[i].diff,
1257 Err(i) if i == 0 => 0,
1258 Err(i) => self.normalized_pos[i-1].diff,
1261 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1265 /// Normalizes the source code and records the normalizations.
1266 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1267 let mut normalized_pos = vec![];
1268 remove_bom(src, &mut normalized_pos);
1269 normalize_newlines(src, &mut normalized_pos);
1271 // Offset all the positions by start_pos to match the final file positions.
1272 for np in &mut normalized_pos {
1273 np.pos.0 += start_pos.0;
1279 /// Removes UTF-8 BOM, if any.
1280 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1281 if src.starts_with("\u{feff}") {
1283 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1288 /// Replaces `\r\n` with `\n` in-place in `src`.
1290 /// Returns error if there's a lone `\r` in the string
1291 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1292 if !src.as_bytes().contains(&b'\r') {
1296 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1297 // While we *can* call `as_mut_vec` and do surgery on the live string
1298 // directly, let's rather steal the contents of `src`. This makes the code
1299 // safe even if a panic occurs.
1301 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1302 let mut gap_len = 0;
1303 let mut tail = buf.as_mut_slice();
1305 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1307 let idx = match find_crlf(&tail[gap_len..]) {
1309 Some(idx) => idx + gap_len,
1311 tail.copy_within(gap_len..idx, 0);
1312 tail = &mut tail[idx - gap_len..];
1313 if tail.len() == gap_len {
1316 cursor += idx - gap_len;
1318 normalized_pos.push(NormalizedPos {
1319 pos: BytePos::from_usize(cursor + 1),
1320 diff: original_gap + gap_len as u32,
1324 // Account for removed `\r`.
1325 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1326 let new_len = buf.len() - gap_len;
1328 buf.set_len(new_len);
1329 *src = String::from_utf8_unchecked(buf);
1332 fn find_crlf(src: &[u8]) -> Option<usize> {
1333 let mut search_idx = 0;
1334 while let Some(idx) = find_cr(&src[search_idx..]) {
1335 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1336 search_idx += idx + 1;
1339 return Some(search_idx + idx);
1344 fn find_cr(src: &[u8]) -> Option<usize> {
1345 src.iter().position(|&b| b == b'\r')
1349 // _____________________________________________________________________________
1350 // Pos, BytePos, CharPos
1354 fn from_usize(n: usize) -> Self;
1355 fn to_usize(&self) -> usize;
1356 fn from_u32(n: u32) -> Self;
1357 fn to_u32(&self) -> u32;
1360 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1362 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1363 pub struct BytePos(pub u32);
1365 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1366 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1367 /// values to `CharPos` values as necessary.
1368 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1369 pub struct CharPos(pub usize);
1371 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1372 // have been unsuccessful.
1374 impl Pos for BytePos {
1376 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1379 fn to_usize(&self) -> usize { self.0 as usize }
1382 fn from_u32(n: u32) -> BytePos { BytePos(n) }
1385 fn to_u32(&self) -> u32 { self.0 }
1388 impl Add for BytePos {
1389 type Output = BytePos;
1392 fn add(self, rhs: BytePos) -> BytePos {
1393 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1397 impl Sub for BytePos {
1398 type Output = BytePos;
1401 fn sub(self, rhs: BytePos) -> BytePos {
1402 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1406 impl Encodable for BytePos {
1407 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1412 impl Decodable for BytePos {
1413 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1414 Ok(BytePos(d.read_u32()?))
1418 impl Pos for CharPos {
1420 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1423 fn to_usize(&self) -> usize { self.0 }
1426 fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1429 fn to_u32(&self) -> u32 { self.0 as u32}
1432 impl Add for CharPos {
1433 type Output = CharPos;
1436 fn add(self, rhs: CharPos) -> CharPos {
1437 CharPos(self.to_usize() + rhs.to_usize())
1441 impl Sub for CharPos {
1442 type Output = CharPos;
1445 fn sub(self, rhs: CharPos) -> CharPos {
1446 CharPos(self.to_usize() - rhs.to_usize())
1450 // _____________________________________________________________________________
1451 // Loc, SourceFileAndLine, SourceFileAndBytePos
1454 /// A source code location used for error reporting.
1455 #[derive(Debug, Clone)]
1457 /// Information about the original source.
1458 pub file: Lrc<SourceFile>,
1459 /// The (1-based) line number.
1461 /// The (0-based) column offset.
1463 /// The (0-based) column offset when displayed.
1464 pub col_display: usize,
1467 // Used to be structural records.
1469 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1471 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1473 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1474 pub struct LineInfo {
1475 /// Index of line, starting from 0.
1476 pub line_index: usize,
1478 /// Column in line where span begins, starting from 0.
1479 pub start_col: CharPos,
1481 /// Column in line where span ends, starting from 0, exclusive.
1482 pub end_col: CharPos,
1485 pub struct FileLines {
1486 pub file: Lrc<SourceFile>,
1487 pub lines: Vec<LineInfo>
1490 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1491 Cell::new(default_span_debug));
1494 pub struct MacroBacktrace {
1495 /// span where macro was applied to generate this code
1496 pub call_site: Span,
1498 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1499 pub macro_decl_name: String,
1501 /// span where macro was defined (possibly dummy)
1502 pub def_site_span: Span,
1505 // _____________________________________________________________________________
1506 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1509 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1511 #[derive(Clone, PartialEq, Eq, Debug)]
1512 pub enum SpanLinesError {
1513 DistinctSources(DistinctSources),
1516 #[derive(Clone, PartialEq, Eq, Debug)]
1517 pub enum SpanSnippetError {
1518 IllFormedSpan(Span),
1519 DistinctSources(DistinctSources),
1520 MalformedForSourcemap(MalformedSourceMapPositions),
1521 SourceNotAvailable { filename: FileName }
1524 #[derive(Clone, PartialEq, Eq, Debug)]
1525 pub struct DistinctSources {
1526 pub begin: (FileName, BytePos),
1527 pub end: (FileName, BytePos)
1530 #[derive(Clone, PartialEq, Eq, Debug)]
1531 pub struct MalformedSourceMapPositions {
1533 pub source_len: usize,
1534 pub begin_pos: BytePos,
1535 pub end_pos: BytePos
1538 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1539 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1540 pub struct InnerSpan {
1546 pub fn new(start: usize, end: usize) -> InnerSpan {
1547 InnerSpan { start, end }
1551 // Given a slice of line start positions and a position, returns the index of
1552 // the line the position is on. Returns -1 if the position is located before
1554 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1555 match lines.binary_search(&pos) {
1556 Ok(line) => line as isize,
1557 Err(line) => line as isize - 1