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