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