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