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