Skip to main content

model_lang_python/
detect.rs

1//! Reads one Python file and finds its HTTP endpoints (syntax only).
2
3use std::collections::HashMap;
4
5use model_core::Range;
6use tree_sitter::{Node, Parser};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum Framework {
10    Flask,
11    FastApi,
12    Django,
13}
14
15impl Framework {
16    pub fn as_str(self) -> &'static str {
17        match self {
18            Framework::Flask => "flask",
19            Framework::FastApi => "fastapi",
20            Framework::Django => "django",
21        }
22    }
23}
24
25/// One route, before it meets the model.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Endpoint {
28    pub framework: Framework,
29    /// Upper-case HTTP method, `ANY` for Django routes.
30    pub method: String,
31    pub path: String,
32    /// Decorated function (Flask, FastAPI): where its name sits.
33    pub handler_name_at: Option<Range>,
34    /// View named by the route (Django): `views.users` or `UserView` (from
35    /// `UserView.as_view()`), as written.
36    pub handler_ref: Option<String>,
37    /// Django `name=` of the route.
38    pub route_name: Option<String>,
39    /// The decorator or the `path(...)` call.
40    pub site: Range,
41}
42
43fn range(n: Node) -> Range {
44    let (s, e) = (n.start_position(), n.end_position());
45    Range::new(s.row as u32, s.column as u32, e.row as u32, e.column as u32)
46}
47
48fn text<'a>(n: Node, src: &'a [u8]) -> &'a str {
49    std::str::from_utf8(&src[n.byte_range()]).unwrap_or("")
50}
51
52/// Value of a plain string literal; `None` for f-strings with holes and
53/// anything else.
54fn string_value(n: Node, src: &[u8]) -> Option<String> {
55    if n.kind() != "string" {
56        return None;
57    }
58    let mut out = String::new();
59    let mut cursor = n.walk();
60    for c in n.children(&mut cursor) {
61        match c.kind() {
62            "string_content" => out.push_str(text(c, src)),
63            "interpolation" => return None,
64            _ => {}
65        }
66    }
67    Some(out)
68}
69
70/// Positional arguments and keyword arguments of a call.
71fn arguments<'t>(call: Node<'t>, src: &[u8]) -> (Vec<Node<'t>>, HashMap<String, Node<'t>>) {
72    let mut pos = Vec::new();
73    let mut kw = HashMap::new();
74    if let Some(args) = call.child_by_field_name("arguments") {
75        let mut cursor = args.walk();
76        for a in args.named_children(&mut cursor) {
77            if a.kind() == "keyword_argument" {
78                if let (Some(n), Some(v)) = (
79                    a.child_by_field_name("name"),
80                    a.child_by_field_name("value"),
81                ) {
82                    kw.insert(text(n, src).to_string(), v);
83                }
84            } else if a.kind() != "comment" {
85                pos.push(a);
86            }
87        }
88    }
89    (pos, kw)
90}
91
92/// `callee` of a call as dotted text, and its last segment.
93fn callee<'a>(call: Node, src: &'a [u8]) -> Option<(&'a str, &'a str)> {
94    let f = call.child_by_field_name("function")?;
95    if !matches!(f.kind(), "identifier" | "attribute") {
96        return None;
97    }
98    let t = text(f, src);
99    Some((t, t.rsplit('.').next().unwrap_or(t)))
100}
101
102/// Strings of a list, tuple or set literal.
103fn strings_of(n: Node, src: &[u8]) -> Vec<String> {
104    let mut cursor = n.walk();
105    n.named_children(&mut cursor)
106        .filter_map(|c| string_value(c, src))
107        .collect()
108}
109
110/// An `APIRouter(prefix=...)` / `Blueprint(..., url_prefix=...)` /
111/// `Flask(...)` / `FastAPI(...)` bound to a name.
112struct Router {
113    framework: Framework,
114    prefix: String,
115}
116
117fn routers(root: Node, src: &[u8]) -> HashMap<String, Router> {
118    let mut found = HashMap::new();
119    let mut cursor = root.walk();
120    for stmt in root.named_children(&mut cursor) {
121        if stmt.kind() != "expression_statement" {
122            continue;
123        }
124        let Some(a) = stmt.named_child(0).filter(|a| a.kind() == "assignment") else {
125            continue;
126        };
127        let (Some(left), Some(right)) = (
128            a.child_by_field_name("left"),
129            a.child_by_field_name("right"),
130        ) else {
131            continue;
132        };
133        if left.kind() != "identifier" || right.kind() != "call" {
134            continue;
135        }
136        let Some((_, ctor)) = callee(right, src) else {
137            continue;
138        };
139        let (framework, key) = match ctor {
140            "FastAPI" => (Framework::FastApi, "prefix"),
141            "APIRouter" => (Framework::FastApi, "prefix"),
142            "Flask" | "Quart" => (Framework::Flask, "url_prefix"),
143            "Blueprint" => (Framework::Flask, "url_prefix"),
144            _ => continue,
145        };
146        let (_, kw) = arguments(right, src);
147        let prefix = kw
148            .get(key)
149            .and_then(|v| string_value(*v, src))
150            .unwrap_or_default();
151        found.insert(text(left, src).to_string(), Router { framework, prefix });
152    }
153    found
154}
155
156/// Which framework the file's imports point at, if any.
157fn imported_framework(root: Node, src: &[u8]) -> Option<Framework> {
158    let mut cursor = root.walk();
159    let mut flask = false;
160    for stmt in root.named_children(&mut cursor) {
161        if matches!(stmt.kind(), "import_statement" | "import_from_statement") {
162            let t = text(stmt, src);
163            if t.contains("fastapi") || t.contains("starlette") {
164                return Some(Framework::FastApi);
165            }
166            flask |= t.contains("flask") || t.contains("quart");
167        }
168    }
169    flask.then_some(Framework::Flask)
170}
171
172const VERBS: [&str; 7] = ["get", "post", "put", "delete", "patch", "head", "options"];
173
174fn decorator_endpoints(
175    root: Node,
176    src: &[u8],
177    routers: &HashMap<String, Router>,
178    out: &mut Vec<Endpoint>,
179) {
180    let hint = imported_framework(root, src);
181    let mut stack = vec![root];
182    while let Some(n) = stack.pop() {
183        let mut cursor = n.walk();
184        for c in n.named_children(&mut cursor) {
185            stack.push(c);
186        }
187        if n.kind() != "decorated_definition" {
188            continue;
189        }
190        let Some(func) = n
191            .child_by_field_name("definition")
192            .filter(|d| d.kind() == "function_definition")
193        else {
194            continue;
195        };
196        let Some(name_at) = func.child_by_field_name("name").map(range) else {
197            continue;
198        };
199        let mut dc = n.walk();
200        for dec in n
201            .named_children(&mut dc)
202            .filter(|d| d.kind() == "decorator")
203        {
204            let Some(call) = dec.named_child(0).filter(|c| c.kind() == "call") else {
205                continue;
206            };
207            let Some(f) = call
208                .child_by_field_name("function")
209                .filter(|f| f.kind() == "attribute")
210            else {
211                continue;
212            };
213            let (Some(obj), Some(attr)) = (
214                f.child_by_field_name("object"),
215                f.child_by_field_name("attribute"),
216            ) else {
217                continue;
218            };
219            let (obj, attr) = (text(obj, src), text(attr, src));
220            let router = routers.get(obj);
221            let is_route = matches!(attr, "route" | "api_route");
222            let is_verb = VERBS.contains(&attr);
223            if !is_route && !is_verb {
224                continue;
225            }
226            // A verb needs proof of the framework; `route` is Flask's own.
227            let framework = router
228                .map(|r| r.framework)
229                .or(hint)
230                .or(is_route.then_some(Framework::Flask));
231            let Some(framework) = framework else { continue };
232            let (pos, kw) = arguments(call, src);
233            let Some(path) = pos
234                .first()
235                .copied()
236                .or_else(|| kw.get("rule").or_else(|| kw.get("path")).copied())
237                .and_then(|p| string_value(p, src))
238            else {
239                continue;
240            };
241            let methods: Vec<String> = if is_verb {
242                vec![attr.to_uppercase()]
243            } else {
244                let m = kw
245                    .get("methods")
246                    .map(|m| strings_of(*m, src))
247                    .filter(|m| !m.is_empty())
248                    .unwrap_or_else(|| vec!["GET".to_string()]);
249                m.into_iter().map(|m| m.to_uppercase()).collect()
250            };
251            let path = format!("{}{}", router.map_or("", |r| r.prefix.as_str()), path);
252            for method in methods {
253                out.push(Endpoint {
254                    framework,
255                    method,
256                    path: path.clone(),
257                    handler_name_at: Some(name_at),
258                    handler_ref: None,
259                    route_name: None,
260                    site: range(dec),
261                });
262            }
263        }
264    }
265}
266
267fn django_endpoints(root: Node, src: &[u8], out: &mut Vec<Endpoint>) {
268    let mut stack = vec![root];
269    while let Some(n) = stack.pop() {
270        let mut cursor = n.walk();
271        for c in n.named_children(&mut cursor) {
272            stack.push(c);
273        }
274        if n.kind() != "call" {
275            continue;
276        }
277        let Some((_, name)) = callee(n, src) else {
278            continue;
279        };
280        if !matches!(name, "path" | "re_path" | "url") {
281            continue;
282        }
283        let (pos, kw) = arguments(n, src);
284        let (Some(route), Some(view)) = (pos.first(), pos.get(1)) else {
285            continue;
286        };
287        let Some(path) = string_value(*route, src) else {
288            continue;
289        };
290        // `include(...)` mounts other patterns, it is no endpoint itself.
291        let handler_ref = match view.kind() {
292            "identifier" | "attribute" => Some(text(*view, src).to_string()),
293            "call" => match callee(*view, src) {
294                Some((_, "include")) => continue,
295                // `UserView.as_view()` names the class.
296                Some((full, "as_view")) => full.strip_suffix(".as_view").map(str::to_string),
297                _ => None,
298            },
299            _ => None,
300        };
301        out.push(Endpoint {
302            framework: Framework::Django,
303            method: "ANY".to_string(),
304            path,
305            handler_name_at: None,
306            handler_ref,
307            route_name: kw.get("name").and_then(|v| string_value(*v, src)),
308            site: range(n),
309        });
310    }
311}
312
313/// Endpoints of one file, in source order.
314pub fn endpoints(src: &str) -> Vec<Endpoint> {
315    let mut parser = Parser::new();
316    if parser
317        .set_language(&tree_sitter_python::LANGUAGE.into())
318        .is_err()
319    {
320        return Vec::new();
321    }
322    let Some(tree) = parser.parse(src, None) else {
323        return Vec::new();
324    };
325    let root = tree.root_node();
326    let bytes = src.as_bytes();
327    let mut out = Vec::new();
328    let routers = routers(root, bytes);
329    decorator_endpoints(root, bytes, &routers, &mut out);
330    if src.contains("urlpatterns") {
331        django_endpoints(root, bytes, &mut out);
332    }
333    out.sort_by_key(|e| (e.site.start_line, e.site.start_col));
334    out
335}