]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/lib.rs
Added hash verification to external source loading.
[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     /// add externally loaded source.
608     /// if the hash of the input doesn't match or no input is supplied via None,
609     /// it is interpreted as an error and the corresponding enum variant is set.
610     pub fn add_external_src(&self, src: Option<String>) -> bool {
611         let mut external_src = self.external_src.borrow_mut();
612         if let Some(src) = src {
613             let mut hasher: StableHasher<u128> = StableHasher::new();
614             hasher.write(src.as_bytes());
615
616             if hasher.finish() == self.src_hash {
617                 *external_src = ExternalSource::Present(src);
618                 return true;
619             }
620         } else {
621             *external_src = ExternalSource::AbsentErr;
622         }
623
624         false
625     }
626
627     /// get a line from the list of pre-computed line-beginnings.
628     /// line-number here is 0-based.
629     pub fn get_line(&self, line_number: usize) -> Option<Cow<str>> {
630         fn get_until_newline(src: &str, begin: usize) -> &str {
631             // We can't use `lines.get(line_number+1)` because we might
632             // be parsing when we call this function and thus the current
633             // line is the last one we have line info for.
634             let slice = &src[begin..];
635             match slice.find('\n') {
636                 Some(e) => &slice[..e],
637                 None => slice
638             }
639         }
640
641         let lines = self.lines.borrow();
642         let line = if let Some(line) = lines.get(line_number) {
643             line
644         } else {
645             return None;
646         };
647         let begin: BytePos = *line - self.start_pos;
648         let begin = begin.to_usize();
649
650         if let Some(ref src) = self.src {
651             Some(Cow::from(get_until_newline(src, begin)))
652         } else if let Some(src) = self.external_src.borrow().get_source() {
653             Some(Cow::Owned(String::from(get_until_newline(src, begin))))
654         } else {
655             None
656         }
657     }
658
659     pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
660         assert!(bytes >=2 && bytes <= 4);
661         let mbc = MultiByteChar {
662             pos: pos,
663             bytes: bytes,
664         };
665         self.multibyte_chars.borrow_mut().push(mbc);
666     }
667
668     pub fn is_real_file(&self) -> bool {
669         !(self.name.starts_with("<") &&
670           self.name.ends_with(">"))
671     }
672
673     pub fn is_imported(&self) -> bool {
674         self.src.is_none()
675     }
676
677     pub fn byte_length(&self) -> u32 {
678         self.end_pos.0 - self.start_pos.0
679     }
680     pub fn count_lines(&self) -> usize {
681         self.lines.borrow().len()
682     }
683
684     /// Find the line containing the given position. The return value is the
685     /// index into the `lines` array of this FileMap, not the 1-based line
686     /// number. If the filemap is empty or the position is located before the
687     /// first line, None is returned.
688     pub fn lookup_line(&self, pos: BytePos) -> Option<usize> {
689         let lines = self.lines.borrow();
690         if lines.len() == 0 {
691             return None;
692         }
693
694         let line_index = lookup_line(&lines[..], pos);
695         assert!(line_index < lines.len() as isize);
696         if line_index >= 0 {
697             Some(line_index as usize)
698         } else {
699             None
700         }
701     }
702
703     pub fn line_bounds(&self, line_index: usize) -> (BytePos, BytePos) {
704         if self.start_pos == self.end_pos {
705             return (self.start_pos, self.end_pos);
706         }
707
708         let lines = self.lines.borrow();
709         assert!(line_index < lines.len());
710         if line_index == (lines.len() - 1) {
711             (lines[line_index], self.end_pos)
712         } else {
713             (lines[line_index], lines[line_index + 1])
714         }
715     }
716 }
717
718 /// Remove utf-8 BOM if any.
719 fn remove_bom(src: &mut String) {
720     if src.starts_with("\u{feff}") {
721         src.drain(..3);
722     }
723 }
724
725 // _____________________________________________________________________________
726 // Pos, BytePos, CharPos
727 //
728
729 pub trait Pos {
730     fn from_usize(n: usize) -> Self;
731     fn to_usize(&self) -> usize;
732 }
733
734 /// A byte offset. Keep this small (currently 32-bits), as AST contains
735 /// a lot of them.
736 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
737 pub struct BytePos(pub u32);
738
739 /// A character offset. Because of multibyte utf8 characters, a byte offset
740 /// is not equivalent to a character offset. The CodeMap will convert BytePos
741 /// values to CharPos values as necessary.
742 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
743 pub struct CharPos(pub usize);
744
745 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
746 // have been unsuccessful
747
748 impl Pos for BytePos {
749     fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
750     fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
751 }
752
753 impl Add for BytePos {
754     type Output = BytePos;
755
756     fn add(self, rhs: BytePos) -> BytePos {
757         BytePos((self.to_usize() + rhs.to_usize()) as u32)
758     }
759 }
760
761 impl Sub for BytePos {
762     type Output = BytePos;
763
764     fn sub(self, rhs: BytePos) -> BytePos {
765         BytePos((self.to_usize() - rhs.to_usize()) as u32)
766     }
767 }
768
769 impl Encodable for BytePos {
770     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
771         s.emit_u32(self.0)
772     }
773 }
774
775 impl Decodable for BytePos {
776     fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
777         Ok(BytePos(d.read_u32()?))
778     }
779 }
780
781 impl Pos for CharPos {
782     fn from_usize(n: usize) -> CharPos { CharPos(n) }
783     fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
784 }
785
786 impl Add for CharPos {
787     type Output = CharPos;
788
789     fn add(self, rhs: CharPos) -> CharPos {
790         CharPos(self.to_usize() + rhs.to_usize())
791     }
792 }
793
794 impl Sub for CharPos {
795     type Output = CharPos;
796
797     fn sub(self, rhs: CharPos) -> CharPos {
798         CharPos(self.to_usize() - rhs.to_usize())
799     }
800 }
801
802 // _____________________________________________________________________________
803 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
804 //
805
806 /// A source code location used for error reporting
807 #[derive(Debug, Clone)]
808 pub struct Loc {
809     /// Information about the original source
810     pub file: Rc<FileMap>,
811     /// The (1-based) line number
812     pub line: usize,
813     /// The (0-based) column offset
814     pub col: CharPos
815 }
816
817 /// A source code location used as the result of lookup_char_pos_adj
818 // Actually, *none* of the clients use the filename *or* file field;
819 // perhaps they should just be removed.
820 #[derive(Debug)]
821 pub struct LocWithOpt {
822     pub filename: FileName,
823     pub line: usize,
824     pub col: CharPos,
825     pub file: Option<Rc<FileMap>>,
826 }
827
828 // used to be structural records. Better names, anyone?
829 #[derive(Debug)]
830 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
831 #[derive(Debug)]
832 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
833
834 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
835 pub struct LineInfo {
836     /// Index of line, starting from 0.
837     pub line_index: usize,
838
839     /// Column in line where span begins, starting from 0.
840     pub start_col: CharPos,
841
842     /// Column in line where span ends, starting from 0, exclusive.
843     pub end_col: CharPos,
844 }
845
846 pub struct FileLines {
847     pub file: Rc<FileMap>,
848     pub lines: Vec<LineInfo>
849 }
850
851 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
852                 Cell::new(default_span_debug));
853
854 pub struct MacroBacktrace {
855     /// span where macro was applied to generate this code
856     pub call_site: Span,
857
858     /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
859     pub macro_decl_name: String,
860
861     /// span where macro was defined (if known)
862     pub def_site_span: Option<Span>,
863 }
864
865 // _____________________________________________________________________________
866 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
867 //
868
869 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
870
871 #[derive(Clone, PartialEq, Eq, Debug)]
872 pub enum SpanLinesError {
873     IllFormedSpan(Span),
874     DistinctSources(DistinctSources),
875 }
876
877 #[derive(Clone, PartialEq, Eq, Debug)]
878 pub enum SpanSnippetError {
879     IllFormedSpan(Span),
880     DistinctSources(DistinctSources),
881     MalformedForCodemap(MalformedCodemapPositions),
882     SourceNotAvailable { filename: String }
883 }
884
885 #[derive(Clone, PartialEq, Eq, Debug)]
886 pub struct DistinctSources {
887     pub begin: (String, BytePos),
888     pub end: (String, BytePos)
889 }
890
891 #[derive(Clone, PartialEq, Eq, Debug)]
892 pub struct MalformedCodemapPositions {
893     pub name: String,
894     pub source_len: usize,
895     pub begin_pos: BytePos,
896     pub end_pos: BytePos
897 }
898
899 // Given a slice of line start positions and a position, returns the index of
900 // the line the position is on. Returns -1 if the position is located before
901 // the first line.
902 fn lookup_line(lines: &[BytePos], pos: BytePos) -> isize {
903     match lines.binary_search(&pos) {
904         Ok(line) => line as isize,
905         Err(line) => line as isize - 1
906     }
907 }
908
909 #[cfg(test)]
910 mod tests {
911     use super::{lookup_line, BytePos};
912
913     #[test]
914     fn test_lookup_line() {
915
916         let lines = &[BytePos(3), BytePos(17), BytePos(28)];
917
918         assert_eq!(lookup_line(lines, BytePos(0)), -1);
919         assert_eq!(lookup_line(lines, BytePos(3)),  0);
920         assert_eq!(lookup_line(lines, BytePos(4)),  0);
921
922         assert_eq!(lookup_line(lines, BytePos(16)), 0);
923         assert_eq!(lookup_line(lines, BytePos(17)), 1);
924         assert_eq!(lookup_line(lines, BytePos(18)), 1);
925
926         assert_eq!(lookup_line(lines, BytePos(28)), 2);
927         assert_eq!(lookup_line(lines, BytePos(29)), 2);
928     }
929 }