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