1#[derive(Debug, Clone, PartialEq)]
6pub enum DirectiveKind {
7 IncludeSymbol,
9 Witness,
11 LeanCheck,
13 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#[derive(Debug, Clone, PartialEq)]
44pub struct Directive {
45 pub kind: DirectiveKind,
47 pub attrs: Vec<(String, String)>,
49 pub body: String,
53 pub byte_range: (usize, usize),
56}
57
58impl Directive {
59 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 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#[derive(Debug)]
80pub struct Scanned<'a> {
81 source: &'a str,
82 blocks: Vec<Block>,
83}
84
85#[derive(Debug)]
87pub enum Block {
88 Text(usize, usize),
90 Directive(Directive),
92}
93
94impl<'a> Scanned<'a> {
95 pub fn blocks(&self) -> &[Block] {
97 &self.blocks
98 }
99
100 pub fn source(&self) -> &'a str {
102 self.source
103 }
104
105 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 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
141pub 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 if let Some(kind) = DirectiveKind::from_info(info).filter(|_| !info.contains('`')) {
162 if cursor > text_start {
164 blocks.push(Block::Text(text_start, cursor));
165 }
166 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 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
206fn 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 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#[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}