Skip to main content

arbor_core/usages/
python.rs

1//! Python SDK usage extraction.
2//!
3//! # Soundness policy
4//!
5//! A value or route reported with no gap is confirmed: a consumer acts on it
6//! without asking. Python is too dynamic to make that hold by resolving every
7//! shape, so this module resolves a small **supported grammar** exactly and
8//! turns everything else into a gap. `docs/SDK_USAGES.md` states the grammar
9//! in full; in short, a value or route has no gap only when it is:
10//!
11//! - a string literal written at the call (never downgraded);
12//! - a name with one reaching assignment of such a value, in the scope that
13//!   binds it (module constant, local, enclosing local);
14//! - a class attribute assigned once, read by class name or through
15//!   `self`/`cls`, in a class with no decorator, class keyword or second
16//!   base, at most one same-file level of inheritance and at most 16
17//!   direct subclasses (a model value read through `self`/`cls` in a class
18//!   another module may subclass keeps a `subclass_override` gap). Every
19//!   binding of the name in a class body (`def`, `class`, an import, a loop
20//!   target...) is an assignment of it, in the class, its base and its
21//!   subclasses alike; and a method that binds its `self`/`cls` name other
22//!   than as that parameter reads nothing through it;
23//! - a parameter default of a function whose calls are all in this file (a
24//!   nested or `_private` function, a private class's `__init__`, anything
25//!   in a script), none of which passes another value;
26//! - an entry of a same-file dict literal read by literal key, when the dict
27//!   is only ever used through its one name and no `**` expansion or
28//!   computed key follows the entry (in a dict written at the call too);
29//! - a client from a tracked constructor with no `base_url`, or one that
30//!   resolves to a string (the provider's own host is direct, another host
31//!   is `custom_base_url`), and for Gemini no `vertexai=True`, endpoint
32//!   `http_options` or `**` expansion, in a file that does not configure
33//!   the endpoint some other way;
34//! - the module-level API, configured only in the top-of-file setup block:
35//!   plain `=` statements, each routing setting once, on a name only
36//!   imports bind, before the first `def`, `class`, decorator, bare
37//!   expression or compound statement (and before any module-level call in
38//!   the block). No code of the file exists yet there, so none can run
39//!   first; import-time execution is not followed any further.
40//!
41//! The collection walk also records **dynamic features** that can change a
42//! resolved name, class, dict or the environment (`exec`, `globals()`,
43//! `sys.modules`, `__dict__`, `setattr` with a run-time name, attribute
44//! hooks, decorators and metaclasses on a class whose attributes are read,
45//! multiple or deep inheritance, a class used as a value, environment
46//! writes with run-time names, ...). A value or route one of them may affect
47//! keeps a `dynamic_feature` gap naming the feature and its line; the most
48//! dynamic ones affect the whole file (namespace builtins reached under
49//! any name, `builtins` or `sys` imported under another name or used as a
50//! value, a frame's `f_globals`, scopes nested past
51//! [`MAX_SCOPE_DEPTH`]). Replacing a precise but costly resolution with
52//! such a gap is always acceptable, so each lookup does a bounded amount of
53//! work (see the `MAX_*` constants), every walk up the scopes is bounded by
54//! [`MAX_SCOPE_DEPTH`], and the whole pass is linear in the file.
55//!
56//! # Passes
57//!
58//! Two passes over the tree-sitter tree:
59//!
60//! 1. **Collect.** One iterative walk records scopes (module, class,
61//!    function, lambda), imports, every assignment target (names, `self.x`,
62//!    class attributes, `with ... as`, `except ... as`, `match` captures,
63//!    walrus, `global`, `nonlocal`, `globals()["NAME"]`, `del`, and a wildcard
64//!    import from another module, which may bind any module-level name),
65//!    parameters, every call, every attribute chain used as a value, where
66//!    each binding takes effect, and the dynamic features. Parent kinds and
67//!    field names travel down the walk, so no node is asked for its parent:
68//!    tree-sitter answers that by descending from the root, which made deep
69//!    trees quadratic.
70//! 2. **Analyze.** Each call's callee is evaluated against those bindings.
71//!    A chain rooted at a tracked SDK binding becomes a construction or a
72//!    call; an SDK-shaped chain on an unknown receiver, `getattr` on a
73//!    tracked binding and an unresolved model value become typed gaps.
74//!
75//! Names resolve the way Python scopes them, approximately: function and
76//! lambda locals, parameters and imports shadow enclosing functions, class
77//! bodies are skipped from inside methods, comprehensions have their own
78//! scope, `global` re-homes an assignment to the module and `nonlocal` to
79//! the enclosing function that binds the name. A use sees its
80//! reaching definitions: the nearest definition that dominates it in
81//! straight-line code, every definition between that one and the use (in a
82//! branch), later ones in a loop that runs the use again without passing
83//! the dominating one, and `global` or `nonlocal` assignments made by
84//! nested or other functions, which may run at any time. Class
85//! bodies and list, set and dict comprehensions run where they are written,
86//! so their uses are placed there. A use from a function, lambda or
87//! generator sees what reaches its definition plus every later definition,
88//! since it may run after any of them. With no dominating definition, or
89//! past the search limits, every definition of the name counts.
90//!
91//! An untyped parameter used as a client resolves when every call to its
92//! function (or to a lambda assigned to a plain name) in this file passes
93//! the same tracked client. Other modules may call a public function too, so
94//! there the routing keeps an `ambiguous_client` gap (`in_file_callers`),
95//! and a public function's model or client default keeps a
96//! `parameter_default` gap. The calls of `__init__` are the calls of its
97//! class; a method's are every call of its name, on any object. A function
98//! whose calls cannot all be seen (it is decorated, passed, stored or bound
99//! twice, or instances are built without naming their class) keeps an
100//! `unseen_callers` gap on a client or model default. A model parameter
101//! default that an in-file caller overrides keeps a `parameter_overridden`
102//! gap listing the values the callers pass.
103
104use super::{
105    is_capturable_value, is_credential_value, is_identifier_key, is_secret_key, is_value_key,
106    model_family, BindingKind, CapturedValue, ClientConstruction, ClientScope, FileUsages, GapKind,
107    Receiver, Routing, Sdk, SdkCall, SdkImport, Span, UsageGap, ValueOrigin, VertexAi,
108};
109use std::collections::{HashMap, HashSet};
110use std::rc::Rc;
111use tree_sitter::{Node, Tree};
112
113/// A file mentioning none of these cannot report anything, so it is neither
114/// parsed nor walked.
115const PREFILTER: &[&str] = &[
116    "openai",
117    "anthropic",
118    "genai",
119    "generativeai",
120    "Completion",
121    "completions.",
122    "responses.",
123    "messages.",
124    "embeddings.",
125    "generate_content",
126    "embed_content",
127];
128
129/// Whether `source` mentions anything the extractor tracks. A file that does
130/// not reports nothing, so callers may skip parsing it.
131pub fn may_use_sdk(source: &str) -> bool {
132    PREFILTER.iter().any(|needle| source.contains(needle))
133}
134
135/// Last member names that send a request to the provider (resource verbs and
136/// the Gemini/PaLM call names). A call ending in one is an [`SdkCall::request`];
137/// storing or passing one as a value hides the eventual request.
138const REQUEST_METHODS: &[&str] = &[
139    "create",
140    "acreate",
141    "stream",
142    "parse",
143    "retrieve",
144    "list",
145    "delete",
146    "update",
147    "cancel",
148    "upload",
149    "download",
150    "content",
151    "completion",
152    "completion_stream",
153    "generate",
154    "edit",
155    "create_variation",
156    "connect",
157    "generate_content",
158    "generate_content_async",
159    "generate_content_stream",
160    "embed_content",
161    "embed_content_async",
162    "batch_embed_contents",
163    "count_tokens",
164    "count_tokens_async",
165    "count_text_tokens",
166    "compute_tokens",
167    "send_message",
168    "send_message_async",
169    "send_message_stream",
170    "generate_text",
171    "generate_embeddings",
172    "generate_message",
173    "generate_images",
174    "generate_videos",
175    "chat",
176    "upload_file",
177    "get_file",
178    "list_files",
179    "delete_file",
180    "list_models",
181    "get_model",
182];
183
184/// Whether a call's member path ends in a request method.
185fn is_request(member: &str) -> bool {
186    let last = member.rsplit('.').next().unwrap_or(member);
187    REQUEST_METHODS.contains(&last)
188}
189
190/// Members that take a model. Like a request, an unresolved model value here
191/// is an `unresolved_model` gap, and so is `**kwargs` with no explicit model
192/// key.
193const MODEL_BEARING: &[&str] = &[
194    "chat.completions.create",
195    "chat.completions.parse",
196    "chat.completions.stream",
197    "completions.create",
198    "responses.create",
199    "responses.parse",
200    "responses.stream",
201    "embeddings.create",
202    "images.generate",
203    "images.edit",
204    "images.create_variation",
205    "audio.transcriptions.create",
206    "audio.translations.create",
207    "audio.speech.create",
208    "moderations.create",
209    "fine_tuning.jobs.create",
210    "assistants.create",
211    "runs.create",
212    "realtime.connect",
213    "messages.create",
214    "messages.stream",
215    "messages.count_tokens",
216    "models.generate_content",
217    "models.generate_content_stream",
218    "models.generate_images",
219    "models.generate_videos",
220    "embed_content",
221    "generate_embeddings",
222    "generate_text",
223    "count_text_tokens",
224    "chats.create",
225    "ChatCompletion.create",
226    "ChatCompletion.acreate",
227    "Completion.create",
228    "Completion.acreate",
229    "Embedding.create",
230    "GenerativeModel",
231];
232
233/// Members that wrap a resource without changing the request
234/// (`client.chat.completions.with_raw_response.create`).
235const RESPONSE_WRAPPERS: &[&str] = &["with_raw_response", "with_streaming_response"];
236
237/// Legacy `google.generativeai` functions whose first positional argument is
238/// the model (`genai.embed_content("models/embedding-001", text)`).
239const LEGACY_POSITIONAL_MODEL: &[&str] = &[
240    "embed_content",
241    "embed_content_async",
242    "generate_embeddings",
243    "count_text_tokens",
244];
245
246/// Calls whose `default=` (or second positional argument) is the fallback of
247/// an environment lookup: python-decouple and django-environ.
248const CONFIG_LOOKUPS: &[&str] = &["config", "decouple.config", "env", "env.str"];
249
250/// Maximum expression depth within one evaluation; deeper chains are
251/// treated as unresolved. Every name resolution starts a fresh budget.
252const MAX_DEPTH: u32 = 64;
253/// Maximum nesting of name, attribute and caller resolutions. A value cut
254/// off here is memoized with the budget it had (see [`Memo`]), so a long
255/// chain of names that each use the previous one more than once stays
256/// linear instead of doubling per link.
257const MAX_NAME_DEPTH: u32 = 64;
258/// Maximum nesting of scopes (functions, classes, lambdas, comprehensions)
259/// the collection pass follows. Every scope walk (name binding, `self`,
260/// import time) is then bounded by it. A deeper scope is not analyzed: it
261/// is a `truncated` gap, and a dynamic feature of the whole file, since
262/// what it binds or writes is not seen.
263const MAX_SCOPE_DEPTH: u32 = 64;
264/// Bases read per class when same-file subclasses are indexed.
265const MAX_BASES: usize = 32;
266/// Direct same-file subclasses a `self.x` read looks at, and assignments
267/// of the attribute taken from each. Past either, the read is a
268/// `dynamic_feature` gap instead of a longer walk.
269const MAX_SUBCLASSES: usize = 16;
270const MAX_SUBCLASS_ASSIGNS: usize = 4;
271/// Assignments of one attribute read per lookup. More is a gap anyway
272/// (`reassigned`), so the rest are not copied.
273const MAX_ATTR_ASSIGNS: usize = 64;
274/// Definitions a reaching-definition search may look at before it gives up
275/// and counts every definition of the name.
276const MAX_REACH_SCAN: usize = 64;
277/// Wildcard imports from other modules placed as definitions of every
278/// module-level name. Past it, every module-level name may come from one
279/// at any point.
280const MAX_STARS: usize = 16;
281/// Longest string literal read, in source bytes. A captured value is at
282/// most 256 bytes, so a longer literal is refused without being copied.
283const MAX_LITERAL_BYTES: usize = 4096;
284/// Most arguments an environment, config or dict lookup takes. A call with
285/// more is not a lookup and its arguments are not scanned.
286const MAX_LOOKUP_ARGS: usize = 8;
287/// Container entries a search for nested model keys reads: per call across
288/// all of its literal arguments (`fallbacks=[{"model": ...}, ...]`), and
289/// per dict literal for what its `**` expansion nests (read once, reused by
290/// every call that expands it). The rest of a huge literal is not read.
291const MAX_NESTED_ENTRIES: usize = 256;
292/// Nested model values listed per call. Past it, and past
293/// [`MAX_FILE_NESTED_VALUES`], the call gets a `truncated` gap instead.
294const MAX_NESTED_VALUES: usize = 32;
295/// Nested model values listed per file, so a dict expanded at thousands of
296/// calls cannot multiply the report.
297const MAX_FILE_NESTED_VALUES: usize = 4096;
298/// Candidate values listed with one gap, and per file.
299const MAX_CANDIDATES: usize = 32;
300const MAX_FILE_CANDIDATES: usize = 4096;
301/// In-file calls read for the values a parameter is given.
302const MAX_CALLERS_READ: usize = 256;
303/// Definitions, or dict entries, read for the values a name or a lookup
304/// with a run-time key may take.
305const MAX_CANDIDATE_READS: usize = 64;
306/// Longest name, chain or expression shape reported, in bytes: a longer one
307/// keeps its start and end around `...`. A name defined once and reported
308/// at every use (a function's symbol, a constant behind an alias, a client
309/// bound to a long attribute chain) can then not multiply the report.
310const MAX_TEXT: usize = 200;
311/// Longest member path followed off a tracked binding. SDK paths are a few
312/// segments (`beta.threads.runs.steps.list`).
313const MAX_PATH: usize = 32;
314/// Imports, calls, gaps and clients reported per file. Past it, the rest of
315/// the file is one `truncated` gap: the report stays proportional to real
316/// code however a generated file repeats itself.
317const MAX_FILE_RECORDS: usize = 20_000;
318/// Names bound by import statements per file. A file that binds more is
319/// not analyzed past its imports (one `truncated` gap): a name it no longer
320/// binds could change what any call resolves to.
321const MAX_FILE_IMPORTS: usize = MAX_FILE_RECORDS;
322
323/// Extracts SDK usages from a parsed Python file.
324pub fn extract(tree: &Tree, source: &str, file_path: &str) -> FileUsages {
325    if !may_use_sdk(source) {
326        return FileUsages::new(file_path, "python");
327    }
328    let mut cx = Ctx::new(source, file_path);
329    cx.collect(tree.root_node());
330    cx.place_nonlocal_assigns();
331    cx.note_rebound_receivers();
332    cx.bind_definitions();
333    cx.index_definitions();
334    cx.settle_dict_escapes();
335    cx.analyze();
336    let mut found = cx.finish();
337    found.syntax_errors = tree.root_node().has_error();
338    found
339}
340
341// ============================================================================
342// SDK tables
343// ============================================================================
344
345#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
346enum Pkg {
347    Openai,
348    Anthropic,
349    GoogleGenai,
350    GoogleGenerativeai,
351}
352
353impl Pkg {
354    fn sdk(self) -> Sdk {
355        match self {
356            Pkg::Openai => Sdk::Openai,
357            Pkg::Anthropic => Sdk::Anthropic,
358            Pkg::GoogleGenai | Pkg::GoogleGenerativeai => Sdk::Google,
359        }
360    }
361
362    fn package(self) -> &'static str {
363        match self {
364            Pkg::Openai => "openai",
365            Pkg::Anthropic => "anthropic",
366            Pkg::GoogleGenai => "google.genai",
367            Pkg::GoogleGenerativeai => "google.generativeai",
368        }
369    }
370
371    /// The package a dotted module path belongs to, and the rest of the
372    /// path: at most [`MAX_PATH`] segments, each clipped, so a generated
373    /// module path is not copied in full into every name it imports.
374    fn of_module(module: &str) -> Option<(Pkg, Vec<String>)> {
375        let mut parts = module.split('.').map(str::trim);
376        let pkg = match (parts.next(), parts.clone().next()) {
377            (Some("openai"), _) => Pkg::Openai,
378            (Some("anthropic"), _) => Pkg::Anthropic,
379            (Some("google"), Some("genai")) => Pkg::GoogleGenai,
380            (Some("google"), Some("generativeai")) => Pkg::GoogleGenerativeai,
381            _ => return None,
382        };
383        if matches!(pkg, Pkg::GoogleGenai | Pkg::GoogleGenerativeai) {
384            parts.next();
385        }
386        Some((pkg, parts.take(MAX_PATH).map(clip).collect()))
387    }
388}
389
390#[derive(Debug, Clone, Copy, PartialEq, Eq)]
391enum Family {
392    OpenaiDirect,
393    Azure,
394    AnthropicDirect,
395    Bedrock,
396    Vertex,
397    Genai,
398    LegacyModel,
399    /// A hosted-platform client this version does not classify.
400    Platform,
401}
402
403#[derive(Debug, Clone, Copy, PartialEq, Eq)]
404struct ClientClass {
405    pkg: Pkg,
406    name: &'static str,
407    family: Family,
408}
409
410/// Client constructors, by package. Platform clients route through a cloud
411/// vendor this version does not classify (see [`Routing::Unknown`]).
412const CLASSES: &[ClientClass] = &[
413    class(Pkg::Openai, "OpenAI", Family::OpenaiDirect),
414    class(Pkg::Openai, "AsyncOpenAI", Family::OpenaiDirect),
415    class(Pkg::Openai, "Client", Family::OpenaiDirect),
416    class(Pkg::Openai, "AsyncClient", Family::OpenaiDirect),
417    class(Pkg::Openai, "AzureOpenAI", Family::Azure),
418    class(Pkg::Openai, "AsyncAzureOpenAI", Family::Azure),
419    class(Pkg::Anthropic, "Anthropic", Family::AnthropicDirect),
420    class(Pkg::Anthropic, "AsyncAnthropic", Family::AnthropicDirect),
421    class(Pkg::Anthropic, "Client", Family::AnthropicDirect),
422    class(Pkg::Anthropic, "AsyncClient", Family::AnthropicDirect),
423    class(Pkg::Openai, "BedrockOpenAI", Family::Platform),
424    class(Pkg::Openai, "AsyncBedrockOpenAI", Family::Platform),
425    class(Pkg::Anthropic, "AnthropicAWS", Family::Platform),
426    class(Pkg::Anthropic, "AsyncAnthropicAWS", Family::Platform),
427    class(Pkg::Anthropic, "AnthropicFoundry", Family::Platform),
428    class(Pkg::Anthropic, "AsyncAnthropicFoundry", Family::Platform),
429    class(Pkg::Anthropic, "AnthropicGoogleCloud", Family::Platform),
430    class(
431        Pkg::Anthropic,
432        "AsyncAnthropicGoogleCloud",
433        Family::Platform,
434    ),
435    class(Pkg::Anthropic, "AnthropicBedrock", Family::Bedrock),
436    class(Pkg::Anthropic, "AsyncAnthropicBedrock", Family::Bedrock),
437    class(Pkg::Anthropic, "AnthropicVertex", Family::Vertex),
438    class(Pkg::Anthropic, "AsyncAnthropicVertex", Family::Vertex),
439    class(Pkg::GoogleGenai, "Client", Family::Genai),
440    class(
441        Pkg::GoogleGenerativeai,
442        "GenerativeModel",
443        Family::LegacyModel,
444    ),
445];
446
447const fn class(pkg: Pkg, name: &'static str, family: Family) -> ClientClass {
448    ClientClass { pkg, name, family }
449}
450
451fn client_class(pkg: Pkg, name: &str) -> Option<ClientClass> {
452    CLASSES
453        .iter()
454        .copied()
455        .find(|class| class.pkg == pkg && class.name == name)
456}
457
458impl ClientClass {
459    fn is_async(self) -> bool {
460        self.name.starts_with("Async")
461    }
462
463    /// Routing from the constructor, its keyword names and what its
464    /// `base_url` is.
465    fn routing(self, kwargs: &[String], splat: bool, base_url: BaseUrl) -> Routing {
466        // `OpenAI(provider=bedrock(...))` hands requests to a platform adapter.
467        let adapter = kwargs.iter().any(|k| k == "provider");
468        match self.family {
469            Family::OpenaiDirect | Family::AnthropicDirect if adapter => Routing::Unknown,
470            Family::OpenaiDirect | Family::AnthropicDirect
471                if matches!(base_url, BaseUrl::Custom | BaseUrl::CustomFallback) =>
472            {
473                Routing::CustomBaseUrl
474            }
475            Family::OpenaiDirect | Family::AnthropicDirect
476                if matches!(base_url, BaseUrl::Unknown { .. }) =>
477            {
478                Routing::Unknown
479            }
480            Family::OpenaiDirect | Family::AnthropicDirect
481                if splat && base_url == BaseUrl::Absent =>
482            {
483                Routing::Unknown
484            }
485            Family::OpenaiDirect => Routing::OpenaiDirect,
486            Family::AnthropicDirect => Routing::AnthropicDirect,
487            Family::Azure => Routing::AzureOpenai,
488            Family::Bedrock => Routing::AnthropicBedrock,
489            Family::Vertex => Routing::AnthropicVertex,
490            Family::Genai => Routing::GoogleGenai,
491            Family::LegacyModel => Routing::GoogleGenerativeaiLegacy,
492            Family::Platform => Routing::Unknown,
493        }
494    }
495
496    /// Routing known from a type annotation alone: a direct client may still
497    /// have been given a `base_url` (a Gemini client `vertexai=True` or an
498    /// endpoint), so it is `unknown`.
499    fn typed_routing(self) -> Routing {
500        match self.family {
501            Family::OpenaiDirect | Family::AnthropicDirect | Family::Genai => Routing::Unknown,
502            _ => self.routing(&[], false, BaseUrl::Absent),
503        }
504    }
505}
506
507fn is_base_url_key(key: &str) -> bool {
508    key == "base_url" || key == "api_base"
509}
510
511/// The provider an SDK-shaped chain on an unknown receiver most likely
512/// belongs to, and whether the shape alone is distinctive enough to report.
513fn sdk_shape(chain: &str) -> Option<(Sdk, bool)> {
514    const GOOGLE: &[&str] = &[
515        ".models.generate_content",
516        ".models.generate_content_stream",
517        ".models.embed_content",
518        ".generate_content",
519        ".generate_content_async",
520        ".generate_content_stream",
521    ];
522    const OPENAI: &[&str] = &[
523        ".chat.completions.create",
524        ".chat.completions.parse",
525        ".chat.completions.stream",
526        ".responses.create",
527        ".responses.parse",
528        ".responses.stream",
529        ".completions.create",
530        ".embeddings.create",
531        ".images.generate",
532        ".images.edit",
533        ".images.create_variation",
534        ".audio.transcriptions.create",
535        ".audio.translations.create",
536        ".audio.speech.create",
537        ".realtime.connect",
538        "ChatCompletion.create",
539        "ChatCompletion.acreate",
540        "Completion.create",
541        "Completion.acreate",
542    ];
543    // `messages.create` is also Twilio's and Slack's shape, so it counts only
544    // where the file imports the Anthropic SDK.
545    const ANTHROPIC: &[&str] = &[
546        ".messages.create",
547        ".messages.stream",
548        ".messages.count_tokens",
549    ];
550    let chain = strip_wrappers(chain);
551    if GOOGLE.iter().any(|s| chain.ends_with(s)) {
552        Some((Sdk::Google, true))
553    } else if OPENAI.iter().any(|s| chain.ends_with(s)) {
554        Some((Sdk::Openai, true))
555    } else if ANTHROPIC.iter().any(|s| chain.ends_with(s)) {
556        Some((Sdk::Anthropic, false))
557    } else {
558        None
559    }
560}
561
562/// A dotted path without the response wrappers.
563fn strip_wrappers(path: &str) -> String {
564    path.split('.')
565        .filter(|segment| !RESPONSE_WRAPPERS.contains(segment))
566        .collect::<Vec<_>>()
567        .join(".")
568}
569
570// ============================================================================
571// Values
572// ============================================================================
573
574/// A resolved client.
575#[derive(Debug, Clone, PartialEq, Eq)]
576struct Client {
577    pkg: Pkg,
578    routing: Routing,
579    /// Line of the same-file construction, when there is exactly one.
580    line: Option<u32>,
581    /// The construction call (its node id), when there is exactly one.
582    site: Option<usize>,
583    /// Assigned more than one kind of client, or a client and something else.
584    ambiguous: bool,
585    /// Known only from a type annotation, not from a construction.
586    typed: bool,
587    /// Why the routing may not hold at a call, reported there as an
588    /// `ambiguous_client` gap.
589    caveat: Option<ClientCaveat>,
590}
591
592/// Why a resolved client's routing may not be the one a request uses.
593#[derive(Debug, Clone, PartialEq, Eq)]
594enum ClientCaveat {
595    /// Every in-file caller of a function passes this client for
596    /// parameter `param`, but other modules may call it with another.
597    InFileCallers { param: String },
598    /// The client is the default of parameter `param`: other modules may
599    /// call the (public) function with another one, or (`unseen`) the
600    /// function is decorated, passed or stored, so callers this file does
601    /// not show may.
602    ParameterDefault { param: String, unseen: bool },
603    /// `client.base_url = ...` after the client is built.
604    BaseUrlAssigned,
605    /// The file sets an environment variable the SDK reads its endpoint
606    /// from (`os.environ["OPENAI_BASE_URL"] = ...`).
607    EndpointEnv { var: &'static str },
608    /// The file writes the environment with a name known only at run time
609    /// or through an alias of `os.environ`, which may set the endpoint
610    /// variable.
611    EnvWrite(Feature),
612    /// The `base_url` given to the constructor is read from the environment
613    /// with no fallback (`env`), falls back to the provider's own host
614    /// (`fallback`), or does not resolve to a string.
615    BaseUrl { env: bool, fallback: bool },
616    /// A dynamic feature of the file may rebind or replace the client.
617    Dynamic(Feature),
618    /// A Gemini client built with an option that may send its requests to
619    /// Vertex AI or another endpoint (`vertexai=True`, `http_options=` with
620    /// a `base_url`, `**options`), or the legacy SDK configured with
621    /// `client_options`.
622    EndpointOption { option: &'static str },
623    /// A module-level API call passes `engine` or `deployment_id`, which
624    /// Azure deployments take, in a file that does not configure the API:
625    /// another module may route it to Azure (the SDK's module state is
626    /// process-wide).
627    ModuleConfig,
628    /// The module-level API's routing is configured outside the top-of-file
629    /// setup block (in a function, a branch, after a `def`...), so it may
630    /// not hold when a call runs (see [`Ctx::module_openai_routing`]).
631    ModuleSetup(Feature),
632}
633
634/// A Python feature that can change what a name, attribute, dict or the
635/// environment holds at run time (see "Dynamic features" in the module
636/// documentation), and the line it is on.
637#[derive(Debug, Clone, Copy, PartialEq, Eq)]
638struct Feature {
639    what: &'static str,
640    line: u32,
641}
642
643impl Feature {
644    fn describe(self) -> String {
645        format!("{} at line {}", self.what, self.line)
646    }
647}
648
649/// How the `base_url` given to a direct client routes it.
650#[derive(Debug, Clone, Copy, PartialEq, Eq)]
651enum BaseUrl {
652    /// None given, or `None`: the SDK's default host or its endpoint
653    /// variable.
654    Absent,
655    /// The provider's own host (`https://api.openai.com/v1`).
656    Provider,
657    /// Another host: a gateway, a proxy or a local server.
658    Custom,
659    /// The provider's own host as the fallback of an environment lookup.
660    ProviderFallback,
661    /// Another host as the fallback of an environment lookup: the
662    /// deployment may point it anywhere, the provider included.
663    CustomFallback,
664    /// Read from the environment with no fallback (`env`), or not a string
665    /// this file resolves.
666    Unknown { env: bool },
667}
668
669/// The provider's own API host, for [`BaseUrl::Provider`].
670fn provider_host(pkg: Pkg) -> &'static str {
671    match pkg {
672        Pkg::Openai => "api.openai.com",
673        Pkg::Anthropic => "api.anthropic.com",
674        Pkg::GoogleGenai | Pkg::GoogleGenerativeai => "generativelanguage.googleapis.com",
675    }
676}
677
678/// The host of a URL, lowercase, without user information or port.
679fn url_host(url: &str) -> String {
680    let rest = url.trim().split_once("://").map_or(url, |(_, rest)| rest);
681    let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
682    let host = authority.rsplit('@').next().unwrap_or_default();
683    let host = match host.strip_prefix('[') {
684        Some(v6) => v6.split(']').next().unwrap_or_default(),
685        None => host.split(':').next().unwrap_or_default(),
686    };
687    host.trim_end_matches('.').to_ascii_lowercase()
688}
689
690/// [`BaseUrl::Provider`] when `url` is the provider's own host, else
691/// [`BaseUrl::Custom`].
692fn host_kind(pkg: Pkg, url: &str) -> BaseUrl {
693    if url_host(url) == provider_host(pkg) {
694        BaseUrl::Provider
695    } else {
696        BaseUrl::Custom
697    }
698}
699
700/// Environment variables an SDK reads its endpoint from when the
701/// constructor is not given one.
702const ENDPOINT_ENV: &[(Pkg, &str)] = &[
703    (Pkg::Openai, "OPENAI_BASE_URL"),
704    (Pkg::Anthropic, "ANTHROPIC_BASE_URL"),
705    // `google.genai.Client()` reads whether to use Vertex AI, and its
706    // endpoints, from these.
707    (Pkg::GoogleGenai, "GOOGLE_GENAI_USE_VERTEXAI"),
708    (Pkg::GoogleGenai, "GOOGLE_GEMINI_BASE_URL"),
709    (Pkg::GoogleGenai, "GOOGLE_VERTEX_BASE_URL"),
710];
711
712/// Environment variables the module-level OpenAI API (v0 and the v1 module
713/// client) reads its endpoint or API type from.
714const OPENAI_MODULE_ENV: &[&str] = &["OPENAI_BASE_URL", "OPENAI_API_BASE", "OPENAI_API_TYPE"];
715
716/// Attributes that re-route a built client when assigned.
717const BASE_URL_ATTRS: &[&str] = &["base_url", "api_base", "_base_url"];
718
719/// Where an untracked value came from, for gap details.
720#[derive(Debug, Clone, PartialEq, Eq)]
721enum Origin {
722    /// No binding in this file.
723    Unbound,
724    /// `None`, a literal or a container: ignored next to a real value.
725    Placeholder,
726    /// A binding that refers to itself while being resolved.
727    Cycle,
728    /// The result of calling something that is not a tracked constructor.
729    Factory {
730        callee: String,
731        wraps: Option<Pkg>,
732    },
733    /// A parameter with no tracked annotation.
734    Parameter {
735        name: String,
736    },
737    /// A name imported from a module that is not a tracked SDK.
738    Imported {
739        module: String,
740    },
741    /// `self.x` with no assignment in the class.
742    UnassignedAttribute {
743        name: String,
744    },
745    /// The value returned by an SDK call that is not a known constructor.
746    SdkResult {
747        pkg: Option<Pkg>,
748    },
749    /// A client constructor next to another that routes differently, or
750    /// next to something that is not a tracked constructor
751    /// (`AzureOpenAI if azure else build`, `try: from openai import
752    /// AzureOpenAI as Maker` / `except ImportError: from mylib import
753    /// FakeClient as Maker`); calling it builds an ambiguous client of the
754    /// first constructor's package.
755    MixedClasses(Pkg),
756    /// A dynamic feature of the file may rebind or replace the value.
757    Dynamic(Feature),
758    Other,
759}
760
761#[derive(Debug, Clone, PartialEq, Eq)]
762enum Val {
763    /// A tracked module, or a member path off one (`openai.ChatCompletion`).
764    Module {
765        pkg: Pkg,
766        path: Vec<String>,
767    },
768    /// The `google` namespace package, from `import google.genai`.
769    GoogleNs,
770    /// A client constructor.
771    Class(ClientClass),
772    /// Another imported SDK name, plus a member path.
773    Symbol {
774        pkg: Pkg,
775        path: Vec<String>,
776    },
777    /// A client, plus a member path (`client.chat.completions`).
778    Client {
779        client: Client,
780        path: Vec<String>,
781    },
782    /// The return value of an SDK call that is not a known client.
783    Result(Option<Pkg>),
784    Untracked(Origin),
785}
786
787impl Val {
788    fn untracked(origin: Origin) -> Self {
789        Val::Untracked(origin)
790    }
791
792    fn is_tracked(&self) -> bool {
793        !matches!(self, Val::Untracked(_) | Val::Result(_))
794    }
795
796    fn pkg(&self) -> Option<Pkg> {
797        match self {
798            Val::Module { pkg, .. } | Val::Symbol { pkg, .. } => Some(*pkg),
799            Val::Class(class) => Some(class.pkg),
800            Val::Client { client, .. } => Some(client.pkg),
801            Val::Result(pkg) => *pkg,
802            _ => None,
803        }
804    }
805
806    /// The member path after the tracked root.
807    fn path(&self) -> &[String] {
808        match self {
809            Val::Module { path, .. } | Val::Symbol { path, .. } | Val::Client { path, .. } => path,
810            _ => &[],
811        }
812    }
813}
814
815/// Why an allowlisted value did not resolve, and the expression's shape.
816#[derive(Debug, Clone)]
817struct Unresolved {
818    reason: &'static str,
819    shape: String,
820    via: Option<String>,
821    /// Values it may take that are known: what in-file callers pass for a
822    /// parameter, the entries of a dict looked up with a run-time key, the
823    /// assignments in each branch, the items a loop runs over. Listed with
824    /// the gap for triage, never as the call's value.
825    candidates: Vec<Resolved>,
826    /// Whether `candidates` (with the value captured next to the gap, if
827    /// any) are every value it can take: `Some(true)` only when every
828    /// source added was complete.
829    complete: Option<bool>,
830}
831
832impl Unresolved {
833    fn new(reason: &'static str, shape: String) -> Self {
834        Self {
835            reason,
836            shape: clip_owned(shape),
837            via: None,
838            candidates: Vec::new(),
839            complete: None,
840        }
841    }
842
843    /// Adds the values one source says it may take, and whether that
844    /// source listed all of its values.
845    fn with_candidates(mut self, candidates: Vec<Resolved>, complete: bool) -> Self {
846        for candidate in candidates {
847            if !push_candidate(&mut self.candidates, candidate) {
848                self.complete = Some(false);
849            }
850        }
851        self.complete = Some(self.complete.unwrap_or(true) && complete);
852        self
853    }
854
855    /// A `dynamic_feature` gap naming `feature`.
856    fn dynamic(feature: Feature) -> Self {
857        Self::new("dynamic_feature", feature.describe())
858    }
859
860    /// Marks the candidates as possibly partial.
861    fn incomplete(mut self) -> Self {
862        self.complete = Some(false);
863        self
864    }
865
866    /// Whether the candidates are known to be every value.
867    fn complete(&self) -> bool {
868        self.complete == Some(true) && !self.candidates.is_empty()
869    }
870
871    fn via(mut self, name: &str) -> Self {
872        if self.via.is_none() {
873            self.via = Some(clip(name));
874        }
875        self
876    }
877
878    fn phrase(&self) -> &'static str {
879        match self.reason {
880            "env_var" => "read from the environment",
881            "f_string" => "built with an f-string",
882            "function_call" => "returned by a function call",
883            "attribute" => "an attribute of another object",
884            "subscript" => "looked up by subscript",
885            "conditional" => "chosen at run time",
886            "parameter" => "a parameter whose default is not a resolvable string",
887            "reassigned" => "assigned more than once",
888            "imported_name" => "imported from another module",
889            "unbound" => "not defined in this file",
890            "splat" => "possibly passed through **kwargs",
891            "parameter_overridden" => "a parameter that in-file callers set to other values",
892            "unseen_callers" => {
893                "a parameter of a function that is decorated, passed or stored, so callers this file does not show may set it"
894            }
895            "credential" => {
896                "credential-shaped (a secret-like name or value), so it is never captured"
897            }
898            "parameter_default" => {
899                "a parameter of a function other modules may call with another value"
900            }
901            "dynamic_feature" => "something this file may change at run time",
902            "subclass_override" => {
903                "an attribute read through `self` or `cls` in a public class (or one with a public subclass), which a subclass in another module may override"
904            }
905            _ => "not a string literal",
906        }
907    }
908}
909
910/// A captured value before it is attached to a key.
911#[derive(Debug, Clone)]
912struct Resolved {
913    value: String,
914    origin: ValueOrigin,
915    name: Option<String>,
916    span: Span,
917    /// Why the value may not be the one sent, each reported as an
918    /// `unresolved_model` gap next to it: the lookup behind an
919    /// [`ValueOrigin::EnvDefault`] fallback, or in-file callers that pass
920    /// their own value for a parameter default. A value that has one is
921    /// captured only where its gap can be reported.
922    caveats: Vec<Unresolved>,
923}
924
925impl Resolved {
926    /// Whether the value is the only one its source gives: no caveat, and
927    /// not a parameter default (another module may pass the parameter).
928    fn is_certain(&self) -> bool {
929        self.caveats.is_empty() && self.origin != ValueOrigin::ParameterDefault
930    }
931
932    /// Names `name` as the binding the value came through: the value's own
933    /// name when it was written inline there, and the gaps of its caveats.
934    fn through(mut self, name: &str, origin: ValueOrigin) -> Self {
935        if self.name.is_none() || self.origin == origin {
936            self.name = Some(clip(name));
937        }
938        self.caveats = self
939            .caveats
940            .into_iter()
941            .map(|caveat| caveat.via(name))
942            .collect();
943        self
944    }
945}
946
947/// A model value found inside a container argument or a `**` expansion.
948#[derive(Debug, Clone)]
949struct NestedValue {
950    /// The key path (`fallbacks.model`).
951    path: String,
952    positional: bool,
953    resolved: Resolved,
954}
955
956/// A bounded read of nested model values.
957struct NestedRead {
958    /// Container entries that may still be read.
959    left: usize,
960    /// Entries were left unread when the budget ran out.
961    cut: bool,
962    found: Vec<NestedValue>,
963    /// Key paths of model values that a `**` expansion or computed key
964    /// written after them may replace (`{"model": "a", **extra}`): each is
965    /// a gap, not a value.
966    overridden: Vec<String>,
967}
968
969impl NestedRead {
970    fn new() -> Self {
971        Self {
972            left: MAX_NESTED_ENTRIES,
973            cut: false,
974            found: Vec::new(),
975            overridden: Vec::new(),
976        }
977    }
978}
979
980/// Where a nested read is: the key path so far, whether the outer argument
981/// is positional, the scope its values resolve in, and whether an enclosing
982/// entry may be replaced by a later `**` expansion or computed key.
983#[derive(Clone, Copy)]
984struct NestedPlace<'p> {
985    prefix: &'p str,
986    positional: bool,
987    scope: usize,
988    overridden: bool,
989}
990
991/// What a dict literal's `**` expansion nests, read once.
992struct NestedList {
993    found: Vec<NestedValue>,
994    overridden: Vec<String>,
995    cut: bool,
996}
997
998/// A memoized evaluation. `budget` is `None` when no resolution inside it
999/// was cut off at [`MAX_NAME_DEPTH`]: the value is final. Otherwise it is
1000/// the name budget the evaluation ran with. A lookup with no more budget
1001/// reuses the value (and counts as cut off itself); one with more budget
1002/// recomputes it. Each entry is therefore computed at most
1003/// `MAX_NAME_DEPTH + 1` times, which keeps the work linear in the file
1004/// however its names branch.
1005#[derive(Clone)]
1006struct Memo<V> {
1007    val: V,
1008    budget: Option<u32>,
1009}
1010
1011/// The memoized value for `key`, if one may be reused with `budget` left,
1012/// and whether it was cut off.
1013fn recall<K: std::hash::Hash + Eq, V: Clone>(
1014    memo: &HashMap<K, Memo<V>>,
1015    key: &K,
1016    budget: u32,
1017) -> Option<(V, bool)> {
1018    let entry = memo.get(key)?;
1019    match entry.budget {
1020        None => Some((entry.val.clone(), false)),
1021        Some(had) if budget <= had => Some((entry.val.clone(), true)),
1022        Some(_) => None,
1023    }
1024}
1025
1026// ============================================================================
1027// Collection state
1028// ============================================================================
1029
1030#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1031enum ScopeKind {
1032    Module,
1033    Class,
1034    Function,
1035}
1036
1037#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1038enum SlotKind {
1039    Positional,
1040    PositionalOnly,
1041    KeywordOnly,
1042    VarArgs,
1043    VarKwargs,
1044}
1045
1046#[derive(Debug, Clone)]
1047struct Slot {
1048    name: String,
1049    kind: SlotKind,
1050}
1051
1052struct Scope {
1053    kind: ScopeKind,
1054    parent: Option<usize>,
1055    /// Nearest enclosing class (through functions), for `self`.
1056    class: Option<usize>,
1057    /// The symbol name the graph uses for this scope (`Bot.ask`).
1058    symbol: Option<String>,
1059    /// For a class or function: its own name.
1060    name: String,
1061    globals: HashSet<String>,
1062    /// Names declared `nonlocal` in this function.
1063    nonlocals: HashSet<String>,
1064    /// For a class: base class names as written.
1065    bases: Vec<String>,
1066    /// Byte range of the scope's node.
1067    start: usize,
1068    end: usize,
1069    /// For a function or lambda: its parameters in order.
1070    slots: Vec<Slot>,
1071    /// Decorated with something other than `staticmethod`/`classmethod`, so
1072    /// a framework may call it. For a class: decorated at all
1073    /// (`@dataclass`), so its annotated attributes may be fields.
1074    decorated: bool,
1075    /// For a class: a base that is not a same-file class (`BaseModel`,
1076    /// `NamedTuple`, `mod.Base`) or a class keyword (`metaclass=...`), whose
1077    /// constructor may set annotated attributes from its arguments.
1078    external_bases: bool,
1079    /// For a class: why attributes read through it may change at run time
1080    /// whatever its body says: a decorator, a metaclass or other class
1081    /// keyword, or more than one base.
1082    class_feature: Option<Feature>,
1083    /// The 1-based line the scope starts on (set for classes, functions
1084    /// and lambdas).
1085    line: u32,
1086    staticmethod: bool,
1087    lambda: bool,
1088    /// A list, set or dict comprehension or a generator expression: its
1089    /// own scope for its targets, with no name.
1090    comprehension: bool,
1091    /// The body runs where it is written (a class body, a list, set or dict
1092    /// comprehension), not when called later.
1093    immediate: bool,
1094    /// For a lambda assigned to a plain name (`ask = lambda q: ...`): that
1095    /// name, through which its in-file calls are found.
1096    bound_name: Option<String>,
1097    /// For a function or lambda: where its body starts. A walrus before it
1098    /// (in a default or an annotation) binds in the enclosing scope.
1099    body_start: usize,
1100    /// The class whose instance (`self_recv`) or which class itself
1101    /// (`cls_recv`) the name `self` / `cls` holds here, and the method that
1102    /// binds it: the first parameter of a method directly in the class body
1103    /// that is not a `staticmethod`, seen from that method and the
1104    /// functions, lambdas and comprehensions nested in it that do not bind
1105    /// the name again.
1106    self_recv: Option<(usize, usize)>,
1107    cls_recv: Option<(usize, usize)>,
1108    /// How many scopes enclose this one (the module is 0); at most
1109    /// [`MAX_SCOPE_DEPTH`].
1110    depth: u32,
1111}
1112
1113impl Scope {
1114    fn new(kind: ScopeKind, parent: Option<usize>, start: usize, end: usize) -> Self {
1115        Self {
1116            kind,
1117            parent,
1118            class: None,
1119            symbol: None,
1120            name: String::new(),
1121            globals: HashSet::new(),
1122            nonlocals: HashSet::new(),
1123            bases: Vec::new(),
1124            start,
1125            end,
1126            slots: Vec::new(),
1127            decorated: false,
1128            external_bases: false,
1129            class_feature: None,
1130            line: 0,
1131            staticmethod: false,
1132            lambda: false,
1133            comprehension: false,
1134            immediate: kind == ScopeKind::Class,
1135            bound_name: None,
1136            body_start: 0,
1137            self_recv: None,
1138            cls_recv: None,
1139            depth: 0,
1140        }
1141    }
1142}
1143
1144/// Where a definition takes effect.
1145#[derive(Clone, Copy, Debug)]
1146struct Place {
1147    /// The byte offset after which the binding exists.
1148    at: usize,
1149    /// The byte range it certainly holds in, in straight-line code (the rest
1150    /// of its block after its statement). `None` for bindings that do not
1151    /// dominate what follows (walrus, loop targets).
1152    region: Option<(usize, usize)>,
1153}
1154
1155impl Place {
1156    /// Whether the binding certainly holds at `pos`. The end is inclusive,
1157    /// so a definition holds at the end of its block.
1158    fn dominates(&self, pos: usize) -> bool {
1159        self.region
1160            .is_some_and(|(start, end)| start <= pos && pos <= end)
1161    }
1162}
1163
1164#[derive(Clone, Copy)]
1165struct Assign<'t> {
1166    id: usize,
1167    /// The scope the value expression lives in.
1168    scope: usize,
1169    value: Option<Node<'t>>,
1170    annotation: Option<Node<'t>>,
1171    /// Bound by a loop, an unpacking or an augmented assignment.
1172    unknowable: bool,
1173    place: Place,
1174    /// For a plain-name loop target: what the loop runs over.
1175    iter: Option<Node<'t>>,
1176}
1177
1178#[derive(Clone, Copy)]
1179struct Param<'t> {
1180    annotation: Option<Node<'t>>,
1181    default: Option<Node<'t>>,
1182}
1183
1184#[derive(Clone)]
1185struct ImportDef {
1186    val: Val,
1187    place: Place,
1188}
1189
1190#[derive(Clone)]
1191struct OtherImport {
1192    /// The module as written, clipped, shared by every name one statement
1193    /// imports.
1194    module: Rc<str>,
1195    place: Place,
1196}
1197
1198/// One definition of a name.
1199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1200enum DefRef {
1201    Import(usize),
1202    Other(usize),
1203    Param,
1204    Assign(usize),
1205    /// `from other import *` at module level (an index into
1206    /// [`Ctx::module_stars`]): it may bind any module-level name.
1207    Star(usize),
1208    /// A write to the module namespace whose name is known only at run
1209    /// time (`globals().update(...)`, `globals()[name] = v`), or more
1210    /// wildcard imports than [`MAX_STARS`]: any module-level name, at any
1211    /// time.
1212    Dynamic,
1213}
1214
1215#[derive(Clone, Copy)]
1216struct DefPos {
1217    place: Place,
1218    def: DefRef,
1219}
1220
1221/// Every definition of one name in its scope, by position.
1222struct DefIndex {
1223    /// Definitions made in the binding scope itself, sorted by `place.at`.
1224    local: Vec<DefPos>,
1225    /// `global` assignments made by other functions: they may run at any time.
1226    foreign: Vec<DefRef>,
1227    total: usize,
1228}
1229
1230/// The definitions that reach a use.
1231enum Reach {
1232    All,
1233    Subset(Vec<DefRef>),
1234}
1235
1236/// What kinds of definition reach a use, without listing every one: a
1237/// name assigned thousands of times costs the same as one assigned twice.
1238#[derive(Default)]
1239struct DefKinds {
1240    param: bool,
1241    /// A tracked or other import.
1242    imported: bool,
1243    assigns: usize,
1244    /// The assignment, when there is exactly one.
1245    only_assign: Option<usize>,
1246}
1247
1248/// A `x.attr = value` or `setattr(x, "attr", value)` whose object is not
1249/// `self`/`cls`/a class, checked later for module-level OpenAI
1250/// configuration and clients re-routed after they are built.
1251#[derive(Clone, Copy)]
1252struct ConfigAssign<'t> {
1253    object: Node<'t>,
1254    attr: &'t str,
1255    value: Option<Node<'t>>,
1256    scope: usize,
1257    /// The write is a statement of its own directly in the module body
1258    /// (not in a branch, loop, `try`, `with`, class body or function, and
1259    /// not part of a larger expression): it runs once, at import.
1260    top: bool,
1261    /// A plain `=` assignment (not `+=`, `setattr` or `del`).
1262    plain: bool,
1263    /// Where the write is.
1264    at: usize,
1265}
1266
1267/// Calls and the scope each is in.
1268type CallSites<'t> = Rc<[(Node<'t>, usize)]>;
1269
1270/// Calls of one name, by the scope that binds the name at each.
1271type CallIndex<'t> = Rc<HashMap<usize, CallSites<'t>>>;
1272
1273/// Calls of a function or method name, and whether the name is also used as
1274/// a value (passed, stored, decorated, rebound).
1275#[derive(Default)]
1276struct Uses<'t> {
1277    calls: Vec<(Node<'t>, usize)>,
1278    escapes: bool,
1279}
1280
1281/// One node of the collection walk, with the context its ancestors give it.
1282#[derive(Clone, Copy)]
1283struct Frame<'t> {
1284    node: Node<'t>,
1285    scope: usize,
1286    parent: Option<Node<'t>>,
1287    field: Option<&'static str>,
1288    /// End of the enclosing block (or module).
1289    block_end: usize,
1290    /// The statement of that block this node is part of; `None` when the
1291    /// node is the statement.
1292    stmt: Option<(usize, usize)>,
1293    /// Innermost loop around the node in its scope (an index into that
1294    /// scope's [`Ctx::loops`]).
1295    inner_loop: Option<usize>,
1296    /// The parent's parent.
1297    grand: Option<Node<'t>>,
1298    /// Inside a type annotation, where a name is a type, not a value.
1299    annotation: bool,
1300}
1301
1302/// A `for` or `while` statement, for loop-carried definitions.
1303#[derive(Clone, Copy, Debug)]
1304struct LoopRange {
1305    start: usize,
1306    end: usize,
1307    /// The loop around it in the same scope.
1308    parent: Option<usize>,
1309}
1310
1311impl LoopRange {
1312    fn contains(&self, pos: usize) -> bool {
1313        self.start <= pos && pos < self.end
1314    }
1315}
1316
1317/// Where a use runs relative to the scope that binds its name.
1318#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1319enum UseAt {
1320    /// At this byte of the binding scope: code in the scope itself, a class
1321    /// body or a list, set or dict comprehension, which all run where they
1322    /// are written.
1323    At(usize),
1324    /// Later, from a function, lambda or generator defined at this byte of
1325    /// the binding scope: it may run after any later definition.
1326    Deferred(usize),
1327}
1328
1329/// How a dict, or a part of one, is used where it appears.
1330#[derive(Clone, Copy, PartialEq, Eq)]
1331enum DictUse<'t> {
1332    /// Read without letting it change: a subscript, `.get`, `.keys()`,
1333    /// `**d` in a call, a test or a read-only builtin.
1334    Safe,
1335    /// Assigned to this plain name: the two refer to one dict.
1336    Alias(&'t str),
1337    /// Its entries are handed out (`.items()`, `.values()`, `.copy()`,
1338    /// `dict(d)`, `{**d}`, iterated): a change to a nested container
1339    /// changes it.
1340    Shallow,
1341    /// Passed, stored, returned or mutated: it may change.
1342    Escape,
1343}
1344
1345/// A part of a dict literal (`D["a"]`, `D.get("a")`, or the whole of `D`
1346/// for a shallow use) that leaves the dict, decided after collection.
1347#[derive(Clone, Copy)]
1348struct Exposed<'t> {
1349    root: &'t str,
1350    /// The identifier, subscript or `.get` call.
1351    node: Node<'t>,
1352    scope: usize,
1353    /// Assigned to this plain name.
1354    alias: Option<&'t str>,
1355}
1356
1357/// A dict literal reached through names and subscripts.
1358struct DictRef<'t> {
1359    node: Node<'t>,
1360    scope: usize,
1361    /// How the code names it (`PARAMS`, `CONFIG["openai"]`), `None` inline.
1362    name: Option<String>,
1363    origin: ValueOrigin,
1364}
1365
1366enum Lookup<'t> {
1367    Found(Node<'t>),
1368    Absent,
1369    Unknown,
1370}
1371
1372/// A dict literal read once: where each key's last entry is, and the
1373/// entries a `**` expansion needs. Lookups are then constant time however
1374/// large the literal and however often it is used.
1375struct DictSummary<'t> {
1376    last: HashMap<String, (usize, Node<'t>)>,
1377    /// Index of the last entry that could not be read (`**other`, a computed
1378    /// key): it may override any key before it.
1379    last_unknown: Option<usize>,
1380    /// Identifier-keyed entries a `**` expansion reads (allowlisted keys,
1381    /// base URLs, containers): the last one per key with its index, at most
1382    /// 256.
1383    expansion: Vec<(String, usize, Node<'t>)>,
1384    /// Part of the dict could not be read, or the expansion list was cut.
1385    opaque: bool,
1386}
1387
1388impl DictSummary<'_> {
1389    /// Whether an entry that cannot be read (`**other`, a computed key)
1390    /// comes after entry `index`, so it may replace that entry's value:
1391    /// the entry is then not the dict's value for its key (rules 1 and 5).
1392    fn overridable(&self, index: usize) -> bool {
1393        self.last_unknown.is_some_and(|unknown| unknown > index)
1394    }
1395}
1396
1397/// A dict expanded with `**`.
1398struct Expansion<'t> {
1399    /// The dict literal.
1400    node: Node<'t>,
1401    /// Its summary: `expansion` holds the pairs that can matter.
1402    summary: Rc<DictSummary<'t>>,
1403    scope: usize,
1404    name: Option<String>,
1405    origin: ValueOrigin,
1406}
1407
1408impl Expansion<'_> {
1409    /// Part of it could not be read (`**other`, a computed key).
1410    fn opaque(&self) -> bool {
1411        self.summary.opaque
1412    }
1413}
1414
1415/// A `D.get(key, default)` call on a same-file dict literal.
1416#[derive(Clone, Copy)]
1417struct DictGet<'t> {
1418    call: Node<'t>,
1419    key: Option<Node<'t>>,
1420    default: Option<Node<'t>>,
1421    /// The scope the call is in, where its default is evaluated.
1422    scope: usize,
1423}
1424
1425/// The model values in-file calls pass for one parameter.
1426#[derive(Default)]
1427struct CallerModels {
1428    /// Distinct resolved values, at most [`MAX_CANDIDATES`].
1429    values: Vec<Resolved>,
1430    /// Some caller passes a value that does not resolve, passes it through
1431    /// `*args`/`**kwargs`, or was not read.
1432    unknown: bool,
1433    /// Some calls cannot be seen: the function is decorated, passed,
1434    /// stored or bound more than once (see [`Ctx::visible_calls`]).
1435    unseen: bool,
1436    /// `values` are every value the parameter is given: every call is
1437    /// seen and read, each passes a value that resolves (or none), and the
1438    /// function is called only from this file.
1439    complete: bool,
1440}
1441
1442/// What an attribute read through a class (`Bot.model`, `self.model`) may
1443/// hold: the assignments the supported grammar sees, and the dynamic
1444/// feature that may change it whatever they say.
1445struct AttrLookup<'t> {
1446    assigns: Rc<[Assign<'t>]>,
1447    dynamic: Option<Feature>,
1448}
1449
1450/// A class's place in its hierarchy, for attribute reads.
1451#[derive(Clone, Copy)]
1452struct ClassShape {
1453    /// Its one same-file base class.
1454    base: Option<usize>,
1455    /// It or that base has a base outside this file, whose metaclass or
1456    /// constructor may turn class attributes into fields.
1457    external: bool,
1458    /// Why its attributes may change whatever its body says.
1459    feature: Option<Feature>,
1460}
1461
1462/// Candidate values read once for a dict literal.
1463struct DictCandidates {
1464    values: Vec<Resolved>,
1465    complete: bool,
1466}
1467
1468/// How a call passes one parameter (see [`Ctx::param_slot`]).
1469struct ParamSlot {
1470    /// Index among the explicit positional arguments, `None` when the
1471    /// parameter is keyword-only.
1472    position: Option<usize>,
1473    /// It may be passed by keyword (it is not positional-only).
1474    keyword: bool,
1475    /// The scope the function is defined in, where its defaults run.
1476    parent: usize,
1477}
1478
1479/// Where a parameter's argument is in one call.
1480enum ArgFor<'t> {
1481    Found(Node<'t>),
1482    Missing,
1483    Unknown,
1484}
1485
1486type Key = (usize, String);
1487
1488/// Candidate values read once, and whether they are every value.
1489type CandidateList = Rc<(Vec<Resolved>, bool)>;
1490
1491struct Ctx<'t> {
1492    src: &'t str,
1493    file: String,
1494    ascii: bool,
1495    /// Continuation bytes before each 64-byte block, for character columns.
1496    cont_blocks: Vec<u32>,
1497    scopes: Vec<Scope>,
1498    /// Tracked imports, keyed by the scope they bind in: a function for an
1499    /// import inside its body, the module for everything else.
1500    imports: HashMap<Key, Vec<ImportDef>>,
1501    /// Other imports (for gap details), keyed the same way.
1502    other_imports: HashMap<Key, Vec<OtherImport>>,
1503    sdk_imported: HashSet<Sdk>,
1504    assigns: HashMap<Key, Vec<Assign<'t>>>,
1505    attr_assigns: HashMap<Key, Vec<Assign<'t>>>,
1506    /// Assignments to a `nonlocal` name, by the declaring function: placed
1507    /// in the scope that binds the name once every binding is known.
1508    nonlocal_assigns: Vec<(usize, String, Assign<'t>)>,
1509    params: HashMap<Key, Param<'t>>,
1510    /// Function definitions, keyed by the scope their name binds in.
1511    functions: HashMap<Key, Vec<usize>>,
1512    classes_by_name: HashMap<String, Vec<usize>>,
1513    /// The same-file classes that list each class as a base.
1514    subclasses: HashMap<usize, Vec<usize>>,
1515    config_assigns: Vec<ConfigAssign<'t>>,
1516    /// Attribute writes on objects other than `self`/`cls`/a class, by
1517    /// attribute name (the first one): any instance's or class's attribute
1518    /// of that name may be one of them.
1519    outside_attr_writes: HashMap<&'t str, Feature>,
1520    /// Writes whose attribute name is known only at run time
1521    /// (`setattr(self, name, v)`, `delattr`, `__setattr__`) on `self`/`cls`
1522    /// of a class: any attribute of its instances may be one of them.
1523    wild_attr_writes: HashMap<usize, Feature>,
1524    /// The same on any other object: any attribute of anything.
1525    wild_attr_any: Option<Feature>,
1526    /// The objects written that way, for clients re-routed after they are
1527    /// built.
1528    wild_attr_objects: Vec<(Node<'t>, usize)>,
1529    /// The first feature that may rebind any name, attribute or dict of the
1530    /// file (`exec`, `eval`, `compile`, `globals()`, `locals()`, `vars()`,
1531    /// `sys.modules`, `__dict__`, `import __main__`, importing the module
1532    /// itself): every value not written at its call, and every route, is
1533    /// then a `dynamic_feature` gap.
1534    file_dynamic: Option<Feature>,
1535    /// A class defines `__getattr__`, `__getattribute__`, `__setattr__`,
1536    /// `__delattr__` or `__init_subclass__`: any attribute read may run it.
1537    attr_hooks: Option<Feature>,
1538    /// The environment is written with a name known only at run time
1539    /// (`os.environ[key] = v`, `os.environ |= {...}`, `update(**cfg)`) or
1540    /// through an alias of `os.environ` (`env = os.environ`).
1541    env_wild: Option<Feature>,
1542    /// The same through a bare `environ`, which counts only when the file
1543    /// imports it from `os` (a WSGI `environ` is a request's).
1544    bare_environ_wild: Option<Feature>,
1545    /// Instances may be built without naming their class
1546    /// (`type(self)(...)`, `self.__class__(...)`, `cls(...)`): no class's
1547    /// constructor calls are all seen.
1548    dynamic_constructors: Option<Feature>,
1549    /// Names used as a value other than to read an attribute, call or
1550    /// subclass it (stored, aliased, passed, returned): a class of that
1551    /// name may be changed by whatever receives it.
1552    class_escapes: HashMap<&'t str, Feature>,
1553    /// Base names that more than one same-file class has: their classes
1554    /// may have subclasses this file cannot attribute.
1555    ambiguous_base_names: HashSet<String>,
1556    /// A method or module function may be called by a name known only at
1557    /// run time (`getattr(obj, name)(...)`, `globals()[name](...)`): no
1558    /// method's (or, for the namespace, no function's) calls are all seen.
1559    dynamic_method_calls: bool,
1560    dynamic_function_calls: bool,
1561    calls: Vec<(Node<'t>, usize)>,
1562    refs: Vec<(Node<'t>, usize)>,
1563    call_scope: HashMap<usize, usize>,
1564    /// Parents of calls and of the wrappers between a call and its binding.
1565    parents: HashMap<usize, Node<'t>>,
1566    name_uses: HashMap<&'t str, Uses<'t>>,
1567    attr_uses: HashMap<&'t str, Uses<'t>>,
1568    /// Names whose dict literal may change after it is written: mutated
1569    /// (`D[k] = v`, `D["a"]["b"] = v`, `D["a"].update()`), passed to a
1570    /// function, stored, returned, or aliased by a name that is. Their
1571    /// literal is never read.
1572    escaped: HashSet<&'t str>,
1573    /// Dict parts that leave their dict, and plain-name aliases.
1574    exposed: Vec<Exposed<'t>>,
1575    def_index: HashMap<Key, DefIndex>,
1576    /// `for`/`while` statements per scope, in source order.
1577    loops: HashMap<usize, Vec<LoopRange>>,
1578    /// Start bytes of the expressions that read the process environment
1579    /// (`os.environ`, `os.getenv`, `getenv(...)`, `environ[...]`), in
1580    /// order, so "does this expression read the environment?" is a binary
1581    /// search instead of a walk.
1582    env_reads: Vec<usize>,
1583    /// Constructions recorded so far: the index of the record and why its
1584    /// routing may not hold.
1585    constructions: HashMap<usize, (usize, Option<ClientCaveat>)>,
1586    name_memo: HashMap<Key, Memo<Val>>,
1587    attr_memo: HashMap<Key, Memo<Val>>,
1588    /// The same for `self.x` / `cls.x`, read with subclasses and outside
1589    /// writes.
1590    dyn_attr_memo: HashMap<Key, Memo<Val>>,
1591    def_memo: HashMap<usize, Memo<Val>>,
1592    param_memo: HashMap<Key, Memo<Val>>,
1593    call_memo: HashMap<(usize, usize), Memo<Val>>,
1594    dict_cache: HashMap<usize, Rc<DictSummary<'t>>>,
1595    dict_contents_memo: HashMap<usize, (bool, Rc<[&'t str]>)>,
1596    /// What each expanded dict literal nests, by node id.
1597    dict_nested: HashMap<usize, Rc<NestedList>>,
1598    /// Nested values that may still be listed in this file.
1599    nested_left: usize,
1600    /// Candidate values that may still be listed with gaps in this file.
1601    candidates_left: usize,
1602    /// A class's own assignments of an attribute (its body and
1603    /// `self.x = ...`), read once per class and name.
1604    own_attr_memo: HashMap<Key, Rc<[Assign<'t>]>>,
1605    /// Attribute lookups through a class name, and through `self`/`cls`.
1606    class_attr_memo: HashMap<Key, Rc<AttrLookup<'t>>>,
1607    self_attr_memo: HashMap<Key, Rc<AttrLookup<'t>>>,
1608    /// The items a loop runs over, read once per iterable and origin.
1609    loop_items_memo: HashMap<(usize, ValueOrigin), CandidateList>,
1610    /// Candidates of a name every definition of which reaches the use,
1611    /// read once per name and origin.
1612    reach_all_memo: HashMap<(Key, ValueOrigin), CandidateList>,
1613    caller_memo: HashMap<Key, Memo<Option<Val>>>,
1614    /// Model values in-file callers pass for a parameter, by (function,
1615    /// parameter).
1616    caller_models: HashMap<Key, Rc<CallerModels>>,
1617    /// The values a dict literal's entries hold, by node id and the name
1618    /// the dict is used through.
1619    dict_candidates_memo: HashMap<(usize, Option<String>), Rc<DictCandidates>>,
1620    /// Candidate values are being collected: a nested lookup does not
1621    /// collect its own, so the work stays linear.
1622    collecting: u32,
1623    name_call_index: HashMap<String, CallIndex<'t>>,
1624    method_call_index: HashMap<String, CallSites<'t>>,
1625    /// Resolutions in progress: (kind, scope or id, name).
1626    visiting: HashSet<(u8, usize, String)>,
1627    /// Current nesting of name resolutions, and how many were cut off at
1628    /// [`MAX_NAME_DEPTH`]; a value computed across a cut-off is memoized
1629    /// with its budget (see [`Memo`]).
1630    name_depth: u32,
1631    cutoffs: u64,
1632    next_id: usize,
1633    openai_routing: Routing,
1634    /// The file is a script (no extension, or `__main__.py`): other modules
1635    /// do not import it, so its in-file callers are all the callers.
1636    script: bool,
1637    /// Environment variables the file sets by name
1638    /// (`os.environ["OPENAI_BASE_URL"] = ...`, `os.environ.setdefault(...)`,
1639    /// `os.environ.update(...)`, `os.putenv(...)`).
1640    env_writes: HashSet<String>,
1641    /// Construction calls whose client has `base_url` assigned later, and
1642    /// packages with such a client that could not be singled out.
1643    rerouted: HashSet<usize>,
1644    rerouted_pkgs: HashSet<Pkg>,
1645    /// A `base_url` written on an object this file cannot identify, which
1646    /// may be any of its clients.
1647    rerouted_any: Option<Feature>,
1648    /// Why the module-level OpenAI API's routing may not hold.
1649    openai_caveat: Option<ClientCaveat>,
1650    /// Namespace builtins used as a value, by name (see
1651    /// [`Ctx::note_builtin_value`]).
1652    builtin_values: HashMap<&'t str, Feature>,
1653    /// `C.m` read as a value (not called, not written): when `C` is a class
1654    /// and `m` one of its methods, the method may run on another class's
1655    /// instance (`B2.go = B.go`, `go = B.go` in another class body).
1656    member_values: HashSet<(&'t str, &'t str)>,
1657    /// Attribute writes through a method's `self`/`cls`: the method, the
1658    /// attribute and the object written.
1659    method_self_writes: Vec<(usize, &'t str, Node<'t>)>,
1660    /// Methods that bind their `self` (`true`) or `cls` (`false`) other
1661    /// than as the first parameter, themselves or in a scope nested in them
1662    /// (`self = other`, `for self in ...`, `nonlocal self`...): a read
1663    /// through the name there is a `dynamic_feature` gap, and a write an
1664    /// outside write (see [`Ctx::note_rebound_receivers`]).
1665    rebound_receivers: HashMap<(usize, bool), Feature>,
1666    /// Why the legacy Gemini SDK's module-level routing may not hold.
1667    legacy_caveat: Option<ClientCaveat>,
1668    /// The file imports the legacy Gemini SDK (`google.generativeai`).
1669    legacy_imported: bool,
1670    /// Names `__all__` lists, and whether it is built from names
1671    /// (`__all__ = _EXPORTS`), when any module-level name may be exported.
1672    exported: HashSet<&'t str>,
1673    exports_dynamic: bool,
1674    /// An SDK member replaced in this file (`client.chat.completions.create
1675    /// = patched`, `openai.OpenAI = Sub`), by package: every route of that
1676    /// package is then a `dynamic_feature` gap.
1677    sdk_patched: HashMap<Pkg, Feature>,
1678    /// Names bound by `def` and `class` statements and class-body imports,
1679    /// where they bind: a name also assigned there gets an assignment of no
1680    /// known value for each (see [`Ctx::bind_definitions`]).
1681    def_bindings: Vec<(Key, usize, Place)>,
1682    /// The last write that configures the module-level OpenAI API's
1683    /// routing, and where it is: a call that runs at import before it is
1684    /// not routed by it.
1685    openai_last_config: Option<(usize, Feature)>,
1686    /// The attribute write or `setattr` call being recorded is a statement
1687    /// of its own directly in the module body (see [`ConfigAssign::top`]),
1688    /// and a plain `=` assignment ([`ConfigAssign::plain`]).
1689    config_top: bool,
1690    config_plain: bool,
1691    /// Where the top-of-file setup block ends (see
1692    /// [`Ctx::setup_block_end`]): the module-level API's configuration
1693    /// counts only before it. Computed on first use: most files never
1694    /// configure the module-level API.
1695    setup_end: Option<usize>,
1696    /// The module node.
1697    root: Option<Node<'t>>,
1698    /// Scopes nested deeper than [`MAX_SCOPE_DEPTH`], which are not walked,
1699    /// and the scope each is in: one `truncated` gap each.
1700    scope_cuts: Vec<(Node<'t>, usize)>,
1701    /// Wildcard imports from other modules, in order, and whether there
1702    /// were more than [`MAX_STARS`] or the module namespace is written with
1703    /// a run-time name (see [`DefRef::Dynamic`]).
1704    module_stars: Vec<(Place, Rc<str>)>,
1705    dynamic_globals: bool,
1706    /// While a plain-name loop target is recorded: what the loop runs over.
1707    loop_iter: Option<Node<'t>>,
1708    /// Names bound by imports so far, and the import statement at which
1709    /// [`MAX_FILE_IMPORTS`] was reached.
1710    import_bindings: usize,
1711    import_cut: Option<Node<'t>>,
1712    out: FileUsages,
1713}
1714
1715impl<'t> Ctx<'t> {
1716    fn new(src: &'t str, file: &str) -> Self {
1717        let ascii = src.is_ascii();
1718        let mut cont_blocks = Vec::new();
1719        if !ascii {
1720            let mut total = 0u32;
1721            cont_blocks.push(0);
1722            for chunk in src.as_bytes().chunks(64) {
1723                total += chunk.iter().filter(|b| (**b & 0xC0) == 0x80).count() as u32;
1724                cont_blocks.push(total);
1725            }
1726        }
1727        Self {
1728            src,
1729            file: file.to_string(),
1730            ascii,
1731            cont_blocks,
1732            scopes: vec![Scope::new(ScopeKind::Module, None, 0, src.len())],
1733            imports: HashMap::new(),
1734            other_imports: HashMap::new(),
1735            sdk_imported: HashSet::new(),
1736            assigns: HashMap::new(),
1737            attr_assigns: HashMap::new(),
1738            nonlocal_assigns: Vec::new(),
1739            params: HashMap::new(),
1740            functions: HashMap::new(),
1741            classes_by_name: HashMap::new(),
1742            subclasses: HashMap::new(),
1743            config_assigns: Vec::new(),
1744            outside_attr_writes: HashMap::new(),
1745            wild_attr_writes: HashMap::new(),
1746            wild_attr_any: None,
1747            wild_attr_objects: Vec::new(),
1748            file_dynamic: None,
1749            attr_hooks: None,
1750            env_wild: None,
1751            bare_environ_wild: None,
1752            dynamic_constructors: None,
1753            class_escapes: HashMap::new(),
1754            ambiguous_base_names: HashSet::new(),
1755            dynamic_method_calls: false,
1756            dynamic_function_calls: false,
1757            calls: Vec::new(),
1758            refs: Vec::new(),
1759            call_scope: HashMap::new(),
1760            parents: HashMap::new(),
1761            name_uses: HashMap::new(),
1762            attr_uses: HashMap::new(),
1763            escaped: HashSet::new(),
1764            exposed: Vec::new(),
1765            def_index: HashMap::new(),
1766            loops: HashMap::new(),
1767            env_reads: Vec::new(),
1768            constructions: HashMap::new(),
1769            name_memo: HashMap::new(),
1770            attr_memo: HashMap::new(),
1771            dyn_attr_memo: HashMap::new(),
1772            def_memo: HashMap::new(),
1773            param_memo: HashMap::new(),
1774            call_memo: HashMap::new(),
1775            dict_cache: HashMap::new(),
1776            dict_contents_memo: HashMap::new(),
1777            dict_nested: HashMap::new(),
1778            nested_left: MAX_FILE_NESTED_VALUES,
1779            candidates_left: MAX_FILE_CANDIDATES,
1780            own_attr_memo: HashMap::new(),
1781            class_attr_memo: HashMap::new(),
1782            self_attr_memo: HashMap::new(),
1783            loop_items_memo: HashMap::new(),
1784            reach_all_memo: HashMap::new(),
1785            caller_memo: HashMap::new(),
1786            caller_models: HashMap::new(),
1787            dict_candidates_memo: HashMap::new(),
1788            collecting: 0,
1789            name_call_index: HashMap::new(),
1790            method_call_index: HashMap::new(),
1791            visiting: HashSet::new(),
1792            name_depth: 0,
1793            cutoffs: 0,
1794            next_id: 0,
1795            openai_routing: Routing::OpenaiDirect,
1796            script: is_script_path(file),
1797            env_writes: HashSet::new(),
1798            rerouted: HashSet::new(),
1799            rerouted_pkgs: HashSet::new(),
1800            rerouted_any: None,
1801            openai_caveat: None,
1802            builtin_values: HashMap::new(),
1803            member_values: HashSet::new(),
1804            method_self_writes: Vec::new(),
1805            rebound_receivers: HashMap::new(),
1806            legacy_caveat: None,
1807            legacy_imported: false,
1808            exported: HashSet::new(),
1809            exports_dynamic: false,
1810            sdk_patched: HashMap::new(),
1811            def_bindings: Vec::new(),
1812            openai_last_config: None,
1813            config_top: false,
1814            config_plain: false,
1815            setup_end: None,
1816            root: None,
1817            scope_cuts: Vec::new(),
1818            module_stars: Vec::new(),
1819            dynamic_globals: false,
1820            loop_iter: None,
1821            import_bindings: 0,
1822            import_cut: None,
1823            out: FileUsages::new(file, "python"),
1824        }
1825    }
1826
1827    fn text(&self, node: Node<'t>) -> &'t str {
1828        self.src.get(node.byte_range()).unwrap_or("")
1829    }
1830
1831    fn span(&self, node: Node<'t>) -> Span {
1832        let start = node.start_position();
1833        let end = node.end_position();
1834        Span {
1835            line: start.row as u32 + 1,
1836            column: self.char_column(node.start_byte(), start.column),
1837            end_line: end.row as u32 + 1,
1838            end_column: self.char_column(node.end_byte(), end.column),
1839            start_byte: node.start_byte() as u32,
1840            end_byte: node.end_byte() as u32,
1841        }
1842    }
1843
1844    /// 1-based column in Unicode scalar values for a byte offset whose
1845    /// tree-sitter column (in bytes) is `byte_column`. Constant time per
1846    /// call, so a long minified line is not rescanned for every record.
1847    fn char_column(&self, byte: usize, byte_column: usize) -> u32 {
1848        if self.ascii {
1849            return byte_column as u32 + 1;
1850        }
1851        let line_start = byte.saturating_sub(byte_column);
1852        let continuation = self.continuation_before(byte) - self.continuation_before(line_start);
1853        (byte_column - continuation.min(byte_column)) as u32 + 1
1854    }
1855
1856    fn continuation_before(&self, at: usize) -> usize {
1857        let at = at.min(self.src.len());
1858        let block = at / 64;
1859        let base = self.cont_blocks.get(block).copied().unwrap_or(0) as usize;
1860        base + self.src.as_bytes()[block * 64..at]
1861            .iter()
1862            .filter(|b| (**b & 0xC0) == 0x80)
1863            .count()
1864    }
1865
1866    fn symbol(&self, scope: usize) -> Option<String> {
1867        self.scopes[scope].symbol.clone()
1868    }
1869
1870    fn fresh_id(&mut self) -> usize {
1871        self.next_id += 1;
1872        self.next_id
1873    }
1874
1875    // ------------------------------------------------------------------
1876    // Pass 1: collect
1877    // ------------------------------------------------------------------
1878
1879    fn collect(&mut self, root: Node<'t>) {
1880        self.scopes[0].start = root.start_byte();
1881        self.scopes[0].end = root.end_byte();
1882        self.root = Some(root);
1883        let mut stack = vec![Frame {
1884            node: root,
1885            scope: 0,
1886            parent: None,
1887            field: None,
1888            block_end: root.end_byte(),
1889            stmt: None,
1890            inner_loop: None,
1891            grand: None,
1892            annotation: false,
1893        }];
1894        // One cursor, reset at each node, walks every node's children.
1895        let mut cursor = root.walk();
1896        while let Some(frame) = stack.pop() {
1897            let node = frame.node;
1898            let scope = frame.scope;
1899            let stmt = frame.stmt.unwrap_or((node.start_byte(), node.end_byte()));
1900            // A statement-level binding holds from the end of its statement
1901            // to the end of its block.
1902            let place = Place {
1903                at: stmt.1,
1904                region: Some((stmt.1, frame.block_end)),
1905            };
1906            let mut inner = scope;
1907            let mut child_loop = frame.inner_loop;
1908            if node.is_named() {
1909                match node.kind() {
1910                    "function_definition"
1911                    | "class_definition"
1912                    | "lambda"
1913                    | "list_comprehension"
1914                    | "set_comprehension"
1915                    | "dictionary_comprehension"
1916                    | "generator_expression"
1917                        if self.scopes[scope].depth >= MAX_SCOPE_DEPTH =>
1918                    {
1919                        // Nothing inside is walked: every scope walk stays
1920                        // bounded, and what it binds or writes is unknown.
1921                        self.note_file_dynamic(
1922                            "scopes nested more than 64 deep, which are not analyzed",
1923                            node,
1924                        );
1925                        self.scope_cuts.push((node, scope));
1926                        continue;
1927                    }
1928                    "function_definition" => {
1929                        inner = self.enter_function(node, scope, frame.parent);
1930                        child_loop = None;
1931                    }
1932                    "class_definition" => {
1933                        inner = self.enter_class(node, scope, frame.parent);
1934                        child_loop = None;
1935                    }
1936                    "lambda" => {
1937                        inner = self.enter_lambda(node, scope, frame.parent, frame.field);
1938                        child_loop = None;
1939                    }
1940                    "list_comprehension"
1941                    | "set_comprehension"
1942                    | "dictionary_comprehension"
1943                    | "generator_expression" => {
1944                        inner = self.enter_comprehension(node, scope);
1945                        child_loop = None;
1946                    }
1947                    "for_statement" | "while_statement" => {
1948                        let loops = self.loops.entry(scope).or_default();
1949                        loops.push(LoopRange {
1950                            start: node.start_byte(),
1951                            end: node.end_byte(),
1952                            parent: frame.inner_loop,
1953                        });
1954                        child_loop = Some(loops.len() - 1);
1955                        self.record_loop_target(node, scope);
1956                    }
1957                    "for_in_clause" => self.record_loop_target(node, scope),
1958                    "import_statement" => self.import_statement(node, scope, place),
1959                    "import_from_statement" => self.import_from(node, scope, place),
1960                    "assignment" | "augmented_assignment"
1961                        if node
1962                            .child_by_field_name("left")
1963                            .is_some_and(|l| self.text(l) == "__all__")
1964                            && node.child_by_field_name("right").is_some() =>
1965                    {
1966                        if let Some(right) = node.child_by_field_name("right") {
1967                            self.note_exports(right);
1968                        }
1969                        if let Some(left) = node.child_by_field_name("left") {
1970                            self.record_target(left, None, None, scope, true, place);
1971                        }
1972                    }
1973                    "assignment" => {
1974                        if let Some(left) = node.child_by_field_name("left") {
1975                            let value = node.child_by_field_name("right");
1976                            let annotation = node.child_by_field_name("type");
1977                            self.config_top = is_top_statement(&frame);
1978                            self.config_plain = true;
1979                            self.record_target(left, value, annotation, scope, false, place);
1980                            self.config_top = false;
1981                            self.config_plain = false;
1982                        }
1983                        self.note_chained_alias(node);
1984                    }
1985                    "augmented_assignment" => {
1986                        if let Some(left) = node.child_by_field_name("left") {
1987                            self.config_top = is_top_statement(&frame);
1988                            self.record_target(left, None, None, scope, true, place);
1989                            self.config_top = false;
1990                        }
1991                    }
1992                    "with_item" => {
1993                        // Bound before the body runs, for the rest of the block.
1994                        let place = Place {
1995                            at: node.end_byte(),
1996                            region: Some((node.end_byte(), frame.block_end)),
1997                        };
1998                        self.record_with_item(node, scope, place);
1999                    }
2000                    "named_expression" => {
2001                        if let Some(name) = node.child_by_field_name("name") {
2002                            let value = node.child_by_field_name("value");
2003                            // A walrus in a comprehension binds in the
2004                            // enclosing function or module (PEP 572), and
2005                            // one in a default or annotation of a `def` or
2006                            // `lambda` where that header runs.
2007                            let mut home = scope;
2008                            loop {
2009                                let current = &self.scopes[home];
2010                                let header = current.kind == ScopeKind::Function
2011                                    && node.start_byte() < current.body_start;
2012                                if home == 0 || !(current.comprehension || header) {
2013                                    break;
2014                                }
2015                                home = current.parent.unwrap_or(0);
2016                            }
2017                            let place = Place {
2018                                at: node.end_byte(),
2019                                region: None,
2020                            };
2021                            self.record_target(name, value, None, home, false, place);
2022                        }
2023                    }
2024                    "type_alias_statement" => self.record_type_alias(node, scope, place),
2025                    "case_clause" => {
2026                        for pattern in named_children(node) {
2027                            if pattern.kind() == "case_pattern" {
2028                                self.record_pattern_captures(pattern, scope);
2029                            }
2030                        }
2031                    }
2032                    "except_clause" | "except_group_clause" => {
2033                        // `except E as name:` binds `name` in the handler
2034                        // only (it is deleted after it).
2035                        for child in named_children(node) {
2036                            let target = (child.kind() == "as_pattern")
2037                                .then(|| child.child_by_field_name("alias"))
2038                                .flatten()
2039                                .and_then(|alias| alias.named_child(0));
2040                            if let Some(target) = target {
2041                                let place = Place {
2042                                    at: target.end_byte(),
2043                                    region: None,
2044                                };
2045                                self.record_target(target, None, None, scope, true, place);
2046                            }
2047                        }
2048                    }
2049                    "global_statement" | "nonlocal_statement" => {
2050                        // In a class body too: `class C: global M; M = 1`
2051                        // binds the module's `M`, not a class attribute.
2052                        if self.scopes[scope].kind != ScopeKind::Module {
2053                            let global = node.kind() == "global_statement";
2054                            for name in named_children(node) {
2055                                let name = self.text(name).to_string();
2056                                let declared = &mut self.scopes[scope];
2057                                if global {
2058                                    declared.globals.insert(name);
2059                                } else {
2060                                    declared.nonlocals.insert(name);
2061                                }
2062                            }
2063                        }
2064                    }
2065                    "delete_statement" => {
2066                        for target in named_children(node) {
2067                            let targets = match target.kind() {
2068                                "expression_list" => named_children(target),
2069                                _ => vec![target],
2070                            };
2071                            for target in targets {
2072                                // `del M` and `del Bot.model` unbind what a
2073                                // later read sees (a base's attribute, or
2074                                // nothing): an assignment of no value.
2075                                if matches!(target.kind(), "identifier" | "attribute") {
2076                                    self.config_top =
2077                                        frame.parent.is_some_and(|p| p.kind() == "module");
2078                                    self.record_target(target, None, None, scope, true, place);
2079                                    self.config_top = false;
2080                                } else {
2081                                    self.note_mutated_root(target);
2082                                }
2083                            }
2084                        }
2085                    }
2086                    "call" => {
2087                        let callee = node.child_by_field_name("function");
2088                        // `__all__.extend([...])`, `__all__.append("name")`.
2089                        if callee
2090                            .and_then(|f| f.child_by_field_name("object"))
2091                            .is_some_and(|o| self.text(o) == "__all__")
2092                        {
2093                            if let Some(args) = node.child_by_field_name("arguments") {
2094                                self.note_exports(args);
2095                            }
2096                        }
2097                        self.note_dynamic_call(node, scope);
2098                        self.config_top = is_top_statement(&frame);
2099                        self.note_attr_write_call(node, scope, place);
2100                        self.config_top = false;
2101                        self.calls.push((node, scope));
2102                        self.call_scope.insert(node.id(), scope);
2103                        if let Some(parent) = frame.parent {
2104                            self.parents.insert(node.id(), parent);
2105                        }
2106                        self.note_dict_mutation(node);
2107                        self.note_env_read(node);
2108                        self.note_env_write(node);
2109                        if is_get_call(node, |n| self.text(n)) {
2110                            self.note_dict_part(node, &frame, scope);
2111                        }
2112                    }
2113                    "subscript" => {
2114                        self.note_env_read(node);
2115                        self.note_dict_part(node, &frame, scope);
2116                        self.note_namespace_lookup(node);
2117                    }
2118                    "parenthesized_expression"
2119                    | "boolean_operator"
2120                    | "conditional_expression"
2121                    | "await" => {
2122                        if let Some(parent) = frame.parent {
2123                            self.parents.insert(node.id(), parent);
2124                        }
2125                    }
2126                    "attribute" => {
2127                        if is_value_reference(frame.parent, frame.field) {
2128                            self.refs.push((node, scope));
2129                        }
2130                        self.note_attr_use(node, &frame, scope);
2131                        self.note_env_read(node);
2132                        self.note_dict_attribute(node, &frame);
2133                        self.note_dynamic_attribute(node, &frame);
2134                        self.note_member_value(node, &frame);
2135                    }
2136                    "identifier" => {
2137                        self.note_name_use(node, &frame, scope);
2138                        self.note_dict_name(node, &frame, scope);
2139                        self.note_class_use(node, &frame);
2140                        self.note_builtin_value(node, &frame);
2141                        if is_environ_name(self.text(node)) {
2142                            self.note_environ_use(node, &frame, true);
2143                        }
2144                    }
2145                    _ => {}
2146                }
2147            }
2148            // An import's names were read above and bind nothing else: its
2149            // children (one per imported name) are not walked.
2150            if matches!(
2151                node.kind(),
2152                "import_statement" | "import_from_statement" | "future_import_statement"
2153            ) {
2154                continue;
2155            }
2156            let (block_end, child_stmt) = match node.kind() {
2157                "module" | "block" => (node.end_byte(), None),
2158                _ => (frame.block_end, Some(stmt)),
2159            };
2160            // Punctuation and keywords carry nothing: only named children
2161            // are walked, which also keeps the stack small on deep chains.
2162            // They are pushed in order, then that run is reversed, so the
2163            // walk stays pre-order without a list per node.
2164            let first = stack.len();
2165            let annotation = frame.annotation || node.kind() == "type";
2166            cursor.reset(node);
2167            if cursor.goto_first_child() {
2168                loop {
2169                    let child = cursor.node();
2170                    if child.is_named() {
2171                        stack.push(Frame {
2172                            node: child,
2173                            scope: inner,
2174                            parent: Some(node),
2175                            field: cursor.field_name(),
2176                            block_end,
2177                            stmt: child_stmt,
2178                            inner_loop: child_loop,
2179                            grand: frame.parent,
2180                            annotation,
2181                        });
2182                    }
2183                    if !cursor.goto_next_sibling() {
2184                        break;
2185                    }
2186                }
2187            }
2188            stack[first..].reverse();
2189        }
2190        // The walk is pre-order, so this is already sorted; keep it so.
2191        self.env_reads.sort_unstable();
2192    }
2193
2194    /// The target of a `for` statement or clause: bound once per item, so it
2195    /// never dominates; a plain name keeps what the loop runs over, whose
2196    /// items are the values it may take.
2197    fn record_loop_target(&mut self, node: Node<'t>, scope: usize) {
2198        let Some(left) = node.child_by_field_name("left") else {
2199            return;
2200        };
2201        let place = Place {
2202            at: left.end_byte(),
2203            region: None,
2204        };
2205        if left.kind() == "identifier" {
2206            self.loop_iter = node.child_by_field_name("right");
2207        }
2208        self.record_target(left, None, None, scope, true, place);
2209        self.loop_iter = None;
2210    }
2211
2212    /// Records a call or value use of a bare name, for resolving parameters
2213    /// from in-file callers.
2214    fn note_name_use(&mut self, node: Node<'t>, frame: &Frame<'t>, scope: usize) {
2215        let Some(parent) = frame.parent else {
2216            return;
2217        };
2218        let declaration = match (parent.kind(), frame.field) {
2219            ("call", Some("function")) => {
2220                let name = self.text(node);
2221                self.name_uses
2222                    .entry(name)
2223                    .or_default()
2224                    .calls
2225                    .push((parent, scope));
2226                return;
2227            }
2228            // An annotation names a type; it does not pass the value on.
2229            ("type", _) => true,
2230            _ => is_declaration(parent.kind(), frame.field),
2231        };
2232        if !declaration {
2233            let name = self.text(node);
2234            self.name_uses.entry(name).or_default().escapes = true;
2235        }
2236    }
2237
2238    /// Records a call or value use of `x.name`, for resolving method
2239    /// parameters from in-file callers.
2240    fn note_attr_use(&mut self, node: Node<'t>, frame: &Frame<'t>, scope: usize) {
2241        let Some(attr) = node.child_by_field_name("attribute") else {
2242            return;
2243        };
2244        let name = self.text(attr);
2245        let uses = self.attr_uses.entry(name).or_default();
2246        match frame.parent {
2247            Some(parent) if parent.kind() == "call" && frame.field == Some("function") => {
2248                uses.calls.push((parent, scope));
2249            }
2250            _ => uses.escapes = true,
2251        }
2252        self.note_mangled_use(name);
2253    }
2254
2255    /// `__all__ = [...]`, `__all__ += [...]`, `__all__.extend([...])`: a
2256    /// `_private` function or class listed there is exported, so other
2257    /// modules may call or subclass it (its calls are not all in this
2258    /// file). A list built from names (`__all__ = _EXPORTS`, `extend(names)`)
2259    /// may export any module-level name ([`Ctx::exports_dynamic`]).
2260    fn note_exports(&mut self, node: Node<'t>) {
2261        let mut cursor = node.walk();
2262        let mut stack = vec![node];
2263        while let Some(current) = stack.pop() {
2264            if let Some(name) = self.plain_literal(current) {
2265                self.name_uses.entry(name).or_default().escapes = true;
2266                self.exported.insert(name);
2267                continue;
2268            }
2269            if current.kind() == "identifier" {
2270                self.exports_dynamic = true;
2271            }
2272            for child in current.named_children(&mut cursor) {
2273                stack.push(child);
2274            }
2275        }
2276    }
2277
2278    /// `_A__go`, the mangled name of `A.__go` used from outside `A`: a call
2279    /// this file cannot attribute, so `__go`'s calls are not all seen.
2280    fn note_mangled_use(&mut self, name: &'t str) {
2281        if let Some(rest) = name.strip_prefix('_') {
2282            if let Some(at) = rest.find("__").filter(|at| *at > 0) {
2283                let mangled = &rest[at..];
2284                if mangled.len() > 2 && !mangled.ends_with("__") {
2285                    self.attr_uses.entry(mangled).or_default().escapes = true;
2286                }
2287            }
2288        }
2289    }
2290
2291    /// Records `node` when it reads the process environment: `os.environ`,
2292    /// `os.getenv`, `environ.get`, `getenv(...)` or `environ[...]`.
2293    fn note_env_read(&mut self, node: Node<'t>) {
2294        let (object, member) = match node.kind() {
2295            "attribute" => (
2296                node.child_by_field_name("object"),
2297                node.child_by_field_name("attribute"),
2298            ),
2299            "call" => (node.child_by_field_name("function"), None),
2300            "subscript" => (node.child_by_field_name("value"), None),
2301            _ => return,
2302        };
2303        let Some(object) = object.filter(|o| o.kind() == "identifier") else {
2304            return;
2305        };
2306        let reads = match (node.kind(), self.text(object), member.map(|m| self.text(m))) {
2307            ("attribute", "os", Some(member)) => {
2308                matches!(member, "environ" | "environb" | "getenv" | "getenvb")
2309            }
2310            ("attribute", "environ", Some(member)) => matches!(member, "get" | "setdefault"),
2311            ("call", name, _) => name == "getenv",
2312            ("subscript", name, _) => name == "environ",
2313            _ => false,
2314        };
2315        if reads {
2316            self.env_reads.push(node.start_byte());
2317        }
2318    }
2319
2320    /// Records the names of environment variables set by `node`: an
2321    /// assignment target `os.environ["NAME"]`, or a call to
2322    /// `os.environ.setdefault("NAME", ...)`, `os.environ.update(...)`,
2323    /// `os.environ.__setitem__("NAME", ...)` or `os.putenv("NAME", ...)`. A
2324    /// name that is not a literal may be any variable: the write is a
2325    /// dynamic feature ([`Ctx::env_wild`]).
2326    fn note_env_write(&mut self, node: Node<'t>) {
2327        // `os.environ`, or the same through any other object (`_os.environ`
2328        // for `import os as _os`, `import_module("os").environ`): matched by
2329        // the attribute name, so an alias of `os` cannot hide a write.
2330        let environ = |n: Node<'t>| match n.kind() {
2331            "identifier" => is_environ_name(self.text(n)),
2332            "attribute" => n
2333                .child_by_field_name("attribute")
2334                .is_some_and(|a| is_environ_name(self.text(a))),
2335            _ => false,
2336        };
2337        let mut names: Vec<String> = Vec::new();
2338        let mut wild = false;
2339        let mut bare = false;
2340        match node.kind() {
2341            "subscript" => {
2342                if let Some(value) = node.child_by_field_name("value").filter(|v| environ(*v)) {
2343                    bare = value.kind() == "identifier";
2344                    match single_subscript(node).and_then(|k| self.literal(k).ok()) {
2345                        Some(name) => names.push(name),
2346                        None => wild = true,
2347                    }
2348                }
2349            }
2350            "call" => {
2351                let Some(function) = node.child_by_field_name("function") else {
2352                    return;
2353                };
2354                // Most calls are something else: decide from the last name
2355                // before rendering anything.
2356                let last = match function.kind() {
2357                    "identifier" => Some(function),
2358                    "attribute" => function.child_by_field_name("attribute"),
2359                    _ => None,
2360                };
2361                if !last.is_some_and(|n| {
2362                    matches!(
2363                        self.text(n),
2364                        "putenv" | "setdefault" | "update" | "__setitem__"
2365                    )
2366                }) {
2367                    return;
2368                }
2369                let (positional, keywords) = call_arguments(node, |n| self.text(n));
2370                let putenv = last.is_some_and(|n| self.text(n) == "putenv");
2371                let method = function
2372                    .child_by_field_name("attribute")
2373                    .map(|a| self.text(a))
2374                    .unwrap_or_default();
2375                let object = function.child_by_field_name("object");
2376                let on_environ = object.is_some_and(environ);
2377                bare = object.is_some_and(|o| o.kind() == "identifier");
2378                if putenv || (on_environ && matches!(method, "setdefault" | "__setitem__")) {
2379                    bare = false;
2380                    match positional.first().and_then(|k| self.literal(*k).ok()) {
2381                        Some(name) => names.push(name),
2382                        None => wild = true,
2383                    }
2384                } else if on_environ && method == "update" {
2385                    names.extend(keywords.iter().map(|(k, _)| k.clone()));
2386                    let splat = node.child_by_field_name("arguments").is_some_and(|args| {
2387                        named_children(args)
2388                            .iter()
2389                            .any(|a| matches!(a.kind(), "dictionary_splat" | "list_splat"))
2390                    });
2391                    wild |= splat;
2392                    for arg in positional {
2393                        if arg.kind() != "dictionary" {
2394                            // A name, a call or pairs: any variable.
2395                            wild = true;
2396                            continue;
2397                        }
2398                        for entry in dict_entries(arg, |n| self.literal(n).ok(), |n| self.text(n)) {
2399                            match entry {
2400                                Some((key, _)) => names.push(key),
2401                                None => wild = true,
2402                            }
2403                        }
2404                    }
2405                }
2406            }
2407            _ => {}
2408        }
2409        if wild {
2410            let feature =
2411                Self::feature("an environment variable written with a run-time name", node);
2412            if bare {
2413                self.bare_environ_wild.get_or_insert(feature);
2414            } else {
2415                self.env_wild.get_or_insert(feature);
2416            }
2417        }
2418        self.env_writes.extend(names);
2419    }
2420
2421    /// The 1-based line `node` starts on.
2422    fn line_of(node: Node<'t>) -> u32 {
2423        node.start_position().row as u32 + 1
2424    }
2425
2426    fn feature(what: &'static str, node: Node<'t>) -> Feature {
2427        Feature {
2428            what,
2429            line: Self::line_of(node),
2430        }
2431    }
2432
2433    /// Records the first feature that may rebind anything in the file.
2434    fn note_file_dynamic(&mut self, what: &'static str, node: Node<'t>) {
2435        self.file_dynamic.get_or_insert(Self::feature(what, node));
2436    }
2437
2438    /// `exec`, `eval`, `compile`, `globals()`, `vars(obj)` (an object's
2439    /// `__dict__`), `locals()` and `vars()` outside a function (where they
2440    /// are the module's or the class body's namespace; a function's
2441    /// `locals()` cannot rebind its names), the module importing itself,
2442    /// and instances built without naming their class (`type(self)(...)`,
2443    /// `cls(...)`).
2444    fn note_dynamic_call(&mut self, call: Node<'t>, scope: usize) {
2445        let Some(function) = call.child_by_field_name("function") else {
2446            return;
2447        };
2448        // `__import__(__name__)`, `importlib.import_module(__name__)`, and
2449        // the same for `builtins` and `sys`, whose namespace features are
2450        // then reached under a name this file does not spell.
2451        let imported = |cx: &Self| {
2452            call_arguments(call, |n| cx.text(n))
2453                .0
2454                .first()
2455                .and_then(|arg| match arg.kind() {
2456                    "identifier" if cx.text(*arg) == "__name__" => {
2457                        Some("the module importing itself")
2458                    }
2459                    _ => match cx.plain_literal(*arg) {
2460                        Some("__main__") => Some("the module importing itself"),
2461                        Some("builtins" | "sys") => Some("`builtins` or `sys` imported by name"),
2462                        _ => None,
2463                    },
2464                })
2465        };
2466        match function.kind() {
2467            "identifier" => {
2468                let what = match self.text(function) {
2469                    "exec" => "`exec`",
2470                    "eval" => "`eval`",
2471                    "compile" => "`compile`",
2472                    "globals" => "`globals()`",
2473                    "locals" | "vars"
2474                        if self.scopes[scope].kind == ScopeKind::Function
2475                            && !self.scopes[scope].comprehension
2476                            && call_arguments(call, |n| self.text(n)).0.is_empty() =>
2477                    {
2478                        return;
2479                    }
2480                    "locals" => "`locals()`",
2481                    "vars" => "`vars()`",
2482                    "__import__" | "import_module" => match imported(self) {
2483                        Some(what) => what,
2484                        None => return,
2485                    },
2486                    "cls" => {
2487                        self.dynamic_constructors
2488                            .get_or_insert(Self::feature("`cls(...)`", call));
2489                        return;
2490                    }
2491                    _ => return,
2492                };
2493                self.note_file_dynamic(what, call);
2494            }
2495            "attribute" => {
2496                let imports = function
2497                    .child_by_field_name("attribute")
2498                    .is_some_and(|a| matches!(self.text(a), "import_module" | "reload"));
2499                if let Some(what) = imports.then(|| imported(self)).flatten() {
2500                    self.note_file_dynamic(what, call);
2501                }
2502            }
2503            "call" => {
2504                // `type(self)(...)`.
2505                let inner = function.child_by_field_name("function");
2506                if inner.is_some_and(|f| f.kind() == "identifier" && self.text(f) == "type")
2507                    && call_arguments(function, |n| self.text(n)).0.len() == 1
2508                {
2509                    self.dynamic_constructors
2510                        .get_or_insert(Self::feature("`type(...)(...)`", call));
2511                }
2512            }
2513            _ => {}
2514        }
2515    }
2516
2517    /// `exec`, `eval`, `compile`, `globals`, `locals`, `vars` or
2518    /// `__import__` used as a value (`run = exec`, `g = globals`), which a
2519    /// call through another name may then run; and `__builtins__`, through
2520    /// which any of them can be reached. A name the file binds itself (a
2521    /// parameter `eval`) is not the builtin: that is checked once every
2522    /// binding is known ([`Ctx::settle_builtin_values`]).
2523    fn note_builtin_value(&mut self, node: Node<'t>, frame: &Frame<'t>) {
2524        let name = self.text(node);
2525        if matches!(name, "builtins" | "sys") {
2526            // The module itself handed on (`s = sys`, `f(builtins)`): its
2527            // namespace features are then reached under another name.
2528            let used = frame.parent.is_some_and(|parent| {
2529                !(parent.kind() == "attribute" && frame.field == Some("object"))
2530                    && !is_declaration(parent.kind(), frame.field)
2531            });
2532            if used && !frame.annotation {
2533                self.note_file_dynamic("`builtins` or `sys` used as a value", node);
2534            }
2535            return;
2536        }
2537        if !is_namespace_builtin(name) && name != "__builtins__" {
2538            return;
2539        }
2540        let Some(parent) = frame.parent else {
2541            return;
2542        };
2543        let called = parent.kind() == "call" && frame.field == Some("function");
2544        if (called && name != "__builtins__") || is_declaration(parent.kind(), frame.field) {
2545            return;
2546        }
2547        self.builtin_values.entry(name).or_insert(Self::feature(
2548            "a builtin that reads or rebinds names (`exec`, `eval`, `globals`...) used as a value",
2549            node,
2550        ));
2551    }
2552
2553    /// Whole-file features from [`Ctx::note_builtin_value`] whose name the
2554    /// file does not bind anywhere itself.
2555    fn settle_builtin_values(&mut self) {
2556        if self.builtin_values.is_empty() {
2557            return;
2558        }
2559        let bound: HashSet<&str> = self
2560            .assigns
2561            .keys()
2562            .chain(self.params.keys())
2563            .chain(self.functions.keys())
2564            .chain(self.imports.keys())
2565            .chain(self.other_imports.keys())
2566            .map(|(_, name)| name.as_str())
2567            .collect();
2568        let mut found: Vec<Feature> = self
2569            .builtin_values
2570            .iter()
2571            .filter(|(name, _)| !bound.contains(**name))
2572            .map(|(_, feature)| *feature)
2573            .collect();
2574        found.sort_by_key(|f| f.line);
2575        if let Some(feature) = found.first() {
2576            self.file_dynamic.get_or_insert(*feature);
2577        }
2578    }
2579
2580    /// Imports that hand out a dynamic feature under another name:
2581    /// `from sys import modules`, `from builtins import exec` (and the other
2582    /// namespace builtins), and `os.environ` or `os.putenv` imported under
2583    /// another name (`from os import environ as E`), which is an alias of
2584    /// the process environment.
2585    fn note_dynamic_import(&mut self, module: &str, name: &str, local: &str, node: Node<'t>) {
2586        match (module, name) {
2587            ("sys", "modules") => self.note_file_dynamic("`sys.modules` imported by name", node),
2588            ("builtins", name) if is_namespace_builtin(name) => self.note_file_dynamic(
2589                "a builtin that reads or rebinds names (`exec`, `eval`, `globals`...) imported by name",
2590                node,
2591            ),
2592            ("os", "environ" | "environb" | "putenv") if local != name => {
2593                self.env_wild.get_or_insert(Self::feature(
2594                    "`os.environ` or `os.putenv` imported under another name",
2595                    node,
2596                ));
2597            }
2598            _ => {}
2599        }
2600    }
2601
2602    /// The file's own module name (its stem), when other modules can import
2603    /// it by that name: not a package `__init__`, a `__main__` or a script.
2604    fn own_module_name(&self) -> Option<&str> {
2605        let stem = std::path::Path::new(&self.file).file_stem()?.to_str()?;
2606        (!self.script && !matches!(stem, "__init__" | "__main__")).then_some(stem)
2607    }
2608
2609    /// `import app` in `app.py`: the module importing itself, through which
2610    /// it may rebind its own names or call its private functions. A tracked
2611    /// SDK's name is left alone (`import openai` in an `openai.py` example).
2612    fn note_self_import(&mut self, written: &str, node: Node<'t>) {
2613        let last = written.rsplit('.').next().unwrap_or(written);
2614        if Pkg::of_module(written).is_none() && self.own_module_name() == Some(last) {
2615            self.note_file_dynamic("the module importing itself", node);
2616        }
2617    }
2618
2619    /// `x.__dict__`, `sys.modules`, `x.__class__` and uses of `os.environ`.
2620    fn note_dynamic_attribute(&mut self, node: Node<'t>, frame: &Frame<'t>) {
2621        let Some(attr) = node.child_by_field_name("attribute") else {
2622            return;
2623        };
2624        let object = node.child_by_field_name("object");
2625        let on =
2626            |name: &str| object.is_some_and(|o| o.kind() == "identifier" && self.text(o) == name);
2627        match self.text(attr) {
2628            "__dict__" => self.note_file_dynamic("`__dict__`", node),
2629            "modules" if on("sys") => self.note_file_dynamic("`sys.modules`", node),
2630            "__class__" => {
2631                self.dynamic_constructors
2632                    .get_or_insert(Self::feature("`__class__`", node));
2633            }
2634            // `os.environ` (or `os.environb`, which shares its data on
2635            // POSIX), or through an alias of `os`.
2636            "environ" | "environb" => self.note_environ_use(node, frame, false),
2637            // A frame's namespaces (`inspect.currentframe().f_globals`,
2638            // `sys._getframe(1).f_locals`) rebind names at run time.
2639            "f_globals" | "f_locals" | "f_builtins" => {
2640                self.note_file_dynamic("a frame's namespace (`f_globals`, `f_locals`)", node);
2641            }
2642            name if is_namespace_builtin(name) && (on("builtins") || on("__builtins__")) => {
2643                self.note_file_dynamic(
2644                    "a builtin that reads or rebinds names (`exec`, `eval`, `globals`...) reached through `builtins`",
2645                    node,
2646                );
2647            }
2648            _ => {}
2649        }
2650    }
2651
2652    /// `os.environ` (or a bare `environ`) used other than to read it or to
2653    /// write a variable named by a literal: assigned to another name,
2654    /// passed to a call, updated in place. Any variable, the SDK's endpoint
2655    /// variable among them, may then be set.
2656    fn note_environ_use(&mut self, node: Node<'t>, frame: &Frame<'t>, bare: bool) {
2657        let Some(parent) = frame.parent else {
2658            return;
2659        };
2660        let reads = match (parent.kind(), frame.field) {
2661            // `os.environ[...]`: a read, or a write `note_env_write` sees.
2662            ("subscript", Some("value")) => true,
2663            ("attribute", Some("object")) => {
2664                let method = parent
2665                    .child_by_field_name("attribute")
2666                    .map(|a| self.text(a))
2667                    .unwrap_or_default();
2668                // Writes through `setdefault`, `update` and `__setitem__` are
2669                // read by `note_env_write`; removals cannot add an endpoint.
2670                matches!(
2671                    method,
2672                    "get"
2673                        | "copy"
2674                        | "keys"
2675                        | "items"
2676                        | "values"
2677                        | "__contains__"
2678                        | "__getitem__"
2679                        | "setdefault"
2680                        | "update"
2681                        | "__setitem__"
2682                        | "pop"
2683                        | "popitem"
2684                        | "clear"
2685                        | "__delitem__"
2686                )
2687            }
2688            // `{**os.environ, ...}` copies it.
2689            ("comparison_operator", _)
2690            | ("expression_statement", _)
2691            | ("dictionary_splat", _)
2692            | ("for_statement" | "for_in_clause", Some("right")) => true,
2693            ("argument_list", _) => {
2694                let callee = frame
2695                    .grand
2696                    .and_then(|call| call.child_by_field_name("function"))
2697                    .map(|f| self.render_links(f, 4))
2698                    .unwrap_or_default();
2699                READ_ONLY_CALLS.contains(&callee.as_str())
2700                    || SHALLOW_CALLS.contains(&callee.as_str())
2701            }
2702            (kind, field) => bare && is_declaration(kind, field),
2703        };
2704        if reads {
2705            return;
2706        }
2707        let feature = Self::feature("`os.environ` aliased, passed or updated in place", node);
2708        if bare {
2709            self.bare_environ_wild.get_or_insert(feature);
2710        } else {
2711            self.env_wild.get_or_insert(feature);
2712        }
2713    }
2714
2715    /// A name used as a value other than to read or write one of its
2716    /// attributes, call it, subclass it, test it or annotate with it: if a
2717    /// class has that name, whatever receives it may change its attributes.
2718    fn note_class_use(&mut self, node: Node<'t>, frame: &Frame<'t>) {
2719        let Some(parent) = frame.parent else {
2720            return;
2721        };
2722        if frame.annotation || self.class_escapes.contains_key(self.text(node)) {
2723            return;
2724        }
2725        let safe = match (parent.kind(), frame.field) {
2726            ("attribute", Some("object")) | ("call", Some("function")) => true,
2727            ("argument_list", _) => match frame.grand {
2728                Some(grand) if grand.kind() == "class_definition" => true,
2729                Some(grand) if grand.kind() == "call" => grand
2730                    .child_by_field_name("function")
2731                    .filter(|f| f.kind() == "identifier")
2732                    .is_some_and(|f| {
2733                        matches!(
2734                            self.text(f),
2735                            "isinstance"
2736                                | "issubclass"
2737                                | "type"
2738                                | "super"
2739                                | "print"
2740                                | "repr"
2741                                | "str"
2742                                | "id"
2743                                | "hash"
2744                        )
2745                    }),
2746                _ => false,
2747            },
2748            ("comparison_operator", _) | ("expression_statement", _) | ("type", _) => true,
2749            (kind, field) => is_declaration(kind, field),
2750        };
2751        if !safe {
2752            let name = self.text(node);
2753            self.class_escapes
2754                .entry(name)
2755                .or_insert_with(|| Self::feature("the class used as a value", node));
2756        }
2757    }
2758
2759    /// `D[k] = v`, `del D[k]`, `D["a"]["b"] = v`, `H.d["k"] = v`,
2760    /// `self.cfg["k"] = v`: the name at the root of the target, and every
2761    /// attribute name along it (`d`, `cfg`: a class or instance attribute
2762    /// may alias a dict), may hold a dict that changes.
2763    fn note_mutated_root(&mut self, target: Node<'t>) {
2764        if matches!(target.kind(), "subscript" | "attribute") {
2765            let names = self.chain_names(target);
2766            self.escaped.extend(names);
2767        }
2768    }
2769
2770    /// The root name of a subscript, attribute or call chain and every
2771    /// attribute name along it, plus the literal key of
2772    /// `globals()["NAME"]` / `vars()["NAME"]`, which names a module-level
2773    /// binding.
2774    fn chain_names(&self, node: Node<'t>) -> Vec<&'t str> {
2775        let mut names = Vec::new();
2776        let mut node = node;
2777        for _ in 0..MAX_DEPTH {
2778            node = match node.kind() {
2779                "identifier" => {
2780                    names.push(self.text(node));
2781                    break;
2782                }
2783                "subscript" => {
2784                    let Some(value) = node.child_by_field_name("value") else {
2785                        break;
2786                    };
2787                    if is_namespace_call(value, |n| self.text(n)) {
2788                        if let Some(key) =
2789                            single_subscript(node).and_then(|k| self.plain_literal(k))
2790                        {
2791                            names.push(key);
2792                        }
2793                        break;
2794                    }
2795                    value
2796                }
2797                "attribute" => {
2798                    if let Some(attr) = node.child_by_field_name("attribute") {
2799                        names.push(self.text(attr));
2800                    }
2801                    match node.child_by_field_name("object") {
2802                        Some(object) => object,
2803                        None => break,
2804                    }
2805                }
2806                "call" => match node.child_by_field_name("function") {
2807                    Some(function) => function,
2808                    None => break,
2809                },
2810                "parenthesized_expression" => match node.named_child(0) {
2811                    Some(inner) => inner,
2812                    None => break,
2813                },
2814                _ => break,
2815            };
2816        }
2817        names
2818    }
2819
2820    /// `D.update(...)`, `D["a"].setdefault(...)`, `D["fallbacks"].append(...)`.
2821    fn note_dict_mutation(&mut self, call: Node<'t>) {
2822        let Some(function) = call
2823            .child_by_field_name("function")
2824            .filter(|f| f.kind() == "attribute")
2825        else {
2826            return;
2827        };
2828        let (Some(object), Some(attr)) = (
2829            function.child_by_field_name("object"),
2830            function.child_by_field_name("attribute"),
2831        ) else {
2832            return;
2833        };
2834        if MUTATING_METHODS.contains(&self.text(attr)) {
2835            let names = self.chain_names(object);
2836            self.escaped.extend(names);
2837        }
2838    }
2839
2840    /// `x = y = D` and `self.d = x = D`: `D` is aliased or stored, so it
2841    /// escapes (the inner target is also seen by [`Self::dict_use`]).
2842    fn note_chained_alias(&mut self, assignment: Node<'t>) {
2843        let mut value = assignment.child_by_field_name("right");
2844        let mut chained = false;
2845        for _ in 0..MAX_DEPTH {
2846            match value {
2847                Some(inner) if inner.kind() == "assignment" => {
2848                    chained = true;
2849                    value = inner.child_by_field_name("right");
2850                }
2851                _ => break,
2852            }
2853        }
2854        if let (Some(value), true) = (value, chained) {
2855            if value.kind() == "identifier" {
2856                self.escaped.insert(self.text(value));
2857            }
2858        }
2859    }
2860
2861    /// `K.cfg` or `self.cfg` used where a dict held there may be changed
2862    /// (assigned to a name, passed, iterated): the attribute name
2863    /// escapes, so a dict aliased by an attribute of that name is not read.
2864    fn note_dict_attribute(&mut self, node: Node<'t>, frame: &Frame<'t>) {
2865        if matches!(self.dict_use(frame, true), DictUse::Safe) {
2866            return;
2867        }
2868        if let Some(attr) = node.child_by_field_name("attribute") {
2869            self.escaped.insert(self.text(attr));
2870        }
2871    }
2872
2873    /// A bare name: whether a dict bound to it may change or escape here.
2874    fn note_dict_name(&mut self, node: Node<'t>, frame: &Frame<'t>, scope: usize) {
2875        let name = self.text(node);
2876        match self.dict_use(frame, false) {
2877            DictUse::Safe => {}
2878            DictUse::Escape => {
2879                self.escaped.insert(name);
2880            }
2881            use_ @ (DictUse::Shallow | DictUse::Alias(_)) => self.exposed.push(Exposed {
2882                root: name,
2883                node,
2884                scope,
2885                alias: match use_ {
2886                    DictUse::Alias(target) => Some(target),
2887                    _ => None,
2888                },
2889            }),
2890        }
2891    }
2892
2893    /// `D["a"]` or `D.get("a")` on a name: whether that part leaves the
2894    /// dict here. What it holds is checked after collection: handing out a
2895    /// string cannot change the dict, handing out a nested container can.
2896    fn note_dict_part(&mut self, node: Node<'t>, frame: &Frame<'t>, scope: usize) {
2897        let Some(root) = chain_root_name(node, |n| self.text(n)) else {
2898            return;
2899        };
2900        let alias = match self.dict_use(frame, true) {
2901            DictUse::Safe => return,
2902            DictUse::Alias(target) => Some(target),
2903            DictUse::Shallow | DictUse::Escape => None,
2904        };
2905        self.exposed.push(Exposed {
2906            root,
2907            node,
2908            scope,
2909            alias,
2910        });
2911    }
2912
2913    /// How the dict or dict part at `frame` is used, from its parent, the
2914    /// field it fills there and its grandparent. `part` is set for a
2915    /// subscript or `.get` call: iterating one hands out its elements.
2916    fn dict_use(&self, frame: &Frame<'t>, part: bool) -> DictUse<'t> {
2917        let Some(parent) = frame.parent else {
2918            return DictUse::Safe;
2919        };
2920        match (parent.kind(), frame.field) {
2921            // A longer chain decides at its outer end; a target is a
2922            // definition or a mutation, recorded where it is assigned.
2923            ("subscript", Some("value"))
2924            | ("assignment" | "augmented_assignment", Some("left"))
2925            | ("delete_statement", _) => DictUse::Safe,
2926            ("attribute", Some("object")) => {
2927                let attr = parent
2928                    .child_by_field_name("attribute")
2929                    .map(|a| self.text(a))
2930                    .unwrap_or_default();
2931                if READ_ONLY_METHODS.contains(&attr) {
2932                    DictUse::Safe
2933                } else if SHALLOW_METHODS.contains(&attr) {
2934                    DictUse::Shallow
2935                } else {
2936                    DictUse::Escape
2937                }
2938            }
2939            ("dictionary_splat", _) => match frame.grand.map(|g| g.kind()) {
2940                Some("argument_list") => DictUse::Safe,
2941                _ => DictUse::Shallow,
2942            },
2943            ("list_splat", _) | ("for_statement" | "for_in_clause", Some("right")) => {
2944                // A dict iterates its keys; a nested list hands out its
2945                // elements.
2946                if part {
2947                    DictUse::Shallow
2948                } else {
2949                    DictUse::Safe
2950                }
2951            }
2952            ("if_statement" | "elif_clause" | "while_statement", Some("condition"))
2953            | ("comparison_operator" | "not_operator" | "expression_statement", _)
2954            | ("interpolation", _) => DictUse::Safe,
2955            ("argument_list", _) => {
2956                let callee = frame
2957                    .grand
2958                    .and_then(|call| call.child_by_field_name("function"))
2959                    .map(|f| self.render_links(f, 4))
2960                    .unwrap_or_default();
2961                if READ_ONLY_CALLS.contains(&callee.as_str()) {
2962                    DictUse::Safe
2963                } else if SHALLOW_CALLS.contains(&callee.as_str()) {
2964                    DictUse::Shallow
2965                } else {
2966                    DictUse::Escape
2967                }
2968            }
2969            // A whole dict or list aliased by another name may change
2970            // through it: escaped (the supported grammar reads a container
2971            // only through its one name). A part assigned to a name escapes
2972            // its dict when that part is itself a container.
2973            ("assignment", Some("right")) if part => match parent.child_by_field_name("left") {
2974                Some(target) if target.kind() == "identifier" => DictUse::Alias(self.text(target)),
2975                _ => DictUse::Escape,
2976            },
2977            (kind, field) if !part && is_declaration(kind, field) => DictUse::Safe,
2978            _ => DictUse::Escape,
2979        }
2980    }
2981
2982    /// Decides the exposed dict parts once every definition is known: a
2983    /// part that hands out a nested container or an entry that cannot be
2984    /// read, whether to a call, a loop or another name, lets its dict
2985    /// change, so the dict escapes; a name held in the dict is handed out
2986    /// and escapes too. There is no alias tracking to get wrong: a whole
2987    /// container assigned to another name has already escaped.
2988    fn settle_dict_escapes(&mut self) {
2989        for exposed in std::mem::take(&mut self.exposed) {
2990            let (alters, names) = self.exposed_contents(&exposed);
2991            if alters {
2992                self.escaped.insert(exposed.root);
2993            }
2994            self.escaped.extend(names.iter().copied());
2995        }
2996    }
2997
2998    /// What an exposed part hands out: whether a change through it could
2999    /// alter its dict (a nested container, or an entry that cannot be
3000    /// read), and the names stored in it (which may be dicts themselves).
3001    fn exposed_contents(&mut self, exposed: &Exposed<'t>) -> (bool, Rc<[&'t str]>) {
3002        let none: Rc<[&'t str]> = Rc::from(Vec::new());
3003        // The literal keys from the root to the part.
3004        let mut keys: Vec<Option<String>> = Vec::new();
3005        let mut node = exposed.node;
3006        for _ in 0..MAX_DEPTH {
3007            match node.kind() {
3008                "identifier" => break,
3009                "subscript" => {
3010                    keys.push(single_subscript(node).and_then(|k| self.literal(k).ok()));
3011                    match node.child_by_field_name("value") {
3012                        Some(value) => node = value,
3013                        None => return (true, none),
3014                    }
3015                }
3016                "call" => {
3017                    let key = call_arguments(node, |n| self.text(n)).0.first().copied();
3018                    keys.push(key.and_then(|k| self.literal(k).ok()));
3019                    match node
3020                        .child_by_field_name("function")
3021                        .and_then(|f| f.child_by_field_name("object"))
3022                    {
3023                        Some(object) => node = object,
3024                        None => return (true, none),
3025                    }
3026                }
3027                "parenthesized_expression" => match node.named_child(0) {
3028                    Some(inner) => node = inner,
3029                    None => return (true, none),
3030                },
3031                _ => return (true, none),
3032            }
3033        }
3034        if node.kind() != "identifier" {
3035            return (true, none);
3036        }
3037        // Not a dict literal this file can read here (or past the depth
3038        // limit): it escapes, so no later read can trust it.
3039        let Some(mut dict) = self.dict_node(node, exposed.scope, 0) else {
3040            return (true, none);
3041        };
3042        keys.reverse();
3043        let last = keys.len();
3044        for (i, key) in keys.into_iter().enumerate() {
3045            let Some(key) = key else {
3046                // A key known only at run time: any entry may leave.
3047                return self.dict_contents(dict.node);
3048            };
3049            let value = match self.dict_lookup(dict.node, &key) {
3050                Lookup::Found(value) => value,
3051                Lookup::Absent => return (false, none),
3052                Lookup::Unknown => return (true, none),
3053            };
3054            if i + 1 == last {
3055                return match value.kind() {
3056                    "identifier" => (false, Rc::from(vec![self.text(value)])),
3057                    _ => (is_mutable_literal(value, |n| self.text(n)), none),
3058                };
3059            }
3060            match self.dict_node(value, dict.scope, 0) {
3061                Some(inner) => dict = inner,
3062                // An entry that is not a dict literal: not readable as one.
3063                None => return (false, none),
3064            }
3065        }
3066        // The whole dict is handed out (`.items()`, `dict(D)`, an alias).
3067        if exposed.alias.is_some() && exposed.node.kind() == "identifier" {
3068            return (true, none);
3069        }
3070        self.dict_contents(dict.node)
3071    }
3072
3073    /// Whether a dict literal holds a container or an unreadable entry, and
3074    /// the names it holds. Computed once per literal.
3075    fn dict_contents(&mut self, dict: Node<'t>) -> (bool, Rc<[&'t str]>) {
3076        if let Some(found) = self.dict_contents_memo.get(&dict.id()) {
3077            return found.clone();
3078        }
3079        let mut alters = false;
3080        let mut names = Vec::new();
3081        for entry in dict_entries(dict, |n| self.literal(n).ok(), |n| self.text(n)) {
3082            match entry {
3083                None => alters = true,
3084                Some((_, value)) if value.kind() == "identifier" => names.push(self.text(value)),
3085                Some((_, value)) => alters |= is_mutable_literal(value, |n| self.text(n)),
3086            }
3087        }
3088        let found = (alters, Rc::from(names));
3089        self.dict_contents_memo.insert(dict.id(), found.clone());
3090        found
3091    }
3092
3093    fn enter_function(
3094        &mut self,
3095        node: Node<'t>,
3096        parent: usize,
3097        wrapper: Option<Node<'t>>,
3098    ) -> usize {
3099        let name = node
3100            .child_by_field_name("name")
3101            .map(|n| self.text(n).to_string())
3102            .unwrap_or_default();
3103        let class = match self.scopes[parent].kind {
3104            ScopeKind::Class => Some(parent),
3105            _ => self.scopes[parent].class,
3106        };
3107        // Same naming as the graph's Python extractor: `Class.method` inside
3108        // a class (including functions nested in a method), else the name.
3109        let symbol = match class {
3110            Some(class) => format!("{}.{}", self.scopes[class].name, name),
3111            None => name.clone(),
3112        };
3113        let mut scope = Scope::new(
3114            ScopeKind::Function,
3115            Some(parent),
3116            node.start_byte(),
3117            node.end_byte(),
3118        );
3119        scope.class = class;
3120        scope.symbol = Some(clip_owned(symbol));
3121        scope.line = node.start_position().row as u32 + 1;
3122        scope.name = name.clone();
3123        if self.scopes[parent].kind == ScopeKind::Class
3124            && matches!(
3125                name.as_str(),
3126                "__getattr__"
3127                    | "__getattribute__"
3128                    | "__setattr__"
3129                    | "__delattr__"
3130                    | "__init_subclass__"
3131            )
3132        {
3133            // Any attribute read or write may run it.
3134            self.attr_hooks
3135                .get_or_insert(Self::feature("an attribute hook (`__getattr__`...)", node));
3136        }
3137        if let Some(wrapper) = wrapper.filter(|w| w.kind() == "decorated_definition") {
3138            for decorator in named_children(wrapper) {
3139                if decorator.kind() != "decorator" {
3140                    continue;
3141                }
3142                match decorator.named_child(0).map(|d| self.text(d)) {
3143                    Some("staticmethod") => scope.staticmethod = true,
3144                    Some("classmethod") => {}
3145                    _ => scope.decorated = true,
3146                }
3147            }
3148        }
3149        scope.body_start = node
3150            .child_by_field_name("body")
3151            .map_or(node.end_byte(), |b| b.start_byte());
3152        let id = self.scopes.len();
3153        scope.depth = self.scopes[parent].depth + 1;
3154        self.scopes.push(scope);
3155        if let Some(params) = node.child_by_field_name("parameters") {
3156            self.record_params(params, id);
3157        }
3158        self.bind_receivers(id);
3159        // A method binds in its class; any other `def` where an import would.
3160        let home = match self.scopes[parent].kind {
3161            ScopeKind::Class => parent,
3162            _ => self.import_home(parent, &name),
3163        };
3164        self.def_bindings.push((
3165            (home, name.clone()),
3166            parent,
3167            Place {
3168                at: node.end_byte(),
3169                region: None,
3170            },
3171        ));
3172        self.functions.entry((home, name)).or_default().push(id);
3173        id
3174    }
3175
3176    /// A comprehension or generator expression: its own scope for its
3177    /// targets (Python 3), named after the enclosing symbol like a lambda.
3178    /// List, set and dict comprehensions run where they are written; a
3179    /// generator runs when consumed.
3180    fn enter_comprehension(&mut self, node: Node<'t>, parent: usize) -> usize {
3181        let class = match self.scopes[parent].kind {
3182            ScopeKind::Class => Some(parent),
3183            _ => self.scopes[parent].class,
3184        };
3185        let mut scope = Scope::new(
3186            ScopeKind::Function,
3187            Some(parent),
3188            node.start_byte(),
3189            node.end_byte(),
3190        );
3191        scope.class = class;
3192        scope.symbol = self.scopes[parent].symbol.clone();
3193        scope.name = "<comprehension>".to_string();
3194        scope.lambda = true;
3195        scope.comprehension = true;
3196        scope.immediate = node.kind() != "generator_expression";
3197        scope.self_recv = self.scopes[parent].self_recv;
3198        scope.cls_recv = self.scopes[parent].cls_recv;
3199        let id = self.scopes.len();
3200        scope.depth = self.scopes[parent].depth + 1;
3201        self.scopes.push(scope);
3202        id
3203    }
3204
3205    fn enter_lambda(
3206        &mut self,
3207        node: Node<'t>,
3208        parent: usize,
3209        holder: Option<Node<'t>>,
3210        field: Option<&'static str>,
3211    ) -> usize {
3212        let class = match self.scopes[parent].kind {
3213            ScopeKind::Class => Some(parent),
3214            _ => self.scopes[parent].class,
3215        };
3216        let mut scope = Scope::new(
3217            ScopeKind::Function,
3218            Some(parent),
3219            node.start_byte(),
3220            node.end_byte(),
3221        );
3222        scope.class = class;
3223        // The graph has no node for a lambda: calls in it belong to the
3224        // enclosing function.
3225        scope.symbol = self.scopes[parent].symbol.clone();
3226        scope.name = "<lambda>".to_string();
3227        scope.line = node.start_position().row as u32 + 1;
3228        scope.lambda = true;
3229        scope.body_start = node
3230            .child_by_field_name("body")
3231            .map_or(node.end_byte(), |b| b.start_byte());
3232        scope.bound_name = holder
3233            .filter(|h| h.kind() == "assignment" && field == Some("right"))
3234            .and_then(|h| h.child_by_field_name("left"))
3235            .filter(|left| left.kind() == "identifier")
3236            .map(|left| self.text(left).to_string());
3237        let id = self.scopes.len();
3238        scope.depth = self.scopes[parent].depth + 1;
3239        self.scopes.push(scope);
3240        if let Some(params) = node.child_by_field_name("parameters") {
3241            self.record_params(params, id);
3242        }
3243        self.bind_receivers(id);
3244        id
3245    }
3246
3247    /// What `self` and `cls` hold in function or lambda `id` (see
3248    /// [`Scope::self_recv`]): the method's own class when it is a method
3249    /// directly in a class body, not a `staticmethod`, and the name is its
3250    /// first parameter; nothing when it binds the name some other way (a
3251    /// nested `def inner(self)`, a later parameter); else what the enclosing
3252    /// scope's name holds.
3253    fn bind_receivers(&mut self, id: usize) {
3254        let Some(parent) = self.scopes[id].parent else {
3255            return;
3256        };
3257        // A lambda in a class body is a method only when the body assigns it
3258        // to a name (`go = lambda self: ...`), not when it is passed
3259        // (`map(lambda self: ..., items)`).
3260        let method = self.scopes[parent].kind == ScopeKind::Class
3261            && !self.scopes[id].staticmethod
3262            && (!self.scopes[id].lambda || self.scopes[id].bound_name.is_some());
3263        let first = self.scopes[id].slots.first().map(|s| s.name.clone());
3264        for name in ["self", "cls"] {
3265            let bound = self.params.contains_key(&(id, name.to_string()));
3266            let recv = if !bound {
3267                match name {
3268                    "self" => self.scopes[parent].self_recv,
3269                    _ => self.scopes[parent].cls_recv,
3270                }
3271            } else if method && first.as_deref() == Some(name) {
3272                Some((parent, id))
3273            } else {
3274                None
3275            };
3276            match name {
3277                "self" => self.scopes[id].self_recv = recv,
3278                _ => self.scopes[id].cls_recv = recv,
3279            }
3280        }
3281    }
3282
3283    /// The class and method `self` / `cls` (`name`) refers to in `scope`.
3284    fn receiver(&self, name: &str, scope: usize) -> Option<(usize, usize)> {
3285        match name {
3286            "self" => self.scopes[scope].self_recv,
3287            "cls" => self.scopes[scope].cls_recv,
3288            _ => None,
3289        }
3290    }
3291
3292    /// `C.m` read as a value, recorded for [`Ctx::member_values`].
3293    fn note_member_value(&mut self, node: Node<'t>, frame: &Frame<'t>) {
3294        let (Some(object), Some(attr)) = (
3295            node.child_by_field_name("object"),
3296            node.child_by_field_name("attribute"),
3297        ) else {
3298            return;
3299        };
3300        if object.kind() != "identifier" || matches!(self.text(object), "self" | "cls") {
3301            return;
3302        }
3303        if let Some(parent) = frame.parent {
3304            let called = parent.kind() == "call" && frame.field == Some("function");
3305            if called || is_declaration(parent.kind(), frame.field) {
3306                return;
3307            }
3308        }
3309        self.member_values
3310            .insert((self.text(object), self.text(attr)));
3311    }
3312
3313    /// Whether method `method` of its class is read as a value through the
3314    /// class (`B.go`), so it may run with another class's instance as
3315    /// `self`.
3316    fn is_borrowed(&self, method: usize) -> bool {
3317        let Some(class) = self.scopes[method].parent else {
3318            return false;
3319        };
3320        self.member_values.contains(&(
3321            self.scopes[class].name.as_str(),
3322            self.scopes[method].name.as_str(),
3323        ))
3324    }
3325
3326    /// Lead decision D3: a method that binds its `self` or `cls` in any way
3327    /// other than as its first parameter, in its body or in a scope nested
3328    /// in it (an assignment, `+=`, a `for`, `with`, `except` or walrus
3329    /// target, a `match` capture, `del`, an import, a `def` or `class`, a
3330    /// closure's `nonlocal` or `global`), reads nothing through that name:
3331    /// every such read is a `dynamic_feature` gap. One pass over the
3332    /// scopes, after `nonlocal` assignments are placed.
3333    fn note_rebound_receivers(&mut self) {
3334        let mut found: Vec<(usize, bool)> = Vec::new();
3335        for s in 0..self.scopes.len() {
3336            for (name, is_self) in [("self", true), ("cls", false)] {
3337                let Some((_, method)) = self.receiver(name, s) else {
3338                    continue;
3339                };
3340                let key = (s, name.to_string());
3341                if self.assigns.contains_key(&key)
3342                    || self.imports.contains_key(&key)
3343                    || self.other_imports.contains_key(&key)
3344                    || self.functions.contains_key(&key)
3345                    || self.scopes[s].globals.contains(name)
3346                {
3347                    found.push((method, is_self));
3348                }
3349            }
3350        }
3351        for ((home, name), _, _) in &self.def_bindings {
3352            let is_self = name == "self";
3353            if is_self || name == "cls" {
3354                if let Some((_, method)) = self.receiver(name, *home) {
3355                    found.push((method, is_self));
3356                }
3357            }
3358        }
3359        for (method, is_self) in found {
3360            let line = self.scopes[method].line;
3361            self.rebound_receivers
3362                .entry((method, is_self))
3363                .or_insert(Feature {
3364                    what: "`self` or `cls` rebound in the method",
3365                    line,
3366                });
3367        }
3368    }
3369
3370    /// The feature that makes a read through `object` unknown when it is
3371    /// `self` / `cls` of a method that rebinds the name (D3).
3372    fn rebound_receiver(&self, object: Node<'t>, scope: usize) -> Option<Feature> {
3373        if object.kind() != "identifier" || self.rebound_receivers.is_empty() {
3374            return None;
3375        }
3376        let name = self.text(object);
3377        let is_self = match name {
3378            "self" => true,
3379            "cls" => false,
3380            _ => return None,
3381        };
3382        let (_, method) = self.receiver(name, scope)?;
3383        self.rebound_receivers.get(&(method, is_self)).copied()
3384    }
3385
3386    /// A write through `self` in a method another class may borrow sets
3387    /// that class's instances too, and one through a rebound `self` (D3)
3388    /// sets whatever the name holds then: an outside write of the
3389    /// attribute. So is a write with a run-time name through a rebound
3390    /// `self`.
3391    fn settle_borrowed_methods(&mut self) {
3392        if self.member_values.is_empty() && self.rebound_receivers.is_empty() {
3393            return;
3394        }
3395        for (method, attr, object) in std::mem::take(&mut self.method_self_writes) {
3396            let what = if self.is_borrowed(method) {
3397                "a write through `self` in a method another class may borrow"
3398            } else if self.rebound_receivers.contains_key(&(method, true))
3399                || self.rebound_receivers.contains_key(&(method, false))
3400            {
3401                "a write through `self` or `cls` in a method that rebinds it"
3402            } else {
3403                continue;
3404            };
3405            self.outside_attr_writes
3406                .entry(attr)
3407                .or_insert_with(|| Self::feature(what, object));
3408        }
3409        for (object, scope) in self.wild_attr_objects.clone() {
3410            if let Some(feature) = self.rebound_receiver(object, scope) {
3411                self.wild_attr_any.get_or_insert(feature);
3412            }
3413        }
3414    }
3415
3416    /// Whether other modules can name `class` to subclass it: not
3417    /// `_private` (nor inside a private class) unless `__all__` exports
3418    /// it, not defined in a function, and not in a script.
3419    fn is_public_class(&self, class: usize) -> bool {
3420        if self.script {
3421            return false;
3422        }
3423        let mut current = Some(class);
3424        while let Some(s) = current {
3425            let scope = &self.scopes[s];
3426            match scope.kind {
3427                ScopeKind::Module => return true,
3428                ScopeKind::Function => return false,
3429                // `__all__` may export a private module-level class.
3430                ScopeKind::Class if scope.name.starts_with('_') => {
3431                    return scope.parent == Some(0)
3432                        && (self.exports_dynamic || self.exported.contains(scope.name.as_str()));
3433                }
3434                ScopeKind::Class => current = scope.parent,
3435            }
3436        }
3437        true
3438    }
3439
3440    /// Whether another module may subclass `class` and set an attribute its
3441    /// methods read through `self`/`cls`: it is public, or one of its direct
3442    /// same-file subclasses is (deeper inheritance is a dynamic feature
3443    /// already, and so are more than [`MAX_SUBCLASSES`] subclasses).
3444    fn may_be_subclassed_elsewhere(&self, class: usize) -> bool {
3445        self.is_public_class(class)
3446            || self.subclasses.get(&class).is_some_and(|subs| {
3447                subs.iter()
3448                    .take(MAX_SUBCLASSES)
3449                    .any(|&sub| self.is_public_class(sub))
3450            })
3451    }
3452
3453    fn record_params(&mut self, params: Node<'t>, scope: usize) {
3454        let mut kind = SlotKind::Positional;
3455        let mut slots: Vec<Slot> = Vec::new();
3456        for param in named_children(params) {
3457            let (name, annotation, default, slot) = match param.kind() {
3458                "identifier" => (Some(param), None, None, kind),
3459                "typed_parameter" => {
3460                    let inner = param.named_child(0);
3461                    let (name, slot) = match inner.map(|n| n.kind()) {
3462                        Some("list_splat_pattern") => {
3463                            kind = SlotKind::KeywordOnly;
3464                            (inner.and_then(|n| n.named_child(0)), SlotKind::VarArgs)
3465                        }
3466                        Some("dictionary_splat_pattern") => {
3467                            (inner.and_then(|n| n.named_child(0)), SlotKind::VarKwargs)
3468                        }
3469                        _ => (inner, kind),
3470                    };
3471                    (name, param.child_by_field_name("type"), None, slot)
3472                }
3473                "default_parameter" => (
3474                    param.child_by_field_name("name"),
3475                    None,
3476                    param.child_by_field_name("value"),
3477                    kind,
3478                ),
3479                "typed_default_parameter" => (
3480                    param.child_by_field_name("name"),
3481                    param.child_by_field_name("type"),
3482                    param.child_by_field_name("value"),
3483                    kind,
3484                ),
3485                "list_splat_pattern" => {
3486                    kind = SlotKind::KeywordOnly;
3487                    (param.named_child(0), None, None, SlotKind::VarArgs)
3488                }
3489                "dictionary_splat_pattern" => {
3490                    (param.named_child(0), None, None, SlotKind::VarKwargs)
3491                }
3492                "keyword_separator" => {
3493                    kind = SlotKind::KeywordOnly;
3494                    continue;
3495                }
3496                "positional_separator" => {
3497                    for slot in &mut slots {
3498                        if slot.kind == SlotKind::Positional {
3499                            slot.kind = SlotKind::PositionalOnly;
3500                        }
3501                    }
3502                    continue;
3503                }
3504                // A tuple parameter (Python 2) still takes a position.
3505                _ => (None, None, None, kind),
3506            };
3507            let name = name.filter(|n| n.kind() == "identifier");
3508            slots.push(Slot {
3509                name: name.map(|n| self.text(n).to_string()).unwrap_or_default(),
3510                kind: slot,
3511            });
3512            if let Some(name) = name {
3513                let key = (scope, self.text(name).to_string());
3514                self.params.insert(
3515                    key,
3516                    Param {
3517                        annotation,
3518                        default,
3519                    },
3520                );
3521            }
3522        }
3523        self.scopes[scope].slots = slots;
3524    }
3525
3526    fn enter_class(&mut self, node: Node<'t>, parent: usize, wrapper: Option<Node<'t>>) -> usize {
3527        let name = node
3528            .child_by_field_name("name")
3529            .map(|n| self.text(n).to_string())
3530            .unwrap_or_default();
3531        let mut bases = Vec::new();
3532        let mut external_bases = false;
3533        let mut other_bases = 0usize;
3534        let mut keywords = false;
3535        if let Some(list) = node.child_by_field_name("superclasses") {
3536            for base in named_children(list) {
3537                match base.kind() {
3538                    "identifier" | "attribute" => {
3539                        let text = self.text(base);
3540                        // Bases that add no attributes and no metaclass
3541                        // that rewrites them.
3542                        if matches!(text, "object" | "ABC" | "abc.ABC") {
3543                            continue;
3544                        }
3545                        external_bases |= !self.classes_by_name.contains_key(text);
3546                        bases.push(text.to_string());
3547                    }
3548                    "keyword_argument" | "dictionary_splat" => {
3549                        keywords = true;
3550                        external_bases = true;
3551                    }
3552                    "comment" => {}
3553                    _ => {
3554                        other_bases += 1;
3555                        external_bases = true;
3556                    }
3557                }
3558            }
3559        }
3560        let decorated = wrapper.is_some_and(|w| w.kind() == "decorated_definition");
3561        let line = node.start_position().row as u32 + 1;
3562        let what = if decorated {
3563            Some("a class decorator")
3564        } else if keywords {
3565            Some("a metaclass or class keyword")
3566        } else if bases.len() + other_bases > 1 {
3567            Some("multiple inheritance")
3568        } else {
3569            None
3570        };
3571        let id = self.scopes.len();
3572        let mut scope = Scope::new(
3573            ScopeKind::Class,
3574            Some(parent),
3575            node.start_byte(),
3576            node.end_byte(),
3577        );
3578        scope.class = Some(id);
3579        scope.symbol = Some(clip(&name));
3580        scope.name = name.clone();
3581        scope.bases = bases;
3582        scope.external_bases = external_bases;
3583        scope.decorated = decorated;
3584        scope.class_feature = what.map(|what| Feature { what, line });
3585        scope.line = line;
3586        scope.depth = self.scopes[parent].depth + 1;
3587        self.scopes.push(scope);
3588        let home = match self.scopes[parent].kind {
3589            ScopeKind::Class => parent,
3590            _ => self.import_home(parent, &name),
3591        };
3592        self.def_bindings.push((
3593            (home, name.clone()),
3594            parent,
3595            Place {
3596                at: node.end_byte(),
3597                region: None,
3598            },
3599        ));
3600        self.classes_by_name.entry(name).or_default().push(id);
3601        id
3602    }
3603
3604    fn record_with_item(&mut self, node: Node<'t>, scope: usize, place: Place) {
3605        let Some(value) = node.child_by_field_name("value") else {
3606            return;
3607        };
3608        if value.kind() != "as_pattern" {
3609            return;
3610        }
3611        let expr = value.named_child(0);
3612        let target = value
3613            .child_by_field_name("alias")
3614            .and_then(|alias| alias.named_child(0));
3615        if let Some(target) = target {
3616            self.record_target(target, expr, None, scope, false, place);
3617        }
3618    }
3619
3620    fn record_target(
3621        &mut self,
3622        target: Node<'t>,
3623        value: Option<Node<'t>>,
3624        annotation: Option<Node<'t>>,
3625        scope: usize,
3626        unknowable: bool,
3627        place: Place,
3628    ) {
3629        stacker::maybe_grow(64 * 1024, 2 * 1024 * 1024, || {
3630            self.record_target_inner(target, value, annotation, scope, unknowable, place)
3631        })
3632    }
3633
3634    fn record_target_inner(
3635        &mut self,
3636        target: Node<'t>,
3637        value: Option<Node<'t>>,
3638        annotation: Option<Node<'t>>,
3639        scope: usize,
3640        unknowable: bool,
3641        place: Place,
3642    ) {
3643        let assign = Assign {
3644            id: self.fresh_id(),
3645            scope,
3646            value,
3647            annotation,
3648            unknowable,
3649            place,
3650            iter: self.loop_iter,
3651        };
3652        match target.kind() {
3653            "identifier" => {
3654                let name = self.text(target).to_string();
3655                let current = &self.scopes[scope];
3656                let home = if current.kind != ScopeKind::Module && current.globals.contains(&name) {
3657                    0
3658                } else if current.kind != ScopeKind::Module && current.nonlocals.contains(&name) {
3659                    self.nonlocal_assigns.push((scope, name, assign));
3660                    return;
3661                } else {
3662                    scope
3663                };
3664                self.assigns.entry((home, name)).or_default().push(assign);
3665            }
3666            "attribute" => {
3667                let (Some(object), Some(attr)) = (
3668                    target.child_by_field_name("object"),
3669                    target.child_by_field_name("attribute"),
3670                ) else {
3671                    return;
3672                };
3673                let attr = self.text(attr);
3674                self.note_mutated_root(object);
3675                self.record_attr_write(object, attr, assign, scope);
3676            }
3677            "subscript" => {
3678                self.note_env_write(target);
3679                self.note_mutated_root(target);
3680                // `globals()["MODEL"] = v` rebinds a module-level name.
3681                if target
3682                    .child_by_field_name("value")
3683                    .is_some_and(|v| self.is_module_namespace(v, scope))
3684                {
3685                    match single_subscript(target).and_then(|k| self.plain_literal(k)) {
3686                        Some(name) => {
3687                            self.assigns
3688                                .entry((0, name.to_string()))
3689                                .or_default()
3690                                .push(assign);
3691                        }
3692                        None => self.dynamic_globals = true,
3693                    }
3694                    return;
3695                }
3696                // `obj.__dict__["model"] = v`, `vars(obj)[name] = v`.
3697                if let Some(owner) = target
3698                    .child_by_field_name("value")
3699                    .and_then(|v| self.attribute_dict_owner(v))
3700                {
3701                    match single_subscript(target).and_then(|k| self.plain_literal(k)) {
3702                        Some(attr) => self.record_attr_write(owner, attr, assign, scope),
3703                        None => self.note_wild_attr_write(owner, scope),
3704                    }
3705                }
3706            }
3707            "pattern_list"
3708            | "tuple_pattern"
3709            | "list_pattern"
3710            | "tuple"
3711            | "list"
3712            | "list_splat_pattern"
3713            | "parenthesized_expression" => {
3714                for child in named_children(target) {
3715                    self.record_target(child, None, None, scope, true, place);
3716                }
3717            }
3718            _ => {}
3719        }
3720    }
3721
3722    /// Records `object.attr = value` (or the same through `setattr` or
3723    /// `__dict__`): on `self`/`cls` or a class by name it is an assignment
3724    /// of that class's attribute; on anything else it is an outside write
3725    /// that may set any instance's attribute of that name.
3726    fn record_attr_write(
3727        &mut self,
3728        object: Node<'t>,
3729        attr: &'t str,
3730        assign: Assign<'t>,
3731        scope: usize,
3732    ) {
3733        // `super().__setattr__(...)` writes the instance.
3734        if is_super_call(object, |n| self.text(n)) {
3735            if let Some(class) = self.scopes[scope].class {
3736                self.attr_assigns
3737                    .entry((class, attr.to_string()))
3738                    .or_default()
3739                    .push(assign);
3740                return;
3741            }
3742        }
3743        // `sys.modules[__name__].MODEL = v` rebinds a module-level name.
3744        if self.is_module_object(object) {
3745            self.assigns
3746                .entry((0, attr.to_string()))
3747                .or_default()
3748                .push(assign);
3749            return;
3750        }
3751        if object.kind() == "identifier" {
3752            let object_name = self.text(object);
3753            // `self`/`cls` of a method: its class's attribute. Anywhere else
3754            // (a `staticmethod`, a nested `def inner(self)`) the name is not
3755            // the instance: an outside write, below.
3756            if let Some((class, method)) = self.receiver(object_name, scope) {
3757                self.attr_assigns
3758                    .entry((class, attr.to_string()))
3759                    .or_default()
3760                    .push(assign);
3761                self.method_self_writes.push((method, attr, object));
3762                return;
3763            }
3764            if let Some([class]) = self.classes_by_name.get(object_name).map(Vec::as_slice) {
3765                let class = *class;
3766                self.attr_assigns
3767                    .entry((class, attr.to_string()))
3768                    .or_default()
3769                    .push(assign);
3770                return;
3771            }
3772        }
3773        // Any instance's or class's attribute of that name may be this one:
3774        // reads of it are `dynamic_feature` gaps (the values are not
3775        // copied into every class's lookup).
3776        self.outside_attr_writes
3777            .entry(attr)
3778            .or_insert_with(|| Self::feature("a write of the attribute on another object", object));
3779        self.config_assigns.push(ConfigAssign {
3780            object,
3781            attr,
3782            value: assign.value,
3783            scope,
3784            top: self.config_top && scope == 0,
3785            plain: self.config_plain,
3786            at: object.start_byte(),
3787        });
3788    }
3789
3790    /// The names a `match` case pattern binds: captures (`case model:`,
3791    /// `case [a, *rest]`, `case {"k": v, **kw}`, `case P(x=m)`) and
3792    /// `as` targets (`case str() as model`). A class name, a value pattern
3793    /// (`Color.RED`) and a keyword name bind nothing. Each holds only where
3794    /// its case matched, so none dominates what follows.
3795    fn record_pattern_captures(&mut self, pattern: Node<'t>, scope: usize) {
3796        // Each pattern is walked once: linear in its size.
3797        let mut stack = vec![(pattern, "")];
3798        while let Some((node, parent)) = stack.pop() {
3799            let bound = match node.kind() {
3800                "dotted_name"
3801                    if matches!(parent, "case_pattern" | "keyword_pattern" | "union_pattern") =>
3802                {
3803                    match named_children(node).as_slice() {
3804                        [only] => Some(*only),
3805                        _ => None,
3806                    }
3807                }
3808                "splat_pattern" => node.named_child(0),
3809                "identifier" if parent == "as_pattern" => Some(node),
3810                _ => None,
3811            };
3812            if let Some(target) = bound.filter(|t| t.kind() == "identifier" && self.text(*t) != "_")
3813            {
3814                let place = Place {
3815                    at: target.end_byte(),
3816                    region: None,
3817                };
3818                self.record_target(target, None, None, scope, true, place);
3819                continue;
3820            }
3821            if matches!(node.kind(), "dotted_name" | "identifier") {
3822                continue;
3823            }
3824            let mut cursor = node.walk();
3825            for (index, child) in node.named_children(&mut cursor).enumerate() {
3826                // A class pattern's first child is the class; a dict
3827                // pattern's keys are values.
3828                let skip = (node.kind() == "class_pattern" && index == 0)
3829                    || (node.kind() == "dict_pattern"
3830                        && child.kind() != "case_pattern"
3831                        && child.kind() != "splat_pattern");
3832                if !skip {
3833                    stack.push((child, node.kind()));
3834                }
3835            }
3836        }
3837    }
3838
3839    /// `globals()["ask"]` hands out `ask`; `globals()[name]` may hand out
3840    /// any module-level function.
3841    fn note_namespace_lookup(&mut self, node: Node<'t>) {
3842        if !node
3843            .child_by_field_name("value")
3844            .is_some_and(|v| is_namespace_call(v, |n| self.text(n)))
3845        {
3846            return;
3847        }
3848        match single_subscript(node).and_then(|k| self.plain_literal(k)) {
3849            Some(name) => self.name_uses.entry(name).or_default().escapes = true,
3850            None => self.dynamic_function_calls = true,
3851        }
3852    }
3853
3854    /// `sys.modules[...]`: a module object, taken to be this one.
3855    fn is_module_object(&self, node: Node<'t>) -> bool {
3856        node.kind() == "subscript" && self.render_links(node, 4) == "sys.modules[...]"
3857    }
3858
3859    /// A write to an attribute named only at run time.
3860    fn note_wild_attr_write(&mut self, object: Node<'t>, scope: usize) {
3861        if self.is_module_object(object) {
3862            self.dynamic_globals = true;
3863            return;
3864        }
3865        let own = if object.kind() == "identifier" {
3866            self.receiver(self.text(object), scope)
3867                .map(|(class, _)| class)
3868        } else if is_super_call(object, |n| self.text(n)) {
3869            self.scopes[scope].class
3870        } else {
3871            None
3872        };
3873        let feature = Self::feature("an attribute written with a run-time name", object);
3874        match own {
3875            Some(class) => {
3876                self.wild_attr_writes.entry(class).or_insert(feature);
3877            }
3878            None => {
3879                self.wild_attr_any.get_or_insert(feature);
3880            }
3881        }
3882        self.wild_attr_objects.push((object, scope));
3883    }
3884
3885    /// `setattr(obj, "attr", value)`, `setattr(obj, name, value)`, the same
3886    /// through `__setattr__`, `obj.__dict__.update(...)`,
3887    /// `vars(obj).update(...)`, and `getattr(obj, name)`, which may hand
3888    /// out any method.
3889    fn note_attr_write_call(&mut self, call: Node<'t>, scope: usize, place: Place) {
3890        let Some(function) = call.child_by_field_name("function") else {
3891            return;
3892        };
3893        let last = match function.kind() {
3894            "identifier" => self.text(function),
3895            "attribute" => function
3896                .child_by_field_name("attribute")
3897                .map(|a| self.text(a))
3898                .unwrap_or_default(),
3899            _ => return,
3900        };
3901        // Most calls are none of these: decide before reading arguments.
3902        if !matches!(
3903            last,
3904            "getattr"
3905                | "setattr"
3906                | "delattr"
3907                | "__setattr__"
3908                | "__delattr__"
3909                | "update"
3910                | "setdefault"
3911                | "__setitem__"
3912                | "__init__"
3913        ) {
3914            return;
3915        }
3916        let (positional, _) = call_arguments(call, |n| self.text(n));
3917        if function.kind() == "identifier" && self.text(function) == "getattr" {
3918            // A method or function looked up by name may be called with
3919            // any arguments.
3920            match positional
3921                .get(1)
3922                .map(|name| (name, self.plain_literal(*name)))
3923            {
3924                Some((_, Some(name))) => {
3925                    self.attr_uses.entry(name).or_default().escapes = true;
3926                    self.name_uses.entry(name).or_default().escapes = true;
3927                    // `getattr(_A(), "_A__go")`.
3928                    self.note_mangled_use(name);
3929                    // `getattr(os, "environ")`, `getattr(builtins, "exec")`.
3930                    if matches!(name, "environ" | "environb" | "putenv") {
3931                        self.env_wild.get_or_insert(Self::feature(
3932                            "`os.environ` or `os.putenv` looked up by name",
3933                            call,
3934                        ));
3935                    } else if is_namespace_builtin(name) || name == "modules" {
3936                        self.note_file_dynamic(
3937                            "a builtin that reads or rebinds names (`exec`, `eval`, `globals`...) looked up by name",
3938                            call,
3939                        );
3940                    }
3941                }
3942                Some((_, None)) => {
3943                    self.dynamic_method_calls = true;
3944                    if positional
3945                        .first()
3946                        .is_some_and(|object| self.is_module_object(*object))
3947                    {
3948                        self.dynamic_function_calls = true;
3949                    }
3950                }
3951                None => {}
3952            }
3953            return;
3954        }
3955        // `setattr(obj, name, v)`, `object.__setattr__(obj, name, v)`,
3956        // `obj.__setattr__(name, v)`, and the same with `delattr`, which
3957        // writes no value (the read falls back to whatever else holds it).
3958        let dunder =
3959            function.kind() == "attribute" && matches!(last, "__setattr__" | "__delattr__");
3960        let builtin = function.kind() == "identifier" && matches!(last, "setattr" | "delattr");
3961        let deleting = matches!(last, "delattr" | "__delattr__");
3962        let explicit = if deleting { 2 } else { 3 };
3963        let value_at = |i: usize| (!deleting).then(|| positional.get(i)).flatten();
3964        let target = if builtin || (dunder && positional.len() >= explicit) {
3965            Some((positional.first().copied(), positional.get(1), value_at(2)))
3966        } else if dunder {
3967            Some((
3968                function.child_by_field_name("object"),
3969                positional.first(),
3970                value_at(1),
3971            ))
3972        } else {
3973            None
3974        };
3975        if let Some((object, name, value)) = target {
3976            let (Some(object), Some(&name)) = (object, name) else {
3977                return;
3978            };
3979            let value = value.copied();
3980            match self.plain_literal(name) {
3981                Some(attr) if is_environ_name(attr) && !deleting => {
3982                    // `setattr(os, "environ", {...})`, like `os.environ =
3983                    // {...}`, replaces the process environment.
3984                    self.env_wild.get_or_insert(Self::feature(
3985                        "`os.environ` replaced through `setattr`",
3986                        call,
3987                    ));
3988                }
3989                Some(attr) => {
3990                    let assign = Assign {
3991                        id: self.fresh_id(),
3992                        scope,
3993                        value,
3994                        annotation: None,
3995                        unknowable: value.is_none(),
3996                        place,
3997                        iter: None,
3998                    };
3999                    self.record_attr_write(object, attr, assign, scope);
4000                }
4001                None => self.note_wild_attr_write(object, scope),
4002            }
4003            return;
4004        }
4005        if function.kind() != "attribute" {
4006            return;
4007        }
4008        let method = function
4009            .child_by_field_name("attribute")
4010            .map(|a| self.text(a))
4011            .unwrap_or_default();
4012        if matches!(method, "update" | "setdefault" | "__setitem__" | "__init__") {
4013            let object = function.child_by_field_name("object");
4014            if object.is_some_and(|o| self.is_module_namespace(o, scope)) {
4015                self.dynamic_globals = true;
4016            } else if let Some(owner) = object.and_then(|o| self.attribute_dict_owner(o)) {
4017                self.note_wild_attr_write(owner, scope);
4018            }
4019        }
4020    }
4021
4022    /// `globals()`, or `vars()` / `locals()` at module level: the module
4023    /// namespace, which a write rebinds names in.
4024    fn is_module_namespace(&self, node: Node<'t>, scope: usize) -> bool {
4025        is_namespace_call(node, |n| self.text(n))
4026            && (scope == 0
4027                || node
4028                    .child_by_field_name("function")
4029                    .is_some_and(|f| self.text(f) == "globals"))
4030    }
4031
4032    /// `obj` for `obj.__dict__` or `vars(obj)`.
4033    fn attribute_dict_owner(&self, node: Node<'t>) -> Option<Node<'t>> {
4034        match node.kind() {
4035            "attribute"
4036                if node
4037                    .child_by_field_name("attribute")
4038                    .is_some_and(|a| self.text(a) == "__dict__") =>
4039            {
4040                node.child_by_field_name("object")
4041            }
4042            "call"
4043                if node
4044                    .child_by_field_name("function")
4045                    .is_some_and(|f| f.kind() == "identifier" && self.text(f) == "vars") =>
4046            {
4047                call_arguments(node, |n| self.text(n)).0.first().copied()
4048            }
4049            _ => None,
4050        }
4051    }
4052
4053    /// The text of a plain string literal (no prefix, interpolation or
4054    /// escape), borrowed from the source.
4055    fn plain_literal(&self, node: Node<'t>) -> Option<&'t str> {
4056        if node.kind() != "string" {
4057            return None;
4058        }
4059        let parts = children(node);
4060        let [start, content, _end] = parts.as_slice() else {
4061            return None;
4062        };
4063        let text = self.text(*content);
4064        (content.kind() == "string_content"
4065            && matches!(self.text(*start), "\"" | "'")
4066            && !text.contains('\\'))
4067        .then_some(text)
4068    }
4069
4070    /// The scope an import or definition of `name` in `scope` binds in:
4071    /// the function itself (unless the name is declared `global`), a class
4072    /// for a method, else the module. Class-body imports are treated as
4073    /// module-level.
4074    fn import_home(&self, scope: usize, name: &str) -> usize {
4075        let current = &self.scopes[scope];
4076        if current.kind != ScopeKind::Function || current.globals.contains(name) {
4077            return 0;
4078        }
4079        if current.nonlocals.contains(name) {
4080            // `nonlocal x` then `import x` / `def x()`: the enclosing
4081            // function's binding.
4082            let mut parent = current.parent;
4083            while let Some(p) = parent {
4084                match self.scopes[p].kind {
4085                    ScopeKind::Function => return p,
4086                    ScopeKind::Module => return 0,
4087                    ScopeKind::Class => parent = self.scopes[p].parent,
4088                }
4089            }
4090        }
4091        scope
4092    }
4093
4094    fn other_import(&mut self, scope: usize, local: String, module: &Rc<str>, place: Place) {
4095        self.class_body_import(scope, &local, place);
4096        let home = self.import_home(scope, &local);
4097        self.other_imports
4098            .entry((home, local))
4099            .or_default()
4100            .push(OtherImport {
4101                module: Rc::clone(module),
4102                place,
4103            });
4104    }
4105
4106    /// Counts one more imported name at `statement`: `false` once the file
4107    /// has bound [`MAX_FILE_IMPORTS`], and from then on.
4108    fn import_budget(&mut self, statement: Node<'t>) -> bool {
4109        if self.import_cut.is_some() {
4110            return false;
4111        }
4112        if self.import_bindings >= MAX_FILE_IMPORTS {
4113            self.import_cut = Some(statement);
4114            return false;
4115        }
4116        self.import_bindings += 1;
4117        true
4118    }
4119
4120    fn import_statement(&mut self, node: Node<'t>, scope: usize, place: Place) {
4121        let mut cursor = node.walk();
4122        let names: Vec<Node<'t>> = node.children_by_field_name("name", &mut cursor).collect();
4123        for item in names {
4124            if !self.import_budget(node) {
4125                return;
4126            }
4127            let (module_node, alias) = match item.kind() {
4128                "aliased_import" => (
4129                    item.child_by_field_name("name"),
4130                    item.child_by_field_name("alias"),
4131                ),
4132                _ => (Some(item), None),
4133            };
4134            let Some(module_node) = module_node else {
4135                continue;
4136            };
4137            let written = self.text(module_node);
4138            if written == "__main__" {
4139                // The running script's namespace, which may be this one.
4140                self.note_file_dynamic("`import __main__`", node);
4141            }
4142            if alias.is_some() && matches!(written, "builtins" | "sys") {
4143                // `import builtins as B; B.exec(...)`, `import sys as S;
4144                // S.modules[...]`: the names this file matches are spelled
4145                // differently.
4146                self.note_file_dynamic("`builtins` or `sys` imported under another name", node);
4147            }
4148            self.note_self_import(written, node);
4149            let module = clip(written);
4150            let Some((pkg, rest)) = Pkg::of_module(written) else {
4151                let local = match alias {
4152                    Some(alias) => self.text(alias).to_string(),
4153                    None => written.split('.').next().unwrap_or("").to_string(),
4154                };
4155                self.other_import(scope, local, &Rc::from(module), place);
4156                continue;
4157            };
4158            let (local, val) = match alias {
4159                Some(alias) => (
4160                    self.text(alias).to_string(),
4161                    Val::Module { pkg, path: rest },
4162                ),
4163                // `import google.genai` binds `google`; `import openai.types`
4164                // binds `openai`.
4165                None => match pkg {
4166                    Pkg::GoogleGenai | Pkg::GoogleGenerativeai => {
4167                        ("google".to_string(), Val::GoogleNs)
4168                    }
4169                    _ => (
4170                        written.split('.').next().unwrap_or("").to_string(),
4171                        Val::Module {
4172                            pkg,
4173                            path: Vec::new(),
4174                        },
4175                    ),
4176                },
4177            };
4178            let binding = Binding {
4179                local: &local,
4180                pkg,
4181                module: &module,
4182                name: None,
4183                kind: BindingKind::Module,
4184            };
4185            self.add_import(binding, val, scope, item, place);
4186        }
4187    }
4188
4189    fn import_from(&mut self, node: Node<'t>, scope: usize, place: Place) {
4190        if self.import_cut.is_some() {
4191            return;
4192        }
4193        let Some(module_node) = node.child_by_field_name("module_name") else {
4194            return;
4195        };
4196        // Read and clipped once: every name below shares it.
4197        let written = self.text(module_node);
4198        let module = clip(written);
4199        let shared: Rc<str> = Rc::from(module.as_str());
4200        let relative = module_node.kind() == "relative_import";
4201
4202        let mut cursor = node.walk();
4203        let names: Vec<Node<'t>> = node.children_by_field_name("name", &mut cursor).collect();
4204        let wildcard = named_children(node)
4205            .iter()
4206            .any(|c| c.kind() == "wildcard_import");
4207
4208        let target = if relative {
4209            None
4210        } else {
4211            Pkg::of_module(written)
4212        };
4213        if !relative {
4214            self.note_self_import(written, node);
4215        }
4216
4217        if wildcard {
4218            if target.is_none() {
4219                // `from settings import *` may rebind any module-level name
4220                // (`MODEL` among them) from here on.
4221                if self.import_budget(node) {
4222                    if self.module_stars.len() < MAX_STARS {
4223                        self.module_stars.push((place, Rc::clone(&shared)));
4224                    } else {
4225                        self.dynamic_globals = true;
4226                    }
4227                }
4228                return;
4229            }
4230            if let Some((pkg, _)) = target {
4231                for class in CLASSES.iter().filter(|c| c.pkg == pkg) {
4232                    if !self.import_budget(node) {
4233                        return;
4234                    }
4235                    let key = (self.import_home(scope, class.name), class.name.to_string());
4236                    self.imports.entry(key).or_default().push(ImportDef {
4237                        val: Val::Class(*class),
4238                        place,
4239                    });
4240                }
4241                let binding = Binding {
4242                    local: "*",
4243                    pkg,
4244                    module: &module,
4245                    name: Some("*".to_string()),
4246                    kind: BindingKind::Symbol,
4247                };
4248                self.record_import(binding, node);
4249            }
4250            return;
4251        }
4252
4253        for item in names {
4254            if !self.import_budget(node) {
4255                return;
4256            }
4257            let (name_node, alias) = match item.kind() {
4258                "aliased_import" => (
4259                    item.child_by_field_name("name"),
4260                    item.child_by_field_name("alias"),
4261                ),
4262                _ => (Some(item), None),
4263            };
4264            let Some(name_node) = name_node else {
4265                continue;
4266            };
4267            let name = self.text(name_node).to_string();
4268            let local = alias
4269                .map(|a| self.text(a).to_string())
4270                .unwrap_or_else(|| name.clone());
4271            if !relative {
4272                self.note_dynamic_import(written, &name, &local, node);
4273            }
4274
4275            // `from google import genai` / `from google import generativeai`.
4276            if !relative && written == "google" {
4277                let pkg = match name.as_str() {
4278                    "genai" => Pkg::GoogleGenai,
4279                    "generativeai" => Pkg::GoogleGenerativeai,
4280                    _ => {
4281                        self.other_import(scope, local, &shared, place);
4282                        continue;
4283                    }
4284                };
4285                let val = Val::Module {
4286                    pkg,
4287                    path: Vec::new(),
4288                };
4289                let binding = Binding {
4290                    local: &local,
4291                    pkg,
4292                    module: &module,
4293                    name: Some(name),
4294                    kind: BindingKind::Module,
4295                };
4296                self.add_import(binding, val, scope, item, place);
4297                continue;
4298            }
4299
4300            let Some((pkg, rest)) = target.clone() else {
4301                self.other_import(scope, local, &shared, place);
4302                continue;
4303            };
4304            let (val, kind) = match client_class(pkg, &name) {
4305                Some(class) => (Val::Class(class), BindingKind::ClientClass),
4306                None => {
4307                    let mut path = rest;
4308                    path.push(name.clone());
4309                    (Val::Symbol { pkg, path }, BindingKind::Symbol)
4310                }
4311            };
4312            let binding = Binding {
4313                local: &local,
4314                pkg,
4315                module: &module,
4316                name: Some(name),
4317                kind,
4318            };
4319            self.add_import(binding, val, scope, item, place);
4320        }
4321    }
4322
4323    /// Binds a tracked import in the scope it appears in and records it.
4324    fn add_import(
4325        &mut self,
4326        binding: Binding<'_>,
4327        val: Val,
4328        scope: usize,
4329        node: Node<'t>,
4330        place: Place,
4331    ) {
4332        self.class_body_import(scope, binding.local, place);
4333        let key = (
4334            self.import_home(scope, binding.local),
4335            binding.local.to_string(),
4336        );
4337        self.imports
4338            .entry(key)
4339            .or_default()
4340            .push(ImportDef { val, place });
4341        self.record_import(binding, node);
4342    }
4343
4344    fn record_import(&mut self, binding: Binding<'_>, node: Node<'t>) {
4345        self.sdk_imported.insert(binding.pkg.sdk());
4346        self.legacy_imported |= binding.pkg == Pkg::GoogleGenerativeai;
4347        let span = self.span(node);
4348        self.out.imports.push(SdkImport {
4349            sdk: binding.pkg.sdk(),
4350            package: binding.pkg.package().to_string(),
4351            module: binding.module.to_string(),
4352            name: binding.name.map(clip_owned),
4353            local: clip(binding.local),
4354            kind: binding.kind,
4355            file: self.file.clone(),
4356            span,
4357        });
4358    }
4359
4360    /// An import in a class body binds a class attribute too (`class Bot:
4361    /// model = "gpt-4o"; from cfg import model`): when the class also
4362    /// assigns that name, it is one more assignment, of no known value (see
4363    /// [`Ctx::bind_definitions`]). The import is still bound at module
4364    /// level, as before.
4365    fn class_body_import(&mut self, scope: usize, local: &str, place: Place) {
4366        if self.scopes[scope].kind == ScopeKind::Class {
4367            self.def_bindings
4368                .push(((scope, local.to_string()), scope, place));
4369        }
4370    }
4371
4372    /// `type M = ...` binds `M` to a type alias object: an assignment of no
4373    /// known value. tree-sitter also reads `type(self).model = v` as a type
4374    /// alias statement whose left side is an attribute (`(self).model`):
4375    /// that is a write of `model` on an object this file cannot identify.
4376    fn record_type_alias(&mut self, node: Node<'t>, scope: usize, place: Place) {
4377        let parts = named_children(node);
4378        let (Some(left), value) = (
4379            parts.first().and_then(|t| t.named_child(0)),
4380            parts.get(1).and_then(|t| t.named_child(0)),
4381        ) else {
4382            return;
4383        };
4384        match left.kind() {
4385            "identifier" => self.record_target(left, None, None, scope, true, place),
4386            "generic_type" => {
4387                if let Some(name) = left.named_child(0).filter(|n| n.kind() == "identifier") {
4388                    self.record_target(name, None, None, scope, true, place);
4389                }
4390            }
4391            "attribute" => {
4392                let (Some(object), Some(attr)) = (
4393                    left.child_by_field_name("object"),
4394                    left.child_by_field_name("attribute"),
4395                ) else {
4396                    return;
4397                };
4398                let attr = self.text(attr);
4399                let assign = Assign {
4400                    id: self.fresh_id(),
4401                    scope,
4402                    value,
4403                    annotation: None,
4404                    unknowable: value.is_none(),
4405                    place,
4406                    iter: None,
4407                };
4408                self.note_mutated_root(object);
4409                self.record_attr_write(object, attr, assign, scope);
4410            }
4411            _ => {}
4412        }
4413    }
4414
4415    /// A `def`, `class` or class-body import that rebinds an assigned name
4416    /// (`MODEL = "gpt-4o"` then `def MODEL(): ...`) is one more definition
4417    /// of it, of no known value. Elsewhere names never assigned are left
4418    /// alone, so functions, classes and imports still resolve as before.
4419    /// In a class body every one of them is a write of that class
4420    /// attribute (lead decision D4), whatever the class assigns: a read
4421    /// through the class, a subclass or a base that may see it then has an
4422    /// assignment of no known value, and a gap.
4423    fn bind_definitions(&mut self) {
4424        for (key, scope, place) in std::mem::take(&mut self.def_bindings) {
4425            let class_body = self.scopes[key.0].kind == ScopeKind::Class;
4426            if !class_body && !self.assigns.contains_key(&key) {
4427                continue;
4428            }
4429            // `scope` is where the statement runs: a `global` def in a
4430            // function binds the module's name whenever it is called.
4431            let assign = Assign {
4432                id: self.fresh_id(),
4433                scope,
4434                value: None,
4435                annotation: None,
4436                unknowable: true,
4437                place,
4438                iter: None,
4439            };
4440            self.assigns.entry(key).or_default().push(assign);
4441        }
4442    }
4443
4444    /// Moves each assignment to a `nonlocal` name into the nearest
4445    /// enclosing function that binds the name (Python's rule), or the
4446    /// nearest enclosing function when none does. Its value expression
4447    /// stays in the nested function, so it reaches every use there as a
4448    /// definition that may run at any time.
4449    fn place_nonlocal_assigns(&mut self) {
4450        for (declared, name, assign) in std::mem::take(&mut self.nonlocal_assigns) {
4451            let mut nearest = None;
4452            let mut home = None;
4453            let mut current = self.scopes[declared].parent;
4454            while let Some(s) = current {
4455                let scope = &self.scopes[s];
4456                match scope.kind {
4457                    ScopeKind::Module => break,
4458                    ScopeKind::Class => {}
4459                    ScopeKind::Function => {
4460                        nearest.get_or_insert(s);
4461                        if !scope.nonlocals.contains(&name) && self.binds(s, &name) {
4462                            home = Some(s);
4463                            break;
4464                        }
4465                    }
4466                }
4467                current = scope.parent;
4468            }
4469            let home = home.or(nearest).unwrap_or(declared);
4470            self.assigns.entry((home, name)).or_default().push(assign);
4471        }
4472    }
4473
4474    /// Orders every name's definitions by position, for reaching-definition
4475    /// queries.
4476    fn index_definitions(&mut self) {
4477        for class in 0..self.scopes.len() {
4478            if self.scopes[class].kind != ScopeKind::Class {
4479                continue;
4480            }
4481            for base in self.scopes[class].bases.iter().take(MAX_BASES) {
4482                match self.classes_by_name.get(base).map(Vec::as_slice) {
4483                    Some([parent]) if *parent != class => {
4484                        self.subclasses.entry(*parent).or_default().push(class);
4485                    }
4486                    // Any class of that name may be the base: none of them
4487                    // knows its subclasses (no walk over every pair).
4488                    Some(many) if many.len() > 1 => {
4489                        self.ambiguous_base_names.insert(base.clone());
4490                    }
4491                    _ => {}
4492                }
4493            }
4494        }
4495        let mut keys: HashSet<Key> = HashSet::new();
4496        let module_wide = !self.module_stars.is_empty() || self.dynamic_globals;
4497        keys.extend(self.imports.keys().cloned());
4498        keys.extend(self.other_imports.keys().cloned());
4499        keys.extend(self.params.keys().cloned());
4500        keys.extend(self.assigns.keys().cloned());
4501        for key in keys {
4502            let home = key.0;
4503            let mut local = Vec::new();
4504            let mut foreign = Vec::new();
4505            for (i, import) in self.imports.get(&key).into_iter().flatten().enumerate() {
4506                local.push(DefPos {
4507                    place: import.place,
4508                    def: DefRef::Import(i),
4509                });
4510            }
4511            for (i, import) in self
4512                .other_imports
4513                .get(&key)
4514                .into_iter()
4515                .flatten()
4516                .enumerate()
4517            {
4518                local.push(DefPos {
4519                    place: import.place,
4520                    def: DefRef::Other(i),
4521                });
4522            }
4523            if self.params.contains_key(&key) {
4524                let scope = &self.scopes[home];
4525                local.push(DefPos {
4526                    place: Place {
4527                        at: scope.start,
4528                        region: Some((scope.start, scope.end)),
4529                    },
4530                    def: DefRef::Param,
4531                });
4532            }
4533            for (i, assign) in self.assigns.get(&key).into_iter().flatten().enumerate() {
4534                if assign.scope == home {
4535                    local.push(DefPos {
4536                        place: assign.place,
4537                        def: DefRef::Assign(i),
4538                    });
4539                } else {
4540                    foreign.push(DefRef::Assign(i));
4541                }
4542            }
4543            if home == 0 && module_wide {
4544                // It may not bind this name: it never dominates.
4545                for (i, (place, _)) in self.module_stars.iter().enumerate() {
4546                    local.push(DefPos {
4547                        place: Place {
4548                            at: place.at,
4549                            region: None,
4550                        },
4551                        def: DefRef::Star(i),
4552                    });
4553                }
4554                if self.dynamic_globals {
4555                    foreign.push(DefRef::Dynamic);
4556                }
4557            }
4558            local.sort_by_key(|d| d.place.at);
4559            let total = local.len() + foreign.len();
4560            self.def_index.insert(
4561                key,
4562                DefIndex {
4563                    local,
4564                    foreign,
4565                    total,
4566                },
4567            );
4568        }
4569    }
4570
4571    /// The definitions of `key` that reach a use.
4572    ///
4573    /// A use [`UseAt::At`] a byte sees the nearest definition that dominates
4574    /// it, every definition between that one and the use (in a branch), and
4575    /// the definitions later in a loop that runs the use again without
4576    /// passing the dominating one first. A [`UseAt::Deferred`] use (from a
4577    /// function defined at that byte) sees what reaches the definition plus
4578    /// every later definition: it may be called after any of them.
4579    fn reaching(&self, key: &Key, at: UseAt) -> Reach {
4580        let Some(index) = self.def_index.get(key) else {
4581            return Reach::All;
4582        };
4583        if index.total <= 1 {
4584            return Reach::All;
4585        }
4586        let (pos, deferred) = match at {
4587            UseAt::At(pos) => (pos, false),
4588            UseAt::Deferred(pos) => (pos, true),
4589        };
4590        let local = &index.local;
4591        let before = local.partition_point(|d| d.place.at <= pos);
4592        let mut nearest = None;
4593        for (steps, i) in (0..before).rev().enumerate() {
4594            if steps >= MAX_REACH_SCAN {
4595                return Reach::All;
4596            }
4597            if local[i].place.dominates(pos) {
4598                nearest = Some(i);
4599                break;
4600            }
4601        }
4602        let first = match nearest {
4603            Some(i) => i,
4604            None if before > MAX_REACH_SCAN => return Reach::All,
4605            None => 0,
4606        };
4607        let mut chosen: Vec<DefRef> = local[first..before].iter().map(|d| d.def).collect();
4608        let later_until = if deferred {
4609            Some(usize::MAX)
4610        } else {
4611            let dominating_at = nearest.map(|i| local[i].place.at);
4612            match self.reentry_loop(key.0, pos, dominating_at) {
4613                Some(found) => found,
4614                None => return Reach::All,
4615            }
4616        };
4617        if let Some(until) = later_until {
4618            for d in &local[before..] {
4619                if d.place.at > until {
4620                    break;
4621                }
4622                if chosen.len() >= MAX_REACH_SCAN {
4623                    return Reach::All;
4624                }
4625                chosen.push(d.def);
4626            }
4627        }
4628        // Every foreign definition reaches every use: past the scan limit,
4629        // listing them per use would make many uses quadratic.
4630        if chosen.is_empty()
4631            || index.foreign.len() > MAX_REACH_SCAN
4632            || chosen.len() + index.foreign.len() >= index.total
4633        {
4634            return Reach::All;
4635        }
4636        chosen.extend(index.foreign.iter().copied());
4637        Reach::Subset(chosen)
4638    }
4639
4640    /// The end of the outermost loop of `scope` that runs byte `pos` again
4641    /// without passing a dominating definition at `dominating_at` first:
4642    /// definitions later in that loop reach `pos` on its next iteration.
4643    /// `Some(None)` when there is no such loop, `None` past the search
4644    /// limit.
4645    fn reentry_loop(
4646        &self,
4647        scope: usize,
4648        pos: usize,
4649        dominating_at: Option<usize>,
4650    ) -> Option<Option<usize>> {
4651        let Some(loops) = self.loops.get(&scope) else {
4652            return Some(None);
4653        };
4654        // The last loop starting before `pos`; every loop around `pos` is
4655        // it or one of its ancestors, since loops nest.
4656        let last = loops.partition_point(|l| l.start <= pos);
4657        let mut current = last.checked_sub(1);
4658        let mut found = None;
4659        let mut steps = 0;
4660        while let Some(i) = current {
4661            steps += 1;
4662            if steps > MAX_REACH_SCAN {
4663                return None;
4664            }
4665            let range = loops[i];
4666            if range.contains(pos) {
4667                // This loop re-runs the dominating definition before the
4668                // use, and so does every loop around it.
4669                if dominating_at.is_some_and(|at| range.start < at && at <= range.end) {
4670                    break;
4671                }
4672                found = Some(range.end);
4673            }
4674            current = range.parent;
4675        }
4676        Some(found)
4677    }
4678
4679    /// Where a use at byte `pos` of `scope` runs, seen from `home`, the
4680    /// scope that binds the name: at its position when only immediate
4681    /// scopes (class bodies, comprehensions) lie between them, else deferred
4682    /// from where the outermost nested scope is defined.
4683    fn use_at(&self, scope: usize, home: usize, pos: usize) -> UseAt {
4684        let mut s = scope;
4685        let mut outer = None;
4686        let mut deferred = false;
4687        while s != home {
4688            let current = &self.scopes[s];
4689            deferred |= !current.immediate;
4690            outer = Some(s);
4691            match current.parent {
4692                Some(parent) => s = parent,
4693                None => break,
4694            }
4695        }
4696        match outer {
4697            Some(outer) if deferred => UseAt::Deferred(self.scopes[outer].start),
4698            _ => UseAt::At(pos),
4699        }
4700    }
4701
4702    /// The binding scope of `name` used at byte `pos` of `scope`, and where
4703    /// that use runs in it.
4704    fn locate(&self, name: &str, scope: usize, pos: usize) -> (Key, UseAt) {
4705        let home = self.binding_scope(name, scope);
4706        let at = self.use_at(scope, home, pos);
4707        ((home, name.to_string()), at)
4708    }
4709
4710    /// Every definition of `key`, in a fixed order.
4711    fn all_defs(&self, key: &Key) -> Vec<DefRef> {
4712        let mut defs = Vec::new();
4713        defs.extend((0..self.imports.get(key).map_or(0, Vec::len)).map(DefRef::Import));
4714        defs.extend((0..self.other_imports.get(key).map_or(0, Vec::len)).map(DefRef::Other));
4715        if self.params.contains_key(key) {
4716            defs.push(DefRef::Param);
4717        }
4718        defs.extend((0..self.assigns.get(key).map_or(0, Vec::len)).map(DefRef::Assign));
4719        if key.0 == 0 {
4720            defs.extend((0..self.module_stars.len()).map(DefRef::Star));
4721            if self.dynamic_globals {
4722                defs.push(DefRef::Dynamic);
4723            }
4724        }
4725        defs
4726    }
4727
4728    /// The kinds of definition of `name` a use at `pos` in `scope` sees,
4729    /// and the key they belong to. Constant time when every definition
4730    /// reaches the use, however many there are.
4731    fn defs_at(&self, name: &str, scope: usize, pos: usize) -> (Key, DefKinds) {
4732        let (key, at) = self.locate(name, scope, pos);
4733        let kinds = match self.reaching(&key, at) {
4734            Reach::All => {
4735                let assigns = self.assigns.get(&key).map_or(0, Vec::len);
4736                DefKinds {
4737                    param: self.params.contains_key(&key),
4738                    imported: self.imports.contains_key(&key)
4739                        || self.other_imports.contains_key(&key)
4740                        || (key.0 == 0 && (!self.module_stars.is_empty() || self.dynamic_globals)),
4741                    assigns,
4742                    only_assign: (assigns == 1).then_some(0),
4743                }
4744            }
4745            Reach::Subset(defs) => {
4746                let mut kinds = DefKinds::default();
4747                for def in defs {
4748                    match def {
4749                        DefRef::Import(_)
4750                        | DefRef::Other(_)
4751                        | DefRef::Star(_)
4752                        | DefRef::Dynamic => kinds.imported = true,
4753                        DefRef::Param => kinds.param = true,
4754                        DefRef::Assign(i) => {
4755                            kinds.assigns += 1;
4756                            kinds.only_assign = (kinds.assigns == 1).then_some(i);
4757                        }
4758                    }
4759                }
4760                kinds
4761            }
4762        };
4763        (key, kinds)
4764    }
4765
4766    // ------------------------------------------------------------------
4767    // Evaluation
4768    // ------------------------------------------------------------------
4769
4770    fn eval(&mut self, node: Node<'t>, scope: usize, depth: u32) -> Val {
4771        if depth > MAX_DEPTH {
4772            return Val::untracked(Origin::Other);
4773        }
4774        stacker::maybe_grow(64 * 1024, 2 * 1024 * 1024, || {
4775            self.eval_inner(node, scope, depth)
4776        })
4777    }
4778
4779    fn eval_inner(&mut self, node: Node<'t>, scope: usize, depth: u32) -> Val {
4780        match node.kind() {
4781            "identifier" => {
4782                let name = self.text(node).to_string();
4783                self.resolve_name(&name, scope, node.start_byte())
4784            }
4785            "attribute" => {
4786                let (Some(object), Some(attr)) = (
4787                    node.child_by_field_name("object"),
4788                    node.child_by_field_name("attribute"),
4789                ) else {
4790                    return Val::untracked(Origin::Other);
4791                };
4792                let attr = self.text(attr).to_string();
4793                if let Some(feature) = self.rebound_receiver(object, scope) {
4794                    return Val::untracked(Origin::Dynamic(feature));
4795                }
4796                if let Some((class, dynamic)) = self.class_receiver(object, scope) {
4797                    return self.resolve_attr(class, &attr, dynamic);
4798                }
4799                let base = self.eval(object, scope, depth + 1);
4800                self.member(base, &attr)
4801            }
4802            "call" => {
4803                // Each call is evaluated once per scope: a chain of calls
4804                // (`x.a().b().c()...`) is then linear, not quadratic.
4805                let key = (node.id(), scope);
4806                let budget = self.budget();
4807                if let Some(val) = self.reuse(recall(&self.call_memo, &key, budget)) {
4808                    return val;
4809                }
4810                let Some(function) = node.child_by_field_name("function") else {
4811                    return Val::untracked(Origin::Other);
4812                };
4813                let cutoffs = self.cutoffs;
4814                let callee = self.eval(function, scope, depth + 1);
4815                let val = self.apply_call(callee, node, scope, depth + 1);
4816                let memo = self.memo(val.clone(), cutoffs, budget);
4817                self.call_memo.insert(key, memo);
4818                val
4819            }
4820            "parenthesized_expression" | "await" => match node.named_child(0) {
4821                Some(inner) => self.eval(inner, scope, depth + 1),
4822                None => Val::untracked(Origin::Other),
4823            },
4824            "assignment" => match node.child_by_field_name("right") {
4825                Some(right) => self.eval(right, scope, depth + 1),
4826                None => Val::untracked(Origin::Other),
4827            },
4828            "boolean_operator" => {
4829                let mut vals = Vec::new();
4830                for field in ["left", "right"] {
4831                    if let Some(side) = node.child_by_field_name(field) {
4832                        vals.push(self.eval(side, scope, depth + 1));
4833                    }
4834                }
4835                combine(vals)
4836            }
4837            "conditional_expression" => {
4838                // `a if cond else b`: the first and last named children.
4839                let children = named_children(node);
4840                let mut vals = Vec::new();
4841                for side in [children.first(), children.last()].into_iter().flatten() {
4842                    vals.push(self.eval(*side, scope, depth + 1));
4843                }
4844                combine(vals)
4845            }
4846            "none"
4847            | "true"
4848            | "false"
4849            | "integer"
4850            | "float"
4851            | "string"
4852            | "concatenated_string"
4853            | "list"
4854            | "dictionary"
4855            | "tuple"
4856            | "set" => Val::untracked(Origin::Placeholder),
4857            _ => Val::untracked(Origin::Other),
4858        }
4859    }
4860
4861    /// The class `self.x` / `cls.x` / `ClassName.x` refers to, when the
4862    /// object is one of those, and whether it is `self`/`cls`: an instance
4863    /// that may be a subclass's, or have its attributes written from
4864    /// outside.
4865    fn class_receiver(&self, object: Node<'t>, scope: usize) -> Option<(usize, bool)> {
4866        if object.kind() != "identifier" {
4867            return None;
4868        }
4869        let name = self.text(object);
4870        if matches!(name, "self" | "cls") {
4871            // Only a method's own first parameter is its instance (or
4872            // class), and not when another class may borrow the method.
4873            let (class, method) = self.receiver(name, scope)?;
4874            if self.rebound_receiver(object, scope).is_some() {
4875                return None;
4876            }
4877            return (!self.is_borrowed(method)).then_some((class, true));
4878        }
4879        // The one class of that name, which nothing else rebinds (`Bot =
4880        // wrap(Bot)`, an import, a function of the same name).
4881        match self.classes_by_name.get(name).map(Vec::as_slice) {
4882            Some([class])
4883                if !self.is_bound_locally(name, scope)
4884                    && !self.binds(self.class_home(*class), name) =>
4885            {
4886                Some((*class, false))
4887            }
4888            _ => None,
4889        }
4890    }
4891
4892    /// The scope a class definition binds its name in: the enclosing
4893    /// function, else the module.
4894    fn class_home(&self, class: usize) -> usize {
4895        let mut parent = self.scopes[class].parent;
4896        while let Some(p) = parent {
4897            match self.scopes[p].kind {
4898                ScopeKind::Function => return p,
4899                ScopeKind::Module => return 0,
4900                ScopeKind::Class => parent = self.scopes[p].parent,
4901            }
4902        }
4903        0
4904    }
4905
4906    /// Whether `name` is assigned or a parameter in a function scope between
4907    /// `scope` and the module (which would shadow a class of that name).
4908    fn is_bound_locally(&self, name: &str, scope: usize) -> bool {
4909        let mut current = Some(scope);
4910        while let Some(s) = current {
4911            if self.scopes[s].kind == ScopeKind::Function && self.binds(s, name) {
4912                return true;
4913            }
4914            current = self.scopes[s].parent;
4915        }
4916        false
4917    }
4918
4919    /// Whether scope `s` itself binds `name` (assignment, parameter, import
4920    /// or `def`).
4921    fn binds(&self, s: usize, name: &str) -> bool {
4922        let key = (s, name.to_string());
4923        self.assigns.contains_key(&key)
4924            || self.params.contains_key(&key)
4925            || self.imports.contains_key(&key)
4926            || self.other_imports.contains_key(&key)
4927            || self.functions.contains_key(&key)
4928    }
4929
4930    /// The scope whose binding of `name` is visible from `scope`.
4931    fn binding_scope(&self, name: &str, scope: usize) -> usize {
4932        let mut s = scope;
4933        loop {
4934            let current = &self.scopes[s];
4935            match current.kind {
4936                ScopeKind::Function => {
4937                    if current.globals.contains(name) {
4938                        return 0;
4939                    }
4940                    if self.binds(s, name) {
4941                        return s;
4942                    }
4943                }
4944                ScopeKind::Class => {
4945                    // Only code directly in the class body sees its names.
4946                    if s == scope && self.assigns.contains_key(&(s, name.to_string())) {
4947                        return s;
4948                    }
4949                }
4950                ScopeKind::Module => return 0,
4951            }
4952            // Methods do not see class-body names: skip enclosing classes.
4953            let mut parent = current.parent.unwrap_or(0);
4954            while self.scopes[parent].kind == ScopeKind::Class {
4955                parent = self.scopes[parent].parent.unwrap_or(0);
4956            }
4957            s = parent;
4958        }
4959    }
4960
4961    /// Enters a nested name resolution; `false` past [`MAX_NAME_DEPTH`].
4962    fn enter_name(&mut self) -> bool {
4963        if self.name_depth >= MAX_NAME_DEPTH {
4964            self.cutoffs += 1;
4965            return false;
4966        }
4967        self.name_depth += 1;
4968        true
4969    }
4970
4971    fn leave_name(&mut self) {
4972        self.name_depth -= 1;
4973    }
4974
4975    /// Name resolutions that may still nest below this point.
4976    fn budget(&self) -> u32 {
4977        MAX_NAME_DEPTH.saturating_sub(self.name_depth)
4978    }
4979
4980    /// A value [`recall`] found; reusing a cut-off value makes the current
4981    /// evaluation cut off too.
4982    fn reuse<V>(&mut self, found: Option<(V, bool)>) -> Option<V> {
4983        let (val, cut) = found?;
4984        if cut {
4985            self.cutoffs += 1;
4986        }
4987        Some(val)
4988    }
4989
4990    /// `val` as computed with `budget`, final unless a resolution was cut
4991    /// off since `cutoffs` was read.
4992    fn memo<V>(&self, val: V, cutoffs: u64, budget: u32) -> Memo<V> {
4993        Memo {
4994            val,
4995            budget: (self.cutoffs != cutoffs).then_some(budget),
4996        }
4997    }
4998
4999    /// The value of `name` used at byte `pos` of `scope`.
5000    fn resolve_name(&mut self, name: &str, scope: usize, pos: usize) -> Val {
5001        if !self.enter_name() {
5002            return Val::untracked(Origin::Other);
5003        }
5004        let (key, at) = self.locate(name, scope, pos);
5005        let val = match self.reaching(&key, at) {
5006            Reach::All => self.resolve_all(key),
5007            Reach::Subset(defs) => {
5008                let vals = self.def_values(&key, &defs);
5009                if vals.is_empty() {
5010                    self.no_value(&key, &defs)
5011                } else {
5012                    combine(vals)
5013                }
5014            }
5015        };
5016        self.leave_name();
5017        val
5018    }
5019
5020    /// Every definition of `key` combined, memoized.
5021    fn resolve_all(&mut self, key: Key) -> Val {
5022        let budget = self.budget();
5023        if let Some(val) = self.reuse(recall(&self.name_memo, &key, budget)) {
5024            return val;
5025        }
5026        let guard = (0u8, key.0, key.1.clone());
5027        if !self.visiting.insert(guard.clone()) {
5028            return Val::untracked(Origin::Cycle);
5029        }
5030        let cutoffs = self.cutoffs;
5031        let defs = self.all_defs(&key);
5032        let vals = self.def_values(&key, &defs);
5033        let val = if vals.is_empty() {
5034            self.no_value(&key, &defs)
5035        } else {
5036            combine(vals)
5037        };
5038        self.visiting.remove(&guard);
5039        let memo = self.memo(val.clone(), cutoffs, budget);
5040        self.name_memo.insert(key, memo);
5041        val
5042    }
5043
5044    /// Values of the imports, parameter and assignments among `defs`. A
5045    /// name imported from another module is an untracked value next to
5046    /// the others (`except ImportError: from mylib import Client`).
5047    fn def_values(&mut self, key: &Key, defs: &[DefRef]) -> Vec<Val> {
5048        let mut vals = Vec::new();
5049        for def in defs {
5050            match *def {
5051                DefRef::Import(i) => {
5052                    if let Some(import) = self.imports.get(key).and_then(|v| v.get(i)) {
5053                        vals.push(import.val.clone());
5054                    }
5055                }
5056                DefRef::Other(i) => {
5057                    if let Some(import) = self.other_imports.get(key).and_then(|v| v.get(i)) {
5058                        vals.push(Val::untracked(Origin::Imported {
5059                            module: import.module.to_string(),
5060                        }));
5061                    }
5062                }
5063                DefRef::Star(i) => {
5064                    if let Some((_, module)) = self.module_stars.get(i) {
5065                        vals.push(Val::untracked(Origin::Imported {
5066                            module: module.to_string(),
5067                        }));
5068                    }
5069                }
5070                DefRef::Dynamic => vals.push(Val::untracked(Origin::Other)),
5071                DefRef::Param => {
5072                    if self.params.contains_key(key) {
5073                        vals.push(self.param_value_memo(key));
5074                    }
5075                }
5076                DefRef::Assign(i) => {
5077                    if let Some(assign) = self.assigns.get(key).and_then(|v| v.get(i)).copied() {
5078                        vals.push(self.assign_value_memo(assign));
5079                    }
5080                }
5081            }
5082        }
5083        vals
5084    }
5085
5086    fn no_value(&self, key: &Key, defs: &[DefRef]) -> Val {
5087        let module = defs.iter().find_map(|def| match def {
5088            DefRef::Other(i) => self
5089                .other_imports
5090                .get(key)
5091                .and_then(|v| v.get(*i))
5092                .map(|o| o.module.to_string()),
5093            DefRef::Star(i) => self.module_stars.get(*i).map(|(_, m)| m.to_string()),
5094            _ => None,
5095        });
5096        match module {
5097            Some(module) => Val::untracked(Origin::Imported { module }),
5098            None => Val::untracked(Origin::Unbound),
5099        }
5100    }
5101
5102    fn assign_value_memo(&mut self, assign: Assign<'t>) -> Val {
5103        let budget = self.budget();
5104        if let Some(val) = self.reuse(recall(&self.def_memo, &assign.id, budget)) {
5105            return val;
5106        }
5107        let guard = (2u8, assign.id, String::new());
5108        if !self.visiting.insert(guard.clone()) {
5109            return Val::untracked(Origin::Cycle);
5110        }
5111        let cutoffs = self.cutoffs;
5112        let val = self.assign_value(assign);
5113        self.visiting.remove(&guard);
5114        let memo = self.memo(val.clone(), cutoffs, budget);
5115        self.def_memo.insert(assign.id, memo);
5116        val
5117    }
5118
5119    /// The value of parameter `key.1` of function `key.0`, memoized.
5120    fn param_value_memo(&mut self, key: &Key) -> Val {
5121        let budget = self.budget();
5122        if let Some(val) = self.reuse(recall(&self.param_memo, key, budget)) {
5123            return val;
5124        }
5125        let Some(param) = self.params.get(key).copied() else {
5126            return Val::untracked(Origin::Unbound);
5127        };
5128        let guard = (4u8, key.0, key.1.clone());
5129        if !self.visiting.insert(guard.clone()) {
5130            return Val::untracked(Origin::Cycle);
5131        }
5132        let cutoffs = self.cutoffs;
5133        let val = self.param_value(&key.1, param, key.0);
5134        self.visiting.remove(&guard);
5135        let memo = self.memo(val.clone(), cutoffs, budget);
5136        self.param_memo.insert(key.clone(), memo);
5137        val
5138    }
5139
5140    fn param_value(&mut self, name: &str, param: Param<'t>, scope: usize) -> Val {
5141        if let Some(annotation) = param.annotation {
5142            if let Some(val) = self.typed(annotation, scope) {
5143                return val;
5144            }
5145        }
5146        // A client default holds only where a caller leaves the argument out.
5147        let mut default_client = None;
5148        if let Some(default) = param.default {
5149            let parent = self.scopes[scope].parent.unwrap_or(0);
5150            let val = self.eval(default, parent, 0);
5151            if matches!(val, Val::Client { .. }) {
5152                default_client = Some(val);
5153            }
5154        }
5155        if let Some(val) = self.param_from_callers(scope, name, default_client.clone()) {
5156            return val;
5157        }
5158        match default_client {
5159            // No in-file call passes the argument, or the calls cannot all
5160            // be seen: the default holds only where nobody else calls.
5161            Some(Val::Client { mut client, path }) => {
5162                // Calls past the read limit are not seen either.
5163                let unseen = self
5164                    .calls_of(scope)
5165                    .is_none_or(|calls| calls.len() > MAX_CALLERS_READ);
5166                if (unseen || !self.is_private(scope)) && client.caveat.is_none() {
5167                    client.caveat = Some(ClientCaveat::ParameterDefault {
5168                        param: name.to_string(),
5169                        unseen,
5170                    });
5171                }
5172                Val::Client { client, path }
5173            }
5174            Some(other) => other,
5175            None => Val::untracked(Origin::Parameter {
5176                name: name.to_string(),
5177            }),
5178        }
5179    }
5180
5181    /// What the in-file calls of `func` pass for parameter `name`, memoized.
5182    /// With a client default (`default_client`), every caller's argument is
5183    /// combined with it: a caller passing another client makes the binding
5184    /// ambiguous. Without one, the client every caller passes. `None` when
5185    /// the calls cannot all be seen or (without a default) they disagree.
5186    fn param_from_callers(
5187        &mut self,
5188        func: usize,
5189        name: &str,
5190        default_client: Option<Val>,
5191    ) -> Option<Val> {
5192        let key = (func, name.to_string());
5193        let budget = self.budget();
5194        if let Some(found) = self.reuse(recall(&self.caller_memo, &key, budget)) {
5195            return found;
5196        }
5197        let guard = (3u8, func, name.to_string());
5198        if !self.visiting.insert(guard.clone()) {
5199            return Some(Val::untracked(Origin::Cycle));
5200        }
5201        let cutoffs = self.cutoffs;
5202        if !self.enter_name() {
5203            self.visiting.remove(&guard);
5204            return None;
5205        }
5206        let found = self.callers_agree(func, name, default_client);
5207        self.leave_name();
5208        self.visiting.remove(&guard);
5209        let memo = self.memo(found.clone(), cutoffs, budget);
5210        self.caller_memo.insert(key, memo);
5211        found
5212    }
5213
5214    fn callers_agree(
5215        &mut self,
5216        func: usize,
5217        name: &str,
5218        default_client: Option<Val>,
5219    ) -> Option<Val> {
5220        let vals = self.caller_vals(func, name)?;
5221        if vals.is_empty() {
5222            return None;
5223        }
5224        let private = self.is_private(func);
5225        if let Some(default) = default_client {
5226            // Other modules may call a public function without the
5227            // argument, so its default stays possible, and with another
5228            // client, so the result keeps a gap.
5229            let mut all = vals;
5230            if !private {
5231                all.push(default);
5232            }
5233            return Some(match combine(all) {
5234                Val::Client { mut client, path } if !private => {
5235                    if !client.ambiguous && client.caveat.is_none() {
5236                        client.caveat = Some(ClientCaveat::ParameterDefault {
5237                            param: name.to_string(),
5238                            unseen: false,
5239                        });
5240                    }
5241                    Val::Client { client, path }
5242                }
5243                other => other,
5244            });
5245        }
5246        let first = vals.first()?.clone();
5247        let agree = vals.iter().all(|v| *v == first);
5248        match first {
5249            Val::Client { path, .. } if path.is_empty() => match combine(vals) {
5250                Val::Client { mut client, path } if path.is_empty() && !client.ambiguous => {
5251                    if !private && client.caveat.is_none() {
5252                        client.caveat = Some(ClientCaveat::InFileCallers {
5253                            param: name.to_string(),
5254                        });
5255                    }
5256                    Some(Val::Client { client, path })
5257                }
5258                _ => None,
5259            },
5260            Val::Module { .. } | Val::Symbol { .. } | Val::Class(_) | Val::GoogleNs if agree => {
5261                Some(first)
5262            }
5263            _ => None,
5264        }
5265    }
5266
5267    /// The value each in-file call of `func` passes for parameter `name`
5268    /// (the default where a call leaves it out; unknown through `*args` or
5269    /// `**kwargs`), self-references dropped. `None` when the calls cannot
5270    /// all be seen or a call leaves out a parameter that has no default.
5271    fn caller_vals(&mut self, func: usize, name: &str) -> Option<Vec<Val>> {
5272        let slot = self.param_slot(func, name)?;
5273        let calls = self.calls_of(func)?;
5274        if calls.len() > MAX_CALLERS_READ {
5275            return None;
5276        }
5277        let default = self
5278            .params
5279            .get(&(func, name.to_string()))
5280            .and_then(|p| p.default);
5281        let keyword = slot.keyword.then_some(name);
5282        let mut vals = Vec::new();
5283        for &(call, call_scope) in calls.iter() {
5284            let val = match argument_for(call, slot.position, keyword, |n| self.text(n)) {
5285                ArgFor::Found(expr) => self.eval(expr, call_scope, 0),
5286                ArgFor::Missing => self.eval(default?, slot.parent, 0),
5287                ArgFor::Unknown => Val::untracked(Origin::Other),
5288            };
5289            if !matches!(val, Val::Untracked(Origin::Cycle)) {
5290                vals.push(val);
5291            }
5292        }
5293        Some(vals)
5294    }
5295
5296    /// How a call passes parameter `name` of `func`: its position among
5297    /// the explicit arguments (not for keyword-only parameters), whether it
5298    /// may be passed by keyword, and the scope its default is evaluated in.
5299    /// `None` for `self`/`cls`, `*args` and `**kwargs`.
5300    fn param_slot(&self, func: usize, name: &str) -> Option<ParamSlot> {
5301        let scope = &self.scopes[func];
5302        let parent = scope.parent?;
5303        let method = self.scopes[parent].kind == ScopeKind::Class && !scope.lambda;
5304        let shift = usize::from(method && !scope.staticmethod);
5305        let index = scope.slots.iter().position(|s| s.name == name)?;
5306        let slot = scope.slots[index].kind;
5307        if index < shift || matches!(slot, SlotKind::VarArgs | SlotKind::VarKwargs) {
5308            return None;
5309        }
5310        Some(ParamSlot {
5311            position: matches!(slot, SlotKind::Positional | SlotKind::PositionalOnly)
5312                .then(|| index - shift),
5313            keyword: slot != SlotKind::PositionalOnly,
5314            parent,
5315        })
5316    }
5317
5318    /// Whether every call of `func` can be in this file: a function nested
5319    /// in another function or lambda, a `_private` (not dunder) function or
5320    /// method, or anything in a script (an extensionless file or
5321    /// `__main__.py`), which other modules do not import.
5322    fn is_private(&self, func: usize) -> bool {
5323        if self.script {
5324            return true;
5325        }
5326        let scope = &self.scopes[func];
5327        let Some(parent) = scope.parent else {
5328            return false;
5329        };
5330        if self.scopes[parent].kind == ScopeKind::Function {
5331            return true;
5332        }
5333        // A constructor is called wherever its class is: as private as the
5334        // class.
5335        if self.scopes[parent].kind == ScopeKind::Class && scope.name == "__init__" && !scope.lambda
5336        {
5337            return self.is_private(parent);
5338        }
5339        let name = match &scope.bound_name {
5340            Some(name) if scope.lambda => name.as_str(),
5341            _ => scope.name.as_str(),
5342        };
5343        name.starts_with('_') && !(name.starts_with("__") && name.ends_with("__"))
5344    }
5345
5346    /// Every in-file call of function or method `func`, or `None` when some
5347    /// may not be seen (see [`Self::visible_calls`]).
5348    fn calls_of(&mut self, func: usize) -> Option<CallSites<'t>> {
5349        match self.visible_calls(func) {
5350            Some((calls, true)) => Some(calls),
5351            _ => None,
5352        }
5353    }
5354
5355    /// The in-file calls of function or method `func` that can be seen, and
5356    /// whether they are all of its calls. They are not when it is
5357    /// decorated, its name is used as a value (passed, stored, partially
5358    /// applied, `ask.delay(...)`) or bound more than once; `None` for a
5359    /// comprehension or a lambda not assigned to a plain name, which is
5360    /// never called by name. A method's calls are every call of its name on
5361    /// any object (a superset: an unrelated method of the same name only
5362    /// adds candidates), and `__init__`'s are the calls of its class. Calls
5363    /// are indexed once per name (by binding scope for functions), so a file
5364    /// with thousands of same-named functions stays linear.
5365    fn visible_calls(&mut self, func: usize) -> Option<(CallSites<'t>, bool)> {
5366        let scope = &self.scopes[func];
5367        if scope.comprehension {
5368            return None;
5369        }
5370        let lambda = scope.lambda;
5371        let decorated = scope.decorated;
5372        let fname = if lambda {
5373            scope.bound_name.clone()?
5374        } else {
5375            scope.name.clone()
5376        };
5377        let parent = scope.parent?;
5378        let empty = || Rc::from(Vec::new());
5379        if self.scopes[parent].kind == ScopeKind::Class {
5380            if lambda {
5381                return None;
5382            }
5383            if fname == "__init__" {
5384                let (calls, all) = self.constructor_calls(parent);
5385                return Some((calls, all && !decorated));
5386            }
5387            let escapes = self.dynamic_method_calls
5388                || self
5389                    .attr_uses
5390                    .get(fname.as_str())
5391                    .is_some_and(|uses| uses.escapes);
5392            let calls = self.method_calls(&fname);
5393            return Some((calls, !escapes && !decorated));
5394        }
5395        let home = self.import_home(parent, &fname);
5396        let key = (home, fname.clone());
5397        let defined_once = if lambda {
5398            self.assigns.get(&key).map_or(0, Vec::len) == 1 && !self.functions.contains_key(&key)
5399        } else {
5400            self.functions.get(&key).map_or(0, Vec::len) == 1 && !self.assigns.contains_key(&key)
5401        };
5402        let only_def = defined_once
5403            && !self.imports.contains_key(&key)
5404            && !self.other_imports.contains_key(&key)
5405            && !self.params.contains_key(&key);
5406        let escapes = ((self.dynamic_function_calls || self.exports_dynamic) && home == 0)
5407            || self
5408                .name_uses
5409                .get(fname.as_str())
5410                .is_some_and(|uses| uses.escapes);
5411        let index = self.name_calls(&fname);
5412        let calls = index.get(&home).map_or_else(empty, Rc::clone);
5413        Some((calls, only_def && !escapes && !decorated))
5414    }
5415
5416    /// The calls that run `__init__` of `class`: calls of the class name
5417    /// where it binds to this class. They are all of them only when the
5418    /// class is the one class of that name, its name is bound nowhere else
5419    /// and is never used as a value (subclassed, passed, stored, its
5420    /// `__init__` called explicitly).
5421    fn constructor_calls(&mut self, class: usize) -> (CallSites<'t>, bool) {
5422        let name = self.scopes[class].name.clone();
5423        let Some(parent) = self.scopes[class].parent else {
5424            return (Rc::from(Vec::new()), false);
5425        };
5426        let home = self.import_home(parent, &name);
5427        let key = (home, name.clone());
5428        // A class decorator may wrap or replace the class, and an instance
5429        // built without naming its class (`type(self)(...)`, `cls(...)`,
5430        // `self.__class__(...)`) is a constructor call this index misses.
5431        let unique = self.classes_by_name.get(&name).map_or(0, Vec::len) == 1
5432            && !self.binds(home, &name)
5433            && !self.scopes[class].decorated
5434            && self.dynamic_constructors.is_none();
5435        let escapes = (self.exports_dynamic && home == 0)
5436            || self
5437                .name_uses
5438                .get(name.as_str())
5439                .is_some_and(|uses| uses.escapes);
5440        let index = self.name_calls(&key.1);
5441        let calls = index
5442            .get(&home)
5443            .map_or_else(|| Rc::from(Vec::new()), Rc::clone);
5444        (calls, unique && !escapes)
5445    }
5446
5447    /// The calls of bare name `name`, grouped by the scope that binds the
5448    /// name at each call. Built once per name.
5449    fn name_calls(&mut self, name: &str) -> CallIndex<'t> {
5450        if let Some(index) = self.name_call_index.get(name) {
5451            return Rc::clone(index);
5452        }
5453        let mut grouped: HashMap<usize, Vec<(Node<'t>, usize)>> = HashMap::new();
5454        if let Some(uses) = self.name_uses.get(name) {
5455            for &(call, call_scope) in &uses.calls {
5456                let home = self.binding_scope(name, call_scope);
5457                grouped.entry(home).or_default().push((call, call_scope));
5458            }
5459        }
5460        let index: CallIndex<'t> = Rc::new(
5461            grouped
5462                .into_iter()
5463                .map(|(home, calls)| (home, Rc::from(calls)))
5464                .collect(),
5465        );
5466        self.name_call_index
5467            .insert(name.to_string(), Rc::clone(&index));
5468        index
5469    }
5470
5471    /// Every call of method name `name`, on any object. Built once per name.
5472    fn method_calls(&mut self, name: &str) -> CallSites<'t> {
5473        if let Some(calls) = self.method_call_index.get(name) {
5474            return Rc::clone(calls);
5475        }
5476        let calls: CallSites<'t> = match self.attr_uses.get(name) {
5477            Some(uses) => Rc::from(uses.calls.as_slice()),
5478            None => Rc::from(Vec::new()),
5479        };
5480        self.method_call_index
5481            .insert(name.to_string(), Rc::clone(&calls));
5482        calls
5483    }
5484
5485    fn assign_value(&mut self, assign: Assign<'t>) -> Val {
5486        if assign.unknowable {
5487            return Val::untracked(Origin::Other);
5488        }
5489        let value = assign.value.map(|v| self.eval(v, assign.scope, 0));
5490        if let Some(val @ Val::Client { .. }) = &value {
5491            return val.clone();
5492        }
5493        if let Some(annotation) = assign.annotation {
5494            if let Some(val) = self.typed(annotation, assign.scope) {
5495                return val;
5496            }
5497        }
5498        value.unwrap_or(Val::untracked(Origin::Placeholder))
5499    }
5500
5501    /// A client typed by an annotation (`client: OpenAI`,
5502    /// `Optional[AzureOpenAI]`).
5503    fn typed(&mut self, annotation: Node<'t>, scope: usize) -> Option<Val> {
5504        // Each entry: a node and whether its parent is an attribute.
5505        let mut stack = vec![(annotation, false)];
5506        while let Some((node, in_attribute)) = stack.pop() {
5507            let top_chain = matches!(node.kind(), "identifier" | "attribute") && !in_attribute;
5508            if top_chain {
5509                if let Val::Class(class) = self.eval(node, scope, 0) {
5510                    return Some(Val::Client {
5511                        client: Client {
5512                            pkg: class.pkg,
5513                            routing: class.typed_routing(),
5514                            line: None,
5515                            site: None,
5516                            ambiguous: false,
5517                            typed: true,
5518                            caveat: None,
5519                        },
5520                        path: Vec::new(),
5521                    });
5522                }
5523                continue;
5524            }
5525            let is_attribute = node.kind() == "attribute";
5526            for child in named_children(node).into_iter().rev() {
5527                stack.push((child, is_attribute));
5528            }
5529        }
5530        None
5531    }
5532
5533    /// A class's own assignments of attribute `attr`: class-body names and
5534    /// `self.attr = ...`, `cls.attr = ...` or `Class.attr = ...`, read once
5535    /// per class and name.
5536    fn own_attrs(&mut self, class: usize, attr: &str) -> Rc<[Assign<'t>]> {
5537        let key = (class, attr.to_string());
5538        if let Some(found) = self.own_attr_memo.get(&key) {
5539            return Rc::clone(found);
5540        }
5541        let mut found: Vec<Assign<'t>> = Vec::new();
5542        found.extend(self.assigns.get(&key).into_iter().flatten().copied());
5543        found.extend(self.attr_assigns.get(&key).into_iter().flatten().copied());
5544        let found: Rc<[Assign<'t>]> = Rc::from(found);
5545        self.own_attr_memo.insert(key, Rc::clone(&found));
5546        found
5547    }
5548
5549    /// Where `class` sits in its hierarchy: its one same-file base (one
5550    /// level only), whether a base comes from outside the file, and why its
5551    /// attributes may change whatever its body says (see [`ClassShape`]).
5552    fn class_shape(&self, class: usize) -> ClassShape {
5553        let scope = &self.scopes[class];
5554        let mut shape = ClassShape {
5555            base: None,
5556            external: scope.external_bases,
5557            feature: scope.class_feature,
5558        };
5559        let [base] = scope.bases.as_slice() else {
5560            return shape;
5561        };
5562        let at = |what| {
5563            Some(Feature {
5564                what,
5565                line: scope.line,
5566            })
5567        };
5568        match self.classes_by_name.get(base).map(Vec::as_slice) {
5569            Some([parent]) if *parent != class && !self.binds(0, base) => {
5570                let parent_scope = &self.scopes[*parent];
5571                shape.base = Some(*parent);
5572                shape.external |= parent_scope.external_bases;
5573                if shape.feature.is_none() {
5574                    if parent_scope.class_feature.is_some() {
5575                        shape.feature =
5576                            at("a base class with a decorator, a metaclass or several bases");
5577                    } else if parent_scope
5578                        .bases
5579                        .iter()
5580                        .any(|b| self.classes_by_name.contains_key(b))
5581                    {
5582                        shape.feature = at("inheritance more than one level deep");
5583                    }
5584                }
5585            }
5586            Some(_) if shape.feature.is_none() => {
5587                shape.feature = at("a base class name bound more than once");
5588            }
5589            _ => {}
5590        }
5591        shape
5592    }
5593
5594    /// What attribute `attr` read through `class` may hold: by the class's
5595    /// name (`Bot.model`) or, when `through_self`, through `self`/`cls` in
5596    /// its methods, where the instance may also be a direct subclass's.
5597    ///
5598    /// The supported grammar: the class's own assignments, else its one
5599    /// same-file base's, plus (through `self`) those of at most
5600    /// [`MAX_SUBCLASSES`] direct subclasses that have no subclasses of
5601    /// their own. Anything else that may change the attribute is a dynamic
5602    /// feature, reported as a gap instead of resolved: a decorator,
5603    /// metaclass or several bases on the class, its base or a subclass;
5604    /// deeper inheritance; an attribute hook; a write of that attribute
5605    /// name on any other object; a write with a run-time name; the class
5606    /// used as a value; a method of the same name; a class attribute of a
5607    /// class with a base outside the file. Memoized; constant work per
5608    /// lookup, however many classes and writes the file has.
5609    fn attr_lookup(&mut self, class: usize, attr: &str, through_self: bool) -> Rc<AttrLookup<'t>> {
5610        let key = (class, attr.to_string());
5611        let memo = if through_self {
5612            &self.self_attr_memo
5613        } else {
5614            &self.class_attr_memo
5615        };
5616        if let Some(found) = memo.get(&key) {
5617            return Rc::clone(found);
5618        }
5619        let shape = self.class_shape(class);
5620        let line = self.scopes[class].line;
5621        let at = |what| Feature { what, line };
5622        let shadowed = |cx: &Self, c: usize| cx.functions.contains_key(&(c, attr.to_string()));
5623        let mut dynamic = shape
5624            .feature
5625            .or(self.attr_hooks)
5626            .or(self.wild_attr_any)
5627            .or_else(|| self.outside_attr_writes.get(attr).copied())
5628            .or_else(|| self.wild_attr_writes.get(&class).copied())
5629            .or_else(|| {
5630                shape
5631                    .base
5632                    .and_then(|b| self.wild_attr_writes.get(&b).copied())
5633            })
5634            .or_else(|| {
5635                self.class_escapes
5636                    .get(self.scopes[class].name.as_str())
5637                    .copied()
5638            });
5639        if dynamic.is_none()
5640            && (shadowed(self, class) || shape.base.is_some_and(|b| shadowed(self, b)))
5641        {
5642            dynamic = Some(at("a method of the same name"));
5643        }
5644        let mut from = class;
5645        let mut assigns = self.own_attrs(class, attr);
5646        if assigns.is_empty() {
5647            if let Some(base) = shape.base {
5648                from = base;
5649                assigns = self.own_attrs(base, attr);
5650            }
5651        }
5652        // A class attribute of a class with a base from outside the file
5653        // may be a field its constructor sets (a dataclass, a pydantic or
5654        // attrs model, a NamedTuple) or one its metaclass rewrites (an
5655        // enum member).
5656        let external = if from == class {
5657            shape.external
5658        } else {
5659            self.scopes[from].external_bases
5660        };
5661        if dynamic.is_none() && external && assigns.iter().any(|a| a.scope == from) {
5662            dynamic = Some(at(
5663                "a class attribute of a class with a base outside this file",
5664            ));
5665        }
5666        let mut extra: Vec<Assign<'t>> = Vec::new();
5667        if through_self {
5668            if dynamic.is_none() && self.ambiguous_base_names.contains(&self.scopes[class].name) {
5669                dynamic = Some(at("a base class name more than one class has"));
5670            }
5671            let subs: Vec<usize> = self
5672                .subclasses
5673                .get(&class)
5674                .map(|subs| subs.iter().take(MAX_SUBCLASSES + 1).copied().collect())
5675                .unwrap_or_default();
5676            if subs.len() > MAX_SUBCLASSES {
5677                dynamic.get_or_insert(at("more than 16 subclasses"));
5678            }
5679            for &sub in subs.iter().take(MAX_SUBCLASSES) {
5680                let sub_line = self.scopes[sub].line;
5681                let found = if self.subclasses.contains_key(&sub) {
5682                    Some("inheritance more than one level deep")
5683                } else if self.scopes[sub].class_feature.is_some() {
5684                    Some("a subclass with a decorator, a metaclass or several bases")
5685                } else if self.wild_attr_writes.contains_key(&sub) {
5686                    Some("an attribute written with a run-time name")
5687                } else if shadowed(self, sub) {
5688                    Some("a method of the same name")
5689                } else {
5690                    None
5691                };
5692                if let Some(what) = found {
5693                    dynamic.get_or_insert(Feature {
5694                        what,
5695                        line: sub_line,
5696                    });
5697                }
5698                let own = self.own_attrs(sub, attr);
5699                if own.len() > MAX_SUBCLASS_ASSIGNS {
5700                    dynamic.get_or_insert(Feature {
5701                        what: "more assignments in a subclass than are read",
5702                        line: sub_line,
5703                    });
5704                }
5705                extra.extend(own.iter().take(MAX_SUBCLASS_ASSIGNS).copied());
5706            }
5707            // Set only by subclasses: an abstract attribute, which
5708            // subclasses in other modules may set too.
5709            if assigns.is_empty() && !extra.is_empty() {
5710                dynamic.get_or_insert(at("an attribute only subclasses assign"));
5711            }
5712        }
5713        if assigns.len() > MAX_ATTR_ASSIGNS {
5714            dynamic.get_or_insert(at("more assignments of the attribute than are read"));
5715        }
5716        let assigns: Rc<[Assign<'t>]> = if extra.is_empty() && assigns.len() <= MAX_ATTR_ASSIGNS {
5717            assigns
5718        } else {
5719            assigns
5720                .iter()
5721                .take(MAX_ATTR_ASSIGNS)
5722                .copied()
5723                .chain(extra)
5724                .collect()
5725        };
5726        let found = Rc::new(AttrLookup { assigns, dynamic });
5727        let memo = if through_self {
5728            &mut self.self_attr_memo
5729        } else {
5730            &mut self.class_attr_memo
5731        };
5732        memo.insert(key, Rc::clone(&found));
5733        found
5734    }
5735
5736    /// The value of attribute `attr` of `class`, read through `self`/`cls`
5737    /// when `through_self` (see [`Self::attr_lookup`]). A dynamic feature
5738    /// is combined in as a value of its own: a client next to it keeps a
5739    /// `dynamic_feature` gap.
5740    fn resolve_attr(&mut self, class: usize, attr: &str, through_self: bool) -> Val {
5741        let key = (class, attr.to_string());
5742        let budget = self.budget();
5743        let memo = if through_self {
5744            &self.dyn_attr_memo
5745        } else {
5746            &self.attr_memo
5747        };
5748        if let Some(val) = self.reuse(recall(memo, &key, budget)) {
5749            return val;
5750        }
5751        let guard = (
5752            if through_self { 5u8 } else { 1u8 },
5753            class,
5754            attr.to_string(),
5755        );
5756        if !self.visiting.insert(guard.clone()) {
5757            return Val::untracked(Origin::Cycle);
5758        }
5759        let cutoffs = self.cutoffs;
5760        if !self.enter_name() {
5761            self.visiting.remove(&guard);
5762            return Val::untracked(Origin::Other);
5763        }
5764        let lookup = self.attr_lookup(class, attr, through_self);
5765        let mut vals: Vec<Val> = lookup
5766            .assigns
5767            .iter()
5768            .map(|a| self.assign_value_memo(*a))
5769            .collect();
5770        if let Some(feature) = lookup.dynamic {
5771            vals.push(Val::untracked(Origin::Dynamic(feature)));
5772        }
5773        let val = if vals.is_empty() {
5774            Val::untracked(Origin::UnassignedAttribute {
5775                name: attr.to_string(),
5776            })
5777        } else {
5778            combine(vals)
5779        };
5780        self.leave_name();
5781        self.visiting.remove(&guard);
5782        let memo = self.memo(val.clone(), cutoffs, budget);
5783        if through_self {
5784            self.dyn_attr_memo.insert(key, memo);
5785        } else {
5786            self.attr_memo.insert(key, memo);
5787        }
5788        val
5789    }
5790
5791    fn member(&mut self, base: Val, attr: &str) -> Val {
5792        if base.path().len() >= MAX_PATH {
5793            return Val::untracked(Origin::Other);
5794        }
5795        let clipped = clip(attr);
5796        let attr = clipped.as_str();
5797        match base {
5798            Val::Module { pkg, mut path } => {
5799                if let Some(class) = client_class(pkg, attr) {
5800                    return Val::Class(class);
5801                }
5802                path.push(attr.to_string());
5803                Val::Module { pkg, path }
5804            }
5805            Val::GoogleNs => match attr {
5806                "genai" => Val::Module {
5807                    pkg: Pkg::GoogleGenai,
5808                    path: Vec::new(),
5809                },
5810                "generativeai" => Val::Module {
5811                    pkg: Pkg::GoogleGenerativeai,
5812                    path: Vec::new(),
5813                },
5814                _ => Val::untracked(Origin::Other),
5815            },
5816            Val::Class(class) => Val::Symbol {
5817                pkg: class.pkg,
5818                path: vec![class.name.to_string(), attr.to_string()],
5819            },
5820            Val::Symbol { pkg, mut path } => {
5821                path.push(attr.to_string());
5822                Val::Symbol { pkg, path }
5823            }
5824            Val::Client { client, mut path } => {
5825                path.push(attr.to_string());
5826                Val::Client { client, path }
5827            }
5828            Val::Result(pkg) => Val::Result(pkg),
5829            Val::Untracked(origin) => Val::Untracked(origin),
5830        }
5831    }
5832
5833    fn apply_call(&mut self, callee: Val, call: Node<'t>, scope: usize, depth: u32) -> Val {
5834        match callee {
5835            Val::Class(class) => Val::Client {
5836                client: self.construction(call, class),
5837                path: Vec::new(),
5838            },
5839            Val::Client { client, path } => {
5840                let pkg = client.pkg;
5841                let joined = path.join(".");
5842                match joined.as_str() {
5843                    // Copies of the same client, re-routed by their options.
5844                    "with_options" | "copy" => Val::Client {
5845                        client: self.copied_client(client, call, scope),
5846                        path: Vec::new(),
5847                    },
5848                    // Chat sessions that keep the client's routing.
5849                    "start_chat" | "chats.create" | "aio.chats.create" => Val::Client {
5850                        client,
5851                        path: Vec::new(),
5852                    },
5853                    _ => Val::Result(Some(pkg)),
5854                }
5855            }
5856            Val::Module { pkg, .. } | Val::Symbol { pkg, .. } => Val::Result(Some(pkg)),
5857            Val::Result(pkg) => Val::Result(pkg),
5858            Val::GoogleNs => Val::untracked(Origin::Other),
5859            Val::Untracked(Origin::MixedClasses(pkg)) => Val::Client {
5860                client: Client {
5861                    pkg,
5862                    routing: Routing::Unknown,
5863                    line: None,
5864                    site: None,
5865                    ambiguous: true,
5866                    typed: false,
5867                    caveat: None,
5868                },
5869                path: Vec::new(),
5870            },
5871            Val::Untracked(_) => {
5872                let callee = call
5873                    .child_by_field_name("function")
5874                    .map(|f| self.render_links(f, 16))
5875                    .unwrap_or_else(|| "<expr>".to_string());
5876                let wraps = self.wrapped_pkg(call, scope, depth);
5877                Val::untracked(Origin::Factory { callee, wraps })
5878            }
5879        }
5880    }
5881
5882    /// `client.with_options(...)` / `client.copy(...)`: both SDKs accept
5883    /// `base_url` there, so a direct client given one routes by what it is
5884    /// (see [`Self::base_url_kind`]), and options passed through an
5885    /// unreadable `**kwargs` make it unknown.
5886    fn copied_client(&mut self, mut client: Client, call: Node<'t>, scope: usize) -> Client {
5887        let args = self.arguments(call);
5888        let mut base_url = BaseUrl::Absent;
5889        let mut opaque = false;
5890        if let Some(expr) = keyword_value(call, |n| self.text(n), is_base_url_key) {
5891            base_url = self.base_url_kind(client.pkg, expr, scope);
5892        }
5893        for splat in &args.splats {
5894            match self.expand_splat(*splat, scope) {
5895                Some(expansion) => {
5896                    let given = expansion
5897                        .summary
5898                        .expansion
5899                        .iter()
5900                        .find(|(k, _, _)| is_base_url_key(k))
5901                        .map(|(_, index, v)| (*index, *v));
5902                    match given {
5903                        // A later `**other` may replace it.
5904                        Some((index, _)) if expansion.summary.overridable(index) => {
5905                            base_url = BaseUrl::Unknown { env: false };
5906                        }
5907                        Some((_, expr)) => {
5908                            base_url = self.base_url_kind(client.pkg, expr, expansion.scope);
5909                        }
5910                        None => {}
5911                    }
5912                    opaque |= expansion.opaque();
5913                }
5914                None => opaque = true,
5915            }
5916        }
5917        let direct = matches!(
5918            client.routing,
5919            Routing::OpenaiDirect | Routing::AnthropicDirect
5920        );
5921        if !direct {
5922            return client;
5923        }
5924        match base_url {
5925            BaseUrl::Custom => client.routing = Routing::CustomBaseUrl,
5926            BaseUrl::CustomFallback => {
5927                client.routing = Routing::CustomBaseUrl;
5928                client.caveat.get_or_insert(ClientCaveat::BaseUrl {
5929                    env: true,
5930                    fallback: true,
5931                });
5932            }
5933            BaseUrl::Unknown { env } => {
5934                client.routing = Routing::Unknown;
5935                client.caveat.get_or_insert(ClientCaveat::BaseUrl {
5936                    env,
5937                    fallback: false,
5938                });
5939            }
5940            BaseUrl::ProviderFallback => {
5941                client.caveat.get_or_insert(ClientCaveat::BaseUrl {
5942                    env: false,
5943                    fallback: true,
5944                });
5945            }
5946            // `with_options(**opts)`: the expansion may hold a `base_url`.
5947            BaseUrl::Absent if opaque => {
5948                client.routing = Routing::Unknown;
5949                client.caveat.get_or_insert(ClientCaveat::BaseUrl {
5950                    env: false,
5951                    fallback: false,
5952                });
5953            }
5954            BaseUrl::Absent | BaseUrl::Provider => {}
5955        }
5956        client
5957    }
5958
5959    /// What a `base_url` argument of a `pkg` client routes it to (P6): the
5960    /// provider's own host is direct, any other host a custom route, the
5961    /// provider's host as an environment fallback direct with a gap, and an
5962    /// environment lookup with no fallback, or anything that does not
5963    /// resolve to a string, unknown with a gap. The URL is never reported.
5964    fn base_url_kind(&mut self, pkg: Pkg, expr: Node<'t>, scope: usize) -> BaseUrl {
5965        if expr.kind() == "none" {
5966            return BaseUrl::Absent;
5967        }
5968        // A literal at the call: its host decides, credentials or not.
5969        if let Ok(url) = self.literal(expr) {
5970            return host_kind(pkg, &url);
5971        }
5972        match self.resolve_value(expr, scope, 0) {
5973            Ok(resolved) if resolved.origin == ValueOrigin::EnvDefault => {
5974                match host_kind(pkg, &resolved.value) {
5975                    BaseUrl::Provider => BaseUrl::ProviderFallback,
5976                    _ => BaseUrl::CustomFallback,
5977                }
5978            }
5979            Ok(resolved) if resolved.caveats.is_empty() => host_kind(pkg, &resolved.value),
5980            Ok(_) => BaseUrl::Unknown { env: false },
5981            Err(unresolved) => BaseUrl::Unknown {
5982                env: unresolved.reason == "env_var",
5983            },
5984        }
5985    }
5986
5987    /// The SDK of a tracked client or constructor passed to a call
5988    /// (`instructor.from_openai(OpenAI())`).
5989    fn wrapped_pkg(&mut self, call: Node<'t>, scope: usize, depth: u32) -> Option<Pkg> {
5990        let args = call.child_by_field_name("arguments")?;
5991        for arg in named_children(args) {
5992            let expr = if arg.kind() == "keyword_argument" {
5993                arg.child_by_field_name("value")
5994            } else {
5995                Some(arg)
5996            };
5997            if let Some(expr) = expr {
5998                if let val @ (Val::Client { .. } | Val::Class(_)) =
5999                    self.eval(expr, scope, depth + 1)
6000                {
6001                    return val.pkg();
6002                }
6003            }
6004        }
6005        None
6006    }
6007
6008    /// The client built by `call`, recorded once.
6009    fn construction(&mut self, call: Node<'t>, class: ClientClass) -> Client {
6010        let site = Some(call.id());
6011        if let Some((index, caveat)) = self.constructions.get(&call.id()).cloned() {
6012            let built = &self.out.clients[index];
6013            return Client {
6014                pkg: class.pkg,
6015                routing: built.routing,
6016                line: Some(built.span.line),
6017                site,
6018                ambiguous: false,
6019                typed: false,
6020                caveat,
6021            };
6022        }
6023        let scope = self.call_scope.get(&call.id()).copied().unwrap_or(0);
6024        let args = self.arguments(call);
6025        let direct = matches!(class.family, Family::OpenaiDirect | Family::AnthropicDirect);
6026        let base_url = match keyword_value(call, |n| self.text(n), is_base_url_key) {
6027            Some(expr) if direct => self.base_url_kind(class.pkg, expr, scope),
6028            Some(_) => BaseUrl::Custom,
6029            None => BaseUrl::Absent,
6030        };
6031        let mut routing = class.routing(&args.kwargs, args.splat, base_url);
6032        let mut caveat = match self.genai_endpoint_option(call, class, &args) {
6033            Some(option) => Some(ClientCaveat::EndpointOption { option }),
6034            None => self.endpoint_env(class, base_url),
6035        };
6036        if caveat.is_some() {
6037            routing = Routing::Unknown;
6038        }
6039        if direct {
6040            match base_url {
6041                BaseUrl::CustomFallback => {
6042                    caveat.get_or_insert(ClientCaveat::BaseUrl {
6043                        env: true,
6044                        fallback: true,
6045                    });
6046                }
6047                BaseUrl::Unknown { env } => {
6048                    caveat.get_or_insert(ClientCaveat::BaseUrl {
6049                        env,
6050                        fallback: false,
6051                    });
6052                }
6053                BaseUrl::ProviderFallback => {
6054                    caveat.get_or_insert(ClientCaveat::BaseUrl {
6055                        env: false,
6056                        fallback: true,
6057                    });
6058                }
6059                // `OpenAI(**options)`: the expansion may hold a `base_url`.
6060                BaseUrl::Absent if args.splat => {
6061                    caveat.get_or_insert(ClientCaveat::BaseUrl {
6062                        env: false,
6063                        fallback: false,
6064                    });
6065                }
6066                _ => {}
6067            }
6068        }
6069        let (binding, binding_scope) = self.binding_target(call, scope);
6070        let chain = call
6071            .child_by_field_name("function")
6072            .map(|f| self.render(f))
6073            .unwrap_or_default();
6074        let span = self.span(call);
6075        // Only the class of the value: `True`, `False`/`None`, or anything
6076        // decided at run time.
6077        let vertexai = (class.family == Family::Genai)
6078            .then(|| keyword_value(call, |n| self.text(n), |k| k == "vertexai"))
6079            .flatten()
6080            .map(|value| match value.kind() {
6081                "true" => VertexAi::On,
6082                "false" | "none" => VertexAi::Off,
6083                _ => VertexAi::Unknown,
6084            });
6085        let record = ClientConstruction {
6086            sdk: class.pkg.sdk(),
6087            package: class.pkg.package().to_string(),
6088            constructor: format!("{}.{}", class.pkg.package(), class.name),
6089            chain,
6090            binding,
6091            scope: binding_scope,
6092            routing,
6093            is_async: class.is_async(),
6094            kwargs: args.kwargs,
6095            splat: args.splat,
6096            file: self.file.clone(),
6097            span,
6098            symbol: self.symbol(scope),
6099            vertexai,
6100        };
6101        self.constructions
6102            .insert(call.id(), (self.out.clients.len(), caveat.clone()));
6103        self.out.clients.push(record);
6104        Client {
6105            pkg: class.pkg,
6106            routing,
6107            line: Some(span.line),
6108            site,
6109            ambiguous: false,
6110            typed: false,
6111            caveat,
6112        }
6113    }
6114
6115    /// For `google.genai.Client(...)`: the option that may send its requests
6116    /// to Vertex AI or another endpoint instead of the Gemini API, if any.
6117    /// `vertexai=` (unless `False` or `None`), `http_options=` (unless `None`
6118    /// or a dict literal or `HttpOptions(...)` call that names no
6119    /// `base_url` and expands nothing) and a `**` expansion each count.
6120    fn genai_endpoint_option(
6121        &self,
6122        call: Node<'t>,
6123        class: ClientClass,
6124        args: &Args<'t>,
6125    ) -> Option<&'static str> {
6126        if class.family != Family::Genai {
6127            return None;
6128        }
6129        if args.splat {
6130            return Some("a `**` expansion");
6131        }
6132        let text = |n: Node<'t>| self.text(n);
6133        if let Some(value) = keyword_value(call, text, |k| k == "vertexai") {
6134            if !matches!(value.kind(), "false" | "none") {
6135                return Some("`vertexai=`");
6136            }
6137        }
6138        let options = keyword_value(call, text, |k| k == "http_options")?;
6139        let names_no_endpoint = match options.kind() {
6140            "none" => true,
6141            "dictionary" => dict_entries(options, |n| self.literal(n).ok(), text)
6142                .iter()
6143                .all(|entry| entry.as_ref().is_some_and(|(k, _)| k != "base_url")),
6144            "call" => {
6145                let last = options
6146                    .child_by_field_name("function")
6147                    .and_then(|f| match f.kind() {
6148                        "identifier" => Some(f),
6149                        "attribute" => f.child_by_field_name("attribute"),
6150                        _ => None,
6151                    });
6152                last.is_some_and(|n| self.text(n) == "HttpOptions")
6153                    && options
6154                        .child_by_field_name("arguments")
6155                        .is_some_and(|list| {
6156                            named_children(list).iter().all(|arg| {
6157                                arg.kind() == "comment"
6158                                    || (arg.kind() == "keyword_argument"
6159                                        && arg
6160                                            .child_by_field_name("name")
6161                                            .is_some_and(|n| self.text(n) != "base_url"))
6162                            })
6163                        })
6164            }
6165            _ => false,
6166        };
6167        (!names_no_endpoint).then_some("`http_options=`")
6168    }
6169
6170    /// Why a client built by `class` may not reach the endpoint its
6171    /// constructor names: when it names none (`base_url` absent or `None`),
6172    /// the SDK reads its endpoint variable, which this file sets
6173    /// ([`ClientCaveat::EndpointEnv`]) or may set through a run-time name or
6174    /// an alias of `os.environ` ([`ClientCaveat::EnvWrite`]).
6175    fn endpoint_env(&self, class: ClientClass, base_url: BaseUrl) -> Option<ClientCaveat> {
6176        if !matches!(
6177            class.family,
6178            Family::OpenaiDirect | Family::AnthropicDirect | Family::Genai
6179        ) || base_url != BaseUrl::Absent
6180        {
6181            return None;
6182        }
6183        ENDPOINT_ENV
6184            .iter()
6185            .find(|(pkg, var)| *pkg == class.pkg && self.env_writes.contains(*var))
6186            .map(|(_, var)| ClientCaveat::EndpointEnv { var })
6187            .or_else(|| self.env_wild.map(ClientCaveat::EnvWrite))
6188    }
6189
6190    /// The name a constructed client is assigned to, and how it is held.
6191    fn binding_target(&self, call: Node<'t>, scope: usize) -> (Option<String>, ClientScope) {
6192        let mut child = call;
6193        let mut parent = self.parents.get(&call.id()).copied();
6194        while let Some(p) = parent {
6195            if matches!(
6196                p.kind(),
6197                "parenthesized_expression"
6198                    | "boolean_operator"
6199                    | "conditional_expression"
6200                    | "await"
6201            ) && p.is_named()
6202            {
6203                child = p;
6204                parent = self.parents.get(&p.id()).copied();
6205            } else {
6206                break;
6207            }
6208        }
6209        let Some(parent) = parent else {
6210            return (None, ClientScope::Inline);
6211        };
6212        let target = match parent.kind() {
6213            "assignment"
6214                if parent.child_by_field_name("right").map(|r| r.id()) == Some(child.id()) =>
6215            {
6216                parent.child_by_field_name("left")
6217            }
6218            "as_pattern" => parent
6219                .child_by_field_name("alias")
6220                .and_then(|alias| alias.named_child(0)),
6221            "named_expression" => parent.child_by_field_name("name"),
6222            _ => None,
6223        };
6224        let Some(target) = target else {
6225            return (None, ClientScope::Inline);
6226        };
6227        match target.kind() {
6228            "identifier" => {
6229                let name = self.text(target).to_string();
6230                let held = match self.scopes[scope].kind {
6231                    ScopeKind::Module => ClientScope::Module,
6232                    ScopeKind::Class => ClientScope::Class,
6233                    ScopeKind::Function if self.scopes[scope].globals.contains(&name) => {
6234                        ClientScope::Module
6235                    }
6236                    ScopeKind::Function => ClientScope::Local,
6237                };
6238                (Some(clip_owned(name)), held)
6239            }
6240            "attribute" => (Some(self.render(target)), ClientScope::Attribute),
6241            _ => (Some(self.render(target)), ClientScope::Inline),
6242        }
6243    }
6244
6245    // ------------------------------------------------------------------
6246    // Pass 2: analyze
6247    // ------------------------------------------------------------------
6248
6249    fn analyze(&mut self) {
6250        if let Some(statement) = self.import_cut {
6251            // A name the file no longer binds could change what any call
6252            // resolves to: report nothing rather than something wrong.
6253            self.out.gaps.push(UsageGap {
6254                kind: GapKind::UnresolvedModel,
6255                sdk: None,
6256                file: self.file.clone(),
6257                span: Some(self.span(statement)),
6258                symbol: None,
6259                chain: None,
6260                key: None,
6261                reason: "truncated".to_string(),
6262                detail: format!(
6263                    "this file binds more than {MAX_FILE_IMPORTS} imported names, so its calls are not analyzed"
6264                ),
6265                values: Vec::new(),
6266                values_complete: false,
6267            });
6268            return;
6269        }
6270        // Calls inside a scope nested past the cap are not analyzed.
6271        for (node, scope) in std::mem::take(&mut self.scope_cuts) {
6272            if self.records() >= MAX_FILE_RECORDS {
6273                return self.truncate_file(node, scope);
6274            }
6275            self.out.gaps.push(UsageGap {
6276                kind: GapKind::UnresolvedModel,
6277                sdk: None,
6278                file: self.file.clone(),
6279                span: Some(self.span(node)),
6280                symbol: self.symbol(scope),
6281                chain: None,
6282                key: None,
6283                reason: "truncated".to_string(),
6284                detail: format!(
6285                    "scopes here are nested more than {MAX_SCOPE_DEPTH} deep, so the calls inside are not analyzed"
6286                ),
6287                values: Vec::new(),
6288                values_complete: false,
6289            });
6290        }
6291        self.settle_builtin_values();
6292        self.settle_borrowed_methods();
6293        // A bare `environ` is the process environment only when imported
6294        // from `os`.
6295        let environ_from_os = ["environ", "environb"].iter().any(|name| {
6296            self.other_imports
6297                .get(&(0, name.to_string()))
6298                .is_some_and(|defs| defs.iter().any(|d| &*d.module == "os"))
6299        });
6300        if environ_from_os {
6301            if let Some(feature) = self.bare_environ_wild {
6302                self.env_wild.get_or_insert(feature);
6303            }
6304        }
6305        self.openai_routing = self.module_openai_routing();
6306        if let Some(var) = OPENAI_MODULE_ENV
6307            .iter()
6308            .find(|var| self.env_writes.contains(**var))
6309        {
6310            if self.openai_routing == Routing::OpenaiDirect {
6311                self.openai_routing = Routing::Unknown;
6312            }
6313            self.openai_caveat = Some(ClientCaveat::EndpointEnv { var });
6314        } else if let Some(feature) = self.env_wild {
6315            if self.openai_routing == Routing::OpenaiDirect {
6316                self.openai_routing = Routing::Unknown;
6317            }
6318            self.openai_caveat = Some(ClientCaveat::EnvWrite(feature));
6319        }
6320        self.note_legacy_configure();
6321        self.note_rerouted_clients();
6322        for (call, scope) in self.calls.clone() {
6323            if self.records() >= MAX_FILE_RECORDS {
6324                return self.truncate_file(call, scope);
6325            }
6326            self.analyze_call(call, scope);
6327        }
6328        for (reference, scope) in self.refs.clone() {
6329            if self.records() >= MAX_FILE_RECORDS {
6330                return self.truncate_file(reference, scope);
6331            }
6332            self.analyze_reference(reference, scope);
6333        }
6334    }
6335
6336    /// Imports, calls, gaps and clients reported so far.
6337    fn records(&self) -> usize {
6338        self.out.imports.len() + self.out.calls.len() + self.out.gaps.len() + self.out.clients.len()
6339    }
6340
6341    /// Stops the analysis at `node`: the rest of the file is one gap.
6342    fn truncate_file(&mut self, node: Node<'t>, scope: usize) {
6343        self.out.gaps.push(UsageGap {
6344            kind: GapKind::UnresolvedModel,
6345            sdk: None,
6346            file: self.file.clone(),
6347            span: Some(self.span(node)),
6348            symbol: self.symbol(scope),
6349            chain: None,
6350            key: None,
6351            reason: "truncated".to_string(),
6352            detail: format!(
6353                "this file reports more than {MAX_FILE_RECORDS} imports, calls, clients and gaps; nothing from this line on is analyzed"
6354            ),
6355            values: Vec::new(),
6356            values_complete: false,
6357        });
6358    }
6359
6360    /// Where the top-of-file setup block ends: the start of the first
6361    /// module-level statement that is not an import, a string (the
6362    /// docstring), or an assignment (`=`, annotated or augmented) with no
6363    /// lambda, comprehension, generator expression, walrus, `yield` or
6364    /// `await` in it. A `def`, a `class`, a decorator, a bare expression or
6365    /// call, and any compound statement (`if`, `try`, `for`, `with`...) end
6366    /// it. Before it this file has defined no function, class or lambda,
6367    /// so no code of its own can run: a configuration written there holds
6368    /// for every call this file's functions make. One pass over the
6369    /// statements of the block, on first use.
6370    fn setup_end(&mut self) -> usize {
6371        if let Some(end) = self.setup_end {
6372            return end;
6373        }
6374        let end = self.root.map_or(0, |root| self.setup_block_end(root));
6375        self.setup_end = Some(end);
6376        end
6377    }
6378
6379    /// [`Ctx::setup_end`], read from the module's statements.
6380    fn setup_block_end(&self, root: Node<'t>) -> usize {
6381        let mut cursor = root.walk();
6382        for statement in root.named_children(&mut cursor) {
6383            let setup = match statement.kind() {
6384                "import_statement"
6385                | "import_from_statement"
6386                | "future_import_statement"
6387                | "comment" => true,
6388                "expression_statement" => match named_children(statement).as_slice() {
6389                    [only] => match only.kind() {
6390                        "string" | "concatenated_string" => true,
6391                        "assignment" | "augmented_assignment" => !self.may_define_code(*only),
6392                        _ => false,
6393                    },
6394                    _ => false,
6395                },
6396                _ => false,
6397            };
6398            if !setup {
6399                return statement.start_byte();
6400            }
6401        }
6402        root.end_byte()
6403    }
6404
6405    /// Whether `node` holds a lambda, comprehension, generator expression,
6406    /// walrus, `yield` or `await`: code that defines a scope or binds a name
6407    /// where it runs.
6408    fn may_define_code(&self, node: Node<'t>) -> bool {
6409        let mut cursor = node.walk();
6410        let mut stack = vec![node];
6411        while let Some(current) = stack.pop() {
6412            if matches!(
6413                current.kind(),
6414                "lambda"
6415                    | "list_comprehension"
6416                    | "set_comprehension"
6417                    | "dictionary_comprehension"
6418                    | "generator_expression"
6419                    | "named_expression"
6420                    | "yield"
6421                    | "await"
6422            ) {
6423                return true;
6424            }
6425            stack.extend(current.named_children(&mut cursor));
6426        }
6427        false
6428    }
6429
6430    /// Routing of the module-level OpenAI API, from `openai.api_type`,
6431    /// `openai.api_base` / `base_url` and `openai.azure_endpoint`
6432    /// assignments anywhere in the file. The supported grammar is a
6433    /// configuration written in the top-of-file setup block (see
6434    /// [`Ctx::setup_block_end`]): plain `=` statements directly in the
6435    /// module body, each routing attribute assigned once. Anything else (a
6436    /// routing setting in a function, a branch, loop, `try`, `with` or class
6437    /// body, after a `def`, `class`, decorator or other statement, by `+=`,
6438    /// `setattr` or `del`, assigned twice, or written on an object this file
6439    /// cannot identify) gives every module-level call a `module_config` gap;
6440    /// the routing reported is what the assignments together suggest, as a
6441    /// candidate.
6442    fn module_openai_routing(&mut self) -> Routing {
6443        let (mut azure, mut unknown, mut custom) = (false, false, false);
6444        let mut assigned: HashSet<&'t str> = HashSet::new();
6445        for assign in self.config_assigns.clone() {
6446            let target = self.eval(assign.object, assign.scope, 0);
6447            self.note_sdk_patch(&target, assign);
6448            let attr = assign.attr;
6449            let routes = is_module_routing_attr(attr);
6450            if !matches!(&target, Val::Module { pkg: Pkg::Openai, path } if path.is_empty()) {
6451                // An object this file cannot identify (an alias chosen at
6452                // run time, a parameter) may be the module.
6453                if routes && matches!(target, Val::Untracked(_)) {
6454                    self.openai_caveat
6455                        .get_or_insert(ClientCaveat::ModuleSetup(Self::feature(
6456                            "a routing setting written on an object this file cannot identify, which may be the SDK module",
6457                            assign.object,
6458                        )));
6459                }
6460                continue;
6461            }
6462            if routes && self.openai_last_config.is_none_or(|(at, _)| at < assign.at) {
6463                let feature = Self::feature("the SDK configured after the call", assign.object);
6464                self.openai_last_config = Some((assign.at, feature));
6465            }
6466            if routes {
6467                // Set in a function, the configuration holds only once (and
6468                // if) the function runs; in a branch, loop or `try`, only on
6469                // that path; after the setup block, perhaps after this
6470                // file's own code ran; assigned twice, whichever ran last.
6471                let what = if self.scopes[assign.scope].kind == ScopeKind::Function {
6472                    Some("the SDK configured inside a function, which may not run first")
6473                } else if !assign.top {
6474                    Some("the SDK configured inside a branch, loop, `try`, `with` or class body, which may not run")
6475                } else if !assign.plain {
6476                    Some("the SDK configured by `+=`, `setattr` or `del`")
6477                } else if !self.imported_only(assign.object) {
6478                    Some("the SDK configured through a name this file also assigns, or a wildcard import may rebind")
6479                } else if assign.at >= self.setup_end() {
6480                    Some("the SDK configured after the top-of-file setup block, where this file's own code may already have run")
6481                } else if !assigned.insert(attr) {
6482                    Some("an SDK routing setting assigned more than once")
6483                } else {
6484                    None
6485                };
6486                if let Some(what) = what {
6487                    self.openai_caveat
6488                        .get_or_insert(ClientCaveat::ModuleSetup(Self::feature(
6489                            what,
6490                            assign.object,
6491                        )));
6492                }
6493            }
6494            match attr {
6495                "api_type" => match assign.value.and_then(|v| self.literal(v).ok()) {
6496                    Some(kind) => match kind.to_ascii_lowercase().as_str() {
6497                        "azure" | "azure_ad" | "azuread" => azure = true,
6498                        "openai" | "open_ai" => {}
6499                        // `amazon-bedrock` and anything newer.
6500                        _ => unknown = true,
6501                    },
6502                    None => unknown = true,
6503                },
6504                "azure_endpoint" | "azure_ad_token" | "azure_ad_token_provider" => azure = true,
6505                "api_base" | "base_url" => {
6506                    let kind = match assign.value {
6507                        Some(value) => self.base_url_kind(Pkg::Openai, value, assign.scope),
6508                        None => BaseUrl::Unknown { env: false },
6509                    };
6510                    match kind {
6511                        BaseUrl::Absent | BaseUrl::Provider => {}
6512                        BaseUrl::Custom => custom = true,
6513                        BaseUrl::CustomFallback => {
6514                            custom = true;
6515                            self.openai_caveat.get_or_insert(ClientCaveat::BaseUrl {
6516                                env: true,
6517                                fallback: true,
6518                            });
6519                        }
6520                        BaseUrl::ProviderFallback => {
6521                            self.openai_caveat.get_or_insert(ClientCaveat::BaseUrl {
6522                                env: false,
6523                                fallback: true,
6524                            });
6525                        }
6526                        BaseUrl::Unknown { env } => {
6527                            unknown = true;
6528                            self.openai_caveat.get_or_insert(ClientCaveat::BaseUrl {
6529                                env,
6530                                fallback: false,
6531                            });
6532                        }
6533                    }
6534                }
6535                _ if attr.starts_with("bedrock_") => unknown = true,
6536                _ => {}
6537            }
6538        }
6539        // An attribute written with a run-time name may be a routing
6540        // setting of the module.
6541        for (object, scope) in self.wild_attr_objects.clone() {
6542            let target = self.eval(object, scope, 0);
6543            let module =
6544                matches!(&target, Val::Module { pkg: Pkg::Openai, path } if path.is_empty());
6545            if module || matches!(target, Val::Untracked(_)) {
6546                self.openai_caveat
6547                    .get_or_insert(ClientCaveat::ModuleSetup(Self::feature(
6548                        "an attribute written with a run-time name on an object that may be the SDK module",
6549                        object,
6550                    )));
6551                break;
6552            }
6553        }
6554        if azure {
6555            Routing::AzureOpenai
6556        } else if unknown {
6557            Routing::Unknown
6558        } else if custom {
6559            Routing::CustomBaseUrl
6560        } else {
6561            Routing::OpenaiDirect
6562        }
6563    }
6564
6565    /// Whether `call` passes `client_options=` or a `**` expansion, which
6566    /// may hold it.
6567    fn may_pass_client_options(&self, call: Node<'t>) -> bool {
6568        let Some(args) = call.child_by_field_name("arguments") else {
6569            return false;
6570        };
6571        let mut cursor = args.walk();
6572        let found = args
6573            .named_children(&mut cursor)
6574            .any(|arg| match arg.kind() {
6575                "dictionary_splat" => true,
6576                "keyword_argument" => arg
6577                    .child_by_field_name("name")
6578                    .is_some_and(|n| self.text(n) == "client_options"),
6579                _ => false,
6580            });
6581        found
6582    }
6583
6584    /// `genai.configure(client_options=...)` (the legacy Gemini SDK) may
6585    /// point every legacy call at another endpoint: they then route
6586    /// `unknown` with an `endpoint_option` gap. So may `**options`. In a
6587    /// file that imports the legacy SDK, the callee of every call that may
6588    /// pass `client_options` is evaluated, so `configure` under another
6589    /// name (`setup = genai.configure`) counts.
6590    fn note_legacy_configure(&mut self) {
6591        if !self.legacy_imported {
6592            return;
6593        }
6594        for (call, scope) in self.calls.clone() {
6595            if !self.may_pass_client_options(call) {
6596                continue;
6597            }
6598            let Some(function) = call.child_by_field_name("function") else {
6599                continue;
6600            };
6601            let configures = matches!(
6602                self.eval(function, scope, 0),
6603                Val::Module { pkg: Pkg::GoogleGenerativeai, ref path }
6604                    | Val::Symbol { pkg: Pkg::GoogleGenerativeai, ref path }
6605                    if path.last().is_some_and(|p| p == "configure")
6606            );
6607            if !configures {
6608                continue;
6609            }
6610            let args = self.arguments(call);
6611            let endpoint = keyword_value(call, |n| self.text(n), |k| k == "client_options")
6612                .is_some_and(|v| v.kind() != "none");
6613            if endpoint || args.splat {
6614                self.legacy_caveat
6615                    .get_or_insert(ClientCaveat::EndpointOption {
6616                        option: "`configure(client_options=...)`",
6617                    });
6618            }
6619        }
6620    }
6621
6622    /// A write that replaces an SDK member rather than configuring it: on a
6623    /// submodule, a class, an SDK symbol or a client's resource
6624    /// (`client.chat.completions.create = patched`), or a class or resource
6625    /// of the module or a client (`openai.OpenAI = Sub`, `client.chat =
6626    /// wrapper`). Settings (`openai.api_key`, `client.max_retries`) are not.
6627    fn note_sdk_patch(&mut self, target: &Val, assign: ConfigAssign<'t>) {
6628        const RESOURCES: &[&str] = &[
6629            "chat",
6630            "completions",
6631            "responses",
6632            "messages",
6633            "models",
6634            "beta",
6635            "embeddings",
6636            "images",
6637            "audio",
6638            "files",
6639            "batches",
6640            "aio",
6641            "chats",
6642            "with_options",
6643            "with_raw_response",
6644            "with_streaming_response",
6645            "copy",
6646            "generate_content",
6647            "generate_content_async",
6648        ];
6649        let attr = assign.attr;
6650        let resource =
6651            RESOURCES.contains(&attr) || attr.starts_with(|c: char| c.is_ascii_uppercase());
6652        let pkg = match target {
6653            Val::Module { pkg, path } if !path.is_empty() || resource => *pkg,
6654            Val::Class(class) => class.pkg,
6655            Val::Symbol { pkg, .. } => *pkg,
6656            Val::Client { client, path } if !path.is_empty() || resource => client.pkg,
6657            _ => return,
6658        };
6659        self.sdk_patched
6660            .entry(pkg)
6661            .or_insert_with(|| Self::feature("an SDK member replaced in this file", assign.object));
6662    }
6663
6664    /// Clients given a new `base_url` after they are built
6665    /// (`client.base_url = "https://openrouter.ai/api/v1"`).
6666    fn note_rerouted_clients(&mut self) {
6667        let written: Vec<(Node<'t>, usize)> = self
6668            .config_assigns
6669            .iter()
6670            .filter(|assign| BASE_URL_ATTRS.contains(&assign.attr))
6671            .map(|assign| (assign.object, assign.scope))
6672            // An attribute named at run time may be the base URL too.
6673            .chain(self.wild_attr_objects.iter().copied())
6674            .collect();
6675        for (object, scope) in written {
6676            match self.eval(object, scope, 0) {
6677                Val::Client { client, path } if path.is_empty() => match client.site {
6678                    Some(site) => {
6679                        self.rerouted.insert(site);
6680                    }
6681                    None => {
6682                        self.rerouted_pkgs.insert(client.pkg);
6683                    }
6684                },
6685                // An SDK module is routed by `module_openai_routing`; a
6686                // member of a client, or `self` of a same-file class, is not
6687                // a client.
6688                Val::Client { .. }
6689                | Val::Module { .. }
6690                | Val::Symbol { .. }
6691                | Val::Class(_)
6692                | Val::Result(_)
6693                | Val::GoogleNs => {}
6694                // `self`/`cls`, or a same-file class by name: not a client.
6695                _ if object.kind() == "identifier"
6696                    && (matches!(self.text(object), "self" | "cls")
6697                        || self.class_receiver(object, scope).is_some()) => {}
6698                // An object this file cannot identify may be any client.
6699                _ => {
6700                    self.rerouted_any.get_or_insert(Self::feature(
6701                        "a `base_url` written on an object this file cannot identify",
6702                        object,
6703                    ));
6704                }
6705            }
6706        }
6707    }
6708
6709    /// `client` with its routing unknown when a `base_url` is assigned to it
6710    /// after it is built.
6711    fn reroute(&self, mut client: Client) -> Client {
6712        // A legacy Gemini model object: `configure(client_options=...)`
6713        // routes every one of them.
6714        if client.pkg == Pkg::GoogleGenerativeai && client.caveat.is_none() && !client.ambiguous {
6715            if let Some(caveat) = &self.legacy_caveat {
6716                client.routing = Routing::Unknown;
6717                client.caveat = Some(caveat.clone());
6718            }
6719        }
6720        let assigned = client
6721            .site
6722            .is_some_and(|site| self.rerouted.contains(&site))
6723            || (self.rerouted_pkgs.contains(&client.pkg)
6724                && matches!(
6725                    client.routing,
6726                    Routing::OpenaiDirect | Routing::AnthropicDirect
6727                ));
6728        if assigned && !client.ambiguous {
6729            if matches!(
6730                client.routing,
6731                Routing::OpenaiDirect | Routing::AnthropicDirect
6732            ) {
6733                client.routing = Routing::Unknown;
6734            }
6735            client.caveat = Some(ClientCaveat::BaseUrlAssigned);
6736        } else if let Some(feature) = self.rerouted_any {
6737            let direct = matches!(
6738                client.routing,
6739                Routing::OpenaiDirect | Routing::AnthropicDirect
6740            );
6741            if direct && client.caveat.is_none() && !client.ambiguous {
6742                client.caveat = Some(ClientCaveat::Dynamic(feature));
6743            }
6744        }
6745        if let Some(feature) = self.sdk_patched.get(&client.pkg) {
6746            if client.caveat.is_none() && !client.ambiguous {
6747                client.caveat = Some(ClientCaveat::Dynamic(*feature));
6748            }
6749        }
6750        client
6751    }
6752
6753    /// Why the module-level API of `pkg` may not route as reported.
6754    fn module_caveat(&self, pkg: Pkg) -> Option<ClientCaveat> {
6755        match pkg {
6756            Pkg::Openai => self.openai_caveat.clone(),
6757            Pkg::GoogleGenerativeai => self.legacy_caveat.clone(),
6758            _ => None,
6759        }
6760    }
6761
6762    fn module_routing(&self, pkg: Pkg) -> Routing {
6763        match pkg {
6764            Pkg::Openai => self.openai_routing,
6765            Pkg::Anthropic => Routing::AnthropicDirect,
6766            Pkg::GoogleGenai => Routing::GoogleGenai,
6767            Pkg::GoogleGenerativeai if self.legacy_caveat.is_some() => Routing::Unknown,
6768            Pkg::GoogleGenerativeai => Routing::GoogleGenerativeaiLegacy,
6769        }
6770    }
6771
6772    /// Routing of a module-level API call (`openai.ChatCompletion.create`)
6773    /// and why it may not hold: the file's configuration (see
6774    /// [`Self::module_openai_routing`]), a configuration written after a
6775    /// call that runs at import, or (with no configuration in the file) an
6776    /// `engine`/`deployment_id` argument, which another module's Azure
6777    /// configuration would serve.
6778    fn module_target(
6779        &mut self,
6780        pkg: Pkg,
6781        call: Node<'t>,
6782        scope: usize,
6783    ) -> (Routing, Option<ClientCaveat>) {
6784        let mut routing = self.module_routing(pkg);
6785        let mut caveat = self.module_caveat(pkg);
6786        if caveat.is_none() {
6787            caveat = self
6788                .sdk_patched
6789                .get(&pkg)
6790                .map(|f| ClientCaveat::Dynamic(*f));
6791        }
6792        if pkg != Pkg::Openai || caveat.is_some() {
6793            return (routing, caveat);
6794        }
6795        match self.openai_last_config {
6796            Some((at, feature)) => {
6797                // The configuration is in the setup block (else the caveat
6798                // is set): no function of this file exists before it, but a
6799                // call that runs at import in the block itself
6800                // (`R = openai.chat.completions.create(...)`) may come
6801                // before it.
6802                if self.runs_at_import(scope) && call.start_byte() < at {
6803                    caveat = Some(ClientCaveat::ModuleSetup(feature));
6804                }
6805            }
6806            None => {
6807                if self.passes_engine(call, scope) {
6808                    routing = Routing::Unknown;
6809                    caveat = Some(ClientCaveat::ModuleConfig);
6810                }
6811            }
6812        }
6813        (routing, caveat)
6814    }
6815
6816    /// Whether `object` is a name only import statements bind at module
6817    /// level: never assigned (an alias such as `o = openai if x else y`),
6818    /// and no wildcard import or namespace write may rebind it.
6819    fn imported_only(&self, object: Node<'t>) -> bool {
6820        object.kind() == "identifier"
6821            && !self
6822                .assigns
6823                .contains_key(&(0, self.text(object).to_string()))
6824            && self.module_stars.is_empty()
6825            && !self.dynamic_globals
6826    }
6827
6828    /// Whether code in `scope` runs when the module is imported: the module
6829    /// body, a class body in it, or a list, set or dict comprehension there.
6830    fn runs_at_import(&self, scope: usize) -> bool {
6831        let mut s = scope;
6832        while s != 0 {
6833            let current = &self.scopes[s];
6834            if current.kind == ScopeKind::Function && !current.immediate {
6835                return false;
6836            }
6837            s = current.parent.unwrap_or(0);
6838        }
6839        true
6840    }
6841
6842    /// Whether `call` passes `engine` or `deployment_id`, by keyword or
6843    /// possibly through a `**` expansion. Two lookups per expansion, however
6844    /// many keys its dict has.
6845    fn passes_engine(&mut self, call: Node<'t>, scope: usize) -> bool {
6846        let args = self.arguments(call);
6847        let azure_key = |k: &str| k == "engine" || k == "deployment_id";
6848        if args.kwargs.iter().any(|k| azure_key(k)) {
6849            return true;
6850        }
6851        args.splats
6852            .iter()
6853            .any(|splat| match self.expand_splat(*splat, scope) {
6854                Some(expansion) => {
6855                    let last = &expansion.summary.last;
6856                    expansion.opaque()
6857                        || last.contains_key("engine")
6858                        || last.contains_key("deployment_id")
6859                }
6860                None => true,
6861            })
6862    }
6863
6864    fn analyze_call(&mut self, call: Node<'t>, scope: usize) {
6865        let Some(function) = call.child_by_field_name("function") else {
6866            return;
6867        };
6868
6869        if function.kind() == "identifier" && self.text(function) == "getattr" {
6870            self.check_getattr(call, scope);
6871            return;
6872        }
6873
6874        let callee = self.eval(function, scope, 0);
6875        match callee {
6876            Val::Class(class) => {
6877                self.construction(call, class);
6878                if class.family == Family::LegacyModel {
6879                    let receiver = if function.kind() == "attribute" {
6880                        Receiver::Module
6881                    } else {
6882                        Receiver::Symbol
6883                    };
6884                    let target = CallTarget {
6885                        pkg: class.pkg,
6886                        member: class.name.to_string(),
6887                        receiver,
6888                        routing: self.module_routing(class.pkg),
6889                        client_line: None,
6890                        ambiguous: false,
6891                        caveat: self.module_caveat(class.pkg).or_else(|| {
6892                            self.sdk_patched
6893                                .get(&class.pkg)
6894                                .map(|f| ClientCaveat::Dynamic(*f))
6895                        }),
6896                    };
6897                    self.record_call(call, function, scope, target);
6898                }
6899            }
6900            Val::Module { pkg, path } if !path.is_empty() => {
6901                let (routing, caveat) = self.module_target(pkg, call, scope);
6902                let target = CallTarget {
6903                    pkg,
6904                    member: path.join("."),
6905                    receiver: Receiver::Module,
6906                    routing,
6907                    client_line: None,
6908                    ambiguous: false,
6909                    caveat,
6910                };
6911                self.record_call(call, function, scope, target);
6912            }
6913            Val::Symbol { pkg, path } => {
6914                let (routing, caveat) = self.module_target(pkg, call, scope);
6915                let target = CallTarget {
6916                    pkg,
6917                    member: path.join("."),
6918                    receiver: Receiver::Symbol,
6919                    routing,
6920                    client_line: None,
6921                    ambiguous: false,
6922                    caveat,
6923                };
6924                self.record_call(call, function, scope, target);
6925            }
6926            Val::Client { client, path } if !path.is_empty() => {
6927                let client = self.reroute(client);
6928                let target = CallTarget {
6929                    pkg: client.pkg,
6930                    member: path.join("."),
6931                    receiver: Receiver::Client,
6932                    routing: client.routing,
6933                    client_line: client.line,
6934                    ambiguous: client.ambiguous,
6935                    caveat: client.caveat,
6936                };
6937                self.record_call(call, function, scope, target);
6938            }
6939            Val::Untracked(origin) => self.check_unknown_receiver(call, function, scope, origin),
6940            Val::Result(pkg) => {
6941                let origin = Origin::SdkResult { pkg };
6942                self.check_unknown_receiver(call, function, scope, origin);
6943            }
6944            _ => {}
6945        }
6946    }
6947
6948    fn record_call(
6949        &mut self,
6950        call: Node<'t>,
6951        function: Node<'t>,
6952        scope: usize,
6953        target: CallTarget,
6954    ) {
6955        let chain = self.render(function);
6956        let span = self.span(call);
6957        let symbol = self.symbol(scope);
6958        let args = self.arguments(call);
6959        let sdk = target.pkg.sdk();
6960        let member = clip_owned(strip_wrappers(&target.member));
6961        let request = is_request(&member);
6962        let model_bearing = is_model_bearing(&member);
6963
6964        // An unresolved model matters where it reaches a request, a model
6965        // object, or any call on a client or SDK module; on an SDK type
6966        // (`ChatCompletion(model=model)`) the call still lists `model` in
6967        // its kwargs, without a gap.
6968        let on_sdk_object = matches!(target.receiver, Receiver::Client | Receiver::Module)
6969            && member.split('.').next() != Some("types");
6970        let gap_worthy = request || model_bearing || on_sdk_object;
6971        let site = Site {
6972            sdk,
6973            call,
6974            chain: &chain,
6975            scope,
6976            gap_worthy,
6977        };
6978
6979        let gaps_before = self.out.gaps.len();
6980        let mut values = Vec::new();
6981        let mut keyed = false;
6982        // A keyword repeated with the same expression (a syntax error
6983        // tree-sitter accepts) is read once.
6984        let mut read_args: HashSet<(&str, &str)> = HashSet::new();
6985        for (key, expr) in &args.value_args {
6986            keyed = true;
6987            if !read_args.insert((key.as_str(), self.text(*expr))) {
6988                continue;
6989            }
6990            let result = self.resolve_value(*expr, scope, 0);
6991            self.take_value(&site, key, false, result, &mut values);
6992        }
6993
6994        // `GenerativeModel("gemini-pro")`, `genai.embed_content("models/...", text)`:
6995        // the model is positional.
6996        if !keyed {
6997            if let (Some(key), Some(first)) = (
6998                positional_model_key(target.pkg, target.receiver, &member),
6999                args.first_positional,
7000            ) {
7001                keyed = true;
7002                let result = self.resolve_value(first, scope, 0);
7003                let site = Site {
7004                    gap_worthy: true,
7005                    ..site
7006                };
7007                self.take_value(&site, key, true, result, &mut values);
7008            }
7009        }
7010
7011        // Model keys nested in literal arguments share one read budget per
7012        // call; what an expanded dict nests is read once per dict.
7013        let mut read = NestedRead::new();
7014        for (keyword, expr) in &args.literal_args {
7015            let prefix = keyword
7016                .as_ref()
7017                .map(|k| format!("{k}."))
7018                .unwrap_or_default();
7019            let place = NestedPlace {
7020                prefix: &prefix,
7021                positional: keyword.is_none(),
7022                scope,
7023                overridden: false,
7024            };
7025            self.nested_values_in(*expr, place, 0, &mut read);
7026        }
7027        let mut nested = read.found;
7028        let mut nested_overridden = read.overridden;
7029        let mut nested_cut = read.cut;
7030
7031        // `**PARAMS` where `PARAMS` is a same-file dict literal.
7032        let mut opaque_splat = false;
7033        let mut expanded: Vec<usize> = Vec::new();
7034        for splat in &args.splats {
7035            let Some(expansion) = self.expand_splat(*splat, scope) else {
7036                opaque_splat = true;
7037                continue;
7038            };
7039            opaque_splat |= expansion.opaque();
7040            // `f(**P, **P)` is a TypeError; read each dict once.
7041            if expanded.contains(&expansion.node.id()) {
7042                continue;
7043            }
7044            expanded.push(expansion.node.id());
7045            for (key, index, value) in expansion.summary.expansion.iter() {
7046                if !is_value_key(key) {
7047                    continue;
7048                }
7049                keyed = true;
7050                let label = expansion.name.as_ref().map(|n| format!("{n}[\"{key}\"]"));
7051                let mut result = self
7052                    .resolve_value(*value, expansion.scope, 0)
7053                    .map(|mut r| {
7054                        if r.origin == ValueOrigin::Literal {
7055                            r.origin = expansion.origin;
7056                            r.name = label.clone();
7057                        }
7058                        r
7059                    })
7060                    .map_err(|u| match &label {
7061                        Some(label) => u.via(label),
7062                        None => u,
7063                    });
7064                // `{"model": "gpt-4o", **overrides}`: the `**overrides` (or a
7065                // computed key) written after the entry may replace it, so
7066                // the entry is a candidate, not the value.
7067                if expansion.summary.overridable(*index) {
7068                    let shape = expansion
7069                        .name
7070                        .clone()
7071                        .unwrap_or_else(|| "{...}".to_string());
7072                    let candidates: Vec<Resolved> = result.ok().into_iter().collect();
7073                    result =
7074                        Err(Unresolved::new("splat", shape).with_candidates(candidates, false));
7075                }
7076                self.take_value(&site, key, false, result, &mut values);
7077            }
7078            let list = self.dict_nested(&expansion);
7079            nested.extend(list.found.iter().cloned());
7080            nested_overridden.extend(list.overridden.iter().cloned());
7081            nested_cut |= list.cut;
7082        }
7083        self.take_nested(&site, nested, nested_cut, &mut values);
7084        if site.gap_worthy && !nested_overridden.is_empty() {
7085            // One gap per key path, at most [`MAX_NESTED_VALUES`]; past
7086            // that, one `truncated` gap stands for the rest.
7087            let mut seen: HashSet<String> = HashSet::new();
7088            let mut cut = false;
7089            for path in nested_overridden {
7090                if seen.contains(&path) {
7091                    continue;
7092                }
7093                if seen.len() >= MAX_NESTED_VALUES {
7094                    cut = true;
7095                    break;
7096                }
7097                let unresolved = Unresolved::new("splat", "{...}".to_string());
7098                self.unresolved_gap(&site, &path, &unresolved, None);
7099                seen.insert(path);
7100            }
7101            if cut {
7102                self.out.gaps.push(UsageGap {
7103                    kind: GapKind::UnresolvedModel,
7104                    sdk: Some(site.sdk),
7105                    file: self.file.clone(),
7106                    span: Some(span),
7107                    symbol: symbol.clone(),
7108                    chain: Some(chain.clone()),
7109                    key: None,
7110                    reason: "truncated".to_string(),
7111                    detail: format!(
7112                        "`{chain}` passes more nested model values that a `**` expansion may replace than are listed ({MAX_NESTED_VALUES} listed); the rest are not reported"
7113                    ),
7114                    values: Vec::new(),
7115                    values_complete: false,
7116                });
7117            }
7118        }
7119
7120        let model_key = if member == "GenerativeModel" {
7121            "model_name"
7122        } else {
7123            "model"
7124        };
7125        if !keyed && opaque_splat && (request || model_bearing) {
7126            let unresolved = Unresolved::new("splat", "**kwargs".to_string());
7127            self.unresolved_gap(&site, model_key, &unresolved, None);
7128        } else if !keyed && model_bearing && !args.list_splat {
7129            // No model at all: the SDK's or the server's default applies,
7130            // and it may be one that retires.
7131            let unresolved = Unresolved::new("missing_model", String::new());
7132            self.unresolved_gap(&site, model_key, &unresolved, None);
7133        }
7134
7135        if target.ambiguous {
7136            self.out.gaps.push(UsageGap {
7137                kind: GapKind::AmbiguousClient,
7138                sdk: Some(sdk),
7139                file: self.file.clone(),
7140                span: Some(span),
7141                symbol: symbol.clone(),
7142                chain: Some(chain.clone()),
7143                key: None,
7144                reason: "multiple_assignments".to_string(),
7145                detail: format!(
7146                    "the receiver of `{chain}` is assigned more than one kind of client or a non-client value, so its routing depends on a runtime branch"
7147                ),
7148                values: Vec::new(),
7149                values_complete: false,
7150            });
7151        } else if let Some(caveat) = &target.caveat {
7152            let (reason, detail) = match caveat {
7153                ClientCaveat::InFileCallers { param } => (
7154                    "in_file_callers",
7155                    format!(
7156                        "the receiver of `{chain}` is parameter `{param}`: every caller in this file passes the same client, but other modules may call the function with another one"
7157                    ),
7158                ),
7159                ClientCaveat::ParameterDefault { param, unseen: false } => (
7160                    "parameter_default",
7161                    format!(
7162                        "the receiver of `{chain}` is the default of parameter `{param}`, but other modules may call the function with another client"
7163                    ),
7164                ),
7165                ClientCaveat::ParameterDefault { param, unseen: true } => (
7166                    "unseen_callers",
7167                    format!(
7168                        "the receiver of `{chain}` is the default of parameter `{param}`, but the function is decorated, passed or stored, so a caller this file does not show may pass another client"
7169                    ),
7170                ),
7171                ClientCaveat::BaseUrlAssigned => (
7172                    "base_url_assigned",
7173                    format!(
7174                        "the client behind `{chain}` is given a `base_url` after it is built, so its requests may go to another endpoint"
7175                    ),
7176                ),
7177                ClientCaveat::EndpointEnv { var } => (
7178                    "endpoint_env",
7179                    format!(
7180                        "this file sets `{var}`, which the SDK reads its endpoint from, so `{chain}` may send its requests elsewhere"
7181                    ),
7182                ),
7183                ClientCaveat::EnvWrite(feature) => (
7184                    "dynamic_feature",
7185                    format!(
7186                        "this file may set the SDK's endpoint variable ({}), so `{chain}` may send its requests elsewhere",
7187                        feature.describe()
7188                    ),
7189                ),
7190                ClientCaveat::BaseUrl {
7191                    env: true,
7192                    fallback: true,
7193                } => (
7194                    "base_url_env",
7195                    format!(
7196                        "the `base_url` of the client behind `{chain}` is read from the environment and falls back to another host, so the deployment may point it anywhere"
7197                    ),
7198                ),
7199                ClientCaveat::EndpointOption { option } => (
7200                    "endpoint_option",
7201                    format!(
7202                        "the client behind `{chain}` is configured with {option}, which may send its requests to Vertex AI or another endpoint"
7203                    ),
7204                ),
7205                ClientCaveat::BaseUrl { env: true, .. } => (
7206                    "base_url_env",
7207                    format!(
7208                        "the `base_url` of the client behind `{chain}` is read from the environment with no fallback, so its endpoint is not known"
7209                    ),
7210                ),
7211                ClientCaveat::BaseUrl { fallback: true, .. } => (
7212                    "base_url_env",
7213                    format!(
7214                        "the `base_url` of the client behind `{chain}` falls back to the provider's own host, but the environment may set another"
7215                    ),
7216                ),
7217                ClientCaveat::BaseUrl { .. } => (
7218                    "base_url_unresolved",
7219                    format!(
7220                        "the `base_url` of the client behind `{chain}` does not resolve to a string in this file, so its endpoint is not known"
7221                    ),
7222                ),
7223                ClientCaveat::Dynamic(feature) => (
7224                    "dynamic_feature",
7225                    format!(
7226                        "the receiver of `{chain}` may be rebound or replaced at run time: {}",
7227                        feature.describe()
7228                    ),
7229                ),
7230                ClientCaveat::ModuleSetup(feature) => (
7231                    "module_config",
7232                    format!(
7233                        "the module-level API's routing is not configured by a top-of-file setup block ({}), so it may not hold when `{chain}` runs",
7234                        feature.describe()
7235                    ),
7236                ),
7237                ClientCaveat::ModuleConfig => (
7238                    "module_config",
7239                    format!(
7240                        "`{chain}` passes `engine` or `deployment_id`, which Azure deployments take, but this file does not configure the module-level API, so another module may route it to Azure"
7241                    ),
7242                ),
7243            };
7244            self.out.gaps.push(UsageGap {
7245                kind: GapKind::AmbiguousClient,
7246                sdk: Some(sdk),
7247                file: self.file.clone(),
7248                span: Some(span),
7249                symbol: symbol.clone(),
7250                chain: Some(chain.clone()),
7251                key: None,
7252                reason: reason.to_string(),
7253                detail,
7254                values: Vec::new(),
7255                values_complete: false,
7256            });
7257        } else if let Some(feature) = self.file_dynamic {
7258            // Anything in this file may be rebound, the receiver and the
7259            // SDK's configuration included.
7260            self.out.gaps.push(UsageGap {
7261                kind: GapKind::AmbiguousClient,
7262                sdk: Some(sdk),
7263                file: self.file.clone(),
7264                span: Some(span),
7265                symbol: symbol.clone(),
7266                chain: Some(chain.clone()),
7267                key: None,
7268                reason: "dynamic_feature".to_string(),
7269                detail: format!(
7270                    "this file may rebind any name or attribute at run time ({}), so the routing of `{chain}` is not confirmed",
7271                    feature.describe()
7272                ),
7273                values: Vec::new(),
7274                values_complete: false,
7275            });
7276        }
7277
7278        // The same value or gap reached twice (one dict expanded twice, one
7279        // fallback behind two names) is listed once.
7280        let mut seen_values = HashSet::new();
7281        values.retain(|v| seen_values.insert((v.key.clone(), v.span.start_byte, v.value.clone())));
7282        let mut seen_gaps = HashSet::new();
7283        for gap in self.out.gaps.split_off(gaps_before) {
7284            if seen_gaps.insert((
7285                gap.kind,
7286                gap.key.clone(),
7287                gap.reason.clone(),
7288                gap.detail.clone(),
7289            )) {
7290                self.out.gaps.push(gap);
7291            }
7292        }
7293
7294        self.out.calls.push(SdkCall {
7295            sdk,
7296            package: target.pkg.package().to_string(),
7297            chain,
7298            request,
7299            member,
7300            receiver: target.receiver,
7301            routing: target.routing,
7302            client_line: target.client_line,
7303            file: self.file.clone(),
7304            span,
7305            symbol,
7306            kwargs: args.kwargs,
7307            positional: args.positional,
7308            splat: args.splat,
7309            values,
7310        });
7311    }
7312
7313    /// Attaches a resolved value to `key`, or reports why it did not
7314    /// resolve. A fallback captured from an environment or config lookup is
7315    /// both a value and a gap.
7316    fn take_value(
7317        &mut self,
7318        site: &Site<'_, 't>,
7319        key: &str,
7320        positional: bool,
7321        result: Result<Resolved, Unresolved>,
7322        values: &mut Vec<CapturedValue>,
7323    ) {
7324        // In a file that may rebind anything at run time, only a value
7325        // written at the call itself is confirmed.
7326        let result = result.map(|mut resolved| {
7327            let flagged = resolved
7328                .caveats
7329                .iter()
7330                .any(|c| c.reason == "dynamic_feature");
7331            if let (Some(feature), false) = (self.file_dynamic, flagged) {
7332                if !within(site.call, resolved.span) {
7333                    let name = resolved.name.clone().unwrap_or_else(|| key.to_string());
7334                    resolved
7335                        .caveats
7336                        .push(Unresolved::dynamic(feature).via(&name));
7337                }
7338            }
7339            resolved
7340        });
7341        match result {
7342            // A value whose gap cannot be reported here (an SDK type such as
7343            // `ChatCompletion(model=os.getenv(...))`) is not captured: it
7344            // would read as confirmed.
7345            Ok(resolved) if !resolved.caveats.is_empty() && !site.gap_worthy => {}
7346            Ok(mut resolved) => {
7347                let caveats = std::mem::take(&mut resolved.caveats);
7348                let origin = resolved.origin;
7349                values.push(captured(key, resolved, positional));
7350                for caveat in &caveats {
7351                    self.unresolved_gap(site, key, caveat, Some(origin));
7352                }
7353            }
7354            Err(unresolved) if site.gap_worthy => self.unresolved_gap(site, key, &unresolved, None),
7355            Err(_) => {}
7356        }
7357    }
7358
7359    /// Attaches nested model values, at most [`MAX_NESTED_VALUES`] per call
7360    /// and [`MAX_FILE_NESTED_VALUES`] per file. Values cut by either limit,
7361    /// or a read cut short after model values were found, leave a
7362    /// `truncated` gap: the call may carry values the report does not list.
7363    fn take_nested(
7364        &mut self,
7365        site: &Site<'_, 't>,
7366        nested: Vec<NestedValue>,
7367        read_cut: bool,
7368        values: &mut Vec<CapturedValue>,
7369    ) {
7370        if nested.is_empty() {
7371            return;
7372        }
7373        let mut seen: HashSet<(u32, String)> = HashSet::new();
7374        let mut listed = 0;
7375        let mut dropped = false;
7376        for item in nested {
7377            if !seen.insert((item.resolved.span.start_byte, item.path.clone())) {
7378                continue;
7379            }
7380            if listed >= MAX_NESTED_VALUES || self.nested_left == 0 {
7381                dropped = true;
7382                continue;
7383            }
7384            listed += 1;
7385            self.nested_left -= 1;
7386            self.take_value(site, &item.path, item.positional, Ok(item.resolved), values);
7387        }
7388        if (dropped || read_cut) && site.gap_worthy {
7389            let chain = site.chain;
7390            self.out.gaps.push(UsageGap {
7391                kind: GapKind::UnresolvedModel,
7392                sdk: Some(site.sdk),
7393                file: self.file.clone(),
7394                span: Some(self.span(site.call)),
7395                symbol: self.symbol(site.scope),
7396                chain: Some(chain.to_string()),
7397                key: None,
7398                reason: "truncated".to_string(),
7399                detail: format!(
7400                    "`{chain}` passes more nested model values than are read or listed ({listed} listed); the rest are not reported"
7401                ),
7402                values: Vec::new(),
7403                values_complete: false,
7404            });
7405        }
7406    }
7407
7408    /// An `unresolved_model` gap for `key` at `site`. `captured` is the
7409    /// origin of the value captured next to it, when the gap is that
7410    /// value's caveat.
7411    fn unresolved_gap(
7412        &mut self,
7413        site: &Site<'_, 't>,
7414        key: &str,
7415        unresolved: &Unresolved,
7416        captured: Option<ValueOrigin>,
7417    ) {
7418        let chain = site.chain;
7419        let phrase = unresolved.phrase();
7420        let shape = &unresolved.shape;
7421        let mut detail = match unresolved.via.as_deref() {
7422            _ if unresolved.reason == "splat" && shape != "**kwargs" => format!(
7423                "`{key}` for `{chain}` is set in a dict (`{shape}`) where a `**` expansion or a computed key written after it may replace it"
7424            ),
7425            _ if unresolved.reason == "splat" => {
7426                format!("`{key}` for `{chain}` is not passed by name and may come from `**kwargs`")
7427            }
7428            _ if unresolved.reason == "missing_model" => {
7429                format!("`{key}` for `{chain}` is not passed, so the SDK or server default applies")
7430            }
7431            Some(via) if unresolved.reason == "dynamic_feature" => format!(
7432                "`{key}` for `{chain}` comes from `{via}`, which may change at run time: {shape}"
7433            ),
7434            None if unresolved.reason == "dynamic_feature" => {
7435                format!("`{key}` for `{chain}` may change at run time: {shape}")
7436            }
7437            Some(via) if !shape.is_empty() && via != shape => {
7438                format!("`{key}` for `{chain}` comes from `{via}`, which is {phrase} (`{shape}`)")
7439            }
7440            Some(via) => format!("`{key}` for `{chain}` comes from `{via}`, which is {phrase}"),
7441            None => format!("`{key}` for `{chain}` is `{shape}`, which is {phrase}"),
7442        };
7443        let (values, cut) = self.candidate_values(key, &unresolved.candidates);
7444        // A file that may rebind anything at run time can complete a list
7445        // only with literals written at the call.
7446        let rebinding = self.file_dynamic.is_some()
7447            && !unresolved
7448                .candidates
7449                .iter()
7450                .all(|c| within(site.call, c.span));
7451        let complete = unresolved.complete() && !cut && !rebinding;
7452        let listed = if complete {
7453            "every other value it may take is listed"
7454        } else {
7455            "some values it may take are listed, not necessarily all"
7456        };
7457        match captured {
7458            Some(origin) if unresolved.reason == "parameter_overridden" => {
7459                detail.push_str(&format!(
7460                    "; its default is captured with origin `{}`",
7461                    origin.as_str()
7462                ));
7463                if complete {
7464                    detail.push_str(", and every other value in-file callers pass is listed");
7465                } else if !values.is_empty() {
7466                    detail
7467                        .push_str(", and some values callers pass are listed, not necessarily all");
7468                }
7469            }
7470            Some(origin) if unresolved.reason == "unseen_callers" => {
7471                detail.push_str(&format!(
7472                    "; its default is captured with origin `{}`",
7473                    origin.as_str()
7474                ));
7475                if !values.is_empty() {
7476                    detail.push_str(
7477                        ", and some values in-file calls pass are listed, not necessarily all",
7478                    );
7479                }
7480            }
7481            Some(origin) if unresolved.reason == "parameter_default" => {
7482                detail.push_str(&format!(
7483                    "; its default is captured with origin `{}`",
7484                    origin.as_str()
7485                ));
7486            }
7487            Some(origin) if unresolved.reason == "dynamic_feature" => {
7488                detail.push_str(&format!(
7489                    "; its value is captured with origin `{}`",
7490                    origin.as_str()
7491                ));
7492            }
7493            Some(_) => {
7494                detail.push_str("; its literal fallback is captured with origin `env_default`");
7495                if !values.is_empty() {
7496                    detail.push_str(&format!(", and {listed}"));
7497                }
7498            }
7499            None if complete => detail.push_str("; every value it may take is listed"),
7500            None if !values.is_empty() => detail.push_str(&format!("; {listed}")),
7501            None => {}
7502        }
7503        self.out.gaps.push(UsageGap {
7504            kind: GapKind::UnresolvedModel,
7505            sdk: Some(site.sdk),
7506            file: self.file.clone(),
7507            span: Some(self.span(site.call)),
7508            symbol: self.symbol(site.scope),
7509            chain: Some(chain.to_string()),
7510            key: Some(key.to_string()),
7511            reason: unresolved.reason.to_string(),
7512            detail,
7513            values_complete: complete && !values.is_empty(),
7514            values,
7515        });
7516    }
7517
7518    /// Candidate values listed with a gap for `key`: distinct, at most
7519    /// [`MAX_CANDIDATES`] per gap and [`MAX_FILE_CANDIDATES`] per file; and
7520    /// whether a limit cut the list.
7521    fn candidate_values(
7522        &mut self,
7523        key: &str,
7524        candidates: &[Resolved],
7525    ) -> (Vec<CapturedValue>, bool) {
7526        let mut seen = HashSet::new();
7527        let mut listed = Vec::new();
7528        for candidate in candidates {
7529            if !seen.insert(candidate.value.as_str()) {
7530                continue;
7531            }
7532            if listed.len() >= MAX_CANDIDATES || self.candidates_left == 0 {
7533                return (listed, true);
7534            }
7535            self.candidates_left -= 1;
7536            let mut candidate = candidate.clone();
7537            candidate.caveats.clear();
7538            listed.push(captured(key, candidate, false));
7539        }
7540        (listed, false)
7541    }
7542
7543    /// `getattr(client, name)` on a tracked binding.
7544    fn check_getattr(&mut self, call: Node<'t>, scope: usize) {
7545        let Some(args) = call.child_by_field_name("arguments") else {
7546            return;
7547        };
7548        let Some(first) = args
7549            .named_child(0)
7550            .filter(|a| a.kind() != "keyword_argument")
7551        else {
7552            return;
7553        };
7554        let target = self.eval(first, scope, 0);
7555        if !target.is_tracked() {
7556            return;
7557        }
7558        let rendered = self.render(first);
7559        self.out.gaps.push(UsageGap {
7560            kind: GapKind::DynamicDispatch,
7561            sdk: target.pkg().map(Pkg::sdk),
7562            file: self.file.clone(),
7563            span: Some(self.span(call)),
7564            symbol: self.symbol(scope),
7565            chain: Some(format!("getattr({rendered}, ...)")),
7566            key: None,
7567            reason: "getattr".to_string(),
7568            detail: format!(
7569                "`getattr` on `{rendered}` picks the SDK member at run time; calls through it are not tracked"
7570            ),
7571            values: Vec::new(),
7572            values_complete: false,
7573        });
7574    }
7575
7576    /// An SDK-shaped call on a receiver that is not a tracked client.
7577    fn check_unknown_receiver(
7578        &mut self,
7579        call: Node<'t>,
7580        function: Node<'t>,
7581        scope: usize,
7582        origin: Origin,
7583    ) {
7584        // Every SDK shape has a member: a bare name never matches.
7585        if function.kind() == "identifier" || sdk_shape(&self.render_links(function, 8)).is_none() {
7586            return;
7587        }
7588        let chain = self.render(function);
7589        let Some((shape_sdk, strong)) = sdk_shape(&chain) else {
7590            return;
7591        };
7592        if !strong && !self.sdk_imported.contains(&shape_sdk) {
7593            return;
7594        }
7595        let root = chain_root(&chain);
7596        let (reason, detail, sdk) = match &origin {
7597            Origin::Factory { callee, wraps } => (
7598                "factory_call",
7599                format!("`{root}` comes from `{callee}`, which is not a tracked SDK constructor"),
7600                wraps.map(Pkg::sdk).unwrap_or(shape_sdk),
7601            ),
7602            Origin::Parameter { name } => (
7603                "parameter",
7604                format!("`{root}` comes from parameter `{name}`, which has no SDK type annotation and no in-file caller that passes a known client"),
7605                shape_sdk,
7606            ),
7607            Origin::Imported { module } => (
7608                "imported_name",
7609                format!("`{root}` is imported from `{module}`; cross-file resolution is not in this version"),
7610                shape_sdk,
7611            ),
7612            Origin::UnassignedAttribute { name } => (
7613                "unassigned_attribute",
7614                format!("`{root}` is never assigned in this class (`{name}`)"),
7615                shape_sdk,
7616            ),
7617            Origin::SdkResult { pkg } => (
7618                "sdk_call_result",
7619                format!("`{root}` is returned by an SDK call that is not a known client constructor"),
7620                pkg.map(Pkg::sdk).unwrap_or(shape_sdk),
7621            ),
7622            Origin::Unbound => (
7623                "unbound",
7624                format!("`{root}` is not assigned in this file"),
7625                shape_sdk,
7626            ),
7627            Origin::Dynamic(feature) => (
7628                "dynamic_feature",
7629                format!(
7630                    "the receiver of `{chain}` may be rebound or replaced at run time: {}",
7631                    feature.describe()
7632                ),
7633                shape_sdk,
7634            ),
7635            _ => (
7636                "unresolved_receiver",
7637                format!("the receiver of `{chain}` could not be resolved"),
7638                shape_sdk,
7639            ),
7640        };
7641
7642        let args = self.arguments(call);
7643        let mut values = Vec::new();
7644        for (key, expr) in &args.value_args {
7645            if let Ok(resolved) = self.resolve_value(*expr, scope, 0) {
7646                values.push(captured(key, resolved, false));
7647            }
7648        }
7649        self.out.gaps.push(UsageGap {
7650            kind: GapKind::UnknownClientFactory,
7651            sdk: Some(sdk),
7652            file: self.file.clone(),
7653            span: Some(self.span(call)),
7654            symbol: self.symbol(scope),
7655            chain: Some(chain),
7656            key: None,
7657            reason: reason.to_string(),
7658            detail,
7659            values,
7660            values_complete: false,
7661        });
7662    }
7663
7664    /// An SDK request method used as a value (`create = client.chat.completions.create`).
7665    fn analyze_reference(&mut self, reference: Node<'t>, scope: usize) {
7666        let val = self.eval(reference, scope, 0);
7667        if !val.is_tracked() {
7668            return;
7669        }
7670        let Some(last) = val.path().last() else {
7671            return;
7672        };
7673        if !REQUEST_METHODS.contains(&last.as_str()) {
7674            return;
7675        }
7676        let rendered = self.render(reference);
7677        self.out.gaps.push(UsageGap {
7678            kind: GapKind::DynamicDispatch,
7679            sdk: val.pkg().map(Pkg::sdk),
7680            file: self.file.clone(),
7681            span: Some(self.span(reference)),
7682            symbol: self.symbol(scope),
7683            chain: Some(rendered.clone()),
7684            key: None,
7685            reason: "method_reference".to_string(),
7686            detail: format!(
7687                "`{rendered}` is stored or passed as a value; calls through it are not tracked"
7688            ),
7689            values: Vec::new(),
7690            values_complete: false,
7691        });
7692    }
7693
7694    // ------------------------------------------------------------------
7695    // Arguments and values
7696    // ------------------------------------------------------------------
7697
7698    fn arguments(&self, call: Node<'t>) -> Args<'t> {
7699        let mut args = Args::default();
7700        let Some(list) = call.child_by_field_name("arguments") else {
7701            return args;
7702        };
7703        if list.kind() != "argument_list" {
7704            // A bare generator argument: `f(x for x in y)`.
7705            args.positional = 1;
7706            return args;
7707        }
7708        for arg in named_children(list) {
7709            match arg.kind() {
7710                "keyword_argument" => {
7711                    let Some(name) = arg.child_by_field_name("name") else {
7712                        continue;
7713                    };
7714                    let name = self.text(name).to_string();
7715                    if let Some(value) = arg.child_by_field_name("value") {
7716                        if is_value_key(&name) {
7717                            args.value_args.push((name.clone(), value));
7718                        } else if is_container(value) && !is_secret_key(&name) {
7719                            args.literal_args.push((Some(name.clone()), value));
7720                        }
7721                    }
7722                    args.kwargs.push(name);
7723                }
7724                "dictionary_splat" => {
7725                    args.splat = true;
7726                    if let Some(inner) = arg.named_child(0) {
7727                        args.splats.push(inner);
7728                    }
7729                }
7730                "list_splat" => args.list_splat = true,
7731                "comment" => {}
7732                _ => {
7733                    if args.positional == 0 {
7734                        args.first_positional = Some(arg);
7735                    }
7736                    if is_container(arg) {
7737                        args.literal_args.push((None, arg));
7738                    }
7739                    args.positional += 1;
7740                }
7741            }
7742        }
7743        args
7744    }
7745
7746    /// What the containers in a dict literal's `**` expansion nest
7747    /// (`**{"extra_body": {"model": ...}}`), read once per dict with one
7748    /// budget and reused by every call that expands it.
7749    fn dict_nested(&mut self, expansion: &Expansion<'t>) -> Rc<NestedList> {
7750        if let Some(list) = self.dict_nested.get(&expansion.node.id()) {
7751            return Rc::clone(list);
7752        }
7753        let mut read = NestedRead::new();
7754        for (key, index, value) in expansion.summary.expansion.iter() {
7755            if !is_value_key(key) && is_container(*value) {
7756                let prefix = format!("{key}.");
7757                let place = NestedPlace {
7758                    prefix: &prefix,
7759                    positional: false,
7760                    scope: expansion.scope,
7761                    overridden: expansion.summary.overridable(*index),
7762                };
7763                self.nested_values_in(*value, place, 0, &mut read);
7764            }
7765        }
7766        let list = Rc::new(NestedList {
7767            found: read.found,
7768            overridden: read.overridden,
7769            cut: read.cut,
7770        });
7771        self.dict_nested
7772            .insert(expansion.node.id(), Rc::clone(&list));
7773        list
7774    }
7775
7776    /// Allowlisted keys inside dict literals passed to a call
7777    /// (`fallbacks=[{"model": "claude-opus-4-8"}]`). Only identifier-shaped
7778    /// keys are followed and only keys [`is_value_key`] accepts are read; an
7779    /// unresolvable nested value is skipped, not reported, because the
7780    /// argument may not configure the request at all. A dict keeps the last
7781    /// entry of each key, as Python does, and an entry that a later `**`
7782    /// expansion or computed key may replace (or one inside such an entry,
7783    /// `place.overridden`) is listed in `read.overridden` instead of read.
7784    /// `read` bounds the entries read (see [`MAX_NESTED_ENTRIES`]).
7785    fn nested_values_in(
7786        &mut self,
7787        node: Node<'t>,
7788        place: NestedPlace<'_>,
7789        depth: u32,
7790        read: &mut NestedRead,
7791    ) {
7792        if depth > 4 {
7793            return;
7794        }
7795        let mut cursor = node.walk();
7796        match node.kind() {
7797            "dictionary" => {
7798                // Read once per literal (memoized), like any dict lookup.
7799                let summary = self.dict_summary(node);
7800                // Indexes as `dict_entries` counts them: every named child
7801                // but comments.
7802                let mut index = 0;
7803                for pair in node.named_children(&mut cursor) {
7804                    if pair.kind() == "comment" {
7805                        continue;
7806                    }
7807                    let at = index;
7808                    index += 1;
7809                    if read.left == 0 {
7810                        read.cut = true;
7811                        return;
7812                    }
7813                    read.left -= 1;
7814                    if pair.kind() != "pair" {
7815                        continue;
7816                    }
7817                    let (Some(key), Some(value)) = (
7818                        pair.child_by_field_name("key"),
7819                        pair.child_by_field_name("value"),
7820                    ) else {
7821                        continue;
7822                    };
7823                    let Ok(key) = self.literal(key) else {
7824                        continue;
7825                    };
7826                    // Nothing under a credential-shaped or non-identifier key
7827                    // is read, at any depth (`extra_headers={"auth": {...}}`).
7828                    if !is_identifier_key(&key) {
7829                        continue;
7830                    }
7831                    // `{"model": "a", "model": "b"}` sends `b`: an earlier
7832                    // entry of a key is discarded.
7833                    if summary.last.get(&key).is_some_and(|(last, _)| *last != at) {
7834                        continue;
7835                    }
7836                    let overridden = place.overridden || summary.overridable(at);
7837                    let path = format!("{}{key}", place.prefix);
7838                    if is_value_key(&key) {
7839                        if overridden {
7840                            read.overridden.push(path);
7841                        } else if let Ok(resolved) = self.resolve_value(value, place.scope, 0) {
7842                            read.found.push(NestedValue {
7843                                path,
7844                                positional: place.positional,
7845                                resolved,
7846                            });
7847                        }
7848                    } else if is_container(value) {
7849                        let nested = format!("{path}.");
7850                        let inner = NestedPlace {
7851                            prefix: &nested,
7852                            overridden,
7853                            ..place
7854                        };
7855                        self.nested_values_in(value, inner, depth + 1, read);
7856                    }
7857                }
7858            }
7859            "list" | "tuple" | "set" | "parenthesized_expression" => {
7860                for item in node.named_children(&mut cursor) {
7861                    if read.left == 0 {
7862                        read.cut = true;
7863                        return;
7864                    }
7865                    read.left -= 1;
7866                    self.nested_values_in(item, place, depth + 1, read);
7867                }
7868            }
7869            _ => {}
7870        }
7871    }
7872
7873    /// A plain string literal's value. `Err` carries the reason it is not.
7874    /// A literal longer than [`MAX_LITERAL_BYTES`] is never read.
7875    fn literal(&self, node: Node<'t>) -> Result<String, &'static str> {
7876        if node.end_byte() - node.start_byte() > MAX_LITERAL_BYTES {
7877            return Err("non_literal");
7878        }
7879        match node.kind() {
7880            "string" => {
7881                let mut value = String::new();
7882                for part in children(node) {
7883                    match part.kind() {
7884                        "string_start" => {
7885                            let prefix = self.text(part).to_ascii_lowercase();
7886                            if prefix.contains('b') {
7887                                return Err("non_literal");
7888                            }
7889                        }
7890                        "string_content" => value.push_str(self.text(part)),
7891                        "interpolation" => return Err("f_string"),
7892                        _ => {}
7893                    }
7894                }
7895                if value.contains('\\') {
7896                    return Err("non_literal");
7897                }
7898                Ok(value)
7899            }
7900            "concatenated_string" => {
7901                let mut value = String::new();
7902                for part in named_children(node) {
7903                    value.push_str(&self.literal(part)?);
7904                }
7905                Ok(value)
7906            }
7907            _ => Err("non_literal"),
7908        }
7909    }
7910
7911    fn resolve_value(
7912        &mut self,
7913        expr: Node<'t>,
7914        scope: usize,
7915        depth: u32,
7916    ) -> Result<Resolved, Unresolved> {
7917        if depth > 16 {
7918            return Err(Unresolved::new("non_literal", self.render(expr)));
7919        }
7920        stacker::maybe_grow(64 * 1024, 2 * 1024 * 1024, || {
7921            self.resolve_value_inner(expr, scope, depth)
7922        })
7923    }
7924
7925    fn resolve_value_inner(
7926        &mut self,
7927        expr: Node<'t>,
7928        scope: usize,
7929        depth: u32,
7930    ) -> Result<Resolved, Unresolved> {
7931        match expr.kind() {
7932            "string" | "concatenated_string" => match self.literal(expr) {
7933                Ok(value) if is_capturable_value(&value) => Ok(Resolved {
7934                    value,
7935                    origin: ValueOrigin::Literal,
7936                    name: None,
7937                    span: self.span(expr),
7938                    caveats: Vec::new(),
7939                }),
7940                Ok(value) if is_credential_value(&value) => {
7941                    Err(Unresolved::new("credential", self.render(expr)))
7942                }
7943                Ok(_) => Err(Unresolved::new("non_literal", self.render(expr))),
7944                Err(reason) => Err(Unresolved::new(reason, self.render(expr))),
7945            },
7946            "parenthesized_expression" => match expr.named_child(0) {
7947                Some(inner) => self.resolve_value(inner, scope, depth + 1),
7948                None => Err(Unresolved::new("non_literal", self.render(expr))),
7949            },
7950            "identifier" => {
7951                let name = self.text(expr).to_string();
7952                self.resolve_constant(&name, scope, expr.start_byte(), depth)
7953            }
7954            "attribute" => {
7955                let rendered = self.render(expr);
7956                if let (Some(object), Some(attr)) = (
7957                    expr.child_by_field_name("object"),
7958                    expr.child_by_field_name("attribute"),
7959                ) {
7960                    let attr = self.text(attr).to_string();
7961                    // `self.secret`, `ApiKeys.openai`, `cfg.credentials.model`.
7962                    if is_secret_key(&attr) || self.chain_has_secret_name(object) {
7963                        return Err(Unresolved::new("credential", rendered));
7964                    }
7965                    if let Some(feature) = self.rebound_receiver(object, scope) {
7966                        return Err(Unresolved::dynamic(feature).via(&rendered));
7967                    }
7968                    if let Some((class, through_self)) = self.class_receiver(object, scope) {
7969                        let lookup = self.attr_lookup(class, &attr, through_self);
7970                        let assigns = Rc::clone(&lookup.assigns);
7971                        let dynamic = lookup.dynamic;
7972                        // Nothing the grammar reads, and a dynamic feature
7973                        // that may set it.
7974                        if let (true, Some(feature)) = (assigns.is_empty(), dynamic) {
7975                            return Err(Unresolved::dynamic(feature).via(&rendered));
7976                        }
7977                        let only = match assigns.as_ref() {
7978                            [assign] => Some(*assign),
7979                            _ => None,
7980                        };
7981                        return match self.single_constant(
7982                            only,
7983                            assigns.len(),
7984                            ValueOrigin::ClassConstant,
7985                            depth,
7986                        ) {
7987                            Ok(resolved) => {
7988                                let mut resolved =
7989                                    resolved.through(&rendered, ValueOrigin::ClassConstant);
7990                                if let Some(feature) = dynamic {
7991                                    resolved
7992                                        .caveats
7993                                        .push(Unresolved::dynamic(feature).via(&rendered));
7994                                } else if through_self && self.may_be_subclassed_elsewhere(class) {
7995                                    // Other modules may subclass a public
7996                                    // class (or a private one's public
7997                                    // subclass) and set the attribute (rule
7998                                    // 3, like a public function's default).
7999                                    resolved
8000                                        .caveats
8001                                        .push(Unresolved::new("subclass_override", rendered));
8002                                }
8003                                Ok(resolved)
8004                            }
8005                            Err(unresolved) if unresolved.reason == "reassigned" => {
8006                                let (candidates, complete) = self.assign_candidates(
8007                                    &assigns,
8008                                    ValueOrigin::ClassConstant,
8009                                    &rendered,
8010                                    depth,
8011                                );
8012                                // Complete only for assignments in one
8013                                // scope (a class body's branches), with no
8014                                // dynamic feature (P4).
8015                                let one_scope = assigns.iter().all(|a| a.scope == assigns[0].scope);
8016                                Err(unresolved.via(&rendered).with_candidates(
8017                                    candidates,
8018                                    complete && one_scope && dynamic.is_none(),
8019                                ))
8020                            }
8021                            Err(unresolved) if dynamic.is_some() => {
8022                                Err(unresolved.via(&rendered).incomplete())
8023                            }
8024                            Err(unresolved) => Err(unresolved.via(&rendered)),
8025                        };
8026                    }
8027                }
8028                let reason = if self.contains_env(expr) {
8029                    "env_var"
8030                } else {
8031                    "attribute"
8032                };
8033                Err(Unresolved::new(reason, rendered))
8034            }
8035            "call" => {
8036                if let Some(result) = self.fallback_value(expr, scope, depth) {
8037                    return result;
8038                }
8039                let reason = if self.contains_env(expr) {
8040                    "env_var"
8041                } else {
8042                    "function_call"
8043                };
8044                Err(Unresolved::new(reason, self.render(expr)))
8045            }
8046            "subscript" => {
8047                if let Some(result) = self.subscript_value(expr, scope, depth) {
8048                    return result;
8049                }
8050                let reason = if self.contains_env(expr) {
8051                    "env_var"
8052                } else {
8053                    "subscript"
8054                };
8055                // `MODELS[os.getenv("TIER")]`: the dict's values are the
8056                // candidates.
8057                let unresolved = Unresolved::new(reason, self.render(expr));
8058                let dict = expr
8059                    .child_by_field_name("value")
8060                    .and_then(|base| self.dict_node(base, scope, 0));
8061                Err(match dict {
8062                    Some(dict) => {
8063                        let found = self.dict_candidates(&dict);
8064                        unresolved.with_candidates(found.values.clone(), found.complete)
8065                    }
8066                    None => unresolved,
8067                })
8068            }
8069            "boolean_operator" => {
8070                if let Some(result) = self.or_fallback(expr, scope, depth) {
8071                    return result;
8072                }
8073                let reason = if self.contains_env(expr) {
8074                    "env_var"
8075                } else {
8076                    "conditional"
8077                };
8078                Err(Unresolved::new(reason, self.render(expr)))
8079            }
8080            "conditional_expression" => {
8081                let reason = if self.contains_env(expr) {
8082                    "env_var"
8083                } else {
8084                    "conditional"
8085                };
8086                // `"gpt-4o" if fast else "o1"`: each side is a candidate.
8087                let (candidates, complete) = self.branch_candidates(expr, scope, depth);
8088                Err(Unresolved::new(reason, self.render(expr))
8089                    .with_candidates(candidates, complete))
8090            }
8091            _ => Err(Unresolved::new("non_literal", self.render(expr))),
8092        }
8093    }
8094
8095    /// Whether a name written in the attribute chain `node` looks like a
8096    /// credential's (`ApiKeys` in `ApiKeys.openai`, `keys` in
8097    /// `cfg.keys.openai`). `self` and `cls` are not names of their own.
8098    fn chain_has_secret_name(&self, node: Node<'t>) -> bool {
8099        let mut node = node;
8100        for _ in 0..MAX_DEPTH {
8101            match node.kind() {
8102                "identifier" => return is_secret_key(self.text(node)),
8103                "attribute" => {
8104                    let secret = node
8105                        .child_by_field_name("attribute")
8106                        .is_some_and(|a| is_secret_key(self.text(a)));
8107                    match node.child_by_field_name("object") {
8108                        Some(object) if !secret => node = object,
8109                        _ => return secret,
8110                    }
8111                }
8112                _ => return false,
8113            }
8114        }
8115        false
8116    }
8117
8118    fn resolve_constant(
8119        &mut self,
8120        name: &str,
8121        scope: usize,
8122        pos: usize,
8123        depth: u32,
8124    ) -> Result<Resolved, Unresolved> {
8125        // A value that flows through a secret-named binding is never read.
8126        if is_secret_key(name) {
8127            return Err(Unresolved::new("credential", name.to_string()));
8128        }
8129        let (key, defs) = self.defs_at(name, scope, pos);
8130        let home = key.0;
8131        let imported = defs.imported;
8132        if defs.param {
8133            if defs.assigns > 0 || imported {
8134                // The parameter's own values are not listed: partial.
8135                let origin = constant_origin(self.scopes[home].kind);
8136                let (candidates, _) = self.name_candidates(name, scope, pos, origin, depth);
8137                return Err(Unresolved::new("reassigned", name.to_string())
8138                    .with_candidates(candidates, false));
8139            }
8140            let default = self.params.get(&key).and_then(|p| p.default);
8141            let Some(default) = default else {
8142                // What in-file callers pass, for triage.
8143                let passed = self.caller_models(home, name);
8144                return Err(Unresolved::new("parameter", name.to_string())
8145                    .with_candidates(passed.values.clone(), passed.complete));
8146            };
8147            // Defaults are evaluated where the function is defined.
8148            let parent = self.scopes[home].parent.unwrap_or(0);
8149            return match self.resolve_value(default, parent, depth + 1) {
8150                Ok(mut resolved) => {
8151                    if resolved.origin != ValueOrigin::EnvDefault {
8152                        resolved.origin = ValueOrigin::ParameterDefault;
8153                        resolved.name = Some(name.to_string());
8154                    }
8155                    resolved.caveats = resolved
8156                        .caveats
8157                        .into_iter()
8158                        .map(|caveat| caveat.via(name))
8159                        .collect();
8160                    // In-file callers that pass another value make the
8161                    // default one of several; a function other modules may
8162                    // call (not private, not in a script) may be passed
8163                    // anything.
8164                    if let Some(caveat) = self.overridden(home, name, &resolved.value) {
8165                        resolved.caveats.push(caveat);
8166                    } else if !self.is_private(home) {
8167                        resolved
8168                            .caveats
8169                            .push(Unresolved::new("parameter_default", name.to_string()));
8170                    }
8171                    Ok(resolved)
8172                }
8173                Err(unresolved) if unresolved.reason == "credential" => Err(unresolved.via(name)),
8174                Err(unresolved) => {
8175                    let passed = self.caller_models(home, name);
8176                    let default_complete = unresolved.complete();
8177                    Err(Unresolved::new("parameter", name.to_string())
8178                        .with_candidates(unresolved.candidates, default_complete)
8179                        .with_candidates(passed.values.clone(), passed.complete))
8180                }
8181            };
8182        }
8183        if defs.assigns > 0 {
8184            if imported {
8185                // What the assignments give; the import's value is unknown.
8186                let origin = constant_origin(self.scopes[home].kind);
8187                let (candidates, _) = self.name_candidates(name, scope, pos, origin, depth);
8188                return Err(Unresolved::new("reassigned", name.to_string())
8189                    .with_candidates(candidates, false));
8190            }
8191            let origin = constant_origin(self.scopes[home].kind);
8192            let only = defs
8193                .only_assign
8194                .and_then(|i| self.assigns.get(&key).and_then(|v| v.get(i)).copied());
8195            return match self.single_constant(only, defs.assigns, origin, depth) {
8196                Ok(resolved) => Ok(resolved.through(name, origin)),
8197                // Assigned in more than one branch: what each assigns.
8198                Err(unresolved) if unresolved.reason == "reassigned" => {
8199                    let (candidates, complete) =
8200                        self.name_candidates(name, scope, pos, origin, depth);
8201                    Err(unresolved.via(name).with_candidates(candidates, complete))
8202                }
8203                Err(unresolved) => Err(unresolved.via(name)),
8204            };
8205        }
8206        if imported {
8207            Err(Unresolved::new("imported_name", name.to_string()))
8208        } else {
8209            Err(Unresolved::new("unbound", name.to_string()))
8210        }
8211    }
8212
8213    /// The model values in-file calls of `func` pass for parameter `name`,
8214    /// read once per parameter (at most [`MAX_CALLERS_READ`] calls). Empty
8215    /// while candidates are being collected for another lookup.
8216    fn caller_models(&mut self, func: usize, name: &str) -> Rc<CallerModels> {
8217        let key = (func, name.to_string());
8218        if let Some(found) = self.caller_models.get(&key) {
8219            return Rc::clone(found);
8220        }
8221        if self.collecting > 0 {
8222            return Rc::new(CallerModels::default());
8223        }
8224        let mut models = CallerModels::default();
8225        let visible = self.visible_calls(func);
8226        models.unseen = !matches!(visible, Some((_, true)));
8227        let mut read = false;
8228        if let (Some(slot), Some((calls, _))) = (self.param_slot(func, name), visible) {
8229            read = true;
8230            let keyword = slot.keyword.then_some(name);
8231            self.collecting += 1;
8232            for (i, &(call, call_scope)) in calls.iter().enumerate() {
8233                if i >= MAX_CALLERS_READ {
8234                    models.unknown = true;
8235                    break;
8236                }
8237                match argument_for(call, slot.position, keyword, |n| self.text(n)) {
8238                    ArgFor::Found(expr) => match self.resolve_value(expr, call_scope, 0) {
8239                        Ok(resolved) if resolved.is_certain() => {
8240                            if !push_candidate(&mut models.values, resolved) {
8241                                models.unknown = true;
8242                            }
8243                        }
8244                        Ok(resolved) => {
8245                            push_candidate(&mut models.values, resolved);
8246                            models.unknown = true;
8247                        }
8248                        Err(_) => models.unknown = true,
8249                    },
8250                    ArgFor::Missing => {}
8251                    ArgFor::Unknown => models.unknown = true,
8252                }
8253            }
8254            self.collecting -= 1;
8255        }
8256        models.complete = read && !models.unseen && !models.unknown && self.is_private(func);
8257        let models = Rc::new(models);
8258        self.caller_models.insert(key, Rc::clone(&models));
8259        models
8260    }
8261
8262    /// A `parameter_overridden` caveat when an in-file call passes `name`
8263    /// a value other than its `default` (or one that does not resolve), and
8264    /// an `unseen_callers` one when some calls of the function cannot be
8265    /// seen (it is decorated, passed, stored or bound twice).
8266    fn overridden(&mut self, func: usize, name: &str, default: &str) -> Option<Unresolved> {
8267        let passed = self.caller_models(func, name);
8268        let others: Vec<Resolved> = passed
8269            .values
8270            .iter()
8271            .filter(|r| r.value != default)
8272            .cloned()
8273            .collect();
8274        let reason = if passed.unseen {
8275            "unseen_callers"
8276        } else if !others.is_empty() || passed.unknown {
8277            "parameter_overridden"
8278        } else {
8279            return None;
8280        };
8281        Some(Unresolved::new(reason, name.to_string()).with_candidates(others, passed.complete))
8282    }
8283
8284    /// The assignments of `key` among `reach`, at most
8285    /// [`MAX_CANDIDATE_READS`] (only those are copied, however many the
8286    /// name has), and whether that is all of them.
8287    fn reaching_assigns(&self, key: &Key, reach: &Reach) -> (Vec<Assign<'t>>, bool) {
8288        let Some(assigns) = self.assigns.get(key) else {
8289            return (Vec::new(), true);
8290        };
8291        let mut reaching: Vec<Assign<'t>> = match reach {
8292            Reach::All => assigns
8293                .iter()
8294                .take(MAX_CANDIDATE_READS + 1)
8295                .copied()
8296                .collect(),
8297            Reach::Subset(defs) => defs
8298                .iter()
8299                .filter_map(|def| match def {
8300                    DefRef::Assign(i) => assigns.get(*i).copied(),
8301                    _ => None,
8302                })
8303                .take(MAX_CANDIDATE_READS + 1)
8304                .collect(),
8305        };
8306        let all = reaching.len() <= MAX_CANDIDATE_READS;
8307        reaching.truncate(MAX_CANDIDATE_READS);
8308        (reaching, all)
8309    }
8310
8311    /// The values the assignments of `name` that reach a use at byte `pos`
8312    /// of `scope` give it (see [`Self::assign_candidates`]), and whether
8313    /// they are every value: only when each resolved, there were few
8314    /// enough to read, and all are in the scope that binds the name (a
8315    /// `global` or `nonlocal` write from another function is not). When
8316    /// every definition reaches the use, the list is the same for every
8317    /// use and is read once.
8318    fn name_candidates(
8319        &mut self,
8320        name: &str,
8321        scope: usize,
8322        pos: usize,
8323        origin: ValueOrigin,
8324        depth: u32,
8325    ) -> (Vec<Resolved>, bool) {
8326        let (key, at) = self.locate(name, scope, pos);
8327        let reach = self.reaching(&key, at);
8328        let every_use = matches!(reach, Reach::All);
8329        let memo_key = (key, origin);
8330        if every_use {
8331            if let Some(found) = self.reach_all_memo.get(&memo_key) {
8332                return (found.0.clone(), found.1);
8333            }
8334        }
8335        let (reaching, all) = self.reaching_assigns(&memo_key.0, &reach);
8336        let one_scope = reaching.iter().all(|a| a.scope == memo_key.0 .0);
8337        // A nested lookup collects nothing; its empty answer is not kept.
8338        let reading = self.collecting == 0;
8339        let (candidates, complete) = self.assign_candidates(&reaching, origin, name, depth);
8340        let found = (candidates, complete && all && one_scope);
8341        if every_use && reading {
8342            self.reach_all_memo
8343                .insert(memo_key, Rc::new((found.0.clone(), found.1)));
8344        }
8345        found
8346    }
8347
8348    /// The values `assigns` give a name, for a `reassigned` gap: each
8349    /// assignment resolved on its own (without collecting candidates of
8350    /// its own), a loop target's items, distinct, at most
8351    /// [`MAX_CANDIDATES`]; and whether every assignment resolved, with no
8352    /// caveat, into the list. At most [`MAX_CANDIDATE_READS`] values are
8353    /// read in all, assignments and loop items together, so a use reached
8354    /// by many loops over a long list costs no more than one.
8355    fn assign_candidates(
8356        &mut self,
8357        assigns: &[Assign<'t>],
8358        origin: ValueOrigin,
8359        name: &str,
8360        depth: u32,
8361    ) -> (Vec<Resolved>, bool) {
8362        if self.collecting > 0 {
8363            return (Vec::new(), false);
8364        }
8365        self.collecting += 1;
8366        let mut found = Vec::new();
8367        let mut complete = assigns.len() <= MAX_CANDIDATE_READS;
8368        let mut reads_left = MAX_CANDIDATE_READS;
8369        for assign in assigns.iter().take(MAX_CANDIDATE_READS) {
8370            if reads_left == 0 {
8371                complete = false;
8372                break;
8373            }
8374            let value = match (assign.value, assign.unknowable) {
8375                (Some(value), false) => value,
8376                _ => {
8377                    // A loop target takes each item of a literal list.
8378                    let Some(iter) = assign.iter else {
8379                        complete = false;
8380                        continue;
8381                    };
8382                    let items = self.loop_items(iter, assign.scope, origin, depth);
8383                    complete &= items.1;
8384                    for item in items.0.iter() {
8385                        if reads_left == 0 {
8386                            complete = false;
8387                            break;
8388                        }
8389                        reads_left -= 1;
8390                        complete &= push_candidate(&mut found, item.clone().through(name, origin));
8391                    }
8392                    continue;
8393                }
8394            };
8395            reads_left -= 1;
8396            match self.resolve_value(value, assign.scope, depth + 1) {
8397                Ok(mut resolved) => {
8398                    complete &= resolved.is_certain();
8399                    if resolved.origin == ValueOrigin::Literal {
8400                        resolved.origin = origin;
8401                    }
8402                    complete &= push_candidate(&mut found, resolved.through(name, origin));
8403                }
8404                Err(_) => complete = false,
8405            }
8406        }
8407        self.collecting -= 1;
8408        (found, complete)
8409    }
8410
8411    /// The items of the literal list, tuple or set a loop runs over (or of
8412    /// one bound once to a name that is never aliased, passed or mutated),
8413    /// resolved, and whether every item resolved. Called while candidates
8414    /// are being collected; read once per iterable, and at most
8415    /// [`MAX_CANDIDATE_READS`] items of it.
8416    fn loop_items(
8417        &mut self,
8418        iter: Node<'t>,
8419        scope: usize,
8420        origin: ValueOrigin,
8421        depth: u32,
8422    ) -> CandidateList {
8423        let key = (iter.id(), origin);
8424        if let Some(found) = self.loop_items_memo.get(&key) {
8425            return Rc::clone(found);
8426        }
8427        let found = Rc::new(self.read_loop_items(iter, scope, origin, depth));
8428        self.loop_items_memo.insert(key, Rc::clone(&found));
8429        found
8430    }
8431
8432    fn read_loop_items(
8433        &mut self,
8434        iter: Node<'t>,
8435        scope: usize,
8436        origin: ValueOrigin,
8437        depth: u32,
8438    ) -> (Vec<Resolved>, bool) {
8439        // A comprehension in a class body runs its first iterable in the
8440        // class scope and the rest in its own: not read.
8441        let in_class = self.scopes[scope].comprehension
8442            && self.scopes[scope]
8443                .parent
8444                .is_some_and(|p| self.scopes[p].kind == ScopeKind::Class);
8445        if in_class {
8446            return (Vec::new(), false);
8447        }
8448        let list = match iter.kind() {
8449            "list" | "tuple" | "set" => Some((iter, scope)),
8450            "identifier" => {
8451                let name = self.text(iter);
8452                let (key, defs) = self.defs_at(name, scope, iter.start_byte());
8453                let single = !defs.param && !defs.imported && defs.assigns == 1;
8454                match defs
8455                    .only_assign
8456                    .filter(|_| single && !self.escaped.contains(name))
8457                {
8458                    Some(i) => self
8459                        .assigns
8460                        .get(&key)
8461                        .and_then(|v| v.get(i))
8462                        .filter(|a| !a.unknowable)
8463                        .and_then(|a| a.value.map(|value| (value, a.scope)))
8464                        .filter(|(value, _)| matches!(value.kind(), "list" | "tuple" | "set")),
8465                    None => None,
8466                }
8467            }
8468            _ => None,
8469        };
8470        let Some((list, list_scope)) = list else {
8471            return (Vec::new(), false);
8472        };
8473        let mut found = Vec::new();
8474        let mut complete = true;
8475        let mut read = 0;
8476        // A cursor stops at the limit: a huge literal is not listed whole.
8477        let mut cursor = list.walk();
8478        let mut more = cursor.goto_first_child();
8479        while more {
8480            let item = cursor.node();
8481            more = cursor.goto_next_sibling();
8482            if !item.is_named() || item.kind() == "comment" {
8483                continue;
8484            }
8485            if read >= MAX_CANDIDATE_READS {
8486                complete = false;
8487                break;
8488            }
8489            read += 1;
8490            match self.resolve_value(item, list_scope, depth + 1) {
8491                Ok(mut resolved) => {
8492                    complete &= resolved.is_certain();
8493                    if resolved.origin == ValueOrigin::Literal {
8494                        resolved.origin = origin;
8495                    }
8496                    complete &= push_candidate(&mut found, resolved);
8497                }
8498                Err(_) => complete = false,
8499            }
8500        }
8501        (found, complete)
8502    }
8503
8504    /// The two sides of `a if cond else b`, each resolved on its own, and
8505    /// whether both resolved.
8506    fn branch_candidates(
8507        &mut self,
8508        expr: Node<'t>,
8509        scope: usize,
8510        depth: u32,
8511    ) -> (Vec<Resolved>, bool) {
8512        if self.collecting > 0 {
8513            return (Vec::new(), false);
8514        }
8515        self.collecting += 1;
8516        let children = named_children(expr);
8517        let mut found = Vec::new();
8518        let mut complete = true;
8519        for side in [children.first(), children.last()].into_iter().flatten() {
8520            match self.resolve_value(*side, scope, depth + 1) {
8521                Ok(resolved) => {
8522                    complete &= resolved.is_certain();
8523                    complete &= push_candidate(&mut found, resolved);
8524                }
8525                Err(unresolved) => {
8526                    complete &= unresolved.complete();
8527                    for candidate in unresolved.candidates {
8528                        complete &= push_candidate(&mut found, candidate);
8529                    }
8530                }
8531            }
8532        }
8533        self.collecting -= 1;
8534        (found, complete)
8535    }
8536
8537    /// The values a dict literal's entries hold, for a lookup whose key is
8538    /// known only at run time: the first [`MAX_CANDIDATE_READS`] entries
8539    /// (never under a secret-named or credential-shaped key), distinct, at
8540    /// most [`MAX_CANDIDATES`], and whether they are all of its values.
8541    /// Read once per dict.
8542    fn dict_candidates(&mut self, dict: &DictRef<'t>) -> Rc<DictCandidates> {
8543        let key = (dict.node.id(), dict.name.clone());
8544        if let Some(found) = self.dict_candidates_memo.get(&key) {
8545            return Rc::clone(found);
8546        }
8547        if self.collecting > 0 {
8548            return Rc::new(DictCandidates {
8549                values: Vec::new(),
8550                complete: false,
8551            });
8552        }
8553        self.collecting += 1;
8554        let mut found = Vec::new();
8555        let entries = dict_entries(dict.node, |n| self.literal(n).ok(), |n| self.text(n));
8556        let mut complete = entries.len() <= MAX_CANDIDATE_READS;
8557        for entry in entries.into_iter().take(MAX_CANDIDATE_READS) {
8558            // `**other` or a computed key: anything may be there.
8559            let Some((entry_key, value)) = entry else {
8560                complete = false;
8561                continue;
8562            };
8563            // A value under a credential's key is never read.
8564            if is_secret_key(&entry_key) || is_credential_value(&entry_key) {
8565                complete = false;
8566                continue;
8567            }
8568            match self.dict_entry(dict, &entry_key, value, 0) {
8569                Ok(resolved) => {
8570                    complete &= resolved.is_certain();
8571                    complete &= push_candidate(&mut found, resolved);
8572                }
8573                Err(_) => complete = false,
8574            }
8575        }
8576        self.collecting -= 1;
8577        let found = Rc::new(DictCandidates {
8578            values: found,
8579            complete,
8580        });
8581        self.dict_candidates_memo.insert(key, Rc::clone(&found));
8582        found
8583    }
8584
8585    /// A name or attribute assigned exactly once (`only`, out of `count`
8586    /// assignments), to something that itself resolves to a string.
8587    fn single_constant(
8588        &mut self,
8589        only: Option<Assign<'t>>,
8590        count: usize,
8591        origin: ValueOrigin,
8592        depth: u32,
8593    ) -> Result<Resolved, Unresolved> {
8594        match (only, count) {
8595            (_, 0) => Err(Unresolved::new("unbound", String::new())),
8596            (Some(assign), 1) => {
8597                let Some(value) = assign.value.filter(|_| !assign.unknowable) else {
8598                    let unresolved = Unresolved::new("non_literal", String::new());
8599                    // `for model in ["gpt-4o", "o1"]`: each item is a value.
8600                    let Some(iter) = assign.iter.filter(|_| self.collecting == 0) else {
8601                        return Err(unresolved);
8602                    };
8603                    self.collecting += 1;
8604                    let items = self.loop_items(iter, assign.scope, origin, depth);
8605                    self.collecting -= 1;
8606                    return Err(unresolved.with_candidates(items.0.clone(), items.1));
8607                };
8608                let mut resolved = self.resolve_value(value, assign.scope, depth + 1)?;
8609                if resolved.origin == ValueOrigin::Literal {
8610                    resolved.origin = origin;
8611                }
8612                Ok(resolved)
8613            }
8614            (_, many) => Err(Unresolved::new("reassigned", format!("{many} assignments"))),
8615        }
8616    }
8617
8618    /// The literal fallback of an environment or config lookup, or an exact
8619    /// lookup in a same-file dict literal (`MODELS.get("fast", "gpt-4o")`).
8620    /// `None` when `call` is neither.
8621    fn fallback_value(
8622        &mut self,
8623        call: Node<'t>,
8624        scope: usize,
8625        depth: u32,
8626    ) -> Option<Result<Resolved, Unresolved>> {
8627        let function = call.child_by_field_name("function")?;
8628        let rendered = self.render_links(function, 4);
8629        let dict_get = function.kind() == "attribute"
8630            && function
8631                .child_by_field_name("attribute")
8632                .is_some_and(|a| self.text(a) == "get");
8633        let lookup = dict_get
8634            || CONFIG_LOOKUPS.contains(&rendered.as_str())
8635            || matches!(
8636                rendered.as_str(),
8637                "os.getenv"
8638                    | "getenv"
8639                    | "os.environ.get"
8640                    | "environ.get"
8641                    | "os.environ.setdefault"
8642                    | "environ.setdefault"
8643                    | "getattr"
8644            );
8645        // Lookups take a key and a default: a call with many arguments is
8646        // something else, and its arguments are not scanned.
8647        let few_args = call
8648            .child_by_field_name("arguments")
8649            .is_some_and(|a| a.named_child_count() <= MAX_LOOKUP_ARGS);
8650        if !lookup || !few_args {
8651            return None;
8652        }
8653        let (positional, keywords) = call_arguments(call, |n| self.text(n));
8654        let keyword = |name: &str| {
8655            keywords
8656                .iter()
8657                .find(|(k, _)| k.as_str() == name)
8658                .map(|(_, v)| *v)
8659        };
8660        let mut candidates: Vec<Resolved> = Vec::new();
8661        let mut candidates_complete = false;
8662        let (lookup_key, default, reason) = match rendered.as_str() {
8663            "os.getenv"
8664            | "getenv"
8665            | "os.environ.get"
8666            | "environ.get"
8667            | "os.environ.setdefault"
8668            | "environ.setdefault" => (
8669                positional.first().copied(),
8670                positional.get(1).copied().or_else(|| keyword("default")),
8671                "env_var",
8672            ),
8673            _ if CONFIG_LOOKUPS.contains(&rendered.as_str()) => (
8674                positional.first().copied(),
8675                keyword("default").or_else(|| positional.get(1).copied()),
8676                "env_var",
8677            ),
8678            "getattr" => (
8679                positional.get(1).copied(),
8680                positional.get(2).copied(),
8681                "attribute",
8682            ),
8683            _ if function.kind() == "attribute"
8684                && function
8685                    .child_by_field_name("attribute")
8686                    .is_some_and(|a| self.text(a) == "get") =>
8687            {
8688                let key = positional.first().copied();
8689                let default = positional.get(1).copied().or_else(|| keyword("default"));
8690                if let Some(object) = function.child_by_field_name("object") {
8691                    if let Some(dict) = self.dict_node(object, scope, 0) {
8692                        let get = DictGet {
8693                            call,
8694                            key,
8695                            default,
8696                            scope,
8697                        };
8698                        if let Some(found) = self.dict_get_value(&dict, get, depth) {
8699                            return Some(found);
8700                        }
8701                        // A key known only at run time: the dict's values
8702                        // are the candidates.
8703                        let found = self.dict_candidates(&dict);
8704                        candidates = found.values.clone();
8705                        candidates_complete = found.complete;
8706                    }
8707                }
8708                let reason = if self.contains_env(function) {
8709                    "env_var"
8710                } else {
8711                    "function_call"
8712                };
8713                (key, default, reason)
8714            }
8715            _ => return None,
8716        };
8717        let shape = self.render(call);
8718        // The name being looked up must not be a credential's.
8719        if let Some(lookup_key) = lookup_key {
8720            let looked_up = self
8721                .literal(lookup_key)
8722                .unwrap_or_else(|_| self.text(lookup_key).to_string());
8723            if is_secret_key(&looked_up) {
8724                return Some(Err(Unresolved::new("credential", shape)));
8725            }
8726        }
8727        let Some(default) = default else {
8728            if candidates.is_empty() {
8729                return None;
8730            }
8731            return Some(Err(
8732                Unresolved::new(reason, shape).with_candidates(candidates, candidates_complete)
8733            ));
8734        };
8735        Some(match self.resolve_value(default, scope, depth + 1) {
8736            Ok(mut resolved) => {
8737                resolved.origin = ValueOrigin::EnvDefault;
8738                // With the default captured, the dict's values are every
8739                // other value only for a dict lookup; an environment or
8740                // config lookup may return anything.
8741                let complete = candidates_complete && resolved.caveats.is_empty();
8742                resolved
8743                    .caveats
8744                    .push(Unresolved::new(reason, shape).with_candidates(candidates, complete));
8745                Ok(resolved)
8746            }
8747            Err(unresolved) if unresolved.reason == "credential" => Err(unresolved),
8748            Err(_) => Err(Unresolved::new(reason, shape).with_candidates(candidates, false)),
8749        })
8750    }
8751
8752    /// `os.getenv("MODEL") or "gpt-4o"`: the right side is the fallback.
8753    fn or_fallback(
8754        &mut self,
8755        expr: Node<'t>,
8756        scope: usize,
8757        depth: u32,
8758    ) -> Option<Result<Resolved, Unresolved>> {
8759        let operator = expr.child_by_field_name("operator")?;
8760        if self.text(operator) != "or" {
8761            return None;
8762        }
8763        let left = expr.child_by_field_name("left")?;
8764        let right = expr.child_by_field_name("right")?;
8765        let lookup = self.contains_env(left)
8766            || (left.kind() == "call"
8767                && left
8768                    .child_by_field_name("function")
8769                    .is_some_and(|f| CONFIG_LOOKUPS.contains(&self.render(f).as_str())));
8770        if !lookup {
8771            return None;
8772        }
8773        match self.resolve_value(right, scope, depth + 1) {
8774            Ok(mut resolved) => {
8775                resolved.origin = ValueOrigin::EnvDefault;
8776                resolved
8777                    .caveats
8778                    .push(Unresolved::new("env_var", self.render(left)));
8779                Some(Ok(resolved))
8780            }
8781            Err(unresolved) if unresolved.reason == "credential" => Some(Err(unresolved)),
8782            Err(_) => None,
8783        }
8784    }
8785
8786    /// `MODELS["fast"]` where `MODELS` is a same-file dict literal.
8787    fn subscript_value(
8788        &mut self,
8789        expr: Node<'t>,
8790        scope: usize,
8791        depth: u32,
8792    ) -> Option<Result<Resolved, Unresolved>> {
8793        let base = expr.child_by_field_name("value")?;
8794        let index = single_subscript(expr)?;
8795        let key = self.literal(index).ok()?;
8796        if is_secret_key(&key) {
8797            return Some(Err(Unresolved::new("credential", self.render(expr))));
8798        }
8799        let dict = self.dict_node(base, scope, 0)?;
8800        match self.dict_lookup(dict.node, &key) {
8801            Lookup::Found(value) => Some(self.dict_entry(&dict, &key, value, depth)),
8802            Lookup::Absent | Lookup::Unknown => None,
8803        }
8804    }
8805
8806    /// The value of `dict.get(key, default)` on a same-file dict literal:
8807    /// the entry when the key is there, the default when it certainly is not.
8808    /// The default is an argument of the call, so it is resolved where the
8809    /// call runs, not where the dict is written.
8810    fn dict_get_value(
8811        &mut self,
8812        dict: &DictRef<'t>,
8813        get: DictGet<'t>,
8814        depth: u32,
8815    ) -> Option<Result<Resolved, Unresolved>> {
8816        let key = self.literal(get.key?).ok()?;
8817        if is_secret_key(&key) {
8818            // The key is a literal: name the call, never the key.
8819            return Some(Err(Unresolved::new("credential", self.render(get.call))));
8820        }
8821        match self.dict_lookup(dict.node, &key) {
8822            Lookup::Found(value) => Some(self.dict_entry(dict, &key, value, depth)),
8823            Lookup::Absent => {
8824                let default = get.default?;
8825                Some(self.resolve_value(default, get.scope, depth + 1))
8826            }
8827            Lookup::Unknown => None,
8828        }
8829    }
8830
8831    fn dict_entry(
8832        &mut self,
8833        dict: &DictRef<'t>,
8834        key: &str,
8835        value: Node<'t>,
8836        depth: u32,
8837    ) -> Result<Resolved, Unresolved> {
8838        let label = dict.name.as_ref().map(|name| {
8839            if is_identifier_key(key) {
8840                format!("{name}[\"{key}\"]")
8841            } else {
8842                format!("{name}[...]")
8843            }
8844        });
8845        self.resolve_value(value, dict.scope, depth + 1)
8846            .map(|mut r| {
8847                if r.origin == ValueOrigin::Literal {
8848                    r.origin = dict.origin;
8849                    r.name = label.clone();
8850                }
8851                r
8852            })
8853            .map_err(|u| match &label {
8854                Some(label) => u.via(label),
8855                None => u,
8856            })
8857    }
8858
8859    /// The dict literal `expr` evaluates to: a `{...}` or `dict(...)`
8860    /// written inline, a name assigned exactly one (and never mutated or
8861    /// passed on, see [`Ctx::escaped`]), or a
8862    /// constant key of one of those.
8863    fn dict_node(&mut self, expr: Node<'t>, scope: usize, depth: u32) -> Option<DictRef<'t>> {
8864        if depth > 8 {
8865            return None;
8866        }
8867        match expr.kind() {
8868            "dictionary" => Some(DictRef {
8869                node: expr,
8870                scope,
8871                name: None,
8872                origin: ValueOrigin::Literal,
8873            }),
8874            "call" if is_dict_call(expr, |n| self.text(n)) => Some(DictRef {
8875                node: expr,
8876                scope,
8877                name: None,
8878                origin: ValueOrigin::Literal,
8879            }),
8880            "parenthesized_expression" => {
8881                let inner = expr.named_child(0)?;
8882                self.dict_node(inner, scope, depth + 1)
8883            }
8884            "identifier" => {
8885                let name = self.text(expr);
8886                if is_secret_key(name) || self.escaped.contains(name) {
8887                    return None;
8888                }
8889                let (key, defs) = self.defs_at(name, scope, expr.start_byte());
8890                if defs.param || defs.imported || defs.assigns != 1 {
8891                    return None;
8892                }
8893                let assign = self.assigns.get(&key)?.get(defs.only_assign?).copied()?;
8894                if assign.unknowable {
8895                    return None;
8896                }
8897                let mut dict = self.dict_node(assign.value?, assign.scope, depth + 1)?;
8898                if dict.name.is_none() {
8899                    dict.name = Some(name.to_string());
8900                    dict.origin = constant_origin(self.scopes[key.0].kind);
8901                }
8902                Some(dict)
8903            }
8904            "subscript" => {
8905                let base = expr.child_by_field_name("value")?;
8906                let key = self.literal(single_subscript(expr)?).ok()?;
8907                if !is_identifier_key(&key) {
8908                    return None;
8909                }
8910                let outer = self.dict_node(base, scope, depth + 1)?;
8911                let Lookup::Found(value) = self.dict_lookup(outer.node, &key) else {
8912                    return None;
8913                };
8914                let mut dict = self.dict_node(value, outer.scope, depth + 1)?;
8915                if dict.name.is_none() {
8916                    dict.name = outer.name.map(|n| format!("{n}[\"{key}\"]"));
8917                    dict.origin = outer.origin;
8918                }
8919                Some(dict)
8920            }
8921            _ => None,
8922        }
8923    }
8924
8925    /// The entries of a dict expanded with `**` that can matter.
8926    fn expand_splat(&mut self, expr: Node<'t>, scope: usize) -> Option<Expansion<'t>> {
8927        let dict = self.dict_node(expr, scope, 0)?;
8928        let summary = self.dict_summary(dict.node);
8929        Some(Expansion {
8930            node: dict.node,
8931            summary,
8932            scope: dict.scope,
8933            name: dict.name,
8934            origin: dict.origin,
8935        })
8936    }
8937
8938    /// Looks `key` up in a dict literal: the last matching entry wins, as in
8939    /// Python, unless an unreadable entry after it could override it.
8940    fn dict_lookup(&mut self, dict: Node<'t>, key: &str) -> Lookup<'t> {
8941        let summary = self.dict_summary(dict);
8942        match summary.last.get(key) {
8943            Some((index, value)) if !summary.overridable(*index) => Lookup::Found(*value),
8944            Some(_) => Lookup::Unknown,
8945            None if summary.last_unknown.is_some() => Lookup::Unknown,
8946            None => Lookup::Absent,
8947        }
8948    }
8949
8950    fn dict_summary(&mut self, dict: Node<'t>) -> Rc<DictSummary<'t>> {
8951        if let Some(summary) = self.dict_cache.get(&dict.id()) {
8952            return Rc::clone(summary);
8953        }
8954        let mut summary = DictSummary {
8955            last: HashMap::new(),
8956            last_unknown: None,
8957            expansion: Vec::new(),
8958            opaque: false,
8959        };
8960        let entries = dict_entries(dict, |n| self.literal(n).ok(), |n| self.text(n));
8961        for (index, entry) in entries.into_iter().enumerate() {
8962            let Some((key, value)) = entry else {
8963                summary.last_unknown = Some(index);
8964                summary.opaque = true;
8965                continue;
8966            };
8967            // A credential-named or non-identifier key cannot be a model
8968            // argument; it is never read through an expansion.
8969            let relevant = is_identifier_key(&key)
8970                && (is_value_key(&key) || is_base_url_key(&key) || is_container(value));
8971            if relevant {
8972                if let Some(slot) = summary.expansion.iter_mut().find(|(k, _, _)| *k == key) {
8973                    slot.1 = index;
8974                    slot.2 = value;
8975                } else if summary.expansion.len() < 256 {
8976                    summary.expansion.push((key.clone(), index, value));
8977                } else {
8978                    summary.opaque = true;
8979                }
8980            }
8981            summary.last.insert(key, (index, value));
8982        }
8983        let summary = Rc::new(summary);
8984        self.dict_cache.insert(dict.id(), Rc::clone(&summary));
8985        summary
8986    }
8987
8988    /// Whether `node` reads the process environment
8989    /// (`os.getenv(...)`, `os.environ[...]`, `os.environ.get(...)`): a
8990    /// binary search over the reads recorded during collection, so asking
8991    /// it of every nested call in a deep expression stays linear.
8992    fn contains_env(&self, node: Node<'t>) -> bool {
8993        let first = self
8994            .env_reads
8995            .partition_point(|&start| start < node.start_byte());
8996        self.env_reads
8997            .get(first)
8998            .is_some_and(|&start| start < node.end_byte())
8999    }
9000
9001    /// An expression's shape with every argument and literal elided, so a
9002    /// rendering can never carry a value. The spine (attribute objects, call
9003    /// functions, subscript values) is walked iteratively, at most
9004    /// [`MAX_DEPTH`] links deep, so rendering is linear in the chain.
9005    fn render(&self, node: Node<'t>) -> String {
9006        self.render_links(node, MAX_DEPTH)
9007    }
9008
9009    /// [`Self::render`] keeping at most `links` links of the spine.
9010    fn render_links(&self, node: Node<'t>, links: u32) -> String {
9011        let mut suffixes: Vec<String> = Vec::new();
9012        let mut current = Some(node);
9013        let mut depth = 0;
9014        let base = loop {
9015            let Some(node) = current else {
9016                break String::new();
9017            };
9018            if depth > links {
9019                break "<expr>".to_string();
9020            }
9021            depth += 1;
9022            match node.kind() {
9023                "identifier" => break self.text(node).to_string(),
9024                "attribute" => {
9025                    let attr = node
9026                        .child_by_field_name("attribute")
9027                        .map(|a| self.text(a))
9028                        .unwrap_or_default();
9029                    suffixes.push(format!(".{attr}"));
9030                    current = node.child_by_field_name("object");
9031                }
9032                "call" => {
9033                    suffixes.push(if self.has_args(node) { "(...)" } else { "()" }.to_string());
9034                    current = node.child_by_field_name("function");
9035                }
9036                "subscript" => {
9037                    suffixes.push("[...]".to_string());
9038                    current = node.child_by_field_name("value");
9039                }
9040                "parenthesized_expression" | "await" => match node.named_child(0) {
9041                    Some(inner) => current = Some(inner),
9042                    None => break "<expr>".to_string(),
9043                },
9044                "string" => {
9045                    let interpolated = children(node).iter().any(|c| c.kind() == "interpolation");
9046                    break if interpolated { "f\"...\"" } else { "\"...\"" }.to_string();
9047                }
9048                "concatenated_string" => break "\"...\"".to_string(),
9049                "conditional_expression" => break "<conditional>".to_string(),
9050                "boolean_operator" => break "<boolean>".to_string(),
9051                _ => break "<expr>".to_string(),
9052            }
9053        };
9054        let mut rendered = base;
9055        for suffix in suffixes.iter().rev() {
9056            rendered.push_str(suffix);
9057        }
9058        clip_owned(rendered)
9059    }
9060
9061    fn has_args(&self, call: Node<'t>) -> bool {
9062        call.child_by_field_name("arguments")
9063            .is_some_and(|args| args.named_child_count() > 0)
9064    }
9065
9066    fn finish(mut self) -> FileUsages {
9067        self.out.imports.sort_by_key(|i| i.span.start_byte);
9068        self.out
9069            .clients
9070            .sort_by_key(|c| (c.span.start_byte, c.span.end_byte));
9071        // A call chained on another (`m(...).start_chat()`) starts at the same
9072        // byte; the inner, shorter one comes first.
9073        self.out
9074            .calls
9075            .sort_by_key(|c| (c.span.start_byte, c.span.end_byte));
9076        self.out
9077            .gaps
9078            .sort_by_key(|g| (g.span.map(|s| s.start_byte).unwrap_or(0), g.kind));
9079        self.out
9080    }
9081}
9082
9083/// `text`, or its first and last bytes around `...` when it is longer than
9084/// [`MAX_TEXT`].
9085fn clip(text: &str) -> String {
9086    if text.len() <= MAX_TEXT {
9087        return text.to_string();
9088    }
9089    let half = (MAX_TEXT - 3) / 2;
9090    let mut head = half;
9091    while !text.is_char_boundary(head) {
9092        head -= 1;
9093    }
9094    let mut tail = text.len() - half;
9095    while !text.is_char_boundary(tail) {
9096        tail += 1;
9097    }
9098    format!("{}...{}", &text[..head], &text[tail..])
9099}
9100
9101/// [`clip`] for an owned string, which is returned as is when short.
9102fn clip_owned(text: String) -> String {
9103    if text.len() <= MAX_TEXT {
9104        text
9105    } else {
9106        clip(&text)
9107    }
9108}
9109
9110/// Whether `file` is a script other modules do not import: no extension
9111/// (a shebang script) or `__main__.py`.
9112fn is_script_path(file: &str) -> bool {
9113    let path = std::path::Path::new(file);
9114    path.extension().is_none()
9115        || path
9116            .file_name()
9117            .is_some_and(|name| name.eq_ignore_ascii_case("__main__.py"))
9118}
9119
9120/// What an import statement binds, for [`SdkImport`].
9121struct Binding<'a> {
9122    local: &'a str,
9123    pkg: Pkg,
9124    module: &'a str,
9125    name: Option<String>,
9126    kind: BindingKind,
9127}
9128
9129/// Everything the analysis needs to know about a call's target.
9130struct CallTarget {
9131    pkg: Pkg,
9132    member: String,
9133    receiver: Receiver,
9134    routing: Routing,
9135    client_line: Option<u32>,
9136    ambiguous: bool,
9137    caveat: Option<ClientCaveat>,
9138}
9139
9140/// The call a value or gap is reported for.
9141#[derive(Clone, Copy)]
9142struct Site<'a, 't> {
9143    sdk: Sdk,
9144    call: Node<'t>,
9145    chain: &'a str,
9146    scope: usize,
9147    /// Whether an unresolved value here is reported as a gap.
9148    gap_worthy: bool,
9149}
9150
9151#[derive(Default)]
9152struct Args<'t> {
9153    kwargs: Vec<String>,
9154    positional: u32,
9155    splat: bool,
9156    first_positional: Option<Node<'t>>,
9157    /// Allowlisted keyword arguments and their value expressions.
9158    value_args: Vec<(String, Node<'t>)>,
9159    /// Other arguments that are dict/list/tuple literals, with the keyword
9160    /// they were passed under (`None` when positional).
9161    literal_args: Vec<(Option<String>, Node<'t>)>,
9162    /// The expressions passed with `**`.
9163    splats: Vec<Node<'t>>,
9164    /// Arguments were spread with `*`.
9165    list_splat: bool,
9166}
9167
9168/// Adds `resolved` to `values` unless its value is already there, keeping at
9169/// most [`MAX_CANDIDATES`]; `false` when it was dropped at that limit.
9170fn push_candidate(values: &mut Vec<Resolved>, mut resolved: Resolved) -> bool {
9171    if values.iter().any(|v| v.value == resolved.value) {
9172        return true;
9173    }
9174    if values.len() >= MAX_CANDIDATES {
9175        return false;
9176    }
9177    resolved.caveats.clear();
9178    values.push(resolved);
9179    true
9180}
9181
9182/// Whether `span` lies inside `node`: a literal written at that call.
9183fn within(node: Node<'_>, span: Span) -> bool {
9184    node.start_byte() <= span.start_byte as usize && span.end_byte as usize <= node.end_byte()
9185}
9186
9187fn captured(key: &str, resolved: Resolved, positional: bool) -> CapturedValue {
9188    let family = model_family(&resolved.value);
9189    CapturedValue {
9190        key: key.to_string(),
9191        value: resolved.value,
9192        origin: resolved.origin,
9193        name: resolved.name.map(clip_owned),
9194        positional,
9195        span: resolved.span,
9196        model_family: family,
9197    }
9198}
9199
9200fn constant_origin(kind: ScopeKind) -> ValueOrigin {
9201    match kind {
9202        ScopeKind::Module => ValueOrigin::ModuleConstant,
9203        ScopeKind::Class => ValueOrigin::ClassConstant,
9204        ScopeKind::Function => ValueOrigin::LocalConstant,
9205    }
9206}
9207
9208/// The key a call's first positional argument is captured under, when that
9209/// argument is the model.
9210fn positional_model_key(pkg: Pkg, receiver: Receiver, member: &str) -> Option<&'static str> {
9211    if member == "GenerativeModel" {
9212        return Some("model_name");
9213    }
9214    let last = member.rsplit('.').next().unwrap_or(member);
9215    (pkg == Pkg::GoogleGenerativeai
9216        && receiver != Receiver::Client
9217        && LEGACY_POSITIONAL_MODEL.contains(&last))
9218    .then_some("model")
9219}
9220
9221/// A dict, list, tuple or set literal.
9222fn is_container(node: Node<'_>) -> bool {
9223    matches!(node.kind(), "dictionary" | "list" | "tuple" | "set")
9224}
9225
9226fn is_model_bearing(member: &str) -> bool {
9227    MODEL_BEARING
9228        .iter()
9229        .any(|m| member == *m || member.ends_with(&format!(".{m}")))
9230}
9231
9232/// Methods that read a dict or list without changing it or handing out
9233/// its entries.
9234const READ_ONLY_METHODS: &[&str] = &[
9235    "get",
9236    "keys",
9237    "__contains__",
9238    "__len__",
9239    "__getitem__",
9240    "count",
9241    "index",
9242];
9243
9244/// Methods that hand out a dict's entries (or a shallow copy of them).
9245const SHALLOW_METHODS: &[&str] = &["items", "values", "copy", "__iter__"];
9246
9247/// Methods that change a dict, list or set in place.
9248const MUTATING_METHODS: &[&str] = &[
9249    "update",
9250    "setdefault",
9251    "pop",
9252    "popitem",
9253    "clear",
9254    "__setitem__",
9255    "__delitem__",
9256    "__ior__",
9257    "append",
9258    "extend",
9259    "insert",
9260    "remove",
9261    "sort",
9262    "reverse",
9263    "add",
9264    "discard",
9265];
9266
9267/// Calls that only read their argument.
9268const READ_ONLY_CALLS: &[&str] = &[
9269    "len",
9270    "print",
9271    "repr",
9272    "str",
9273    "sorted",
9274    "list",
9275    "tuple",
9276    "set",
9277    "frozenset",
9278    "iter",
9279    "bool",
9280    "isinstance",
9281    "type",
9282    "id",
9283    "hash",
9284    "enumerate",
9285    "any",
9286    "all",
9287    "json.dumps",
9288    "copy.deepcopy",
9289    "deepcopy",
9290];
9291
9292/// Calls that return a shallow copy, sharing nested containers.
9293const SHALLOW_CALLS: &[&str] = &["dict", "copy.copy", "copy"];
9294
9295/// Builtins that read or rebind a namespace by name.
9296fn is_namespace_builtin(name: &str) -> bool {
9297    matches!(
9298        name,
9299        "exec" | "eval" | "compile" | "globals" | "locals" | "vars" | "__import__"
9300    )
9301}
9302
9303/// Whether the node of `frame` is a statement of its own directly in the
9304/// module body: an expression statement there, not a branch, loop, `try`,
9305/// `with`, class body or function, nor part of a larger expression.
9306/// `os.environ` or `os.environb`, which shares its data on POSIX.
9307fn is_environ_name(name: &str) -> bool {
9308    matches!(name, "environ" | "environb")
9309}
9310
9311/// A module attribute that routes the module-level OpenAI API.
9312fn is_module_routing_attr(attr: &str) -> bool {
9313    matches!(
9314        attr,
9315        "api_type"
9316            | "api_base"
9317            | "base_url"
9318            | "azure_endpoint"
9319            | "azure_ad_token"
9320            | "azure_ad_token_provider"
9321    ) || attr.starts_with("bedrock_")
9322}
9323
9324fn is_top_statement(frame: &Frame<'_>) -> bool {
9325    frame
9326        .parent
9327        .is_some_and(|p| p.kind() == "expression_statement")
9328        && frame.grand.is_some_and(|g| g.kind() == "module")
9329}
9330
9331/// Whether a field of a node of kind `parent` names a binding rather than
9332/// using one: a definition's name, a parameter, an import, a keyword
9333/// argument's name, an attribute name or an assignment target.
9334fn is_declaration(parent: &str, field: Option<&str>) -> bool {
9335    matches!(
9336        (parent, field),
9337        ("function_definition" | "class_definition", Some("name"))
9338            | ("keyword_argument", Some("name"))
9339            | ("attribute", Some("attribute"))
9340            | (
9341                "default_parameter" | "typed_default_parameter",
9342                Some("name")
9343            )
9344            | ("assignment" | "augmented_assignment", Some("left"))
9345            | (
9346                "parameters"
9347                    | "lambda_parameters"
9348                    | "typed_parameter"
9349                    | "list_splat_pattern"
9350                    | "dictionary_splat_pattern"
9351                    | "dotted_name"
9352                    | "aliased_import"
9353                    | "import_from_statement"
9354                    | "global_statement"
9355                    | "nonlocal_statement",
9356                _,
9357            )
9358    )
9359}
9360
9361/// The name at the root of a subscript, attribute or `.get` chain
9362/// (`CFG` in `CFG["a"]["b"]`, `H` in `H.d["k"]`, `D` in `D.get("a")["b"]`).
9363fn chain_root_name<'t>(mut node: Node<'t>, text: impl Fn(Node<'t>) -> &'t str) -> Option<&'t str> {
9364    for _ in 0..MAX_DEPTH {
9365        node = match node.kind() {
9366            "identifier" => return Some(text(node)),
9367            "subscript" => node.child_by_field_name("value")?,
9368            "attribute" => node.child_by_field_name("object")?,
9369            "call" => node.child_by_field_name("function")?,
9370            "parenthesized_expression" => node.named_child(0)?,
9371            _ => return None,
9372        };
9373    }
9374    None
9375}
9376
9377/// `super()`.
9378fn is_super_call<'t>(node: Node<'t>, text: impl Fn(Node<'t>) -> &'t str) -> bool {
9379    node.kind() == "call"
9380        && node
9381            .child_by_field_name("function")
9382            .is_some_and(|f| f.kind() == "identifier" && text(f) == "super")
9383}
9384
9385/// `globals()`, `locals()` or `vars()` with no argument: the namespace
9386/// itself, whose keys are binding names.
9387fn is_namespace_call<'t>(node: Node<'t>, text: impl Fn(Node<'t>) -> &'t str) -> bool {
9388    node.kind() == "call"
9389        && node.child_by_field_name("function").is_some_and(|f| {
9390            f.kind() == "identifier" && matches!(text(f), "globals" | "locals" | "vars")
9391        })
9392        && node
9393            .child_by_field_name("arguments")
9394            .is_some_and(|a| a.named_child_count() == 0)
9395}
9396
9397/// `x.get(...)`.
9398fn is_get_call<'t>(call: Node<'t>, text: impl Fn(Node<'t>) -> &'t str) -> bool {
9399    call.child_by_field_name("function")
9400        .filter(|f| f.kind() == "attribute")
9401        .and_then(|f| f.child_by_field_name("attribute"))
9402        .is_some_and(|a| text(a) == "get")
9403}
9404
9405/// A dict, list or set literal, or a `dict(...)`/`list(...)` call: a
9406/// container that can be changed in place. Strings, numbers and tuples of
9407/// them cannot.
9408fn is_mutable_literal<'t>(node: Node<'t>, text: impl Fn(Node<'t>) -> &'t str + Copy) -> bool {
9409    match node.kind() {
9410        "dictionary"
9411        | "list"
9412        | "set"
9413        | "dictionary_comprehension"
9414        | "list_comprehension"
9415        | "set_comprehension" => true,
9416        "tuple" | "parenthesized_expression" => named_children(node)
9417            .into_iter()
9418            .any(|n| is_mutable_literal(n, text)),
9419        "call" => node
9420            .child_by_field_name("function")
9421            .is_some_and(|f| matches!(text(f), "dict" | "list" | "set")),
9422        _ => false,
9423    }
9424}
9425
9426/// `dict(model=..., ...)`.
9427fn is_dict_call<'t>(call: Node<'t>, text: impl Fn(Node<'t>) -> &'t str) -> bool {
9428    call.child_by_field_name("function")
9429        .is_some_and(|f| f.kind() == "identifier" && text(f) == "dict")
9430}
9431
9432/// The one index of `x[i]`, if there is exactly one.
9433fn single_subscript(expr: Node<'_>) -> Option<Node<'_>> {
9434    let mut cursor = expr.walk();
9435    let mut indexes = expr.children_by_field_name("subscript", &mut cursor);
9436    let first = indexes.next()?;
9437    indexes.next().is_none().then_some(first)
9438}
9439
9440/// The entries of a dict literal or `dict(...)` call: `Some((key, value))`
9441/// for a string or keyword key, `None` for a part that cannot be read
9442/// (`**other`, a computed key, a positional argument to `dict`).
9443fn dict_entries<'t>(
9444    dict: Node<'t>,
9445    literal: impl Fn(Node<'t>) -> Option<String>,
9446    text: impl Fn(Node<'t>) -> &'t str,
9447) -> Vec<Option<(String, Node<'t>)>> {
9448    let mut entries = Vec::new();
9449    if dict.kind() == "dictionary" {
9450        for item in named_children(dict) {
9451            match item.kind() {
9452                "pair" => {
9453                    let key = item.child_by_field_name("key").and_then(&literal);
9454                    match (key, item.child_by_field_name("value")) {
9455                        (Some(key), Some(value)) => entries.push(Some((key, value))),
9456                        _ => entries.push(None),
9457                    }
9458                }
9459                "comment" => {}
9460                _ => entries.push(None),
9461            }
9462        }
9463    } else if let Some(args) = dict.child_by_field_name("arguments") {
9464        if args.kind() != "argument_list" {
9465            entries.push(None);
9466            return entries;
9467        }
9468        for arg in named_children(args) {
9469            match arg.kind() {
9470                "keyword_argument" => {
9471                    match (
9472                        arg.child_by_field_name("name"),
9473                        arg.child_by_field_name("value"),
9474                    ) {
9475                        (Some(name), Some(value)) => {
9476                            entries.push(Some((text(name).to_string(), value)))
9477                        }
9478                        _ => entries.push(None),
9479                    }
9480                }
9481                "comment" => {}
9482                _ => entries.push(None),
9483            }
9484        }
9485    }
9486    entries
9487}
9488
9489/// The value of the first keyword argument of `call` whose name `wanted`
9490/// accepts.
9491fn keyword_value<'t>(
9492    call: Node<'t>,
9493    text: impl Fn(Node<'t>) -> &'t str,
9494    wanted: impl Fn(&str) -> bool,
9495) -> Option<Node<'t>> {
9496    let args = call
9497        .child_by_field_name("arguments")
9498        .filter(|a| a.kind() == "argument_list")?;
9499    named_children(args).into_iter().find_map(|arg| {
9500        let name = arg.child_by_field_name("name")?;
9501        (arg.kind() == "keyword_argument" && wanted(text(name)))
9502            .then(|| arg.child_by_field_name("value"))
9503            .flatten()
9504    })
9505}
9506
9507/// Positional and keyword arguments of a call, as written.
9508fn call_arguments<'t>(
9509    call: Node<'t>,
9510    text: impl Fn(Node<'t>) -> &'t str,
9511) -> (Vec<Node<'t>>, Vec<(String, Node<'t>)>) {
9512    let mut positional = Vec::new();
9513    let mut keywords = Vec::new();
9514    let Some(args) = call
9515        .child_by_field_name("arguments")
9516        .filter(|a| a.kind() == "argument_list")
9517    else {
9518        return (positional, keywords);
9519    };
9520    for arg in named_children(args) {
9521        match arg.kind() {
9522            "keyword_argument" => {
9523                if let (Some(name), Some(value)) = (
9524                    arg.child_by_field_name("name"),
9525                    arg.child_by_field_name("value"),
9526                ) {
9527                    keywords.push((text(name).to_string(), value));
9528                }
9529            }
9530            "list_splat" | "dictionary_splat" | "comment" => {}
9531            _ => positional.push(arg),
9532        }
9533    }
9534    (positional, keywords)
9535}
9536
9537/// The argument a call passes for a parameter at `position` (counting from
9538/// the first explicit argument) or named `keyword`.
9539fn argument_for<'t>(
9540    call: Node<'t>,
9541    position: Option<usize>,
9542    keyword: Option<&str>,
9543    text: impl Fn(Node<'t>) -> &'t str,
9544) -> ArgFor<'t> {
9545    let Some(args) = call.child_by_field_name("arguments") else {
9546        return ArgFor::Missing;
9547    };
9548    if args.kind() != "argument_list" {
9549        return ArgFor::Unknown;
9550    }
9551    let mut index = 0;
9552    let mut star = false;
9553    let mut double_star = false;
9554    let mut found = None;
9555    for arg in named_children(args) {
9556        match arg.kind() {
9557            "keyword_argument" => {
9558                let name = arg.child_by_field_name("name").map(&text);
9559                if keyword.is_some() && name == keyword {
9560                    if let Some(value) = arg.child_by_field_name("value") {
9561                        return ArgFor::Found(value);
9562                    }
9563                }
9564            }
9565            "list_splat" => star = true,
9566            "dictionary_splat" => double_star = true,
9567            "comment" => {}
9568            _ => {
9569                if !star && Some(index) == position {
9570                    found = Some(arg);
9571                }
9572                index += 1;
9573            }
9574        }
9575    }
9576    match found {
9577        Some(arg) => ArgFor::Found(arg),
9578        None if (star && position.is_some()) || double_star => ArgFor::Unknown,
9579        None => ArgFor::Missing,
9580    }
9581}
9582
9583/// The first segment of a rendered chain (`self.client` for
9584/// `self.client.chat.completions.create`).
9585fn chain_root(chain: &str) -> String {
9586    let mut parts = chain.split('.');
9587    let first = parts.next().unwrap_or_default();
9588    if matches!(first, "self" | "cls") {
9589        if let Some(second) = parts.next() {
9590            return format!("{first}.{second}");
9591        }
9592    }
9593    first.to_string()
9594}
9595
9596/// Whether an attribute node is used as a value: not the callee of a call,
9597/// not the object of a longer chain, not an assignment target. Decided from
9598/// the parent's kind and the field the node fills in it.
9599fn is_value_reference(parent: Option<Node<'_>>, field: Option<&str>) -> bool {
9600    let Some(parent) = parent else {
9601        return false;
9602    };
9603    match parent.kind() {
9604        "attribute" => field != Some("object"),
9605        "call" => field != Some("function"),
9606        "assignment" | "augmented_assignment" => field != Some("left"),
9607        "as_pattern_target" | "delete_statement" => false,
9608        _ => true,
9609    }
9610}
9611
9612/// Every child, in order, in time linear in their number.
9613fn children(node: Node<'_>) -> Vec<Node<'_>> {
9614    let mut cursor = node.walk();
9615    node.children(&mut cursor).collect()
9616}
9617
9618/// Every named child, in order, in time linear in their number
9619/// (`Node::named_child(i)` walks from the first child on every call).
9620fn named_children(node: Node<'_>) -> Vec<Node<'_>> {
9621    let mut cursor = node.walk();
9622    node.named_children(&mut cursor).collect()
9623}
9624
9625/// Combines every value a binding is given. Placeholders (`None`, literals)
9626/// and self-references are ignored next to a real value. A client mixed with
9627/// a different client or with an unknown value is ambiguous.
9628fn combine(vals: Vec<Val>) -> Val {
9629    // A dynamic feature next to the values: a client keeps them with a
9630    // `dynamic_feature` caveat; anything else is replaced by it.
9631    let dynamic = vals.iter().find_map(|v| match v {
9632        Val::Untracked(Origin::Dynamic(feature)) => Some(*feature),
9633        _ => None,
9634    });
9635    if let Some(feature) = dynamic {
9636        let rest: Vec<Val> = vals
9637            .into_iter()
9638            .filter(|v| !matches!(v, Val::Untracked(Origin::Dynamic(_))))
9639            .collect();
9640        if rest.is_empty() {
9641            return Val::untracked(Origin::Dynamic(feature));
9642        }
9643        return match combine(rest) {
9644            Val::Client { mut client, path } => {
9645                if client.caveat.is_none() {
9646                    client.caveat = Some(ClientCaveat::Dynamic(feature));
9647                }
9648                Val::Client { client, path }
9649            }
9650            _ => Val::untracked(Origin::Dynamic(feature)),
9651        };
9652    }
9653    let real: Vec<Val> = vals
9654        .iter()
9655        .filter(|v| {
9656            !matches!(
9657                v,
9658                Val::Untracked(Origin::Placeholder) | Val::Untracked(Origin::Cycle)
9659            )
9660        })
9661        .cloned()
9662        .collect();
9663    if real.is_empty() {
9664        return vals
9665            .into_iter()
9666            .next()
9667            .unwrap_or(Val::untracked(Origin::Unbound));
9668    }
9669    if real.len() == 1 {
9670        return real
9671            .into_iter()
9672            .next()
9673            .unwrap_or(Val::untracked(Origin::Other));
9674    }
9675
9676    let clients: Vec<&Client> = real
9677        .iter()
9678        .filter_map(|v| match v {
9679            Val::Client { client, path } if path.is_empty() => Some(client),
9680            _ => None,
9681        })
9682        .collect();
9683    // A construction says more than an annotation; an annotation alone says
9684    // more than an unknown factory next to it (`client: OpenAI` in the class
9685    // body, `self.client = make_client()` in `__init__`).
9686    let constructed: Vec<&Client> = clients.iter().copied().filter(|c| !c.typed).collect();
9687    if constructed.is_empty() {
9688        if let Some(typed) = clients.first() {
9689            return Val::Client {
9690                client: (*typed).clone(),
9691                path: Vec::new(),
9692            };
9693        }
9694    } else {
9695        let first = constructed[0].clone();
9696        let others = real.len() - clients.len();
9697        let same_routing = constructed.iter().all(|c| c.routing == first.routing);
9698        let same_pkg = constructed.iter().all(|c| c.pkg == first.pkg);
9699        let same_line = constructed.iter().all(|c| c.line == first.line);
9700        let same_site = constructed.iter().all(|c| c.site == first.site);
9701        let ambiguous =
9702            others > 0 || !same_routing || !same_pkg || constructed.iter().any(|c| c.ambiguous);
9703        return Val::Client {
9704            client: Client {
9705                pkg: first.pkg,
9706                routing: if ambiguous {
9707                    Routing::Unknown
9708                } else {
9709                    first.routing
9710                },
9711                line: if same_line { first.line } else { None },
9712                site: if same_site { first.site } else { None },
9713                ambiguous,
9714                typed: false,
9715                caveat: constructed.iter().find_map(|c| c.caveat.clone()),
9716            },
9717            path: Vec::new(),
9718        };
9719    }
9720
9721    // Constructors that route differently, or a constructor next to
9722    // something else (a factory, a name from another module, an unknown
9723    // value): what they build is ambiguous.
9724    let classes: Vec<ClientClass> = real
9725        .iter()
9726        .filter_map(|v| match v {
9727            Val::Class(class) => Some(*class),
9728            _ => None,
9729        })
9730        .collect();
9731    if let Some(first) = classes.first() {
9732        if classes.len() < real.len()
9733            || classes
9734                .iter()
9735                .any(|c| c.pkg != first.pkg || c.family != first.family)
9736        {
9737            return Val::untracked(Origin::MixedClasses(first.pkg));
9738        }
9739    }
9740
9741    // No client or constructor: a tracked module beats a fallback;
9742    // otherwise keep the most informative origin.
9743    if let Some(tracked) = real.iter().find(|v| v.is_tracked()) {
9744        return tracked.clone();
9745    }
9746    let rank = |v: &Val| match v {
9747        Val::Untracked(Origin::Factory { .. }) => 0,
9748        Val::Untracked(Origin::Parameter { .. }) => 1,
9749        Val::Untracked(Origin::Imported { .. }) => 2,
9750        Val::Untracked(Origin::UnassignedAttribute { .. }) => 3,
9751        Val::Untracked(Origin::Other) => 4,
9752        _ => 5,
9753    };
9754    real.into_iter()
9755        .min_by_key(rank)
9756        .unwrap_or(Val::untracked(Origin::Other))
9757}
9758
9759#[cfg(test)]
9760mod tests;