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 (main_pre, main_post) = if returns_result {
534 ("fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {",
535 "}\n_inner().unwrap() }")
537 ("fn main() {\n", "\n}")
539 prog.extend([main_pre, everything_else, main_post].iter().cloned());
543 debug!("final doctest:\n{}", prog);
548 // FIXME(aburka): use a real parser to deal with multiline attributes
549 fn partition_source(s: &str) -> (String, String, String) {
550 #[derive(Copy, Clone, PartialEq)]
551 enum PartitionState {
556 let mut state = PartitionState::Attrs;
557 let mut before = String::new();
558 let mut crates = String::new();
559 let mut after = String::new();
561 for line in s.lines() {
562 let trimline = line.trim();
564 // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
565 // shunted into "everything else"
567 PartitionState::Attrs => {
568 state = if trimline.starts_with("#![") ||
569 trimline.chars().all(|c| c.is_whitespace()) ||
570 (trimline.starts_with("//") && !trimline.starts_with("///"))
572 PartitionState::Attrs
573 } else if trimline.starts_with("extern crate") ||
574 trimline.starts_with("#[macro_use] extern crate")
576 PartitionState::Crates
578 PartitionState::Other
581 PartitionState::Crates => {
582 state = if trimline.starts_with("extern crate") ||
583 trimline.starts_with("#[macro_use] extern crate") ||
584 trimline.chars().all(|c| c.is_whitespace()) ||
585 (trimline.starts_with("//") && !trimline.starts_with("///"))
587 PartitionState::Crates
589 PartitionState::Other
592 PartitionState::Other => {}
596 PartitionState::Attrs => {
597 before.push_str(line);
598 before.push_str("\n");
600 PartitionState::Crates => {
601 crates.push_str(line);
602 crates.push_str("\n");
604 PartitionState::Other => {
605 after.push_str(line);
606 after.push_str("\n");
611 debug!("before:\n{}", before);
612 debug!("crates:\n{}", crates);
613 debug!("after:\n{}", after);
615 (before, after, crates)
619 fn add_test(&mut self, test: String, config: LangString, line: usize);
620 fn get_line(&self) -> usize {
623 fn register_header(&mut self, _name: &str, _level: u32) {}
626 pub struct Collector {
627 pub tests: Vec<testing::TestDescAndFn>,
629 // The name of the test displayed to the user, separated by `::`.
631 // In tests from Rust source, this is the path to the item
632 // e.g., `["std", "vec", "Vec", "push"]`.
634 // In tests from a markdown file, this is the titles of all headers (h1~h6)
635 // of the sections that contain the code block, e.g., if the markdown file is
648 // the `names` vector of that test will be `["Title", "Subtitle"]`.
652 libs: Vec<SearchPath>,
658 maybe_sysroot: Option<PathBuf>,
660 source_map: Option<Lrc<SourceMap>>,
661 filename: Option<PathBuf>,
662 linker: Option<PathBuf>,
664 persist_doctests: Option<PathBuf>,
668 pub fn new(cratename: String, cfgs: Vec<String>, libs: Vec<SearchPath>, cg: CodegenOptions,
669 externs: Externs, use_headers: bool, opts: TestOptions,
670 maybe_sysroot: Option<PathBuf>, source_map: Option<Lrc<SourceMap>>,
671 filename: Option<PathBuf>, linker: Option<PathBuf>, edition: Edition,
672 persist_doctests: Option<PathBuf>) -> Collector {
693 fn generate_name(&self, line: usize, filename: &FileName) -> String {
694 format!("{} - {} (line {})", filename, self.names.join("::"), line)
697 pub fn set_position(&mut self, position: Span) {
698 self.position = position;
701 fn get_filename(&self) -> FileName {
702 if let Some(ref source_map) = self.source_map {
703 let filename = source_map.span_to_filename(self.position);
704 if let FileName::Real(ref filename) = filename {
705 if let Ok(cur_dir) = env::current_dir() {
706 if let Ok(path) = filename.strip_prefix(&cur_dir) {
707 return path.to_owned().into();
712 } else if let Some(ref filename) = self.filename {
713 filename.clone().into()
715 FileName::Custom("input".to_owned())
720 impl Tester for Collector {
721 fn add_test(&mut self, test: String, config: LangString, line: usize) {
722 let filename = self.get_filename();
723 let name = self.generate_name(line, &filename);
724 let cfgs = self.cfgs.clone();
725 let libs = self.libs.clone();
726 let cg = self.cg.clone();
727 let externs = self.externs.clone();
728 let cratename = self.cratename.to_string();
729 let opts = self.opts.clone();
730 let maybe_sysroot = self.maybe_sysroot.clone();
731 let linker = self.linker.clone();
732 let edition = config.edition.unwrap_or(self.edition);
733 let persist_doctests = self.persist_doctests.clone();
735 debug!("Creating test {}: {}", name, test);
736 self.tests.push(testing::TestDescAndFn {
737 desc: testing::TestDesc {
738 name: testing::DynTestName(name.clone()),
739 ignore: config.ignore,
740 // compiler failures are test failures
741 should_panic: testing::ShouldPanic::No,
742 allow_fail: config.allow_fail,
744 testfn: testing::DynTestFn(box move || {
766 if let Err(err) = res {
768 TestFailure::CompileError => {
769 eprint!("Couldn't compile the test.");
771 TestFailure::UnexpectedCompilePass => {
772 eprint!("Test compiled successfully, but it's marked `compile_fail`.");
774 TestFailure::UnexpectedRunPass => {
775 eprint!("Test executable succeeded, but it's marked `should_panic`.");
777 TestFailure::MissingErrorCodes(codes) => {
778 eprint!("Some expected error codes were not found: {:?}", codes);
780 TestFailure::ExecutionError(err) => {
781 eprint!("Couldn't run the test: {}", err);
782 if err.kind() == io::ErrorKind::PermissionDenied {
783 eprint!(" - maybe your tempdir is mounted with noexec?");
786 TestFailure::ExecutionFailure(out) => {
787 let reason = if let Some(code) = out.status.code() {
788 format!("exit code {}", code)
790 String::from("terminated by signal")
793 eprintln!("Test executable failed ({}).", reason);
795 // FIXME(#12309): An unfortunate side-effect of capturing the test
796 // executable's output is that the relative ordering between the test's
797 // stdout and stderr is lost. However, this is better than the
798 // alternative: if the test executable inherited the parent's I/O
799 // handles the output wouldn't be captured at all, even on success.
801 // The ordering could be preserved if the test process' stderr was
802 // redirected to stdout, but that functionality does not exist in the
803 // standard library, so it may not be portable enough.
804 let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
805 let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
807 if !stdout.is_empty() || !stderr.is_empty() {
810 if !stdout.is_empty() {
811 eprintln!("stdout:\n{}", stdout);
814 if !stderr.is_empty() {
815 eprintln!("stderr:\n{}", stderr);
821 panic::resume_unwind(box ());
827 fn get_line(&self) -> usize {
828 if let Some(ref source_map) = self.source_map {
829 let line = self.position.lo().to_usize();
830 let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
831 if line > 0 { line - 1 } else { line }
837 fn register_header(&mut self, name: &str, level: u32) {
838 if self.use_headers {
839 // We use these headings as test names, so it's good if
840 // they're valid identifiers.
841 let name = name.chars().enumerate().map(|(i, c)| {
842 if (i == 0 && c.is_xid_start()) ||
843 (i != 0 && c.is_xid_continue()) {
848 }).collect::<String>();
850 // Here we try to efficiently assemble the header titles into the
851 // test name in the form of `h1::h2::h3::h4::h5::h6`.
853 // Suppose that originally `self.names` contains `[h1, h2, h3]`...
854 let level = level as usize;
855 if level <= self.names.len() {
856 // ... Consider `level == 2`. All headers in the lower levels
857 // are irrelevant in this new level. So we should reset
858 // `self.names` to contain headers until <h2>, and replace that
859 // slot with the new name: `[h1, name]`.
860 self.names.truncate(level);
861 self.names[level - 1] = name;
863 // ... On the other hand, consider `level == 5`. This means we
864 // need to extend `self.names` to contain five headers. We fill
865 // in the missing level (<h4>) with `_`. Thus `self.names` will
866 // become `[h1, h2, h3, "_", name]`.
867 if level - 1 > self.names.len() {
868 self.names.resize(level - 1, "_".to_owned());
870 self.names.push(name);
876 struct HirCollector<'a, 'hir: 'a> {
877 sess: &'a session::Session,
878 collector: &'a mut Collector,
879 map: &'a hir::map::Map<'hir>,
883 impl<'a, 'hir> HirCollector<'a, 'hir> {
884 fn visit_testable<F: FnOnce(&mut Self)>(&mut self,
886 attrs: &[ast::Attribute],
888 let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
889 if let Some(ref cfg) = attrs.cfg {
890 if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
895 let has_name = !name.is_empty();
897 self.collector.names.push(name);
900 attrs.collapse_doc_comments();
901 attrs.unindent_doc_comments();
902 // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
903 // anything else, this will combine them for us.
904 if let Some(doc) = attrs.collapsed_doc_value() {
905 self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP));
906 markdown::find_testable_code(&doc, self.collector, self.codes);
912 self.collector.names.pop();
917 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
918 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
919 intravisit::NestedVisitorMap::All(&self.map)
922 fn visit_item(&mut self, item: &'hir hir::Item) {
923 let name = if let hir::ItemKind::Impl(.., ref ty, _) = item.node {
924 self.map.hir_to_pretty_string(ty.hir_id)
926 item.ident.to_string()
929 self.visit_testable(name, &item.attrs, |this| {
930 intravisit::walk_item(this, item);
934 fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
935 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
936 intravisit::walk_trait_item(this, item);
940 fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
941 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
942 intravisit::walk_impl_item(this, item);
946 fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
947 self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
948 intravisit::walk_foreign_item(this, item);
952 fn visit_variant(&mut self,
953 v: &'hir hir::Variant,
954 g: &'hir hir::Generics,
955 item_id: hir::HirId) {
956 self.visit_testable(v.node.ident.to_string(), &v.node.attrs, |this| {
957 intravisit::walk_variant(this, v, g, item_id);
961 fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
962 self.visit_testable(f.ident.to_string(), &f.attrs, |this| {
963 intravisit::walk_struct_field(this, f);
967 fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
968 self.visit_testable(macro_def.name.to_string(), ¯o_def.attrs, |_| ());
974 use super::{TestOptions, make_test};
975 use syntax::edition::DEFAULT_EDITION;
978 fn make_test_basic() {
979 //basic use: wraps with `fn main`, adds `#![allow(unused)]`
980 let opts = TestOptions::default();
982 "assert_eq!(2+2, 4);";
988 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
989 assert_eq!(output, (expected, 2));
993 fn make_test_crate_name_no_use() {
994 // If you give a crate name but *don't* use it within the test, it won't bother inserting
995 // the `extern crate` statement.
996 let opts = TestOptions::default();
998 "assert_eq!(2+2, 4);";
1004 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1005 assert_eq!(output, (expected, 2));
1009 fn make_test_crate_name() {
1010 // If you give a crate name and use it within the test, it will insert an `extern crate`
1011 // statement before `fn main`.
1012 let opts = TestOptions::default();
1015 assert_eq!(2+2, 4);";
1023 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1024 assert_eq!(output, (expected, 3));
1028 fn make_test_no_crate_inject() {
1029 // Even if you do use the crate within the test, setting `opts.no_crate_inject` will skip
1030 // adding it anyway.
1031 let opts = TestOptions {
1032 no_crate_inject: true,
1033 display_warnings: false,
1038 assert_eq!(2+2, 4);";
1045 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1046 assert_eq!(output, (expected, 2));
1050 fn make_test_ignore_std() {
1051 // Even if you include a crate name, and use it in the doctest, we still won't include an
1052 // `extern crate` statement if the crate is "std" -- that's included already by the
1054 let opts = TestOptions::default();
1057 assert_eq!(2+2, 4);";
1064 let output = make_test(input, Some("std"), false, &opts, DEFAULT_EDITION);
1065 assert_eq!(output, (expected, 2));
1069 fn make_test_manual_extern_crate() {
1070 // When you manually include an `extern crate` statement in your doctest, `make_test`
1071 // assumes you've included one for your own crate too.
1072 let opts = TestOptions::default();
1076 assert_eq!(2+2, 4);";
1084 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1085 assert_eq!(output, (expected, 2));
1089 fn make_test_manual_extern_crate_with_macro_use() {
1090 let opts = TestOptions::default();
1092 "#[macro_use] extern crate asdf;
1094 assert_eq!(2+2, 4);";
1097 #[macro_use] extern crate asdf;
1102 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1103 assert_eq!(output, (expected, 2));
1107 fn make_test_opts_attrs() {
1108 // If you supplied some doctest attributes with `#![doc(test(attr(...)))]`, it will use
1109 // those instead of the stock `#![allow(unused)]`.
1110 let mut opts = TestOptions::default();
1111 opts.attrs.push("feature(sick_rad)".to_string());
1114 assert_eq!(2+2, 4);";
1116 "#![feature(sick_rad)]
1122 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1123 assert_eq!(output, (expected, 3));
1125 // Adding more will also bump the returned line offset.
1126 opts.attrs.push("feature(hella_dope)".to_string());
1128 "#![feature(sick_rad)]
1129 #![feature(hella_dope)]
1135 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1136 assert_eq!(output, (expected, 4));
1140 fn make_test_crate_attrs() {
1141 // Including inner attributes in your doctest will apply them to the whole "crate", pasting
1142 // them outside the generated main function.
1143 let opts = TestOptions::default();
1145 "#![feature(sick_rad)]
1146 assert_eq!(2+2, 4);";
1149 #![feature(sick_rad)]
1153 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1154 assert_eq!(output, (expected, 2));
1158 fn make_test_with_main() {
1159 // Including your own `fn main` wrapper lets the test use it verbatim.
1160 let opts = TestOptions::default();
1170 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1171 assert_eq!(output, (expected, 1));
1175 fn make_test_fake_main() {
1176 // ... but putting it in a comment will still provide a wrapper.
1177 let opts = TestOptions::default();
1179 "//Ceci n'est pas une `fn main`
1180 assert_eq!(2+2, 4);";
1183 //Ceci n'est pas une `fn main`
1187 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1188 assert_eq!(output, (expected, 2));
1192 fn make_test_dont_insert_main() {
1193 // Even with that, if you set `dont_insert_main`, it won't create the `fn main` wrapper.
1194 let opts = TestOptions::default();
1196 "//Ceci n'est pas une `fn main`
1197 assert_eq!(2+2, 4);";
1200 //Ceci n'est pas une `fn main`
1201 assert_eq!(2+2, 4);".to_string();
1202 let output = make_test(input, None, true, &opts, DEFAULT_EDITION);
1203 assert_eq!(output, (expected, 1));
1207 fn make_test_display_warnings() {
1208 // If the user is asking to display doctest warnings, suppress the default `allow(unused)`.
1209 let mut opts = TestOptions::default();
1210 opts.display_warnings = true;
1212 "assert_eq!(2+2, 4);";
1217 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1218 assert_eq!(output, (expected, 1));
1222 fn make_test_issues_21299_33731() {
1223 let opts = TestOptions::default();
1227 assert_eq!(2+2, 4);";
1236 let output = make_test(input, None, false, &opts, DEFAULT_EDITION);
1237 assert_eq!(output, (expected, 2));
1240 "extern crate hella_qwop;
1241 assert_eq!(asdf::foo, 4);";
1245 extern crate hella_qwop;
1248 assert_eq!(asdf::foo, 4);
1251 let output = make_test(input, Some("asdf"), false, &opts, DEFAULT_EDITION);
1252 assert_eq!(output, (expected, 3));
1256 fn make_test_main_in_macro() {
1257 let opts = TestOptions::default();
1259 "#[macro_use] extern crate my_crate;
1265 #[macro_use] extern crate my_crate;
1270 let output = make_test(input, Some("my_crate"), false, &opts, DEFAULT_EDITION);
1271 assert_eq!(output, (expected, 1));