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