1 use rustc_data_structures::sync::Lrc;
2 use rustc_interface::interface;
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;
11 use syntax::with_globals;
12 use syntax::source_map::SourceMap;
13 use syntax::edition::Edition;
14 use syntax::feature_gate::UnstableFeatures;
16 use std::io::prelude::*;
18 use std::panic::{self, AssertUnwindSafe};
19 use std::path::PathBuf;
20 use std::process::{self, Command};
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;
28 use crate::clean::Attributes;
29 use crate::config::Options;
30 use crate::html::markdown::{self, ErrorCodes, LangString};
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>,
43 pub fn run(options: Options) -> i32 {
44 let input = config::Input::File(options.input.clone());
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()
59 edition: options.edition,
60 ..config::Options::default()
63 let config = interface::Config {
65 crate_cfg: config::parse_cfgspecs(options.cfgs.clone()),
71 diagnostic_output: DiagnosticOutput::Default,
73 crate_name: options.crate_name.clone(),
74 lint_caps: Default::default(),
77 let mut test_args = options.test_args.clone();
78 let display_warnings = options.display_warnings;
80 let tests = interface::run_compiler(config, |compiler| -> Result<_, ErrorReported> {
81 let lower_to_hir = compiler.lower_to_hir()?;
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(),
89 options.codegen_options,
93 options.maybe_sysroot,
94 Some(compiler.source_map().clone()),
98 options.persist_doctests,
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,
108 codes: ErrorCodes::from(compiler.session().opts
109 .unstable_features.is_nightly_build()),
111 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
112 intravisit::walk_crate(this, krate);
117 }).expect("compiler aborted in rustdoc!");
119 test_args.insert(0, "rustdoctest".to_string());
124 testing::Options::new().display_output(display_warnings)
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;
134 let mut opts = TestOptions {
135 no_crate_inject: false,
136 display_warnings: false,
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))
145 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
148 if attr.check_name(sym::no_crate_inject) {
149 opts.no_crate_inject = true;
151 if attr.check_name(sym::attr) {
152 if let Some(l) = attr.meta_item_list() {
154 opts.attrs.push(pprust::meta_list_item_to_string(item));
163 /// Documentation test failure modes.
165 /// The test failed to compile.
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.
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.
188 libs: Vec<SearchPath>,
193 as_test_harness: bool,
195 mut error_codes: Vec<String>,
197 maybe_sysroot: Option<PathBuf>,
198 linker: Option<PathBuf>,
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)
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.
211 Err(cause) => panic::resume_unwind(cause),
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"),
221 let input = config::Input::Str {
222 name: FileName::DocTest(path, line as isize - line_offset as isize),
225 let outputs = OutputTypes::new(&[(OutputType::Exe, None)]);
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())),
231 crate_types: vec![config::CrateType::Executable],
232 output_types: outputs,
234 cg: config::CodegenOptions {
238 test: as_test_harness,
239 unstable_features: UnstableFeatures::from_environment(),
240 debugging_opts: config::DebuggingOptions {
241 ..config::basic_debugging_options()
244 ..config::Options::default()
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.
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.
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)
262 fn flush(&mut self) -> io::Result<()> { Ok(()) }
264 struct Bomb(Arc<Mutex<Vec<u8>>>, Option<Box<dyn Write+Send>>);
267 let mut old = self.1.take().unwrap();
268 let _ = old.write_all(&self.0.lock().unwrap());
269 io::set_panic(Some(old));
272 let data = Arc::new(Mutex::new(Vec::new()));
274 let old = io::set_panic(Some(box Sink(data.clone())));
275 let _bomb = Bomb(data.clone(), Some(old.unwrap_or(box io::stdout())));
278 Temp(tempfile::TempDir),
283 fn path(&self) -> &std::path::Path {
285 DirState::Temp(t) => t.path(),
286 DirState::Perm(p) => p.as_path(),
291 let outdir = if let Some(mut path) = persist_doctests {
292 path.push(format!("{}_{}",
301 std::fs::create_dir_all(&path)
302 .expect("Couldn't create directory for doctest executables");
306 DirState::Temp(TempFileBuilder::new()
307 .prefix("rustdoctest")
309 .expect("rustdoc needs a tempdir"))
311 let output_file = outdir.path().join("rust_out");
313 let config = interface::Config {
315 crate_cfg: config::parse_cfgspecs(cfgs),
318 output_file: Some(output_file.clone()),
321 diagnostic_output: DiagnosticOutput::Raw(box Sink(data.clone())),
322 stderr: Some(data.clone()),
324 lint_caps: Default::default(),
327 let compile_result = panic::catch_unwind(AssertUnwindSafe(|| {
328 interface::run_compiler(config, |compiler| {
330 compiler.global_ctxt().and_then(|global_ctxt| global_ctxt.take().enter(|tcx| {
331 tcx.analysis(LOCAL_CRATE)
334 compiler.compile().ok();
336 compiler.session().compile_status()
338 })).map_err(|_| ()).and_then(|s| s.map_err(|_| ()));
340 match (compile_result, compile_fail) {
342 return Err(TestFailure::UnexpectedCompilePass);
344 (Ok(()), false) => {}
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));
350 if !error_codes.is_empty() {
351 return Err(TestFailure::MissingErrorCodes(error_codes));
356 return Err(TestFailure::CompileError);
365 let mut cmd = Command::new(output_file);
368 Err(e) => return Err(TestFailure::ExecutionError(e)),
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));
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.
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,
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();
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");
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));
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);
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;
426 let filename = FileName::anon_source_code(s);
427 let source = crates + &everything_else;
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);
437 let mut found_main = false;
438 let mut found_extern_crate = cratename.is_none();
439 let mut found_macro = false;
441 let mut parser = match parse::maybe_new_parser_from_source_str(&sess, filename, source) {
444 for mut err in errs {
448 return (found_main, found_extern_crate, found_macro);
453 match parser.parse_item() {
456 if let ast::ItemKind::Fn(..) = item.node {
457 if item.ident.as_str() == "main" {
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();
470 Some(name) => found_extern_crate = name.as_str() == cratename,
471 None => found_extern_crate = item.ident.as_str() == cratename,
477 if let ast::ItemKind::Mac(..) = item.node {
482 if found_main && found_extern_crate {
494 (found_main, found_extern_crate, found_macro)
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 {
504 let comment = line.find("//");
505 if let Some(comment_begins) = comment {
506 &line[0..comment_begins]
511 .any(|code| code.contains("fn main"))
516 // Don't inject `extern crate std` because it's already injected by the
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));
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);
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 {
536 "fn main() { fn _inner() -> Option<()> {"
538 "fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {"
540 "}\n_inner().unwrap() }")
542 ("fn main() {\n", "\n}")
544 prog.extend([main_pre, everything_else, main_post].iter().cloned());
548 debug!("final doctest:\n{}", prog);
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 {
561 let mut state = PartitionState::Attrs;
562 let mut before = String::new();
563 let mut crates = String::new();
564 let mut after = String::new();
566 for line in s.lines() {
567 let trimline = line.trim();
569 // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
570 // shunted into "everything else"
572 PartitionState::Attrs => {
573 state = if trimline.starts_with("#![") ||
574 trimline.chars().all(|c| c.is_whitespace()) ||
575 (trimline.starts_with("//") && !trimline.starts_with("///"))
577 PartitionState::Attrs
578 } else if trimline.starts_with("extern crate") ||
579 trimline.starts_with("#[macro_use] extern crate")
581 PartitionState::Crates
583 PartitionState::Other
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("///"))
592 PartitionState::Crates
594 PartitionState::Other
597 PartitionState::Other => {}
601 PartitionState::Attrs => {
602 before.push_str(line);
603 before.push_str("\n");
605 PartitionState::Crates => {
606 crates.push_str(line);
607 crates.push_str("\n");
609 PartitionState::Other => {
610 after.push_str(line);
611 after.push_str("\n");
616 debug!("before:\n{}", before);
617 debug!("crates:\n{}", crates);
618 debug!("after:\n{}", after);
620 (before, after, crates)
624 fn add_test(&mut self, test: String, config: LangString, line: usize);
625 fn get_line(&self) -> usize {
628 fn register_header(&mut self, _name: &str, _level: u32) {}
631 pub struct Collector {
632 pub tests: Vec<testing::TestDescAndFn>,
634 // The name of the test displayed to the user, separated by `::`.
636 // In tests from Rust source, this is the path to the item
637 // e.g., `["std", "vec", "Vec", "push"]`.
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
653 // the `names` vector of that test will be `["Title", "Subtitle"]`.
657 libs: Vec<SearchPath>,
663 maybe_sysroot: Option<PathBuf>,
665 source_map: Option<Lrc<SourceMap>>,
666 filename: Option<PathBuf>,
667 linker: Option<PathBuf>,
669 persist_doctests: Option<PathBuf>,
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 {
698 fn generate_name(&self, line: usize, filename: &FileName) -> String {
699 format!("{} - {} (line {})", filename, self.names.join("::"), line)
702 pub fn set_position(&mut self, position: Span) {
703 self.position = position;
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();
717 } else if let Some(ref filename) = self.filename {
718 filename.clone().into()
720 FileName::Custom("input".to_owned())
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();
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,
749 testfn: testing::DynTestFn(box move || {
771 if let Err(err) = res {
773 TestFailure::CompileError => {
774 eprint!("Couldn't compile the test.");
776 TestFailure::UnexpectedCompilePass => {
777 eprint!("Test compiled successfully, but it's marked `compile_fail`.");
779 TestFailure::UnexpectedRunPass => {
780 eprint!("Test executable succeeded, but it's marked `should_panic`.");
782 TestFailure::MissingErrorCodes(codes) => {
783 eprint!("Some expected error codes were not found: {:?}", codes);
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?");
791 TestFailure::ExecutionFailure(out) => {
792 let reason = if let Some(code) = out.status.code() {
793 format!("exit code {}", code)
795 String::from("terminated by signal")
798 eprintln!("Test executable failed ({}).", reason);
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.
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();
812 if !stdout.is_empty() || !stderr.is_empty() {
815 if !stdout.is_empty() {
816 eprintln!("stdout:\n{}", stdout);
819 if !stderr.is_empty() {
820 eprintln!("stderr:\n{}", stderr);
826 panic::resume_unwind(box ());
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 }
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()) {
853 }).collect::<String>();
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`.
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;
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());
875 self.names.push(name);
881 struct HirCollector<'a, 'hir: 'a> {
882 sess: &'a session::Session,
883 collector: &'a mut Collector,
884 map: &'a hir::map::Map<'hir>,
888 impl<'a, 'hir> HirCollector<'a, 'hir> {
889 fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
891 attrs: &[ast::Attribute],
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())) {
900 let has_name = !name.is_empty();
902 self.collector.names.push(name);
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);
917 self.collector.names.pop();
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)
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)
931 item.ident.to_string()
934 self.visit_testable(name, &item.attrs, |this| {
935 intravisit::walk_item(this, item);
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);
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);
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);
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);
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);
972 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
973 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());
979 use super::{TestOptions, make_test};
980 use syntax::edition::DEFAULT_EDITION;
983 fn make_test_basic() {
984 //basic use: wraps with `fn main`, adds `#![allow(unused)]`
985 let opts = TestOptions::default();
987 "assert_eq!(2+2, 4);";
993 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
994 assert_eq!(output, (expected, 2));
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();
1003 "assert_eq!(2+2, 4);";
1009 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1010 assert_eq!(output, (expected, 2));
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();
1020 assert_eq!(2+2, 4);";
1028 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1029 assert_eq!(output, (expected, 3));
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,
1043 assert_eq!(2+2, 4);";
1050 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1051 assert_eq!(output, (expected, 2));
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
1059 let opts = TestOptions::default();
1062 assert_eq!(2+2, 4);";
1069 let output = make_test(input, Some("std"), false, &opts, DEFAULT_EDITION);
1070 assert_eq!(output, (expected, 2));
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();
1081 assert_eq!(2+2, 4);";
1089 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1090 assert_eq!(output, (expected, 2));
1094 fn make_test_manual_extern_crate_with_macro_use() {
1095 let opts = TestOptions::default();
1097 "#[macro_use] extern crate asdf;
1099 assert_eq!(2+2, 4);";
1102 #[macro_use] extern crate asdf;
1107 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1108 assert_eq!(output, (expected, 2));
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());
1119 assert_eq!(2+2, 4);";
1121 "#![feature(sick_rad)]
1127 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1128 assert_eq!(output, (expected, 3));
1130 // Adding more will also bump the returned line offset.
1131 opts.attrs.push("feature(hella_dope)".to_string());
1133 "#![feature(sick_rad)]
1134 #![feature(hella_dope)]
1140 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1141 assert_eq!(output, (expected, 4));
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();
1150 "#![feature(sick_rad)]
1151 assert_eq!(2+2, 4);";
1154 #![feature(sick_rad)]
1158 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1159 assert_eq!(output, (expected, 2));
1163 fn make_test_with_main() {
1164 // Including your own `fn main` wrapper lets the test use it verbatim.
1165 let opts = TestOptions::default();
1175 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1176 assert_eq!(output, (expected, 1));
1180 fn make_test_fake_main() {
1181 // ... but putting it in a comment will still provide a wrapper.
1182 let opts = TestOptions::default();
1184 "//Ceci n'est pas une `fn main`
1185 assert_eq!(2+2, 4);";
1188 //Ceci n'est pas une `fn main`
1192 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1193 assert_eq!(output, (expected, 2));
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();
1201 "//Ceci n'est pas une `fn main`
1202 assert_eq!(2+2, 4);";
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));
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;
1217 "assert_eq!(2+2, 4);";
1222 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1223 assert_eq!(output, (expected, 1));
1227 fn make_test_issues_21299_33731() {
1228 let opts = TestOptions::default();
1232 assert_eq!(2+2, 4);";
1241 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1242 assert_eq!(output, (expected, 2));
1245 "extern crate hella_qwop;
1246 assert_eq!(asdf::foo, 4);";
1250 extern crate hella_qwop;
1253 assert_eq!(asdf::foo, 4);
1256 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1257 assert_eq!(output, (expected, 3));
1261 fn make_test_main_in_macro() {
1262 let opts = TestOptions::default();
1264 "#[macro_use] extern crate my_crate;
1270 #[macro_use] extern crate my_crate;
1275 let output = make_test(input, Some("my_crate"), false, &opts, DEFAULT_EDITION);
1276 assert_eq!(output, (expected, 1));