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