1 use errors::{self, FatalError};
2 use errors::emitter::ColorConfig;
3 use rustc_data_structures::sync::Lrc;
5 use rustc_driver::{self, driver, Compilation};
6 use rustc_driver::driver::phase_2_configure_and_expand;
7 use rustc_metadata::cstore::CStore;
8 use rustc_interface::util;
10 use rustc::hir::intravisit;
11 use rustc::session::{self, CompileIncomplete, config};
12 use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions};
13 use rustc::session::search_paths::SearchPath;
15 use syntax::source_map::SourceMap;
16 use syntax::edition::Edition;
17 use syntax::feature_gate::UnstableFeatures;
18 use syntax::with_globals;
19 use syntax_pos::{BytePos, DUMMY_SP, Pos, Span, FileName};
20 use tempfile::Builder as TempFileBuilder;
24 use std::io::prelude::*;
26 use std::path::PathBuf;
27 use std::panic::{self, AssertUnwindSafe};
28 use std::process::Command;
30 use std::sync::{Arc, Mutex};
32 use crate::clean::Attributes;
33 use crate::config::Options;
34 use crate::html::markdown::{self, ErrorCodes, LangString};
36 #[derive(Clone, Default)]
37 pub struct TestOptions {
38 /// Whether to disable the default `extern crate my_crate;` when creating doctests.
39 pub no_crate_inject: bool,
40 /// Whether to emit compilation warnings when compiling doctests. Setting this will suppress
41 /// the default `#![allow(unused)]`.
42 pub display_warnings: bool,
43 /// Additional crate-level attributes to add to doctests.
44 pub attrs: Vec<String>,
47 pub fn run(mut options: Options) -> isize {
48 let input = config::Input::File(options.input.clone());
50 let sessopts = config::Options {
51 maybe_sysroot: options.maybe_sysroot.clone().or_else(
52 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
53 search_paths: options.libs.clone(),
54 crate_types: vec![config::CrateType::Dylib],
55 cg: options.codegen_options.clone(),
56 externs: options.externs.clone(),
57 unstable_features: UnstableFeatures::from_environment(),
58 lint_cap: Some(::rustc::lint::Level::Allow),
59 actually_rustdoc: true,
60 debugging_opts: config::DebuggingOptions {
61 ..config::basic_debugging_options()
63 edition: options.edition,
64 ..config::Options::default()
66 driver::spawn_thread_pool(sessopts, |sessopts| {
67 let source_map = Lrc::new(SourceMap::new(sessopts.file_path_mapping()));
69 errors::Handler::with_tty_emitter(ColorConfig::Auto,
71 Some(source_map.clone()));
73 let mut sess = session::build_session_(
74 sessopts, Some(options.input), handler, source_map.clone(), Default::default(),
76 let codegen_backend = util::get_codegen_backend(&sess);
77 let cstore = CStore::new(codegen_backend.metadata_loader());
78 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
80 let mut cfg = config::build_configuration(&sess,
81 config::parse_cfgspecs(options.cfgs.clone()));
82 util::add_configuration(&mut cfg, &sess, &*codegen_backend);
83 sess.parse_sess.config = cfg;
86 match driver::phase_1_parse_input(&driver::CompileController::basic(), &sess, &input) {
93 let driver::ExpansionResult { defs, mut hir_forest, .. } = {
94 phase_2_configure_and_expand(
102 ).expect("phase_2_configure_and_expand aborted in rustdoc!")
105 let crate_name = options.crate_name.unwrap_or_else(|| {
106 ::rustc_codegen_utils::link::find_crate_name(None, &hir_forest.krate().attrs, &input)
108 let mut opts = scrape_test_config(hir_forest.krate());
109 opts.display_warnings |= options.display_warnings;
110 let mut collector = Collector::new(
114 options.codegen_options,
118 options.maybe_sysroot,
123 options.persist_doctests,
127 let map = hir::map::map_crate(&sess, &cstore, &mut hir_forest, &defs);
128 let krate = map.krate();
129 let mut hir_collector = HirCollector {
131 collector: &mut collector,
133 codes: ErrorCodes::from(sess.opts.unstable_features.is_nightly_build()),
135 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
136 intravisit::walk_crate(this, krate);
140 options.test_args.insert(0, "rustdoctest".to_string());
142 testing::test_main(&options.test_args,
143 collector.tests.into_iter().collect(),
144 testing::Options::new().display_output(options.display_warnings));
149 // Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
150 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
151 use syntax::print::pprust;
153 let mut opts = TestOptions {
154 no_crate_inject: false,
155 display_warnings: false,
159 let test_attrs: Vec<_> = krate.attrs.iter()
160 .filter(|a| a.check_name("doc"))
161 .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
162 .filter(|a| a.check_name("test"))
164 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
167 if attr.check_name("no_crate_inject") {
168 opts.no_crate_inject = true;
170 if attr.check_name("attr") {
171 if let Some(l) = attr.meta_item_list() {
173 opts.attrs.push(pprust::meta_list_item_to_string(item));
182 fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize,
183 cfgs: Vec<String>, libs: Vec<SearchPath>,
184 cg: CodegenOptions, externs: Externs,
185 should_panic: bool, no_run: bool, as_test_harness: bool,
186 compile_fail: bool, mut error_codes: Vec<String>, opts: &TestOptions,
187 maybe_sysroot: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition,
188 persist_doctests: Option<PathBuf>) {
189 // The test harness wants its own `main` and top-level functions, so
190 // never wrap the test in `fn main() { ... }`.
191 let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts);
192 // FIXME(#44940): if doctests ever support path remapping, then this filename
193 // needs to be the result of `SourceMap::span_to_unmapped_path`.
194 let path = match filename {
195 FileName::Real(path) => path.clone(),
196 _ => PathBuf::from(r"doctest.rs"),
199 let input = config::Input::Str {
200 name: FileName::DocTest(path, line as isize - line_offset as isize),
203 let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
205 let sessopts = config::Options {
206 maybe_sysroot: maybe_sysroot.or_else(
207 || Some(env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_path_buf())),
209 crate_types: vec![config::CrateType::Executable],
210 output_types: outputs,
212 cg: config::CodegenOptions {
216 test: as_test_harness,
217 unstable_features: UnstableFeatures::from_environment(),
218 debugging_opts: config::DebuggingOptions {
219 ..config::basic_debugging_options()
222 ..config::Options::default()
225 // Shuffle around a few input and output handles here. We're going to pass
226 // an explicit handle into rustc to collect output messages, but we also
227 // want to catch the error message that rustc prints when it fails.
229 // We take our thread-local stderr (likely set by the test runner) and replace
230 // it with a sink that is also passed to rustc itself. When this function
231 // returns the output of the sink is copied onto the output of our own thread.
233 // The basic idea is to not use a default Handler for rustc, and then also
234 // not print things by default to the actual stderr.
235 struct Sink(Arc<Mutex<Vec<u8>>>);
236 impl Write for Sink {
237 fn write(&mut self, data: &[u8]) -> io::Result<usize> {
238 Write::write(&mut *self.0.lock().unwrap(), data)
240 fn flush(&mut self) -> io::Result<()> { Ok(()) }
242 struct Bomb(Arc<Mutex<Vec<u8>>>, Box<dyn Write+Send>);
245 let _ = self.1.write_all(&self.0.lock().unwrap());
248 let data = Arc::new(Mutex::new(Vec::new()));
250 let old = io::set_panic(Some(box Sink(data.clone())));
251 let _bomb = Bomb(data.clone(), old.unwrap_or(box io::stdout()));
254 Temp(tempfile::TempDir),
259 fn path(&self) -> &std::path::Path {
261 DirState::Temp(t) => t.path(),
262 DirState::Perm(p) => p.as_path(),
267 let (outdir, compile_result) = driver::spawn_thread_pool(sessopts, |sessopts| {
268 let source_map = Lrc::new(SourceMap::new(sessopts.file_path_mapping()));
269 let emitter = errors::emitter::EmitterWriter::new(box Sink(data.clone()),
270 Some(source_map.clone()),
275 let diagnostic_handler = errors::Handler::with_emitter(true, false, box emitter);
277 let mut sess = session::build_session_(
278 sessopts, None, diagnostic_handler, source_map, Default::default(),
280 let codegen_backend = util::get_codegen_backend(&sess);
281 let cstore = CStore::new(codegen_backend.metadata_loader());
282 rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
284 let outdir = Mutex::new(
285 if let Some(mut path) = persist_doctests {
286 path.push(format!("{}_{}",
295 std::fs::create_dir_all(&path)
296 .expect("Couldn't create directory for doctest executables");
300 DirState::Temp(TempFileBuilder::new()
301 .prefix("rustdoctest")
303 .expect("rustdoc needs a tempdir"))
306 let mut control = driver::CompileController::basic();
308 let mut cfg = config::build_configuration(&sess, config::parse_cfgspecs(cfgs.clone()));
309 util::add_configuration(&mut cfg, &sess, &*codegen_backend);
310 sess.parse_sess.config = cfg;
312 let out = Some(outdir.lock().unwrap().path().join("rust_out"));
315 control.after_analysis.stop = Compilation::Stop;
318 let res = panic::catch_unwind(AssertUnwindSafe(|| {
319 driver::compile_input(
332 let compile_result = match res {
333 Ok(Ok(())) | Ok(Err(CompileIncomplete::Stopped)) => Ok(()),
334 Err(_) | Ok(Err(CompileIncomplete::Errored(_))) => Err(())
337 (outdir, compile_result)
340 match (compile_result, compile_fail) {
342 panic!("test compiled while it wasn't supposed to")
344 (Ok(()), false) => {}
346 if error_codes.len() > 0 {
347 let out = String::from_utf8(data.lock().unwrap().to_vec()).unwrap();
348 error_codes.retain(|err| !out.contains(err));
351 (Err(()), false) => {
352 panic!("couldn't compile the test")
356 if error_codes.len() > 0 {
357 panic!("Some expected error codes were not found: {:?}", error_codes);
363 let mut cmd = Command::new(&outdir.lock().unwrap().path().join("rust_out"));
365 Err(e) => panic!("couldn't run the test: {}{}", e,
366 if e.kind() == io::ErrorKind::PermissionDenied {
367 " - maybe your tempdir is mounted with noexec?"
370 if should_panic && out.status.success() {
371 panic!("test executable succeeded when it should have failed");
372 } else if !should_panic && !out.status.success() {
373 panic!("test executable failed:\n{}\n{}\n",
374 str::from_utf8(&out.stdout).unwrap_or(""),
375 str::from_utf8(&out.stderr).unwrap_or(""));
381 /// Makes the test file. Also returns the number of lines before the code begins
382 pub fn make_test(s: &str,
383 cratename: Option<&str>,
384 dont_insert_main: bool,
387 let (crate_attrs, everything_else, crates) = partition_source(s);
388 let everything_else = everything_else.trim();
389 let mut line_offset = 0;
390 let mut prog = String::new();
392 if opts.attrs.is_empty() && !opts.display_warnings {
393 // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
394 // lints that are commonly triggered in doctests. The crate-level test attributes are
395 // commonly used to make tests fail in case they trigger warnings, so having this there in
396 // that case may cause some tests to pass when they shouldn't have.
397 prog.push_str("#![allow(unused)]\n");
401 // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
402 for attr in &opts.attrs {
403 prog.push_str(&format!("#![{}]\n", attr));
407 // Now push any outer attributes from the example, assuming they
408 // are intended to be crate attributes.
409 prog.push_str(&crate_attrs);
410 prog.push_str(&crates);
412 // Uses libsyntax to parse the doctest and find if there's a main fn and the extern
413 // crate already is included.
414 let (already_has_main, already_has_extern_crate, found_macro) = crate::syntax::with_globals(|| {
415 use crate::syntax::{ast, parse::{self, ParseSess}, source_map::FilePathMapping};
416 use crate::syntax_pos::FileName;
417 use errors::emitter::EmitterWriter;
420 let filename = FileName::anon_source_code(s);
421 let source = crates + &everything_else;
423 // Any errors in parsing should also appear when the doctest is compiled for real, so just
424 // send all the errors that libsyntax emits directly into a `Sink` instead of stderr.
425 let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
426 let emitter = EmitterWriter::new(box io::sink(), None, false, false);
427 let handler = Handler::with_emitter(false, false, box emitter);
428 let sess = ParseSess::with_span_handler(handler, cm);
430 let mut found_main = false;
431 let mut found_extern_crate = cratename.is_none();
432 let mut found_macro = false;
434 let mut parser = match parse::maybe_new_parser_from_source_str(&sess, filename, source) {
437 for mut err in errs {
441 return (found_main, found_extern_crate, found_macro);
446 match parser.parse_item() {
449 if let ast::ItemKind::Fn(..) = item.node {
450 if item.ident.as_str() == "main" {
456 if !found_extern_crate {
457 if let ast::ItemKind::ExternCrate(original) = item.node {
458 // This code will never be reached if `cratename` is none because
459 // `found_extern_crate` is initialized to `true` if it is none.
460 let cratename = cratename.unwrap();
463 Some(name) => found_extern_crate = name.as_str() == cratename,
464 None => found_extern_crate = item.ident.as_str() == cratename,
470 if let ast::ItemKind::Mac(..) = item.node {
475 if found_main && found_extern_crate {
487 (found_main, found_extern_crate, found_macro)
490 // If a doctest's `fn main` is being masked by a wrapper macro, the parsing loop above won't
491 // see it. In that case, run the old text-based scan to see if they at least have a main
492 // function written inside a macro invocation. See
493 // https://github.com/rust-lang/rust/issues/56898
494 let already_has_main = if found_macro && !already_has_main {
497 let comment = line.find("//");
498 if let Some(comment_begins) = comment {
499 &line[0..comment_begins]
504 .any(|code| code.contains("fn main"))
509 // Don't inject `extern crate std` because it's already injected by the
511 if !already_has_extern_crate && !opts.no_crate_inject && cratename != Some("std") {
512 if let Some(cratename) = cratename {
513 // Make sure its actually used if not included.
514 if s.contains(cratename) {
515 prog.push_str(&format!("extern crate {};\n", cratename));
521 // FIXME: This code cannot yet handle no_std test cases yet
522 if dont_insert_main || already_has_main || prog.contains("![no_std]") {
523 prog.push_str(everything_else);
525 let returns_result = everything_else.trim_end().ends_with("(())");
526 let (main_pre, main_post) = if returns_result {
527 ("fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {",
528 "}\n_inner().unwrap() }")
530 ("fn main() {\n", "\n}")
532 prog.extend([main_pre, everything_else, main_post].iter().cloned());
536 debug!("final doctest:\n{}", prog);
541 // FIXME(aburka): use a real parser to deal with multiline attributes
542 fn partition_source(s: &str) -> (String, String, String) {
543 #[derive(Copy, Clone, PartialEq)]
544 enum PartitionState {
549 let mut state = PartitionState::Attrs;
550 let mut before = String::new();
551 let mut crates = String::new();
552 let mut after = String::new();
554 for line in s.lines() {
555 let trimline = line.trim();
557 // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
558 // shunted into "everything else"
560 PartitionState::Attrs => {
561 state = if trimline.starts_with("#![") ||
562 trimline.chars().all(|c| c.is_whitespace()) ||
563 (trimline.starts_with("//") && !trimline.starts_with("///"))
565 PartitionState::Attrs
566 } else if trimline.starts_with("extern crate") ||
567 trimline.starts_with("#[macro_use] extern crate")
569 PartitionState::Crates
571 PartitionState::Other
574 PartitionState::Crates => {
575 state = if trimline.starts_with("extern crate") ||
576 trimline.starts_with("#[macro_use] extern crate") ||
577 trimline.chars().all(|c| c.is_whitespace()) ||
578 (trimline.starts_with("//") && !trimline.starts_with("///"))
580 PartitionState::Crates
582 PartitionState::Other
585 PartitionState::Other => {}
589 PartitionState::Attrs => {
590 before.push_str(line);
591 before.push_str("\n");
593 PartitionState::Crates => {
594 crates.push_str(line);
595 crates.push_str("\n");
597 PartitionState::Other => {
598 after.push_str(line);
599 after.push_str("\n");
604 debug!("before:\n{}", before);
605 debug!("crates:\n{}", crates);
606 debug!("after:\n{}", after);
608 (before, after, crates)
612 fn add_test(&mut self, test: String, config: LangString, line: usize);
613 fn get_line(&self) -> usize {
616 fn register_header(&mut self, _name: &str, _level: u32) {}
619 pub struct Collector {
620 pub tests: Vec<testing::TestDescAndFn>,
622 // The name of the test displayed to the user, separated by `::`.
624 // In tests from Rust source, this is the path to the item
625 // e.g., `["std", "vec", "Vec", "push"]`.
627 // In tests from a markdown file, this is the titles of all headers (h1~h6)
628 // of the sections that contain the code block, e.g., if the markdown file is
641 // the `names` vector of that test will be `["Title", "Subtitle"]`.
645 libs: Vec<SearchPath>,
651 maybe_sysroot: Option<PathBuf>,
653 source_map: Option<Lrc<SourceMap>>,
654 filename: Option<PathBuf>,
655 linker: Option<PathBuf>,
657 persist_doctests: Option<PathBuf>,
661 pub fn new(cratename: String, cfgs: Vec<String>, libs: Vec<SearchPath>, cg: CodegenOptions,
662 externs: Externs, use_headers: bool, opts: TestOptions,
663 maybe_sysroot: Option<PathBuf>, source_map: Option<Lrc<SourceMap>>,
664 filename: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition,
665 persist_doctests: Option<PathBuf>) -> Collector {
686 fn generate_name(&self, line: usize, filename: &FileName) -> String {
687 format!("{} - {} (line {})", filename, self.names.join("::"), line)
690 pub fn set_position(&mut self, position: Span) {
691 self.position = position;
694 fn get_filename(&self) -> FileName {
695 if let Some(ref source_map) = self.source_map {
696 let filename = source_map.span_to_filename(self.position);
697 if let FileName::Real(ref filename) = filename {
698 if let Ok(cur_dir) = env::current_dir() {
699 if let Ok(path) = filename.strip_prefix(&cur_dir) {
700 return path.to_owned().into();
705 } else if let Some(ref filename) = self.filename {
706 filename.clone().into()
708 FileName::Custom("input".to_owned())
713 impl Tester for Collector {
714 fn add_test(&mut self, test: String, config: LangString, line: usize) {
715 let filename = self.get_filename();
716 let name = self.generate_name(line, &filename);
717 let cfgs = self.cfgs.clone();
718 let libs = self.libs.clone();
719 let cg = self.cg.clone();
720 let externs = self.externs.clone();
721 let cratename = self.cratename.to_string();
722 let opts = self.opts.clone();
723 let maybe_sysroot = self.maybe_sysroot.clone();
724 let linker = self.linker.clone();
725 let edition = config.edition.unwrap_or(self.edition);
726 let persist_doctests = self.persist_doctests.clone();
728 debug!("Creating test {}: {}", name, test);
729 self.tests.push(testing::TestDescAndFn {
730 desc: testing::TestDesc {
731 name: testing::DynTestName(name.clone()),
732 ignore: config.ignore,
733 // compiler failures are test failures
734 should_panic: testing::ShouldPanic::No,
735 allow_fail: config.allow_fail,
737 testfn: testing::DynTestFn(box move || {
738 let panic = io::set_panic(None);
739 let print = io::set_print(None);
741 rustc_driver::in_named_rustc_thread(name, move || with_globals(move || {
742 io::set_panic(panic);
743 io::set_print(print);
765 Err(err) => panic::resume_unwind(err),
771 fn get_line(&self) -> usize {
772 if let Some(ref source_map) = self.source_map {
773 let line = self.position.lo().to_usize();
774 let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
775 if line > 0 { line - 1 } else { line }
781 fn register_header(&mut self, name: &str, level: u32) {
782 if self.use_headers {
783 // We use these headings as test names, so it's good if
784 // they're valid identifiers.
785 let name = name.chars().enumerate().map(|(i, c)| {
786 if (i == 0 && c.is_xid_start()) ||
787 (i != 0 && c.is_xid_continue()) {
792 }).collect::<String>();
794 // Here we try to efficiently assemble the header titles into the
795 // test name in the form of `h1::h2::h3::h4::h5::h6`.
797 // Suppose that originally `self.names` contains `[h1, h2, h3]`...
798 let level = level as usize;
799 if level <= self.names.len() {
800 // ... Consider `level == 2`. All headers in the lower levels
801 // are irrelevant in this new level. So we should reset
802 // `self.names` to contain headers until <h2>, and replace that
803 // slot with the new name: `[h1, name]`.
804 self.names.truncate(level);
805 self.names[level - 1] = name;
807 // ... On the other hand, consider `level == 5`. This means we
808 // need to extend `self.names` to contain five headers. We fill
809 // in the missing level (<h4>) with `_`. Thus `self.names` will
810 // become `[h1, h2, h3, "_", name]`.
811 if level - 1 > self.names.len() {
812 self.names.resize(level - 1, "_".to_owned());
814 self.names.push(name);
820 struct HirCollector<'a, 'hir: 'a> {
821 sess: &'a session::Session,
822 collector: &'a mut Collector,
823 map: &'a hir::map::Map<'hir>,
827 impl<'a, 'hir> HirCollector<'a, 'hir> {
828 fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
830 attrs: &[ast::Attribute],
832 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
833 if let Some(ref cfg) = attrs.cfg {
834 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
839 let has_name = !name.is_empty();
841 self.collector.names.push(name);
844 attrs.collapse_doc_comments();
845 attrs.unindent_doc_comments();
846 // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
847 // anything else, this will combine them for us.
848 if let Some(doc) = attrs.collapsed_doc_value() {
849 self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP));
850 let res = markdown::find_testable_code(&doc, self.collector, self.codes);
851 if let Err(err) = res {
852 self.sess.diagnostic().span_warn(attrs.span.unwrap_or(DUMMY_SP),
860 self.collector.names.pop();
865 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
866 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
867 intravisit::NestedVisitorMap::All(&self.map)
870 fn visit_item(&mut self, item: &'hir hir::Item) {
871 let name = if let hir::ItemKind::Impl(.., ref ty, _) = item.node {
872 self.map.hir_to_pretty_string(ty.hir_id)
874 item.ident.to_string()
877 self.visit_testable(name, &item.attrs, |this| {
878 intravisit::walk_item(this, item);
882 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
883 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
884 intravisit::walk_trait_item(this, item);
888 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
889 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
890 intravisit::walk_impl_item(this, item);
894 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
895 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
896 intravisit::walk_foreign_item(this, item);
900 fn visit_variant(&mut self,
901 v: &'hir hir::Variant,
902 g: &'hir hir::Generics,
903 item_id: hir::HirId) {
904 self.visit_testable(v.node.ident.to_string(), &v.node.attrs, |this| {
905 intravisit::walk_variant(this, v, g, item_id);
909 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
910 self.visit_testable(f.ident.to_string(), &f.attrs, |this| {
911 intravisit::walk_struct_field(this, f);
915 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
916 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());
922 use super::{TestOptions, make_test};
925 fn make_test_basic() {
926 //basic use: wraps with `fn main`, adds `#![allow(unused)]`
927 let opts = TestOptions::default();
929 "assert_eq!(2+2, 4);";
935 let output = make_test(input, None, false, &opts);
936 assert_eq!(output, (expected, 2));
940 fn make_test_crate_name_no_use() {
941 // If you give a crate name but *don't* use it within the test, it won't bother inserting
942 // the `extern crate` statement.
943 let opts = TestOptions::default();
945 "assert_eq!(2+2, 4);";
951 let output = make_test(input, Some("asdf"), false, &opts);
952 assert_eq!(output, (expected, 2));
956 fn make_test_crate_name() {
957 // If you give a crate name and use it within the test, it will insert an `extern crate`
958 // statement before `fn main`.
959 let opts = TestOptions::default();
962 assert_eq!(2+2, 4);";
970 let output = make_test(input, Some("asdf"), false, &opts);
971 assert_eq!(output, (expected, 3));
975 fn make_test_no_crate_inject() {
976 // Even if you do use the crate within the test, setting `opts.no_crate_inject` will skip
978 let opts = TestOptions {
979 no_crate_inject: true,
980 display_warnings: false,
985 assert_eq!(2+2, 4);";
992 let output = make_test(input, Some("asdf"), false, &opts);
993 assert_eq!(output, (expected, 2));
997 fn make_test_ignore_std() {
998 // Even if you include a crate name, and use it in the doctest, we still won't include an
999 // `extern crate` statement if the crate is "std" -- that's included already by the
1001 let opts = TestOptions::default();
1004 assert_eq!(2+2, 4);";
1011 let output = make_test(input, Some("std"), false, &opts);
1012 assert_eq!(output, (expected, 2));
1016 fn make_test_manual_extern_crate() {
1017 // When you manually include an `extern crate` statement in your doctest, `make_test`
1018 // assumes you've included one for your own crate too.
1019 let opts = TestOptions::default();
1023 assert_eq!(2+2, 4);";
1031 let output = make_test(input, Some("asdf"), false, &opts);
1032 assert_eq!(output, (expected, 2));
1036 fn make_test_manual_extern_crate_with_macro_use() {
1037 let opts = TestOptions::default();
1039 "#[macro_use] extern crate asdf;
1041 assert_eq!(2+2, 4);";
1044 #[macro_use] extern crate asdf;
1049 let output = make_test(input, Some("asdf"), false, &opts);
1050 assert_eq!(output, (expected, 2));
1054 fn make_test_opts_attrs() {
1055 // If you supplied some doctest attributes with `#![doc(test(attr(...)))]`, it will use
1056 // those instead of the stock `#![allow(unused)]`.
1057 let mut opts = TestOptions::default();
1058 opts.attrs.push("feature(sick_rad)".to_string());
1061 assert_eq!(2+2, 4);";
1063 "#![feature(sick_rad)]
1069 let output = make_test(input, Some("asdf"), false, &opts);
1070 assert_eq!(output, (expected, 3));
1072 // Adding more will also bump the returned line offset.
1073 opts.attrs.push("feature(hella_dope)".to_string());
1075 "#![feature(sick_rad)]
1076 #![feature(hella_dope)]
1082 let output = make_test(input, Some("asdf"), false, &opts);
1083 assert_eq!(output, (expected, 4));
1087 fn make_test_crate_attrs() {
1088 // Including inner attributes in your doctest will apply them to the whole "crate", pasting
1089 // them outside the generated main function.
1090 let opts = TestOptions::default();
1092 "#![feature(sick_rad)]
1093 assert_eq!(2+2, 4);";
1096 #![feature(sick_rad)]
1100 let output = make_test(input, None, false, &opts);
1101 assert_eq!(output, (expected, 2));
1105 fn make_test_with_main() {
1106 // Including your own `fn main` wrapper lets the test use it verbatim.
1107 let opts = TestOptions::default();
1117 let output = make_test(input, None, false, &opts);
1118 assert_eq!(output, (expected, 1));
1122 fn make_test_fake_main() {
1123 // ... but putting it in a comment will still provide a wrapper.
1124 let opts = TestOptions::default();
1126 "//Ceci n'est pas une `fn main`
1127 assert_eq!(2+2, 4);";
1130 //Ceci n'est pas une `fn main`
1134 let output = make_test(input, None, false, &opts);
1135 assert_eq!(output, (expected, 2));
1139 fn make_test_dont_insert_main() {
1140 // Even with that, if you set `dont_insert_main`, it won't create the `fn main` wrapper.
1141 let opts = TestOptions::default();
1143 "//Ceci n'est pas une `fn main`
1144 assert_eq!(2+2, 4);";
1147 //Ceci n'est pas une `fn main`
1148 assert_eq!(2+2, 4);".to_string();
1149 let output = make_test(input, None, true, &opts);
1150 assert_eq!(output, (expected, 1));
1154 fn make_test_display_warnings() {
1155 // If the user is asking to display doctest warnings, suppress the default `allow(unused)`.
1156 let mut opts = TestOptions::default();
1157 opts.display_warnings = true;
1159 "assert_eq!(2+2, 4);";
1164 let output = make_test(input, None, false, &opts);
1165 assert_eq!(output, (expected, 1));
1169 fn make_test_issues_21299_33731() {
1170 let opts = TestOptions::default();
1174 assert_eq!(2+2, 4);";
1183 let output = make_test(input, None, false, &opts);
1184 assert_eq!(output, (expected, 2));
1187 "extern crate hella_qwop;
1188 assert_eq!(asdf::foo, 4);";
1192 extern crate hella_qwop;
1195 assert_eq!(asdf::foo, 4);
1198 let output = make_test(input, Some("asdf"), false, &opts);
1199 assert_eq!(output, (expected, 3));
1203 fn make_test_main_in_macro() {
1204 let opts = TestOptions::default();
1206 "#[macro_use] extern crate my_crate;
1212 #[macro_use] extern crate my_crate;
1217 let output = make_test(input, Some("my_crate"), false, &opts);
1218 assert_eq!(output, (expected, 1));