]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
Rollup merge of #61720 - alexcrichton:libstd-cfg-if-dep, r=sfackler
[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 returns_option = everything_else.trim_end().ends_with("Some(())");
534         let (main_pre, main_post) = if returns_result {
535             (if returns_option {
536                 "fn main() { fn _inner() -> Option<()> {"
537             } else {
538                 "fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {"
539             },
540              "}\n_inner().unwrap() }")
541         } else {
542             ("fn main() {\n", "\n}")
543         };
544         prog.extend([main_pre, everything_else, main_post].iter().cloned());
545         line_offset += 1;
546     }
547
548     debug!("final doctest:\n{}", prog);
549
550     (prog, line_offset)
551 }
552
553 // FIXME(aburka): use a real parser to deal with multiline attributes
554 fn partition_source(s: &str) -> (String, String, String) {
555     #[derive(Copy, Clone, PartialEq)]
556     enum PartitionState {
557         Attrs,
558         Crates,
559         Other,
560     }
561     let mut state = PartitionState::Attrs;
562     let mut before = String::new();
563     let mut crates = String::new();
564     let mut after = String::new();
565
566     for line in s.lines() {
567         let trimline = line.trim();
568
569         // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
570         // shunted into "everything else"
571         match state {
572             PartitionState::Attrs => {
573                 state = if trimline.starts_with("#![") ||
574                     trimline.chars().all(|c| c.is_whitespace()) ||
575                     (trimline.starts_with("//") && !trimline.starts_with("///"))
576                 {
577                     PartitionState::Attrs
578                 } else if trimline.starts_with("extern crate") ||
579                     trimline.starts_with("#[macro_use] extern crate")
580                 {
581                     PartitionState::Crates
582                 } else {
583                     PartitionState::Other
584                 };
585             }
586             PartitionState::Crates => {
587                 state = if trimline.starts_with("extern crate") ||
588                     trimline.starts_with("#[macro_use] extern crate") ||
589                     trimline.chars().all(|c| c.is_whitespace()) ||
590                     (trimline.starts_with("//") && !trimline.starts_with("///"))
591                 {
592                     PartitionState::Crates
593                 } else {
594                     PartitionState::Other
595                 };
596             }
597             PartitionState::Other => {}
598         }
599
600         match state {
601             PartitionState::Attrs => {
602                 before.push_str(line);
603                 before.push_str("\n");
604             }
605             PartitionState::Crates => {
606                 crates.push_str(line);
607                 crates.push_str("\n");
608             }
609             PartitionState::Other => {
610                 after.push_str(line);
611                 after.push_str("\n");
612             }
613         }
614     }
615
616     debug!("before:\n{}", before);
617     debug!("crates:\n{}", crates);
618     debug!("after:\n{}", after);
619
620     (before, after, crates)
621 }
622
623 pub trait Tester {
624     fn add_test(&mut self, test: String, config: LangString, line: usize);
625     fn get_line(&self) -> usize {
626         0
627     }
628     fn register_header(&mut self, _name: &str, _level: u32) {}
629 }
630
631 pub struct Collector {
632     pub tests: Vec<testing::TestDescAndFn>,
633
634     // The name of the test displayed to the user, separated by `::`.
635     //
636     // In tests from Rust source, this is the path to the item
637     // e.g., `["std", "vec", "Vec", "push"]`.
638     //
639     // In tests from a markdown file, this is the titles of all headers (h1~h6)
640     // of the sections that contain the code block, e.g., if the markdown file is
641     // written as:
642     //
643     // ``````markdown
644     // # Title
645     //
646     // ## Subtitle
647     //
648     // ```rust
649     // assert!(true);
650     // ```
651     // ``````
652     //
653     // the `names` vector of that test will be `["Title", "Subtitle"]`.
654     names: Vec<String>,
655
656     cfgs: Vec<String>,
657     libs: Vec<SearchPath>,
658     cg: CodegenOptions,
659     externs: Externs,
660     use_headers: bool,
661     cratename: String,
662     opts: TestOptions,
663     maybe_sysroot: Option<PathBuf>,
664     position: Span,
665     source_map: Option<Lrc<SourceMap>>,
666     filename: Option<PathBuf>,
667     linker: Option<PathBuf>,
668     edition: Edition,
669     persist_doctests: Option<PathBuf>,
670 }
671
672 impl Collector {
673     pub fn new(cratename: String, cfgs: Vec<String>, libs: Vec<SearchPath>, cg: CodegenOptions,
674                externs: Externs, use_headers: bool, opts: TestOptions,
675                maybe_sysroot: Option<PathBuf>, source_map: Option<Lrc<SourceMap>>,
676                filename: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition,
677                persist_doctests: Option<PathBuf>) -> Collector {
678         Collector {
679             tests: Vec::new(),
680             names: Vec::new(),
681             cfgs,
682             libs,
683             cg,
684             externs,
685             use_headers,
686             cratename,
687             opts,
688             maybe_sysroot,
689             position: DUMMY_SP,
690             source_map,
691             filename,
692             linker,
693             edition,
694             persist_doctests,
695         }
696     }
697
698     fn generate_name(&self, line: usize, filename: &FileName) -> String {
699         format!("{} - {} (line {})", filename, self.names.join("::"), line)
700     }
701
702     pub fn set_position(&mut self, position: Span) {
703         self.position = position;
704     }
705
706     fn get_filename(&self) -> FileName {
707         if let Some(ref source_map) = self.source_map {
708             let filename = source_map.span_to_filename(self.position);
709             if let FileName::Real(ref filename) = filename {
710                 if let Ok(cur_dir) = env::current_dir() {
711                     if let Ok(path) = filename.strip_prefix(&cur_dir) {
712                         return path.to_owned().into();
713                     }
714                 }
715             }
716             filename
717         } else if let Some(ref filename) = self.filename {
718             filename.clone().into()
719         } else {
720             FileName::Custom("input".to_owned())
721         }
722     }
723 }
724
725 impl Tester for Collector {
726     fn add_test(&mut self, test: String, config: LangString, line: usize) {
727         let filename = self.get_filename();
728         let name = self.generate_name(line, &filename);
729         let cfgs = self.cfgs.clone();
730         let libs = self.libs.clone();
731         let cg = self.cg.clone();
732         let externs = self.externs.clone();
733         let cratename = self.cratename.to_string();
734         let opts = self.opts.clone();
735         let maybe_sysroot = self.maybe_sysroot.clone();
736         let linker = self.linker.clone();
737         let edition = config.edition.unwrap_or(self.edition);
738         let persist_doctests = self.persist_doctests.clone();
739
740         debug!("Creating test {}: {}", name, test);
741         self.tests.push(testing::TestDescAndFn {
742             desc: testing::TestDesc {
743                 name: testing::DynTestName(name.clone()),
744                 ignore: config.ignore,
745                 // compiler failures are test failures
746                 should_panic: testing::ShouldPanic::No,
747                 allow_fail: config.allow_fail,
748             },
749             testfn: testing::DynTestFn(box move || {
750                 let res = run_test(
751                     &test,
752                     &cratename,
753                     &filename,
754                     line,
755                     cfgs,
756                     libs,
757                     cg,
758                     externs,
759                     config.should_panic,
760                     config.no_run,
761                     config.test_harness,
762                     config.compile_fail,
763                     config.error_codes,
764                     &opts,
765                     maybe_sysroot,
766                     linker,
767                     edition,
768                     persist_doctests
769                 );
770
771                 if let Err(err) = res {
772                     match err {
773                         TestFailure::CompileError => {
774                             eprint!("Couldn't compile the test.");
775                         }
776                         TestFailure::UnexpectedCompilePass => {
777                             eprint!("Test compiled successfully, but it's marked `compile_fail`.");
778                         }
779                         TestFailure::UnexpectedRunPass => {
780                             eprint!("Test executable succeeded, but it's marked `should_panic`.");
781                         }
782                         TestFailure::MissingErrorCodes(codes) => {
783                             eprint!("Some expected error codes were not found: {:?}", codes);
784                         }
785                         TestFailure::ExecutionError(err) => {
786                             eprint!("Couldn't run the test: {}", err);
787                             if err.kind() == io::ErrorKind::PermissionDenied {
788                                 eprint!(" - maybe your tempdir is mounted with noexec?");
789                             }
790                         }
791                         TestFailure::ExecutionFailure(out) => {
792                             let reason = if let Some(code) = out.status.code() {
793                                 format!("exit code {}", code)
794                             } else {
795                                 String::from("terminated by signal")
796                             };
797
798                             eprintln!("Test executable failed ({}).", reason);
799
800                             // FIXME(#12309): An unfortunate side-effect of capturing the test
801                             // executable's output is that the relative ordering between the test's
802                             // stdout and stderr is lost. However, this is better than the
803                             // alternative: if the test executable inherited the parent's I/O
804                             // handles the output wouldn't be captured at all, even on success.
805                             //
806                             // The ordering could be preserved if the test process' stderr was
807                             // redirected to stdout, but that functionality does not exist in the
808                             // standard library, so it may not be portable enough.
809                             let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
810                             let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
811
812                             if !stdout.is_empty() || !stderr.is_empty() {
813                                 eprintln!();
814
815                                 if !stdout.is_empty() {
816                                     eprintln!("stdout:\n{}", stdout);
817                                 }
818
819                                 if !stderr.is_empty() {
820                                     eprintln!("stderr:\n{}", stderr);
821                                 }
822                             }
823                         }
824                     }
825
826                     panic::resume_unwind(box ());
827                 }
828             }),
829         });
830     }
831
832     fn get_line(&self) -> usize {
833         if let Some(ref source_map) = self.source_map {
834             let line = self.position.lo().to_usize();
835             let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
836             if line > 0 { line - 1 } else { line }
837         } else {
838             0
839         }
840     }
841
842     fn register_header(&mut self, name: &str, level: u32) {
843         if self.use_headers {
844             // We use these headings as test names, so it's good if
845             // they're valid identifiers.
846             let name = name.chars().enumerate().map(|(i, c)| {
847                     if (i == 0 && c.is_xid_start()) ||
848                         (i != 0 && c.is_xid_continue()) {
849                         c
850                     } else {
851                         '_'
852                     }
853                 }).collect::<String>();
854
855             // Here we try to efficiently assemble the header titles into the
856             // test name in the form of `h1::h2::h3::h4::h5::h6`.
857             //
858             // Suppose that originally `self.names` contains `[h1, h2, h3]`...
859             let level = level as usize;
860             if level <= self.names.len() {
861                 // ... Consider `level == 2`. All headers in the lower levels
862                 // are irrelevant in this new level. So we should reset
863                 // `self.names` to contain headers until <h2>, and replace that
864                 // slot with the new name: `[h1, name]`.
865                 self.names.truncate(level);
866                 self.names[level - 1] = name;
867             } else {
868                 // ... On the other hand, consider `level == 5`. This means we
869                 // need to extend `self.names` to contain five headers. We fill
870                 // in the missing level (<h4>) with `_`. Thus `self.names` will
871                 // become `[h1, h2, h3, "_", name]`.
872                 if level - 1 > self.names.len() {
873                     self.names.resize(level - 1, "_".to_owned());
874                 }
875                 self.names.push(name);
876             }
877         }
878     }
879 }
880
881 struct HirCollector<'a, 'hir: 'a> {
882     sess: &'a session::Session,
883     collector: &'a mut Collector,
884     map: &'a hir::map::Map<'hir>,
885     codes: ErrorCodes,
886 }
887
888 impl<'a, 'hir> HirCollector<'a, 'hir> {
889     fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
890                                             name: String,
891                                             attrs: &[ast::Attribute],
892                                             nested: F) {
893         let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
894         if let Some(ref cfg) = attrs.cfg {
895             if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
896                 return;
897             }
898         }
899
900         let has_name = !name.is_empty();
901         if has_name {
902             self.collector.names.push(name);
903         }
904
905         attrs.collapse_doc_comments();
906         attrs.unindent_doc_comments();
907         // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
908         // anything else, this will combine them for us.
909         if let Some(doc) = attrs.collapsed_doc_value() {
910             self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP));
911             markdown::find_testable_code(&doc, self.collector, self.codes);
912         }
913
914         nested(self);
915
916         if has_name {
917             self.collector.names.pop();
918         }
919     }
920 }
921
922 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
923     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
924         intravisit::NestedVisitorMap::All(&self.map)
925     }
926
927     fn visit_item(&mut self, item: &'hir hir::Item) {
928         let name = if let hir::ItemKind::Impl(.., ref ty, _) = item.node {
929             self.map.hir_to_pretty_string(ty.hir_id)
930         } else {
931             item.ident.to_string()
932         };
933
934         self.visit_testable(name, &item.attrs, |this| {
935             intravisit::walk_item(this, item);
936         });
937     }
938
939     fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
940         self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
941             intravisit::walk_trait_item(this, item);
942         });
943     }
944
945     fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
946         self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
947             intravisit::walk_impl_item(this, item);
948         });
949     }
950
951     fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
952         self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
953             intravisit::walk_foreign_item(this, item);
954         });
955     }
956
957     fn visit_variant(&mut self,
958                      v: &'hir hir::Variant,
959                      g: &'hir hir::Generics,
960                      item_id: hir::HirId) {
961         self.visit_testable(v.node.ident.to_string(), &v.node.attrs, |this| {
962             intravisit::walk_variant(this, v, g, item_id);
963         });
964     }
965
966     fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
967         self.visit_testable(f.ident.to_string(), &f.attrs, |this| {
968             intravisit::walk_struct_field(this, f);
969         });
970     }
971
972     fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
973         self.visit_testable(macro_def.name.to_string(), &macro_def.attrs, |_| ());
974     }
975 }
976
977 #[cfg(test)]
978 mod tests {
979     use super::{TestOptions, make_test};
980     use syntax::edition::DEFAULT_EDITION;
981
982     #[test]
983     fn make_test_basic() {
984         //basic use: wraps with `fn main`, adds `#![allow(unused)]`
985         let opts = TestOptions::default();
986         let input =
987 "assert_eq!(2+2, 4);";
988         let expected =
989 "#![allow(unused)]
990 fn main() {
991 assert_eq!(2+2, 4);
992 }".to_string();
993         let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
994         assert_eq!(output, (expected, 2));
995     }
996
997     #[test]
998     fn make_test_crate_name_no_use() {
999         // If you give a crate name but *don't* use it within the test, it won't bother inserting
1000         // the `extern crate` statement.
1001         let opts = TestOptions::default();
1002         let input =
1003 "assert_eq!(2+2, 4);";
1004         let expected =
1005 "#![allow(unused)]
1006 fn main() {
1007 assert_eq!(2+2, 4);
1008 }".to_string();
1009         let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1010         assert_eq!(output, (expected, 2));
1011     }
1012
1013     #[test]
1014     fn make_test_crate_name() {
1015         // If you give a crate name and use it within the test, it will insert an `extern crate`
1016         // statement before `fn main`.
1017         let opts = TestOptions::default();
1018         let input =
1019 "use asdf::qwop;
1020 assert_eq!(2+2, 4);";
1021         let expected =
1022 "#![allow(unused)]
1023 extern crate asdf;
1024 fn main() {
1025 use asdf::qwop;
1026 assert_eq!(2+2, 4);
1027 }".to_string();
1028         let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1029         assert_eq!(output, (expected, 3));
1030     }
1031
1032     #[test]
1033     fn make_test_no_crate_inject() {
1034         // Even if you do use the crate within the test, setting `opts.no_crate_inject` will skip
1035         // adding it anyway.
1036         let opts = TestOptions {
1037             no_crate_inject: true,
1038             display_warnings: false,
1039             attrs: vec![],
1040         };
1041         let input =
1042 "use asdf::qwop;
1043 assert_eq!(2+2, 4);";
1044         let expected =
1045 "#![allow(unused)]
1046 fn main() {
1047 use asdf::qwop;
1048 assert_eq!(2+2, 4);
1049 }".to_string();
1050         let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1051         assert_eq!(output, (expected, 2));
1052     }
1053
1054     #[test]
1055     fn make_test_ignore_std() {
1056         // Even if you include a crate name, and use it in the doctest, we still won't include an
1057         // `extern crate` statement if the crate is "std" -- that's included already by the
1058         // compiler!
1059         let opts = TestOptions::default();
1060         let input =
1061 "use std::*;
1062 assert_eq!(2+2, 4);";
1063         let expected =
1064 "#![allow(unused)]
1065 fn main() {
1066 use std::*;
1067 assert_eq!(2+2, 4);
1068 }".to_string();
1069         let output = make_test(input, Some("std"), false, &opts, DEFAULT_EDITION);
1070         assert_eq!(output, (expected, 2));
1071     }
1072
1073     #[test]
1074     fn make_test_manual_extern_crate() {
1075         // When you manually include an `extern crate` statement in your doctest, `make_test`
1076         // assumes you've included one for your own crate too.
1077         let opts = TestOptions::default();
1078         let input =
1079 "extern crate asdf;
1080 use asdf::qwop;
1081 assert_eq!(2+2, 4);";
1082         let expected =
1083 "#![allow(unused)]
1084 extern crate asdf;
1085 fn main() {
1086 use asdf::qwop;
1087 assert_eq!(2+2, 4);
1088 }".to_string();
1089         let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1090         assert_eq!(output, (expected, 2));
1091     }
1092
1093     #[test]
1094     fn make_test_manual_extern_crate_with_macro_use() {
1095         let opts = TestOptions::default();
1096         let input =
1097 "#[macro_use] extern crate asdf;
1098 use asdf::qwop;
1099 assert_eq!(2+2, 4);";
1100         let expected =
1101 "#![allow(unused)]
1102 #[macro_use] extern crate asdf;
1103 fn main() {
1104 use asdf::qwop;
1105 assert_eq!(2+2, 4);
1106 }".to_string();
1107         let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1108         assert_eq!(output, (expected, 2));
1109     }
1110
1111     #[test]
1112     fn make_test_opts_attrs() {
1113         // If you supplied some doctest attributes with `#![doc(test(attr(...)))]`, it will use
1114         // those instead of the stock `#![allow(unused)]`.
1115         let mut opts = TestOptions::default();
1116         opts.attrs.push("feature(sick_rad)".to_string());
1117         let input =
1118 "use asdf::qwop;
1119 assert_eq!(2+2, 4);";
1120         let expected =
1121 "#![feature(sick_rad)]
1122 extern crate asdf;
1123 fn main() {
1124 use asdf::qwop;
1125 assert_eq!(2+2, 4);
1126 }".to_string();
1127         let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1128         assert_eq!(output, (expected, 3));
1129
1130         // Adding more will also bump the returned line offset.
1131         opts.attrs.push("feature(hella_dope)".to_string());
1132         let expected =
1133 "#![feature(sick_rad)]
1134 #![feature(hella_dope)]
1135 extern crate asdf;
1136 fn main() {
1137 use asdf::qwop;
1138 assert_eq!(2+2, 4);
1139 }".to_string();
1140         let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1141         assert_eq!(output, (expected, 4));
1142     }
1143
1144     #[test]
1145     fn make_test_crate_attrs() {
1146         // Including inner attributes in your doctest will apply them to the whole "crate", pasting
1147         // them outside the generated main function.
1148         let opts = TestOptions::default();
1149         let input =
1150 "#![feature(sick_rad)]
1151 assert_eq!(2+2, 4);";
1152         let expected =
1153 "#![allow(unused)]
1154 #![feature(sick_rad)]
1155 fn main() {
1156 assert_eq!(2+2, 4);
1157 }".to_string();
1158         let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1159         assert_eq!(output, (expected, 2));
1160     }
1161
1162     #[test]
1163     fn make_test_with_main() {
1164         // Including your own `fn main` wrapper lets the test use it verbatim.
1165         let opts = TestOptions::default();
1166         let input =
1167 "fn main() {
1168     assert_eq!(2+2, 4);
1169 }";
1170         let expected =
1171 "#![allow(unused)]
1172 fn main() {
1173     assert_eq!(2+2, 4);
1174 }".to_string();
1175         let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1176         assert_eq!(output, (expected, 1));
1177     }
1178
1179     #[test]
1180     fn make_test_fake_main() {
1181         // ... but putting it in a comment will still provide a wrapper.
1182         let opts = TestOptions::default();
1183         let input =
1184 "//Ceci n'est pas une `fn main`
1185 assert_eq!(2+2, 4);";
1186         let expected =
1187 "#![allow(unused)]
1188 //Ceci n'est pas une `fn main`
1189 fn main() {
1190 assert_eq!(2+2, 4);
1191 }".to_string();
1192         let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1193         assert_eq!(output, (expected, 2));
1194     }
1195
1196     #[test]
1197     fn make_test_dont_insert_main() {
1198         // Even with that, if you set `dont_insert_main`, it won't create the `fn main` wrapper.
1199         let opts = TestOptions::default();
1200         let input =
1201 "//Ceci n'est pas une `fn main`
1202 assert_eq!(2+2, 4);";
1203         let expected =
1204 "#![allow(unused)]
1205 //Ceci n'est pas une `fn main`
1206 assert_eq!(2+2, 4);".to_string();
1207         let output = make_test(input, None, true, &opts, DEFAULT_EDITION);
1208         assert_eq!(output, (expected, 1));
1209     }
1210
1211     #[test]
1212     fn make_test_display_warnings() {
1213         // If the user is asking to display doctest warnings, suppress the default `allow(unused)`.
1214         let mut opts = TestOptions::default();
1215         opts.display_warnings = true;
1216         let input =
1217 "assert_eq!(2+2, 4);";
1218         let expected =
1219 "fn main() {
1220 assert_eq!(2+2, 4);
1221 }".to_string();
1222         let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1223         assert_eq!(output, (expected, 1));
1224     }
1225
1226     #[test]
1227     fn make_test_issues_21299_33731() {
1228         let opts = TestOptions::default();
1229
1230         let input =
1231 "// fn main
1232 assert_eq!(2+2, 4);";
1233
1234         let expected =
1235 "#![allow(unused)]
1236 // fn main
1237 fn main() {
1238 assert_eq!(2+2, 4);
1239 }".to_string();
1240
1241         let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1242         assert_eq!(output, (expected, 2));
1243
1244         let input =
1245 "extern crate hella_qwop;
1246 assert_eq!(asdf::foo, 4);";
1247
1248         let expected =
1249 "#![allow(unused)]
1250 extern crate hella_qwop;
1251 extern crate asdf;
1252 fn main() {
1253 assert_eq!(asdf::foo, 4);
1254 }".to_string();
1255
1256         let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1257         assert_eq!(output, (expected, 3));
1258     }
1259
1260     #[test]
1261     fn make_test_main_in_macro() {
1262         let opts = TestOptions::default();
1263         let input =
1264 "#[macro_use] extern crate my_crate;
1265 test_wrapper! {
1266     fn main() {}
1267 }";
1268         let expected =
1269 "#![allow(unused)]
1270 #[macro_use] extern crate my_crate;
1271 test_wrapper! {
1272     fn main() {}
1273 }".to_string();
1274
1275         let output = make_test(input, Some("my_crate"), false, &opts, DEFAULT_EDITION);
1276         assert_eq!(output, (expected, 1));
1277     }
1278 }