Skip to main content

docs_compiler/
directives.rs

1//! Directive resolution and static HTML emission.
2
3use std::path::PathBuf;
4
5use docs_symbols::Language;
6use docs_witness::{check, run, Assertions, WitnessConfig};
7
8use crate::d2::diagram;
9use crate::error::CompilerError;
10use crate::fences::{Directive, DirectiveKind};
11use crate::lean::lean_check;
12
13/// The build context: directive file paths resolve against this root.
14#[derive(Debug, Clone)]
15pub struct BuildContext {
16    /// Repository/docs root (fence paths are relative to it).
17    pub root: PathBuf,
18}
19
20impl BuildContext {
21    /// A context rooted at `root`.
22    pub fn new(root: impl Into<PathBuf>) -> Self {
23        Self { root: root.into() }
24    }
25
26    fn read(&self, path: &str) -> Result<Vec<u8>, CompilerError> {
27        let full = self.root.join(path);
28        std::fs::read(&full).map_err(|source| CompilerError::Io {
29            path: path.to_string(),
30            source,
31        })
32    }
33
34    pub(crate) fn read_text(&self, path: &str) -> Result<String, CompilerError> {
35        let bytes = self.read(path)?;
36        String::from_utf8(bytes).map_err(|_| CompilerError::Io {
37            path: path.to_string(),
38            source: std::io::Error::new(std::io::ErrorKind::InvalidData, "file is not valid UTF-8"),
39        })
40    }
41}
42
43/// Resolve one directive fence to a raw HTML block.
44pub fn resolve(d: &Directive, ctx: &BuildContext) -> Result<String, CompilerError> {
45    match d.kind {
46        DirectiveKind::IncludeSymbol => include_symbol(d, ctx),
47        DirectiveKind::Witness => witness(d, ctx),
48        DirectiveKind::LeanCheck => lean_check(d, ctx),
49        DirectiveKind::Diagram => diagram(d, ctx),
50    }
51}
52
53/// `include-symbol file=... symbol=... [lang=rust]`
54fn include_symbol(d: &Directive, ctx: &BuildContext) -> Result<String, CompilerError> {
55    let file = d.require("file")?;
56    let symbol = d.require("symbol")?;
57    let lang = match d.attr("lang").unwrap_or("rust") {
58        "rust" => Language::Rust,
59        other => {
60            return Err(CompilerError::Attribute {
61                directive: "include-symbol",
62                reason: format!("unsupported language `{other}` (0.1 ships rust)"),
63            })
64        }
65    };
66    let source = ctx.read_text(file)?;
67    let span = docs_symbols::extract(&source, lang, symbol).map_err(CompilerError::Symbol)?;
68    Ok(format!(
69        "<figure class=\"docs-symbol\" data-anchor=\"{anchor}\"><figcaption>{file} :: {symbol}</figcaption><pre><code>{code}</code></pre></figure>",
70        anchor = span.anchor_id,
71        code = html_escape(&span.code),
72    ))
73}
74
75/// `witness wasm=... [fuel=...] [stdout_capacity=...] [assert_exit=...]
76/// [assert_stdout="..."]`
77fn witness(d: &Directive, ctx: &BuildContext) -> Result<String, CompilerError> {
78    let wasm_path = d.require("wasm")?;
79    let wasm = ctx.read(wasm_path)?;
80    let cfg = WitnessConfig {
81        fuel: d
82            .attr("fuel")
83            .and_then(|v| v.parse().ok())
84            .unwrap_or(docs_witness::DEFAULT_FUEL),
85        stdout_capacity: d
86            .attr("stdout_capacity")
87            .and_then(|v| v.parse().ok())
88            .unwrap_or(docs_witness::DEFAULT_STDOUT_CAPACITY),
89    };
90    let w = run(&wasm, &cfg).map_err(CompilerError::Witness)?;
91    let assertions = Assertions {
92        exit: d.attr("assert_exit").and_then(|v| v.parse().ok()),
93        stdout: d.attr("assert_stdout").map(str::to_string),
94    };
95    check(&w, &assertions).map_err(CompilerError::WitnessAssert)?;
96
97    Ok(format!(
98        "<div class=\"docs-witness\" data-exit=\"{exit}\" data-fuel=\"{fuel}\"><pre class=\"docs-witness-stdout\">{stdout}</pre></div>",
99        exit = w.exit,
100        fuel = w.fuel_consumed,
101        stdout = html_escape(&String::from_utf8_lossy(&w.stdout)),
102    ))
103}
104
105/// First few lines of a diagnostics blob, for error messages.
106pub(crate) fn first_lines(text: &str) -> String {
107    let collected: Vec<&str> = text
108        .lines()
109        .filter(|l| !l.trim().is_empty())
110        .take(3)
111        .collect();
112    collected.join(" | ")
113}
114
115/// Minimal HTML text escaping: `&`, `<`, `>`; blank-line guard included
116/// (an empty line inside a raw-HTML block would end the block in
117/// pulldown-cmark, so interior double newlines gain a zero-width entity
118/// line).
119pub(crate) fn html_escape(text: &str) -> String {
120    let escaped = text
121        .replace('&', "&amp;")
122        .replace('<', "&lt;")
123        .replace('>', "&gt;");
124    escaped.replace("\n\n", "\n&#10;\n")
125}