Skip to main content

soothfast_docs/
gentests.rs

1//! Generated artifacts from markdown code blocks: one integration-test target
2//! per package with a module per page (plain rust blocks), and one example
3//! per package with a module per capture block. CI compares regenerated
4//! content against disk, so stale artifacts fail.
5
6use crate::markdown::{CodeBlock, Doc};
7
8/// First line of every generated file; `docs check` uses it to tell
9/// generated artifacts from hand-written ones.
10pub const GENERATED_HEADER: &str = "// @generated by `cargo soothfast docs gen-tests`";
11
12/// `docs/measuring.md` → `soothfast_doc_docs_measuring`.
13pub fn sanitized_stem(rel_path: &str) -> String {
14    let stem = rel_path.trim_end_matches(".md");
15    let san: String = stem
16        .chars()
17        .map(|c| {
18            if c.is_ascii_alphanumeric() {
19                c.to_ascii_lowercase()
20            } else {
21                '_'
22            }
23        })
24        .collect();
25    san.trim_matches('_').to_string()
26}
27
28fn indent(code: &str, pad: &str) -> String {
29    code.lines()
30        .map(|l| {
31            if l.is_empty() {
32                String::new()
33            } else {
34                format!("{pad}{l}")
35            }
36        })
37        .collect::<Vec<_>>()
38        .join("\n")
39}
40
41/// One generated file, its path relative to the package directory.
42#[derive(Debug, Clone, PartialEq)]
43pub struct Generated {
44    /// Where the file goes, relative to the package directory.
45    pub path: String,
46    /// The file's full content, header included.
47    pub content: String,
48}
49
50/// Wraps the generated `mod` lines and dispatch of a target's `main.rs`.
51/// rustfmt neither formats a brace-delimited macro body nor follows a `mod`
52/// inside one, so `cargo fmt` cannot make a generated file differ from what
53/// `docs check` regenerates, whatever its version, edition or config.
54const VERBATIM: &str =
55    "macro_rules! verbatim {\n    ($($tokens:tt)*) => {\n        $($tokens)*\n    };\n}\n";
56
57/// The one integration-test target the doc tests of a package compile into.
58pub const DOC_TESTS_DIR: &str = "tests/soothfast_docs";
59
60/// Where generated files live, as (directory, file-name prefix, replaced by),
61/// relative to the package directory. A file there that starts with
62/// [`GENERATED_HEADER`] belongs to gen-tests: it is rewritten when expected
63/// and removed when not. An entry with an empty prefix is a target directory
64/// gen-tests owns outright; a prefixed entry is the per-page or per-block
65/// layout of earlier releases and names the target directory that replaced it.
66pub const OWNED: &[(&str, &str, Option<&str>)] = &[
67    ("tests", "soothfast_doc_", Some(DOC_TESTS_DIR)),
68    (DOC_TESTS_DIR, "", None),
69    ("examples", "soothfast_capture_", Some(CAPTURE_DIR)),
70    (CAPTURE_DIR, "", None),
71];
72
73/// The page a generated file was generated from, and the line of the block
74/// when it is one block's file, read from its `// source: PAGE[ line N]` line.
75pub fn recorded_source(content: &str) -> Option<(&str, Option<usize>)> {
76    let source = content.lines().nth(1)?.strip_prefix("// source: ")?;
77    match source.rsplit_once(" line ") {
78        Some((page, line)) => match line.parse::<usize>() {
79            Ok(line) => Some((page, Some(line))),
80            Err(_) => Some((source, None)),
81        },
82        None => Some((source, None)),
83    }
84}
85
86/// Every doc-test file a package needs: one module per page with testable
87/// blocks under [`DOC_TESTS_DIR`], and the `main.rs` that declares them.
88/// Empty when no page has a testable block. An error names two pages whose
89/// paths sanitize to the same module.
90pub fn doc_test_set<'a>(
91    docs: impl IntoIterator<Item = (&'a str, &'a Doc)>,
92) -> Result<Vec<Generated>, String> {
93    let docs: Vec<(&str, &Doc)> = docs.into_iter().collect();
94    one_global_allocator(&docs, CodeBlock::is_testable_rust)?;
95    let mut pages: Vec<(String, &str, String)> = Vec::new();
96    for (rel_path, doc) in docs {
97        if let Some(content) = test_file(rel_path, doc) {
98            pages.push((
99                format!("doc_{}", sanitized_stem(rel_path)),
100                rel_path,
101                content,
102            ));
103        }
104    }
105    pages.sort_by(|a, b| a.1.cmp(b.1));
106    for (i, (module, path, _)) in pages.iter().enumerate() {
107        if let Some((_, other, _)) = pages[..i].iter().find(|(m, _, _)| m == module) {
108            return Err(format!(
109                "{other} and {path} both generate doc-test module `{module}`; rename one"
110            ));
111        }
112    }
113    if pages.is_empty() {
114        return Ok(Vec::new());
115    }
116    let mods: String = pages
117        .iter()
118        .map(|(m, _, _)| format!("mod {m};\n"))
119        .collect();
120    let main =
121        format!("{GENERATED_HEADER}\n#![allow(unused)]\n\n{VERBATIM}\nverbatim! {{\n{mods}}}\n");
122    let mut set = vec![Generated {
123        path: format!("{DOC_TESTS_DIR}/main.rs"),
124        content: main,
125    }];
126    set.extend(pages.into_iter().map(|(module, _, content)| Generated {
127        path: format!("{DOC_TESTS_DIR}/{module}.rs"),
128        content,
129    }));
130    Ok(set)
131}
132
133/// The blocks of one target share a crate, so at most one of them may install
134/// a global allocator, directly or through `soothfast::bench_main!()`.
135fn one_global_allocator(
136    docs: &[(&str, &Doc)],
137    in_target: fn(&CodeBlock) -> bool,
138) -> Result<(), String> {
139    let mut found = docs.iter().flat_map(|(page, doc)| {
140        doc.blocks
141            .iter()
142            .filter(move |b| in_target(b))
143            .filter(|b| b.code.contains("#[global_allocator]") || b.code.contains("bench_main!"))
144            .map(move |b| format!("{page} line {}", b.line))
145    });
146    match (found.next(), found.next()) {
147        (Some(first), Some(second)) => Err(format!(
148            "{first} and {second} both install a global allocator, and the blocks of a package compile into one crate; mark one `ignore` or `no_run` in another package"
149        )),
150        _ => Ok(()),
151    }
152}
153
154/// For `rel_path` (relative to the package directory) in a place gen-tests
155/// writes, per [`OWNED`]: the target directory it belongs to, and whether it is
156/// a leftover of the layout that target replaced. The file's header decides
157/// ownership.
158pub fn owning_target(rel_path: &str) -> Option<(&'static str, bool)> {
159    let (dir, name) = rel_path.rsplit_once('/').unwrap_or(("", rel_path));
160    if !name.ends_with(".rs") {
161        return None;
162    }
163    OWNED
164        .iter()
165        .find(|(d, prefix, _)| *d == dir && name.starts_with(prefix))
166        .map(|(dir, _, replaced_by)| (replaced_by.unwrap_or(dir), replaced_by.is_some()))
167}
168
169/// Module content for one markdown page's doc tests, or None when it has no
170/// testable blocks (all ignored / non-rust / capture).
171pub fn test_file(rel_path: &str, doc: &Doc) -> Option<String> {
172    let testable: Vec<&CodeBlock> = doc.blocks.iter().filter(|b| b.is_testable_rust()).collect();
173    if testable.is_empty() {
174        return None;
175    }
176    let mut out = format!("{GENERATED_HEADER}\n// source: {rel_path}\n#![allow(unused)]\n");
177    for block in testable {
178        let body = indent(&block.code, "    ");
179        // Blocks that define `fn main` get it as a nested fn, then called.
180        let call_main = if block.code.lines().any(|l| top_level_main(l).is_some()) {
181            "\n    main();"
182        } else {
183            ""
184        };
185        // A `feature=NAME` tag gates the generated test behind that feature (`feature=A,B` behind all of them).
186        let cfg = match block.feature_cfg() {
187            Some(pred) => format!("#[cfg({pred})]\n"),
188            None => String::new(),
189        };
190        // rustfmt::skip (per-item — the inner-attribute form is unstable):
191        // blocks are verbatim from the markdown; formatting the generated fn
192        // would make it diverge from its source and fail `docs check`.
193        if block.has_tag("no_run") {
194            out.push_str(&format!(
195                "\n// line {}: compile-only (no_run)\n{cfg}#[rustfmt::skip]\n#[allow(dead_code)]\nfn doc_block_line_{}() {{\n{body}\n}}\n",
196                block.line, block.line
197            ));
198        } else {
199            out.push_str(&format!(
200                "\n// line {}\n{cfg}#[rustfmt::skip]\n#[test]\nfn doc_block_line_{}() {{\n{body}{call_main}\n}}\n",
201                block.line, block.line
202            ));
203        }
204    }
205    Some(out)
206}
207
208/// What one page's rust blocks and markers add up to.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
210pub struct PageCounts {
211    /// Blocks gen-tests turns into a running `#[test]`.
212    pub executed: usize,
213    /// Blocks that are only compiled (`no_run`) or never generated
214    /// (`ignore`, `compile_fail` and the other rustdoc attributes).
215    pub compile_only: usize,
216    /// `soothfast:bind` markers.
217    pub binds: usize,
218    /// `soothfast:claim` markers.
219    pub claims: usize,
220}
221
222impl PageCounts {
223    /// Whether nothing on the page ties its prose to code or a measurement.
224    pub fn unanchored(&self) -> bool {
225        self.binds == 0 && self.claims == 0
226    }
227}
228
229/// Count `doc`'s rust blocks by whether they execute, and its markers.
230/// Capture blocks run in the capture example, not as doc tests, so they are
231/// in neither count.
232pub fn page_counts(doc: &Doc) -> PageCounts {
233    let mut counts = PageCounts {
234        binds: doc.binds.len(),
235        claims: doc.claims.len(),
236        ..PageCounts::default()
237    };
238    for block in doc
239        .blocks
240        .iter()
241        .filter(|b| b.is_rust_example() && !b.is_capture())
242    {
243        if block.is_testable_rust() && !block.has_tag("no_run") {
244            counts.executed += 1;
245        } else {
246            counts.compile_only += 1;
247        }
248    }
249    counts
250}
251
252/// The one example target every capture block of a package compiles into.
253pub const CAPTURE_DIR: &str = "examples/soothfast_capture";
254
255/// Cargo's name for the [`CAPTURE_DIR`] example.
256pub const CAPTURE_EXAMPLE: &str = "soothfast_capture";
257
258/// Exit status of the capture example for a block id it does not contain.
259pub const CAPTURE_UNKNOWN: (i32, &str) = (2, "soothfast_capture: unknown block");
260
261/// Exit status of the capture example for a block whose `feature=` tag is
262/// not enabled in this build. The stderr line starts with the sentinel.
263pub const CAPTURE_DISABLED: (i32, &str) = (3, "soothfast_capture: disabled block");
264
265/// Block ids for one page's capture blocks, in capture order: the argument
266/// the capture example takes to run that block.
267pub fn capture_ids(rel_path: &str, doc: &Doc) -> Vec<String> {
268    let stem = sanitized_stem(rel_path);
269    let count = doc.blocks.iter().filter(|b| b.is_capture()).count();
270    (1..=count).map(|n| format!("{stem}_{n}")).collect()
271}
272
273/// Every capture file a package needs: one `block_<id>.rs` module per capture
274/// block under [`CAPTURE_DIR`], and the `main.rs` that runs the block its first
275/// argument names. Empty when no page has a capture block.
276///
277/// A block with a `feature=` tag (`feature=A,B` for all of them) compiles in
278/// only under its features; without them the example exits with
279/// [`CAPTURE_DISABLED`], so a capture run can keep the recorded output rather
280/// than splice in nothing. A block keeps its own top-level `fn main`, whatever
281/// it returns or however it is attributed (`#[tokio::main]`); a block without
282/// one becomes the body of one. An error names a page whose block uses a
283/// crate-level attribute, which a module cannot carry, or two pages whose
284/// paths sanitize to the same block ids.
285pub fn capture_set<'a>(
286    docs: impl IntoIterator<Item = (&'a str, &'a Doc)>,
287) -> Result<Vec<Generated>, String> {
288    let docs: Vec<(&str, &Doc)> = docs.into_iter().collect();
289    one_global_allocator(&docs, CodeBlock::is_capture)?;
290    let mut blocks: Vec<(String, &str, Option<String>, String)> = Vec::new();
291    let mut stems: Vec<(String, &str)> = Vec::new();
292    for (rel_path, doc) in docs {
293        let ids = capture_ids(rel_path, doc);
294        if ids.is_empty() {
295            continue;
296        }
297        let stem = sanitized_stem(rel_path);
298        if let Some((_, other)) = stems.iter().find(|(s, _)| *s == stem) {
299            return Err(format!(
300                "{other} and {rel_path} both generate capture blocks `{stem}_N`; rename one"
301            ));
302        }
303        stems.push((stem, rel_path));
304        let captures = doc.blocks.iter().filter(|b| b.is_capture());
305        for (id, block) in ids.into_iter().zip(captures) {
306            let body = capture_module(block)
307                .map_err(|e| format!("{rel_path} line {}: {e}", block.line))?;
308            let content = format!(
309                "{GENERATED_HEADER}\n// source: {rel_path} line {}\n{body}",
310                block.line
311            );
312            blocks.push((id, rel_path, block.feature_cfg(), content));
313        }
314    }
315    if blocks.is_empty() {
316        return Ok(Vec::new());
317    }
318    blocks.sort_by(|a, b| a.1.cmp(b.1));
319    let mut set = vec![Generated {
320        path: format!("{CAPTURE_DIR}/main.rs"),
321        content: capture_main(&blocks),
322    }];
323    set.extend(blocks.into_iter().map(|(id, _, _, content)| Generated {
324        path: format!("{CAPTURE_DIR}/block_{id}.rs"),
325        content,
326    }));
327    Ok(set)
328}
329
330fn capture_main(blocks: &[(String, &str, Option<String>, String)]) -> String {
331    let mut mods = String::new();
332    let mut arms = String::new();
333    for (id, _, cfg, _) in blocks {
334        let run = format!("\"{id}\" => run(block_{id}::main),\n");
335        match cfg {
336            Some(pred) => {
337                mods.push_str(&format!("#[cfg({pred})]\nmod block_{id};\n"));
338                arms.push_str(&format!("            #[cfg({pred})]\n            {run}"));
339                arms.push_str(&format!(
340                    "            #[cfg(not({pred}))]\n            \"{id}\" => exit(CAPTURE_DISABLED, &id),\n"
341                ));
342            }
343            None => {
344                mods.push_str(&format!("mod block_{id};\n"));
345                arms.push_str(&format!("            {run}"));
346            }
347        }
348    }
349    let (unknown, unknown_msg) = CAPTURE_UNKNOWN;
350    let (disabled, disabled_msg) = CAPTURE_DISABLED;
351    format!(
352        "{GENERATED_HEADER}\n#![allow(dead_code, unused_imports)]\n\n\
353         use std::process::{{ExitCode, Termination}};\n\n\
354         {VERBATIM}\n\
355         verbatim! {{\n{mods}}}\n\n\
356         const CAPTURE_UNKNOWN: (u8, &str) = ({unknown}, \"{unknown_msg}\");\n\
357         const CAPTURE_DISABLED: (u8, &str) = ({disabled}, \"{disabled_msg}\");\n\n\
358         fn main() -> ExitCode {{\n    \
359             let id = std::env::args().nth(1).unwrap_or_default();\n    \
360             verbatim! {{\n        \
361                 match id.as_str() {{\n{arms}            \
362                     _ => exit(CAPTURE_UNKNOWN, &id),\n        \
363                 }}\n    \
364             }}\n\
365         }}\n\n\
366         fn run<T: Termination>(main: fn() -> T) -> ExitCode {{\n    \
367             main().report()\n\
368         }}\n\n\
369         fn exit((code, sentinel): (u8, &str), id: &str) -> ExitCode {{\n    \
370             eprintln!(\"{{sentinel}} {{id}}\");\n    \
371             ExitCode::from(code)\n\
372         }}\n"
373    )
374}
375
376/// One block as a module whose `pub fn main` the capture example calls.
377fn capture_module(block: &CodeBlock) -> Result<String, String> {
378    let lines: Vec<&str> = block.code.lines().collect();
379    let Some(at) = lines.iter().position(|l| top_level_main(l).is_some()) else {
380        return Ok(format!(
381            "pub fn main() {{\n{}\n}}\n",
382            indent(&block.code, "    ")
383        ));
384    };
385    for (i, line) in lines.iter().enumerate() {
386        let next = lines[i + 1..].iter().find(|l| !l.trim().is_empty());
387        if line.starts_with("#![") && !is_lint_attribute(line) {
388            return Err(
389                "a capture block cannot use a crate-level attribute (`#![...]`) other than a lint level"
390                    .into(),
391            );
392        }
393        if line.starts_with("#[macro_use]") && next.is_some_and(|l| l.starts_with("extern crate")) {
394            return Err("a capture block cannot use `#[macro_use] extern crate`".into());
395        }
396    }
397    let mut out: Vec<String> = lines.iter().map(|l| l.to_string()).collect();
398    if top_level_main(lines[at]) == Some(false) {
399        out[at] = format!("pub {}", lines[at]);
400    }
401    Ok(format!("{}\n", out.join("\n")))
402}
403
404/// Whether an inner attribute only sets lint levels, which a module file may
405/// carry as well as a crate root.
406fn is_lint_attribute(line: &str) -> bool {
407    ["allow", "warn", "deny", "forbid", "expect"]
408        .iter()
409        .any(|lint| {
410            line.strip_prefix("#![")
411                .is_some_and(|a| a.starts_with(&format!("{lint}(")))
412        })
413}
414
415/// For a line declaring a top-level `fn main` (or `async fn main`), whether
416/// it is already `pub`. Indented lines and other items are None.
417fn top_level_main(line: &str) -> Option<bool> {
418    let restricted = line
419        .strip_prefix("pub(")
420        .and_then(|rest| rest.split_once(") ").map(|(_, rest)| rest));
421    let (public, rest) = match restricted.or_else(|| line.strip_prefix("pub ")) {
422        Some(rest) => (true, rest),
423        None => (false, line),
424    };
425    let rest = rest.strip_prefix("async ").unwrap_or(rest);
426    let after = rest.strip_prefix("fn main")?;
427    (!after.starts_with(|c: char| c.is_alphanumeric() || c == '_')).then_some(public)
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433    use crate::markdown;
434
435    #[test]
436    fn page_counts_split_executed_from_compile_only() {
437        let md = "<!-- soothfast:bind item=a::b -->\n```rust\nlet x = 1;\n```\n```rust no_run\nloop {}\n```\n```rust ignore\nx();\n```\n```rust,compile_fail\nbad;\n```\n```rust capture-output\nprintln!(\"h\");\n```\n```console\n$ ls\n```\n";
438        let counts = page_counts(&markdown::scan(md).unwrap());
439        assert_eq!((counts.executed, counts.compile_only), (1, 3));
440        assert_eq!((counts.binds, counts.claims), (1, 0));
441        assert!(!counts.unanchored());
442    }
443
444    #[test]
445    fn a_page_with_no_markers_is_unanchored() {
446        let counts = page_counts(&markdown::scan("```rust\nlet x = 1;\n```\n").unwrap());
447        assert!(counts.unanchored());
448    }
449
450    #[test]
451    fn generates_tests_and_examples() {
452        let md = "```rust\nlet x = 1;\n```\n```rust no_run\nloop {}\n```\n```rust capture-output\nprintln!(\"h\");\n```\n";
453        let doc = markdown::scan(md).unwrap();
454        let tests = test_file("docs/a.md", &doc).unwrap();
455        assert!(tests.contains("#[test]"));
456        assert!(tests.contains("compile-only"));
457        assert!(!tests.contains("println!")); // capture block excluded
458        assert_eq!(capture_ids("docs/a.md", &doc), ["docs_a_1"]);
459    }
460
461    #[test]
462    fn doc_tests_compile_into_one_target_with_a_module_per_page() {
463        let a = markdown::scan("```rust\nlet x = 1;\n```\n").unwrap();
464        let b = markdown::scan("```rust\nlet y = 2;\n```\n").unwrap();
465        let none = markdown::scan("```rust ignore\nnope();\n```\n").unwrap();
466        let set = doc_test_set([
467            ("docs/b.md", &b),
468            ("README.md", &a),
469            ("docs/skip.md", &none),
470        ])
471        .unwrap();
472        let paths: Vec<&str> = set.iter().map(|g| g.path.as_str()).collect();
473        assert_eq!(
474            paths,
475            [
476                "tests/soothfast_docs/main.rs",
477                "tests/soothfast_docs/doc_readme.rs",
478                "tests/soothfast_docs/doc_docs_b.rs"
479            ]
480        );
481        assert!(set[0].content.starts_with(GENERATED_HEADER));
482        assert!(
483            set[0]
484                .content
485                .ends_with("verbatim! {\nmod doc_readme;\nmod doc_docs_b;\n}\n")
486        );
487        assert_eq!(set[1].content, test_file("README.md", &a).unwrap());
488    }
489
490    #[test]
491    fn no_testable_page_means_no_doc_test_target() {
492        let none = markdown::scan("```rust ignore\nnope();\n```\n").unwrap();
493        assert!(doc_test_set([("README.md", &none)]).unwrap().is_empty());
494    }
495
496    #[test]
497    fn two_pages_on_one_module_name_are_an_error_naming_both() {
498        let a = markdown::scan("```rust\nlet x = 1;\n```\n").unwrap();
499        let e = doc_test_set([("docs/a-b.md", &a), ("docs/a_b.md", &a)]).unwrap_err();
500        assert!(
501            e.contains("docs/a-b.md") && e.contains("docs/a_b.md"),
502            "{e}"
503        );
504    }
505
506    #[test]
507    fn owned_places_cover_both_layouts_and_nothing_else() {
508        assert_eq!(
509            owning_target("tests/soothfast_doc_readme.rs"),
510            Some((DOC_TESTS_DIR, true))
511        );
512        assert_eq!(
513            owning_target("tests/soothfast_docs/main.rs"),
514            Some((DOC_TESTS_DIR, false))
515        );
516        assert_eq!(
517            owning_target("examples/soothfast_capture_readme_1.rs"),
518            Some((CAPTURE_DIR, true))
519        );
520        assert_eq!(
521            owning_target("examples/soothfast_capture/block_readme_1.rs"),
522            Some((CAPTURE_DIR, false))
523        );
524        assert_eq!(owning_target("tests/integration.rs"), None);
525        assert_eq!(owning_target("tests/soothfast_docs/data.json"), None);
526        assert_eq!(owning_target("src/soothfast_doc_x.rs"), None);
527    }
528
529    #[test]
530    fn all_ignored_means_no_test_file() {
531        let doc = markdown::scan("```rust ignore\nfictional();\n```\n").unwrap();
532        assert!(test_file("README.md", &doc).is_none());
533    }
534
535    #[test]
536    fn feature_tag_gates_generated_test() {
537        let md =
538            "```rust feature=risk\nlet x = 1;\n```\n```rust no_run feature=risk\nloop {}\n```\n";
539        let doc = markdown::scan(md).unwrap();
540        let tests = test_file("docs/r.md", &doc).unwrap();
541        assert_eq!(tests.matches("#[cfg(feature = \"risk\")]").count(), 2);
542    }
543
544    #[test]
545    fn comma_separated_feature_tag_gates_on_all_of_them() {
546        // A block whose body needs two features to compile — gating on only
547        // the first leaves it enabled, and failing to build, when the second
548        // is off.
549        let md = "```rust no_run feature=risk,polygon\nloop {}\n```\n";
550        let doc = markdown::scan(md).unwrap();
551        let tests = test_file("docs/r.md", &doc).unwrap();
552        assert!(tests.contains("#[cfg(all(feature = \"risk\", feature = \"polygon\"))]"));
553    }
554
555    fn capture(md: &str) -> Vec<Generated> {
556        capture_set([("docs/c.md", &markdown::scan(md).unwrap())]).unwrap()
557    }
558
559    #[test]
560    fn capture_blocks_compile_into_one_example_with_a_module_per_block() {
561        let set = capture(
562            "```rust capture-output\nprintln!(\"a\");\n```\n```rust capture-output\nprintln!(\"b\");\n```\n",
563        );
564        let paths: Vec<&str> = set.iter().map(|g| g.path.as_str()).collect();
565        assert_eq!(
566            paths,
567            [
568                "examples/soothfast_capture/main.rs",
569                "examples/soothfast_capture/block_docs_c_1.rs",
570                "examples/soothfast_capture/block_docs_c_2.rs",
571            ]
572        );
573        let main = &set[0].content;
574        assert!(main.contains("mod block_docs_c_1;\nmod block_docs_c_2;\n"));
575        assert!(main.contains("\"docs_c_2\" => run(block_docs_c_2::main),"));
576        assert!(main.contains("_ => exit(CAPTURE_UNKNOWN, &id),"));
577        assert!(
578            set[1]
579                .content
580                .contains("pub fn main() {\n    println!(\"a\");\n}")
581        );
582        assert_eq!(
583            recorded_source(&set[1].content),
584            Some(("docs/c.md", Some(1)))
585        );
586    }
587
588    #[test]
589    fn no_capture_block_means_no_capture_example() {
590        assert!(capture("```rust\nlet x = 1;\n```\n").is_empty());
591    }
592
593    #[test]
594    fn feature_tag_gates_the_module_and_dispatches_disabled_without_it() {
595        let set = capture("```rust capture-output feature=risk,polygon\nprintln!(\"hi\");\n```\n");
596        let main = &set[0].content;
597        let pred = "all(feature = \"risk\", feature = \"polygon\")";
598        assert!(main.contains(&format!("#[cfg({pred})]\nmod block_docs_c_1;")));
599        assert!(main.contains(&format!(
600            "#[cfg({pred})]\n            \"docs_c_1\" => run(block_docs_c_1::main),"
601        )));
602        assert!(main.contains(&format!(
603            "#[cfg(not({pred}))]\n            \"docs_c_1\" => exit(CAPTURE_DISABLED, &id),"
604        )));
605        assert!(main.contains(
606            "const CAPTURE_DISABLED: (u8, &str) = (3, \"soothfast_capture: disabled block\");"
607        ));
608    }
609
610    #[test]
611    fn a_blocks_own_top_level_main_becomes_pub_and_keeps_its_attributes() {
612        let md = "```rust capture-output\n// fn main is below\nuse std::fmt;\n\n#[tokio::main]\nasync fn main() -> Result<(), Box<dyn std::error::Error>> {\n    fn main_helper() {}\n    Ok(())\n}\n```\n";
613        let block = &capture(md)[1].content;
614        assert!(block.contains("// fn main is below\nuse std::fmt;"));
615        assert!(block.contains("#[tokio::main]\npub async fn main() -> Result<"));
616        assert!(block.contains("    fn main_helper() {}"));
617        assert_eq!(block.matches("fn main(").count(), 1);
618    }
619
620    #[test]
621    fn an_already_pub_main_is_left_alone() {
622        let block = &capture("```rust capture-output\npub fn main() {}\n```\n")[1].content;
623        assert!(block.ends_with("\npub fn main() {}\n"), "{block}");
624    }
625
626    #[test]
627    fn crate_level_attributes_in_a_capture_block_are_an_error() {
628        for code in [
629            "#![feature(test)]\nfn main() {}",
630            "#[macro_use]\nextern crate serde;\nfn main() {}",
631        ] {
632            let doc = markdown::scan(&format!("```rust capture-output\n{code}\n```\n")).unwrap();
633            let e = capture_set([("docs/c.md", &doc)]).unwrap_err();
634            assert!(
635                e.starts_with("docs/c.md line 1: a capture block cannot"),
636                "{e}"
637            );
638        }
639    }
640
641    #[test]
642    fn two_pages_on_one_capture_stem_are_an_error_naming_both() {
643        let a = markdown::scan("```rust capture-output\nlet x = 1;\n```\n").unwrap();
644        let e = capture_set([("docs/a-b.md", &a), ("docs/a_b.md", &a)]).unwrap_err();
645        assert!(
646            e.contains("docs/a-b.md") && e.contains("docs/a_b.md"),
647            "{e}"
648        );
649    }
650
651    #[test]
652    fn recorded_source_reads_page_with_or_without_a_line() {
653        let h = GENERATED_HEADER;
654        assert_eq!(
655            recorded_source(&format!("{h}\n// source: README.md\n")),
656            Some(("README.md", None))
657        );
658        assert_eq!(
659            recorded_source(&format!("{h}\n// source: docs/a line b.md line 41\n")),
660            Some(("docs/a line b.md", Some(41)))
661        );
662        assert_eq!(
663            recorded_source(&format!("{h}\n// source: docs/a line b.md\n")),
664            Some(("docs/a line b.md", None))
665        );
666        assert_eq!(recorded_source(&format!("{h}\nfn main() {{}}\n")), None);
667    }
668
669    #[test]
670    fn a_lint_level_inner_attribute_is_allowed_in_a_capture_block() {
671        for attr in ["allow(dead_code)", "warn(missing_docs)", "expect(unused)"] {
672            let md = format!("```rust capture-output\n#![{attr}]\nfn main() {{}}\n```\n");
673            let block = &capture(&md)[1].content;
674            assert!(
675                block.contains(&format!("#![{attr}]\npub fn main() {{}}")),
676                "{block}"
677            );
678        }
679    }
680
681    #[test]
682    fn a_restricted_visibility_main_is_the_blocks_own_main() {
683        for vis in ["pub(crate)", "pub(super)"] {
684            let md = format!("```rust capture-output\n{vis} fn main() {{}}\n```\n");
685            let block = &capture(&md)[1].content;
686            assert!(
687                block.ends_with(&format!("\n{vis} fn main() {{}}\n")),
688                "{block}"
689            );
690        }
691    }
692
693    #[test]
694    fn only_a_top_level_main_is_called_by_a_doc_test() {
695        let md = "```rust\n// fn main is not here\nfn main_loop() {}\nlet s = \"fn main\";\n```\n```rust\nfn main() {}\n```\n";
696        let tests = test_file("docs/m.md", &markdown::scan(md).unwrap()).unwrap();
697        assert_eq!(tests.matches("    main();").count(), 1, "{tests}");
698    }
699
700    #[test]
701    fn two_blocks_installing_a_global_allocator_are_an_error_naming_both() {
702        let a = markdown::scan("```rust no_run\nsoothfast::bench_main!();\n```\n").unwrap();
703        let b =
704            markdown::scan("```rust no_run\n#[global_allocator]\nstatic A: X = X;\n```\n").unwrap();
705        let e = doc_test_set([("docs/a.md", &a), ("docs/b.md", &b)]).unwrap_err();
706        assert!(
707            e.starts_with("docs/a.md line 1 and docs/b.md line 1 both install"),
708            "{e}"
709        );
710        assert!(doc_test_set([("docs/a.md", &a)]).is_ok());
711    }
712
713    /// Writes `set` under a temp dir and asks rustfmt, in every edition,
714    /// whether it would change the target's `main.rs`.
715    fn assert_rustfmt_leaves_alone(name: &str, set: &[Generated], root: &str) {
716        let dir = std::env::temp_dir().join(format!("soothfast-fmt-{name}-{}", std::process::id()));
717        let _ = std::fs::remove_dir_all(&dir);
718        for g in set {
719            let path = dir.join(&g.path);
720            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
721            std::fs::write(path, &g.content).unwrap();
722        }
723        for edition in ["2015", "2021", "2024"] {
724            let out = std::process::Command::new("rustfmt")
725                .args(["--check", "--edition", edition])
726                .arg(dir.join(root).join("main.rs"))
727                .output()
728                .unwrap();
729            assert!(
730                out.status.success(),
731                "edition {edition}:\n{}",
732                String::from_utf8_lossy(&out.stdout)
733            );
734        }
735        let _ = std::fs::remove_dir_all(&dir);
736    }
737
738    fn rustfmt_present() -> bool {
739        std::process::Command::new("rustfmt")
740            .arg("--version")
741            .output()
742            .is_ok_and(|o| o.status.success())
743    }
744
745    #[test]
746    fn generated_targets_are_already_rustfmt_clean() {
747        if !rustfmt_present() {
748            return;
749        }
750        let long =
751            "docs/library/an_unusually_long_page_name_for_a_reference_section_of_the_library.md";
752        let mut capture_md = String::new();
753        for n in 0..12 {
754            let tag = if n % 3 == 0 {
755                " feature=risk,polygon,indicators,backtesting"
756            } else {
757                ""
758            };
759            capture_md.push_str(&format!(
760                "```rust capture-output{tag}\nprintln!(\"{n}\");\n```\n"
761            ));
762        }
763        let md = format!("```rust\nlet x = 1;\n```\n{capture_md}");
764        let pages: Vec<(&str, Doc)> = [
765            long,
766            "docs/b.md",
767            "docs/a_10.md",
768            "docs/a_2.md",
769            "README.md",
770        ]
771        .into_iter()
772        .map(|p| (p, markdown::scan(&md).unwrap()))
773        .collect();
774        let docs = || pages.iter().map(|(p, d)| (*p, d));
775        assert_rustfmt_leaves_alone("tests", &doc_test_set(docs()).unwrap(), DOC_TESTS_DIR);
776        assert_rustfmt_leaves_alone("capture", &capture_set(docs()).unwrap(), CAPTURE_DIR);
777    }
778}