Skip to main content

rustdoc/doctest/
markdown.rs

1//! Doctest functionality used only for doctests in `.md` Markdown files.
2
3use std::fs::read_to_string;
4use std::process::ExitCode;
5use std::sync::{Arc, Mutex};
6
7use rustc_errors::DiagCtxtHandle;
8use rustc_session::config::Input;
9use rustc_span::source_map::FilePathMapping;
10use rustc_span::{DUMMY_SP, FileName, RealFileName};
11use tempfile::tempdir;
12
13use super::{
14    CreateRunnableDocTests, DocTestVisitor, GlobalTestOptions, ScrapedDocTest, generate_args_file,
15};
16use crate::config::Options;
17use crate::html::markdown::{
18    CodeBlockPosition, CodeLineMapping, ErrorCodes, LangString, find_testable_code,
19};
20
21struct MdCollector {
22    tests: Vec<ScrapedDocTest>,
23    cur_path: Vec<String>,
24    filename: FileName,
25}
26
27impl DocTestVisitor for MdCollector {
28    fn visit_test(
29        &mut self,
30        test: String,
31        config: LangString,
32        position: CodeBlockPosition,
33        code_mappings: Vec<CodeLineMapping>,
34    ) {
35        let filename = self.filename.clone();
36        let line = match position {
37            CodeBlockPosition::Relative(rel_line) => {
38                // First line of Markdown is line 1.
39                1 + rel_line.offset()
40            }
41            CodeBlockPosition::Span(_) => {
42                rustc_span::bug!("markdown collector doesn't produce spans")
43            }
44        };
45        self.tests.push(ScrapedDocTest::new(
46            filename,
47            line,
48            self.cur_path.clone(),
49            config,
50            test,
51            DUMMY_SP,
52            code_mappings,
53            Vec::new(),
54        ));
55    }
56
57    fn visit_header(&mut self, name: &str, level: u32) {
58        // We use these headings as test names, so it's good if
59        // they're valid identifiers.
60        let name = name
61            .chars()
62            .enumerate()
63            .map(|(i, c)| {
64                if (i == 0 && rustc_lexer::is_id_start(c))
65                    || (i != 0 && rustc_lexer::is_id_continue(c))
66                {
67                    c
68                } else {
69                    '_'
70                }
71            })
72            .collect::<String>();
73
74        // Here we try to efficiently assemble the header titles into the
75        // test name in the form of `h1::h2::h3::h4::h5::h6`.
76        //
77        // Suppose that originally `self.cur_path` contains `[h1, h2, h3]`...
78        let level = level as usize;
79        if level <= self.cur_path.len() {
80            // ... Consider `level == 2`. All headers in the lower levels
81            // are irrelevant in this new level. So we should reset
82            // `self.names` to contain headers until <h2>, and replace that
83            // slot with the new name: `[h1, name]`.
84            self.cur_path.truncate(level);
85            self.cur_path[level - 1] = name;
86        } else {
87            // ... On the other hand, consider `level == 5`. This means we
88            // need to extend `self.names` to contain five headers. We fill
89            // in the missing level (<h4>) with `_`. Thus `self.names` will
90            // become `[h1, h2, h3, "_", name]`.
91            if level - 1 > self.cur_path.len() {
92                self.cur_path.resize(level - 1, "_".to_owned());
93            }
94            self.cur_path.push(name);
95        }
96    }
97}
98
99/// Runs any tests/code examples in the markdown file `options.input`.
100pub(crate) fn test(
101    input: &Input,
102    options: Options,
103    dcx: DiagCtxtHandle<'_>,
104) -> Result<ExitCode, String> {
105    let input_str = match input {
106        Input::File(path) => {
107            read_to_string(path).map_err(|err| format!("{}: {err}", path.display()))?
108        }
109        Input::Str { name: _, input } | Input::DocTestStr { input, .. } => input.clone(),
110    };
111
112    // Obviously not a real crate name, but close enough for purposes of doctests.
113    let crate_name = input.filestem().to_string();
114    let temp_dir =
115        tempdir().map_err(|error| format!("failed to create temporary directory: {error:?}"))?;
116    let args_file = temp_dir.path().join("rustdoc-cfgs");
117    generate_args_file(&args_file, &options)?;
118
119    let opts = GlobalTestOptions {
120        crate_name,
121        no_crate_inject: true,
122        insert_indent_space: false,
123        args_file,
124    };
125
126    let mut md_collector = MdCollector {
127        tests: vec![],
128        cur_path: vec![],
129        filename: input
130            .opt_path()
131            .map(|f| {
132                // We don't have access to a rustc Session so let's just use a dummy
133                // filepath mapping to create a real filename.
134                let file_mapping = FilePathMapping::empty();
135                FileName::Real(file_mapping.to_real_filename(&RealFileName::empty(), f))
136            })
137            .unwrap_or(FileName::Custom("input".to_owned())),
138    };
139    let codes = ErrorCodes::from(options.unstable_features.is_nightly_build());
140
141    find_testable_code(&input_str, &mut md_collector, codes, None);
142
143    let mut collector = CreateRunnableDocTests::new(options.clone(), opts);
144    md_collector.tests.into_iter().for_each(|t| collector.add_test(t, None));
145    let CreateRunnableDocTests { opts, rustdoc_options, standalone_tests, mergeable_tests, .. } =
146        collector;
147    Ok(crate::doctest::run_tests(
148        dcx,
149        opts,
150        &rustdoc_options,
151        &Arc::new(Mutex::new(Vec::new())),
152        standalone_tests,
153        mergeable_tests,
154    ))
155}