]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
Rollup merge of #58906 - Nemo157:generator-state-debug-info, r=Zoxc
[rust.git] / src / librustdoc / test.rs
1 use errors::{self, FatalError};
2 use errors::emitter::ColorConfig;
3 use rustc_data_structures::sync::Lrc;
4 use rustc_lint;
5 use rustc_driver::{self, driver, Compilation};
6 use rustc_driver::driver::phase_2_configure_and_expand;
7 use rustc_metadata::cstore::CStore;
8 use rustc_interface::util;
9 use rustc::hir;
10 use rustc::hir::intravisit;
11 use rustc::session::{self, CompileIncomplete, config};
12 use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions};
13 use rustc::session::search_paths::SearchPath;
14 use syntax::ast;
15 use syntax::source_map::SourceMap;
16 use syntax::edition::Edition;
17 use syntax::feature_gate::UnstableFeatures;
18 use syntax::with_globals;
19 use syntax_pos::{BytePos, DUMMY_SP, Pos, Span, FileName};
20 use tempfile::Builder as TempFileBuilder;
21 use testing;
22
23 use std::env;
24 use std::io::prelude::*;
25 use std::io;
26 use std::path::PathBuf;
27 use std::panic::{self, AssertUnwindSafe};
28 use std::process::Command;
29 use std::str;
30 use std::sync::{Arc, Mutex};
31
32 use crate::clean::Attributes;
33 use crate::config::Options;
34 use crate::html::markdown::{self, ErrorCodes, LangString};
35
36 #[derive(Clone, Default)]
37 pub struct TestOptions {
38     /// Whether to disable the default `extern crate my_crate;` when creating doctests.
39     pub no_crate_inject: bool,
40     /// Whether to emit compilation warnings when compiling doctests. Setting this will suppress
41     /// the default `#![allow(unused)]`.
42     pub display_warnings: bool,
43     /// Additional crate-level attributes to add to doctests.
44     pub attrs: Vec<String>,
45 }
46
47 pub fn run(mut options: Options) -> isize {
48     let input = config::Input::File(options.input.clone());
49
50     let sessopts = config::Options {
51         maybe_sysroot: options.maybe_sysroot.clone().or_else(
52             || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
53         search_paths: options.libs.clone(),
54         crate_types: vec![config::CrateType::Dylib],
55         cg: options.codegen_options.clone(),
56         externs: options.externs.clone(),
57         unstable_features: UnstableFeatures::from_environment(),
58         lint_cap: Some(::rustc::lint::Level::Allow),
59         actually_rustdoc: true,
60         debugging_opts: config::DebuggingOptions {
61             ..config::basic_debugging_options()
62         },
63         edition: options.edition,
64         ..config::Options::default()
65     };
66     driver::spawn_thread_pool(sessopts, |sessopts| {
67         let source_map = Lrc::new(SourceMap::new(sessopts.file_path_mapping()));
68         let handler =
69             errors::Handler::with_tty_emitter(ColorConfig::Auto,
70                                             true, false,
71                                             Some(source_map.clone()));
72
73         let mut sess = session::build_session_(
74             sessopts, Some(options.input), handler, source_map.clone(), Default::default(),
75         );
76         let codegen_backend = util::get_codegen_backend(&sess);
77         let cstore = CStore::new(codegen_backend.metadata_loader());
78         rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
79
80         let mut cfg = config::build_configuration(&sess,
81                                                   config::parse_cfgspecs(options.cfgs.clone()));
82         util::add_configuration(&mut cfg, &sess, &*codegen_backend);
83         sess.parse_sess.config = cfg;
84
85         let krate =
86             match driver::phase_1_parse_input(&driver::CompileController::basic(), &sess, &input) {
87                 Ok(krate) => krate,
88                 Err(mut e) => {
89                     e.emit();
90                     FatalError.raise();
91                 }
92             };
93         let driver::ExpansionResult { defs, mut hir_forest, .. } = {
94             phase_2_configure_and_expand(
95                 &sess,
96                 &cstore,
97                 krate,
98                 None,
99                 "rustdoc-test",
100                 None,
101                 |_| Ok(()),
102             ).expect("phase_2_configure_and_expand aborted in rustdoc!")
103         };
104
105         let crate_name = options.crate_name.unwrap_or_else(|| {
106             ::rustc_codegen_utils::link::find_crate_name(None, &hir_forest.krate().attrs, &input)
107         });
108         let mut opts = scrape_test_config(hir_forest.krate());
109         opts.display_warnings |= options.display_warnings;
110         let mut collector = Collector::new(
111             crate_name,
112             options.cfgs,
113             options.libs,
114             options.codegen_options,
115             options.externs,
116             false,
117             opts,
118             options.maybe_sysroot,
119             Some(source_map),
120             None,
121             options.linker,
122             options.edition,
123             options.persist_doctests,
124         );
125
126         {
127             let map = hir::map::map_crate(&sess, &cstore, &mut hir_forest, &defs);
128             let krate = map.krate();
129             let mut hir_collector = HirCollector {
130                 sess: &sess,
131                 collector: &mut collector,
132                 map: &map,
133                 codes: ErrorCodes::from(sess.opts.unstable_features.is_nightly_build()),
134             };
135             hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
136                 intravisit::walk_crate(this, krate);
137             });
138         }
139
140         options.test_args.insert(0, "rustdoctest".to_string());
141
142         testing::test_main(&options.test_args,
143                         collector.tests.into_iter().collect(),
144                         testing::Options::new().display_output(options.display_warnings));
145         0
146     })
147 }
148
149 // Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
150 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
151     use syntax::print::pprust;
152
153     let mut opts = TestOptions {
154         no_crate_inject: false,
155         display_warnings: false,
156         attrs: Vec::new(),
157     };
158
159     let test_attrs: Vec<_> = krate.attrs.iter()
160         .filter(|a| a.check_name("doc"))
161         .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
162         .filter(|a| a.check_name("test"))
163         .collect();
164     let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
165
166     for attr in attrs {
167         if attr.check_name("no_crate_inject") {
168             opts.no_crate_inject = true;
169         }
170         if attr.check_name("attr") {
171             if let Some(l) = attr.meta_item_list() {
172                 for item in l {
173                     opts.attrs.push(pprust::meta_list_item_to_string(item));
174                 }
175             }
176         }
177     }
178
179     opts
180 }
181
182 fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
183             cfgs: Vec<String>, libs: Vec<SearchPath>,
184             cg: CodegenOptions, externs: Externs,
185             should_panic: bool, no_run: bool, as_test_harness: bool,
186             compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
187             maybe_sysroot: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition,
188             persist_doctests: Option<PathBuf>) {
189     // The test harness wants its own `main` and top-level functions, so
190     // never wrap the test in `fn main() { ... }`.
191     let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts);
192     // FIXME(#44940): if doctests ever support path remapping, then this filename
193     // needs to be the result of `SourceMap::span_to_unmapped_path`.
194     let path = match filename {
195         FileName::Real(path) => path.clone(),
196         _ => PathBuf::from(r"doctest.rs"),
197     };
198
199     let input = config::Input::Str {
200         name: FileName::DocTest(path, line as isize - line_offset as isize),
201         input: test,
202     };
203     let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
204
205     let sessopts = config::Options {
206         maybe_sysroot: maybe_sysroot.or_else(
207             || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
208         search_paths: libs,
209         crate_types: vec![config::CrateType::Executable],
210         output_types: outputs,
211         externs,
212         cg: config::CodegenOptions {
213             linker,
214             ..cg
215         },
216         test: as_test_harness,
217         unstable_features: UnstableFeatures::from_environment(),
218         debugging_opts: config::DebuggingOptions {
219             ..config::basic_debugging_options()
220         },
221         edition,
222         ..config::Options::default()
223     };
224
225     // Shuffle around a few input and output handles here. We're going to pass
226     // an explicit handle into rustc to collect output messages, but we also
227     // want to catch the error message that rustc prints when it fails.
228     //
229     // We take our thread-local stderr (likely set by the test runner) and replace
230     // it with a sink that is also passed to rustc itself. When this function
231     // returns the output of the sink is copied onto the output of our own thread.
232     //
233     // The basic idea is to not use a default Handler for rustc, and then also
234     // not print things by default to the actual stderr.
235     struct Sink(Arc<Mutex<Vec<u8>>>);
236     impl Write for Sink {
237         fn write(&mut self, data: &[u8]) -> io::Result<usize> {
238             Write::write(&mut *self.0.lock().unwrap(), data)
239         }
240         fn flush(&mut self) -> io::Result<()> { Ok(()) }
241     }
242     struct Bomb(Arc<Mutex<Vec<u8>>>, Box<dyn Write+Send>);
243     impl Drop for Bomb {
244         fn drop(&mut self) {
245             let _ = self.1.write_all(&self.0.lock().unwrap());
246         }
247     }
248     let data = Arc::new(Mutex::new(Vec::new()));
249
250     let old = io::set_panic(Some(box Sink(data.clone())));
251     let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
252
253     enum DirState {
254         Temp(tempfile::TempDir),
255         Perm(PathBuf),
256     }
257
258     impl DirState {
259         fn path(&self) -> &std::path::Path {
260             match self {
261                 DirState::Temp(t) => t.path(),
262                 DirState::Perm(p) => p.as_path(),
263             }
264         }
265     }
266
267     let (outdir, compile_result) = driver::spawn_thread_pool(sessopts, |sessopts| {
268         let source_map = Lrc::new(SourceMap::new(sessopts.file_path_mapping()));
269         let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
270                                                         Some(source_map.clone()),
271                                                         false,
272                                                         false);
273
274         // Compile the code
275         let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
276
277         let mut sess = session::build_session_(
278             sessopts, None, diagnostic_handler, source_map, Default::default(),
279         );
280         let codegen_backend = util::get_codegen_backend(&sess);
281         let cstore = CStore::new(codegen_backend.metadata_loader());
282         rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
283
284         let outdir = Mutex::new(
285             if let Some(mut path) = persist_doctests {
286                 path.push(format!("{}_{}",
287                     filename
288                         .to_string()
289                         .rsplit('/')
290                         .next()
291                         .unwrap()
292                         .replace(".", "_"),
293                         line)
294                 );
295                 std::fs::create_dir_all(&path)
296                     .expect("Couldn't create directory for doctest executables");
297
298                 DirState::Perm(path)
299             } else {
300                 DirState::Temp(TempFileBuilder::new()
301                                 .prefix("rustdoctest")
302                                 .tempdir()
303                                 .expect("rustdoc needs a tempdir"))
304             }
305         );
306         let mut control = driver::CompileController::basic();
307
308         let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
309         util::add_configuration(&mut cfg, &sess, &*codegen_backend);
310         sess.parse_sess.config = cfg;
311
312         let out = Some(outdir.lock().unwrap().path().join("rust_out"));
313
314         if no_run {
315             control.after_analysis.stop = Compilation::Stop;
316         }
317
318         let res = panic::catch_unwind(AssertUnwindSafe(|| {
319             driver::compile_input(
320                 codegen_backend,
321                 &sess,
322                 &cstore,
323                 &None,
324                 &input,
325                 &None,
326                 &out,
327                 None,
328                 &control
329             )
330         }));
331
332         let compile_result = match res {
333             Ok(Ok(())) | Ok(Err(CompileIncomplete::Stopped)) => Ok(()),
334             Err(_) | Ok(Err(CompileIncomplete::Errored(_))) => Err(())
335         };
336
337         (outdir, compile_result)
338     });
339
340     match (compile_result, compile_fail) {
341         (Ok(()), true) => {
342             panic!("test compiled while it wasn't supposed to")
343         }
344         (Ok(()), false) => {}
345         (Err(()), true) => {
346             if error_codes.len() > 0 {
347                 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
348                 error_codes.retain(|err| !out.contains(err));
349             }
350         }
351         (Err(()), false) => {
352             panic!("couldn't compile the test")
353         }
354     }
355
356     if error_codes.len() > 0 {
357         panic!("Some expected error codes were not found: {:?}", error_codes);
358     }
359
360     if no_run { return }
361
362     // Run the code!
363     let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
364     match cmd.output() {
365         Err(e) => panic!("couldn't run the test: {}{}", e,
366                         if e.kind() == io::ErrorKind::PermissionDenied {
367                             " - maybe your tempdir is mounted with noexec?"
368                         } else { "" }),
369         Ok(out) => {
370             if should_panic && out.status.success() {
371                 panic!("test executable succeeded when it should have failed");
372             } else if !should_panic && !out.status.success() {
373                 panic!("test executable failed:\n{}\n{}\n",
374                        str::from_utf8(&out.stdout).unwrap_or(""),
375                        str::from_utf8(&out.stderr).unwrap_or(""));
376             }
377         }
378     }
379 }
380
381 /// Makes the test file. Also returns the number of lines before the code begins
382 pub fn make_test(s: &str,
383                  cratename: Option<&str>,
384                  dont_insert_main: bool,
385                  opts: &TestOptions)
386                  -> (String, usize) {
387     let (crate_attrs, everything_else, crates) = partition_source(s);
388     let everything_else = everything_else.trim();
389     let mut line_offset = 0;
390     let mut prog = String::new();
391
392     if opts.attrs.is_empty() && !opts.display_warnings {
393         // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
394         // lints that are commonly triggered in doctests. The crate-level test attributes are
395         // commonly used to make tests fail in case they trigger warnings, so having this there in
396         // that case may cause some tests to pass when they shouldn't have.
397         prog.push_str("#![allow(unused)]\n");
398         line_offset += 1;
399     }
400
401     // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
402     for attr in &opts.attrs {
403         prog.push_str(&format!("#![{}]\n", attr));
404         line_offset += 1;
405     }
406
407     // Now push any outer attributes from the example, assuming they
408     // are intended to be crate attributes.
409     prog.push_str(&crate_attrs);
410     prog.push_str(&crates);
411
412     // Uses libsyntax to parse the doctest and find if there's a main fn and the extern
413     // crate already is included.
414     let (already_has_main, already_has_extern_crate, found_macro) = crate::syntax::with_globals(|| {
415         use crate::syntax::{ast, parse::{self, ParseSess}, source_map::FilePathMapping};
416         use crate::syntax_pos::FileName;
417         use errors::emitter::EmitterWriter;
418         use errors::Handler;
419
420         let filename = FileName::anon_source_code(s);
421         let source = crates + &everything_else;
422
423         // Any errors in parsing should also appear when the doctest is compiled for real, so just
424         // send all the errors that libsyntax emits directly into a `Sink` instead of stderr.
425         let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
426         let emitter = EmitterWriter::new(box io::sink(), None, false, false);
427         let handler = Handler::with_emitter(false, false, box emitter);
428         let sess = ParseSess::with_span_handler(handler, cm);
429
430         let mut found_main = false;
431         let mut found_extern_crate = cratename.is_none();
432         let mut found_macro = false;
433
434         let mut parser = match parse::maybe_new_parser_from_source_str(&sess, filename, source) {
435             Ok(p) => p,
436             Err(errs) => {
437                 for mut err in errs {
438                     err.cancel();
439                 }
440
441                 return (found_main, found_extern_crate, found_macro);
442             }
443         };
444
445         loop {
446             match parser.parse_item() {
447                 Ok(Some(item)) => {
448                     if !found_main {
449                         if let ast::ItemKind::Fn(..) = item.node {
450                             if item.ident.as_str() == "main" {
451                                 found_main = true;
452                             }
453                         }
454                     }
455
456                     if !found_extern_crate {
457                         if let ast::ItemKind::ExternCrate(original) = item.node {
458                             // This code will never be reached if `cratename` is none because
459                             // `found_extern_crate` is initialized to `true` if it is none.
460                             let cratename = cratename.unwrap();
461
462                             match original {
463                                 Some(name) => found_extern_crate = name.as_str() == cratename,
464                                 None => found_extern_crate = item.ident.as_str() == cratename,
465                             }
466                         }
467                     }
468
469                     if !found_macro {
470                         if let ast::ItemKind::Mac(..) = item.node {
471                             found_macro = true;
472                         }
473                     }
474
475                     if found_main && found_extern_crate {
476                         break;
477                     }
478                 }
479                 Ok(None) => break,
480                 Err(mut e) => {
481                     e.cancel();
482                     break;
483                 }
484             }
485         }
486
487         (found_main, found_extern_crate, found_macro)
488     });
489
490     // If a doctest's `fn main` is being masked by a wrapper macro, the parsing loop above won't
491     // see it. In that case, run the old text-based scan to see if they at least have a main
492     // function written inside a macro invocation. See
493     // https://github.com/rust-lang/rust/issues/56898
494     let already_has_main = if found_macro && !already_has_main {
495         s.lines()
496             .map(|line| {
497                 let comment = line.find("//");
498                 if let Some(comment_begins) = comment {
499                     &line[0..comment_begins]
500                 } else {
501                     line
502                 }
503             })
504             .any(|code| code.contains("fn main"))
505     } else {
506         already_has_main
507     };
508
509     // Don't inject `extern crate std` because it's already injected by the
510     // compiler.
511     if !already_has_extern_crate && !opts.no_crate_inject && cratename != Some("std") {
512         if let Some(cratename) = cratename {
513             // Make sure its actually used if not included.
514             if s.contains(cratename) {
515                 prog.push_str(&format!("extern crate {};\n", cratename));
516                 line_offset += 1;
517             }
518         }
519     }
520
521     // FIXME: This code cannot yet handle no_std test cases yet
522     if dont_insert_main || already_has_main || prog.contains("![no_std]") {
523         prog.push_str(everything_else);
524     } else {
525         let returns_result = everything_else.trim_end().ends_with("(())");
526         let (main_pre, main_post) = if returns_result {
527             ("fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {",
528              "}\n_inner().unwrap() }")
529         } else {
530             ("fn main() {\n", "\n}")
531         };
532         prog.extend([main_pre, everything_else, main_post].iter().cloned());
533         line_offset += 1;
534     }
535
536     debug!("final doctest:\n{}", prog);
537
538     (prog, line_offset)
539 }
540
541 // FIXME(aburka): use a real parser to deal with multiline attributes
542 fn partition_source(s: &str) -> (String, String, String) {
543     #[derive(Copy, Clone, PartialEq)]
544     enum PartitionState {
545         Attrs,
546         Crates,
547         Other,
548     }
549     let mut state = PartitionState::Attrs;
550     let mut before = String::new();
551     let mut crates = String::new();
552     let mut after = String::new();
553
554     for line in s.lines() {
555         let trimline = line.trim();
556
557         // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
558         // shunted into "everything else"
559         match state {
560             PartitionState::Attrs => {
561                 state = if trimline.starts_with("#![") ||
562                     trimline.chars().all(|c| c.is_whitespace()) ||
563                     (trimline.starts_with("//") && !trimline.starts_with("///"))
564                 {
565                     PartitionState::Attrs
566                 } else if trimline.starts_with("extern crate") ||
567                     trimline.starts_with("#[macro_use] extern crate")
568                 {
569                     PartitionState::Crates
570                 } else {
571                     PartitionState::Other
572                 };
573             }
574             PartitionState::Crates => {
575                 state = if trimline.starts_with("extern crate") ||
576                     trimline.starts_with("#[macro_use] extern crate") ||
577                     trimline.chars().all(|c| c.is_whitespace()) ||
578                     (trimline.starts_with("//") && !trimline.starts_with("///"))
579                 {
580                     PartitionState::Crates
581                 } else {
582                     PartitionState::Other
583                 };
584             }
585             PartitionState::Other => {}
586         }
587
588         match state {
589             PartitionState::Attrs => {
590                 before.push_str(line);
591                 before.push_str("\n");
592             }
593             PartitionState::Crates => {
594                 crates.push_str(line);
595                 crates.push_str("\n");
596             }
597             PartitionState::Other => {
598                 after.push_str(line);
599                 after.push_str("\n");
600             }
601         }
602     }
603
604     debug!("before:\n{}", before);
605     debug!("crates:\n{}", crates);
606     debug!("after:\n{}", after);
607
608     (before, after, crates)
609 }
610
611 pub trait Tester {
612     fn add_test(&mut self, test: String, config: LangString, line: usize);
613     fn get_line(&self) -> usize {
614         0
615     }
616     fn register_header(&mut self, _name: &str, _level: u32) {}
617 }
618
619 pub struct Collector {
620     pub tests: Vec<testing::TestDescAndFn>,
621
622     // The name of the test displayed to the user, separated by `::`.
623     //
624     // In tests from Rust source, this is the path to the item
625     // e.g., `["std", "vec", "Vec", "push"]`.
626     //
627     // In tests from a markdown file, this is the titles of all headers (h1~h6)
628     // of the sections that contain the code block, e.g., if the markdown file is
629     // written as:
630     //
631     // ``````markdown
632     // # Title
633     //
634     // ## Subtitle
635     //
636     // ```rust
637     // assert!(true);
638     // ```
639     // ``````
640     //
641     // the `names` vector of that test will be `["Title", "Subtitle"]`.
642     names: Vec<String>,
643
644     cfgs: Vec<String>,
645     libs: Vec<SearchPath>,
646     cg: CodegenOptions,
647     externs: Externs,
648     use_headers: bool,
649     cratename: String,
650     opts: TestOptions,
651     maybe_sysroot: Option<PathBuf>,
652     position: Span,
653     source_map: Option<Lrc<SourceMap>>,
654     filename: Option<PathBuf>,
655     linker: Option<PathBuf>,
656     edition: Edition,
657     persist_doctests: Option<PathBuf>,
658 }
659
660 impl Collector {
661     pub fn new(cratename: String, cfgs: Vec<String>, libs: Vec<SearchPath>, cg: CodegenOptions,
662                externs: Externs, use_headers: bool, opts: TestOptions,
663                maybe_sysroot: Option<PathBuf>, source_map: Option<Lrc<SourceMap>>,
664                filename: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition,
665                persist_doctests: Option<PathBuf>) -> Collector {
666         Collector {
667             tests: Vec::new(),
668             names: Vec::new(),
669             cfgs,
670             libs,
671             cg,
672             externs,
673             use_headers,
674             cratename,
675             opts,
676             maybe_sysroot,
677             position: DUMMY_SP,
678             source_map,
679             filename,
680             linker,
681             edition,
682             persist_doctests,
683         }
684     }
685
686     fn generate_name(&self, line: usize, filename: &FileName) -> String {
687         format!("{} - {} (line {})", filename, self.names.join("::"), line)
688     }
689
690     pub fn set_position(&mut self, position: Span) {
691         self.position = position;
692     }
693
694     fn get_filename(&self) -> FileName {
695         if let Some(ref source_map) = self.source_map {
696             let filename = source_map.span_to_filename(self.position);
697             if let FileName::Real(ref filename) = filename {
698                 if let Ok(cur_dir) = env::current_dir() {
699                     if let Ok(path) = filename.strip_prefix(&cur_dir) {
700                         return path.to_owned().into();
701                     }
702                 }
703             }
704             filename
705         } else if let Some(ref filename) = self.filename {
706             filename.clone().into()
707         } else {
708             FileName::Custom("input".to_owned())
709         }
710     }
711 }
712
713 impl Tester for Collector {
714     fn add_test(&mut self, test: String, config: LangString, line: usize) {
715         let filename = self.get_filename();
716         let name = self.generate_name(line, &filename);
717         let cfgs = self.cfgs.clone();
718         let libs = self.libs.clone();
719         let cg = self.cg.clone();
720         let externs = self.externs.clone();
721         let cratename = self.cratename.to_string();
722         let opts = self.opts.clone();
723         let maybe_sysroot = self.maybe_sysroot.clone();
724         let linker = self.linker.clone();
725         let edition = config.edition.unwrap_or(self.edition);
726         let persist_doctests = self.persist_doctests.clone();
727
728         debug!("Creating test {}: {}", name, test);
729         self.tests.push(testing::TestDescAndFn {
730             desc: testing::TestDesc {
731                 name: testing::DynTestName(name.clone()),
732                 ignore: config.ignore,
733                 // compiler failures are test failures
734                 should_panic: testing::ShouldPanic::No,
735                 allow_fail: config.allow_fail,
736             },
737             testfn: testing::DynTestFn(box move || {
738                 let panic = io::set_panic(None);
739                 let print = io::set_print(None);
740                 match {
741                     rustc_driver::in_named_rustc_thread(name, move || with_globals(move || {
742                         io::set_panic(panic);
743                         io::set_print(print);
744                         run_test(&test,
745                                  &cratename,
746                                  &filename,
747                                  line,
748                                  cfgs,
749                                  libs,
750                                  cg,
751                                  externs,
752                                  config.should_panic,
753                                  config.no_run,
754                                  config.test_harness,
755                                  config.compile_fail,
756                                  config.error_codes,
757                                  &opts,
758                                  maybe_sysroot,
759                                  linker,
760                                  edition,
761                                  persist_doctests)
762                     }))
763                 } {
764                     Ok(()) => (),
765                     Err(err) => panic::resume_unwind(err),
766                 }
767             }),
768         });
769     }
770
771     fn get_line(&self) -> usize {
772         if let Some(ref source_map) = self.source_map {
773             let line = self.position.lo().to_usize();
774             let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
775             if line > 0 { line - 1 } else { line }
776         } else {
777             0
778         }
779     }
780
781     fn register_header(&mut self, name: &str, level: u32) {
782         if self.use_headers {
783             // We use these headings as test names, so it's good if
784             // they're valid identifiers.
785             let name = name.chars().enumerate().map(|(i, c)| {
786                     if (i == 0 && c.is_xid_start()) ||
787                         (i != 0 && c.is_xid_continue()) {
788                         c
789                     } else {
790                         '_'
791                     }
792                 }).collect::<String>();
793
794             // Here we try to efficiently assemble the header titles into the
795             // test name in the form of `h1::h2::h3::h4::h5::h6`.
796             //
797             // Suppose that originally `self.names` contains `[h1, h2, h3]`...
798             let level = level as usize;
799             if level <= self.names.len() {
800                 // ... Consider `level == 2`. All headers in the lower levels
801                 // are irrelevant in this new level. So we should reset
802                 // `self.names` to contain headers until <h2>, and replace that
803                 // slot with the new name: `[h1, name]`.
804                 self.names.truncate(level);
805                 self.names[level - 1] = name;
806             } else {
807                 // ... On the other hand, consider `level == 5`. This means we
808                 // need to extend `self.names` to contain five headers. We fill
809                 // in the missing level (<h4>) with `_`. Thus `self.names` will
810                 // become `[h1, h2, h3, "_", name]`.
811                 if level - 1 > self.names.len() {
812                     self.names.resize(level - 1, "_".to_owned());
813                 }
814                 self.names.push(name);
815             }
816         }
817     }
818 }
819
820 struct HirCollector<'a, 'hir: 'a> {
821     sess: &'a session::Session,
822     collector: &'a mut Collector,
823     map: &'a hir::map::Map<'hir>,
824     codes: ErrorCodes,
825 }
826
827 impl<'a, 'hir> HirCollector<'a, 'hir> {
828     fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
829                                             name: String,
830                                             attrs: &[ast::Attribute],
831                                             nested: F) {
832         let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
833         if let Some(ref cfg) = attrs.cfg {
834             if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
835                 return;
836             }
837         }
838
839         let has_name = !name.is_empty();
840         if has_name {
841             self.collector.names.push(name);
842         }
843
844         attrs.collapse_doc_comments();
845         attrs.unindent_doc_comments();
846         // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
847         // anything else, this will combine them for us.
848         if let Some(doc) = attrs.collapsed_doc_value() {
849             self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP));
850             let res = markdown::find_testable_code(&doc, self.collector, self.codes);
851             if let Err(err) = res {
852                 self.sess.diagnostic().span_warn(attrs.span.unwrap_or(DUMMY_SP),
853                     &err.to_string());
854             }
855         }
856
857         nested(self);
858
859         if has_name {
860             self.collector.names.pop();
861         }
862     }
863 }
864
865 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
866     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
867         intravisit::NestedVisitorMap::All(&self.map)
868     }
869
870     fn visit_item(&mut self, item: &'hir hir::Item) {
871         let name = if let hir::ItemKind::Impl(.., ref ty, _) = item.node {
872             self.map.hir_to_pretty_string(ty.hir_id)
873         } else {
874             item.ident.to_string()
875         };
876
877         self.visit_testable(name, &item.attrs, |this| {
878             intravisit::walk_item(this, item);
879         });
880     }
881
882     fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
883         self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
884             intravisit::walk_trait_item(this, item);
885         });
886     }
887
888     fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
889         self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
890             intravisit::walk_impl_item(this, item);
891         });
892     }
893
894     fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
895         self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
896             intravisit::walk_foreign_item(this, item);
897         });
898     }
899
900     fn visit_variant(&mut self,
901                      v: &'hir hir::Variant,
902                      g: &'hir hir::Generics,
903                      item_id: hir::HirId) {
904         self.visit_testable(v.node.ident.to_string(), &v.node.attrs, |this| {
905             intravisit::walk_variant(this, v, g, item_id);
906         });
907     }
908
909     fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
910         self.visit_testable(f.ident.to_string(), &f.attrs, |this| {
911             intravisit::walk_struct_field(this, f);
912         });
913     }
914
915     fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
916         self.visit_testable(macro_def.name.to_string(), &macro_def.attrs, |_| ());
917     }
918 }
919
920 #[cfg(test)]
921 mod tests {
922     use super::{TestOptions, make_test};
923
924     #[test]
925     fn make_test_basic() {
926         //basic use: wraps with `fn main`, adds `#![allow(unused)]`
927         let opts = TestOptions::default();
928         let input =
929 "assert_eq!(2+2, 4);";
930         let expected =
931 "#![allow(unused)]
932 fn main() {
933 assert_eq!(2+2, 4);
934 }".to_string();
935         let output = make_test(input, None, false, &opts);
936         assert_eq!(output, (expected, 2));
937     }
938
939     #[test]
940     fn make_test_crate_name_no_use() {
941         // If you give a crate name but *don't* use it within the test, it won't bother inserting
942         // the `extern crate` statement.
943         let opts = TestOptions::default();
944         let input =
945 "assert_eq!(2+2, 4);";
946         let expected =
947 "#![allow(unused)]
948 fn main() {
949 assert_eq!(2+2, 4);
950 }".to_string();
951         let output = make_test(input, Some("asdf"), false, &opts);
952         assert_eq!(output, (expected, 2));
953     }
954
955     #[test]
956     fn make_test_crate_name() {
957         // If you give a crate name and use it within the test, it will insert an `extern crate`
958         // statement before `fn main`.
959         let opts = TestOptions::default();
960         let input =
961 "use asdf::qwop;
962 assert_eq!(2+2, 4);";
963         let expected =
964 "#![allow(unused)]
965 extern crate asdf;
966 fn main() {
967 use asdf::qwop;
968 assert_eq!(2+2, 4);
969 }".to_string();
970         let output = make_test(input, Some("asdf"), false, &opts);
971         assert_eq!(output, (expected, 3));
972     }
973
974     #[test]
975     fn make_test_no_crate_inject() {
976         // Even if you do use the crate within the test, setting `opts.no_crate_inject` will skip
977         // adding it anyway.
978         let opts = TestOptions {
979             no_crate_inject: true,
980             display_warnings: false,
981             attrs: vec![],
982         };
983         let input =
984 "use asdf::qwop;
985 assert_eq!(2+2, 4);";
986         let expected =
987 "#![allow(unused)]
988 fn main() {
989 use asdf::qwop;
990 assert_eq!(2+2, 4);
991 }".to_string();
992         let output = make_test(input, Some("asdf"), false, &opts);
993         assert_eq!(output, (expected, 2));
994     }
995
996     #[test]
997     fn make_test_ignore_std() {
998         // Even if you include a crate name, and use it in the doctest, we still won't include an
999         // `extern crate` statement if the crate is "std" -- that's included already by the
1000         // compiler!
1001         let opts = TestOptions::default();
1002         let input =
1003 "use std::*;
1004 assert_eq!(2+2, 4);";
1005         let expected =
1006 "#![allow(unused)]
1007 fn main() {
1008 use std::*;
1009 assert_eq!(2+2, 4);
1010 }".to_string();
1011         let output = make_test(input, Some("std"), false, &opts);
1012         assert_eq!(output, (expected, 2));
1013     }
1014
1015     #[test]
1016     fn make_test_manual_extern_crate() {
1017         // When you manually include an `extern crate` statement in your doctest, `make_test`
1018         // assumes you've included one for your own crate too.
1019         let opts = TestOptions::default();
1020         let input =
1021 "extern crate asdf;
1022 use asdf::qwop;
1023 assert_eq!(2+2, 4);";
1024         let expected =
1025 "#![allow(unused)]
1026 extern crate asdf;
1027 fn main() {
1028 use asdf::qwop;
1029 assert_eq!(2+2, 4);
1030 }".to_string();
1031         let output = make_test(input, Some("asdf"), false, &opts);
1032         assert_eq!(output, (expected, 2));
1033     }
1034
1035     #[test]
1036     fn make_test_manual_extern_crate_with_macro_use() {
1037         let opts = TestOptions::default();
1038         let input =
1039 "#[macro_use] extern crate asdf;
1040 use asdf::qwop;
1041 assert_eq!(2+2, 4);";
1042         let expected =
1043 "#![allow(unused)]
1044 #[macro_use] extern crate asdf;
1045 fn main() {
1046 use asdf::qwop;
1047 assert_eq!(2+2, 4);
1048 }".to_string();
1049         let output = make_test(input, Some("asdf"), false, &opts);
1050         assert_eq!(output, (expected, 2));
1051     }
1052
1053     #[test]
1054     fn make_test_opts_attrs() {
1055         // If you supplied some doctest attributes with `#![doc(test(attr(...)))]`, it will use
1056         // those instead of the stock `#![allow(unused)]`.
1057         let mut opts = TestOptions::default();
1058         opts.attrs.push("feature(sick_rad)".to_string());
1059         let input =
1060 "use asdf::qwop;
1061 assert_eq!(2+2, 4);";
1062         let expected =
1063 "#![feature(sick_rad)]
1064 extern crate asdf;
1065 fn main() {
1066 use asdf::qwop;
1067 assert_eq!(2+2, 4);
1068 }".to_string();
1069         let output = make_test(input, Some("asdf"), false, &opts);
1070         assert_eq!(output, (expected, 3));
1071
1072         // Adding more will also bump the returned line offset.
1073         opts.attrs.push("feature(hella_dope)".to_string());
1074         let expected =
1075 "#![feature(sick_rad)]
1076 #![feature(hella_dope)]
1077 extern crate asdf;
1078 fn main() {
1079 use asdf::qwop;
1080 assert_eq!(2+2, 4);
1081 }".to_string();
1082         let output = make_test(input, Some("asdf"), false, &opts);
1083         assert_eq!(output, (expected, 4));
1084     }
1085
1086     #[test]
1087     fn make_test_crate_attrs() {
1088         // Including inner attributes in your doctest will apply them to the whole "crate", pasting
1089         // them outside the generated main function.
1090         let opts = TestOptions::default();
1091         let input =
1092 "#![feature(sick_rad)]
1093 assert_eq!(2+2, 4);";
1094         let expected =
1095 "#![allow(unused)]
1096 #![feature(sick_rad)]
1097 fn main() {
1098 assert_eq!(2+2, 4);
1099 }".to_string();
1100         let output = make_test(input, None, false, &opts);
1101         assert_eq!(output, (expected, 2));
1102     }
1103
1104     #[test]
1105     fn make_test_with_main() {
1106         // Including your own `fn main` wrapper lets the test use it verbatim.
1107         let opts = TestOptions::default();
1108         let input =
1109 "fn main() {
1110     assert_eq!(2+2, 4);
1111 }";
1112         let expected =
1113 "#![allow(unused)]
1114 fn main() {
1115     assert_eq!(2+2, 4);
1116 }".to_string();
1117         let output = make_test(input, None, false, &opts);
1118         assert_eq!(output, (expected, 1));
1119     }
1120
1121     #[test]
1122     fn make_test_fake_main() {
1123         // ... but putting it in a comment will still provide a wrapper.
1124         let opts = TestOptions::default();
1125         let input =
1126 "//Ceci n'est pas une `fn main`
1127 assert_eq!(2+2, 4);";
1128         let expected =
1129 "#![allow(unused)]
1130 //Ceci n'est pas une `fn main`
1131 fn main() {
1132 assert_eq!(2+2, 4);
1133 }".to_string();
1134         let output = make_test(input, None, false, &opts);
1135         assert_eq!(output, (expected, 2));
1136     }
1137
1138     #[test]
1139     fn make_test_dont_insert_main() {
1140         // Even with that, if you set `dont_insert_main`, it won't create the `fn main` wrapper.
1141         let opts = TestOptions::default();
1142         let input =
1143 "//Ceci n'est pas une `fn main`
1144 assert_eq!(2+2, 4);";
1145         let expected =
1146 "#![allow(unused)]
1147 //Ceci n'est pas une `fn main`
1148 assert_eq!(2+2, 4);".to_string();
1149         let output = make_test(input, None, true, &opts);
1150         assert_eq!(output, (expected, 1));
1151     }
1152
1153     #[test]
1154     fn make_test_display_warnings() {
1155         // If the user is asking to display doctest warnings, suppress the default `allow(unused)`.
1156         let mut opts = TestOptions::default();
1157         opts.display_warnings = true;
1158         let input =
1159 "assert_eq!(2+2, 4);";
1160         let expected =
1161 "fn main() {
1162 assert_eq!(2+2, 4);
1163 }".to_string();
1164         let output = make_test(input, None, false, &opts);
1165         assert_eq!(output, (expected, 1));
1166     }
1167
1168     #[test]
1169     fn make_test_issues_21299_33731() {
1170         let opts = TestOptions::default();
1171
1172         let input =
1173 "// fn main
1174 assert_eq!(2+2, 4);";
1175
1176         let expected =
1177 "#![allow(unused)]
1178 // fn main
1179 fn main() {
1180 assert_eq!(2+2, 4);
1181 }".to_string();
1182
1183         let output = make_test(input, None, false, &opts);
1184         assert_eq!(output, (expected, 2));
1185
1186         let input =
1187 "extern crate hella_qwop;
1188 assert_eq!(asdf::foo, 4);";
1189
1190         let expected =
1191 "#![allow(unused)]
1192 extern crate hella_qwop;
1193 extern crate asdf;
1194 fn main() {
1195 assert_eq!(asdf::foo, 4);
1196 }".to_string();
1197
1198         let output = make_test(input, Some("asdf"), false, &opts);
1199         assert_eq!(output, (expected, 3));
1200     }
1201
1202     #[test]
1203     fn make_test_main_in_macro() {
1204         let opts = TestOptions::default();
1205         let input =
1206 "#[macro_use] extern crate my_crate;
1207 test_wrapper! {
1208     fn main() {}
1209 }";
1210         let expected =
1211 "#![allow(unused)]
1212 #[macro_use] extern crate my_crate;
1213 test_wrapper! {
1214     fn main() {}
1215 }".to_string();
1216
1217         let output = make_test(input, Some("my_crate"), false, &opts);
1218         assert_eq!(output, (expected, 1));
1219     }
1220 }