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