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
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
108 impl std::fmt::Display for FileName {
109 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
110 use self::FileName::*;
112 Real(ref path) => write!(fmt, "{}", path.display()),
113 Macros(ref name) => write!(fmt, "<{} macros>", name),
114 QuoteExpansion => write!(fmt, "<quote expansion>"),
115 MacroExpansion => write!(fmt, "<macro expansion>"),
116 Anon => write!(fmt, "<anon>"),
117 ProcMacroSourceCode => write!(fmt, "<proc-macro source code>"),
118 CfgSpec => write!(fmt, "cfgspec"),
119 CliCrateAttr => write!(fmt, "<crate attribute>"),
120 Custom(ref s) => write!(fmt, "<{}>", s),
125 impl From<PathBuf> for FileName {
126 fn from(p: PathBuf) -> Self {
127 assert!(!p.to_string_lossy().ends_with('>'));
133 pub fn is_real(&self) -> bool {
134 use self::FileName::*;
140 ProcMacroSourceCode |
144 QuoteExpansion => false,
148 pub fn is_macros(&self) -> bool {
149 use self::FileName::*;
154 ProcMacroSourceCode |
158 QuoteExpansion => false,
164 /// Spans represent a region of code, used for error reporting. Positions in spans
165 /// are *absolute* positions from the beginning of the source_map, not positions
166 /// relative to SourceFiles. Methods on the SourceMap can be used to relate spans back
167 /// to the original source.
168 /// You must be careful if the span crosses more than one file - you will not be
169 /// able to use many of the functions on spans in source_map and you cannot assume
170 /// that the length of the span = hi - lo; there may be space in the BytePos
171 /// range between files.
173 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
174 /// sent to other threads, but some pieces of performance infra run in a separate thread.
175 /// Using `Span` is generally preferred.
176 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
177 pub struct SpanData {
180 /// Information about where the macro came from, if this piece of
181 /// code was created by a macro expansion.
182 pub ctxt: SyntaxContext,
187 pub fn with_lo(&self, lo: BytePos) -> Span {
188 Span::new(lo, self.hi, self.ctxt)
191 pub fn with_hi(&self, hi: BytePos) -> Span {
192 Span::new(self.lo, hi, self.ctxt)
195 pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
196 Span::new(self.lo, self.hi, ctxt)
200 // The interner is pointed to by a thread local value which is only set on the main thread
201 // with parallelization is disabled. So we don't allow Span to transfer between threads
202 // to avoid panics and other errors, even though it would be memory safe to do so.
203 #[cfg(not(parallel_queries))]
204 impl !Send for Span {}
205 #[cfg(not(parallel_queries))]
206 impl !Sync for Span {}
208 impl PartialOrd for Span {
209 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
210 PartialOrd::partial_cmp(&self.data(), &rhs.data())
214 fn cmp(&self, rhs: &Self) -> Ordering {
215 Ord::cmp(&self.data(), &rhs.data())
219 /// A collection of spans. Spans have two orthogonal attributes:
221 /// - they can be *primary spans*. In this case they are the locus of
222 /// the error, and would be rendered with `^^^`.
223 /// - they can have a *label*. In this case, the label is written next
224 /// to the mark in the snippet when we render.
225 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
226 pub struct MultiSpan {
227 primary_spans: Vec<Span>,
228 span_labels: Vec<(Span, String)>,
233 pub fn lo(self) -> BytePos {
237 pub fn with_lo(self, lo: BytePos) -> Span {
238 self.data().with_lo(lo)
241 pub fn hi(self) -> BytePos {
245 pub fn with_hi(self, hi: BytePos) -> Span {
246 self.data().with_hi(hi)
249 pub fn ctxt(self) -> SyntaxContext {
253 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
254 self.data().with_ctxt(ctxt)
257 /// Returns `true` if this is a dummy span with any hygienic context.
259 pub fn is_dummy(self) -> bool {
260 let span = self.data();
261 span.lo.0 == 0 && span.hi.0 == 0
264 /// Returns a new span representing an empty span at the beginning of this span
266 pub fn shrink_to_lo(self) -> Span {
267 let span = self.data();
268 span.with_hi(span.lo)
270 /// Returns a new span representing an empty span at the end of this span
272 pub fn shrink_to_hi(self) -> Span {
273 let span = self.data();
274 span.with_lo(span.hi)
277 /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
278 pub fn substitute_dummy(self, other: Span) -> Span {
279 if self.is_dummy() { other } else { self }
282 /// Return true if `self` fully encloses `other`.
283 pub fn contains(self, other: Span) -> bool {
284 let span = self.data();
285 let other = other.data();
286 span.lo <= other.lo && other.hi <= span.hi
289 /// Return true if the spans are equal with regards to the source text.
291 /// Use this instead of `==` when either span could be generated code,
292 /// and you only care that they point to the same bytes of source text.
293 pub fn source_equal(&self, other: &Span) -> bool {
294 let span = self.data();
295 let other = other.data();
296 span.lo == other.lo && span.hi == other.hi
299 /// Returns `Some(span)`, where the start is trimmed by the end of `other`
300 pub fn trim_start(self, other: Span) -> Option<Span> {
301 let span = self.data();
302 let other = other.data();
303 if span.hi > other.hi {
304 Some(span.with_lo(cmp::max(span.lo, other.hi)))
310 /// Return the source span - this is either the supplied span, or the span for
311 /// the macro callsite that expanded to it.
312 pub fn source_callsite(self) -> Span {
313 self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
316 /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
318 pub fn parent(self) -> Option<Span> {
319 self.ctxt().outer().expn_info().map(|i| i.call_site)
322 /// Edition of the crate from which this span came.
323 pub fn edition(self) -> edition::Edition {
324 self.ctxt().outer().expn_info().map_or_else(|| hygiene::default_edition(),
325 |einfo| einfo.edition)
328 /// Return the source callee.
330 /// Returns `None` if the supplied span has no expansion trace,
331 /// else returns the `ExpnInfo` for the macro definition
332 /// corresponding to the source callsite.
333 pub fn source_callee(self) -> Option<ExpnInfo> {
334 fn source_callee(info: ExpnInfo) -> ExpnInfo {
335 match info.call_site.ctxt().outer().expn_info() {
336 Some(info) => source_callee(info),
340 self.ctxt().outer().expn_info().map(source_callee)
343 /// Check if a span is "internal" to a macro in which #[unstable]
344 /// items can be used (that is, a macro marked with
345 /// `#[allow_internal_unstable]`).
346 pub fn allows_unstable(&self) -> bool {
347 match self.ctxt().outer().expn_info() {
348 Some(info) => info.allow_internal_unstable,
353 /// Check if this span arises from a compiler desugaring of kind `kind`.
354 pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
355 match self.ctxt().outer().expn_info() {
356 Some(info) => match info.format {
357 ExpnFormat::CompilerDesugaring(k) => k == kind,
364 /// Return the compiler desugaring that created this span, or None
365 /// if this span is not from a desugaring.
366 pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
367 match self.ctxt().outer().expn_info() {
368 Some(info) => match info.format {
369 ExpnFormat::CompilerDesugaring(k) => Some(k),
376 /// Check if a span is "internal" to a macro in which `unsafe`
377 /// can be used without triggering the `unsafe_code` lint
378 // (that is, a macro marked with `#[allow_internal_unsafe]`).
379 pub fn allows_unsafe(&self) -> bool {
380 match self.ctxt().outer().expn_info() {
381 Some(info) => info.allow_internal_unsafe,
386 pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
387 let mut prev_span = DUMMY_SP;
388 let mut result = vec![];
389 while let Some(info) = self.ctxt().outer().expn_info() {
390 // Don't print recursive invocations
391 if !info.call_site.source_equal(&prev_span) {
392 let (pre, post) = match info.format {
393 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
394 ExpnFormat::MacroBang(..) => ("", "!"),
395 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
397 result.push(MacroBacktrace {
398 call_site: info.call_site,
399 macro_decl_name: format!("{}{}{}", pre, info.format.name(), post),
400 def_site_span: info.def_site,
405 self = info.call_site;
410 /// Return a `Span` that would enclose both `self` and `end`.
411 pub fn to(self, end: Span) -> Span {
412 let span_data = self.data();
413 let end_data = end.data();
414 // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480)
415 // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
416 // have an incomplete span than a completely nonsensical one.
417 if span_data.ctxt != end_data.ctxt {
418 if span_data.ctxt == SyntaxContext::empty() {
420 } else if end_data.ctxt == SyntaxContext::empty() {
423 // both span fall within a macro
424 // FIXME(estebank) check if it is the *same* macro
427 cmp::min(span_data.lo, end_data.lo),
428 cmp::max(span_data.hi, end_data.hi),
429 if span_data.ctxt == SyntaxContext::empty() { end_data.ctxt } else { span_data.ctxt },
433 /// Return a `Span` between the end of `self` to the beginning of `end`.
434 pub fn between(self, end: Span) -> Span {
435 let span = self.data();
436 let end = end.data();
440 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
444 /// Return a `Span` between the beginning of `self` to the beginning of `end`.
445 pub fn until(self, end: Span) -> Span {
446 let span = self.data();
447 let end = end.data();
451 if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
455 pub fn from_inner_byte_pos(self, start: usize, end: usize) -> Span {
456 let span = self.data();
457 Span::new(span.lo + BytePos::from_usize(start),
458 span.lo + BytePos::from_usize(end),
463 pub fn apply_mark(self, mark: Mark) -> Span {
464 let span = self.data();
465 span.with_ctxt(span.ctxt.apply_mark(mark))
469 pub fn remove_mark(&mut self) -> Mark {
470 let mut span = self.data();
471 let mark = span.ctxt.remove_mark();
472 *self = Span::new(span.lo, span.hi, span.ctxt);
477 pub fn adjust(&mut self, expansion: Mark) -> Option<Mark> {
478 let mut span = self.data();
479 let mark = span.ctxt.adjust(expansion);
480 *self = Span::new(span.lo, span.hi, span.ctxt);
485 pub fn glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
486 -> Option<Option<Mark>> {
487 let mut span = self.data();
488 let mark = span.ctxt.glob_adjust(expansion, glob_ctxt);
489 *self = Span::new(span.lo, span.hi, span.ctxt);
494 pub fn reverse_glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
495 -> Option<Option<Mark>> {
496 let mut span = self.data();
497 let mark = span.ctxt.reverse_glob_adjust(expansion, glob_ctxt);
498 *self = Span::new(span.lo, span.hi, span.ctxt);
503 pub fn modern(self) -> Span {
504 let span = self.data();
505 span.with_ctxt(span.ctxt.modern())
509 pub fn modern_and_legacy(self) -> Span {
510 let span = self.data();
511 span.with_ctxt(span.ctxt.modern_and_legacy())
515 #[derive(Clone, Debug)]
516 pub struct SpanLabel {
517 /// The span we are going to include in the final snippet.
520 /// Is this a primary span? This is the "locus" of the message,
521 /// and is indicated with a `^^^^` underline, versus `----`.
522 pub is_primary: bool,
524 /// What label should we attach to this span (if any)?
525 pub label: Option<String>,
528 impl Default for Span {
529 fn default() -> Self {
534 impl serialize::UseSpecializedEncodable for Span {
535 fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
536 let span = self.data();
537 s.emit_struct("Span", 2, |s| {
538 s.emit_struct_field("lo", 0, |s| {
542 s.emit_struct_field("hi", 1, |s| {
549 impl serialize::UseSpecializedDecodable for Span {
550 fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
551 d.read_struct("Span", 2, |d| {
552 let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
553 let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
554 Ok(Span::new(lo, hi, NO_EXPANSION))
559 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
560 f.debug_struct("Span")
561 .field("lo", &span.lo())
562 .field("hi", &span.hi())
563 .field("ctxt", &span.ctxt())
567 impl fmt::Debug for Span {
568 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
569 SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
573 impl fmt::Debug for SpanData {
574 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
575 SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
580 pub fn new() -> MultiSpan {
582 primary_spans: vec![],
587 pub fn from_span(primary_span: Span) -> MultiSpan {
589 primary_spans: vec![primary_span],
594 pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
601 pub fn push_span_label(&mut self, span: Span, label: String) {
602 self.span_labels.push((span, label));
605 /// Selects the first primary span (if any)
606 pub fn primary_span(&self) -> Option<Span> {
607 self.primary_spans.first().cloned()
610 /// Returns all primary spans.
611 pub fn primary_spans(&self) -> &[Span] {
615 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
616 pub fn is_dummy(&self) -> bool {
617 let mut is_dummy = true;
618 for span in &self.primary_spans {
619 if !span.is_dummy() {
626 /// Replaces all occurrences of one Span with another. Used to move Spans in areas that don't
627 /// display well (like std macros). Returns true if replacements occurred.
628 pub fn replace(&mut self, before: Span, after: Span) -> bool {
629 let mut replacements_occurred = false;
630 for primary_span in &mut self.primary_spans {
631 if *primary_span == before {
632 *primary_span = after;
633 replacements_occurred = true;
636 for span_label in &mut self.span_labels {
637 if span_label.0 == before {
638 span_label.0 = after;
639 replacements_occurred = true;
642 replacements_occurred
645 /// Returns the strings to highlight. We always ensure that there
646 /// is an entry for each of the primary spans -- for each primary
647 /// span P, if there is at least one label with span P, we return
648 /// those labels (marked as primary). But otherwise we return
649 /// `SpanLabel` instances with empty labels.
650 pub fn span_labels(&self) -> Vec<SpanLabel> {
651 let is_primary = |span| self.primary_spans.contains(&span);
653 let mut span_labels = self.span_labels.iter().map(|&(span, ref label)|
656 is_primary: is_primary(span),
657 label: Some(label.clone())
659 ).collect::<Vec<_>>();
661 for &span in &self.primary_spans {
662 if !span_labels.iter().any(|sl| sl.span == span) {
663 span_labels.push(SpanLabel {
675 impl From<Span> for MultiSpan {
676 fn from(span: Span) -> MultiSpan {
677 MultiSpan::from_span(span)
681 impl From<Vec<Span>> for MultiSpan {
682 fn from(spans: Vec<Span>) -> MultiSpan {
683 MultiSpan::from_spans(spans)
687 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
689 /// Identifies an offset of a multi-byte character in a SourceFile
690 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
691 pub struct MultiByteChar {
692 /// The absolute offset of the character in the SourceMap
694 /// The number of bytes, >=2
698 /// Identifies an offset of a non-narrow character in a SourceFile
699 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
700 pub enum NonNarrowChar {
701 /// Represents a zero-width character
703 /// Represents a wide (fullwidth) character
705 /// Represents a tab character, represented visually with a width of 4 characters
710 fn new(pos: BytePos, width: usize) -> Self {
712 0 => NonNarrowChar::ZeroWidth(pos),
713 2 => NonNarrowChar::Wide(pos),
714 4 => NonNarrowChar::Tab(pos),
715 _ => panic!("width {} given for non-narrow character", width),
719 /// Returns the absolute offset of the character in the SourceMap
720 pub fn pos(&self) -> BytePos {
722 NonNarrowChar::ZeroWidth(p) |
723 NonNarrowChar::Wide(p) |
724 NonNarrowChar::Tab(p) => p,
728 /// Returns the width of the character, 0 (zero-width) or 2 (wide)
729 pub fn width(&self) -> usize {
731 NonNarrowChar::ZeroWidth(_) => 0,
732 NonNarrowChar::Wide(_) => 2,
733 NonNarrowChar::Tab(_) => 4,
738 impl Add<BytePos> for NonNarrowChar {
741 fn add(self, rhs: BytePos) -> Self {
743 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
744 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
745 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
750 impl Sub<BytePos> for NonNarrowChar {
753 fn sub(self, rhs: BytePos) -> Self {
755 NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
756 NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
757 NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
762 /// The state of the lazy external source loading mechanism of a SourceFile.
763 #[derive(PartialEq, Eq, Clone)]
764 pub enum ExternalSource {
765 /// The external source has been loaded already.
767 /// No attempt has been made to load the external source.
769 /// A failed attempt has been made to load the external source.
771 /// No external source has to be loaded, since the SourceFile represents a local crate.
775 impl ExternalSource {
776 pub fn is_absent(&self) -> bool {
778 ExternalSource::Present(_) => false,
783 pub fn get_source(&self) -> Option<&str> {
785 ExternalSource::Present(ref src) => Some(src),
791 /// A single source in the SourceMap.
793 pub struct SourceFile {
794 /// The name of the file that the source came from, source that doesn't
795 /// originate from files has names between angle brackets by convention,
798 /// True if the `name` field above has been modified by --remap-path-prefix
799 pub name_was_remapped: bool,
800 /// The unmapped path of the file that the source came from.
801 /// Set to `None` if the SourceFile was imported from an external crate.
802 pub unmapped_path: Option<FileName>,
803 /// Indicates which crate this SourceFile was imported from.
804 pub crate_of_origin: u32,
805 /// The complete source code
806 pub src: Option<Lrc<String>>,
807 /// The source code's hash
809 /// The external source code (used for external crates, which will have a `None`
810 /// value as `self.src`.
811 pub external_src: Lock<ExternalSource>,
812 /// The start position of this source in the SourceMap
813 pub start_pos: BytePos,
814 /// The end position of this source in the SourceMap
815 pub end_pos: BytePos,
816 /// Locations of lines beginnings in the source code
817 pub lines: Vec<BytePos>,
818 /// Locations of multi-byte characters in the source code
819 pub multibyte_chars: Vec<MultiByteChar>,
820 /// Width of characters that are not narrow in the source code
821 pub non_narrow_chars: Vec<NonNarrowChar>,
822 /// A hash of the filename, used for speeding up the incr. comp. hashing.
826 impl Encodable for SourceFile {
827 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
828 s.emit_struct("SourceFile", 8, |s| {
829 s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
830 s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
831 s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
832 s.emit_struct_field("start_pos", 4, |s| self.start_pos.encode(s))?;
833 s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
834 s.emit_struct_field("lines", 6, |s| {
835 let lines = &self.lines[..];
837 s.emit_u32(lines.len() as u32)?;
839 if !lines.is_empty() {
840 // In order to preserve some space, we exploit the fact that
841 // the lines list is sorted and individual lines are
842 // probably not that long. Because of that we can store lines
843 // as a difference list, using as little space as possible
844 // for the differences.
845 let max_line_length = if lines.len() == 1 {
849 .map(|w| w[1] - w[0])
850 .map(|bp| bp.to_usize())
855 let bytes_per_diff: u8 = match max_line_length {
857 0x100 ..= 0xFFFF => 2,
861 // Encode the number of bytes used per diff.
862 bytes_per_diff.encode(s)?;
864 // Encode the first element.
867 let diff_iter = (&lines[..]).windows(2)
868 .map(|w| (w[1] - w[0]));
870 match bytes_per_diff {
871 1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
872 2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
873 4 => for diff in diff_iter { diff.0.encode(s)? },
880 s.emit_struct_field("multibyte_chars", 7, |s| {
881 self.multibyte_chars.encode(s)
883 s.emit_struct_field("non_narrow_chars", 8, |s| {
884 self.non_narrow_chars.encode(s)
886 s.emit_struct_field("name_hash", 9, |s| {
887 self.name_hash.encode(s)
893 impl Decodable for SourceFile {
894 fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
896 d.read_struct("SourceFile", 8, |d| {
897 let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
898 let name_was_remapped: bool =
899 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
901 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
902 let start_pos: BytePos =
903 d.read_struct_field("start_pos", 4, |d| Decodable::decode(d))?;
904 let end_pos: BytePos = d.read_struct_field("end_pos", 5, |d| Decodable::decode(d))?;
905 let lines: Vec<BytePos> = d.read_struct_field("lines", 6, |d| {
906 let num_lines: u32 = Decodable::decode(d)?;
907 let mut lines = Vec::with_capacity(num_lines as usize);
910 // Read the number of bytes used per diff.
911 let bytes_per_diff: u8 = Decodable::decode(d)?;
913 // Read the first element.
914 let mut line_start: BytePos = Decodable::decode(d)?;
915 lines.push(line_start);
917 for _ in 1..num_lines {
918 let diff = match bytes_per_diff {
919 1 => d.read_u8()? as u32,
920 2 => d.read_u16()? as u32,
925 line_start = line_start + BytePos(diff);
927 lines.push(line_start);
933 let multibyte_chars: Vec<MultiByteChar> =
934 d.read_struct_field("multibyte_chars", 7, |d| Decodable::decode(d))?;
935 let non_narrow_chars: Vec<NonNarrowChar> =
936 d.read_struct_field("non_narrow_chars", 8, |d| Decodable::decode(d))?;
937 let name_hash: u128 =
938 d.read_struct_field("name_hash", 9, |d| Decodable::decode(d))?;
943 // `crate_of_origin` has to be set by the importer.
944 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
945 // That constant is not available here unfortunately :(
946 crate_of_origin: ::std::u32::MAX - 1,
951 external_src: Lock::new(ExternalSource::AbsentOk),
961 impl fmt::Debug for SourceFile {
962 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
963 write!(fmt, "SourceFile({})", self.name)
968 pub fn new(name: FileName,
969 name_was_remapped: bool,
970 unmapped_path: FileName,
972 start_pos: BytePos) -> SourceFile {
973 remove_bom(&mut src);
976 let mut hasher: StableHasher<u128> = StableHasher::new();
977 hasher.write(src.as_bytes());
981 let mut hasher: StableHasher<u128> = StableHasher::new();
982 name.hash(&mut hasher);
985 let end_pos = start_pos.to_usize() + src.len();
987 let (lines, multibyte_chars, non_narrow_chars) =
988 analyze_source_file::analyze_source_file(&src[..], start_pos);
993 unmapped_path: Some(unmapped_path),
995 src: Some(Lrc::new(src)),
997 external_src: Lock::new(ExternalSource::Unneeded),
999 end_pos: Pos::from_usize(end_pos),
1007 /// Return the BytePos of the beginning of the current line.
1008 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1009 let line_index = self.lookup_line(pos).unwrap();
1010 self.lines[line_index]
1013 /// Add externally loaded source.
1014 /// If the hash of the input doesn't match or no input is supplied via None,
1015 /// it is interpreted as an error and the corresponding enum variant is set.
1016 /// The return value signifies whether some kind of source is present.
1017 pub fn add_external_src<F>(&self, get_src: F) -> bool
1018 where F: FnOnce() -> Option<String>
1020 if *self.external_src.borrow() == ExternalSource::AbsentOk {
1021 let src = get_src();
1022 let mut external_src = self.external_src.borrow_mut();
1023 // Check that no-one else have provided the source while we were getting it
1024 if *external_src == ExternalSource::AbsentOk {
1025 if let Some(src) = src {
1026 let mut hasher: StableHasher<u128> = StableHasher::new();
1027 hasher.write(src.as_bytes());
1029 if hasher.finish() == self.src_hash {
1030 *external_src = ExternalSource::Present(src);
1034 *external_src = ExternalSource::AbsentErr;
1039 self.src.is_some() || external_src.get_source().is_some()
1042 self.src.is_some() || self.external_src.borrow().get_source().is_some()
1046 /// Get a line from the list of pre-computed line-beginnings.
1047 /// The line number here is 0-based.
1048 pub fn get_line(&self, line_number: usize) -> Option<Cow<str>> {
1049 fn get_until_newline(src: &str, begin: usize) -> &str {
1050 // We can't use `lines.get(line_number+1)` because we might
1051 // be parsing when we call this function and thus the current
1052 // line is the last one we have line info for.
1053 let slice = &src[begin..];
1054 match slice.find('\n') {
1055 Some(e) => &slice[..e],
1061 let line = if let Some(line) = self.lines.get(line_number) {
1066 let begin: BytePos = *line - self.start_pos;
1070 if let Some(ref src) = self.src {
1071 Some(Cow::from(get_until_newline(src, begin)))
1072 } else if let Some(src) = self.external_src.borrow().get_source() {
1073 Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1079 pub fn is_real_file(&self) -> bool {
1083 pub fn is_imported(&self) -> bool {
1087 pub fn byte_length(&self) -> u32 {
1088 self.end_pos.0 - self.start_pos.0
1090 pub fn count_lines(&self) -> usize {
1094 /// Find the line containing the given position. The return value is the
1095 /// index into the `lines` array of this SourceFile, not the 1-based line
1096 /// number. If the source_file is empty or the position is located before the
1097 /// first line, None is returned.
1098 pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1099 if self.lines.len() == 0 {
1103 let line_index = lookup_line(&self.lines[..], pos);
1104 assert!(line_index < self.lines.len() as isize);
1105 if line_index >= 0 {
1106 Some(line_index as usize)
1112 pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1113 if self.start_pos == self.end_pos {
1114 return (self.start_pos, self.end_pos);
1117 assert!(line_index < self.lines.len());
1118 if line_index == (self.lines.len() - 1) {
1119 (self.lines[line_index], self.end_pos)
1121 (self.lines[line_index], self.lines[line_index + 1])
1126 pub fn contains(&self, byte_pos: BytePos) -> bool {
1127 byte_pos >= self.start_pos && byte_pos <= self.end_pos
1131 /// Remove utf-8 BOM if any.
1132 fn remove_bom(src: &mut String) {
1133 if src.starts_with("\u{feff}") {
1138 // _____________________________________________________________________________
1139 // Pos, BytePos, CharPos
1143 fn from_usize(n: usize) -> Self;
1144 fn to_usize(&self) -> usize;
1145 fn from_u32(n: u32) -> Self;
1146 fn to_u32(&self) -> u32;
1149 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1151 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1152 pub struct BytePos(pub u32);
1154 /// A character offset. Because of multibyte utf8 characters, a byte offset
1155 /// is not equivalent to a character offset. The SourceMap will convert BytePos
1156 /// values to CharPos values as necessary.
1157 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1158 pub struct CharPos(pub usize);
1160 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
1161 // have been unsuccessful
1163 impl Pos for BytePos {
1165 fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1168 fn to_usize(&self) -> usize { self.0 as usize }
1171 fn from_u32(n: u32) -> BytePos { BytePos(n) }
1174 fn to_u32(&self) -> u32 { self.0 }
1177 impl Add for BytePos {
1178 type Output = BytePos;
1181 fn add(self, rhs: BytePos) -> BytePos {
1182 BytePos((self.to_usize() + rhs.to_usize()) as u32)
1186 impl Sub for BytePos {
1187 type Output = BytePos;
1190 fn sub(self, rhs: BytePos) -> BytePos {
1191 BytePos((self.to_usize() - rhs.to_usize()) as u32)
1195 impl Encodable for BytePos {
1196 fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1201 impl Decodable for BytePos {
1202 fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1203 Ok(BytePos(d.read_u32()?))
1207 impl Pos for CharPos {
1209 fn from_usize(n: usize) -> CharPos { CharPos(n) }
1212 fn to_usize(&self) -> usize { self.0 }
1215 fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1218 fn to_u32(&self) -> u32 { self.0 as u32}
1221 impl Add for CharPos {
1222 type Output = CharPos;
1225 fn add(self, rhs: CharPos) -> CharPos {
1226 CharPos(self.to_usize() + rhs.to_usize())
1230 impl Sub for CharPos {
1231 type Output = CharPos;
1234 fn sub(self, rhs: CharPos) -> CharPos {
1235 CharPos(self.to_usize() - rhs.to_usize())
1239 // _____________________________________________________________________________
1240 // Loc, LocWithOpt, SourceFileAndLine, SourceFileAndBytePos
1243 /// A source code location used for error reporting
1244 #[derive(Debug, Clone)]
1246 /// Information about the original source
1247 pub file: Lrc<SourceFile>,
1248 /// The (1-based) line number
1250 /// The (0-based) column offset
1252 /// The (0-based) column offset when displayed
1253 pub col_display: usize,
1256 /// A source code location used as the result of lookup_char_pos_adj
1257 // Actually, *none* of the clients use the filename *or* file field;
1258 // perhaps they should just be removed.
1260 pub struct LocWithOpt {
1261 pub filename: FileName,
1264 pub file: Option<Lrc<SourceFile>>,
1267 // used to be structural records. Better names, anyone?
1269 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1271 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1273 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1274 pub struct LineInfo {
1275 /// Index of line, starting from 0.
1276 pub line_index: usize,
1278 /// Column in line where span begins, starting from 0.
1279 pub start_col: CharPos,
1281 /// Column in line where span ends, starting from 0, exclusive.
1282 pub end_col: CharPos,
1285 pub struct FileLines {
1286 pub file: Lrc<SourceFile>,
1287 pub lines: Vec<LineInfo>
1290 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
1291 Cell::new(default_span_debug));
1294 pub struct MacroBacktrace {
1295 /// span where macro was applied to generate this code
1296 pub call_site: Span,
1298 /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1299 pub macro_decl_name: String,
1301 /// span where macro was defined (if known)
1302 pub def_site_span: Option<Span>,
1305 // _____________________________________________________________________________
1306 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1309 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1311 #[derive(Clone, PartialEq, Eq, Debug)]
1312 pub enum SpanLinesError {
1313 IllFormedSpan(Span),
1314 DistinctSources(DistinctSources),
1317 #[derive(Clone, PartialEq, Eq, Debug)]
1318 pub enum SpanSnippetError {
1319 IllFormedSpan(Span),
1320 DistinctSources(DistinctSources),
1321 MalformedForSourcemap(MalformedSourceMapPositions),
1322 SourceNotAvailable { filename: FileName }
1325 #[derive(Clone, PartialEq, Eq, Debug)]
1326 pub struct DistinctSources {
1327 pub begin: (FileName, BytePos),
1328 pub end: (FileName, BytePos)
1331 #[derive(Clone, PartialEq, Eq, Debug)]
1332 pub struct MalformedSourceMapPositions {
1334 pub source_len: usize,
1335 pub begin_pos: BytePos,
1336 pub end_pos: BytePos
1339 // Given a slice of line start positions and a position, returns the index of
1340 // the line the position is on. Returns -1 if the position is located before
1342 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1343 match lines.binary_search(&pos) {
1344 Ok(line) => line as isize,
1345 Err(line) => line as isize - 1
1351 use super::{lookup_line, BytePos};
1354 fn test_lookup_line() {
1356 let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1358 assert_eq!(lookup_line(lines, BytePos(0)), -1);
1359 assert_eq!(lookup_line(lines, BytePos(3)), 0);
1360 assert_eq!(lookup_line(lines, BytePos(4)), 0);
1362 assert_eq!(lookup_line(lines, BytePos(16)), 0);
1363 assert_eq!(lookup_line(lines, BytePos(17)), 1);
1364 assert_eq!(lookup_line(lines, BytePos(18)), 1);
1366 assert_eq!(lookup_line(lines, BytePos(28)), 2);
1367 assert_eq!(lookup_line(lines, BytePos(29)), 2);