]> git.proxmox.com Git - rustc.git/blame - src/libsyntax/codemap.rs
New upstream version 1.23.0+dfsg1
[rustc.git] / src / libsyntax / codemap.rs
CommitLineData
223e47cc
LB
1// Copyright 2012 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
1a4d82fc
JJ
11//! The CodeMap tracks all the source code used within a single crate, mapping
12//! from integer byte positions to the original source code location. Each bit
13//! of source parsed during crate parsing (typically files, in-memory strings,
14//! or various bits of macro expansion) cover a continuous range of bytes in the
15//! CodeMap and are represented by FileMaps. Byte positions are stored in
16//! `spans` and used pervasively in the compiler. They are absolute positions
17//! within the CodeMap, which upon request can be converted to line and column
18//! information, source code snippets, etc.
223e47cc 19
abe05a73 20
cc61c64b
XL
21pub use syntax_pos::*;
22pub use syntax_pos::hygiene::{ExpnFormat, ExpnInfo, NameAndSpan};
d9579d0f 23pub use self::ExpnFormat::*;
223e47cc 24
abe05a73
XL
25use rustc_data_structures::fx::FxHashMap;
26use rustc_data_structures::stable_hasher::StableHasher;
7cac9316 27use std::cell::{RefCell, Ref};
abe05a73 28use std::hash::Hash;
7cac9316 29use std::path::{Path, PathBuf};
1a4d82fc 30use std::rc::Rc;
223e47cc 31
3157f602
XL
32use std::env;
33use std::fs;
62682a34 34use std::io::{self, Read};
3157f602 35use errors::CodeMapper;
223e47cc 36
1a4d82fc
JJ
37/// Return the span itself if it doesn't come from a macro expansion,
38/// otherwise return the call site span up to the `enclosing_sp` by
39/// following the `expn_info` chain.
cc61c64b 40pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
ea8adc8c
XL
41 let call_site1 = sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
42 let call_site2 = enclosing_sp.ctxt().outer().expn_info().map(|ei| ei.call_site);
1a4d82fc
JJ
43 match (call_site1, call_site2) {
44 (None, _) => sp,
45 (Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
cc61c64b 46 (Some(call_site1), _) => original_sp(call_site1, enclosing_sp),
1a4d82fc
JJ
47 }
48}
223e47cc 49
3157f602
XL
50#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
51pub struct Spanned<T> {
52 pub node: T,
53 pub span: Span,
7453a54e
SL
54}
55
3157f602
XL
56pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
57 Spanned {node: t, span: sp}
223e47cc
LB
58}
59
3157f602
XL
60pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
61 respan(DUMMY_SP, t)
1a4d82fc
JJ
62}
63
c34b1796
AL
64// _____________________________________________________________________________
65// FileMap, MultiByteChar, FileName, FileLines
66//
67
62682a34
SL
68/// An abstraction over the fs operations used by the Parser.
69pub trait FileLoader {
70 /// Query the existence of a file.
71 fn file_exists(&self, path: &Path) -> bool;
72
3157f602
XL
73 /// Return an absolute path to a file, if possible.
74 fn abs_path(&self, path: &Path) -> Option<PathBuf>;
75
62682a34
SL
76 /// Read the contents of an UTF-8 file into memory.
77 fn read_file(&self, path: &Path) -> io::Result<String>;
78}
79
80/// A FileLoader that uses std::fs to load real files.
81pub struct RealFileLoader;
82
83impl FileLoader for RealFileLoader {
84 fn file_exists(&self, path: &Path) -> bool {
85 fs::metadata(path).is_ok()
86 }
87
3157f602
XL
88 fn abs_path(&self, path: &Path) -> Option<PathBuf> {
89 if path.is_absolute() {
90 Some(path.to_path_buf())
91 } else {
92 env::current_dir()
93 .ok()
94 .map(|cwd| cwd.join(path))
95 }
96 }
97
62682a34
SL
98 fn read_file(&self, path: &Path) -> io::Result<String> {
99 let mut src = String::new();
54a0048b 100 fs::File::open(path)?.read_to_string(&mut src)?;
62682a34
SL
101 Ok(src)
102 }
103}
c34b1796 104
abe05a73
XL
105// This is a FileMap identifier that is used to correlate FileMaps between
106// subsequent compilation sessions (which is something we need to do during
107// incremental compilation).
108#[derive(Copy, Clone, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable)]
109pub struct StableFilemapId(u128);
110
111impl StableFilemapId {
112 pub fn new(filemap: &FileMap) -> StableFilemapId {
113 let mut hasher = StableHasher::new();
114
115 filemap.name.hash(&mut hasher);
116 filemap.name_was_remapped.hash(&mut hasher);
117 filemap.unmapped_path.hash(&mut hasher);
118
119 StableFilemapId(hasher.finish())
120 }
121}
122
c34b1796
AL
123// _____________________________________________________________________________
124// CodeMap
125//
126
223e47cc 127pub struct CodeMap {
7cac9316
XL
128 pub(super) files: RefCell<Vec<Rc<FileMap>>>,
129 file_loader: Box<FileLoader>,
130 // This is used to apply the file path remapping as specified via
131 // -Zremap-path-prefix to all FileMaps allocated within this CodeMap.
132 path_mapping: FilePathMapping,
abe05a73 133 stable_id_to_filemap: RefCell<FxHashMap<StableFilemapId, Rc<FileMap>>>,
223e47cc
LB
134}
135
970d7e83 136impl CodeMap {
7cac9316 137 pub fn new(path_mapping: FilePathMapping) -> CodeMap {
223e47cc 138 CodeMap {
1a4d82fc 139 files: RefCell::new(Vec::new()),
7cac9316 140 file_loader: Box::new(RealFileLoader),
3b2f2976 141 path_mapping,
abe05a73 142 stable_id_to_filemap: RefCell::new(FxHashMap()),
62682a34
SL
143 }
144 }
145
7cac9316
XL
146 pub fn with_file_loader(file_loader: Box<FileLoader>,
147 path_mapping: FilePathMapping)
148 -> CodeMap {
62682a34
SL
149 CodeMap {
150 files: RefCell::new(Vec::new()),
3b2f2976
XL
151 file_loader,
152 path_mapping,
abe05a73 153 stable_id_to_filemap: RefCell::new(FxHashMap()),
223e47cc
LB
154 }
155 }
156
7cac9316
XL
157 pub fn path_mapping(&self) -> &FilePathMapping {
158 &self.path_mapping
159 }
160
62682a34
SL
161 pub fn file_exists(&self, path: &Path) -> bool {
162 self.file_loader.file_exists(path)
163 }
164
165 pub fn load_file(&self, path: &Path) -> io::Result<Rc<FileMap>> {
54a0048b 166 let src = self.file_loader.read_file(path)?;
7cac9316
XL
167 Ok(self.new_filemap(path.to_str().unwrap().to_string(), src))
168 }
169
170 pub fn files(&self) -> Ref<Vec<Rc<FileMap>>> {
171 self.files.borrow()
62682a34
SL
172 }
173
abe05a73
XL
174 pub fn filemap_by_stable_id(&self, stable_id: StableFilemapId) -> Option<Rc<FileMap>> {
175 self.stable_id_to_filemap.borrow().get(&stable_id).map(|fm| fm.clone())
176 }
177
c1a9b12d
SL
178 fn next_start_pos(&self) -> usize {
179 let files = self.files.borrow();
180 match files.last() {
181 None => 0,
182 // Add one so there is some space between files. This lets us distinguish
183 // positions in the codemap, even in the presence of zero-length files.
184 Some(last) => last.end_pos.to_usize() + 1,
185 }
186 }
187
188 /// Creates a new filemap without setting its line information. If you don't
189 /// intend to set the line information yourself, you should use new_filemap_and_lines.
041b39d2 190 pub fn new_filemap(&self, filename: FileName, src: String) -> Rc<FileMap> {
c1a9b12d 191 let start_pos = self.next_start_pos();
1a4d82fc 192 let mut files = self.files.borrow_mut();
223e47cc 193
ea8adc8c
XL
194 // The path is used to determine the directory for loading submodules and
195 // include files, so it must be before remapping.
196 // Note that filename may not be a valid path, eg it may be `<anon>` etc,
197 // but this is okay because the directory determined by `path.pop()` will
198 // be empty, so the working directory will be used.
199 let unmapped_path = PathBuf::from(filename.clone());
200
7cac9316 201 let (filename, was_remapped) = self.path_mapping.map_prefix(filename);
ea8adc8c
XL
202 let filemap = Rc::new(FileMap::new(
203 filename,
204 was_remapped,
205 unmapped_path,
206 src,
207 Pos::from_usize(start_pos),
208 ));
223e47cc 209
1a4d82fc
JJ
210 files.push(filemap.clone());
211
abe05a73
XL
212 self.stable_id_to_filemap
213 .borrow_mut()
214 .insert(StableFilemapId::new(&filemap), filemap.clone());
215
1a4d82fc 216 filemap
223e47cc
LB
217 }
218
c1a9b12d 219 /// Creates a new filemap and sets its line information.
7cac9316
XL
220 pub fn new_filemap_and_lines(&self, filename: &str, src: &str) -> Rc<FileMap> {
221 let fm = self.new_filemap(filename.to_string(), src.to_owned());
a7813a04 222 let mut byte_pos: u32 = fm.start_pos.0;
c1a9b12d
SL
223 for line in src.lines() {
224 // register the start of this line
225 fm.next_line(BytePos(byte_pos));
226
227 // update byte_pos to include this line and the \n at the end
228 byte_pos += line.len() as u32 + 1;
229 }
230 fm
231 }
232
233
c34b1796
AL
234 /// Allocates a new FileMap representing a source file from an external
235 /// crate. The source code of such an "imported filemap" is not available,
236 /// but we still know enough to generate accurate debuginfo location
237 /// information for things inlined from other crates.
238 pub fn new_imported_filemap(&self,
239 filename: FileName,
7cac9316
XL
240 name_was_remapped: bool,
241 crate_of_origin: u32,
041b39d2 242 src_hash: u128,
c34b1796 243 source_len: usize,
d9579d0f 244 mut file_local_lines: Vec<BytePos>,
abe05a73
XL
245 mut file_local_multibyte_chars: Vec<MultiByteChar>,
246 mut file_local_non_narrow_chars: Vec<NonNarrowChar>)
c34b1796 247 -> Rc<FileMap> {
c1a9b12d 248 let start_pos = self.next_start_pos();
c34b1796 249 let mut files = self.files.borrow_mut();
c34b1796
AL
250
251 let end_pos = Pos::from_usize(start_pos + source_len);
252 let start_pos = Pos::from_usize(start_pos);
253
d9579d0f
AL
254 for pos in &mut file_local_lines {
255 *pos = *pos + start_pos;
256 }
257
258 for mbc in &mut file_local_multibyte_chars {
259 mbc.pos = mbc.pos + start_pos;
260 }
c34b1796 261
abe05a73
XL
262 for swc in &mut file_local_non_narrow_chars {
263 *swc = *swc + start_pos;
264 }
265
c34b1796
AL
266 let filemap = Rc::new(FileMap {
267 name: filename,
3b2f2976 268 name_was_remapped,
ea8adc8c 269 unmapped_path: None,
3b2f2976 270 crate_of_origin,
c34b1796 271 src: None,
3b2f2976 272 src_hash,
041b39d2 273 external_src: RefCell::new(ExternalSource::AbsentOk),
3b2f2976
XL
274 start_pos,
275 end_pos,
d9579d0f
AL
276 lines: RefCell::new(file_local_lines),
277 multibyte_chars: RefCell::new(file_local_multibyte_chars),
abe05a73 278 non_narrow_chars: RefCell::new(file_local_non_narrow_chars),
c34b1796
AL
279 });
280
281 files.push(filemap.clone());
282
abe05a73
XL
283 self.stable_id_to_filemap
284 .borrow_mut()
285 .insert(StableFilemapId::new(&filemap), filemap.clone());
286
c34b1796
AL
287 filemap
288 }
289
1a4d82fc 290 pub fn mk_substr_filename(&self, sp: Span) -> String {
ea8adc8c 291 let pos = self.lookup_char_pos(sp.lo());
1a4d82fc
JJ
292 (format!("<{}:{}:{}>",
293 pos.file.name,
294 pos.line,
85aaf69f 295 pos.col.to_usize() + 1)).to_string()
223e47cc
LB
296 }
297
298 /// Lookup source information about a BytePos
970d7e83 299 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
d9579d0f 300 let chpos = self.bytepos_to_file_charpos(pos);
c1a9b12d
SL
301 match self.lookup_line(pos) {
302 Ok(FileMapAndLine { fm: f, line: a }) => {
303 let line = a + 1; // Line numbers start at 1
304 let linebpos = (*f.lines.borrow())[a];
305 let linechpos = self.bytepos_to_file_charpos(linebpos);
abe05a73
XL
306 let col = chpos - linechpos;
307
308 let col_display = {
309 let non_narrow_chars = f.non_narrow_chars.borrow();
310 let start_width_idx = non_narrow_chars
311 .binary_search_by_key(&linebpos, |x| x.pos())
312 .unwrap_or_else(|x| x);
313 let end_width_idx = non_narrow_chars
314 .binary_search_by_key(&pos, |x| x.pos())
315 .unwrap_or_else(|x| x);
316 let special_chars = end_width_idx - start_width_idx;
317 let non_narrow: usize =
318 non_narrow_chars[start_width_idx..end_width_idx]
319 .into_iter()
320 .map(|x| x.width())
321 .sum();
322 col.0 - special_chars + non_narrow
323 };
c1a9b12d
SL
324 debug!("byte pos {:?} is on the line at byte pos {:?}",
325 pos, linebpos);
326 debug!("char pos {:?} is on the line at char pos {:?}",
327 chpos, linechpos);
328 debug!("byte is on line: {}", line);
329 assert!(chpos >= linechpos);
330 Loc {
331 file: f,
3b2f2976 332 line,
abe05a73
XL
333 col,
334 col_display,
c1a9b12d
SL
335 }
336 }
337 Err(f) => {
abe05a73
XL
338 let col_display = {
339 let non_narrow_chars = f.non_narrow_chars.borrow();
340 let end_width_idx = non_narrow_chars
341 .binary_search_by_key(&pos, |x| x.pos())
342 .unwrap_or_else(|x| x);
343 let non_narrow: usize =
344 non_narrow_chars[0..end_width_idx]
345 .into_iter()
346 .map(|x| x.width())
347 .sum();
348 chpos.0 - end_width_idx + non_narrow
349 };
c1a9b12d
SL
350 Loc {
351 file: f,
352 line: 0,
353 col: chpos,
abe05a73 354 col_display,
c1a9b12d
SL
355 }
356 }
d9579d0f
AL
357 }
358 }
359
c1a9b12d
SL
360 // If the relevant filemap is empty, we don't return a line number.
361 fn lookup_line(&self, pos: BytePos) -> Result<FileMapAndLine, Rc<FileMap>> {
d9579d0f
AL
362 let idx = self.lookup_filemap_idx(pos);
363
364 let files = self.files.borrow();
365 let f = (*files)[idx].clone();
c1a9b12d 366
9e0c209e
SL
367 match f.lookup_line(pos) {
368 Some(line) => Ok(FileMapAndLine { fm: f, line: line }),
369 None => Err(f)
c1a9b12d 370 }
223e47cc
LB
371 }
372
970d7e83 373 pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
223e47cc 374 let loc = self.lookup_char_pos(pos);
1a4d82fc
JJ
375 LocWithOpt {
376 filename: loc.file.name.to_string(),
377 line: loc.line,
378 col: loc.col,
379 file: Some(loc.file)
223e47cc
LB
380 }
381 }
382
9e0c209e
SL
383 /// Returns `Some(span)`, a union of the lhs and rhs span. The lhs must precede the rhs. If
384 /// there are gaps between lhs and rhs, the resulting union will cross these gaps.
385 /// For this to work, the spans have to be:
cc61c64b 386 /// * the ctxt of both spans much match
9e0c209e
SL
387 /// * the lhs span needs to end on the same line the rhs span begins
388 /// * the lhs span must start at or before the rhs span
389 pub fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
9e0c209e 390 // make sure we're at the same expansion id
ea8adc8c 391 if sp_lhs.ctxt() != sp_rhs.ctxt() {
9e0c209e
SL
392 return None;
393 }
394
ea8adc8c 395 let lhs_end = match self.lookup_line(sp_lhs.hi()) {
9e0c209e
SL
396 Ok(x) => x,
397 Err(_) => return None
398 };
ea8adc8c 399 let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
9e0c209e
SL
400 Ok(x) => x,
401 Err(_) => return None
402 };
403
404 // if we must cross lines to merge, don't merge
405 if lhs_end.line != rhs_begin.line {
406 return None;
407 }
408
409 // ensure these follow the expected order and we don't overlap
ea8adc8c
XL
410 if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
411 Some(sp_lhs.to(sp_rhs))
9e0c209e
SL
412 } else {
413 None
414 }
415 }
416
1a4d82fc 417 pub fn span_to_string(&self, sp: Span) -> String {
7453a54e 418 if self.files.borrow().is_empty() && sp.source_equal(&DUMMY_SP) {
1a4d82fc 419 return "no-location".to_string();
223e47cc
LB
420 }
421
ea8adc8c
XL
422 let lo = self.lookup_char_pos_adj(sp.lo());
423 let hi = self.lookup_char_pos_adj(sp.hi());
1a4d82fc
JJ
424 return (format!("{}:{}:{}: {}:{}",
425 lo.filename,
426 lo.line,
85aaf69f 427 lo.col.to_usize() + 1,
1a4d82fc 428 hi.line,
85aaf69f 429 hi.col.to_usize() + 1)).to_string()
223e47cc
LB
430 }
431
1a4d82fc 432 pub fn span_to_filename(&self, sp: Span) -> FileName {
ea8adc8c
XL
433 self.lookup_char_pos(sp.lo()).file.name.clone()
434 }
435
436 pub fn span_to_unmapped_path(&self, sp: Span) -> PathBuf {
437 self.lookup_char_pos(sp.lo()).file.unmapped_path.clone()
438 .expect("CodeMap::span_to_unmapped_path called for imported FileMap?")
223e47cc
LB
439 }
440
d9579d0f 441 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
a7813a04
XL
442 debug!("span_to_lines(sp={:?})", sp);
443
ea8adc8c 444 if sp.lo() > sp.hi() {
d9579d0f
AL
445 return Err(SpanLinesError::IllFormedSpan(sp));
446 }
447
ea8adc8c 448 let lo = self.lookup_char_pos(sp.lo());
a7813a04 449 debug!("span_to_lines: lo={:?}", lo);
ea8adc8c 450 let hi = self.lookup_char_pos(sp.hi());
a7813a04 451 debug!("span_to_lines: hi={:?}", hi);
d9579d0f
AL
452
453 if lo.file.start_pos != hi.file.start_pos {
454 return Err(SpanLinesError::DistinctSources(DistinctSources {
455 begin: (lo.file.name.clone(), lo.file.start_pos),
456 end: (hi.file.name.clone(), hi.file.start_pos),
457 }));
458 }
459 assert!(hi.line >= lo.line);
460
9346a6ac
AL
461 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
462
463 // The span starts partway through the first line,
464 // but after that it starts from offset 0.
465 let mut start_col = lo.col;
466
467 // For every line but the last, it extends from `start_col`
468 // and to the end of the line. Be careful because the line
469 // numbers in Loc are 1-based, so we subtract 1 to get 0-based
470 // lines.
471 for line_index in lo.line-1 .. hi.line-1 {
a7813a04
XL
472 let line_len = lo.file.get_line(line_index)
473 .map(|s| s.chars().count())
474 .unwrap_or(0);
3b2f2976
XL
475 lines.push(LineInfo { line_index,
476 start_col,
9346a6ac
AL
477 end_col: CharPos::from_usize(line_len) });
478 start_col = CharPos::from_usize(0);
479 }
480
481 // For the last line, it extends from `start_col` to `hi.col`:
482 lines.push(LineInfo { line_index: hi.line - 1,
3b2f2976 483 start_col,
9346a6ac
AL
484 end_col: hi.col });
485
d9579d0f 486 Ok(FileLines {file: lo.file, lines: lines})
223e47cc
LB
487 }
488
85aaf69f 489 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
ea8adc8c 490 if sp.lo() > sp.hi() {
85aaf69f
SL
491 return Err(SpanSnippetError::IllFormedSpan(sp));
492 }
493
ea8adc8c
XL
494 let local_begin = self.lookup_byte_offset(sp.lo());
495 let local_end = self.lookup_byte_offset(sp.hi());
1a4d82fc 496
c34b1796 497 if local_begin.fm.start_pos != local_end.fm.start_pos {
85aaf69f 498 return Err(SpanSnippetError::DistinctSources(DistinctSources {
c34b1796
AL
499 begin: (local_begin.fm.name.clone(),
500 local_begin.fm.start_pos),
501 end: (local_end.fm.name.clone(),
502 local_end.fm.start_pos)
85aaf69f 503 }));
1a4d82fc 504 } else {
041b39d2
XL
505 self.ensure_filemap_source_present(local_begin.fm.clone());
506
507 let start_index = local_begin.pos.to_usize();
508 let end_index = local_end.pos.to_usize();
509 let source_len = (local_begin.fm.end_pos -
510 local_begin.fm.start_pos).to_usize();
511
512 if start_index > end_index || end_index > source_len {
513 return Err(SpanSnippetError::MalformedForCodemap(
514 MalformedCodemapPositions {
515 name: local_begin.fm.name.clone(),
3b2f2976 516 source_len,
041b39d2
XL
517 begin_pos: local_begin.pos,
518 end_pos: local_end.pos,
519 }));
520 }
521
522 if let Some(ref src) = local_begin.fm.src {
523 return Ok((&src[start_index..end_index]).to_string());
524 } else if let Some(src) = local_begin.fm.external_src.borrow().get_source() {
525 return Ok((&src[start_index..end_index]).to_string());
526 } else {
527 return Err(SpanSnippetError::SourceNotAvailable {
528 filename: local_begin.fm.name.clone()
529 });
c34b1796 530 }
1a4d82fc 531 }
223e47cc
LB
532 }
533
cc61c64b
XL
534 /// Given a `Span`, try to get a shorter span ending before the first occurrence of `c` `char`
535 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
536 match self.span_to_snippet(sp) {
537 Ok(snippet) => {
538 let snippet = snippet.split(c).nth(0).unwrap_or("").trim_right();
7cac9316 539 if !snippet.is_empty() && !snippet.contains('\n') {
ea8adc8c 540 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
cc61c64b
XL
541 } else {
542 sp
543 }
544 }
545 _ => sp,
546 }
547 }
548
abe05a73
XL
549 /// Given a `Span`, try to get a shorter span ending just after the first
550 /// occurrence of `char` `c`.
551 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
552 if let Ok(snippet) = self.span_to_snippet(sp) {
553 if let Some(offset) = snippet.find(c) {
554 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
555 }
556 }
557 sp
558 }
559
cc61c64b
XL
560 pub fn def_span(&self, sp: Span) -> Span {
561 self.span_until_char(sp, '{')
562 }
563
3157f602 564 pub fn get_filemap(&self, filename: &str) -> Option<Rc<FileMap>> {
62682a34 565 for fm in self.files.borrow().iter() {
1a4d82fc 566 if filename == fm.name {
3157f602 567 return Some(fm.clone());
1a4d82fc
JJ
568 }
569 }
3157f602 570 None
1a4d82fc
JJ
571 }
572
c34b1796 573 /// For a global BytePos compute the local offset within the containing FileMap
1a4d82fc
JJ
574 pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
575 let idx = self.lookup_filemap_idx(bpos);
576 let fm = (*self.files.borrow())[idx].clone();
577 let offset = bpos - fm.start_pos;
578 FileMapAndBytePos {fm: fm, pos: offset}
579 }
580
c1a9b12d 581 /// Converts an absolute BytePos to a CharPos relative to the filemap.
1a4d82fc
JJ
582 pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
583 let idx = self.lookup_filemap_idx(bpos);
584 let files = self.files.borrow();
585 let map = &(*files)[idx];
586
587 // The number of extra bytes due to multibyte chars in the FileMap
588 let mut total_extra_bytes = 0;
589
62682a34 590 for mbc in map.multibyte_chars.borrow().iter() {
1a4d82fc
JJ
591 debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
592 if mbc.pos < bpos {
593 // every character is at least one byte, so we only
594 // count the actual extra bytes.
595 total_extra_bytes += mbc.bytes - 1;
596 // We should never see a byte position in the middle of a
597 // character
85aaf69f 598 assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
1a4d82fc
JJ
599 } else {
600 break;
601 }
602 }
603
85aaf69f
SL
604 assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
605 CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
223e47cc 606 }
223e47cc 607
c1a9b12d 608 // Return the index of the filemap (in self.files) which contains pos.
9e0c209e 609 pub fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
1a4d82fc
JJ
610 let files = self.files.borrow();
611 let files = &*files;
c1a9b12d
SL
612 let count = files.len();
613
614 // Binary search for the filemap.
85aaf69f 615 let mut a = 0;
c1a9b12d 616 let mut b = count;
85aaf69f
SL
617 while b - a > 1 {
618 let m = (a + b) / 2;
1a4d82fc 619 if files[m].start_pos > pos {
223e47cc
LB
620 b = m;
621 } else {
622 a = m;
623 }
624 }
c1a9b12d
SL
625
626 assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
223e47cc
LB
627
628 return a;
629 }
630
92a42be0 631 pub fn count_lines(&self) -> usize {
7cac9316 632 self.files().iter().fold(0, |a, f| a + f.count_lines())
92a42be0 633 }
a7813a04
XL
634}
635
3157f602
XL
636impl CodeMapper for CodeMap {
637 fn lookup_char_pos(&self, pos: BytePos) -> Loc {
638 self.lookup_char_pos(pos)
639 }
640 fn span_to_lines(&self, sp: Span) -> FileLinesResult {
641 self.span_to_lines(sp)
642 }
643 fn span_to_string(&self, sp: Span) -> String {
644 self.span_to_string(sp)
645 }
646 fn span_to_filename(&self, sp: Span) -> FileName {
647 self.span_to_filename(sp)
648 }
9e0c209e
SL
649 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
650 self.merge_spans(sp_lhs, sp_rhs)
651 }
7cac9316
XL
652 fn call_span_if_macro(&self, sp: Span) -> Span {
653 if self.span_to_filename(sp.clone()).contains("macros>") {
654 let v = sp.macro_backtrace();
655 if let Some(use_site) = v.last() {
656 return use_site.call_site;
657 }
658 }
659 sp
660 }
041b39d2
XL
661 fn ensure_filemap_source_present(&self, file_map: Rc<FileMap>) -> bool {
662 file_map.add_external_src(
663 || self.file_loader.read_file(Path::new(&file_map.name)).ok()
664 )
665 }
7cac9316
XL
666}
667
668#[derive(Clone)]
669pub struct FilePathMapping {
670 mapping: Vec<(String, String)>,
671}
672
673impl FilePathMapping {
674 pub fn empty() -> FilePathMapping {
675 FilePathMapping {
676 mapping: vec![]
677 }
678 }
679
680 pub fn new(mapping: Vec<(String, String)>) -> FilePathMapping {
681 FilePathMapping {
3b2f2976 682 mapping,
7cac9316
XL
683 }
684 }
685
686 /// Applies any path prefix substitution as defined by the mapping.
687 /// The return value is the remapped path and a boolean indicating whether
688 /// the path was affected by the mapping.
689 pub fn map_prefix(&self, path: String) -> (String, bool) {
690 // NOTE: We are iterating over the mapping entries from last to first
691 // because entries specified later on the command line should
692 // take precedence.
693 for &(ref from, ref to) in self.mapping.iter().rev() {
694 if path.starts_with(from) {
695 let mapped = path.replacen(from, to, 1);
696 return (mapped, true);
697 }
698 }
699
700 (path, false)
701 }
85aaf69f
SL
702}
703
c34b1796
AL
704// _____________________________________________________________________________
705// Tests
706//
707
223e47cc 708#[cfg(test)]
d9579d0f 709mod tests {
223e47cc 710 use super::*;
041b39d2 711 use std::borrow::Cow;
3157f602 712 use std::rc::Rc;
223e47cc
LB
713
714 #[test]
715 fn t1 () {
7cac9316 716 let cm = CodeMap::new(FilePathMapping::empty());
1a4d82fc
JJ
717 let fm = cm.new_filemap("blork.rs".to_string(),
718 "first line.\nsecond line".to_string());
223e47cc 719 fm.next_line(BytePos(0));
c1a9b12d 720 // Test we can get lines with partial line info.
041b39d2 721 assert_eq!(fm.get_line(0), Some(Cow::from("first line.")));
c1a9b12d 722 // TESTING BROKEN BEHAVIOR: line break declared before actual line break.
223e47cc 723 fm.next_line(BytePos(10));
041b39d2 724 assert_eq!(fm.get_line(1), Some(Cow::from(".")));
c1a9b12d 725 fm.next_line(BytePos(12));
041b39d2 726 assert_eq!(fm.get_line(2), Some(Cow::from("second line")));
223e47cc
LB
727 }
728
729 #[test]
c34b1796 730 #[should_panic]
223e47cc 731 fn t2 () {
7cac9316 732 let cm = CodeMap::new(FilePathMapping::empty());
1a4d82fc
JJ
733 let fm = cm.new_filemap("blork.rs".to_string(),
734 "first line.\nsecond line".to_string());
223e47cc
LB
735 // TESTING *REALLY* BROKEN BEHAVIOR:
736 fm.next_line(BytePos(0));
737 fm.next_line(BytePos(10));
738 fm.next_line(BytePos(2));
739 }
1a4d82fc
JJ
740
741 fn init_code_map() -> CodeMap {
7cac9316 742 let cm = CodeMap::new(FilePathMapping::empty());
1a4d82fc
JJ
743 let fm1 = cm.new_filemap("blork.rs".to_string(),
744 "first line.\nsecond line".to_string());
745 let fm2 = cm.new_filemap("empty.rs".to_string(),
746 "".to_string());
747 let fm3 = cm.new_filemap("blork2.rs".to_string(),
748 "first line.\nsecond line".to_string());
749
750 fm1.next_line(BytePos(0));
751 fm1.next_line(BytePos(12));
c1a9b12d
SL
752 fm2.next_line(fm2.start_pos);
753 fm3.next_line(fm3.start_pos);
754 fm3.next_line(fm3.start_pos + BytePos(12));
1a4d82fc
JJ
755
756 cm
757 }
758
759 #[test]
760 fn t3() {
761 // Test lookup_byte_offset
762 let cm = init_code_map();
763
c1a9b12d 764 let fmabp1 = cm.lookup_byte_offset(BytePos(23));
1a4d82fc 765 assert_eq!(fmabp1.fm.name, "blork.rs");
c1a9b12d
SL
766 assert_eq!(fmabp1.pos, BytePos(23));
767
768 let fmabp1 = cm.lookup_byte_offset(BytePos(24));
769 assert_eq!(fmabp1.fm.name, "empty.rs");
770 assert_eq!(fmabp1.pos, BytePos(0));
1a4d82fc 771
c1a9b12d 772 let fmabp2 = cm.lookup_byte_offset(BytePos(25));
1a4d82fc
JJ
773 assert_eq!(fmabp2.fm.name, "blork2.rs");
774 assert_eq!(fmabp2.pos, BytePos(0));
775 }
776
777 #[test]
778 fn t4() {
779 // Test bytepos_to_file_charpos
780 let cm = init_code_map();
781
782 let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
783 assert_eq!(cp1, CharPos(22));
784
c1a9b12d 785 let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
1a4d82fc
JJ
786 assert_eq!(cp2, CharPos(0));
787 }
788
789 #[test]
790 fn t5() {
791 // Test zero-length filemaps.
792 let cm = init_code_map();
793
794 let loc1 = cm.lookup_char_pos(BytePos(22));
795 assert_eq!(loc1.file.name, "blork.rs");
796 assert_eq!(loc1.line, 2);
797 assert_eq!(loc1.col, CharPos(10));
798
c1a9b12d 799 let loc2 = cm.lookup_char_pos(BytePos(25));
1a4d82fc
JJ
800 assert_eq!(loc2.file.name, "blork2.rs");
801 assert_eq!(loc2.line, 1);
802 assert_eq!(loc2.col, CharPos(0));
803 }
804
805 fn init_code_map_mbc() -> CodeMap {
7cac9316 806 let cm = CodeMap::new(FilePathMapping::empty());
1a4d82fc
JJ
807 // € is a three byte utf8 char.
808 let fm1 =
809 cm.new_filemap("blork.rs".to_string(),
810 "fir€st €€€€ line.\nsecond line".to_string());
811 let fm2 = cm.new_filemap("blork2.rs".to_string(),
812 "first line€€.\n€ second line".to_string());
813
814 fm1.next_line(BytePos(0));
c1a9b12d
SL
815 fm1.next_line(BytePos(28));
816 fm2.next_line(fm2.start_pos);
817 fm2.next_line(fm2.start_pos + BytePos(20));
1a4d82fc
JJ
818
819 fm1.record_multibyte_char(BytePos(3), 3);
820 fm1.record_multibyte_char(BytePos(9), 3);
821 fm1.record_multibyte_char(BytePos(12), 3);
822 fm1.record_multibyte_char(BytePos(15), 3);
823 fm1.record_multibyte_char(BytePos(18), 3);
c1a9b12d
SL
824 fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3);
825 fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3);
826 fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3);
1a4d82fc
JJ
827
828 cm
829 }
830
831 #[test]
832 fn t6() {
833 // Test bytepos_to_file_charpos in the presence of multi-byte chars
834 let cm = init_code_map_mbc();
835
836 let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
837 assert_eq!(cp1, CharPos(3));
838
839 let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
840 assert_eq!(cp2, CharPos(4));
841
842 let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
843 assert_eq!(cp3, CharPos(12));
844
845 let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
846 assert_eq!(cp4, CharPos(15));
847 }
848
849 #[test]
850 fn t7() {
851 // Test span_to_lines for a span ending at the end of filemap
852 let cm = init_code_map();
ea8adc8c 853 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
d9579d0f 854 let file_lines = cm.span_to_lines(span).unwrap();
1a4d82fc
JJ
855
856 assert_eq!(file_lines.file.name, "blork.rs");
857 assert_eq!(file_lines.lines.len(), 1);
9346a6ac
AL
858 assert_eq!(file_lines.lines[0].line_index, 1);
859 }
860
a7813a04 861 /// Given a string like " ~~~~~~~~~~~~ ", produces a span
3b2f2976 862 /// converting that range. The idea is that the string has the same
9346a6ac
AL
863 /// length as the input, and we uncover the byte positions. Note
864 /// that this can span lines and so on.
865 fn span_from_selection(input: &str, selection: &str) -> Span {
866 assert_eq!(input.len(), selection.len());
a7813a04 867 let left_index = selection.find('~').unwrap() as u32;
7453a54e 868 let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
ea8adc8c 869 Span::new(BytePos(left_index), BytePos(right_index + 1), NO_EXPANSION)
9346a6ac
AL
870 }
871
3b2f2976 872 /// Test span_to_snippet and span_to_lines for a span converting 3
9346a6ac
AL
873 /// lines in the middle of a file.
874 #[test]
875 fn span_to_snippet_and_lines_spanning_multiple_lines() {
7cac9316 876 let cm = CodeMap::new(FilePathMapping::empty());
9346a6ac 877 let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
a7813a04 878 let selection = " \n ~~\n~~~\n~~~~~ \n \n";
7cac9316 879 cm.new_filemap_and_lines("blork.rs", inputtext);
9346a6ac
AL
880 let span = span_from_selection(inputtext, selection);
881
882 // check that we are extracting the text we thought we were extracting
883 assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
884
885 // check that span_to_lines gives us the complete result with the lines/cols we expected
d9579d0f 886 let lines = cm.span_to_lines(span).unwrap();
9346a6ac
AL
887 let expected = vec![
888 LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
889 LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
890 LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
891 ];
892 assert_eq!(lines.lines, expected);
1a4d82fc
JJ
893 }
894
895 #[test]
896 fn t8() {
897 // Test span_to_snippet for a span ending at the end of filemap
898 let cm = init_code_map();
ea8adc8c 899 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1a4d82fc
JJ
900 let snippet = cm.span_to_snippet(span);
901
85aaf69f 902 assert_eq!(snippet, Ok("second line".to_string()));
1a4d82fc
JJ
903 }
904
905 #[test]
906 fn t9() {
907 // Test span_to_str for a span ending at the end of filemap
908 let cm = init_code_map();
ea8adc8c 909 let span = Span::new(BytePos(12), BytePos(23), NO_EXPANSION);
1a4d82fc
JJ
910 let sstr = cm.span_to_string(span);
911
912 assert_eq!(sstr, "blork.rs:2:1: 2:12");
913 }
92a42be0 914
9e0c209e
SL
915 /// Test failing to merge two spans on different lines
916 #[test]
917 fn span_merging_fail() {
7cac9316 918 let cm = CodeMap::new(FilePathMapping::empty());
9e0c209e
SL
919 let inputtext = "bbbb BB\ncc CCC\n";
920 let selection1 = " ~~\n \n";
921 let selection2 = " \n ~~~\n";
7cac9316 922 cm.new_filemap_and_lines("blork.rs", inputtext);
9e0c209e
SL
923 let span1 = span_from_selection(inputtext, selection1);
924 let span2 = span_from_selection(inputtext, selection2);
925
926 assert!(cm.merge_spans(span1, span2).is_none());
927 }
928
3157f602
XL
929 /// Returns the span corresponding to the `n`th occurrence of
930 /// `substring` in `source_text`.
931 trait CodeMapExtension {
932 fn span_substr(&self,
933 file: &Rc<FileMap>,
934 source_text: &str,
935 substring: &str,
936 n: usize)
937 -> Span;
938 }
939
940 impl CodeMapExtension for CodeMap {
941 fn span_substr(&self,
942 file: &Rc<FileMap>,
943 source_text: &str,
944 substring: &str,
945 n: usize)
946 -> Span
947 {
948 println!("span_substr(file={:?}/{:?}, substring={:?}, n={})",
949 file.name, file.start_pos, substring, n);
950 let mut i = 0;
951 let mut hi = 0;
952 loop {
953 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
954 panic!("source_text `{}` does not have {} occurrences of `{}`, only {}",
955 source_text, n, substring, i);
956 });
957 let lo = hi + offset;
958 hi = lo + substring.len();
959 if i == n {
ea8adc8c
XL
960 let span = Span::new(
961 BytePos(lo as u32 + file.start_pos.0),
962 BytePos(hi as u32 + file.start_pos.0),
963 NO_EXPANSION,
964 );
3157f602
XL
965 assert_eq!(&self.span_to_snippet(span).unwrap()[..],
966 substring);
967 return span;
968 }
969 i += 1;
970 }
971 }
972 }
223e47cc 973}