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