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 #![cfg_attr(bootstrap, feature(non_exhaustive))]
13 #![feature(optin_builtin_traits)]
14 #![feature(rustc_attrs)]
15 #![cfg_attr(bootstrap, feature(proc_macro_hygiene))]
16 #![feature(specialization)]
17 #![feature(step_trait)]
19 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;
35 use rustc_data_structures::stable_hasher::StableHasher;
36 use rustc_data_structures::sync::{Lrc, Lock};
40 use std::cmp::{self, Ordering};
42 use std::hash::{Hasher, Hash};
43 use std::ops::{Add, Sub};
44 use std::path::PathBuf;
50 symbol_interner: Lock<symbol::Interner>,
51 span_interner: Lock<span_encoding::SpanInterner>,
52 hygiene_data: Lock<hygiene::HygieneData>,
56 pub fn new(edition: Edition) -> Globals {
58 symbol_interner: Lock::new(symbol::Interner::fresh()),
59 span_interner: Lock::new(span_encoding::SpanInterner::default()),
60 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
65 scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
67 /// Differentiates between real files and common virtual files.
68 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
71 /// A macro. This includes the full name of the macro, so that there are no clashes.
77 /// Hack in `src/libsyntax/parse.rs`.
80 ProcMacroSourceCode(u64),
81 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
83 /// Strings provided as crate attributes in the CLI.
85 /// Custom sources for explicit parser calls from plugins and drivers.
87 DocTest(PathBuf, isize),
90 impl std::fmt::Display for FileName {
91 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 Real(ref path) => write!(fmt, "{}", path.display()),
95 Macros(ref name) => write!(fmt, "<{} macros>", name),
96 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
97 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
98 Anon(_) => write!(fmt, "<anon>"),
99 ProcMacroSourceCode(_) =>
100 write!(fmt, "<proc-macro source code>"),
101 CfgSpec(_) => write!(fmt, "<cfgspec>"),
102 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
103 Custom(ref s) => write!(fmt, "<{}>", s),
104 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
109 impl From<PathBuf> for FileName {
110 fn from(p: PathBuf) -> Self {
111 assert!(!p.to_string_lossy().ends_with('>'));
117 pub fn is_real(&self) -> bool {
124 ProcMacroSourceCode(_) |
129 DocTest(_, _) => false,
133 pub fn is_macros(&self) -> bool {
139 ProcMacroSourceCode(_) |
144 DocTest(_, _) => false,
149 pub fn quote_expansion_source_code(src: &str) -> FileName {
150 let mut hasher = StableHasher::new();
151 src.hash(&mut hasher);
152 FileName::QuoteExpansion(hasher.finish())
155 pub fn macro_expansion_source_code(src: &str) -> FileName {
156 let mut hasher = StableHasher::new();
157 src.hash(&mut hasher);
158 FileName::MacroExpansion(hasher.finish())
161 pub fn anon_source_code(src: &str) -> FileName {
162 let mut hasher = StableHasher::new();
163 src.hash(&mut hasher);
164 FileName::Anon(hasher.finish())
167 pub fn proc_macro_source_code(src: &str) -> FileName {
168 let mut hasher = StableHasher::new();
169 src.hash(&mut hasher);
170 FileName::ProcMacroSourceCode(hasher.finish())
173 pub fn cfg_spec_source_code(src: &str) -> FileName {
174 let mut hasher = StableHasher::new();
175 src.hash(&mut hasher);
176 FileName::QuoteExpansion(hasher.finish())
179 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
180 let mut hasher = StableHasher::new();
181 src.hash(&mut hasher);
182 FileName::CliCrateAttr(hasher.finish())
185 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{
186 FileName::DocTest(path, line)
190 /// Spans represent a region of code, used for error reporting. Positions in spans
191 /// are *absolute* positions from the beginning of the source_map, not positions
192 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
193 /// to the original source.
194 /// You must be careful if the span crosses more than one file - you will not be
195 /// able to use many of the functions on spans in source_map and you cannot assume
196 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
197 /// range between files.
199 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
200 /// sent to other threads, but some pieces of performance infra run in a separate thread.
201 /// Using `Span` is generally preferred.
202 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
203 pub struct SpanData {
206 /// Information about where the macro came from, if this piece of
207 /// code was created by a macro expansion.
208 pub ctxt: SyntaxContext,
213 pub fn with_lo(&self, lo: BytePos) -> Span {
214 Span::new(lo, self.hi, self.ctxt)
217 pub fn with_hi(&self, hi: BytePos) -> Span {
218 Span::new(self.lo, hi, self.ctxt)
221 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
222 Span::new(self.lo, self.hi, ctxt)
226 // The interner is pointed to by a thread local value which is only set on the main thread
227 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
228 // to avoid panics and other errors, even though it would be memory safe to do so.
229 #[cfg(not(parallel_compiler))]
230 impl !Send for Span {}
231 #[cfg(not(parallel_compiler))]
232 impl !Sync for Span {}
234 impl PartialOrd for Span {
235 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
236 PartialOrd::partial_cmp(&self.data(), &rhs.data())
240 fn cmp(&self, rhs: &Self) -> Ordering {
241 Ord::cmp(&self.data(), &rhs.data())
245 /// A collection of spans. Spans have two orthogonal attributes:
247 /// - They can be *primary spans*. In this case they are the locus of
248 /// the error, and would be rendered with `^^^`.
249 /// - They can have a *label*. In this case, the label is written next
250 /// to the mark in the snippet when we render.
251 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
252 pub struct MultiSpan {
253 primary_spans: Vec<Span>,
254 span_labels: Vec<(Span, String)>,
259 pub fn lo(self) -> BytePos {
263 pub fn with_lo(self, lo: BytePos) -> Span {
264 self.data().with_lo(lo)
267 pub fn hi(self) -> BytePos {
271 pub fn with_hi(self, hi: BytePos) -> Span {
272 self.data().with_hi(hi)
275 pub fn ctxt(self) -> SyntaxContext {
279 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
280 self.data().with_ctxt(ctxt)
283 /// Returns `true` if this is a dummy span with any hygienic context.
285 pub fn is_dummy(self) -> bool {
286 let span = self.data();
287 span.lo.0 == 0 && span.hi.0 == 0
290 /// Returns `true` if this span comes from a macro or desugaring.
292 pub fn from_expansion(self) -> bool {
293 self.ctxt() != SyntaxContext::root()
297 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
298 Span::new(lo, hi, SyntaxContext::root())
301 /// Returns a new span representing an empty span at the beginning of this span
303 pub fn shrink_to_lo(self) -> Span {
304 let span = self.data();
305 span.with_hi(span.lo)
307 /// Returns a new span representing an empty span at the end of this span.
309 pub fn shrink_to_hi(self) -> Span {
310 let span = self.data();
311 span.with_lo(span.hi)
314 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
315 pub fn substitute_dummy(self, other: Span) -> Span {
316 if self.is_dummy() { other } else { self }
319 /// Returns `true` if `self` fully encloses `other`.
320 pub fn contains(self, other: Span) -> bool {
321 let span = self.data();
322 let other = other.data();
323 span.lo <= other.lo && other.hi <= span.hi
326 /// Returns `true` if `self` touches `other`.
327 pub fn overlaps(self, other: Span) -> bool {
328 let span = self.data();
329 let other = other.data();
330 span.lo < other.hi && other.lo < span.hi
333 /// Returns `true` if the spans are equal with regards to the source text.
335 /// Use this instead of `==` when either span could be generated code,
336 /// and you only care that they point to the same bytes of source text.
337 pub fn source_equal(&self, other: &Span) -> bool {
338 let span = self.data();
339 let other = other.data();
340 span.lo == other.lo && span.hi == other.hi
343 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
344 pub fn trim_start(self, other: Span) -> Option<Span> {
345 let span = self.data();
346 let other = other.data();
347 if span.hi > other.hi {
348 Some(span.with_lo(cmp::max(span.lo, other.hi)))
354 /// Returns the source span -- this is either the supplied span, or the span for
355 /// the macro callsite that expanded to it.
356 pub fn source_callsite(self) -> Span {
357 let expn_data = self.ctxt().outer_expn_data();
358 if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
361 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
363 pub fn parent(self) -> Option<Span> {
364 let expn_data = self.ctxt().outer_expn_data();
365 if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
368 /// Edition of the crate from which this span came.
369 pub fn edition(self) -> edition::Edition {
370 self.ctxt().outer_expn_data().edition
374 pub fn rust_2015(&self) -> bool {
375 self.edition() == edition::Edition::Edition2015
379 pub fn rust_2018(&self) -> bool {
380 self.edition() >= edition::Edition::Edition2018
383 /// Returns the source callee.
385 /// Returns `None` if the supplied span has no expansion trace,
386 /// else returns the `ExpnData` for the macro definition
387 /// corresponding to the source callsite.
388 pub fn source_callee(self) -> Option<ExpnData> {
389 fn source_callee(expn_data: ExpnData) -> ExpnData {
390 let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
391 if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
393 let expn_data = self.ctxt().outer_expn_data();
394 if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
397 /// Checks if a span is "internal" to a macro in which `#[unstable]`
398 /// items can be used (that is, a macro marked with
399 /// `#[allow_internal_unstable]`).
400 pub fn allows_unstable(&self, feature: Symbol) -> bool {
401 self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
402 features.iter().any(|&f| {
403 f == feature || f == sym::allow_internal_unstable_backcompat_hack
408 /// Checks if this span arises from a compiler desugaring of kind `kind`.
409 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
410 match self.ctxt().outer_expn_data().kind {
411 ExpnKind::Desugaring(k) => k == kind,
416 /// Returns the compiler desugaring that created this span, or `None`
417 /// if this span is not from a desugaring.
418 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
419 match self.ctxt().outer_expn_data().kind {
420 ExpnKind::Desugaring(k) => Some(k),
425 /// Checks if a span is "internal" to a macro in which `unsafe`
426 /// can be used without triggering the `unsafe_code` lint
427 // (that is, a macro marked with `#[allow_internal_unsafe]`).
428 pub fn allows_unsafe(&self) -> bool {
429 self.ctxt().outer_expn_data().allow_internal_unsafe
432 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
433 let mut prev_span = DUMMY_SP;
434 let mut result = vec![];
436 let expn_data = self.ctxt().outer_expn_data();
437 if expn_data.is_root() {
440 // Don't print recursive invocations.
441 if !expn_data.call_site.source_equal(&prev_span) {
442 let (pre, post) = match expn_data.kind {
443 ExpnKind::Root => break,
444 ExpnKind::Desugaring(..) => ("desugaring of ", ""),
445 ExpnKind::AstPass(..) => ("", ""),
446 ExpnKind::Macro(macro_kind, _) => match macro_kind {
447 MacroKind::Bang => ("", "!"),
448 MacroKind::Attr => ("#[", "]"),
449 MacroKind::Derive => ("#[derive(", ")]"),
452 result.push(MacroBacktrace {
453 call_site: expn_data.call_site,
454 macro_decl_name: format!("{}{}{}", pre, expn_data.kind.descr(), post),
455 def_site_span: expn_data.def_site,
460 self = expn_data.call_site;
465 /// Returns a `Span` that would enclose both `self` and `end`.
466 pub fn to(self, end: Span) -> Span {
467 let span_data = self.data();
468 let end_data = end.data();
469 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
470 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
471 // have an incomplete span than a completely nonsensical one.
472 if span_data.ctxt != end_data.ctxt {
473 if span_data.ctxt == SyntaxContext::root() {
475 } else if end_data.ctxt == SyntaxContext::root() {
478 // Both spans fall within a macro.
479 // FIXME(estebank): check if it is the *same* macro.
482 cmp::min(span_data.lo, end_data.lo),
483 cmp::max(span_data.hi, end_data.hi),
484 if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
488 /// Returns a `Span` between the end of `self` to the beginning of `end`.
489 pub fn between(self, end: Span) -> Span {
490 let span = self.data();
491 let end = end.data();
495 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
499 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
500 pub fn until(self, end: Span) -> Span {
501 let span = self.data();
502 let end = end.data();
506 if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
510 pub fn from_inner(self, inner: InnerSpan) -> Span {
511 let span = self.data();
512 Span::new(span.lo + BytePos::from_usize(inner.start),
513 span.lo + BytePos::from_usize(inner.end),
517 /// Equivalent of `Span::def_site` from the proc macro API,
518 /// except that the location is taken from the `self` span.
519 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
520 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
523 /// Equivalent of `Span::call_site` from the proc macro API,
524 /// except that the location is taken from the `self` span.
525 pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
526 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
529 /// Equivalent of `Span::mixed_site` from the proc macro API,
530 /// except that the location is taken from the `self` span.
531 pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
532 self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
535 /// Produces a span with the same location as `self` and context produced by a macro with the
536 /// given ID and transparency, assuming that macro was defined directly and not produced by
537 /// some other macro (which is the case for built-in and procedural macros).
538 pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
539 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
543 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
544 let span = self.data();
545 span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
549 pub fn remove_mark(&mut self) -> ExpnId {
550 let mut span = self.data();
551 let mark = span.ctxt.remove_mark();
552 *self = Span::new(span.lo, span.hi, span.ctxt);
557 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
558 let mut span = self.data();
559 let mark = span.ctxt.adjust(expn_id);
560 *self = Span::new(span.lo, span.hi, span.ctxt);
565 pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
566 let mut span = self.data();
567 let mark = span.ctxt.modernize_and_adjust(expn_id);
568 *self = Span::new(span.lo, span.hi, span.ctxt);
573 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
574 let mut span = self.data();
575 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
576 *self = Span::new(span.lo, span.hi, span.ctxt);
581 pub fn reverse_glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span)
582 -> Option<Option<ExpnId>> {
583 let mut span = self.data();
584 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
585 *self = Span::new(span.lo, span.hi, span.ctxt);
590 pub fn modern(self) -> Span {
591 let span = self.data();
592 span.with_ctxt(span.ctxt.modern())
596 pub fn modern_and_legacy(self) -> Span {
597 let span = self.data();
598 span.with_ctxt(span.ctxt.modern_and_legacy())
602 #[derive(Clone, Debug)]
603 pub struct SpanLabel {
604 /// The span we are going to include in the final snippet.
607 /// Is this a primary span? This is the "locus" of the message,
608 /// and is indicated with a `^^^^` underline, versus `----`.
609 pub is_primary: bool,
611 /// What label should we attach to this span (if any)?
612 pub label: Option<String>,
615 impl Default for Span {
616 fn default() -> Self {
621 impl rustc_serialize::UseSpecializedEncodable for Span {
622 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
623 let span = self.data();
624 s.emit_struct("Span", 2, |s| {
625 s.emit_struct_field("lo", 0, |s| {
629 s.emit_struct_field("hi", 1, |s| {
636 impl rustc_serialize::UseSpecializedDecodable for Span {
637 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
638 d.read_struct("Span", 2, |d| {
639 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
640 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
641 Ok(Span::with_root_ctxt(lo, hi))
646 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647 f.debug_struct("Span")
648 .field("lo", &span.lo())
649 .field("hi", &span.hi())
650 .field("ctxt", &span.ctxt())
654 impl fmt::Debug for Span {
655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
660 impl fmt::Debug for SpanData {
661 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
662 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
668 pub fn new() -> MultiSpan {
670 primary_spans: vec![],
675 pub fn from_span(primary_span: Span) -> MultiSpan {
677 primary_spans: vec![primary_span],
682 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
689 pub fn push_span_label(&mut self, span: Span, label: String) {
690 self.span_labels.push((span, label));
693 /// Selects the first primary span (if any).
694 pub fn primary_span(&self) -> Option<Span> {
695 self.primary_spans.first().cloned()
698 /// Returns all primary spans.
699 pub fn primary_spans(&self) -> &[Span] {
703 /// Returns `true` if any of the primary spans are displayable.
704 pub fn has_primary_spans(&self) -> bool {
705 self.primary_spans.iter().any(|sp| !sp.is_dummy())
708 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
709 pub fn is_dummy(&self) -> bool {
710 let mut is_dummy = true;
711 for span in &self.primary_spans {
712 if !span.is_dummy() {
719 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
720 /// display well (like std macros). Returns whether replacements occurred.
721 pub fn replace(&mut self, before: Span, after: Span) -> bool {
722 let mut replacements_occurred = false;
723 for primary_span in &mut self.primary_spans {
724 if *primary_span == before {
725 *primary_span = after;
726 replacements_occurred = true;
729 for span_label in &mut self.span_labels {
730 if span_label.0 == before {
731 span_label.0 = after;
732 replacements_occurred = true;
735 replacements_occurred
738 /// Returns the strings to highlight. We always ensure that there
739 /// is an entry for each of the primary spans -- for each primary
740 /// span `P`, if there is at least one label with span `P`, we return
741 /// those labels (marked as primary). But otherwise we return
742 /// `SpanLabel` instances with empty labels.
743 pub fn span_labels(&self) -> Vec<SpanLabel> {
744 let is_primary = |span| self.primary_spans.contains(&span);
746 let mut span_labels = self.span_labels.iter().map(|&(span, ref label)|
749 is_primary: is_primary(span),
750 label: Some(label.clone())
752 ).collect::<Vec<_>>();
754 for &span in &self.primary_spans {
755 if !span_labels.iter().any(|sl| sl.span == span) {
756 span_labels.push(SpanLabel {
767 /// Returns `true` if any of the span labels is displayable.
768 pub fn has_span_labels(&self) -> bool {
769 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
773 impl From<Span> for MultiSpan {
774 fn from(span: Span) -> MultiSpan {
775 MultiSpan::from_span(span)
779 impl From<Vec<Span>> for MultiSpan {
780 fn from(spans: Vec<Span>) -> MultiSpan {
781 MultiSpan::from_spans(spans)
785 /// Identifies an offset of a multi-byte character in a `SourceFile`.
786 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
787 pub struct MultiByteChar {
788 /// The absolute offset of the character in the `SourceMap`.
790 /// The number of bytes, `>= 2`.
794 /// Identifies an offset of a non-narrow character in a `SourceFile`.
795 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
796 pub enum NonNarrowChar {
797 /// Represents a zero-width character.
799 /// Represents a wide (full-width) character.
801 /// Represents a tab character, represented visually with a width of 4 characters.
806 fn new(pos: BytePos, width: usize) -> Self {
808 0 => NonNarrowChar::ZeroWidth(pos),
809 2 => NonNarrowChar::Wide(pos),
810 4 => NonNarrowChar::Tab(pos),
811 _ => panic!("width {} given for non-narrow character", width),
815 /// Returns the absolute offset of the character in the `SourceMap`.
816 pub fn pos(&self) -> BytePos {
818 NonNarrowChar::ZeroWidth(p) |
819 NonNarrowChar::Wide(p) |
820 NonNarrowChar::Tab(p) => p,
824 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
825 pub fn width(&self) -> usize {
827 NonNarrowChar::ZeroWidth(_) => 0,
828 NonNarrowChar::Wide(_) => 2,
829 NonNarrowChar::Tab(_) => 4,
834 impl Add<BytePos> for NonNarrowChar {
837 fn add(self, rhs: BytePos) -> Self {
839 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
840 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
841 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
846 impl Sub<BytePos> for NonNarrowChar {
849 fn sub(self, rhs: BytePos) -> Self {
851 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
852 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
853 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
858 /// Identifies an offset of a character that was normalized away from `SourceFile`.
859 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
860 pub struct NormalizedPos {
861 /// The absolute offset of the character in the `SourceMap`.
863 /// The difference between original and normalized string at position.
867 /// The state of the lazy external source loading mechanism of a `SourceFile`.
868 #[derive(PartialEq, Eq, Clone)]
869 pub enum ExternalSource {
870 /// The external source has been loaded already.
872 /// No attempt has been made to load the external source.
874 /// A failed attempt has been made to load the external source.
876 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
880 impl ExternalSource {
881 pub fn is_absent(&self) -> bool {
883 ExternalSource::Present(_) => false,
888 pub fn get_source(&self) -> Option<&str> {
890 ExternalSource::Present(ref src) => Some(src),
897 pub struct OffsetOverflowError;
899 /// A single source in the `SourceMap`.
901 pub struct SourceFile {
902 /// The name of the file that the source came from. Source that doesn't
903 /// originate from files has names between angle brackets by convention
904 /// (e.g., `<anon>`).
906 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
907 pub name_was_remapped: bool,
908 /// The unmapped path of the file that the source came from.
909 /// Set to `None` if the `SourceFile` was imported from an external crate.
910 pub unmapped_path: Option<FileName>,
911 /// Indicates which crate this `SourceFile` was imported from.
912 pub crate_of_origin: u32,
913 /// The complete source code.
914 pub src: Option<Lrc<String>>,
915 /// The source code's hash.
917 /// The external source code (used for external crates, which will have a `None`
918 /// value as `self.src`.
919 pub external_src: Lock<ExternalSource>,
920 /// The start position of this source in the `SourceMap`.
921 pub start_pos: BytePos,
922 /// The end position of this source in the `SourceMap`.
923 pub end_pos: BytePos,
924 /// Locations of lines beginnings in the source code.
925 pub lines: Vec<BytePos>,
926 /// Locations of multi-byte characters in the source code.
927 pub multibyte_chars: Vec<MultiByteChar>,
928 /// Width of characters that are not narrow in the source code.
929 pub non_narrow_chars: Vec<NonNarrowChar>,
930 /// Locations of characters removed during normalization.
931 pub normalized_pos: Vec<NormalizedPos>,
932 /// A hash of the filename, used for speeding up hashing in incremental compilation.
936 impl Encodable for SourceFile {
937 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
938 s.emit_struct("SourceFile", 8, |s| {
939 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
940 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
941 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
942 s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
943 s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
944 s.emit_struct_field("lines", 5, |s| {
945 let lines = &self.lines[..];
947 s.emit_u32(lines.len() as u32)?;
949 if !lines.is_empty() {
950 // In order to preserve some space, we exploit the fact that
951 // the lines list is sorted and individual lines are
952 // probably not that long. Because of that we can store lines
953 // as a difference list, using as little space as possible
954 // for the differences.
955 let max_line_length = if lines.len() == 1 {
959 .map(|w| w[1] - w[0])
960 .map(|bp| bp.to_usize())
965 let bytes_per_diff: u8 = match max_line_length {
967 0x100 ..= 0xFFFF => 2,
971 // Encode the number of bytes used per diff.
972 bytes_per_diff.encode(s)?;
974 // Encode the first element.
977 let diff_iter = (&lines[..]).windows(2)
978 .map(|w| (w[1] - w[0]));
980 match bytes_per_diff {
981 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
982 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
983 4 => for diff in diff_iter { diff.0.encode(s)? },
990 s.emit_struct_field("multibyte_chars", 6, |s| {
991 self.multibyte_chars.encode(s)
993 s.emit_struct_field("non_narrow_chars", 7, |s| {
994 self.non_narrow_chars.encode(s)
996 s.emit_struct_field("name_hash", 8, |s| {
997 self.name_hash.encode(s)
999 s.emit_struct_field("normalized_pos", 9, |s| {
1000 self.normalized_pos.encode(s)
1006 impl Decodable for SourceFile {
1007 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
1008 d.read_struct("SourceFile", 8, |d| {
1009 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1010 let name_was_remapped: bool =
1011 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1012 let src_hash: u128 =
1013 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1014 let start_pos: BytePos =
1015 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1016 let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1017 let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1018 let num_lines: u32 = Decodable::decode(d)?;
1019 let mut lines = Vec::with_capacity(num_lines as usize);
1022 // Read the number of bytes used per diff.
1023 let bytes_per_diff: u8 = Decodable::decode(d)?;
1025 // Read the first element.
1026 let mut line_start: BytePos = Decodable::decode(d)?;
1027 lines.push(line_start);
1029 for _ in 1..num_lines {
1030 let diff = match bytes_per_diff {
1031 1 => d.read_u8()? as u32,
1032 2 => d.read_u16()? as u32,
1037 line_start = line_start + BytePos(diff);
1039 lines.push(line_start);
1045 let multibyte_chars: Vec<MultiByteChar> =
1046 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1047 let non_narrow_chars: Vec<NonNarrowChar> =
1048 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1049 let name_hash: u128 =
1050 d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1051 let normalized_pos: Vec<NormalizedPos> =
1052 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1056 unmapped_path: None,
1057 // `crate_of_origin` has to be set by the importer.
1058 // This value matches up with `rustc::hir::def_id::INVALID_CRATE`.
1059 // That constant is not available here, unfortunately.
1060 crate_of_origin: std::u32::MAX - 1,
1065 external_src: Lock::new(ExternalSource::AbsentOk),
1076 impl fmt::Debug for SourceFile {
1077 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1078 write!(fmt, "SourceFile({})", self.name)
1083 pub fn new(name: FileName,
1084 name_was_remapped: bool,
1085 unmapped_path: FileName,
1087 start_pos: BytePos) -> Result<SourceFile, OffsetOverflowError> {
1088 let normalized_pos = normalize_src(&mut src, start_pos);
1091 let mut hasher: StableHasher = StableHasher::new();
1092 hasher.write(src.as_bytes());
1093 hasher.finish::<u128>()
1096 let mut hasher: StableHasher = StableHasher::new();
1097 name.hash(&mut hasher);
1098 hasher.finish::<u128>()
1100 let end_pos = start_pos.to_usize() + src.len();
1101 if end_pos > u32::max_value() as usize {
1102 return Err(OffsetOverflowError);
1105 let (lines, multibyte_chars, non_narrow_chars) =
1106 analyze_source_file::analyze_source_file(&src[..], start_pos);
1111 unmapped_path: Some(unmapped_path),
1113 src: Some(Lrc::new(src)),
1115 external_src: Lock::new(ExternalSource::Unneeded),
1117 end_pos: Pos::from_usize(end_pos),
1126 /// Returns the `BytePos` of the beginning of the current line.
1127 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1128 let line_index = self.lookup_line(pos).unwrap();
1129 self.lines[line_index]
1132 /// Add externally loaded source.
1133 /// If the hash of the input doesn't match or no input is supplied via None,
1134 /// it is interpreted as an error and the corresponding enum variant is set.
1135 /// The return value signifies whether some kind of source is present.
1136 pub fn add_external_src<F>(&self, get_src: F) -> bool
1137 where F: FnOnce() -> Option<String>
1139 if *self.external_src.borrow() == ExternalSource::AbsentOk {
1140 let src = get_src();
1141 let mut external_src = self.external_src.borrow_mut();
1142 // Check that no-one else have provided the source while we were getting it
1143 if *external_src == ExternalSource::AbsentOk {
1144 if let Some(src) = src {
1145 let mut hasher: StableHasher = StableHasher::new();
1146 hasher.write(src.as_bytes());
1148 if hasher.finish::<u128>() == self.src_hash {
1149 *external_src = ExternalSource::Present(src);
1153 *external_src = ExternalSource::AbsentErr;
1158 self.src.is_some() || external_src.get_source().is_some()
1161 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1165 /// Gets a line from the list of pre-computed line-beginnings.
1166 /// The line number here is 0-based.
1167 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1168 fn get_until_newline(src: &str, begin: usize) -> &str {
1169 // We can't use `lines.get(line_number+1)` because we might
1170 // be parsing when we call this function and thus the current
1171 // line is the last one we have line info for.
1172 let slice = &src[begin..];
1173 match slice.find('\n') {
1174 Some(e) => &slice[..e],
1180 let line = if let Some(line) = self.lines.get(line_number) {
1185 let begin: BytePos = *line - self.start_pos;
1189 if let Some(ref src) = self.src {
1190 Some(Cow::from(get_until_newline(src, begin)))
1191 } else if let Some(src) = self.external_src.borrow().get_source() {
1192 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1198 pub fn is_real_file(&self) -> bool {
1202 pub fn is_imported(&self) -> bool {
1206 pub fn byte_length(&self) -> u32 {
1207 self.end_pos.0 - self.start_pos.0
1209 pub fn count_lines(&self) -> usize {
1213 /// Finds the line containing the given position. The return value is the
1214 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1215 /// number. If the source_file is empty or the position is located before the
1216 /// first line, `None` is returned.
1217 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1218 if self.lines.len() == 0 {
1222 let line_index = lookup_line(&self.lines[..], pos);
1223 assert!(line_index < self.lines.len() as isize);
1224 if line_index >= 0 {
1225 Some(line_index as usize)
1231 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1232 if self.start_pos == self.end_pos {
1233 return (self.start_pos, self.end_pos);
1236 assert!(line_index < self.lines.len());
1237 if line_index == (self.lines.len() - 1) {
1238 (self.lines[line_index], self.end_pos)
1240 (self.lines[line_index], self.lines[line_index + 1])
1245 pub fn contains(&self, byte_pos: BytePos) -> bool {
1246 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1249 /// Calculates the original byte position relative to the start of the file
1250 /// based on the given byte position.
1251 pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1253 // Diff before any records is 0. Otherwise use the previously recorded
1254 // diff as that applies to the following characters until a new diff
1256 let diff = match self.normalized_pos.binary_search_by(
1257 |np| np.pos.cmp(&pos)) {
1258 Ok(i) => self.normalized_pos[i].diff,
1259 Err(i) if i == 0 => 0,
1260 Err(i) => self.normalized_pos[i-1].diff,
1263 BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1267 /// Normalizes the source code and records the normalizations.
1268 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1269 let mut normalized_pos = vec![];
1270 remove_bom(src, &mut normalized_pos);
1271 normalize_newlines(src, &mut normalized_pos);
1273 // Offset all the positions by start_pos to match the final file positions.
1274 for np in &mut normalized_pos {
1275 np.pos.0 += start_pos.0;
1281 /// Removes UTF-8 BOM, if any.
1282 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1283 if src.starts_with("\u{feff}") {
1285 normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1290 /// Replaces `\r\n` with `\n` in-place in `src`.
1292 /// Returns error if there's a lone `\r` in the string
1293 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1294 if !src.as_bytes().contains(&b'\r') {
1298 // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1299 // While we *can* call `as_mut_vec` and do surgery on the live string
1300 // directly, let's rather steal the contents of `src`. This makes the code
1301 // safe even if a panic occurs.
1303 let mut buf = std::mem::replace(src, String::new()).into_bytes();
1304 let mut gap_len = 0;
1305 let mut tail = buf.as_mut_slice();
1307 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1309 let idx = match find_crlf(&tail[gap_len..]) {
1311 Some(idx) => idx + gap_len,
1313 tail.copy_within(gap_len..idx, 0);
1314 tail = &mut tail[idx - gap_len..];
1315 if tail.len() == gap_len {
1318 cursor += idx - gap_len;
1320 normalized_pos.push(NormalizedPos {
1321 pos: BytePos::from_usize(cursor + 1),
1322 diff: original_gap + gap_len as u32,
1326 // Account for removed `\r`.
1327 // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1328 let new_len = buf.len() - gap_len;
1330 buf.set_len(new_len);
1331 *src = String::from_utf8_unchecked(buf);
1334 fn find_crlf(src: &[u8]) -> Option<usize> {
1335 let mut search_idx = 0;
1336 while let Some(idx) = find_cr(&src[search_idx..]) {
1337 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1338 search_idx += idx + 1;
1341 return Some(search_idx + idx);
1346 fn find_cr(src: &[u8]) -> Option<usize> {
1347 src.iter().position(|&b| b == b'\r')
1351 // _____________________________________________________________________________
1352 // Pos, BytePos, CharPos
1356 fn from_usize(n: usize) -> Self;
1357 fn to_usize(&self) -> usize;
1358 fn from_u32(n: u32) -> Self;
1359 fn to_u32(&self) -> u32;
1362 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1364 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1365 pub struct BytePos(pub u32);
1367 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1368 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1369 /// values to `CharPos` values as necessary.
1370 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1371 pub struct CharPos(pub usize);
1373 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1374 // have been unsuccessful.
1376 impl Pos for BytePos {
1378 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1381 fn to_usize(&self) -> usize { self.0 as usize }
1384 fn from_u32(n: u32) -> BytePos { BytePos(n) }
1387 fn to_u32(&self) -> u32 { self.0 }
1390 impl Add for BytePos {
1391 type Output = BytePos;
1394 fn add(self, rhs: BytePos) -> BytePos {
1395 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1399 impl Sub for BytePos {
1400 type Output = BytePos;
1403 fn sub(self, rhs: BytePos) -> BytePos {
1404 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1408 impl Encodable for BytePos {
1409 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1414 impl Decodable for BytePos {
1415 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1416 Ok(BytePos(d.read_u32()?))
1420 impl Pos for CharPos {
1422 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1425 fn to_usize(&self) -> usize { self.0 }
1428 fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1431 fn to_u32(&self) -> u32 { self.0 as u32}
1434 impl Add for CharPos {
1435 type Output = CharPos;
1438 fn add(self, rhs: CharPos) -> CharPos {
1439 CharPos(self.to_usize() + rhs.to_usize())
1443 impl Sub for CharPos {
1444 type Output = CharPos;
1447 fn sub(self, rhs: CharPos) -> CharPos {
1448 CharPos(self.to_usize() - rhs.to_usize())
1452 // _____________________________________________________________________________
1453 // Loc, SourceFileAndLine, SourceFileAndBytePos
1456 /// A source code location used for error reporting.
1457 #[derive(Debug, Clone)]
1459 /// Information about the original source.
1460 pub file: Lrc<SourceFile>,
1461 /// The (1-based) line number.
1463 /// The (0-based) column offset.
1465 /// The (0-based) column offset when displayed.
1466 pub col_display: usize,
1469 // Used to be structural records.
1471 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1473 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1475 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1476 pub struct LineInfo {
1477 /// Index of line, starting from 0.
1478 pub line_index: usize,
1480 /// Column in line where span begins, starting from 0.
1481 pub start_col: CharPos,
1483 /// Column in line where span ends, starting from 0, exclusive.
1484 pub end_col: CharPos,
1487 pub struct FileLines {
1488 pub file: Lrc<SourceFile>,
1489 pub lines: Vec<LineInfo>
1492 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1493 Cell::new(default_span_debug));
1496 pub struct MacroBacktrace {
1497 /// span where macro was applied to generate this code
1498 pub call_site: Span,
1500 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1501 pub macro_decl_name: String,
1503 /// span where macro was defined (possibly dummy)
1504 pub def_site_span: Span,
1507 // _____________________________________________________________________________
1508 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1511 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1513 #[derive(Clone, PartialEq, Eq, Debug)]
1514 pub enum SpanLinesError {
1515 DistinctSources(DistinctSources),
1518 #[derive(Clone, PartialEq, Eq, Debug)]
1519 pub enum SpanSnippetError {
1520 IllFormedSpan(Span),
1521 DistinctSources(DistinctSources),
1522 MalformedForSourcemap(MalformedSourceMapPositions),
1523 SourceNotAvailable { filename: FileName }
1526 #[derive(Clone, PartialEq, Eq, Debug)]
1527 pub struct DistinctSources {
1528 pub begin: (FileName, BytePos),
1529 pub end: (FileName, BytePos)
1532 #[derive(Clone, PartialEq, Eq, Debug)]
1533 pub struct MalformedSourceMapPositions {
1535 pub source_len: usize,
1536 pub begin_pos: BytePos,
1537 pub end_pos: BytePos
1540 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1541 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1542 pub struct InnerSpan {
1548 pub fn new(start: usize, end: usize) -> InnerSpan {
1549 InnerSpan { start, end }
1553 // Given a slice of line start positions and a position, returns the index of
1554 // the line the position is on. Returns -1 if the position is located before
1556 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1557 match lines.binary_search(&pos) {
1558 Ok(line) => line as isize,
1559 Err(line) => line as isize - 1