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)]
12 #![feature(crate_visibility_modifier)]
13 #![feature(custom_attribute)]
15 #![feature(non_exhaustive)]
16 #![feature(optin_builtin_traits)]
17 #![feature(rustc_attrs)]
18 #![feature(specialization)]
19 #![feature(step_trait)]
20 #![cfg_attr(not(stage0), feature(stdsimd))]
22 use serialize::{Encodable, Decodable, Encoder, Decoder};
24 #[allow(unused_extern_crates)]
25 extern crate serialize as rustc_serialize; // used by deriving
29 pub use hygiene::{Mark, SyntaxContext, ExpnInfo, ExpnFormat, CompilerDesugaringKind};
32 pub use span_encoding::{Span, DUMMY_SP};
36 mod analyze_source_file;
38 use rustc_data_structures::stable_hasher::StableHasher;
39 use rustc_data_structures::sync::{Lrc, Lock};
43 use std::cmp::{self, Ordering};
45 use std::hash::{Hasher, Hash};
46 use std::ops::{Add, Sub};
47 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() -> 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()),
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 a new span representing an empty span at the beginning of this span
292 pub fn shrink_to_lo(self) -> Span {
293 let span = self.data();
294 span.with_hi(span.lo)
296 /// Returns a new span representing an empty span at the end of this span.
298 pub fn shrink_to_hi(self) -> Span {
299 let span = self.data();
300 span.with_lo(span.hi)
303 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
304 pub fn substitute_dummy(self, other: Span) -> Span {
305 if self.is_dummy() { other } else { self }
308 /// Return `true` if `self` fully encloses `other`.
309 pub fn contains(self, other: Span) -> bool {
310 let span = self.data();
311 let other = other.data();
312 span.lo <= other.lo && other.hi <= span.hi
315 /// Return `true` if `self` touches `other`.
316 pub fn overlaps(self, other: Span) -> bool {
317 let span = self.data();
318 let other = other.data();
319 span.lo < other.hi && other.lo < span.hi
322 /// Return true if the spans are equal with regards to the source text.
324 /// Use this instead of `==` when either span could be generated code,
325 /// and you only care that they point to the same bytes of source text.
326 pub fn source_equal(&self, other: &Span) -> bool {
327 let span = self.data();
328 let other = other.data();
329 span.lo == other.lo && span.hi == other.hi
332 /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
333 pub fn trim_start(self, other: Span) -> Option<Span> {
334 let span = self.data();
335 let other = other.data();
336 if span.hi > other.hi {
337 Some(span.with_lo(cmp::max(span.lo, other.hi)))
343 /// Return the source span -- this is either the supplied span, or the span for
344 /// the macro callsite that expanded to it.
345 pub fn source_callsite(self) -> Span {
346 self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
349 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
351 pub fn parent(self) -> Option<Span> {
352 self.ctxt().outer().expn_info().map(|i| i.call_site)
355 /// Edition of the crate from which this span came.
356 pub fn edition(self) -> edition::Edition {
357 self.ctxt().outer().expn_info().map_or_else(|| hygiene::default_edition(),
358 |einfo| einfo.edition)
362 pub fn rust_2015(&self) -> bool {
363 self.edition() == edition::Edition::Edition2015
367 pub fn rust_2018(&self) -> bool {
368 self.edition() >= edition::Edition::Edition2018
371 /// Return the source callee.
373 /// Returns `None` if the supplied span has no expansion trace,
374 /// else returns the `ExpnInfo` for the macro definition
375 /// corresponding to the source callsite.
376 pub fn source_callee(self) -> Option<ExpnInfo> {
377 fn source_callee(info: ExpnInfo) -> ExpnInfo {
378 match info.call_site.ctxt().outer().expn_info() {
379 Some(info) => source_callee(info),
383 self.ctxt().outer().expn_info().map(source_callee)
386 /// Check if a span is "internal" to a macro in which `#[unstable]`
387 /// items can be used (that is, a macro marked with
388 /// `#[allow_internal_unstable]`).
389 pub fn allows_unstable(&self) -> bool {
390 match self.ctxt().outer().expn_info() {
391 Some(info) => info.allow_internal_unstable,
396 /// Check if this span arises from a compiler desugaring of kind `kind`.
397 pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
398 match self.ctxt().outer().expn_info() {
399 Some(info) => match info.format {
400 ExpnFormat::CompilerDesugaring(k) => k == kind,
407 /// Return the compiler desugaring that created this span, or `None`
408 /// if this span is not from a desugaring.
409 pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
410 match self.ctxt().outer().expn_info() {
411 Some(info) => match info.format {
412 ExpnFormat::CompilerDesugaring(k) => Some(k),
419 /// Check if a span is "internal" to a macro in which `unsafe`
420 /// can be used without triggering the `unsafe_code` lint
421 // (that is, a macro marked with `#[allow_internal_unsafe]`).
422 pub fn allows_unsafe(&self) -> bool {
423 match self.ctxt().outer().expn_info() {
424 Some(info) => info.allow_internal_unsafe,
429 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
430 let mut prev_span = DUMMY_SP;
431 let mut result = vec![];
432 while let Some(info) = self.ctxt().outer().expn_info() {
433 // Don't print recursive invocations.
434 if !info.call_site.source_equal(&prev_span) {
435 let (pre, post) = match info.format {
436 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
437 ExpnFormat::MacroBang(..) => ("", "!"),
438 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
440 result.push(MacroBacktrace {
441 call_site: info.call_site,
442 macro_decl_name: format!("{}{}{}", pre, info.format.name(), post),
443 def_site_span: info.def_site,
448 self = info.call_site;
453 /// Return a `Span` that would enclose both `self` and `end`.
454 pub fn to(self, end: Span) -> Span {
455 let span_data = self.data();
456 let end_data = end.data();
457 // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
458 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
459 // have an incomplete span than a completely nonsensical one.
460 if span_data.ctxt != end_data.ctxt {
461 if span_data.ctxt == SyntaxContext::empty() {
463 } else if end_data.ctxt == SyntaxContext::empty() {
466 // Both spans fall within a macro.
467 // FIXME(estebank): check if it is the *same* macro.
470 cmp::min(span_data.lo, end_data.lo),
471 cmp::max(span_data.hi, end_data.hi),
472 if span_data.ctxt == SyntaxContext::empty() { end_data.ctxt } else { span_data.ctxt },
476 /// Return a `Span` between the end of `self` to the beginning of `end`.
477 pub fn between(self, end: Span) -> Span {
478 let span = self.data();
479 let end = end.data();
483 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
487 /// Return a `Span` between the beginning of `self` to the beginning of `end`.
488 pub fn until(self, end: Span) -> Span {
489 let span = self.data();
490 let end = end.data();
494 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
498 pub fn from_inner_byte_pos(self, start: usize, end: usize) -> Span {
499 let span = self.data();
500 Span::new(span.lo + BytePos::from_usize(start),
501 span.lo + BytePos::from_usize(end),
506 pub fn apply_mark(self, mark: Mark) -> Span {
507 let span = self.data();
508 span.with_ctxt(span.ctxt.apply_mark(mark))
512 pub fn remove_mark(&mut self) -> Mark {
513 let mut span = self.data();
514 let mark = span.ctxt.remove_mark();
515 *self = Span::new(span.lo, span.hi, span.ctxt);
520 pub fn adjust(&mut self, expansion: Mark) -> Option<Mark> {
521 let mut span = self.data();
522 let mark = span.ctxt.adjust(expansion);
523 *self = Span::new(span.lo, span.hi, span.ctxt);
528 pub fn glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
529 -> Option<Option<Mark>> {
530 let mut span = self.data();
531 let mark = span.ctxt.glob_adjust(expansion, glob_ctxt);
532 *self = Span::new(span.lo, span.hi, span.ctxt);
537 pub fn reverse_glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
538 -> Option<Option<Mark>> {
539 let mut span = self.data();
540 let mark = span.ctxt.reverse_glob_adjust(expansion, glob_ctxt);
541 *self = Span::new(span.lo, span.hi, span.ctxt);
546 pub fn modern(self) -> Span {
547 let span = self.data();
548 span.with_ctxt(span.ctxt.modern())
552 pub fn modern_and_legacy(self) -> Span {
553 let span = self.data();
554 span.with_ctxt(span.ctxt.modern_and_legacy())
558 #[derive(Clone, Debug)]
559 pub struct SpanLabel {
560 /// The span we are going to include in the final snippet.
563 /// Is this a primary span? This is the "locus" of the message,
564 /// and is indicated with a `^^^^` underline, versus `----`.
565 pub is_primary: bool,
567 /// What label should we attach to this span (if any)?
568 pub label: Option<String>,
571 impl Default for Span {
572 fn default() -> Self {
577 impl serialize::UseSpecializedEncodable for Span {
578 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
579 let span = self.data();
580 s.emit_struct("Span", 2, |s| {
581 s.emit_struct_field("lo", 0, |s| {
585 s.emit_struct_field("hi", 1, |s| {
592 impl serialize::UseSpecializedDecodable for Span {
593 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
594 d.read_struct("Span", 2, |d| {
595 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
596 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
597 Ok(Span::new(lo, hi, NO_EXPANSION))
602 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
603 f.debug_struct("Span")
604 .field("lo", &span.lo())
605 .field("hi", &span.hi())
606 .field("ctxt", &span.ctxt())
610 impl fmt::Debug for Span {
611 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
612 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
616 impl fmt::Debug for SpanData {
617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
624 pub fn new() -> MultiSpan {
626 primary_spans: vec![],
631 pub fn from_span(primary_span: Span) -> MultiSpan {
633 primary_spans: vec![primary_span],
638 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
645 pub fn push_span_label(&mut self, span: Span, label: String) {
646 self.span_labels.push((span, label));
649 /// Selects the first primary span (if any).
650 pub fn primary_span(&self) -> Option<Span> {
651 self.primary_spans.first().cloned()
654 /// Returns all primary spans.
655 pub fn primary_spans(&self) -> &[Span] {
659 /// Returns whether any of the primary spans is displayable.
660 pub fn has_primary_spans(&self) -> bool {
661 self.primary_spans.iter().any(|sp| !sp.is_dummy())
664 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
665 pub fn is_dummy(&self) -> bool {
666 let mut is_dummy = true;
667 for span in &self.primary_spans {
668 if !span.is_dummy() {
675 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
676 /// display well (like std macros). Returns true if replacements occurred.
677 pub fn replace(&mut self, before: Span, after: Span) -> bool {
678 let mut replacements_occurred = false;
679 for primary_span in &mut self.primary_spans {
680 if *primary_span == before {
681 *primary_span = after;
682 replacements_occurred = true;
685 for span_label in &mut self.span_labels {
686 if span_label.0 == before {
687 span_label.0 = after;
688 replacements_occurred = true;
691 replacements_occurred
694 /// Returns the strings to highlight. We always ensure that there
695 /// is an entry for each of the primary spans -- for each primary
696 /// span `P`, if there is at least one label with span `P`, we return
697 /// those labels (marked as primary). But otherwise we return
698 /// `SpanLabel` instances with empty labels.
699 pub fn span_labels(&self) -> Vec<SpanLabel> {
700 let is_primary = |span| self.primary_spans.contains(&span);
702 let mut span_labels = self.span_labels.iter().map(|&(span, ref label)|
705 is_primary: is_primary(span),
706 label: Some(label.clone())
708 ).collect::<Vec<_>>();
710 for &span in &self.primary_spans {
711 if !span_labels.iter().any(|sl| sl.span == span) {
712 span_labels.push(SpanLabel {
723 /// Returns whether any of the span labels is displayable.
724 pub fn has_span_labels(&self) -> bool {
725 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
729 impl From<Span> for MultiSpan {
730 fn from(span: Span) -> MultiSpan {
731 MultiSpan::from_span(span)
735 impl From<Vec<Span>> for MultiSpan {
736 fn from(spans: Vec<Span>) -> MultiSpan {
737 MultiSpan::from_spans(spans)
741 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
743 /// Identifies an offset of a multi-byte character in a `SourceFile`.
744 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
745 pub struct MultiByteChar {
746 /// The absolute offset of the character in the `SourceMap`.
748 /// The number of bytes, `>= 2`.
752 /// Identifies an offset of a non-narrow character in a `SourceFile`.
753 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
754 pub enum NonNarrowChar {
755 /// Represents a zero-width character.
757 /// Represents a wide (full-width) character.
759 /// Represents a tab character, represented visually with a width of 4 characters.
764 fn new(pos: BytePos, width: usize) -> Self {
766 0 => NonNarrowChar::ZeroWidth(pos),
767 2 => NonNarrowChar::Wide(pos),
768 4 => NonNarrowChar::Tab(pos),
769 _ => panic!("width {} given for non-narrow character", width),
773 /// Returns the absolute offset of the character in the `SourceMap`.
774 pub fn pos(&self) -> BytePos {
776 NonNarrowChar::ZeroWidth(p) |
777 NonNarrowChar::Wide(p) |
778 NonNarrowChar::Tab(p) => p,
782 /// Returns the width of the character, 0 (zero-width) or 2 (wide).
783 pub fn width(&self) -> usize {
785 NonNarrowChar::ZeroWidth(_) => 0,
786 NonNarrowChar::Wide(_) => 2,
787 NonNarrowChar::Tab(_) => 4,
792 impl Add<BytePos> for NonNarrowChar {
795 fn add(self, rhs: BytePos) -> Self {
797 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
798 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
799 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
804 impl Sub<BytePos> for NonNarrowChar {
807 fn sub(self, rhs: BytePos) -> Self {
809 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
810 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
811 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
816 /// The state of the lazy external source loading mechanism of a `SourceFile`.
817 #[derive(PartialEq, Eq, Clone)]
818 pub enum ExternalSource {
819 /// The external source has been loaded already.
821 /// No attempt has been made to load the external source.
823 /// A failed attempt has been made to load the external source.
825 /// No external source has to be loaded, since the `SourceFile` represents a local crate.
829 impl ExternalSource {
830 pub fn is_absent(&self) -> bool {
832 ExternalSource::Present(_) => false,
837 pub fn get_source(&self) -> Option<&str> {
839 ExternalSource::Present(ref src) => Some(src),
845 /// A single source in the `SourceMap`.
847 pub struct SourceFile {
848 /// The name of the file that the source came from, source that doesn't
849 /// originate from files has names between angle brackets by convention
850 /// (e.g., `<anon>`).
852 /// True if the `name` field above has been modified by `--remap-path-prefix`.
853 pub name_was_remapped: bool,
854 /// The unmapped path of the file that the source came from.
855 /// Set to `None` if the `SourceFile` was imported from an external crate.
856 pub unmapped_path: Option<FileName>,
857 /// Indicates which crate this `SourceFile` was imported from.
858 pub crate_of_origin: u32,
859 /// The complete source code.
860 pub src: Option<Lrc<String>>,
861 /// The source code's hash.
863 /// The external source code (used for external crates, which will have a `None`
864 /// value as `self.src`.
865 pub external_src: Lock<ExternalSource>,
866 /// The start position of this source in the `SourceMap`.
867 pub start_pos: BytePos,
868 /// The end position of this source in the `SourceMap`.
869 pub end_pos: BytePos,
870 /// Locations of lines beginnings in the source code.
871 pub lines: Vec<BytePos>,
872 /// Locations of multi-byte characters in the source code.
873 pub multibyte_chars: Vec<MultiByteChar>,
874 /// Width of characters that are not narrow in the source code.
875 pub non_narrow_chars: Vec<NonNarrowChar>,
876 /// A hash of the filename, used for speeding up hashing in incremental compilation.
880 impl Encodable for SourceFile {
881 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
882 s.emit_struct("SourceFile", 8, |s| {
883 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
884 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
885 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
886 s.emit_struct_field("start_pos", 4, |s| self.start_pos.encode(s))?;
887 s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
888 s.emit_struct_field("lines", 6, |s| {
889 let lines = &self.lines[..];
891 s.emit_u32(lines.len() as u32)?;
893 if !lines.is_empty() {
894 // In order to preserve some space, we exploit the fact that
895 // the lines list is sorted and individual lines are
896 // probably not that long. Because of that we can store lines
897 // as a difference list, using as little space as possible
898 // for the differences.
899 let max_line_length = if lines.len() == 1 {
903 .map(|w| w[1] - w[0])
904 .map(|bp| bp.to_usize())
909 let bytes_per_diff: u8 = match max_line_length {
911 0x100 ..= 0xFFFF => 2,
915 // Encode the number of bytes used per diff.
916 bytes_per_diff.encode(s)?;
918 // Encode the first element.
921 let diff_iter = (&lines[..]).windows(2)
922 .map(|w| (w[1] - w[0]));
924 match bytes_per_diff {
925 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
926 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
927 4 => for diff in diff_iter { diff.0.encode(s)? },
934 s.emit_struct_field("multibyte_chars", 7, |s| {
935 self.multibyte_chars.encode(s)
937 s.emit_struct_field("non_narrow_chars", 8, |s| {
938 self.non_narrow_chars.encode(s)
940 s.emit_struct_field("name_hash", 9, |s| {
941 self.name_hash.encode(s)
947 impl Decodable for SourceFile {
948 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
950 d.read_struct("SourceFile", 8, |d| {
951 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
952 let name_was_remapped: bool =
953 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
955 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
956 let start_pos: BytePos =
957 d.read_struct_field("start_pos", 4, |d| Decodable::decode(d))?;
958 let end_pos: BytePos = d.read_struct_field("end_pos", 5, |d| Decodable::decode(d))?;
959 let lines: Vec<BytePos> = d.read_struct_field("lines", 6, |d| {
960 let num_lines: u32 = Decodable::decode(d)?;
961 let mut lines = Vec::with_capacity(num_lines as usize);
964 // Read the number of bytes used per diff.
965 let bytes_per_diff: u8 = Decodable::decode(d)?;
967 // Read the first element.
968 let mut line_start: BytePos = Decodable::decode(d)?;
969 lines.push(line_start);
971 for _ in 1..num_lines {
972 let diff = match bytes_per_diff {
973 1 => d.read_u8()? as u32,
974 2 => d.read_u16()? as u32,
979 line_start = line_start + BytePos(diff);
981 lines.push(line_start);
987 let multibyte_chars: Vec<MultiByteChar> =
988 d.read_struct_field("multibyte_chars", 7, |d| Decodable::decode(d))?;
989 let non_narrow_chars: Vec<NonNarrowChar> =
990 d.read_struct_field("non_narrow_chars", 8, |d| Decodable::decode(d))?;
991 let name_hash: u128 =
992 d.read_struct_field("name_hash", 9, |d| Decodable::decode(d))?;
997 // `crate_of_origin` has to be set by the importer.
998 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
999 // That constant is not available here unfortunately :(
1000 crate_of_origin: std::u32::MAX - 1,
1005 external_src: Lock::new(ExternalSource::AbsentOk),
1015 impl fmt::Debug for SourceFile {
1016 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1017 write!(fmt, "SourceFile({})", self.name)
1022 pub fn new(name: FileName,
1023 name_was_remapped: bool,
1024 unmapped_path: FileName,
1026 start_pos: BytePos) -> SourceFile {
1027 remove_bom(&mut src);
1030 let mut hasher: StableHasher<u128> = StableHasher::new();
1031 hasher.write(src.as_bytes());
1035 let mut hasher: StableHasher<u128> = StableHasher::new();
1036 name.hash(&mut hasher);
1039 let end_pos = start_pos.to_usize() + src.len();
1041 let (lines, multibyte_chars, non_narrow_chars) =
1042 analyze_source_file::analyze_source_file(&src[..], start_pos);
1047 unmapped_path: Some(unmapped_path),
1049 src: Some(Lrc::new(src)),
1051 external_src: Lock::new(ExternalSource::Unneeded),
1053 end_pos: Pos::from_usize(end_pos),
1061 /// Return the `BytePos` of the beginning of the current line.
1062 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1063 let line_index = self.lookup_line(pos).unwrap();
1064 self.lines[line_index]
1067 /// Add externally loaded source.
1068 /// If the hash of the input doesn't match or no input is supplied via None,
1069 /// it is interpreted as an error and the corresponding enum variant is set.
1070 /// The return value signifies whether some kind of source is present.
1071 pub fn add_external_src<F>(&self, get_src: F) -> bool
1072 where F: FnOnce() -> Option<String>
1074 if *self.external_src.borrow() == ExternalSource::AbsentOk {
1075 let src = get_src();
1076 let mut external_src = self.external_src.borrow_mut();
1077 // Check that no-one else have provided the source while we were getting it
1078 if *external_src == ExternalSource::AbsentOk {
1079 if let Some(src) = src {
1080 let mut hasher: StableHasher<u128> = StableHasher::new();
1081 hasher.write(src.as_bytes());
1083 if hasher.finish() == self.src_hash {
1084 *external_src = ExternalSource::Present(src);
1088 *external_src = ExternalSource::AbsentErr;
1093 self.src.is_some() || external_src.get_source().is_some()
1096 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1100 /// Get a line from the list of pre-computed line-beginnings.
1101 /// The line number here is 0-based.
1102 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1103 fn get_until_newline(src: &str, begin: usize) -> &str {
1104 // We can't use `lines.get(line_number+1)` because we might
1105 // be parsing when we call this function and thus the current
1106 // line is the last one we have line info for.
1107 let slice = &src[begin..];
1108 match slice.find('\n') {
1109 Some(e) => &slice[..e],
1115 let line = if let Some(line) = self.lines.get(line_number) {
1120 let begin: BytePos = *line - self.start_pos;
1124 if let Some(ref src) = self.src {
1125 Some(Cow::from(get_until_newline(src, begin)))
1126 } else if let Some(src) = self.external_src.borrow().get_source() {
1127 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1133 pub fn is_real_file(&self) -> bool {
1137 pub fn is_imported(&self) -> bool {
1141 pub fn byte_length(&self) -> u32 {
1142 self.end_pos.0 - self.start_pos.0
1144 pub fn count_lines(&self) -> usize {
1148 /// Find the line containing the given position. The return value is the
1149 /// index into the `lines` array of this `SourceFile`, not the 1-based line
1150 /// number. If the source_file is empty or the position is located before the
1151 /// first line, `None` is returned.
1152 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1153 if self.lines.len() == 0 {
1157 let line_index = lookup_line(&self.lines[..], pos);
1158 assert!(line_index < self.lines.len() as isize);
1159 if line_index >= 0 {
1160 Some(line_index as usize)
1166 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1167 if self.start_pos == self.end_pos {
1168 return (self.start_pos, self.end_pos);
1171 assert!(line_index < self.lines.len());
1172 if line_index == (self.lines.len() - 1) {
1173 (self.lines[line_index], self.end_pos)
1175 (self.lines[line_index], self.lines[line_index + 1])
1180 pub fn contains(&self, byte_pos: BytePos) -> bool {
1181 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1185 /// Remove utf-8 BOM if any.
1186 fn remove_bom(src: &mut String) {
1187 if src.starts_with("\u{feff}") {
1192 // _____________________________________________________________________________
1193 // Pos, BytePos, CharPos
1197 fn from_usize(n: usize) -> Self;
1198 fn to_usize(&self) -> usize;
1199 fn from_u32(n: u32) -> Self;
1200 fn to_u32(&self) -> u32;
1203 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1205 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1206 pub struct BytePos(pub u32);
1208 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1209 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1210 /// values to `CharPos` values as necessary.
1211 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1212 pub struct CharPos(pub usize);
1214 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1215 // have been unsuccessful.
1217 impl Pos for BytePos {
1219 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1222 fn to_usize(&self) -> usize { self.0 as usize }
1225 fn from_u32(n: u32) -> BytePos { BytePos(n) }
1228 fn to_u32(&self) -> u32 { self.0 }
1231 impl Add for BytePos {
1232 type Output = BytePos;
1235 fn add(self, rhs: BytePos) -> BytePos {
1236 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1240 impl Sub for BytePos {
1241 type Output = BytePos;
1244 fn sub(self, rhs: BytePos) -> BytePos {
1245 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1249 impl Encodable for BytePos {
1250 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1255 impl Decodable for BytePos {
1256 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1257 Ok(BytePos(d.read_u32()?))
1261 impl Pos for CharPos {
1263 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1266 fn to_usize(&self) -> usize { self.0 }
1269 fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1272 fn to_u32(&self) -> u32 { self.0 as u32}
1275 impl Add for CharPos {
1276 type Output = CharPos;
1279 fn add(self, rhs: CharPos) -> CharPos {
1280 CharPos(self.to_usize() + rhs.to_usize())
1284 impl Sub for CharPos {
1285 type Output = CharPos;
1288 fn sub(self, rhs: CharPos) -> CharPos {
1289 CharPos(self.to_usize() - rhs.to_usize())
1293 // _____________________________________________________________________________
1294 // Loc, LocWithOpt, SourceFileAndLine, SourceFileAndBytePos
1297 /// A source code location used for error reporting.
1298 #[derive(Debug, Clone)]
1300 /// Information about the original source.
1301 pub file: Lrc<SourceFile>,
1302 /// The (1-based) line number.
1304 /// The (0-based) column offset.
1306 /// The (0-based) column offset when displayed.
1307 pub col_display: usize,
1310 /// A source code location used as the result of `lookup_char_pos_adj`.
1311 // Actually, *none* of the clients use the filename *or* file field;
1312 // perhaps they should just be removed.
1314 pub struct LocWithOpt {
1315 pub filename: FileName,
1318 pub file: Option<Lrc<SourceFile>>,
1321 // Used to be structural records.
1323 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1325 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1327 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1328 pub struct LineInfo {
1329 /// Index of line, starting from 0.
1330 pub line_index: usize,
1332 /// Column in line where span begins, starting from 0.
1333 pub start_col: CharPos,
1335 /// Column in line where span ends, starting from 0, exclusive.
1336 pub end_col: CharPos,
1339 pub struct FileLines {
1340 pub file: Lrc<SourceFile>,
1341 pub lines: Vec<LineInfo>
1344 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1345 Cell::new(default_span_debug));
1348 pub struct MacroBacktrace {
1349 /// span where macro was applied to generate this code
1350 pub call_site: Span,
1352 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1353 pub macro_decl_name: String,
1355 /// span where macro was defined (if known)
1356 pub def_site_span: Option<Span>,
1359 // _____________________________________________________________________________
1360 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1363 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1365 #[derive(Clone, PartialEq, Eq, Debug)]
1366 pub enum SpanLinesError {
1367 IllFormedSpan(Span),
1368 DistinctSources(DistinctSources),
1371 #[derive(Clone, PartialEq, Eq, Debug)]
1372 pub enum SpanSnippetError {
1373 IllFormedSpan(Span),
1374 DistinctSources(DistinctSources),
1375 MalformedForSourcemap(MalformedSourceMapPositions),
1376 SourceNotAvailable { filename: FileName }
1379 #[derive(Clone, PartialEq, Eq, Debug)]
1380 pub struct DistinctSources {
1381 pub begin: (FileName, BytePos),
1382 pub end: (FileName, BytePos)
1385 #[derive(Clone, PartialEq, Eq, Debug)]
1386 pub struct MalformedSourceMapPositions {
1388 pub source_len: usize,
1389 pub begin_pos: BytePos,
1390 pub end_pos: BytePos
1393 // Given a slice of line start positions and a position, returns the index of
1394 // the line the position is on. Returns -1 if the position is located before
1396 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1397 match lines.binary_search(&pos) {
1398 Ok(line) => line as isize,
1399 Err(line) => line as isize - 1
1405 use super::{lookup_line, BytePos};
1408 fn test_lookup_line() {
1410 let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1412 assert_eq!(lookup_line(lines, BytePos(0)), -1);
1413 assert_eq!(lookup_line(lines, BytePos(3)), 0);
1414 assert_eq!(lookup_line(lines, BytePos(4)), 0);
1416 assert_eq!(lookup_line(lines, BytePos(16)), 0);
1417 assert_eq!(lookup_line(lines, BytePos(17)), 1);
1418 assert_eq!(lookup_line(lines, BytePos(18)), 1);
1420 assert_eq!(lookup_line(lines, BytePos(28)), 2);
1421 assert_eq!(lookup_line(lines, BytePos(29)), 2);