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