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