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