Skip to content

Commit f0f8aa9

Browse files
author
Matthew Russo
committedDec 5, 2018
adds DocTest filename variant, refactors doctest_offset out of source_map, fixes remaining test failures

File tree

12 files changed

+52
-54
lines changed

12 files changed

+52
-54
lines changed
 

‎src/librustc/ich/impls_syntax.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -423,7 +423,8 @@ impl_stable_hash_for!(enum ::syntax_pos::FileName {
423423
ProcMacroSourceCode(s),
424424
CliCrateAttr(s),
425425
CfgSpec(s),
426-
Custom(s)
426+
Custom(s),
427+
DocTest(pb, line),
427428
});
428429

429430
impl<'a> HashStable<StableHashingContext<'a>> for SourceFile {

‎src/librustc_errors/emitter.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -1044,7 +1044,7 @@ impl EmitterWriter {
10441044
buffer.append(buffer_msg_line_offset,
10451045
&format!("{}:{}:{}",
10461046
loc.file.name,
1047-
sm.doctest_offset_line(loc.line),
1047+
sm.doctest_offset_line(&loc.file.name, loc.line),
10481048
loc.col.0 + 1),
10491049
Style::LineAndColumn);
10501050
for _ in 0..max_line_num_len {
@@ -1054,7 +1054,7 @@ impl EmitterWriter {
10541054
buffer.prepend(0,
10551055
&format!("{}:{}:{}: ",
10561056
loc.file.name,
1057-
sm.doctest_offset_line(loc.line),
1057+
sm.doctest_offset_line(&loc.file.name, loc.line),
10581058
loc.col.0 + 1),
10591059
Style::LineAndColumn);
10601060
}
@@ -1075,7 +1075,8 @@ impl EmitterWriter {
10751075
};
10761076
format!("{}:{}{}",
10771077
annotated_file.file.name,
1078-
sm.doctest_offset_line(first_line.line_index),
1078+
sm.doctest_offset_line(
1079+
&annotated_file.file.name, first_line.line_index),
10791080
col)
10801081
} else {
10811082
annotated_file.file.name.to_string()

‎src/librustc_errors/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ pub trait SourceMapper {
130130
fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
131131
fn call_span_if_macro(&self, sp: Span) -> Span;
132132
fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool;
133-
fn doctest_offset_line(&self, line: usize) -> usize;
133+
fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize;
134134
}
135135

136136
impl CodeSuggestion {

‎src/librustdoc/test.rs

+9-9
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,14 @@ fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
197197
let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts);
198198
// FIXME(#44940): if doctests ever support path remapping, then this filename
199199
// needs to be the result of SourceMap::span_to_unmapped_path
200+
201+
let path = match filename {
202+
FileName::Real(path) => path.clone(),
203+
_ => PathBuf::from(r"doctest.rs"),
204+
};
205+
200206
let input = config::Input::Str {
201-
name: filename.to_owned(),
207+
name: FileName::DocTest(path, line as isize - line_offset as isize),
202208
input: test,
203209
};
204210
let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
@@ -252,9 +258,7 @@ fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
252258
let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
253259

254260
let (libdir, outdir, compile_result) = driver::spawn_thread_pool(sessopts, |sessopts| {
255-
let source_map = Lrc::new(SourceMap::new_doctest(
256-
sessopts.file_path_mapping(), filename.clone(), line as isize - line_offset as isize
257-
));
261+
let source_map = Lrc::new(SourceMap::new(sessopts.file_path_mapping()));
258262
let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
259263
Some(source_map.clone()),
260264
false,
@@ -401,7 +405,7 @@ pub fn make_test(s: &str,
401405
use errors::emitter::EmitterWriter;
402406
use errors::Handler;
403407

404-
let filename = FileName::Anon;
408+
let filename = FileName::anon_source_code(s);
405409
let source = crates + &everything_else;
406410

407411
// any errors in parsing should also appear when the doctest is compiled for real, so just
@@ -411,8 +415,6 @@ pub fn make_test(s: &str,
411415
let handler = Handler::with_emitter(false, false, box emitter);
412416
let sess = ParseSess::with_span_handler(handler, cm);
413417

414-
debug!("about to parse: \n{}", source);
415-
416418
let mut found_main = false;
417419
let mut found_extern_crate = cratename.is_none();
418420

@@ -487,8 +489,6 @@ pub fn make_test(s: &str,
487489
prog.push_str("\n}");
488490
}
489491

490-
info!("final test program: {}", prog);
491-
492492
(prog, line_offset)
493493
}
494494

‎src/libsyntax/ext/source_util.rs

+1
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ fn res_rel_file(cx: &mut ExtCtxt, sp: syntax_pos::Span, arg: String) -> PathBuf
204204
let callsite = sp.source_callsite();
205205
let mut path = match cx.source_map().span_to_unmapped_path(callsite) {
206206
FileName::Real(path) => path,
207+
FileName::DocTest(path, _) => path,
207208
other => panic!("cannot resolve relative path in non-file source `{}`", other),
208209
};
209210
path.pop();

‎src/libsyntax/parse/lexer/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1898,7 +1898,7 @@ mod tests {
18981898
sess: &'a ParseSess,
18991899
teststr: String)
19001900
-> StringReader<'a> {
1901-
let sf = sm.new_source_file(PathBuf::from("zebra.rs").into(), teststr);
1901+
let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
19021902
StringReader::new(sess, sf, None)
19031903
}
19041904

‎src/libsyntax/parse/mod.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -977,23 +977,25 @@ mod tests {
977977
with_globals(|| {
978978
let sess = ParseSess::new(FilePathMapping::empty());
979979

980-
let name = FileName::Custom("source".to_string());
980+
let name_1 = FileName::Custom("crlf_source_1".to_string());
981981
let source = "/// doc comment\r\nfn foo() {}".to_string();
982-
let item = parse_item_from_source_str(name.clone(), source, &sess)
982+
let item = parse_item_from_source_str(name_1, source, &sess)
983983
.unwrap().unwrap();
984984
let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
985985
assert_eq!(doc, "/// doc comment");
986986

987+
let name_2 = FileName::Custom("crlf_source_2".to_string());
987988
let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
988-
let item = parse_item_from_source_str(name.clone(), source, &sess)
989+
let item = parse_item_from_source_str(name_2, source, &sess)
989990
.unwrap().unwrap();
990991
let docs = item.attrs.iter().filter(|a| a.path == "doc")
991992
.map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
992993
let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
993994
assert_eq!(&docs[..], b);
994995

996+
let name_3 = FileName::Custom("clrf_source_3".to_string());
995997
let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string();
996-
let item = parse_item_from_source_str(name, source, &sess).unwrap().unwrap();
998+
let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
997999
let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
9981000
assert_eq!(doc, "/** doc comment\n * with CRLF */");
9991001
});

‎src/libsyntax/source_map.rs

+13-29
Original file line numberDiff line numberDiff line change
@@ -144,9 +144,6 @@ pub struct SourceMap {
144144
// This is used to apply the file path remapping as specified via
145145
// --remap-path-prefix to all SourceFiles allocated within this SourceMap.
146146
path_mapping: FilePathMapping,
147-
/// In case we are in a doctest, replace all file names with the PathBuf,
148-
/// and add the given offsets to the line info
149-
doctest_offset: Option<(FileName, isize)>,
150147
}
151148

152149
impl SourceMap {
@@ -155,27 +152,16 @@ impl SourceMap {
155152
files: Default::default(),
156153
file_loader: Box::new(RealFileLoader),
157154
path_mapping,
158-
doctest_offset: None,
159155
}
160156
}
161157

162-
pub fn new_doctest(path_mapping: FilePathMapping,
163-
file: FileName, line: isize) -> SourceMap {
164-
SourceMap {
165-
doctest_offset: Some((file, line)),
166-
..SourceMap::new(path_mapping)
167-
}
168-
169-
}
170-
171158
pub fn with_file_loader(file_loader: Box<dyn FileLoader + Sync + Send>,
172159
path_mapping: FilePathMapping)
173160
-> SourceMap {
174161
SourceMap {
175162
files: Default::default(),
176163
file_loader: file_loader,
177164
path_mapping,
178-
doctest_offset: None,
179165
}
180166
}
181167

@@ -189,11 +175,7 @@ impl SourceMap {
189175

190176
pub fn load_file(&self, path: &Path) -> io::Result<Lrc<SourceFile>> {
191177
let src = self.file_loader.read_file(path)?;
192-
let filename = if let Some((ref name, _)) = self.doctest_offset {
193-
name.clone()
194-
} else {
195-
path.to_owned().into()
196-
};
178+
let filename = path.to_owned().into();
197179
Ok(self.new_source_file(filename, src))
198180
}
199181

@@ -328,15 +310,17 @@ impl SourceMap {
328310
}
329311

330312
// If there is a doctest_offset, apply it to the line
331-
pub fn doctest_offset_line(&self, mut orig: usize) -> usize {
332-
if let Some((_, line)) = self.doctest_offset {
333-
if line >= 0 {
334-
orig = orig + line as usize;
335-
} else {
336-
orig = orig - (-line) as usize;
337-
}
313+
pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
314+
return match file {
315+
FileName::DocTest(_, offset) => {
316+
return if *offset >= 0 {
317+
orig + *offset as usize
318+
} else {
319+
orig - (-(*offset)) as usize
320+
}
321+
},
322+
_ => orig
338323
}
339-
orig
340324
}
341325

342326
/// Lookup source information about a BytePos
@@ -1001,8 +985,8 @@ impl SourceMapper for SourceMap {
1001985
}
1002986
)
1003987
}
1004-
fn doctest_offset_line(&self, line: usize) -> usize {
1005-
self.doctest_offset_line(line)
988+
fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize {
989+
self.doctest_offset_line(file, line)
1006990
}
1007991
}
1008992

‎src/libsyntax_ext/proc_macro_server.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,7 @@ impl server::TokenStream for Rustc<'_> {
402402
}
403403
fn from_str(&mut self, src: &str) -> Self::TokenStream {
404404
parse::parse_stream_from_source_str(
405-
FileName::ProcMacroSourceCode,
405+
FileName::proc_macro_source_code(src.clone()),
406406
src.to_string(),
407407
self.sess,
408408
Some(self.call_site),

‎src/libsyntax_pos/lib.rs

+10-2
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ pub enum FileName {
103103
CliCrateAttr(u64),
104104
/// Custom sources for explicit parser calls from plugins and drivers
105105
Custom(String),
106+
DocTest(PathBuf, isize),
106107
}
107108

108109
impl std::fmt::Display for FileName {
@@ -119,6 +120,7 @@ impl std::fmt::Display for FileName {
119120
CfgSpec(_) => write!(fmt, "<cfgspec>"),
120121
CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
121122
Custom(ref s) => write!(fmt, "<{}>", s),
123+
DocTest(ref path, _) => write!(fmt, "{}", path.display()),
122124
}
123125
}
124126
}
@@ -142,7 +144,8 @@ impl FileName {
142144
CfgSpec(_) |
143145
CliCrateAttr(_) |
144146
Custom(_) |
145-
QuoteExpansion(_) => false,
147+
QuoteExpansion(_) |
148+
DocTest(_, _) => false,
146149
}
147150
}
148151

@@ -156,7 +159,8 @@ impl FileName {
156159
CfgSpec(_) |
157160
CliCrateAttr(_) |
158161
Custom(_) |
159-
QuoteExpansion(_) => false,
162+
QuoteExpansion(_) |
163+
DocTest(_, _) => false,
160164
Macros(_) => true,
161165
}
162166
}
@@ -196,6 +200,10 @@ impl FileName {
196200
src.hash(&mut hasher);
197201
FileName::CliCrateAttr(hasher.finish())
198202
}
203+
204+
pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{
205+
FileName::DocTest(path, line)
206+
}
199207
}
200208

201209
/// Spans represent a region of code, used for error reporting. Positions in spans

‎src/test/run-make-fulldeps/issue-19371/foo.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ fn compile(code: String, output: PathBuf, sysroot: PathBuf) {
7272
driver::spawn_thread_pool(opts, |opts| {
7373
let (sess, cstore, codegen_backend) = basic_sess(opts);
7474
let control = CompileController::basic();
75-
let input = Input::Str { name: FileName::Anon, input: code };
75+
let name = FileName::anon_source_code(&code);
76+
let input = Input::Str { name, input: code };
7677
let _ = compile_input(
7778
codegen_backend,
7879
&sess,

‎src/test/rustdoc-ui/failed-doctest-output.stdout

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ error[E0425]: cannot find value `no` in this scope
1212
3 | no
1313
| ^^ not found in this scope
1414

15-
thread '$DIR/failed-doctest-output.rs - OtherStruct (line 27)' panicked at 'couldn't compile the test', src/librustdoc/test.rs:323:13
15+
thread '$DIR/failed-doctest-output.rs - OtherStruct (line 27)' panicked at 'couldn't compile the test', src/librustdoc/test.rs:327:13
1616
note: Run with `RUST_BACKTRACE=1` for a backtrace.
1717

1818
---- $DIR/failed-doctest-output.rs - SomeStruct (line 21) stdout ----
@@ -21,7 +21,7 @@ thread '$DIR/failed-doctest-output.rs - SomeStruct (line 21)' panicked at 'test
2121
thread 'main' panicked at 'oh no', $DIR/failed-doctest-output.rs:3:1
2222
note: Run with `RUST_BACKTRACE=1` for a backtrace.
2323

24-
', src/librustdoc/test.rs:358:17
24+
', src/librustdoc/test.rs:362:17
2525

2626

2727
failures:

0 commit comments

Comments
 (0)
Please sign in to comment.