]> git.lizzy.rs Git - rust.git/blob - src/librustc_span/lib.rs
Auto merge of #69474 - Dylan-DPC:rollup-ciotplu, r=Dylan-DPC
[rust.git] / src / librustc_span / lib.rs
1 //! The source positions and related helper functions.
2 //!
3 //! ## Note
4 //!
5 //! This API is completely unstable and subject to change.
6
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
8 #![feature(crate_visibility_modifier)]
9 #![feature(nll)]
10 #![feature(optin_builtin_traits)]
11 #![feature(specialization)]
12
13 use rustc_data_structures::AtomicRef;
14 use rustc_macros::HashStable_Generic;
15 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
16
17 mod caching_source_map_view;
18 pub mod source_map;
19 pub use self::caching_source_map_view::CachingSourceMapView;
20
21 pub mod edition;
22 use edition::Edition;
23 pub mod hygiene;
24 use hygiene::Transparency;
25 pub use hygiene::{DesugaringKind, ExpnData, ExpnId, ExpnKind, MacroKind, SyntaxContext};
26 pub mod def_id;
27 use def_id::DefId;
28 mod span_encoding;
29 pub use span_encoding::{Span, DUMMY_SP};
30
31 pub mod symbol;
32 pub use symbol::{sym, Symbol};
33
34 mod analyze_source_file;
35 pub mod fatal_error;
36
37 use rustc_data_structures::fingerprint::Fingerprint;
38 use rustc_data_structures::fx::FxHashMap;
39 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
40 use rustc_data_structures::sync::{Lock, Lrc};
41
42 use std::borrow::Cow;
43 use std::cell::RefCell;
44 use std::cmp::{self, Ordering};
45 use std::fmt;
46 use std::hash::{Hash, Hasher};
47 use std::ops::{Add, Sub};
48 use std::path::PathBuf;
49
50 #[cfg(test)]
51 mod tests;
52
53 pub struct Globals {
54     symbol_interner: Lock<symbol::Interner>,
55     span_interner: Lock<span_encoding::SpanInterner>,
56     hygiene_data: Lock<hygiene::HygieneData>,
57 }
58
59 impl Globals {
60     pub fn new(edition: Edition) -> Globals {
61         Globals {
62             symbol_interner: Lock::new(symbol::Interner::fresh()),
63             span_interner: Lock::new(span_encoding::SpanInterner::default()),
64             hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
65         }
66     }
67 }
68
69 scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
70
71 /// Differentiates between real files and common virtual files.
72 #[derive(
73     Debug,
74     Eq,
75     PartialEq,
76     Clone,
77     Ord,
78     PartialOrd,
79     Hash,
80     RustcDecodable,
81     RustcEncodable,
82     HashStable_Generic
83 )]
84 pub enum FileName {
85     Real(PathBuf),
86     /// A macro. This includes the full name of the macro, so that there are no clashes.
87     Macros(String),
88     /// Call to `quote!`.
89     QuoteExpansion(u64),
90     /// Command line.
91     Anon(u64),
92     /// Hack in `src/libsyntax/parse.rs`.
93     // FIXME(jseyfried)
94     MacroExpansion(u64),
95     ProcMacroSourceCode(u64),
96     /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
97     CfgSpec(u64),
98     /// Strings provided as crate attributes in the CLI.
99     CliCrateAttr(u64),
100     /// Custom sources for explicit parser calls from plugins and drivers.
101     Custom(String),
102     DocTest(PathBuf, isize),
103 }
104
105 impl std::fmt::Display for FileName {
106     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107         use FileName::*;
108         match *self {
109             Real(ref path) => write!(fmt, "{}", path.display()),
110             Macros(ref name) => write!(fmt, "<{} macros>", name),
111             QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
112             MacroExpansion(_) => write!(fmt, "<macro expansion>"),
113             Anon(_) => write!(fmt, "<anon>"),
114             ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
115             CfgSpec(_) => write!(fmt, "<cfgspec>"),
116             CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
117             Custom(ref s) => write!(fmt, "<{}>", s),
118             DocTest(ref path, _) => write!(fmt, "{}", path.display()),
119         }
120     }
121 }
122
123 impl From<PathBuf> for FileName {
124     fn from(p: PathBuf) -> Self {
125         assert!(!p.to_string_lossy().ends_with('>'));
126         FileName::Real(p)
127     }
128 }
129
130 impl FileName {
131     pub fn is_real(&self) -> bool {
132         use FileName::*;
133         match *self {
134             Real(_) => true,
135             Macros(_)
136             | Anon(_)
137             | MacroExpansion(_)
138             | ProcMacroSourceCode(_)
139             | CfgSpec(_)
140             | CliCrateAttr(_)
141             | Custom(_)
142             | QuoteExpansion(_)
143             | DocTest(_, _) => false,
144         }
145     }
146
147     pub fn is_macros(&self) -> bool {
148         use FileName::*;
149         match *self {
150             Real(_)
151             | Anon(_)
152             | MacroExpansion(_)
153             | ProcMacroSourceCode(_)
154             | CfgSpec(_)
155             | CliCrateAttr(_)
156             | Custom(_)
157             | QuoteExpansion(_)
158             | DocTest(_, _) => false,
159             Macros(_) => true,
160         }
161     }
162
163     pub fn quote_expansion_source_code(src: &str) -> FileName {
164         let mut hasher = StableHasher::new();
165         src.hash(&mut hasher);
166         FileName::QuoteExpansion(hasher.finish())
167     }
168
169     pub fn macro_expansion_source_code(src: &str) -> FileName {
170         let mut hasher = StableHasher::new();
171         src.hash(&mut hasher);
172         FileName::MacroExpansion(hasher.finish())
173     }
174
175     pub fn anon_source_code(src: &str) -> FileName {
176         let mut hasher = StableHasher::new();
177         src.hash(&mut hasher);
178         FileName::Anon(hasher.finish())
179     }
180
181     pub fn proc_macro_source_code(src: &str) -> FileName {
182         let mut hasher = StableHasher::new();
183         src.hash(&mut hasher);
184         FileName::ProcMacroSourceCode(hasher.finish())
185     }
186
187     pub fn cfg_spec_source_code(src: &str) -> FileName {
188         let mut hasher = StableHasher::new();
189         src.hash(&mut hasher);
190         FileName::QuoteExpansion(hasher.finish())
191     }
192
193     pub fn cli_crate_attr_source_code(src: &str) -> FileName {
194         let mut hasher = StableHasher::new();
195         src.hash(&mut hasher);
196         FileName::CliCrateAttr(hasher.finish())
197     }
198
199     pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
200         FileName::DocTest(path, line)
201     }
202 }
203
204 /// Spans represent a region of code, used for error reporting. Positions in spans
205 /// are *absolute* positions from the beginning of the source_map, not positions
206 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
207 /// to the original source.
208 /// You must be careful if the span crosses more than one file - you will not be
209 /// able to use many of the functions on spans in source_map and you cannot assume
210 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
211 /// range between files.
212 ///
213 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
214 /// sent to other threads, but some pieces of performance infra run in a separate thread.
215 /// Using `Span` is generally preferred.
216 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
217 pub struct SpanData {
218     pub lo: BytePos,
219     pub hi: BytePos,
220     /// Information about where the macro came from, if this piece of
221     /// code was created by a macro expansion.
222     pub ctxt: SyntaxContext,
223 }
224
225 impl SpanData {
226     #[inline]
227     pub fn with_lo(&self, lo: BytePos) -> Span {
228         Span::new(lo, self.hi, self.ctxt)
229     }
230     #[inline]
231     pub fn with_hi(&self, hi: BytePos) -> Span {
232         Span::new(self.lo, hi, self.ctxt)
233     }
234     #[inline]
235     pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
236         Span::new(self.lo, self.hi, ctxt)
237     }
238 }
239
240 // The interner is pointed to by a thread local value which is only set on the main thread
241 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
242 // to avoid panics and other errors, even though it would be memory safe to do so.
243 #[cfg(not(parallel_compiler))]
244 impl !Send for Span {}
245 #[cfg(not(parallel_compiler))]
246 impl !Sync for Span {}
247
248 impl PartialOrd for Span {
249     fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
250         PartialOrd::partial_cmp(&self.data(), &rhs.data())
251     }
252 }
253 impl Ord for Span {
254     fn cmp(&self, rhs: &Self) -> Ordering {
255         Ord::cmp(&self.data(), &rhs.data())
256     }
257 }
258
259 /// A collection of spans. Spans have two orthogonal attributes:
260 ///
261 /// - They can be *primary spans*. In this case they are the locus of
262 ///   the error, and would be rendered with `^^^`.
263 /// - They can have a *label*. In this case, the label is written next
264 ///   to the mark in the snippet when we render.
265 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
266 pub struct MultiSpan {
267     primary_spans: Vec<Span>,
268     span_labels: Vec<(Span, String)>,
269 }
270
271 impl Span {
272     #[inline]
273     pub fn lo(self) -> BytePos {
274         self.data().lo
275     }
276     #[inline]
277     pub fn with_lo(self, lo: BytePos) -> Span {
278         self.data().with_lo(lo)
279     }
280     #[inline]
281     pub fn hi(self) -> BytePos {
282         self.data().hi
283     }
284     #[inline]
285     pub fn with_hi(self, hi: BytePos) -> Span {
286         self.data().with_hi(hi)
287     }
288     #[inline]
289     pub fn ctxt(self) -> SyntaxContext {
290         self.data().ctxt
291     }
292     #[inline]
293     pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
294         self.data().with_ctxt(ctxt)
295     }
296
297     /// Returns `true` if this is a dummy span with any hygienic context.
298     #[inline]
299     pub fn is_dummy(self) -> bool {
300         let span = self.data();
301         span.lo.0 == 0 && span.hi.0 == 0
302     }
303
304     /// Returns `true` if this span comes from a macro or desugaring.
305     #[inline]
306     pub fn from_expansion(self) -> bool {
307         self.ctxt() != SyntaxContext::root()
308     }
309
310     /// Returns `true` if `span` originates in a derive-macro's expansion.
311     pub fn in_derive_expansion(self) -> bool {
312         matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
313     }
314
315     #[inline]
316     pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
317         Span::new(lo, hi, SyntaxContext::root())
318     }
319
320     /// Returns a new span representing an empty span at the beginning of this span
321     #[inline]
322     pub fn shrink_to_lo(self) -> Span {
323         let span = self.data();
324         span.with_hi(span.lo)
325     }
326     /// Returns a new span representing an empty span at the end of this span.
327     #[inline]
328     pub fn shrink_to_hi(self) -> Span {
329         let span = self.data();
330         span.with_lo(span.hi)
331     }
332
333     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
334     pub fn substitute_dummy(self, other: Span) -> Span {
335         if self.is_dummy() { other } else { self }
336     }
337
338     /// Returns `true` if `self` fully encloses `other`.
339     pub fn contains(self, other: Span) -> bool {
340         let span = self.data();
341         let other = other.data();
342         span.lo <= other.lo && other.hi <= span.hi
343     }
344
345     /// Returns `true` if `self` touches `other`.
346     pub fn overlaps(self, other: Span) -> bool {
347         let span = self.data();
348         let other = other.data();
349         span.lo < other.hi && other.lo < span.hi
350     }
351
352     /// Returns `true` if the spans are equal with regards to the source text.
353     ///
354     /// Use this instead of `==` when either span could be generated code,
355     /// and you only care that they point to the same bytes of source text.
356     pub fn source_equal(&self, other: &Span) -> bool {
357         let span = self.data();
358         let other = other.data();
359         span.lo == other.lo && span.hi == other.hi
360     }
361
362     /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
363     pub fn trim_start(self, other: Span) -> Option<Span> {
364         let span = self.data();
365         let other = other.data();
366         if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
367     }
368
369     /// Returns the source span -- this is either the supplied span, or the span for
370     /// the macro callsite that expanded to it.
371     pub fn source_callsite(self) -> Span {
372         let expn_data = self.ctxt().outer_expn_data();
373         if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self }
374     }
375
376     /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
377     /// if any.
378     pub fn parent(self) -> Option<Span> {
379         let expn_data = self.ctxt().outer_expn_data();
380         if !expn_data.is_root() { Some(expn_data.call_site) } else { None }
381     }
382
383     /// Edition of the crate from which this span came.
384     pub fn edition(self) -> edition::Edition {
385         self.ctxt().outer_expn_data().edition
386     }
387
388     #[inline]
389     pub fn rust_2015(&self) -> bool {
390         self.edition() == edition::Edition::Edition2015
391     }
392
393     #[inline]
394     pub fn rust_2018(&self) -> bool {
395         self.edition() >= edition::Edition::Edition2018
396     }
397
398     /// Returns the source callee.
399     ///
400     /// Returns `None` if the supplied span has no expansion trace,
401     /// else returns the `ExpnData` for the macro definition
402     /// corresponding to the source callsite.
403     pub fn source_callee(self) -> Option<ExpnData> {
404         fn source_callee(expn_data: ExpnData) -> ExpnData {
405             let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
406             if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
407         }
408         let expn_data = self.ctxt().outer_expn_data();
409         if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }
410     }
411
412     /// Checks if a span is "internal" to a macro in which `#[unstable]`
413     /// items can be used (that is, a macro marked with
414     /// `#[allow_internal_unstable]`).
415     pub fn allows_unstable(&self, feature: Symbol) -> bool {
416         self.ctxt().outer_expn_data().allow_internal_unstable.map_or(false, |features| {
417             features
418                 .iter()
419                 .any(|&f| f == feature || f == sym::allow_internal_unstable_backcompat_hack)
420         })
421     }
422
423     /// Checks if this span arises from a compiler desugaring of kind `kind`.
424     pub fn is_desugaring(&self, kind: DesugaringKind) -> bool {
425         match self.ctxt().outer_expn_data().kind {
426             ExpnKind::Desugaring(k) => k == kind,
427             _ => false,
428         }
429     }
430
431     /// Returns the compiler desugaring that created this span, or `None`
432     /// if this span is not from a desugaring.
433     pub fn desugaring_kind(&self) -> Option<DesugaringKind> {
434         match self.ctxt().outer_expn_data().kind {
435             ExpnKind::Desugaring(k) => Some(k),
436             _ => None,
437         }
438     }
439
440     /// Checks if a span is "internal" to a macro in which `unsafe`
441     /// can be used without triggering the `unsafe_code` lint
442     //  (that is, a macro marked with `#[allow_internal_unsafe]`).
443     pub fn allows_unsafe(&self) -> bool {
444         self.ctxt().outer_expn_data().allow_internal_unsafe
445     }
446
447     pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
448         let mut prev_span = DUMMY_SP;
449         std::iter::from_fn(move || {
450             loop {
451                 let expn_data = self.ctxt().outer_expn_data();
452                 if expn_data.is_root() {
453                     return None;
454                 }
455
456                 let is_recursive = expn_data.call_site.source_equal(&prev_span);
457
458                 prev_span = self;
459                 self = expn_data.call_site;
460
461                 // Don't print recursive invocations.
462                 if !is_recursive {
463                     return Some(expn_data);
464                 }
465             }
466         })
467     }
468
469     /// Returns a `Span` that would enclose both `self` and `end`.
470     pub fn to(self, end: Span) -> Span {
471         let span_data = self.data();
472         let end_data = end.data();
473         // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
474         // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
475         // have an incomplete span than a completely nonsensical one.
476         if span_data.ctxt != end_data.ctxt {
477             if span_data.ctxt == SyntaxContext::root() {
478                 return end;
479             } else if end_data.ctxt == SyntaxContext::root() {
480                 return self;
481             }
482             // Both spans fall within a macro.
483             // FIXME(estebank): check if it is the *same* macro.
484         }
485         Span::new(
486             cmp::min(span_data.lo, end_data.lo),
487             cmp::max(span_data.hi, end_data.hi),
488             if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt },
489         )
490     }
491
492     /// Returns a `Span` between the end of `self` to the beginning of `end`.
493     pub fn between(self, end: Span) -> Span {
494         let span = self.data();
495         let end = end.data();
496         Span::new(
497             span.hi,
498             end.lo,
499             if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
500         )
501     }
502
503     /// Returns a `Span` between the beginning of `self` to the beginning of `end`.
504     pub fn until(self, end: Span) -> Span {
505         let span = self.data();
506         let end = end.data();
507         Span::new(
508             span.lo,
509             end.lo,
510             if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt },
511         )
512     }
513
514     pub fn from_inner(self, inner: InnerSpan) -> Span {
515         let span = self.data();
516         Span::new(
517             span.lo + BytePos::from_usize(inner.start),
518             span.lo + BytePos::from_usize(inner.end),
519             span.ctxt,
520         )
521     }
522
523     /// Equivalent of `Span::def_site` from the proc macro API,
524     /// except that the location is taken from the `self` span.
525     pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
526         self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
527     }
528
529     /// Equivalent of `Span::call_site` from the proc macro API,
530     /// except that the location is taken from the `self` span.
531     pub fn with_call_site_ctxt(&self, expn_id: ExpnId) -> Span {
532         self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
533     }
534
535     /// Equivalent of `Span::mixed_site` from the proc macro API,
536     /// except that the location is taken from the `self` span.
537     pub fn with_mixed_site_ctxt(&self, expn_id: ExpnId) -> Span {
538         self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent)
539     }
540
541     /// Produces a span with the same location as `self` and context produced by a macro with the
542     /// given ID and transparency, assuming that macro was defined directly and not produced by
543     /// some other macro (which is the case for built-in and procedural macros).
544     pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
545         self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
546     }
547
548     #[inline]
549     pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
550         let span = self.data();
551         span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency))
552     }
553
554     #[inline]
555     pub fn remove_mark(&mut self) -> ExpnId {
556         let mut span = self.data();
557         let mark = span.ctxt.remove_mark();
558         *self = Span::new(span.lo, span.hi, span.ctxt);
559         mark
560     }
561
562     #[inline]
563     pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
564         let mut span = self.data();
565         let mark = span.ctxt.adjust(expn_id);
566         *self = Span::new(span.lo, span.hi, span.ctxt);
567         mark
568     }
569
570     #[inline]
571     pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
572         let mut span = self.data();
573         let mark = span.ctxt.modernize_and_adjust(expn_id);
574         *self = Span::new(span.lo, span.hi, span.ctxt);
575         mark
576     }
577
578     #[inline]
579     pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
580         let mut span = self.data();
581         let mark = span.ctxt.glob_adjust(expn_id, glob_span);
582         *self = Span::new(span.lo, span.hi, span.ctxt);
583         mark
584     }
585
586     #[inline]
587     pub fn reverse_glob_adjust(
588         &mut self,
589         expn_id: ExpnId,
590         glob_span: Span,
591     ) -> Option<Option<ExpnId>> {
592         let mut span = self.data();
593         let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span);
594         *self = Span::new(span.lo, span.hi, span.ctxt);
595         mark
596     }
597
598     #[inline]
599     pub fn modern(self) -> Span {
600         let span = self.data();
601         span.with_ctxt(span.ctxt.modern())
602     }
603
604     #[inline]
605     pub fn modern_and_legacy(self) -> Span {
606         let span = self.data();
607         span.with_ctxt(span.ctxt.modern_and_legacy())
608     }
609 }
610
611 #[derive(Clone, Debug)]
612 pub struct SpanLabel {
613     /// The span we are going to include in the final snippet.
614     pub span: Span,
615
616     /// Is this a primary span? This is the "locus" of the message,
617     /// and is indicated with a `^^^^` underline, versus `----`.
618     pub is_primary: bool,
619
620     /// What label should we attach to this span (if any)?
621     pub label: Option<String>,
622 }
623
624 impl Default for Span {
625     fn default() -> Self {
626         DUMMY_SP
627     }
628 }
629
630 impl rustc_serialize::UseSpecializedEncodable for Span {
631     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
632         let span = self.data();
633         s.emit_struct("Span", 2, |s| {
634             s.emit_struct_field("lo", 0, |s| span.lo.encode(s))?;
635
636             s.emit_struct_field("hi", 1, |s| span.hi.encode(s))
637         })
638     }
639 }
640
641 impl rustc_serialize::UseSpecializedDecodable for Span {
642     fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
643         d.read_struct("Span", 2, |d| {
644             let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
645             let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
646             Ok(Span::with_root_ctxt(lo, hi))
647         })
648     }
649 }
650
651 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
652     f.debug_struct("Span")
653         .field("lo", &span.lo())
654         .field("hi", &span.hi())
655         .field("ctxt", &span.ctxt())
656         .finish()
657 }
658
659 impl fmt::Debug for Span {
660     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661         (*SPAN_DEBUG)(*self, f)
662     }
663 }
664
665 impl fmt::Debug for SpanData {
666     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
667         (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt), f)
668     }
669 }
670
671 impl MultiSpan {
672     #[inline]
673     pub fn new() -> MultiSpan {
674         MultiSpan { primary_spans: vec![], span_labels: vec![] }
675     }
676
677     pub fn from_span(primary_span: Span) -> MultiSpan {
678         MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
679     }
680
681     pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
682         MultiSpan { primary_spans: vec, span_labels: vec![] }
683     }
684
685     pub fn push_span_label(&mut self, span: Span, label: String) {
686         self.span_labels.push((span, label));
687     }
688
689     /// Selects the first primary span (if any).
690     pub fn primary_span(&self) -> Option<Span> {
691         self.primary_spans.first().cloned()
692     }
693
694     /// Returns all primary spans.
695     pub fn primary_spans(&self) -> &[Span] {
696         &self.primary_spans
697     }
698
699     /// Returns `true` if any of the primary spans are displayable.
700     pub fn has_primary_spans(&self) -> bool {
701         self.primary_spans.iter().any(|sp| !sp.is_dummy())
702     }
703
704     /// Returns `true` if this contains only a dummy primary span with any hygienic context.
705     pub fn is_dummy(&self) -> bool {
706         let mut is_dummy = true;
707         for span in &self.primary_spans {
708             if !span.is_dummy() {
709                 is_dummy = false;
710             }
711         }
712         is_dummy
713     }
714
715     /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
716     /// display well (like std macros). Returns whether replacements occurred.
717     pub fn replace(&mut self, before: Span, after: Span) -> bool {
718         let mut replacements_occurred = false;
719         for primary_span in &mut self.primary_spans {
720             if *primary_span == before {
721                 *primary_span = after;
722                 replacements_occurred = true;
723             }
724         }
725         for span_label in &mut self.span_labels {
726             if span_label.0 == before {
727                 span_label.0 = after;
728                 replacements_occurred = true;
729             }
730         }
731         replacements_occurred
732     }
733
734     /// Returns the strings to highlight. We always ensure that there
735     /// is an entry for each of the primary spans -- for each primary
736     /// span `P`, if there is at least one label with span `P`, we return
737     /// those labels (marked as primary). But otherwise we return
738     /// `SpanLabel` instances with empty labels.
739     pub fn span_labels(&self) -> Vec<SpanLabel> {
740         let is_primary = |span| self.primary_spans.contains(&span);
741
742         let mut span_labels = self
743             .span_labels
744             .iter()
745             .map(|&(span, ref label)| SpanLabel {
746                 span,
747                 is_primary: is_primary(span),
748                 label: Some(label.clone()),
749             })
750             .collect::<Vec<_>>();
751
752         for &span in &self.primary_spans {
753             if !span_labels.iter().any(|sl| sl.span == span) {
754                 span_labels.push(SpanLabel { span, is_primary: true, label: None });
755             }
756         }
757
758         span_labels
759     }
760
761     /// Returns `true` if any of the span labels is displayable.
762     pub fn has_span_labels(&self) -> bool {
763         self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
764     }
765 }
766
767 impl From<Span> for MultiSpan {
768     fn from(span: Span) -> MultiSpan {
769         MultiSpan::from_span(span)
770     }
771 }
772
773 impl From<Vec<Span>> for MultiSpan {
774     fn from(spans: Vec<Span>) -> MultiSpan {
775         MultiSpan::from_spans(spans)
776     }
777 }
778
779 /// Identifies an offset of a multi-byte character in a `SourceFile`.
780 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
781 pub struct MultiByteChar {
782     /// The absolute offset of the character in the `SourceMap`.
783     pub pos: BytePos,
784     /// The number of bytes, `>= 2`.
785     pub bytes: u8,
786 }
787
788 /// Identifies an offset of a non-narrow character in a `SourceFile`.
789 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
790 pub enum NonNarrowChar {
791     /// Represents a zero-width character.
792     ZeroWidth(BytePos),
793     /// Represents a wide (full-width) character.
794     Wide(BytePos),
795     /// Represents a tab character, represented visually with a width of 4 characters.
796     Tab(BytePos),
797 }
798
799 impl NonNarrowChar {
800     fn new(pos: BytePos, width: usize) -> Self {
801         match width {
802             0 => NonNarrowChar::ZeroWidth(pos),
803             2 => NonNarrowChar::Wide(pos),
804             4 => NonNarrowChar::Tab(pos),
805             _ => panic!("width {} given for non-narrow character", width),
806         }
807     }
808
809     /// Returns the absolute offset of the character in the `SourceMap`.
810     pub fn pos(&self) -> BytePos {
811         match *self {
812             NonNarrowChar::ZeroWidth(p) | NonNarrowChar::Wide(p) | NonNarrowChar::Tab(p) => p,
813         }
814     }
815
816     /// Returns the width of the character, 0 (zero-width) or 2 (wide).
817     pub fn width(&self) -> usize {
818         match *self {
819             NonNarrowChar::ZeroWidth(_) => 0,
820             NonNarrowChar::Wide(_) => 2,
821             NonNarrowChar::Tab(_) => 4,
822         }
823     }
824 }
825
826 impl Add<BytePos> for NonNarrowChar {
827     type Output = Self;
828
829     fn add(self, rhs: BytePos) -> Self {
830         match self {
831             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
832             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
833             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
834         }
835     }
836 }
837
838 impl Sub<BytePos> for NonNarrowChar {
839     type Output = Self;
840
841     fn sub(self, rhs: BytePos) -> Self {
842         match self {
843             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
844             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
845             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
846         }
847     }
848 }
849
850 /// Identifies an offset of a character that was normalized away from `SourceFile`.
851 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
852 pub struct NormalizedPos {
853     /// The absolute offset of the character in the `SourceMap`.
854     pub pos: BytePos,
855     /// The difference between original and normalized string at position.
856     pub diff: u32,
857 }
858
859 /// The state of the lazy external source loading mechanism of a `SourceFile`.
860 #[derive(PartialEq, Eq, Clone)]
861 pub enum ExternalSource {
862     /// The external source has been loaded already.
863     Present(String),
864     /// No attempt has been made to load the external source.
865     AbsentOk,
866     /// A failed attempt has been made to load the external source.
867     AbsentErr,
868     /// No external source has to be loaded, since the `SourceFile` represents a local crate.
869     Unneeded,
870 }
871
872 impl ExternalSource {
873     pub fn is_absent(&self) -> bool {
874         match *self {
875             ExternalSource::Present(_) => false,
876             _ => true,
877         }
878     }
879
880     pub fn get_source(&self) -> Option<&str> {
881         match *self {
882             ExternalSource::Present(ref src) => Some(src),
883             _ => None,
884         }
885     }
886 }
887
888 #[derive(Debug)]
889 pub struct OffsetOverflowError;
890
891 /// A single source in the `SourceMap`.
892 #[derive(Clone)]
893 pub struct SourceFile {
894     /// The name of the file that the source came from. Source that doesn't
895     /// originate from files has names between angle brackets by convention
896     /// (e.g., `<anon>`).
897     pub name: FileName,
898     /// `true` if the `name` field above has been modified by `--remap-path-prefix`.
899     pub name_was_remapped: bool,
900     /// The unmapped path of the file that the source came from.
901     /// Set to `None` if the `SourceFile` was imported from an external crate.
902     pub unmapped_path: Option<FileName>,
903     /// Indicates which crate this `SourceFile` was imported from.
904     pub crate_of_origin: u32,
905     /// The complete source code.
906     pub src: Option<Lrc<String>>,
907     /// The source code's hash.
908     pub src_hash: u128,
909     /// The external source code (used for external crates, which will have a `None`
910     /// value as `self.src`.
911     pub external_src: Lock<ExternalSource>,
912     /// The start position of this source in the `SourceMap`.
913     pub start_pos: BytePos,
914     /// The end position of this source in the `SourceMap`.
915     pub end_pos: BytePos,
916     /// Locations of lines beginnings in the source code.
917     pub lines: Vec<BytePos>,
918     /// Locations of multi-byte characters in the source code.
919     pub multibyte_chars: Vec<MultiByteChar>,
920     /// Width of characters that are not narrow in the source code.
921     pub non_narrow_chars: Vec<NonNarrowChar>,
922     /// Locations of characters removed during normalization.
923     pub normalized_pos: Vec<NormalizedPos>,
924     /// A hash of the filename, used for speeding up hashing in incremental compilation.
925     pub name_hash: u128,
926 }
927
928 impl Encodable for SourceFile {
929     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
930         s.emit_struct("SourceFile", 8, |s| {
931             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
932             s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
933             s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
934             s.emit_struct_field("start_pos", 3, |s| self.start_pos.encode(s))?;
935             s.emit_struct_field("end_pos", 4, |s| self.end_pos.encode(s))?;
936             s.emit_struct_field("lines", 5, |s| {
937                 let lines = &self.lines[..];
938                 // Store the length.
939                 s.emit_u32(lines.len() as u32)?;
940
941                 if !lines.is_empty() {
942                     // In order to preserve some space, we exploit the fact that
943                     // the lines list is sorted and individual lines are
944                     // probably not that long. Because of that we can store lines
945                     // as a difference list, using as little space as possible
946                     // for the differences.
947                     let max_line_length = if lines.len() == 1 {
948                         0
949                     } else {
950                         lines.windows(2).map(|w| w[1] - w[0]).map(|bp| bp.to_usize()).max().unwrap()
951                     };
952
953                     let bytes_per_diff: u8 = match max_line_length {
954                         0..=0xFF => 1,
955                         0x100..=0xFFFF => 2,
956                         _ => 4,
957                     };
958
959                     // Encode the number of bytes used per diff.
960                     bytes_per_diff.encode(s)?;
961
962                     // Encode the first element.
963                     lines[0].encode(s)?;
964
965                     let diff_iter = (&lines[..]).windows(2).map(|w| (w[1] - w[0]));
966
967                     match bytes_per_diff {
968                         1 => {
969                             for diff in diff_iter {
970                                 (diff.0 as u8).encode(s)?
971                             }
972                         }
973                         2 => {
974                             for diff in diff_iter {
975                                 (diff.0 as u16).encode(s)?
976                             }
977                         }
978                         4 => {
979                             for diff in diff_iter {
980                                 diff.0.encode(s)?
981                             }
982                         }
983                         _ => unreachable!(),
984                     }
985                 }
986
987                 Ok(())
988             })?;
989             s.emit_struct_field("multibyte_chars", 6, |s| self.multibyte_chars.encode(s))?;
990             s.emit_struct_field("non_narrow_chars", 7, |s| self.non_narrow_chars.encode(s))?;
991             s.emit_struct_field("name_hash", 8, |s| self.name_hash.encode(s))?;
992             s.emit_struct_field("normalized_pos", 9, |s| self.normalized_pos.encode(s))
993         })
994     }
995 }
996
997 impl Decodable for SourceFile {
998     fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
999         d.read_struct("SourceFile", 8, |d| {
1000             let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
1001             let name_was_remapped: bool =
1002                 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
1003             let src_hash: u128 = d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
1004             let start_pos: BytePos =
1005                 d.read_struct_field("start_pos", 3, |d| Decodable::decode(d))?;
1006             let end_pos: BytePos = d.read_struct_field("end_pos", 4, |d| Decodable::decode(d))?;
1007             let lines: Vec<BytePos> = d.read_struct_field("lines", 5, |d| {
1008                 let num_lines: u32 = Decodable::decode(d)?;
1009                 let mut lines = Vec::with_capacity(num_lines as usize);
1010
1011                 if num_lines > 0 {
1012                     // Read the number of bytes used per diff.
1013                     let bytes_per_diff: u8 = Decodable::decode(d)?;
1014
1015                     // Read the first element.
1016                     let mut line_start: BytePos = Decodable::decode(d)?;
1017                     lines.push(line_start);
1018
1019                     for _ in 1..num_lines {
1020                         let diff = match bytes_per_diff {
1021                             1 => d.read_u8()? as u32,
1022                             2 => d.read_u16()? as u32,
1023                             4 => d.read_u32()?,
1024                             _ => unreachable!(),
1025                         };
1026
1027                         line_start = line_start + BytePos(diff);
1028
1029                         lines.push(line_start);
1030                     }
1031                 }
1032
1033                 Ok(lines)
1034             })?;
1035             let multibyte_chars: Vec<MultiByteChar> =
1036                 d.read_struct_field("multibyte_chars", 6, |d| Decodable::decode(d))?;
1037             let non_narrow_chars: Vec<NonNarrowChar> =
1038                 d.read_struct_field("non_narrow_chars", 7, |d| Decodable::decode(d))?;
1039             let name_hash: u128 = d.read_struct_field("name_hash", 8, |d| Decodable::decode(d))?;
1040             let normalized_pos: Vec<NormalizedPos> =
1041                 d.read_struct_field("normalized_pos", 9, |d| Decodable::decode(d))?;
1042             Ok(SourceFile {
1043                 name,
1044                 name_was_remapped,
1045                 unmapped_path: None,
1046                 // `crate_of_origin` has to be set by the importer.
1047                 // This value matches up with `rustc_hir::def_id::INVALID_CRATE`.
1048                 // That constant is not available here, unfortunately.
1049                 crate_of_origin: std::u32::MAX - 1,
1050                 start_pos,
1051                 end_pos,
1052                 src: None,
1053                 src_hash,
1054                 external_src: Lock::new(ExternalSource::AbsentOk),
1055                 lines,
1056                 multibyte_chars,
1057                 non_narrow_chars,
1058                 normalized_pos,
1059                 name_hash,
1060             })
1061         })
1062     }
1063 }
1064
1065 impl fmt::Debug for SourceFile {
1066     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1067         write!(fmt, "SourceFile({})", self.name)
1068     }
1069 }
1070
1071 impl SourceFile {
1072     pub fn new(
1073         name: FileName,
1074         name_was_remapped: bool,
1075         unmapped_path: FileName,
1076         mut src: String,
1077         start_pos: BytePos,
1078     ) -> Self {
1079         let normalized_pos = normalize_src(&mut src, start_pos);
1080
1081         let src_hash = {
1082             let mut hasher: StableHasher = StableHasher::new();
1083             hasher.write(src.as_bytes());
1084             hasher.finish::<u128>()
1085         };
1086         let name_hash = {
1087             let mut hasher: StableHasher = StableHasher::new();
1088             name.hash(&mut hasher);
1089             hasher.finish::<u128>()
1090         };
1091         let end_pos = start_pos.to_usize() + src.len();
1092         assert!(end_pos <= u32::max_value() as usize);
1093
1094         let (lines, multibyte_chars, non_narrow_chars) =
1095             analyze_source_file::analyze_source_file(&src[..], start_pos);
1096
1097         SourceFile {
1098             name,
1099             name_was_remapped,
1100             unmapped_path: Some(unmapped_path),
1101             crate_of_origin: 0,
1102             src: Some(Lrc::new(src)),
1103             src_hash,
1104             external_src: Lock::new(ExternalSource::Unneeded),
1105             start_pos,
1106             end_pos: Pos::from_usize(end_pos),
1107             lines,
1108             multibyte_chars,
1109             non_narrow_chars,
1110             normalized_pos,
1111             name_hash,
1112         }
1113     }
1114
1115     /// Returns the `BytePos` of the beginning of the current line.
1116     pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1117         let line_index = self.lookup_line(pos).unwrap();
1118         self.lines[line_index]
1119     }
1120
1121     /// Add externally loaded source.
1122     /// If the hash of the input doesn't match or no input is supplied via None,
1123     /// it is interpreted as an error and the corresponding enum variant is set.
1124     /// The return value signifies whether some kind of source is present.
1125     pub fn add_external_src<F>(&self, get_src: F) -> bool
1126     where
1127         F: FnOnce() -> Option<String>,
1128     {
1129         if *self.external_src.borrow() == ExternalSource::AbsentOk {
1130             let src = get_src();
1131             let mut external_src = self.external_src.borrow_mut();
1132             // Check that no-one else have provided the source while we were getting it
1133             if *external_src == ExternalSource::AbsentOk {
1134                 if let Some(src) = src {
1135                     let mut hasher: StableHasher = StableHasher::new();
1136                     hasher.write(src.as_bytes());
1137
1138                     if hasher.finish::<u128>() == self.src_hash {
1139                         *external_src = ExternalSource::Present(src);
1140                         return true;
1141                     }
1142                 } else {
1143                     *external_src = ExternalSource::AbsentErr;
1144                 }
1145
1146                 false
1147             } else {
1148                 self.src.is_some() || external_src.get_source().is_some()
1149             }
1150         } else {
1151             self.src.is_some() || self.external_src.borrow().get_source().is_some()
1152         }
1153     }
1154
1155     /// Gets a line from the list of pre-computed line-beginnings.
1156     /// The line number here is 0-based.
1157     pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1158         fn get_until_newline(src: &str, begin: usize) -> &str {
1159             // We can't use `lines.get(line_number+1)` because we might
1160             // be parsing when we call this function and thus the current
1161             // line is the last one we have line info for.
1162             let slice = &src[begin..];
1163             match slice.find('\n') {
1164                 Some(e) => &slice[..e],
1165                 None => slice,
1166             }
1167         }
1168
1169         let begin = {
1170             let line = if let Some(line) = self.lines.get(line_number) {
1171                 line
1172             } else {
1173                 return None;
1174             };
1175             let begin: BytePos = *line - self.start_pos;
1176             begin.to_usize()
1177         };
1178
1179         if let Some(ref src) = self.src {
1180             Some(Cow::from(get_until_newline(src, begin)))
1181         } else if let Some(src) = self.external_src.borrow().get_source() {
1182             Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1183         } else {
1184             None
1185         }
1186     }
1187
1188     pub fn is_real_file(&self) -> bool {
1189         self.name.is_real()
1190     }
1191
1192     pub fn is_imported(&self) -> bool {
1193         self.src.is_none()
1194     }
1195
1196     pub fn byte_length(&self) -> u32 {
1197         self.end_pos.0 - self.start_pos.0
1198     }
1199     pub fn count_lines(&self) -> usize {
1200         self.lines.len()
1201     }
1202
1203     /// Finds the line containing the given position. The return value is the
1204     /// index into the `lines` array of this `SourceFile`, not the 1-based line
1205     /// number. If the source_file is empty or the position is located before the
1206     /// first line, `None` is returned.
1207     pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1208         if self.lines.len() == 0 {
1209             return None;
1210         }
1211
1212         let line_index = lookup_line(&self.lines[..], pos);
1213         assert!(line_index < self.lines.len() as isize);
1214         if line_index >= 0 { Some(line_index as usize) } else { None }
1215     }
1216
1217     pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1218         if self.start_pos == self.end_pos {
1219             return (self.start_pos, self.end_pos);
1220         }
1221
1222         assert!(line_index < self.lines.len());
1223         if line_index == (self.lines.len() - 1) {
1224             (self.lines[line_index], self.end_pos)
1225         } else {
1226             (self.lines[line_index], self.lines[line_index + 1])
1227         }
1228     }
1229
1230     #[inline]
1231     pub fn contains(&self, byte_pos: BytePos) -> bool {
1232         byte_pos >= self.start_pos && byte_pos <= self.end_pos
1233     }
1234
1235     /// Calculates the original byte position relative to the start of the file
1236     /// based on the given byte position.
1237     pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos {
1238         // Diff before any records is 0. Otherwise use the previously recorded
1239         // diff as that applies to the following characters until a new diff
1240         // is recorded.
1241         let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
1242             Ok(i) => self.normalized_pos[i].diff,
1243             Err(i) if i == 0 => 0,
1244             Err(i) => self.normalized_pos[i - 1].diff,
1245         };
1246
1247         BytePos::from_u32(pos.0 - self.start_pos.0 + diff)
1248     }
1249 }
1250
1251 /// Normalizes the source code and records the normalizations.
1252 fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec<NormalizedPos> {
1253     let mut normalized_pos = vec![];
1254     remove_bom(src, &mut normalized_pos);
1255     normalize_newlines(src, &mut normalized_pos);
1256
1257     // Offset all the positions by start_pos to match the final file positions.
1258     for np in &mut normalized_pos {
1259         np.pos.0 += start_pos.0;
1260     }
1261
1262     normalized_pos
1263 }
1264
1265 /// Removes UTF-8 BOM, if any.
1266 fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1267     if src.starts_with("\u{feff}") {
1268         src.drain(..3);
1269         normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 });
1270     }
1271 }
1272
1273 /// Replaces `\r\n` with `\n` in-place in `src`.
1274 ///
1275 /// Returns error if there's a lone `\r` in the string
1276 fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
1277     if !src.as_bytes().contains(&b'\r') {
1278         return;
1279     }
1280
1281     // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
1282     // While we *can* call `as_mut_vec` and do surgery on the live string
1283     // directly, let's rather steal the contents of `src`. This makes the code
1284     // safe even if a panic occurs.
1285
1286     let mut buf = std::mem::replace(src, String::new()).into_bytes();
1287     let mut gap_len = 0;
1288     let mut tail = buf.as_mut_slice();
1289     let mut cursor = 0;
1290     let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
1291     loop {
1292         let idx = match find_crlf(&tail[gap_len..]) {
1293             None => tail.len(),
1294             Some(idx) => idx + gap_len,
1295         };
1296         tail.copy_within(gap_len..idx, 0);
1297         tail = &mut tail[idx - gap_len..];
1298         if tail.len() == gap_len {
1299             break;
1300         }
1301         cursor += idx - gap_len;
1302         gap_len += 1;
1303         normalized_pos.push(NormalizedPos {
1304             pos: BytePos::from_usize(cursor + 1),
1305             diff: original_gap + gap_len as u32,
1306         });
1307     }
1308
1309     // Account for removed `\r`.
1310     // After `set_len`, `buf` is guaranteed to contain utf-8 again.
1311     let new_len = buf.len() - gap_len;
1312     unsafe {
1313         buf.set_len(new_len);
1314         *src = String::from_utf8_unchecked(buf);
1315     }
1316
1317     fn find_crlf(src: &[u8]) -> Option<usize> {
1318         let mut search_idx = 0;
1319         while let Some(idx) = find_cr(&src[search_idx..]) {
1320             if src[search_idx..].get(idx + 1) != Some(&b'\n') {
1321                 search_idx += idx + 1;
1322                 continue;
1323             }
1324             return Some(search_idx + idx);
1325         }
1326         None
1327     }
1328
1329     fn find_cr(src: &[u8]) -> Option<usize> {
1330         src.iter().position(|&b| b == b'\r')
1331     }
1332 }
1333
1334 // _____________________________________________________________________________
1335 // Pos, BytePos, CharPos
1336 //
1337
1338 pub trait Pos {
1339     fn from_usize(n: usize) -> Self;
1340     fn to_usize(&self) -> usize;
1341     fn from_u32(n: u32) -> Self;
1342     fn to_u32(&self) -> u32;
1343 }
1344
1345 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1346 /// a lot of them.
1347 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1348 pub struct BytePos(pub u32);
1349
1350 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1351 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1352 /// values to `CharPos` values as necessary.
1353 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
1354 pub struct CharPos(pub usize);
1355
1356 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1357 // have been unsuccessful.
1358
1359 impl Pos for BytePos {
1360     #[inline(always)]
1361     fn from_usize(n: usize) -> BytePos {
1362         BytePos(n as u32)
1363     }
1364
1365     #[inline(always)]
1366     fn to_usize(&self) -> usize {
1367         self.0 as usize
1368     }
1369
1370     #[inline(always)]
1371     fn from_u32(n: u32) -> BytePos {
1372         BytePos(n)
1373     }
1374
1375     #[inline(always)]
1376     fn to_u32(&self) -> u32 {
1377         self.0
1378     }
1379 }
1380
1381 impl Add for BytePos {
1382     type Output = BytePos;
1383
1384     #[inline(always)]
1385     fn add(self, rhs: BytePos) -> BytePos {
1386         BytePos((self.to_usize() + rhs.to_usize()) as u32)
1387     }
1388 }
1389
1390 impl Sub for BytePos {
1391     type Output = BytePos;
1392
1393     #[inline(always)]
1394     fn sub(self, rhs: BytePos) -> BytePos {
1395         BytePos((self.to_usize() - rhs.to_usize()) as u32)
1396     }
1397 }
1398
1399 impl Encodable for BytePos {
1400     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1401         s.emit_u32(self.0)
1402     }
1403 }
1404
1405 impl Decodable for BytePos {
1406     fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1407         Ok(BytePos(d.read_u32()?))
1408     }
1409 }
1410
1411 impl Pos for CharPos {
1412     #[inline(always)]
1413     fn from_usize(n: usize) -> CharPos {
1414         CharPos(n)
1415     }
1416
1417     #[inline(always)]
1418     fn to_usize(&self) -> usize {
1419         self.0
1420     }
1421
1422     #[inline(always)]
1423     fn from_u32(n: u32) -> CharPos {
1424         CharPos(n as usize)
1425     }
1426
1427     #[inline(always)]
1428     fn to_u32(&self) -> u32 {
1429         self.0 as u32
1430     }
1431 }
1432
1433 impl Add for CharPos {
1434     type Output = CharPos;
1435
1436     #[inline(always)]
1437     fn add(self, rhs: CharPos) -> CharPos {
1438         CharPos(self.to_usize() + rhs.to_usize())
1439     }
1440 }
1441
1442 impl Sub for CharPos {
1443     type Output = CharPos;
1444
1445     #[inline(always)]
1446     fn sub(self, rhs: CharPos) -> CharPos {
1447         CharPos(self.to_usize() - rhs.to_usize())
1448     }
1449 }
1450
1451 // _____________________________________________________________________________
1452 // Loc, SourceFileAndLine, SourceFileAndBytePos
1453 //
1454
1455 /// A source code location used for error reporting.
1456 #[derive(Debug, Clone)]
1457 pub struct Loc {
1458     /// Information about the original source.
1459     pub file: Lrc<SourceFile>,
1460     /// The (1-based) line number.
1461     pub line: usize,
1462     /// The (0-based) column offset.
1463     pub col: CharPos,
1464     /// The (0-based) column offset when displayed.
1465     pub col_display: usize,
1466 }
1467
1468 // Used to be structural records.
1469 #[derive(Debug)]
1470 pub struct SourceFileAndLine {
1471     pub sf: Lrc<SourceFile>,
1472     pub line: usize,
1473 }
1474 #[derive(Debug)]
1475 pub struct SourceFileAndBytePos {
1476     pub sf: Lrc<SourceFile>,
1477     pub pos: BytePos,
1478 }
1479
1480 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1481 pub struct LineInfo {
1482     /// Index of line, starting from 0.
1483     pub line_index: usize,
1484
1485     /// Column in line where span begins, starting from 0.
1486     pub start_col: CharPos,
1487
1488     /// Column in line where span ends, starting from 0, exclusive.
1489     pub end_col: CharPos,
1490 }
1491
1492 pub struct FileLines {
1493     pub file: Lrc<SourceFile>,
1494     pub lines: Vec<LineInfo>,
1495 }
1496
1497 pub static SPAN_DEBUG: AtomicRef<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1498     AtomicRef::new(&(default_span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
1499
1500 // _____________________________________________________________________________
1501 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1502 //
1503
1504 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1505
1506 #[derive(Clone, PartialEq, Eq, Debug)]
1507 pub enum SpanLinesError {
1508     DistinctSources(DistinctSources),
1509 }
1510
1511 #[derive(Clone, PartialEq, Eq, Debug)]
1512 pub enum SpanSnippetError {
1513     IllFormedSpan(Span),
1514     DistinctSources(DistinctSources),
1515     MalformedForSourcemap(MalformedSourceMapPositions),
1516     SourceNotAvailable { filename: FileName },
1517 }
1518
1519 #[derive(Clone, PartialEq, Eq, Debug)]
1520 pub struct DistinctSources {
1521     pub begin: (FileName, BytePos),
1522     pub end: (FileName, BytePos),
1523 }
1524
1525 #[derive(Clone, PartialEq, Eq, Debug)]
1526 pub struct MalformedSourceMapPositions {
1527     pub name: FileName,
1528     pub source_len: usize,
1529     pub begin_pos: BytePos,
1530     pub end_pos: BytePos,
1531 }
1532
1533 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
1534 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
1535 pub struct InnerSpan {
1536     pub start: usize,
1537     pub end: usize,
1538 }
1539
1540 impl InnerSpan {
1541     pub fn new(start: usize, end: usize) -> InnerSpan {
1542         InnerSpan { start, end }
1543     }
1544 }
1545
1546 // Given a slice of line start positions and a position, returns the index of
1547 // the line the position is on. Returns -1 if the position is located before
1548 // the first line.
1549 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1550     match lines.binary_search(&pos) {
1551         Ok(line) => line as isize,
1552         Err(line) => line as isize - 1,
1553     }
1554 }
1555
1556 /// Requirements for a `StableHashingContext` to be used in this crate.
1557 /// This is a hack to allow using the `HashStable_Generic` derive macro
1558 /// instead of implementing everything in librustc.
1559 pub trait HashStableContext {
1560     fn hash_spans(&self) -> bool;
1561     fn hash_def_id(&mut self, _: DefId, hasher: &mut StableHasher);
1562     fn byte_pos_to_line_and_col(
1563         &mut self,
1564         byte: BytePos,
1565     ) -> Option<(Lrc<SourceFile>, usize, BytePos)>;
1566 }
1567
1568 impl<CTX> HashStable<CTX> for Span
1569 where
1570     CTX: HashStableContext,
1571 {
1572     /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
1573     /// fields (that would be similar to hashing pointers, since those are just
1574     /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
1575     /// triple, which stays the same even if the containing `SourceFile` has moved
1576     /// within the `SourceMap`.
1577     /// Also note that we are hashing byte offsets for the column, not unicode
1578     /// codepoint offsets. For the purpose of the hash that's sufficient.
1579     /// Also, hashing filenames is expensive so we avoid doing it twice when the
1580     /// span starts and ends in the same file, which is almost always the case.
1581     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1582         const TAG_VALID_SPAN: u8 = 0;
1583         const TAG_INVALID_SPAN: u8 = 1;
1584         const TAG_EXPANSION: u8 = 0;
1585         const TAG_NO_EXPANSION: u8 = 1;
1586
1587         if !ctx.hash_spans() {
1588             return;
1589         }
1590
1591         if *self == DUMMY_SP {
1592             return std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1593         }
1594
1595         // If this is not an empty or invalid span, we want to hash the last
1596         // position that belongs to it, as opposed to hashing the first
1597         // position past it.
1598         let span = self.data();
1599         let (file_lo, line_lo, col_lo) = match ctx.byte_pos_to_line_and_col(span.lo) {
1600             Some(pos) => pos,
1601             None => {
1602                 return std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1603             }
1604         };
1605
1606         if !file_lo.contains(span.hi) {
1607             return std::hash::Hash::hash(&TAG_INVALID_SPAN, hasher);
1608         }
1609
1610         std::hash::Hash::hash(&TAG_VALID_SPAN, hasher);
1611         // We truncate the stable ID hash and line and column numbers. The chances
1612         // of causing a collision this way should be minimal.
1613         std::hash::Hash::hash(&(file_lo.name_hash as u64), hasher);
1614
1615         let col = (col_lo.0 as u64) & 0xFF;
1616         let line = ((line_lo as u64) & 0xFF_FF_FF) << 8;
1617         let len = ((span.hi - span.lo).0 as u64) << 32;
1618         let line_col_len = col | line | len;
1619         std::hash::Hash::hash(&line_col_len, hasher);
1620
1621         if span.ctxt == SyntaxContext::root() {
1622             TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1623         } else {
1624             TAG_EXPANSION.hash_stable(ctx, hasher);
1625
1626             // Since the same expansion context is usually referenced many
1627             // times, we cache a stable hash of it and hash that instead of
1628             // recursing every time.
1629             thread_local! {
1630                 static CACHE: RefCell<FxHashMap<hygiene::ExpnId, u64>> = Default::default();
1631             }
1632
1633             let sub_hash: u64 = CACHE.with(|cache| {
1634                 let expn_id = span.ctxt.outer_expn();
1635
1636                 if let Some(&sub_hash) = cache.borrow().get(&expn_id) {
1637                     return sub_hash;
1638                 }
1639
1640                 let mut hasher = StableHasher::new();
1641                 expn_id.expn_data().hash_stable(ctx, &mut hasher);
1642                 let sub_hash: Fingerprint = hasher.finish();
1643                 let sub_hash = sub_hash.to_smaller_hash();
1644                 cache.borrow_mut().insert(expn_id, sub_hash);
1645                 sub_hash
1646             });
1647
1648             sub_hash.hash_stable(ctx, hasher);
1649         }
1650     }
1651 }