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(non_exhaustive)]
13 #![feature(optin_builtin_traits)]
14 #![feature(rustc_attrs)]
15 #![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, ExpnInfo, ExpnKind, MacroKind, DesugaringKind};
27 pub use span_encoding::{Span, DUMMY_SP};
30 pub use symbol::{Symbol, sym};
32 mod analyze_source_file;
34 use rustc_data_structures::stable_hasher::StableHasher;
35 use rustc_data_structures::sync::{Lrc, Lock};
39 use std::cmp::{self, Ordering};
41 use std::hash::{Hasher, Hash};
42 use std::ops::{Add, Sub};
43 use std::path::PathBuf;
46 symbol_interner: Lock<symbol::Interner>,
47 span_interner: Lock<span_encoding::SpanInterner>,
48 hygiene_data: Lock<hygiene::HygieneData>,
53 pub fn new(edition: Edition) -> Globals {
55 symbol_interner: Lock::new(symbol::Interner::fresh()),
56 span_interner: Lock::new(span_encoding::SpanInterner::default()),
57 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 a new span representing an empty span at the beginning of this span
290 pub fn shrink_to_lo(self) -> Span {
291 let span = self.data();
292 span.with_hi(span.lo)
294 /// Returns a new span representing an empty span at the end of this span.
296 pub fn shrink_to_hi(self) -> Span {
297 let span = self.data();
298 span.with_lo(span.hi)
301 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
302 pub fn substitute_dummy(self, other: Span) -> Span {
303 if self.is_dummy() { other } else { self }
306 /// Returns `true` if `self` fully encloses `other`.
307 pub fn contains(self, other: Span) -> bool {
308 let span = self.data();
309 let other = other.data();
310 span.lo <= other.lo && other.hi <= span.hi
313 /// Returns `true` if `self` touches `other`.
314 pub fn overlaps(self, other: Span) -> bool {
315 let span = self.data();
316 let other = other.data();
317 span.lo < other.hi && other.lo < span.hi
320 /// Returns `true` if the spans are equal with regards to the source text.
322 /// Use this instead of `==` when either span could be generated code,
323 /// and you only care that they point to the same bytes of source text.
324 pub fn source_equal(&self, other: &Span) -> bool {
325 let span = self.data();
326 let other = other.data();
327 span.lo == other.lo && span.hi == other.hi
330 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
331 pub fn trim_start(self, other: Span) -> Option<Span> {
332 let span = self.data();
333 let other = other.data();
334 if span.hi > other.hi {
335 Some(span.with_lo(cmp::max(span.lo, other.hi)))
341 /// Returns the source span -- this is either the supplied span, or the span for
342 /// the macro callsite that expanded to it.
343 pub fn source_callsite(self) -> Span {
344 self.ctxt().outer_expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
347 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
349 pub fn parent(self) -> Option<Span> {
350 self.ctxt().outer_expn_info().map(|i| i.call_site)
353 /// Edition of the crate from which this span came.
354 pub fn edition(self) -> edition::Edition {
355 self.ctxt().outer_expn_info().map_or_else(|| {
356 Edition::from_session()
357 }, |einfo| einfo.edition)
361 pub fn rust_2015(&self) -> bool {
362 self.edition() == edition::Edition::Edition2015
366 pub fn rust_2018(&self) -> bool {
367 self.edition() >= edition::Edition::Edition2018
370 /// Returns the source callee.
372 /// Returns `None` if the supplied span has no expansion trace,
373 /// else returns the `ExpnInfo` for the macro definition
374 /// corresponding to the source callsite.
375 pub fn source_callee(self) -> Option<ExpnInfo> {
376 fn source_callee(info: ExpnInfo) -> ExpnInfo {
377 match info.call_site.ctxt().outer_expn_info() {
378 Some(info) => source_callee(info),
382 self.ctxt().outer_expn_info().map(source_callee)
385 /// Checks if a span is "internal" to a macro in which `#[unstable]`
386 /// items can be used (that is, a macro marked with
387 /// `#[allow_internal_unstable]`).
388 pub fn allows_unstable(&self, feature: Symbol) -> bool {
389 match self.ctxt().outer_expn_info() {
391 .allow_internal_unstable
392 .map_or(false, |features| features.iter().any(|&f|
393 f == feature || f == sym::allow_internal_unstable_backcompat_hack
399 /// Checks if this span arises from a compiler desugaring of kind `kind`.
400 pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
401 match self.ctxt().outer_expn_info() {
402 Some(info) => match info.kind {
403 ExpnKind::Desugaring(k) => k == kind,
410 /// Returns the compiler desugaring that created this span, or `None`
411 /// if this span is not from a desugaring.
412 pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
413 match self.ctxt().outer_expn_info() {
414 Some(info) => match info.kind {
415 ExpnKind::Desugaring(k) => Some(k),
422 /// Checks if a span is "internal" to a macro in which `unsafe`
423 /// can be used without triggering the `unsafe_code` lint
424 // (that is, a macro marked with `#[allow_internal_unsafe]`).
425 pub fn allows_unsafe(&self) -> bool {
426 match self.ctxt().outer_expn_info() {
427 Some(info) => info.allow_internal_unsafe,
432 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
433 let mut prev_span = DUMMY_SP;
434 let mut result = vec![];
435 while let Some(info) = self.ctxt().outer_expn_info() {
436 // Don't print recursive invocations.
437 if !info.call_site.source_equal(&prev_span) {
438 let (pre, post) = match info.kind {
439 ExpnKind::Root => break,
440 ExpnKind::Desugaring(..) => ("desugaring of ", ""),
441 ExpnKind::Macro(macro_kind, _) => match macro_kind {
442 MacroKind::Bang => ("", "!"),
443 MacroKind::Attr => ("#[", "]"),
444 MacroKind::Derive => ("#[derive(", ")]"),
447 result.push(MacroBacktrace {
448 call_site: info.call_site,
449 macro_decl_name: format!("{}{}{}", pre, info.kind.descr(), post),
450 def_site_span: info.def_site,
455 self = info.call_site;
460 /// Returns a `Span` that would enclose both `self` and `end`.
461 pub fn to(self, end: Span) -> Span {
462 let span_data = self.data();
463 let end_data = end.data();
464 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
465 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
466 // have an incomplete span than a completely nonsensical one.
467 if span_data.ctxt != end_data.ctxt {
468 if span_data.ctxt == SyntaxContext::empty() {
470 } else if end_data.ctxt == SyntaxContext::empty() {
473 // Both spans fall within a macro.
474 // FIXME(estebank): check if it is the *same* macro.
477 cmp::min(span_data.lo, end_data.lo),
478 cmp::max(span_data.hi, end_data.hi),
479 if span_data.ctxt == SyntaxContext::empty() { end_data.ctxt } else { span_data.ctxt },
483 /// Returns a `Span` between the end of `self` to the beginning of `end`.
484 pub fn between(self, end: Span) -> Span {
485 let span = self.data();
486 let end = end.data();
490 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
494 /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
495 pub fn until(self, end: Span) -> Span {
496 let span = self.data();
497 let end = end.data();
501 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
505 pub fn from_inner(self, inner: InnerSpan) -> Span {
506 let span = self.data();
507 Span::new(span.lo + BytePos::from_usize(inner.start),
508 span.lo + BytePos::from_usize(inner.end),
513 pub fn apply_mark(self, mark: ExpnId) -> Span {
514 let span = self.data();
515 span.with_ctxt(span.ctxt.apply_mark(mark))
519 pub fn remove_mark(&mut self) -> ExpnId {
520 let mut span = self.data();
521 let mark = span.ctxt.remove_mark();
522 *self = Span::new(span.lo, span.hi, span.ctxt);
527 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
528 let mut span = self.data();
529 let mark = span.ctxt.adjust(expn_id);
530 *self = Span::new(span.lo, span.hi, span.ctxt);
535 pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
536 let mut span = self.data();
537 let mark = span.ctxt.modernize_and_adjust(expn_id);
538 *self = Span::new(span.lo, span.hi, span.ctxt);
543 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
544 let mut span = self.data();
545 let mark = span.ctxt.glob_adjust(expn_id, glob_span);
546 *self = Span::new(span.lo, span.hi, span.ctxt);
551 pub fn reverse_glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span)
552 -> Option<Option<ExpnId>> {
553 let mut span = self.data();
554 let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
555 *self = Span::new(span.lo, span.hi, span.ctxt);
560 pub fn modern(self) -> Span {
561 let span = self.data();
562 span.with_ctxt(span.ctxt.modern())
566 pub fn modern_and_legacy(self) -> Span {
567 let span = self.data();
568 span.with_ctxt(span.ctxt.modern_and_legacy())
572 #[derive(Clone, Debug)]
573 pub struct SpanLabel {
574 /// The span we are going to include in the final snippet.
577 /// Is this a primary span? This is the "locus" of the message,
578 /// and is indicated with a `^^^^` underline, versus `----`.
579 pub is_primary: bool,
581 /// What label should we attach to this span (if any)?
582 pub label: Option<String>,
585 impl Default for Span {
586 fn default() -> Self {
591 impl rustc_serialize::UseSpecializedEncodable for Span {
592 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
593 let span = self.data();
594 s.emit_struct("Span", 2, |s| {
595 s.emit_struct_field("lo", 0, |s| {
599 s.emit_struct_field("hi", 1, |s| {
606 impl rustc_serialize::UseSpecializedDecodable for Span {
607 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
608 d.read_struct("Span", 2, |d| {
609 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
610 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
611 Ok(Span::new(lo, hi, NO_EXPANSION))
616 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
617 f.debug_struct("Span")
618 .field("lo", &span.lo())
619 .field("hi", &span.hi())
620 .field("ctxt", &span.ctxt())
624 impl fmt::Debug for Span {
625 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
626 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
630 impl fmt::Debug for SpanData {
631 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
632 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
638 pub fn new() -> MultiSpan {
640 primary_spans: vec![],
645 pub fn from_span(primary_span: Span) -> MultiSpan {
647 primary_spans: vec![primary_span],
652 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
659 pub fn push_span_label(&mut self, span: Span, label: String) {
660 self.span_labels.push((span, label));
663 /// Selects the first primary span (if any).
664 pub fn primary_span(&self) -> Option<Span> {
665 self.primary_spans.first().cloned()
668 /// Returns all primary spans.
669 pub fn primary_spans(&self) -> &[Span] {
673 /// Returns `true` if any of the primary spans are displayable.
674 pub fn has_primary_spans(&self) -> bool {
675 self.primary_spans.iter().any(|sp| !sp.is_dummy())
678 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
679 pub fn is_dummy(&self) -> bool {
680 let mut is_dummy = true;
681 for span in &self.primary_spans {
682 if !span.is_dummy() {
689 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
690 /// display well (like std macros). Returns whether replacements occurred.
691 pub fn replace(&mut self, before: Span, after: Span) -> bool {
692 let mut replacements_occurred = false;
693 for primary_span in &mut self.primary_spans {
694 if *primary_span == before {
695 *primary_span = after;
696 replacements_occurred = true;
699 for span_label in &mut self.span_labels {
700 if span_label.0 == before {
701 span_label.0 = after;
702 replacements_occurred = true;
705 replacements_occurred
708 /// Returns the strings to highlight. We always ensure that there
709 /// is an entry for each of the primary spans -- for each primary
710 /// span `P`, if there is at least one label with span `P`, we return
711 /// those labels (marked as primary). But otherwise we return
712 /// `SpanLabel` instances with empty labels.
713 pub fn span_labels(&self) -> Vec<SpanLabel> {
714 let is_primary = |span| self.primary_spans.contains(&span);
716 let mut span_labels = self.span_labels.iter().map(|&(span, ref label)|
719 is_primary: is_primary(span),
720 label: Some(label.clone())
722 ).collect::<Vec<_>>();
724 for &span in &self.primary_spans {
725 if !span_labels.iter().any(|sl| sl.span == span) {
726 span_labels.push(SpanLabel {
737 /// Returns `true` if any of the span labels is displayable.
738 pub fn has_span_labels(&self) -> bool {
739 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
743 impl From<Span> for MultiSpan {
744 fn from(span: Span) -> MultiSpan {
745 MultiSpan::from_span(span)
749 impl From<Vec<Span>> for MultiSpan {
750 fn from(spans: Vec<Span>) -> MultiSpan {
751 MultiSpan::from_spans(spans)
755 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
757 /// Identifies an offset of a multi-byte character in a `SourceFile`.
758 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
759 pub struct MultiByteChar {
760 /// The absolute offset of the character in the `SourceMap`.
762 /// The number of bytes, `>= 2`.
766 /// Identifies an offset of a non-narrow character in a `SourceFile`.
767 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
768 pub enum NonNarrowChar {
769 /// Represents a zero-width character.
771 /// Represents a wide (full-width) character.
773 /// Represents a tab character, represented visually with a width of 4 characters.
778 fn new(pos: BytePos, width: usize) -> Self {
780 0 => NonNarrowChar::ZeroWidth(pos),
781 2 => NonNarrowChar::Wide(pos),
782 4 => NonNarrowChar::Tab(pos),
783 _ => panic!("width {} given for non-narrow character", width),
787 /// Returns the absolute offset of the character in the `SourceMap`.
788 pub fn pos(&self) -> BytePos {
790 NonNarrowChar::ZeroWidth(p) |
791 NonNarrowChar::Wide(p) |
792 NonNarrowChar::Tab(p) => p,
796 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
797 pub fn width(&self) -> usize {
799 NonNarrowChar::ZeroWidth(_) => 0,
800 NonNarrowChar::Wide(_) => 2,
801 NonNarrowChar::Tab(_) => 4,
806 impl Add<BytePos> for NonNarrowChar {
809 fn add(self, rhs: BytePos) -> Self {
811 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
812 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
813 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
818 impl Sub<BytePos> for NonNarrowChar {
821 fn sub(self, rhs: BytePos) -> Self {
823 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
824 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
825 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
830 /// The state of the lazy external source loading mechanism of a `SourceFile`.
831 #[derive(PartialEq, Eq, Clone)]
832 pub enum ExternalSource {
833 /// The external source has been loaded already.
835 /// No attempt has been made to load the external source.
837 /// A failed attempt has been made to load the external source.
839 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
843 impl ExternalSource {
844 pub fn is_absent(&self) -> bool {
846 ExternalSource::Present(_) => false,
851 pub fn get_source(&self) -> Option<&str> {
853 ExternalSource::Present(ref src) => Some(src),
860 pub struct OffsetOverflowError;
862 /// A single source in the `SourceMap`.
864 pub struct SourceFile {
865 /// The name of the file that the source came from, source that doesn't
866 /// originate from files has names between angle brackets by convention
867 /// (e.g., `<anon>`).
869 /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
870 pub name_was_remapped: bool,
871 /// The unmapped path of the file that the source came from.
872 /// Set to `None` if the `SourceFile` was imported from an external crate.
873 pub unmapped_path: Option<FileName>,
874 /// Indicates which crate this `SourceFile` was imported from.
875 pub crate_of_origin: u32,
876 /// The complete source code.
877 pub src: Option<Lrc<String>>,
878 /// The source code's hash.
880 /// The external source code (used for external crates, which will have a `None`
881 /// value as `self.src`.
882 pub external_src: Lock<ExternalSource>,
883 /// The start position of this source in the `SourceMap`.
884 pub start_pos: BytePos,
885 /// The end position of this source in the `SourceMap`.
886 pub end_pos: BytePos,
887 /// Locations of lines beginnings in the source code.
888 pub lines: Vec<BytePos>,
889 /// Locations of multi-byte characters in the source code.
890 pub multibyte_chars: Vec<MultiByteChar>,
891 /// Width of characters that are not narrow in the source code.
892 pub non_narrow_chars: Vec<NonNarrowChar>,
893 /// A hash of the filename, used for speeding up hashing in incremental compilation.
897 impl Encodable for SourceFile {
898 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
899 s.emit_struct("SourceFile", 8, |s| {
900 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
901 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
902 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
903 s.emit_struct_field("start_pos", 4, |s| self.start_pos.encode(s))?;
904 s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
905 s.emit_struct_field("lines", 6, |s| {
906 let lines = &self.lines[..];
908 s.emit_u32(lines.len() as u32)?;
910 if !lines.is_empty() {
911 // In order to preserve some space, we exploit the fact that
912 // the lines list is sorted and individual lines are
913 // probably not that long. Because of that we can store lines
914 // as a difference list, using as little space as possible
915 // for the differences.
916 let max_line_length = if lines.len() == 1 {
920 .map(|w| w[1] - w[0])
921 .map(|bp| bp.to_usize())
926 let bytes_per_diff: u8 = match max_line_length {
928 0x100 ..= 0xFFFF => 2,
932 // Encode the number of bytes used per diff.
933 bytes_per_diff.encode(s)?;
935 // Encode the first element.
938 let diff_iter = (&lines[..]).windows(2)
939 .map(|w| (w[1] - w[0]));
941 match bytes_per_diff {
942 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
943 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
944 4 => for diff in diff_iter { diff.0.encode(s)? },
951 s.emit_struct_field("multibyte_chars", 7, |s| {
952 self.multibyte_chars.encode(s)
954 s.emit_struct_field("non_narrow_chars", 8, |s| {
955 self.non_narrow_chars.encode(s)
957 s.emit_struct_field("name_hash", 9, |s| {
958 self.name_hash.encode(s)
964 impl Decodable for SourceFile {
965 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
967 d.read_struct("SourceFile", 8, |d| {
968 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
969 let name_was_remapped: bool =
970 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
972 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
973 let start_pos: BytePos =
974 d.read_struct_field("start_pos", 4, |d| Decodable::decode(d))?;
975 let end_pos: BytePos = d.read_struct_field("end_pos", 5, |d| Decodable::decode(d))?;
976 let lines: Vec<BytePos> = d.read_struct_field("lines", 6, |d| {
977 let num_lines: u32 = Decodable::decode(d)?;
978 let mut lines = Vec::with_capacity(num_lines as usize);
981 // Read the number of bytes used per diff.
982 let bytes_per_diff: u8 = Decodable::decode(d)?;
984 // Read the first element.
985 let mut line_start: BytePos = Decodable::decode(d)?;
986 lines.push(line_start);
988 for _ in 1..num_lines {
989 let diff = match bytes_per_diff {
990 1 => d.read_u8()? as u32,
991 2 => d.read_u16()? as u32,
996 line_start = line_start + BytePos(diff);
998 lines.push(line_start);
1004 let multibyte_chars: Vec<MultiByteChar> =
1005 d.read_struct_field("multibyte_chars", 7, |d| Decodable::decode(d))?;
1006 let non_narrow_chars: Vec<NonNarrowChar> =
1007 d.read_struct_field("non_narrow_chars", 8, |d| Decodable::decode(d))?;
1008 let name_hash: u128 =
1009 d.read_struct_field("name_hash", 9, |d| Decodable::decode(d))?;
1013 unmapped_path: None,
1014 // `crate_of_origin` has to be set by the importer.
1015 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
1016 // That constant is not available here unfortunately :(
1017 crate_of_origin: std::u32::MAX - 1,
1022 external_src: Lock::new(ExternalSource::AbsentOk),
1032 impl fmt::Debug for SourceFile {
1033 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1034 write!(fmt, "SourceFile({})", self.name)
1039 pub fn new(name: FileName,
1040 name_was_remapped: bool,
1041 unmapped_path: FileName,
1043 start_pos: BytePos) -> Result<SourceFile, OffsetOverflowError> {
1044 remove_bom(&mut src);
1047 let mut hasher: StableHasher<u128> = StableHasher::new();
1048 hasher.write(src.as_bytes());
1052 let mut hasher: StableHasher<u128> = StableHasher::new();
1053 name.hash(&mut hasher);
1056 let end_pos = start_pos.to_usize() + src.len();
1057 if end_pos > u32::max_value() as usize {
1058 return Err(OffsetOverflowError);
1061 let (lines, multibyte_chars, non_narrow_chars) =
1062 analyze_source_file::analyze_source_file(&src[..], start_pos);
1067 unmapped_path: Some(unmapped_path),
1069 src: Some(Lrc::new(src)),
1071 external_src: Lock::new(ExternalSource::Unneeded),
1073 end_pos: Pos::from_usize(end_pos),
1081 /// Returns the `BytePos` of the beginning of the current line.
1082 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1083 let line_index = self.lookup_line(pos).unwrap();
1084 self.lines[line_index]
1087 /// Add externally loaded source.
1088 /// If the hash of the input doesn't match or no input is supplied via None,
1089 /// it is interpreted as an error and the corresponding enum variant is set.
1090 /// The return value signifies whether some kind of source is present.
1091 pub fn add_external_src<F>(&self, get_src: F) -> bool
1092 where F: FnOnce() -> Option<String>
1094 if *self.external_src.borrow() == ExternalSource::AbsentOk {
1095 let src = get_src();
1096 let mut external_src = self.external_src.borrow_mut();
1097 // Check that no-one else have provided the source while we were getting it
1098 if *external_src == ExternalSource::AbsentOk {
1099 if let Some(src) = src {
1100 let mut hasher: StableHasher<u128> = StableHasher::new();
1101 hasher.write(src.as_bytes());
1103 if hasher.finish() == self.src_hash {
1104 *external_src = ExternalSource::Present(src);
1108 *external_src = ExternalSource::AbsentErr;
1113 self.src.is_some() || external_src.get_source().is_some()
1116 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1120 /// Gets a line from the list of pre-computed line-beginnings.
1121 /// The line number here is 0-based.
1122 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1123 fn get_until_newline(src: &str, begin: usize) -> &str {
1124 // We can't use `lines.get(line_number+1)` because we might
1125 // be parsing when we call this function and thus the current
1126 // line is the last one we have line info for.
1127 let slice = &src[begin..];
1128 match slice.find('\n') {
1129 Some(e) => &slice[..e],
1135 let line = if let Some(line) = self.lines.get(line_number) {
1140 let begin: BytePos = *line - self.start_pos;
1144 if let Some(ref src) = self.src {
1145 Some(Cow::from(get_until_newline(src, begin)))
1146 } else if let Some(src) = self.external_src.borrow().get_source() {
1147 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1153 pub fn is_real_file(&self) -> bool {
1157 pub fn is_imported(&self) -> bool {
1161 pub fn byte_length(&self) -> u32 {
1162 self.end_pos.0 - self.start_pos.0
1164 pub fn count_lines(&self) -> usize {
1168 /// Finds the line containing the given position. The return value is the
1169 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1170 /// number. If the source_file is empty or the position is located before the
1171 /// first line, `None` is returned.
1172 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1173 if self.lines.len() == 0 {
1177 let line_index = lookup_line(&self.lines[..], pos);
1178 assert!(line_index < self.lines.len() as isize);
1179 if line_index >= 0 {
1180 Some(line_index as usize)
1186 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1187 if self.start_pos == self.end_pos {
1188 return (self.start_pos, self.end_pos);
1191 assert!(line_index < self.lines.len());
1192 if line_index == (self.lines.len() - 1) {
1193 (self.lines[line_index], self.end_pos)
1195 (self.lines[line_index], self.lines[line_index + 1])
1200 pub fn contains(&self, byte_pos: BytePos) -> bool {
1201 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1205 /// Removes UTF-8 BOM, if any.
1206 fn remove_bom(src: &mut String) {
1207 if src.starts_with("\u{feff}") {
1212 // _____________________________________________________________________________
1213 // Pos, BytePos, CharPos
1217 fn from_usize(n: usize) -> Self;
1218 fn to_usize(&self) -> usize;
1219 fn from_u32(n: u32) -> Self;
1220 fn to_u32(&self) -> u32;
1223 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1225 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1226 pub struct BytePos(pub u32);
1228 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1229 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1230 /// values to `CharPos` values as necessary.
1231 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1232 pub struct CharPos(pub usize);
1234 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1235 // have been unsuccessful.
1237 impl Pos for BytePos {
1239 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1242 fn to_usize(&self) -> usize { self.0 as usize }
1245 fn from_u32(n: u32) -> BytePos { BytePos(n) }
1248 fn to_u32(&self) -> u32 { self.0 }
1251 impl Add for BytePos {
1252 type Output = BytePos;
1255 fn add(self, rhs: BytePos) -> BytePos {
1256 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1260 impl Sub for BytePos {
1261 type Output = BytePos;
1264 fn sub(self, rhs: BytePos) -> BytePos {
1265 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1269 impl Encodable for BytePos {
1270 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1275 impl Decodable for BytePos {
1276 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1277 Ok(BytePos(d.read_u32()?))
1281 impl Pos for CharPos {
1283 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1286 fn to_usize(&self) -> usize { self.0 }
1289 fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1292 fn to_u32(&self) -> u32 { self.0 as u32}
1295 impl Add for CharPos {
1296 type Output = CharPos;
1299 fn add(self, rhs: CharPos) -> CharPos {
1300 CharPos(self.to_usize() + rhs.to_usize())
1304 impl Sub for CharPos {
1305 type Output = CharPos;
1308 fn sub(self, rhs: CharPos) -> CharPos {
1309 CharPos(self.to_usize() - rhs.to_usize())
1313 // _____________________________________________________________________________
1314 // Loc, SourceFileAndLine, SourceFileAndBytePos
1317 /// A source code location used for error reporting.
1318 #[derive(Debug, Clone)]
1320 /// Information about the original source.
1321 pub file: Lrc<SourceFile>,
1322 /// The (1-based) line number.
1324 /// The (0-based) column offset.
1326 /// The (0-based) column offset when displayed.
1327 pub col_display: usize,
1330 // Used to be structural records.
1332 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1334 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1336 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1337 pub struct LineInfo {
1338 /// Index of line, starting from 0.
1339 pub line_index: usize,
1341 /// Column in line where span begins, starting from 0.
1342 pub start_col: CharPos,
1344 /// Column in line where span ends, starting from 0, exclusive.
1345 pub end_col: CharPos,
1348 pub struct FileLines {
1349 pub file: Lrc<SourceFile>,
1350 pub lines: Vec<LineInfo>
1353 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1354 Cell::new(default_span_debug));
1357 pub struct MacroBacktrace {
1358 /// span where macro was applied to generate this code
1359 pub call_site: Span,
1361 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1362 pub macro_decl_name: String,
1364 /// span where macro was defined (possibly dummy)
1365 pub def_site_span: Span,
1368 // _____________________________________________________________________________
1369 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1372 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1374 #[derive(Clone, PartialEq, Eq, Debug)]
1375 pub enum SpanLinesError {
1376 IllFormedSpan(Span),
1377 DistinctSources(DistinctSources),
1380 #[derive(Clone, PartialEq, Eq, Debug)]
1381 pub enum SpanSnippetError {
1382 IllFormedSpan(Span),
1383 DistinctSources(DistinctSources),
1384 MalformedForSourcemap(MalformedSourceMapPositions),
1385 SourceNotAvailable { filename: FileName }
1388 #[derive(Clone, PartialEq, Eq, Debug)]
1389 pub struct DistinctSources {
1390 pub begin: (FileName, BytePos),
1391 pub end: (FileName, BytePos)
1394 #[derive(Clone, PartialEq, Eq, Debug)]
1395 pub struct MalformedSourceMapPositions {
1397 pub source_len: usize,
1398 pub begin_pos: BytePos,
1399 pub end_pos: BytePos
1402 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1403 pub struct InnerSpan {
1409 pub fn new(start: usize, end: usize) -> InnerSpan {
1410 InnerSpan { start, end }
1414 // Given a slice of line start positions and a position, returns the index of
1415 // the line the position is on. Returns -1 if the position is located before
1417 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1418 match lines.binary_search(&pos) {
1419 Ok(line) => line as isize,
1420 Err(line) => line as isize - 1
1426 use super::{lookup_line, BytePos};
1429 fn test_lookup_line() {
1431 let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1433 assert_eq!(lookup_line(lines, BytePos(0)), -1);
1434 assert_eq!(lookup_line(lines, BytePos(3)), 0);
1435 assert_eq!(lookup_line(lines, BytePos(4)), 0);
1437 assert_eq!(lookup_line(lines, BytePos(16)), 0);
1438 assert_eq!(lookup_line(lines, BytePos(17)), 1);
1439 assert_eq!(lookup_line(lines, BytePos(18)), 1);
1441 assert_eq!(lookup_line(lines, BytePos(28)), 2);
1442 assert_eq!(lookup_line(lines, BytePos(29)), 2);