Skip to main content

model_lang_python/
lib.rs

1//! Python enricher for Model.
2//!
3//! Runs after `model-treesitter` extraction, on the same [`ModelBuilder`]:
4//! it re-reads each `.py` file for facts a query cannot express and adds them
5//! with [`Provenance::Frontend`].
6//!
7//! HTTP endpoints, from
8//! - Flask: `@app.route("/x", methods=[...])`, `@bp.get("/x")`;
9//! - FastAPI: `@router.get("/x")`, `@app.api_route(...)`, with the
10//!   `prefix=` of the `APIRouter` / `Blueprint` they are declared on;
11//! - Django: `path()`, `re_path()`, `url()` calls of a file defining
12//!   `urlpatterns` (`include(...)` mounts are not followed: the route prefix
13//!   of an included module is not composed).
14//!
15//! Each endpoint is an entity of kind `http.endpoint` (shared with the Java and TypeScript enrichers) (archetype
16//! `Variable`, no FM3 class: the Famix Python metamodel's class names are not
17//! settled), keyed under its handler (decorators) or its `urls.py` file
18//! (Django) with a `Meta` descriptor `METHOD path:`. Props: `http.framework`,
19//! `http.verb`, `http.path`, `http.handler`, `http.route_name`. Django
20//! endpoints also get a `Calls` relation to their view when one project
21//! function or class carries its name.
22
23use std::collections::HashMap;
24use std::path::Path;
25
26use anyhow::Context;
27use model_core::{
28    Descriptor, EntityId, EntityKind, KindId, LanguageId, ModelBuilder, Provenance, RelationKind,
29    SymbolKey,
30};
31
32mod detect;
33#[cfg(test)]
34mod tests;
35
36pub use detect::{Endpoint, Framework, endpoints};
37
38/// Fine kind of an HTTP endpoint.
39pub const HTTP_ENDPOINT: &str = "http.endpoint";
40
41/// Directories never descended into.
42pub const IGNORED_DIRS: &[&str] = &[
43    ".git",
44    "node_modules",
45    "__pycache__",
46    ".venv",
47    "venv",
48    "site-packages",
49];
50
51#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
52pub struct PythonStats {
53    /// Python files read.
54    pub files: usize,
55    pub endpoints: usize,
56    /// Django views resolved to a project function or class.
57    pub resolved_views: usize,
58}
59
60fn language() -> LanguageId {
61    LanguageId::new("python")
62}
63
64/// Defines the kinds this enricher adds (normally defined when first met),
65/// see `model_treesitter::declare_kinds`.
66pub fn declare_kinds(b: &mut ModelBuilder) -> KindId {
67    let id = b.define_kind(
68        HTTP_ENDPOINT,
69        EntityKind::Variable,
70        model_traits::mask(&["Named"]),
71        None,
72    );
73    b.set_kind_concept(id, Some("HttpEndpoint"), Some("httpEndpoints"));
74    id
75}
76
77/// Entities of the builder by where their name is, and callables / types by
78/// name.
79struct Index {
80    at: HashMap<(String, u32, u32), EntityId>,
81    by_name: HashMap<String, Vec<EntityId>>,
82}
83
84impl Index {
85    fn new(b: &ModelBuilder) -> Index {
86        let mut at = HashMap::new();
87        let mut by_name: HashMap<String, Vec<EntityId>> = HashMap::new();
88        for id in b.ids() {
89            if b.external(id) {
90                continue;
91            }
92            let (Some(file), Some(r)) = (b.file(id), b.name_range(id)) else {
93                continue;
94            };
95            at.insert((file.to_string(), r.start_line, r.start_col), id);
96            let kind = b.kind(id);
97            if kind.is_callable() || kind.is_type() {
98                by_name.entry(b.name(id).to_string()).or_default().push(id);
99            }
100        }
101        Index { at, by_name }
102    }
103}
104
105/// Adds the endpoints of `files` (`(relative path, source)`) to `b`.
106pub fn enrich_sources(b: &mut ModelBuilder, files: &[(String, String)]) -> PythonStats {
107    let prepared: Vec<Prepared> = files
108        .iter()
109        .filter(|(p, _)| p.ends_with(".py"))
110        .map(|(p, src)| prepare_source(p, src))
111        .collect();
112    enrich_prepared(b, prepared.iter())
113}
114
115/// Parsed endpoints of one file; ownership is resolved when applied.
116pub struct Prepared {
117    path: String,
118    endpoints: Vec<Endpoint>,
119}
120
121pub fn prepare_source(path: &str, src: &str) -> Prepared {
122    Prepared {
123        path: path.into(),
124        endpoints: endpoints(src),
125    }
126}
127
128/// Applies retained endpoints to the current model, in path order.
129pub fn enrich_prepared<'a>(
130    b: &mut ModelBuilder,
131    files: impl IntoIterator<Item = &'a Prepared>,
132) -> PythonStats {
133    let kind = declare_kinds(b);
134    let index = Index::new(b);
135    let lang = language();
136    let mut stats = PythonStats::default();
137    let mut seen: HashMap<String, u32> = HashMap::new();
138    let mut files: Vec<&Prepared> = files.into_iter().collect();
139    files.sort_by(|a, b| a.path.cmp(&b.path));
140    for file in files {
141        let path = &file.path;
142        stats.files += 1;
143        let file_key = SymbolKey::for_file(&lang, path);
144        let file_id = b.get(&file_key.to_string());
145        for e in &file.endpoints {
146            let handler = e
147                .handler_name_at
148                .and_then(|r| index.at.get(&(path.clone(), r.start_line, r.start_col)))
149                .copied();
150            let (parent, parent_key) = match handler {
151                Some(h) => (Some(h), b.key(h).to_string()),
152                None => (file_id, file_key.to_string()),
153            };
154            let name = format!("{} {}", e.method, e.path);
155            let mut key = format!("{parent_key}{}", Descriptor::Meta(name.clone()));
156            let n = seen.entry(key.clone()).or_insert(0);
157            if *n > 0 {
158                key = format!("{parent_key}{}", Descriptor::Meta(format!("{name}+{n}")));
159            }
160            *n += 1;
161            let id = b.entity_of_kind(&key, kind, &name);
162            b.set_language(id, &lang);
163            b.set_source(id, path, e.site, None);
164            b.set_parent(id, parent);
165            if let Some(p) = parent {
166                b.occurrence(
167                    &RelationKind::Other("http.endpoints".to_string()),
168                    p,
169                    id,
170                    Provenance::Frontend,
171                    e.site,
172                );
173            }
174            b.set_prop(id, "http.framework", e.framework.as_str());
175            b.set_prop(id, "http.verb", e.method.as_str());
176            b.set_prop(id, "http.path", e.path.as_str());
177            if let Some(h) = handler {
178                b.set_prop(id, "http.handler", b.name(h).to_string());
179            }
180            if let Some(r) = &e.route_name {
181                b.set_prop(id, "http.route_name", r.as_str());
182            }
183            if let Some(view) = &e.handler_ref {
184                let last = view.rsplit('.').next().unwrap_or(view);
185                b.set_prop(id, "http.handler", last);
186                if let Some([only]) = index.by_name.get(last).map(Vec::as_slice) {
187                    b.occurrence(
188                        &RelationKind::Calls,
189                        id,
190                        *only,
191                        Provenance::Frontend,
192                        e.site,
193                    );
194                    stats.resolved_views += 1;
195                }
196            }
197            stats.endpoints += 1;
198        }
199    }
200    stats
201}
202
203/// Reads every `.py` file under `root` (gitignore honoured) accepted by
204/// `keep` (path relative to `root`, `/`-separated) and adds its endpoints.
205pub fn enrich(
206    b: &mut ModelBuilder,
207    root: &Path,
208    keep: &dyn Fn(&str) -> bool,
209    warnings: &mut Vec<String>,
210) -> anyhow::Result<PythonStats> {
211    let mut files = Vec::new();
212    for rel in source_files(root)? {
213        if !keep(&rel) {
214            continue;
215        }
216        let p = root.join(&rel);
217        match std::fs::read_to_string(&p) {
218            Ok(src) => files.push((rel, src)),
219            Err(e) => warnings.push(format!("cannot read {}: {e}", p.display())),
220        }
221    }
222    Ok(enrich_sources(b, &files))
223}
224
225/// Python sources read by [`enrich`], relative to `root`, in path order.
226pub fn source_files(root: &Path) -> anyhow::Result<Vec<String>> {
227    let mut walker = ignore::WalkBuilder::new(root);
228    walker.filter_entry(|e| {
229        !e.file_type().is_some_and(|t| t.is_dir())
230            || !IGNORED_DIRS.contains(&e.file_name().to_string_lossy().as_ref())
231    });
232    let mut paths = model_detect::par_walk(&walker, true, |entry| {
233        let p = entry.path();
234        if p.extension().and_then(|e| e.to_str()) != Some("py") || !p.is_file() {
235            return None;
236        }
237        let rel = p
238            .strip_prefix(root)
239            .unwrap_or(p)
240            .to_string_lossy()
241            .replace('\\', "/");
242        Some(rel)
243    })
244    .with_context(|| format!("walking {}", root.display()))?;
245    paths.sort();
246    Ok(paths)
247}