]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_span/src/source_map/tests.rs
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / compiler / rustc_span / src / source_map / tests.rs
CommitLineData
416331ca
XL
1use super::*;
2
3use rustc_data_structures::sync::Lrc;
4
5fn init_source_map() -> SourceMap {
6 let sm = SourceMap::new(FilePathMapping::empty());
dfeec247
XL
7 sm.new_source_file(PathBuf::from("blork.rs").into(), "first line.\nsecond line".to_string());
8 sm.new_source_file(PathBuf::from("empty.rs").into(), String::new());
9 sm.new_source_file(PathBuf::from("blork2.rs").into(), "first line.\nsecond line".to_string());
416331ca
XL
10 sm
11}
12
6a06907d
XL
13impl SourceMap {
14 /// Returns `Some(span)`, a union of the LHS and RHS span. The LHS must precede the RHS. If
15 /// there are gaps between LHS and RHS, the resulting union will cross these gaps.
16 /// For this to work,
17 ///
18 /// * the syntax contexts of both spans much match,
19 /// * the LHS span needs to end on the same line the RHS span begins,
20 /// * the LHS span must start at or before the RHS span.
21 fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span> {
22 // Ensure we're at the same expansion ID.
23 if sp_lhs.ctxt() != sp_rhs.ctxt() {
24 return None;
25 }
26
27 let lhs_end = match self.lookup_line(sp_lhs.hi()) {
28 Ok(x) => x,
29 Err(_) => return None,
30 };
31 let rhs_begin = match self.lookup_line(sp_rhs.lo()) {
32 Ok(x) => x,
33 Err(_) => return None,
34 };
35
36 // If we must cross lines to merge, don't merge.
37 if lhs_end.line != rhs_begin.line {
38 return None;
39 }
40
41 // Ensure these follow the expected order and that we don't overlap.
42 if (sp_lhs.lo() <= sp_rhs.lo()) && (sp_lhs.hi() <= sp_rhs.lo()) {
43 Some(sp_lhs.to(sp_rhs))
44 } else {
45 None
46 }
47 }
48
49 /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`.
50 fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
51 let idx = self.lookup_source_file_idx(bpos);
52 let sf = &(*self.files.borrow().source_files)[idx];
53 sf.bytepos_to_file_charpos(bpos)
54 }
55}
56
e1599b0c 57/// Tests `lookup_byte_offset`.
416331ca
XL
58#[test]
59fn t3() {
416331ca
XL
60 let sm = init_source_map();
61
62 let srcfbp1 = sm.lookup_byte_offset(BytePos(23));
63 assert_eq!(srcfbp1.sf.name, PathBuf::from("blork.rs").into());
64 assert_eq!(srcfbp1.pos, BytePos(23));
65
66 let srcfbp1 = sm.lookup_byte_offset(BytePos(24));
67 assert_eq!(srcfbp1.sf.name, PathBuf::from("empty.rs").into());
68 assert_eq!(srcfbp1.pos, BytePos(0));
69
70 let srcfbp2 = sm.lookup_byte_offset(BytePos(25));
71 assert_eq!(srcfbp2.sf.name, PathBuf::from("blork2.rs").into());
72 assert_eq!(srcfbp2.pos, BytePos(0));
73}
74
e1599b0c 75/// Tests `bytepos_to_file_charpos`.
416331ca
XL
76#[test]
77fn t4() {
416331ca
XL
78 let sm = init_source_map();
79
80 let cp1 = sm.bytepos_to_file_charpos(BytePos(22));
81 assert_eq!(cp1, CharPos(22));
82
83 let cp2 = sm.bytepos_to_file_charpos(BytePos(25));
84 assert_eq!(cp2, CharPos(0));
85}
86
e1599b0c 87/// Tests zero-length `SourceFile`s.
416331ca
XL
88#[test]
89fn t5() {
416331ca
XL
90 let sm = init_source_map();
91
92 let loc1 = sm.lookup_char_pos(BytePos(22));
93 assert_eq!(loc1.file.name, PathBuf::from("blork.rs").into());
94 assert_eq!(loc1.line, 2);
95 assert_eq!(loc1.col, CharPos(10));
96
97 let loc2 = sm.lookup_char_pos(BytePos(25));
98 assert_eq!(loc2.file.name, PathBuf::from("blork2.rs").into());
99 assert_eq!(loc2.line, 1);
100 assert_eq!(loc2.col, CharPos(0));
101}
102
103fn init_source_map_mbc() -> SourceMap {
104 let sm = SourceMap::new(FilePathMapping::empty());
e1599b0c 105 // "€" is a three-byte UTF8 char.
dfeec247
XL
106 sm.new_source_file(
107 PathBuf::from("blork.rs").into(),
108 "fir€st €€€€ line.\nsecond line".to_string(),
109 );
110 sm.new_source_file(
111 PathBuf::from("blork2.rs").into(),
112 "first line€€.\n€ second line".to_string(),
113 );
416331ca
XL
114 sm
115}
116
e1599b0c 117/// Tests `bytepos_to_file_charpos` in the presence of multi-byte chars.
416331ca
XL
118#[test]
119fn t6() {
416331ca
XL
120 let sm = init_source_map_mbc();
121
122 let cp1 = sm.bytepos_to_file_charpos(BytePos(3));
123 assert_eq!(cp1, CharPos(3));
124
125 let cp2 = sm.bytepos_to_file_charpos(BytePos(6));
126 assert_eq!(cp2, CharPos(4));
127
128 let cp3 = sm.bytepos_to_file_charpos(BytePos(56));
129 assert_eq!(cp3, CharPos(12));
130
131 let cp4 = sm.bytepos_to_file_charpos(BytePos(61));
132 assert_eq!(cp4, CharPos(15));
133}
134
e1599b0c 135/// Test `span_to_lines` for a span ending at the end of a `SourceFile`.
416331ca
XL
136#[test]
137fn t7() {
416331ca 138 let sm = init_source_map();
e1599b0c 139 let span = Span::with_root_ctxt(BytePos(12), BytePos(23));
416331ca
XL
140 let file_lines = sm.span_to_lines(span).unwrap();
141
142 assert_eq!(file_lines.file.name, PathBuf::from("blork.rs").into());
143 assert_eq!(file_lines.lines.len(), 1);
144 assert_eq!(file_lines.lines[0].line_index, 1);
145}
146
147/// Given a string like " ~~~~~~~~~~~~ ", produces a span
148/// converting that range. The idea is that the string has the same
149/// length as the input, and we uncover the byte positions. Note
150/// that this can span lines and so on.
151fn span_from_selection(input: &str, selection: &str) -> Span {
152 assert_eq!(input.len(), selection.len());
153 let left_index = selection.find('~').unwrap() as u32;
5869c6ff 154 let right_index = selection.rfind('~').map_or(left_index, |x| x as u32);
e1599b0c 155 Span::with_root_ctxt(BytePos(left_index), BytePos(right_index + 1))
416331ca
XL
156}
157
e1599b0c 158/// Tests `span_to_snippet` and `span_to_lines` for a span converting 3
416331ca
XL
159/// lines in the middle of a file.
160#[test]
161fn span_to_snippet_and_lines_spanning_multiple_lines() {
162 let sm = SourceMap::new(FilePathMapping::empty());
163 let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
164 let selection = " \n ~~\n~~~\n~~~~~ \n \n";
165 sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_string());
166 let span = span_from_selection(inputtext, selection);
167
e1599b0c 168 // Check that we are extracting the text we thought we were extracting.
416331ca
XL
169 assert_eq!(&sm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
170
e1599b0c 171 // Check that span_to_lines gives us the complete result with the lines/cols we expected.
416331ca
XL
172 let lines = sm.span_to_lines(span).unwrap();
173 let expected = vec![
174 LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
175 LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
dfeec247
XL
176 LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) },
177 ];
416331ca
XL
178 assert_eq!(lines.lines, expected);
179}
180
e1599b0c 181/// Test span_to_snippet for a span ending at the end of a `SourceFile`.
416331ca
XL
182#[test]
183fn t8() {
416331ca 184 let sm = init_source_map();
e1599b0c 185 let span = Span::with_root_ctxt(BytePos(12), BytePos(23));
416331ca
XL
186 let snippet = sm.span_to_snippet(span);
187
188 assert_eq!(snippet, Ok("second line".to_string()));
189}
190
e1599b0c 191/// Test `span_to_str` for a span ending at the end of a `SourceFile`.
416331ca
XL
192#[test]
193fn t9() {
416331ca 194 let sm = init_source_map();
e1599b0c 195 let span = Span::with_root_ctxt(BytePos(12), BytePos(23));
dfeec247 196 let sstr = sm.span_to_string(span);
416331ca
XL
197
198 assert_eq!(sstr, "blork.rs:2:1: 2:12");
199}
200
e1599b0c 201/// Tests failing to merge two spans on different lines.
416331ca
XL
202#[test]
203fn span_merging_fail() {
204 let sm = SourceMap::new(FilePathMapping::empty());
dfeec247 205 let inputtext = "bbbb BB\ncc CCC\n";
416331ca
XL
206 let selection1 = " ~~\n \n";
207 let selection2 = " \n ~~~\n";
208 sm.new_source_file(Path::new("blork.rs").to_owned().into(), inputtext.to_owned());
209 let span1 = span_from_selection(inputtext, selection1);
210 let span2 = span_from_selection(inputtext, selection2);
211
212 assert!(sm.merge_spans(span1, span2).is_none());
213}
214
ba9703b0
XL
215/// Tests loading an external source file that requires normalization.
216#[test]
217fn t10() {
218 let sm = SourceMap::new(FilePathMapping::empty());
219 let unnormalized = "first line.\r\nsecond line";
220 let normalized = "first line.\nsecond line";
221
222 let src_file = sm.new_source_file(PathBuf::from("blork.rs").into(), unnormalized.to_string());
223
224 assert_eq!(src_file.src.as_ref().unwrap().as_ref(), normalized);
225 assert!(
226 src_file.src_hash.matches(unnormalized),
227 "src_hash should use the source before normalization"
228 );
229
230 let SourceFile {
231 name,
232 name_was_remapped,
233 src_hash,
234 start_pos,
235 end_pos,
236 lines,
237 multibyte_chars,
238 non_narrow_chars,
239 normalized_pos,
240 name_hash,
241 ..
242 } = (*src_file).clone();
243
244 let imported_src_file = sm.new_imported_source_file(
245 name,
246 name_was_remapped,
247 src_hash,
248 name_hash,
249 (end_pos - start_pos).to_usize(),
250 CrateNum::new(0),
251 lines,
252 multibyte_chars,
253 non_narrow_chars,
254 normalized_pos,
255 start_pos,
256 end_pos,
257 );
258
259 assert!(
260 imported_src_file.external_src.borrow().get_source().is_none(),
261 "imported source file should not have source yet"
262 );
263 imported_src_file.add_external_src(|| Some(unnormalized.to_string()));
264 assert_eq!(
265 imported_src_file.external_src.borrow().get_source().unwrap().as_ref(),
266 normalized,
267 "imported source file should be normalized"
268 );
269}
270
e1599b0c 271/// Returns the span corresponding to the `n`th occurrence of `substring` in `source_text`.
416331ca 272trait SourceMapExtension {
e1599b0c
XL
273 fn span_substr(
274 &self,
275 file: &Lrc<SourceFile>,
276 source_text: &str,
277 substring: &str,
278 n: usize,
279 ) -> Span;
416331ca
XL
280}
281
282impl SourceMapExtension for SourceMap {
e1599b0c
XL
283 fn span_substr(
284 &self,
285 file: &Lrc<SourceFile>,
286 source_text: &str,
287 substring: &str,
288 n: usize,
289 ) -> Span {
6a06907d 290 eprintln!(
e1599b0c
XL
291 "span_substr(file={:?}/{:?}, substring={:?}, n={})",
292 file.name, file.start_pos, substring, n
293 );
416331ca
XL
294 let mut i = 0;
295 let mut hi = 0;
296 loop {
297 let offset = source_text[hi..].find(substring).unwrap_or_else(|| {
e1599b0c
XL
298 panic!(
299 "source_text `{}` does not have {} occurrences of `{}`, only {}",
300 source_text, n, substring, i
301 );
416331ca
XL
302 });
303 let lo = hi + offset;
304 hi = lo + substring.len();
305 if i == n {
e1599b0c 306 let span = Span::with_root_ctxt(
416331ca
XL
307 BytePos(lo as u32 + file.start_pos.0),
308 BytePos(hi as u32 + file.start_pos.0),
416331ca 309 );
e1599b0c 310 assert_eq!(&self.span_to_snippet(span).unwrap()[..], substring);
416331ca
XL
311 return span;
312 }
313 i += 1;
314 }
315 }
316}