]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_pos/lib.rs
Partial rewrite/expansion of `Vec::truncate` documentation.
[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 impl ExpnId {
269     pub fn from_u32(id: u32) -> ExpnId {
270         ExpnId(id)
271     }
272
273     pub fn into_u32(self) -> u32 {
274         self.0
275     }
276 }
277
278 /// Identifies an offset of a multi-byte character in a FileMap
279 #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
280 pub struct MultiByteChar {
281     /// The absolute offset of the character in the CodeMap
282     pub pos: BytePos,
283     /// The number of bytes, >=2
284     pub bytes: usize,
285 }
286
287 /// A single source in the CodeMap.
288 pub struct FileMap {
289     /// The name of the file that the source came from, source that doesn't
290     /// originate from files has names between angle brackets by convention,
291     /// e.g. `<anon>`
292     pub name: FileName,
293     /// The absolute path of the file that the source came from.
294     pub abs_path: Option<FileName>,
295     /// The complete source code
296     pub src: Option<Rc<String>>,
297     /// The start position of this source in the CodeMap
298     pub start_pos: BytePos,
299     /// The end position of this source in the CodeMap
300     pub end_pos: BytePos,
301     /// Locations of lines beginnings in the source code
302     pub lines: RefCell<Vec<BytePos>>,
303     /// Locations of multi-byte characters in the source code
304     pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
305 }
306
307 impl Encodable for FileMap {
308     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
309         s.emit_struct("FileMap", 6, |s| {
310             s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
311             s.emit_struct_field("abs_path", 1, |s| self.abs_path.encode(s))?;
312             s.emit_struct_field("start_pos", 2, |s| self.start_pos.encode(s))?;
313             s.emit_struct_field("end_pos", 3, |s| self.end_pos.encode(s))?;
314             s.emit_struct_field("lines", 4, |s| {
315                 let lines = self.lines.borrow();
316                 // store the length
317                 s.emit_u32(lines.len() as u32)?;
318
319                 if !lines.is_empty() {
320                     // In order to preserve some space, we exploit the fact that
321                     // the lines list is sorted and individual lines are
322                     // probably not that long. Because of that we can store lines
323                     // as a difference list, using as little space as possible
324                     // for the differences.
325                     let max_line_length = if lines.len() == 1 {
326                         0
327                     } else {
328                         lines.windows(2)
329                              .map(|w| w[1] - w[0])
330                              .map(|bp| bp.to_usize())
331                              .max()
332                              .unwrap()
333                     };
334
335                     let bytes_per_diff: u8 = match max_line_length {
336                         0 ... 0xFF => 1,
337                         0x100 ... 0xFFFF => 2,
338                         _ => 4
339                     };
340
341                     // Encode the number of bytes used per diff.
342                     bytes_per_diff.encode(s)?;
343
344                     // Encode the first element.
345                     lines[0].encode(s)?;
346
347                     let diff_iter = (&lines[..]).windows(2)
348                                                 .map(|w| (w[1] - w[0]));
349
350                     match bytes_per_diff {
351                         1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
352                         2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
353                         4 => for diff in diff_iter { diff.0.encode(s)? },
354                         _ => unreachable!()
355                     }
356                 }
357
358                 Ok(())
359             })?;
360             s.emit_struct_field("multibyte_chars", 5, |s| {
361                 (*self.multibyte_chars.borrow()).encode(s)
362             })
363         })
364     }
365 }
366
367 impl Decodable for FileMap {
368     fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
369
370         d.read_struct("FileMap", 6, |d| {
371             let name: String = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
372             let abs_path: Option<String> =
373                 d.read_struct_field("abs_path", 1, |d| Decodable::decode(d))?;
374             let start_pos: BytePos = d.read_struct_field("start_pos", 2, |d| Decodable::decode(d))?;
375             let end_pos: BytePos = d.read_struct_field("end_pos", 3, |d| Decodable::decode(d))?;
376             let lines: Vec<BytePos> = d.read_struct_field("lines", 4, |d| {
377                 let num_lines: u32 = Decodable::decode(d)?;
378                 let mut lines = Vec::with_capacity(num_lines as usize);
379
380                 if num_lines > 0 {
381                     // Read the number of bytes used per diff.
382                     let bytes_per_diff: u8 = Decodable::decode(d)?;
383
384                     // Read the first element.
385                     let mut line_start: BytePos = Decodable::decode(d)?;
386                     lines.push(line_start);
387
388                     for _ in 1..num_lines {
389                         let diff = match bytes_per_diff {
390                             1 => d.read_u8()? as u32,
391                             2 => d.read_u16()? as u32,
392                             4 => d.read_u32()?,
393                             _ => unreachable!()
394                         };
395
396                         line_start = line_start + BytePos(diff);
397
398                         lines.push(line_start);
399                     }
400                 }
401
402                 Ok(lines)
403             })?;
404             let multibyte_chars: Vec<MultiByteChar> =
405                 d.read_struct_field("multibyte_chars", 5, |d| Decodable::decode(d))?;
406             Ok(FileMap {
407                 name: name,
408                 abs_path: abs_path,
409                 start_pos: start_pos,
410                 end_pos: end_pos,
411                 src: None,
412                 lines: RefCell::new(lines),
413                 multibyte_chars: RefCell::new(multibyte_chars)
414             })
415         })
416     }
417 }
418
419 impl fmt::Debug for FileMap {
420     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
421         write!(fmt, "FileMap({})", self.name)
422     }
423 }
424
425 impl FileMap {
426     /// EFFECT: register a start-of-line offset in the
427     /// table of line-beginnings.
428     /// UNCHECKED INVARIANT: these offsets must be added in the right
429     /// order and must be in the right places; there is shared knowledge
430     /// about what ends a line between this file and parse.rs
431     /// WARNING: pos param here is the offset relative to start of CodeMap,
432     /// and CodeMap will append a newline when adding a filemap without a newline at the end,
433     /// so the safe way to call this is with value calculated as
434     /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
435     pub fn next_line(&self, pos: BytePos) {
436         // the new charpos must be > the last one (or it's the first one).
437         let mut lines = self.lines.borrow_mut();
438         let line_len = lines.len();
439         assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
440         lines.push(pos);
441     }
442
443     /// get a line from the list of pre-computed line-beginnings.
444     /// line-number here is 0-based.
445     pub fn get_line(&self, line_number: usize) -> Option<&str> {
446         match self.src {
447             Some(ref src) => {
448                 let lines = self.lines.borrow();
449                 lines.get(line_number).map(|&line| {
450                     let begin: BytePos = line - self.start_pos;
451                     let begin = begin.to_usize();
452                     // We can't use `lines.get(line_number+1)` because we might
453                     // be parsing when we call this function and thus the current
454                     // line is the last one we have line info for.
455                     let slice = &src[begin..];
456                     match slice.find('\n') {
457                         Some(e) => &slice[..e],
458                         None => slice
459                     }
460                 })
461             }
462             None => None
463         }
464     }
465
466     pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
467         assert!(bytes >=2 && bytes <= 4);
468         let mbc = MultiByteChar {
469             pos: pos,
470             bytes: bytes,
471         };
472         self.multibyte_chars.borrow_mut().push(mbc);
473     }
474
475     pub fn is_real_file(&self) -> bool {
476         !(self.name.starts_with("<") &&
477           self.name.ends_with(">"))
478     }
479
480     pub fn is_imported(&self) -> bool {
481         self.src.is_none()
482     }
483
484     pub fn count_lines(&self) -> usize {
485         self.lines.borrow().len()
486     }
487 }
488
489 // _____________________________________________________________________________
490 // Pos, BytePos, CharPos
491 //
492
493 pub trait Pos {
494     fn from_usize(n: usize) -> Self;
495     fn to_usize(&self) -> usize;
496 }
497
498 /// A byte offset. Keep this small (currently 32-bits), as AST contains
499 /// a lot of them.
500 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
501 pub struct BytePos(pub u32);
502
503 /// A character offset. Because of multibyte utf8 characters, a byte offset
504 /// is not equivalent to a character offset. The CodeMap will convert BytePos
505 /// values to CharPos values as necessary.
506 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
507 pub struct CharPos(pub usize);
508
509 // FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
510 // have been unsuccessful
511
512 impl Pos for BytePos {
513     fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
514     fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
515 }
516
517 impl Add for BytePos {
518     type Output = BytePos;
519
520     fn add(self, rhs: BytePos) -> BytePos {
521         BytePos((self.to_usize() + rhs.to_usize()) as u32)
522     }
523 }
524
525 impl Sub for BytePos {
526     type Output = BytePos;
527
528     fn sub(self, rhs: BytePos) -> BytePos {
529         BytePos((self.to_usize() - rhs.to_usize()) as u32)
530     }
531 }
532
533 impl Encodable for BytePos {
534     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
535         s.emit_u32(self.0)
536     }
537 }
538
539 impl Decodable for BytePos {
540     fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
541         Ok(BytePos(d.read_u32()?))
542     }
543 }
544
545 impl Pos for CharPos {
546     fn from_usize(n: usize) -> CharPos { CharPos(n) }
547     fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
548 }
549
550 impl Add for CharPos {
551     type Output = CharPos;
552
553     fn add(self, rhs: CharPos) -> CharPos {
554         CharPos(self.to_usize() + rhs.to_usize())
555     }
556 }
557
558 impl Sub for CharPos {
559     type Output = CharPos;
560
561     fn sub(self, rhs: CharPos) -> CharPos {
562         CharPos(self.to_usize() - rhs.to_usize())
563     }
564 }
565
566 // _____________________________________________________________________________
567 // Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
568 //
569
570 /// A source code location used for error reporting
571 #[derive(Debug)]
572 pub struct Loc {
573     /// Information about the original source
574     pub file: Rc<FileMap>,
575     /// The (1-based) line number
576     pub line: usize,
577     /// The (0-based) column offset
578     pub col: CharPos
579 }
580
581 /// A source code location used as the result of lookup_char_pos_adj
582 // Actually, *none* of the clients use the filename *or* file field;
583 // perhaps they should just be removed.
584 #[derive(Debug)]
585 pub struct LocWithOpt {
586     pub filename: FileName,
587     pub line: usize,
588     pub col: CharPos,
589     pub file: Option<Rc<FileMap>>,
590 }
591
592 // used to be structural records. Better names, anyone?
593 #[derive(Debug)]
594 pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
595 #[derive(Debug)]
596 pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
597
598 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
599 pub struct LineInfo {
600     /// Index of line, starting from 0.
601     pub line_index: usize,
602
603     /// Column in line where span begins, starting from 0.
604     pub start_col: CharPos,
605
606     /// Column in line where span ends, starting from 0, exclusive.
607     pub end_col: CharPos,
608 }
609
610 pub struct FileLines {
611     pub file: Rc<FileMap>,
612     pub lines: Vec<LineInfo>
613 }
614
615 thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
616                 Cell::new(default_span_debug));
617
618 /* assuming that we're not in macro expansion */
619 pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
620     Span {lo: lo, hi: hi, expn_id: NO_EXPANSION}
621 }
622
623 pub struct MacroBacktrace {
624     /// span where macro was applied to generate this code
625     pub call_site: Span,
626
627     /// name of macro that was applied (e.g., "foo!" or "#[derive(Eq)]")
628     pub macro_decl_name: String,
629
630     /// span where macro was defined (if known)
631     pub def_site_span: Option<Span>,
632 }
633
634 // _____________________________________________________________________________
635 // SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
636 //
637
638 pub type FileLinesResult = Result<FileLines, SpanLinesError>;
639
640 #[derive(Clone, PartialEq, Eq, Debug)]
641 pub enum SpanLinesError {
642     IllFormedSpan(Span),
643     DistinctSources(DistinctSources),
644 }
645
646 #[derive(Clone, PartialEq, Eq, Debug)]
647 pub enum SpanSnippetError {
648     IllFormedSpan(Span),
649     DistinctSources(DistinctSources),
650     MalformedForCodemap(MalformedCodemapPositions),
651     SourceNotAvailable { filename: String }
652 }
653
654 #[derive(Clone, PartialEq, Eq, Debug)]
655 pub struct DistinctSources {
656     pub begin: (String, BytePos),
657     pub end: (String, BytePos)
658 }
659
660 #[derive(Clone, PartialEq, Eq, Debug)]
661 pub struct MalformedCodemapPositions {
662     pub name: String,
663     pub source_len: usize,
664     pub begin_pos: BytePos,
665     pub end_pos: BytePos
666 }
667