Skip to main content

rpc/references/
sources.rs

1//! The declared directory of shipped source files (`.org` with `lisp` blocks,
2//! `.nms`, `.lisp`), scanned for string literals that name an entity.
3
4use std::path::Path;
5
6use nomiscript::{Expr, Reader};
7use uuid::Uuid;
8
9use super::templates::judge;
10use super::{Finding, Subject, TenantReport};
11use crate::lookup_log::{Lookup, LookupKind};
12use crate::resolve::Directory;
13
14#[derive(Debug)]
15pub struct Source {
16    pub name: String,
17    pub lookups: Vec<Lookup>,
18}
19
20/// The lisp text of an `.org` file: the bodies of its `lisp` source blocks.
21fn lisp_blocks(org: &str) -> String {
22    let mut inside = false;
23    let mut text = String::new();
24    for line in org.lines() {
25        let directive = line.trim_start().to_ascii_lowercase();
26        match (inside, directive.as_str()) {
27            (false, d) if d.starts_with("#+begin_src lisp") => inside = true,
28            (true, d) if d.starts_with("#+end_src") => inside = false,
29            (true, _) => {
30                text.push_str(line);
31                text.push('\n');
32            }
33            _ => {}
34        }
35    }
36    text
37}
38
39fn is_head(items: &[Expr], names: &[&str]) -> bool {
40    matches!(items.first(), Some(Expr::Symbol(head)) if names.iter().any(|n| head.eq_ignore_ascii_case(n)))
41}
42
43fn keyed_kind(keyword: &str) -> Option<LookupKind> {
44    match keyword
45        .trim_start_matches(':')
46        .to_ascii_lowercase()
47        .as_str()
48    {
49        "from" | "to" => Some(LookupKind::Account),
50        "from-commodity" | "to-commodity" => Some(LookupKind::Commodity),
51        _ => None,
52    }
53}
54
55/// The lookups one list form makes: `(get-account "k")`, `(get-commodity "k")`
56/// or the `:from` / `:to` / `:from-commodity` / `:to-commodity` keys of a
57/// logical row.
58fn form_lookups(items: &[Expr]) -> Vec<Lookup> {
59    let head = match items {
60        [Expr::Symbol(_), Expr::String(key), ..] if is_head(items, &["get-account"]) => {
61            Some((LookupKind::Account, key, false))
62        }
63        [Expr::Symbol(_), Expr::String(key), ..] if is_head(items, &["get-commodity"]) => {
64            Some((LookupKind::Commodity, key, false))
65        }
66        _ => None,
67    };
68    let keyed = items.windows(2).filter_map(|pair| match pair {
69        [Expr::Keyword(name), Expr::String(key)] => Some((keyed_kind(name)?, key, true)),
70        _ => None,
71    });
72    head.into_iter()
73        .chain(keyed)
74        .map(|(kind, key, row_key)| Lookup {
75            kind,
76            key: key.clone(),
77            row_key,
78        })
79        .collect()
80}
81
82fn lookups(source: &str) -> Result<Vec<Lookup>, String> {
83    let program = Reader::parse(source).map_err(|err| format!("does not parse: {err}"))?;
84    let mut found: Vec<Lookup> = Vec::new();
85    let mut pending: Vec<&Expr> = program.exprs.iter().collect();
86    while let Some(expr) = pending.pop() {
87        match expr {
88            Expr::List(items) => {
89                found.extend(form_lookups(items));
90                pending.extend(items);
91            }
92            Expr::Cons(car, cdr) => pending.extend([&**car, &**cdr]),
93            Expr::Quote(inner)
94            | Expr::Quasiquote(inner)
95            | Expr::Unquote(inner)
96            | Expr::UnquoteSplicing(inner)
97            | Expr::Lambda(_, inner) => pending.push(inner),
98            _ => {}
99        }
100    }
101    Ok(found)
102}
103
104fn load_file(path: &Path) -> Result<Option<Source>, String> {
105    let extension = path.extension().and_then(|e| e.to_str());
106    if !matches!(extension, Some("org" | "nms" | "lisp")) {
107        return Ok(None);
108    }
109    let text = std::fs::read_to_string(path).map_err(|err| format!("cannot read: {err}"))?;
110    let code = match extension {
111        Some("org") => lisp_blocks(&text),
112        _ => text,
113    };
114    Ok(Some(Source {
115        name: path.display().to_string(),
116        lookups: lookups(&code)?,
117    }))
118}
119
120fn unreadable(path: &Path, reason: String) -> Finding {
121    Finding {
122        user: None,
123        subject: Subject::Source(path.display().to_string()),
124        reason,
125    }
126}
127
128/// The sources of `dir` in name order, and a finding for each that cannot be
129/// read, or for the directory itself.
130pub fn load(dir: &Path) -> (Vec<Source>, Vec<Finding>) {
131    let entries = match std::fs::read_dir(dir) {
132        Ok(entries) => entries,
133        Err(err) => {
134            return (
135                Vec::new(),
136                vec![unreadable(dir, format!("cannot list: {err}"))],
137            );
138        }
139    };
140    let mut paths: Vec<_> = entries
141        .filter_map(|entry| Some(entry.ok()?.path()))
142        .collect();
143    paths.sort();
144    let mut sources = Vec::new();
145    let mut findings = Vec::new();
146    let mirrors = |path: &std::path::PathBuf| {
147        path.extension().is_some_and(|e| e == "nms") && path.with_extension("org").is_file()
148    };
149    for path in paths.iter().filter(|path| path.is_file() && !mirrors(path)) {
150        match load_file(path) {
151            Ok(source) => sources.extend(source),
152            Err(reason) => findings.push(unreadable(path, reason)),
153        }
154    }
155    (sources, findings)
156}
157
158pub(super) fn check(
159    user: Uuid,
160    directory: &Directory,
161    declared: &[Source],
162    report: &mut TenantReport,
163) {
164    report.coverage.sources = declared.len();
165    for source in declared {
166        let subject = Subject::Source(source.name.clone());
167        judge(user, &subject, directory, source.lookups.clone(), report);
168    }
169}
170
171#[cfg(test)]
172mod tests;