]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/lib.rs
Auto merge of #61373 - tmandry:emit-storagedead-along-unwind, r=eddyb
[rust.git] / src / libsyntax_pos / lib.rs
1 //! The source positions and related helper functions.
2 //!
3 //! ## Note
4 //!
5 //! This API is completely unstable and subject to change.
6
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
8
9 #![deny(rust_2018_idioms)]
10 #![deny(internal)]
11
12 #![feature(const_fn)]
13 #![feature(crate_visibility_modifier)]
14 #![feature(custom_attribute)]
15 #![feature(nll)]
16 #![feature(non_exhaustive)]
17 #![feature(optin_builtin_traits)]
18 #![feature(rustc_attrs)]
19 #![feature(proc_macro_hygiene)]
20 #![feature(specialization)]
21 #![feature(step_trait)]
22
23 use serialize::{Encodable, Decodable, Encoder, Decoder};
24
25 #[allow(unused_extern_crates)]
26 extern crate serialize as rustc_serialize; // used by deriving
27
28 pub mod edition;
29 use edition::Edition;
30 pub mod hygiene;
31 pub use hygiene::{Mark, SyntaxContext, ExpnInfo, ExpnFormat, CompilerDesugaringKind};
32
33 mod span_encoding;
34 pub use span_encoding::{Span, DUMMY_SP};
35
36 pub mod symbol;
37 pub use symbol::{Symbol, sym};
38
39 mod analyze_source_file;
40
41 use rustc_data_structures::stable_hasher::StableHasher;
42 use rustc_data_structures::sync::{Lrc, Lock};
43
44 use std::borrow::Cow;
45 use std::cell::Cell;
46 use std::cmp::{self, Ordering};
47 use std::fmt;
48 use std::hash::{Hasher, Hash};
49 use std::ops::{Add, Sub};
50 use std::path::PathBuf;
51
52 pub struct Globals {
53     symbol_interner: Lock<symbol::Interner>,
54     span_interner: Lock<span_encoding::SpanInterner>,
55     hygiene_data: Lock<hygiene::HygieneData>,
56     edition: Edition,
57 }
58
59 impl Globals {
60     pub fn new(edition: Edition) -> Globals {
61         Globals {
62             symbol_interner: Lock::new(symbol::Interner::fresh()),
63             span_interner: Lock::new(span_encoding::SpanInterner::default()),
64             hygiene_data: Lock::new(hygiene::HygieneData::new()),
65             edition,
66         }
67     }
68 }
69
70 scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
71
72 /// Differentiates between real files and common virtual files.
73 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)]
74 pub enum FileName {
75     Real(PathBuf),
76     /// A macro. This includes the full name of the macro, so that there are no clashes.
77     Macros(String),
78     /// Call to `quote!`.
79     QuoteExpansion(u64),
80     /// Command line.
81     Anon(u64),
82     /// Hack in `src/libsyntax/parse.rs`.
83     // FIXME(jseyfried)
84     MacroExpansion(u64),
85     ProcMacroSourceCode(u64),
86     /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`.
87     CfgSpec(u64),
88     /// Strings provided as crate attributes in the CLI.
89     CliCrateAttr(u64),
90     /// Custom sources for explicit parser calls from plugins and drivers.
91     Custom(String),
92     DocTest(PathBuf, isize),
93 }
94
95 impl std::fmt::Display for FileName {
96     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97         use FileName::*;
98         match *self {
99             Real(ref path) => write!(fmt, "{}", path.display()),
100             Macros(ref name) => write!(fmt, "<{} macros>", name),
101             QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
102             MacroExpansion(_) => write!(fmt, "<macro expansion>"),
103             Anon(_) => write!(fmt, "<anon>"),
104             ProcMacroSourceCode(_) =>
105                 write!(fmt, "<proc-macro source code>"),
106             CfgSpec(_) => write!(fmt, "<cfgspec>"),
107             CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
108             Custom(ref s) => write!(fmt, "<{}>", s),
109             DocTest(ref path, _) => write!(fmt, "{}", path.display()),
110         }
111     }
112 }
113
114 impl From<PathBuf> for FileName {
115     fn from(p: PathBuf) -> Self {
116         assert!(!p.to_string_lossy().ends_with('>'));
117         FileName::Real(p)
118     }
119 }
120
121 impl FileName {
122     pub fn is_real(&self) -> bool {
123         use FileName::*;
124         match *self {
125             Real(_) => true,
126             Macros(_) |
127             Anon(_) |
128             MacroExpansion(_) |
129             ProcMacroSourceCode(_) |
130             CfgSpec(_) |
131             CliCrateAttr(_) |
132             Custom(_) |
133             QuoteExpansion(_) |
134             DocTest(_, _) => false,
135         }
136     }
137
138     pub fn is_macros(&self) -> bool {
139         use FileName::*;
140         match *self {
141             Real(_) |
142             Anon(_) |
143             MacroExpansion(_) |
144             ProcMacroSourceCode(_) |
145             CfgSpec(_) |
146             CliCrateAttr(_) |
147             Custom(_) |
148             QuoteExpansion(_) |
149             DocTest(_, _) => false,
150             Macros(_) => true,
151         }
152     }
153
154     pub fn quote_expansion_source_code(src: &str) -> FileName {
155         let mut hasher = StableHasher::new();
156         src.hash(&mut hasher);
157         FileName::QuoteExpansion(hasher.finish())
158     }
159
160     pub fn macro_expansion_source_code(src: &str) -> FileName {
161         let mut hasher = StableHasher::new();
162         src.hash(&mut hasher);
163         FileName::MacroExpansion(hasher.finish())
164     }
165
166     pub fn anon_source_code(src: &str) -> FileName {
167         let mut hasher = StableHasher::new();
168         src.hash(&mut hasher);
169         FileName::Anon(hasher.finish())
170     }
171
172     pub fn proc_macro_source_code(src: &str) -> FileName {
173         let mut hasher = StableHasher::new();
174         src.hash(&mut hasher);
175         FileName::ProcMacroSourceCode(hasher.finish())
176     }
177
178     pub fn cfg_spec_source_code(src: &str) -> FileName {
179         let mut hasher = StableHasher::new();
180         src.hash(&mut hasher);
181         FileName::QuoteExpansion(hasher.finish())
182     }
183
184     pub fn cli_crate_attr_source_code(src: &str) -> FileName {
185         let mut hasher = StableHasher::new();
186         src.hash(&mut hasher);
187         FileName::CliCrateAttr(hasher.finish())
188     }
189
190     pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{
191         FileName::DocTest(path, line)
192     }
193 }
194
195 /// Spans represent a region of code, used for error reporting. Positions in spans
196 /// are *absolute* positions from the beginning of the source_map, not positions
197 /// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back
198 /// to the original source.
199 /// You must be careful if the span crosses more than one file - you will not be
200 /// able to use many of the functions on spans in source_map and you cannot assume
201 /// that the length of the `span = hi - lo`; there may be space in the `BytePos`
202 /// range between files.
203 ///
204 /// `SpanData` is public because `Span` uses a thread-local interner and can't be
205 /// sent to other threads, but some pieces of performance infra run in a separate thread.
206 /// Using `Span` is generally preferred.
207 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
208 pub struct SpanData {
209     pub lo: BytePos,
210     pub hi: BytePos,
211     /// Information about where the macro came from, if this piece of
212     /// code was created by a macro expansion.
213     pub ctxt: SyntaxContext,
214 }
215
216 impl SpanData {
217     #[inline]
218     pub fn with_lo(&self, lo: BytePos) -> Span {
219         Span::new(lo, self.hi, self.ctxt)
220     }
221     #[inline]
222     pub fn with_hi(&self, hi: BytePos) -> Span {
223         Span::new(self.lo, hi, self.ctxt)
224     }
225     #[inline]
226     pub fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
227         Span::new(self.lo, self.hi, ctxt)
228     }
229 }
230
231 // The interner is pointed to by a thread local value which is only set on the main thread
232 // with parallelization is disabled. So we don't allow `Span` to transfer between threads
233 // to avoid panics and other errors, even though it would be memory safe to do so.
234 #[cfg(not(parallel_compiler))]
235 impl !Send for Span {}
236 #[cfg(not(parallel_compiler))]
237 impl !Sync for Span {}
238
239 impl PartialOrd for Span {
240     fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
241         PartialOrd::partial_cmp(&self.data(), &rhs.data())
242     }
243 }
244 impl Ord for Span {
245     fn cmp(&self, rhs: &Self) -> Ordering {
246         Ord::cmp(&self.data(), &rhs.data())
247     }
248 }
249
250 /// A collection of spans. Spans have two orthogonal attributes:
251 ///
252 /// - They can be *primary spans*. In this case they are the locus of
253 ///   the error, and would be rendered with `^^^`.
254 /// - They can have a *label*. In this case, the label is written next
255 ///   to the mark in the snippet when we render.
256 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
257 pub struct MultiSpan {
258     primary_spans: Vec<Span>,
259     span_labels: Vec<(Span, String)>,
260 }
261
262 impl Span {
263     #[inline]
264     pub fn lo(self) -> BytePos {
265         self.data().lo
266     }
267     #[inline]
268     pub fn with_lo(self, lo: BytePos) -> Span {
269         self.data().with_lo(lo)
270     }
271     #[inline]
272     pub fn hi(self) -> BytePos {
273         self.data().hi
274     }
275     #[inline]
276     pub fn with_hi(self, hi: BytePos) -> Span {
277         self.data().with_hi(hi)
278     }
279     #[inline]
280     pub fn ctxt(self) -> SyntaxContext {
281         self.data().ctxt
282     }
283     #[inline]
284     pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
285         self.data().with_ctxt(ctxt)
286     }
287
288     /// Returns `true` if this is a dummy span with any hygienic context.
289     #[inline]
290     pub fn is_dummy(self) -> bool {
291         let span = self.data();
292         span.lo.0 == 0 && span.hi.0 == 0
293     }
294
295     /// Returns a new span representing an empty span at the beginning of this span
296     #[inline]
297     pub fn shrink_to_lo(self) -> Span {
298         let span = self.data();
299         span.with_hi(span.lo)
300     }
301     /// Returns a new span representing an empty span at the end of this span.
302     #[inline]
303     pub fn shrink_to_hi(self) -> Span {
304         let span = self.data();
305         span.with_lo(span.hi)
306     }
307
308     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
309     pub fn substitute_dummy(self, other: Span) -> Span {
310         if self.is_dummy() { other } else { self }
311     }
312
313     /// Returns `true` if `self` fully encloses `other`.
314     pub fn contains(self, other: Span) -> bool {
315         let span = self.data();
316         let other = other.data();
317         span.lo <= other.lo && other.hi <= span.hi
318     }
319
320     /// Returns `true` if `self` touches `other`.
321     pub fn overlaps(self, other: Span) -> bool {
322         let span = self.data();
323         let other = other.data();
324         span.lo < other.hi && other.lo < span.hi
325     }
326
327     /// Returns `true` if the spans are equal with regards to the source text.
328     ///
329     /// Use this instead of `==` when either span could be generated code,
330     /// and you only care that they point to the same bytes of source text.
331     pub fn source_equal(&self, other: &Span) -> bool {
332         let span = self.data();
333         let other = other.data();
334         span.lo == other.lo && span.hi == other.hi
335     }
336
337     /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
338     pub fn trim_start(self, other: Span) -> Option<Span> {
339         let span = self.data();
340         let other = other.data();
341         if span.hi > other.hi {
342             Some(span.with_lo(cmp::max(span.lo, other.hi)))
343         } else {
344             None
345         }
346     }
347
348     /// Returns the source span -- this is either the supplied span, or the span for
349     /// the macro callsite that expanded to it.
350     pub fn source_callsite(self) -> Span {
351         self.ctxt().outer_expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
352     }
353
354     /// The `Span` for the tokens in the previous macro expansion from which `self` was generated,
355     /// if any.
356     pub fn parent(self) -> Option<Span> {
357         self.ctxt().outer_expn_info().map(|i| i.call_site)
358     }
359
360     /// Edition of the crate from which this span came.
361     pub fn edition(self) -> edition::Edition {
362         self.ctxt().outer_expn_info().map_or_else(|| {
363             Edition::from_session()
364         }, |einfo| einfo.edition)
365     }
366
367     #[inline]
368     pub fn rust_2015(&self) -> bool {
369         self.edition() == edition::Edition::Edition2015
370     }
371
372     #[inline]
373     pub fn rust_2018(&self) -> bool {
374         self.edition() >= edition::Edition::Edition2018
375     }
376
377     /// Returns the source callee.
378     ///
379     /// Returns `None` if the supplied span has no expansion trace,
380     /// else returns the `ExpnInfo` for the macro definition
381     /// corresponding to the source callsite.
382     pub fn source_callee(self) -> Option<ExpnInfo> {
383         fn source_callee(info: ExpnInfo) -> ExpnInfo {
384             match info.call_site.ctxt().outer_expn_info() {
385                 Some(info) => source_callee(info),
386                 None => info,
387             }
388         }
389         self.ctxt().outer_expn_info().map(source_callee)
390     }
391
392     /// Checks if a span is "internal" to a macro in which `#[unstable]`
393     /// items can be used (that is, a macro marked with
394     /// `#[allow_internal_unstable]`).
395     pub fn allows_unstable(&self, feature: Symbol) -> bool {
396         match self.ctxt().outer_expn_info() {
397             Some(info) => info
398                 .allow_internal_unstable
399                 .map_or(false, |features| features.iter().any(|&f|
400                     f == feature || f == sym::allow_internal_unstable_backcompat_hack
401                 )),
402             None => false,
403         }
404     }
405
406     /// Checks if this span arises from a compiler desugaring of kind `kind`.
407     pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
408         match self.ctxt().outer_expn_info() {
409             Some(info) => match info.format {
410                 ExpnFormat::CompilerDesugaring(k) => k == kind,
411                 _ => false,
412             },
413             None => false,
414         }
415     }
416
417     /// Returns the compiler desugaring that created this span, or `None`
418     /// if this span is not from a desugaring.
419     pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
420         match self.ctxt().outer_expn_info() {
421             Some(info) => match info.format {
422                 ExpnFormat::CompilerDesugaring(k) => Some(k),
423                 _ => None
424             },
425             None => None
426         }
427     }
428
429     /// Checks if a span is "internal" to a macro in which `unsafe`
430     /// can be used without triggering the `unsafe_code` lint
431     //  (that is, a macro marked with `#[allow_internal_unsafe]`).
432     pub fn allows_unsafe(&self) -> bool {
433         match self.ctxt().outer_expn_info() {
434             Some(info) => info.allow_internal_unsafe,
435             None => false,
436         }
437     }
438
439     pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
440         let mut prev_span = DUMMY_SP;
441         let mut result = vec![];
442         while let Some(info) = self.ctxt().outer_expn_info() {
443             // Don't print recursive invocations.
444             if !info.call_site.source_equal(&prev_span) {
445                 let (pre, post) = match info.format {
446                     ExpnFormat::MacroAttribute(..) => ("#[", "]"),
447                     ExpnFormat::MacroBang(..) => ("", "!"),
448                     ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
449                 };
450                 result.push(MacroBacktrace {
451                     call_site: info.call_site,
452                     macro_decl_name: format!("{}{}{}", pre, info.format.name(), 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_byte_pos(self, start: usize, end: usize) -> Span {
509         let span = self.data();
510         Span::new(span.lo + BytePos::from_usize(start),
511                   span.lo + BytePos::from_usize(end),
512                   span.ctxt)
513     }
514
515     #[inline]
516     pub fn apply_mark(self, mark: Mark) -> 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) -> Mark {
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, expansion: Mark) -> Option<Mark> {
531         let mut span = self.data();
532         let mark = span.ctxt.adjust(expansion);
533         *self = Span::new(span.lo, span.hi, span.ctxt);
534         mark
535     }
536
537     #[inline]
538     pub fn modernize_and_adjust(&mut self, expansion: Mark) -> Option<Mark> {
539         let mut span = self.data();
540         let mark = span.ctxt.modernize_and_adjust(expansion);
541         *self = Span::new(span.lo, span.hi, span.ctxt);
542         mark
543     }
544
545     #[inline]
546     pub fn glob_adjust(&mut self, expansion: Mark, glob_span: Span) -> Option<Option<Mark>> {
547         let mut span = self.data();
548         let mark = span.ctxt.glob_adjust(expansion, 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, expansion: Mark, glob_span: Span)
555                                -> Option<Option<Mark>> {
556         let mut span = self.data();
557         let mark = span.ctxt.reverse_glob_adjust(expansion, 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 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 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 /// 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) -> SourceFile {
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
1058         let (lines, multibyte_chars, non_narrow_chars) =
1059             analyze_source_file::analyze_source_file(&src[..], start_pos);
1060
1061         SourceFile {
1062             name,
1063             name_was_remapped,
1064             unmapped_path: Some(unmapped_path),
1065             crate_of_origin: 0,
1066             src: Some(Lrc::new(src)),
1067             src_hash,
1068             external_src: Lock::new(ExternalSource::Unneeded),
1069             start_pos,
1070             end_pos: Pos::from_usize(end_pos),
1071             lines,
1072             multibyte_chars,
1073             non_narrow_chars,
1074             name_hash,
1075         }
1076     }
1077
1078     /// Returns the `BytePos` of the beginning of the current line.
1079     pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
1080         let line_index = self.lookup_line(pos).unwrap();
1081         self.lines[line_index]
1082     }
1083
1084     /// Add externally loaded source.
1085     /// If the hash of the input doesn't match or no input is supplied via None,
1086     /// it is interpreted as an error and the corresponding enum variant is set.
1087     /// The return value signifies whether some kind of source is present.
1088     pub fn add_external_src<F>(&self, get_src: F) -> bool
1089         where F: FnOnce() -> Option<String>
1090     {
1091         if *self.external_src.borrow() == ExternalSource::AbsentOk {
1092             let src = get_src();
1093             let mut external_src = self.external_src.borrow_mut();
1094             // Check that no-one else have provided the source while we were getting it
1095             if *external_src == ExternalSource::AbsentOk {
1096                 if let Some(src) = src {
1097                     let mut hasher: StableHasher<u128> = StableHasher::new();
1098                     hasher.write(src.as_bytes());
1099
1100                     if hasher.finish() == self.src_hash {
1101                         *external_src = ExternalSource::Present(src);
1102                         return true;
1103                     }
1104                 } else {
1105                     *external_src = ExternalSource::AbsentErr;
1106                 }
1107
1108                 false
1109             } else {
1110                 self.src.is_some() || external_src.get_source().is_some()
1111             }
1112         } else {
1113             self.src.is_some() || self.external_src.borrow().get_source().is_some()
1114         }
1115     }
1116
1117     /// Gets a line from the list of pre-computed line-beginnings.
1118     /// The line number here is 0-based.
1119     pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
1120         fn get_until_newline(src: &str, begin: usize) -> &str {
1121             // We can't use `lines.get(line_number+1)` because we might
1122             // be parsing when we call this function and thus the current
1123             // line is the last one we have line info for.
1124             let slice = &src[begin..];
1125             match slice.find('\n') {
1126                 Some(e) => &slice[..e],
1127                 None => slice
1128             }
1129         }
1130
1131         let begin = {
1132             let line = if let Some(line) = self.lines.get(line_number) {
1133                 line
1134             } else {
1135                 return None;
1136             };
1137             let begin: BytePos = *line - self.start_pos;
1138             begin.to_usize()
1139         };
1140
1141         if let Some(ref src) = self.src {
1142             Some(Cow::from(get_until_newline(src, begin)))
1143         } else if let Some(src) = self.external_src.borrow().get_source() {
1144             Some(Cow::Owned(String::from(get_until_newline(src, begin))))
1145         } else {
1146             None
1147         }
1148     }
1149
1150     pub fn is_real_file(&self) -> bool {
1151         self.name.is_real()
1152     }
1153
1154     pub fn is_imported(&self) -> bool {
1155         self.src.is_none()
1156     }
1157
1158     pub fn byte_length(&self) -> u32 {
1159         self.end_pos.0 - self.start_pos.0
1160     }
1161     pub fn count_lines(&self) -> usize {
1162         self.lines.len()
1163     }
1164
1165     /// Finds the line containing the given position. The return value is the
1166     /// index into the `lines` array of this `SourceFile`, not the 1-based line
1167     /// number. If the source_file is empty or the position is located before the
1168     /// first line, `None` is returned.
1169     pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
1170         if self.lines.len() == 0 {
1171             return None;
1172         }
1173
1174         let line_index = lookup_line(&self.lines[..], pos);
1175         assert!(line_index < self.lines.len() as isize);
1176         if line_index >= 0 {
1177             Some(line_index as usize)
1178         } else {
1179             None
1180         }
1181     }
1182
1183     pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
1184         if self.start_pos == self.end_pos {
1185             return (self.start_pos, self.end_pos);
1186         }
1187
1188         assert!(line_index < self.lines.len());
1189         if line_index == (self.lines.len() - 1) {
1190             (self.lines[line_index], self.end_pos)
1191         } else {
1192             (self.lines[line_index], self.lines[line_index + 1])
1193         }
1194     }
1195
1196     #[inline]
1197     pub fn contains(&self, byte_pos: BytePos) -> bool {
1198         byte_pos >= self.start_pos && byte_pos <= self.end_pos
1199     }
1200 }
1201
1202 /// Removes UTF-8 BOM, if any.
1203 fn remove_bom(src: &mut String) {
1204     if src.starts_with("\u{feff}") {
1205         src.drain(..3);
1206     }
1207 }
1208
1209 // _____________________________________________________________________________
1210 // Pos, BytePos, CharPos
1211 //
1212
1213 pub trait Pos {
1214     fn from_usize(n: usize) -> Self;
1215     fn to_usize(&self) -> usize;
1216     fn from_u32(n: u32) -> Self;
1217     fn to_u32(&self) -> u32;
1218 }
1219
1220 /// A byte offset. Keep this small (currently 32-bits), as AST contains
1221 /// a lot of them.
1222 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1223 pub struct BytePos(pub u32);
1224
1225 /// A character offset. Because of multibyte UTF-8 characters, a byte offset
1226 /// is not equivalent to a character offset. The `SourceMap` will convert `BytePos`
1227 /// values to `CharPos` values as necessary.
1228 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1229 pub struct CharPos(pub usize);
1230
1231 // FIXME: lots of boilerplate in these impls, but so far my attempts to fix
1232 // have been unsuccessful.
1233
1234 impl Pos for BytePos {
1235     #[inline(always)]
1236     fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
1237
1238     #[inline(always)]
1239     fn to_usize(&self) -> usize { self.0 as usize }
1240
1241     #[inline(always)]
1242     fn from_u32(n: u32) -> BytePos { BytePos(n) }
1243
1244     #[inline(always)]
1245     fn to_u32(&self) -> u32 { self.0 }
1246 }
1247
1248 impl Add for BytePos {
1249     type Output = BytePos;
1250
1251     #[inline(always)]
1252     fn add(self, rhs: BytePos) -> BytePos {
1253         BytePos((self.to_usize() + rhs.to_usize()) as u32)
1254     }
1255 }
1256
1257 impl Sub for BytePos {
1258     type Output = BytePos;
1259
1260     #[inline(always)]
1261     fn sub(self, rhs: BytePos) -> BytePos {
1262         BytePos((self.to_usize() - rhs.to_usize()) as u32)
1263     }
1264 }
1265
1266 impl Encodable for BytePos {
1267     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
1268         s.emit_u32(self.0)
1269     }
1270 }
1271
1272 impl Decodable for BytePos {
1273     fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
1274         Ok(BytePos(d.read_u32()?))
1275     }
1276 }
1277
1278 impl Pos for CharPos {
1279     #[inline(always)]
1280     fn from_usize(n: usize) -> CharPos { CharPos(n) }
1281
1282     #[inline(always)]
1283     fn to_usize(&self) -> usize { self.0 }
1284
1285     #[inline(always)]
1286     fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
1287
1288     #[inline(always)]
1289     fn to_u32(&self) -> u32 { self.0 as u32}
1290 }
1291
1292 impl Add for CharPos {
1293     type Output = CharPos;
1294
1295     #[inline(always)]
1296     fn add(self, rhs: CharPos) -> CharPos {
1297         CharPos(self.to_usize() + rhs.to_usize())
1298     }
1299 }
1300
1301 impl Sub for CharPos {
1302     type Output = CharPos;
1303
1304     #[inline(always)]
1305     fn sub(self, rhs: CharPos) -> CharPos {
1306         CharPos(self.to_usize() - rhs.to_usize())
1307     }
1308 }
1309
1310 // _____________________________________________________________________________
1311 // Loc, SourceFileAndLine, SourceFileAndBytePos
1312 //
1313
1314 /// A source code location used for error reporting.
1315 #[derive(Debug, Clone)]
1316 pub struct Loc {
1317     /// Information about the original source.
1318     pub file: Lrc<SourceFile>,
1319     /// The (1-based) line number.
1320     pub line: usize,
1321     /// The (0-based) column offset.
1322     pub col: CharPos,
1323     /// The (0-based) column offset when displayed.
1324     pub col_display: usize,
1325 }
1326
1327 // Used to be structural records.
1328 #[derive(Debug)]
1329 pub struct SourceFileAndLine { pub sf: Lrc<SourceFile>, pub line: usize }
1330 #[derive(Debug)]
1331 pub struct SourceFileAndBytePos { pub sf: Lrc<SourceFile>, pub pos: BytePos }
1332
1333 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1334 pub struct LineInfo {
1335     /// Index of line, starting from 0.
1336     pub line_index: usize,
1337
1338     /// Column in line where span begins, starting from 0.
1339     pub start_col: CharPos,
1340
1341     /// Column in line where span ends, starting from 0, exclusive.
1342     pub end_col: CharPos,
1343 }
1344
1345 pub struct FileLines {
1346     pub file: Lrc<SourceFile>,
1347     pub lines: Vec<LineInfo>
1348 }
1349
1350 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter<'_>) -> fmt::Result> =
1351                 Cell::new(default_span_debug));
1352
1353 #[derive(Debug)]
1354 pub struct MacroBacktrace {
1355     /// span where macro was applied to generate this code
1356     pub call_site: Span,
1357
1358     /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
1359     pub macro_decl_name: String,
1360
1361     /// span where macro was defined (if known)
1362     pub def_site_span: Option<Span>,
1363 }
1364
1365 // _____________________________________________________________________________
1366 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
1367 //
1368
1369 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
1370
1371 #[derive(Clone, PartialEq, Eq, Debug)]
1372 pub enum SpanLinesError {
1373     IllFormedSpan(Span),
1374     DistinctSources(DistinctSources),
1375 }
1376
1377 #[derive(Clone, PartialEq, Eq, Debug)]
1378 pub enum SpanSnippetError {
1379     IllFormedSpan(Span),
1380     DistinctSources(DistinctSources),
1381     MalformedForSourcemap(MalformedSourceMapPositions),
1382     SourceNotAvailable { filename: FileName }
1383 }
1384
1385 #[derive(Clone, PartialEq, Eq, Debug)]
1386 pub struct DistinctSources {
1387     pub begin: (FileName, BytePos),
1388     pub end: (FileName, BytePos)
1389 }
1390
1391 #[derive(Clone, PartialEq, Eq, Debug)]
1392 pub struct MalformedSourceMapPositions {
1393     pub name: FileName,
1394     pub source_len: usize,
1395     pub begin_pos: BytePos,
1396     pub end_pos: BytePos
1397 }
1398
1399 // Given a slice of line start positions and a position, returns the index of
1400 // the line the position is on. Returns -1 if the position is located before
1401 // the first line.
1402 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
1403     match lines.binary_search(&pos) {
1404         Ok(line) => line as isize,
1405         Err(line) => line as isize - 1
1406     }
1407 }
1408
1409 #[cfg(test)]
1410 mod tests {
1411     use super::{lookup_line, BytePos};
1412
1413     #[test]
1414     fn test_lookup_line() {
1415
1416         let lines = &[BytePos(3), BytePos(17), BytePos(28)];
1417
1418         assert_eq!(lookup_line(lines, BytePos(0)), -1);
1419         assert_eq!(lookup_line(lines, BytePos(3)),  0);
1420         assert_eq!(lookup_line(lines, BytePos(4)),  0);
1421
1422         assert_eq!(lookup_line(lines, BytePos(16)), 0);
1423         assert_eq!(lookup_line(lines, BytePos(17)), 1);
1424         assert_eq!(lookup_line(lines, BytePos(18)), 1);
1425
1426         assert_eq!(lookup_line(lines, BytePos(28)), 2);
1427         assert_eq!(lookup_line(lines, BytePos(29)), 2);
1428     }
1429 }