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