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