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/")]
9 #![deny(rust_2018_idioms)]
10 #![deny(unused_lifetimes)]
13 #![feature(crate_visibility_modifier)]
15 #![feature(non_exhaustive)]
16 #![feature(optin_builtin_traits)]
17 #![feature(rustc_attrs)]
18 #![feature(proc_macro_hygiene)]
19 #![feature(specialization)]
20 #![feature(step_trait)]
22 use rustc_serialize::{Encodable, Decodable, Encoder, Decoder};
27 pub use hygiene::{ExpnId, SyntaxContext, ExpnInfo, ExpnKind, MacroKind, DesugaringKind};
30 pub use span_encoding::{Span, DUMMY_SP};
33 pub use symbol::{Symbol, sym};
35 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;
49 symbol_interner: Lock<symbol::Interner>,
50 span_interner: Lock<span_encoding::SpanInterner>,
51 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)),
66 scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
68 /// Differentiates between real files and common virtual files.
69 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
72 /// A macro. This includes the full name of the macro, so that there are no clashes.
78 /// Hack in `src/libsyntax/parse.rs`.
81 ProcMacroSourceCode(u64),
82 /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
84 /// Strings provided as crate attributes in the CLI.
86 /// Custom sources for explicit parser calls from plugins and drivers.
88 DocTest(PathBuf, isize),
91 impl std::fmt::Display for FileName {
92 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 Real(ref path) => write!(fmt, "{}", path.display()),
96 Macros(ref name) => write!(fmt, "<{} macros>", name),
97 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
98 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
99 Anon(_) => write!(fmt, "<anon>"),
100 ProcMacroSourceCode(_) =>
101 write!(fmt, "<proc-macro source code>"),
102 CfgSpec(_) => write!(fmt, "<cfgspec>"),
103 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
104 Custom(ref s) => write!(fmt, "<{}>", s),
105 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
110 impl From<PathBuf> for FileName {
111 fn from(p: PathBuf) -> Self {
112 assert!(!p.to_string_lossy().ends_with('>'));
118 pub fn is_real(&self) -> bool {
125 ProcMacroSourceCode(_) |
130 DocTest(_, _) => false,
134 pub fn is_macros(&self) -> bool {
140 ProcMacroSourceCode(_) |
145 DocTest(_, _) => false,
150 pub fn quote_expansion_source_code(src: &str) -> FileName {
151 let mut hasher = StableHasher::new();
152 src.hash(&mut hasher);
153 FileName::QuoteExpansion(hasher.finish())
156 pub fn macro_expansion_source_code(src: &str) -> FileName {
157 let mut hasher = StableHasher::new();
158 src.hash(&mut hasher);
159 FileName::MacroExpansion(hasher.finish())
162 pub fn anon_source_code(src: &str) -> FileName {
163 let mut hasher = StableHasher::new();
164 src.hash(&mut hasher);
165 FileName::Anon(hasher.finish())
168 pub fn proc_macro_source_code(src: &str) -> FileName {
169 let mut hasher = StableHasher::new();
170 src.hash(&mut hasher);
171 FileName::ProcMacroSourceCode(hasher.finish())
174 pub fn cfg_spec_source_code(src: &str) -> FileName {
175 let mut hasher = StableHasher::new();
176 src.hash(&mut hasher);
177 FileName::QuoteExpansion(hasher.finish())
180 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
181 let mut hasher = StableHasher::new();
182 src.hash(&mut hasher);
183 FileName::CliCrateAttr(hasher.finish())
186 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{
187 FileName::DocTest(path, line)
191 /// Spans represent a region of code, used for error reporting. Positions in spans
192 /// are *absolute* positions from the beginning of the source_map, not positions
193 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
194 /// to the original source.
195 /// You must be careful if the span crosses more than one file - you will not be
196 /// able to use many of the functions on spans in source_map and you cannot assume
197 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
198 /// range between files.
200 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
201 /// sent to other threads, but some pieces of performance infra run in a separate thread.
202 /// Using `Span` is generally preferred.
203 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
204 pub struct SpanData {
207 /// Information about where the macro came from, if this piece of
208 /// code was created by a macro expansion.
209 pub ctxt: SyntaxContext,
214 pub fn with_lo(&self, lo: BytePos) -> Span {
215 Span::new(lo, self.hi, self.ctxt)
218 pub fn with_hi(&self, hi: BytePos) -> Span {
219 Span::new(self.lo, hi, self.ctxt)
222 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
223 Span::new(self.lo, self.hi, ctxt)
227 // The interner is pointed to by a thread local value which is only set on the main thread
228 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
229 // to avoid panics and other errors, even though it would be memory safe to do so.
230 #[cfg(not(parallel_compiler))]
231 impl !Send for Span {}
232 #[cfg(not(parallel_compiler))]
233 impl !Sync for Span {}
235 impl PartialOrd for Span {
236 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
237 PartialOrd::partial_cmp(&self.data(), &rhs.data())
241 fn cmp(&self, rhs: &Self) -> Ordering {
242 Ord::cmp(&self.data(), &rhs.data())
246 /// A collection of spans. Spans have two orthogonal attributes:
248 /// - They can be *primary spans*. In this case they are the locus of
249 /// the error, and would be rendered with `^^^`.
250 /// - They can have a *label*. In this case, the label is written next
251 /// to the mark in the snippet when we render.
252 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
253 pub struct MultiSpan {
254 primary_spans: Vec<Span>,
255 span_labels: Vec<(Span, String)>,
260 pub fn lo(self) -> BytePos {
264 pub fn with_lo(self, lo: BytePos) -> Span {
265 self.data().with_lo(lo)
268 pub fn hi(self) -> BytePos {
272 pub fn with_hi(self, hi: BytePos) -> Span {
273 self.data().with_hi(hi)
276 pub fn ctxt(self) -> SyntaxContext {
280 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
281 self.data().with_ctxt(ctxt)
284 /// Returns `true` if this is a dummy span with any hygienic context.
286 pub fn is_dummy(self) -> bool {
287 let span = self.data();
288 span.lo.0 == 0 && span.hi.0 == 0
291 /// Returns a new span representing an empty span at the beginning of this span
293 pub fn shrink_to_lo(self) -> Span {
294 let span = self.data();
295 span.with_hi(span.lo)
297 /// Returns a new span representing an empty span at the end of this span.
299 pub fn shrink_to_hi(self) -> Span {
300 let span = self.data();
301 span.with_lo(span.hi)
304 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
305 pub fn substitute_dummy(self, other: Span) -> Span {
306 if self.is_dummy() { other } else { self }
309 /// Returns `true` if `self` fully encloses `other`.
310 pub fn contains(self, other: Span) -> bool {
311 let span = self.data();
312 let other = other.data();
313 span.lo <= other.lo && other.hi <= span.hi
316 /// Returns `true` if `self` touches `other`.
317 pub fn overlaps(self, other: Span) -> bool {
318 let span = self.data();
319 let other = other.data();
320 span.lo < other.hi && other.lo < span.hi
323 /// Returns `true` if the spans are equal with regards to the source text.
325 /// Use this instead of `==` when either span could be generated code,
326 /// and you only care that they point to the same bytes of source text.
327 pub fn source_equal(&self, other: &Span) -> bool {
328 let span = self.data();
329 let other = other.data();
330 span.lo == other.lo && span.hi == other.hi
333 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
334 pub fn trim_start(self, other: Span) -> Option<Span> {
335 let span = self.data();
336 let other = other.data();
337 if span.hi > other.hi {
338 Some(span.with_lo(cmp::max(span.lo, other.hi)))
344 /// Returns the source span -- this is either the supplied span, or the span for
345 /// the macro callsite that expanded to it.
346 pub fn source_callsite(self) -> Span {
347 self.ctxt().outer_expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
350 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
352 pub fn parent(self) -> Option<Span> {
353 self.ctxt().outer_expn_info().map(|i| i.call_site)
356 /// Edition of the crate from which this span came.
357 pub fn edition(self) -> edition::Edition {
358 self.ctxt().outer_expn_info().map_or_else(|| {
359 Edition::from_session()
360 }, |einfo| einfo.edition)
364 pub fn rust_2015(&self) -> bool {
365 self.edition() == edition::Edition::Edition2015
369 pub fn rust_2018(&self) -> bool {
370 self.edition() >= edition::Edition::Edition2018
373 /// Returns the source callee.
375 /// Returns `None` if the supplied span has no expansion trace,
376 /// else returns the `ExpnInfo` for the macro definition
377 /// corresponding to the source callsite.
378 pub fn source_callee(self) -> Option<ExpnInfo> {
379 fn source_callee(info: ExpnInfo) -> ExpnInfo {
380 match info.call_site.ctxt().outer_expn_info() {
381 Some(info) => source_callee(info),
385 self.ctxt().outer_expn_info().map(source_callee)
388 /// Checks if a span is "internal" to a macro in which `#[unstable]`
389 /// items can be used (that is, a macro marked with
390 /// `#[allow_internal_unstable]`).
391 pub fn allows_unstable(&self, feature: Symbol) -> bool {
392 match self.ctxt().outer_expn_info() {
394 .allow_internal_unstable
395 .map_or(false, |features| features.iter().any(|&f|
396 f == feature || f == sym::allow_internal_unstable_backcompat_hack
402 /// Checks if this span arises from a compiler desugaring of kind `kind`.
403 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
404 match self.ctxt().outer_expn_info() {
405 Some(info) => match info.kind {
406 ExpnKind::Desugaring(k) => k == kind,
413 /// Returns the compiler desugaring that created this span, or `None`
414 /// if this span is not from a desugaring.
415 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
416 match self.ctxt().outer_expn_info() {
417 Some(info) => match info.kind {
418 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 match self.ctxt().outer_expn_info() {
430 Some(info) => info.allow_internal_unsafe,
435 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
436 let mut prev_span = DUMMY_SP;
437 let mut result = vec![];
438 while let Some(info) = self.ctxt().outer_expn_info() {
439 // Don't print recursive invocations.
440 if !info.call_site.source_equal(&prev_span) {
441 let (pre, post) = match info.kind {
442 ExpnKind::Root => break,
443 ExpnKind::Desugaring(..) => ("desugaring of ", ""),
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: info.call_site,
452 macro_decl_name: format!("{}{}{}", pre, info.kind.descr(), post),
453 def_site_span: info.def_site,
458 self = info.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::empty() {
473 } else if end_data.ctxt == SyntaxContext::empty() {
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::empty() { 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::empty() { 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::empty() { 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),
516 pub fn apply_mark(self, mark: ExpnId) -> Span {
517 let span = self.data();
518 span.with_ctxt(span.ctxt.apply_mark(mark))
522 pub fn remove_mark(&mut self) -> ExpnId {
523 let mut span = self.data();
524 let mark = span.ctxt.remove_mark();
525 *self = Span::new(span.lo, span.hi, span.ctxt);
530 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
531 let mut span = self.data();
532 let mark = span.ctxt.adjust(expn_id);
533 *self = Span::new(span.lo, span.hi, span.ctxt);
538 pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
539 let mut span = self.data();
540 let mark = span.ctxt.modernize_and_adjust(expn_id);
541 *self = Span::new(span.lo, span.hi, span.ctxt);
546 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
547 let mut span = self.data();
548 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
549 *self = Span::new(span.lo, span.hi, span.ctxt);
554 pub fn reverse_glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span)
555 -> Option<Option<ExpnId>> {
556 let mut span = self.data();
557 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
558 *self = Span::new(span.lo, span.hi, span.ctxt);
563 pub fn modern(self) -> Span {
564 let span = self.data();
565 span.with_ctxt(span.ctxt.modern())
569 pub fn modern_and_legacy(self) -> Span {
570 let span = self.data();
571 span.with_ctxt(span.ctxt.modern_and_legacy())
575 #[derive(Clone, Debug)]
576 pub struct SpanLabel {
577 /// The span we are going to include in the final snippet.
580 /// Is this a primary span? This is the "locus" of the message,
581 /// and is indicated with a `^^^^` underline, versus `----`.
582 pub is_primary: bool,
584 /// What label should we attach to this span (if any)?
585 pub label: Option<String>,
588 impl Default for Span {
589 fn default() -> Self {
594 impl rustc_serialize::UseSpecializedEncodable for Span {
595 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
596 let span = self.data();
597 s.emit_struct("Span", 2, |s| {
598 s.emit_struct_field("lo", 0, |s| {
602 s.emit_struct_field("hi", 1, |s| {
609 impl rustc_serialize::UseSpecializedDecodable for Span {
610 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
611 d.read_struct("Span", 2, |d| {
612 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
613 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
614 Ok(Span::new(lo, hi, NO_EXPANSION))
619 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620 f.debug_struct("Span")
621 .field("lo", &span.lo())
622 .field("hi", &span.hi())
623 .field("ctxt", &span.ctxt())
627 impl fmt::Debug for Span {
628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
633 impl fmt::Debug for SpanData {
634 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
635 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
641 pub fn new() -> MultiSpan {
643 primary_spans: vec![],
648 pub fn from_span(primary_span: Span) -> MultiSpan {
650 primary_spans: vec![primary_span],
655 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
662 pub fn push_span_label(&mut self, span: Span, label: String) {
663 self.span_labels.push((span, label));
666 /// Selects the first primary span (if any).
667 pub fn primary_span(&self) -> Option<Span> {
668 self.primary_spans.first().cloned()
671 /// Returns all primary spans.
672 pub fn primary_spans(&self) -> &[Span] {
676 /// Returns `true` if any of the primary spans are displayable.
677 pub fn has_primary_spans(&self) -> bool {
678 self.primary_spans.iter().any(|sp| !sp.is_dummy())
681 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
682 pub fn is_dummy(&self) -> bool {
683 let mut is_dummy = true;
684 for span in &self.primary_spans {
685 if !span.is_dummy() {
692 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
693 /// display well (like std macros). Returns whether replacements occurred.
694 pub fn replace(&mut self, before: Span, after: Span) -> bool {
695 let mut replacements_occurred = false;
696 for primary_span in &mut self.primary_spans {
697 if *primary_span == before {
698 *primary_span = after;
699 replacements_occurred = true;
702 for span_label in &mut self.span_labels {
703 if span_label.0 == before {
704 span_label.0 = after;
705 replacements_occurred = true;
708 replacements_occurred
711 /// Returns the strings to highlight. We always ensure that there
712 /// is an entry for each of the primary spans -- for each primary
713 /// span `P`, if there is at least one label with span `P`, we return
714 /// those labels (marked as primary). But otherwise we return
715 /// `SpanLabel` instances with empty labels.
716 pub fn span_labels(&self) -> Vec<SpanLabel> {
717 let is_primary = |span| self.primary_spans.contains(&span);
719 let mut span_labels = self.span_labels.iter().map(|&(span, ref label)|
722 is_primary: is_primary(span),
723 label: Some(label.clone())
725 ).collect::<Vec<_>>();
727 for &span in &self.primary_spans {
728 if !span_labels.iter().any(|sl| sl.span == span) {
729 span_labels.push(SpanLabel {
740 /// Returns `true` if any of the span labels is displayable.
741 pub fn has_span_labels(&self) -> bool {
742 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
746 impl From<Span> for MultiSpan {
747 fn from(span: Span) -> MultiSpan {
748 MultiSpan::from_span(span)
752 impl From<Vec<Span>> for MultiSpan {
753 fn from(spans: Vec<Span>) -> MultiSpan {
754 MultiSpan::from_spans(spans)
758 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
760 /// Identifies an offset of a multi-byte character in a `SourceFile`.
761 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
762 pub struct MultiByteChar {
763 /// The absolute offset of the character in the `SourceMap`.
765 /// The number of bytes, `>= 2`.
769 /// Identifies an offset of a non-narrow character in a `SourceFile`.
770 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
771 pub enum NonNarrowChar {
772 /// Represents a zero-width character.
774 /// Represents a wide (full-width) character.
776 /// Represents a tab character, represented visually with a width of 4 characters.
781 fn new(pos: BytePos, width: usize) -> Self {
783 0 => NonNarrowChar::ZeroWidth(pos),
784 2 => NonNarrowChar::Wide(pos),
785 4 => NonNarrowChar::Tab(pos),
786 _ => panic!("width {} given for non-narrow character", width),
790 /// Returns the absolute offset of the character in the `SourceMap`.
791 pub fn pos(&self) -> BytePos {
793 NonNarrowChar::ZeroWidth(p) |
794 NonNarrowChar::Wide(p) |
795 NonNarrowChar::Tab(p) => p,
799 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
800 pub fn width(&self) -> usize {
802 NonNarrowChar::ZeroWidth(_) => 0,
803 NonNarrowChar::Wide(_) => 2,
804 NonNarrowChar::Tab(_) => 4,
809 impl Add<BytePos> for NonNarrowChar {
812 fn add(self, rhs: BytePos) -> Self {
814 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
815 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
816 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
821 impl Sub<BytePos> for NonNarrowChar {
824 fn sub(self, rhs: BytePos) -> Self {
826 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
827 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
828 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
833 /// The state of the lazy external source loading mechanism of a `SourceFile`.
834 #[derive(PartialEq, Eq, Clone)]
835 pub enum ExternalSource {
836 /// The external source has been loaded already.
838 /// No attempt has been made to load the external source.
840 /// A failed attempt has been made to load the external source.
842 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
846 impl ExternalSource {
847 pub fn is_absent(&self) -> bool {
849 ExternalSource::Present(_) => false,
854 pub fn get_source(&self) -> Option<&str> {
856 ExternalSource::Present(ref src) => Some(src),
863 pub struct OffsetOverflowError;
865 /// A single source in the `SourceMap`.
867 pub struct SourceFile {
868 /// The name of the file that the source came from, source that doesn't
869 /// originate from files has names between angle brackets by convention
870 /// (e.g., `<anon>`).
872 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
873 pub name_was_remapped: bool,
874 /// The unmapped path of the file that the source came from.
875 /// Set to `None` if the `SourceFile` was imported from an external crate.
876 pub unmapped_path: Option<FileName>,
877 /// Indicates which crate this `SourceFile` was imported from.
878 pub crate_of_origin: u32,
879 /// The complete source code.
880 pub src: Option<Lrc<String>>,
881 /// The source code's hash.
883 /// The external source code (used for external crates, which will have a `None`
884 /// value as `self.src`.
885 pub external_src: Lock<ExternalSource>,
886 /// The start position of this source in the `SourceMap`.
887 pub start_pos: BytePos,
888 /// The end position of this source in the `SourceMap`.
889 pub end_pos: BytePos,
890 /// Locations of lines beginnings in the source code.
891 pub lines: Vec<BytePos>,
892 /// Locations of multi-byte characters in the source code.
893 pub multibyte_chars: Vec<MultiByteChar>,
894 /// Width of characters that are not narrow in the source code.
895 pub non_narrow_chars: Vec<NonNarrowChar>,
896 /// A hash of the filename, used for speeding up hashing in incremental compilation.
900 impl Encodable for SourceFile {
901 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
902 s.emit_struct("SourceFile", 8, |s| {
903 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
904 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
905 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
906 s.emit_struct_field("start_pos", 4, |s| self.start_pos.encode(s))?;
907 s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
908 s.emit_struct_field("lines", 6, |s| {
909 let lines = &self.lines[..];
911 s.emit_u32(lines.len() as u32)?;
913 if !lines.is_empty() {
914 // In order to preserve some space, we exploit the fact that
915 // the lines list is sorted and individual lines are
916 // probably not that long. Because of that we can store lines
917 // as a difference list, using as little space as possible
918 // for the differences.
919 let max_line_length = if lines.len() == 1 {
923 .map(|w| w[1] - w[0])
924 .map(|bp| bp.to_usize())
929 let bytes_per_diff: u8 = match max_line_length {
931 0x100 ..= 0xFFFF => 2,
935 // Encode the number of bytes used per diff.
936 bytes_per_diff.encode(s)?;
938 // Encode the first element.
941 let diff_iter = (&lines[..]).windows(2)
942 .map(|w| (w[1] - w[0]));
944 match bytes_per_diff {
945 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
946 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
947 4 => for diff in diff_iter { diff.0.encode(s)? },
954 s.emit_struct_field("multibyte_chars", 7, |s| {
955 self.multibyte_chars.encode(s)
957 s.emit_struct_field("non_narrow_chars", 8, |s| {
958 self.non_narrow_chars.encode(s)
960 s.emit_struct_field("name_hash", 9, |s| {
961 self.name_hash.encode(s)
967 impl Decodable for SourceFile {
968 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
970 d.read_struct("SourceFile", 8, |d| {
971 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
972 let name_was_remapped: bool =
973 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
975 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
976 let start_pos: BytePos =
977 d.read_struct_field("start_pos", 4, |d| Decodable::decode(d))?;
978 let end_pos: BytePos = d.read_struct_field("end_pos", 5, |d| Decodable::decode(d))?;
979 let lines: Vec<BytePos> = d.read_struct_field("lines", 6, |d| {
980 let num_lines: u32 = Decodable::decode(d)?;
981 let mut lines = Vec::with_capacity(num_lines as usize);
984 // Read the number of bytes used per diff.
985 let bytes_per_diff: u8 = Decodable::decode(d)?;
987 // Read the first element.
988 let mut line_start: BytePos = Decodable::decode(d)?;
989 lines.push(line_start);
991 for _ in 1..num_lines {
992 let diff = match bytes_per_diff {
993 1 => d.read_u8()? as u32,
994 2 => d.read_u16()? as u32,
999 line_start = line_start + BytePos(diff);
1001 lines.push(line_start);
1007 let multibyte_chars: Vec<MultiByteChar> =
1008 d.read_struct_field("multibyte_chars", 7, |d| Decodable::decode(d))?;
1009 let non_narrow_chars: Vec<NonNarrowChar> =
1010 d.read_struct_field("non_narrow_chars", 8, |d| Decodable::decode(d))?;
1011 let name_hash: u128 =
1012 d.read_struct_field("name_hash", 9, |d| Decodable::decode(d))?;
1016 unmapped_path: None,
1017 // `crate_of_origin` has to be set by the importer.
1018 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
1019 // That constant is not available here unfortunately :(
1020 crate_of_origin: std::u32::MAX - 1,
1025 external_src: Lock::new(ExternalSource::AbsentOk),
1035 impl fmt::Debug for SourceFile {
1036 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1037 write!(fmt, "SourceFile({})", self.name)
1042 pub fn new(name: FileName,
1043 name_was_remapped: bool,
1044 unmapped_path: FileName,
1046 start_pos: BytePos) -> Result<SourceFile, OffsetOverflowError> {
1047 remove_bom(&mut src);
1050 let mut hasher: StableHasher<u128> = StableHasher::new();
1051 hasher.write(src.as_bytes());
1055 let mut hasher: StableHasher<u128> = StableHasher::new();
1056 name.hash(&mut hasher);
1059 let end_pos = start_pos.to_usize() + src.len();
1060 if end_pos > u32::max_value() as usize {
1061 return Err(OffsetOverflowError);
1064 let (lines, multibyte_chars, non_narrow_chars) =
1065 analyze_source_file::analyze_source_file(&src[..], start_pos);
1070 unmapped_path: Some(unmapped_path),
1072 src: Some(Lrc::new(src)),
1074 external_src: Lock::new(ExternalSource::Unneeded),
1076 end_pos: Pos::from_usize(end_pos),
1084 /// Returns the `BytePos` of the beginning of the current line.
1085 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1086 let line_index = self.lookup_line(pos).unwrap();
1087 self.lines[line_index]
1090 /// Add externally loaded source.
1091 /// If the hash of the input doesn't match or no input is supplied via None,
1092 /// it is interpreted as an error and the corresponding enum variant is set.
1093 /// The return value signifies whether some kind of source is present.
1094 pub fn add_external_src<F>(&self, get_src: F) -> bool
1095 where F: FnOnce() -> Option<String>
1097 if *self.external_src.borrow() == ExternalSource::AbsentOk {
1098 let src = get_src();
1099 let mut external_src = self.external_src.borrow_mut();
1100 // Check that no-one else have provided the source while we were getting it
1101 if *external_src == ExternalSource::AbsentOk {
1102 if let Some(src) = src {
1103 let mut hasher: StableHasher<u128> = StableHasher::new();
1104 hasher.write(src.as_bytes());
1106 if hasher.finish() == self.src_hash {
1107 *external_src = ExternalSource::Present(src);
1111 *external_src = ExternalSource::AbsentErr;
1116 self.src.is_some() || external_src.get_source().is_some()
1119 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1123 /// Gets a line from the list of pre-computed line-beginnings.
1124 /// The line number here is 0-based.
1125 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1126 fn get_until_newline(src: &str, begin: usize) -> &str {
1127 // We can't use `lines.get(line_number+1)` because we might
1128 // be parsing when we call this function and thus the current
1129 // line is the last one we have line info for.
1130 let slice = &src[begin..];
1131 match slice.find('\n') {
1132 Some(e) => &slice[..e],
1138 let line = if let Some(line) = self.lines.get(line_number) {
1143 let begin: BytePos = *line - self.start_pos;
1147 if let Some(ref src) = self.src {
1148 Some(Cow::from(get_until_newline(src, begin)))
1149 } else if let Some(src) = self.external_src.borrow().get_source() {
1150 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1156 pub fn is_real_file(&self) -> bool {
1160 pub fn is_imported(&self) -> bool {
1164 pub fn byte_length(&self) -> u32 {
1165 self.end_pos.0 - self.start_pos.0
1167 pub fn count_lines(&self) -> usize {
1171 /// Finds the line containing the given position. The return value is the
1172 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1173 /// number. If the source_file is empty or the position is located before the
1174 /// first line, `None` is returned.
1175 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1176 if self.lines.len() == 0 {
1180 let line_index = lookup_line(&self.lines[..], pos);
1181 assert!(line_index < self.lines.len() as isize);
1182 if line_index >= 0 {
1183 Some(line_index as usize)
1189 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1190 if self.start_pos == self.end_pos {
1191 return (self.start_pos, self.end_pos);
1194 assert!(line_index < self.lines.len());
1195 if line_index == (self.lines.len() - 1) {
1196 (self.lines[line_index], self.end_pos)
1198 (self.lines[line_index], self.lines[line_index + 1])
1203 pub fn contains(&self, byte_pos: BytePos) -> bool {
1204 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1208 /// Removes UTF-8 BOM, if any.
1209 fn remove_bom(src: &mut String) {
1210 if src.starts_with("\u{feff}") {
1215 // _____________________________________________________________________________
1216 // Pos, BytePos, CharPos
1220 fn from_usize(n: usize) -> Self;
1221 fn to_usize(&self) -> usize;
1222 fn from_u32(n: u32) -> Self;
1223 fn to_u32(&self) -> u32;
1226 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1228 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1229 pub struct BytePos(pub u32);
1231 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1232 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1233 /// values to `CharPos` values as necessary.
1234 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1235 pub struct CharPos(pub usize);
1237 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1238 // have been unsuccessful.
1240 impl Pos for BytePos {
1242 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1245 fn to_usize(&self) -> usize { self.0 as usize }
1248 fn from_u32(n: u32) -> BytePos { BytePos(n) }
1251 fn to_u32(&self) -> u32 { self.0 }
1254 impl Add for BytePos {
1255 type Output = BytePos;
1258 fn add(self, rhs: BytePos) -> BytePos {
1259 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1263 impl Sub for BytePos {
1264 type Output = BytePos;
1267 fn sub(self, rhs: BytePos) -> BytePos {
1268 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1272 impl Encodable for BytePos {
1273 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1278 impl Decodable for BytePos {
1279 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1280 Ok(BytePos(d.read_u32()?))
1284 impl Pos for CharPos {
1286 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1289 fn to_usize(&self) -> usize { self.0 }
1292 fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1295 fn to_u32(&self) -> u32 { self.0 as u32}
1298 impl Add for CharPos {
1299 type Output = CharPos;
1302 fn add(self, rhs: CharPos) -> CharPos {
1303 CharPos(self.to_usize() + rhs.to_usize())
1307 impl Sub for CharPos {
1308 type Output = CharPos;
1311 fn sub(self, rhs: CharPos) -> CharPos {
1312 CharPos(self.to_usize() - rhs.to_usize())
1316 // _____________________________________________________________________________
1317 // Loc, SourceFileAndLine, SourceFileAndBytePos
1320 /// A source code location used for error reporting.
1321 #[derive(Debug, Clone)]
1323 /// Information about the original source.
1324 pub file: Lrc<SourceFile>,
1325 /// The (1-based) line number.
1327 /// The (0-based) column offset.
1329 /// The (0-based) column offset when displayed.
1330 pub col_display: usize,
1333 // Used to be structural records.
1335 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1337 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1339 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1340 pub struct LineInfo {
1341 /// Index of line, starting from 0.
1342 pub line_index: usize,
1344 /// Column in line where span begins, starting from 0.
1345 pub start_col: CharPos,
1347 /// Column in line where span ends, starting from 0, exclusive.
1348 pub end_col: CharPos,
1351 pub struct FileLines {
1352 pub file: Lrc<SourceFile>,
1353 pub lines: Vec<LineInfo>
1356 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1357 Cell::new(default_span_debug));
1360 pub struct MacroBacktrace {
1361 /// span where macro was applied to generate this code
1362 pub call_site: Span,
1364 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1365 pub macro_decl_name: String,
1367 /// span where macro was defined (possibly dummy)
1368 pub def_site_span: Span,
1371 // _____________________________________________________________________________
1372 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1375 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1377 #[derive(Clone, PartialEq, Eq, Debug)]
1378 pub enum SpanLinesError {
1379 IllFormedSpan(Span),
1380 DistinctSources(DistinctSources),
1383 #[derive(Clone, PartialEq, Eq, Debug)]
1384 pub enum SpanSnippetError {
1385 IllFormedSpan(Span),
1386 DistinctSources(DistinctSources),
1387 MalformedForSourcemap(MalformedSourceMapPositions),
1388 SourceNotAvailable { filename: FileName }
1391 #[derive(Clone, PartialEq, Eq, Debug)]
1392 pub struct DistinctSources {
1393 pub begin: (FileName, BytePos),
1394 pub end: (FileName, BytePos)
1397 #[derive(Clone, PartialEq, Eq, Debug)]
1398 pub struct MalformedSourceMapPositions {
1400 pub source_len: usize,
1401 pub begin_pos: BytePos,
1402 pub end_pos: BytePos
1405 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1406 pub struct InnerSpan {
1412 pub fn new(start: usize, end: usize) -> InnerSpan {
1413 InnerSpan { start, end }
1417 // Given a slice of line start positions and a position, returns the index of
1418 // the line the position is on. Returns -1 if the position is located before
1420 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1421 match lines.binary_search(&pos) {
1422 Ok(line) => line as isize,
1423 Err(line) => line as isize - 1
1429 use super::{lookup_line, BytePos};
1432 fn test_lookup_line() {
1434 let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1436 assert_eq!(lookup_line(lines, BytePos(0)), -1);
1437 assert_eq!(lookup_line(lines, BytePos(3)), 0);
1438 assert_eq!(lookup_line(lines, BytePos(4)), 0);
1440 assert_eq!(lookup_line(lines, BytePos(16)), 0);
1441 assert_eq!(lookup_line(lines, BytePos(17)), 1);
1442 assert_eq!(lookup_line(lines, BytePos(18)), 1);
1444 assert_eq!(lookup_line(lines, BytePos(28)), 2);
1445 assert_eq!(lookup_line(lines, BytePos(29)), 2);