Skip to main content

work_graph/
extract.rs

1//! Grounded ALL_BOUND / catalog extract. Parses tree text — does not invent ids.
2
3use std::collections::BTreeMap;
4use std::fmt;
5
6use crate::model::FamilyNode;
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum ExtractError {
10    MissingAllBound,
11    MissingCatalog,
12    Unresolved { names: Vec<String> },
13}
14
15impl fmt::Display for ExtractError {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        match self {
18            ExtractError::MissingAllBound => write!(f, "ALL_BOUND array not found"),
19            ExtractError::MissingCatalog => write!(f, "ALL_INVOKE_IDS array not found"),
20            ExtractError::Unresolved { names } => {
21                write!(f, "ALL_BOUND names had no string literal: {names:?}")
22            }
23        }
24    }
25}
26
27impl std::error::Error for ExtractError {}
28
29/// `pub const NAME: &str = "Family.method";` including a wrapped literal line.
30pub fn parse_str_consts(src: &str) -> BTreeMap<String, String> {
31    let mut out = BTreeMap::new();
32    let bytes = src.as_bytes();
33    let mut i = 0;
34    while i < bytes.len() {
35        let rest = &src[i..];
36        let Some(rel) = rest.find("pub const ") else {
37            break;
38        };
39        i += rel + "pub const ".len();
40        let ident = take_ident(&src[i..]);
41        if ident.is_empty() {
42            continue;
43        }
44        i += ident.len();
45        let after = skip_ws(&src[i..]);
46        i += src[i..].len() - after.len();
47        if !after.starts_with(": &str") {
48            continue;
49        }
50        i += ": &str".len();
51        let after = skip_ws(&src[i..]);
52        i += src[i..].len() - after.len();
53        if !after.starts_with('=') {
54            continue;
55        }
56        i += 1;
57        let after = skip_ws(&src[i..]);
58        i += src[i..].len() - after.len();
59        if !after.starts_with('"') {
60            continue;
61        }
62        i += 1;
63        if let Some((lit, consumed)) = take_string_lit(&src[i..]) {
64            out.insert(ident.to_string(), lit);
65            i += consumed;
66        }
67    }
68    out
69}
70
71/// Resolve `ALL_BOUND` const names to `Family.method` strings.
72pub fn extract_all_bound(src: &str) -> Result<Vec<String>, ExtractError> {
73    let consts = parse_str_consts(src);
74    let names = parse_slice_idents(src, "ALL_BOUND").ok_or(ExtractError::MissingAllBound)?;
75    let mut unresolved = Vec::new();
76    let mut ids = Vec::new();
77    for name in names {
78        match consts.get(&name) {
79            Some(id) => ids.push(id.clone()),
80            None => unresolved.push(name),
81        }
82    }
83    if !unresolved.is_empty() {
84        return Err(ExtractError::Unresolved { names: unresolved });
85    }
86    ids.sort();
87    ids.dedup();
88    Ok(ids)
89}
90
91/// Quoted strings inside `ALL_INVOKE_IDS`.
92pub fn extract_catalog_ids(src: &str) -> Result<Vec<String>, ExtractError> {
93    let ids = parse_slice_strings(src, "ALL_INVOKE_IDS").ok_or(ExtractError::MissingCatalog)?;
94    let mut ids = ids;
95    ids.sort();
96    ids.dedup();
97    Ok(ids)
98}
99
100/// Families from IDs.
101pub fn families_from_ids(ids: &[String]) -> Vec<FamilyNode> {
102    let mut counts: BTreeMap<String, u32> = BTreeMap::new();
103    for id in ids {
104        if let Some(fam) = family_of(id) {
105            *counts.entry(fam.to_string()).or_insert(0) += 1;
106        }
107    }
108    counts
109        .into_iter()
110        .map(|(name, member_count)| FamilyNode { name, member_count })
111        .collect()
112}
113
114/// Family of an item.
115pub fn family_of(id: &str) -> Option<&str> {
116    let dot = id.find('.')?;
117    if dot == 0 {
118        return None;
119    }
120    Some(&id[..dot])
121}
122
123/// Exact `Family.method` (or longer dotted) strings found in a doc page.
124pub fn cited_invoke_ids(text: &str, invoke_ids: &[String]) -> Vec<String> {
125    let mut found = Vec::new();
126    for id in invoke_ids {
127        if text.contains(id.as_str()) {
128            found.push(id.clone());
129        }
130    }
131    found
132}
133
134/// Family cite only when the catalog prefix `Family.` appears (avoids bare-word hits).
135pub fn cited_families(text: &str, families: &[String]) -> Vec<String> {
136    let mut found = Vec::new();
137    for fam in families {
138        let prefix = format!("{fam}.");
139        if text.contains(&prefix) {
140            found.push(fam.clone());
141        }
142    }
143    found
144}
145
146fn parse_slice_idents(src: &str, const_name: &str) -> Option<Vec<String>> {
147    let body = slice_body(src, const_name)?;
148    let mut names = Vec::new();
149    let mut i = 0;
150    let bytes = body.as_bytes();
151    while i < bytes.len() {
152        if body[i..].starts_with("//") {
153            if let Some(nl) = body[i..].find('\n') {
154                i += nl + 1;
155                continue;
156            }
157            break;
158        }
159        let c = bytes[i];
160        if is_ident_start(c) {
161            let ident = take_ident(&body[i..]);
162            names.push(ident.to_string());
163            i += ident.len();
164            continue;
165        }
166        i += 1;
167    }
168    Some(names)
169}
170
171fn parse_slice_strings(src: &str, const_name: &str) -> Option<Vec<String>> {
172    let body = slice_body(src, const_name)?;
173    let mut ids = Vec::new();
174    let mut i = 0;
175    while i < body.len() {
176        if body[i..].starts_with("//") {
177            if let Some(nl) = body[i..].find('\n') {
178                i += nl + 1;
179                continue;
180            }
181            break;
182        }
183        if body.as_bytes()[i] == b'"' {
184            i += 1;
185            if let Some((lit, consumed)) = take_string_lit(&body[i..]) {
186                ids.push(lit);
187                i += consumed;
188                continue;
189            }
190        }
191        i += 1;
192    }
193    Some(ids)
194}
195
196fn slice_body<'a>(src: &'a str, const_name: &str) -> Option<&'a str> {
197    let needle = format!("pub const {const_name}");
198    let start = src.find(&needle)?;
199    let after = &src[start + needle.len()..];
200    let open = after
201        .find("=[")
202        .or_else(|| after.find("= ["))
203        .or_else(|| after.find("= &["))?;
204    let after_eq = &after[open..];
205    let bracket = after_eq.find('[')?;
206    let inner_start = start + needle.len() + open + bracket + 1;
207    let rest = &src[inner_start..];
208    let close = find_slice_close(rest)?;
209    Some(&rest[..close])
210}
211
212fn find_slice_close(rest: &str) -> Option<usize> {
213    rest.find("];")
214}
215
216fn take_ident(s: &str) -> &str {
217    let bytes = s.as_bytes();
218    if bytes.is_empty() || !is_ident_start(bytes[0]) {
219        return "";
220    }
221    let mut n = 1;
222    while n < bytes.len() && is_ident_cont(bytes[n]) {
223        n += 1;
224    }
225    &s[..n]
226}
227
228fn take_string_lit(after_open_quote: &str) -> Option<(String, usize)> {
229    let bytes = after_open_quote.as_bytes();
230    let mut i = 0;
231    let mut out = String::new();
232    while i < bytes.len() {
233        match bytes[i] {
234            b'\\' => {
235                i += 1;
236                if i >= bytes.len() {
237                    return None;
238                }
239                match bytes[i] {
240                    b'n' => out.push('\n'),
241                    b't' => out.push('\t'),
242                    b'r' => out.push('\r'),
243                    b'\\' => out.push('\\'),
244                    b'"' => out.push('"'),
245                    other => out.push(other as char),
246                }
247                i += 1;
248            }
249            b'"' => return Some((out, i + 1)),
250            c => {
251                out.push(c as char);
252                i += 1;
253            }
254        }
255    }
256    None
257}
258
259fn skip_ws(s: &str) -> &str {
260    s.trim_start()
261}
262
263fn is_ident_start(c: u8) -> bool {
264    c == b'_' || c.is_ascii_alphabetic()
265}
266
267fn is_ident_cont(c: u8) -> bool {
268    c == b'_' || c.is_ascii_alphanumeric()
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    const FIXTURE: &str = r#"
276pub const DISCOVERY_LIST: &str = "CapabilityDiscovery.list";
277pub const CLIN_FRAMINGHAM: &str =
278    "ClinicalRisk.framingham";
279pub const LTL_EVALUATE: &str = "TemporalAndDescriptionLogic.ltl.evaluate";
280
281pub const ALL_BOUND: &[&str] = &[
282    DISCOVERY_LIST,
283    CLIN_FRAMINGHAM,
284    // comment
285    LTL_EVALUATE,
286];
287
288/// Family bound.
289pub fn family_bound(name: &str) -> bool { true }
290"#;
291
292    const CATALOG: &str = r#"
293pub const ALL_INVOKE_IDS: &[&str] = &[
294    "CapabilityDiscovery.list",
295    "ClinicalRisk.framingham",
296    "TemporalAndDescriptionLogic.ltl.evaluate",
297];
298"#;
299
300    #[test]
301    fn extracts_wrapped_and_commented_all_bound() {
302        let ids = extract_all_bound(FIXTURE).unwrap();
303        assert_eq!(
304            ids,
305            vec![
306                "CapabilityDiscovery.list".to_string(),
307                "ClinicalRisk.framingham".to_string(),
308                "TemporalAndDescriptionLogic.ltl.evaluate".to_string(),
309            ]
310        );
311    }
312
313    #[test]
314    fn extracts_catalog_strings() {
315        let ids = extract_catalog_ids(CATALOG).unwrap();
316        assert_eq!(ids.len(), 3);
317        assert!(ids.contains(&"ClinicalRisk.framingham".to_string()));
318    }
319
320    #[test]
321    fn unresolved_const_fails_closed() {
322        let src = r#"
323pub const FOO: &str = "A.b";
324pub const ALL_BOUND: &[&str] = &[FOO, MISSING];
325"#;
326        match extract_all_bound(src) {
327            Err(ExtractError::Unresolved { names }) => {
328                assert_eq!(names, vec!["MISSING".to_string()])
329            }
330            other => panic!("expected unresolved, got {other:?}"),
331        }
332    }
333
334    #[test]
335    fn missing_all_bound_fails() {
336        assert_eq!(
337            extract_all_bound("pub const FOO: &str = \"A.b\";"),
338            Err(ExtractError::MissingAllBound)
339        );
340    }
341
342    #[test]
343    fn family_grouping() {
344        let ids = vec![
345            "Statistics.mean".into(),
346            "Statistics.median".into(),
347            "SHACL.validate".into(),
348        ];
349        let fams = families_from_ids(&ids);
350        assert_eq!(fams.len(), 2);
351        assert_eq!(
352            fams.iter()
353                .find(|f| f.name == "Statistics")
354                .unwrap()
355                .member_count,
356            2
357        );
358    }
359
360    #[test]
361    fn doc_cites_require_family_dot_prefix() {
362        let text = "See ClinicalRisk.framingham and also Statistics in passing.";
363        let ids = vec!["ClinicalRisk.framingham".into()];
364        let fams = vec!["ClinicalRisk".into(), "Statistics".into()];
365        assert_eq!(
366            cited_invoke_ids(text, &ids),
367            vec!["ClinicalRisk.framingham".to_string()]
368        );
369        assert_eq!(
370            cited_families(text, &fams),
371            vec!["ClinicalRisk".to_string()]
372        );
373    }
374
375    #[test]
376    fn empty_all_bound_is_ok() {
377        let src = r#"pub const ALL_BOUND: &[&str] = &[];"#;
378        assert_eq!(extract_all_bound(src).unwrap(), Vec::<String>::new());
379    }
380}