Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

59.3 KB
Raw Blame
//! The routes: Flask, FastAPI, Starlette, Django, aiohttp, and hand-written servers.

use std::collections::{HashMap, HashSet};

use tree_sitter::Node;

use super::ast::{
    Args, head, key, last, literal_string, literal_strings, method_call, parameter_names,
};
use super::{Ctx, Value, Var, clip, mounts};
use crate::lang::syntax::{self, line, named_children};
use crate::obligations::Family;

/// The methods of a web application that register routes without being decorators.
const REGISTRATIONS: &[&str] = &[
    "add_url_rule",
    "add_api_route",
    "add_api_websocket_route",
    "add_websocket_route",
    "add_route",
    "register_blueprint",
    "include_router",
    "mount",
];

/// A name that holds a route method: `route = app.route`.
#[derive(Clone, Debug)]
pub(super) struct RouteAlias {
    /// The application's library, `None` when the receiver comes from elsewhere.
    library: Option<&'static str>,
    method: String,
    /// The receiver's container, for its mount prefixes (empty: at the root).
    place: Vec<String>,
}

/// What the second argument of a Django `path()` is.
enum View<'t> {
    /// A view: a function, `X.as_view()`, a lambda, a view decorated by Django.
    Plain,
    /// An include, with the expression that holds the included patterns when it is visible.
    Include(Option<Node<'t>>),
    /// Neither a recognised view nor a recognised include.
    Unknown,
}

/// A name that denotes a list of patterns rather than a view: `urls`, `api_urls`,
/// `urlpatterns`, `admin.site.urls`.
fn looks_like_patterns(name: &str) -> bool {
    let name = name.to_lowercase();
    name.ends_with("urls") || name.ends_with("patterns")
}

const VERBS: &[&str] = &[
    "get", "post", "put", "patch", "delete", "head", "options", "trace",
];
/// What aiohttp's `add_route("METHOD", "/path", handler)` accepts as a first argument.
const METHOD_NAMES: &[&str] = &[
    "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "TRACE", "*",
];
const NOT_LITERAL_PATH: &str = "route path is not a string literal";
const NOT_LITERAL_METHODS: &str = "route methods are not string literals";
const RAW_SERVER: &str = "requests are handled by a raw http server; routes cannot be enumerated";
const UNKNOWN_ORIGIN: &str =
    "a route may be declared on an object whose origin is not known in this file";
const COMPUTED_METHOD: &str =
    "route method is computed (getattr); the routes it declares are not enumerated";

/// What a decorator or a method adds as a route.
#[derive(Clone, Copy)]
enum Kind<'a> {
    /// `@app.get(...)`: the method is the name.
    Verb(&'a str),
    /// `@app.route(..., methods=[...])`, `@app.api_route(...)`: the methods are an argument.
    Methods,
    Websocket,
    /// A view class: all the methods it defines.
    Any,
}

fn kind_of(method: &str) -> Option<Kind<'_>> {
    match method {
        "route" | "api_route" | "add_url_rule" | "add_api_route" => Some(Kind::Methods),
        "websocket" | "websocket_route" | "add_websocket_route" | "add_api_websocket_route" => {
            Some(Kind::Websocket)
        }
        "view" | "add_view" => Some(Kind::Any),
        verb => VERBS.contains(&verb).then_some(Kind::Verb(verb)),
    }
}

/// `route` with no method given: `GET` for a function, `ANY` for a class.
fn default_methods(class: bool) -> Vec<String> {
    vec![if class { "ANY" } else { "GET" }.to_string()]
}

impl<'t> Ctx<'t> {
    /// The decorators `@app.route(...)`, `@router.get(...)`, `@routes.get(...)` of a function
    /// or a class.
    pub(super) fn route_decorated(&mut self, definition: Node<'t>, decorators: &[Node<'t>]) {
        let handler = definition
            .child_by_field_name("name")
            .map(|n| self.text(n).to_string());
        let class = definition.kind() == "class_definition";
        for decorator in decorators {
            let Some(call) = named_children(*decorator)
                .into_iter()
                .find(|n| n.kind() == "call")
            else {
                continue;
            };
            let detail = handler.as_ref().map(|h| format!("handler {h}"));
            let Some((receiver, method)) = method_call(call, self.source) else {
                // `route = app.route` then `@route("/x")`.
                self.aliased_route(call, detail, class);
                continue;
            };
            let Some(kind) = kind_of(&method) else {
                continue;
            };
            // `@app.add_url_rule` is not a Flask decorator: the call is read by `routes_call`,
            // which also visits the decorator's call.
            if method.starts_with("add_") {
                continue;
            }
            self.route_or_site(call, receiver, kind, detail, class);
        }
    }

    /// `call` calls an alias of a route method (`get = app.get`): its routes.
    fn aliased_route(&mut self, call: Node<'t>, detail: Option<String>, class: bool) -> bool {
        let Some(alias) = call
            .child_by_field_name("function")
            .filter(|f| f.kind() == "identifier")
            .and_then(|f| self.tracked_key(f))
            .and_then(|k| self.route_aliases.get(&k).cloned())
        else {
            return false;
        };
        let Some(kind) = kind_of(&alias.method) else {
            return false;
        };
        let library = alias.library.unwrap_or_else(|| self.guess_library(kind));
        self.emit_routes_in(call, kind, library, detail, class, &alias.place);
        true
    }

    /// `name = app.route` (or `name = other_alias`): the alias is followed; any other
    /// assignment of `name` erases it.
    pub(super) fn route_alias_assign(
        &mut self,
        left: Node<'t>,
        right: Node<'t>,
        plain: &str,
        target: &str,
    ) {
        let alias = if left.kind() == "identifier" {
            self.route_alias_of(right)
        } else {
            None
        };
        match alias {
            Some(alias) => {
                self.var_names.insert(plain.to_string());
                self.route_aliases.insert(target.to_string(), alias);
            }
            None => {
                self.route_aliases.remove(target);
            }
        }
    }

    fn route_alias_of(&self, node: Node<'t>) -> Option<RouteAlias> {
        match node.kind() {
            "attribute" => {
                let method = self
                    .text(node.child_by_field_name("attribute")?)
                    .to_string();
                kind_of(&method)?;
                if method.starts_with("add_") {
                    return None;
                }
                let receiver = node.child_by_field_name("object")?;
                let library = match self.route_origin(receiver) {
                    Origin::Framework(library) => Some(library),
                    Origin::Unknown if self.route_framework_imported() => None,
                    _ => return None,
                };
                let place = self.receiver_place(receiver);
                Some(RouteAlias {
                    library,
                    method,
                    place,
                })
            }
            "identifier" => self
                .tracked_key(node)
                .and_then(|k| self.route_aliases.get(&k).cloned()),
            _ => None,
        }
    }

    /// A route method of a web application (`app.get`) or a method alias, taken as a value
    /// rather than called or assigned to a name: the routes it declares elsewhere are not
    /// visible.
    pub(super) fn route_method_reference(&mut self, node: Node<'t>) {
        let alias = node.kind() == "identifier"
            && self
                .tracked_key(node)
                .is_some_and(|k| self.route_aliases.contains_key(&k));
        if !alias {
            if node.kind() != "attribute" {
                return;
            }
            let Some(method) = node.child_by_field_name("attribute") else {
                return;
            };
            let method = self.text(method);
            if !(kind_of(method).is_some() || REGISTRATIONS.contains(&method)) {
                return;
            }
            let Some(receiver) = node.child_by_field_name("object") else {
                return;
            };
            if !matches!(self.route_origin(receiver), Origin::Framework(_)) {
                return;
            }
        }
        let Some(parent) = node.parent() else {
            return;
        };
        let is = |field: &str| {
            parent
                .child_by_field_name(field)
                .is_some_and(|n| n.id() == node.id())
        };
        // An identifier that does not denote the variable: `x.get`, `f(get=1)`, `def get()`.
        let not_the_variable = match parent.kind() {
            "attribute" => is("attribute"),
            "keyword_argument" | "function_definition" | "class_definition" => is("name"),
            _ => false,
        };
        if not_the_variable {
            return;
        }
        let consumed = match parent.kind() {
            "call" => is("function"),
            "assignment" => {
                is("left")
                    || parent
                        .child_by_field_name("left")
                        .is_some_and(|l| l.kind() == "identifier")
                        && self.route_alias_of(node).is_some()
            }
            "attribute" => is("object"),
            _ => false,
        };
        if !consumed {
            let reason = format!(
                "route method {} is used as a value; the routes it declares are not enumerated",
                clip(self.text(node))
            );
            self.unresolved(Family::Route, line(node), reason);
        }
    }

    /// A framework's route constructor or function (`Route`, `path`, `web.get`) taken as a
    /// value: `partial(Route, methods=[...])`, `p = path`, a subclass. What is done with it
    /// afterwards cannot be read.
    pub(super) fn route_constructor_reference(&mut self, node: Node<'t>, qualified: &str) {
        let constructor = match (head(qualified), last(qualified)) {
            ("django", "path" | "re_path" | "url" | "include") => qualified.contains(".urls"),
            (
                "starlette" | "fastapi",
                "Route" | "WebSocketRoute" | "APIRoute" | "APIWebSocketRoute" | "Mount" | "Host",
            ) => true,
            ("aiohttp", name) => {
                qualified.contains(".web") && (kind_of(name).is_some() || name == "static")
            }
            _ => false,
        };
        if !constructor {
            return;
        }
        let Some(parent) = node.parent() else {
            return;
        };
        let is = |field: &str| {
            parent
                .child_by_field_name(field)
                .is_some_and(|n| n.id() == node.id())
        };
        if (parent.kind() == "call" && is("function"))
            || (parent.kind() == "attribute" && is("object"))
        {
            return;
        }
        // A type annotation, or `isinstance(x, Route)`, declares nothing.
        let mut current = node;
        for _ in 0..6 {
            let Some(p) = current.parent() else {
                break;
            };
            if matches!(p.kind(), "type" | "generic_type") {
                return;
            }
            if p.kind() == "call"
                && p.child_by_field_name("function")
                    .is_some_and(|f| matches!(self.text(f), "isinstance" | "issubclass"))
            {
                return;
            }
            current = p;
        }
        let reason = format!(
            "route constructor {} is used as a value; the routes it builds are not enumerated",
            clip(self.text(node))
        );
        self.unresolved(Family::Route, line(node), reason);
    }

    /// The routes of a `receiver.route(...)` applied to a handler; a receiver of unknown origin
    /// that nothing says is a web application gives a site, not silence.
    fn route_or_site(
        &mut self,
        call: Node<'t>,
        receiver: Node<'t>,
        kind: Kind,
        detail: Option<String>,
        class: bool,
    ) {
        if let Some(library) = self.route_library(call, receiver, kind) {
            self.emit_routes(call, kind, library, detail, class);
        } else if matches!(self.route_origin(receiver), Origin::Unknown) {
            self.unresolved(Family::Route, line(call), UNKNOWN_ORIGIN);
        }
    }

    /// `app.get("/g")(secret)`, `app.route("/x", methods=[...])(view)`: the decorator called by
    /// hand. `getattr(app, method)("/x")(view)`: a computed method, a site.
    fn route_call_form(&mut self, call: Node<'t>, function: Node<'t>) {
        if function.kind() != "call" {
            return;
        }
        if method_call(function, self.source).is_none() {
            let detail = Args::read(call, self.source)
                .positional
                .first()
                .map(|h| format!("handler {}", clip(self.text(*h))));
            if self.aliased_route(function, detail, false) {
                return;
            }
        }
        if let Some((receiver, method)) = method_call(function, self.source)
            && let Some(kind) = kind_of(&method)
            && !method.starts_with("add_")
        {
            let detail = Args::read(call, self.source)
                .positional
                .first()
                .map(|h| format!("handler {}", clip(self.text(*h))));
            self.route_or_site(function, receiver, kind, detail, false);
            return;
        }
        let Some(inner) = function.child_by_field_name("function") else {
            return;
        };
        if inner.kind() != "identifier"
            || self.text(inner) != "getattr"
            || self.qualify(inner).is_some()
        {
            return;
        }
        let args = Args::read(function, self.source);
        let Some(receiver) = args.positional.first().copied() else {
            return;
        };
        let origin = self.route_origin(receiver);
        let rooted = Args::read(call, self.source)
            .get(0, "path")
            .and_then(|n| literal_string(n, self.source))
            .is_some_and(|p| p.starts_with('/'));
        let web = matches!(origin, Origin::Framework(_))
            || (matches!(origin, Origin::Unknown) && (rooted || self.route_framework_imported()));
        if web {
            self.unresolved(Family::Route, line(call), COMPUTED_METHOD);
        }
    }

    /// The library of a route receiver; `None` when it is not a web application.
    fn route_library(
        &self,
        call: Node<'t>,
        receiver: Node<'t>,
        kind: Kind,
    ) -> Option<&'static str> {
        match self.route_origin(receiver) {
            Origin::Framework(library) => Some(library),
            Origin::Other => None,
            Origin::Unknown => {
                let args = Args::read(call, self.source);
                let rooted = args
                    .get(0, "path")
                    .and_then(|n| literal_string(n, self.source))
                    .is_some_and(|p| p.starts_with('/'));
                (rooted || self.route_framework_imported()).then(|| self.guess_library(kind))
            }
        }
    }

    /// The library that an unknown receiver is most likely to be.
    fn guess_library(&self, kind: Kind) -> &'static str {
        ["fastapi", "flask", "quart", "starlette", "aiohttp"]
            .into_iter()
            .find(|m| self.imports.has(m))
            .map_or(
                if matches!(kind, Kind::Methods) {
                    "flask"
                } else {
                    "fastapi"
                },
                |m| if m == "quart" { "flask" } else { m },
            )
    }

    /// The routes of a decorator call or an `add_*` call: one per method and per mount prefix
    /// of the receiver.
    fn emit_routes(
        &mut self,
        call: Node<'t>,
        kind: Kind,
        library: &str,
        detail: Option<String>,
        class: bool,
    ) {
        let place = self.route_place(call);
        self.emit_routes_in(call, kind, library, detail, class, &place);
    }

    /// The routes of a call declared in the containers `place` (empty: at the root).
    fn emit_routes_in(
        &mut self,
        call: Node<'t>,
        kind: Kind,
        library: &str,
        detail: Option<String>,
        class: bool,
        place: &[String],
    ) {
        let args = Args::read(call, self.source);
        let at = line(call);
        self.recognise(Family::Route, library);
        let (path, methods) = self.path_and_methods(&args, kind, class);
        let Some(methods) = methods else {
            self.unresolved(Family::Route, at, NOT_LITERAL_METHODS);
            return;
        };
        let Some(path) = path.and_then(|n| literal_string(n, self.source)) else {
            self.unresolved(Family::Route, at, NOT_LITERAL_PATH);
            return;
        };
        let paths = self.mounted_paths(place, &path);
        for method in methods {
            for (path, relative) in &paths {
                let detail = if *relative {
                    Some(mounts::relative_detail(detail.clone()))
                } else {
                    detail.clone()
                };
                self.found(Family::Route, format!("{method} {path}"), at, None, detail);
            }
        }
    }

    /// The path and the methods; the methods are `None` when `methods=` is not a literal.
    fn path_and_methods(
        &self,
        args: &Args<'t>,
        kind: Kind,
        class: bool,
    ) -> (Option<Node<'t>>, Option<Vec<String>>) {
        let path = args.get(0, "path").or_else(|| args.keyword("rule"));
        match kind {
            Kind::Verb(verb) => (path, Some(vec![verb.to_uppercase()])),
            Kind::Websocket => (path, Some(vec!["WEBSOCKET".to_string()])),
            Kind::Any => (path, Some(vec!["ANY".to_string()])),
            Kind::Methods => self.route_methods(args, path, class),
        }
    }

    /// `route("/p", methods=[...])`, or aiohttp's form `route("GET", "/p")`.
    fn route_methods(
        &self,
        args: &Args<'t>,
        path: Option<Node<'t>>,
        class: bool,
    ) -> (Option<Node<'t>>, Option<Vec<String>>) {
        if let [method, path, ..] = args.positional[..]
            && let Some(method) = literal_string(method, self.source)
            && METHOD_NAMES.contains(&method.to_uppercase().as_str())
        {
            let method = if method == "*" {
                "ANY".to_string()
            } else {
                method.to_uppercase()
            };
            return (Some(path), Some(vec![method]));
        }
        let methods = match args.keyword("methods") {
            None => Some(default_methods(class)),
            Some(node) => literal_strings(node, self.source)
                .map(|ms| ms.iter().map(|m| m.to_uppercase()).collect()),
        };
        (path, methods)
    }

    pub(super) fn routes_call(&mut self, call: Node<'t>) {
        let Some(function) = call.child_by_field_name("function") else {
            return;
        };
        if let Some(qualified) = self.qualify(function) {
            self.qualified_route_call(call, &qualified);
        }
        self.route_call_form(call, function);
        if let Some((receiver, method)) = method_call(call, self.source) {
            self.urlpatterns_call(call, receiver, &method);
            self.server_method_call(call, &method);
            self.route_method_call(call, receiver, &method);
        }
    }

    /// The calls to functions that the imports name: `path(...)`, `Route(...)`, `web.get(...)`
    /// and server constructors.
    fn qualified_route_call(&mut self, call: Node<'t>, qualified: &str) {
        let at = line(call);
        match (head(qualified), last(qualified)) {
            ("django", "path") => self.django_path(call),
            ("django", "re_path" | "url") => self.django_regex(call),
            ("django", "include") => self.unresolved(Family::Route, at, prefix_note("include()")),
            ("starlette" | "fastapi", "Route" | "APIRoute") => self.starlette_route(call, false),
            ("starlette" | "fastapi", "WebSocketRoute" | "APIWebSocketRoute") => {
                self.starlette_route(call, true);
            }
            // `Mount` is read by `read_mounts`; `Host` serves its routes under a host name.
            ("starlette" | "fastapi", "Mount") => {}
            ("starlette" | "fastapi", "Host") => {
                self.unresolved(Family::Route, at, prefix_note("Host"));
            }
            ("aiohttp", "static") => self.unresolved(Family::Route, at, prefix_note("web.static")),
            ("aiohttp", name) => {
                if let Some(kind) = kind_of(name) {
                    let detail = self.handler_detail(call, 1);
                    self.emit_routes(call, kind, "aiohttp", detail, false);
                }
            }
            _ if stdlib_server(qualified) => self.stdlib_server_site(call, qualified),
            (_, constructor) => self.prefix_constructor(call, qualified, constructor),
        }
    }

    /// A standard-library server started by the program: what it serves cannot be enumerated
    /// (XML-RPC methods, a socket server's protocol, a WSGI application).
    fn stdlib_server_site(&mut self, call: Node<'t>, qualified: &str) {
        let at = line(call);
        let http = matches!(head(qualified), "http" | "socketserver" | "SocketServer")
            || qualified == "wsgiref.simple_server.make_server"
            || last(qualified) == "make_server";
        if http {
            self.unresolved(Family::Route, at, RAW_SERVER);
        } else {
            let reason =
                format!("a server is started with {qualified}; what it serves is not enumerated");
            self.unresolved(Family::Route, at, reason);
        }
    }

    /// `loop.create_server(...)`, `sock.listen()` in a file that imports `socket`: a service
    /// opened without a framework.
    fn server_method_call(&mut self, call: Node<'t>, method: &str) {
        let socket = ["socket", "_socket", "ssl"]
            .iter()
            .any(|m| self.imports.has(m));
        let serves = match method {
            "create_server" | "create_unix_server" => true,
            "create_datagram_endpoint" => Args::read(call, self.source)
                .keyword("local_addr")
                .is_some(),
            "listen" | "accept" => socket,
            _ => false,
        };
        if serves {
            let reason =
                format!("a server is opened with {method}(); what it serves is not enumerated");
            self.unresolved(Family::Route, line(call), reason);
        }
    }

    /// `FastAPI(root_path=...)`, `Api(prefix=...)` and Flask-RESTful/RESTX's `Namespace(...)`.
    /// `Blueprint(url_prefix=...)` and `APIRouter(prefix=...)` are composed by `read_mounts`.
    fn prefix_constructor(&mut self, call: Node<'t>, qualified: &str, constructor: &str) {
        let keyword = match (head(qualified), constructor) {
            ("fastapi", "FastAPI") => "root_path",
            ("flask_restful" | "flask_restx" | "flask_restplus", "Api") => "prefix",
            // A namespace is mounted under `/<name>` unless `path=` is given: always a prefix.
            ("flask_restx" | "flask_restplus", "Namespace") => {
                self.unresolved(Family::Route, line(call), prefix_note("Namespace"));
                return;
            }
            _ => return,
        };
        let args = Args::read(call, self.source);
        if self.has_prefix(&args, keyword) {
            self.unresolved(Family::Route, line(call), prefix_note(keyword));
        }
    }

    /// The keyword is given and is not the empty string.
    fn has_prefix(&self, args: &Args<'t>, keyword: &str) -> bool {
        args.keyword(keyword)
            .is_some_and(|n| literal_string(n, self.source).is_none_or(|p| !p.is_empty()))
    }

    /// `path("route/", view)`: the route. A view that is an include (`include(...)`, a tuple
    /// or a list of patterns, `admin.site.urls`, a call not known to be a view) mounts other
    /// patterns under this prefix: a site, and the file's included patterns are named under the
    /// prefix, never at the root.
    fn django_path(&mut self, call: Node<'t>) {
        let args = Args::read(call, self.source);
        let at = line(call);
        self.recognise(Family::Route, "django");
        let view = args.get(1, "view");
        match view.map(|v| self.django_view(v, 0)) {
            Some(View::Plain) | None => {}
            // `include(...)` already reports its prefix.
            Some(View::Include(_)) if view.is_some_and(|v| self.is_include(v)) => return,
            // A list in the file made of `path()` calls: its routes carry the prefix.
            Some(View::Include(Some(content))) if self.followed_patterns(content) => return,
            Some(View::Include(_) | View::Unknown) => {
                let what = view.map_or_else(String::new, |v| clip(self.text(v)));
                self.unresolved(
                    Family::Route,
                    at,
                    prefix_note(&format!("path() view {what}")),
                );
                return;
            }
        }
        let Some(literal) = args
            .get(0, "route")
            .and_then(|n| literal_string(n, self.source))
        else {
            self.unresolved(Family::Route, at, NOT_LITERAL_PATH);
            return;
        };
        for prefix in self.django_prefixes(call, 0) {
            let full = format!("{prefix}{literal}");
            let name = if full.starts_with('/') {
                full.clone()
            } else {
                format!("/{full}")
            };
            let under = if prefix.is_empty() {
                String::new()
            } else {
                format!(" under \"{prefix}\"")
            };
            let detail = format!(
                "path literal \"{literal}\"{under}{}",
                view.map(|v| format!("; view {}", clip(self.text(v))))
                    .unwrap_or_default()
            );
            self.found(Family::Route, format!("ANY {name}"), at, None, Some(detail));
        }
    }

    /// `re_path(...)`, `url(...)`: a regular expression, a site; with a view that is an
    /// include, a prefix as well.
    fn django_regex(&mut self, call: Node<'t>) {
        let at = line(call);
        self.unresolved(Family::Route, at, "route is a regular expression");
        let view = Args::read(call, self.source).get(1, "view");
        if let Some(view) = view
            && !self.is_include(view)
            && !matches!(self.django_view(view, 0), View::Plain)
        {
            let what = clip(self.text(view));
            self.unresolved(
                Family::Route,
                at,
                prefix_note(&format!("re_path() view {what}")),
            );
        }
    }

    /// The mounted patterns are a list in the file whose every element is a Django `path()`,
    /// `re_path()` or `url()`: each one receives the prefix or leaves its own site.
    fn followed_patterns(&self, content: Node<'t>) -> bool {
        let list = match content.kind() {
            "list" => Some(content),
            "identifier" => self.pattern_list(self.text(content)),
            _ => None,
        };
        list.is_some_and(|l| {
            named_children(l)
                .into_iter()
                .filter(|n| n.kind() != "comment")
                .all(|n| self.is_django_pattern(n))
        })
    }

    fn is_include(&self, node: Node<'t>) -> bool {
        node.kind() == "call"
            && node
                .child_by_field_name("function")
                .and_then(|f| self.qualify(f))
                .is_some_and(|q| head(&q) == "django" && last(&q) == "include")
    }

    /// Django's `path()`, `re_path()` or `url()`.
    fn is_django_pattern(&self, call: Node<'t>) -> bool {
        call.kind() == "call"
            && call
                .child_by_field_name("function")
                .and_then(|f| self.qualify(f))
                .is_some_and(|q| {
                    head(&q) == "django" && matches!(last(&q), "path" | "re_path" | "url")
                })
    }

    /// What the second argument of a `path()` is: a view, an include (with the patterns it
    /// mounts when they are in the file), or unknown.
    fn django_view(&self, view: Node<'t>, depth: usize) -> View<'t> {
        if depth > 4 {
            return View::Unknown;
        }
        match view.kind() {
            "lambda" => View::Plain,
            "parenthesized_expression" => named_children(view)
                .first()
                .map_or(View::Unknown, |inner| self.django_view(*inner, depth + 1)),
            // `(patterns, app_name, namespace)`, the form that `include()` returns.
            // A list is itself the mounted patterns.
            "list" => View::Include(Some(view)),
            "tuple" => View::Include(
                named_children(view)
                    .into_iter()
                    .find(|n| n.kind() != "comment"),
            ),
            "attribute" => {
                let name = last(self.text(view));
                if looks_like_patterns(name) {
                    View::Include(None)
                } else {
                    View::Plain
                }
            }
            "identifier" => {
                let name = self.text(view);
                // A list assigned at module level: followed by its name, with what is added
                // to it afterwards.
                if self.pattern_list(name).is_some() {
                    return View::Include(Some(view));
                }
                if let Some(right) = self.module_assignment(name)
                    && !matches!(self.django_view(right, depth + 1), View::Plain)
                {
                    return self.django_view(right, depth + 1);
                }
                if looks_like_patterns(name) {
                    View::Include(Some(view))
                } else {
                    View::Plain
                }
            }
            "call" => {
                if self.is_include(view) {
                    let args = Args::read(view, self.source);
                    let content = args.get(0, "arg").map(|a| {
                        if a.kind() == "tuple" {
                            named_children(a)
                                .into_iter()
                                .find(|n| n.kind() != "comment")
                                .unwrap_or(a)
                        } else {
                            a
                        }
                    });
                    return View::Include(content);
                }
                if method_call(view, self.source).is_some_and(|(_, m)| m == "as_view") {
                    return View::Plain;
                }
                // `login_required(v)`, `cache_page(60)(v)`: a Django view decorator.
                let mut function = view.child_by_field_name("function");
                for _ in 0..2 {
                    let Some(f) = function else {
                        break;
                    };
                    if self
                        .qualify(f)
                        .is_some_and(|q| head(&q) == "django" && q.contains(".decorators."))
                    {
                        return View::Plain;
                    }
                    function = (f.kind() == "call")
                        .then(|| f.child_by_field_name("function"))
                        .flatten();
                }
                View::Unknown
            }
            _ => View::Unknown,
        }
    }

    /// The first list assigned to `name` at module level (`api = [path(...)]`); what is done
    /// to it afterwards is read by `urlpatterns` and `django_list_reference`.
    fn pattern_list(&self, name: &str) -> Option<Node<'t>> {
        named_children(self.root)
            .into_iter()
            .filter(|s| s.kind() == "expression_statement")
            .filter_map(|s| {
                named_children(s)
                    .into_iter()
                    .find(|n| n.kind() == "assignment")
            })
            .filter(|a| {
                a.child_by_field_name("left")
                    .is_some_and(|l| l.kind() == "identifier" && self.text(l) == name)
            })
            .filter_map(|a| a.child_by_field_name("right"))
            .find(|r| r.kind() == "list")
    }

    /// The value of the last assignment `name = value` at module level.
    pub(super) fn module_assignment(&self, name: &str) -> Option<Node<'t>> {
        named_children(self.root)
            .into_iter()
            .filter(|s| s.kind() == "expression_statement")
            .filter_map(|s| {
                named_children(s)
                    .into_iter()
                    .find(|n| n.kind() == "assignment")
            })
            .filter(|a| {
                a.child_by_field_name("left")
                    .is_some_and(|l| l.kind() == "identifier" && self.text(l) == name)
            })
            .filter_map(|a| a.child_by_field_name("right"))
            .last()
    }

    /// The patterns that each include in the file mounts: for each included `path()`, the
    /// `path()`/`re_path()` calls that include it. Read once, before the walk.
    pub(super) fn read_django_mounts(&mut self) {
        if !self.imports.has("django") {
            return;
        }
        let mut patterns = Vec::new();
        let mut assignments: Vec<(String, Node<'t>)> = Vec::new();
        let mut appended: Vec<(String, Node<'t>)> = Vec::new();
        syntax::walk(self.root, |node| match node.kind() {
            "call" => {
                if self.is_django_pattern(node) {
                    patterns.push(node);
                }
                if let Some((receiver, method)) = method_call(node, self.source)
                    && matches!(method.as_str(), "append" | "extend" | "insert")
                    && receiver.kind() == "identifier"
                    && let Some(args) = node.child_by_field_name("arguments")
                {
                    appended.push((self.text(receiver).to_string(), args));
                }
            }
            "assignment" | "augmented_assignment" => {
                if let (Some(left), Some(right)) = (
                    node.child_by_field_name("left"),
                    node.child_by_field_name("right"),
                ) && left.kind() == "identifier"
                {
                    assignments.push((self.text(left).to_string(), right));
                }
            }
            _ => {}
        });
        let ids: HashSet<usize> = patterns.iter().map(Node::id).collect();
        let mut mounts: HashMap<usize, Vec<Node<'t>>> = HashMap::new();
        let mut lists = HashSet::new();
        for mount in &patterns {
            let Some(view) = Args::read(*mount, self.source).get(1, "view") else {
                continue;
            };
            let View::Include(Some(content)) = self.django_view(view, 0) else {
                continue;
            };
            let mut roots = Vec::new();
            match content.kind() {
                "identifier" => {
                    let name = self.text(content);
                    lists.insert(name.to_string());
                    roots.extend(
                        assignments
                            .iter()
                            .chain(&appended)
                            .filter(|(n, _)| n == name)
                            .map(|(_, r)| *r),
                    );
                }
                _ => roots.push(content),
            }
            for root in roots {
                let mut seen = 0;
                syntax::walk(root, |node| {
                    seen += 1;
                    if seen < 20_000 && node.id() != mount.id() && ids.contains(&node.id()) {
                        mounts.entry(node.id()).or_default().push(*mount);
                    }
                });
            }
        }
        self.django_mounts = mounts;
        self.django_lists = lists;
    }

    /// The prefixes under which a `path()` is mounted in the file: `[""]` at the root, nothing
    /// when all its includes are under a regular expression or a computed prefix (the site is
    /// at the include).
    fn django_prefixes(&self, call: Node<'t>, depth: usize) -> Vec<String> {
        let Some(mounts) = self.django_mounts.get(&call.id()) else {
            return vec![String::new()];
        };
        if depth >= 8 {
            return Vec::new();
        }
        let mut out = Vec::new();
        for mount in mounts {
            let is_path = mount
                .child_by_field_name("function")
                .and_then(|f| self.qualify(f))
                .is_some_and(|q| last(&q) == "path");
            let literal = Args::read(*mount, self.source)
                .get(0, "route")
                .and_then(|n| literal_string(n, self.source));
            let (true, Some(literal)) = (is_path, literal) else {
                continue;
            };
            for prefix in self.django_prefixes(*mount, depth + 1) {
                if out.len() < 64 {
                    out.push(format!("{prefix}{literal}"));
                }
            }
        }
        out.sort();
        out.dedup();
        out
    }

    /// Starlette's `Route("/path", endpoint, methods=[...])`.
    fn starlette_route(&mut self, call: Node<'t>, websocket: bool) {
        let kind = if websocket {
            Kind::Websocket
        } else {
            Kind::Methods
        };
        let args = Args::read(call, self.source);
        let detail = args
            .get(1, "endpoint")
            .map(|n| format!("handler {}", clip(self.text(n))));
        self.emit_routes(call, kind, "starlette", detail, false);
    }

    /// The registration methods: `add_url_rule`, `add_api_route`, `add_get`, `mount`...
    fn route_method_call(&mut self, call: Node<'t>, receiver: Node<'t>, method: &str) {
        let origin = self.route_origin(receiver);
        if matches!(origin, Origin::Other) {
            return;
        }
        let known = matches!(origin, Origin::Framework(_));
        let router =
            key(receiver, self.source).is_some_and(|k| k.to_lowercase().contains("router"));
        let aiohttp = self.imports.has("aiohttp") || router;
        let web = known || self.route_framework_imported();
        let at = line(call);
        match method {
            "add_url_rule" => self.emit_flask_rule(call),
            "add_api_route" | "add_api_websocket_route" | "add_websocket_route" if web => {
                let library = if method == "add_websocket_route" {
                    "starlette"
                } else {
                    "fastapi"
                };
                self.emit_registered(call, method, library, 1);
            }
            "add_route" => self.add_route(call, web),
            "add_view" if aiohttp || known => self.emit_registered(call, method, "aiohttp", 1),
            "add_get" | "add_post" | "add_put" | "add_patch" | "add_delete" | "add_head"
            | "add_options"
                if aiohttp || known =>
            {
                let verb = method.trim_start_matches("add_");
                self.emit_routes(
                    call,
                    Kind::Verb(verb),
                    "aiohttp",
                    self.handler_detail(call, 1),
                    false,
                );
            }
            "add_resource" => self.add_resource(call, aiohttp || known),
            "add_static" if aiohttp || known => {
                self.unresolved(Family::Route, at, prefix_note("add_static"));
            }
            // The mounts are composed by `read_mounts`.
            "register_blueprint" | "include_router" if web => {}
            // Flask-RESTX: `api.namespace("users")` and `api.add_namespace(ns, path=...)` mount
            // the resources under a prefix.
            "namespace" | "add_namespace"
                if ["flask_restx", "flask_restplus"]
                    .iter()
                    .any(|m| self.imports.has(m)) =>
            {
                self.unresolved(Family::Route, at, prefix_note(method));
            }
            // The `mount` of a tracked container is composed by `read_mounts`.
            "mount" if known && self.receiver_place(receiver).is_empty() => {
                self.unresolved(Family::Route, at, prefix_note("mount"));
            }
            "register"
                if (router || self.is_drf_router(receiver))
                    && self.imports.has("rest_framework") =>
            {
                self.unresolved(Family::Route, at, "routes are generated by a DRF router");
            }
            // A registration method on an object of unknown origin, in a file that imports no
            // framework: possibly a route, a site.
            m if matches!(origin, Origin::Unknown)
                && ((m.starts_with("add_") && kind_of(m).is_some())
                    || matches!(m, "add_static" | "register_blueprint" | "include_router")) =>
            {
                self.unresolved(Family::Route, at, UNKNOWN_ORIGIN);
            }
            // Any other method registers no route (`get`, `route` called without a handler
            // are read by `route_call_form` on the enclosing call).
            _ => {}
        }
    }

    /// The handler passed as argument `index`, as a detail.
    fn handler_detail(&self, call: Node<'t>, index: usize) -> Option<String> {
        let args = Args::read(call, self.source);
        args.get(index, "handler")
            .or_else(|| args.keyword("endpoint"))
            .map(|n| format!("handler {}", clip(self.text(n))))
    }

    fn emit_registered(&mut self, call: Node<'t>, method: &str, library: &str, handler: usize) {
        let kind = kind_of(method).unwrap_or(Kind::Methods);
        let detail = self.handler_detail(call, handler);
        self.emit_routes(call, kind, library, detail, false);
    }

    /// Flask's `app.add_url_rule("/p", "endpoint", view, methods=[...])`.
    fn emit_flask_rule(&mut self, call: Node<'t>) {
        let args = Args::read(call, self.source);
        let view = args.get(2, "view_func");
        let class_view =
            view.is_some_and(|v| method_call(v, self.source).is_some_and(|(_, m)| m == "as_view"));
        let detail = view.map(|v| format!("handler {}", clip(self.text(v))));
        self.emit_routes(
            call,
            Kind::Methods,
            "flask",
            detail,
            class_view && args.keyword("methods").is_none(),
        );
    }

    /// aiohttp's `add_route("GET", "/p", handler)` or Starlette's `add_route("/p", endpoint)`.
    fn add_route(&mut self, call: Node<'t>, web: bool) {
        let args = Args::read(call, self.source);
        let aiohttp = args
            .positional
            .first()
            .and_then(|n| literal_string(*n, self.source))
            .is_some_and(|m| METHOD_NAMES.contains(&m.to_uppercase().as_str()));
        if aiohttp {
            self.emit_routes(
                call,
                Kind::Methods,
                "aiohttp",
                self.handler_detail(call, 2),
                false,
            );
        } else if web {
            self.emit_routes(
                call,
                Kind::Methods,
                "starlette",
                self.handler_detail(call, 1),
                false,
            );
        } else {
            // `route_method_call` only gets here for an unknown origin.
            self.unresolved(Family::Route, line(call), UNKNOWN_ORIGIN);
        }
    }

    /// aiohttp's `add_resource("/p")`, or Flask-RESTful's `api.add_resource(Resource, "/a", "/b")`.
    fn add_resource(&mut self, call: Node<'t>, aiohttp: bool) {
        let args = Args::read(call, self.source);
        let at = line(call);
        let first_is_path = args
            .positional
            .first()
            .is_some_and(|n| n.kind() == "string");
        if first_is_path && aiohttp {
            self.unresolved(
                Family::Route,
                at,
                "route is added through a resource object",
            );
        } else if !first_is_path
            && ["flask_restful", "flask_restx", "flask_restplus"]
                .iter()
                .any(|m| self.imports.has(m))
        {
            self.restful_resource(call, &args);
        } else {
            self.unresolved(Family::Route, at, UNKNOWN_ORIGIN);
        }
    }

    fn restful_resource(&mut self, call: Node<'t>, args: &Args<'t>) {
        let at = line(call);
        self.recognise(Family::Route, "flask");
        let detail = args
            .positional
            .first()
            .map(|n| format!("handler {}", clip(self.text(*n))));
        for node in args.positional.iter().skip(1) {
            match literal_string(*node, self.source) {
                Some(path) => self.found(
                    Family::Route,
                    format!("ANY {path}"),
                    at,
                    None,
                    detail.clone(),
                ),
                None => self.unresolved(Family::Route, at, NOT_LITERAL_PATH),
            }
        }
    }

    /// The class answers requests by hand: `BaseHTTPRequestHandler`, `socketserver`.
    pub(super) fn is_raw_handler(&self, class: Node<'t>) -> bool {
        let Some(bases) = class.child_by_field_name("superclasses") else {
            return false;
        };
        named_children(bases).into_iter().any(|base| {
            self.qualify(base).is_some_and(|q| match head(&q) {
                "http" => last(&q).ends_with("HTTPRequestHandler"),
                "socketserver" | "SocketServer" => last(&q).ends_with("RequestHandler"),
                // An extended XML-RPC or WSGI handler or server: its methods serve.
                "xmlrpc" | "wsgiref" => {
                    let name = last(&q);
                    name.ends_with("Handler") || name.ends_with("Server")
                }
                _ => false,
            })
        })
    }

    /// A class that answers requests by hand.
    pub(super) fn raw_server_class(&mut self, class: Node<'t>) {
        if self.is_raw_handler(class) {
            self.unresolved(Family::Route, line(class), RAW_SERVER);
        }
    }

    /// A WSGI function (`environ, start_response`) or ASGI function (`scope, receive, send`)
    /// in a file with no framework whose routes can be read.
    pub(super) fn raw_callable(&mut self, function: Node<'t>) {
        if self.route_framework_imported() {
            return;
        }
        let names = parameter_names(function, self.source);
        let has = |n: &str| names.iter().any(|p| p == n);
        if has("start_response") || (has("scope") && has("receive") && has("send")) {
            self.unresolved(
                Family::Route,
                line(function),
                "requests are handled by a raw WSGI or ASGI callable; routes cannot be enumerated",
            );
        }
    }
}

/// A standard-library constructor or function (Python 3.13) that opens a service: servers of
/// `http.server`, `socketserver`, `xmlrpc.server` (and its CGI handlers), `wsgiref`,
/// `asyncio.start_server`, `socket.create_server`, `multiprocessing.connection.Listener`
/// and the managers of `multiprocessing.managers`.
fn stdlib_server(qualified: &str) -> bool {
    let name = last(qualified);
    match head(qualified) {
        "http" => {
            qualified.starts_with("http.server.") && (name.ends_with("Server") || name == "test")
        }
        "socketserver" | "SocketServer" => name.ends_with("Server"),
        "xmlrpc" => {
            qualified.starts_with("xmlrpc.server.")
                && (name.ends_with("Server") || name.ends_with("CGIXMLRPCRequestHandler"))
        }
        "wsgiref" => {
            name == "make_server"
                || name.ends_with("Server")
                || (qualified.starts_with("wsgiref.handlers.") && name.ends_with("Handler"))
        }
        "asyncio" => matches!(name, "start_server" | "start_unix_server"),
        "socket" => name == "create_server",
        "multiprocessing" => {
            name == "Listener" || (qualified.contains(".managers.") && name.ends_with("Manager"))
        }
        _ => false,
    }
}

fn prefix_note(what: &str) -> String {
    format!("routes are mounted under a prefix ({what}); listed paths under it are relative")
}

/// Where the receiver of a route declaration comes from.
enum Origin {
    /// An object that the file built with a web framework.
    Framework(&'static str),
    /// An origin proven foreign: a literal, a container, an HTTP client, a module that is not a
    /// framework. `requests.get("/x")` is not a route.
    Other,
    /// A parameter, an import of a local module, the result of a factory.
    Unknown,
}

/// The modules, from the standard library or from known clients and caches, whose objects are
/// never a web application.
const NON_WEB_MODULES: &[&str] = &[
    "requests",
    "httpx",
    "urllib",
    "urllib3",
    "http",
    "socket",
    "json",
    "collections",
    "functools",
    "itertools",
    "asyncio",
    "os",
    "sys",
    "re",
    "typing",
    "cachetools",
    "redis",
    "diskcache",
    "responses",
    "respx",
    "httpretty",
    "requests_mock",
    "pytest",
    "unittest",
    "logging",
    "pathlib",
    "subprocess",
    "shutil",
    "time",
    "datetime",
    "threading",
    "queue",
    "sqlite3",
];

/// The standard library's container constructors.
const CONTAINERS: &[&str] = &["dict", "list", "set", "tuple", "frozenset", "str", "bytes"];

impl<'t> Ctx<'t> {
    /// The variable was built by a `rest_framework` class (`DefaultRouter()`).
    fn is_drf_router(&self, receiver: Node<'t>) -> bool {
        key(receiver, self.source).is_some_and(|k| self.drf.contains(&k))
    }

    fn route_origin(&self, receiver: Node<'t>) -> Origin {
        match self.value_of(receiver) {
            Value::Known(Var::Web(library)) => Origin::Framework(library),
            Value::Known(_) => Origin::Other,
            Value::Param => Origin::Unknown,
            Value::Unknown if self.proven_other(receiver) => Origin::Other,
            Value::Unknown => Origin::Unknown,
        }
    }

    /// The expression is proven foreign to a web framework: a literal, a container, an object
    /// of a module in the list, or a variable already classed that way.
    pub(super) fn proven_other(&self, node: Node<'t>) -> bool {
        match node.kind() {
            "dictionary"
            | "list"
            | "set"
            | "tuple"
            | "string"
            | "concatenated_string"
            | "integer"
            | "float"
            | "true"
            | "false"
            | "none"
            | "list_comprehension"
            | "dictionary_comprehension"
            | "set_comprehension" => true,
            "call" => node.child_by_field_name("function").is_some_and(|f| {
                self.text(f) == "dict" && f.kind() == "identifier"
                    || CONTAINERS.contains(&self.text(f)) && f.kind() == "identifier"
                    || self.foreign(f)
            }),
            "identifier" | "attribute" => {
                self.foreign(node)
                    || key(node, self.source).is_some_and(|k| self.others.contains(&k))
            }
            _ => false,
        }
    }

    /// The name comes from an import of a module in `NON_WEB_MODULES`.
    fn foreign(&self, node: Node<'t>) -> bool {
        self.qualify(node)
            .is_some_and(|q| NON_WEB_MODULES.contains(&head(&q)))
    }

    /// `urlpatterns`, or a list of patterns that the file mounts by name (`path('api/',
    /// (api_patterns, 'api', 'api'))`): what each addition puts in it must be read.
    fn is_pattern_list(&self, name: &str) -> bool {
        name == "urlpatterns" || self.django_lists.contains(name)
    }

    /// `urlpatterns = [...]` or `urlpatterns += [...]` (and likewise for a mounted list):
    /// each entry must be a Django `path`, `re_path` or `include` call, otherwise the list
    /// cannot be enumerated.
    pub(super) fn urlpatterns(&mut self, node: Node<'t>) {
        if !self.imports.has("django") {
            return;
        }
        let Some(name) = node
            .child_by_field_name("left")
            .and_then(|l| key(l, self.source))
            .filter(|k| self.is_pattern_list(k))
        else {
            return;
        };
        if let Some(right) = node.child_by_field_name("right") {
            self.urlpattern_items(right, &name);
        }
    }

    /// The entries of an addition to a list of patterns: a literal list of calls, or a single
    /// call.
    fn urlpattern_items(&mut self, node: Node<'t>, name: &str) {
        self.urlpattern_items_at(node, name, 0);
    }

    fn urlpattern_items_at(&mut self, node: Node<'t>, name: &str, depth: usize) {
        match node.kind() {
            "list" if depth < super::ast::MAX_DEPTH => {
                for item in named_children(node) {
                    if item.kind() != "comment" {
                        self.urlpattern_items_at(item, name, depth + 1);
                    }
                }
            }
            "call" if self.is_django_route(node) => {}
            _ => self.unresolved(
                Family::Route,
                line(node),
                format!("{name} is not built from a literal list of path() calls"),
            ),
        }
    }

    fn is_django_route(&self, call: Node<'t>) -> bool {
        call.child_by_field_name("function")
            .and_then(|f| self.qualify(f))
            .is_some_and(|q| {
                head(&q) == "django" && matches!(last(&q), "path" | "re_path" | "url" | "include")
            })
    }

    /// `urlpatterns.append(path(...))`, `urlpatterns.extend([...])`; any other method that
    /// changes the list (`remove`, `pop`, `clear`, `sort`...) is a site: the listed routes may
    /// no longer be served.
    pub(super) fn urlpatterns_call(&mut self, call: Node<'t>, receiver: Node<'t>, method: &str) {
        let Some(name) = key(receiver, self.source)
            .filter(|k| receiver.kind() == "identifier" && self.is_pattern_list(k))
        else {
            return;
        };
        if !self.imports.has("django") {
            return;
        }
        match method {
            "append" | "extend" | "insert" => {
                let args = Args::read(call, self.source);
                match args.positional.last() {
                    Some(item) if !args.splat => self.urlpattern_items(*item, &name),
                    _ => self.unresolved(
                        Family::Route,
                        line(call),
                        format!("{name} is not built from a literal list of path() calls"),
                    ),
                }
            }
            // Reads.
            "copy" | "index" | "count" => {}
            _ => self.unresolved(
                Family::Route,
                line(call),
                format!("{name}.{method}() changes the patterns; the routes it serves are not enumerated"),
            ),
        }
    }

    /// A list of patterns named anywhere other than in a form that is read (assignment,
    /// addition, method, include by Django, read): passed to a function, returned, copied to
    /// another name, it may gain or lose patterns that cannot be seen.
    pub(super) fn django_list_reference(&mut self, node: Node<'t>) {
        if node.kind() != "identifier"
            || !self.imports.has("django")
            || !self.is_pattern_list(self.text(node))
        {
            return;
        }
        let name = self.text(node).to_string();
        // An identifier that does not denote the list: `x.urlpatterns`, `f(urlpatterns=...)`,
        // a parameter, an import, `global urlpatterns`.
        if let Some(p) = node.parent() {
            let named = |field: &str| {
                p.child_by_field_name(field)
                    .is_some_and(|n| n.id() == node.id())
            };
            let elsewhere = match p.kind() {
                "attribute" => named("attribute"),
                "keyword_argument" | "function_definition" | "class_definition" => named("name"),
                "parameters" | "default_parameter" | "typed_parameter" | "dotted_name"
                | "aliased_import" | "global_statement" | "nonlocal_statement" => true,
                _ => false,
            };
            if elsewhere {
                return;
            }
        }
        let mut child = node;
        let mut parent = node.parent();
        // Walks up the expressions that compose a value (`a + b`, `[*a]`, `(a)`).
        while let Some(p) = parent {
            if matches!(
                p.kind(),
                "binary_operator" | "list" | "list_splat" | "parenthesized_expression"
            ) {
                child = p;
                parent = p.parent();
            } else {
                break;
            }
        }
        let Some(parent) = parent else {
            return;
        };
        let is = |field: &str| {
            parent
                .child_by_field_name(field)
                .is_some_and(|n| n.id() == child.id())
        };
        let direct = child.id() == node.id();
        let consumed = match parent.kind() {
            // The target: `urlpatterns = ...`, `urlpatterns += ...`.
            "assignment" | "augmented_assignment" if is("left") => direct,
            // The value of an assignment to a list of patterns: the assignment has its site.
            "assignment" | "augmented_assignment" if is("right") => parent
                .child_by_field_name("left")
                .and_then(|l| key(l, self.source))
                .is_some_and(|k| self.is_pattern_list(&k)),
            // `urlpatterns.append(...)`: the method is read by `urlpatterns_call`.
            "attribute" if direct && is("object") => parent.parent().is_some_and(|c| {
                c.kind() == "call" && {
                    c.child_by_field_name("function")
                        .is_some_and(|f| f.id() == parent.id())
                }
            }),
            // `urlpatterns[i]` is a read; `urlpatterns[i] = x` changes the list.
            "subscript" if direct => !parent.parent().is_some_and(|a| {
                matches!(
                    a.kind(),
                    "assignment" | "augmented_assignment" | "delete_statement"
                ) && a
                    .child_by_field_name("left")
                    .is_none_or(|l| l.id() == parent.id())
            }),
            // `for p in urlpatterns`, `p in urlpatterns`.
            "for_statement" | "for_in_clause" if is("right") => direct,
            "comparison_operator" => direct,
            // An argument of a Django call (`path('api/', (api, 'a', 'a'))`) or of a read.
            "argument_list" | "tuple" | "keyword_argument" => {
                let call = std::iter::successors(Some(parent), |n| n.parent())
                    .take(3)
                    .find(|n| n.kind() == "call");
                call.is_some_and(|c| {
                    self.is_django_route(c)
                        || c.child_by_field_name("function").is_some_and(|f| {
                            f.kind() == "identifier"
                                && matches!(
                                    self.text(f),
                                    "len"
                                        | "print"
                                        | "repr"
                                        | "str"
                                        | "bool"
                                        | "enumerate"
                                        | "iter"
                                )
                        })
                })
            }
            _ => false,
        };
        if !consumed {
            self.unresolved(
                Family::Route,
                line(node),
                format!(
                    "{name} is used where its patterns may change; the routes added or removed there are not enumerated"
                ),
            );
        }
    }
}