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