Skip to main content

soothfast_docs/
markdown.rs

1//! Line-based markdown scanning: fenced code blocks with info tags, and
2//! `<!-- soothfast:... -->` markers. Deliberately not a markdown AST — we need
3//! fences and comment markers only (dependency policy: no pulldown-cmark).
4
5/// One fenced code block.
6#[derive(Debug, Clone)]
7pub struct CodeBlock {
8    /// 0-based ordinal among ALL fenced blocks in the file.
9    pub index: usize,
10    /// First token of the info string ("rust", "text", "console", ...).
11    pub lang: String,
12    /// Remaining info-string tokens ("no_run", "ignore", "capture-output", ...).
13    pub tags: Vec<String>,
14    pub code: String,
15    /// 1-based line of the opening fence.
16    pub line: usize,
17    /// 1-based line of the closing fence.
18    pub close_line: usize,
19    /// Backtick count of the opening fence.
20    pub ticks: usize,
21}
22
23impl CodeBlock {
24    /// Whether the info string carries `tag`.
25    pub fn has_tag(&self, tag: &str) -> bool {
26        self.tags.iter().any(|t| t == tag)
27    }
28    /// A rust block that should become a generated test.
29    pub fn is_testable_rust(&self) -> bool {
30        self.lang == "rust" && !self.has_tag("ignore") && !self.has_tag("capture-output")
31    }
32    /// A fence rustdoc compiles as Rust: no language, `rust`, or only
33    /// rustdoc attributes, comma-joined (`no_run`, `rust,ignore`).
34    pub fn is_rust_example(&self) -> bool {
35        const RUSTDOC_TAGS: [&str; 7] = [
36            "",
37            "rust",
38            "no_run",
39            "ignore",
40            "should_panic",
41            "compile_fail",
42            "test_harness",
43        ];
44        self.lang
45            .split(',')
46            .all(|t| RUSTDOC_TAGS.contains(&t) || t.starts_with("edition"))
47    }
48    /// A rust block whose output `capture-output` splices into the page.
49    pub fn is_capture(&self) -> bool {
50        self.lang == "rust" && self.has_tag("capture-output")
51    }
52    /// Raw value of a `feature=NAME` tag: the cargo feature the generated test
53    /// is gated behind (for blocks exercising feature-gated API). Callers that
54    /// want the individual features want [`Self::feature_list`] instead.
55    pub fn feature_tag(&self) -> Option<&str> {
56        self.tags.iter().find_map(|t| t.strip_prefix("feature="))
57    }
58    /// Individual features of a `feature=` tag — one, or several
59    /// comma-separated with **no spaces** (`feature=risk,polygon`; a space
60    /// would split into a separate fence tag) when a block needs more than one
61    /// feature to compile. Empty when the block has no `feature=` tag; `scan`
62    /// rejects a tag whose value names no feature.
63    pub fn feature_list(&self) -> Vec<&str> {
64        self.feature_tag()
65            .into_iter()
66            .flat_map(|raw| raw.split(','))
67            .map(str::trim)
68            .filter(|f| !f.is_empty())
69            .collect()
70    }
71    /// The `cfg` predicate gating this block, or None when it has no
72    /// `feature=` tag. Several features become an `all(...)` — every listed
73    /// feature must be on for the block to compile.
74    pub fn feature_cfg(&self) -> Option<String> {
75        match self.feature_list().as_slice() {
76            [] => None,
77            [one] => Some(format!("feature = \"{one}\"")),
78            many => Some(format!(
79                "all({})",
80                many.iter()
81                    .map(|f| format!("feature = \"{f}\""))
82                    .collect::<Vec<_>>()
83                    .join(", ")
84            )),
85        }
86    }
87    /// `(name, arg)` from a `mock=NAME` or `mock=NAME(ARG)` tag — the name of
88    /// a `#[soothfast::mock_seam]` fn this block calls via
89    /// `soothfast::mock::activate(name, arg)`, and its arg (`""` when
90    /// omitted). Requires an accompanying `feature=` tag; enforced in `scan`.
91    pub fn mock_tag(&self) -> Option<(&str, &str)> {
92        let raw = self.tags.iter().find_map(|t| t.strip_prefix("mock="))?;
93        match raw.strip_suffix(')').and_then(|s| s.split_once('(')) {
94            Some((name, arg)) => Some((name, arg)),
95            None => Some((raw, "")),
96        }
97    }
98    /// Raw value of a `covers=path::to::item` tag — one item, or several
99    /// comma-separated with **no spaces** (`covers=a::b,a::c`; a space
100    /// would split into a separate fence tag) when a single example
101    /// demonstrates more than one measured/bound item. A claim or bind for
102    /// any listed item renders attached to this block instead of as a
103    /// standalone chip. Callers that need the individual items should split
104    /// the value on `,` and trim.
105    pub fn covers_tag(&self) -> Option<&str> {
106        self.tags.iter().find_map(|t| t.strip_prefix("covers="))
107    }
108}
109
110/// `<!-- soothfast:bind path::to::item -->`, or several whitespace-separated
111/// targets in one marker.
112#[derive(Debug, Clone)]
113pub struct Bind {
114    pub item: String,
115    pub line: usize,
116}
117
118impl Bind {
119    /// The marker's targets: Rust items or `path#Symbol` file targets.
120    pub fn targets(&self) -> impl Iterator<Item = &str> {
121        self.item.split_whitespace()
122    }
123}
124
125/// `<!-- soothfast:claim item.backend.metric < value -->`
126#[derive(Debug, Clone)]
127pub struct ClaimMarker {
128    pub expr: String,
129    pub line: usize,
130}
131
132/// Everything [`scan`] extracts from one markdown file: fenced code blocks
133/// plus `soothfast:bind` / `soothfast:claim` markers, in document order.
134#[derive(Debug, Default)]
135pub struct Doc {
136    /// Fenced code blocks, with language and tags.
137    pub blocks: Vec<CodeBlock>,
138    /// `<!-- soothfast:bind ... -->` markers.
139    pub binds: Vec<Bind>,
140    /// `<!-- soothfast:claim ... -->` markers.
141    pub claims: Vec<ClaimMarker>,
142}
143
144/// Scan one markdown text. Closing markers (`<!-- /soothfast:... -->`) are
145/// structural for readers and ignored here. Errs on an unclosed fence:
146/// dropping it would silently swallow the block and every later marker.
147pub fn scan(text: &str) -> Result<Doc, String> {
148    let mut doc = Doc::default();
149    let mut fence: Option<(usize, String, Vec<String>, String, usize)> = None; // (ticks, lang, tags, code, line)
150
151    for (i, line) in text.lines().enumerate() {
152        let lineno = i + 1;
153        let trimmed = line.trim_start();
154
155        if let Some((ticks, lang, tags, code, open_line)) = fence.take() {
156            let closes = trimmed.chars().take_while(|&c| c == '`').count() >= ticks
157                && trimmed.trim_end().chars().all(|c| c == '`');
158            if closes {
159                doc.blocks.push(CodeBlock {
160                    index: doc.blocks.len(),
161                    lang,
162                    tags,
163                    code,
164                    line: open_line,
165                    close_line: lineno,
166                    ticks,
167                });
168            } else {
169                let mut code = code;
170                code.push_str(line);
171                code.push('\n');
172                fence = Some((ticks, lang, tags, code, open_line));
173            }
174            continue;
175        }
176
177        let ticks = trimmed.chars().take_while(|&c| c == '`').count();
178        if ticks >= 3 {
179            let info = trimmed[ticks..].trim();
180            let mut tokens = info.split_whitespace().map(str::to_string);
181            let lang = tokens.next().unwrap_or_default();
182            fence = Some((ticks, lang, tokens.collect(), String::new(), lineno));
183            continue;
184        }
185
186        // A marker the scanner declines to read is a claim nothing gates, so
187        // every failure below is an error rather than a `continue`.
188        if let Some(rest) = trimmed.trim_end().strip_prefix("<!-- soothfast:") {
189            let body = rest
190                .strip_suffix("-->")
191                .map(str::trim)
192                .ok_or_else(|| format!("unterminated soothfast marker at line {lineno}"))?;
193            if let Some(item) = body.strip_prefix("bind ") {
194                doc.binds.push(Bind {
195                    item: item.trim().to_string(),
196                    line: lineno,
197                });
198            } else if let Some(expr) = body.strip_prefix("claim ") {
199                doc.claims.push(ClaimMarker {
200                    expr: expr.trim().to_string(),
201                    line: lineno,
202                });
203            } else {
204                return Err(format!(
205                    "unknown soothfast marker at line {lineno}: expected `bind <item>` or `claim <expr>`"
206                ));
207            }
208        }
209    }
210    if let Some((_, _, _, _, open_line)) = fence {
211        return Err(format!("unclosed code fence opened at line {open_line}"));
212    }
213    for block in &doc.blocks {
214        if block.mock_tag().is_some() && block.feature_tag().is_none() {
215            return Err(format!(
216                "mock=NAME requires an accompanying feature=NAME tag (block opened at line {})",
217                block.line
218            ));
219        }
220        // A tag that names no feature would silently generate an ungated
221        // block, which is exactly what the tag was written to prevent.
222        if block.feature_tag().is_some() && block.feature_list().is_empty() {
223            return Err(format!(
224                "feature= tag names no feature (block opened at line {})",
225                block.line
226            ));
227        }
228    }
229    Ok(doc)
230}
231
232/// Info string of the generated output fence (fence length varies).
233const OUTPUT_INFO: &str = "text soothfast-output";
234
235/// Replace (or insert) the `text soothfast-output` fence that follows the
236/// `nth` capture-output block (0-based among capture blocks). Ok(None) when
237/// the capture block wasn't found; Err on malformed markdown.
238pub fn splice_output(
239    text: &str,
240    nth_capture: usize,
241    output: &str,
242) -> Result<Option<String>, String> {
243    // Consuming scan() keeps capture indices in lockstep with gen-tests;
244    // a second ad-hoc fence parser here desynced them in the past.
245    let doc = scan(text)?;
246    let Some(block) = doc
247        .blocks
248        .iter()
249        .filter(|b| b.is_capture())
250        .nth(nth_capture)
251    else {
252        return Ok(None);
253    };
254    let lines: Vec<&str> = text.lines().collect();
255    Ok(Some(splice_after(&lines, block.close_line - 1, output)))
256}
257
258fn splice_after(lines: &[&str], close_idx: usize, output: &str) -> String {
259    // The fence must outrun any backtick run in the output, or the block
260    // would close early and every re-splice would duplicate its tail.
261    let max_run = output
262        .lines()
263        .map(|l| l.trim_start().chars().take_while(|&c| c == '`').count())
264        .max()
265        .unwrap_or(0);
266    let fence = "`".repeat((max_run + 1).max(3));
267
268    let mut out: Vec<String> = lines[..=close_idx].iter().map(|s| s.to_string()).collect();
269
270    // Skip an existing output fence (allowing one blank line between),
271    // honoring its exact opening length so removal is exact.
272    let mut rest_start = close_idx + 1;
273    let mut peek = rest_start;
274    if peek < lines.len() && lines[peek].trim().is_empty() {
275        peek += 1;
276    }
277    if peek < lines.len() {
278        let t = lines[peek].trim_start();
279        let open_ticks = t.chars().take_while(|&c| c == '`').count();
280        if open_ticks >= 3 && t[open_ticks..].trim() == OUTPUT_INFO {
281            let mut k = peek + 1;
282            while k < lines.len() {
283                let c = lines[k].trim_start();
284                if c.chars().take_while(|&ch| ch == '`').count() >= open_ticks
285                    && c.trim_end().chars().all(|ch| ch == '`')
286                {
287                    break;
288                }
289                k += 1;
290            }
291            rest_start = k + 1;
292        }
293    }
294
295    out.push(String::new());
296    out.push(format!("{fence}{OUTPUT_INFO}"));
297    for l in output.trim_end().lines() {
298        out.push(l.to_string());
299    }
300    out.push(fence);
301    for l in &lines[rest_start.min(lines.len())..] {
302        out.push(l.to_string());
303    }
304    let mut s = out.join("\n");
305    s.push('\n');
306    s
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    #[test]
314    fn rust_examples_are_fences_rustdoc_compiles() {
315        let doc = scan(
316            "```
317a
318```
319```rust
320b
321```
322```no_run
323c
324```
325```rust,edition2021
326d
327```
328```text
329e
330```
331```toml
332f
333```
334",
335        )
336        .unwrap();
337        let rust: Vec<_> = doc.blocks.iter().map(CodeBlock::is_rust_example).collect();
338        assert_eq!(rust, [true, true, true, true, false, false]);
339    }
340
341    const MD: &str = "\
342# T
343
344<!-- soothfast:bind demo::sorted -->
345prose
346<!-- /soothfast:bind -->
347
348```rust
349let x = 1;
350```
351
352<!-- soothfast:claim demo::f.perfcnt.instructions < 100 -->
353
354```rust no_run
355loop {}
356```
357
358```rust capture-output
359println!(\"hi\");
360```
361
362```text
363not rust
364```
365";
366
367    #[test]
368    fn scans_blocks_binds_claims() {
369        let doc = scan(MD).unwrap();
370        assert_eq!(doc.blocks.len(), 4);
371        assert_eq!(doc.binds.len(), 1);
372        assert_eq!(doc.binds[0].item, "demo::sorted");
373        assert_eq!(doc.claims.len(), 1);
374        assert!(doc.blocks[0].is_testable_rust());
375        assert!(doc.blocks[1].has_tag("no_run"));
376        assert!(doc.blocks[2].is_capture());
377        assert_eq!(doc.blocks[3].lang, "text");
378    }
379
380    #[test]
381    fn trailing_whitespace_still_reads_the_marker() {
382        let doc = scan("<!-- soothfast:claim demo::f.alloc == 0 -->  \n").unwrap();
383        assert_eq!(doc.claims.len(), 1);
384        assert_eq!(doc.claims[0].expr, "demo::f.alloc == 0");
385    }
386
387    #[test]
388    fn scan_errors_on_a_marker_it_cannot_read() {
389        assert!(scan("<!-- soothfast:claim demo::f.alloc == 0\n").is_err());
390        assert!(scan("<!-- soothfast:clam demo::f.alloc == 0 -->\n").is_err());
391    }
392
393    #[test]
394    fn splice_inserts_then_replaces() {
395        let once = splice_output(MD, 0, "hi").unwrap().unwrap();
396        assert!(once.contains("```text soothfast-output\nhi\n```"));
397        // Re-splicing with new output replaces, not duplicates.
398        let twice = splice_output(&once, 0, "bye").unwrap().unwrap();
399        assert_eq!(twice.matches("soothfast-output").count(), 1);
400        assert!(twice.contains("bye"));
401        assert!(!twice.contains("\nhi\n"));
402    }
403
404    #[test]
405    fn scan_errors_on_unclosed_fence() {
406        let err = scan("# T\n\n```rust\nlet x = 1;\n").unwrap_err();
407        assert!(err.contains("line 3"), "{err}");
408        // Markers after the open fence must not be silently consumed.
409        let err = scan("```text\n<!-- soothfast:bind demo::f -->\n").unwrap_err();
410        assert!(err.contains("unclosed"), "{err}");
411    }
412
413    #[test]
414    fn splice_errors_on_unclosed_fence_instead_of_panicking() {
415        let md = "```rust capture-output\nprintln!(\"hi\");\n";
416        let err = splice_output(md, 0, "hi").unwrap_err();
417        assert!(err.contains("unclosed"), "{err}");
418    }
419
420    #[test]
421    fn mock_tag_parses_name_and_optional_arg() {
422        let md =
423            "```rust capture-output feature=test-utils mock=fmp_profile(AAPL)\nlet x = 1;\n```\n";
424        let doc = scan(md).unwrap();
425        assert_eq!(doc.blocks[0].mock_tag(), Some(("fmp_profile", "AAPL")));
426
427        let md_no_arg =
428            "```rust capture-output feature=test-utils mock=fmp_profile\nlet x = 1;\n```\n";
429        let doc_no_arg = scan(md_no_arg).unwrap();
430        assert_eq!(doc_no_arg.blocks[0].mock_tag(), Some(("fmp_profile", "")));
431    }
432
433    #[test]
434    fn scan_errors_when_mock_tag_lacks_feature_tag() {
435        let md = "```rust capture-output mock=fmp_profile\nlet x = 1;\n```\n";
436        let err = scan(md).unwrap_err();
437        assert!(err.contains("feature=NAME"), "{err}");
438    }
439
440    #[test]
441    fn feature_list_splits_on_commas() {
442        let doc = scan("```rust feature=risk,polygon\nlet x = 1;\n```\n").unwrap();
443        assert_eq!(doc.blocks[0].feature_list(), ["risk", "polygon"]);
444        let doc = scan("```rust feature=risk\nlet x = 1;\n```\n").unwrap();
445        assert_eq!(doc.blocks[0].feature_list(), ["risk"]);
446        assert!(
447            scan("```rust\nlet x = 1;\n```\n").unwrap().blocks[0]
448                .feature_list()
449                .is_empty()
450        );
451    }
452
453    #[test]
454    fn a_bind_splits_into_whitespace_separated_targets() {
455        let doc = scan(
456            "<!-- soothfast:bind corvid_mime::parse_headers  client/Headers.kt#Headers.parse -->\n",
457        )
458        .unwrap();
459        let targets: Vec<&str> = doc.binds[0].targets().collect();
460        assert_eq!(
461            targets,
462            [
463                "corvid_mime::parse_headers",
464                "client/Headers.kt#Headers.parse"
465            ]
466        );
467    }
468
469    #[test]
470    fn scan_errors_when_feature_tag_names_no_feature() {
471        // Silently generating an ungated block would defeat the tag.
472        let err = scan("```rust feature=\nlet x = 1;\n```\n").unwrap_err();
473        assert!(err.contains("names no feature"), "{err}");
474        let err = scan("```rust feature=,,\nlet x = 1;\n```\n").unwrap_err();
475        assert!(err.contains("names no feature"), "{err}");
476    }
477
478    #[test]
479    fn scan_keeps_a_file_symbol_bind_target_whole() {
480        let doc =
481            scan("<!-- soothfast:bind web/my-app/util.test.tsx#Foo.Companion.bar -->\n").unwrap();
482        assert_eq!(
483            doc.binds[0].item,
484            "web/my-app/util.test.tsx#Foo.Companion.bar"
485        );
486    }
487
488    #[test]
489    fn splice_missing_capture_block_is_none() {
490        assert!(splice_output("prose only\n", 0, "hi").unwrap().is_none());
491    }
492
493    #[test]
494    fn splice_is_idempotent_when_output_contains_backtick_fences() {
495        let md = "```rust capture-output\nprintln!(\"```\");\n```\n\ntail prose\n";
496        let out = "before\n```\nafter";
497        let once = splice_output(md, 0, out).unwrap().unwrap();
498        // Output containing ``` forces a longer surrounding fence.
499        assert!(once.contains("````text soothfast-output\nbefore\n```\nafter\n````"));
500        let twice = splice_output(&once, 0, out).unwrap().unwrap();
501        assert_eq!(once, twice, "second splice must be a no-op");
502        // Replacing with new output removes the old block exactly once.
503        let replaced = splice_output(&once, 0, "plain").unwrap().unwrap();
504        assert_eq!(replaced.matches("soothfast-output").count(), 1);
505        assert_eq!(replaced.matches("tail prose").count(), 1);
506        assert!(!replaced.contains("before"));
507    }
508}