Skip to main content

docs_compiler/
fences.rs

1//! Fence scanning: find directive fences in markdown, parse attributes.
2
3/// The four directive fences this compiler resolves. Island fences are
4/// not here: docs-core renders those natively.
5#[derive(Debug, Clone, PartialEq)]
6pub enum DirectiveKind {
7    /// `include-symbol file=... symbol=...`
8    IncludeSymbol,
9    /// `witness wasm=... [fuel=...] [assert_exit=...] [assert_stdout=...]`
10    Witness,
11    /// `lean-check file=... theorem=... toolchain=...`
12    LeanCheck,
13    /// `d2` + body: a D2 diagram rendered to static SVG at build time.
14    Diagram,
15}
16
17impl DirectiveKind {
18    fn label(&self) -> &'static str {
19        match self {
20            Self::IncludeSymbol => "include-symbol",
21            Self::Witness => "witness",
22            Self::LeanCheck => "lean-check",
23            Self::Diagram => "d2",
24        }
25    }
26
27    fn from_info(info: &str) -> Option<Self> {
28        if info.starts_with("include-symbol") {
29            Some(Self::IncludeSymbol)
30        } else if info.starts_with("witness") {
31            Some(Self::Witness)
32        } else if info.starts_with("lean-check") {
33            Some(Self::LeanCheck)
34        } else if info.starts_with("d2") {
35            Some(Self::Diagram)
36        } else {
37            None
38        }
39    }
40}
41
42/// One resolved directive fence.
43#[derive(Debug, Clone, PartialEq)]
44pub struct Directive {
45    /// Which fence this is.
46    pub kind: DirectiveKind,
47    /// Parsed `key=value` attributes (quotes stripped, order preserved).
48    pub attrs: Vec<(String, String)>,
49    /// The fence body: everything between the opening and closing fence
50    /// lines, verbatim. (File-reading directives ignore it; body-driven
51    /// directives like `d2` own it.)
52    pub body: String,
53    /// Byte range of the whole fence (opening line through closing
54    /// triple-backtick), into the original source.
55    pub byte_range: (usize, usize),
56}
57
58impl Directive {
59    /// The value of an attribute, by key.
60    pub fn attr(&self, key: &str) -> Option<&str> {
61        self.attrs
62            .iter()
63            .find(|(k, _)| k == key)
64            .map(|(_, v)| v.as_str())
65    }
66
67    /// The value of a required attribute, or a typed failure reason.
68    pub fn require(&self, key: &str) -> Result<&str, crate::CompilerError> {
69        self.attr(key)
70            .ok_or_else(|| crate::CompilerError::Attribute {
71                directive: self.kind.label(),
72                reason: format!("missing required attribute `{key}`"),
73            })
74    }
75}
76
77/// A scanned source: raw markdown segments and directive fences, in
78/// document order.
79#[derive(Debug)]
80pub struct Scanned<'a> {
81    source: &'a str,
82    blocks: Vec<Block>,
83}
84
85/// A scanned source block: raw markdown text or a directive fence.
86#[derive(Debug)]
87pub enum Block {
88    /// Raw markdown text, byte range into the source.
89    Text(usize, usize),
90    /// A resolved-ready directive fence.
91    Directive(Directive),
92}
93
94impl<'a> Scanned<'a> {
95    /// All blocks in document order.
96    pub fn blocks(&self) -> &[Block] {
97        &self.blocks
98    }
99
100    /// The original source.
101    pub fn source(&self) -> &'a str {
102        self.source
103    }
104
105    /// Byte range of a block.
106    pub fn range(block: &Block) -> (usize, usize) {
107        match block {
108            Block::Text(start, end) => (*start, *end),
109            Block::Directive(d) => d.byte_range,
110        }
111    }
112
113    /// Rebuild the source with every directive fence replaced by the
114    /// output of `resolve` (raw HTML blocks; docs-core passes raw HTML
115    /// through unchanged).
116    pub fn substitute<F>(&self, mut resolve: F) -> Result<String, crate::CompilerError>
117    where
118        F: FnMut(&Directive) -> Result<String, crate::CompilerError>,
119    {
120        let mut out = String::with_capacity(self.source.len());
121        let mut cursor = 0usize;
122        for block in &self.blocks {
123            let (start, end) = Self::range(block);
124            out.push_str(self.source.get(cursor..start).unwrap_or_default());
125            match block {
126                Block::Text(..) => {
127                    out.push_str(self.source.get(start..end).unwrap_or_default());
128                }
129                Block::Directive(d) => {
130                    out.push_str(&resolve(d)?);
131                    out.push_str("\n\n");
132                }
133            }
134            cursor = end;
135        }
136        out.push_str(self.source.get(cursor..).unwrap_or_default());
137        Ok(out)
138    }
139}
140
141/// Scan markdown for directive fences. Unrecognized fences (plain code,
142/// islands) are left as raw text for docs-core.
143pub fn scan(source: &str) -> Scanned<'_> {
144    let mut blocks: Vec<Block> = Vec::new();
145    let bytes = source.as_bytes();
146    let mut cursor = 0usize;
147    let mut text_start = 0usize;
148
149    while cursor < bytes.len() {
150        let line_end = source[cursor..]
151            .find('\n')
152            .map(|p| cursor + p)
153            .unwrap_or(bytes.len());
154        let line = source.get(cursor..line_end).unwrap_or_default();
155        let trimmed = line.trim_start();
156        if let Some(rest) = trimmed.strip_prefix("```") {
157            let info = rest.trim();
158            // CommonMark: a fence's info string cannot contain backticks;
159            // a line like ```lang x``` is not a valid opening fence, and
160            // treating it as one would swallow the rest of the document.
161            if let Some(kind) = DirectiveKind::from_info(info).filter(|_| !info.contains('`')) {
162                // Flush pending text up to the fence opening.
163                if cursor > text_start {
164                    blocks.push(Block::Text(text_start, cursor));
165                }
166                // Find the closing fence line.
167                let mut close = None;
168                let mut scan = line_end + 1;
169                while scan <= bytes.len() {
170                    let e = source[scan..]
171                        .find('\n')
172                        .map(|p| scan + p)
173                        .unwrap_or(bytes.len());
174                    if source.get(scan..e).unwrap_or_default().trim() == "```" {
175                        close = Some((scan, e));
176                        break;
177                    }
178                    scan = e + 1;
179                }
180                let (close_start, close_end) = close.unwrap_or((bytes.len(), bytes.len()));
181                // The body is everything between the opening line and the
182                // closing fence line, verbatim.
183                let body = source
184                    .get(line_end + 1..close_start)
185                    .unwrap_or_default()
186                    .to_string();
187                blocks.push(Block::Directive(Directive {
188                    kind,
189                    attrs: parse_attrs(info),
190                    body,
191                    byte_range: (cursor, close_end),
192                }));
193                cursor = close_end;
194                text_start = close_end;
195                continue;
196            }
197        }
198        cursor = line_end + 1;
199    }
200    if text_start < bytes.len() {
201        blocks.push(Block::Text(text_start, bytes.len()));
202    }
203    Scanned { source, blocks }
204}
205
206/// Parse `key=value` / `key="value with spaces"` tokens from a fence
207/// info string, after the directive word. Order preserved, duplicates
208/// keep their first value.
209fn parse_attrs(info: &str) -> Vec<(String, String)> {
210    let mut attrs = Vec::new();
211    let rest = match info.find(char::is_whitespace) {
212        Some(pos) => &info[pos..],
213        None => "",
214    };
215    let mut tokens = rest.split_whitespace();
216    while let Some(token) = tokens.next() {
217        let Some(eq) = token.find('=') else {
218            continue;
219        };
220        let Some(key) = token.get(..eq) else {
221            continue;
222        };
223        let Some(mut value) = token.get(eq + 1..).map(str::to_string) else {
224            continue;
225        };
226        if value.starts_with('"') && !value.ends_with('"') {
227            // Quoted value with spaces: keep consuming tokens.
228            for cont in tokens.by_ref() {
229                value.push(' ');
230                value.push_str(cont);
231                if cont.ends_with('"') {
232                    break;
233                }
234            }
235        }
236        let value = value.trim_matches('"').to_string();
237        if !attrs.iter().any(|(k, _)| k == key) {
238            attrs.push((key.to_string(), value));
239        }
240    }
241    attrs
242}
243
244#[cfg(test)]
245// Test-only lifts (docs-core decoder-pattern precedent): assertions index
246// on purpose; the library paths keep the denies.
247#[allow(clippy::indexing_slicing)]
248mod tests {
249    use super::*;
250
251    #[test]
252    fn finds_directive_fences_and_keeps_other_fences() {
253        let md = "intro\n\n```include-symbol file=\"a.rs\" symbol=\"x\"\ncode here\n```\n\n\
254                  ```rust\nfn plain() {}\n```\n\n```witness wasm=\"m.wasm\" fuel=1000\nbody\n```\n";
255        let scanned = scan(md);
256        let directives: Vec<&Directive> = scanned
257            .blocks()
258            .iter()
259            .filter_map(|b| match b {
260                Block::Directive(d) => Some(d),
261                _ => None,
262            })
263            .collect();
264        assert_eq!(directives.len(), 2);
265        assert_eq!(directives[0].kind, DirectiveKind::IncludeSymbol);
266        assert_eq!(
267            directives[0].attr("file"),
268            Some("a.rs"),
269            "quoted value unquoted"
270        );
271        assert_eq!(directives[1].kind, DirectiveKind::Witness);
272        assert_eq!(directives[1].attr("fuel"), Some("1000"));
273    }
274
275    #[test]
276    fn quoted_values_with_spaces_stay_one_value() {
277        let attrs = parse_attrs("witness assert_stdout=\"hello world\" fuel=5");
278        assert_eq!(
279            attrs,
280            vec![
281                ("assert_stdout".to_string(), "hello world".to_string()),
282                ("fuel".to_string(), "5".to_string()),
283            ]
284        );
285    }
286}