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