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