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.

41.8 KB
Raw Blame
//! The environment variables: `os.environ` (and `os.environb`, `posix.environ`), `os.getenv`
//! (and `os.getenvb`) and the `BaseSettings` classes.

use std::collections::HashSet;

use tree_sitter::Node;

use super::ast::{Args, head, last, literal_name, literal_string, literal_strings, method_call};
use super::{Ctx, clip};
use crate::lang::syntax::{line, named_children};
use crate::obligations::Family;

const WHOLE_MAPPING: &str = "the whole environment is read, not named variables";
const NOT_LITERAL: &str = "environment variable name is not a string literal";

const SETTINGS_CLI: &str = "settings parse the command line (cli_parse_args); their flags and subcommands are not enumerated";
const SETTINGS_SOURCES: &str =
    "settings sources are chosen by code; the variables and flags they read are not enumerated";

/// The configuration keys of pydantic (v1 and v2) and of pydantic-settings that change neither
/// the name of the variables read nor the sources: any other key gives a site.
const SETTINGS_INERT: &[&str] = &[
    "env_file",
    "env_file_encoding",
    "env_ignore_empty",
    "env_parse_none_str",
    "env_parse_enums",
    "secrets_dir",
    "extra",
    "frozen",
    "strict",
    "validate_default",
    "validate_assignment",
    "validate_return",
    "revalidate_instances",
    "arbitrary_types_allowed",
    "str_strip_whitespace",
    "str_to_lower",
    "str_to_upper",
    "str_min_length",
    "str_max_length",
    "use_enum_values",
    "use_attribute_docstrings",
    "protected_namespaces",
    "title",
    "json_schema_extra",
    "json_encoders",
    "ser_json_timedelta",
    "ser_json_bytes",
    "ser_json_inf_nan",
    "coerce_numbers_to_str",
    "hide_input_in_errors",
    "defer_build",
    "regex_engine",
    "nested_model_default_partial_update",
    "yaml_file",
    "yaml_file_encoding",
    "toml_file",
    "json_file",
    "json_file_encoding",
    "pyproject_toml_depth",
    "pyproject_toml_table_header",
    // pydantic v1
    "allow_mutation",
    "validate_all",
    "orm_mode",
    "anystr_strip_whitespace",
    "anystr_lower",
    "underscore_attrs_are_private",
    "keep_untouched",
    "smart_union",
    "copy_on_model_validation",
];

/// How many levels of nested models are named under a settings field.
const NESTING: usize = 6;

/// The types whose value is read from a single variable, even with `env_nested_delimiter`.
const SCALARS: &[&str] = &[
    "str",
    "int",
    "float",
    "bool",
    "bytes",
    "complex",
    "Decimal",
    "Path",
    "PosixPath",
    "PurePath",
    "FilePath",
    "DirectoryPath",
    "datetime",
    "date",
    "time",
    "timedelta",
    "UUID",
    "SecretStr",
    "SecretBytes",
    "EmailStr",
    "NameEmail",
    "IPvAnyAddress",
    "IPv4Address",
    "IPv6Address",
    "ByteSize",
    "None",
];

/// The qualified names that denote the environment dictionary.
pub(super) fn is_environment(qualified: &str) -> bool {
    matches!(
        qualified,
        "os.environ" | "os.environb" | "posix.environ" | "posix.environb" | "nt.environ"
    )
}

/// The qualified names of the functions that read a named variable.
pub(super) fn is_getenv(qualified: &str) -> bool {
    matches!(qualified, "os.getenv" | "os.getenvb")
}

fn is_field(parent: Node, field: &str, node: Node) -> bool {
    parent
        .child_by_field_name(field)
        .is_some_and(|n| n.id() == node.id())
}

impl<'t> Ctx<'t> {
    /// `os.getenv("NAME"[, default])`, `os.getenvb(b"NAME")`.
    pub(super) fn env_call(&mut self, call: Node<'t>) {
        let Some(function) = call.child_by_field_name("function") else {
            return;
        };
        if !self.qualify(function).is_some_and(|q| is_getenv(&q)) {
            return;
        }
        let args = Args::read(call, self.source);
        self.env_read(args.get(0, "key"), args.get(1, "default"), line(call));
    }

    /// A read of the variable named by `key`.
    fn env_read(&mut self, key: Option<Node<'t>>, default: Option<Node<'t>>, at: u32) {
        self.recognise(Family::Env, "os");
        match key.and_then(|k| literal_name(k, self.source)) {
            Some(name) => {
                let detail = default.map(|d| format!("default {}", clip(self.text(d))));
                self.found(Family::Env, name, at, None, detail);
            }
            None => self.unresolved(Family::Env, at, NOT_LITERAL),
        }
    }

    /// `node` denotes `os.environ`: what the surrounding code does decides what it is.
    pub(super) fn environ_use(&mut self, node: Node<'t>) {
        let Some(parent) = node.parent() else {
            return;
        };
        let at = line(node);
        match parent.kind() {
            "attribute" if is_field(parent, "object", node) => self.environ_method(parent, at),
            "subscript" if is_field(parent, "value", node) => self.environ_item(parent, at),
            "comparison_operator" => self.environ_membership(node, at),
            "assignment" | "augmented_assignment" if is_field(parent, "left", node) => {}
            // `env = os.environ`: the alias is followed, its reads are named.
            "assignment"
                if parent
                    .child_by_field_name("left")
                    .is_some_and(|l| l.kind() == "identifier") => {}
            _ => self.environ_whole(node, at),
        }
    }

    fn environ_whole(&mut self, node: Node<'t>, at: u32) {
        self.recognise(Family::Env, "os");
        if !forwarded(node, self) {
            self.unresolved(Family::Env, at, WHOLE_MAPPING);
        }
    }

    /// `os.environ.get(...)` and the other methods of the dictionary.
    fn environ_method(&mut self, attribute: Node<'t>, at: u32) {
        let Some(method) = attribute.child_by_field_name("attribute") else {
            return;
        };
        let call = attribute
            .parent()
            .filter(|c| c.kind() == "call" && is_field(*c, "function", attribute));
        match (self.text(method), call) {
            ("get" | "setdefault" | "pop", Some(call)) => {
                let args = Args::read(call, self.source);
                self.env_read(args.get(0, "key"), args.get(1, "default"), at);
            }
            ("update" | "clear" | "popitem" | "__setitem__" | "__delitem__", Some(_)) => {}
            ("copy", Some(call)) => self.environ_whole(call, at),
            _ => self.environ_whole(attribute, at),
        }
    }

    /// `os.environ["NAME"]`, except when it is written or deleted.
    fn environ_item(&mut self, subscript: Node<'t>, at: u32) {
        if is_write(subscript) {
            return;
        }
        self.env_read(subscript.child_by_field_name("subscript"), None, at);
    }

    /// `"NAME" in os.environ`.
    fn environ_membership(&mut self, node: Node<'t>, at: u32) {
        let operator = node.prev_sibling().map(|n| n.kind());
        let left = node.prev_named_sibling();
        match (operator, left) {
            (Some("in" | "not in"), Some(left)) => self.env_read(Some(left), None, at),
            _ => self.environ_whole(node, at),
        }
    }
}

// ---- settings classes ---------------------------------------------------------------------------

/// How a settings class names its variables; `None` when the value is not a literal.
#[derive(Clone, Debug, PartialEq)]
struct Conf {
    prefix: Option<String>,
    case_sensitive: Option<bool>,
    /// `env_nested_delimiter`: `Some(None)` when there is none.
    delimiter: Option<Option<String>>,
    /// What renames the fields other than the prefix (`alias_generator`, `populate_by_name`,
    /// `fields`): the reason of the site, inherited by subclasses.
    renamed: Option<String>,
}

impl Conf {
    fn pydantic() -> Self {
        Self {
            prefix: Some(String::new()),
            case_sensitive: Some(false),
            delimiter: Some(None),
            renamed: None,
        }
    }

    /// The name as pydantic looks it up: as written with `case_sensitive=True`, in uppercase
    /// otherwise (the usual form; the lookup then ignores case).
    fn cased(&self, name: &str) -> String {
        if self.case_sensitive == Some(true) {
            name.to_string()
        } else {
            name.to_uppercase()
        }
    }
}

/// A settings class of the file.
pub(super) struct Settings<'t> {
    conf: Conf,
    class: Node<'t>,
    /// The settings class of the file that it inherits from.
    parent: Option<String>,
}

/// The base of a settings class.
enum Base {
    Pydantic,
    Local(String),
    /// An imported class that looks like a settings class: its name.
    Foreign(String),
}

/// What the type of a field gives with `env_nested_delimiter`.
enum Shape<'t> {
    /// A single variable.
    Scalar,
    /// A model defined in the file: one variable per field, under the delimiter.
    Model(Node<'t>),
    /// A model or a dictionary that is not visible: variables that cannot be named.
    Opaque,
}

impl<'t> Ctx<'t> {
    /// A class that inherits from `BaseSettings`: each annotated field is an environment
    /// variable, named by the field, the class prefix or an alias.
    pub(super) fn settings_class(&mut self, class: Node<'t>) {
        let (Some(name), Some(bases)) = (
            class.child_by_field_name("name"),
            class.child_by_field_name("superclasses"),
        ) else {
            return;
        };
        let name = self.text(name).to_string();
        let mut base = None;
        for node in named_children(bases) {
            if matches!(node.kind(), "keyword_argument" | "comment") {
                continue;
            }
            if let Some(found) = self.settings_base(class, node) {
                let decisive = !matches!(found, Base::Foreign(_));
                base = Some(found);
                if decisive {
                    break;
                }
            }
        }
        let at = line(class);
        let (inherited, parent) = match base {
            None => return,
            Some(Base::Foreign(base)) => {
                self.foreign_settings.insert(name);
                if self.declares_settings(class) {
                    self.unresolved(
                        Family::Env,
                        at,
                        format!(
                            "settings class inherits from imported {base}; its fields are not followed"
                        ),
                    );
                }
                return;
            }
            Some(Base::Pydantic) => (Conf::pydantic(), None),
            Some(Base::Local(parent)) => match self.settings.get(&parent) {
                Some(s) => (s.conf.clone(), Some(parent)),
                None => return,
            },
        };
        let conf = self.settings_conf(class, inherited, at);
        self.settings.insert(
            name.clone(),
            Settings {
                conf: conf.clone(),
                class,
                parent,
            },
        );
        if conf.prefix.is_none() {
            self.unresolved(
                Family::Env,
                at,
                "settings fields are read under a prefix that is not known",
            );
            return;
        }
        if let Some(reason) = conf.renamed.clone() {
            self.unresolved(Family::Env, at, reason);
            return;
        }
        if conf.case_sensitive.is_none() {
            return;
        }
        self.recognise(Family::Env, "pydantic");
        // The fields of the class, and those of the parent classes of the file when it reads
        // them under another configuration (`env_prefix` changed in the subclass).
        let before = self.out.found.len();
        let mut ancestors = false;
        let mut current = Some(name);
        for _ in 0..16 {
            let Some(key) = current else {
                break;
            };
            let Some(settings) = self.settings.get(&key) else {
                break;
            };
            let (owner, own_conf, next) = (
                settings.class,
                settings.conf.clone(),
                settings.parent.clone(),
            );
            // A parent class read under the same configuration has already named its fields
            // (and those of its own parents).
            if owner.id() != class.id() && own_conf == conf {
                break;
            }
            ancestors |= owner.id() != class.id();
            for statement in owner
                .child_by_field_name("body")
                .map(named_children)
                .unwrap_or_default()
            {
                self.settings_field(statement, &conf);
            }
            current = next;
        }
        // An alias does not depend on the prefix: the parent class has already named it on the
        // same line.
        if ancestors {
            let added = self.out.found.split_off(before);
            let mut known: HashSet<(String, u32)> = self
                .out
                .found
                .iter()
                .filter(|f| f.family == Family::Env)
                .map(|f| (f.name.clone(), f.line))
                .collect();
            for item in added {
                if item.family != Family::Env || known.insert((item.name.clone(), item.line)) {
                    self.out.found.push(item);
                }
            }
        }
    }

    /// What a base makes of the class: a settings class of pydantic, of the file, or imported.
    /// `None` for any other base.
    fn settings_base(&self, class: Node<'t>, base: Node<'t>) -> Option<Base> {
        let qualified = self.qualify(base);
        if let Some(q) = qualified.as_deref()
            && matches!(head(q), "pydantic" | "pydantic_settings")
        {
            return (last(q) == "BaseSettings").then_some(Base::Pydantic);
        }
        let text = self.text(base);
        if self.settings.contains_key(text) {
            return Some(Base::Local(text.to_string()));
        }
        if self.foreign_settings.contains(text) {
            return Some(Base::Foreign(text.to_string()));
        }
        let q = qualified?;
        if matches!(
            head(&q),
            "typing" | "typing_extensions" | "enum" | "abc" | "dataclasses" | "collections"
        ) {
            return None;
        }
        let looks = last(&q).contains("Settings")
            || self.configures_env(class)
            || self.imports.has("pydantic_settings");
        looks.then(|| Base::Foreign(last(&q).to_string()))
    }

    /// The class declares annotated fields or a configuration: it has something to read.
    fn declares_settings(&self, class: Node<'t>) -> bool {
        let (entries, opaque) = self.config_entries(class);
        opaque
            || !entries.is_empty()
            || class
                .child_by_field_name("body")
                .map(named_children)
                .unwrap_or_default()
                .into_iter()
                .any(|s| self.annotated_field(s).is_some())
    }

    /// The configuration of the class concerns environment variables.
    fn configures_env(&self, class: Node<'t>) -> bool {
        let (entries, _) = self.config_entries(class);
        entries
            .iter()
            .any(|(k, _)| k.starts_with("env_") || k == "case_sensitive")
            || class
                .child_by_field_name("body")
                .map(named_children)
                .unwrap_or_default()
                .into_iter()
                .filter_map(assignment_of)
                .filter_map(|a| a.child_by_field_name("right"))
                .any(|r| {
                    r.kind() == "call"
                        && r.child_by_field_name("function")
                            .is_some_and(|f| last(self.text(f)) == "SettingsConfigDict")
                })
    }

    /// The settings of the class: the keywords of the declaration (`class S(BaseSettings,
    /// env_prefix="A_")`), `model_config = SettingsConfigDict(...)` or a dictionary, and
    /// `class Config:`. The boolean says that part of it is not readable.
    fn config_entries(&self, class: Node<'t>) -> (Vec<(String, Node<'t>)>, bool) {
        let mut entries = Vec::new();
        let mut opaque = false;
        if let Some(bases) = class.child_by_field_name("superclasses") {
            for node in named_children(bases) {
                match node.kind() {
                    "keyword_argument" => {
                        if let (Some(k), Some(v)) = (
                            node.child_by_field_name("name"),
                            node.child_by_field_name("value"),
                        ) {
                            entries.push((self.text(k).to_string(), v));
                        }
                    }
                    "dictionary_splat" | "list_splat" => opaque = true,
                    _ => {}
                }
            }
        }
        let Some(body) = class.child_by_field_name("body") else {
            return (entries, opaque);
        };
        for statement in named_children(body) {
            if statement.kind() == "class_definition"
                && statement
                    .child_by_field_name("name")
                    .is_some_and(|n| self.text(n) == "Config")
            {
                for inner in statement
                    .child_by_field_name("body")
                    .map(named_children)
                    .unwrap_or_default()
                {
                    if let Some(assignment) = assignment_of(inner)
                        && let (Some(left), Some(right)) = (
                            assignment.child_by_field_name("left"),
                            assignment.child_by_field_name("right"),
                        )
                        && left.kind() == "identifier"
                    {
                        entries.push((self.text(left).to_string(), right));
                    }
                }
                continue;
            }
            let Some(assignment) = assignment_of(statement) else {
                continue;
            };
            let (Some(left), Some(right)) = (
                assignment.child_by_field_name("left"),
                assignment.child_by_field_name("right"),
            ) else {
                continue;
            };
            if left.kind() != "identifier" || self.text(left) != "model_config" {
                continue;
            }
            match right.kind() {
                "call" => {
                    let args = Args::read(right, self.source);
                    opaque |= args.splat || !args.positional.is_empty();
                    entries.extend(args.keywords.iter().map(|(k, v)| (k.clone(), *v)));
                }
                "dictionary" => {
                    for pair in named_children(right) {
                        match pair.kind() {
                            "pair" => {
                                let key = pair
                                    .child_by_field_name("key")
                                    .and_then(|k| literal_string(k, self.source));
                                match (key, pair.child_by_field_name("value")) {
                                    (Some(k), Some(v)) => entries.push((k, v)),
                                    _ => opaque = true,
                                }
                            }
                            "comment" => {}
                            _ => opaque = true,
                        }
                    }
                }
                _ => opaque = true,
            }
        }
        (entries, opaque)
    }

    /// The configuration of the class, starting from the one it inherits.
    fn settings_conf(&mut self, class: Node<'t>, inherited: Conf, at: u32) -> Conf {
        let (entries, opaque) = self.config_entries(class);
        let mut conf = inherited;
        if opaque {
            self.unresolved(
                Family::Env,
                at,
                "settings config is not a literal; how its fields are named is not known",
            );
            conf = Conf {
                prefix: None,
                case_sensitive: None,
                delimiter: None,
                renamed: conf.renamed,
            };
        }
        self.settings_sources(class, at);
        for (key, value) in entries {
            match key.as_str() {
                "env_prefix" => {
                    conf.prefix = literal_string(value, self.source);
                    if conf.prefix.is_none() {
                        self.unresolved(
                            Family::Env,
                            at,
                            "settings env_prefix is not a string literal",
                        );
                    }
                }
                "case_sensitive" => {
                    conf.case_sensitive = match self.text(value) {
                        "True" => Some(true),
                        "False" => Some(false),
                        _ => {
                            self.unresolved(
                                Family::Env,
                                at,
                                "settings case_sensitive is not a literal; the case of its names is not known",
                            );
                            None
                        }
                    };
                }
                "env_nested_delimiter" => {
                    conf.delimiter = match literal_string(value, self.source) {
                        Some(d) if !d.is_empty() => Some(Some(d)),
                        Some(_) => Some(None),
                        None if self.text(value) == "None" => Some(None),
                        None => {
                            self.unresolved(
                                Family::Env,
                                at,
                                "settings env_nested_delimiter is not a string literal",
                            );
                            None
                        }
                    };
                }
                "cli_parse_args" => {
                    if !matches!(self.text(value), "False" | "None") {
                        self.unresolved(Family::Flag, at, SETTINGS_CLI);
                        self.unresolved(Family::Command, at, SETTINGS_CLI);
                    }
                }
                "alias_generator" | "populate_by_name" | "validate_by_name" | "fields" => {
                    if !matches!(self.text(value), "False" | "None") {
                        conf.renamed = Some(format!(
                            "settings config {key} renames the fields; the variables they are read from are not enumerated"
                        ));
                    }
                }
                k if SETTINGS_INERT.contains(&k) || k.starts_with("cli_") => {}
                k => self.unresolved(
                    Family::Env,
                    at,
                    format!(
                        "settings config {k} is not followed; it may change which variables are read"
                    ),
                ),
            }
        }
        conf
    }

    /// `settings_customise_sources` (pydantic v2) or `customise_sources` in `class Config`
    /// (v1): the sources, and so the variables and flags read, are chosen by code.
    fn settings_sources(&mut self, class: Node<'t>, at: u32) {
        let body = |node: Node<'t>| {
            node.child_by_field_name("body")
                .map(named_children)
                .unwrap_or_default()
        };
        let defined = |node: Node<'t>, name: &str| {
            let node = if node.kind() == "decorated_definition" {
                match node.child_by_field_name("definition") {
                    Some(d) => d,
                    None => return false,
                }
            } else {
                node
            };
            node.kind() == "function_definition"
                && node
                    .child_by_field_name("name")
                    .is_some_and(|n| self.text(n) == name)
        };
        let mut custom = false;
        for statement in body(class) {
            custom |= defined(statement, "settings_customise_sources");
            if statement.kind() == "class_definition"
                && statement
                    .child_by_field_name("name")
                    .is_some_and(|n| self.text(n) == "Config")
            {
                custom |= body(statement)
                    .into_iter()
                    .any(|s| defined(s, "customise_sources"));
            }
        }
        if custom {
            self.unresolved(Family::Env, at, SETTINGS_SOURCES);
            self.unresolved(Family::Flag, at, SETTINGS_SOURCES);
        }
    }

    /// A call that configures a settings class at instantiation (`S(_cli_parse_args=True)`,
    /// `S(_env_prefix="A_")`), or that starts `CliApp`: flags or variables that are not
    /// named.
    pub(super) fn settings_call(&mut self, call: Node<'t>) {
        if !self.imports.has("pydantic_settings") {
            return;
        }
        let at = line(call);
        if let Some(function) = call.child_by_field_name("function")
            && let Some(q) = self.qualify(function)
            && (q.starts_with("pydantic_settings.CliApp")
                || q.starts_with("pydantic_settings.CliSettingsSource"))
        {
            let reason = format!(
                "{} parses the command line; its flags are not enumerated",
                last(&q)
            );
            self.unresolved(Family::Flag, at, reason.clone());
            self.unresolved(Family::Command, at, reason);
            return;
        }
        let args = Args::read(call, self.source);
        for (key, value) in &args.keywords {
            match key.as_str() {
                "_cli_parse_args" if !matches!(self.text(*value), "False" | "None") => {
                    self.unresolved(Family::Flag, at, SETTINGS_CLI);
                    self.unresolved(Family::Command, at, SETTINGS_CLI);
                }
                "_env_prefix" | "_case_sensitive" | "_env_nested_delimiter"
                | "_env_prefix_target" => self.unresolved(
                    Family::Env,
                    at,
                    format!(
                        "settings are created with {key}; the variables they read are not enumerated"
                    ),
                ),
                _ => {}
            }
        }
    }

    /// `name: type [= value]` in the body of a class: the assignment, the name and the type.
    fn annotated_field(&self, statement: Node<'t>) -> Option<(Node<'t>, String, Node<'t>)> {
        let assignment = assignment_of(statement)?;
        let left = assignment.child_by_field_name("left")?;
        let annotation = assignment.child_by_field_name("type")?;
        if left.kind() != "identifier" {
            return None;
        }
        let field = self.text(left);
        if field.starts_with('_')
            || field == "model_config"
            || self.text(annotation).contains("ClassVar")
        {
            return None;
        }
        Some((assignment, field.to_string(), annotation))
    }

    /// An annotated field of the body of a settings class.
    fn settings_field(&mut self, statement: Node<'t>, conf: &Conf) {
        let Some((assignment, field, annotation)) = self.annotated_field(statement) else {
            return;
        };
        let Some(prefix) = conf.prefix.as_deref() else {
            return;
        };
        let at = line(statement);
        let value = assignment.child_by_field_name("right");
        let field_call = value.filter(|v| v.kind() == "call" && self.is_field_call(*v));
        let names = match self.field_call(field_call, annotation) {
            Some(call) => self.field_aliases(call),
            None => Aliases::None,
        };
        let names: Vec<String> = match names {
            Aliases::Given(names) => names.iter().map(|n| conf.cased(n)).collect(),
            Aliases::Unknown => {
                self.unresolved(
                    Family::Env,
                    at,
                    "settings field alias is not made of string literals",
                );
                return;
            }
            Aliases::None => vec![conf.cased(&format!("{prefix}{field}"))],
        };
        let detail = match (value, field_call) {
            (Some(default), None) => format!("default {}", clip(self.text(default))),
            _ => format!("settings field {field}"),
        };
        for name in &names {
            self.found(Family::Env, name.clone(), at, None, Some(detail.clone()));
        }
        if let Some(Some(delimiter)) = &conf.delimiter {
            for name in names {
                self.nested_names(annotation, &name, delimiter, conf, &field, at, 0);
            }
        }
    }

    /// `field: Model` with `env_nested_delimiter`: `FIELD__SUB_FIELD` for each field of the
    /// model, if it is defined in the file; a site otherwise.
    #[allow(clippy::too_many_arguments)]
    fn nested_names(
        &mut self,
        annotation: Node<'t>,
        base: &str,
        delimiter: &str,
        conf: &Conf,
        field: &str,
        at: u32,
        depth: usize,
    ) {
        match self.shape(annotation, 0) {
            Shape::Scalar => {}
            Shape::Opaque => self.unresolved(
                Family::Env,
                at,
                format!(
                    "settings field {field} may be read as nested variables under {delimiter}; its type is not defined in this file"
                ),
            ),
            Shape::Model(_) if depth >= NESTING => self.unresolved(
                Family::Env,
                at,
                format!("settings field {field} nests models too deep to follow"),
            ),
            Shape::Model(model) => {
                for statement in model
                    .child_by_field_name("body")
                    .map(named_children)
                    .unwrap_or_default()
                {
                    let Some((assignment, sub, sub_annotation)) = self.annotated_field(statement)
                    else {
                        continue;
                    };
                    let value = assignment.child_by_field_name("right");
                    let call = value.filter(|v| v.kind() == "call" && self.is_field_call(*v));
                    let sub_names = match self.field_call(call, sub_annotation) {
                        Some(call) => self.field_aliases(call),
                        None => Aliases::None,
                    };
                    let sub = match sub_names {
                        Aliases::Given(names) if names.len() == 1 => names[0].clone(),
                        Aliases::None => sub,
                        _ => {
                            self.unresolved(
                                Family::Env,
                                at,
                                format!("nested settings field {field}.{sub} has an alias that is not followed"),
                            );
                            continue;
                        }
                    };
                    let name = conf.cased(&format!("{base}{delimiter}{sub}"));
                    let path = format!("{field}.{sub}");
                    self.found(
                        Family::Env,
                        name.clone(),
                        at,
                        None,
                        Some(format!("nested settings field {path}")),
                    );
                    self.nested_names(
                        sub_annotation,
                        &name,
                        delimiter,
                        conf,
                        &path,
                        at,
                        depth + 1,
                    );
                }
            }
        }
    }

    /// What the type of a field gives with a nesting delimiter.
    fn shape(&self, node: Node<'t>, depth: usize) -> Shape<'t> {
        if depth > 8 {
            return Shape::Opaque;
        }
        match node.kind() {
            "type" | "parenthesized_expression" => named_children(node)
                .first()
                .map_or(Shape::Opaque, |n| self.shape(*n, depth + 1)),
            "identifier" => self.named_shape(self.text(node)),
            "attribute" | "member_type" => self.named_shape(last(self.text(node))),
            "none" => Shape::Scalar,
            "string" => literal_string(node, self.source)
                .map_or(Shape::Opaque, |name| self.named_shape(&name)),
            "binary_operator" | "union_type" => {
                let parts: Vec<Shape> = named_children(node)
                    .into_iter()
                    .map(|n| self.shape(n, depth + 1))
                    .collect();
                combine(parts)
            }
            "subscript" | "generic_type" => {
                let children = named_children(node);
                let Some(value) = node
                    .child_by_field_name("value")
                    .or_else(|| children.first().copied())
                else {
                    return Shape::Opaque;
                };
                let arguments: Vec<Node> = if node.kind() == "subscript" {
                    let mut cursor = node.walk();
                    node.children_by_field_name("subscript", &mut cursor)
                        .collect()
                } else {
                    children
                        .iter()
                        .filter(|c| c.kind() == "type_parameter")
                        .flat_map(|c| named_children(*c))
                        .collect()
                };
                match last(self.text(value)) {
                    "Optional" | "Annotated" | "Required" | "NotRequired" | "Final" => arguments
                        .first()
                        .map_or(Shape::Opaque, |a| self.shape(*a, depth + 1)),
                    "Union" => combine(
                        arguments
                            .iter()
                            .map(|a| self.shape(*a, depth + 1))
                            .collect(),
                    ),
                    "list" | "List" | "set" | "Set" | "frozenset" | "FrozenSet" | "tuple"
                    | "Tuple" | "Sequence" | "Iterable" | "Literal" => Shape::Scalar,
                    _ => Shape::Opaque,
                }
            }
            _ => Shape::Opaque,
        }
    }

    fn named_shape(&self, name: &str) -> Shape<'t> {
        if SCALARS.contains(&name)
            || name.ends_with("Url")
            || name.ends_with("Dsn")
            || name.ends_with("Str")
        {
            return Shape::Scalar;
        }
        let Some(class) = self.classes.get(name).copied() else {
            return Shape::Opaque;
        };
        let is_enum = class
            .child_by_field_name("superclasses")
            .map(named_children)
            .unwrap_or_default()
            .into_iter()
            .any(|b| self.qualify(b).is_some_and(|q| head(&q) == "enum"));
        if is_enum {
            return Shape::Scalar;
        }
        let has_fields = class
            .child_by_field_name("body")
            .map(named_children)
            .unwrap_or_default()
            .into_iter()
            .any(|s| self.annotated_field(s).is_some());
        if has_fields {
            Shape::Model(class)
        } else {
            Shape::Opaque
        }
    }

    fn is_field_call(&self, call: Node<'t>) -> bool {
        call.child_by_field_name("function")
            .is_some_and(|f| last(self.text(f)) == "Field")
    }

    /// The `Field(...)` of a field: its value, or the one in `Annotated[type, Field(...)]`.
    fn field_call(&self, value: Option<Node<'t>>, annotation: Node<'t>) -> Option<Node<'t>> {
        if value.is_some() {
            return value;
        }
        let mut node = annotation;
        if node.kind() == "type" {
            node = *named_children(node).first()?;
        }
        if !matches!(node.kind(), "subscript" | "generic_type") {
            return None;
        }
        let mut found = None;
        let mut stack = named_children(node);
        let mut seen = 0;
        while let Some(n) = stack.pop() {
            seen += 1;
            if seen > 64 {
                break;
            }
            if n.kind() == "call" && self.is_field_call(n) {
                found = Some(n);
                break;
            }
            if matches!(n.kind(), "type" | "type_parameter") {
                stack.extend(named_children(n));
            }
        }
        found
    }

    /// `Field(alias="X")`, `Field(validation_alias=AliasChoices("A", "B"))`, `Field(env="X")`
    /// or `Field(env=["A", "B"])` (pydantic 1).
    fn field_aliases(&self, call: Node<'t>) -> Aliases {
        let args = Args::read(call, self.source);
        for keyword in ["validation_alias", "alias", "env"] {
            let Some(node) = args.keyword(keyword) else {
                continue;
            };
            if keyword == "env"
                && let Some(names) = literal_strings(node, self.source)
            {
                return Aliases::Given(names);
            }
            if let Some(name) = literal_string(node, self.source) {
                return Aliases::Given(vec![name]);
            }
            let choices = (node.kind() == "call"
                && node
                    .child_by_field_name("function")
                    .is_some_and(|f| last(self.text(f)) == "AliasChoices"))
            .then(|| Args::read(node, self.source));
            let names: Option<Vec<String>> = choices.and_then(|a| {
                (!a.splat)
                    .then(|| {
                        a.positional
                            .iter()
                            .map(|n| literal_string(*n, self.source))
                            .collect()
                    })
                    .flatten()
            });
            return names.map_or(Aliases::Unknown, Aliases::Given);
        }
        if args.splat {
            return Aliases::Unknown;
        }
        Aliases::None
    }
}

/// A union: a single model with `None` gives the model; only scalars, a scalar.
fn combine(parts: Vec<Shape>) -> Shape {
    let mut model = None;
    for part in parts {
        match part {
            Shape::Scalar => {}
            Shape::Opaque => return Shape::Opaque,
            Shape::Model(m) if model.is_none() => model = Some(m),
            Shape::Model(_) => return Shape::Opaque,
        }
    }
    model.map_or(Shape::Scalar, Shape::Model)
}

/// The names that a `Field(...)` gives to a variable.
enum Aliases {
    Given(Vec<String>),
    Unknown,
    None,
}

/// The assignment of an expression statement: `x: int = 1`.
fn assignment_of(statement: Node) -> Option<Node> {
    if statement.kind() != "expression_statement" {
        return None;
    }
    named_children(statement)
        .into_iter()
        .find(|n| n.kind() == "assignment")
}

/// A write: `os.environ["X"] = ...`, `os.environ["X"] += ...` or `del os.environ["X"]`.
fn is_write(subscript: Node) -> bool {
    let Some(parent) = subscript.parent() else {
        return false;
    };
    match parent.kind() {
        "assignment" | "augmented_assignment" => is_field(parent, "left", subscript),
        "delete_statement" => true,
        "expression_list" => parent
            .parent()
            .is_some_and(|p| p.kind() == "delete_statement"),
        _ => false,
    }
}

/// The mapping is passed whole to a subprocess: `env=os.environ`, `env=os.environ.copy()`,
/// `env={**os.environ, "X": "1"}` or `env=dict(os.environ, X="1")` in a call that starts a
/// process. This is not a read; `env=` of another function (a template, a library) may be
/// one.
fn forwarded(node: Node, ctx: &Ctx) -> bool {
    let mut current = node;
    for _ in 0..4 {
        let Some(parent) = current.parent() else {
            return false;
        };
        match parent.kind() {
            "keyword_argument" => {
                return is_field(parent, "value", current)
                    && parent
                        .child_by_field_name("name")
                        .is_some_and(|n| ctx.text(n) == "env")
                    && parent
                        .parent()
                        .and_then(|list| list.parent())
                        .is_some_and(|call| spawns(call, ctx));
            }
            "dictionary_splat" | "dictionary" => current = parent,
            "argument_list" => match parent.parent() {
                Some(call) if is_dict_call(call, ctx) => current = call,
                _ => return false,
            },
            _ => return false,
        }
    }
    false
}

/// The call starts a process: `subprocess.*`, `asyncio.create_subprocess_*`, `os.exec*` or
/// `os.spawn*`, or an asyncio loop (`loop.subprocess_exec`).
fn spawns(call: Node, ctx: &Ctx) -> bool {
    if call.kind() != "call" {
        return false;
    }
    if let Some((_, method)) = method_call(call, ctx.source)
        && matches!(
            method.as_str(),
            "subprocess_exec"
                | "subprocess_shell"
                | "create_subprocess_exec"
                | "create_subprocess_shell"
        )
    {
        return true;
    }
    let Some(qualified) = call
        .child_by_field_name("function")
        .and_then(|f| ctx.qualify(f))
    else {
        return false;
    };
    match head(&qualified) {
        "subprocess" => true,
        "asyncio" => last(&qualified).starts_with("create_subprocess"),
        "os" => {
            let name = last(&qualified);
            name.starts_with("exec") || name.starts_with("spawn") || name.starts_with("posix_spawn")
        }
        _ => false,
    }
}

fn is_dict_call(call: Node, ctx: &Ctx) -> bool {
    call.kind() == "call"
        && method_call(call, ctx.source).is_none()
        && call
            .child_by_field_name("function")
            .is_some_and(|f| ctx.text(f) == "dict")
}

impl<'t> Ctx<'t> {
    /// `os.getenv` passed as a value (`map(os.getenv, names)`): the names read are not visible.
    pub(super) fn getenv_value(&mut self, node: Node<'t>) {
        let called = node
            .parent()
            .is_some_and(|p| p.kind() == "call" && is_field(p, "function", node));
        if !called {
            self.unresolved(
                Family::Env,
                line(node),
                "os.getenv is passed as a value; the names it reads are not enumerated",
            );
        }
    }
}