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