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