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