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