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