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