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