]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/lib.rs
rustdoc: pretty-print Unevaluated expressions in types.
[rust.git] / src / libsyntax_pos / lib.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The source positions and related helper functions
12 //!
13 //! # Note
14 //!
15 //! This API is completely unstable and subject to change.
16
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19       html_root_url = "https://doc.rust-lang.org/nightly/")]
20 #![deny(warnings)]
21
22 #![feature(const_fn)]
23 #![feature(custom_attribute)]
24 #![feature(i128_type)]
25 #![feature(optin_builtin_traits)]
26 #![allow(unused_attributes)]
27 #![feature(specialization)]
28 #![feature(staged_api)]
29
30 use std::borrow::Cow;
31 use std::cell::{Cell, RefCell};
32 use std::cmp;
33 use std::fmt;
34 use std::hash::Hasher;
35 use std::ops::{Add, Sub};
36 use std::rc::Rc;
37
38 use rustc_data_structures::stable_hasher::StableHasher;
39
40 extern crate rustc_data_structures;
41
42 use serialize::{Encodable, Decodable, Encoder, Decoder};
43
44 extern crate serialize;
45 extern crate serialize as rustc_serialize; // used by deriving
46
47 pub mod hygiene;
48 pub use hygiene::{SyntaxContext, ExpnInfo, ExpnFormat, NameAndSpan, CompilerDesugaringKind};
49
50 pub mod symbol;
51
52 pub type FileName = String;
53
54 /// Spans represent a region of code, used for error reporting. Positions in spans
55 /// are *absolute* positions from the beginning of the codemap, not positions
56 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
57 /// to the original source.
58 /// You must be careful if the span crosses more than one file - you will not be
59 /// able to use many of the functions on spans in codemap and you cannot assume
60 /// that the length of the span = hi - lo; there may be space in the BytePos
61 /// range between files.
62 #[derive(Clone, Copy, Hash, PartialEq, Eq, Ord, PartialOrd)]
63 pub struct Span {
64     #[unstable(feature = "rustc_private", issue = "27812")]
65     #[rustc_deprecated(since = "1.21", reason = "use getters/setters instead")]
66     pub lo: BytePos,
67     #[unstable(feature = "rustc_private", issue = "27812")]
68     #[rustc_deprecated(since = "1.21", reason = "use getters/setters instead")]
69     pub hi: BytePos,
70     /// Information about where the macro came from, if this piece of
71     /// code was created by a macro expansion.
72     #[unstable(feature = "rustc_private", issue = "27812")]
73     #[rustc_deprecated(since = "1.21", reason = "use getters/setters instead")]
74     pub ctxt: SyntaxContext,
75 }
76
77 #[allow(deprecated)]
78 pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), ctxt: NO_EXPANSION };
79
80 /// A collection of spans. Spans have two orthogonal attributes:
81 ///
82 /// - they can be *primary spans*. In this case they are the locus of
83 ///   the error, and would be rendered with `^^^`.
84 /// - they can have a *label*. In this case, the label is written next
85 ///   to the mark in the snippet when we render.
86 #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
87 pub struct MultiSpan {
88     primary_spans: Vec<Span>,
89     span_labels: Vec<(Span, String)>,
90 }
91
92 impl Span {
93     #[allow(deprecated)]
94     #[inline]
95     pub fn new(lo: BytePos, hi: BytePos, ctxt: SyntaxContext) -> Self {
96         if lo <= hi { Span { lo, hi, ctxt } } else { Span { lo: hi, hi: lo, ctxt } }
97     }
98
99     #[allow(deprecated)]
100     #[inline]
101     pub fn lo(self) -> BytePos {
102         self.lo
103     }
104     #[inline]
105     pub fn with_lo(self, lo: BytePos) -> Span {
106         Span::new(lo, self.hi(), self.ctxt())
107     }
108     #[allow(deprecated)]
109     #[inline]
110     pub fn hi(self) -> BytePos {
111         self.hi
112     }
113     #[inline]
114     pub fn with_hi(self, hi: BytePos) -> Span {
115         Span::new(self.lo(), hi, self.ctxt())
116     }
117     #[allow(deprecated)]
118     #[inline]
119     pub fn ctxt(self) -> SyntaxContext {
120         self.ctxt
121     }
122     #[inline]
123     pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
124         Span::new(self.lo(), self.hi(), ctxt)
125     }
126
127     /// Returns a new span representing just the end-point of this span
128     pub fn end_point(self) -> Span {
129         let lo = cmp::max(self.hi().0 - 1, self.lo().0);
130         self.with_lo(BytePos(lo))
131     }
132
133     /// Returns a new span representing the next character after the end-point of this span
134     pub fn next_point(self) -> Span {
135         let lo = cmp::max(self.hi().0, self.lo().0 + 1);
136         Span::new(BytePos(lo), BytePos(lo), self.ctxt())
137     }
138
139     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
140     pub fn substitute_dummy(self, other: Span) -> Span {
141         if self.source_equal(&DUMMY_SP) { other } else { self }
142     }
143
144     /// Return true if `self` fully encloses `other`.
145     pub fn contains(self, other: Span) -> bool {
146         self.lo() <= other.lo() && other.hi() <= self.hi()
147     }
148
149     /// Return true if the spans are equal with regards to the source text.
150     ///
151     /// Use this instead of `==` when either span could be generated code,
152     /// and you only care that they point to the same bytes of source text.
153     pub fn source_equal(&self, other: &Span) -> bool {
154         self.lo() == other.lo() && self.hi() == other.hi()
155     }
156
157     /// Returns `Some(span)`, where the start is trimmed by the end of `other`
158     pub fn trim_start(self, other: Span) -> Option<Span> {
159         if self.hi() > other.hi() {
160             Some(self.with_lo(cmp::max(self.lo(), other.hi())))
161         } else {
162             None
163         }
164     }
165
166     /// Return the source span - this is either the supplied span, or the span for
167     /// the macro callsite that expanded to it.
168     pub fn source_callsite(self) -> Span {
169         self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self)
170     }
171
172     /// Return the source callee.
173     ///
174     /// Returns None if the supplied span has no expansion trace,
175     /// else returns the NameAndSpan for the macro definition
176     /// corresponding to the source callsite.
177     pub fn source_callee(self) -> Option<NameAndSpan> {
178         fn source_callee(info: ExpnInfo) -> NameAndSpan {
179             match info.call_site.ctxt().outer().expn_info() {
180                 Some(info) => source_callee(info),
181                 None => info.callee,
182             }
183         }
184         self.ctxt().outer().expn_info().map(source_callee)
185     }
186
187     /// Check if a span is "internal" to a macro in which #[unstable]
188     /// items can be used (that is, a macro marked with
189     /// `#[allow_internal_unstable]`).
190     pub fn allows_unstable(&self) -> bool {
191         match self.ctxt().outer().expn_info() {
192             Some(info) => info.callee.allow_internal_unstable,
193             None => false,
194         }
195     }
196
197     /// Check if this span arises from a compiler desugaring of kind `kind`.
198     pub fn is_compiler_desugaring(&self, kind: CompilerDesugaringKind) -> bool {
199         match self.ctxt().outer().expn_info() {
200             Some(info) => match info.callee.format {
201                 ExpnFormat::CompilerDesugaring(k) => k == kind,
202                 _ => false,
203             },
204             None => false,
205         }
206     }
207
208     /// Return the compiler desugaring that created this span, or None
209     /// if this span is not from a desugaring.
210     pub fn compiler_desugaring_kind(&self) -> Option<CompilerDesugaringKind> {
211         match self.ctxt().outer().expn_info() {
212             Some(info) => match info.callee.format {
213                 ExpnFormat::CompilerDesugaring(k) => Some(k),
214                 _ => None
215             },
216             None => None
217         }
218     }
219
220     /// Check if a span is "internal" to a macro in which `unsafe`
221     /// can be used without triggering the `unsafe_code` lint
222     //  (that is, a macro marked with `#[allow_internal_unsafe]`).
223     pub fn allows_unsafe(&self) -> bool {
224         match self.ctxt().outer().expn_info() {
225             Some(info) => info.callee.allow_internal_unsafe,
226             None => false,
227         }
228     }
229
230     pub fn macro_backtrace(mut self) -> Vec<MacroBacktrace> {
231         let mut prev_span = DUMMY_SP;
232         let mut result = vec![];
233         loop {
234             let info = match self.ctxt().outer().expn_info() {
235                 Some(info) => info,
236                 None => break,
237             };
238
239             let (pre, post) = match info.callee.format {
240                 ExpnFormat::MacroAttribute(..) => ("#[", "]"),
241                 ExpnFormat::MacroBang(..) => ("", "!"),
242                 ExpnFormat::CompilerDesugaring(..) => ("desugaring of `", "`"),
243             };
244             let macro_decl_name = format!("{}{}{}", pre, info.callee.name(), post);
245             let def_site_span = info.callee.span;
246
247             // Don't print recursive invocations
248             if !info.call_site.source_equal(&prev_span) {
249                 result.push(MacroBacktrace {
250                     call_site: info.call_site,
251                     macro_decl_name,
252                     def_site_span,
253                 });
254             }
255
256             prev_span = self;
257             self = info.call_site;
258         }
259         result
260     }
261
262     /// Return a `Span` that would enclose both `self` and `end`.
263     pub fn to(self, end: Span) -> Span {
264         Span::new(
265             cmp::min(self.lo(), end.lo()),
266             cmp::max(self.hi(), end.hi()),
267             // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480)
268             if self.ctxt() == SyntaxContext::empty() { end.ctxt() } else { self.ctxt() },
269         )
270     }
271
272     /// Return a `Span` between the end of `self` to the beginning of `end`.
273     pub fn between(self, end: Span) -> Span {
274         Span::new(
275             self.hi(),
276             end.lo(),
277             if end.ctxt() == SyntaxContext::empty() { end.ctxt() } else { self.ctxt() },
278         )
279     }
280
281     /// Return a `Span` between the beginning of `self` to the beginning of `end`.
282     pub fn until(self, end: Span) -> Span {
283         Span::new(
284             self.lo(),
285             end.lo(),
286             if end.ctxt() == SyntaxContext::empty() { end.ctxt() } else { self.ctxt() },
287         )
288     }
289 }
290
291 #[derive(Clone, Debug)]
292 pub struct SpanLabel {
293     /// The span we are going to include in the final snippet.
294     pub span: Span,
295
296     /// Is this a primary span? This is the "locus" of the message,
297     /// and is indicated with a `^^^^` underline, versus `----`.
298     pub is_primary: bool,
299
300     /// What label should we attach to this span (if any)?
301     pub label: Option<String>,
302 }
303
304 impl Default for Span {
305     fn default() -> Self {
306         DUMMY_SP
307     }
308 }
309
310 impl serialize::UseSpecializedEncodable for Span {
311     fn default_encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
312         s.emit_struct("Span", 2, |s| {
313             s.emit_struct_field("lo", 0, |s| {
314                 self.lo().encode(s)
315             })?;
316
317             s.emit_struct_field("hi", 1, |s| {
318                 self.hi().encode(s)
319             })
320         })
321     }
322 }
323
324 impl serialize::UseSpecializedDecodable for Span {
325     fn default_decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
326         d.read_struct("Span", 2, |d| {
327             let lo = d.read_struct_field("lo", 0, Decodable::decode)?;
328             let hi = d.read_struct_field("hi", 1, Decodable::decode)?;
329             Ok(Span::new(lo, hi, NO_EXPANSION))
330         })
331     }
332 }
333
334 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
335     write!(f, "Span {{ lo: {:?}, hi: {:?}, ctxt: {:?} }}",
336            span.lo(), span.hi(), span.ctxt())
337 }
338
339 impl fmt::Debug for Span {
340     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
341         SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
342     }
343 }
344
345 impl MultiSpan {
346     pub fn new() -> MultiSpan {
347         MultiSpan {
348             primary_spans: vec![],
349             span_labels: vec![]
350         }
351     }
352
353     pub fn from_span(primary_span: Span) -> MultiSpan {
354         MultiSpan {
355             primary_spans: vec![primary_span],
356             span_labels: vec![]
357         }
358     }
359
360     pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
361         MultiSpan {
362             primary_spans: vec,
363             span_labels: vec![]
364         }
365     }
366
367     pub fn push_span_label(&mut self, span: Span, label: String) {
368         self.span_labels.push((span, label));
369     }
370
371     /// Selects the first primary span (if any)
372     pub fn primary_span(&self) -> Option<Span> {
373         self.primary_spans.first().cloned()
374     }
375
376     /// Returns all primary spans.
377     pub fn primary_spans(&self) -> &[Span] {
378         &self.primary_spans
379     }
380
381     /// Replaces all occurrences of one Span with another. Used to move Spans in areas that don't
382     /// display well (like std macros). Returns true if replacements occurred.
383     pub fn replace(&mut self, before: Span, after: Span) -> bool {
384         let mut replacements_occurred = false;
385         for primary_span in &mut self.primary_spans {
386             if *primary_span == before {
387                 *primary_span = after;
388                 replacements_occurred = true;
389             }
390         }
391         for span_label in &mut self.span_labels {
392             if span_label.0 == before {
393                 span_label.0 = after;
394                 replacements_occurred = true;
395             }
396         }
397         replacements_occurred
398     }
399
400     /// Returns the strings to highlight. We always ensure that there
401     /// is an entry for each of the primary spans -- for each primary
402     /// span P, if there is at least one label with span P, we return
403     /// those labels (marked as primary). But otherwise we return
404     /// `SpanLabel` instances with empty labels.
405     pub fn span_labels(&self) -> Vec<SpanLabel> {
406         let is_primary = |span| self.primary_spans.contains(&span);
407         let mut span_labels = vec![];
408
409         for &(span, ref label) in &self.span_labels {
410             span_labels.push(SpanLabel {
411                 span,
412                 is_primary: is_primary(span),
413                 label: Some(label.clone())
414             });
415         }
416
417         for &span in &self.primary_spans {
418             if !span_labels.iter().any(|sl| sl.span == span) {
419                 span_labels.push(SpanLabel {
420                     span,
421                     is_primary: true,
422                     label: None
423                 });
424             }
425         }
426
427         span_labels
428     }
429 }
430
431 impl From<Span> for MultiSpan {
432     fn from(span: Span) -> MultiSpan {
433         MultiSpan::from_span(span)
434     }
435 }
436
437 pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty();
438
439 /// Identifies an offset of a multi-byte character in a FileMap
440 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
441 pub struct MultiByteChar {
442     /// The absolute offset of the character in the CodeMap
443     pub pos: BytePos,
444     /// The number of bytes, >=2
445     pub bytes: usize,
446 }
447
448 /// The state of the lazy external source loading mechanism of a FileMap.
449 #[derive(PartialEq, Eq, Clone)]
450 pub enum ExternalSource {
451     /// The external source has been loaded already.
452     Present(String),
453     /// No attempt has been made to load the external source.
454     AbsentOk,
455     /// A failed attempt has been made to load the external source.
456     AbsentErr,
457     /// No external source has to be loaded, since the FileMap represents a local crate.
458     Unneeded,
459 }
460
461 impl ExternalSource {
462     pub fn is_absent(&self) -> bool {
463         match *self {
464             ExternalSource::Present(_) => false,
465             _ => true,
466         }
467     }
468
469     pub fn get_source(&self) -> Option<&str> {
470         match *self {
471             ExternalSource::Present(ref src) => Some(src),
472             _ => None,
473         }
474     }
475 }
476
477 /// A single source in the CodeMap.
478 #[derive(Clone)]
479 pub struct FileMap {
480     /// The name of the file that the source came from, source that doesn't
481     /// originate from files has names between angle brackets by convention,
482     /// e.g. `<anon>`
483     pub name: FileName,
484     /// True if the `name` field above has been modified by -Zremap-path-prefix
485     pub name_was_remapped: bool,
486     /// Indicates which crate this FileMap was imported from.
487     pub crate_of_origin: u32,
488     /// The complete source code
489     pub src: Option<Rc<String>>,
490     /// The source code's hash
491     pub src_hash: u128,
492     /// The external source code (used for external crates, which will have a `None`
493     /// value as `self.src`.
494     pub external_src: RefCell<ExternalSource>,
495     /// The start position of this source in the CodeMap
496     pub start_pos: BytePos,
497     /// The end position of this source in the CodeMap
498     pub end_pos: BytePos,
499     /// Locations of lines beginnings in the source code
500     pub lines: RefCell<Vec<BytePos>>,
501     /// Locations of multi-byte characters in the source code
502     pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
503 }
504
505 impl Encodable for FileMap {
506     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
507         s.emit_struct("FileMap", 7, |s| {
508             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
509             s.emit_struct_field("name_was_remapped", 1, |s| self.name_was_remapped.encode(s))?;
510             s.emit_struct_field("src_hash", 6, |s| self.src_hash.encode(s))?;
511             s.emit_struct_field("start_pos", 2, |s| self.start_pos.encode(s))?;
512             s.emit_struct_field("end_pos", 3, |s| self.end_pos.encode(s))?;
513             s.emit_struct_field("lines", 4, |s| {
514                 let lines = self.lines.borrow();
515                 // store the length
516                 s.emit_u32(lines.len() as u32)?;
517
518                 if !lines.is_empty() {
519                     // In order to preserve some space, we exploit the fact that
520                     // the lines list is sorted and individual lines are
521                     // probably not that long. Because of that we can store lines
522                     // as a difference list, using as little space as possible
523                     // for the differences.
524                     let max_line_length = if lines.len() == 1 {
525                         0
526                     } else {
527                         lines.windows(2)
528                              .map(|w| w[1] - w[0])
529                              .map(|bp| bp.to_usize())
530                              .max()
531                              .unwrap()
532                     };
533
534                     let bytes_per_diff: u8 = match max_line_length {
535                         0 ... 0xFF => 1,
536                         0x100 ... 0xFFFF => 2,
537                         _ => 4
538                     };
539
540                     // Encode the number of bytes used per diff.
541                     bytes_per_diff.encode(s)?;
542
543                     // Encode the first element.
544                     lines[0].encode(s)?;
545
546                     let diff_iter = (&lines[..]).windows(2)
547                                                 .map(|w| (w[1] - w[0]));
548
549                     match bytes_per_diff {
550                         1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
551                         2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
552                         4 => for diff in diff_iter { diff.0.encode(s)? },
553                         _ => unreachable!()
554                     }
555                 }
556
557                 Ok(())
558             })?;
559             s.emit_struct_field("multibyte_chars", 5, |s| {
560                 (*self.multibyte_chars.borrow()).encode(s)
561             })
562         })
563     }
564 }
565
566 impl Decodable for FileMap {
567     fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
568
569         d.read_struct("FileMap", 6, |d| {
570             let name: String = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
571             let name_was_remapped: bool =
572                 d.read_struct_field("name_was_remapped", 1, |d| Decodable::decode(d))?;
573             let src_hash: u128 =
574                 d.read_struct_field("src_hash", 6, |d| Decodable::decode(d))?;
575             let start_pos: BytePos =
576                 d.read_struct_field("start_pos", 2, |d| Decodable::decode(d))?;
577             let end_pos: BytePos = d.read_struct_field("end_pos", 3, |d| Decodable::decode(d))?;
578             let lines: Vec<BytePos> = d.read_struct_field("lines", 4, |d| {
579                 let num_lines: u32 = Decodable::decode(d)?;
580                 let mut lines = Vec::with_capacity(num_lines as usize);
581
582                 if num_lines > 0 {
583                     // Read the number of bytes used per diff.
584                     let bytes_per_diff: u8 = Decodable::decode(d)?;
585
586                     // Read the first element.
587                     let mut line_start: BytePos = Decodable::decode(d)?;
588                     lines.push(line_start);
589
590                     for _ in 1..num_lines {
591                         let diff = match bytes_per_diff {
592                             1 => d.read_u8()? as u32,
593                             2 => d.read_u16()? as u32,
594                             4 => d.read_u32()?,
595                             _ => unreachable!()
596                         };
597
598                         line_start = line_start + BytePos(diff);
599
600                         lines.push(line_start);
601                     }
602                 }
603
604                 Ok(lines)
605             })?;
606             let multibyte_chars: Vec<MultiByteChar> =
607                 d.read_struct_field("multibyte_chars", 5, |d| Decodable::decode(d))?;
608             Ok(FileMap {
609                 name,
610                 name_was_remapped,
611                 // `crate_of_origin` has to be set by the importer.
612                 // This value matches up with rustc::hir::def_id::INVALID_CRATE.
613                 // That constant is not available here unfortunately :(
614                 crate_of_origin: ::std::u32::MAX - 1,
615                 start_pos,
616                 end_pos,
617                 src: None,
618                 src_hash,
619                 external_src: RefCell::new(ExternalSource::AbsentOk),
620                 lines: RefCell::new(lines),
621                 multibyte_chars: RefCell::new(multibyte_chars)
622             })
623         })
624     }
625 }
626
627 impl fmt::Debug for FileMap {
628     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
629         write!(fmt, "FileMap({})", self.name)
630     }
631 }
632
633 impl FileMap {
634     pub fn new(name: FileName,
635                name_was_remapped: bool,
636                mut src: String,
637                start_pos: BytePos) -> FileMap {
638         remove_bom(&mut src);
639
640         let mut hasher: StableHasher<u128> = StableHasher::new();
641         hasher.write(src.as_bytes());
642         let src_hash = hasher.finish();
643
644         let end_pos = start_pos.to_usize() + src.len();
645
646         FileMap {
647             name,
648             name_was_remapped,
649             crate_of_origin: 0,
650             src: Some(Rc::new(src)),
651             src_hash,
652             external_src: RefCell::new(ExternalSource::Unneeded),
653             start_pos,
654             end_pos: Pos::from_usize(end_pos),
655             lines: RefCell::new(Vec::new()),
656             multibyte_chars: RefCell::new(Vec::new()),
657         }
658     }
659
660     /// EFFECT: register a start-of-line offset in the
661     /// table of line-beginnings.
662     /// UNCHECKED INVARIANT: these offsets must be added in the right
663     /// order and must be in the right places; there is shared knowledge
664     /// about what ends a line between this file and parse.rs
665     /// WARNING: pos param here is the offset relative to start of CodeMap,
666     /// and CodeMap will append a newline when adding a filemap without a newline at the end,
667     /// so the safe way to call this is with value calculated as
668     /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
669     pub fn next_line(&self, pos: BytePos) {
670         // the new charpos must be > the last one (or it's the first one).
671         let mut lines = self.lines.borrow_mut();
672         let line_len = lines.len();
673         assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
674         lines.push(pos);
675     }
676
677     /// Add externally loaded source.
678     /// If the hash of the input doesn't match or no input is supplied via None,
679     /// it is interpreted as an error and the corresponding enum variant is set.
680     /// The return value signifies whether some kind of source is present.
681     pub fn add_external_src<F>(&self, get_src: F) -> bool
682         where F: FnOnce() -> Option<String>
683     {
684         if *self.external_src.borrow() == ExternalSource::AbsentOk {
685             let src = get_src();
686             let mut external_src = self.external_src.borrow_mut();
687             if let Some(src) = src {
688                 let mut hasher: StableHasher<u128> = StableHasher::new();
689                 hasher.write(src.as_bytes());
690
691                 if hasher.finish() == self.src_hash {
692                     *external_src = ExternalSource::Present(src);
693                     return true;
694                 }
695             } else {
696                 *external_src = ExternalSource::AbsentErr;
697             }
698
699             false
700         } else {
701             self.src.is_some() || self.external_src.borrow().get_source().is_some()
702         }
703     }
704
705     /// Get a line from the list of pre-computed line-beginnings.
706     /// The line number here is 0-based.
707     pub fn get_line(&self, line_number: usize) -> Option<Cow<str>> {
708         fn get_until_newline(src: &str, begin: usize) -> &str {
709             // We can't use `lines.get(line_number+1)` because we might
710             // be parsing when we call this function and thus the current
711             // line is the last one we have line info for.
712             let slice = &src[begin..];
713             match slice.find('\n') {
714                 Some(e) => &slice[..e],
715                 None => slice
716             }
717         }
718
719         let lines = self.lines.borrow();
720         let line = if let Some(line) = lines.get(line_number) {
721             line
722         } else {
723             return None;
724         };
725         let begin: BytePos = *line - self.start_pos;
726         let begin = begin.to_usize();
727
728         if let Some(ref src) = self.src {
729             Some(Cow::from(get_until_newline(src, begin)))
730         } else if let Some(src) = self.external_src.borrow().get_source() {
731             Some(Cow::Owned(String::from(get_until_newline(src, begin))))
732         } else {
733             None
734         }
735     }
736
737     pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
738         assert!(bytes >=2 && bytes <= 4);
739         let mbc = MultiByteChar {
740             pos,
741             bytes,
742         };
743         self.multibyte_chars.borrow_mut().push(mbc);
744     }
745
746     pub fn is_real_file(&self) -> bool {
747         !(self.name.starts_with("<") &&
748           self.name.ends_with(">"))
749     }
750
751     pub fn is_imported(&self) -> bool {
752         self.src.is_none()
753     }
754
755     pub fn byte_length(&self) -> u32 {
756         self.end_pos.0 - self.start_pos.0
757     }
758     pub fn count_lines(&self) -> usize {
759         self.lines.borrow().len()
760     }
761
762     /// Find the line containing the given position. The return value is the
763     /// index into the `lines` array of this FileMap, not the 1-based line
764     /// number. If the filemap is empty or the position is located before the
765     /// first line, None is returned.
766     pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
767         let lines = self.lines.borrow();
768         if lines.len() == 0 {
769             return None;
770         }
771
772         let line_index = lookup_line(&lines[..], pos);
773         assert!(line_index < lines.len() as isize);
774         if line_index >= 0 {
775             Some(line_index as usize)
776         } else {
777             None
778         }
779     }
780
781     pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
782         if self.start_pos == self.end_pos {
783             return (self.start_pos, self.end_pos);
784         }
785
786         let lines = self.lines.borrow();
787         assert!(line_index < lines.len());
788         if line_index == (lines.len() - 1) {
789             (lines[line_index], self.end_pos)
790         } else {
791             (lines[line_index], lines[line_index + 1])
792         }
793     }
794 }
795
796 /// Remove utf-8 BOM if any.
797 fn remove_bom(src: &mut String) {
798     if src.starts_with("\u{feff}") {
799         src.drain(..3);
800     }
801 }
802
803 // _____________________________________________________________________________
804 // Pos, BytePos, CharPos
805 //
806
807 pub trait Pos {
808     fn from_usize(n: usize) -> Self;
809     fn to_usize(&self) -> usize;
810 }
811
812 /// A byte offset. Keep this small (currently 32-bits), as AST contains
813 /// a lot of them.
814 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
815 pub struct BytePos(pub u32);
816
817 /// A character offset. Because of multibyte utf8 characters, a byte offset
818 /// is not equivalent to a character offset. The CodeMap will convert BytePos
819 /// values to CharPos values as necessary.
820 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
821 pub struct CharPos(pub usize);
822
823 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
824 // have been unsuccessful
825
826 impl Pos for BytePos {
827     fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
828     fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
829 }
830
831 impl Add for BytePos {
832     type Output = BytePos;
833
834     fn add(self, rhs: BytePos) -> BytePos {
835         BytePos((self.to_usize() + rhs.to_usize()) as u32)
836     }
837 }
838
839 impl Sub for BytePos {
840     type Output = BytePos;
841
842     fn sub(self, rhs: BytePos) -> BytePos {
843         BytePos((self.to_usize() - rhs.to_usize()) as u32)
844     }
845 }
846
847 impl Encodable for BytePos {
848     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
849         s.emit_u32(self.0)
850     }
851 }
852
853 impl Decodable for BytePos {
854     fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
855         Ok(BytePos(d.read_u32()?))
856     }
857 }
858
859 impl Pos for CharPos {
860     fn from_usize(n: usize) -> CharPos { CharPos(n) }
861     fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
862 }
863
864 impl Add for CharPos {
865     type Output = CharPos;
866
867     fn add(self, rhs: CharPos) -> CharPos {
868         CharPos(self.to_usize() + rhs.to_usize())
869     }
870 }
871
872 impl Sub for CharPos {
873     type Output = CharPos;
874
875     fn sub(self, rhs: CharPos) -> CharPos {
876         CharPos(self.to_usize() - rhs.to_usize())
877     }
878 }
879
880 // _____________________________________________________________________________
881 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
882 //
883
884 /// A source code location used for error reporting
885 #[derive(Debug, Clone)]
886 pub struct Loc {
887     /// Information about the original source
888     pub file: Rc<FileMap>,
889     /// The (1-based) line number
890     pub line: usize,
891     /// The (0-based) column offset
892     pub col: CharPos
893 }
894
895 /// A source code location used as the result of lookup_char_pos_adj
896 // Actually, *none* of the clients use the filename *or* file field;
897 // perhaps they should just be removed.
898 #[derive(Debug)]
899 pub struct LocWithOpt {
900     pub filename: FileName,
901     pub line: usize,
902     pub col: CharPos,
903     pub file: Option<Rc<FileMap>>,
904 }
905
906 // used to be structural records. Better names, anyone?
907 #[derive(Debug)]
908 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
909 #[derive(Debug)]
910 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
911
912 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
913 pub struct LineInfo {
914     /// Index of line, starting from 0.
915     pub line_index: usize,
916
917     /// Column in line where span begins, starting from 0.
918     pub start_col: CharPos,
919
920     /// Column in line where span ends, starting from 0, exclusive.
921     pub end_col: CharPos,
922 }
923
924 pub struct FileLines {
925     pub file: Rc<FileMap>,
926     pub lines: Vec<LineInfo>
927 }
928
929 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
930                 Cell::new(default_span_debug));
931
932 #[derive(Debug)]
933 pub struct MacroBacktrace {
934     /// span where macro was applied to generate this code
935     pub call_site: Span,
936
937     /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
938     pub macro_decl_name: String,
939
940     /// span where macro was defined (if known)
941     pub def_site_span: Option<Span>,
942 }
943
944 // _____________________________________________________________________________
945 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
946 //
947
948 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
949
950 #[derive(Clone, PartialEq, Eq, Debug)]
951 pub enum SpanLinesError {
952     IllFormedSpan(Span),
953     DistinctSources(DistinctSources),
954 }
955
956 #[derive(Clone, PartialEq, Eq, Debug)]
957 pub enum SpanSnippetError {
958     IllFormedSpan(Span),
959     DistinctSources(DistinctSources),
960     MalformedForCodemap(MalformedCodemapPositions),
961     SourceNotAvailable { filename: String }
962 }
963
964 #[derive(Clone, PartialEq, Eq, Debug)]
965 pub struct DistinctSources {
966     pub begin: (String, BytePos),
967     pub end: (String, BytePos)
968 }
969
970 #[derive(Clone, PartialEq, Eq, Debug)]
971 pub struct MalformedCodemapPositions {
972     pub name: String,
973     pub source_len: usize,
974     pub begin_pos: BytePos,
975     pub end_pos: BytePos
976 }
977
978 // Given a slice of line start positions and a position, returns the index of
979 // the line the position is on. Returns -1 if the position is located before
980 // the first line.
981 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
982     match lines.binary_search(&pos) {
983         Ok(line) => line as isize,
984         Err(line) => line as isize - 1
985     }
986 }
987
988 #[cfg(test)]
989 mod tests {
990     use super::{lookup_line, BytePos};
991
992     #[test]
993     fn test_lookup_line() {
994
995         let lines = &[BytePos(3), BytePos(17), BytePos(28)];
996
997         assert_eq!(lookup_line(lines, BytePos(0)), -1);
998         assert_eq!(lookup_line(lines, BytePos(3)),  0);
999         assert_eq!(lookup_line(lines, BytePos(4)),  0);
1000
1001         assert_eq!(lookup_line(lines, BytePos(16)), 0);
1002         assert_eq!(lookup_line(lines, BytePos(17)), 1);
1003         assert_eq!(lookup_line(lines, BytePos(18)), 1);
1004
1005         assert_eq!(lookup_line(lines, BytePos(28)), 2);
1006         assert_eq!(lookup_line(lines, BytePos(29)), 2);
1007     }
1008 }