]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/lib.rs
Changed issue number to 36105
[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 #![cfg_attr(not(stage0), deny(warnings))]
25
26 #![feature(custom_attribute)]
27 #![allow(unused_attributes)]
28 #![feature(rustc_private)]
29 #![feature(staged_api)]
30 #![feature(question_mark)]
31
32 use std::cell::{Cell, RefCell};
33 use std::ops::{Add, Sub};
34 use std::rc::Rc;
35 use std::cmp;
36
37 use std::fmt;
38
39 use serialize::{Encodable, Decodable, Encoder, Decoder};
40
41 extern crate serialize;
42 extern crate serialize as rustc_serialize; // used by deriving
43
44 pub type FileName = String;
45
46 /// Spans represent a region of code, used for error reporting. Positions in spans
47 /// are *absolute* positions from the beginning of the codemap, not positions
48 /// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
49 /// to the original source.
50 /// You must be careful if the span crosses more than one file - you will not be
51 /// able to use many of the functions on spans in codemap and you cannot assume
52 /// that the length of the span = hi - lo; there may be space in the BytePos
53 /// range between files.
54 #[derive(Clone, Copy, Hash, PartialEq, Eq)]
55 pub struct Span {
56     pub lo: BytePos,
57     pub hi: BytePos,
58     /// Information about where the macro came from, if this piece of
59     /// code was created by a macro expansion.
60     pub expn_id: ExpnId
61 }
62
63 /// A collection of spans. Spans have two orthogonal attributes:
64 ///
65 /// - they can be *primary spans*. In this case they are the locus of
66 ///   the error, and would be rendered with `^^^`.
67 /// - they can have a *label*. In this case, the label is written next
68 ///   to the mark in the snippet when we render.
69 #[derive(Clone)]
70 pub struct MultiSpan {
71     primary_spans: Vec<Span>,
72     span_labels: Vec<(Span, String)>,
73 }
74
75 impl Span {
76     /// Returns a new span representing just the end-point of this span
77     pub fn end_point(self) -> Span {
78         let lo = cmp::max(self.hi.0 - 1, self.lo.0);
79         Span { lo: BytePos(lo), hi: self.hi, expn_id: self.expn_id}
80     }
81
82     /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
83     pub fn substitute_dummy(self, other: Span) -> Span {
84         if self.source_equal(&DUMMY_SP) { other } else { self }
85     }
86
87     pub fn contains(self, other: Span) -> bool {
88         self.lo <= other.lo && other.hi <= self.hi
89     }
90
91     /// Return true if the spans are equal with regards to the source text.
92     ///
93     /// Use this instead of `==` when either span could be generated code,
94     /// and you only care that they point to the same bytes of source text.
95     pub fn source_equal(&self, other: &Span) -> bool {
96         self.lo == other.lo && self.hi == other.hi
97     }
98
99     /// Returns `Some(span)`, a union of `self` and `other`, on overlap.
100     pub fn merge(self, other: Span) -> Option<Span> {
101         if self.expn_id != other.expn_id {
102             return None;
103         }
104
105         if (self.lo <= other.lo && self.hi > other.lo) ||
106            (self.lo >= other.lo && self.lo < other.hi) {
107             Some(Span {
108                 lo: cmp::min(self.lo, other.lo),
109                 hi: cmp::max(self.hi, other.hi),
110                 expn_id: self.expn_id,
111             })
112         } else {
113             None
114         }
115     }
116
117     /// Returns `Some(span)`, where the start is trimmed by the end of `other`
118     pub fn trim_start(self, other: Span) -> Option<Span> {
119         if self.hi > other.hi {
120             Some(Span { lo: cmp::max(self.lo, other.hi), .. self })
121         } else {
122             None
123         }
124     }
125 }
126
127 #[derive(Clone, Debug)]
128 pub struct SpanLabel {
129     /// The span we are going to include in the final snippet.
130     pub span: Span,
131
132     /// Is this a primary span? This is the "locus" of the message,
133     /// and is indicated with a `^^^^` underline, versus `----`.
134     pub is_primary: bool,
135
136     /// What label should we attach to this span (if any)?
137     pub label: Option<String>,
138 }
139
140 impl Encodable for Span {
141     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
142         s.emit_struct("Span", 2, |s| {
143             s.emit_struct_field("lo", 0, |s| {
144                 self.lo.encode(s)
145             })?;
146
147             s.emit_struct_field("hi", 1, |s| {
148                 self.hi.encode(s)
149             })
150         })
151     }
152 }
153
154 impl Decodable for Span {
155     fn decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
156         d.read_struct("Span", 2, |d| {
157             let lo = d.read_struct_field("lo", 0, |d| {
158                 BytePos::decode(d)
159             })?;
160
161             let hi = d.read_struct_field("hi", 1, |d| {
162                 BytePos::decode(d)
163             })?;
164
165             Ok(mk_sp(lo, hi))
166         })
167     }
168 }
169
170 fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
171     write!(f, "Span {{ lo: {:?}, hi: {:?}, expn_id: {:?} }}",
172            span.lo, span.hi, span.expn_id)
173 }
174
175 impl fmt::Debug for Span {
176     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
177         SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
178     }
179 }
180
181 pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION };
182
183 // Generic span to be used for code originating from the command line
184 pub const COMMAND_LINE_SP: Span = Span { lo: BytePos(0),
185                                          hi: BytePos(0),
186                                          expn_id: COMMAND_LINE_EXPN };
187
188 impl MultiSpan {
189     pub fn new() -> MultiSpan {
190         MultiSpan {
191             primary_spans: vec![],
192             span_labels: vec![]
193         }
194     }
195
196     pub fn from_span(primary_span: Span) -> MultiSpan {
197         MultiSpan {
198             primary_spans: vec![primary_span],
199             span_labels: vec![]
200         }
201     }
202
203     pub fn from_spans(vec: Vec<Span>) -> MultiSpan {
204         MultiSpan {
205             primary_spans: vec,
206             span_labels: vec![]
207         }
208     }
209
210     pub fn push_span_label(&mut self, span: Span, label: String) {
211         self.span_labels.push((span, label));
212     }
213
214     /// Selects the first primary span (if any)
215     pub fn primary_span(&self) -> Option<Span> {
216         self.primary_spans.first().cloned()
217     }
218
219     /// Returns all primary spans.
220     pub fn primary_spans(&self) -> &[Span] {
221         &self.primary_spans
222     }
223
224     /// Returns the strings to highlight. We always ensure that there
225     /// is an entry for each of the primary spans -- for each primary
226     /// span P, if there is at least one label with span P, we return
227     /// those labels (marked as primary). But otherwise we return
228     /// `SpanLabel` instances with empty labels.
229     pub fn span_labels(&self) -> Vec<SpanLabel> {
230         let is_primary = |span| self.primary_spans.contains(&span);
231         let mut span_labels = vec![];
232
233         for &(span, ref label) in &self.span_labels {
234             span_labels.push(SpanLabel {
235                 span: span,
236                 is_primary: is_primary(span),
237                 label: Some(label.clone())
238             });
239         }
240
241         for &span in &self.primary_spans {
242             if !span_labels.iter().any(|sl| sl.span == span) {
243                 span_labels.push(SpanLabel {
244                     span: span,
245                     is_primary: true,
246                     label: None
247                 });
248             }
249         }
250
251         span_labels
252     }
253 }
254
255 impl From<Span> for MultiSpan {
256     fn from(span: Span) -> MultiSpan {
257         MultiSpan::from_span(span)
258     }
259 }
260
261 #[derive(PartialEq, Eq, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Copy)]
262 pub struct ExpnId(pub u32);
263
264 pub const NO_EXPANSION: ExpnId = ExpnId(!0);
265 // For code appearing from the command line
266 pub const COMMAND_LINE_EXPN: ExpnId = ExpnId(!1);
267
268 // For code generated by a procedural macro, without knowing which
269 // Used in `qquote!`
270 pub const PROC_EXPN: ExpnId = ExpnId(!2);
271
272 impl ExpnId {
273     pub fn from_u32(id: u32) -> ExpnId {
274         ExpnId(id)
275     }
276
277     pub fn into_u32(self) -> u32 {
278         self.0
279     }
280 }
281
282 /// Identifies an offset of a multi-byte character in a FileMap
283 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
284 pub struct MultiByteChar {
285     /// The absolute offset of the character in the CodeMap
286     pub pos: BytePos,
287     /// The number of bytes, >=2
288     pub bytes: usize,
289 }
290
291 /// A single source in the CodeMap.
292 pub struct FileMap {
293     /// The name of the file that the source came from, source that doesn't
294     /// originate from files has names between angle brackets by convention,
295     /// e.g. `<anon>`
296     pub name: FileName,
297     /// The absolute path of the file that the source came from.
298     pub abs_path: Option<FileName>,
299     /// The complete source code
300     pub src: Option<Rc<String>>,
301     /// The start position of this source in the CodeMap
302     pub start_pos: BytePos,
303     /// The end position of this source in the CodeMap
304     pub end_pos: BytePos,
305     /// Locations of lines beginnings in the source code
306     pub lines: RefCell<Vec<BytePos>>,
307     /// Locations of multi-byte characters in the source code
308     pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
309 }
310
311 impl Encodable for FileMap {
312     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
313         s.emit_struct("FileMap", 6, |s| {
314             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
315             s.emit_struct_field("abs_path", 1, |s| self.abs_path.encode(s))?;
316             s.emit_struct_field("start_pos", 2, |s| self.start_pos.encode(s))?;
317             s.emit_struct_field("end_pos", 3, |s| self.end_pos.encode(s))?;
318             s.emit_struct_field("lines", 4, |s| {
319                 let lines = self.lines.borrow();
320                 // store the length
321                 s.emit_u32(lines.len() as u32)?;
322
323                 if !lines.is_empty() {
324                     // In order to preserve some space, we exploit the fact that
325                     // the lines list is sorted and individual lines are
326                     // probably not that long. Because of that we can store lines
327                     // as a difference list, using as little space as possible
328                     // for the differences.
329                     let max_line_length = if lines.len() == 1 {
330                         0
331                     } else {
332                         lines.windows(2)
333                              .map(|w| w[1] - w[0])
334                              .map(|bp| bp.to_usize())
335                              .max()
336                              .unwrap()
337                     };
338
339                     let bytes_per_diff: u8 = match max_line_length {
340                         0 ... 0xFF => 1,
341                         0x100 ... 0xFFFF => 2,
342                         _ => 4
343                     };
344
345                     // Encode the number of bytes used per diff.
346                     bytes_per_diff.encode(s)?;
347
348                     // Encode the first element.
349                     lines[0].encode(s)?;
350
351                     let diff_iter = (&lines[..]).windows(2)
352                                                 .map(|w| (w[1] - w[0]));
353
354                     match bytes_per_diff {
355                         1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
356                         2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
357                         4 => for diff in diff_iter { diff.0.encode(s)? },
358                         _ => unreachable!()
359                     }
360                 }
361
362                 Ok(())
363             })?;
364             s.emit_struct_field("multibyte_chars", 5, |s| {
365                 (*self.multibyte_chars.borrow()).encode(s)
366             })
367         })
368     }
369 }
370
371 impl Decodable for FileMap {
372     fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
373
374         d.read_struct("FileMap", 6, |d| {
375             let name: String = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
376             let abs_path: Option<String> =
377                 d.read_struct_field("abs_path", 1, |d| Decodable::decode(d))?;
378             let start_pos: BytePos = d.read_struct_field("start_pos", 2, |d| Decodable::decode(d))?;
379             let end_pos: BytePos = d.read_struct_field("end_pos", 3, |d| Decodable::decode(d))?;
380             let lines: Vec<BytePos> = d.read_struct_field("lines", 4, |d| {
381                 let num_lines: u32 = Decodable::decode(d)?;
382                 let mut lines = Vec::with_capacity(num_lines as usize);
383
384                 if num_lines > 0 {
385                     // Read the number of bytes used per diff.
386                     let bytes_per_diff: u8 = Decodable::decode(d)?;
387
388                     // Read the first element.
389                     let mut line_start: BytePos = Decodable::decode(d)?;
390                     lines.push(line_start);
391
392                     for _ in 1..num_lines {
393                         let diff = match bytes_per_diff {
394                             1 => d.read_u8()? as u32,
395                             2 => d.read_u16()? as u32,
396                             4 => d.read_u32()?,
397                             _ => unreachable!()
398                         };
399
400                         line_start = line_start + BytePos(diff);
401
402                         lines.push(line_start);
403                     }
404                 }
405
406                 Ok(lines)
407             })?;
408             let multibyte_chars: Vec<MultiByteChar> =
409                 d.read_struct_field("multibyte_chars", 5, |d| Decodable::decode(d))?;
410             Ok(FileMap {
411                 name: name,
412                 abs_path: abs_path,
413                 start_pos: start_pos,
414                 end_pos: end_pos,
415                 src: None,
416                 lines: RefCell::new(lines),
417                 multibyte_chars: RefCell::new(multibyte_chars)
418             })
419         })
420     }
421 }
422
423 impl fmt::Debug for FileMap {
424     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
425         write!(fmt, "FileMap({})", self.name)
426     }
427 }
428
429 impl FileMap {
430     /// EFFECT: register a start-of-line offset in the
431     /// table of line-beginnings.
432     /// UNCHECKED INVARIANT: these offsets must be added in the right
433     /// order and must be in the right places; there is shared knowledge
434     /// about what ends a line between this file and parse.rs
435     /// WARNING: pos param here is the offset relative to start of CodeMap,
436     /// and CodeMap will append a newline when adding a filemap without a newline at the end,
437     /// so the safe way to call this is with value calculated as
438     /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
439     pub fn next_line(&self, pos: BytePos) {
440         // the new charpos must be > the last one (or it's the first one).
441         let mut lines = self.lines.borrow_mut();
442         let line_len = lines.len();
443         assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
444         lines.push(pos);
445     }
446
447     /// get a line from the list of pre-computed line-beginnings.
448     /// line-number here is 0-based.
449     pub fn get_line(&self, line_number: usize) -> Option<&str> {
450         match self.src {
451             Some(ref src) => {
452                 let lines = self.lines.borrow();
453                 lines.get(line_number).map(|&line| {
454                     let begin: BytePos = line - self.start_pos;
455                     let begin = begin.to_usize();
456                     // We can't use `lines.get(line_number+1)` because we might
457                     // be parsing when we call this function and thus the current
458                     // line is the last one we have line info for.
459                     let slice = &src[begin..];
460                     match slice.find('\n') {
461                         Some(e) => &slice[..e],
462                         None => slice
463                     }
464                 })
465             }
466             None => None
467         }
468     }
469
470     pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
471         assert!(bytes >=2 && bytes <= 4);
472         let mbc = MultiByteChar {
473             pos: pos,
474             bytes: bytes,
475         };
476         self.multibyte_chars.borrow_mut().push(mbc);
477     }
478
479     pub fn is_real_file(&self) -> bool {
480         !(self.name.starts_with("<") &&
481           self.name.ends_with(">"))
482     }
483
484     pub fn is_imported(&self) -> bool {
485         self.src.is_none()
486     }
487
488     pub fn count_lines(&self) -> usize {
489         self.lines.borrow().len()
490     }
491 }
492
493 // _____________________________________________________________________________
494 // Pos, BytePos, CharPos
495 //
496
497 pub trait Pos {
498     fn from_usize(n: usize) -> Self;
499     fn to_usize(&self) -> usize;
500 }
501
502 /// A byte offset. Keep this small (currently 32-bits), as AST contains
503 /// a lot of them.
504 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
505 pub struct BytePos(pub u32);
506
507 /// A character offset. Because of multibyte utf8 characters, a byte offset
508 /// is not equivalent to a character offset. The CodeMap will convert BytePos
509 /// values to CharPos values as necessary.
510 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
511 pub struct CharPos(pub usize);
512
513 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
514 // have been unsuccessful
515
516 impl Pos for BytePos {
517     fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
518     fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
519 }
520
521 impl Add for BytePos {
522     type Output = BytePos;
523
524     fn add(self, rhs: BytePos) -> BytePos {
525         BytePos((self.to_usize() + rhs.to_usize()) as u32)
526     }
527 }
528
529 impl Sub for BytePos {
530     type Output = BytePos;
531
532     fn sub(self, rhs: BytePos) -> BytePos {
533         BytePos((self.to_usize() - rhs.to_usize()) as u32)
534     }
535 }
536
537 impl Encodable for BytePos {
538     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
539         s.emit_u32(self.0)
540     }
541 }
542
543 impl Decodable for BytePos {
544     fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
545         Ok(BytePos(d.read_u32()?))
546     }
547 }
548
549 impl Pos for CharPos {
550     fn from_usize(n: usize) -> CharPos { CharPos(n) }
551     fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
552 }
553
554 impl Add for CharPos {
555     type Output = CharPos;
556
557     fn add(self, rhs: CharPos) -> CharPos {
558         CharPos(self.to_usize() + rhs.to_usize())
559     }
560 }
561
562 impl Sub for CharPos {
563     type Output = CharPos;
564
565     fn sub(self, rhs: CharPos) -> CharPos {
566         CharPos(self.to_usize() - rhs.to_usize())
567     }
568 }
569
570 // _____________________________________________________________________________
571 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
572 //
573
574 /// A source code location used for error reporting
575 #[derive(Debug, Clone)]
576 pub struct Loc {
577     /// Information about the original source
578     pub file: Rc<FileMap>,
579     /// The (1-based) line number
580     pub line: usize,
581     /// The (0-based) column offset
582     pub col: CharPos
583 }
584
585 /// A source code location used as the result of lookup_char_pos_adj
586 // Actually, *none* of the clients use the filename *or* file field;
587 // perhaps they should just be removed.
588 #[derive(Debug)]
589 pub struct LocWithOpt {
590     pub filename: FileName,
591     pub line: usize,
592     pub col: CharPos,
593     pub file: Option<Rc<FileMap>>,
594 }
595
596 // used to be structural records. Better names, anyone?
597 #[derive(Debug)]
598 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
599 #[derive(Debug)]
600 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
601
602 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
603 pub struct LineInfo {
604     /// Index of line, starting from 0.
605     pub line_index: usize,
606
607     /// Column in line where span begins, starting from 0.
608     pub start_col: CharPos,
609
610     /// Column in line where span ends, starting from 0, exclusive.
611     pub end_col: CharPos,
612 }
613
614 pub struct FileLines {
615     pub file: Rc<FileMap>,
616     pub lines: Vec<LineInfo>
617 }
618
619 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
620                 Cell::new(default_span_debug));
621
622 /* assuming that we're not in macro expansion */
623 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
624     Span {lo: lo, hi: hi, expn_id: NO_EXPANSION}
625 }
626
627 pub struct MacroBacktrace {
628     /// span where macro was applied to generate this code
629     pub call_site: Span,
630
631     /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
632     pub macro_decl_name: String,
633
634     /// span where macro was defined (if known)
635     pub def_site_span: Option<Span>,
636 }
637
638 // _____________________________________________________________________________
639 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
640 //
641
642 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
643
644 #[derive(Clone, PartialEq, Eq, Debug)]
645 pub enum SpanLinesError {
646     IllFormedSpan(Span),
647     DistinctSources(DistinctSources),
648 }
649
650 #[derive(Clone, PartialEq, Eq, Debug)]
651 pub enum SpanSnippetError {
652     IllFormedSpan(Span),
653     DistinctSources(DistinctSources),
654     MalformedForCodemap(MalformedCodemapPositions),
655     SourceNotAvailable { filename: String }
656 }
657
658 #[derive(Clone, PartialEq, Eq, Debug)]
659 pub struct DistinctSources {
660     pub begin: (String, BytePos),
661     pub end: (String, BytePos)
662 }
663
664 #[derive(Clone, PartialEq, Eq, Debug)]
665 pub struct MalformedCodemapPositions {
666     pub name: String,
667     pub source_len: usize,
668     pub begin_pos: BytePos,
669     pub end_pos: BytePos
670 }
671