]> git.lizzy.rs Git - rust.git/commitdiff
adds DocTest filename variant, refactors doctest_offset out of source_map, fixes...
authorMatthew Russo <matthew@edapp.com>
Tue, 4 Dec 2018 20:18:03 +0000 (15:18 -0500)
committerMatthew Russo <matthew@edapp.com>
Wed, 5 Dec 2018 00:52:42 +0000 (19:52 -0500)
12 files changed:
src/librustc/ich/impls_syntax.rs
src/librustc_errors/emitter.rs
src/librustc_errors/lib.rs
src/librustdoc/test.rs
src/libsyntax/ext/source_util.rs
src/libsyntax/parse/lexer/mod.rs
src/libsyntax/parse/mod.rs
src/libsyntax/source_map.rs
src/libsyntax_ext/proc_macro_server.rs
src/libsyntax_pos/lib.rs
src/test/run-make-fulldeps/issue-19371/foo.rs
src/test/rustdoc-ui/failed-doctest-output.stdout

index dbf0147928a4e9d36dfa642c1c9cc3ff10b676b1..439c6e42e1a3f105120f2193c914ab7d92cd5a31 100644 (file)
@@ -423,7 +423,8 @@ fn hash_token<'a, 'gcx, W: StableHasherResult>(
     ProcMacroSourceCode(s),
     CliCrateAttr(s),
     CfgSpec(s),
-    Custom(s)
+    Custom(s),
+    DocTest(pb, line),
 });
 
 impl<'a> HashStable<StableHashingContext<'a>> for SourceFile {
index 7e69e98071d4b1fa29ad1453d8f9733f8e1e1424..ab2ab25c91aa541321bf4e23d0c33dfe25efd746 100644 (file)
@@ -1044,7 +1044,7 @@ fn emit_message_default(&mut self,
                     buffer.append(buffer_msg_line_offset,
                                   &format!("{}:{}:{}",
                                            loc.file.name,
-                                           sm.doctest_offset_line(loc.line),
+                                           sm.doctest_offset_line(&loc.file.name, loc.line),
                                            loc.col.0 + 1),
                                   Style::LineAndColumn);
                     for _ in 0..max_line_num_len {
@@ -1054,7 +1054,7 @@ fn emit_message_default(&mut self,
                     buffer.prepend(0,
                                    &format!("{}:{}:{}: ",
                                             loc.file.name,
-                                            sm.doctest_offset_line(loc.line),
+                                            sm.doctest_offset_line(&loc.file.name, loc.line),
                                             loc.col.0 + 1),
                                    Style::LineAndColumn);
                 }
@@ -1075,7 +1075,8 @@ fn emit_message_default(&mut self,
                     };
                     format!("{}:{}{}",
                             annotated_file.file.name,
-                            sm.doctest_offset_line(first_line.line_index),
+                            sm.doctest_offset_line(
+                                &annotated_file.file.name, first_line.line_index),
                             col)
                 } else {
                     annotated_file.file.name.to_string()
index 0fb77a7a3ab526a59a5708fd78b51b05b353f40d..b6528cbe2c810cd91b8d496941252ce1f7e5afc4 100644 (file)
@@ -130,7 +130,7 @@ pub trait SourceMapper {
     fn merge_spans(&self, sp_lhs: Span, sp_rhs: Span) -> Option<Span>;
     fn call_span_if_macro(&self, sp: Span) -> Span;
     fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> bool;
-    fn doctest_offset_line(&self, line: usize) -> usize;
+    fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize;
 }
 
 impl CodeSuggestion {
index d9bab91fd0c7892b8b79e70333f7a16b84035e90..74583196818b84e4e7ddf80c6712948bc0f58070 100644 (file)
@@ -197,8 +197,14 @@ fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
     let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts);
     // FIXME(#44940): if doctests ever support path remapping, then this filename
     // needs to be the result of SourceMap::span_to_unmapped_path
+
+    let path = match filename {
+        FileName::Real(path) => path.clone(),
+        _ => PathBuf::from(r"doctest.rs"),
+    };
+
     let input = config::Input::Str {
-        name: filename.to_owned(),
+        name: FileName::DocTest(path, line as isize - line_offset as isize),
         input: test,
     };
     let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
@@ -252,9 +258,7 @@ fn drop(&mut self) {
     let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
 
     let (libdir, outdir, compile_result) = driver::spawn_thread_pool(sessopts, |sessopts| {
-        let source_map = Lrc::new(SourceMap::new_doctest(
-            sessopts.file_path_mapping(), filename.clone(), line as isize - line_offset as isize
-        ));
+        let source_map = Lrc::new(SourceMap::new(sessopts.file_path_mapping()));
         let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
                                                         Some(source_map.clone()),
                                                         false,
@@ -401,7 +405,7 @@ pub fn make_test(s: &str,
         use errors::emitter::EmitterWriter;
         use errors::Handler;
 
-        let filename = FileName::Anon;
+        let filename = FileName::anon_source_code(s);
         let source = crates + &everything_else;
 
         // 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,
         let handler = Handler::with_emitter(false, false, box emitter);
         let sess = ParseSess::with_span_handler(handler, cm);
 
-        debug!("about to parse: \n{}", source);
-
         let mut found_main = false;
         let mut found_extern_crate = cratename.is_none();
 
@@ -487,8 +489,6 @@ pub fn make_test(s: &str,
         prog.push_str("\n}");
     }
 
-    info!("final test program: {}", prog);
-
     (prog, line_offset)
 }
 
index 654be85862f08bd1cb4f5d3ac81ca1219eb678bc..75e25083d03be70288128dabeece8ca6f5c26cda 100644 (file)
@@ -204,6 +204,7 @@ fn res_rel_file(cx: &mut ExtCtxt, sp: syntax_pos::Span, arg: String) -> PathBuf
         let callsite = sp.source_callsite();
         let mut path = match cx.source_map().span_to_unmapped_path(callsite) {
             FileName::Real(path) => path,
+            FileName::DocTest(path, _) => path,
             other => panic!("cannot resolve relative path in non-file source `{}`", other),
         };
         path.pop();
index c90c62c13f969bc13f94abf070fe536af2cfb77a..5c3e11c8c19af9bea443b45df201324c12756853 100644 (file)
@@ -1898,7 +1898,7 @@ fn setup<'a>(sm: &SourceMap,
                  sess: &'a ParseSess,
                  teststr: String)
                  -> StringReader<'a> {
-        let sf = sm.new_source_file(PathBuf::from("zebra.rs").into(), teststr);
+        let sf = sm.new_source_file(PathBuf::from(teststr.clone()).into(), teststr);
         StringReader::new(sess, sf, None)
     }
 
index ac972f20f94326f5f52c863011a42ddf35265a08..a229ccfa2656df284d91b795cc91b9fa661cb46d 100644 (file)
@@ -977,23 +977,25 @@ fn wb() -> c_int { O_WRONLY as c_int }
         with_globals(|| {
             let sess = ParseSess::new(FilePathMapping::empty());
 
-            let name = FileName::Custom("source".to_string());
+            let name_1 = FileName::Custom("crlf_source_1".to_string());
             let source = "/// doc comment\r\nfn foo() {}".to_string();
-            let item = parse_item_from_source_str(name.clone(), source, &sess)
+            let item = parse_item_from_source_str(name_1, source, &sess)
                 .unwrap().unwrap();
             let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
             assert_eq!(doc, "/// doc comment");
 
+            let name_2 = FileName::Custom("crlf_source_2".to_string());
             let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string();
-            let item = parse_item_from_source_str(name.clone(), source, &sess)
+            let item = parse_item_from_source_str(name_2, source, &sess)
                 .unwrap().unwrap();
             let docs = item.attrs.iter().filter(|a| a.path == "doc")
                         .map(|a| a.value_str().unwrap().to_string()).collect::<Vec<_>>();
             let b: &[_] = &["/// doc comment".to_string(), "/// line 2".to_string()];
             assert_eq!(&docs[..], b);
 
+            let name_3 = FileName::Custom("clrf_source_3".to_string());
             let source = "/** doc comment\r\n *  with CRLF */\r\nfn foo() {}".to_string();
-            let item = parse_item_from_source_str(name, source, &sess).unwrap().unwrap();
+            let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap();
             let doc = first_attr_value_str_by_name(&item.attrs, "doc").unwrap();
             assert_eq!(doc, "/** doc comment\n *  with CRLF */");
         });
index e22d4f8f1332504529191d05424654574bbfad9d..ee60d2dd6156f8accbef46c954d8df71f8cc661f 100644 (file)
@@ -144,9 +144,6 @@ pub struct SourceMap {
     // This is used to apply the file path remapping as specified via
     // --remap-path-prefix to all SourceFiles allocated within this SourceMap.
     path_mapping: FilePathMapping,
-    /// In case we are in a doctest, replace all file names with the PathBuf,
-    /// and add the given offsets to the line info
-    doctest_offset: Option<(FileName, isize)>,
 }
 
 impl SourceMap {
@@ -155,19 +152,9 @@ pub fn new(path_mapping: FilePathMapping) -> SourceMap {
             files: Default::default(),
             file_loader: Box::new(RealFileLoader),
             path_mapping,
-            doctest_offset: None,
         }
     }
 
-    pub fn new_doctest(path_mapping: FilePathMapping,
-                       file: FileName, line: isize) -> SourceMap {
-        SourceMap {
-            doctest_offset: Some((file, line)),
-            ..SourceMap::new(path_mapping)
-        }
-
-    }
-
     pub fn with_file_loader(file_loader: Box<dyn FileLoader + Sync + Send>,
                             path_mapping: FilePathMapping)
                             -> SourceMap {
@@ -175,7 +162,6 @@ pub fn with_file_loader(file_loader: Box<dyn FileLoader + Sync + Send>,
             files: Default::default(),
             file_loader: file_loader,
             path_mapping,
-            doctest_offset: None,
         }
     }
 
@@ -189,11 +175,7 @@ pub fn file_exists(&self, path: &Path) -> bool {
 
     pub fn load_file(&self, path: &Path) -> io::Result<Lrc<SourceFile>> {
         let src = self.file_loader.read_file(path)?;
-        let filename = if let Some((ref name, _)) = self.doctest_offset {
-            name.clone()
-        } else {
-            path.to_owned().into()
-        };
+        let filename = path.to_owned().into();
         Ok(self.new_source_file(filename, src))
     }
 
@@ -328,15 +310,17 @@ pub fn mk_substr_filename(&self, sp: Span) -> String {
     }
 
     // If there is a doctest_offset, apply it to the line
-    pub fn doctest_offset_line(&self, mut orig: usize) -> usize {
-        if let Some((_, line)) = self.doctest_offset {
-            if line >= 0 {
-                orig = orig + line as usize;
-            } else {
-                orig = orig - (-line) as usize;
-            }
+    pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
+        return match file {
+            FileName::DocTest(_, offset) => {
+                return if *offset >= 0 {
+                    orig + *offset as usize
+                } else {
+                    orig - (-(*offset)) as usize
+                }
+            },
+            _ => orig
         }
-        orig
     }
 
     /// Lookup source information about a BytePos
@@ -1001,8 +985,8 @@ fn ensure_source_file_source_present(&self, source_file: Lrc<SourceFile>) -> boo
             }
         )
     }
-    fn doctest_offset_line(&self, line: usize) -> usize {
-        self.doctest_offset_line(line)
+    fn doctest_offset_line(&self, file: &FileName, line: usize) -> usize {
+        self.doctest_offset_line(file, line)
     }
 }
 
index 4babc2e612fd8680323dc79ad47ca8791119ae71..6c7da589a425710dc42d9e344cf73707eaf6d08d 100644 (file)
@@ -402,7 +402,7 @@ fn is_empty(&mut self, stream: &Self::TokenStream) -> bool {
     }
     fn from_str(&mut self, src: &str) -> Self::TokenStream {
         parse::parse_stream_from_source_str(
-            FileName::ProcMacroSourceCode,
+            FileName::proc_macro_source_code(src.clone()),
             src.to_string(),
             self.sess,
             Some(self.call_site),
index ff3c1cf9f47758339ac3126ac89033121ad29fa3..4d42b85ea75488d393c6452983064082b9162a55 100644 (file)
@@ -103,6 +103,7 @@ pub enum FileName {
     CliCrateAttr(u64),
     /// Custom sources for explicit parser calls from plugins and drivers
     Custom(String),
+    DocTest(PathBuf, isize),
 }
 
 impl std::fmt::Display for FileName {
@@ -119,6 +120,7 @@ fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
             CfgSpec(_) => write!(fmt, "<cfgspec>"),
             CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
             Custom(ref s) => write!(fmt, "<{}>", s),
+            DocTest(ref path, _) => write!(fmt, "{}", path.display()),
         }
     }
 }
@@ -142,7 +144,8 @@ pub fn is_real(&self) -> bool {
             CfgSpec(_) |
             CliCrateAttr(_) |
             Custom(_) |
-            QuoteExpansion(_) => false,
+            QuoteExpansion(_) |
+            DocTest(_, _) => false,
         }
     }
 
@@ -156,7 +159,8 @@ pub fn is_macros(&self) -> bool {
             CfgSpec(_) |
             CliCrateAttr(_) |
             Custom(_) |
-            QuoteExpansion(_) => false,
+            QuoteExpansion(_) |
+            DocTest(_, _) => false,
             Macros(_) => true,
         }
     }
@@ -196,6 +200,10 @@ pub fn cli_crate_attr_source_code(src: &str) -> FileName {
         src.hash(&mut hasher);
         FileName::CliCrateAttr(hasher.finish())
     }
+
+    pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName{
+        FileName::DocTest(path, line)
+    }
 }
 
 /// Spans represent a region of code, used for error reporting. Positions in spans
index 4dfecb33c144d003b4dfeccd63ad240813d894f8..c342e1c48359e98923664b36a2bd1f5bf533dc03 100644 (file)
@@ -72,7 +72,8 @@ fn compile(code: String, output: PathBuf, sysroot: PathBuf) {
         driver::spawn_thread_pool(opts, |opts| {
             let (sess, cstore, codegen_backend) = basic_sess(opts);
             let control = CompileController::basic();
-            let input = Input::Str { name: FileName::Anon, input: code };
+            let name = FileName::anon_source_code(&code);
+            let input = Input::Str { name, input: code };
             let _ = compile_input(
                 codegen_backend,
                 &sess,
index cab7bda6c672153313c07ef41289ba6aec287a16..52e0cdca9509fda01882a29ab7b559e4da693205 100644 (file)
@@ -12,7 +12,7 @@ error[E0425]: cannot find value `no` in this scope
 3 | no
   | ^^ not found in this scope
 
-thread '$DIR/failed-doctest-output.rs - OtherStruct (line 27)' panicked at 'couldn't compile the test', src/librustdoc/test.rs:323:13
+thread '$DIR/failed-doctest-output.rs - OtherStruct (line 27)' panicked at 'couldn't compile the test', src/librustdoc/test.rs:327:13
 note: Run with `RUST_BACKTRACE=1` for a backtrace.
 
 ---- $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
 thread 'main' panicked at 'oh no', $DIR/failed-doctest-output.rs:3:1
 note: Run with `RUST_BACKTRACE=1` for a backtrace.
 
-', src/librustdoc/test.rs:358:17
+', src/librustdoc/test.rs:362:17
 
 
 failures: