]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/lib.rs
Auto merge of #58389 - Centril:rollup, r=Centril
[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 #![deny(rust_2018_idioms)]
10
11 #![feature(const_fn)]
12 #![feature(crate_visibility_modifier)]
13 #![feature(custom_attribute)]
14 #![feature(nll)]
15 #![feature(non_exhaustive)]
16 #![feature(optin_builtin_traits)]
17 #![feature(rustc_attrs)]
18 #![feature(specialization)]
19 #![feature(step_trait)]
20 #![cfg_attr(not(stage0), feature(stdsimd))]
21
22 use serialize::{Encodable, Decodable, Encoder, Decoder};
23
24 #[allow(unused_extern_crates)]
25 extern crate serialize as rustc_serialize; // used by deriving
26
27 pub mod edition;
28 pub mod hygiene;
29 pub use hygiene::{Mark, SyntaxContext, ExpnInfo, ExpnFormat, CompilerDesugaringKind};
30
31 mod span_encoding;
32 pub use span_encoding::{Span, DUMMY_SP};
33
34 pub mod symbol;
35
36 mod analyze_source_file;
37
38 use rustc_data_structures::stable_hasher::StableHasher;
39 use rustc_data_structures::sync::{Lrc, Lock};
40
41 use std::borrow::Cow;
42 use std::cell::Cell;
43 use std::cmp::{self, Ordering};
44 use std::fmt;
45 use std::hash::{Hasher, Hash};
46 use std::ops::{Add, Sub};
47 use std::path::PathBuf;
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() -> 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()),
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 a new span representing an empty span at the beginning of this span
291     #[inline]
292     pub fn shrink_to_lo(self) -> Span {
293         let span = self.data();
294         span.with_hi(span.lo)
295     }
296     /// Returns a new span representing an empty span at the end of this span.
297     #[inline]
298     pub fn shrink_to_hi(self) -> Span {
299         let span = self.data();
300         span.with_lo(span.hi)
301     }
302
303     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
304     pub fn substitute_dummy(self, other: Span) -> Span {
305         if self.is_dummy() { other } else { self }
306     }
307
308     /// Return `true` if `self` fully encloses `other`.
309     pub fn contains(self, other: Span) -> bool {
310         let span = self.data();
311         let other = other.data();
312         span.lo <= other.lo && other.hi <= span.hi
313     }
314
315     /// Return `true` if `self` touches `other`.
316     pub fn overlaps(self, other: Span) -> bool {
317         let span = self.data();
318         let other = other.data();
319         span.lo < other.hi && other.lo < span.hi
320     }
321
322     /// Return true if the spans are equal with regards to the source text.
323     ///
324     /// Use this instead of `==` when either span could be generated code,
325     /// and you only care that they point to the same bytes of source text.
326     pub fn source_equal(&self, other: &Span) -> bool {
327         let span = self.data();
328         let other = other.data();
329         span.lo == other.lo && span.hi == other.hi
330     }
331
332     /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
333     pub fn trim_start(self, other: Span) -> Option<Span> {
334         let span = self.data();
335         let other = other.data();
336         if span.hi > other.hi {
337             Some(span.with_lo(cmp::max(span.lo, other.hi)))
338         } else {
339             None
340         }
341     }
342
343     /// Return the source span -- this is either the supplied span, or the span for
344     /// the macro callsite that expanded to it.
345     pub fn source_callsite(self) -> Span {
346         self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
347     }
348
349     /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
350     /// if any.
351     pub fn parent(self) -> Option<Span> {
352         self.ctxt().outer().expn_info().map(|i| i.call_site)
353     }
354
355     /// Edition of the crate from which this span came.
356     pub fn edition(self) -> edition::Edition {
357         self.ctxt().outer().expn_info().map_or_else(|| hygiene::default_edition(),
358                                                     |einfo| einfo.edition)
359     }
360
361     #[inline]
362     pub fn rust_2015(&self) -> bool {
363         self.edition() == edition::Edition::Edition2015
364     }
365
366     #[inline]
367     pub fn rust_2018(&self) -> bool {
368         self.edition() >= edition::Edition::Edition2018
369     }
370
371     /// Return the source callee.
372     ///
373     /// Returns `None` if the supplied span has no expansion trace,
374     /// else returns the `ExpnInfo` for the macro definition
375     /// corresponding to the source callsite.
376     pub fn source_callee(self) -> Option<ExpnInfo> {
377         fn source_callee(info: ExpnInfo) -> ExpnInfo {
378             match info.call_site.ctxt().outer().expn_info() {
379                 Some(info) => source_callee(info),
380                 None => info,
381             }
382         }
383         self.ctxt().outer().expn_info().map(source_callee)
384     }
385
386     /// Check if a span is "internal" to a macro in which `#[unstable]`
387     /// items can be used (that is, a macro marked with
388     /// `#[allow_internal_unstable]`).
389     pub fn allows_unstable(&self) -> bool {
390         match self.ctxt().outer().expn_info() {
391             Some(info) => info.allow_internal_unstable,
392             None => false,
393         }
394     }
395
396     /// Check if this span arises from a compiler desugaring of kind `kind`.
397     pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
398         match self.ctxt().outer().expn_info() {
399             Some(info) => match info.format {
400                 ExpnFormat::CompilerDesugaring(k) => k == kind,
401                 _ => false,
402             },
403             None => false,
404         }
405     }
406
407     /// Return the compiler desugaring that created this span, or `None`
408     /// if this span is not from a desugaring.
409     pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
410         match self.ctxt().outer().expn_info() {
411             Some(info) => match info.format {
412                 ExpnFormat::CompilerDesugaring(k) => Some(k),
413                 _ => None
414             },
415             None => None
416         }
417     }
418
419     /// Check if a span is "internal" to a macro in which `unsafe`
420     /// can be used without triggering the `unsafe_code` lint
421     //  (that is, a macro marked with `#[allow_internal_unsafe]`).
422     pub fn allows_unsafe(&self) -> bool {
423         match self.ctxt().outer().expn_info() {
424             Some(info) => info.allow_internal_unsafe,
425             None => false,
426         }
427     }
428
429     pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
430         let mut prev_span = DUMMY_SP;
431         let mut result = vec![];
432         while let Some(info) = self.ctxt().outer().expn_info() {
433             // Don't print recursive invocations.
434             if !info.call_site.source_equal(&prev_span) {
435                 let (pre, post) = match info.format {
436                     ExpnFormat::MacroAttribute(..) => ("#[", "]"),
437                     ExpnFormat::MacroBang(..) => ("", "!"),
438                     ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
439                 };
440                 result.push(MacroBacktrace {
441                     call_site: info.call_site,
442                     macro_decl_name: format!("{}{}{}", pre, info.format.name(), post),
443                     def_site_span: info.def_site,
444                 });
445             }
446
447             prev_span = self;
448             self = info.call_site;
449         }
450         result
451     }
452
453     /// Return a `Span` that would enclose both `self` and `end`.
454     pub fn to(self, end: Span) -> Span {
455         let span_data = self.data();
456         let end_data = end.data();
457         // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480).
458         // Return the macro span on its own to avoid weird diagnostic output. It is preferable to
459         // have an incomplete span than a completely nonsensical one.
460         if span_data.ctxt != end_data.ctxt {
461             if span_data.ctxt == SyntaxContext::empty() {
462                 return end;
463             } else if end_data.ctxt == SyntaxContext::empty() {
464                 return self;
465             }
466             // Both spans fall within a macro.
467             // FIXME(estebank): check if it is the *same* macro.
468         }
469         Span::new(
470             cmp::min(span_data.lo, end_data.lo),
471             cmp::max(span_data.hi, end_data.hi),
472             if span_data.ctxt == SyntaxContext::empty() { end_data.ctxt } else { span_data.ctxt },
473         )
474     }
475
476     /// Return a `Span` between the end of `self` to the beginning of `end`.
477     pub fn between(self, end: Span) -> Span {
478         let span = self.data();
479         let end = end.data();
480         Span::new(
481             span.hi,
482             end.lo,
483             if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
484         )
485     }
486
487     /// Return a `Span` between the beginning of `self` to the beginning of `end`.
488     pub fn until(self, end: Span) -> Span {
489         let span = self.data();
490         let end = end.data();
491         Span::new(
492             span.lo,
493             end.lo,
494             if end.ctxt == SyntaxContext::empty() { end.ctxt } else { span.ctxt },
495         )
496     }
497
498     pub fn from_inner_byte_pos(self, start: usize, end: usize) -> Span {
499         let span = self.data();
500         Span::new(span.lo + BytePos::from_usize(start),
501                   span.lo + BytePos::from_usize(end),
502                   span.ctxt)
503     }
504
505     #[inline]
506     pub fn apply_mark(self, mark: Mark) -> Span {
507         let span = self.data();
508         span.with_ctxt(span.ctxt.apply_mark(mark))
509     }
510
511     #[inline]
512     pub fn remove_mark(&mut self) -> Mark {
513         let mut span = self.data();
514         let mark = span.ctxt.remove_mark();
515         *self = Span::new(span.lo, span.hi, span.ctxt);
516         mark
517     }
518
519     #[inline]
520     pub fn adjust(&mut self, expansion: Mark) -> Option<Mark> {
521         let mut span = self.data();
522         let mark = span.ctxt.adjust(expansion);
523         *self = Span::new(span.lo, span.hi, span.ctxt);
524         mark
525     }
526
527     #[inline]
528     pub fn glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
529                        -> Option<Option<Mark>> {
530         let mut span = self.data();
531         let mark = span.ctxt.glob_adjust(expansion, glob_ctxt);
532         *self = Span::new(span.lo, span.hi, span.ctxt);
533         mark
534     }
535
536     #[inline]
537     pub fn reverse_glob_adjust(&mut self, expansion: Mark, glob_ctxt: SyntaxContext)
538                                -> Option<Option<Mark>> {
539         let mut span = self.data();
540         let mark = span.ctxt.reverse_glob_adjust(expansion, glob_ctxt);
541         *self = Span::new(span.lo, span.hi, span.ctxt);
542         mark
543     }
544
545     #[inline]
546     pub fn modern(self) -> Span {
547         let span = self.data();
548         span.with_ctxt(span.ctxt.modern())
549     }
550
551     #[inline]
552     pub fn modern_and_legacy(self) -> Span {
553         let span = self.data();
554         span.with_ctxt(span.ctxt.modern_and_legacy())
555     }
556 }
557
558 #[derive(Clone, Debug)]
559 pub struct SpanLabel {
560     /// The span we are going to include in the final snippet.
561     pub span: Span,
562
563     /// Is this a primary span? This is the "locus" of the message,
564     /// and is indicated with a `^^^^` underline, versus `----`.
565     pub is_primary: bool,
566
567     /// What label should we attach to this span (if any)?
568     pub label: Option<String>,
569 }
570
571 impl Default for Span {
572     fn default() -> Self {
573         DUMMY_SP
574     }
575 }
576
577 impl serialize::UseSpecializedEncodable for Span {
578     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
579         let span = self.data();
580         s.emit_struct("Span", 2, |s| {
581             s.emit_struct_field("lo", 0, |s| {
582                 span.lo.encode(s)
583             })?;
584
585             s.emit_struct_field("hi", 1, |s| {
586                 span.hi.encode(s)
587             })
588         })
589     }
590 }
591
592 impl serialize::UseSpecializedDecodable for Span {
593     fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
594         d.read_struct("Span", 2, |d| {
595             let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
596             let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
597             Ok(Span::new(lo, hi, NO_EXPANSION))
598         })
599     }
600 }
601
602 pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
603     f.debug_struct("Span")
604         .field("lo", &span.lo())
605         .field("hi", &span.hi())
606         .field("ctxt", &span.ctxt())
607         .finish()
608 }
609
610 impl fmt::Debug for Span {
611     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
612         SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
613     }
614 }
615
616 impl fmt::Debug for SpanData {
617     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618         SPAN_DEBUG.with(|span_debug| span_debug.get()(Span::new(self.lo, self.hi, self.ctxt), f))
619     }
620 }
621
622 impl MultiSpan {
623     #[inline]
624     pub fn new() -> MultiSpan {
625         MultiSpan {
626             primary_spans: vec![],
627             span_labels: vec![]
628         }
629     }
630
631     pub fn from_span(primary_span: Span) -> MultiSpan {
632         MultiSpan {
633             primary_spans: vec![primary_span],
634             span_labels: vec![]
635         }
636     }
637
638     pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
639         MultiSpan {
640             primary_spans: vec,
641             span_labels: vec![]
642         }
643     }
644
645     pub fn push_span_label(&mut self, span: Span, label: String) {
646         self.span_labels.push((span, label));
647     }
648
649     /// Selects the first primary span (if any).
650     pub fn primary_span(&self) -> Option<Span> {
651         self.primary_spans.first().cloned()
652     }
653
654     /// Returns all primary spans.
655     pub fn primary_spans(&self) -> &[Span] {
656         &self.primary_spans
657     }
658
659     /// Returns whether any of the primary spans is displayable.
660     pub fn has_primary_spans(&self) -> bool {
661         self.primary_spans.iter().any(|sp| !sp.is_dummy())
662     }
663
664     /// Returns `true` if this contains only a dummy primary span with any hygienic context.
665     pub fn is_dummy(&self) -> bool {
666         let mut is_dummy = true;
667         for span in &self.primary_spans {
668             if !span.is_dummy() {
669                 is_dummy = false;
670             }
671         }
672         is_dummy
673     }
674
675     /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
676     /// display well (like std macros). Returns true if replacements occurred.
677     pub fn replace(&mut self, before: Span, after: Span) -> bool {
678         let mut replacements_occurred = false;
679         for primary_span in &mut self.primary_spans {
680             if *primary_span == before {
681                 *primary_span = after;
682                 replacements_occurred = true;
683             }
684         }
685         for span_label in &mut self.span_labels {
686             if span_label.0 == before {
687                 span_label.0 = after;
688                 replacements_occurred = true;
689             }
690         }
691         replacements_occurred
692     }
693
694     /// Returns the strings to highlight. We always ensure that there
695     /// is an entry for each of the primary spans -- for each primary
696     /// span `P`, if there is at least one label with span `P`, we return
697     /// those labels (marked as primary). But otherwise we return
698     /// `SpanLabel` instances with empty labels.
699     pub fn span_labels(&self) -> Vec<SpanLabel> {
700         let is_primary = |span| self.primary_spans.contains(&span);
701
702         let mut span_labels = self.span_labels.iter().map(|&(span, ref label)|
703             SpanLabel {
704                 span,
705                 is_primary: is_primary(span),
706                 label: Some(label.clone())
707             }
708         ).collect::<Vec<_>>();
709
710         for &span in &self.primary_spans {
711             if !span_labels.iter().any(|sl| sl.span == span) {
712                 span_labels.push(SpanLabel {
713                     span,
714                     is_primary: true,
715                     label: None
716                 });
717             }
718         }
719
720         span_labels
721     }
722
723     /// Returns whether any of the span labels is displayable.
724     pub fn has_span_labels(&self) -> bool {
725         self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
726     }
727 }
728
729 impl From<Span> for MultiSpan {
730     fn from(span: Span) -> MultiSpan {
731         MultiSpan::from_span(span)
732     }
733 }
734
735 impl From<Vec<Span>> for MultiSpan {
736     fn from(spans: Vec<Span>) -> MultiSpan {
737         MultiSpan::from_spans(spans)
738     }
739 }
740
741 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
742
743 /// Identifies an offset of a multi-byte character in a `SourceFile`.
744 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
745 pub struct MultiByteChar {
746     /// The absolute offset of the character in the `SourceMap`.
747     pub pos: BytePos,
748     /// The number of bytes, `>= 2`.
749     pub bytes: u8,
750 }
751
752 /// Identifies an offset of a non-narrow character in a `SourceFile`.
753 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)]
754 pub enum NonNarrowChar {
755     /// Represents a zero-width character.
756     ZeroWidth(BytePos),
757     /// Represents a wide (full-width) character.
758     Wide(BytePos),
759     /// Represents a tab character, represented visually with a width of 4 characters.
760     Tab(BytePos),
761 }
762
763 impl NonNarrowChar {
764     fn new(pos: BytePos, width: usize) -> Self {
765         match width {
766             0 => NonNarrowChar::ZeroWidth(pos),
767             2 => NonNarrowChar::Wide(pos),
768             4 => NonNarrowChar::Tab(pos),
769             _ => panic!("width {} given for non-narrow character", width),
770         }
771     }
772
773     /// Returns the absolute offset of the character in the `SourceMap`.
774     pub fn pos(&self) -> BytePos {
775         match *self {
776             NonNarrowChar::ZeroWidth(p) |
777             NonNarrowChar::Wide(p) |
778             NonNarrowChar::Tab(p) => p,
779         }
780     }
781
782     /// Returns the width of the character, 0 (zero-width) or 2 (wide).
783     pub fn width(&self) -> usize {
784         match *self {
785             NonNarrowChar::ZeroWidth(_) => 0,
786             NonNarrowChar::Wide(_) => 2,
787             NonNarrowChar::Tab(_) => 4,
788         }
789     }
790 }
791
792 impl Add<BytePos> for NonNarrowChar {
793     type Output = Self;
794
795     fn add(self, rhs: BytePos) -> Self {
796         match self {
797             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs),
798             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs),
799             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs),
800         }
801     }
802 }
803
804 impl Sub<BytePos> for NonNarrowChar {
805     type Output = Self;
806
807     fn sub(self, rhs: BytePos) -> Self {
808         match self {
809             NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs),
810             NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs),
811             NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs),
812         }
813     }
814 }
815
816 /// The state of the lazy external source loading mechanism of a `SourceFile`.
817 #[derive(PartialEq, Eq, Clone)]
818 pub enum ExternalSource {
819     /// The external source has been loaded already.
820     Present(String),
821     /// No attempt has been made to load the external source.
822     AbsentOk,
823     /// A failed attempt has been made to load the external source.
824     AbsentErr,
825     /// No external source has to be loaded, since the `SourceFile` represents a local crate.
826     Unneeded,
827 }
828
829 impl ExternalSource {
830     pub fn is_absent(&self) -> bool {
831         match *self {
832             ExternalSource::Present(_) => false,
833             _ => true,
834         }
835     }
836
837     pub fn get_source(&self) -> Option<&str> {
838         match *self {
839             ExternalSource::Present(ref src) => Some(src),
840             _ => None,
841         }
842     }
843 }
844
845 /// A single source in the `SourceMap`.
846 #[derive(Clone)]
847 pub struct SourceFile {
848     /// The name of the file that the source came from, source that doesn't
849     /// originate from files has names between angle brackets by convention
850     /// (e.g., `<anon>`).
851     pub name: FileName,
852     /// True if the `name` field above has been modified by `--remap-path-prefix`.
853     pub name_was_remapped: bool,
854     /// The unmapped path of the file that the source came from.
855     /// Set to `None` if the `SourceFile` was imported from an external crate.
856     pub unmapped_path: Option<FileName>,
857     /// Indicates which crate this `SourceFile` was imported from.
858     pub crate_of_origin: u32,
859     /// The complete source code.
860     pub src: Option<Lrc<String>>,
861     /// The source code's hash.
862     pub src_hash: u128,
863     /// The external source code (used for external crates, which will have a `None`
864     /// value as `self.src`.
865     pub external_src: Lock<ExternalSource>,
866     /// The start position of this source in the `SourceMap`.
867     pub start_pos: BytePos,
868     /// The end position of this source in the `SourceMap`.
869     pub end_pos: BytePos,
870     /// Locations of lines beginnings in the source code.
871     pub lines: Vec<BytePos>,
872     /// Locations of multi-byte characters in the source code.
873     pub multibyte_chars: Vec<MultiByteChar>,
874     /// Width of characters that are not narrow in the source code.
875     pub non_narrow_chars: Vec<NonNarrowChar>,
876     /// A hash of the filename, used for speeding up hashing in incremental compilation.
877     pub name_hash: u128,
878 }
879
880 impl Encodable for SourceFile {
881     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
882         s.emit_struct("SourceFile", 8, |s| {
883             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
884             s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
885             s.emit_struct_field("src_hash", 2, |s| self.src_hash.encode(s))?;
886             s.emit_struct_field("start_pos", 4, |s| self.start_pos.encode(s))?;
887             s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?;
888             s.emit_struct_field("lines", 6, |s| {
889                 let lines = &self.lines[..];
890                 // Store the length.
891                 s.emit_u32(lines.len() as u32)?;
892
893                 if !lines.is_empty() {
894                     // In order to preserve some space, we exploit the fact that
895                     // the lines list is sorted and individual lines are
896                     // probably not that long. Because of that we can store lines
897                     // as a difference list, using as little space as possible
898                     // for the differences.
899                     let max_line_length = if lines.len() == 1 {
900                         0
901                     } else {
902                         lines.windows(2)
903                              .map(|w| w[1] - w[0])
904                              .map(|bp| bp.to_usize())
905                              .max()
906                              .unwrap()
907                     };
908
909                     let bytes_per_diff: u8 = match max_line_length {
910                         0 ..= 0xFF => 1,
911                         0x100 ..= 0xFFFF => 2,
912                         _ => 4
913                     };
914
915                     // Encode the number of bytes used per diff.
916                     bytes_per_diff.encode(s)?;
917
918                     // Encode the first element.
919                     lines[0].encode(s)?;
920
921                     let diff_iter = (&lines[..]).windows(2)
922                                                 .map(|w| (w[1] - w[0]));
923
924                     match bytes_per_diff {
925                         1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
926                         2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
927                         4 => for diff in diff_iter { diff.0.encode(s)? },
928                         _ => unreachable!()
929                     }
930                 }
931
932                 Ok(())
933             })?;
934             s.emit_struct_field("multibyte_chars", 7, |s| {
935                 self.multibyte_chars.encode(s)
936             })?;
937             s.emit_struct_field("non_narrow_chars", 8, |s| {
938                 self.non_narrow_chars.encode(s)
939             })?;
940             s.emit_struct_field("name_hash", 9, |s| {
941                 self.name_hash.encode(s)
942             })
943         })
944     }
945 }
946
947 impl Decodable for SourceFile {
948     fn decode<D: Decoder>(d: &mut D) -> Result<SourceFile, D::Error> {
949
950         d.read_struct("SourceFile", 8, |d| {
951             let name: FileName = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
952             let name_was_remapped: bool =
953                 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
954             let src_hash: u128 =
955                 d.read_struct_field("src_hash", 2, |d| Decodable::decode(d))?;
956             let start_pos: BytePos =
957                 d.read_struct_field("start_pos", 4, |d| Decodable::decode(d))?;
958             let end_pos: BytePos = d.read_struct_field("end_pos", 5, |d| Decodable::decode(d))?;
959             let lines: Vec<BytePos> = d.read_struct_field("lines", 6, |d| {
960                 let num_lines: u32 = Decodable::decode(d)?;
961                 let mut lines = Vec::with_capacity(num_lines as usize);
962
963                 if num_lines > 0 {
964                     // Read the number of bytes used per diff.
965                     let bytes_per_diff: u8 = Decodable::decode(d)?;
966
967                     // Read the first element.
968                     let mut line_start: BytePos = Decodable::decode(d)?;
969                     lines.push(line_start);
970
971                     for _ in 1..num_lines {
972                         let diff = match bytes_per_diff {
973                             1 => d.read_u8()? as u32,
974                             2 => d.read_u16()? as u32,
975                             4 => d.read_u32()?,
976                             _ => unreachable!()
977                         };
978
979                         line_start = line_start + BytePos(diff);
980
981                         lines.push(line_start);
982                     }
983                 }
984
985                 Ok(lines)
986             })?;
987             let multibyte_chars: Vec<MultiByteChar> =
988                 d.read_struct_field("multibyte_chars", 7, |d| Decodable::decode(d))?;
989             let non_narrow_chars: Vec<NonNarrowChar> =
990                 d.read_struct_field("non_narrow_chars", 8, |d| Decodable::decode(d))?;
991             let name_hash: u128 =
992                 d.read_struct_field("name_hash", 9, |d| Decodable::decode(d))?;
993             Ok(SourceFile {
994                 name,
995                 name_was_remapped,
996                 unmapped_path: None,
997                 // `crate_of_origin` has to be set by the importer.
998                 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
999                 // That constant is not available here unfortunately :(
1000                 crate_of_origin: std::u32::MAX - 1,
1001                 start_pos,
1002                 end_pos,
1003                 src: None,
1004                 src_hash,
1005                 external_src: Lock::new(ExternalSource::AbsentOk),
1006                 lines,
1007                 multibyte_chars,
1008                 non_narrow_chars,
1009                 name_hash,
1010             })
1011         })
1012     }
1013 }
1014
1015 impl fmt::Debug for SourceFile {
1016     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1017         write!(fmt, "SourceFile({})", self.name)
1018     }
1019 }
1020
1021 impl SourceFile {
1022     pub fn new(name: FileName,
1023                name_was_remapped: bool,
1024                unmapped_path: FileName,
1025                mut src: String,
1026                start_pos: BytePos) -> SourceFile {
1027         remove_bom(&mut src);
1028
1029         let src_hash = {
1030             let mut hasher: StableHasher<u128> = StableHasher::new();
1031             hasher.write(src.as_bytes());
1032             hasher.finish()
1033         };
1034         let name_hash = {
1035             let mut hasher: StableHasher<u128> = StableHasher::new();
1036             name.hash(&mut hasher);
1037             hasher.finish()
1038         };
1039         let end_pos = start_pos.to_usize() + src.len();
1040
1041         let (lines, multibyte_chars, non_narrow_chars) =
1042             analyze_source_file::analyze_source_file(&src[..], start_pos);
1043
1044         SourceFile {
1045             name,
1046             name_was_remapped,
1047             unmapped_path: Some(unmapped_path),
1048             crate_of_origin: 0,
1049             src: Some(Lrc::new(src)),
1050             src_hash,
1051             external_src: Lock::new(ExternalSource::Unneeded),
1052             start_pos,
1053             end_pos: Pos::from_usize(end_pos),
1054             lines,
1055             multibyte_chars,
1056             non_narrow_chars,
1057             name_hash,
1058         }
1059     }
1060
1061     /// Return the `BytePos` of the beginning of the current line.
1062     pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1063         let line_index = self.lookup_line(pos).unwrap();
1064         self.lines[line_index]
1065     }
1066
1067     /// Add externally loaded source.
1068     /// If the hash of the input doesn't match or no input is supplied via None,
1069     /// it is interpreted as an error and the corresponding enum variant is set.
1070     /// The return value signifies whether some kind of source is present.
1071     pub fn add_external_src<F>(&self, get_src: F) -> bool
1072         where F: FnOnce() -> Option<String>
1073     {
1074         if *self.external_src.borrow() == ExternalSource::AbsentOk {
1075             let src = get_src();
1076             let mut external_src = self.external_src.borrow_mut();
1077             // Check that no-one else have provided the source while we were getting it
1078             if *external_src == ExternalSource::AbsentOk {
1079                 if let Some(src) = src {
1080                     let mut hasher: StableHasher<u128> = StableHasher::new();
1081                     hasher.write(src.as_bytes());
1082
1083                     if hasher.finish() == self.src_hash {
1084                         *external_src = ExternalSource::Present(src);
1085                         return true;
1086                     }
1087                 } else {
1088                     *external_src = ExternalSource::AbsentErr;
1089                 }
1090
1091                 false
1092             } else {
1093                 self.src.is_some() || external_src.get_source().is_some()
1094             }
1095         } else {
1096             self.src.is_some() || self.external_src.borrow().get_source().is_some()
1097         }
1098     }
1099
1100     /// Get a line from the list of pre-computed line-beginnings.
1101     /// The line number here is 0-based.
1102     pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1103         fn get_until_newline(src: &str, begin: usize) -> &str {
1104             // We can't use `lines.get(line_number+1)` because we might
1105             // be parsing when we call this function and thus the current
1106             // line is the last one we have line info for.
1107             let slice = &src[begin..];
1108             match slice.find('\n') {
1109                 Some(e) => &slice[..e],
1110                 None => slice
1111             }
1112         }
1113
1114         let begin = {
1115             let line = if let Some(line) = self.lines.get(line_number) {
1116                 line
1117             } else {
1118                 return None;
1119             };
1120             let begin: BytePos = *line - self.start_pos;
1121             begin.to_usize()
1122         };
1123
1124         if let Some(ref src) = self.src {
1125             Some(Cow::from(get_until_newline(src, begin)))
1126         } else if let Some(src) = self.external_src.borrow().get_source() {
1127             Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1128         } else {
1129             None
1130         }
1131     }
1132
1133     pub fn is_real_file(&self) -> bool {
1134         self.name.is_real()
1135     }
1136
1137     pub fn is_imported(&self) -> bool {
1138         self.src.is_none()
1139     }
1140
1141     pub fn byte_length(&self) -> u32 {
1142         self.end_pos.0 - self.start_pos.0
1143     }
1144     pub fn count_lines(&self) -> usize {
1145         self.lines.len()
1146     }
1147
1148     /// Find the line containing the given position. The return value is the
1149     /// index into the `lines` array of this `SourceFile`, not the 1-based line
1150     /// number. If the source_file is empty or the position is located before the
1151     /// first line, `None` is returned.
1152     pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1153         if self.lines.len() == 0 {
1154             return None;
1155         }
1156
1157         let line_index = lookup_line(&self.lines[..], pos);
1158         assert!(line_index < self.lines.len() as isize);
1159         if line_index >= 0 {
1160             Some(line_index as usize)
1161         } else {
1162             None
1163         }
1164     }
1165
1166     pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1167         if self.start_pos == self.end_pos {
1168             return (self.start_pos, self.end_pos);
1169         }
1170
1171         assert!(line_index < self.lines.len());
1172         if line_index == (self.lines.len() - 1) {
1173             (self.lines[line_index], self.end_pos)
1174         } else {
1175             (self.lines[line_index], self.lines[line_index + 1])
1176         }
1177     }
1178
1179     #[inline]
1180     pub fn contains(&self, byte_pos: BytePos) -> bool {
1181         byte_pos >= self.start_pos && byte_pos <= self.end_pos
1182     }
1183 }
1184
1185 /// Remove utf-8 BOM if any.
1186 fn remove_bom(src: &mut String) {
1187     if src.starts_with("\u{feff}") {
1188         src.drain(..3);
1189     }
1190 }
1191
1192 // _____________________________________________________________________________
1193 // Pos, BytePos, CharPos
1194 //
1195
1196 pub trait Pos {
1197     fn from_usize(n: usize) -> Self;
1198     fn to_usize(&self) -> usize;
1199     fn from_u32(n: u32) -> Self;
1200     fn to_u32(&self) -> u32;
1201 }
1202
1203 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1204 /// a lot of them.
1205 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1206 pub struct BytePos(pub u32);
1207
1208 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1209 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1210 /// values to `CharPos` values as necessary.
1211 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1212 pub struct CharPos(pub usize);
1213
1214 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1215 // have been unsuccessful.
1216
1217 impl Pos for BytePos {
1218     #[inline(always)]
1219     fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1220
1221     #[inline(always)]
1222     fn to_usize(&self) -> usize { self.0 as usize }
1223
1224     #[inline(always)]
1225     fn from_u32(n: u32) -> BytePos { BytePos(n) }
1226
1227     #[inline(always)]
1228     fn to_u32(&self) -> u32 { self.0 }
1229 }
1230
1231 impl Add for BytePos {
1232     type Output = BytePos;
1233
1234     #[inline(always)]
1235     fn add(self, rhs: BytePos) -> BytePos {
1236         BytePos((self.to_usize() + rhs.to_usize()) as u32)
1237     }
1238 }
1239
1240 impl Sub for BytePos {
1241     type Output = BytePos;
1242
1243     #[inline(always)]
1244     fn sub(self, rhs: BytePos) -> BytePos {
1245         BytePos((self.to_usize() - rhs.to_usize()) as u32)
1246     }
1247 }
1248
1249 impl Encodable for BytePos {
1250     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1251         s.emit_u32(self.0)
1252     }
1253 }
1254
1255 impl Decodable for BytePos {
1256     fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1257         Ok(BytePos(d.read_u32()?))
1258     }
1259 }
1260
1261 impl Pos for CharPos {
1262     #[inline(always)]
1263     fn from_usize(n: usize) -> CharPos { CharPos(n) }
1264
1265     #[inline(always)]
1266     fn to_usize(&self) -> usize { self.0 }
1267
1268     #[inline(always)]
1269     fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1270
1271     #[inline(always)]
1272     fn to_u32(&self) -> u32 { self.0 as u32}
1273 }
1274
1275 impl Add for CharPos {
1276     type Output = CharPos;
1277
1278     #[inline(always)]
1279     fn add(self, rhs: CharPos) -> CharPos {
1280         CharPos(self.to_usize() + rhs.to_usize())
1281     }
1282 }
1283
1284 impl Sub for CharPos {
1285     type Output = CharPos;
1286
1287     #[inline(always)]
1288     fn sub(self, rhs: CharPos) -> CharPos {
1289         CharPos(self.to_usize() - rhs.to_usize())
1290     }
1291 }
1292
1293 // _____________________________________________________________________________
1294 // Loc, LocWithOpt, SourceFileAndLine, SourceFileAndBytePos
1295 //
1296
1297 /// A source code location used for error reporting.
1298 #[derive(Debug, Clone)]
1299 pub struct Loc {
1300     /// Information about the original source.
1301     pub file: Lrc<SourceFile>,
1302     /// The (1-based) line number.
1303     pub line: usize,
1304     /// The (0-based) column offset.
1305     pub col: CharPos,
1306     /// The (0-based) column offset when displayed.
1307     pub col_display: usize,
1308 }
1309
1310 /// A source code location used as the result of `lookup_char_pos_adj`.
1311 // Actually, *none* of the clients use the filename *or* file field;
1312 // perhaps they should just be removed.
1313 #[derive(Debug)]
1314 pub struct LocWithOpt {
1315     pub filename: FileName,
1316     pub line: usize,
1317     pub col: CharPos,
1318     pub file: Option<Lrc<SourceFile>>,
1319 }
1320
1321 // Used to be structural records.
1322 #[derive(Debug)]
1323 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1324 #[derive(Debug)]
1325 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1326
1327 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1328 pub struct LineInfo {
1329     /// Index of line, starting from 0.
1330     pub line_index: usize,
1331
1332     /// Column in line where span begins, starting from 0.
1333     pub start_col: CharPos,
1334
1335     /// Column in line where span ends, starting from 0, exclusive.
1336     pub end_col: CharPos,
1337 }
1338
1339 pub struct FileLines {
1340     pub file: Lrc<SourceFile>,
1341     pub lines: Vec<LineInfo>
1342 }
1343
1344 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1345                 Cell::new(default_span_debug));
1346
1347 #[derive(Debug)]
1348 pub struct MacroBacktrace {
1349     /// span where macro was applied to generate this code
1350     pub call_site: Span,
1351
1352     /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1353     pub macro_decl_name: String,
1354
1355     /// span where macro was defined (if known)
1356     pub def_site_span: Option<Span>,
1357 }
1358
1359 // _____________________________________________________________________________
1360 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1361 //
1362
1363 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1364
1365 #[derive(Clone, PartialEq, Eq, Debug)]
1366 pub enum SpanLinesError {
1367     IllFormedSpan(Span),
1368     DistinctSources(DistinctSources),
1369 }
1370
1371 #[derive(Clone, PartialEq, Eq, Debug)]
1372 pub enum SpanSnippetError {
1373     IllFormedSpan(Span),
1374     DistinctSources(DistinctSources),
1375     MalformedForSourcemap(MalformedSourceMapPositions),
1376     SourceNotAvailable { filename: FileName }
1377 }
1378
1379 #[derive(Clone, PartialEq, Eq, Debug)]
1380 pub struct DistinctSources {
1381     pub begin: (FileName, BytePos),
1382     pub end: (FileName, BytePos)
1383 }
1384
1385 #[derive(Clone, PartialEq, Eq, Debug)]
1386 pub struct MalformedSourceMapPositions {
1387     pub name: FileName,
1388     pub source_len: usize,
1389     pub begin_pos: BytePos,
1390     pub end_pos: BytePos
1391 }
1392
1393 // Given a slice of line start positions and a position, returns the index of
1394 // the line the position is on. Returns -1 if the position is located before
1395 // the first line.
1396 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1397     match lines.binary_search(&pos) {
1398         Ok(line) => line as isize,
1399         Err(line) => line as isize - 1
1400     }
1401 }
1402
1403 #[cfg(test)]
1404 mod tests {
1405     use super::{lookup_line, BytePos};
1406
1407     #[test]
1408     fn test_lookup_line() {
1409
1410         let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1411
1412         assert_eq!(lookup_line(lines, BytePos(0)), -1);
1413         assert_eq!(lookup_line(lines, BytePos(3)),  0);
1414         assert_eq!(lookup_line(lines, BytePos(4)),  0);
1415
1416         assert_eq!(lookup_line(lines, BytePos(16)), 0);
1417         assert_eq!(lookup_line(lines, BytePos(17)), 1);
1418         assert_eq!(lookup_line(lines, BytePos(18)), 1);
1419
1420         assert_eq!(lookup_line(lines, BytePos(28)), 2);
1421         assert_eq!(lookup_line(lines, BytePos(29)), 2);
1422     }
1423 }