1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The source positions and related helper functions
15 //! This API is completely unstable and subject to change.
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19 html_root_url = "https://doc.rust-lang.org/nightly/")]
22 #![feature(crate_visibility_modifier)]
23 #![feature(custom_attribute)]
25 #![feature(non_exhaustive)]
26 #![feature(optin_builtin_traits)]
27 #![feature(specialization)]
28 #![cfg_attr(not(stage0), feature(stdsimd))]
32 use std::cmp::{self, Ordering};
34 use std::hash::{Hasher, Hash};
35 use std::ops::{Add, Sub};
36 use std::path::PathBuf;
38 use rustc_data_structures::stable_hasher::StableHasher;
39 use rustc_data_structures::sync::{Lrc, Lock};
42 extern crate rustc_data_structures;
45 extern crate scoped_tls;
47 use serialize::{Encodable, Decodable, Encoder, Decoder};
49 extern crate serialize;
50 extern crate serialize as rustc_serialize; // used by deriving
55 extern crate unicode_width;
59 pub use hygiene::{Mark, SyntaxContext, ExpnInfo, ExpnFormat, CompilerDesugaringKind};
62 pub use span_encoding::{Span, DUMMY_SP};
66 mod analyze_source_file;
69 symbol_interner: Lock<symbol::Interner>,
70 span_interner: Lock<span_encoding::SpanInterner>,
71 hygiene_data: Lock<hygiene::HygieneData>,
75 pub fn new() -> Globals {
77 symbol_interner: Lock::new(symbol::Interner::fresh()),
78 span_interner: Lock::new(span_encoding::SpanInterner::default()),
79 hygiene_data: Lock::new(hygiene::HygieneData::new()),
84 scoped_thread_local!(pub static GLOBALS: Globals);
86 /// Differentiates between real files and common virtual files
87 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
90 /// A macro. This includes the full name of the macro, so that there are no clashes.
96 /// Hack in src/libsyntax/parse.rs
99 ProcMacroSourceCode(u64),
100 /// Strings provided as --cfg [cfgspec] stored in a crate_cfg
102 /// Strings provided as crate attributes in the CLI
104 /// Custom sources for explicit parser calls from plugins and drivers
106 DocTest(PathBuf, isize),
109 impl std::fmt::Display for FileName {
110 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
111 use self::FileName::*;
113 Real(ref path) => write!(fmt, "{}", path.display()),
114 Macros(ref name) => write!(fmt, "<{} macros>", name),
115 QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
116 MacroExpansion(_) => write!(fmt, "<macro expansion>"),
117 Anon(_) => write!(fmt, "<anon>"),
118 ProcMacroSourceCode(_) =>
119 write!(fmt, "<proc-macro source code>"),
120 CfgSpec(_) => write!(fmt, "<cfgspec>"),
121 CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
122 Custom(ref s) => write!(fmt, "<{}>", s),
123 DocTest(ref path, _) => write!(fmt, "{}", path.display()),
128 impl From<PathBuf> for FileName {
129 fn from(p: PathBuf) -> Self {
130 assert!(!p.to_string_lossy().ends_with('>'));
136 pub fn is_real(&self) -> bool {
137 use self::FileName::*;
143 ProcMacroSourceCode(_) |
148 DocTest(_, _) => false,
152 pub fn is_macros(&self) -> bool {
153 use self::FileName::*;
158 ProcMacroSourceCode(_) |
163 DocTest(_, _) => false,
168 pub fn quote_expansion_source_code(src: &str) -> FileName {
169 let mut hasher = StableHasher::new();
170 src.hash(&mut hasher);
171 FileName::QuoteExpansion(hasher.finish())
174 pub fn macro_expansion_source_code(src: &str) -> FileName {
175 let mut hasher = StableHasher::new();
176 src.hash(&mut hasher);
177 FileName::MacroExpansion(hasher.finish())
180 pub fn anon_source_code(src: &str) -> FileName {
181 let mut hasher = StableHasher::new();
182 src.hash(&mut hasher);
183 FileName::Anon(hasher.finish())
186 pub fn proc_macro_source_code(src: &str) -> FileName {
187 let mut hasher = StableHasher::new();
188 src.hash(&mut hasher);
189 FileName::ProcMacroSourceCode(hasher.finish())
192 pub fn cfg_spec_source_code(src: &str) -> FileName {
193 let mut hasher = StableHasher::new();
194 src.hash(&mut hasher);
195 FileName::QuoteExpansion(hasher.finish())
198 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
199 let mut hasher = StableHasher::new();
200 src.hash(&mut hasher);
201 FileName::CliCrateAttr(hasher.finish())
204 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{
205 FileName::DocTest(path, line)
209 /// Spans represent a region of code, used for error reporting. Positions in spans
210 /// are *absolute* positions from the beginning of the source_map, not positions
211 /// relative to SourceFiles. Methods on the SourceMap can be used to relate spans back
212 /// to the original source.
213 /// You must be careful if the span crosses more than one file - you will not be
214 /// able to use many of the functions on spans in source_map and you cannot assume
215 /// that the length of the span = hi - lo; there may be space in the BytePos
216 /// range between files.
218 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
219 /// sent to other threads, but some pieces of performance infra run in a separate thread.
220 /// Using `Span` is generally preferred.
221 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
222 pub struct SpanData {
225 /// Information about where the macro came from, if this piece of
226 /// code was created by a macro expansion.
227 pub ctxt: SyntaxContext,
232 pub fn with_lo(&self, lo: BytePos) -> Span {
233 Span::new(lo, self.hi, self.ctxt)
236 pub fn with_hi(&self, hi: BytePos) -> Span {
237 Span::new(self.lo, hi, self.ctxt)
240 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
241 Span::new(self.lo, self.hi, ctxt)
245 // The interner is pointed to by a thread local value which is only set on the main thread
246 // with parallelization is disabled. So we don't allow Span to transfer between threads
247 // to avoid panics and other errors, even though it would be memory safe to do so.
248 #[cfg(not(parallel_queries))]
249 impl !Send for Span {}
250 #[cfg(not(parallel_queries))]
251 impl !Sync for Span {}
253 impl PartialOrd for Span {
254 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
255 PartialOrd::partial_cmp(&self.data(), &rhs.data())
259 fn cmp(&self, rhs: &Self) -> Ordering {
260 Ord::cmp(&self.data(), &rhs.data())
264 /// A collection of spans. Spans have two orthogonal attributes:
266 /// - they can be *primary spans*. In this case they are the locus of
267 /// the error, and would be rendered with `^^^`.
268 /// - they can have a *label*. In this case, the label is written next
269 /// to the mark in the snippet when we render.
270 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
271 pub struct MultiSpan {
272 primary_spans: Vec<Span>,
273 span_labels: Vec<(Span, String)>,
278 pub fn lo(self) -> BytePos {
282 pub fn with_lo(self, lo: BytePos) -> Span {
283 self.data().with_lo(lo)
286 pub fn hi(self) -> BytePos {
290 pub fn with_hi(self, hi: BytePos) -> Span {
291 self.data().with_hi(hi)
294 pub fn ctxt(self) -> SyntaxContext {
298 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
299 self.data().with_ctxt(ctxt)
302 /// Returns `true` if this is a dummy span with any hygienic context.
304 pub fn is_dummy(self) -> bool {
305 let span = self.data();
306 span.lo.0 == 0 && span.hi.0 == 0
309 /// Returns a new span representing an empty span at the beginning of this span
311 pub fn shrink_to_lo(self) -> Span {
312 let span = self.data();
313 span.with_hi(span.lo)
315 /// Returns a new span representing an empty span at the end of this span
317 pub fn shrink_to_hi(self) -> Span {
318 let span = self.data();
319 span.with_lo(span.hi)
322 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
323 pub fn substitute_dummy(self, other: Span) -> Span {
324 if self.is_dummy() { other } else { self }
327 /// Return true if `self` fully encloses `other`.
328 pub fn contains(self, other: Span) -> bool {
329 let span = self.data();
330 let other = other.data();
331 span.lo <= other.lo && other.hi <= span.hi
334 /// Return true if the spans are equal with regards to the source text.
336 /// Use this instead of `==` when either span could be generated code,
337 /// and you only care that they point to the same bytes of source text.
338 pub fn source_equal(&self, other: &Span) -> bool {
339 let span = self.data();
340 let other = other.data();
341 span.lo == other.lo && span.hi == other.hi
344 /// Returns `Some(span)`, where the start is trimmed by the end of `other`
345 pub fn trim_start(self, other: Span) -> Option<Span> {
346 let span = self.data();
347 let other = other.data();
348 if span.hi > other.hi {
349 Some(span.with_lo(cmp::max(span.lo, other.hi)))
355 /// Return the source span - this is either the supplied span, or the span for
356 /// the macro callsite that expanded to it.
357 pub fn source_callsite(self) -> Span {
358 self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
361 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
363 pub fn parent(self) -> Option<Span> {
364 self.ctxt().outer().expn_info().map(|i| i.call_site)
367 /// Edition of the crate from which this span came.
368 pub fn edition(self) -> edition::Edition {
369 self.ctxt().outer().expn_info().map_or_else(|| hygiene::default_edition(),
370 |einfo| einfo.edition)
374 pub fn rust_2015(&self) -> bool {
375 self.edition() == edition::Edition::Edition2015
379 pub fn rust_2018(&self) -> bool {
380 self.edition() >= edition::Edition::Edition2018
383 /// Return the source callee.
385 /// Returns `None` if the supplied span has no expansion trace,
386 /// else returns the `ExpnInfo` for the macro definition
387 /// corresponding to the source callsite.
388 pub fn source_callee(self) -> Option<ExpnInfo> {
389 fn source_callee(info: ExpnInfo) -> ExpnInfo {
390 match info.call_site.ctxt().outer().expn_info() {
391 Some(info) => source_callee(info),
395 self.ctxt().outer().expn_info().map(source_callee)
398 /// Check if a span is "internal" to a macro in which #[unstable]
399 /// items can be used (that is, a macro marked with
400 /// `#[allow_internal_unstable]`).
401 pub fn allows_unstable(&self) -> bool {
402 match self.ctxt().outer().expn_info() {
403 Some(info) => info.allow_internal_unstable,
408 /// Check if this span arises from a compiler desugaring of kind `kind`.
409 pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
410 match self.ctxt().outer().expn_info() {
411 Some(info) => match info.format {
412 ExpnFormat::CompilerDesugaring(k) => k == kind,
419 /// Return the compiler desugaring that created this span, or None
420 /// if this span is not from a desugaring.
421 pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
422 match self.ctxt().outer().expn_info() {
423 Some(info) => match info.format {
424 ExpnFormat::CompilerDesugaring(k) => Some(k),
431 /// Check if a span is "internal" to a macro in which `unsafe`
432 /// can be used without triggering the `unsafe_code` lint
433 // (that is, a macro marked with `#[allow_internal_unsafe]`).
434 pub fn allows_unsafe(&self) -> bool {
435 match self.ctxt().outer().expn_info() {
436 Some(info) => info.allow_internal_unsafe,
441 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
442 let mut prev_span = DUMMY_SP;
443 let mut result = vec![];
444 while let Some(info) = self.ctxt().outer().expn_info() {
445 // Don't print recursive invocations
446 if !info.call_site.source_equal(&prev_span) {
447 let (pre, post) = match info.format {
448 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
449 ExpnFormat::MacroBang(..) => ("", "!"),
450 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
452 result.push(MacroBacktrace {
453 call_site: info.call_site,
454 macro_decl_name: format!("{}{}{}", pre, info.format.name(), post),
455 def_site_span: info.def_site,
460 self = info.call_site;
465 /// Return a `Span` that would enclose both `self` and `end`.
466 pub fn to(self, end: Span) -> Span {
467 let span_data = self.data();
468 let end_data = end.data();
469 // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480)
470 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
471 // have an incomplete span than a completely nonsensical one.
472 if span_data.ctxt != end_data.ctxt {
473 if span_data.ctxt == SyntaxContext::empty() {
475 } else if end_data.ctxt == SyntaxContext::empty() {
478 // both span fall within a macro
479 // FIXME(estebank) check if it is the *same* macro
482 cmp::min(span_data.lo, end_data.lo),
483 cmp::max(span_data.hi, end_data.hi),
484 if span_data.ctxt == SyntaxContext::empty() { end_data.ctxt } else { span_data.ctxt },
488 /// Return a `Span` between the end of `self` to the beginning of `end`.
489 pub fn between(self, end: Span) -> Span {
490 let span = self.data();
491 let end = end.data();
495 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
499 /// Return a `Span` between the beginning of `self` to the beginning of `end`.
500 pub fn until(self, end: Span) -> Span {
501 let span = self.data();
502 let end = end.data();
506 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
510 pub fn from_inner_byte_pos(self, start: usize, end: usize) -> Span {
511 let span = self.data();
512 Span::new(span.lo + BytePos::from_usize(start),
513 span.lo + BytePos::from_usize(end),
518 pub fn apply_mark(self, mark: Mark) -> Span {
519 let span = self.data();
520 span.with_ctxt(span.ctxt.apply_mark(mark))
524 pub fn remove_mark(&mut self) -> Mark {
525 let mut span = self.data();
526 let mark = span.ctxt.remove_mark();
527 *self = Span::new(span.lo, span.hi, span.ctxt);
532 pub fn adjust(&mut self, expansion: Mark) -> Option<Mark> {
533 let mut span = self.data();
534 let mark = span.ctxt.adjust(expansion);
535 *self = Span::new(span.lo, span.hi, span.ctxt);
540 pub fn glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
541 -> Option<Option<Mark>> {
542 let mut span = self.data();
543 let mark = span.ctxt.glob_adjust(expansion, glob_ctxt);
544 *self = Span::new(span.lo, span.hi, span.ctxt);
549 pub fn reverse_glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
550 -> Option<Option<Mark>> {
551 let mut span = self.data();
552 let mark = span.ctxt.reverse_glob_adjust(expansion, glob_ctxt);
553 *self = Span::new(span.lo, span.hi, span.ctxt);
558 pub fn modern(self) -> Span {
559 let span = self.data();
560 span.with_ctxt(span.ctxt.modern())
564 pub fn modern_and_legacy(self) -> Span {
565 let span = self.data();
566 span.with_ctxt(span.ctxt.modern_and_legacy())
570 #[derive(Clone, Debug)]
571 pub struct SpanLabel {
572 /// The span we are going to include in the final snippet.
575 /// Is this a primary span? This is the "locus" of the message,
576 /// and is indicated with a `^^^^` underline, versus `----`.
577 pub is_primary: bool,
579 /// What label should we attach to this span (if any)?
580 pub label: Option<String>,
583 impl Default for Span {
584 fn default() -> Self {
589 impl serialize::UseSpecializedEncodable for Span {
590 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
591 let span = self.data();
592 s.emit_struct("Span", 2, |s| {
593 s.emit_struct_field("lo", 0, |s| {
597 s.emit_struct_field("hi", 1, |s| {
604 impl serialize::UseSpecializedDecodable for Span {
605 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
606 d.read_struct("Span", 2, |d| {
607 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
608 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
609 Ok(Span::new(lo, hi, NO_EXPANSION))
614 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
615 f.debug_struct("Span")
616 .field("lo", &span.lo())
617 .field("hi", &span.hi())
618 .field("ctxt", &span.ctxt())
622 impl fmt::Debug for Span {
623 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
624 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
628 impl fmt::Debug for SpanData {
629 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
630 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
636 pub fn new() -> MultiSpan {
638 primary_spans: vec![],
643 pub fn from_span(primary_span: Span) -> MultiSpan {
645 primary_spans: vec![primary_span],
650 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
657 pub fn push_span_label(&mut self, span: Span, label: String) {
658 self.span_labels.push((span, label));
661 /// Selects the first primary span (if any)
662 pub fn primary_span(&self) -> Option<Span> {
663 self.primary_spans.first().cloned()
666 /// Returns all primary spans.
667 pub fn primary_spans(&self) -> &[Span] {
671 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
672 pub fn is_dummy(&self) -> bool {
673 let mut is_dummy = true;
674 for span in &self.primary_spans {
675 if !span.is_dummy() {
682 /// Replaces all occurrences of one Span with another. Used to move Spans in areas that don't
683 /// display well (like std macros). Returns true if replacements occurred.
684 pub fn replace(&mut self, before: Span, after: Span) -> bool {
685 let mut replacements_occurred = false;
686 for primary_span in &mut self.primary_spans {
687 if *primary_span == before {
688 *primary_span = after;
689 replacements_occurred = true;
692 for span_label in &mut self.span_labels {
693 if span_label.0 == before {
694 span_label.0 = after;
695 replacements_occurred = true;
698 replacements_occurred
701 /// Returns the strings to highlight. We always ensure that there
702 /// is an entry for each of the primary spans -- for each primary
703 /// span P, if there is at least one label with span P, we return
704 /// those labels (marked as primary). But otherwise we return
705 /// `SpanLabel` instances with empty labels.
706 pub fn span_labels(&self) -> Vec<SpanLabel> {
707 let is_primary = |span| self.primary_spans.contains(&span);
709 let mut span_labels = self.span_labels.iter().map(|&(span, ref label)|
712 is_primary: is_primary(span),
713 label: Some(label.clone())
715 ).collect::<Vec<_>>();
717 for &span in &self.primary_spans {
718 if !span_labels.iter().any(|sl| sl.span == span) {
719 span_labels.push(SpanLabel {
731 impl From<Span> for MultiSpan {
732 fn from(span: Span) -> MultiSpan {
733 MultiSpan::from_span(span)
737 impl From<Vec<Span>> for MultiSpan {
738 fn from(spans: Vec<Span>) -> MultiSpan {
739 MultiSpan::from_spans(spans)
743 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
745 /// Identifies an offset of a multi-byte character in a SourceFile
746 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
747 pub struct MultiByteChar {
748 /// The absolute offset of the character in the SourceMap
750 /// The number of bytes, >=2
754 /// Identifies an offset of a non-narrow character in a SourceFile
755 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
756 pub enum NonNarrowChar {
757 /// Represents a zero-width character
759 /// Represents a wide (fullwidth) character
761 /// Represents a tab character, represented visually with a width of 4 characters
766 fn new(pos: BytePos, width: usize) -> Self {
768 0 => NonNarrowChar::ZeroWidth(pos),
769 2 => NonNarrowChar::Wide(pos),
770 4 => NonNarrowChar::Tab(pos),
771 _ => panic!("width {} given for non-narrow character", width),
775 /// Returns the absolute offset of the character in the SourceMap
776 pub fn pos(&self) -> BytePos {
778 NonNarrowChar::ZeroWidth(p) |
779 NonNarrowChar::Wide(p) |
780 NonNarrowChar::Tab(p) => p,
784 /// Returns the width of the character, 0 (zero-width) or 2 (wide)
785 pub fn width(&self) -> usize {
787 NonNarrowChar::ZeroWidth(_) => 0,
788 NonNarrowChar::Wide(_) => 2,
789 NonNarrowChar::Tab(_) => 4,
794 impl Add<BytePos> for NonNarrowChar {
797 fn add(self, rhs: BytePos) -> Self {
799 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
800 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
801 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
806 impl Sub<BytePos> for NonNarrowChar {
809 fn sub(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 /// The state of the lazy external source loading mechanism of a SourceFile.
819 #[derive(PartialEq, Eq, Clone)]
820 pub enum ExternalSource {
821 /// The external source has been loaded already.
823 /// No attempt has been made to load the external source.
825 /// A failed attempt has been made to load the external source.
827 /// No external source has to be loaded, since the SourceFile represents a local crate.
831 impl ExternalSource {
832 pub fn is_absent(&self) -> bool {
834 ExternalSource::Present(_) => false,
839 pub fn get_source(&self) -> Option<&str> {
841 ExternalSource::Present(ref src) => Some(src),
847 /// A single source in the SourceMap.
849 pub struct SourceFile {
850 /// The name of the file that the source came from, source that doesn't
851 /// originate from files has names between angle brackets by convention,
854 /// True if the `name` field above has been modified by --remap-path-prefix
855 pub name_was_remapped: bool,
856 /// The unmapped path of the file that the source came from.
857 /// Set to `None` if the SourceFile was imported from an external crate.
858 pub unmapped_path: Option<FileName>,
859 /// Indicates which crate this SourceFile was imported from.
860 pub crate_of_origin: u32,
861 /// The complete source code
862 pub src: Option<Lrc<String>>,
863 /// The source code's hash
865 /// The external source code (used for external crates, which will have a `None`
866 /// value as `self.src`.
867 pub external_src: Lock<ExternalSource>,
868 /// The start position of this source in the SourceMap
869 pub start_pos: BytePos,
870 /// The end position of this source in the SourceMap
871 pub end_pos: BytePos,
872 /// Locations of lines beginnings in the source code
873 pub lines: Vec<BytePos>,
874 /// Locations of multi-byte characters in the source code
875 pub multibyte_chars: Vec<MultiByteChar>,
876 /// Width of characters that are not narrow in the source code
877 pub non_narrow_chars: Vec<NonNarrowChar>,
878 /// A hash of the filename, used for speeding up the incr. comp. hashing.
882 impl Encodable for SourceFile {
883 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
884 s.emit_struct("SourceFile", 8, |s| {
885 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
886 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
887 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
888 s.emit_struct_field("start_pos", 4, |s| self.start_pos.encode(s))?;
889 s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
890 s.emit_struct_field("lines", 6, |s| {
891 let lines = &self.lines[..];
893 s.emit_u32(lines.len() as u32)?;
895 if !lines.is_empty() {
896 // In order to preserve some space, we exploit the fact that
897 // the lines list is sorted and individual lines are
898 // probably not that long. Because of that we can store lines
899 // as a difference list, using as little space as possible
900 // for the differences.
901 let max_line_length = if lines.len() == 1 {
905 .map(|w| w[1] - w[0])
906 .map(|bp| bp.to_usize())
911 let bytes_per_diff: u8 = match max_line_length {
913 0x100 ..= 0xFFFF => 2,
917 // Encode the number of bytes used per diff.
918 bytes_per_diff.encode(s)?;
920 // Encode the first element.
923 let diff_iter = (&lines[..]).windows(2)
924 .map(|w| (w[1] - w[0]));
926 match bytes_per_diff {
927 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
928 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
929 4 => for diff in diff_iter { diff.0.encode(s)? },
936 s.emit_struct_field("multibyte_chars", 7, |s| {
937 self.multibyte_chars.encode(s)
939 s.emit_struct_field("non_narrow_chars", 8, |s| {
940 self.non_narrow_chars.encode(s)
942 s.emit_struct_field("name_hash", 9, |s| {
943 self.name_hash.encode(s)
949 impl Decodable for SourceFile {
950 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
952 d.read_struct("SourceFile", 8, |d| {
953 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
954 let name_was_remapped: bool =
955 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
957 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
958 let start_pos: BytePos =
959 d.read_struct_field("start_pos", 4, |d| Decodable::decode(d))?;
960 let end_pos: BytePos = d.read_struct_field("end_pos", 5, |d| Decodable::decode(d))?;
961 let lines: Vec<BytePos> = d.read_struct_field("lines", 6, |d| {
962 let num_lines: u32 = Decodable::decode(d)?;
963 let mut lines = Vec::with_capacity(num_lines as usize);
966 // Read the number of bytes used per diff.
967 let bytes_per_diff: u8 = Decodable::decode(d)?;
969 // Read the first element.
970 let mut line_start: BytePos = Decodable::decode(d)?;
971 lines.push(line_start);
973 for _ in 1..num_lines {
974 let diff = match bytes_per_diff {
975 1 => d.read_u8()? as u32,
976 2 => d.read_u16()? as u32,
981 line_start = line_start + BytePos(diff);
983 lines.push(line_start);
989 let multibyte_chars: Vec<MultiByteChar> =
990 d.read_struct_field("multibyte_chars", 7, |d| Decodable::decode(d))?;
991 let non_narrow_chars: Vec<NonNarrowChar> =
992 d.read_struct_field("non_narrow_chars", 8, |d| Decodable::decode(d))?;
993 let name_hash: u128 =
994 d.read_struct_field("name_hash", 9, |d| Decodable::decode(d))?;
999 // `crate_of_origin` has to be set by the importer.
1000 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
1001 // That constant is not available here unfortunately :(
1002 crate_of_origin: ::std::u32::MAX - 1,
1007 external_src: Lock::new(ExternalSource::AbsentOk),
1017 impl fmt::Debug for SourceFile {
1018 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1019 write!(fmt, "SourceFile({})", self.name)
1024 pub fn new(name: FileName,
1025 name_was_remapped: bool,
1026 unmapped_path: FileName,
1028 start_pos: BytePos) -> SourceFile {
1029 remove_bom(&mut src);
1032 let mut hasher: StableHasher<u128> = StableHasher::new();
1033 hasher.write(src.as_bytes());
1037 let mut hasher: StableHasher<u128> = StableHasher::new();
1038 name.hash(&mut hasher);
1041 let end_pos = start_pos.to_usize() + src.len();
1043 let (lines, multibyte_chars, non_narrow_chars) =
1044 analyze_source_file::analyze_source_file(&src[..], start_pos);
1049 unmapped_path: Some(unmapped_path),
1051 src: Some(Lrc::new(src)),
1053 external_src: Lock::new(ExternalSource::Unneeded),
1055 end_pos: Pos::from_usize(end_pos),
1063 /// Return the BytePos of the beginning of the current line.
1064 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1065 let line_index = self.lookup_line(pos).unwrap();
1066 self.lines[line_index]
1069 /// Add externally loaded source.
1070 /// If the hash of the input doesn't match or no input is supplied via None,
1071 /// it is interpreted as an error and the corresponding enum variant is set.
1072 /// The return value signifies whether some kind of source is present.
1073 pub fn add_external_src<F>(&self, get_src: F) -> bool
1074 where F: FnOnce() -> Option<String>
1076 if *self.external_src.borrow() == ExternalSource::AbsentOk {
1077 let src = get_src();
1078 let mut external_src = self.external_src.borrow_mut();
1079 // Check that no-one else have provided the source while we were getting it
1080 if *external_src == ExternalSource::AbsentOk {
1081 if let Some(src) = src {
1082 let mut hasher: StableHasher<u128> = StableHasher::new();
1083 hasher.write(src.as_bytes());
1085 if hasher.finish() == self.src_hash {
1086 *external_src = ExternalSource::Present(src);
1090 *external_src = ExternalSource::AbsentErr;
1095 self.src.is_some() || external_src.get_source().is_some()
1098 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1102 /// Get a line from the list of pre-computed line-beginnings.
1103 /// The line number here is 0-based.
1104 pub fn get_line(&self, line_number: usize) -> Option<Cow<str>> {
1105 fn get_until_newline(src: &str, begin: usize) -> &str {
1106 // We can't use `lines.get(line_number+1)` because we might
1107 // be parsing when we call this function and thus the current
1108 // line is the last one we have line info for.
1109 let slice = &src[begin..];
1110 match slice.find('\n') {
1111 Some(e) => &slice[..e],
1117 let line = if let Some(line) = self.lines.get(line_number) {
1122 let begin: BytePos = *line - self.start_pos;
1126 if let Some(ref src) = self.src {
1127 Some(Cow::from(get_until_newline(src, begin)))
1128 } else if let Some(src) = self.external_src.borrow().get_source() {
1129 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1135 pub fn is_real_file(&self) -> bool {
1139 pub fn is_imported(&self) -> bool {
1143 pub fn byte_length(&self) -> u32 {
1144 self.end_pos.0 - self.start_pos.0
1146 pub fn count_lines(&self) -> usize {
1150 /// Find the line containing the given position. The return value is the
1151 /// index into the `lines` array of this SourceFile, not the 1-based line
1152 /// number. If the source_file is empty or the position is located before the
1153 /// first line, None is returned.
1154 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1155 if self.lines.len() == 0 {
1159 let line_index = lookup_line(&self.lines[..], pos);
1160 assert!(line_index < self.lines.len() as isize);
1161 if line_index >= 0 {
1162 Some(line_index as usize)
1168 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1169 if self.start_pos == self.end_pos {
1170 return (self.start_pos, self.end_pos);
1173 assert!(line_index < self.lines.len());
1174 if line_index == (self.lines.len() - 1) {
1175 (self.lines[line_index], self.end_pos)
1177 (self.lines[line_index], self.lines[line_index + 1])
1182 pub fn contains(&self, byte_pos: BytePos) -> bool {
1183 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1187 /// Remove utf-8 BOM if any.
1188 fn remove_bom(src: &mut String) {
1189 if src.starts_with("\u{feff}") {
1194 // _____________________________________________________________________________
1195 // Pos, BytePos, CharPos
1199 fn from_usize(n: usize) -> Self;
1200 fn to_usize(&self) -> usize;
1201 fn from_u32(n: u32) -> Self;
1202 fn to_u32(&self) -> u32;
1205 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1207 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1208 pub struct BytePos(pub u32);
1210 /// A character offset. Because of multibyte utf8 characters, a byte offset
1211 /// is not equivalent to a character offset. The SourceMap will convert BytePos
1212 /// values to CharPos values as necessary.
1213 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1214 pub struct CharPos(pub usize);
1216 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
1217 // have been unsuccessful
1219 impl Pos for BytePos {
1221 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1224 fn to_usize(&self) -> usize { self.0 as usize }
1227 fn from_u32(n: u32) -> BytePos { BytePos(n) }
1230 fn to_u32(&self) -> u32 { self.0 }
1233 impl Add for BytePos {
1234 type Output = BytePos;
1237 fn add(self, rhs: BytePos) -> BytePos {
1238 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1242 impl Sub for BytePos {
1243 type Output = BytePos;
1246 fn sub(self, rhs: BytePos) -> BytePos {
1247 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1251 impl Encodable for BytePos {
1252 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1257 impl Decodable for BytePos {
1258 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1259 Ok(BytePos(d.read_u32()?))
1263 impl Pos for CharPos {
1265 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1268 fn to_usize(&self) -> usize { self.0 }
1271 fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1274 fn to_u32(&self) -> u32 { self.0 as u32}
1277 impl Add for CharPos {
1278 type Output = CharPos;
1281 fn add(self, rhs: CharPos) -> CharPos {
1282 CharPos(self.to_usize() + rhs.to_usize())
1286 impl Sub for CharPos {
1287 type Output = CharPos;
1290 fn sub(self, rhs: CharPos) -> CharPos {
1291 CharPos(self.to_usize() - rhs.to_usize())
1295 // _____________________________________________________________________________
1296 // Loc, LocWithOpt, SourceFileAndLine, SourceFileAndBytePos
1299 /// A source code location used for error reporting
1300 #[derive(Debug, Clone)]
1302 /// Information about the original source
1303 pub file: Lrc<SourceFile>,
1304 /// The (1-based) line number
1306 /// The (0-based) column offset
1308 /// The (0-based) column offset when displayed
1309 pub col_display: usize,
1312 /// A source code location used as the result of lookup_char_pos_adj
1313 // Actually, *none* of the clients use the filename *or* file field;
1314 // perhaps they should just be removed.
1316 pub struct LocWithOpt {
1317 pub filename: FileName,
1320 pub file: Option<Lrc<SourceFile>>,
1323 // used to be structural records. Better names, anyone?
1325 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1327 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1329 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1330 pub struct LineInfo {
1331 /// Index of line, starting from 0.
1332 pub line_index: usize,
1334 /// Column in line where span begins, starting from 0.
1335 pub start_col: CharPos,
1337 /// Column in line where span ends, starting from 0, exclusive.
1338 pub end_col: CharPos,
1341 pub struct FileLines {
1342 pub file: Lrc<SourceFile>,
1343 pub lines: Vec<LineInfo>
1346 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
1347 Cell::new(default_span_debug));
1350 pub struct MacroBacktrace {
1351 /// span where macro was applied to generate this code
1352 pub call_site: Span,
1354 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1355 pub macro_decl_name: String,
1357 /// span where macro was defined (if known)
1358 pub def_site_span: Option<Span>,
1361 // _____________________________________________________________________________
1362 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1365 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1367 #[derive(Clone, PartialEq, Eq, Debug)]
1368 pub enum SpanLinesError {
1369 IllFormedSpan(Span),
1370 DistinctSources(DistinctSources),
1373 #[derive(Clone, PartialEq, Eq, Debug)]
1374 pub enum SpanSnippetError {
1375 IllFormedSpan(Span),
1376 DistinctSources(DistinctSources),
1377 MalformedForSourcemap(MalformedSourceMapPositions),
1378 SourceNotAvailable { filename: FileName }
1381 #[derive(Clone, PartialEq, Eq, Debug)]
1382 pub struct DistinctSources {
1383 pub begin: (FileName, BytePos),
1384 pub end: (FileName, BytePos)
1387 #[derive(Clone, PartialEq, Eq, Debug)]
1388 pub struct MalformedSourceMapPositions {
1390 pub source_len: usize,
1391 pub begin_pos: BytePos,
1392 pub end_pos: BytePos
1395 // Given a slice of line start positions and a position, returns the index of
1396 // the line the position is on. Returns -1 if the position is located before
1398 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1399 match lines.binary_search(&pos) {
1400 Ok(line) => line as isize,
1401 Err(line) => line as isize - 1
1407 use super::{lookup_line, BytePos};
1410 fn test_lookup_line() {
1412 let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1414 assert_eq!(lookup_line(lines, BytePos(0)), -1);
1415 assert_eq!(lookup_line(lines, BytePos(3)), 0);
1416 assert_eq!(lookup_line(lines, BytePos(4)), 0);
1418 assert_eq!(lookup_line(lines, BytePos(16)), 0);
1419 assert_eq!(lookup_line(lines, BytePos(17)), 1);
1420 assert_eq!(lookup_line(lines, BytePos(18)), 1);
1422 assert_eq!(lookup_line(lines, BytePos(28)), 2);
1423 assert_eq!(lookup_line(lines, BytePos(29)), 2);